pydantic-ai/.github/scripts/agentic_workflow_guard.py

1909 lines
90 KiB
Python

"""Static policy checks for the `gh-aw` agentic workflows in `.github/workflows/`.
Every check here encodes a defect that actually reached `main` and burned model
budget before anyone noticed, documented in #6766:
- `dangling_needs` — `pydantic-ai-ui-security-review` gated `activation` on
`needs.detect.outputs.touched` while `detect` was not one of its `needs`. The
expression silently evaluated to empty, so the whole chain skipped for a month.
A job skipped by `if:` reports *success*, so the required check stayed green
while the security review never ran.
- `safe_output_job_max` — `record-attention-decision` relied on the default
`max: 1`, so 9 of every 10 classifications were dropped into an `errors` array
nobody read and the host script then failed the run.
- `prompt_paths` — the review prompt told the agent to read
`/tmp/gh-aw/.review-context/`, outside the `Read` tool's root. Every run wasted
~15 tool calls rediscovering its own context via `bash cat`.
- `timeout_declared` — a sweep silently needs a wall-clock bound; `roundtrip-sweep`
spent three weeks timing out one minute under its limit, filing nothing.
- `job_timeout_env` — the shim reads its wall-clock budget from
`PYDANTIC_AI_JOB_TIMEOUT_MINUTES`, so every workflow must declare it and keep it
equal to `timeout-minutes`. Absent, the shim assumed 30: `stale-issues-finder`
asked for 60 and only ever used 28, and `attention-triage` asked for 20 and was
killed before it could emit anything.
- `compiler_versions` — a partial `gh aw compile` leaves locks on mixed compiler
versions, which is how source and lock drift apart unnoticed.
- `compiled_runner_contract` — every generated agent job must use the public
engine with the pinned runtime, repository policy and isolated Z.ai credentials.
- `awf_binary_version` — the installed firewall must match the compiler bundle.
#8041 moved gh-aw to a release bundling AWF v0.27.44 without touching that pin, and the v0.27.42
binary rejected the v0.27.44 config (`config.apiProxy.providers is not supported`).
The agent job died before the model started, on every workflow using the shim.
- `ai_credits_accounting` — provider overlays use USD per token, unlike default
pricing's USD per million. Confusing those units exhausted the fixed firewall
credit cap on one request. Only the verified GLM overlay is allowed here.
- `daily_aic_guardrail` — gh-aw's daily AI-credits guardrail listed the artifacts of every
run from the past 24h on each activation, about 700 REST calls per CI Review activation,
and exhausted the repo's `GITHUB_TOKEN` rate limit to total credits that were always 0.
- `engine_sys_path_order` — #10347 imported an engine revision from before #12818, so
every lock's wrapper put the checkout ahead of installed packages on `sys.path` (#12815).
- `compiler_version_compatibility` — the compiler version in every generated lock
must not appear in gh-aw's live blocked-version policy.
- `lock_regenerated` — `.github/workflows/AGENTS.md` requires a recompiled
`*.lock.yml` in the same change as its `*.md` source. GitHub Actions runs the
lock, so an un-recompiled source is a silent no-op.
- `logfire-import` / `logfire-compiled` / `logfire-network` — three Z.AI
workflows reached `main` without the shared Logfire import or compiled OTLP
settings, so their runs exported no traces (#19). The compiled firewall must
also allow all six Logfire ingest hosts or it can silently block export.
Run over the repo with `python .github/scripts/agentic_workflow_guard.py check`,
or as policy tests via `test_agentic_workflow_guard.py`.
"""
from __future__ import annotations
import argparse
import json
import posixpath
import re
import shlex
import subprocess
import sys
from collections.abc import Mapping, Sequence
from dataclasses import dataclass
from pathlib import Path
from typing import Any, TypeGuard, cast
import yaml
from agent_provider_health import AGENT_START_HEALTH_STEPS
WORKFLOWS_DIR = Path('.github/workflows')
AGENTIC_GLOB = 'pydantic-ai-*.md'
# gh-aw stages the agent's workspace no-exec and roots its file tools at the
# checkout, so absolute paths under this prefix are unreadable by `Read`.
SANDBOX_PREFIX = '/tmp/gh-aw/'
# Paths the agent is told about but reads through `Bash`/`jq` rather than the file
# tools, which is fine — `Bash` is not rooted at the checkout. `/tmp/gh-aw/bin` is
# gh-aw's exec-able launcher path; the rest is the prefetched GitHub corpus that
# `shared/tool-hints.md` documents with `jq` invocations (#6509).
#
# These stay outside `$GITHUB_WORKSPACE` while PR review context was moved into it
# (#6766 F3), so an agent that reaches for `Read` here still hits the old failure.
# Worth revisiting if a sweep is seen burning turns on them.
# Every entry ends in `/`, and the candidate path gets one appended before comparison.
# That makes the match land on a whole path component in both directions: without it
# `bin` also allows `bindings/`, and `github-context` also allows `github-context.bak`.
PROMPT_PATH_ALLOWLIST_PREFIXES = (
'/tmp/gh-aw/bin/',
'/tmp/gh-aw/agent/github-context/',
)
# A fenced block opens with three or more backticks or tildes, indented at most three
# spaces, optionally followed by an info string. `~~~` and the indent allowance are both
# CommonMark and both appear in the wild. The trailing group is the info string, which
# only an *opener* may carry — see `check_prompt_paths`.
FENCE_MARKER = re.compile(r'^ {0,3}(`{3,}|~{3,})(.*)$')
# Mirrors `pydantic_ai_gh_aw_shim.cli`, which this script deliberately does not import:
# the shim pulls in the whole agent runtime, and the guard must stay a lightweight
# stdlib+yaml script. `test_job_timeout_constants_match_the_shim` pins them together.
DEFAULT_JOB_TIMEOUT_MINS = 30
JOB_TIMEOUT_HEADROOM_MINS = 2
# Run to the end of the path token rather than to the end of a filename-ish character
# class. A class that stops early truncates `/tmp/gh-aw/bin:secret/x` to `/tmp/gh-aw/bin`,
# which then matches the allowlist and lets the real path through unflagged. Stopping at
# whitespace, backtick, quote and the markdown-link delimiters is enough to end the token
# wherever a prompt actually writes one.
SANDBOX_PATH = re.compile(rf'{re.escape(SANDBOX_PREFIX)}[^\s`\'"()\[\]<>]*')
# The version argument of the hand-written AWF install step. Both the script path and
# the version may be quoted, and the capture must not swallow those quotes: a pin that
# only differs from the compiled version by a pair of them is the same pin.
AWF_INSTALL_VERSION = re.compile(r'install_awf_binary\.sh"?\s+"?([^"\s]+)')
# The script gh-aw's daily AI-credits guardrail step runs. Match it rather than the step id,
# which changes across releases: `daily-effective-workflow-guardrail` in v0.86.2,
# `daily-ai-credits-workflow-guardrail` in v0.92.6.
DAILY_AIC_GUARDRAIL_SCRIPT = 'check_daily_aic_workflow_guardrail.cjs'
# The job `shared/provider-health.md` adds after the agent job to record its terminal result on the host.
HOST_RESULT_JOB = 'provider_health_record'
# Expression context names are case-insensitive, and `secrets['X']` and `toJSON(secrets)` read the same context.
SECRETS_CONTEXT = re.compile(r'\bsecrets\b', re.IGNORECASE)
# The engine's Python wrapper is the `AGENT_MODULE` JS template literal in a step's `run`.
# It must contain no `sys.path.insert(0, ...)` statement.
ENGINE_WRAPPER_MODULE = re.compile(r'const AGENT_MODULE = `((?:\\.|[^`\\])*)`')
SYS_PATH_PREPEND = re.compile(r'^\s*sys\.path\.insert\(\s*0\s*,', re.MULTILINE)
# The agent-start recheck fetches the controller through the contents API with no `ref`,
# which serves the default branch, then runs `check` from the file it fetched. A workspace
# copy can come from the PR head or its base branch.
AGENT_START_HEALTH_CHECK = re.compile(
r'/contents/\.github/scripts/agent_provider_health\.py"(?:\s|\\)*>\s*(?P<path>"[^"]+")\s*'
r'python3\s+(?P=path)\s+check\b'
)
# The agent-start recheck's step id. Its `account` output selects the engine's Z.AI key.
AGENT_START_HEALTH_STEP_ID = 'agent_start_health'
# The primary and backup Coding Plan keys, which the gate, the recheck and the host record all receive.
ZAI_KEYS = {
'ZAI_API_KEY': '${{ secrets.ZAI_API_KEY }}',
'ZAI_BACKUP_API_KEY': '${{ secrets.ZAI_BACKUP_API_KEY }}',
}
# The engine's provider credential: the backup key only when the recheck selected that account.
ENGINE_CREDENTIAL = (
f"${{{{ steps.{AGENT_START_HEALTH_STEP_ID}.outputs.account == 'backup' "
'&& secrets.ZAI_BACKUP_API_KEY || secrets.ZAI_API_KEY }}'
)
NEEDS_REFERENCE = re.compile(r'\bneeds\.([A-Za-z_][A-Za-z0-9_-]*)')
EXPRESSION_BLOCK = re.compile(r'\$\{\{(.*?)\}\}', re.DOTALL)
def _strip_boolean_wrappers(expression: str) -> str:
"""Strip parentheses that wrap the whole expression, not a subexpression."""
expression = expression.strip()
while expression.startswith('(') and expression.endswith(')'):
depth = 0
quote: str | None = None
wraps_expression = True
for index, character in enumerate(expression):
if quote is not None:
if character == quote:
quote = None
elif character in ("'", '"'):
quote = character
elif character == '(':
depth += 1
elif character == ')':
depth -= 1
if depth == 0 and index != len(expression) - 1:
wraps_expression = False
break
if not wraps_expression or depth != 0:
break
expression = expression[1:-1].strip()
return expression
def _split_boolean_operator(expression: str, operator: str) -> list[str]:
"""Split at boolean operators outside quotes and parenthesized expressions."""
terms: list[str] = []
depth = 0
quote: str | None = None
start = 0
index = 0
while index < len(expression):
character = expression[index]
if quote is not None:
if character == quote:
quote = None
index += 1
continue
if character in ("'", '"'):
quote = character
index += 1
continue
if character == '(':
depth += 1
index += 1
continue
if character == ')':
depth -= 1
index += 1
continue
if depth == 0 and expression.startswith(operator, index):
terms.append(expression[start:index].strip())
index += len(operator)
start = index
continue
index += 1
if not terms:
return []
terms.append(expression[start:].strip())
return terms
def _boolean_branches(expression: str) -> list[list[str]]:
"""Return conjunction terms for each OR branch in a workflow condition."""
expression = _strip_boolean_wrappers(expression)
if expression.startswith('${{') and expression.endswith('}}'):
expression = expression[3:-2].strip()
disjunctions = _split_boolean_operator(expression, '||')
if disjunctions:
return [branch for term in disjunctions for branch in _boolean_branches(term)]
conjunctions = _split_boolean_operator(expression, '&&')
if not conjunctions:
return [[expression]]
branches: list[list[str]] = [[]]
for term in conjunctions:
term_branches = _boolean_branches(term)
branches = [prefix + suffix for prefix in branches for suffix in term_branches]
return branches
def _normalized_condition(expression: str) -> str:
"""Normalize whitespace for comparisons between boolean-expression terms."""
return re.sub(r'\s+', '', expression)
def _condition_is_required(expression: str, condition: str) -> bool:
"""Check that `condition` is a conjunct in every OR branch."""
expected = _normalized_condition(condition)
branches = _boolean_branches(expression)
return bool(branches) and all(expected in {_normalized_condition(term) for term in branch} for branch in branches)
@dataclass(frozen=True)
class Violation:
"""A single policy failure, rendered as one line of CI output."""
path: str
check: str
message: str
def __str__(self) -> str:
return f'{self.path}: [{self.check}] {self.message}'
def _as_mapping(value: object) -> dict[str, Any]:
"""Coerce a parsed-YAML value to a string-keyed mapping.
YAML 1.1 parses a bare `on:` key as the boolean `True`, so keys are stringified
with that one special case mapped back.
"""
if not isinstance(value, dict):
return {}
mapping = cast(dict[Any, Any], value)
return {('on' if key is True else str(key)): item for key, item in mapping.items()}
def _as_strings(value: object) -> set[str]:
"""Coerce a parsed-YAML scalar-or-sequence to a set of strings."""
if isinstance(value, str):
return {value}
if isinstance(value, list):
return {str(item) for item in cast(list[Any], value)}
return set()
def _is_object_sequence(value: object) -> TypeGuard[Sequence[object]]:
"""Narrow parsed YAML sequences without letting untyped items escape."""
return isinstance(value, Sequence) and not isinstance(value, (str, bytes))
def parse_frontmatter(source: Path) -> dict[str, Any]:
"""Return the YAML frontmatter of a gh-aw workflow source, or `{}` if absent."""
text = source.read_text(encoding='utf-8')
match = re.match(r'^---\n(.*?)\n---\n', text, re.DOTALL)
if match is None:
return {}
return _as_mapping(yaml.safe_load(match.group(1)))
def parse_prompt_body(source: Path) -> str:
"""Return the markdown body (the agent-facing prompt) of a gh-aw source."""
text = source.read_text(encoding='utf-8')
match = re.match(r'^---\n.*?\n---\n(.*)$', text, re.DOTALL)
return match.group(1) if match else text
def _expressions_of(job: dict[str, Any]) -> list[tuple[str, str]]:
"""Return `(field, expression)` pairs whose `needs.*` refs must resolve.
Every one of these silently evaluates to empty when it references a job that is not
a dependency, rather than failing loudly. `if:` skips the job or step outright — and
a job skipped by `if:` reports success. `outputs:`, `env:` and `with:` are worse in
kind: nothing skips, the step just runs with an empty value, so a wrong action call
or a wrong shell variable goes through looking healthy. gh-aw emits exactly that
shape, e.g. `GH_AW_NEEDS_DETECT_OUTPUTS_TOUCHED: ${{ needs.detect.outputs.touched }}`.
"""
expressions: list[tuple[str, str]] = []
def add(field: str, value: Any) -> None:
if isinstance(value, str):
expressions.append((field, value))
add('if', job.get('if'))
for name, value in _as_mapping(job.get('outputs')).items():
add(f'outputs.{name}', value)
for name, value in _as_mapping(job.get('env')).items():
add(f'env.{name}', value)
for name, value in _as_mapping(job.get('with')).items():
add(f'with.{name}', value)
steps = job.get('steps')
for index, raw_step in enumerate(cast(list[Any], steps) if isinstance(steps, list) else []):
step = _as_mapping(raw_step)
label = str(step.get('name') or step.get('uses') or f'#{index}')
add(f'steps[{label}].if', step.get('if'))
add(f'steps[{label}].run', step.get('run'))
for name, value in _as_mapping(step.get('env')).items():
add(f'steps[{label}].env.{name}', value)
for name, value in _as_mapping(step.get('with')).items():
add(f'steps[{label}].with.{name}', value)
return expressions
def check_dangling_needs(lock: Path) -> list[Violation]:
"""Every `needs.<job>` reference must name a declared dependency of that job."""
workflow = _as_mapping(yaml.safe_load(lock.read_text(encoding='utf-8')))
violations: list[Violation] = []
for job_name, raw_job in _as_mapping(workflow.get('jobs')).items():
job = _as_mapping(raw_job)
declared = _as_strings(job.get('needs'))
for field, expression in _expressions_of(job):
# `if:` is the one field GitHub evaluates as an expression without `${{ }}`.
# Everywhere else a bare `needs.foo` is literal text — most often inside a
# `run:` shell script — so only interpolated blocks count, or the check would
# flag prose and jq programs that merely spell the word.
if field == 'if' or field.endswith('.if'):
scanned = expression
else:
scanned = ' '.join(EXPRESSION_BLOCK.findall(expression))
for referenced in sorted(set(NEEDS_REFERENCE.findall(scanned))):
if referenced not in declared:
violations.append(
Violation(
str(lock),
'dangling-needs',
f'job `{job_name}` references `needs.{referenced}` in `{field}:` but '
f'`{referenced}` is not in its `needs:` ({sorted(declared) or "none"}). '
'The expression evaluates to empty and the job silently skips — '
'and a job skipped by `if:` reports success.',
)
)
return violations
def check_safe_output_job_max(source: Path) -> list[Violation]:
"""Custom `safe-outputs.jobs.*` entries must declare `max:` explicitly."""
safe_outputs = _as_mapping(parse_frontmatter(source).get('safe-outputs'))
return [
Violation(
str(source),
'safe-output-job-max',
f'safe-output job `{job_name}` does not declare `max:`. The default is 1, and extra '
'items are dropped into an `errors` array that nothing reads — set it explicitly '
'even when 1 is correct, so the bound is a decision rather than an accident.',
)
for job_name, job in _as_mapping(safe_outputs.get('jobs')).items()
if 'max' not in _as_mapping(job)
]
def check_prompt_paths(source: Path) -> list[Violation]:
"""Prompts must not instruct the agent to read paths outside the workspace.
Only prose is scanned. A path inside a fenced code block is being handed to a
shell, and `Bash` can read anywhere — the F3 defect was prose telling the agent to
`Read` a path its *file tools* reject. Flagging shell snippets too would condemn
the documented `jq /tmp/gh-aw/agent/github-context/...` corpus reads, which work.
"""
violations: list[Violation] = []
fence: str | None = None
for lineno, line in enumerate(parse_prompt_body(source).splitlines(), start=1):
marker = FENCE_MARKER.match(line)
if marker is not None:
run, info = marker.group(1), marker.group(2)
# CommonMark: a closer uses the same character, is at least as long as its
# opener, and carries no info string. Getting any of those wrong leaves the
# scanner out of step with the real block structure — and once it believes it
# is inside a fence it skips every later line, turning a real violation into a
# silent PASS. A ```bash line inside an open block is content, not a closer.
if fence is None:
fence = run
continue
if run[0] == fence[0] and len(run) >= len(fence) and not info.strip():
fence = None
continue
if fence is not None:
continue
for match in SANDBOX_PATH.finditer(line):
# Trailing sentence punctuation belongs to the prose, not the path. Stripped
# after matching rather than excluded from the class, so that `:` and `.`
# inside a path still keep the token whole.
path = match.group(0).rstrip('.,;:!?')
# Normalise for the comparison only, never for the message: the author needs
# to see the path as they wrote it to find it again. `/tmp/gh-aw/bin/../` is
# textually under an allowlisted directory but resolves outside it, which is
# the very class of path this rejects. Compare with a trailing separator too,
# so a directory entry matches the directory itself and everything under it
# but not a sibling sharing its opening characters — bare `bin` would
# otherwise allow `/tmp/gh-aw/bindings/`.
if f'{posixpath.normpath(path)}/'.startswith(PROMPT_PATH_ALLOWLIST_PREFIXES):
continue
violations.append(
Violation(
str(source),
'prompt-path-outside-workspace',
f"line {lineno}: prompt references `{path}`, which is outside the agent's file-tool "
'root — `Read` rejects it with "resolves outside the root directory" and the agent '
'burns turns rediscovering the file. Stage it under `$GITHUB_WORKSPACE` instead.',
)
)
return violations
def check_timeout_declared(source: Path) -> list[Violation]:
"""Agentic workflows must bound their own wall clock."""
if 'timeout-minutes' in parse_frontmatter(source):
return []
return [
Violation(
str(source),
'timeout-declared',
'no `timeout-minutes:` in frontmatter. Without an explicit bound an agent can spend a '
'full run and be killed with nothing to show for it.',
)
]
def check_job_timeout_env(source: Path) -> list[Violation]:
"""`PYDANTIC_AI_JOB_TIMEOUT_MINUTES`, when set, must equal a usable `timeout-minutes`.
The shim derives the agent's own wall-clock budget from that env var, because
gh-aw's `GH_AW_TIMEOUT_MINUTES` is set only on the failure-handler step and never
reaches the agent container. If the two drift, the agent either stops early and
wastes the time it was granted, or overruns and is killed with nothing emitted.
"""
frontmatter = parse_frontmatter(source)
timeout = frontmatter.get('timeout-minutes')
if timeout is None:
# `timeout-declared` already reports this, and every message below would quote
# `None` as the value to copy into `env:`.
return []
if isinstance(timeout, int) and timeout <= JOB_TIMEOUT_HEADROOM_MINS:
return [
Violation(
str(source),
'job-timeout-too-short',
f'`timeout-minutes: {timeout}` leaves the agent no budget. The shim reserves '
f'{JOB_TIMEOUT_HEADROOM_MINS} minutes for container teardown and artifact upload, so it '
f'falls back to {DEFAULT_JOB_TIMEOUT_MINS} minutes rather than granting a non-positive '
'one — the agent then runs well past the point Actions kills the job, and emits nothing. '
f'Give the job more than {JOB_TIMEOUT_HEADROOM_MINS} minutes.',
)
]
declared = _as_mapping(frontmatter.get('env')).get('PYDANTIC_AI_JOB_TIMEOUT_MINUTES')
if declared is None:
return [
Violation(
str(source),
'job-timeout-env-missing',
'no `PYDANTIC_AI_JOB_TIMEOUT_MINUTES` in `env:`. Without it the shim falls back to a '
f'30-minute assumption, so a job with `timeout-minutes: {timeout}` either overruns and '
'is killed with nothing emitted, or silently never uses the time it was granted. '
f'Set it to `"{timeout}"`.',
)
]
if str(declared) == str(timeout):
return []
return [
Violation(
str(source),
'job-timeout-env-mismatch',
f'`PYDANTIC_AI_JOB_TIMEOUT_MINUTES` is `{declared}` but `timeout-minutes` is `{timeout}`. '
"The shim derives the agent's budget from the env var, so a mismatch either wastes the "
'granted time or gets the agent killed mid-run. Keep them equal.',
)
]
def check_compiler_versions(locks: list[Path]) -> list[Violation]:
"""All locks must be compiled by the same gh-aw version."""
versions: dict[str, list[str]] = {}
for lock in locks:
first_line = lock.read_text(encoding='utf-8').split('\n', 1)[0]
_, _, payload = first_line.partition('gh-aw-metadata: ')
if not payload:
continue
try:
# `_as_mapping`, not `.get` directly: a payload that parses as valid JSON but
# isn't an object (a bare string, `null`) would otherwise raise `AttributeError`
# and take down the whole lint job instead of reporting a policy violation.
version = str(_as_mapping(json.loads(payload)).get('compiler_version', 'unknown'))
except json.JSONDecodeError:
continue
versions.setdefault(version, []).append(lock.name)
if len(versions) <= 1:
return []
summary = '; '.join(f'{version}: {", ".join(sorted(names))}' for version, names in sorted(versions.items()))
return [
Violation(
str(WORKFLOWS_DIR),
'compiler-version-drift',
f'locks were built by different gh-aw versions ({summary}). Run `gh aw compile` so every '
'lock is regenerated together.',
)
]
def shell_commands(script: str) -> list[list[str]]:
"""Tokenize commands without treating quoted strings or comments as executions."""
lexer = shlex.shlex(script.replace('\\\n', ''), posix=True, punctuation_chars=';&|\n')
lexer.whitespace = ' \t\r'
lexer.whitespace_split = True
commands: list[list[str]] = []
command: list[str] = []
try:
for token in lexer:
if all(char in ';&|\n' for char in token):
if command:
commands.append(command)
command = []
else:
command.append(token)
except ValueError:
return []
if command:
commands.append(command)
return commands
def check_compiled_runner_contract(lock: Path) -> list[Violation]:
"""Require the public engine, workflow policy and isolated Z.ai credentials."""
workflow = _as_mapping(yaml.safe_load(lock.read_text(encoding='utf-8')))
agent = _as_mapping(_as_mapping(workflow.get('jobs')).get('agent'))
steps = agent.get('steps')
executions: list[Mapping[str, object]] = []
for raw_step in steps if _is_object_sequence(steps) else ():
step = _as_mapping(raw_step)
if step.get('id') == 'agentic_execution':
executions.append(step)
missing: list[str] = []
runtime = str(_as_mapping(agent.get('env')).get('GH_AW_ENGINE_VERSION', ''))
runtime_match = re.fullmatch(r'(\d+)\.(\d+)\.(\d+)', runtime)
if runtime_match is None or tuple(map(int, runtime_match.groups())) < (0, 70, 0):
missing.append('a published runtime pin of 0.70.0 or newer')
if len(executions) != 1:
missing.append('exactly one public engine execution')
else:
execution = executions[0]
run = execution.get('run')
commands = shell_commands(run) if isinstance(run, str) else []
awf_commands = [command for command in commands if command[0] == 'awf']
awf = awf_commands[0] if len(awf_commands) == 1 else []
harness_commands: list[list[str]] = []
if '--' in awf:
child = awf[awf.index('--') + 1 :]
if len(child) >= 3 and child[:2] == ['/bin/bash', '-c']:
harness_commands = shell_commands(child[2])
env = _as_mapping(execution.get('env'))
harness_paths = {
'${RUNNER_TEMP}/gh-aw/actions/pydantic-ai_harness.cjs',
'/tmp/gh-aw/actions/pydantic-ai_harness.cjs',
}
if not any(
len(command) == 4
and command[0] == 'exec'
and command[1] in {'node', '$GH_AW_NODE_EXEC'}
and command[2] in harness_paths
and command[3] == 'clai2'
for command in harness_commands[-1:]
):
missing.append('the public CLAI 2 harness')
for name, expected, description in (
('XDG_CONFIG_HOME', '/tmp/gh-aw/clai2-config', 'isolated CLAI settings for the workflow budgets'),
('PYTHONPATH', '/tmp/gh-aw/workflow-python', 'the staged workflow-policy import path'),
('PAI_AGENT', 'pydantic_ai_gh_aw_shim.agent:agent', 'the repository workflow policy'),
('PAI_RESULT_METADATA', 'pydantic_ai_gh_aw_shim.agent:result_metadata', 'authenticated workflow metadata'),
('PAI_OTEL_EXPORT_PATH', '/tmp/gh-aw/pydantic-ai-private-otel.jsonl', 'credential-free workflow tracing'),
('GH_AW_PROTECTED_SESSION_CAPTURE', '1', 'native protected session capture'),
):
if str(env.get(name)) != expected:
missing.append(description)
options = awf[: awf.index('--')] if '--' in awf else awf
captures = [value for flag, value in zip(options, options[1:]) if flag == '--capture-command-output']
if captures != ['${RUNNER_TEMP}/gh-aw-protected-capture-${GH_AW_PROTECTED_CAPTURE_ID}'] or not env.get(
'GH_AW_PROTECTED_CAPTURE_ID'
):
missing.append('native protected session capture')
exclusions = {value for flag, value in zip(options, options[1:]) if flag == '--exclude-env'}
if 'ANTHROPIC_API_KEY' not in exclusions:
missing.append('AWF exclusion of the provider credential')
if not env.get('PYDANTIC_AI_TASK_ID') or 'PYDANTIC_AI_TASK_ID' in exclusions:
missing.append('task identity available inside the agent sandbox')
if env.get('PAI_MODEL') != 'anthropic/${{ vars.GH_AW_MODEL }}':
missing.append('the unchanged Z.ai model selected through Anthropic')
if env.get('ANTHROPIC_API_KEY') != ENGINE_CREDENTIAL:
missing.append('injection of the account-selected Z.ai key at the provider proxy')
return [Violation(str(lock), 'compiled-runner-contract', 'Missing ' + ', '.join(missing) + '.')] if missing else []
def check_awf_binary_version(lock: Path) -> list[Violation]:
"""The installed AWF binary must match the version of its compiled configuration.
Built-in engines report the bundled version in `GH_AW_INFO_AWF_VERSION`.
Custom engines can leave it empty, so their schema URL supplies the reference.
A lock that pins a version but declares none also fails: the comparison has lost
its reference, and passing there would disarm the check on a gh-aw rename.
"""
workflow = _as_mapping(yaml.safe_load(lock.read_text(encoding='utf-8')))
pinned: set[str] = set()
bundled: set[str] = set()
for raw_job in _as_mapping(workflow.get('jobs')).values():
steps = _as_mapping(raw_job).get('steps')
for raw_step in cast(list[Any], steps) if isinstance(steps, list) else []:
step = _as_mapping(raw_step)
run = step.get('run')
# `finditer`, not `search`: one `run:` block can invoke the installer more than
# once, and the last call is the binary the agent ends up with. Every invocation
# has to match, so stopping at the first would let a stale later one through.
if isinstance(run, str):
pinned.update(match.group(1) for match in AWF_INSTALL_VERSION.finditer(run))
version = _as_mapping(step.get('env')).get('GH_AW_INFO_AWF_VERSION')
if isinstance(version, str) and version:
bundled.add(version)
# Custom engines may leave the info field empty. The generated configuration
# still declares its AWF schema version, independently of the installer pin.
if not bundled:
bundled.update(re.findall(r'gh-aw-firewall/releases/download/(v[0-9.]+)/', lock.read_text(encoding='utf-8')))
# Without an install step there is no binary pin to compare.
if not pinned:
return []
# A pin with nothing to compare it against is the check losing its reference, not a
# pass. Returning empty here would let a gh-aw rename of `GH_AW_INFO_AWF_VERSION`
# disarm this check silently, and the next skew would ship green exactly as #8041 did.
if not bundled:
return [
Violation(
str(lock),
'awf-binary-version',
f'the AWF install step pins {", ".join(sorted(pinned))} but the lock declares no '
'`GH_AW_INFO_AWF_VERSION` or AWF schema URL to check it against. gh-aw stopped reporting the AWF '
'version it bundles, so this check needs a new source before the pin can be trusted.',
)
]
unexpected = sorted(pinned - bundled)
if not unexpected:
return []
return [
Violation(
str(lock),
'awf-binary-version',
f'the AWF install step pins {", ".join(unexpected)} but gh-aw compiled this lock against '
f'{", ".join(sorted(bundled))}. Recompile with a gh-aw release that emits matching AWF installer '
'and schema versions; an older binary rejects the newer firewall config.',
)
]
def compiled_awf_configs(lock: Path) -> list[Mapping[str, object]]:
"""Read emitted AWF configurations, excluding informational environment values."""
workflow = _as_mapping(yaml.safe_load(lock.read_text(encoding='utf-8')))
configs: list[Mapping[str, object]] = []
for raw_job in _as_mapping(workflow.get('jobs')).values():
steps = _as_mapping(raw_job).get('steps')
for raw_step in steps if _is_object_sequence(steps) else ():
run = _as_mapping(raw_step).get('run')
for command in shell_commands(run) if isinstance(run, str) else ():
if command[0] != 'printf':
continue
for argument in command[1:]:
if not argument.startswith('{'):
continue
try:
value: object = json.loads(argument)
except json.JSONDecodeError:
# Decode shell-escaped JSON without executing budget expansion.
# Its numeric value is irrelevant to pricing and network checks.
try:
value = json.loads(
argument.replace('\\"', '"')
.replace('\\$', '$')
.replace('${GH_AW_MAX_AI_CREDITS}', '-1')
)
except json.JSONDecodeError:
continue
config = _as_mapping(value)
if config.get('apiProxy'):
configs.append(config)
return configs
def check_ai_credits_accounting(lock: Path) -> list[Violation]:
"""Allow verified GLM prices in USD per token, never per-million overlay values."""
expected: dict[str, object] = {
'anthropic': {
'models': {'glm-5.3-flash': {'cost': {'input': 0.00000015, 'cache_read': 0.00000003, 'output': 0.00000050}}}
}
}
fallback: dict[str, float] = {'input': 0.15, 'cachedInput': 0.03, 'output': 0.50}
return [
Violation(
str(lock),
'ai-credits-accounting',
'`models.providers` must use the verified GLM-5.3-Flash USD-per-token rates; '
'per-million values incorrectly exhaust the fixed AWF credit cap. '
'`models.default-ai-credits-pricing` must use the same rates in USD per million tokens.',
)
for config in compiled_awf_configs(lock)
for proxy in [_as_mapping(config.get('apiProxy'))]
if (proxy.get('providers') is not None and proxy.get('providers') != expected)
or (proxy.get('defaultAiCreditsPricing') is not None and proxy.get('defaultAiCreditsPricing') != fallback)
]
def check_daily_aic_guardrail(lock: Path) -> list[Violation]:
"""No lock may compile gh-aw's daily AI-credits guardrail.
With a threshold set, the guardrail spends hundreds of REST calls per activation on
the repo's `GITHUB_TOKEN` to total AI credits, which do not measure the Z.AI quota.
gh-aw drops it only for `max-daily-ai-credits: -1` in the workflow's own frontmatter.
An imported `-1` only skips the scan at run time and still compiles the guardrail
with its conclusion-job cache steps, so this reads the lock.
"""
if DAILY_AIC_GUARDRAIL_SCRIPT not in lock.read_text(encoding='utf-8'):
return []
return [
Violation(
str(lock),
'daily-aic-guardrail',
"the lock compiles gh-aw's daily AI-credits guardrail. With a threshold set, every activation "
"lists each recent run's artifacts and exhausts the `GITHUB_TOKEN` rate limit. With `-1` only "
'in an import, that scan is skipped but its conclusion-job cache steps still run whenever the conclusion job runs. '
"Set `max-daily-ai-credits: -1` in the source's own frontmatter and recompile.",
)
]
def check_engine_sys_path_order(lock: Path) -> list[Violation]:
"""No compiled engine wrapper (`AGENT_MODULE`) may contain a `sys.path.insert(0, ...)` statement.
The wrapper comes from the engine revision `shared/engine-zai.md` imports, so a lock
compiled from a revision before #12818 still puts the checkout first on `sys.path`.
"""
workflow = _as_mapping(yaml.safe_load(lock.read_text(encoding='utf-8')))
wrappers: list[str] = []
for raw_job in _as_mapping(workflow.get('jobs')).values():
steps = _as_mapping(raw_job).get('steps')
for raw_step in steps if _is_object_sequence(steps) else ():
run = _as_mapping(raw_step).get('run')
if isinstance(run, str):
wrappers.extend(match.group(1) for match in ENGINE_WRAPPER_MODULE.finditer(run))
if not wrappers:
return [Violation(str(lock), 'engine-sys-path-order', 'Compiled lock has no engine wrapper (`AGENT_MODULE`).')]
if not any(SYS_PATH_PREPEND.search(wrapper) for wrapper in wrappers):
return []
return [
Violation(
str(lock),
'engine-sys-path-order',
'The compiled engine wrapper (`AGENT_MODULE`) contains a `sys.path.insert(0, ...)` statement. '
'Import an engine revision that includes #12818 in `shared/engine-zai.md` and recompile.',
)
]
def check_compiler_version_compatibility(locks: list[Path], compatibility: dict[str, Any]) -> list[Violation]:
"""Compiled gh-aw versions must not be revoked by the upstream runtime policy."""
blocked_raw = compatibility.get('blockedVersions')
blocked = _as_strings(blocked_raw)
if not isinstance(blocked_raw, list):
return [
Violation(
'gh-aw compatibility policy',
'compiler-compatibility-policy-invalid',
'`blockedVersions` is missing or is not a list; refusing to pass without '
'the policy enforced by gh-aw activation jobs.',
)
]
violations: list[Violation] = []
for lock in locks:
first_line = lock.read_text(encoding='utf-8').split('\n', 1)[0]
_, _, payload = first_line.partition('gh-aw-metadata: ')
if not payload:
continue
try:
version = _as_mapping(json.loads(payload)).get('compiler_version')
except json.JSONDecodeError:
continue
if isinstance(version, str) and version in blocked:
violations.append(
Violation(
str(lock),
'compiler-version-blocked',
f'compiler version `{version}` is blocked by gh-aw and the activation job will fail. '
'Upgrade gh-aw and recompile every agentic workflow.',
)
)
return violations
def check_lock_regenerated(changed: list[str], workflows_dir: Path = WORKFLOWS_DIR) -> list[Violation]:
"""A changed `.md` source (or shared import) must ship its recompiled lock.
Actions runs the `.lock.yml`, never the `.md`, so a source edit without its
recompiled lock is a silent no-op that leaves the two drifted apart.
"""
changed_set = set(changed)
violations: list[Violation] = []
# Union of sources still on disk and sources named in the changeset: a deleted `.md`
# is gone from the glob, so globbing alone would let its orphaned lock through and
# Actions would keep running a workflow whose source no longer exists.
changed_sources = {
path for path in changed_set if Path(path).match(str(workflows_dir / AGENTIC_GLOB)) and '/shared/' not in path
}
sources = {str(path) for path in workflows_dir.glob(AGENTIC_GLOB)} | changed_sources
for source_path in sorted(sources):
source = Path(source_path)
lock = source.with_suffix('.lock.yml')
if source_path not in changed_set or str(lock) in changed_set:
continue
if source.exists():
violations.append(
Violation(
source_path,
'lock-not-regenerated',
f'source changed but `{lock.name}` did not. Run `gh aw compile` and commit the '
'regenerated lock in the same change.',
)
)
else:
violations.append(
Violation(
source_path,
'lock-not-regenerated',
f'source was deleted but `{lock.name}` was left behind. Actions runs the lock, so '
'the workflow would keep running with no source. Delete the lock in the same change.',
)
)
changed_shared = {path for path in changed_set if path.startswith(str(workflows_dir / 'shared'))}
for shared in sorted(changed_shared):
name = Path(shared).name
for source in sorted(workflows_dir.glob(AGENTIC_GLOB)):
lock = source.with_suffix('.lock.yml')
imports = _as_strings(parse_frontmatter(source).get('imports'))
if f'shared/{name}' in imports and str(lock) not in changed_set:
violations.append(
Violation(
shared,
'lock-not-regenerated',
f'shared import changed but `{lock.name}`, which imports it, was not '
'regenerated. Run `gh aw compile` and commit every affected lock.',
)
)
return violations
def _is_zai_workflow(frontmatter: Mapping[str, object]) -> bool:
imports = _as_strings(frontmatter.get('imports'))
engine_env = _as_mapping(_as_mapping(frontmatter.get('engine')).get('env'))
return 'shared/engine-zai.md' in imports or engine_env.get('ANTHROPIC_BASE_URL') == 'https://api.z.ai/api/anthropic'
def check_logfire_wiring(workflows_dir: Path = WORKFLOWS_DIR) -> list[Violation]:
"""Every Z.AI workflow must compile the shared Logfire export settings."""
violations: list[Violation] = []
for source in sorted(workflows_dir.glob(AGENTIC_GLOB)):
frontmatter = parse_frontmatter(source)
if not _is_zai_workflow(frontmatter):
continue
if 'shared/otel-logfire.md' not in _as_strings(frontmatter.get('imports')):
violations.append(
Violation(str(source), 'logfire-import', 'Z.AI workflow does not import `shared/otel-logfire.md`.')
)
lock = source.with_suffix('.lock.yml')
if not lock.is_file():
violations.append(Violation(str(lock), 'logfire-compiled', 'Z.AI workflow has no compiled lock.'))
continue
compiled = _as_mapping(yaml.safe_load(lock.read_text(encoding='utf-8')))
env = _as_mapping(compiled.get('env'))
required = ('OTEL_EXPORTER_OTLP_ENDPOINT', 'OTEL_EXPORTER_OTLP_HEADERS', 'GH_AW_OTLP_ENDPOINTS')
if not all(isinstance(env.get(name), str) and env[name] for name in required):
violations.append(
Violation(str(lock), 'logfire-compiled', 'Compiled Z.AI workflow lacks shared OTLP export settings.')
)
logfire_hosts = {
'logfire-api.pydantic.dev',
'logfire-eu.pydantic.dev',
'logfire-us.pydantic.dev',
'logfire-api.pydantic.info',
'logfire-eu.pydantic.info',
'logfire-us.pydantic.info',
}
jobs = _as_mapping(compiled.get('jobs'))
allowed_domain_sets: list[set[str]] = []
for job in jobs.values():
steps_value: object = _as_mapping(job).get('steps')
if not _is_object_sequence(steps_value):
continue
for step in steps_value:
domains = _as_mapping(_as_mapping(step).get('env')).get('GH_AW_ALLOWED_DOMAINS')
if isinstance(domains, str):
allowed_domain_sets.append(set(domains.split(',')))
if not allowed_domain_sets or any(not logfire_hosts <= domains for domains in allowed_domain_sets):
violations.append(
Violation(str(lock), 'logfire-network', 'Compiled Z.AI workflow firewall omits Logfire ingest hosts.')
)
return violations
def check_provider_engine_config(workflows_dir: Path = WORKFLOWS_DIR) -> list[Violation]:
"""Shared and workflow-local engines must use the shared provider configuration."""
engine_path = workflows_dir / 'shared' / 'engine-zai.md'
if not engine_path.is_file():
return [Violation(str(engine_path), 'provider-engine-config', 'Shared Z.AI engine configuration is missing.')]
engine_config = parse_frontmatter(engine_path)
shared_engine = _as_mapping(engine_config.get('engine'))
shared_env = _as_mapping(shared_engine.get('env'))
endpoint = shared_env.get('ANTHROPIC_BASE_URL')
credential = shared_env.get('ANTHROPIC_API_KEY')
if not isinstance(endpoint, str) or not endpoint or not isinstance(credential, str) or not credential:
return [
Violation(
str(engine_path),
'provider-engine-config',
'The shared agent engine must define a nonempty `ANTHROPIC_BASE_URL` and `ANTHROPIC_API_KEY`.',
)
]
shared_engines: tuple[tuple[str, object], ...] = (
(
'threat-detection',
_as_mapping(_as_mapping(engine_config.get('safe-outputs')).get('threat-detection')).get('engine'),
),
)
violations: list[Violation] = []
for engine_name, engine_value in shared_engines:
# `false` disables the gh-aw engine; its replacement uses no provider endpoint.
if engine_value is False:
continue
engine_env = _as_mapping(_as_mapping(engine_value).get('env'))
if engine_env.get('ANTHROPIC_BASE_URL') != endpoint or engine_env.get('ANTHROPIC_API_KEY') != credential:
violations.append(
Violation(
str(engine_path),
'provider-engine-config',
f'The shared {engine_name} engine must use the shared agent engine endpoint and credential.',
)
)
source_paths = list(workflows_dir.glob(AGENTIC_GLOB))
for source in (workflows_dir / 'shared' / 'provider-health.md', workflows_dir / 'agent-provider-health.yml'):
if source.is_file():
source_paths.append(source)
for source in source_paths:
frontmatter = parse_frontmatter(source) if source.suffix == '.md' else {}
local_engines: tuple[object, ...] = (
frontmatter.get('engine'),
_as_mapping(_as_mapping(frontmatter.get('safe-outputs')).get('threat-detection')).get('engine'),
)
for local_engine in local_engines:
local_env = _as_mapping(_as_mapping(local_engine).get('env'))
if ('ANTHROPIC_BASE_URL' in local_env or 'ANTHROPIC_API_KEY' in local_env) and (
local_env.get('ANTHROPIC_BASE_URL') != endpoint or local_env.get('ANTHROPIC_API_KEY') != credential
):
violations.append(
Violation(
str(source),
'provider-engine-config',
'A workflow-local engine override must use the shared engine endpoint and credential.',
)
)
return violations
def check_provider_health_wiring(workflows_dir: Path = WORKFLOWS_DIR) -> list[Violation]:
"""Every Z.AI source must gate activation on its compiled provider-health job."""
violations: list[Violation] = []
for source in sorted(workflows_dir.glob(AGENTIC_GLOB)):
frontmatter = parse_frontmatter(source)
imports = _as_strings(frontmatter.get('imports'))
if not _is_zai_workflow(frontmatter):
continue
if 'shared/provider-health.md' not in imports:
violations.append(
Violation(
str(source),
'provider-health-import',
'Z.AI workflow does not import `shared/provider-health.md`.',
)
)
if 'needs.provider_health.outputs.ready' not in parse_prompt_body(source):
violations.append(
Violation(
str(source),
'provider-health-prompt',
'Workflow prompt body must reference `provider_health` so gh-aw hoists the gate before activation.',
)
)
condition = str(frontmatter.get('if', ''))
health_ready_condition = "needs.provider_health.outputs.ready == 'true'"
if not _condition_is_required(condition, health_ready_condition):
violations.append(
Violation(
str(source),
'provider-health-gate',
'Z.AI workflow top-level `if:` must require `provider_health` readiness.',
)
)
safe_outputs = _as_mapping(frontmatter.get('safe-outputs'))
noop = _as_mapping(safe_outputs.get('noop'))
# `report-failed-jobs` files an `[aw] Failed jobs` issue per run with a failed custom job, which
# duplicates the incident the provider-health monitor opens for the same run.
if (
safe_outputs.get('report-failure-as-issue') is not False
or safe_outputs.get('report-failed-jobs') is not False
or noop.get('report-as-issue') is not False
):
violations.append(
Violation(
str(source),
'provider-health-reporting',
'Z.AI workflows must disable gh-aw generic failure-as-issue and failed-job reporting.',
)
)
lock = source.with_suffix('.lock.yml')
if not lock.is_file():
violations.append(Violation(str(source), 'provider-health-lock', f'Compiled workflow `{lock}` is missing.'))
continue
workflow = _as_mapping(yaml.safe_load(lock.read_text(encoding='utf-8')))
jobs = _as_mapping(workflow.get('jobs'))
activation = _as_mapping(jobs.get('activation'))
activation_needs = _as_strings(activation.get('needs'))
activation_condition = str(activation.get('if', ''))
if 'provider_health' not in activation_needs:
violations.append(
Violation(
str(lock),
'provider-health-activation-needs',
'`activation.needs` does not include `provider_health`; the health gate can resolve empty.',
)
)
if not _condition_is_required(activation_condition, health_ready_condition):
violations.append(
Violation(
str(lock),
'provider-health-activation-if',
'`activation.if` does not require `provider_health` readiness before agent execution.',
)
)
health_job = _as_mapping(jobs.get('provider_health'))
if not health_job:
violations.append(
Violation(str(lock), 'provider-health-job', 'Compiled workflow has no `provider_health` job.')
)
elif 'activation' in _as_strings(health_job.get('needs')):
violations.append(
Violation(
str(lock),
'provider-health-job-order',
'`provider_health` depends on `activation` and therefore cannot gate inference.',
)
)
return violations
def check_provider_health_identity(workflows_dir: Path = WORKFLOWS_DIR) -> list[Violation]:
"""The gate and shim must receive the same stable workflow task identity."""
engine_path = workflows_dir / 'shared' / 'engine-zai.md'
health_path = workflows_dir / 'shared' / 'provider-health.md'
if not engine_path.is_file() or not health_path.is_file():
return [
Violation(
str(engine_path), 'provider-health-identity', 'Shared workflow identity configuration is missing.'
)
]
engine = engine_path.read_text(encoding='utf-8')
health = health_path.read_text(encoding='utf-8')
assignment = re.compile(r'^\s*PYDANTIC_AI_TASK_KEY:\s*(.+?)\s*$', re.MULTILINE)
engine_match = re.search(r'^\s*PYDANTIC_AI_TASK_(?:ID|KEY):\s*(.+?)\s*$', engine, re.MULTILINE)
health_match = assignment.search(health)
attempt_assignment = re.compile(r'^\s*PYDANTIC_AI_RUN_ATTEMPT:\s*(.+?)\s*$', re.MULTILINE)
engine_attempt_match = attempt_assignment.search(engine)
health_attempt_match = attempt_assignment.search(health)
workflow_assignment = 'GITHUB_WORKFLOW: ${{ github.workflow }}'
event_assignment = 'PYDANTIC_AI_TRIGGER_EVENT: ${{ github.event_name }}'
expected_attempt = '${{ github.run_attempt }}'
if (
engine_match is None
or health_match is None
or engine_match.group(1) != health_match.group(1)
or engine_attempt_match is None
or health_attempt_match is None
or engine_attempt_match.group(1) != expected_attempt
or health_attempt_match.group(1) != expected_attempt
or workflow_assignment not in engine
or event_assignment not in engine
):
return [
Violation(
str(engine_path),
'provider-health-identity',
'The agent and provider-health job must forward identical workflow, event, and task identities plus the current run attempt.',
)
]
task_key = engine_match.group(1)
manual_run_id = "(github.event_name == 'workflow_dispatch' && github.run_id)"
if (
manual_run_id not in task_key
or 'github.run_id' in task_key.replace(manual_run_id, '')
or 'github.run_attempt' in task_key
or 'workflow_run.run_attempt' in task_key
):
return [
Violation(
str(engine_path),
'provider-health-task-stability',
'`github.run_id` may distinguish manual dispatches but must not change the same workflow task across runs.',
)
]
expected_task_key = task_key
for source in workflows_dir.glob(AGENTIC_GLOB):
frontmatter = parse_frontmatter(source)
imports = _as_strings(frontmatter.get('imports'))
if not _is_zai_workflow(frontmatter) or 'shared/engine-zai.md' in imports:
continue
engine_env = _as_mapping(_as_mapping(frontmatter.get('engine')).get('env'))
if (
engine_env.get('GITHUB_WORKFLOW') != '${{ github.workflow }}'
or engine_env.get('PYDANTIC_AI_TRIGGER_EVENT') != '${{ github.event_name }}'
or engine_env.get('PYDANTIC_AI_RUN_ATTEMPT') != expected_attempt
or (engine_env.get('PYDANTIC_AI_TASK_ID') or engine_env.get('PYDANTIC_AI_TASK_KEY')) != expected_task_key
):
return [
Violation(
str(source),
'provider-health-identity',
'A Z.AI workflow with a local engine config must forward the shared task identity exactly.',
)
]
return []
def check_provider_health_recovery_wiring(workflows_dir: Path = WORKFLOWS_DIR) -> list[Violation]:
"""Z.AI workflows must expose the incident-bound recovery input when dispatch can reach the model."""
violations: list[Violation] = []
for source in sorted(workflows_dir.glob(AGENTIC_GLOB)):
frontmatter = parse_frontmatter(source)
if not _is_zai_workflow(frontmatter):
continue
trigger = _as_mapping(_as_mapping(frontmatter.get('on')).get('workflow_dispatch'))
recovery_input = _as_mapping(_as_mapping(trigger.get('inputs')).get('recovery_issue'))
if recovery_input.get('type') != 'string' or recovery_input.get('required') is not False:
violations.append(
Violation(
str(source),
'provider-health-recovery-input',
'Z.AI workflows must expose optional string input `recovery_issue` for operator-verified recovery.',
)
)
health_path = workflows_dir / 'shared' / 'provider-health.md'
if (
not health_path.is_file()
or "PYDANTIC_AI_RECOVERY_ISSUE: ${{ inputs.recovery_issue || '' }}"
not in health_path.read_text(encoding='utf-8')
):
violations.append(
Violation(
str(health_path),
'provider-health-recovery-input',
'The trusted provider-health job must pass the optional `recovery_issue` input to its artifact.',
)
)
return violations
def check_provider_health_agent_start(workflows_dir: Path = WORKFLOWS_DIR) -> list[Violation]:
"""Z.AI agent jobs must repeat the gate once they hold the agent slot, and stop before inference when blocked."""
violations: list[Violation] = []
for source in sorted(workflows_dir.glob(AGENTIC_GLOB)):
lock = source.with_suffix('.lock.yml')
if not _is_zai_workflow(parse_frontmatter(source)) or not lock.is_file():
continue
jobs = _as_mapping(_as_mapping(yaml.safe_load(lock.read_text(encoding='utf-8'))).get('jobs'))
gate_steps = _as_mapping(jobs.get('provider_health')).get('steps')
agent_steps = _as_mapping(jobs.get('agent')).get('steps')
gate = [_as_mapping(step) for step in gate_steps] if _is_object_sequence(gate_steps) else []
steps = [_as_mapping(step) for step in agent_steps] if _is_object_sequence(agent_steps) else []
gate_env = next((step.get('env') for step in gate if step.get('id') == 'health'), None)
execution = next((i for i, step in enumerate(steps) if step.get('id') == 'agentic_execution'), 0)
recheck = next(
(
i
for i, step in enumerate(steps[:execution])
if AGENT_START_HEALTH_CHECK.search(str(step.get('run', '')))
),
None,
)
stop_condition = f"steps.{steps[recheck].get('id')}.outputs.ready != 'true'" if recheck is not None else None
after_recheck = steps[recheck + 1 : execution] if recheck is not None else []
recheck_name, replace_name, stop_name, account_stop_name = AGENT_START_HEALTH_STEPS
# The monitor recognizes these steps by name, so a renamed step reads as a setup failure.
named = (
recheck is not None
and steps[recheck].get('name') == recheck_name
and any(step.get('name') == replace_name for step in after_recheck)
)
stops = any(
step.get('name') == stop_name
and _normalized_condition(str(step.get('if', ''))) == _normalized_condition(str(stop_condition))
and str(step.get('run', '')).rstrip().endswith('exit 1')
and not step.get('continue-on-error')
for step in after_recheck
)
keyed = (
recheck is not None
and steps[recheck].get('id') == AGENT_START_HEALTH_STEP_ID
and all(_as_mapping(gate_env).get(key) == value for key, value in ZAI_KEYS.items())
)
# A failed replacement leaves the gate's account in the artifact; the run must not go on under another one.
replace_id = next((step.get('id') for step in after_recheck if step.get('name') == replace_name), None)
account_condition = (
f"steps.{replace_id}.outcome == 'failure' && steps.{AGENT_START_HEALTH_STEP_ID}.outputs.account "
'!= needs.provider_health.outputs.account'
)
guards_account = (
replace_id is not None
and _as_mapping(_as_mapping(jobs.get('provider_health')).get('outputs')).get('account')
== '${{ steps.health.outputs.account }}'
and any(
step.get('name') == account_stop_name
and _normalized_condition(str(step.get('if', ''))) == _normalized_condition(account_condition)
and str(step.get('run', '')).rstrip().endswith('exit 1')
and not step.get('continue-on-error')
for step in after_recheck
)
)
if (
recheck is None
or gate_env is None
or steps[recheck].get('env') != gate_env
or not named
or not stops
or not keyed
or not guards_account
):
violations.append(
Violation(
str(lock),
'provider-health-agent-start',
'The agent job must rerun the default-branch provider-health check with the gate environment '
'before engine execution, then fail before inference unless it reports ready. The steps must '
'keep the names in `agent_provider_health.AGENT_START_HEALTH_STEPS`, the recheck its id '
f'`{AGENT_START_HEALTH_STEP_ID}`, and the gate both Z.AI keys and an `account` output. A failed '
"replacement must stop the job when the recheck's account differs from the gate's.",
)
)
return violations
def check_provider_health_host_result(workflows_dir: Path = WORKFLOWS_DIR) -> list[Violation]:
"""Z.AI workflows must record the agent's terminal result in a host job that also follows a failed agent job."""
violations: list[Violation] = []
for source in sorted(workflows_dir.glob(AGENTIC_GLOB)):
lock = source.with_suffix('.lock.yml')
if not _is_zai_workflow(parse_frontmatter(source)) or not lock.is_file():
continue
jobs = _as_mapping(_as_mapping(yaml.safe_load(lock.read_text(encoding='utf-8'))).get('jobs'))
gate_steps = _as_mapping(jobs.get('provider_health')).get('steps')
gate = [_as_mapping(step) for step in gate_steps] if _is_object_sequence(gate_steps) else []
gate_env = _as_mapping(next((step.get('env') for step in gate if step.get('id') == 'health'), None))
if not gate_env or not _records_host_result(_as_mapping(jobs.get(HOST_RESULT_JOB)), gate_env):
violations.append(
Violation(
str(lock),
'provider-health-host-result',
f'The `{HOST_RESULT_JOB}` job must follow the agent job, including a failed one, check out only '
"the default-branch controller, and download this run's `agent` artifact and health decision. "
'Its record step must run exactly the `record` command, skipped only when a download failed, with '
'the gate identity and the Z.AI keys, which nothing else in the job references. It must then '
'upload `run-result.json` with the health decision, and a failed record must not fail the run.',
)
)
return violations
def _records_host_result(job: Mapping[str, object], gate_env: Mapping[str, object]) -> bool:
"""Whether `job` is the host record job `check_provider_health_host_result` requires."""
controller = '.github/scripts/agent_provider_health.py'
raw_steps = job.get('steps')
steps = [_as_mapping(step) for step in raw_steps] if _is_object_sequence(raw_steps) else []
checkouts = [step for step in steps if str(step.get('uses', '')).startswith('actions/checkout@')]
checkout = _as_mapping(checkouts[0].get('with')) if len(checkouts) == 1 else {}
# This run's `agent` artifact and health decision only: no other artifact, run or repository.
downloads = {
str(step.get('id')): i
for i, step in enumerate(steps)
if str(step.get('uses', '')).startswith('actions/download-artifact@')
and (step.get('id'), _as_mapping(step.get('with')))
in (
('agent_artifact', {'name': 'agent', 'path': 'agent'}),
('health_artifact', {'name': 'provider-health', 'path': 'provider-health'}),
)
}
record_command = (
f'python3 -I {controller} record --agent-session agent/agent-session.jsonl '
'--health-artifact provider-health/provider-health.json --output provider-health/run-result.json'
)
record = next(
(
i
for i, step in enumerate(steps)
if ' '.join(str(step.get('run', '')).replace('\\\n', ' ').split()) == record_command
),
None,
)
if len(downloads) != 2 or record is None or record < max(downloads.values()):
return False
record_step = steps[record]
record_env = _as_mapping(record_step.get('env'))
identity = ('GITHUB_WORKFLOW', 'PYDANTIC_AI_TRIGGER_EVENT', 'PYDANTIC_AI_RUN_ATTEMPT', 'PYDANTIC_AI_TASK_KEY')
# gh-aw wraps the authored condition in its clean-detection guard; the authored part also follows a failed agent.
after_agent = _normalized_condition(
"${{ needs.detection.result == 'success' && needs.detection.outputs.detection_success == 'true' && "
"((!cancelled()) && needs.agent.result != 'skipped') }}"
)
# The record step skips only when a download failed.
downloaded = "steps.agent_artifact.outcome == 'success' && steps.health_artifact.outcome == 'success'"
return (
'agent' in _as_strings(job.get('needs'))
and _normalized_condition(str(job.get('if', ''))) == after_agent
and job.get('continue-on-error') is True
and checkout.get('repository') == '${{ github.repository }}'
and checkout.get('ref') == '${{ github.event.repository.default_branch }}'
and checkout.get('persist-credentials') is False
and checkout.get('sparse-checkout') == controller
# A `shell` or `working-directory` would change what the exact command runs.
and set(record_step) <= {'name', 'if', 'env', 'run'}
and _normalized_condition(str(record_step.get('if', ''))) == _normalized_condition(downloaded)
and all(record_env.get(key) == gate_env.get(key) for key in (*identity, *ZAI_KEYS))
and not SECRETS_CONTEXT.search(str({**job, 'steps': steps[:record] + steps[record + 1 :]}))
and any(
str(step.get('uses', '')).startswith('actions/upload-artifact@')
and _as_mapping(step.get('with')).get('name') == 'provider-health'
and 'run-result.json' in str(_as_mapping(step.get('with')).get('path'))
for step in steps[record + 1 :]
)
)
def check_provider_health_monitor(workflows_dir: Path = WORKFLOWS_DIR) -> list[Violation]: # noqa: C901
"""The monitor accepts completions only from the enumerated Z.AI workflows and serializes only incident work."""
monitor_path = workflows_dir / 'agent-provider-health.yml'
if not monitor_path.is_file():
return [Violation(str(monitor_path), 'provider-health-monitor', 'Provider-health monitor is missing.')]
monitor = _as_mapping(yaml.safe_load(monitor_path.read_text(encoding='utf-8')))
triggers = _as_mapping(monitor.get('on'))
workflow_run = _as_mapping(triggers.get('workflow_run'))
monitor_names = _as_strings(workflow_run.get('workflows'))
expected_names = {
str(parse_frontmatter(source).get('name'))
for source in workflows_dir.glob(AGENTIC_GLOB)
if _is_zai_workflow(parse_frontmatter(source))
}
violations: list[Violation] = []
if monitor_names != expected_names:
missing = sorted(expected_names - monitor_names)
unexpected = sorted(monitor_names - expected_names)
violations.append(
Violation(
str(monitor_path),
'provider-health-monitor-workflows',
f'`workflow_run.workflows` must match all Z.AI workflows; missing={missing}, unexpected={unexpected}.',
)
)
if 'workflow_dispatch' not in triggers or 'schedule' not in triggers:
violations.append(
Violation(
str(monitor_path),
'provider-health-monitor-triggers',
'Monitor needs schedule and manual recovery triggers.',
)
)
dispatch_inputs = _as_mapping(_as_mapping(triggers.get('workflow_dispatch')).get('inputs'))
expected_recovery_inputs = {
'recover_issue': ('number', True),
}
for input_name, (input_type, required) in expected_recovery_inputs.items():
configured = _as_mapping(dispatch_inputs.get(input_name))
if configured.get('type') != input_type or configured.get('required') is not required:
violations.append(
Violation(
str(monitor_path),
'provider-health-monitor-recovery-inputs',
'Manual provider recovery must require the original `recover_issue` input.',
)
)
break
if str(monitor.get('name', '')) in monitor_names:
violations.append(
Violation(
str(monitor_path),
'provider-health-monitor-recursion',
'Monitor must not trigger on its own completion.',
)
)
jobs = _as_mapping(monitor.get('jobs'))
triage_job = _as_mapping(jobs.get('triage'))
monitor_job = _as_mapping(jobs.get('monitor'))
if ' '.join(str(triage_job.get('if', '')).split()) != (
"github.repository == 'pydantic/pydantic-ai' && "
"github.event_name == 'workflow_run' && "
"(github.event.workflow_run.event != 'pull_request' || "
'(github.event.workflow_run.head_repository.full_name == github.repository && '
"github.event.workflow_run.actor.login != 'dependabot[bot]')) && "
"(github.event.workflow_run.event != 'pull_request_review' || "
'github.event.workflow_run.head_repository.full_name == github.repository)'
):
violations.append(
Violation(
str(monitor_path),
'provider-health-monitor-credential-gate',
'Triage must exclude fork and Dependabot `pull_request` completions, and fork `pull_request_review` '
'completions.',
)
)
# Only the incident work `triage` hands over may queue; `.github/workflows/AGENTS.md` explains the overflow.
concurrency = _as_mapping(monitor_job.get('concurrency'))
if (
'concurrency' in monitor
or 'concurrency' in triage_job
or not concurrency.get('group')
or concurrency.get('cancel-in-progress') is not False
):
violations.append(
Violation(
str(monitor_path),
'provider-health-monitor-concurrency',
'Only the `monitor` job may hold the one non-cancelling concurrency group, never the workflow or triage.',
)
)
if concurrency.get('queue') != 'max':
violations.append(
Violation(
str(monitor_path),
'provider-health-monitor-queue',
'Monitor reconciliation must use FIFO `queue: max` and retain up to the platform limit of 100 pending runs.',
)
)
triage_steps: list[Mapping[str, object]] = []
steps: list[Mapping[str, object]] = []
for job, job_steps in ((triage_job, triage_steps), (monitor_job, steps)):
steps_value: object = job.get('steps')
if _is_object_sequence(steps_value):
for raw_step in steps_value:
step = _as_mapping(raw_step)
if step:
job_steps.append(step)
triage_command = 'python3 .github/scripts/agent_provider_health.py triage'
monitor_command = 'python3 .github/scripts/agent_provider_health.py monitor'
# Triage classifies a completion for the monitor, so both must read the same artifacts the same way.
triage_index = next((i for i, step in enumerate(triage_steps) if step.get('id') == 'triage'), len(triage_steps))
reconcile_index = next(
(
i
for i, step in enumerate(steps)
if "github.event_name == 'workflow_run'" in str(step.get('if', ''))
and str(step.get('run', '')).strip().startswith(monitor_command)
),
len(steps),
)
triage_step: Mapping[str, object] = triage_steps[triage_index] if triage_index < len(triage_steps) else {}
reconcile_step: Mapping[str, object] = steps[reconcile_index] if reconcile_index < len(steps) else {}
triage_reads_monitor_inputs = (
str(triage_step.get('run', '')).strip().startswith(triage_command)
and triage_steps[:triage_index] == steps[:reconcile_index]
and triage_step.get('if') == reconcile_step.get('if')
and triage_step.get('env') == reconcile_step.get('env')
and str(triage_step.get('run', '')).replace(triage_command, monitor_command, 1)
== str(reconcile_step.get('run', ''))
)
if (
monitor_job.get('needs') != 'triage'
or ' '.join(str(monitor_job.get('if', '')).split())
!= "!cancelled() && github.repository == 'pydantic/pydantic-ai' && "
"(github.event_name != 'workflow_run' || needs.triage.outputs.reconcile == 'true')"
or _as_mapping(triage_job.get('outputs')).get('reconcile') != '${{ steps.triage.outputs.reconcile }}'
or not triage_reads_monitor_inputs
):
violations.append(
Violation(
str(monitor_path),
'provider-health-monitor-triage',
'The monitor job must reconcile a completion only when `triage`, reading the same artifacts '
'with the same steps, hands it over, and must still run scheduled and manual recovery.',
)
)
untrusted_checkout = False
for job_steps in (triage_steps, steps):
checkout_steps: list[Mapping[str, object]] = [
step for step in job_steps if str(step.get('uses', '')).startswith('actions/checkout@')
]
checkout: Mapping[str, object] = _as_mapping(checkout_steps[0].get('with')) if len(checkout_steps) == 1 else {}
untrusted_checkout = untrusted_checkout or (
len(checkout_steps) != 1
or checkout.get('repository') != '${{ github.repository }}'
or checkout.get('ref') != '${{ github.event.repository.default_branch }}'
or checkout.get('persist-credentials') is not False
or checkout.get('sparse-checkout') != '.github/scripts/agent_provider_health.py'
)
if untrusted_checkout:
violations.append(
Violation(
str(monitor_path),
'provider-health-monitor-trusted-checkout',
'Triage and monitor must each check out only the controller script from the repository default branch, '
'without persisted credentials.',
)
)
artifact_steps: list[Mapping[str, object]] = [
step for step in triage_steps + steps if str(step.get('uses', '')).startswith('actions/download-artifact@')
]
source_artifact_condition = "github.event_name == 'workflow_run'"
if any(
not (
(
str(step.get('if', '')).strip() == source_artifact_condition
or str(step.get('if', '')).strip().startswith(source_artifact_condition + ' && ')
)
and _as_mapping(step.get('with')).get('run-id') == '${{ github.event.workflow_run.id }}'
)
for step in artifact_steps
):
violations.append(
Violation(
str(monitor_path),
'provider-health-monitor-artifact-trigger',
'Artifacts may only be downloaded for allowlisted workflow completions and their exact source run.',
)
)
artifact_paths = re.compile(r'(?:^|[\s"\'=])(?:\./)?(?:agent|provider-health)/\S+')
artifact_execution = False
for step in triage_steps + steps:
uses = str(step.get('uses', ''))
run = str(step.get('run', '')).strip()
if uses.startswith(('./agent/', './provider-health/')):
artifact_execution = True
if not artifact_paths.search(run):
continue
is_stub = run.splitlines() == ['mkdir -p agent', ': > agent/agent-stdio.log']
is_controller = (
run.startswith((monitor_command, triage_command)) and '\n' not in run and not re.search(r';|&&|\|\|', run)
)
if not is_stub and not is_controller:
artifact_execution = True
if artifact_execution:
violations.append(
Violation(
str(monitor_path),
'provider-health-monitor-artifact-execution',
'Downloaded agent artifacts must be parsed only as input to the trusted controller, never executed as code.',
)
)
provider_keys = tuple(ZAI_KEYS)
workflow_env: Mapping[str, object] = _as_mapping(monitor.get('env'))
job_env: Mapping[str, object] = _as_mapping(monitor_job.get('env'))
if job_env.get('PYDANTIC_AI_RUN_ATTEMPT') != '${{ github.run_attempt }}':
violations.append(
Violation(
str(monitor_path),
'provider-health-monitor-run-attempt',
'Monitor job must pass its own positive run attempt to scheduled and manual reconciliation.',
)
)
source_attempt_mismatch = False
for job_steps, command in (
(triage_steps, triage_command),
(steps, monitor_command),
):
source_reconcile_steps = [
step
for step in job_steps
if "github.event_name == 'workflow_run'" in str(step.get('if', ''))
and str(step.get('run', '')).strip().startswith(command)
]
source_attempt_mismatch = source_attempt_mismatch or (
len(source_reconcile_steps) != 1
or _as_mapping(source_reconcile_steps[0].get('env')).get('RUN_ATTEMPT')
!= '${{ github.event.workflow_run.run_attempt }}'
or '--run-attempt "$RUN_ATTEMPT"' not in str(source_reconcile_steps[0].get('run', ''))
)
if source_attempt_mismatch:
violations.append(
Violation(
str(monitor_path),
'provider-health-monitor-source-run-attempt',
'Completed workflow reconciliation must pass the source workflow run attempt from the workflow_run event.',
)
)
recovery_steps = [
step
for step in steps
if str(step.get('if', '')).strip() == "github.event_name == 'workflow_dispatch'"
and 'ISSUE_NUMBER' in _as_mapping(step.get('env'))
]
if (
len(recovery_steps) != 1
or _as_mapping(recovery_steps[0].get('env')).get('ISSUE_NUMBER') != '${{ inputs.recover_issue }}'
or '--recover-issue "$ISSUE_NUMBER"' not in str(recovery_steps[0].get('run', ''))
):
violations.append(
Violation(
str(monitor_path),
'provider-health-monitor-manual-recovery',
'Manual provider recovery must pass the original `recover_issue` input to the controller.',
)
)
provider_key_events: dict[str, set[str]] = {key: set() for key in provider_keys}
triage_env: Mapping[str, object] = _as_mapping(triage_job.get('env'))
if any(
key in workflow_env
or key in job_env
or key in triage_env
or any(key in _as_mapping(step.get('env')) for step in triage_steps)
for key in provider_keys
):
violations.append(
Violation(
str(monitor_path),
'provider-health-monitor-provider-event-scope',
'Z.AI credentials must not be inherited by `workflow_run` steps.',
)
)
for step in steps:
step_env = _as_mapping(step.get('env'))
event_condition = str(step.get('if', ''))
for key in provider_keys:
if key not in step_env:
continue
if event_condition.strip() == "github.event_name == 'schedule'":
provider_key_events[key].add('schedule')
elif event_condition.strip() == "github.event_name == 'workflow_dispatch'":
provider_key_events[key].add('workflow_dispatch')
else:
provider_key_events[key].add('other')
expected_recovery_events: set[str] = {'schedule', 'workflow_dispatch'}
if any(provider_key_events[key] != expected_recovery_events for key in provider_keys):
violations.append(
Violation(
str(monitor_path),
'provider-health-monitor-provider-event-scope',
'Z.AI credentials must be scoped exactly to scheduled or explicitly requested recovery, never `workflow_run`.',
)
)
permissions = _as_mapping(monitor_job.get('permissions'))
if permissions != {
'actions': 'read',
'contents': 'read',
'issues': 'write',
'pull-requests': 'read',
}:
violations.append(
Violation(
str(monitor_path),
'provider-health-monitor-permissions',
'Monitor job permissions must be exactly `actions: read`, `contents: read`, `issues: write`, '
'and `pull-requests: read`.',
)
)
if _as_mapping(triage_job.get('permissions')) != {'actions': 'read', 'contents': 'read'}:
violations.append(
Violation(
str(monitor_path),
'provider-health-monitor-permissions',
'Triage job permissions must be exactly `actions: read` and `contents: read`.',
)
)
return violations
def check_assigned_alert_metadata_gate(workflows_dir: Path = WORKFLOWS_DIR) -> list[Violation]:
"""Operational metadata issues must not start the @claude issue-assignment agent."""
source = workflows_dir / 'at-claude.yml'
if not source.is_file():
return [Violation(str(source), 'assigned-alert-metadata-gate', '@claude workflow is missing.')]
workflow = _as_mapping(yaml.safe_load(source.read_text(encoding='utf-8')))
jobs = _as_mapping(workflow.get('jobs'))
job_condition = str(_as_mapping(jobs.get('get-pr-info')).get('if', ''))
branches = _boolean_branches(job_condition)
metadata_gate = _normalized_condition("!contains(github.event.issue.labels.*.name, 'pydanty:meta')")
event_pattern = re.compile(r"github\.event_name\s*==\s*'([^']+)'")
routes_are_gated = bool(branches)
for event in ('issue_comment', 'issues'):
relevant_branches: list[list[str]] = []
for branch in branches:
branch_events = {found for term in branch for found in event_pattern.findall(term)}
if event in branch_events or not branch_events:
relevant_branches.append(branch)
if not relevant_branches or any(
metadata_gate not in {_normalized_condition(term) for term in branch} for branch in relevant_branches
):
routes_are_gated = False
break
if not routes_are_gated:
return [
Violation(
str(source),
'assigned-alert-metadata-gate',
'`issues` and `issue_comment` route predicates must exclude `pydanty:meta` operational alerts.',
)
]
return []
def check_at_claude_maintainer_threads(workflows_dir: Path = WORKFLOWS_DIR) -> list[Violation]:
"""Same-repo @claude must run only on maintainers' threads, with the action's context from their comments only."""
source = workflows_dir / 'at-claude.yml'
if not source.is_file():
return [Violation(str(source), 'at-claude-maintainer-threads', '@claude workflow is missing.')]
jobs = _as_mapping(_as_mapping(yaml.safe_load(source.read_text(encoding='utf-8'))).get('jobs'))
outputs = _as_mapping(_as_mapping(jobs.get('get-pr-info')).get('outputs'))
job = _as_mapping(jobs.get('at-claude'))
violations: list[Violation] = []
gate = 'contains(fromJSON(\'["write","admin"]\'), needs.get-pr-info.outputs.thread_author_permission)'
if not outputs.get('thread_author_permission') or not _condition_is_required(str(job.get('if', '')), gate):
violations.append(
Violation(
str(source),
'at-claude-maintainer-threads',
'`at-claude` must require `write` or `admin` permission from the thread author.',
)
)
raw_steps = job.get('steps')
steps = [_as_mapping(step) for step in raw_steps] if _is_object_sequence(raw_steps) else []
actions = [
_as_mapping(step.get('with'))
for step in steps
if str(step.get('uses', '')).startswith('anthropics/claude-code-action@')
]
authors = '${{ needs.get-pr-info.outputs.included_comment_authors }}'
non_empty = "needs.get-pr-info.outputs.included_comment_authors != ''"
if (
not outputs.get('included_comment_authors')
or not _condition_is_required(str(job.get('if', '')), non_empty)
or not actions
or any(action.get('include_comments_by_actor') != authors for action in actions)
):
violations.append(
Violation(
str(source),
'at-claude-maintainer-threads',
'`at-claude` must pass `include_comments_by_actor` from `get-pr-info` and skip when it is empty; '
'an empty value includes every commenter.',
)
)
return violations
def changed_files(base_ref: str) -> list[str]:
"""Return paths changed relative to `base_ref` (empty if git can't resolve it)."""
try:
completed = subprocess.run(
['git', 'diff', '--name-only', f'{base_ref}...HEAD'],
capture_output=True,
text=True,
check=True,
)
except (subprocess.CalledProcessError, FileNotFoundError):
return []
return [line for line in completed.stdout.splitlines() if line]
def run_checks(
workflows_dir: Path = WORKFLOWS_DIR,
changed: list[str] | None = None,
compatibility: dict[str, Any] | None = None,
) -> list[Violation]:
"""Run every static check; `changed` enables the lock-freshness check."""
sources = sorted(workflows_dir.glob(AGENTIC_GLOB))
locks = sorted(workflows_dir.glob('*.lock.yml'))
# Resolve `shared/` under the caller's `workflows_dir`, not the module global, so a
# custom root scans its own fragments rather than whatever sits under the cwd.
# `rglob`, not `glob`: the F3 defect this scan exists to catch lived in
# `shared/prompts/pydantic-ai-pr-review.md`. Those prompts are fetched at run time
# rather than compiled in, so they change with no lock diff and are the least
# reviewed files here — the last ones a path check should skip.
shared_dir = workflows_dir / 'shared'
shared = sorted(shared_dir.rglob('*.md')) if shared_dir.is_dir() else []
violations: list[Violation] = []
for lock in locks:
violations += check_dangling_needs(lock)
violations += check_compiled_runner_contract(lock)
violations += check_awf_binary_version(lock)
violations += check_ai_credits_accounting(lock)
violations += check_daily_aic_guardrail(lock)
violations += check_engine_sys_path_order(lock)
for source in sources:
violations += check_safe_output_job_max(source)
violations += check_timeout_declared(source)
violations += check_job_timeout_env(source)
for markdown in [*sources, *shared]:
violations += check_prompt_paths(markdown)
violations += check_compiler_versions(locks)
violations += check_logfire_wiring(workflows_dir)
violations += check_provider_engine_config(workflows_dir)
violations += check_provider_health_wiring(workflows_dir)
violations += check_provider_health_identity(workflows_dir)
violations += check_provider_health_recovery_wiring(workflows_dir)
violations += check_provider_health_agent_start(workflows_dir)
violations += check_provider_health_host_result(workflows_dir)
violations += check_provider_health_monitor(workflows_dir)
violations += check_assigned_alert_metadata_gate(workflows_dir)
violations += check_at_claude_maintainer_threads(workflows_dir)
if compatibility is not None:
violations += check_compiler_version_compatibility(locks, compatibility)
if changed:
violations += check_lock_regenerated(changed, workflows_dir)
return violations
def main(argv: list[str] | None = None) -> int:
"""Print every violation to stderr and return the process exit code."""
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('command', choices=['check'])
parser.add_argument('--base-ref', default='', help='git ref to diff against for lock-freshness')
parser.add_argument(
'--changed-file-list',
default='',
help=(
'file holding one changed path per line, for lock-freshness. Prefer this in CI, where the '
'checkout is shallow and a `git diff` range cannot resolve: feed it `gh pr view --json files`.'
),
)
parser.add_argument(
'--compatibility-file',
type=Path,
help='gh-aw compatibility policy downloaded from `.github/aw/compat.json` in github/gh-aw',
)
args = parser.parse_args(argv)
if args.changed_file_list:
# `splitlines`, not `split`: the producer writes one path per line, and a path
# containing a space would otherwise become two paths that match nothing — the
# real file's lock freshness then goes unchecked while the run still passes.
text = Path(args.changed_file_list).read_text(encoding='utf-8')
changed = [line for line in text.splitlines() if line.strip()]
elif args.base_ref:
changed = changed_files(args.base_ref)
else:
changed = None
if args.compatibility_file is None:
violations = run_checks(changed=changed)
else:
try:
compatibility = _as_mapping(json.loads(args.compatibility_file.read_text(encoding='utf-8')))
except (OSError, json.JSONDecodeError) as error:
print(f'{args.compatibility_file}: [compiler-compatibility-policy-invalid] {error}', file=sys.stderr)
return 1
violations = run_checks(changed=changed, compatibility=compatibility)
for violation in violations:
print(violation, file=sys.stderr)
if violations:
print(f'\n{len(violations)} agentic-workflow policy violation(s).', file=sys.stderr)
return 1
print('Agentic workflow policy checks passed.')
return 0
if __name__ == '__main__':
raise SystemExit(main())