From fa0d438baed8419717503b0ff62169300e8f4735 Mon Sep 17 00:00:00 2001 From: "r4yharris-agent-coder[bot]" <334673250+r4yharris-agent-coder[bot]@users.noreply.github.com> Date: Tue, 29 Sep 2026 13:45:11 -0400 Subject: [PATCH] fix: require AI-Model on agent publishes AI-Agent: r4yharris-agent-coder AI-Model: GPT-6-Sol AI-Run: 1|github-copilot|GPT-6-Sol@unknown|-|-/-|-|-|- --- .github/copilot-instructions.md | 4 +- AGENTS.md | 4 +- COPILOT_DAY1_PROMPT.md | 2 +- README.md | 8 ++-- docs/METRICS.md | 12 ++--- docs/adopt.md | 4 +- docs/commit-trailers.md | 10 ++-- docs/github-app-agent-identity.md | 2 +- scripts/agent-pr.mjs | 18 +++---- scripts/check-agent-trailers.mjs | 16 +++++-- scripts/check-pr-agent-trailers.mjs | 4 +- scripts/parse-agent-run.mjs | 15 ++++-- skills/signed-bot-commit/SKILL.md | 10 ++-- tests/agent-pr.test.mjs | 65 ++++++++++++++++++++------ tests/agent-run.test.mjs | 5 +- tests/check-agent-trailers.test.mjs | 32 +++++++++---- tests/check-pr-agent-trailers.test.mjs | 16 ++++--- 17 files changed, 148 insertions(+), 79 deletions(-) diff --git a/.github/copilot-instructions.md b/.github/copilot-instructions.md index 0b23598..4b68b23 100644 --- a/.github/copilot-instructions.md +++ b/.github/copilot-instructions.md @@ -15,7 +15,7 @@ This workspace is **github-agent-contracts** only. - After reviewing/staging files, passing tests and policy gates, invoke the helper as the final step only after authorization for commit, push, and a draft PR. A request to stop after writing files and testing means no publication. Missing App configuration means leave changes uncommitted after tests. Humans may perform their own bootstrap commits. - The human supplies `GITHUB_APP_ID` and `GITHUB_APP_PRIVATE_KEY_PATH` in the environment. Do not read the PEM into chat, print tokens, or stage/commit `.env` or key files; the helper does not load `.env`. - Use the consuming user/org's own App through `docs/ONBOARDING.md` and `docs/app-manifest.json`; do not recommend the maintainer demo App for private or production repositories. -- The helper discovers the configured App's verified bot identity for author and committer and uses its slug in `AI-Agent`. `--model` defaults to `unknown`; `--files` must be last. Without it, only reviewed staged changes are committed. +- The helper discovers the configured App's verified bot identity for author and committer and uses its slug in `AI-Agent`. Supply the actual model id through `--model` or `AI_MODEL`; there is no `unknown` fallback, and agents must not invent one. `--files` must be last. Without it, only reviewed staged changes are committed. - Run tests first. On a missing prerequisite or failed publication, stop rather than falling back to raw Git; a partial failure can leave a valid local commit. Commits are unsigned, so do not invoke the helper when signing is required. - Keep examples scoped: GitHub App installation tokens, MCP tool allowlists, `permissions: read-all` plus explicit safe-outputs. @@ -24,5 +24,5 @@ Authorized publication example: ```bash node scripts/load-agent-policy.mjs --role coder --capability commit_branch node scripts/load-agent-policy.mjs --role coder --capability open_pr -node scripts/agent-pr.mjs --message "docs: clarify agent contracts" --model unknown --files README.md +node scripts/agent-pr.mjs --message "docs: clarify agent contracts" --model gpt-5 --files README.md ``` diff --git a/AGENTS.md b/AGENTS.md index 5b4e701..c1d3ca2 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -50,7 +50,7 @@ node scripts/load-agent-policy.mjs --role coder --capability open_pr - Only use `--merge-when-green` when the human also authorizes merging and remote feature-branch deletion. A human must first add `merge` to `roles.merger.allow` in root `agent-policy.yml` and publish that grant on the default branch. Never edit the policy yourself or treat the flag as a grant. Keep the flag disabled on coder-only WSL; a trusted launcher/operator must use a separately approved merger App/context for merging. - The human supplies `GITHUB_APP_ID` and `GITHUB_APP_PRIVATE_KEY_PATH` through the environment. Never read the PEM into chat, paste key material, print tokens, or commit `.env` or private-key files. The script does not load `.env` automatically. - Default onboarding is a user/org-owned App from `docs/app-manifest.json`; follow `docs/ONBOARDING.md` and `docs/THREAT_MODEL.md`. Never recommend the maintainer's `r4yharris-agent-coder` App for private or production repositories; a demo install is for public playgrounds only. -- The helper verifies origin's installation against `GITHUB_APP_ID`, resolves that App's bot account, sets both author and committer to it, and adds `AI-Agent: ` plus `AI-Model: unknown`. Do not hard-code or invent a bot identity; use `--model` when the model is known. +- The helper verifies origin's installation against `GITHUB_APP_ID`, resolves that App's bot account, sets both author and committer to it, and adds `AI-Agent: ` plus the actual `AI-Model` id from `--model` or `AI_MODEL`. Neither has an `unknown` fallback; if the model is unavailable, stop without publishing. Do not hard-code or invent a bot identity or model. - Without `--files`, it commits the reviewed staged changes. With `--files`, pass individual repository files last; unrelated staged files cause a failure. Staged or selected `.github/workflows/**` paths are refused before token minting; a human must publish workflow changes. Inspect the changes and run the tests before publication. - Node 20+, Git, and `gh` are required. The App must be installed on origin's repository with contents and pull requests write permissions; the opt-in merge flow also needs Checks read permission. The helper creates a repository-scoped installation token, pushes without force, creates a draft PR only if no open PR exists, and revokes the token. - This is the explicitly authorized branch-publication path, not a general grant of GitHub write permissions. It refuses main, master, and the repository's default branch. Never bypass repository protections. @@ -59,7 +59,7 @@ node scripts/load-agent-policy.mjs --role coder --capability open_pr - Commits are unsigned for now. If signing is required or any step fails, stop and report it without a raw Git fallback. A human may commit a bootstrap slice themselves; agents may not assume that identity. After a partial failure, inspect the existing commit and PR before retrying. ```bash -node scripts/agent-pr.mjs --message "docs: clarify agent contracts" --model unknown --files README.md +node scripts/agent-pr.mjs --message "docs: clarify agent contracts" --model gpt-5 --files README.md ``` ## Optional run metadata diff --git a/COPILOT_DAY1_PROMPT.md b/COPILOT_DAY1_PROMPT.md index 4db004d..eca81f6 100644 --- a/COPILOT_DAY1_PROMPT.md +++ b/COPILOT_DAY1_PROMPT.md @@ -32,7 +32,7 @@ Required trailers when a commit is classified as agent-authored: ``` AI-Agent: -AI-Model: +AI-Model: ``` Recommended: diff --git a/README.md b/README.md index 9bd65bc..62a9f84 100644 --- a/README.md +++ b/README.md @@ -31,7 +31,7 @@ This is **not a git host, not `copilot[bot]`, not a personal access token (PAT), The control is **required PR check + protected branch + bot author + trailers**. The App authenticates GitHub operations. App permissions, branch protection/environments, and the policy must all allow an action; installing an App or adding a prompt does not replace these gates. -The [publisher](scripts/agent-pr.mjs) discovers the configured App's bot, sets both author and committer, appends `AI-Agent` and `AI-Model`, pushes an authorized feature branch, and creates a draft PR if none exists. It uses `GITHUB_APP_ID` and `GITHUB_APP_PRIVATE_KEY_PATH` from the environment, not a signed-in human's credentials. Missing configuration or denied policy means stop with changes uncommitted. +The [publisher](scripts/agent-pr.mjs) discovers the configured App's bot, sets both author and committer, appends `AI-Agent` and the actual `AI-Model` id, pushes an authorized feature branch, and creates a draft PR if none exists. Supply the model through `--model` or `AI_MODEL`; missing or placeholder values stop publication rather than inventing a model. It uses `GITHUB_APP_ID` and `GITHUB_APP_PRIVATE_KEY_PATH` from the environment, not a signed-in human's credentials. Missing configuration or denied policy means stop with changes uncommitted. Humans own policy and workflow changes. Agents cannot grant themselves capabilities or publish `.github/workflows/**` through this helper. Never force-push, push main directly, squash, or self-approve. Deploy and direct protected-push implementations are out of scope. @@ -68,16 +68,16 @@ An agent commit has a blank-separated footer: ```text AI-Agent: your-app-slug -AI-Model: unknown +AI-Model: gpt-5 ``` -The check inspects messages containing `AI-Agent:` and GitHub noreply bot authors by default. Unmarked human commits pass. `--require`, or the Action's `require-on-all-commits: "true"`, requires trailers on every commit. See the [trailer specification](docs/commit-trailers.md) for parsing, exit codes, and limits. +`gpt-5` is an example; use the actual model id for each run. The check inspects messages containing `AI-Agent:` and GitHub noreply bot authors by default, and rejects missing or placeholder models. Unmarked human commits pass. `--require`, or the Action's `require-on-all-commits: "true"`, requires trailers on every commit. See the [trailer specification](docs/commit-trailers.md) for parsing, exit codes, and limits. The [PR workflow](.github/workflows/check-agent-trailers.yml) uses the trusted base revision's checker with full history and read-only permissions. Bootstrap the Action and scripts before enabling the local workflow. Humans must configure required checks, reviews, and branch protection; the script does not configure them. ## Optional run metadata (v0.2.0) -Harnesses can supply compact run information through the documented `AI_*` environment variables. The publisher adds one optional `AI-Run` trailer and upserts a tagged PR body pair; with no supplied metadata, publishing and the default two-trailer check remain unchanged. `--require-run` opts into validation. [METRICS.md](docs/METRICS.md) specifies the format, human-only `AI-Eval` comments, and local JSONL export with [export-agent-metrics.mjs](scripts/export-agent-metrics.mjs). No analytics service, prompts, traces, or generated quality scores are added. +Harnesses can supply compact run information through the documented `AI_*` environment variables. The publisher adds one optional `AI-Run` trailer and upserts a tagged PR body pair; with no supplied optional metadata (but with the required model id), publishing and the default two-trailer check remain unchanged. `--require-run` opts into validation. [METRICS.md](docs/METRICS.md) specifies the format, human-only `AI-Eval` comments, and local JSONL export with [export-agent-metrics.mjs](scripts/export-agent-metrics.mjs). No analytics service, prompts, traces, or generated quality scores are added. ## With gh-aw diff --git a/docs/METRICS.md b/docs/METRICS.md index d41b36e..09baf89 100644 --- a/docs/METRICS.md +++ b/docs/METRICS.md @@ -1,6 +1,6 @@ # Compact agent-run metadata -v0.2.0 adds one optional `AI-Run` trailer. The required `AI-Agent` and `AI-Model` trailers are unchanged. Run metadata is harness-supplied provenance, not proof of authorship, an analytics service, or a quality score. Do not put prompts, traces, credentials, or free-form notes in git. +v0.2.0 adds one optional `AI-Run` trailer. `AI-Agent` and `AI-Model` remain required; `AI-Model` must identify the actual model, not `unknown`. Run metadata is harness-supplied provenance, not proof of authorship, an analytics service, or a quality score. Do not put prompts, traces, credentials, or free-form notes in git. ## Schema 1 @@ -27,9 +27,9 @@ AI-Run: 1|anthropic|claude-sonnet-4.5@20250901|h|18234/200000|2510|ses_01K8|feat | 7: session | Opaque `[A-Za-z0-9._-]{1,64}` identifier | | 8: task | Opaque `[A-Za-z0-9._-]{1,64}` identifier | -Use `-` as the missing-value sentinel for provider, effort, counts, session, and task. It is not another provider or effort level. A missing version is `unknown`, giving `@unknown`. The required `AI-Model` retains its existing `unknown` fallback; when only a provider is supplied, column 3 is `unknown@unknown`. +Use `-` as the missing-value sentinel for provider, effort, counts, session, and task. It is not another provider or effort level. A missing version is `unknown`, giving `@unknown`. A missing model is not a metadata slot: the publisher refuses to create an agent commit without the actual model id. -Keep all eight columns, with no spaces around `|`. Model names are single-line tokens; they may include a provider path such as `owner/model`, but cannot contain whitespace, `|`, `@`, or backticks. No field supplied by the harness may contain a pipe. Session and task identifiers must not contain personal data or secrets. +Keep all eight columns, with no spaces around `|`. Model ids are single-line tokens starting with a letter or digit and may contain letters, digits, `.`, `_`, `-`, `:`, `/`, or `+`, including a provider path such as `owner/model`. Placeholders and whitespace, `|`, `@`, or backticks are invalid. No field supplied by the harness may contain a pipe. Session and task identifiers must not contain personal data or secrets. Parsers ignore extra trailing `|fields` for forward compatibility. Unknown unrelated trailer keys are ignored. When a schema-bearing `AI-Run` is present, invalid columns 1-8 cause a parse error; unsupported schemas are errors too. An absent or empty `AI-Run` has no schema and produces no record. Extra fields do not rescue invalid known columns. There is no `AI-X-*` family or additional YAML document. @@ -40,7 +40,7 @@ Export only values actually reported by the harness before invoking [agent-pr.mj | Environment variable | Stored value | When missing | | --- | --- | --- | | `AI_PROVIDER` | Provider from the allowed list | `-` | -| `AI_MODEL` | Required `AI-Model` and model part of column 3 | `unknown` in the required trailer | +| `AI_MODEL` | Required `AI-Model` and model part of column 3 | Supply `--model` or publishing exits `2` | | `AI_MODEL_VERSION` | Version token in column 3 | `unknown` | | `AI_EFFORT` | `low`/`l` -> `l`, `medium`/`m` -> `m`, `high`/`h` -> `h`, `max`/`x` -> `x` | `-` | | `AI_CONTEXT_USED` | `in` | `-` | @@ -49,9 +49,9 @@ Export only values actually reported by the harness before invoking [agent-pr.mj | `AI_SESSION` | Session identifier | `-` | | `AI_TASK` | Task identifier | `-` | -`--model` takes precedence over `AI_MODEL`; both the required trailer and `AI-Run` use the selected model. If all nine variables are unset or empty, no `AI-Run` is written, even with `--model`. `AI_MODEL` alone counts as environment input. If some variables are supplied, keep the trailer with missing-slot sentinels unless both provider and the explicitly supplied model are empty. Do not invent identity information just to emit a record. Malformed supplied values, including an unknown effort, are rejected before key access or GitHub requests. +`--model` takes precedence over `AI_MODEL`; both the required trailer and `AI-Run` use the selected model. The publisher exits `2` if neither supplies a valid model id; it never invents one. If all nine variables are unset or empty, no `AI-Run` is written, even with `--model`. `AI_MODEL` alone counts as environment input. With run input and a known model, missing slots use sentinels. Do not invent identity information just to emit a record. Malformed supplied values, including an unknown effort, are rejected before key access or GitHub requests. -For example, provider-only input `AI_PROVIDER=local` produces `1|local|unknown@unknown|-|-/-|-|-|-`. Model-only input `AI_MODEL=known-model` produces `1|-|known-model@unknown|-|-/-|-|-|-`. Counts of zero stay `0`, not `-`. +For example, `AI_PROVIDER=local` with `--model gpt-5` produces `1|local|gpt-5@unknown|-|-/-|-|-|-`. Model-only input `AI_MODEL=known-model` produces `1|-|known-model@unknown|-|-/-|-|-|-`. Counts of zero stay `0`, not `-`. The `unknown` suffix is a missing model **version**, not a missing model id. ## PR body diff --git a/docs/adopt.md b/docs/adopt.md index df8e7f1..e8a5d67 100644 --- a/docs/adopt.md +++ b/docs/adopt.md @@ -63,7 +63,7 @@ Agent-classified commits need a blank-separated footer such as: feat: add input validation AI-Agent: copilot-coding-agent -AI-Model: unknown +AI-Model: gpt-5 ``` To require trailers on human commits too, set this input in the Action step's `with:` block: @@ -72,7 +72,7 @@ To require trailers on human commits too, set this input in the Action step's `w require-on-all-commits: "true" ``` -The default is `"false"`. Missing required trailers fail the check, as do invalid commit ranges or incomplete history. Trailers and author emails are provenance claims, not proof of identity or authorization to write to GitHub. +The default is `"false"`. Missing required trailers and placeholder models fail the check, as do invalid commit ranges or incomplete history. `gpt-5` above is an example; use the model id actually reported by the harness. Trailers and author emails are provenance claims, not proof of identity or authorization to write to GitHub. Before requiring the check, verify a PR with valid trailers passes and a marked agent commit missing `AI-Model` fails. In the default mode, an unmarked human commit should pass; in require-all mode, it should fail. Every commit in the PR must satisfy the selected policy, not just the latest commit. diff --git a/docs/commit-trailers.md b/docs/commit-trailers.md index 3662e13..cc3b3b0 100644 --- a/docs/commit-trailers.md +++ b/docs/commit-trailers.md @@ -10,7 +10,7 @@ AI-Model: gpt-4.1 ``` `AI-Agent` is a stable role name (`copilot-coding-agent`, `hermes-coder`, `codex-cli`). -`AI-Model` may be `unknown` if the harness does not expose it. +`AI-Model` must contain the actual model id reported by the harness. It must start with a letter or digit and contain only letters, digits, `.`, `_`, `-`, `:`, `/`, or `+`; placeholders such as `unknown`, `none`, `n/a`, and `unspecified` are invalid. If the model is not known, do not invent one or publish an agent commit. The publisher requires `--model` or `AI_MODEL` and exits `2` before publication when neither supplies a valid model. `--model` takes precedence over `AI_MODEL`; neither has an `unknown` fallback. ## Optional compact run metadata @@ -43,7 +43,7 @@ feat: add health endpoint Return 200 and uptime JSON from GET /health. AI-Agent: hermes-coder -AI-Model: unknown +AI-Model: claude-sonnet-4.5 AI-Session: sess_01 Co-authored-by: Jane Doe ``` @@ -58,7 +58,7 @@ Co-authored-by: Jane Doe For example, `123+coder[bot]@users.noreply.github.com` is a bot address; `123+human@users.noreply.github.com` is not. The PR Action supplies each commit's author email automatically. Local message-only checks cannot infer the author. -Required values must be nonempty and use the exact keys `AI-Agent` and `AI-Model`. The checker parses the final contiguous block of `Key: value` lines, separated from the subject or body by a blank line. A marker in the subject or body triggers checking but does not count as a valid trailer. CRLF and trailing blank lines are supported; the last occurrence of a repeated key wins. +Required values must be nonempty and use the exact keys `AI-Agent` and `AI-Model`; an invalid model id fails the check even when the trailer is present. The checker parses the final contiguous block of `Key: value` lines, separated from the subject or body by a blank line. A marker in the subject or body triggers checking but does not count as a valid trailer. CRLF and trailing blank lines are supported; the last occurrence of a repeated key wins. ## Local use @@ -72,7 +72,7 @@ node scripts/check-agent-trailers.mjs --require --message "fix typo" node scripts/check-agent-trailers.mjs --require-run --message-file path/to/message.txt ``` -Choose exactly one of `--message` or `--message-file`. Exit codes are `0` for a passing check, `1` for missing required trailers or invalid required run metadata, and `2` for invalid arguments or an unreadable message file. `--json` reports `agentAuthored`, `trailers`, `missing`, and `ok` for a completed check. With `--require-run`, `missing` includes `AI-Run` when it is absent or malformed, including a model that differs from `AI-Model`. Without that flag, optional run data does not affect the check. Combine `--require` and `--require-run` to require it on every message. +Choose exactly one of `--message` or `--message-file`. Exit codes are `0` for a passing check, `1` for missing or invalid required trailers (including a placeholder model) or invalid required run metadata, and `2` for invalid arguments or an unreadable message file. `--json` reports `agentAuthored`, `trailers`, `missing`, and `ok` for a completed check; `missing` includes `AI-Model` when its value is invalid. With `--require-run`, `missing` includes `AI-Run` when it is absent or malformed, including a model that differs from `AI-Model`. Without that flag, optional run data does not affect the check. Combine `--require` and `--require-run` to require it on every message. ## PR Action @@ -95,4 +95,4 @@ The workflow fetches PR history, then checks out the base revision before runnin ## Limits -Trailers and author emails are claims, not authentication or cryptographic signatures. An agent using an unmarked human identity is not detected by the default heuristic. Use require-all mode when every commit must declare provenance, and GitHub App permissions and repository rules for authorization. +Trailers and author emails are claims, not authentication or cryptographic signatures. The checker validates the model-id format and rejects placeholders; it cannot prove which model actually ran. An agent using an unmarked human identity is not detected by the default heuristic. Use require-all mode when every commit must declare provenance, and GitHub App permissions and repository rules for authorization. diff --git a/docs/github-app-agent-identity.md b/docs/github-app-agent-identity.md index 24aa047..7ac9f63 100644 --- a/docs/github-app-agent-identity.md +++ b/docs/github-app-agent-identity.md @@ -64,7 +64,7 @@ The publication helper currently makes explicitly unsigned Git commits. Its sign Creating a local commit does not authorize a push. Default GitHub writes are approved safe outputs: comments, labels, and draft PRs. Any separately authorized branch publication must use a repository-scoped installation token and must not force-push. Human-only merge is the default; the explicitly authorized, policy-gated `--merge-when-green` flow is the exception. -For authorized publication, use [scripts/agent-pr.mjs](../scripts/agent-pr.mjs) as described in the [commit skill](../skills/signed-bot-commit/SKILL.md). It loads `GITHUB_APP_ID` and `GITHUB_APP_PRIVATE_KEY_PATH` from the environment, verifies origin's installation, derives that App's bot identity, and mints a token with contents and pull requests write for that repository only; the merge flag additionally requests Checks read. It adds `AI-Agent: ` and `AI-Model: unknown` unless `--model` is supplied. No `.env` loading, token display, global Git identity changes, or human-token fallback is provided. Staged or selected `.github/workflows/**` paths are refused before token minting; humans publish workflow changes. +For authorized publication, use [scripts/agent-pr.mjs](../scripts/agent-pr.mjs) as described in the [commit skill](../skills/signed-bot-commit/SKILL.md). It loads `GITHUB_APP_ID` and `GITHUB_APP_PRIVATE_KEY_PATH` from the environment, verifies origin's installation, derives that App's bot identity, and mints a token with contents and pull requests write for that repository only; the merge flag additionally requests Checks read. It adds `AI-Agent: ` and the actual `AI-Model` id from `--model` or `AI_MODEL`; missing or placeholder model input stops publication instead of writing `unknown`. No `.env` loading, token display, global Git identity changes, or human-token fallback is provided. Staged or selected `.github/workflows/**` paths are refused before token minting; humans publish workflow changes. Require the `check-agent-trailers` PR check and protected-branch rules with no direct agent pushes or bypass. Pull requests write is not a draft-only permission; keep human review and branch rules even for opt-in merge. A passing trailer check is not authentication of the Git author or a substitute for those rules. The policy's `merger.merge` gate does not select an App credential; a trusted launcher/operator must disable merge on coder-only WSL and use a separately approved merger App/context. diff --git a/scripts/agent-pr.mjs b/scripts/agent-pr.mjs index a4530ba..1ae66d1 100644 --- a/scripts/agent-pr.mjs +++ b/scripts/agent-pr.mjs @@ -8,7 +8,7 @@ import { setTimeout as delay } from "node:timers/promises"; import { pathToFileURL } from "node:url"; import { checkMessage } from "./check-agent-trailers.mjs"; import { AgentPolicyError, loadAgentPolicy, parseAgentPolicy, requireCapability } from "./load-agent-policy.mjs"; -import { AgentRunError, packAgentRun, parseAgentRun } from "./parse-agent-run.mjs"; +import { AgentRunError, isModelId, packAgentRun, parseAgentRun } from "./parse-agent-run.mjs"; class AgentPrError extends Error {} @@ -120,16 +120,16 @@ export function parseOrigin(origin) { return { owner: match[1], repository: match[2] }; } -function validateCommitInput(message, model = "unknown") { +function validateCommitInput(message, model) { if (typeof message !== "string" || !message.trim() || message.includes("\0")) { throw new AgentPrError("Provide a nonempty commit message with --message."); } - if (typeof model !== "string" || !model.trim() || /[\r\n\0]/.test(model)) { - throw new AgentPrError("--model must be a nonempty single-line value."); + if (typeof model !== "string" || !isModelId(model.trim()) || /[\r\n\0\u2028\u2029]/.test(model)) { + throw new AgentPrError("Set --model or AI_MODEL to the actual single-line model id (not unknown)."); } } -export function buildCommitMessage(message, model = "unknown", appSlug, agentRun = null) { +export function buildCommitMessage(message, model, appSlug, agentRun = null) { validateCommitInput(message, model); if (typeof appSlug !== "string" || !/^[a-z0-9][a-z0-9-]*$/.test(appSlug)) { throw new AgentPrError("A verified App slug is required for the AI-Agent trailer."); @@ -295,10 +295,9 @@ export async function publishAgentPr(options, { requireCapability(policy, "coder", "commit_branch"); requireCapability(policy, "coder", "open_pr"); if (options.mergeWhenGreen) requireCapability(policy, "merger", "merge"); - const suppliedModel = options.model ?? (env.AI_MODEL || undefined); - const model = suppliedModel ?? "unknown"; + const model = options.model ?? env.AI_MODEL; validateCommitInput(options.message, model); - const agentRun = packAgentRun(env, suppliedModel?.trim() ?? ""); + const agentRun = packAgentRun(env, model.trim()); const appId = env.GITHUB_APP_ID; if (!appId || !/^[1-9][0-9]*$/.test(appId) || !env.GITHUB_APP_PRIVATE_KEY_PATH) { throw new AgentPrError("Set GITHUB_APP_ID and GITHUB_APP_PRIVATE_KEY_PATH in the environment; never paste the key into chat."); @@ -600,7 +599,8 @@ export async function main(argv, { stdout = process.stdout, stderr = process.std stdout.write(`Usage: node scripts/agent-pr.mjs --message TEXT [--model NAME] [--merge-when-green] [--files PATH ...] Without --files, commits the reviewed staged changes. --files must be last. ---model overrides AI_MODEL; otherwise the required AI-Model defaults to unknown. +--model overrides AI_MODEL; one must name the actual model id (not unknown). +Missing or invalid model input exits 2 before publication. Never invent a model. Optional AI_* environment inputs add one AI-Run trailer and upsert one agent-run:1 PR body pair. No metadata is invented; without run input, existing behavior is unchanged. See docs/METRICS.md. AI-Eval is never generated by this helper. diff --git a/scripts/check-agent-trailers.mjs b/scripts/check-agent-trailers.mjs index e051f23..0d48fa9 100644 --- a/scripts/check-agent-trailers.mjs +++ b/scripts/check-agent-trailers.mjs @@ -7,7 +7,7 @@ import { readFileSync } from "node:fs"; import { resolve } from "node:path"; import { pathToFileURL } from "node:url"; -import { parseAgentRun, parseTrailers } from "./parse-agent-run.mjs"; +import { isModelId, parseAgentRun, parseTrailers } from "./parse-agent-run.mjs"; export { parseTrailers } from "./parse-agent-run.mjs"; @@ -28,8 +28,9 @@ function usage(stream = process.stdout) { --json Print the result as JSON --help, -h Show this help + AI-Model must name the actual model id, not unknown, on agent commits. Exit 0 OK - Exit 1 missing required trailers on an agent-authored message + Exit 1 missing or invalid required trailers on an agent-authored message Exit 2 usage error `); } @@ -76,7 +77,7 @@ export function checkMessage(message, requireAll = false, authorEmail = "", requ const missing = []; if (agent) { for (const key of REQUIRED) { - if (!trailers[key] || String(trailers[key]).trim() === "") missing.push(key); + if (!trailers[key] || (key === "AI-Model" && !isModelId(trailers[key]))) missing.push(key); } if (requireRun) { try { @@ -94,6 +95,12 @@ export function checkMessage(message, requireAll = false, authorEmail = "", requ }; } +export function trailerError(result) { + const invalid = result.missing.includes("AI-Run") || + (result.missing.includes("AI-Model") && result.trailers["AI-Model"]); + return `${invalid ? "missing or invalid trailers" : "missing trailers"}: ${result.missing.join(", ")}`; +} + function main(argv) { let args; try { @@ -115,8 +122,7 @@ function main(argv) { if (args.json) { process.stdout.write(`${JSON.stringify(result, null, 2)}\n`); } else if (!result.ok) { - const reason = result.missing.includes("AI-Run") ? "missing or invalid trailers" : "missing trailers"; - process.stderr.write(`${reason}: ${result.missing.join(", ")}\n`); + process.stderr.write(`${trailerError(result)}\n`); } process.exit(result.ok ? 0 : 1); } diff --git a/scripts/check-pr-agent-trailers.mjs b/scripts/check-pr-agent-trailers.mjs index f42cabb..d5799e3 100644 --- a/scripts/check-pr-agent-trailers.mjs +++ b/scripts/check-pr-agent-trailers.mjs @@ -3,7 +3,7 @@ import { execFileSync } from "node:child_process"; import { resolve } from "node:path"; import { pathToFileURL } from "node:url"; -import { checkMessage } from "./check-agent-trailers.mjs"; +import { checkMessage, trailerError } from "./check-agent-trailers.mjs"; function git(args, cwd) { return execFileSync("git", args, { cwd, encoding: "utf8", stdio: ["ignore", "pipe", "pipe"] }); @@ -44,7 +44,7 @@ function main() { requireAll: requireAll === "true", }); for (const result of results) { - const status = result.ok ? "OK" : `missing trailers: ${result.missing.join(", ")}`; + const status = result.ok ? "OK" : trailerError(result); process.stdout.write(`${result.sha}: ${status}\n`); } process.exitCode = results.every((result) => result.ok) ? 0 : 1; diff --git a/scripts/parse-agent-run.mjs b/scripts/parse-agent-run.mjs index 645136d..7f2c853 100644 --- a/scripts/parse-agent-run.mjs +++ b/scripts/parse-agent-run.mjs @@ -13,6 +13,13 @@ const ENV_KEYS = [ export class AgentRunError extends Error {} +export function isModelId(value) { + return typeof value === "string" && + /^[A-Za-z0-9][A-Za-z0-9._:+\/-]*$/.test(value) && + !/\s/.test(value) && + !/^(unknown|none|n\/a|unspecified)$/i.test(value); +} + export function parseTrailers(message) { const normalized = String(message).replace(/\r\n/g, "\n").trimEnd(); const trailers = {}; @@ -82,19 +89,19 @@ export function packAgentRun(env = {}, model = env.AI_MODEL ?? "") { const effort = values.AI_EFFORT || "-"; if (!Object.hasOwn(EFFORTS, effort)) invalid("effort"); if (!values.AI_PROVIDER && !model) return null; - if (typeof model !== "string" || model.includes("|") || ENV_KEYS.some((key) => values[key].includes("|"))) invalid("field separator"); - const resolvedModel = model || "unknown"; + if (!isModelId(model)) invalid("model"); + if (ENV_KEYS.some((key) => values[key].includes("|"))) invalid("field separator"); const packed = [ "1", values.AI_PROVIDER || "-", - `${resolvedModel}@${values.AI_MODEL_VERSION || "unknown"}`, + `${model}@${values.AI_MODEL_VERSION || "unknown"}`, EFFORTS[effort], `${values.AI_CONTEXT_USED || "-"}/${values.AI_CONTEXT_MAX || "-"}`, values.AI_CONTEXT_OUT || "-", values.AI_SESSION || "-", values.AI_TASK || "-", ].join("|"); - parseAgentRun(packed, resolvedModel); + parseAgentRun(packed, model); return packed; } diff --git a/skills/signed-bot-commit/SKILL.md b/skills/signed-bot-commit/SKILL.md index fd940c6..78f7bfb 100644 --- a/skills/signed-bot-commit/SKILL.md +++ b/skills/signed-bot-commit/SKILL.md @@ -27,10 +27,10 @@ Pass a commit message without inventing credentials or manually changing Git's g ```text AI-Agent: -AI-Model: unknown +AI-Model: gpt-5 ``` -Use `AI_MODEL` or `--model` to replace `unknown` when the actual model is known; the flag takes precedence. Harnesses SHOULD supply known `AI_*` run values from [METRICS.md](../../docs/METRICS.md) before invoking the helper. It adds one optional `AI-Run` trailer and upserts the tagged PR pair, omitting run metadata when no environment input is supplied. Never invent missing counts or identifiers. Humans evaluate with separate `AI-Eval` comments; the helper must not generate them. It checks the committed author, committer, trailers, and protected file paths before pushing the verified commit. +Supply the actual model id through `AI_MODEL` or `--model`; the flag takes precedence. `gpt-5` above is an example, not a default. Without a known model, or with a placeholder such as `unknown`, the CLI exits `2` without publishing. Never invent a model. Harnesses SHOULD supply known `AI_*` run values from [METRICS.md](../../docs/METRICS.md) before invoking the helper. It adds one optional `AI-Run` trailer and upserts the tagged PR pair, omitting run metadata when no environment input is supplied. Never invent missing counts or identifiers. Humans evaluate with separate `AI-Eval` comments; the helper must not generate them. It checks the committed author, committer, trailers, and protected file paths before pushing the verified commit. ## Usage @@ -39,13 +39,13 @@ The human must first publish root `agent-policy.yml` on the default branch and i With reviewed changes already staged: ```bash -node scripts/agent-pr.mjs --message "docs: clarify agent contracts" --model unknown +node scripts/agent-pr.mjs --message "docs: clarify agent contracts" --model gpt-5 ``` To stage and commit named files, put `--files` last: ```bash -node scripts/agent-pr.mjs --message "docs: clarify agent contracts" --files README.md AGENTS.md +node scripts/agent-pr.mjs --message "docs: clarify agent contracts" --model gpt-5 --files README.md AGENTS.md ``` `--help` does not read policy, the key, or contact GitHub. Normal invocation first requires the local coder grants, then signs an App JWT, discovers the repository installation, and requests an installation token scoped to that repository with contents and pull requests write permissions. Only the merge flag adds Checks read to the token request. After checking the approved policy and branch protections, it makes an unsigned bot commit, pushes with in-memory authentication, reuses an open PR for the branch or runs `gh pr create --draft`, then revokes the token. New PR titles follow the repository's `[area] summary` convention with `[agent]` as the default area. @@ -58,7 +58,7 @@ The configured App also needs Checks read-only permission, and the repository mu ```bash node scripts/load-agent-policy.mjs --role merger --capability merge -node scripts/agent-pr.mjs --message "fix: validate input" --merge-when-green --files README.md +node scripts/agent-pr.mjs --message "fix: validate input" --model gpt-5 --merge-when-green --files README.md ``` The helper waits for `check-agent-trailers` from GitHub Actions to succeed on the exact published PR head SHA. It may mark a green draft ready, then rechecks head, checks, and mergeability. It never self-approves; required reviews and repository rules still apply. Polling is bounded to approximately ten minutes; failed checks, changed SHAs, policy revocation, and API errors stop the flow. diff --git a/tests/agent-pr.test.mjs b/tests/agent-pr.test.mjs index 82dc713..bbb6c92 100644 --- a/tests/agent-pr.test.mjs +++ b/tests/agent-pr.test.mjs @@ -7,7 +7,7 @@ import test from "node:test"; import { fileURLToPath } from "node:url"; import { buildCommitMessage, createAppJwt, main, - mintInstallationToken, parseArgs, parseOrigin, publishAgentPr, upsertAgentRun, + mintInstallationToken, parseArgs, parseOrigin, publishAgentPr as publishAgentPrRaw, upsertAgentRun, } from "../scripts/agent-pr.mjs"; import { AgentPolicyError, loadAgentPolicy, parseAgentPolicy } from "../scripts/load-agent-policy.mjs"; import { packAgentRun, parseTrailers } from "../scripts/parse-agent-run.mjs"; @@ -32,6 +32,10 @@ const runEnvironment = { }; const compactRun = "1|anthropic|claude-sonnet-4.5@20250901|h|18234/200000|2510|ses_01K8|feat-auth"; +function publishAgentPr(options, dependencies) { + return publishAgentPrRaw({ ...options, model: options.model ?? dependencies.env.AI_MODEL ?? "test-model" }, dependencies); +} + function mockGitHub(responses) { const calls = []; const fetchImpl = async (url, options) => { @@ -172,22 +176,30 @@ test("origin parsing supports GitHub SSH and HTTPS without exposing credentials" } }); -test("CLI builds canonical trailers with unknown or a selected model", () => { - assert.equal(buildCommitMessage("feat: helper", undefined, AGENT), `feat: helper\n\nAI-Agent: ${AGENT}\nAI-Model: unknown\n`); - assert.match(buildCommitMessage("feat: helper", "test-model", AGENT), /AI-Model: test-model\n$/); - assert.throws(() => buildCommitMessage("feat: helper"), /verified App slug/); +test("CLI builds canonical trailers only with an actual model id", () => { + assert.equal(buildCommitMessage("feat: helper", "gpt-5", AGENT), `feat: helper\n\nAI-Agent: ${AGENT}\nAI-Model: gpt-5\n`); + assert.throws(() => buildCommitMessage("feat: helper", undefined, AGENT), /actual single-line model id/); + assert.throws(() => buildCommitMessage("feat: helper", "UNKNOWN", AGENT), /actual single-line model id/); + assert.throws(() => buildCommitMessage("feat: helper", "n/a", AGENT), /actual single-line model id/); + assert.throws(() => buildCommitMessage("feat: helper", "\u2028gpt-5", AGENT), /actual single-line model id/); + assert.throws(() => buildCommitMessage("feat: helper", "gpt-5"), /verified App slug/); assert.deepEqual(parseArgs(["--message", "feat: helper", "--model", "test-model", "--files", "README.md"]), { message: "feat: helper", model: "test-model", files: ["README.md"], }); + assert.equal(parseArgs(["--message", "feat: helper"], { AI_MODEL: "env-model" }).model, "env-model"); + assert.equal(parseArgs(["--message", "feat: helper", "--model", "gpt-5"], { AI_MODEL: "env-model" }).model, "gpt-5"); assert.throws(() => parseArgs(["--message", "feat: helper", "--files"]), /--files must be last/); assert.throws(() => parseArgs([]), /--message/); + assert.throws(() => parseArgs(["--message", "feat: helper"]), /model id/); + assert.throws(() => parseArgs(["--message", "feat: helper"], { AI_MODEL: " " }), /model id/); + assert.throws(() => parseArgs(["--message", "feat: helper", "--model", "unknown"], { AI_MODEL: "env-model" }), /model id/); assert.throws(() => buildCommitMessage("feat: helper", "unknown\nAI-Agent: someone-else"), /single-line/); }); -test("publication commits both bot identities, pushes without token arguments, and creates a draft PR", async () => { +test("--model gpt-5 commits both bot identities, pushes without token arguments, and creates a draft PR", async () => { const mock = mockPublication(); const output = []; - const status = await main(["--message", "feat: helper", "--model", "test-model"], { + const status = await main(["--message", "feat: helper", "--model", "gpt-5"], { ...mock.dependencies, stdout: { write: (text) => output.push(text) }, stderr: { write: (text) => output.push(text) }, @@ -198,7 +210,8 @@ test("publication commits both bot identities, pushes without token arguments, a assert.equal(commit.env.GIT_COMMITTER_NAME, BOT_NAME); assert.equal(commit.env.GIT_AUTHOR_EMAIL, BOT_EMAIL); assert.equal(commit.env.GIT_COMMITTER_EMAIL, BOT_EMAIL); - assert.equal(commit.input, buildCommitMessage("feat: helper", "test-model", AGENT)); + assert.equal(commit.input, buildCommitMessage("feat: helper", "gpt-5", AGENT)); + assert.match(commit.input, /\nAI-Model: gpt-5\n$/); const identityRequest = mock.requests.find((call) => call.url.includes("/users/")); assert.equal(identityRequest.url, `https://api.github.com/users/${encodeURIComponent(BOT_NAME)}`); assert.equal(identityRequest.headers.Authorization, `Bearer ${access.token}`); @@ -289,7 +302,7 @@ test("AI-Run missing slots use sentinels and invalid effort fails before authent const partial = mockPublication(); partial.dependencies.env.AI_PROVIDER = "local"; await publishAgentPr({ message: "feat: helper" }, partial.dependencies); - assert.equal(parseTrailers(partial.commands.find((call) => call.args.includes("commit")).input)["AI-Run"], "1|local|unknown@unknown|-|-/-|-|-|-"); + assert.equal(parseTrailers(partial.commands.find((call) => call.args.includes("commit")).input)["AI-Run"], "1|local|test-model@unknown|-|-/-|-|-|-"); const invalid = mockPublication(); Object.assign(invalid.dependencies.env, runEnvironment, { AI_EFFORT: "secret-invalid-effort" }); await assert.rejects(publishAgentPr({ message: "feat: helper" }, invalid.dependencies), { message: "Invalid AI-Run effort; see docs/METRICS.md." }); @@ -369,8 +382,8 @@ test("workflow files in the index or explicit paths require human publication be }); test("--merge-when-green is opt-in and requires the merger role even if coder.merge is granted", async () => { - assert.equal(parseArgs(["--message", "feat: helper", "--merge-when-green"]).mergeWhenGreen, true); - assert.equal(parseArgs(["--message", "feat: helper"]).mergeWhenGreen, undefined); + assert.equal(parseArgs(["--message", "feat: helper", "--model", "test-model", "--merge-when-green"]).mergeWhenGreen, true); + assert.equal(parseArgs(["--message", "feat: helper", "--model", "test-model"]).mergeWhenGreen, undefined); for (const source of [policySource, policySource.replace("comment, label", "comment, label, merge")]) { const mock = mockPublication(); mock.dependencies.loadPolicy = () => parseAgentPolicy(source); @@ -447,7 +460,7 @@ test("--merge-when-green merges a ready or draft PR by exact SHA and only then d assert.equal(result.mergeCommit, "b".repeat(40)); const merge = mock.requests.find((call) => call.url.endsWith("/pulls/7/merge")); assert.equal(merge.method, "PUT"); - assert.deepEqual(JSON.parse(merge.body), { sha: commitSha, merge_method: "merge", commit_message: buildCommitMessage("feat: helper", undefined, AGENT) }); + assert.deepEqual(JSON.parse(merge.body), { sha: commitSha, merge_method: "merge", commit_message: buildCommitMessage("feat: helper", "test-model", AGENT) }); const tokenRequest = mock.requests.find((call) => call.url.endsWith("/access_tokens")); assert.deepEqual(JSON.parse(tokenRequest.body).permissions, { contents: "write", pull_requests: "write", checks: "read" }); const deletion = mock.requests.find((call) => call.url.includes("/git/refs/heads/")); @@ -864,6 +877,32 @@ test("help needs no environment or key and does not publish", async () => { assert.match(output.join(""), /GITHUB_APP_PRIVATE_KEY_PATH/); assert.match(output.join(""), /--files/); assert.match(output.join(""), /merger\.merge/); + assert.match(output.join(""), /actual model id \(not unknown\)/); + assert.match(output.join(""), /exits 2 before publication/); +}); + +test("missing or placeholder model exits two before key access, Git, or GitHub", async () => { + for (const [args, aiModel] of [ + [["--message", "feat: helper"], ""], + [["--message", "feat: helper"], "unknown"], + [["--message", "feat: helper", "--model", ""], "env-model"], + [["--message", "feat: helper", "--model", "unknown"], "env-model"], + ]) { + const mock = mockPublication(); + mock.dependencies.env.AI_MODEL = aiModel; + const errors = []; + const status = await main(args, { ...mock.dependencies, stderr: { write: (text) => errors.push(text) } }); + assert.equal(status, 2); + assert.match(errors.join(""), /actual single-line model id/); + assert.equal(mock.keyReads(), 0); + assert.equal(mock.commands.length, 0); + assert.equal(mock.requests.length, 0); + } + const missing = mockPublication(); + await assert.rejects(publishAgentPrRaw({ message: "feat: helper" }, missing.dependencies), /actual single-line model id/); + assert.equal(missing.keyReads(), 0); + assert.equal(missing.commands.length, 0); + assert.equal(missing.requests.length, 0); }); test("missing environment and an empty index fail before key access or network calls", async () => { @@ -986,7 +1025,7 @@ test("local Git integration commits selected and staged files with bot provenanc assert.equal(first.createdPullRequest, true); assert.equal(localGit(["ls-tree", "-r", "--name-only", "HEAD"]).trim(), "agent-policy.yml\nselected.txt"); assert.equal(localGit(["log", "-1", "--format=%an%n%ae%n%cn%n%ce"]).trim(), [BOT_NAME, BOT_EMAIL, BOT_NAME, BOT_EMAIL].join("\n")); - assert.ok(localGit(["log", "-1", "--format=%B"]).includes(`AI-Agent: ${AGENT}\nAI-Model: unknown`)); + assert.ok(localGit(["log", "-1", "--format=%B"]).includes(`AI-Agent: ${AGENT}\nAI-Model: test-model`)); writeFileSync(join(directory, "selected.txt"), "updated contents\n"); localGit(["add", "--", "selected.txt"]); const second = await publishAgentPr({ message: "fix: staged file", model: "test-model" }, dependencies); diff --git a/tests/agent-run.test.mjs b/tests/agent-run.test.mjs index 4b1277f..771728e 100644 --- a/tests/agent-run.test.mjs +++ b/tests/agent-run.test.mjs @@ -49,8 +49,11 @@ test("omits AI-Run without environment input or without any provider or model", }); test("partial environment uses missing-slot sentinels rather than inventing metadata", () => { - assert.equal(packAgentRun({ AI_PROVIDER: "local" }), "1|local|unknown@unknown|-|-/-|-|-|-"); + assert.throws(() => packAgentRun({ AI_PROVIDER: "local" }), /Invalid AI-Run model/); + assert.equal(packAgentRun({ AI_PROVIDER: "local" }, "gpt-5"), "1|local|gpt-5@unknown|-|-/-|-|-|-"); assert.equal(packAgentRun({ AI_MODEL: "known-model" }), "1|-|known-model@unknown|-|-/-|-|-|-"); + assert.throws(() => packAgentRun({ AI_MODEL: "unknown" }), /Invalid AI-Run model/); + assert.throws(() => packAgentRun({ AI_MODEL: "gpt-5\n" }), /Invalid AI-Run model/); assert.equal(packAgentRun({ AI_EFFORT: "low" }, "cli-model"), "1|-|cli-model@unknown|l|-/-|-|-|-"); assert.deepEqual(parseAgentRun("1|-|known-model@unknown|-|-/-|-|-|-"), { model: "known-model", schema: 1, provider: null, model_version: "unknown", effort: null, diff --git a/tests/check-agent-trailers.test.mjs b/tests/check-agent-trailers.test.mjs index 640ba1d..5722860 100644 --- a/tests/check-agent-trailers.test.mjs +++ b/tests/check-agent-trailers.test.mjs @@ -19,17 +19,18 @@ test("parses trailers after blank line", () => { body AI-Agent: hermes-coder -AI-Model: unknown +AI-Model: claude-sonnet-4.5 `; const t = parseTrailers(msg); assert.equal(t["AI-Agent"], "hermes-coder"); - assert.equal(t["AI-Model"], "unknown"); + assert.equal(t["AI-Model"], "claude-sonnet-4.5"); }); test("valid agent message passes", () => { - const r = checkMessage(`feat: x\n\nAI-Agent: copilot\nAI-Model: gpt\n`); + const r = checkMessage(`feat: x\n\nAI-Agent: copilot\nAI-Model: gpt-5\n`); assert.equal(r.ok, true); assert.equal(r.agentAuthored, true); + assert.equal(checkMessage("feat: x\n\nAI-Agent: copilot\nAI-Model: owner/model:small\n").ok, true); }); test("missing AI-Agent on unmarked human message passes", () => { @@ -44,6 +45,16 @@ test("missing AI-Model on agent message fails", () => { assert.deepEqual(r.missing, ["AI-Model"]); }); +test("unknown and other placeholder model ids fail on agent commits", () => { + for (const model of ["unknown", "UNKNOWN", "none", "n/a", "unspecified", "-", "not a model", "gpt-5|other", "gpt-5@version"]) { + const message = `feat: x\n\nAI-Agent: copilot\nAI-Model: ${model}\n`; + assert.deepEqual(checkMessage(message).missing, ["AI-Model"], model); + const result = runChecker(["--message", message]); + assert.equal(result.status, 1, model); + assert.match(result.stderr, /missing or invalid trailers: AI-Model/, model); + } +}); + test("--require treats human message as agent-authored", () => { const r = checkMessage(`fix typo\n`, true); assert.equal(r.agentAuthored, true); @@ -52,7 +63,7 @@ test("--require treats human message as agent-authored", () => { }); test("trailers need a blank separator", () => { - const message = "feat: x\nAI-Agent: copilot\nAI-Model: unknown\n"; + const message = "feat: x\nAI-Agent: copilot\nAI-Model: gpt-5\n"; assert.deepEqual(parseTrailers(message), {}); assert.equal(checkMessage(message).ok, false); }); @@ -70,7 +81,7 @@ test("AI-Agent markers outside the footer still require trailers", () => { }); test("--require rejects a footer with AI-Model but no AI-Agent", () => { - const result = checkMessage("feat: x\n\nAI-Model: unknown\n", true); + const result = checkMessage("feat: x\n\nAI-Model: gpt-5\n", true); assert.equal(result.ok, false); assert.deepEqual(result.missing, ["AI-Agent"]); }); @@ -102,7 +113,7 @@ test("human noreply addresses and lookalike domains are not bot authors", () => test("valid bot-authored message passes", () => { const result = checkMessage( - "fix: x\n\nAI-Agent: copilot\nAI-Model: unknown\n", + "fix: x\n\nAI-Agent: copilot\nAI-Model: gpt-5\n", false, "123+agent[bot]@users.noreply.github.com", ); @@ -111,7 +122,7 @@ test("valid bot-authored message passes", () => { test("CRLF messages and recommended trailers are supported", () => { const result = checkMessage( - "fix: x\r\n\r\nAI-Agent: copilot\r\nAI-Model: unknown\r\n" + + "fix: x\r\n\r\nAI-Agent: copilot\r\nAI-Model: gpt-5\r\n" + "AI-Session: opaque-id\r\nCo-authored-by: Owner \r\n\r\n", ); assert.equal(result.ok, true); @@ -120,7 +131,7 @@ test("CRLF messages and recommended trailers are supported", () => { test("empty required trailer values fail", () => { for (const message of [ - "fix: x\n\nAI-Agent: \nAI-Model: unknown\n", + "fix: x\n\nAI-Agent: \nAI-Model: gpt-5\n", "fix: x\n\nAI-Agent: copilot\nAI-Model: \n", ]) { assert.equal(checkMessage(message).ok, false); @@ -129,7 +140,7 @@ test("empty required trailer values fail", () => { test("CLI returns JSON and exits zero for a valid message", () => { const result = runChecker([ - "--json", "--message", "fix: x\n\nAI-Agent: copilot\nAI-Model: unknown\n", + "--json", "--message", "fix: x\n\nAI-Agent: copilot\nAI-Model: gpt-5\n", ]); assert.equal(result.status, 0, result.stderr); assert.equal(JSON.parse(result.stdout).ok, true); @@ -155,7 +166,7 @@ test("CLI reads a UTF-8 message file", (context) => { const directory = mkdtempSync(join(repository, ".trailer-test-")); context.after(() => rmSync(directory, { recursive: true, force: true })); const messageFile = join(directory, "commit message.txt"); - writeFileSync(messageFile, "fix: x\n\nAI-Agent: copilot\nAI-Model: unknown\n"); + writeFileSync(messageFile, "fix: x\n\nAI-Agent: copilot\nAI-Model: gpt-5\n"); const result = runChecker(["--message-file", messageFile, "--json"]); assert.equal(result.status, 0, result.stderr); assert.equal(JSON.parse(result.stdout).ok, true); @@ -185,6 +196,7 @@ test("CLI --help documents flags and exits zero", () => { for (const flag of ["--help", "--message", "--message-file", "--author-email", "--require", "--require-run", "--json"]) { assert.ok(result.stdout.includes(flag), flag); } + assert.match(result.stdout, /AI-Model must name the actual model id, not unknown/); }); test("default checks still require only AI-Agent and AI-Model", () => { diff --git a/tests/check-pr-agent-trailers.test.mjs b/tests/check-pr-agent-trailers.test.mjs index d1e2b94..b4b7851 100644 --- a/tests/check-pr-agent-trailers.test.mjs +++ b/tests/check-pr-agent-trailers.test.mjs @@ -56,21 +56,23 @@ test("PR checker scans every commit and distinguishes human, agent, and bot auth const history = createHistory(context); const human = history.commit("fix typo\n", "123+human@users.noreply.github.com"); const invalidAgent = history.commit("feat: x\n\nAI-Agent: copilot\n"); - const validAgent = history.commit("feat: y\n\nAI-Agent: copilot\nAI-Model: unknown\n"); - const invalidBot = history.commit("fix: z\n\nAI-Model: unknown\n", "123+agent[bot]@users.noreply.github.com"); + const invalidModel = history.commit("feat: x\n\nAI-Agent: copilot\nAI-Model: unknown\n"); + const validAgent = history.commit("feat: y\n\nAI-Agent: copilot\nAI-Model: gpt-5\n"); + const invalidBot = history.commit("fix: z\n\nAI-Model: gpt-5\n", "123+agent[bot]@users.noreply.github.com"); const validBot = history.commit( - "fix: done\n\nAI-Agent: coder\nAI-Model: unknown\n", + "fix: done\n\nAI-Agent: coder\nAI-Model: gpt-5\n", "123+agent[bot]@users.noreply.github.com", ); const results = checkPullRequest({ ...history, headSha: validBot }); - assert.deepEqual(results.map((result) => result.sha), [human, invalidAgent, validAgent, invalidBot, validBot]); - assert.deepEqual(results.map((result) => result.agentAuthored), [false, true, true, true, true]); - assert.deepEqual(results.map((result) => result.missing), [[], ["AI-Model"], [], ["AI-Agent"], []]); + assert.deepEqual(results.map((result) => result.sha), [human, invalidAgent, invalidModel, validAgent, invalidBot, validBot]); + assert.deepEqual(results.map((result) => result.agentAuthored), [false, true, true, true, true, true]); + assert.deepEqual(results.map((result) => result.missing), [[], ["AI-Model"], ["AI-Model"], [], ["AI-Agent"], []]); const result = runPullRequest(history.cwd, history.baseSha, validBot); assert.equal(result.status, 1, result.stderr); - assert.equal(result.stdout.trim().split("\n").length, 5); + assert.equal(result.stdout.trim().split("\n").length, 6); assert.ok(result.stdout.includes(`${invalidAgent}: missing trailers: AI-Model`)); + assert.ok(result.stdout.includes(`${invalidModel}: missing or invalid trailers: AI-Model`)); assert.ok(result.stdout.includes(`${invalidBot}: missing trailers: AI-Agent`)); assert.ok(result.stdout.includes(`${validBot}: OK`)); });