diff --git a/AGENTS.md b/AGENTS.md index 0741740..5b4e701 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -62,6 +62,12 @@ 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 ``` +## Optional run metadata + +- Harnesses SHOULD export the known `AI_PROVIDER`, `AI_MODEL`, `AI_MODEL_VERSION`, `AI_EFFORT`, `AI_CONTEXT_USED`, `AI_CONTEXT_MAX`, `AI_CONTEXT_OUT`, `AI_SESSION`, and `AI_TASK` values before invoking `agent-pr.mjs`. Never invent missing values or infer counts, effort, session, or task identifiers. +- Follow `docs/METRICS.md`: the helper emits a single optional compact `AI-Run` trailer and tagged PR body pair when metadata is supplied. `--model` overrides `AI_MODEL`; absent environment metadata leaves the two required trailers unchanged. No prompts, traces, credentials, extra `AI-X-*` trailers, or second YAML document belong in git. +- Humans evaluate through separate `AI-Eval` PR comments, not by editing trailers. Agents must not generate evaluations, quality scores, or analytics-service integrations. + ## Day-1 build targets Implement what `docs/DAY1_SCOPE.md` lists. Prefer small, tested files. diff --git a/README.md b/README.md index 4c31877..9bd65bc 100644 --- a/README.md +++ b/README.md @@ -48,7 +48,7 @@ See [HARNESSES](docs/HARNESSES.md) for integration details. On a dedicated WSL/H ## Use in another repo -Follow [ONBOARDING](docs/ONBOARDING.md) for the complete file list and [adopt.md](docs/adopt.md) for distribution options. Copy the [consumer workflow](examples/consumer-repo/.github/workflows/check-agent-trailers.yml) with a pinned public Action, or vendor the [composite Action](.github/actions/check-agent-trailers/action.yml) with both checker scripts. No private-package infrastructure or App credentials are required for the read-only trailer check itself. +Follow [ONBOARDING](docs/ONBOARDING.md) for the complete file list and [adopt.md](docs/adopt.md) for distribution options. Copy the [consumer workflow](examples/consumer-repo/.github/workflows/check-agent-trailers.yml) with a pinned public Action, or vendor the [composite Action](.github/actions/check-agent-trailers/action.yml) with both checker scripts and their [shared parser](scripts/parse-agent-run.mjs). No private-package infrastructure or App credentials are required for the read-only trailer check itself. The manifest is a static template, not a hosted registration button. Its placeholder callback URLs need an owner-controlled receiver for GitHub's manifest flow; onboarding also documents the manual registration path. No hosted callback or control plane is provided. @@ -75,6 +75,10 @@ The check inspects messages containing `AI-Agent:` and GitHub noreply bot author 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. + ## With gh-aw The [issue clarifier source](.github/workflows-src/issue-clarifier.md) illustrates `permissions: read-all` and a comment-only safe output. Approved output handlers must enforce the repository policy too. Keep Markdown sources uncompiled unless `gh aw` is already installed; no generated lockfile or agent runtime is required to use the identity contract. diff --git a/docs/METRICS.md b/docs/METRICS.md new file mode 100644 index 0000000..d41b36e --- /dev/null +++ b/docs/METRICS.md @@ -0,0 +1,106 @@ +# 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. + +## Schema 1 + +```text +AI-Run: ||@||/||| +``` + +Example footer: + +```text +AI-Agent: hermes-coder +AI-Model: claude-sonnet-4.5 +AI-Run: 1|anthropic|claude-sonnet-4.5@20250901|h|18234/200000|2510|ses_01K8|feat-auth +``` + +| Column | Rule | +| --- | --- | +| 1: schema | Exactly `1` | +| 2: provider | `anthropic`, `openai`, `github-copilot`, `local`, or `other` | +| 3: model@version | Model must match `AI-Model`; version is `[A-Za-z0-9._-]+` or `unknown` | +| 4: effort | `l`, `m`, `h`, or `x` for low, medium, high, or max | +| 5: in/max | Two nonnegative decimal integer counts, each independently allowed to be `-` | +| 6: out | Nonnegative decimal integer count or `-` | +| 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`. + +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. + +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. + +## Harness environment + +Export only values actually reported by the harness before invoking [agent-pr.mjs](../scripts/agent-pr.mjs). The helper does not read `.env`, infer a provider from a model, estimate token counts, or generate session/task IDs. + +| 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_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` | `-` | +| `AI_CONTEXT_MAX` | `max` | `-` | +| `AI_CONTEXT_OUT` | `out` | `-` | +| `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. + +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 `-`. + +## PR body + +When run metadata is present, the publisher upserts exactly this two-line pair: + +```text + +`1|anthropic|claude-sonnet-4.5@20250901|h|18234/200000|2510|ses_01K8|feat-auth` +``` + +There is no closing marker or second document. An existing `` pair is replaced; duplicates are collapsed to one pair. Other PR body text is retained. For an existing PR, the helper reads the current body and verifies the branch and head SHA before updating it. A new draft PR receives the pair at creation. When no run metadata is supplied, the helper does not modify existing PR metadata. + +The commit receives one `AI-Run` footer line; the PR body receives the tagged pair rather than another copy of that footer line. Evaluation comments are separate from both. + +## Validate and export locally + +The default [trailer checker](../scripts/check-agent-trailers.mjs) still checks only `AI-Agent` and `AI-Model`. Opt in to requiring a valid, model-matching run trailer on agent-classified commits: + +```bash +node scripts/check-agent-trailers.mjs --require-run --message-file path/to/message.txt +node scripts/check-agent-trailers.mjs --require --require-run --message-file path/to/message.txt +``` + +`--require-run` alone does not classify an unmarked human commit as an agent commit. Combine it with `--require` to check every message. The default PR workflow and its permissions are unchanged. + +The [message parser](../scripts/parse-agent-run.mjs) and [history exporter](../scripts/export-agent-metrics.mjs) print JSONL to standard output, with one object per commit containing run metadata: + +```bash +node scripts/parse-agent-run.mjs --message-file path/to/message.txt +node scripts/export-agent-metrics.mjs +node scripts/export-agent-metrics.mjs --ref main..HEAD +``` + +```json +{"sha":"0123456789abcdef0123456789abcdef01234567","agent":"hermes-coder","model":"claude-sonnet-4.5","schema":1,"provider":"anthropic","model_version":"20250901","effort":"h","context_used":18234,"context_max":200000,"context_out":2510,"session":"ses_01K8","task":"feat-auth"} +``` + +The message parser accepts `--message TEXT` instead of `--message-file`, plus an optional full `--sha`; without it, `sha` is `null`. The history exporter reads only local Git history, defaults to `HEAD`, and emits oldest first. Neither fetches from GitHub or exports commit bodies, prompts, traces, unknown fields, or evaluations. + +JSON uses `null` for `-` sentinels, integer numbers for counts, and a string for `model_version`, including `unknown`. Integers beyond JavaScript's safe range remain decimal strings instead of being rounded. Commits without metadata are skipped. A malformed record fails export without partial output. Exit codes are `0` for success or no records, `1` for metadata/history errors, and `2` for usage or message-file input errors. Both commands support `--help`. + +When vendoring the checker or publisher, include `scripts/parse-agent-run.mjs` as well as their existing dependencies. The read-only exporter is optional. See [adopt.md](adopt.md). + +## Human evaluation comments + +A human may leave this separate PR comment: + +```text +AI-Eval: 1|accept|3|n +``` + +This documents a human comment format only. `accept` is the human's decision; the remaining values are not interpreted or assigned a scoring scale by v0.2.0. The publisher must not generate `AI-Eval`, post evaluation comments, or add an evaluation trailer. Humans evaluate via comments, not by rewriting commit trailers. The parser and exporter do not process these comments or calculate quality scores. \ No newline at end of file diff --git a/docs/ONBOARDING.md b/docs/ONBOARDING.md index 36062da..dc87841 100644 --- a/docs/ONBOARDING.md +++ b/docs/ONBOARDING.md @@ -35,6 +35,7 @@ scripts/agent-pr.mjs scripts/load-agent-policy.mjs scripts/check-agent-trailers.mjs scripts/check-pr-agent-trailers.mjs +scripts/parse-agent-run.mjs examples/agent-policy.yml .github/actions/check-agent-trailers/action.yml .github/workflows/check-agent-trailers.yml @@ -42,9 +43,11 @@ examples/agent-policy.yml Use Node 20+, Git, and `gh` for publication. Adapt the workspace name and test command in the copied rules. Follow [HARNESSES.md](HARNESSES.md) for the small harness-specific pointers, and [adopt.md](adopt.md) for the pinned public-Action alternative and vendoring details. No private-package infrastructure or runtime dependency installation is needed. +The shared parser is required by the checker and publisher. Optional run metadata and the local JSONL exporter are documented in [METRICS.md](METRICS.md); no `AI_*` run variables are required for ordinary publication. + A human must review [the policy example](../examples/agent-policy.yml), install it as root `agent-policy.yml`, and publish it on the default branch through the existing human review process. Include that reviewed version in the feature branch too. Keep merger and deploy allow-lists empty. The publisher requires coder `commit_branch` and `open_pr`, checks the default-branch policy, and refuses root-policy edits; there is no example fallback. See [POLICY.md](POLICY.md) and [ROLES.md](ROLES.md). Copy their guidance with the skills when adopting the pack. -For the local Action, land the Action and both checker scripts on the target branch before enabling the workflow, because it executes the base revision's trusted checker. A human bootstraps and publishes `.github/workflows/**` changes: the helper refuses staged or selected workflow paths before token minting, and the coder App intentionally has no Workflows permission. Keep human review on changes to the workflow, instructions, and publisher. +For the local Action, land the Action, both checker scripts, and the shared parser on the target branch before enabling the workflow, because it executes the base revision's trusted checker. A human bootstraps and publishes `.github/workflows/**` changes: the helper refuses staged or selected workflow paths before token minting, and the coder App intentionally has no Workflows permission. Keep human review on changes to the workflow, instructions, and publisher. ## 3. Protect the branch and publish diff --git a/docs/adopt.md b/docs/adopt.md index 83c5abe..df8e7f1 100644 --- a/docs/adopt.md +++ b/docs/adopt.md @@ -23,11 +23,12 @@ Use this option when the consumer cannot reference the public Action or needs to .github/actions/check-agent-trailers/action.yml scripts/check-agent-trailers.mjs scripts/check-pr-agent-trailers.mjs +scripts/parse-agent-run.mjs ``` -The source files are the [composite Action](../.github/actions/check-agent-trailers/action.yml), [message checker](../scripts/check-agent-trailers.mjs), and [PR runner](../scripts/check-pr-agent-trailers.mjs). Retain the pack's [MIT notice](../LICENSE) with the vendored files without replacing the consumer's own license. +The source files are the [composite Action](../.github/actions/check-agent-trailers/action.yml), [message checker](../scripts/check-agent-trailers.mjs), [PR runner](../scripts/check-pr-agent-trailers.mjs), and [shared parser](../scripts/parse-agent-run.mjs). Retain the pack's [MIT notice](../LICENSE) with the vendored files without replacing the consumer's own license. -**Copying only the Action metadata is not sufficient.** Its command expects both scripts at the relative paths above. Copying instruction files or a workflow does not make a local `uses: ./.github/actions/check-agent-trailers` reference point back to this pack. +**Copying only the Action metadata is not sufficient.** Its command needs both checker scripts and their shared parser at the relative paths above. Copying instruction files or a workflow does not make a local `uses: ./.github/actions/check-agent-trailers` reference point back to this pack. For this option, copy the pack's [local workflow](../.github/workflows/check-agent-trailers.yml), not the remotely pinned consumer example. The local workflow fetches full PR history, checks out the trusted base revision, and then runs: @@ -39,7 +40,7 @@ For this option, copy the pack's [local workflow](../.github/workflows/check-age head-sha: ${{ github.event.pull_request.head.sha }} ``` -Land the Action and both scripts on the target branch in a reviewed bootstrap change **before enabling the local workflow**. Otherwise its first run cannot find the checker at the base revision. Keep the trusted-base checkout step when adopting the local workflow; checker updates take effect after they reach that branch. +Land the Action, both checker scripts, and the shared parser on the target branch in a reviewed bootstrap change **before enabling the local workflow**. Otherwise its first run cannot find the checker at the base revision. Keep the trusted-base checkout step when adopting the local workflow; checker updates take effect after they reach that branch. For local validation and future updates, also copy the [message-checker tests](../tests/check-agent-trailers.test.mjs) and [PR-runner tests](../tests/check-pr-agent-trailers.test.mjs) into `tests/`. With Node 20+ and Git available, run from the consumer root: @@ -50,6 +51,8 @@ node --test tests/*.test.mjs Update the Action, scripts, and tests together from a reviewed revision. Neither adoption option needs `npm install`. +Optional v0.2.0 run metadata is described in [METRICS.md](METRICS.md). Copy [export-agent-metrics.mjs](../scripts/export-agent-metrics.mjs) for local JSONL export if needed. The shared parser remains required by the checker even when run metadata is not enabled; the default trailer policy is unchanged. + ## Choose the policy By default, every PR commit is inspected, but required trailers are enforced only when its message contains `AI-Agent:` or its author has a GitHub noreply bot address. Human privacy addresses alone do not trigger the check. See the [trailer specification](commit-trailers.md) for exact parsing and bot-address rules. diff --git a/docs/commit-trailers.md b/docs/commit-trailers.md index cc8638f..3662e13 100644 --- a/docs/commit-trailers.md +++ b/docs/commit-trailers.md @@ -12,6 +12,20 @@ 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. +## Optional compact run metadata + +v0.2.0 adds one optional trailer without changing the two required trailers: + +```text +AI-Agent: hermes-coder +AI-Model: claude-sonnet-4.5 +AI-Run: 1|anthropic|claude-sonnet-4.5@20250901|h|18234/200000|2510|ses_01K8|feat-auth +``` + +The eight fields are `schema|provider|model@version|effort|in/max|out|session|task`, with no spaces around pipes. Use harness-provided values, `-` for missing slots, and `unknown` for a missing version. Additional trailing fields are ignored for forward compatibility; invalid known fields fail parsing. See [METRICS.md](METRICS.md) for exact rules, the `AI_*` environment table, PR body pair, and local JSONL export. + +`agent-pr.mjs` omits `AI-Run` when run environment input is absent. The default checker still requires only `AI-Agent` and `AI-Model`; `--require-run` requires a valid `AI-Run` on agent-classified messages. Do not add `AI-X-*` trailers, prompts, or traces. Human `AI-Eval` belongs in a separate PR comment, never a generated trailer or edited commit. + ## Recommended ``` @@ -19,6 +33,8 @@ AI-Session: 2026-09-27T18:00:00Z-abc123 Co-authored-by: Your Name ``` +`AI-Session` remains compatible with older consumers; new harnesses using `AI-Run` can carry the opaque session identifier in that single compact trailer instead. + ## Example ``` @@ -53,9 +69,10 @@ node scripts/check-agent-trailers.mjs --help node scripts/check-agent-trailers.mjs --message-file path/to/message.txt node scripts/check-agent-trailers.mjs --message-file path/to/message.txt --author-email '123+coder[bot]@users.noreply.github.com' --json 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, and `2` for invalid arguments or an unreadable message file. `--json` reports `agentAuthored`, `trailers`, `missing`, and `ok` for a completed check. +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. ## PR Action @@ -74,7 +91,7 @@ To require trailers even on human-authored commits, change the workflow's Action The runner rejects missing commits, shallow history, empty ranges, and invalid input instead of treating a failed scan as success. It reports each checked SHA without printing untrusted commit messages. -The workflow fetches PR history, then checks out the base revision before running the local Action. Bootstrap the Action and both scripts on the target branch before making this check required. Checker changes take effect after they reach that branch; run the tests on proposed changes before merging them. Protect the workflow and contract files with human review as well. +The workflow fetches PR history, then checks out the base revision before running the local Action. Bootstrap the Action, both checker scripts, and their shared `scripts/parse-agent-run.mjs` dependency on the target branch before making this check required. Checker changes take effect after they reach that branch; run the tests on proposed changes before merging them. Protect the workflow and contract files with human review as well. ## Limits diff --git a/scripts/agent-pr.mjs b/scripts/agent-pr.mjs index c5d9938..a4530ba 100644 --- a/scripts/agent-pr.mjs +++ b/scripts/agent-pr.mjs @@ -8,6 +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"; class AgentPrError extends Error {} @@ -128,16 +129,33 @@ function validateCommitInput(message, model = "unknown") { } } -export function buildCommitMessage(message, model = "unknown", appSlug) { +export function buildCommitMessage(message, model = "unknown", 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."); } - return `${message.replace(/\r\n/g, "\n").trim()}\n\nAI-Agent: ${appSlug}\nAI-Model: ${model.trim()}\n`; + if (agentRun !== null && !parseAgentRun(agentRun, model.trim())) throw new AgentRunError("Invalid AI-Run value."); + const runTrailer = agentRun === null ? "" : `AI-Run: ${agentRun}\n`; + return `${message.replace(/\r\n/g, "\n").trim()}\n\nAI-Agent: ${appSlug}\nAI-Model: ${model.trim()}\n${runTrailer}`; } -export function parseArgs(argv) { - const options = { model: "unknown", files: [] }; +export function upsertAgentRun(body, agentRun) { + if (body !== null && body !== undefined && typeof body !== "string") throw new AgentPrError("GitHub returned an invalid PR body."); + const text = body ?? ""; + if (agentRun === null || agentRun === undefined) return text; + if (!parseAgentRun(agentRun) || /[`\r\n]/.test(agentRun)) throw new AgentRunError("Invalid AI-Run PR block."); + const block = `\n\`${agentRun}\``; + let replaced = false; + const updated = text.replace(/^[ \t]*(?:\r?\n[ \t]*`[^`\r\n]*`[ \t]*)?(?=\r?$)/gm, () => { + if (replaced) return ""; + replaced = true; + return block; + }); + return replaced ? updated : `${text.trimEnd()}${text.trimEnd() ? "\n\n" : ""}${block}`; +} + +export function parseArgs(argv, env = {}) { + const options = { model: env.AI_MODEL || undefined, files: [] }; for (let index = 0; index < argv.length; index += 1) { const argument = argv[index]; if (argument === "--help" || argument === "-h") { @@ -277,7 +295,10 @@ export async function publishAgentPr(options, { requireCapability(policy, "coder", "commit_branch"); requireCapability(policy, "coder", "open_pr"); if (options.mergeWhenGreen) requireCapability(policy, "merger", "merge"); - validateCommitInput(options.message, options.model); + const suppliedModel = options.model ?? (env.AI_MODEL || undefined); + const model = suppliedModel ?? "unknown"; + validateCommitInput(options.message, model); + const agentRun = packAgentRun(env, suppliedModel?.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."); @@ -382,7 +403,7 @@ export async function publishAgentPr(options, { throw new AgentPrError("GitHub did not return the bot identity for the configured App; refusing to publish."); } const botEmail = `${bot.id}+${botName}@users.noreply.github.com`; - const message = buildCommitMessage(options.message, options.model, appSlug); + const message = buildCommitMessage(options.message, model, appSlug, agentRun); const repository = await githubRequest(repoPath, token, { fetchImpl }); if ( repository?.full_name?.toLowerCase() !== slug.toLowerCase() || @@ -440,11 +461,12 @@ export async function publishAgentPr(options, { }); committed = true; const actual = git(["log", "-1", "--format=%H%x00%an%x00%ae%x00%cn%x00%ce%x00%B"], "Committed identity verification").split("\0"); - const checked = checkMessage(actual[5] ?? "", true); + const checked = checkMessage(actual[5] ?? "", true, "", agentRun !== null); if ( !/^[0-9a-f]{40}$/i.test(actual[0]) || actual[1] !== botName || actual[2] !== botEmail || actual[3] !== botName || actual[4] !== botEmail || !checked.ok || - checked.trailers["AI-Agent"] !== appSlug || checked.trailers["AI-Model"] !== (options.model ?? "unknown").trim() + checked.trailers["AI-Agent"] !== appSlug || checked.trailers["AI-Model"] !== model.trim() || + (checked.trailers["AI-Run"] ?? null) !== agentRun ) { throw new AgentPrError("The new commit does not have the required bot identity and trailers; refusing to push."); } @@ -476,8 +498,20 @@ export async function publishAgentPr(options, { const title = /^\[[^\]]+\] /.test(subject) ? subject : `[agent] ${subject.replace(/^[a-z]+(?:\([^)]+\))?!?:\s*/i, "")}`; invoke("gh", [ "pr", "create", "--repo", slug, "--head", branch, "--base", repository.default_branch, - "--draft", "--title", title, "--body", message, + "--draft", "--title", title, "--body", upsertAgentRun(buildCommitMessage(options.message, model, appSlug), agentRun), ], "Draft pull-request creation", { env: { ...baseEnv, GH_TOKEN: token } }); + } else if (agentRun !== null) { + if (pullRequests.length !== 1 || !Number.isSafeInteger(pullRequests[0]?.number) || pullRequests[0].number <= 0) { + throw new AgentPrError("Expected exactly one open PR before updating AI-Run metadata."); + } + const pullPath = `${repoPath}/pulls/${pullRequests[0].number}`; + const pull = await githubRequest(pullPath, token, { fetchImpl }); + if (pull?.number !== pullRequests[0].number || pull.state !== "open" || pull.head?.sha !== actual[0] || + pull.head.ref !== branch || pull.head.repo?.full_name?.toLowerCase() !== slug.toLowerCase()) { + throw new AgentPrError("The PR no longer matches the published branch and head SHA; metadata was not updated."); + } + const body = upsertAgentRun(pull.body, agentRun); + if (body !== pull.body) await githubRequest(pullPath, token, { method: "PATCH", body: { body }, fetchImpl }); } result = { commit: actual[0], botName, createdPullRequest: !pullRequests.length }; if (options.mergeWhenGreen) { @@ -537,7 +571,7 @@ export async function publishAgentPr(options, { result = { ...result, localBranchDeleted: true, checkedOutBranch: repository.default_branch }; } } catch (error) { - const detail = error instanceof AgentPrError || error instanceof AgentPolicyError ? error.message : "Publication failed; details were withheld to protect credentials."; + const detail = error instanceof AgentPrError || error instanceof AgentPolicyError || error instanceof AgentRunError ? error.message : "Publication failed; details were withheld to protect credentials."; const state = merged ? ` PR #${result.pullRequest} was merged; ${result.remoteBranchDeleted ? "the remote feature branch was removed, but local cleanup is incomplete." : "remote-branch cleanup may be incomplete."} Inspect the branch state before retrying.` : committed ? " The local commit remains; do not create a duplicate commit to retry." : ""; @@ -557,7 +591,7 @@ export async function publishAgentPr(options, { export async function main(argv, { stdout = process.stdout, stderr = process.stderr, ...dependencies } = {}) { let options; try { - options = parseArgs(argv); + options = parseArgs(argv, dependencies.env ?? process.env); } catch (error) { stderr.write(`${error instanceof AgentPrError ? error.message : "Invalid arguments."}\n`); return 2; @@ -566,6 +600,10 @@ 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. +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. Requires Node 20+, Git, gh, GITHUB_APP_ID, and GITHUB_APP_PRIVATE_KEY_PATH. Requires root agent-policy.yml with coder commit_branch and open_pr grants, matching the reviewed policy on origin's default branch. No example fallback. @@ -588,7 +626,7 @@ An invocation authorizes commit, push, and PR creation. Keep secrets out of argu if (result.merged) stdout.write(`Merged PR #${result.pullRequest} with a merge commit, removed its remote and local feature branches, and checked out ${result.checkedOutBranch}.\n`); return 0; } catch (error) { - stderr.write(`${error instanceof AgentPrError || error instanceof AgentPolicyError ? error.message : "agent-pr failed; details were withheld to protect credentials."}\n`); + stderr.write(`${error instanceof AgentPrError || error instanceof AgentPolicyError || error instanceof AgentRunError ? error.message : "agent-pr failed; details were withheld to protect credentials."}\n`); return 1; } } diff --git a/scripts/check-agent-trailers.mjs b/scripts/check-agent-trailers.mjs index 57d46e8..e051f23 100644 --- a/scripts/check-agent-trailers.mjs +++ b/scripts/check-agent-trailers.mjs @@ -7,13 +7,16 @@ import { readFileSync } from "node:fs"; import { resolve } from "node:path"; import { pathToFileURL } from "node:url"; +import { parseAgentRun, parseTrailers } from "./parse-agent-run.mjs"; + +export { parseTrailers } from "./parse-agent-run.mjs"; const REQUIRED = ["AI-Agent", "AI-Model"]; const BOT_EMAIL = /^[^@\s]+\[bot\]@(?:users\.)?noreply\.github\.com$/i; function usage(stream = process.stdout) { stream.write(`Usage: - check-agent-trailers.mjs [--require] [--json] [--author-email EMAIL] + check-agent-trailers.mjs [--require] [--require-run] [--json] [--author-email EMAIL] (--message TEXT | --message-file PATH) check-agent-trailers.mjs --help @@ -21,6 +24,7 @@ function usage(stream = process.stdout) { --message-file PATH Read a UTF-8 commit message from a file --author-email EMAIL Also classify GitHub noreply bot authors as agents --require Require trailers on every message + --require-run Require a valid AI-Run on agent-authored messages --json Print the result as JSON --help, -h Show this help @@ -31,13 +35,15 @@ function usage(stream = process.stdout) { } function parseArgs(argv) { - const out = { require: false, json: false, message: null, authorEmail: "" }; + const out = { require: false, requireRun: false, json: false, message: null, authorEmail: "" }; for (let index = 0; index < argv.length; index += 1) { const argument = argv[index]; if (argument === "--help" || argument === "-h") { out.help = true; } else if (argument === "--require") { out.require = true; + } else if (argument === "--require-run") { + out.requireRun = true; } else if (argument === "--json") { out.json = true; } else if (["--message", "--message-file", "--author-email"].includes(argument)) { @@ -60,30 +66,11 @@ function parseArgs(argv) { return out; } -export function parseTrailers(message) { - const normalized = String(message).replace(/\r\n/g, "\n").trimEnd(); - const trailers = {}; - const lines = normalized.split("\n"); - let i = lines.length - 1; - const collected = []; - while (i >= 0 && lines[i].trim() === "") i -= 1; - while (i >= 0) { - const line = lines[i]; - const m = /^([A-Za-z0-9][-A-Za-z0-9]*):\s*(.*)$/.exec(line); - if (!m) break; - collected.push([m[1], m[2].trim()]); - i -= 1; - } - if (i < 0 || lines[i].trim() !== "") return trailers; - for (const [k, v] of collected.reverse()) trailers[k] = v; - return trailers; -} - export function isAgentAuthored(message, requireAll = false, authorEmail = "") { return requireAll || String(message).includes("AI-Agent:") || BOT_EMAIL.test(authorEmail); } -export function checkMessage(message, requireAll = false, authorEmail = "") { +export function checkMessage(message, requireAll = false, authorEmail = "", requireRun = false) { const trailers = parseTrailers(message); const agent = isAgentAuthored(message, requireAll, authorEmail); const missing = []; @@ -91,6 +78,13 @@ export function checkMessage(message, requireAll = false, authorEmail = "") { for (const key of REQUIRED) { if (!trailers[key] || String(trailers[key]).trim() === "") missing.push(key); } + if (requireRun) { + try { + if (!parseAgentRun(trailers["AI-Run"], trailers["AI-Model"])) missing.push("AI-Run"); + } catch { + missing.push("AI-Run"); + } + } } return { agentAuthored: agent, @@ -117,11 +111,12 @@ function main(argv) { usage(process.stderr); process.exit(2); } - const result = checkMessage(args.message, args.require, args.authorEmail); + const result = checkMessage(args.message, args.require, args.authorEmail, args.requireRun); if (args.json) { process.stdout.write(`${JSON.stringify(result, null, 2)}\n`); } else if (!result.ok) { - process.stderr.write(`missing trailers: ${result.missing.join(", ")}\n`); + const reason = result.missing.includes("AI-Run") ? "missing or invalid trailers" : "missing trailers"; + process.stderr.write(`${reason}: ${result.missing.join(", ")}\n`); } process.exit(result.ok ? 0 : 1); } diff --git a/scripts/export-agent-metrics.mjs b/scripts/export-agent-metrics.mjs new file mode 100644 index 0000000..8d09190 --- /dev/null +++ b/scripts/export-agent-metrics.mjs @@ -0,0 +1,64 @@ +#!/usr/bin/env node + +import { execFileSync } from "node:child_process"; +import { resolve } from "node:path"; +import { pathToFileURL } from "node:url"; +import { AgentRunError, parseAgentRunMessage } from "./parse-agent-run.mjs"; + +export function exportAgentMetrics({ cwd = process.cwd(), ref = "HEAD", run = execFileSync } = {}) { + let history; + try { + history = run("git", [ + "log", "--no-show-signature", "--no-color", "--no-decorate", "--reverse", + "--format=%H%x00%B%x00", "--end-of-options", ref, "--", + ], { cwd, encoding: "utf8", stdio: ["ignore", "pipe", "pipe"], maxBuffer: 16 * 1024 * 1024 }); + } catch { + throw new AgentRunError("Could not read local Git history; verify the repository and --ref."); + } + const fields = history.split("\0"); + if (fields.length % 2 !== 1 || fields.at(-1).trim() !== "") { + throw new AgentRunError("Git returned an invalid commit stream; no metrics were exported."); + } + const records = []; + for (let index = 0; index < fields.length - 1; index += 2) { + const sha = fields[index].trim(); + if (!/^(?:[0-9a-f]{40}|[0-9a-f]{64})$/i.test(sha)) { + throw new AgentRunError("Git returned an invalid commit SHA; no metrics were exported."); + } + try { + const record = parseAgentRunMessage(fields[index + 1], sha); + if (record) records.push(JSON.stringify(record)); + } catch { + throw new AgentRunError(`Invalid AI-Run in commit ${sha}; no metrics were exported.`); + } + } + return records.length ? `${records.join("\n")}\n` : ""; +} + +export function main(argv, { stdout = process.stdout, stderr = process.stderr, ...dependencies } = {}) { + if (argv.length === 1 && ["--help", "-h"].includes(argv[0])) { + stdout.write(`Usage: node scripts/export-agent-metrics.mjs [--ref REVISION_OR_RANGE] + +Export compact AI-Run trailers from local Git history as JSONL (default: HEAD). +Commits without AI-Run are skipped; invalid records fail without partial output. +No network access, analytics service, prompts, traces, evaluations, or quality scores. +Exit 0: exported; 1: history or metadata error; 2: invalid arguments. +`); + return 0; + } + if (argv.length && (argv.length !== 2 || argv[0] !== "--ref" || !argv[1] || argv[1].startsWith("-"))) { + stderr.write("Use --ref REVISION_OR_RANGE or --help.\n"); + return 2; + } + try { + stdout.write(exportAgentMetrics({ ...dependencies, ref: argv[1] ?? "HEAD" })); + return 0; + } catch (error) { + stderr.write(`${error instanceof AgentRunError ? error.message : "Could not export local AI-Run metadata."}\n`); + return 1; + } +} + +if (process.argv[1] && import.meta.url === pathToFileURL(resolve(process.argv[1])).href) { + process.exitCode = main(process.argv.slice(2)); +} \ No newline at end of file diff --git a/scripts/parse-agent-run.mjs b/scripts/parse-agent-run.mjs new file mode 100644 index 0000000..645136d --- /dev/null +++ b/scripts/parse-agent-run.mjs @@ -0,0 +1,150 @@ +#!/usr/bin/env node + +import { readFileSync } from "node:fs"; +import { resolve } from "node:path"; +import { pathToFileURL } from "node:url"; + +const PROVIDERS = ["anthropic", "openai", "github-copilot", "local", "other"]; +const EFFORTS = { low: "l", medium: "m", high: "h", max: "x", l: "l", m: "m", h: "h", x: "x", "-": "-" }; +const ENV_KEYS = [ + "AI_PROVIDER", "AI_MODEL", "AI_MODEL_VERSION", "AI_EFFORT", "AI_CONTEXT_USED", + "AI_CONTEXT_MAX", "AI_CONTEXT_OUT", "AI_SESSION", "AI_TASK", +]; + +export class AgentRunError extends Error {} + +export function parseTrailers(message) { + const normalized = String(message).replace(/\r\n/g, "\n").trimEnd(); + const trailers = {}; + const lines = normalized.split("\n"); + let index = lines.length - 1; + const collected = []; + while (index >= 0 && lines[index].trim() === "") index -= 1; + while (index >= 0) { + const match = /^([A-Za-z0-9][-A-Za-z0-9]*):\s*(.*)$/.exec(lines[index]); + if (!match) break; + collected.push([match[1], match[2].trim()]); + index -= 1; + } + if (index < 0 || lines[index].trim() !== "") return trailers; + for (const [key, value] of collected.reverse()) trailers[key] = value; + return trailers; +} + +function invalid(field) { + throw new AgentRunError(`Invalid AI-Run ${field}; see docs/METRICS.md.`); +} + +function count(value, field) { + if (value === "-") return null; + if (!/^[0-9]+$/.test(value)) invalid(field); + const number = Number(value); + return Number.isSafeInteger(number) ? number : value; +} + +export function parseAgentRun(value, expectedModel) { + if (value === undefined || value === null || value === "") return null; + if (typeof value !== "string") invalid("value"); + const fields = value.split("|"); + if (fields.length < 8) invalid("columns (expected at least eight)"); + const [schema, provider, modelVersion, effort, context, output, session, task] = fields; + if (schema !== "1") invalid("schema (expected 1)"); + if (fields.slice(0, 8).some((field) => field !== field.trim())) invalid("delimiter spacing"); + if (provider !== "-" && !PROVIDERS.includes(provider)) invalid("provider"); + const modelParts = /^([^\s|@`]+)@([A-Za-z0-9._-]+)$/.exec(modelVersion); + if (!modelParts || (expectedModel !== undefined && modelParts[1] !== expectedModel)) invalid("model@version"); + if (!["l", "m", "h", "x", "-"].includes(effort)) invalid("effort"); + const contextParts = context.split("/"); + if (contextParts.length !== 2) invalid("in/max"); + if (!/^[A-Za-z0-9._-]{1,64}$/.test(session)) invalid("session"); + if (!/^[A-Za-z0-9._-]{1,64}$/.test(task)) invalid("task"); + return { + model: modelParts[1], + schema: 1, + provider: provider === "-" ? null : provider, + model_version: modelParts[2], + effort: effort === "-" ? null : effort, + context_used: count(contextParts[0], "in"), + context_max: count(contextParts[1], "max"), + context_out: count(output, "out"), + session: session === "-" ? null : session, + task: task === "-" ? null : task, + }; +} + +export function packAgentRun(env = {}, model = env.AI_MODEL ?? "") { + const values = Object.fromEntries(ENV_KEYS.map((key) => { + const value = env[key] ?? ""; + if (typeof value !== "string") invalid(key); + return [key, value]; + })); + if (!ENV_KEYS.some((key) => values[key] !== "")) return null; + 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"; + const packed = [ + "1", + values.AI_PROVIDER || "-", + `${resolvedModel}@${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); + return packed; +} + +export function parseAgentRunMessage(message, sha = null) { + const trailers = parseTrailers(message); + const run = parseAgentRun(trailers["AI-Run"], trailers["AI-Model"]); + return run ? { sha, agent: trailers["AI-Agent"] ?? null, ...run } : null; +} + +export function main(argv, { stdout = process.stdout, stderr = process.stderr } = {}) { + if (argv.length === 1 && ["--help", "-h"].includes(argv[0])) { + stdout.write(`Usage: node scripts/parse-agent-run.mjs [--sha SHA] (--message TEXT | --message-file PATH) + +Print one JSONL record for an AI-Run trailer, or nothing if it is absent. +Exit 0: parsed or absent; 1: invalid AI-Run; 2: invalid arguments or unreadable input. +Unknown trailing fields are ignored. No prompts, traces, or AI-Eval comments are exported. +`); + return 0; + } + let message = null; + let sha = null; + try { + for (let index = 0; index < argv.length; index += 1) { + const argument = argv[index]; + if (!["--sha", "--message", "--message-file"].includes(argument)) throw new Error(); + const value = argv[++index]; + if (value === undefined || value.startsWith("--")) throw new Error(); + if (argument === "--sha") { + if (sha !== null || !/^(?:[0-9a-f]{40}|[0-9a-f]{64})$/i.test(value)) throw new Error(); + sha = value; + } else { + if (message !== null) throw new Error(); + message = argument === "--message-file" ? readFileSync(value, "utf8") : value; + } + } + if (message === null) throw new Error(); + } catch { + stderr.write("Choose one readable --message or --message-file input and an optional full --sha; use --help.\n"); + return 2; + } + try { + const record = parseAgentRunMessage(message, sha); + if (record) stdout.write(`${JSON.stringify(record)}\n`); + return 0; + } catch (error) { + stderr.write(`${error instanceof AgentRunError ? error.message : "Could not parse AI-Run metadata."}\n`); + return 1; + } +} + +if (process.argv[1] && import.meta.url === pathToFileURL(resolve(process.argv[1])).href) { + process.exitCode = main(process.argv.slice(2)); +} \ No newline at end of file diff --git a/skills/signed-bot-commit/SKILL.md b/skills/signed-bot-commit/SKILL.md index 106784d..fd940c6 100644 --- a/skills/signed-bot-commit/SKILL.md +++ b/skills/signed-bot-commit/SKILL.md @@ -30,7 +30,7 @@ AI-Agent: AI-Model: unknown ``` -Use `--model` to replace `unknown` when the actual model is known. It checks the committed author, committer, trailers, and protected file paths before pushing the verified commit. +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. ## Usage diff --git a/tests/agent-pr.test.mjs b/tests/agent-pr.test.mjs index 82f189e..82dc713 100644 --- a/tests/agent-pr.test.mjs +++ b/tests/agent-pr.test.mjs @@ -7,9 +7,10 @@ import test from "node:test"; import { fileURLToPath } from "node:url"; import { buildCommitMessage, createAppJwt, main, - mintInstallationToken, parseArgs, parseOrigin, publishAgentPr, + mintInstallationToken, parseArgs, parseOrigin, publishAgentPr, 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"; const policySource = readFileSync(new URL("../examples/agent-policy.yml", import.meta.url), "utf8"); const approvedPolicyFile = { type: "file", encoding: "base64", content: Buffer.from(policySource).toString("base64") }; @@ -25,6 +26,11 @@ const credentials = { appId: "123", privateKey, owner: "example-owner", reposito const cwd = fileURLToPath(new URL("../", import.meta.url)); const commitSha = "a".repeat(40); const repository = { full_name: "example-owner/example-repo", default_branch: "main", archived: false }; +const runEnvironment = { + AI_PROVIDER: "anthropic", AI_MODEL: "claude-sonnet-4.5", AI_MODEL_VERSION: "20250901", AI_EFFORT: "high", + AI_CONTEXT_USED: "18234", AI_CONTEXT_MAX: "200000", AI_CONTEXT_OUT: "2510", AI_SESSION: "ses_01K8", AI_TASK: "feat-auth", +}; +const compactRun = "1|anthropic|claude-sonnet-4.5@20250901|h|18234/200000|2510|ses_01K8|feat-auth"; function mockGitHub(responses) { const calls = []; @@ -228,6 +234,110 @@ test("an existing open PR is reused without running gh pr create", async () => { assert.ok(!mock.commands.some((call) => call.command === "gh" && call.args[0] === "pr")); }); +test("AI-Run PR body upsert replaces exactly one tagged pair and preserves other text", () => { + const block = `\n\`${compactRun}\``; + assert.equal(upsertAgentRun("", compactRun), block); + assert.equal(upsertAgentRun("Description.", compactRun), `Description.\n\n${block}`); + const existing = "Description.\n\n\n`old-value`\n\n## Review\nHuman text."; + const expected = `Description.\n\n${block}\n\n## Review\nHuman text.`; + assert.equal(upsertAgentRun(existing, compactRun), expected); + assert.equal(upsertAgentRun(expected, compactRun), expected); + assert.equal(upsertAgentRun(existing, null), existing); + assert.equal(upsertAgentRun("\nHuman text.", compactRun), `${block}\nHuman text.`); + const duplicate = upsertAgentRun(`${existing}\n\n\n\`another-value\``, compactRun); + assert.equal(duplicate.match(//g).length, 1); + assert.equal(duplicate.match(new RegExp(compactRun.replaceAll("|", "\\|"), "g")).length, 1); + assert.ok(duplicate.includes("Human text.")); + assert.ok(!duplicate.includes("another-value")); + assert.equal(upsertAgentRun("Description.\r\n\r\n\r\n`old`\r\nEnd.", compactRun), `Description.\r\n\r\n${block}\r\nEnd.`); +}); + +test("AI-Run is omitted when environment input is absent, including with --model alone", async () => { + for (const model of [undefined, "explicit-model"]) { + const mock = mockPublication(); + await publishAgentPr({ message: "feat: helper", model }, mock.dependencies); + const commit = mock.commands.find((call) => call.args.includes("commit")); + assert.ok(!commit.input.includes("AI-Run:")); + const create = mock.commands.find((call) => call.command === "gh" && call.args[1] === "create"); + assert.ok(!create.args[create.args.indexOf("--body") + 1].includes("agent-run:1")); + assert.ok(!mock.requests.some((call) => call.method === "PATCH")); + } +}); + +test("AI-Run uses supplied environment data and AI_MODEL, with --model taking precedence", async () => { + for (const explicitModel of [undefined, "cli-model"]) { + const mock = mockPublication(); + Object.assign(mock.dependencies.env, runEnvironment, { AI_EVAL: "must-not-be-published" }); + const output = []; + const args = ["--message", "feat: helper", ...(explicitModel ? ["--model", explicitModel] : [])]; + assert.equal(await main(args, { ...mock.dependencies, stdout: { write: (text) => output.push(text) }, stderr: { write: (text) => output.push(text) } }), 0); + const expectedModel = explicitModel ?? runEnvironment.AI_MODEL; + const expectedRun = packAgentRun(runEnvironment, expectedModel); + const commit = mock.commands.find((call) => call.args.includes("commit")); + assert.deepEqual(parseTrailers(commit.input), { "AI-Agent": AGENT, "AI-Model": expectedModel, "AI-Run": expectedRun }); + assert.equal(commit.input.match(/^AI-Run:/gm).length, 1); + const create = mock.commands.find((call) => call.command === "gh" && call.args[1] === "create"); + const body = create.args[create.args.indexOf("--body") + 1]; + assert.ok(body.endsWith(`\n\`${expectedRun}\``)); + assert.ok(!body.includes("AI-Run:")); + assert.ok(!commit.input.includes("AI-Eval") && !body.includes("AI-Eval")); + assert.ok(!body.includes("must-not-be-published")); + } +}); + +test("AI-Run missing slots use sentinels and invalid effort fails before authentication", async () => { + 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|-|-/-|-|-|-"); + 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." }); + assert.equal(invalid.keyReads(), 0); + assert.equal(invalid.requests.length, 0); + assert.equal(invalid.commands.length, 0); +}); + +test("AI-Run upserts the current PR body without replacing human content or creating a second PR", async () => { + for (const existingBody of [ + "Human description.\n\n\n`old-value`\n\nReview notes.", + "Human description.", null, + `Human description.\n\n\n\`${compactRun}\``, + ]) { + const mock = mockPublication({ pullRequests: [{ number: 7 }] }); + Object.assign(mock.dependencies.env, runEnvironment); + const originalFetch = mock.dependencies.fetchImpl; + mock.dependencies.fetchImpl = (url, options) => { + if (url.endsWith("/pulls/7")) { + mock.requests.push({ url, ...options }); + return Response.json({ + number: 7, state: "open", body: existingBody, + head: { sha: commitSha, ref: "feat/bot-helper", repo: { full_name: repository.full_name } }, + }); + } + return originalFetch(url, options); + }; + await publishAgentPr({ message: "feat: helper" }, mock.dependencies); + const patches = mock.requests.filter((call) => call.method === "PATCH"); + const expectedBody = upsertAgentRun(existingBody, compactRun); + assert.equal(patches.length, existingBody === expectedBody ? 0 : 1); + if (patches.length) assert.deepEqual(JSON.parse(patches[0].body), { body: expectedBody }); + assert.ok(!mock.commands.some((call) => call.command === "gh" && call.args[1] === "create")); + } +}); + +test("AI-Run changes made by a commit hook are rejected before pushing", async () => { + const mock = mockPublication(); + Object.assign(mock.dependencies.env, runEnvironment); + const originalRun = mock.dependencies.run; + mock.dependencies.run = (command, args, options) => { + const output = originalRun(command, args, options); + return args[0] === "log" ? output.replace("|h|", "|x|") : output; + }; + await assert.rejects(publishAgentPr({ message: "feat: helper" }, mock.dependencies), /required bot identity and trailers/); + assert.ok(!mock.commands.some((call) => call.args[0] === "push")); +}); + test("missing, invalid, or insufficient local policy denies publication before commands, key access, or network calls", async () => { for (const source of [undefined, "default: allow", "version: 1\ndefault: deny\n", policySource.replace("open_pr, ", "")]) { const mock = mockPublication(); @@ -841,7 +951,7 @@ test("local Git integration commits selected and staged files with bot provenanc context.after(() => rmSync(directory, { recursive: true, force: true, maxRetries: 3 })); const commands = []; const gitEnvironment = Object.fromEntries(Object.entries(process.env).filter(([name]) => - !/^(GIT_|GH_|GITHUB_APP_)/i.test(name) && !/^(GITHUB_TOKEN|GITHUB_ENTERPRISE_TOKEN)$/i.test(name) + !/^(AI_|GIT_|GH_|GITHUB_APP_)/i.test(name) && !/^(GITHUB_TOKEN|GITHUB_ENTERPRISE_TOKEN)$/i.test(name) )); const localGit = (args, options = {}) => execFileSync("git", [ "-c", "core.fsmonitor=false", diff --git a/tests/agent-run.test.mjs b/tests/agent-run.test.mjs new file mode 100644 index 0000000..4b1277f --- /dev/null +++ b/tests/agent-run.test.mjs @@ -0,0 +1,175 @@ +import assert from "node:assert/strict"; +import { execFileSync, spawnSync } from "node:child_process"; +import { mkdtempSync, rmSync, writeFileSync } from "node:fs"; +import { join } from "node:path"; +import test from "node:test"; +import { fileURLToPath } from "node:url"; +import { packAgentRun, parseAgentRun, parseAgentRunMessage } from "../scripts/parse-agent-run.mjs"; +import { exportAgentMetrics } from "../scripts/export-agent-metrics.mjs"; + +const repository = fileURLToPath(new URL("../", import.meta.url)); +const parser = fileURLToPath(new URL("../scripts/parse-agent-run.mjs", import.meta.url)); +const exporter = fileURLToPath(new URL("../scripts/export-agent-metrics.mjs", import.meta.url)); +const model = "claude-sonnet-4.5"; +const compact = "1|anthropic|claude-sonnet-4.5@20250901|h|18234/200000|2510|ses_01K8|feat-auth"; +const environment = { + AI_PROVIDER: "anthropic", + AI_MODEL: model, + AI_MODEL_VERSION: "20250901", + AI_EFFORT: "high", + AI_CONTEXT_USED: "18234", + AI_CONTEXT_MAX: "200000", + AI_CONTEXT_OUT: "2510", + AI_SESSION: "ses_01K8", + AI_TASK: "feat-auth", +}; + +test("packs and unpacks the exact schema 1 example", () => { + assert.equal(packAgentRun(environment), compact); + assert.deepEqual(parseAgentRun(compact, model), { + model, + schema: 1, + provider: "anthropic", + model_version: "20250901", + effort: "h", + context_used: 18234, + context_max: 200000, + context_out: 2510, + session: "ses_01K8", + task: "feat-auth", + }); +}); + +test("omits AI-Run without environment input or without any provider or model", () => { + assert.equal(packAgentRun({}), null); + assert.equal(packAgentRun({}, "explicit-model"), null); + assert.equal(packAgentRun({ AI_PROVIDER: "", AI_MODEL: "", AI_EFFORT: "" }), null); + assert.equal(packAgentRun({ AI_CONTEXT_USED: "12", AI_SESSION: "session" }), null); + for (const value of [undefined, null, ""]) assert.equal(parseAgentRun(value), null); +}); + +test("partial environment uses missing-slot sentinels rather than inventing metadata", () => { + assert.equal(packAgentRun({ AI_PROVIDER: "local" }), "1|local|unknown@unknown|-|-/-|-|-|-"); + assert.equal(packAgentRun({ AI_MODEL: "known-model" }), "1|-|known-model@unknown|-|-/-|-|-|-"); + 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, + context_used: null, context_max: null, context_out: null, session: null, task: null, + }); +}); + +test("normalizes only the documented effort aliases", () => { + for (const [input, expected] of [["low", "l"], ["medium", "m"], ["high", "h"], ["max", "x"], ["l", "l"], ["m", "m"], ["h", "h"], ["x", "x"]]) { + assert.equal(packAgentRun({ ...environment, AI_EFFORT: input }).split("|")[3], expected); + } + for (const effort of ["extreme", "HIGH", " high", "h ", "0", "__proto__", "h\nAI-Eval: private-value"]) { + assert.throws(() => packAgentRun({ ...environment, AI_EFFORT: effort }), { message: "Invalid AI-Run effort; see docs/METRICS.md." }); + } +}); + +test("ignores unknown trailing fields without changing the first eight columns", () => { + assert.deepEqual(parseAgentRun(`${compact}|future-key=value||a future field`), parseAgentRun(compact)); + assert.throws(() => parseAgentRun(`2${compact.slice(1)}`), /schema/); +}); + +test("rejects invalid known columns and mismatched AI-Model", () => { + const invalidFields = [ + [0, ""], [0, "01"], [1, "unknown"], [1, "OPENAI"], + [2, `${model}@bad version`], [2, `${model}@`], [2, model], [2, `other@${model}@version`], + [3, "high"], [3, ""], [4, "1.2/200000"], [4, "1e2/200000"], [4, "-1/200000"], + [4, "1/2/3"], [4, "1/"], [5, "abc"], [5, "2.5"], + [6, "has space"], [6, "x".repeat(65)], [7, ""], [7, "task/secret"], + ]; + for (const [index, value] of invalidFields) { + const fields = compact.split("|"); + fields[index] = value; + assert.throws(() => parseAgentRun(fields.join("|")), /Invalid AI-Run/); + } + assert.throws(() => parseAgentRun(compact, "another-model"), /model@version/); + assert.throws(() => parseAgentRun(compact.split("|").slice(0, 7).join("|")), /columns/); + assert.throws(() => parseAgentRun(compact.replace("|h|", "| h|")), /spacing/); + assert.throws(() => packAgentRun({ ...environment, AI_SESSION: "session|injection" }), /Invalid AI-Run/); +}); + +test("preserves zero counts, model paths, token versions, and large integers without rounding", () => { + const packed = packAgentRun({ ...environment, AI_MODEL: "owner/model:small", AI_MODEL_VERSION: "v1.2_rc-3", AI_CONTEXT_USED: "0", AI_CONTEXT_OUT: "9007199254740993" }); + const parsed = parseAgentRun(packed, "owner/model:small"); + assert.equal(parsed.context_used, 0); + assert.equal(parsed.context_out, "9007199254740993"); + assert.equal(parsed.model_version, "v1.2_rc-3"); +}); + +function message(run = compact) { + return `feat: auth\n\nBody text is not exported.\n\nAI-Agent: hermes-coder\nAI-Model: ${model}\nAI-Run: ${run}\n`; +} + +test("parses only footer metadata into the exact JSONL record shape", () => { + const sha = "a".repeat(40); + const record = parseAgentRunMessage(`${message()}AI-Future: ignored\n`, sha); + assert.deepEqual(record, { sha, agent: "hermes-coder", ...parseAgentRun(compact, model) }); + assert.deepEqual(Object.keys(record), ["sha", "agent", "model", "schema", "provider", "model_version", "effort", "context_used", "context_max", "context_out", "session", "task"]); + assert.equal(parseAgentRunMessage("fix: typo\n"), null); + assert.equal(parseAgentRunMessage(`${message()}\nMore body text\n`), null); +}); + +test("the parser CLI emits one record, omits absent metadata, and fails on malformed metadata", (context) => { + const directory = mkdtempSync(join(repository, ".agent-run-test-")); + context.after(() => rmSync(directory, { recursive: true, force: true, maxRetries: 3 })); + const path = join(directory, "message.txt"); + writeFileSync(path, message()); + const result = spawnSync(process.execPath, [parser, "--message-file", path, "--sha", "a".repeat(40)], { encoding: "utf8" }); + assert.equal(result.status, 0, result.stderr); + assert.deepEqual(JSON.parse(result.stdout), parseAgentRunMessage(message(), "a".repeat(40))); + const absent = spawnSync(process.execPath, [parser, "--message", "fix: typo"], { encoding: "utf8" }); + assert.equal(absent.status, 0, absent.stderr); + assert.equal(absent.stdout, ""); + const invalid = spawnSync(process.execPath, [parser, "--message", message("invalid")], { encoding: "utf8" }); + assert.equal(invalid.status, 1); + assert.equal(invalid.stdout, ""); + const usage = spawnSync(process.execPath, [parser, "--message-file"], { encoding: "utf8" }); + assert.equal(usage.status, 2); +}); + +test("JSONL export ignores missing trailers and future fields without leaking message bodies", () => { + const records = [ + ["a".repeat(40), message()], + ["b".repeat(40), "fix: typo\n"], + ["c".repeat(40), message(`${compact}|future-data`)], + ]; + const jsonl = exportAgentMetrics({ run: (command, args) => { + assert.equal(command, "git"); + assert.deepEqual(args.slice(-3), ["--end-of-options", "HEAD", "--"]); + return records.map(([sha, text]) => `${sha}\0${text}\0\n`).join(""); + } }); + assert.deepEqual(jsonl.trim().split("\n").map((line) => JSON.parse(line)), [ + parseAgentRunMessage(message(), "a".repeat(40)), parseAgentRunMessage(message(), "c".repeat(40)), + ]); + assert.ok(!jsonl.includes("Body text")); + assert.ok(!jsonl.includes("future-data")); + assert.throws(() => exportAgentMetrics({ run: () => `${"a".repeat(40)}\0${message("bad")}\0\n` }), /Invalid AI-Run in commit/); + assert.equal(exportAgentMetrics({ run: () => "" }), ""); +}); + +test("the export CLI reads a local Git history and respects revision ranges", (context) => { + const directory = mkdtempSync(join(repository, ".agent-run-test-")); + context.after(() => rmSync(directory, { recursive: true, force: true, maxRetries: 3 })); + const env = { + ...Object.fromEntries(Object.entries(process.env).filter(([name]) => !/^(GIT_|GH_|GITHUB_APP_)/i.test(name))), + GIT_AUTHOR_NAME: "test-agent[bot]", GIT_AUTHOR_EMAIL: "1+test-agent[bot]@users.noreply.github.com", + GIT_COMMITTER_NAME: "test-agent[bot]", GIT_COMMITTER_EMAIL: "1+test-agent[bot]@users.noreply.github.com", + }; + const git = (args, input) => execFileSync("git", [ + "-c", "commit.gpgsign=false", "-c", `core.hooksPath=${join(directory, "no-hooks")}`, ...args, + ], { cwd: directory, env, input, encoding: "utf8", stdio: ["pipe", "pipe", "pipe"] }).trim(); + git(["init", "--quiet", "--initial-branch=fixture", "--object-format=sha1"]); + git(["commit", "--quiet", "--allow-empty", "--file=-"], "Initial fixture\n"); + const base = git(["rev-parse", "HEAD"]); + git(["commit", "--quiet", "--allow-empty", "--file=-"], message()); + const head = git(["rev-parse", "HEAD"]); + const result = spawnSync(process.execPath, [exporter, "--ref", `${base}..${head}`], { cwd: directory, env, encoding: "utf8" }); + assert.equal(result.status, 0, result.stderr); + assert.deepEqual(JSON.parse(result.stdout), parseAgentRunMessage(message(), head)); + const invalid = spawnSync(process.execPath, [exporter, "--ref", "missing-ref"], { cwd: directory, env, encoding: "utf8" }); + assert.equal(invalid.status, 1); + assert.equal(invalid.stdout, ""); +}); \ No newline at end of file diff --git a/tests/check-agent-trailers.test.mjs b/tests/check-agent-trailers.test.mjs index 81459aa..640ba1d 100644 --- a/tests/check-agent-trailers.test.mjs +++ b/tests/check-agent-trailers.test.mjs @@ -182,7 +182,44 @@ test("CLI usage errors exit two", () => { test("CLI --help documents flags and exits zero", () => { const result = runChecker(["--help"]); assert.equal(result.status, 0, result.stderr); - for (const flag of ["--help", "--message", "--message-file", "--author-email", "--require", "--json"]) { + for (const flag of ["--help", "--message", "--message-file", "--author-email", "--require", "--require-run", "--json"]) { assert.ok(result.stdout.includes(flag), flag); } }); + +test("default checks still require only AI-Agent and AI-Model", () => { + const message = "feat: x\n\nAI-Agent: coder\nAI-Model: known-model\n"; + assert.equal(checkMessage(message).ok, true); + assert.equal(checkMessage(`${message}AI-Run: invalid\n`).ok, true); +}); + +test("--require-run requires valid compact metadata matching AI-Model only on agent commits", () => { + const message = "feat: x\n\nAI-Agent: coder\nAI-Model: known-model\n"; + assert.deepEqual(checkMessage(message, false, "", true).missing, ["AI-Run"]); + assert.equal(checkMessage(`${message}AI-Run: 1|openai|known-model@unknown|m|12/100|5|session|task\n`, false, "", true).ok, true); + for (const run of [ + "1|openai|different-model@unknown|m|12/100|5|session|task", + "1|openai|known-model@unknown|medium|12/100|5|session|task", + "2|openai|known-model@unknown|m|12/100|5|session|task", + "", "not a compact record", + ]) { + assert.deepEqual(checkMessage(`${message}AI-Run: ${run}\n`, false, "", true).missing, ["AI-Run"]); + } + assert.equal(checkMessage("fix typo\n", false, "", true).ok, true); + assert.deepEqual(checkMessage("fix typo\n", true, "", true).missing, ["AI-Agent", "AI-Model", "AI-Run"]); + assert.deepEqual(checkMessage("fix typo\n", false, "1+coder[bot]@users.noreply.github.com", true).missing, ["AI-Agent", "AI-Model", "AI-Run"]); +}); + +test("CLI --require-run reports absent or malformed metadata without making human commits mandatory", () => { + const message = "feat: x\n\nAI-Agent: coder\nAI-Model: known-model\n"; + const missing = runChecker(["--require-run", "--message", message, "--json"]); + assert.equal(missing.status, 1); + assert.deepEqual(JSON.parse(missing.stdout).missing, ["AI-Run"]); + const invalid = runChecker(["--require-run", "--message", `${message}AI-Run: invalid\n`]); + assert.equal(invalid.status, 1); + assert.match(invalid.stderr, /missing or invalid trailers: AI-Run/); + assert.equal(runChecker(["--require-run", "--message", "fix typo"]).status, 0); + assert.equal(runChecker(["--require", "--require-run", "--message", "fix typo"]).status, 1); + const valid = runChecker(["--require-run", "--message", `${message}AI-Run: 1|-|known-model@unknown|-|-/-|-|-|-|future\n`]); + assert.equal(valid.status, 0, valid.stderr); +});