Skip to content

Decisions, library versions and deviations

Docs index · Architecture

Each Phase 0 step was specified in docs/phase-0/step-N-*.md, built, and reviewed until approved (the loop is described in docs/phase-0/README.md; the review notes are in docs/phase-0/reviews/). This page records, per step, the library facts that were checked against node_modules, the choices made where a spec was silent, and every place the implementation deviates from its spec. IDs such as U-WH-3, I-INT-9 or D13 refer to tests and decisions in the step specs; grep -rn "<ID>" test/ finds a test. References such as "§6.4" or "T17.1" are sections and tasks of the step's own spec.

Contents: Stack · Step 1 · Step 2 · Step 3 · Step 4 · Step 5 · Step 6 · E2E runner · Live e2e runner

Stack choices and library versions

Choices from the step spec: Node 24 ESM, strict TypeScript (NodeNext, noUncheckedIndexedAccess, verbatimModuleSyntax), tsx for dev, Biome for lint and format, Vitest with unit and integration projects, Fastify, Kysely with pg and a static migration provider, pg-boss in schema pgboss, pino with redaction, Postgres 17 on port 55432, GitHub numeric IDs as bigint keys (parsed to number, throwing above 2^53), smee-client for the dev tunnel.

Versions in the lockfile (majors): Fastify 5, Kysely 0.29, pg 8, pg-boss 12, pino 10, zod 4, @octokit/app 16, @octokit/rest 22, @octokit/webhooks 14, @octokit/webhooks-methods 6, @octokit/webhooks-examples and -schemas 7, TypeScript 7, Vitest 5, Biome 2, tsx 4, ajv 8, smee-client 5.

Step 1: base setup

Spec: step-1-base-setup.md. Deviations and additions relative to the step spec:

  • pg-boss is v12, not v10. The assumed API held with these differences: queue and job retry delay is retryDelay (seconds), not retryDelaySeconds (our JobDefinition.options.retryDelaySeconds is mapped to it); retention is deleteAfterSeconds (7 days on every queue, except github.webhook with 1 hour since step 6; it is a per-job option, JobDefinition.options.deleteAfterSeconds); work() takes { localConcurrency, batchSize } and a handler over Job[]; the transaction option is db with an executeSql(text, values) adapter (type exported as Db), which is what createPgBossQueue builds from a Kysely transaction. start() installs/migrates its own schema, so the server and worker both call it. Defaults when a job sets no options: retryLimit 5, retryBackoff true, retryDelay 10, expireInSeconds 300. They are applied as queue options in createQueue. Queue options are re-applied with updateQueue on every start, because createQueue does nothing for an existing queue (I-Q-3).
  • singletonKey does not deduplicate on pg-boss v12 standard queues. Since v10 the key is only enforced by queue policies short, singleton, stately, exclusive, key_strict_fifo (or together with singletonSeconds); on our standard queues it is stored and ignored. JobQueue.send(..., { singletonKey }) therefore also sets a deterministic job id (UUIDv5-style SHA-1 of job name and key; singletonJobId in src/queue/queue.ts). pg-boss inserts with ON CONFLICT DO NOTHING, so a second send with the same name and key inserts nothing and send returns null (I-Q-2). The window covers queued, active, completed and failed jobs until they are deleted, 7 days after completion or failure (deleteAfterSeconds; 1 hour for github.webhook). A caller that needs a re-run (for example a check_run.rerequested for the same SHA) must use a different key, such as one that includes an attempt number or a timestamp. A null return means "already enqueued". For webhooks the webhook_deliveries primary key is the first line of defence; if the job send returns null (job exists, delivery row gone) the existing job id is stored and the outcome is duplicate.
  • Empty body returns 400 before signature verification (spec deviation: the spec has no empty-body rule). It is a cheap check that needs no secret and touches no state; GitHub never sends an empty body (U-WH-8). A delivery id over 100 characters also returns 400 (U-WH-7).
  • Permanent failures are retried up to retryLimit; a non-retryable error type is deferred to a later step. Job data validation runs inside the logged try.
  • Kysely 0.29 exports Migrator from kysely/migration.
  • zod 4: z.ZodType<T> works as in the spec; config defaults are applied before validation (string form).
  • Fastify 5.12: disableRequestLogging is deprecated in favour of LogController, which buildServer uses (request logging is off; the receiver logs its own outcome line).
  • githubWebhookJob is built by a factory. The job needs the registry's handler lookup and the registry lists the job, so createRegistry builds it with createGithubWebhookJob(registry) and exposes it as registry.webhookJob (also present in registry.jobs). The receiver sends registry.webhookJob.
  • createPgBossQueue returns PgBossJobQueue (a JobQueue plus the boss instance the worker needs) and takes a supervise flag (false for the server, true for the worker). buildServer is async and returns the instance without listening.
  • Store functions (getActiveRepository, listActiveRepositories, ...) take a Kysely Db or Transaction as their first argument.
  • Extra files not in the layout: src/bin/bootstrap.ts and src/bin/env.ts (shared wiring), scripts/generate-fixtures.ts (how the fixtures were produced), pnpm-workspace.yaml (pnpm 11 build-script allowlist for esbuild), test/helpers/app.ts, test/helpers/stubs.ts.
  • The upstream webhook examples are older than @octokit/webhooks-schemas and contain no merged pull_request.closed; the generator repairs missing required fields with neutral values and marks the closed PR as merged so all fixtures validate (U-FIX-1).

Step 2: provenance

Spec: step-2-provenance.md.

  • Library reality. @octokit/rest 22 includes paginate.iterator (used for commits and comments; the iterator is stopped early after 3 and 10 pages). checks.update takes the check run id and no head_sha, so the PATCH body omits it. Nothing else differed from the spec's assumptions. pg-boss 12 only marks a failed job retry and bumps retry_count when it is next fetched, so I-Q-4 asserts the retry state, not the count.
  • D13 fallback (added). New optional env GITHUB_APP_SLUG (Config.githubAppSlug). When set, a comment authored by <slug>[bot] (type Bot) that starts with the marker is accepted as ours when performed_via_github_app.id does not match. Without the slug the strict app-id check is the only check. Tested in U-MC-9, U-MC-10 and I-PROV-9. HUMAN-TODO has an item to confirm the field on real GitHub.
  • Dedup key carries updated_at and the action. (Step 3 appended :{action}; see T18.) D6 as written would swallow any return to an earlier state within 7 days: closed/reopened after opened, a body edited X to Y to X, or a force-push H1 to H2 to H1 would all hit the key of a completed job, leaving stale provenance. The key is prov:{repo}:{pr}:{head}:{base}:{bodyHash}:{pull_request.updated_at} for all five actions, and pull_request.updated_at is required in the payload schema (a payload without it enqueues nothing). A replayed body has the same updated_at, so replay protection is kept. The cost is one redundant, idempotent job for a title-only edit (the comment comes back unchanged, the check run gets one PATCH).
  • In-lock staleness check. Inside withChangeLock the job publishes only if the stored head SHA equals the live head and the stored pr_updated_at is not newer than the live updated_at. Otherwise two jobs on the same head with different bodies could publish the older body last (I-PROV-10b; the head-moved branch is I-PROV-10c). updated_at has one-second resolution, so two edits inside the same second cannot be ordered. The next event, or a Re-run of the check, refreshes the output; until then it can be one same-second change behind. The second window (a same-second change with an unchanged head and body, for example closed then reopened) is now closed by action in the dedup key. The title-edit plus close case remains: a title-only edit and a close inside one second share updated_at, head and body, and only the action tells them apart.
  • Session host is plain LDH (D14 hardening). validateSessionUrl additionally requires every host label to match [a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?, at least two labels, at most 253 characters (one trailing dot is tolerated and localhost. is rejected), because the hostname is the link text and WHATWG URL accepts ` * _ ~ ! $ & ' { } = in a host. \, ` and * are percent-encoded in the href. Trailer whitespace follows git (space and tab only), not JavaScript \s.
  • Output-size failures are permanent. upsertManagedSection throws PermanentJobError (invalid_output) for a marker in the section or an oversize section or comment, instead of retrying a deterministic failure 8 times.
  • Order inside the lock. The provenance job upserts the managed comment first and then the check run (T14 lists the check run first); the intent job publishes in the other order since step 4 (see "Step 4 deviations and additions"). This is what I-PROV-8 describes ("comment created, then the check-run POST fails") and it keeps the outcome identical: a failure rolls everything back and the retry adopts the existing comment (T8 3b).
  • Not applied snapshot returns early. If upsertChangeFromPull reports applied: false (stored updated_at is newer), the job logs stale and stops before any commit fetch or publish. That is what I-PROV-3 requires; T14 does not say it.
  • parseTrailerBlock also returns blockTooLong (P7 needs a way to reach the block_too_long warning); ProvenanceResult also carries truncated (the renderer needs it and counts cannot express it); persistProvenance also takes repositoryFullName (for the issue URL). When the text was cut from the front (P2) the single remaining paragraph is not treated as a subject.
  • Session URLs must be printable ASCII (no non-ASCII at all, not even in the path), a stricter reading of "all character sets are ASCII". | is percent-encoded as well as ( ) [ ], because the URL is rendered inside a table cell (and see the LDH rule above).
  • Rendering of warnings without a field (unknown_graft_key, block_too_long): - <where>: trailer block ignored (<code>), or unknown Graft key ignored (unknown_graft_key) for an unknown key. When there are no trailers and the PR is truncated, the "no Graft-* trailers found" footer still gets the truncation sentence appended.
  • U-REN-7 uses the agent value octo@bot/@team: the spec's @octo/bot starts with @, which the agent character set rejects (a separate assertion checks that it is rejected and never rendered).
  • I-SEC-3 posts the installation.created body as pull_request twice: unchanged (the receiver ignores it, since the action created is not handled) and with action: "opened" so the handler really runs and logs payload_shape_mismatch.
  • pnpm db:rollback reverts one migration (the latest), as T1 requires; in step 1 it rolled back everything. The test helper migrateDown still goes to zero.
  • Extras: getActiveInstallation (installations store, exported) is the "installation exists and is not deleted or suspended" check used by the handlers and the job; ProvenanceTable.source gains pr_body; changes.pr_updated_at and graft_comment_id are optional on insert so step 1 tests compile unchanged; a continue instead of return lets the worker finish a batch after a permanent error (batch size is 1).

Step 3: intent service

Spec: step-3-intent-service.md.

  • Versions. @anthropic-ai/sdk 0.133.0, picomatch 4.0.7, @types/picomatch 4.0.3 (dev; picomatch ships no types).
  • SDK verified against node_modules (T1). Everything the spec names exists and behaves as assumed: the constructor options apiKey, maxRetries, timeout, fetch (and baseURL, used by the tests); per-request { timeout, maxRetries }; output_config: { effort, format: { type: "json_schema", schema } } on the plain messages.create (effort is low | medium | high | xhigh | max); system text blocks with cache_control; client.beta.messages.create with betas and fallbacks: "default" (server-side-fallback-2026-07-01 is a listed beta); usage.{input_tokens, output_tokens, cache_read_input_tokens, cache_creation_input_tokens} (the cache counters can be null); stop_reason "refusal" and "max_tokens"; response.model; the error classes APIConnectionTimeoutError, APIConnectionError, RateLimitError, InternalServerError, AuthenticationError, PermissionDeniedError, BadRequestError and APIError.status. Detail the spec did not state: the beta call puts betas into the anthropic-beta header and adds ?beta=true to the URL, while fallbacks stays in the JSON body (U-LLM-2 asserts exactly that). A 529 arrives as an InternalServerError-style APIError with status 529 and is retried by the SDK (U-LLM-10). Errors that are not AnthropicErrors are rethrown as programmer errors.
  • pg-boss 12.38 verified (T1). schedule(name, cron, data?, options?), unschedule(name, key?), getSchedules(name?, key?) and the constructor option schedule: boolean exist as named. schedule needs the queue to exist (the queue wrapper creates all queues in start()), calling it again for the same name replaces the cron (unschedule removes it), and the cron expression is only validated by pg-boss at schedule() time: GRAFT_FEEDBACK_POLL_CRON is checked for shape only (5 fields of digits, *, /, ,, -), so a cron that passes the shape but is invalid stops the worker at startup. JobQueue.unschedule takes the job definition, like schedule.
  • The card JSON sent to the verifier escapes < as \u003c (still valid JSON). Without it, a writer that echoes the nonce it saw could put a closing data tag into the card and break out of the data block. The spec says "JSON.stringify of the validated writer output"; the parsed JSON is identical.
  • Injection rule (R15) ignores format characters. Before matching, computeRiskFloor removes Unicode Cf characters and the visible [U+XXXX] form that neutralizeUntrusted writes for them, so ig\u200bnore previous instructions still counts. The spec's patterns are unchanged.
  • Floor reasons. FloorReason.paths holds at most 5 paths as specified, so the check output lists at most 5 per rule (the spec's "up to 50" is an upper bound). The injection reason has no paths and count is the number of matching texts; size and listing reasons have none and count 0 (the renderer takes line and file counts from inputs).
  • Classification order. Lockfile, then binary, then generated, then "no patch from the API" (T9), implemented once in classifyFile (risk-floor.ts) and shared by the diff preparation and rule R10. Files beyond the 300th in priority order are summarised per top-level directory; files at the root fall under ".".
  • InputStats.truncated is true when the listing is truncated, the PR is too large, or any file is partial (truncated, or omitted for a reason other than lockfile or binary).
  • Nonce seam. chooseNonce(canonical, untrustedBlocks, derive?) in diff.ts takes the derivation function as an optional parameter; U-DIFF-10 uses it to force a k=0 collision.
  • Two strong readings overrule the first pass. The spec's final = max(floor, writer, first pass, verifier, ...) let the fast model alone decide the class of a change that the strong writer and the verifier, reading the same diff, both rated lower. On the pilot data (228 changes) that was 9 changes, among them a two-line prompt edit that needed two approvals because only the fast model said sensitive. firstPassCounts (risk-floor.ts) now leaves the first pass out when both strong calls answered and both rate lower; it stays in when either agrees with it, when the verifier failed, when the escalation failed and when any model reported instructions in the data (lower ratings are then what an injection would produce). The floor is untouched: no model can lower it. Stored cards keep the class they were written with.
  • A failed escalation keeps what is known. If the fast writer answered and the strong re-write fails, the unavailable result still carries the first-pass class, its model and the instruction flag, so a first pass of sensitive is not lost.
  • Cached cards skip the pending note and the budget. The cache check (step 5) comes before the outdated-section note (D11) and the budget check, so a cache hit makes no extra GitHub write and counts no tokens.
  • Card rows use the injected clock. saveCard writes created_at and updated_at from ctx.clock (not the database default), so the daily budget and the tests follow the injected time.
  • intent.feedback.sweep data is the empty object, validated strictly. The sweep reads owner and repo from repositories.full_name, skips removed repositories, and the poll job re-checks the installation.
  • Feedback summary since applies to the effective vote's reacted_at (the vote that wins first, then the time filter).
  • Reactions with a null user are dropped when read; reactions of any user type other than Bot count (Mannequin and Organization included).
  • Models in the card row are response.model as returned by the API (often a dated id), not the requested alias.
  • Pure generate.ts exports also RETRYABLE (used by the store to rebuild retryable from a stored row) and EFFORTS, MAX_OUTPUT_TOKENS.
  • Test changes outside the spec's list. test/unit/fixtures.test.ts lists the new check_run.requested_action fixture (the generator reuses the upstream example and rewrites it); I-DB-7 now rolls back two migrations (0003 then 0002) because 0003 is the latest; I-CHG-6 uses a replay of opened for its first assertion because the action is now part of the key; U-RISK-13's "removed line does not match" half is tested at the card level (U-RISK-13c), because computeRiskFloor receives only the added lines; U-INJ-2 includes a file whose name tries to close the section from inside a code span, so that removing the <!-- rewrite in codeSpan fails it. New helper files: test/helpers/intent-inputs.ts (pure builders) next to the specified intent-scenario.ts. test/unit/log-hygiene.test.ts (U-LOG-2) is an extra grep-style test that no logger call in src/llm or src/modules/intent mentions prompts, diffs, PR text or model output.
  • T18 follow-ups. Done as specified: provenance re-run key prov-rerun:{repoId}:{pr}:{minute} (I-PROV-11), :{action} in refreshKey, WarningCode and GraftField moved to src/db/schema.ts (fields.ts re-exports them; grep -rn "modules/" src/db/ finds nothing), I-PROV-10c isolated by clearing changes.pr_updated_at before the gate is released, and the README wording in the step 2 section. Mutation check for I-PROV-10c: with the in-lock head check removed from provenance/job.ts the test now fails (the same holds for I-INT-9 and intent/job.ts).
  • Mutation checks (DoD) were run by hand and each made the named tests fail: removing the in-lock head check in intent/job.ts fails I-INT-9; dropping the floor term in combineRisk fails U-RISK-17, U-RISK-18, U-INJ-1 (and U-GEN-4, U-GEN-13, U-GEN-20); adding the PR text to the verifier message fails U-GEN-15; removing the <!-- rewrite in markdown.ts fails U-MD-4, U-MD-9, U-INJ-2 and U-INJ-4.

Step 3 review 1 changes

  • Spend is a ledger (D21 changed). intent_spend (repository_id, change_id, tokens, llm_calls, spent_at) is append-only and saveCard writes one row per model run before the card upsert, so retries, re-runs, in-place regeneration of an unavailable row and a dropped concurrent ok save all count. tokensUsedToday sums the ledger for the UTC day (bounded on both sides), not intent_cards.created_at. The card's token columns still describe only the run that produced the row. Migration 0003_intent (not yet committed) was edited in place; TABLE_NAMES now has 13 tables (I-DB-3 and I-DB-8 updated). I-INT-17, I-INT-18, I-INT-19; I-INT-11 seeds the ledger.
  • Displays are recorded (reaction attribution changed). intent_displays (change_id, card_id, status, shown_at, seq) gets a row whenever what is on screen changes (another card, or the same card in another status), written in the publish lock with ctx.clock.now() taken right before markPublished (not the job start). Reactions are attributed to the display with the greatest shown_at <= created_at, so A, B, A credits later votes to A, and a reaction made while the "card unavailable" notice was shown is dropped. intent_cards.published_at keeps the first display only (the sweep still uses it, and publishedCheckRunForHead); latestPublishedCard (the D11 note) follows the latest display. markPublished takes { id, changeId, status }. I-INT-20, I-FB-6, I-FB-7, I-FB-8, U-FB-7.
  • Retry notice (D9/D8 changed). The retry job is queued before the publish and "Graft retries automatically" is rendered only when send returned an id. The retry key ended with the triggering deliveryId in step 3; since step 4 it ends with a 5-minute bucket (see "Step 4 deviations and additions"). A deduplicated send shows the "Re-run" text. I-INT-21, I-INT-22.
  • Total deadline (D6 changed). LlmRequest.deadlineMs (the remaining job deadline) becomes an AbortSignal.timeout on the SDK request, so SDK retries and their backoff end at the deadline; the abort maps to timeout. The deadline starts at the job start (GenerateOptions.startedAtMs), so the listing time counts. U-LLM-12.
  • Fallback blocks (D5). Only the text blocks after the last fallback block are the answer. U-LLM-11.
  • Feedback button guard. The job data carries the payload's check_run.external_id (externalId, optional); a vote whose card differs from the check run's current external_id is rejected (feedback_rejected). I-FB-9.
  • Nits fixed. Output strings made only of Cf characters are empty (U-OUT-7); R15 patterns use \s+ between words (U-RISK-19); GH-<n> is broken with a word joiner (U-MD-11); intentRepoSettings takes { repositoryId, installationId, owner, repo, baseSha } for step 5 (LivePull.base.sha is optional).
  • Nits not fixed. Paths in R15 (spec change: file names like ai-reviewer.md would raise the floor on ordinary repositories). Pure rename classified no_patch_from_api (needs diff.ts to handle a file without a patch and a spec change to U-DIFF). "Up to 50 paths" in the check output (U-RISK-7 and the stored FloorReason shape fix the cap at 5; carrying a second list is a spec change).
  • I-E2E-3 now waits for both check runs as well as the comment: the comment contains both sections one request before the intent check run exists.
  • Review 1 mutation checks (run by hand in a throwaway copy): dropping the ledger insert in saveCard fails I-INT-17, I-INT-18, I-INT-19; making toJobError return the original error and the worker log and rethrow the raw one fails I-INT-12 and I-E2E-4 (with only one of the two layers undone, U-GHE-4/U-GHE-5 or nothing fails, by design); taking the display time at the job start fails I-INT-20; recording a display only when none exists fails I-FB-6 and I-FB-7 (and I-FB-1, I-FB-2); ignoring the fallback block fails U-LLM-11; removing the abort signal fails U-LLM-12; always showing the retry text fails I-INT-21; removing the external_id guard fails I-FB-9; removing the in-lock head check in provenance/job.ts fails I-PROV-10c.

Step 4: evaluation set

Spec: step-4-evaluation-set.md. (Referred to elsewhere as "Step 4 deviations and additions".)

  • Retry key (T17.1). intent-retry:{changeId}:{headSha}:{inputHash16}:{attempt}:{floor(nowMs / 300000)}, with nowMs from ctx.clock. A pending-only singleton is not available on our standard queues (pg-boss 12), hence the bucket: two triggers for the same inputs within five minutes queue one retry, and a later failure in a new bucket queues its own even when an earlier chain completed. The comment above the send in job.ts says so. I-INT-21 now moves the clock by one bucket for its last step (a different delivery in the same bucket is deduplicated); I-INT-22 covers the new rule.
  • The D11 "outdated" note is a display (T17.2). Migration 0004_intent_display_pending widens intent_displays.status to ok | unavailable | pending (down: deletes pending rows, restores the old CHECK). After the note's comment write, inside the same lock, the job records a pending display of the previous card. attributeReactions already treated every non-ok display as a dropped one, so a reaction made while the note is shown is not credited to any card. latestPublishedCard skips pending displays. markPublished still compares with the last display of any status, so the next ok or unavailable publish after a note adds a row. I-FB-10, I-DB-9.
  • Publish order and display time (T17.3). The intent job now writes the check run first, then the comment, then markPublished with a now taken right after the comment write. A failed check-run call leaves the old comment and no new display, a failed comment call leaves no new display either, and the pg-boss retry finds the saved card and publishes once. This replaces the "comment first" order for the intent job only (the provenance job keeps its order). I-INT-23.
  • 0003 down (T17.4) uses DROP TABLE IF EXISTS for intent_displays and intent_spend. escapeProse (T17.5) keeps the <!-- rewrite with the "unreachable, defence in depth" comment; no behavior change.
  • New exports. modules/intent/index.ts also exports fetchIntentInputs, promptFingerprint, maxRisk, RISK_ORDER, DOCS_GLOBS, TEST_GLOBS, globMatcher and MAX_OUTPUT_TOKENS; modules/provenance/index.ts exports computeProvenance and fetchPrCommits. U-PROMPT-1 also asserts promptFingerprint() equals the pinned hash.
  • No new dependency. zod 4's z.toJSONSchema (draft 2020-12, verified against node_modules) generates the schemas; dates and timestamps are checked with regular expressions instead of format, so that a plain JSON Schema validator needs no format plugin. Refinements JSON Schema cannot express are listed in the case schema's top-level description.
  • Report details the spec left open. status of a row is ok | unavailable | skipped (a case skipped by the budget has status skipped). Report thresholds carry a provisional boolean; report.pass is true only when every result passes (a provisional failure makes it false but exits 1 only with --strict). The baseline comparison also ignores the derived fields thresholds and pass (they depend on the baseline itself) and the per-row cached flag; everything else must be equal. Cached rows keep the cost of the result they reuse, costUsdThisRun counts only the rows that were not cached. A baseline that does not exist is a usage error with --check on the synthetic set, and an explicit --baseline that does not exist is always one.
  • Run options added. RunOptions.git is not part of the harness: the CLI fills report.git itself. maxTokens also gates the pre-run estimate. Budgets and the confirmation apply to --live only (fake mode has no real spend); in-flight cases reserve their estimate so that concurrency cannot overshoot --max-cost-usd.
  • Export details. The export counts cases that already exist toward --sample (so a re-run of the same export writes nothing, and an aborted one resumes with the rest, re-sampled: see "Resumed export" below), and skips them before stage 1. Exported cases are tagged size-s|m|l|xl and path-sensitive|tests|docs|source so that the report's per-tag under-classification shows the strata. --author bot filters on the list response (user.type, --agent-logins) and makes no commit request; --author any fetches commits only to classify. Pull requests with more than 20,000 changed lines or 1,000 files are classified without a file listing (stratum source). source.baseSha falls back to forty zeros if the API omits base.sha. --redact accepts only emails.

Redaction is wider than the spec's §6.4 table (step 4 review 1, finding 1). The assignment rule matches an identifier that contains a secret word (password, passwd, passphrase, secret, credential, api_key, access_key, private_key anywhere in the name; token(s), pwd, auth, authorization as a whole _, -, . or camelCase segment), so DB_PASSWORD, AWS_SECRET_ACCESS_KEY, client_secret, access_token, app.db.password and clientSecret are covered, and tokenize(...) and author are not. It accepts a quote before the operator ("password": "...", 'api_key': '...', escaped JSON), the operators =, ==, ===, :=, => and :, and a quoted value with spaces (up to the matching quote); the name, operator and quotes stay, and a value shorter than 8 characters stays. Further rules: url_credentials (scheme://user:PASSWORD@, only the password), bearer (Authorization: Bearer|Basic|Token ...), <password>...</password> elements, PEM and PGP private key blocks, and the provider tokens GitHub (ghp_, gho_, ghs_, ghu_, ghr_, github_pat_), AWS (AKIA, ASIA), Stripe (sk_live_, rk_live_), Anthropic and OpenAI (sk-), Google (AIza), GitLab (glpat-), npm (npm_), Slack (xox[abprs]-) and JWTs. Every quantifier is bounded, and the assignment scan is linear (step 5, T14): valueSpan looks for a quoted close in a 512-character window, an unquoted value ends at whitespace, a quote, or one of , ; ) } ] &, a run longer than the window is redacted whole up to its real end, and after every candidate (accepted, rejected or empty) the scan resumes past the span it read, so no character is scanned twice per line however adversarial the line is (U-RED-12). The same step 5 pass closes the leak forms found in step 4 review 2: a value on the next lines (a YAML |/> block, an empty password: followed by indented lines that are not key: lines, a \ continuation, an unterminated quote) is redacted too, at most 50 lines, keeping indentation, diff prefixes and the line count; a hunk header or \ No newline line ends that state. New kinds: cli_flag (--password VALUE, -token VALUE when the name is a secret name and the value has 8 or more characters; -pVALUE only on a line that names mysql, mysqldump, mysqladmin or mariadb; the password of -u|--user user:pass), slack_webhook, and redis://:pass@host URLs; encryption_key, master_key and signing_key are secret names; a name is also tested in its flat form so PassWord is caught; names that start with max_, min_, limit_, budget_, num_ or total_ (max_tokens) are left alone. Line count and diff prefixes (+, -, space, @@, \) never change; a hunk header ends an unterminated key block. Intentional over-redaction: any 8+ character value after a secret-looking name is replaced, including a bare identifier (token = someLongVariableName) or PWD=/home/user/project; names ending in length, size, count, type, name, path, file, url, ttl, expires, enabled and similar are left alone, as are placeholders (${VAR}, $VAR, <token>, {{ x }}), env lookups (process.env...), function calls and null/true/false. Not covered: a secret with no secret-looking name and no known prefix (a raw high-entropy string in prose); review show output before sharing a set. --redact-pattern values that match the empty string, or that are not a valid regular expression, are rejected (exit 2).

Further step 4 review 1 changes. Error output never carries pilot paths or label text: schema messages name the field only, unmapped errors print their class name (GRAFT_EVAL_DEBUG=1 adds the message), and a fake-mode generation error echoes its message only for a synthetic set. The baseline comparison also ignores metrics.costUsdThisRun (0 for a run served from the cache). After an unexpected error in one case no worker starts another. The CLI ignores a GRAFT_EVAL_KEY that only .env provides and warns on stderr: .env is for ANTHROPIC_API_KEY and the GitHub App settings, and the case-set key stays in the shell. Resumed export: a re-run does not reproduce the sample of an uninterrupted run. It counts existing cases toward --sample, then draws the remainder (sample - existing) from the fresh candidates with the same seed, and --min-per-stratum applies to the strata of those candidates only. Reproducing the original draw would mean fetching and classifying every already-exported pull request again, which costs requests for no new data; if an exact sample matters, export into a fresh set in one go. Retry key: the 5-minute bucket in the retry singletonKey means two triggers on either side of a bucket boundary queue two retry chains (at most two per boundary, each capped at two attempts); this is accepted, see the comment in src/modules/intent/job.ts. - Fake GitHub API (T8). GET /repos/{o}/{r}/pulls (state, sort, direction, Link paging, and state.listPageSize to force small pages), state.rateLimit with x-ratelimit-* headers and 403 when exhausted, an injectable clock (createFakeGitHubApi({ now })), and base.sha in makePull (optional in FakePull). - Existing tests changed. I-INT-10 (retry key), I-INT-21 (bucket), I-DB-2, I-DB-7 and I-DB-8 (they now roll back and re-apply 0004 too). No assertion was weakened. - Prices and models. Haiku and Sonnet prices are the ones in the spec (PRICING_VERIFIED_AT = 2026-10-06); I did not check them against Anthropic's page (HUMAN-TODO). No live eval was run and the real API was never called. - The synthetic cases are fictional and were adjusted only where the spec's table described behaviour the floor does not produce on its own: none needed a floor change. The floor additionally reports size_large for syn-016 and syn-018 (more than 15 files or 300 lines) and partial_view for syn-025 (the rename has no patch); the table lists the rules that decide the class. Headline values: UC floor 6/30, severe UC floor 1/30, UC final 0, accuracy final 28/30, out-of-scope and flag precision and recall 1, unavailable rate 2/30.

Step 5: policy engine

Spec: step-5-policy-engine.md.

  • Library verification (T1). yaml 2.9.1 (added with pnpm add yaml; it is a CommonJS package with types). Checked against node_modules and by running it: parseAllDocuments returns an array of Document (zero for an empty or comment-only text, which becomes not_a_mapping); LineCounter and error.pos give lines and columns, but linePos is only filled with prettyErrors: true, so the parser uses prettyErrors: false and the LineCounter; node.range is [start, valueEnd, nodeEnd]; uniqueKeys: true reports DUPLICATE_KEY as an error, a tab indent is TAB_AS_INDENT, a bad indent or an open flow collection is BAD_INDENT or similar. maxAliasCount is a toJS option, not a parse option (D6 puts it on the parser): it is passed to toJS, where 0 makes any alias throw "Alias resolution is disabled"; the real defence is that every anchor and alias is rejected by a visit before toJS runs (U-PY-3 spies on Document.prototype.toJS). merge: false makes << an ordinary key whose *alias value is still caught. !custom and !!python/object give a warning (TAG_RESOLVE_FAILED), not an error; !!binary, !!set and even !!str resolve silently and only show in node.tag; so the parser ignores TAG_RESOLVE_FAILED as a warning, reports every other warning as yaml_syntax, and rejects any explicit tag (yaml_tag), a little stricter than D6's "outside the core set". logLevel: "silent" stops toJS from printing a Node warning for a complex mapping key (the schema then reports the stringified key as an unknown key). Octokit: git.getRef({ ref: "heads/main" }) sends GET /git/ref/heads%2Fmain (Octokit percent-encodes the slash; GitHub accepts it; the fake API matches both forms), and data.object.sha is the commit; repos.getContent returns an array for a directory, a base64 content for a file, encoding: "none" above 1 MB, and type: "symlink"/"submodule" for those. That GitHub follows a symlink to an in-repo file and reports the target's path is taken from GitHub's documentation and not verified against a real repository (the check type === "file" && path === "graft.yaml" is correct either way). @octokit/webhooks has types for pull_request_review and push; the handlers validate with their own zod looseObject schemas instead, like the other handlers, and @octokit/webhooks-schemas names the push definition push$event (U-FIX-1 maps it).
  • Schema checks (T3). Structure is the zod schema (with { error: "<code>" } on each leaf and a mapper from zod issues to the catalogue; invalid_union is resolved by looking at whether the raw value is a list). The cross-field rules (exactly one action, non-empty match, approve restrictions, size bounds, unique names, glob validity, the 500-glob cap, empty require) live in crossChecks and always run on the raw value instead of a zod superRefine: zod skips a root refinement when a sibling already has a structural error, which would hide errors. They emit the same codes. policyJsonSchema() additionally writes oneOf (exactly one action) and minProperties: 1 for match, require and size into the generated schema, so editors flag those too; the rules it still cannot express are in its description. too_many_errors counts inside the 50: 49 errors plus the marker. glob_invalid reason 7 is picomatch's $^ answer for a pattern it cannot compile ([z-a]), or a regex above 2,000 characters.
  • Flow-depth pre-scan. [ and { count only where a YAML value can start (the start of a block line, after :, -, ?, ,, [ or {), so brackets inside plain scalars, quotes and comments are text. Any parser failure (for example a stack overflow) is caught and reported as yaml_syntax, so parsePolicyText never throws.
  • Spec examples that the helpers do not produce. E12 as written (Docs/A.md) would match rule 1, because *.md matches A.md with the extension's case; the test uses Docs/A.MD. The spec's rendered examples show infra\-and\-auth, but escapeProse does not escape a hyphen inside a word; the output is infra-and-auth (byte-for-byte tests use the real helper output). The closing (code) of an error line is added after escapeProse, so its parentheses stay literal and the underscore is escaped ((glob\_invalid)), as in the spec's example. EffectiveRisk.raisedBy lists a raise only when it changed the class.
  • Loader. src/policy/load.ts is the one file of src/policy that imports src/github and the error classes of src/queue/errors.ts (PermanentJobError); the CLI never imports it. U-CLI-6 checks the CLI's whole import closure, and that nothing else in src/policy reaches modules, db, config or queue. loadBasePolicy takes an optional log and also shares an in-flight request between concurrent callers. resolveBaseCommit treats a 404 as base_missing and sends other errors through toJobError; a 403 reading graft.yaml is permanent (toJobError).
  • facts_hash is the spec's input plus the rendered title, section and details: the author's name, the labels and the size are shown but not part of the verdict, so a change in them must republish. A repeated evaluation with the same hash makes no GitHub request but still moves the row's facts_read_at and evaluated_at forward (a database write only), so an older job cannot overtake it. rules_matched keeps the PR paths of a paths reason (at most 5) and only the count for a labels reason (a label also appears in the policy).
  • Signals. The intent job emits intent_published whenever a card is on screen after a successful publish (a new card or a cached one); test/helpers/fake-queue.ts needed no change because unit contexts use noSignals.
  • Fixtures. pull_request.labeled clones opened with a hotfix label; the pull_request_review fixtures keep upstream's slimmer pull_request object moved onto the fixture PR's number and head; push is a push to the fixture PR's base branch (master) that modifies graft.yaml. The upstream catalog has no usable push commits, so the generator writes one.
  • Review 1 changes (step 5).
  • Glob matching no longer uses picomatch regexes (blocker). picomatch compiles **/*a*a*/**/*a*a* and similar valid globs to nested overlapping quantifiers; one non-matching path of a few hundred characters took seconds (the §6.2 limits bound each segment, not the interplay across **). src/core/glob.ts now compiles each glob to segments and matches without backtracking over the input: dynamic programming over (pattern part, path segment), where ** costs O(parts x segments) in total, and the classic two-pointer wildcard algorithm per segment, which is polynomial. picomatch stays only inside validateGlob (compile check) and as the oracle in the tests (U-PG-7, 3,000 generated globs x 30 paths x both case modes, plus the repository's real globs, all equal). Decisions: (1) a path over 1,024 characters or 128 segments is not matched; the matcher answers its onLimit option, which the callers set to the strict side (true for sensitive_paths, tightening paths, the policy-file check and the risk floor's R1 to R7 path rules; false for only_paths and approve rules, and for test, docs, lockfile and generated classification, where a match would loosen); (2) each call has a budget of 200,000 work units and 20 ms of wall clock and answers onLimit when it is spent; (3) *** (three or more stars in a row) and ]+ are rejected with glob_invalid detail 7, because picomatch gives them regex meanings ([ab]+ repeats, a/**/*** matches a) that the segment matcher does not model; (4) the quirks that are kept on purpose: a trailing /** matches the directory itself (docs/** matches docs) unless the segment before it ends with a star (*/** needs a second segment), and ** inside a longer segment acts as *. The reviewer suggested 1,024 characters; the 4,096 in the brief would put the worst case at four times the work. The 1,024 cap is the only deliberate behaviour change for ordinary inputs: no path in the corpus is that long. Worst case, measured: about 0.6 ms per path for the worst accepted glob shapes on 1,024-character paths (U-PG-8 runs eleven such cases x 1,000 paths, each under a second).
  • An incomplete file listing may change graft.yaml (major). In step 4 of §9.2 a matched approve rule gives way to the policy_file_changed built-in also when !listingComplete; the verdict is would_require with 1 human and is never would_approve. policyFileChanged stays false (the file was not seen to change), the comment gets a note ("The list of changed files is incomplete..."). U-PE-23 is the reviewer's reproduction (size-only approve rule, 1,001 renames, files empty); U-PE-24 is the same without graft.yaml in the visible part. A require or block match is unaffected (it already needs at least 1 human), the default already requires at least 1, and the effective risk is not raised (raisedBy would claim something unknown).
  • T14 empty values (minor). The empty continuation now starts only for a YAML key line: key: with an optional - list prefix and an optional quote, and nothing else before it on the line. if password:, for token in tokens:, class PasswordForm: and case "password": stay readable (U-RED-15 negatives). An empty value after = (password =) no longer starts it either. The eval baseline is unchanged (pnpm eval:ci reports equal): the synthetic set has no such blocks.
  • Nits. The CLI rejects size > 32768 from lstat before reading (U-CLI-7, with a 3 GB sparse file that could not be read); the push fixture now targets the fixture PR's base (refs/heads/master) so the smoke fan-out finds the PR (U-FIX-3; the integration suite's pushEvent helper keeps main, which is its world's base); I-POL-21 catches mutation 8 on its own (an approving policy plus a PR that edits graft.yaml gives "Would require 1 human"); the loader's missing-blob-SHA failure is a PermanentJobError (U-LOAD-7).
  • Review 2 changes (step 5).
  • Total work is bounded (major). Measured before: a valid 32 KB policy (132 block rules of * + 194 a + b?*) against 1,000 renamed 1,024-character paths took about 6 minutes. Two defences. (a) A cost cap in validateGlob: at most 48 characters other than * per segment and 96 per glob (** segments and stars are free), glob_invalid detail 8 ("too costly"). The worst accepted glob costs about 0.37 ms per 1,024-character path, not 1.3 ms. (b) One shared GlobBudget of 50,000,000 work units (review 3 lowered this to 20,000,000 and made the model structural) per evaluatePolicy call and per computeRiskFloor call (prepareDiff has its own for the file ordering), on top of the 200,000-unit limit per matcher call. Work units are counted, not timed, so the result is the same on every machine and load; wall clock stays only as a coarse backstop (100 ms per call, 3 s per evaluation) that ordinary and crafted inputs do not reach. Each call also pays for splitting the path, so many cheap calls cannot run free. When the budget is spent: a tightening paths key counts as matched and uncertain, sensitive_paths raise the risk, only_paths and approve rules do not match, and the verdict gets limits: ["budget_exhausted"] (rendered as a note); the risk floor adds a rule (see review 3: glob_budget). Measured worst case: the 32 KB policy (161 block rules, 3 hostile globs each, plus 2 hostile sensitive_paths) against 1,000 files with 1,024-character path and previousPath takes about 0.5 s and ends would_block with budget_exhausted; U-PG-12 bounds it at 2 s. The policy-file check uses its own small budget, so a spent shared one cannot fake a change to graft.yaml.
  • / inside [...] (minor). Rejected (glob_invalid detail 6), because the matcher splits at / first while picomatch would read [a/b] as a class. U-PG-7 now covers every allowed punctuation character, more class edge cases ([-a], [a-], [*], [?], [ ], [Z-a], [é-ü]) and the folding characters ß, Kelvin, ı, É. The only accepted difference is case-insensitive matching of Kelvin, ı and ß, where the new matcher matches more than the RegExp engine (strict side).
  • onLimit sides are pinned (minor). U-PE-25 fails if paths or sensitive_paths use the loose side or if only_paths uses the strict one (two extra mutations, both killed).
  • R8 and R9 (minor). A deleted test, a test renamed away, and a shrunk test with an over-long path still raise the floor (onLimit: true for those terms; the "no longer a test" term keeps false). U-RISK-20.
  • path_too_long (nit). An over-long path is no longer reported as a change to graft.yaml: it is a limit reason (limits: ["path_too_long"]), the policy-file check does not match it, and, like an incomplete listing, it makes the built-in apply to approve matches (it may hide a change). U-PE-26.
  • Review 3 changes (step 5): the cost model is structural.
  • Why. Review 2's budget charged one unit per step, but a case-insensitive class cost about 60 units of real work (four range scans and two string allocations per character) and the path was case-folded on every call, so a valid 32 KB policy of 200 class-glob rules against 1,000 maximum-length files took about 36 s, and the 3 s wall-clock check ran only inside a single call's own counter.
  • Cost model (3 lines). (1) Each path is split and case-folded once per job (cached in the GlobBudget, charged one unit per character), and each class is compiled once into a 256-entry table with case folding already applied (code units above 255 are memoised after one charged miss), so a class test costs the same as a literal. (2) Every inner step (one character comparison, class test or DP cell) is exactly 1 unit; per-call setup is charged by size. (3) One GlobBudget per job caps total work at 20,000,000 units and glob x path comparisons at 250,000 (both superseded in review 4: 48,000,000 units, no pair cap), shared by buildFacts's computeRiskFloor and evaluatePolicy of the same policy job (evaluatePolicy(policy, facts, { budget })); when either is spent every later answer is the strict side and exhausted is set.
  • Wall clock. The deadline is now checked on a counter in the shared budget, every 16,384 units, across the whole job, and is set to 10 s: it is a bug guard, not part of the model. The budget runs out in about 0.2 to 0.3 s of matching, so on any machine the fuel binds first and results do not depend on load (U-PG-15 gives deep-equal verdicts for 5 s and 600 s limits). If the guard ever fires the worker logs glob matching hit its wall-clock guard (hook set in bootstrap.ts).
  • Measured, no network (1,000 files, 1,024-character path and previousPath, 200 rules plus 20 sensitive_paths, 32 KB): literal shape about 0.19 s for evaluatePolicy and 0.42 s for computeRiskFloor; class shape (44-entry class) 0.24 s and 0.42 s; mixed (class, two-class two-segment, literal) 0.18 s and 0.44 s. The floor time is mostly its own fixed-glob classification, not the budget. Review 3 measured 32 s and 5 s for the class shape before this change.
  • Floor reason (nit). A spent budget now adds its own floor rule glob_budget ("path matching stopped at its work limit", sensitive) instead of reusing listing_truncated. The rule is only added when the budget runs out, so no synthetic case produces it: the eval schema, the synthetic set and the saved baseline are unchanged (pnpm eval:ci reports equal), and listing_truncated metrics no longer count budget stops.
  • Uncertain hits (nit). A paths key whose answer came from a limit (a path over the caps, a per-call fuel hit or a spent budget) is reported as uncertain: true; a real match stays false. An approve or only_paths key that hit a limit does not match. Reviewers can tell an assumed hit from a real one (U-PE-29).
  • mayChangePolicy terms (nit). evaluatePolicy takes an options seam (budget, policyBudget); U-PE-28 passes a spent shared budget and a spent policy-file budget and expects the 1-human built-in, which kills the mutation that removes both terms.
  • Review 4 changes (step 5): the budget is sized from the legal maximum.
  • Problem. Review 3's 250,000-pair cap and 20 M units were guesses. The shipped example policy plus 1,000 renamed files with a pending card gave a false "Would block: rule 5", and a 41-rule policy added unrelated team requirements. A false block or requirement from the budget is as wrong as a missed one.
  • Derivation. Spec maxima: 500 globs per file, 1,000 listed files, a rename matched on path and previousPath: 500 x 1,000 x 2 = 1,000,000 glob x path pairs for the policy, plus the floor's fixed globs (about 130 x 2,000 = 264,000 pairs). Measured with an unlimited budget on the largest ordinary policy (161 rules, 483 plain globs like area3/part1/**, 7 sensitive_paths, 1,000 renames of 40-character paths, card pending so the floor shares the job): 1,243,900 pairs and 25,547,820 units (floor 4,423,480 + policy 21,124,340), about 0.5 s. EVALUATION_FUEL = 25.5 M x 1.9 = 48,000,000. The pair cap is removed: a pair costs at least 2 units plus its DP cells, so units already bound pairs; pairsUsed stays as a statistic. The derivation is also in the comment on EVALUATION_FUEL.
  • Hostile timings after the change (1,000 files, 1,024-character path and previousPath, 200 rules + 20 sensitive_paths, 32 KB; ms): literal: policy 386, floor 541, one shared budget 591; 44-entry class: 389, 473, 525; class above code 255 ([Ā-ŝ]-style): 458, 461, 533; mixed: 372, 553, 589. The job (shared budget) stays under 0.6 s; two separate budgets under 1 s. To keep the per-character cost low the DP table is now one reusable buffer instead of an allocation per pair. The ordinary maximum above takes about 0.47 s (floor + policy).
  • Memo for code units above 255. Still 4,096 entries per class and now also 100,000 entries in total: when the total is reached every memo is dropped together (and also when the compiled-matcher cache is cleared); a later miss pays its charge again. A miss costs 4 units per range (U-PG-17 pins the exact charge and the global bound).
  • Equivalent mutants. M18 (only_paths with onLimit: true) is equivalent: any limit hit already makes that key not match. M17a (paths with onLimit: false) gives the same verdict but dropped the over-limit file from the reason's list and count; U-PE-29 now asserts the count (2) and both paths, so it is killed.
  • Budget creation. The policy job creates the GlobBudget after its database reads (card and provenance), so the 10 s guard does not include them.
  • Tests. U-PE-30 (largest ordinary policy, 1,000 renames, pending card: no limit hit, correct verdict, more than 1 M pairs and under two thirds of the fuel, which pins the sizing), U-PE-31 (the shipped example is not would_block), U-PG-12/14 (hostile shapes still strict and under the time bound).
  • Review 5 changes (step 5): the cost of an ordinary glob no longer depends on path depth.
  • Problem. The matcher filled a (glob parts + 1) x (segments + 1) table for every pair, so even area3/part1/** cost O(depth). The 48 M fuel was sized on 4-segment paths; on 14-segment Java paths 160 plain 3-glob rules exhausted it and produced a false "Would block: rule 161" and unrelated team requirements. No fixed fuel can cover hundreds of millions of cells at the legal maxima.
  • Design (4 lines). (1) A forward NFA over path segments keeps only the set of live pattern positions (** may stay or skip), so an anchored prefix dies at the first mismatching segment (about 1 segment comparison for area3/part1/** against src/main/...), matching stops as soon as the set is empty, and a trailing ** accepts as soon as it is reached. (2) Prefilters computed once per glob and checked in a few units: the minimum segment count, required star-free literal segments (secrets of **/secrets/**, against a per-path segment set built once, only for floating globs), required literal runs inside parts with stars (part3 of *part3*, one native substring search on the folded path) and the literal tail of the last segment (.md of **/*.md). (3) Charge only the work done: 1 unit per live position and segment, plus the segment match, plus a few units per prefilter. (4) Semantics are unchanged: U-PG-7 still compares against picomatch, now also on 6- to 14-segment paths with several **.
  • Fuel derivation (millions of units, 1,000 renames, 161 rules x 3 globs, floor + policy in one job, pending card; final cards cost about 1 M less):

    Shape 4 segments 15 segments 30 segments
    anchored areaN/partM/** 6.1 6.5 6.7
    floating **/xN/** 5.1 5.5 5.7
    extension **/*.eN 6.1 8.4 9.6
    name part **/*partN*/** 6.1 8.4 9.6
    every glob matches (worst) 7.6 / 14.8 22.4 / 19.9 30.0 / 35.0

    (Review 4's 4-segment figure was 25.5 M with the old matcher; review 5 measured up to 161 M on 30 segments.) The worst ordinary case is 35.0 M; EVALUATION_FUEL = 60,000,000 is 1.7x that. The shipped example policy needs 1.2 to 3.7 M at 4 to 60 segments. - Hostile timings with 60 M (1,000 files with 1,024-character paths, 200 rules + 20 sensitive_paths, ms; eval / floor / shared job): literal that defeats the prefilters 386 / 444 / 483; 44-entry class 439 / 134 / 495; class above code 255 476 / 126 / 522; mixed 406 / 434 / 499; ** chains on 127-segment paths 429 / 55 / 430. All end would_block with budget_exhausted. A literal glob whose literal is missing from the path is now rejected by a prefilter in a few units, so the old literal shape stopped being hostile; the hostile tests use a literal that is present (*a...ab?x* against paths containing it). - Also fixed on the way. compareCodePoints (used to sort the matching paths of every rule) allocated two arrays per comparison; with 161 rules matching 1,000 files that took seconds. It is now allocation-free with the same results. - Tests. U-PE-32 (depths 4, 15 and 30, pending and final cards, five ordinary shapes: no limit hit, correct verdict, under two thirds of the fuel), U-PE-33 (the reviewer's 14-segment Java case: not blocked, no unrelated team requirements), U-PG-7 (deep-path differential), U-PG-18 (the early exit costs a small constant), U-PE-30/31 and U-PG-12/14/15/17 unchanged in intent. - Review 6 changes (step 5). - Blocker: the generation clock wrapped (fixed by removing it). The NFA deduplicated live positions with a module-level stampClock stored in Int32Arrays; past 2^31 ticks (about 2 x 10^9, reached by a long-lived worker, or by a few dozen hostile jobs) every comparison failed and every glob silently stopped matching, process-wide. There is no counter any more: positions are marked with 0/1 flags, and each flag that was set is cleared again in a finally (also when a call stops on a spent budget). Nothing can wrap, go stale or leak between calls. The scratch arrays grow to the largest glob (they were fixed at 128, which a long GRAFT_INTENT_SENSITIVE_PATHS glob could exceed). U-PG-19 runs tens of thousands of deep matches, calls that stop half way on budgets of 1 to 300 units, and asserts matcherScratchClean(), the matches of **/secrets/**, *.ts, infra/** and docs/** before and after, a 100-part glob, and, as a structural guard, that the source has no stampClock or stamp array. Because there is no counter to set near 2^31, the test pins the property that made the counter safe instead (no state survives a call). Audit of the other module-level state: the compiled-matcher caches (cleared past 200 keys), the memo for code units above 255 (per class and global caps, cleared together), the per-job prepared map (on the budget) and the backstop hook hold no fixed-width counter. - Minor: glued ** rejected. /**.ts, a**b, x/**y/z give glob_invalid detail 7 ("a ** glued to other characters is not supported"), because picomatch reads them as "any characters across /" and the matcher as *; the ambiguous form is rejected so a tightening glob can never match less than its author meant. **.ts without a slash is rejected too (it was read as **/**.ts). - Minor: a class's own text. picomatch compiles [ab] to (?:\[ab\]|[ab]), so *[ab] also matches a file named x[Ab] (an attacker could otherwise name a file to evade a secret[ab] glob). It is modelled, not rejected: a part with a class runs a character-level NFA whose class node is "one character of the set" or "the class's source text". Probed on picomatch: the text alternative exists unless the body holds one of - * ? + . (so [a-c], [a.b], [*] do not have it); the matcher follows that rule. U-PG-7 now has paths holding class texts and glued stars (deep and flat), U-PG-20 pins both cases. - Nit: units track time. Every iteration of both NFAs is charged, including when the live set is empty. M23 (removing the empty-set early exit) was a cost-free mutant; now the loop would charge one unit per remaining segment, and U-PG-18 (an anchored glob costs at most 10 units beyond preparation on a 30-segment path) kills it. - Existing tests changed. I-WH-4 (pull_request.labeled is now handled by the policy module, so the test sends assigned for the ignored case), I-E2E-4 (a third publisher, the policy job, also posts a check run, so three first POSTs are made to fail instead of two), U-MAN-1 (events), I-DB-2, I-DB-3 (the new columns), I-DB-7, I-DB-8 and I-DB-9 (they roll back and re-apply 0005 too), U-FIX-1's expected list, and the contexts that build a JobContext by hand (they gained signals). No assertion was weakened. - Not done / left open. Real GitHub behaviour is unverified (symlink path, git/ref encoding, the two new events, comment rendering of the [!IMPORTANT] blocks); see HUMAN-TODO. No Phase 1 feature exists: there is no enforcement code path, and the check's conclusion is a constant.

Step 6: pilots and gate

Spec: step-6-pilots-and-gate.md.

  • Library verification (checked in node_modules, pg-boss 12.38.0).
  • Retention is deleteAfterSeconds, a queue option (createQueue / updateQueue) and also a send option. A job copies the queue's deletion_seconds when it is inserted, so updateQueue changes only jobs created afterwards. Maintenance deletes a job when completed_on + deletion_seconds has passed; failed and cancelled jobs have completed_on too, so one rule covers completed and failed jobs. A job that never ran is bounded by retentionSeconds (14 days by default), which is left alone.
  • Table and column names used by the doctor and the purge: <schema>.job is a partitioned table by queue name (job_common is the default partition; deleting from the parent reaches every queue), with name, state (enum created, retry, active, completed, cancelled, failed), data (jsonb), created_on, completed_on, deletion_seconds; <schema>.schedule holds name and cron; <schema>.queue holds name and deletion_seconds. boss.supervise(name) runs the maintenance for a queue on demand (used by I-Q-6).
  • Octokit: pulls.listRequestedReviewers answers { users, teams }; issues.listEventsForTimeline events are normalized by normalizeEvent (reviewed events carry submitted_at and commit_id, the others created_at; a review request has requested_reviewer or requested_team); the paginate iterator exposes the response headers, which is how a 10-page timeline cap is detected from rel="next".
  • github.webhook retention is 1 hour (the extra task). JobDefinition.options gained deleteAfterSeconds; the queue maps it through resolveJobOptions (default 7 days) and the webhook job sets 3600 (WEBHOOK_JOB_RETENTION_SECONDS). Because a job keeps the value it was inserted with, queue.start() also runs UPDATE <schema>.job SET deletion_seconds = 3600 WHERE name = 'github.webhook' AND deletion_seconds > 3600, so completed webhook jobs that already exist (7 days) are removed at the next maintenance run instead of lingering for a week (I-Q-6). Dedup does not depend on old webhook jobs (see the retention note in architecture.md). The onboarding doc states the same facts, including the two exceptions (a job that has not run yet, up to 14 days; button votes keep the voter login in intent.feedback.record data for 7 days). U-Q-6 pins the retention of every registered job.
  • Dates are strings. src/db/client.ts now parses the Postgres date type (OID 1082) to YYYY-MM-DD; the default would build a Date at local midnight. Only review_time_runs.from_date, to_date and metrics_daily.day are dates.
  • CardResult.costUsd is a top-level optional field and not part of usage: the eval harness copies usage into its report rows (the saved baseline would change). saveCard writes cost_usd from it; an absent value (a result cached before step 6) is stored as NULL. A call that spent no tokens costs 0 whatever its model is (a failed call has a model but no usage), so only a call that used tokens on an unknown model makes the run unpriced (null).
  • effectiveVotes reads the votes of the installations and reduces them in memory with the exported pure pickEffectiveVotes (the feedbackSummary rule), then applies the [since, until) window to the effective vote. This keeps U-GATE-3 a unit test; a DISTINCT ON query would be equivalent. feedback_recorded carries the card's head for a button vote and the change's current head for a reaction poll (the poll does not know which card each reaction belongs to).
  • Reviewer sync. Users of type Bot are not stored; the job throws a PermanentJobError on a 404 (the worker completes it), and syncReviewers is called as it is by pilot sync-reviewers, which counts such a PR as skipped. getChangeByNumber was added to modules/changes.
  • Cron wiring moved from bootstrap.ts into src/app/crons.ts (applyCronSchedules) so that I-ROLL-4 can test it with a real pg-boss.
  • Rollup (§8.4) choices where the spec is silent. Excluded authors are left out of the PR counters (prs_*, merged_*) only; cards, displays, spend, incidents and deliveries count everything. merged_trivial looks at the card of the merge head: an ok card is preferred, the newest first, and it counts when its final class is trivial. The verdict at merge is the one of the merge head with the greatest facts_read_at (ties: the latest created). cost_usd is the sum of the priced rows as a decimal string; rows with NULL are unpriced_runs.
  • Gate choices. "At least 2 installations" counts the installations asked for in the report (each needs 40 eligible votes); a coverage population of 0 PRs is a coverage failure (no data cannot satisfy 98%); the side metrics are summed from metrics_daily for the window, and rollup_incomplete is raised when fewer rollup days exist than window days times repositories. Drops are counted in the order author, bot or agent, not a reviewer, so a vote is dropped once. votes_without_reviewer_sync counts changes with a non-author vote and no pr_reviewers row.
  • Review-time choices. A review that shares the merge's second counts as before the merge (<= for merged_without_review; timeline timestamps have one-second resolution). paused_minutes is the paused time inside [S, merge or close or now]. Only excluded_author and timeline_truncated rows are produced; commits_truncated exists in the table's check constraint but is never written, because commit truncation (more than 250 commits) still classifies the author. A PR whose clock never starts because every request fell in a pause that never ends falls back to ready_for_review, then to creation.
  • Doctor. Without GitHub calls, so the budget check uses GRAFT_LLM_DAILY_TOKEN_BUDGET and intent_spend; the feedback check reports the first of its two warnings; crons warns only for a schedule that is configured but missing in pg-boss. A missing or deleted installation still runs every check (they come back empty).
  • Purge. --confirm is required and checked also for --dry-run, and an installation that was not uninstalled (deleted_at IS NULL) is refused (exit 3) unless --even-if-active is given; a --dry-run deletes nothing and is allowed on an active installation, which the spec's manual smoke test needs. Counts are taken inside the same transaction that deletes, and the pilot_purges row stores them (plus pgboss_jobs).
  • Globs. (1) ALLOWED now accepts combining marks (\p{M}) as the spec's café/** example with a combining accent requires; glob_non_ascii still flags them. (2) The mixed-script check (detail 9) runs right after the character check (detail 2), before the other structural checks; scripts beyond the 14 named are distinguished too (Bengali, Tamil, ..., Coptic: 32 in all) and any other letter shares one Other bucket. (3) The spec's sensitive_paths[0] in U-PY-12 is the 0-based index; locations are 1-based everywhere (sensitive_paths[1]). (4) warnings[].line/column point at the glob's own scalar.
  • Exact-text shortcut (picomatch 4.0.7). lib/picomatch.js test() sets match = input === glob before running the regular expression, where glob is the pattern as it was passed (here the normalized glob, normalizeGlob) and input the path unchanged: a case-sensitive comparison that ignores nocase, with no format (no windows option). src/core/glob.ts stores exact = normalizeGlob(glob) per compiled glob and answers true for an equal path, charging one unit per compared character when the lengths are equal and one unit otherwise (the engine checks lengths first). It matters for a glob that the compiled pattern reads differently from its text, for example ./a, whose leading ./ is dropped. U-PG-7 and U-PG-25 add text-equal paths.
  • Review 1 changes (step 6).
  • Invisible and compatibility lookalikes (major). validateGlob rejects (detail 2) any Default_Ignorable_Code_Point (the combining grapheme joiner U+034F, the variation selectors, zero-width characters, the byte order mark) and any combining mark that does not follow a letter, and rejects (detail 9) a glob whose NFC form changes under NFKC (fullwidth forms, mathematical alphanumerics). Visible accents, written precomposed or as two code points, CJK and Hangul stay valid (U-PG-21, U-CFG-31). This applies to graft.yaml, sensitive_paths and the env globs, which share validateGlob. Deliberately not done: telling two unlisted scripts apart (Ogham and Runic share the Other bucket and may mix); every segment that mixes Other with a listed script is rejected.
  • Paired comparison (major). The shadow-versus-baseline comparison pools only repositories that have both a baseline and a shadow run; the report states how many were left out (baseline only, shadow only) and I-GATE-4 covers both cases. It also shows the unfinished (right-censored) PRs next to each side.
  • Gate hardening (requested by the coordinator, changes spec §8.1.6). (Superseded by review 2: a leave-one-out check replaces the 30% block.) The early FAIL needs at least 6 voters and 2 installations (U-GATE-6 was rewritten for it: with fewer, the verdict is INSUFFICIENT DATA); the 14-day minimum is measured from the first to the last eligible vote (window.dataSpanDays), not from --since; a PASS carries a pass reason (accuracy, lower bound, n). The votes are clustered by PR and reviewer, so the Wilson interval is optimistic: this is stated in the report and not corrected (no bootstrap or design-effect adjustment).
  • Eligibility. A comment-only review no longer makes a reviewer: pr_reviewers.reason = 'reviewed' is written for APPROVED and CHANGES_REQUESTED only. Not configurable (the spec does not ask for it). Previously stored comment-only rows stay (the table is never pruned): clear them with delete from pr_reviewers where reason = 'reviewed' and run pilot sync-reviewers if that matters.
  • Allow-list renames. (Superseded, see the eligibility hardening below: the allow-list matches numeric user IDs, never logins.)
  • Vote-eligibility hardening (security check of the step 6 commit).
    • Reviews need standing. A review makes its author a reviewer only if its author_association is OWNER, MEMBER or COLLABORATOR, its state is APPROVED, CHANGES_REQUESTED or DISMISSED, and the author holds triage-or-higher permission, checked like a request's (security review 1, finding 2): any member of an organisation is a MEMBER of its public repositories and a COLLABORATOR may have read only, so the association alone is not enough (I-REV-6, I-REV-11). One permission call per distinct user per job, shared by requests and reviews.
    • Requested users need permission. A requested user is stored only with triage-or-higher permission (role_name is admin, maintain, write or triage, or the legacy permission is admin or write, which covers custom roles built on write; the legacy field maps triage to read, which is why the role name is read; a custom role built on triage is not eligible, fail closed). The answer must name the same user id as the request. 404 and 403 (forbidden) mean not eligible; rate limits and 5xx fail the job so it retries, storing nothing (I-REV-7, I-REV-8). The manifest is unchanged: Metadata: read covers the endpoint (see github-app.md). The fallback to "review association only" was therefore not needed and is not implemented.
    • Fail-closed is visible (finding 5). Every 403/404 on the permission check logs a warning with the status and the route template only (no login), the sync's info line carries permissionForbidden and permissionNotFound, and the last answer per (change, user) is kept in reviewer_check_denials (ids and status; migration 0007; cleared when a later check passes; purged with the installation). pilot doctor's feedback check WARNs on any 403 in 7 days ("does the App have Metadata: read?") and reports 404s in its OK line (I-REV-12, I-DOC-4).
    • Custom roles are judged by the legacy permission (write/admin pass; a role built on triage or read fails closed) and a role named Triage is not the built-in triage (the match is case-sensitive; I-REV-10).
    • Exclusions by id. changes.author_id (filled from pulls.get on every upsert; null for rows stored before) is compared with the voter's id, so a renamed author who is allow-listed is still dropped (I-GATE-11, U-GATE-16). Residual, not fixed: [bot] logins and GRAFT_AGENT_LOGINS are still matched by login, so a renamed agent account that holds write access and is requested would escape the agent exclusion. It needs an insider's deliberate rename; the fix is a GRAFT_AGENT_IDS setting (skipped: a new configuration surface for Phase 0). Agent accounts should be listed by their current login and re-checked after any rename.
    • Numeric logins. A line of digits is always an ID (GitHub allows all-digit logins, so 1234 alone means id 1234, not the login). A numeric login is written @1234 (login-only, like @alice) and resolve writes 1234:<id>; 1234:<id> is also accepted directly (U-GATE-15, I-ALLOW-1). resolve does not look up bare IDs to confirm their owner: check each ID with the person.
    • Atomic resolve write. src/pilot/atomic-write.ts: temp file .<name>.tmp-<pid>-<rand> in the same directory, fsync, rename, temp removed on failure; the original keeps its mode (0600 for a new file). An empty allow-list is valid, which is why a truncated write must not be possible (U-ATOMIC-1, U-ATOMIC-2, I-ALLOW-1).
    • Legacy rows (strict option). Migration 0007 adds pr_reviewers.verified boolean NOT NULL DEFAULT false: every row stored by the old rules becomes unverified, the gate counts only verified rows, and pilot sync-reviewers re-verifies (it upserts only users who pass the checks, setting verified = true; nothing is deleted). The alternative, trusting old rows until someone cleans them, leaves exactly the bypass this change closes for as long as nobody remembers; the cost of the strict option is a re-sync after deploy, and until then votes are dropped as not_reviewer and the report warns votes_without_reviewer_sync (I-GATE-10, I-REV-9, I-DB-12). The old rows are kept as an audit trail, not deleted. pilot doctor counts a PR as synced only if it has a verified row (I-DOC-4).
    • Allow-list by ID. The allow-list holds user IDs (<id> or <login>:<id>); the login is informational and never matched; a login-only line is an error (line number only) and pilot allow-list resolve rewrites it. The latestLogin rename lookup is gone (I-GATE-9, U-GATE-2, U-GATE-12 to U-GATE-15, I-ALLOW-1). resolve takes --installation <id> because an App JWT is meant for /app endpoints only, so it borrows an installation token (public data only). The report line reads "N user IDs (sha256 ...)".
  • Framed incidents. A culprit named in a fix PR's body is kept only when Graft knows it was merged into the same repository before the fix PR was opened (changes, or a baseline run's merged PRs). Residual risk: someone who can edit the body can still name any merged PR; the report shows incidents by source, incident list is in the weekly ritual and incident remove deletes one.
  • I-PRIV-1 now enqueues the pilot jobs through the handlers and the listener and asserts that jobs exist before searching them.
  • Onboarding mentions installations.account_login and qualifies the 14 days.
  • Skipped nits. votes_without_reviewer_sync only got a clearer wording (it counts PRs with votes and no reviewer row; telling "never synced" from "synced, nobody found" needs a marker).
  • Review 2 changes (step 6).
  • No wall-clock assertions in the default suite (major). Every millisecond bound (U-PY-3, U-PG-4/6/8/9/12/14, U-RISK-21, U-LLM-12, U-RED-12) now goes through expectDuration, which asserts the bound only with GRAFT_PERF=1 (pnpm test:perf) and a 30 s sanity ceiling otherwise. The same tests assert deterministic work: U-PG-4 (under 2,000 units), U-PG-6 (500,000 pairs, under 7 M units, budget not exhausted), U-PG-8 (under 20,000 units per call and no per-call limit hit; measured at most 8,860), U-PG-9 (the call stops once at its own 200,000-unit limit), U-PG-12/14 (budget_exhausted, and the shared budget exhausted); U-PE-30/32 and U-PG-13/15 already did. Removing the required-run, literal-tail or required-literal prefilters of the matcher is still killed (U-PG-8, U-PG-18, U-PE-32), now by units. Unit tests have a 120 s timeout (U-PE-32 no longer depends on the 5 s default).
  • Leave-one-out instead of the 30% block. A PASS (including the n >= 400 point-estimate PASS) must also hold on the votes without the top voter; otherwise INSUFFICIENT DATA with dominant_voter (share, accuracy with and without, lower bound without). The 40% warning stays. A FAIL is never turned into anything else.
  • Breadth counts installations that voted (at least one eligible vote) for the early FAIL.
  • Exact data span. dataSpanDays is the exact first-to-last-vote span (two decimals), and the 14-day rule is span + 1 >= 14: the first day counts as a full day, so 14 days of voting (Monday 10:00 to the second Sunday) are enough. U-GATE-5 changed accordingly (12.99 fails, 13 passes).
  • Compatibility characters, per code point (detail 10). Any code point whose NFKC form differs from itself is rejected with its own message ("contains a compatibility character ..."): fullwidth and mathematical letters, the Kelvin, Angstrom and Ohm signs, CJK compatibility ideographs, compatibility jamo, halfwidth katakana, superscripts and Roman numerals (fail-closed, an error and not a silent miss). Precomposed letters, lone combining accents and Hangul jamo are stable and stay valid.
  • Dismissed reviews count. DISMISSED joins APPROVED and CHANGES_REQUESTED in pr_reviewers (it was a real approval until a push dismissed it; I-REV-2).
  • Existing tests changed. U-CLI-3 (--json now also prints warnings), the registry test (two signal listeners), I-FB-3 (its cards now have intent_displays rows, because the sweep windows on the last display since T13), I-DB-½/3/⅞/9 and step 5's I-DB-10 (they roll back or re-apply 0006 too; I-DB-3 inserts one row into each new table), and U-PG-7 (text-equal paths). After review 1: U-GATE-6 (early FAIL needs 6 voters and 2 installations), the decideGate and I-GATE-1 PASS expectations (a pass reason), I-REV-2 (a comment-only review is not stored) and the incident tests (their culprits are seeded as merged PRs). Step 6's own I-DB-10 shares its ID with step 5's two tests (the spec reused it); its name starts with I-DB-10 0006.
  • Added beyond the spec. U-Q-6 and I-Q-6 (retention), I-PRIV-1 (a sentinel PR title, body, commit message and login never reach the new tables or the new jobs), a sentinel-voter test for the gate report, and the policy checks in .github/workflows/ci.yml. docs/graft-yaml.md documents detail 9, combining marks and the warning. .env.example lists the three new variables.
  • Not done / left open. Real GitHub behaviour is unverified: the shape of timeline events (requested_team, reviewed), issues.listEventsForTimeline on pull requests with the issues: read permission, and rate-limit headers of a long baseline run; check them on the first pilot baseline (HUMAN-TODO). Business-hours time, team expansion and automatic calibration are out of scope by the spec. The smoke test of the spec's DoD was run against a dead local GitHub port only.

E2E runner library facts

Library facts checked against node_modules (@octokit/plugin-rest-endpoint-methods 17): apps.getRepoInstallation (GET /repos/{owner}/{repo}/installation), apps.getInstallation, apps.listWebhookDeliveries, apps.getWebhookDelivery, apps.redeliverWebhookDelivery (POST /app/hook/deliveries/{delivery_id}/attempts), actions.setGithubActionsPermissionsRepository and actions.getGithubActionsPermissionsRepository, repos.createForAuthenticatedUser (POST /user/repos), repos.createFork, repos.mergeUpstream, repos.addCollaborator, git.createBlob|createTree|createCommit|createRef|updateRef|deleteRef|listMatchingRefs, pulls.requestReviewers, reactions.createForIssueComment, issues.addLabels|createLabel|getLabel|listEventsForTimeline all exist under those names. mediaType: { format: "full" } sends Accept: application/vnd.github.v3.full, not ...full+json; the fake world recognises both. octokit.paginate reads response.url, so the fakes now set it.

Live e2e runner deviations and additions

Spec: docs/e2e/live-scenarios-spec.md.

Choices made while implementing docs/e2e/live-scenarios-spec.md, each where the spec was silent or could not hold:

  • Gate window. gate report --since <run day> needs --until after it (the default is the start of today), so s08 passes --until <run day + 2>; b1 passes --to <run day + 1> as specified.
  • Product fixes found by the first review (both reproduced by the runner). (1) The card's task input. The intent job read changes.task_id, which the provenance job writes concurrently; for the same head the card could miss the Graft-Task issue (intent won the race) or use the previous head's (after a rewritten history), and the input hash, hence the cache, varied from run to run. Design choice: the intent job now derives the task from this head's own commits with the shared provenance parser (fetchPrCommits and computeProvenance, through modules/provenance/index.ts), before any lock, so the card has no dependency on provenance ordering and the input hash is a function of the head. Waiting for or scheduling after provenance would have added a retry path and a latency to every card; reading change_provenance only for a matching head would still need a fallback. The extra cost is one pulls.listCommits call per card. A 404 on that call leaves the card without a task (the provenance job reports the failure itself). Tests: I-INT-TASK-1 (intent before and after provenance give the same inputs), I-INT-TASK-2 (a trailer-less rewrite does not use the stale task; the original head hits its cache again). s01 asserts intent_cards.linked_issue_number, and s07 (d) carries Graft-Task again. (2) Reviewer requests. pull_request.review_requested arrives with opened; its sync job could run before the changes row existed and returned skipped, and once the reviewer reviewed GitHub no longer listed them as requested. Design choice: the job now creates the change from pulls.get (API data, not the payload) instead of skipping, reads the request from the API: the webhook only names a user to look at, and the job records requested only if the PR's issue timeline holds a review_requested event for that user id (the timeline keeps it after the reviewer has reviewed, the requested list does not) and the permission endpoint gives them triage or higher, so jobs write only API data and a forged or replayed claim records nothing, and it calls ensureRepository like provenance and intent (a removed repository is skipped; an unknown one gets its row), and the provenance_published signal also enqueues one sync per change (rev-sync-open:{repo}:{pr}). No retry loop was added: an upsert has no failure mode that a retry would fix. Tests: I-REV-REQ-1 (a request before the change row exists, then a COMMENTED-only review: the reviewer stays eligible, which is exactly what the gate counts via pr_reviewers.verified), I-REV-REQ-2 (no permission, nothing recorded), I-REV-REQ-3 (a claim the timeline does not show records nothing), I-REV-REQ-4 (removed and unknown repositories), I-REV-REQ-5 (provenance_published enqueues one sync per change; the listener is now onChangeSignal). s08 requests the reviewer at open again, as the spec orders.
  • s02 team check. Graft renders the team as a code span of its full slug (`@mmornati/platform`). The assertion is: a code span @<owner>/platform is in the policy section, and no @...platform mention remains outside code spans.
  • Token minting (POST /app/installations/{id}/access_tokens) is how an App client authenticates; the write hook lets it through for the app and probe clients only, and only for the run's installation. Every other non-GET of the probe client is refused.
  • Redaction pattern. (token|bearer)\s+\S+ would eat prose such as "token budget"; it is narrowed to a credential-looking word (12 or more characters of [A-Za-z0-9._~+/=-]). The registry and the gh[pousr]_, github_pat_, sk-ant-, JWT, PEM and smee patterns are as specified.
  • Installation scope (review 1, finding 1). The preflight of run, verify and setup refuses (exit 3, check installation_scope) unless the App's installation has repository_selection: "selected" and GET /installation/repositories (installation token) lists exactly the sandbox, by id and name; a protected repository or a source in the list is named as such. s10 selects its delivery by installation id, repository id (list and payload) and PR number, never the number alone.
  • Write guard narrowed. The actor may not write to /repos/{sandbox} itself or to /transfer. The outsider may only react, create pull requests, request reviewers, create blobs, trees and commits, create branches graft-e2e/<runId>/... and move or delete them (in public mode: the same on its verified fork, plus merge-upstream). Writes are sent with redirect: "manual" and any 3xx answer is a GuardRefusal; the preflight requires the repository to answer under the sandbox's own name (sandbox_renamed otherwise, also in setup) and pins its id, setup checks that the created repository is the sandbox before pushing and closes repository creation in a finally, and openPr checks base.repo.id against it.
  • HUMAN-TODO ticking (review 1, finding 4). --update-human-todo ticks only items that are a check (s2-performed-via, s3-model-access, s3-outputs, s5-check-github, s6-redelivery). Items that are a deployment or pilot action (s1-install, s5-events, s6-backfill, s6-retention, s6-baseline-github) keep their box and get "Observed in sandbox on (live e2e run ; assumptions ...); the action above is still to do." s3-outputs needs A04, hence a run with --wait-cron (about 16 more minutes).
  • git isolation. Every git child runs with GIT_CONFIG_GLOBAL=/dev/null, GIT_CONFIG_NOSYSTEM=1 and GIT_TERMINAL_PROMPT=0; clone and push reset credential.helper; the push authenticates through a GIT_ASKPASS script in the 0700 temp directory that prints the token from the child's environment (so no helper, URL, argv or file holds it) and goes to the full_name GitHub returned for the created repository. Children start from childEnv (src/e2e/child-env.ts): no GRAFT_E2E_* variable, and for git no inherited GIT_* variable at all (GIT_CONFIG_COUNT, GIT_ASKPASS, ... could inject configuration or credentials).
  • --only-offline runs the live variant only unless --llm none is given, redacts the child's output and passes it only the three offline variables. A plain pnpm test also runs the none variant, on a subset of scenarios (s01, s05, s06, s07, s08, s09, s10, b1) and asserts that no model was called.
  • s10 counts only pull_request.opened deliveries and github.webhook jobs created since the redelivery, and waits for a 15 s quiet window (scaled by --timeout-scale). b2 logs requests before the GET-only hook, so a refused write is counted. Assertions that could pass vacuously were fixed: s01 asserts a policy hash, s05 and s09 fail without H0 (s05 now needs s01), s07's delivery booleans come from the waiters, s02 compares the team name in the policy title, RUN-2 asserts zero model calls.
  • s10 leaves out the cron's children, not only the crons (CI flake after Phase 1 step 1). I-LIVE-RUN-1 failed once on CI with s10.stable: the window ran across 19:15:00, the */15 feedback sweep fired and sent one intent.feedback.poll for PR 1's change, and that job carries the installation id, so jobsSince moved. Reproduced locally with GRAFT_FEEDBACK_POLL_CRON=* * * * * (1 failure in 12 runs, jobsSince: [] -> ["intent.feedback.poll:1"]). Not timing and not a Graft bug: the sweep runs on the clock, not because of the redelivery. The fingerprint now also leaves out intent.feedback.poll, installations.refresh_permissions (the daily fan-out) and pilot.reviewers.sync sent under the vote key rev-sync: (a poll that records a vote sends it). The window and the rest of the fingerprint are unchanged; a policy.fanout from modes.apply still counts, as no mode changes during a run. jobsSince is now a list of queue:count, and the integration test prints a failed assertion's observed value, so a failure names the keys and values that changed. I-LIVE-S10-1 sends those jobs straight to pg-boss and checks what is counted; removing intent.feedback.poll from the list fails it.
  • I-E2E-1 no longer forbids every GitHub call (same PR). Since Phase 1 step 1, installation.created also queues installations.refresh_permissions, whose job calls asApp(); on CI the worker sometimes ran it before the test's calls: 0 assertion. forbiddenGitHub() now also counts installationCalls. I-E2E-1 asserts that none were made and that exactly one refresh job was queued.
  • Public mode now has an integration test (I-LIVE-PUBLIC-1: s08 from a fork, then cleanup in the fork). The worker takes an optional pollingIntervalSeconds (tests use 0.5 s).
  • E2eDeps additions: readDotEnv() (the raw .env, for the token check), rootDir, gitPusher, mutationSpacingMs (the 1,000 ms spacer; tests use 0), pid/isAlive (the run lock), random, target. ops(argv, { baselineToken, requestLog }) records the token client's requests for b2's GET-only assertion. GitPusher is one method, copyAndPush, which does the clone, the drop, the overlay, the commit and the push on disk (binary files never pass through a string map).
  • Preflight scope per command. run and verify need Graft running (installation rows, readyz, no stale queued job, graft.yaml equal to the starter); setup checks the database and migrations but not the App, the marker or the policy before it acts; cleanup needs GitHub only. A queued job counts as stale only when it is due (start_after <= now()) and older than 2 minutes, so a delayed retry is not "a stopped worker". A missing actor token (no variable, gh failing) is exit 2, as U-LIVE-SEC-3 asks; a token that exists but fails GET /user is exit 3.
  • Cleanup also lists git/matching-refs under heads/graft-e2e/<runId>/, so the branches of PRs that were closed by hand are deleted too, and it keeps a ref list for the outsider's fork in public mode.
  • Tests that need the database (U-LIVE-CLI-2, U-LIVE-CLI-3, U-LIVE-PLAN-2, U-LIVE-REP-3, U-LIVE-OPS-1, U-LIVE-BASE-1) are integration tests (test/integration/live-e2e-*.test.ts) because the preflight opens the database; their IDs are unchanged.
  • Fakes. createFakeGitHubApi gains owner, repo, per-issue comments, completed_at on check runs, paged comments and check runs, and response URLs. The world supports base_tree in git/trees (the spec said full trees only; the runner uses base_tree as the real API allows) and a minimal line diff (common prefix and suffix trimmed). Webhook review payloads spell state in lower case, as GitHub does; REST responses keep upper case. Public (fork) mode is covered by I-LIVE-PUBLIC-1.
  • One run directory per run. state.json also holds the evaluated assumptions so report re-renders without a network; verify appends a synthetic verify scenario with the re-run invariants.

LLM gateways and client-side refusal fallback

Step 1 of plan/llm-provider-expansion.md.

  • One wire format, any host. ANTHROPIC_BASE_URL points the existing Messages API client at a gateway or cloud that speaks the same API (OpenRouter, Vercel AI Gateway, Requesty, LiteLLM, Bedrock Mantle). ANTHROPIC_AUTH_TOKEN sends Authorization: Bearer instead of x-api-key; at most one of the two may be set. The client passes null for every credential and base URL it is not given, so the SDK never falls back to reading ANTHROPIC_* from the process environment: the validated config is the only source (U-LLM-13). The log line names the host only, because a URL can carry credentials (U-LLM-15).
  • Model IDs. Still Claude only, since this is the Anthropic wire format, but a gateway's vendor prefix and a version suffix are accepted (anthropic/claude-sonnet-5.5, us.anthropic.claude-sonnet-5-5-v1:0). The pattern (MODEL_ID in src/llm/types.ts) is shared by src/config and src/eval/env.ts. Such IDs have no entry in src/llm/pricing.ts: the service records the run as unpriced (costUsd null), and pnpm eval --live refuses until a price is added.
  • Server-side refusal fallback on the Claude API only. The server-side-fallback-2026-07-01 beta exists on the Claude API alone, so GRAFT_LLM_REFUSAL_FALLBACK is ignored when ANTHROPIC_BASE_URL is set to any host other than api.anthropic.com (isClaudeApi, U-LLM-14).
  • Client-side refusal fallback. GRAFT_LLM_REFUSAL_FALLBACK_MODEL (off by default, so nothing changes without it): on refusal, callValidated repeats the call once on that model, unless the client reports through the new optional LlmClient.serverRefusalFallback(model) that it already fell back server-side, or the fallback is the model that refused. The switch is not one of the two D6 attempts, so a call may run three times (refused, fallback, repaired output), still bounded by the deadline. Each call is priced by the model that answered, and the card names that model (U-GEN-32 to U-GEN-35).
  • Diff filtering: no change. The plan listed "drop lockfiles, generated and vendored files" as new work, but classifyFile already leaves lockfiles, binaries and GENERATED_GLOBS paths (dist/, vendor/, minified, snapshots, protobuf output) out of the model input. Filtering more would not save money: every file the model does not see except lockfiles and binaries raises the floor to logic (R13 partial_view, so that a pull request cannot hide code behind a "generated" path), which moves the PR off the cheap Haiku first pass.

Workload Identity Federation

Step 1, item 5 of plan/llm-provider-expansion.md.

  • A third credential, still explicit. ANTHROPIC_FEDERATION_RULE_ID, ANTHROPIC_ORGANIZATION_ID, ANTHROPIC_SERVICE_ACCOUNT_ID and ANTHROPIC_IDENTITY_TOKEN_FILE (plus the optional ANTHROPIC_WORKSPACE_ID) are validated by Graft (src/llm/federation.ts, shared by src/config and src/eval/env.ts) and passed to the SDK as credentials: oidcFederationProvider({ identityTokenProvider: identityTokenFromFile(path), ... }). The SDK's own environment resolution (federation variables, ANTHROPIC_PROFILE, ~/.config/anthropic) is never used: apiKey and authToken stay null, and credentials is always given when neither is, so the default chain is not consulted (U-LLM-16).
  • Exactly one way to authenticate. The SDK lets an API key shadow federation. Graft refuses the combination at startup instead, so a leftover ANTHROPIC_API_KEY cannot silently win (U-CFG-34). Federation is all-or-nothing; the service account ID is required although the SDK treats it as optional, because the reference lists it as required on the exchange. The identity token path must be absolute. Errors name variables only.
  • Same host for the exchange and the calls. The token is exchanged at ANTHROPIC_BASE_URL (default https://api.anthropic.com), which must be https or loopback with federation, since it receives the identity token. The server-side refusal fallback stays on when the host is the Claude API.
  • Token file re-read on every exchange. Assertions with a jti are single use, so the provider never caches the identity token: the SDK's token cache refreshes the minted token in the 2-minute window before expiry and once after a 401, and each refresh reads the file again (U-LLM-17).
  • Exchange failures are API outcomes. The SDK throws WorkloadIdentityError (an AnthropicError, not an APIError) from inside the request, before any HTTP call, and AnthropicError for an unreadable token file; classify would have rethrown both as programmer errors. A wrapper maps them to FederationError with a failure: 400, 401, 403, a missing access_token and an unreadable or empty file are auth; 429 is rate_limited; 5xx and a network failure (detected in the wrapped fetch, not from the message) are unavailable (U-LLM-18). The message carries the status only, never the token, path or body. The exchange is outside the request's deadline signal, so it has its own 30 s timeout.
  • Logging and redaction. The client log line carries auth: "federation", the rule ID and the host (U-LLM-19). The logger redacts anthropicFederation, organizationId, serviceAccountId, identityTokenFile, identityToken, assertion and access_token. The e2e runner registers the token file's current contents as a secret; later rotations are caught by the JWT pattern.

Phase 1 step 1: modes

Spec: phase-1/step-1-modes.md. Decisions D1 to D17 are in the spec; what follows is what the spec left open, what the library check (T1) found, and where the build differs from the spec.

T1: library verification (offline, against the fake GitHub API).

  • (a) octokit.request.endpoint.parse(options) in hook.before("request") returns the expanded method and url (full URL, base included) for octokit.rest.checks.create, for octokit.request("PATCH /repos/{owner}/{repo}/check-runs/{check_run_id}", …) and for octokit.paginate(octokit.rest.pulls.list, …). It does not return a baseUrl; the guard reads options.baseUrl and strips it (a GitHub Enterprise …/api/v3 prefix) before matching. options.url in the hook is the route template for rest.* calls, which is what the refusal message uses (after replacing any literal owner/repo and numbers). A {ref} parameter is percent-encoded by Octokit (heads/graft-revert/x becomes heads%2Fgraft-revert%2Fx), and the guard refuses every % in a write path (U-MG-2). Step 5 must therefore delete its revert branch with a literal path (octokit.request("DELETE /repos/{owner}/{repo}/git/refs/heads/graft-revert/" + name, …) with the owner and repo expanded by the caller), not with rest.git.deleteRef({ ref }).
  • (b) The installation-token request does pass through the installation client's hook.before: POST /app/installations/{id}/access_tokens is seen by the hook (once per client use, lazily, after the caller's own before-hooks), and asApp().request("POST /app/installations/…") passes it too. So the auth row is reachable and exercised by every write.
  • © A throw in hook.before rejects the call without a network request: the fake's request log stays empty, not even the token call (U-MG-6).

Choices where the spec is silent

  • Fan-out inside the claiming transaction. The pg-boss queue accepts a transaction (send(..., { tx })), so modes.apply sends its policy.fanout jobs in the transaction that claims the mode_changes rows and marks them applied. A rollback sends nothing; a repeated run cannot happen for the same rows.
  • mode set output. When nothing changes it prints no change and nothing else. After a change it prints the show block, then one note: line for each key given on the command line whose requested value is not effective (the note names the reason and the missing permission). A shell/worker ceiling warning is printed once, above the first repository. A removed or unknown repository is unknown or removed repository on stderr, exit 1, for show, set and history. --json prints permissions: {} when they were never read (permissionsReadAt is then null), and the text line says permissions not read.
  • pilot doctor is per installation, so the two new checks (appended after crons, always WARN, never FAIL) count for the installation being examined: permissions is a WARN when its permissions were not read in the last 48 hours; modes is a WARN when a requested mode is not effective (counted by reason). modes uses the worker's ceiling from service_state when there is one, else the shell's. The Phase 0 doctor tests now expect twelve checks, and their healthy installation has read its permissions.
  • Effective modes in the policy job are read after ensureRepository (a repository created after an all install has no row before it), still outside the lock and after the installation check.
  • Mode line when the details are null (no policy, invalid policy): the text is the mode line alone, so renderPolicyDetails returns a string and never null. Two Phase 0 render assertions changed accordingly (U-PR-1 gains the line, U-PR-2 expects the line where it expected null).
  • PolicyView.mode is required, not optional.

Deviations from the spec

  • Ceiling fan-out key. The spec's singleton key policy:mode:<repo>:<pr>:ceiling-<ceiling> would swallow a second change to the same value within the 7-day job retention (report, enforce, report, enforce: the last fan-out would be deduplicated and the check would keep a stale mode line). The repository fan-out therefore carries ceilingAt (epoch ms of the change, null for a mode_change) and the key is policy:mode:<repo>:<pr>:ceiling-<ceilingAt>. modes.ceiling_fanout takes { at } for the same reason.
  • The factory's gate is optional and defaults to a gate that allows no Phase 1 write. The spec says the factory "gains gate" and callers pass one. src/e2e may import only a short list of modules (U-LIVE-BOUND-1) and "no change to the runner" applies, so the runner's own factory cannot be made to pass one. Production wiring (bootstrap.ts) passes the real mutationGate(db, config) and a logger for refusals; graft-ops.ts and eval/export.ts pass the refuse-all gate explicitly.
  • One route is added to the table: POST /app/hook/deliveries/{n}/attempts, class auth. The live e2e runner's s10 scenario redelivers a webhook with the App-JWT client that it builds from the factory, so a table without it breaks I-LIVE-RUN-1. Graft's own code never calls it, and the class auth is not tied to an installation.
  • installations.refresh_permissions lives in src/modules/modes/permissions.ts, not jobs.ts: the installation handler enqueues it and the modes jobs import the policy job, which imports the installations module, so keeping it in jobs.ts would be an import cycle. The daily cron needs a fixed payload, so it runs a second job, installations.refresh_permissions_all, that enqueues one refresh per active installation, two seconds apart.
  • N-4 under the default profile. With a report ceiling the effective mode cannot change, so the mode line cannot change either; the suite asserts that the line stays report and that the extra modes.apply publishes nothing. Under the max profile the repository starts at enforce, so the sequence is report (a rollback, which is the case that matters) and then enforce again.
  • I-MODE-10 freezes the check details (a vi.mock of renderPolicyDetails) because in step 1 the mode line is part of the rendered details, which are already in the facts hash: without the freeze, dropping policyMode from the hash would change nothing visible and the mutation check could not catch it. In step 2 the hash term is what keeps the republication correct if the rendered text does not differ.

Other test changes: db.test.ts and pilot-ops.test.ts step down one more migration and count 22 tables (I-DB-1, I-DB-2, I-DB-3 inserts a row into the two new tables); I-PURGE-2 excludes service_state next to pilot_purges and I-PURGE-1 seeds and counts mode_changes; the two tests that call applyCronSchedules with a queue that registers two jobs switch the modes crons off; policy.test.ts fan-out data gains scope: "branch". The fake GitHub API gains GET /app/installations/{id} (state.installationPermissions), and fakeGitHubFactory(api, gate?, onRefused?).

Review 1 fixes

Finding → fix (review: docs/phase-1/reviews/step-1-review-1.md).

  1. Octokit outside the factory → buildExportClient --auth token now builds makeGetOnly(forToken(...)); the DoD grep is empty without an exemption.
  2. Ceiling fan-out lost on a failed enqueue → casServiceState takes an inTx callback that runs in the same transaction; publishModeCeiling enqueues modes.ceiling_fanout there (queue.send(..., { tx })). If the send throws, the stored ceiling rolls back and the next start fans out (I-MODE-7, new case).
  3. Unknown permission level failed open → effectiveModes treats a level that is not an own key of LEVEL as missing (permission_missing); U-MODE-8 covers unknown strings, toString, numbers, null and non-object permissions.
  4. Guard ignored the host → a write whose parsed URL does not start with ${baseUrl}/ is refused unknown_route; the fallback branch is gone (U-MG-9).
  5. Redelivery route passed for every client → new class app (route table kind and WriteClass): it passes only when installationId === null; installation clients get unknown_route (U-MG-1, U-MG-10). It stays in the production allow-list because the live e2e runner redelivers a webhook with the App JWT.
  6. N-4 cannot catch mutation 6 in step 1 → recorded here: only I-MODE-10 kills "policyMode removed from factsHash" until step 2 stops rendering the mode line into the details; the step 2 reviewer must re-check that N-4 catches it then.
  7. Phase 1 route on the App client → refused app_client (U-MG-7 now expects it) before the feature check.
  8. refuseAllGate reads repository_unknown → commented: the reason union is fixed by the spec; it means "no gate wired in".
  9. routeTemplate kept free names → every segment that is not a known route word or a number is templated ({owner}, {repo}, {x}); a branch name is never logged (U-MG-11).
  10. mode set --repo ambiguity → if more than one active row matches the name, exit 1, print the installation ids, change nothing (I-MODE-4b).

Review 2 fixes

Review: docs/phase-1/reviews/step-1-review-2.md (APPROVED, 2 minors, 2 nits).

  1. Per-request baseUrl bypassed the host check -> the guard takes the factory's configured base URL (baseUrl option, trailing slashes trimmed) instead of reading it from the request options. A write whose per-request baseUrl differs, or whose resolved URL is not under the configured one, is refused unknown_route (U-MG-9b).
  2. Trailing slash in GITHUB_API_URL refused every write -> loadConfig strips trailing slashes from githubApiUrl (U-CFG-1b).
  3. Follow-up (nit): the ceiling send without tx can survive a mutation. Harmless: it runs before the commit, so the fan-out is only enqueued early. Left as is.
  4. Follow-up (nit): modes are kept on transferred or re-added repositories. To decide in step 2.

Phase 1 step 2: approvals

Spec: phase-1/step-2-approvals.md. Decisions D1 to D18 are in the spec; what follows is the library check (T1), what the spec left open, and where the build differs from it.

T1: library and API verification (offline: Octokit against an injected fetch, GitHub's REST documentation from the docs as known at build time, @octokit/webhooks-examples 7.6.1).

  • (a) Check-run bodies in hook.before("request"). For octokit.rest.checks.create, octokit.rest.checks.update and octokit.request("PATCH /repos/{owner}/{repo}/check-runs/{check_run_id}", …) (template or literal URL), status, conclusion and name are top-level keys of the hook's options, next to owner, repo and the URL parameters; they are not nested. But a caller may pass data, and then Octokit sends data as the body and ignores the other parameters: request("POST …/check-runs", { data: { conclusion: "success" } }) has no top-level conclusion, and { conclusion: "success", data: { conclusion: "neutral" } } sends neutral. Reading options.* as the spec says would therefore both miss a non-neutral body and refuse a neutral one. Deviation: the guard reads octokit.request.endpoint.parse(options).body, which is exactly the body sent (a plain object for every JSON call, after data substitution and URL-parameter removal). A body that is not a plain object (a string, an array, a class instance) is refused unknown_route, never assumed neutral (U-MG-13, U-MG-17). A key whose value is undefined is absent (JSON drops it).
  • (b) Teams API. GET /orgs/{org}/teams/{team_slug} answers 200 with the team, 404 when the team does not exist or is not visible to the token, and 403 when the installation token lacks the organization members permission ("Resource not accessible by integration"). GET /orgs/{org}/teams/{team_slug}/memberships/{username} answers 200 with { url, role: "member" | "maintainer", state: "active" | "pending" } (organization owners show as maintainer), 404 when the user is not a member, and it includes members of child teams (GitHub documents that a child team's members count as members of the parent). Graft counts only state: "active". The fake (test/helpers/fake-github-api.ts, state.teams) implements exactly that: 404 for an unknown team or a non-member, 403 for a team marked unreadable, 200 with state otherwise. These shapes come from the documentation and could not be exercised against real GitHub offline (HUMAN-TODO step 2 checks them on a sandbox).
  • © Event payloads. membership (added, removed) carries action, scope: "team", member, team, organization, sender and, for an App, installation: { id, node_id }; team (created, deleted, edited, added_to_repository, removed_from_repository) carries action, team, organization, sender, sometimes repository, and installation. The handlers' zod schema reads installation.id only (test/fixtures/webhooks/membership.added.json and team.deleted.json are built from the package's examples and validate against @octokit/webhooks-schemas, U-FIX-1).

Choices where the spec is silent

  • ApproverFacts and Unverified live in src/policy/enforce.ts (re-exported by src/modules/policy/approvals.ts): the spec puts them in approvals.ts, but the pure enforce.ts needs them and may not import modules.
  • ConstraintStatus.approvedCount is added: approvedBy is cut to 10 for display (§6) while the stored approved: n and met need the full count.
  • Change requesters and the bounds. D17 bounds approver role checks at 20. Change requesters get their own bound of 20 role checks (the user cache is shared, so nobody is checked twice). A requester past the bound counts as blocking, and so does one whose role check answered 403 (Graft cannot tell); a 404 (not a collaborator) does not block, as D2 says "does not count". Both choices fail toward failure.
  • A membership answer of 403 marks the team team_unreadable (fail closed); a 404 is "not a member" (§5).
  • Teams cut by the 100-membership bound become check_limit as a whole: their partial member list is not trusted.
  • A team named in a constraint but absent from ApproverFacts.teams (never looked up) is treated as check_limit; resolveApprovers always fills every named team, so this only matters for hand-built facts.
  • enforcedConclusion with approvers: null on a valid policy concludes approvals_missing (nothing could be verified); the job never passes null there.
  • The card wait is computed with the job's clock. headFirstEvaluatedAt is MIN(policy_verdicts.created_at) for (change, head), and upsertVerdict now sets created_at from the job's clock on insert (the database default was now()), so the window is measured on one clock (I-ENF-8 uses an injected clock). The card_wait job is sent after the lock, in every mode, with startAfterSeconds = seconds left (at least 1) and singleton policy:cardwait:<changeId>:<headSha>, so it is scheduled once per head even though every evaluation in the window asks.
  • Rendering details. The would-be line is its own paragraph right after the headline in all three section variants (valid, missing, invalid policy). Enforce mode replaces the headline with the enforce title (no · report only) and drops the · risk provisional suffix. Several unmet constraints read Needs approvals: 1 from @acme/security, 1 more from anyone ("more" when some approvals already count toward that constraint). The approvals line keeps the Phase 0 list form (`alice` and `bob`) and appends ; N count(s) (write access).; at most three change requesters are named. The "Approvals counted" block appears only when there is a constraint or a not-counted approver; logins and team names are code spans.
  • mode show note is printed indented inside the repository block. pilot doctor gains a 13th check, teams (OK or WARN), after modes; the Phase 0 and step 1 doctor tests now expect thirteen checks.
  • Team fan-out. policy.team_fanout lives in the policy module (team-fanout.ts) and is registered through modules/policy/index.ts, so src/app/registry.ts needs no new line (the registry lists modules, not jobs). Each re-evaluation it sends is keyed policy:team:<repo>:<pr>:<window>, where window is the fan-out's own 5-minute window from its payload (review 1, finding 1).
  • hasMembersRead (the members level is read or above, never-read permissions count as missing) is in src/modes/index.ts, shared by the approvals, mode show and the doctor.
  • The neutral suite's drain ignores jobs deferred into the future (start_after > now()): the card wait and the team fan-out's debounce would otherwise never let it settle. The suite runs the team fan-out job directly after posting membership.added, and transfers the repository away and back at the end, followed by one modes.apply.

Deviations from the spec

  • D4 (from the Phase 1 plan): team membership is checked per approver through the memberships API, with no cache across jobs and nothing stored, instead of listing team members with a TTL cache (as the spec itself records).
  • §8, the body rule reads the parsed body, not options.status/options.conclusion/options.name (T1 (a) above).
  • I-ENF-9 and the published hash term. With the rendering frozen, a mode flip changes both policyMode (step 1 D8) and published in the facts hash, so removing only one of them is not observable through the job: each is sufficient. I-ENF-9 therefore also checks the hash function directly (policyFactsHash, exported from job.ts): two inputs that differ only in published must hash differently. The same redundancy means I-MODE-10 alone no longer catches "policyMode removed from the hash" (the enforced/published terms change too); I-MODE-10 still passes and still asserts the republication.
  • Step 1 tests that pinned "enforce changes nothing" were updated, since step 2 changes exactly that: I-MODE-10 (the enforce publication is in_progress, the rollback completed and neutral), I-MODE-11 (enforce title and footer), N-4 (the enforce mode line), I-MODE-1, I-DB and the pilot-ops rollback tests (one more migration), U-PA-4 (countApprovals has two more fields), the U-PR render fixtures and I-POL-9 (the new footer and approvals wording), U-MAN-1 (members: read, two events).
  • The website and video snapshots (website/) still show the Phase 0 wording; they are captured marketing material, not generated from the code.

Known limits (spec §2)

  • Approvals are counted like GitHub counts them: the PR author is excluded, the last pusher and commit co-authors are not.
  • A collaborator permission change (member event) does not re-evaluate anything; it is picked up at the next trigger.
  • Changing the footer and the approvals line changes the rendered text, and so the facts hash, of every open PR: each is republished once, at its next evaluation, not proactively.
  • Merge queues (merge_group) are not handled; a repository that uses one must stay in report mode.

Mutation checks (§15), run by the developer. Each mutation was applied alone, the named tests run, then the file restored from git. All thirteen were caught:

Mutation (as applied) Failing tests
Stale approvals counted (commit_id === headSha \|\| true in countApprovals) U-ENF-1, I-ENF-3
Triage counts as write (atLeast("triage", "write") true) U-COL-4, I-ENF-4
Unverified team treated as satisfied (every counted approver added as a member) U-ENF-8, I-ENF-5, I-ENF-6
Change requests ignored U-ENF-6, I-ENF-7
no_policy concludes success U-ENF-2, I-ENF-13
Truncated reviews ignored U-ENF-5, I-ENF-14
Guard ignores the body (check-run bodies never read) U-MG-13, N-7 (both profiles)
Guard lets a non-graft/policy check be non-neutral (name check removed) U-MG-15, N-7 [max]
Conclusion published from enforced in report mode (publishedCheck ignores the mode) N-2 [default], N-6 [default], I-ENF-2
published removed from factsHash I-ENF-9 (the direct hash check; see the deviation above)
MutationRefusedError rethrown on mode_report I-ENF-10
Modes kept on transfer (resetModesOnTransfer not called) I-MODE-14
Team fan-out ignores teamCount (>= 0) I-ENF-11

N-4 note (step 1 review finding 6): the mode line is still part of the rendered details, and a mode flip now also changes the enforced/published hash terms, so removing policyMode alone from the hash is still not observable through N-4 or I-MODE-10 (each remaining term is sufficient to republish).

Not run: the manual smoke test of §15 (it needs a running server, worker and a real or tunnelled GitHub App); it is listed in HUMAN-TODO. pnpm db:up could not start a compose project from this worktree because port 55432 is already bound by the shared scionhub-postgres-1 container, which every command reused; the migrate, rollback and migrate sequence ran against a separate database (graft_s2_dod) in that container, and the tests against TEST_DATABASE_URL=…/graft_test_s2, so other checkouts were not disturbed.

Review 1 fixes

Finding → fix (review: docs/phase-1/reviews/step-2-review-1.md, CHANGES REQUESTED, 1 major, 6 minors, 2 nits).

  1. (major) The team fan-out's debounce dropped events after it ran → spec D14 defect. D14's key policy:team:<inst>:<floor(now/300 s)> with startAfterSeconds: 60 is a leading-edge debounce, and our singleton is a deterministic job id that also deduplicates completed jobs (7 days): a membership.removed after the window's fan-out had run was lost, and a PR could keep success in enforce mode. Fixed as a trailing-edge debounce: the key is unchanged, but the fan-out starts after its window closes plus 60 seconds (ceil((window + 1) · 300 − now) + 60), so it runs after every event of its window, and an event after it ran falls into a later window with its own fan-out. The payload is now { installationId, window }, and each per-PR re-evaluation is keyed policy:team:<repo>:<pr>:<window> from the payload, not the run time, so fan-outs of different windows never collide. Cost is unchanged: at most one fan-out per installation and one re-evaluation per PR per 5-minute window. The price is latency: a team change is picked up 1 to 6 minutes later instead of about 1. fanoutTeamChange now counts only the jobs actually enqueued. I-ENF-11 checks the payload, the start time and the per-PR key; I-ENF-11b runs a fan-out, removes the approver from the team one second later, and checks that a second fan-out starts after the removal, sends its own re-evaluation and the check fails. The neutral suite runs the queued fan-out's data. The spec file is not edited; D14 should read as above.
  2. A status-less check-run create passed the guard as neutral → checkRunBodyKind(body, method): a POST …/check-runs is a Phase 0 write only with status: "completed" and conclusion: "neutral" (GitHub creates a run without a status as queued); anything else needs the policy client and the gate. A PATCH keeps the rule that an absent key is unchanged. U-MG-13 refuses {}, { status: "completed" }, { conclusion: "neutral" } and an output-only body on POST, in every call form and through data; U-MG-12 lets the same bodies through as a PATCH. Two older tests (U-MG-5, "phase 0 writes never ask the gate") now create completed + neutral runs. This completes deviation 1 above.
  3. Team slugs and logins in error routes → sanitizeError's route template replaces the segment after teams, memberships, members, collaborators and users with :name, so a retryable team, membership or permission error logs /orgs/acme/teams/:name/memberships/:name (U-GHE-5, also through toJobError).
  4. Outsiders could use up the D17 bound on a public repository → role checks for approvers and change requesters are ordered by the review's author_association (OWNER, MEMBER, COLLABORATOR, then the rest), then by login (listReviews keeps the association; the job passes a user id → association map). The association only orders the checks: everyone counted still passes a role check, and anyone past the bound keeps the fail-closed rules (I-ENF-12b: 20 outsiders whose logins sort first, one MEMBER approver, success). Residual, accepted: 21 or more outsider change requests still block (a requester past the bound blocks, deviation 3), so a cheap denial of service remains on an enforcing public repository. Recorded in HUMAN-TODO; to revisit at step 7's rollout runbook.
  5. Two fail-closed rules had no test → I-ENF-6b: a pending membership does not satisfy a team constraint (kills X5). I-ENF-7b: a change requester whose role check answers 403 blocks, and so does the 21st requester past the bound while 20 readers do not (kills X3 in both forms).
  6. Transfer race read the previous owner's modes → ensureRepository returns other_installation for an active row that belongs to another installation (it neither moves nor resets it). The policy job then reads the modes under a report ceiling, which is what the D13 reset gives the new owner, so it never acts on the old owner's enforce: it publishes neutral and nothing is refused (I-ENF-15). This differs from the reviewer's suggestion (skip with repository moved): a skip would leave the PR with no check for this event when the old modes were already report, because the D13 reset then writes no mode_changes row and nothing republishes. The other callers of ensureRepository compare with "removed" only and keep their behaviour.
  7. The gate trusts the process's own ceiling (rolling restart) → deferred to step 7 (security review and rollout runbook). Making the gate read the lower of the environment ceiling and the one stored in service_state changes step 1's ceiling model (publishModeCeiling, service_state), which is beyond step 2. Documented instead: docs/features/modes.md and HUMAN-TODO say that lowering GRAFT_MODE_CEILING requires stopping every worker before the new one starts (no rolling restart).
  8. (nit) A non-neutral PATCH could rename another run → accepted, commented in the guard: only the policy job holds a policy client, and it PATCHes only a run id it found as graft/policy (its stored id, or listForRef with check_name).
  9. (nit) A role answer with no user passed → collaboratorRole returns none when the response has no user (U-COL-3).

Phase 1 step 3: break-glass

Spec: phase-1/step-3-break-glass.md. Decisions D1 to D12 are in the spec; what follows is the API check (T1), what the spec left open, and where the build differs from it.

Migration number. This step uses 0010_audit_log. Step 4 (guard detection) is built at the same time and takes 0011. Whichever of the two merges second must check the order (the migrator refuses migrations out of order) and renumber, together with the migration step-down tests (db.test.ts, I-MODE-1, I-ENF-1, the pilot-ops "one migration behind" test, I-BG-1).

T1: API verification (offline: GitHub's REST documentation as known at build time and Octokit's issues.listEvents types; nothing could be exercised against real GitHub, see HUMAN-TODO).

  • Endpoint and shape. GET /repos/{owner}/{repo}/issues/{issue_number}/events (octokit.rest.issues.listEvents) works for pull request numbers, because every pull request is an issue. Each item has id, node_id, url, actor (a simple user: login, id, type User or Bot; null for a deleted account), event (labeled, unlabeled, …), commit_id, commit_url, created_at, performed_via_github_app and, for label events, label: { name, color }. The actor of a labeled event is the account that added the label; a label added by an App appears as its <slug>[bot] user with type: "Bot".
  • Ordering. Events are listed oldest first. The endpoint takes only per_page (at most 100) and page: there is no sort, direction or since. So newest-first is not available as a parameter, and Graft reads every page up to the D2 cap (10 pages of 100) and takes the newest matching event. Jumping to the Link: rel="last" page and reading backwards was considered and not used (the simplest option). When the tenth page is full, a later event may sit on an unread page, so the result is "not found" (actor_unknown, fail closed).
  • Permissions. The endpoint is readable with issues: read, or with pull_requests: read for a pull request number. Both manifests already grant issues: read and pull_requests: write, so no manifest change. The role is read with collaboratorRole (step 2 D16; 404 for a non-collaborator).
  • Fakes. test/helpers/fake-github-api.ts serves state.issueEvents (oldest first, paginated like the other lists, 404 for an unknown issue or PR), and the fake world records a labeled event with the acting user whenever it labels a PR.

Choices where the spec is silent

  • Label setting. GRAFT_BREAK_GLASS_LABEL accepts 1 to 50 characters with no control characters and no leading or trailing space; any other character is allowed, because GitHub label names may contain spaces, colons and emoji. off is matched case-insensitively (OFF disables too), so a typo in case never turns the feature on under a strange name. Empty means the default.
  • Only labeled carries the head. The handler handles both labeled and unlabeled, but sets breakGlassHeadSha only for labeled: an unlabel delivery's head is not a labelling-time snapshot, and D9 needs no filter. A late unlabel delivery can therefore never bind a break-glass.
  • Between label events. When the label is on the PR, no applied row matches the head and the run is not the label's own trigger, Graft verifies nothing (§6.2) and shows what the log says for that head: the newest row, if it is ignored or stale, is shown again (no API call); otherwise nothing.
  • Removal on any trigger. A removed row is written by any evaluation that finds the label gone while an applied row matches the head, not only by the unlabeled trigger, so a lost webhook is still caught. Its actor is whoever the newest unlabeled event names, bots included; the role is not checked (actor_role NULL).
  • Stale needs no read. A D4 mismatch is refused before any issue-events or role request; the stale row has no actor.
  • Ties. "Later" between two rows of the same (change, head) compares created_at; a removed row with the same time as an applied one counts as later, so an ambiguous order never keeps a bypass alive.
  • Dedup in the store, under the lock. insertAuditRow checks before inserting: no second applied while one is active, removed only while one is active, one ignored per (change, head, actor) and one stale per (change, head). The partial unique indexes back it (ON CONFLICT DO NOTHING), but audit_log_ignored_once treats a NULL actor_id as distinct, so the store also deduplicates actor_unknown rows itself.
  • A verification that lost the race. If the run that verified a break-glass finds that a later evaluation already published (the step 2 ordering check), it still writes its audit row in the same locked transaction and enqueues one policy.evaluate (trigger pr, singleton policy:breakglass:<change>:<head>:<factsReadAt>). Without this, the later run (not the label's own trigger) would not verify, and the label would silently not apply.
  • EnforceInput.breakGlass is optional (absent means none), so every U-ENF call is unchanged. Under break-glass the constraints are still computed, so the details show what was bypassed.
  • Rendering. The break-glass line is its own paragraph right after the headline, before the would-be line, in all three section variants (a missing or invalid policy is bypassed too). Self-use reads on `abc1234` (on their own pull request):. In report mode the effect clause becomes "Graft would bypass the policy for this commit (report mode)" and the rest of the line is kept. An unknown actor reads "applied by someone (who applied it could not be determined)". role_too_low shows the role GitHub reported (none for a recycled login). The details block comes right after the mode line, before the matched rules, for applied, ignored and stale.
  • graft audit list. --since takes a date (midnight UTC) or an ISO timestamp with a zone. --repo is matched case-insensitively and includes removed repositories (the trail outlives a removal until pilot purge); rows of several matching repository ids are merged. An unknown name is unknown repository, exit 1. [self] prints as self, a null reason is left out, an unknown actor prints unknown. The argument parsing lives in graft-ops.ts like the mode group; src/modules/audit/cli.ts has the query and formatting helpers.
  • Doctor. A fourteenth check, break_glass (OK or WARN), counts applied rows of the last 7 days per active repository of the installation, whether or not they were removed later. The doctor tests now expect fourteen checks.
  • Feature off. With GRAFT_BREAK_GLASS_LABEL=off the job does not resolve anything, so an applied row written before the switch no longer applies.
  • The audit module is not in the registry: it has no handler and no job (its index.ts exports empty lists, like changes).
  • Fixture. pull_request.labeled.break-glass.json is a variant of pull_request.labeled; the fixture test maps a third dotted part of the name to the same schema definition.

Deviations from the spec

  • D12 and D9. Evaluations of PRs without the label make no new API call, except one: when the label was removed while a break-glass was applied, the job reads the issue events once to record who removed it (D9 requires the actor).
  • Mutation "breakGlass removed from factsHash". For an applied break-glass the term is redundant: the enforced reason and the rendered text change too, so a label trigger republishes without it. As for I-ENF-9 in step 2, I-BG-2 also checks the hash function directly (two inputs that differ only in the break-glass term hash differently), and U-BG-4b does the same for every state.
  • I-BG-3 also labels as a write user. A triage user alone cannot catch the mutation "write accepted as enough".
  • N-11. Under the max profile the normal conclusion of the scenario's PR is itself non-neutral (failure), so "the only non-neutral conclusion is success on the labelled head" is checked as: every success written during the scenario is on the labelled head, every non-neutral write went through the policy client with an allowed gate answer, and the next head's conclusion is the normal one (not success, not break_glass).
  • I-BG-14's doctor case is in pilot-ops.test.ts (it needs that file's healthy-installation helper), under the same ID.
  • Earlier tests changed: the migration step-down tests (one more migration), I-DB-1 (twenty-three tables) and I-DB-3 (an audit row), the fixture list, I-DOC-1 and I-DOC-3 (fourteen checks), I-PURGE-1 (seeds and counts an audit row), and I-ENF-9 (its hash input gains the term).

Known limits

  • A PR with more than 1,000 issue events cannot be break-glassed (fail closed, T1).
  • The label stays on the PR after a push; it only counts for the commit it was verified on (D6).
  • The issue-events shape and ordering are from the documentation, not from real GitHub (HUMAN-TODO).

Mutation checks (§12), run by the developer.

Each mutation was applied alone, the named tests run, then every touched file restored byte for byte from a saved copy (git status clean afterwards). All ten were caught:

Mutation (as applied) Failing tests
Actor taken from the payload sender (the handler copies sender into the job, the job's schema keeps it, and resolveBreakGlass uses it instead of the issue event) I-BG-4
write accepted as enough (atLeast(role, "write")) I-BG-3
Bots accepted (the type: Bot check removed) I-BG-9
D4 equality check removed I-BG-5
Break-glass kept after a push (activeBreakGlass ignores the head SHA) I-BG-6, N-11
Break-glass evaluated after blocked instead of before U-BG-1, I-BG-2 (and I-BG-8, whose name matched the filter)
Conclusion published in report mode (publishedCheck lets break_glass through) I-BG-8, N-10
ignored dedup removed (the store's check and its ON CONFLICT DO NOTHING) I-BG-3 (the insert hits audit_log_ignored_once and the job fails)
breakGlass removed from factsHash I-BG-2 (the direct hash check; see the deviation above)
removed row not written on unlabel I-BG-7, I-BG-13

Removing only the store's ignored check, and keeping ON CONFLICT DO NOTHING, is not caught, by design: the unique index audit_log_ignored_once still keeps one row per (change, head, actor), so I-BG-3 passes. The store's own check matters only for the unknown actor (NULL actor_id), which the index does not deduplicate.

Not run: the manual smoke test (it needs a real or tunnelled App; HUMAN-TODO). pnpm db:up was not run: the shared scionhub Postgres container on port 55432 was reused, the tests ran against graft_test_s3 and the migrate, rollback and migrate sequence against graft_s3_dod, both created for this step and dropped afterwards.

Review 1 fixes

Finding → fix (review: docs/phase-1/reviews/step-3-review-1.md, CHANGES REQUESTED, 2 majors, 3 minors, 3 nits). Findings 1 and 2 are defects in the spec (D2, D6, D8, D9), not coding slips; the spec file is not edited, and the decisions below should be read as amended.

Migration number. The schema change is a new migration, 0012_audit_label_event (0010_audit_log is released and unchanged). Merged after step 4 (#26): 0012 sits on 0011_guard, and the step-down tests (I-BG-1, I-BG-24, I-GRD-1, I-DB-*, I-MODE-1, I-ENF-1, pilot-ops "one migration behind") step through both. The top migration is 0012.

  1. (major) The actor was not bound to the label action that queued the run → D2 amended. The labeled handler adds the delivery's sender.id to the job (breakGlassActorId, a positive integer; the handler's schema reads sender.id only, and no login enters the job). readLabelEvents returns the newest event of either kind for the label, by list position. A verification needs the newest listed event to be a labeled event whose actor id equals breakGlassActorId. An unlabeled newest event, another user's event, no event, or a missing id means the API does not show that action (yet): while the job's retry policy allows (ctx.attempt, now passed by the worker: retryCount < retryLimit, 5 retries with backoff from 30 s), the job throws a retryable LabelEventsBehind before anything is published; on the last attempt it records ignored actor_unknown and ends any active bypass (fail closed). The id is a refuse-only filter: the actor, login and role still come from the API, and a matching id never skips the bot or role checks. The cap (1,000 events) is not retried. A delivery without a sender id never applies. Tests: I-BG-16 (R3-A1; and the same user's older labeled event is not used when an unlabel is newest), I-BG-17 (R3-A2, no role read), I-BG-21 (retries while allowed, then fails closed and ends maya's bypass), I-BG-4 (the delivery names maya, the events tom → actor_unknown with no role read; both say tom → role_too_low, read for tom), I-Q-4 (the handler sees its attempt). I-BG-2 and the other label tests now pass the labeller's id.
  2. (major) Revocation drifted → D6, D8 and D9 amended.
  3. audit_log.label_event_id (0012, bigint, > 0) holds the issue event id an applied row was verified from.
  4. Every label trigger reads the events once (D12), even with an active row. The bypass stays only when its event is still the newest labeled one and no unlabeled event is newer, and the newest event is the delivery's user's labeled action (finding 1). Otherwise the job writes removed (actor: the newest unlabeled event after the bound one, else none), then judges the current labeller from scratch in the same run. The new applied row is stamped 1 ms after that removed row, so the tie rule does not end it. A row written before 0012 has no event id and counts as unbound: its next label trigger re-verifies it.
  5. An unlabeled delivery of the label sets breakGlassUnlabeled (a refuse-only flag): the job ends an active bypass whatever pulls.get shows now, with one events read for the remover. A late unlabel delivery can therefore end a newer bypass; that fails closed, and the maintainer re-labels.
  6. A removed row ends every applied row of the change at or before it, whatever head (activeBreakGlass, activeBreakGlassForChange, mergedUnderBreakGlass). insertAuditRow refuses an applied row while any row of the change is active, and a removed row unless one is active for its head (the head of the bypass it ends).
  7. Other triggers still make no read (I-BG-11 unchanged for them; the label trigger again costs one events read and no role read).
  8. Tests: I-BG-18 (R3-B1: failure, removed for maya, ignored for tom, mergedUnderBreakGlass false), I-BG-18b (the unlabel job runs after the re-label: removed from the flag; the handler sets the flag), I-BG-19 (R3-B2: failure on A after the force push, mergedUnderBreakGlass(A) false), I-BG-13 (a removed row at another head ends the bypass), I-BG-25 (another maintainer re-labels while a bypass is active: removed, then applied 1 ms later, which holds on later triggers), I-BG-11 (a redelivery keeps the bypass with one events read).
  9. (minor) A push did not end the bypass for good → fixed by the change-scoped rule, not by changing the wording: when an evaluation finds an active row for another head than the current one, it writes removed for that head with no actor, no read and no role check, inside the lock. A force push back to the labelled commit then gets the normal conclusion. I-BG-20 (R3-B3), I-BG-6 (now expects the removed row), I-BG-14 (the CLI shows it), N-10 and N-11 (one more row, for the labelled head). Residual: if the PR moves and moves back before any evaluation reads the new head, Graft never sees the push and the bypass of the first commit stays (documented in docs/features/policy.md).
  10. (minor) A label-triggered verification could be dropped silently → a run that carries breakGlassHeadSha and ends stale before its audit rows are committed (the early "newer snapshot stored" exit, a lock-time staleness on the same head, or a mode rollback) is sent again with its data unchanged (filters kept), singleton policy:breakglass:<change>:<head>:<deliveryId>, when the stored head is still its head. The filters only refuse, so the re-run grants nothing the first run could not; the singleton deduplicates for 7 days, so a re-run that is dropped again is not re-sent a second time (bounded). I-BG-23 (a hook adds another label and publishes right after the run's first pulls.get; the run ends stale, the re-run is queued with its filters and applies).
  11. (minor) The lost-race path had no test → I-BG-22: a review run with a later clock publishes first; the label's run ends stale, keeps its applied row and queues one policy:breakglass:… job, which publishes success. Mutation X5 (no row in that branch) fails it.
  12. (nit) The fakes could not express findings 1 and 2 → the fake world has DELETE /issues/{n}/labels/{name} (an unlabeled event and the webhook), label events carry the actor's real type (the App's bot for an installation token), and the fake API has issueEventsLag (the newest N events are not listed) and afterNext (a one-shot hook after a response). U-LIVE-WORLD-2; I-BG-16, 17 and 21 use the lag switch, I-BG-23 the hook. N-10 and N-11 still write events by hand: the neutral suite drives the plain fake API, not the world.
  13. (nit) The unknown-actor dedup and the tie rule → 0012 recreates audit_log_ignored_once with NULLS NOT DISTINCT (Postgres 15+), so ON CONFLICT DO NOTHING covers actor_unknown too; its up fails if duplicates exist, which the store has always prevented. down restores the 0010 index and drops the column. I-BG-24 (0012 down and up, the index definition, a second unknown-actor row refused, the stored event id, and a removed row at the same instant ends a bypass: kills X4). I-BG-1 now steps down through 0012.
  14. (nit) The 1,000-event cap is a cost and a lever → deferred to step 7 (security review and rollout runbook), documented in docs/features/policy.md "Known limits". Reading the Link: rel="last" page first and walking backwards depends on how the events endpoint paginates on real GitHub, which T1 could not check offline (HUMAN-TODO now asks for it, with the lag of finding 1). Meanwhile the cap still fails closed.

Also noted: a custom role based on maintain reports permission: write and does not count (fail closed); documented in docs/features/policy.md.

Mutation checks for the fixes, run by the developer: each applied alone with a script, the named tests run, the file restored byte for byte (git status clean after each).

Mutation Failing tests
The newest-kind check removed (the newest labeled event is used even when an unlabel is newer) I-BG-16
The delivery's actor filter removed I-BG-17
The handler drops the sender id I-BG-4
No retry while the events lag I-BG-21
The binding check disabled (an active row is kept on a label trigger) I-BG-18
The unlabel delivery flag ignored I-BG-18b
removed scoped to its own head again I-BG-13
A push does not end the bypass I-BG-20
The new applied row not stamped after the removed one I-BG-25
X5: the lost-race branch writes no row I-BG-22
No resend of a dropped label run I-BG-23
X4: the tie rule >= becomes > I-BG-24
The index without NULLS NOT DISTINCT I-BG-24
label_event_id not stored I-BG-11, I-BG-24
The worker passes no attempt I-Q-4
The world's unlabel records no event U-LIVE-WORLD-2

The review's spec mutations M1 to M10 keep their tests; M1 (the actor from the payload sender) is now also refused by the actor filter, and I-BG-4's first case expects actor_unknown with no role read for the payload's user.

Verification. pnpm lint, pnpm typecheck, pnpm build and pnpm eval:ci (exit 0, matchBaseline: 1) pass; pnpm test passes (95 files, 1,056 tests) against TEST_DATABASE_URL=…/graft_test_fix3; migrate, rollback and migrate on graft_fix3_dod applied 0001..0012, rolled back only 0012_audit_label_event, then re-applied it. N-1 to N-3, N-6, N-10 and N-11 pass, the mutation guard has no diff and break-glass.ts has no sender. Not run: the manual smoke test (HUMAN-TODO). pnpm db:up was not run: the shared Postgres on port 55432 was reused, and both scratch databases were dropped afterwards.

Review 2 fixes

Nits from docs/phase-1/reviews/step-3-review-2.md, PR #30. No behaviour change in report or enforce mode except nit 4.

  1. "A delivery without a sender id never applies" had no test → I-BG-26: a label run with breakGlassHeadSha and no breakGlassActorId, events naming maya (a maintainer), and a retry still allowed: ignored actor_unknown, no role read, no retry, not merged under break-glass. Kills F1c (a missing id counted as a match).
  2. Two defence-in-depth guards had no test → kept, both fail closed. I-BG-27 (F2f, !ev.unlabeledLater in bound): maya's bypass, then maya unlabels and tom re-labels with his event not listed yet, then a label delivery for another head (D4 mismatch): the bypass ends (removed for maya) and is not replayed. I-BG-28 (F2g): two applied rows for different heads of one change in one transaction, and the store refuses the second.
  3. The late re-send had no test → I-BG-29: the mode is set to report between the facts read and the check-run write, so the mutation gate refuses with mode_report and the transaction rolls back. The run is stale with no audit row, and the label run is queued again as policy:breakglass:<change>:<head>:<deliveryId> with its filters. Kills F4b (no resendLabelRun after an uncommitted publish).
  4. canRetry read the definition's retryLimit → the worker passes includeMetadata: true to pg-boss and gives the handler the job's own retryLimit, which pg-boss copies onto each job when it is inserted. A job queued before a deploy that changes the limit keeps its own limit, so canRetry matches what pg-boss will do: no silent drop on a raised limit, and no early fail-closed on a lowered one. I-Q-4b: a job queued with 5 retries and run by a worker whose definition says 1 sees retryLimit: 5.
  5. The "Migration number" paragraph was stale → corrected above, and in step 4's record below.

Mutation checks (each applied alone, the break-glass tests run, the file restored): F1c (I-BG-26), F2f (I-BG-27), F2g (I-BG-28), F4b (I-BG-29); the old worker.ts (I-Q-4b).

Phase 1 step 4: guard detection

Spec: phase-1/step-4-guard-detection.md. Decisions D1 to D17 are in the spec; what follows is the API check (T1), what the spec left open, and where the build differs from it. User page: features/guard.md.

T1: API verification (offline, from GitHub's REST and webhook documentation as known at build time, and @octokit/webhooks-examples / @octokit/webhooks-schemas 7.6.1; the fakes in test/helpers/fake-github-api.ts follow these shapes).

  • (a) Other apps' check events. GitHub documents that an App with the checks permission (read or above; write subscribes automatically) receives the created and completed actions of check_run and check_suite for every check run and suite in the repositories it is installed on, whichever app created them. Only requested, rerequested (suites and runs) and requested_action (runs) go to the App that owns the run or suite. So check_run.completed and check_suite.completed from GitHub Actions and other CI apps reach Graft, and the spec's fallback (observes scheduled from guard.track with re-checks at +5 and +30 minutes) is not built. This could not be exercised against real GitHub offline: the HUMAN-TODO sandbox check of step 4 covers it, and if it turns out wrong, push and status are still triggers and guard.confirm re-observes at the deadline.
  • (b) Results. GET /repos/{o}/{r}/commits/{ref}/check-runs answers { total_count, check_runs: [...] }, per_page up to 100, paginated with page (and a Link header); filter=latest (the default) returns the most recent run per name and app, so it can hide a red run behind a later run of the same name in another check suite; the guard requests filter=all and reduces the runs itself (review 2, finding B). A run carries id, name, head_sha, status, conclusion (null until completed), completed_at, html_url, app { id, slug } and check_suite { id }. GET /repos/{o}/{r}/commits/{ref}/status (combined status) answers one object { state, sha, total_count, statuses: [...] , … } with the latest status per context (context, state, target_url, updated_at), per_page up to 100 with page. Because that body is an object with several keys, octokit.paginate cannot page it; both reads page by hand (page 1 to 5 for check runs, 1 to 3 for statuses, stopping at a short page). A check-run read that reaches page 5 with runs left over is truncated, and every result of that commit is stored as ignored (review 2 fixes, below).
  • © GET /repos/{o}/{r}/commits/{sha}/pulls lists the merged pull request that introduced a default-branch commit (and open or merged ones for a commit elsewhere). Squash merge: the squash commit maps to its PR. Merge commit: the merge commit maps to its PR (the PR's own commits are second parents, never on the first-parent chain). Rebase merge: each rewritten commit maps to the PR, which is why D6 does not rely on merge_commit_sha alone. Graft keeps PRs with merged_at set and base.ref equal to the default branch.
  • (d) Branch hints. The status payload carries sha, context, state, target_url and branches: [{ name, commit: { sha, url }, protected }], the branches that contain that commit, whether or not it is their tip, at most 10 (corrected by review 1, finding 3: the build first read them as the branches whose tip is the commit). A full list can therefore leave out the default branch. check_suite.head_branch (also check_run.check_suite.head_branch) is the branch the suite's head SHA was pushed to, and null when GitHub cannot tell (for example a fork). Graft uses them only to decide whether to enqueue.

D2 deviation (recorded as the spec asks). The phase plan (README §4) lists actions: read and the workflow_run event. The guard reads CI through the checks API instead (GitHub Actions jobs are check runs, covered by checks), so both manifests add only statuses: read and the check_suite and status events (U-MAN-5).

Choices where the spec is silent

  • The observe window is the observe delay. D12 keys guard.observe by floor(now/30 s) and starts it after GRAFT_GUARD_OBSERVE_DELAY_SECONDS. The singleton id also deduplicates completed jobs for 7 days, so a key window longer than the delay would swallow a trigger that arrives after its window's job ran. The window is therefore the delay itself (30 s by default, which is exactly the spec's key): the job starts delay seconds after the first trigger of its window, after every trigger of that window. With a delay of 0 there is no key and every trigger runs.
  • guard.track key guard:track:<repo>:<before>:<after>: a replayed push is one job; another push has another pair. guard.confirm is keyed per event (one per event by construction).
  • guard.track data has a branch (the pushed branch, refs/heads/ removed): §5.2 compares the push's ref with the API's default branch, and the spec's job data has no ref. It is a branch name, not code or PR text, and is never logged.
  • The chain is followed by parents. Detection walks parent_sha back from the failing commit to the nearest break (or a parent that is not stored), not seq order alone, so a rewound branch's abandoned commits never count. In the normal case the two are the same. A walk that stops at a root commit, an unknown SHA or the 10-request bound is a break, like the 300-commit cap.
  • D6, newest first. The 20 commits/{sha}/pulls lookups go to the newest new commits (the ones detection looks at); older ones are unresolved. A lookup that answers 404 is unresolved. The pulls.get and upsertChangeFromPull for a single PR are not counted.
  • Upsert of results. A result that has not completed (completed_at null: an in-progress re-run, a pending status) never replaces one that has; null replaces null only when the class differs. Equal times do nothing.
  • The race of neighbouring commits. Results are upserted inside the repository lock, so two observes are serialised. When the later commit is observed first (its parent had no result yet), it opens an event whose candidates include the parent; when the parent then turns out red on the same check, that open event moves to the parent (failing SHA, candidates, culprit), rather than a second event being opened (I-GRD-10b). When the parent turns out green, the open event narrows to the commits after it (I-GRD-10c, review 1, finding 2). A settled event never moves or narrows.
  • D8 "open" means confirming. A key that goes red on a commit whose event is already settled is not added (it would change nothing visible).
  • More than 50 candidates are stored as the 49 newest plus one truncated entry, which counts as unresolved, so a list that could not be stored in full is never read back as a culprit. Classification is recomputed from the stored candidates when an event is settled.
  • culprit_change_id is set at detection for a culprit classification (also while confirming); it is what the change lock is taken on.
  • guard.confirm re-observes the failing commit (an API read) and then settles every open event of the repository. ~~An event still undecided at the deadline is not rescheduled~~ (review 1, finding 4: it is examined again, see below), and pilot doctor warns after twice the window.
  • Comment publication is retried by every observe: culprit_found events without a comment id (at most 20 per repository) are published after the lock. With the marker search this makes a crash between the POST and the commit harmless (I-GRD-6, N-9).
  • Comment wording. The headline names the first failing check. "It was green at x, the commit before." is used when the last green commit is the failing commit's first parent; otherwise "It was last green at x." The window reads "2 hours", "90 minutes" or "45 seconds".
  • Links. html_url (check run) and target_url (status) are stored only under the GitHub web root derived from GITHUB_API_URL (https://github.com/ for api.github.com, the host root for GitHub Enterprise Server), at most 500 characters, without spaces, parentheses, angle brackets or @.
  • guard.checks error codes. No new code: an empty list, an empty or 201-character name, a control character or a wrong type are wrong_type; 51 items too_many_items; any other key unknown_key. Policy hashes: a file without guard keeps its hash; U-PGD-1 pins the hashes of the example and every valid fixture computed with the code before this step. guard: {} and guard.checks are part of the canonical form when present.
  • mode show notes. The statuses note is printed whenever the stored permissions lack statuses: read (never read counts as lacking); the detection-off note whenever this shell's GRAFT_GUARD_DETECTION is off. Both are indented in the repository block, after the permissions line and the teams note.
  • Doctor. The two new checks are guard_statuses and guard_confirming, appended after teams (fifteen checks now), always OK or WARN. Not-read permissions count as lacking statuses: read.
  • graft guard list prints no guard events for an empty list; check names are joined with , and +N after three; an ambiguous event lists distinct PR numbers and (N unresolved).
  • The neutral suite runs its app with GRAFT_GUARD_OBSERVE_DELAY_SECONDS=0 (its drain does not wait for deferred jobs) and runs the queued guard.confirm directly. The guard scenario runs last, after the mode changes; the max profile restores its modes first. Since review 1 (finding 1) it merges its own PR 3, not PR 2, and the default branch keeps serving the team graft.yaml. N-2 now compares Graft's own check runs (app 12345) only, since the fake now also holds other apps' CI runs.

Deviations from the spec

  • D17: guard.checks is read from the baseline, not from N (security review). An automated security review of the first build found that reading graft.yaml at the failing commit N lets the culprit itself drop its failing check from guard.checks and hide its breakage: a candidate must not be able to filter its own failure. Results are now stored unfiltered (ci_results.filtered stays false), and the allow-list is applied when a transition is judged, from graft.yaml at the transition's last green commit (the baseline before the candidates), through the existing per-commit loader cache. A missing or invalid file there means every key counts. The file is an API read, so it is loaded before the repository lock (baselines found by a read-only dry run), and a transition whose baseline was not loaded is set aside and the lock phase re-run (at most three passes; the last treats an unknown baseline as "every key"). I-GRD-12b (a merge that removes test from guard.checks while turning test red still opens an event) fails against the old behaviour (mutation table below).
  • Migration number 0011_guard, not "the next free number": step 3 (break-glass) was built at the same time and takes 0010. Whichever of the two merges second must check the order (the migrator refuses migrations out of order) and the step-down tests (I-DB-2, I-MODE-1, I-ENF-1, the pilot-ops "one migration behind" test, I-GRD-1), which name 0011_guard as the top migration. Since step 3 review 1 (#27) merged, 0012_audit_label_event sits on 0011, and these tests step through both.
  • The confirm fallback of T1 (a) is not built, because the answer is "all apps" (above).

Other test changes: I-DB-1 counts 24 tables and I-DB-3 inserts one row into each new table; the step-down tests above; I-DOC-1 lists fifteen checks and its healthy installation has statuses: read; I-MODE-5's literal show block gains the statuses note; I-PURGE-1's seed and counts include main_commits and ci_results; two cron tests switch GRAFT_GUARD_PRUNE_CRON off (their queues register two jobs); the fixtures test lists the four new fixtures; U-MAN-1 expects statuses: read and the two events. The fake GitHub API gains GET /repos/{o}/{r}, GET /commits?sha= (first parents), GET /commits/{sha}/pulls, GET /commits/{sha}/status and an html_url on check runs.

Mutation checks (§15), run by the developer. Each mutation was applied alone after a commit, the named tests run, then the file restored with git checkout. All were caught:

Mutation (as applied) Failing tests
cancelled counted as red U-DET-1, U-DET-11
Already-red main opens an event (the already_red return removed) U-DET-6
Two PRs between green and red blamed on the last one U-DET-4, U-DET-7, U-DET-14 (after its generator was fixed: the first one never built a two-PR list)
Search crosses a chain break U-DET-9
Confirmation skipped: event final at detection with confirm on (observe) I-GRD-6, I-GRD-7 (both), I-GRD-8, I-GRD-10b
Confirmation skipped: confirmationStep always confirms (pure) U-DET-13, I-GRD-7 (both)
Result class taken from the webhook payload (conclusion carried in the job and applied) I-GRD-5
Handler enqueues for PR-branch check runs I-GRD-4
No marker check before commenting I-GRD-6 (replay after a lost comment id), N-9 (both profiles)
No advisory lock around detection I-GRD-10 (three runs out of three)
guard.checks ignored I-GRD-12
Comment posted for ambiguous I-GRD-9
guard.checks read at the failing commit (the behaviour before the D17 correction) I-GRD-12, I-GRD-12b

Not run: the manual smoke test of §15 (a dev server, a worker and pnpm webhook:send); it is listed in HUMAN-TODO. pnpm db:up was not run: the shared scionhub-postgres-1 container on port 55432 was reused, the tests ran against TEST_DATABASE_URL=…/graft_test_s4 and the migrate, rollback and migrate sequence against a scratch database graft_s4_dod, both dropped afterwards.

Review 1 fixes

Finding → fix (review: docs/phase-1/reviews/step-4-review-1.md, CHANGES REQUESTED, 1 major, 7 minors, 4 nits).

  1. (major) The neutral suite's break-glass scenarios ran over no_policy → the guard scenario merges its own PR 3 (as MERGE_SHA), so PR 2 is never merged and the reopen block of 57c1bae is gone; NEXT_SHA serves the same team graft.yaml as B2, so the default branch's tip still has the team policy when break-glass runs. breakGlassScenario now asserts that every verdict it produced (the break_glass ones and the next head's) has policy_status = "ok", policy_commit_sha = NEXT_SHA, would_require and the team constraint. N-1g expects the comment on PR 3. Mutation: break-glass that bypasses only an unusable policy (breakGlass.applied && state !== "ok") now fails N-10 and N-11 (it passed before this fix). The same mutation for would_block only is caught by U-BG-1 and I-BG-2/6/⅞/10/11, not by N-10/N-11, whose PR is a would_require one; making the neutral scenario a block would mean changing step 3's scenario, which a parallel branch is editing.
  2. A late green on the parent did not narrow an open event → confirmOpenEvents first re-judges each confirming event's keys on the current line (detectTransition at the failing commit). If every key still has a transition there, and the widest one's last green commit is one of the event's candidates, the event narrows: last_green_sha, candidates and culprit_change_id as the move of I-GRD-10b does. The baseline's guard.checks is not read again for a narrowed event (the key already passed it at the older baseline). I-GRD-10c (the reviewer's P1: ambiguous before, culprit_found #8 now).
  3. The status branch hint could omit the default branch → T1 (d) corrected above. The handler enqueues when the list names the default branch or has 10 entries; the job already keeps only SHAs on the tracked default branch, so a false positive costs one lookup and, at most, one inline track per window. I-GRD-4: 10 branches without main enqueue, 9 do not.
  4. An event undecided at its deadline was never examined again → guard.confirm starts at the window plus 60 seconds (clock skew between workers). A run that leaves the event confirming re-sends guard.confirm with { eventId, attempt: n + 1 }, keyed guard:confirm:<id>:<n + 1>, a window later, at most twice (CONFIRM_RETRIES). Each key is new, so the 7-day singletonJobId deduplication of completed jobs never swallows one; attempt 0 keeps the step 4 key. The last attempt settles an event that is still undecided as flaky with confirm_reason null: the failure did not persist (it is neither red nor green), so it is not confirmed, and no comment is written. That needs no schema change (the reason column allows null), so no migration was added: 0012 stays with the parallel step 3 fix branch, and there is no migration order to check between the two. The doctor still warns past twice the window (an event on its second attempt is worth a look). I-GRD-8 (the job starts 7,250–7,260 s later), I-GRD-8b (the reviewer's P2: a run one second early re-sends, the next attempt settles culprit_found), I-GRD-8c (a cancelled re-run: two re-sends, then flaky).
  5. A transient error inside the D17 attempt loop lost the event → a lock pass that sets a transition aside now throws a private BaselinesMissing out of the transaction, so it rolls back (results, events and queued jobs alike); the files are read outside the lock and the pass runs again. A failure while reading them leaves nothing committed, so the job's retry upserts the same results and sees the transition again. The cached redKeys is gone: every pass computes its red keys from its own upsert. I-GRD-12c (the reviewer's P4: the first job throws on a 502, its retry opens the event at C3 with C2 as the last green).
  6. Retention pruned a quiet repository's tip → pruneOlderThan also keeps each repository's newest commit (highest seq) and its results. I-GRD-15 keeps an old newest commit; I-GRD-15b (the reviewer's P6: 31 days, a prune, then a red merge on the green tip opens an event with no chain break).
  7. D17's principle was narrower than the docs said → documented: docs/features/guard.md has a "trust boundary" section (the guard detects breakage; it is not a control against a hostile merge, which controls its own CI). The D17 sentence above, "a candidate must not be able to filter its own failure", holds for guard.checks only. Hardening: readCheckRuns keeps the latest run per key and check suite; across suites a red run wins, so a later green decoy in a second workflow cannot hide the failure, while a re-run in the same suite keeps D4's "latest wins". I-GRD-17 (the reviewer's P7, and a same-suite re-run still giving flaky_rerun). The token-written results (a workflow posting runs or statuses on other commits) are not addressed: to revisit in step 5's threat model.
  8. Five rules had no test → X3 I-GRD-11 (a graft/policy failure from app 12345 after a success opens nothing and stores nothing); X4 I-GRD-5 (a later read that answers an older, red result keeps the newer green); X5 I-GRD-6 (lint red on the failing commit joins the event; the comment lists test, lint); X9 I-GRD-4 (a SHA the inline track does not reach: not_on_default_branch, no check-runs read, no ci_results row); X11 I-GRD-3 (a PR merged into release is not mapped to the commit). All five mutations re-run: each is killed by the test named.
  9. (nit) A status link could point anywhere on github.com → a status target_url is kept only under <web root><owner>/<repo>/ (check-run html_url keeps the web-root rule; GitHub writes it). I-GRD-11.
  10. (nit) filtered was dead code → KeyResult.filtered and why: "filtered" are removed from detect.ts; the allow-list is the pure allowedByGuardChecks, which observe.ts uses and U-DET-12 tests. The ci_results.filtered column stays (always false) to avoid a migration.
  11. (nit) A fork PR from a branch named like the default branch costs an inline track → accepted: bounded (two repos.get, one git.getRef and listCommits per SHA per 30-second window), and the fix (a negative cache, or reading the suite's head repository) is not cheap. To revisit if the doctor or metrics show the cost.
  12. (nit) The guard's changes rows and step 3 → forwarded to step 5: its spec must read a culprit's break-glass verdict by change_id and the merged head, never by PR number. No code in step 4 reads it.

Mutation checks of these fixes (each applied alone after a commit, the guard tests run, the file restored): no narrowing (I-GRD-10c); no confirm margin (I-GRD-8); no re-send (I-GRD-8b, I-GRD-8c); no final settle (I-GRD-8c); the D17 pass committed before its baselines are read (I-GRD-12c); no "red wins" across suites (I-GRD-17); status links under the web root (I-GRD-11); the branch cap ignored (I-GRD-4); the newest commit pruned (I-GRD-15, I-GRD-15b); X3 (I-GRD-11), X4 (I-GRD-5), X5 (I-GRD-6), X9 (I-GRD-4), X11 (I-GRD-3); break-glass only over an unusable policy (N-10, N-11).

Review 2 fixes

Findings from docs/phase-1/reviews/step-4-review-2.md, PR #30. Report mode is unchanged.

  • A. Narrowing's safety conditions had no test → I-GRD-10d (two failing keys, only test turns green late on the parent: the event keeps [C2, C3] and no culprit; kills F2c, narrowing to the narrowest key), I-GRD-10e (lint joins on a later commit through D8 and has no transition at the failing commit: no narrowing; kills F2d), I-GRD-10f (a cancelled re-run replaces the green at the last green commit: the event does not widen; kills F2b).
  • B. filter=latest could hide the red run → readCheckRuns requests filter: "all". The D4 reduction per suite and "red wins across suites" then give the right answer under either reading of latest. The fake GitHub API now applies latest unless filter=all is passed, so I-GRD-17 fails with latest.
  • B, follow-on: a truncated read. With filter: "all" re-runs count toward the 500 runs read (5 pages of 100), so truncation is easier to reach. A run left unread may be the red that wins across suites, or a later re-run in the same suite, so a truncated read can make a red commit look green (a false culprit on the next commit) or a flake look red. When the pages run out with runs left over, every result of that commit is stored as ignored and a warning is logged: the commit is no baseline, and a later event reaches back to an older green with more candidates. I-GRD-17b (550 runs plus a green decoy hide C2's red: the C3 event names PR 7 and PR 8, not PR 8 alone). Combined statuses are not changed: they hold one status per context, so a dropped page loses contexts but never hides a newer result behind an older one.
  • C. No test for a still-red final attempt → I-GRD-8d (kills F4f). As the review wrote it, the scenario never reaches the final attempt: any observe after the window settles a red event itself. The test observes the red re-run with a worker clock set before the deadline, the clock skew of review 1, finding 4.
  • D. An unconfirmed flaky could not be seen → graft guard list prints flaky (unconfirmed) when confirm_reason is null, and --json adds confirmReason. I-GRD-7 (plain flaky), I-GRD-8c, I-GRD-16.
  • F. The T1 (b) wording → corrected above.
  • Still open: E (record why a narrowed event keeps the older baseline's guard.checks, next to D17 in docs/features/guard.md), and finding B's HUMAN-TODO sandbox items and its workflow_dispatch trade-off.

Mutation checks (each applied alone, the guard tests run, the file restored): F2b (I-GRD-10f), F2c (I-GRD-10d), F2d (I-GRD-10e), F4f (I-GRD-8d), filter: "latest" (I-GRD-17), the old cli.ts (I-GRD-8c, I-GRD-16), no truncation handling (I-GRD-17b).

Phase 1 step 5: revert PRs

Spec: phase-1/step-5-revert-prs.md. Decisions D1 to D21 are in the spec; what follows is the API check (T1), what the spec left open, and where the build differs from it (also listed in the spec's §19). User page: features/guard.md.

T1: API verification (offline, from GitHub's REST, GraphQL and webhook documentation as known at build time; the fakes in test/helpers/fake-github-api.ts and test/helpers/git-trees.ts follow these shapes; every item is re-checked on real GitHub in HUMAN-TODO).

  • (a) GET …/git/trees/{sha} without recursive answers { sha, url, tree: [{ path, mode, type, sha, size?, url }], truncated }, where path is the entry's name (one level), mode one of 100644, 100755, 040000, 160000, 120000 and type one of blob, tree, commit (a submodule). truncated: true means the entry limit (documented as 100,000 entries or 7 MB, for the recursive form; Graft never asks for it) was hit. Graft treats a truncated tree as too_large, and refuses an entry name with a /, . or .. (also too_large).
  • (b) POST …/git/trees with base_tree. Documented: "If both tree.sha and content are null, the file will be deleted." The documentation speaks of files only. Whether sha: null on a type: tree entry deletes the directory could not be verified offline. Decision: no expansion into files is built. The D9 check after the write reads the new tree back and compares every changed path with the plan, so a directory GitHub did not delete ends as error / tree_mismatch before any commit exists; the fake deletes any entry, and HUMAN-TODO checks the real behaviour. If GitHub refuses it, the expansion of the spec's T1 (b) is the follow-up.
  • © The workflows permission. GitHub refuses to let a GitHub App create or update a ref to a commit that adds or changes a file under .github/workflows/ without the workflows permission ("refusing to allow a GitHub App to create or update workflow … without workflows permission"). Graft does not request it, so such a revert is needs_human / workflow_files before any write (D8), including a directory change that contains .github/workflows.
  • (d) POST …/issues/{n}/labels works on a pull request (every PR is an issue) with issues: write or pull_requests: write; Graft has the latter. It answers the issue's labels. GitHub creates a label that does not exist yet (default colour, no description); HUMAN-TODO still asks the repo admin to create graft:revert with a description.
  • (e) enablePullRequestAutoMerge takes { pullRequestId: ID!, mergeMethod, commitHeadline, commitBody, authorEmail, expectedHeadOid, clientMutationId } and answers { actor, clientMutationId, pullRequest }. Errors come back as GraphQL errors (HTTP 200 with errors, Octokit's GraphqlResponseError): UNPROCESSABLE "Auto merge is not allowed for this repository" and "Pull request is in clean status" (the PR can be merged now, for example no required checks). For a PR whose auto-merge is already enabled the documentation is silent: Graft treats a GraphQL error whose message says "already enabled" as enabled, any other GraphQL error as unavailable (its type logged), and an HTTP error like any other GitHub error. clientMutationId is echoed (Relay convention); Graft checks the answer's pullRequest { number repository { nameWithOwner } } instead, which is what D15 asks.
  • (f) Workflows on a Graft PR. Events caused by the repository's GITHUB_TOKEN do not start workflows, but events caused by a GitHub App installation token do: a revert PR opened by Graft runs the repository's pull_request workflows, so its required checks run.
  • (g) GET …/pulls?head=<owner>:<branch>&state=all filters by the head's owner and branch and, with state=all, includes closed and merged PRs, which is what D17 c/d need to adopt a PR opened before a crash.

Choices where the spec is silent

  • Where the markdown helpers live. src/guard/revert-text.ts is pure and the definition of done forbids imports from src/github there, but it needs codeSpan (step 4 §8). The helpers moved to src/core/markdown.ts (unchanged); src/github/markdown.ts re-exports them, so no other import changed.
  • needs_human is set in both modes. In report mode too the event's revert story ends there (the plan says a human is needed); skipped and error keep culprit_found (§14). The guard comment, eventsAwaitingComment and publishGuardComment accept culprit_found, needs_human, revert_opened, reverted and revert_closed.
  • Report mode stores planned, revert_plan_paths, auto_merge_state = 'would' and auto_merge_reason (null when it would be enabled); eligibility is computed as if the PR were opened. A needs_human or skipped plan stores no auto-merge state.
  • already_reverted is checked before conflicts. Every tip entry equal to before is also unequal to after, so D7's conflict test would fire first; the plan checks "all back to before" first. A culprit whose diff is empty counts as already reverted.
  • D8's order is workflow_files, submodule, type_change; the first reason that any change hits wins. The plan keeps the offending paths, but only touched_later lists paths in the comment (the other reasons are one fixed sentence, §10).
  • The tree read budget (GRAFT_GUARD_REVERT_MAX_TREE_READS) counts distinct tree objects the plan reads, which are the plan's requests (the reader is cached per job). The API reader has its own ceiling of twice the budget plus 10 for the whole job: the D9 check reads the new tree along the changed paths after the plan.
  • The culprit's card is the newest intent_cards row of the change at the merged head (pulls.get → head.sha), whatever its prompt version; provenance (task, session) is used only when change_provenance.head_sha is that head.
  • policyPaths is ["graft.yaml"], the one file the policy loader reads; a change on a directory that holds it counts too.
  • The cap counts events in revert_opened plus events claimed by a run that has no outcome yet, so two runs cannot both pass at the last free slot. The claim checks, in §7's order, the cap, then one revert per culprit (an opened or in-progress revert of the same change), then D21. A run that resumes after its claim skips the first two.
  • D21 looks at tracked commits with a higher seq than the failing commit's, and needs every remaining failing key green on one of them.
  • A merge method is the first of squash, merge, rebase that repos.get allows; a repository that allows none counts as repo_setting_off.
  • Wording. A bot author is shown as `renovate[bot]`, merged by @bob; a login that fails D11's rule is a code span. A task matching #\d{1,9} is a live reference, anything else a code span. The session URL (validated by step 2) is checked again for shape (https, plain host, no parentheses, spaces or @). The PR body's auto-merge line is the eligibility decision; the guard comment shows the final state, including off: GitHub did not enable it for unavailable. An error after the PR was opened (a rollback before the label or auto-merge) reads "Graft opened #456 to revert this merge but could not finish (mode_changed)." The commit message names the branch only when it is plain ([A-Za-z0-9._/-]), otherwise "the default branch".
  • GRAFT_GUARD_REVERT=off writes step 4's comment verbatim (its paragraph and the report line), as D19 says, also in enforce mode. §10's revert_off sentence is kept in the text module; graft guard list shows skipped: revert off.
  • A run resumed in report mode for a revert that was opened but not labelled or not given auto-merge records error / mode_changed (those writes would be refused) and comments.
  • An adopted PR that is already closed gets reverted or revert_closed from its state, not revert_opened.
  • The branch deletion uses the literal path DELETE /repos/{owner}/{repo}/git/refs/heads/graft-revert/<eventId>: Octokit percent-encodes the slashes of a {ref} parameter, and the mutation guard refuses any path with %.
  • GraphQL on GitHub Enterprise Server goes to /api/graphql (Octokit rewrites …/api/v3); the mutation guard recognises that URL as the GraphQL endpoint of the configured base.
  • Job options. guard.revert and guard.revert_closed retry 3 times; a transient GitHub error retries, and the last attempt records error / github_<status>. guard.revert_closed is keyed guard:revert_closed:<repo>:<pr>.
  • reverted_at is the PR's merged_at from the API, or the time guard.track mapped the merge commit. The doctor's 72 hours run from revert_claimed_at (there is no "opened at" column).
  • guard.auto_merge_reverts parsing. A repeated item counts once (as every list of graft.yaml); three items are too_many_items before deduplication; an empty list or a scalar is wrong_type. Zod 4 also runs a list's length rule on a string value (it reads the string's length), which reported too_many_items next to wrong_type for auto_merge_reverts: logic; structuralIssues now drops a length issue at a path whose value failed the "array" type check. No existing code changes.
  • The fake GitHub API gives every history commit without an explicit git object a synthesised one: its parent's tree plus one file named after it, so every tracked commit has a tree and a merge changes one path. Tests that need exact trees set them (files() in guard-revert.test.ts).

Deviations from the spec

  • I-REV-20 allows GET …/contents/graft.yaml. The spec's list forbids /contents/, but D16 reads guard.auto_merge_reverts and guard.checks through the existing policy loader, which reads graft.yaml with repos.getContent. That is Graft's own configuration, read since Phase 0 step 5; the test allows that one path and nothing else under /contents/. The DoD grep is unaffected (the loader is in src/policy).
  • autoMergeEligibility returns the risk class with eligible: true (the PR body needs it); the spec's type has { eligible: true } only.
  • N-1 and N-1g are restated for max too, not only N-8: with every mode at its maximum the guard now opens a revert, so "every write is Phase 0" and "the guard's only write is the comment" no longer hold there. N-1 [max] accepts a phase1 route only when it is a guard route; N-1g [max] expects the comment's "Graft opened #N" paragraph and Graft mode: enforce.. N-2b [max] accepts guard gate questions next to policy ones. N-5 creates a graft-revert/<uuid> ref (the §12 body rule refuses graft-revert/n5 with feature_not_allowed) and counts only its own ref.
  • The existing guard tests run guard.revert inline. guard.test.ts takes the queued jobs out of pg-boss after each observe and confirm (no worker runs there), its history() points main at the newest commit (the plan reads the tip), and I-GRD-13 now expects the revert's writes and Graft mode: enforce.: the step 4 enforce line ("Revert PRs are not available in this version…") is gone (§10). I-GRD-16's list line gains skipped: confirmation off and its JSON the revert key; its doctor block has four guard checks.

Other test changes: the migration step-down tests (I-DB-2, I-DB-7 to I-DB-12, I-MODE-1, I-ENF-1, I-BG-1, I-BG-24, the pilot-ops "one migration behind" test, I-GRD-1) step through 0013_guard_revert; I-DOC-1 and I-DOC-3 count eighteen doctor checks; U-GCM-1 checks that a revert section changes only the paragraph and the mode line; U-PGD-2 no longer expects auto_merge_reverts to be an unknown key; U-MG-5, U-MG-6 and U-MG-8 create a graft-revert/<uuid> ref; the fixtures test lists pull_request.closed.revert; U-MAN-1 expects contents: write. The fake GitHub API gains GET/POST …/git/trees, the tree and parents of GET …/git/commits/{sha}, POST …/git/commits, POST …/git/refs, DELETE …/git/refs/heads/…, POST …/pulls, GET …/pulls?head=, POST …/issues/{n}/labels, POST /graphql (enablePullRequestAutoMerge), the merge settings of GET /repos/{o}/{r}, and records each request's accept header.

Mutation checks (§18), run by the developer. Each mutation was applied alone after a commit, the named test files run against a scratch database, then the file restored. All were caught:

Mutation (as applied) Failing tests
Revert opened for flaky with a null confirm_reason (status and reason gates removed) I-REV-7
confirmation_off ignored I-REV-8
D7 skipped (no conflict from the tip) U-RVP-6, I-REV-6
Added file restored instead of deleted (the after SHA in place of sha: null) U-RVP-2, U-RVP-11, I-REV-5 (and ten more)
Old mode not restored (the after mode) U-RVP-2, U-RVP-11
Workflow files reverted (the D8 rule removed) U-RVP-8
Report mode goes on to the guard client and its writes I-REV-2, I-REV-4, N-1g, N-2, N-3, N-8
GraphQL body rule removed (any query with a valid id) U-MG-19
Ref body rule removed U-MG-20
No lookup by head (findPr never finds) I-REV-10
One-per-culprit check removed (the index still refuses the store) I-REV-11
Cap ignored I-REV-12
Break-glass not checked for auto-merge I-REV-14
auto_merge_reverts read at the failing commit instead of the baseline I-REV-13, I-REV-14, I-REV-15, I-REV-17
Narrowed baseline's guard.checks not applied I-REV-15
Revert-of-revert check removed (the database test; the job never reads a branch name or trailer, so "by branch name" has no code to mutate) I-REV-9
reverted taken from the payload (the API's open state and merged ignored) I-REV-12, I-REV-18

Verification. pnpm lint, pnpm typecheck, pnpm build, pnpm graft policy schema --check and pnpm eval:ci (exit 0, matchBaseline: 1) pass; pnpm test passes (101 files, 1,178 tests); pnpm graft e2e run --only-offline passes 12 of 12 scenarios. The DoD greps of §18 find nothing (the only feature: "guard" is in src/modules/guard/revert.ts), and 70 test lines carry the §16 IDs.

Not run: the manual smoke test of §18 (a dev server, a worker and pnpm webhook:send); it is listed in HUMAN-TODO. pnpm db:up was not run: the shared scionhub-postgres-1 container on port 55432 was reused, the tests ran against TEST_DATABASE_URL=…/graft_test_s5 (mutation checks against graft_test_s5m), and the migrate, status, rollback, status and migrate sequence against a scratch database graft_s5_dod (applied 0001..0013, rolled back only 0013_guard_revert, re-applied it), dropped afterwards.

Review 1 fixes

Finding → fix (review: docs/phase-1/reviews/step-5-review-1.md, CHANGES REQUESTED, 2 required, 2 recommended, 4 minors, 4 nits). Report mode is unchanged: no new code path makes a guard client or a write in report mode (the finding 6 lookup is a GET with the default client).

  1. (required) A # in the route string skipped the §12 body rules → mutation-guard.ts has one normalisedPath (query dropped, one trailing slash dropped; #, %, \ or no leading / give null), used by classifyWrite, checkRunWrite and guardBodyAllowed. A write whose URL contains # anywhere is now unknown_route, like % and \; a fragment is never stripped. guardBodyAllowed fails closed: it returns false for a route it does not know, and the three bodiless guard routes (trees, commits, the ref deletion) are listed by name. U-MG-2 (#, #x, ?x=# paths are unknown), U-MG-20 (the # and #x variants of the ref, pulls and labels routes, with good and bad bodies, are unknown_route; guardBodyAllowed refuses an unknown route, a # and a %).
  2. (required) The D9 check had no test → the fake tree writer has quirks (test/helpers/git-trees.ts, writeTree, used by POST …/git/trees only): keepNullTrees ignores sha: null on a type: tree entry, as GitHub might; extra writes entries the request did not name. The check itself is now treeMatchesPlan: every plan path holds its before entry (as before) and diffTrees from the tip's tree to the written tree gives exactly the plan's paths, each with the tip's entry before and the plan's before after. So it checks the whole tree, not only plan paths (the review's second case). The diff runs on the job's API reader (its ceiling is unchanged; past it the check fails closed). I-REV-5b: a culprit that adds a whole directory, with each quirk, ends error / tree_mismatch with one POST …/git/trees, no commit, no ref, no PR, and the comment "Graft could not open the revert (tree_mismatch)…".
  3. D15's response check and "already enabled" had no test → the fake GraphQL handler can answer for another PR (graphqlAnswer); "already enabled" uses the queued graphqlErrors. I-REV-13b: another number and another repository each give error / auto_merge_mismatch (one GraphQL request, no retry, the "could not finish" comment); "Pull request auto merge is already enabled" gives auto_merge_state = enabled.
  4. A failed guard.revert could not run again for 7 days; a stuck claim held a cap slot →
  5. guardRevertJob.handle catches an error that will not be retried (permanent, or the last attempt) and calls settleFailedRun: an event with no outcome gets error with the failure's class (which releases a claimed slot and the one-per-culprit block), and the comment is tried once with the default client. It is best effort: a second failure is logged at warn, and the job still fails.
  6. guard.revert keeps its job row one hour (deleteAfterSeconds: 3600), not 7 days, so the deterministic singleton id of D1 expires and the next guard.observe (which re-sends every event still awaiting its comment) can send it again. While a job is queued, active or retrying, the row exists and still deduplicates. Exactly-once of the effects never relied on the job row: the claim, the stored steps and comment_id do. This also covers a worker killed during the last attempt, which no catch can see.
  7. The bounded age is GRAFT_GUARD_REVERT_MAX_AGE_HOURS (1–168, default 24): an event whose culprit was confirmed (confirmed_at, else detected_at, else created_at) longer ago is skipped / stale before the plan, in both modes. The confirmation time, not the detection, is used because GRAFT_GUARD_CONFIRM_SECONDS may be 24 hours itself. An event whose writes began (revert_commit_sha or revert_branch set) is resumed whatever its age, so nothing Graft created is abandoned. The comment reads "Graft did not open a revert: the failure was confirmed too long ago for an automatic revert."
  8. Doctor: guard_revert_claims warns about events claimed more than an hour ago with no outcome. I-DOC-1 and I-DOC-3 now count nineteen checks; I-GRD-16's doctor block has five guard checks.
  9. I-REV-10b (a token failure: retried while it can, settled error github_… with a comment on the last attempt, the job keeps its row one hour; a culprit confirmed 25 hours ago is stale; a run whose ref answer was lost resumes 25 hours later and opens), I-REV-12b (two reverts open and one claimed with no outcome: a new culprit is cap_reached), I-REV-22 (the claim warning), U-Q-6 (the job's retention).
  10. Every refusal was mode_changed → refusalClass: mode_report and mode_off are mode_changed; any other refusal is refused_<reason> (at most 40 characters), so a deactivated repository or a Graft defect does not read as a rollback. I-REV-17b (the repository removed mid-job: refused_repository_unknown).
  11. A run resumed in report mode after a write began recorded planned → in report mode, an event with revert_commit_sha or revert_branch looks its PR up by head with the default client (a GET), adopts it (storePr), and records error / mode_changed either way. I-REV-17b: a PR opened but not stored is adopted (revert_opened, PR stored, the "could not finish" comment); a commit with no PR gives "could not open (mode_changed)"; an opened revert whose label answer was lost gives error mode_changed. Not handled: a resumed run whose plan becomes needs_human or skipped (the tip moved between the crash and the retry) still settles that outcome before this check, in both modes; a PR it opened stays on GitHub. The window is one crash plus a moved tip; to revisit if it shows up.
  12. The GraphQL rule gated the repository of clientMutationId, not the PR's → bound (option 1 of the review). A guard client records, in an after hook, the node ids and numbers of the pull requests in its own …/pulls responses (create, get, list), with the owner and repository of the route (at most 200 per client). The GraphQL rule requires variables.pullRequestId to be one of them, with the number and repository its client mutation id names; otherwise feature_not_allowed (pull request), before the gate is asked. A client never inherits another's list. Limit: a guard client that listed a repository's pull requests could target any of them in that repository; the job lists by head only, and the gate is now asked for the repository the PR is in. U-MG-19, U-MG-18 (the GraphQL case reads its PR first).
  13. Five rules had no test → X22 I-REV-14 (a logic card at an earlier head only: card_missing); X25 I-REV-10 (the PR is closed before the retry: revert_closed, not counted by the cap); X28 I-REV-18 (a reverted event and a late webhook: settled, no API read, reverted_at unchanged); X20 U-RVP-8 (the base tree truncated, the tip not the head: too_large). revert-closed.ts's update is now conditional (where status = 'revert_opened', returning settled when nothing changed), as markReverted is. A revert PR reopened after revert_closed stays revert_closed and is not counted by the cap again; pull_request.reopened is not handled (accepted: the cap bounds Graft's own runaway, and a human who reopens the PR owns it).
  14. (nit) Two guard routes were wider than needed → a guard client's POST …/pulls needs a base that is a plain branch name ([A-Za-z0-9._/-]{1,255}, no owner: form); a default branch with other characters would be refused (refused_feature_not_allowed), never sent elsewhere. DELETE …/git/refs/heads/graft-revert/… takes only [0-9a-f-]{36}. U-MG-3, U-MG-20.
  15. (nit) The baseline fell back to the failing commit → no fallback: with no last_green_sha the baseline is { checks: null, autoMerge: "not_configured" } (every key counts, auto-merge off). Not reachable today (detect.ts always sets it), so no test.
  16. (nit) A late comment mixed the two modes → a planned outcome is rendered with the report line whatever the mode of the run that writes the comment (it was decided in report mode). I-REV-2b. Other outcomes keep the mode read by the run (an opened revert commented in report mode is already error mode_changed).
  17. (nit) U-RVT-2's bot case → a Bot author ci-helper (a valid mention) is a code span, and only @bob is mentioned. Kills X11.

Mutation checks of these fixes (each applied alone by a script, the named test file run against a scratch database graft_s5fixm, the file restored; git status clean afterwards):

Mutation Result
# stripped as a fragment (the old classifyWrite) Killed: U-MG-2, U-MG-20
guardBodyAllowed falls through to true Killed: U-MG-20
X1: D9 check removed Killed: I-REV-5b
D9 on plan paths only (no diff from the tip) Killed: I-REV-5b
X4: D15 response check removed Killed: I-REV-13b
X5: "already enabled" counted as unavailable Killed: I-REV-13b
X17: the cap does not count claimed runs without an outcome Killed: I-REV-12b
X20: truncated ignored in the diff Killed: U-RVP-8
X22: card of any head Killed: I-REV-14
X24: an opened revert resumed in report mode not marked mode_changed Survived, equivalent now: an opened event always has revert_branch, so finding 6's check settles the same error mode_changed (after one more GET)
X25: storePr ignores an adopted PR's state Killed: I-REV-10
X28: guard.revert_closed without its revert_opened gate Killed: I-REV-18
No settle on the last attempt Killed: I-REV-10b
No stale skip Killed: I-REV-10b
guard.revert rows kept 7 days Killed: I-REV-10b (and U-Q-6)
Every refusal mode_changed Killed: I-REV-17b
Report-mode resume after a write began records planned Killed: I-REV-17b
GraphQL binding removed Killed: U-MG-19
GraphQL binding ignores the number Killed: U-MG-19
PR base not checked Killed: U-MG-20
DELETE of any graft-revert/ name Killed: U-MG-3
A planned comment with the run's mode Killed: I-REV-2b
X11: a bot author mentioned Killed: U-RVT-2

Verification of the fixes. pnpm lint, pnpm typecheck, pnpm build, pnpm graft policy schema --check and pnpm eval:ci (exit 0, matchBaseline: 1) pass; pnpm test passes (101 files, 1,184 tests) against TEST_DATABASE_URL=…/graft_s5fix; pnpm graft e2e run --only-offline passes 12 of 12 scenarios. The DoD greps of §18 find nothing, and 76 test lines carry the §16 IDs. On a scratch database graft_s5fix_dod: migrate applied 0001..0013, rollback rolled back only 0013_guard_revert, migrate re-applied it; the database was dropped. No container was started or stopped. Not run: the manual smoke test (HUMAN-TODO), and the T1 (b) check of sha: null on a directory on real GitHub, which must still be done before a pilot repository enforces.

Phase 1 step 6: MCP server

Spec: phase-1/step-6-mcp-server.md. Decisions D1 to D22 are in the spec; what follows is the SDK and API check (T1), what the spec left open, and where the build differs from it. User page: features/mcp.md.

T1: SDK and API verification (from the installed packages' types and READMEs, a scratch run of the SDK against itself, and GitHub's REST documentation as known at build time; the fakes in test/helpers/fake-github-api.ts follow these shapes; the items marked real are re-checked in HUMAN-TODO).

  • (a) Versions. @modelcontextprotocol/server@2.3.1, @modelcontextprotocol/node@2.1.1 and @modelcontextprotocol/client@2.3.1 are still the npm latest tags (checked 2026-10-23) and were published on 2026-10-02 to 2026-10-05, so more than two weeks old. They are pinned exactly (dependencies, and the client as a devDependency). They bring @modelcontextprotocol/core@2.3.1 and, through node, hono and @hono/node-server; the server's zod ^4.2.0 resolves to the project's zod@4.6.7 (one copy). createMcpHandler(factory, { legacy, responseMode, maxRequestBodySize, onerror }), toNodeHandler(handler, { onerror, maxRequestBodySize }), legacy: "stateless", responseMode: "json" and McpHandlerRequestOptions.authInfo exist with the meaning D2 and D3 give them. No name changed.
  • (b) AuthInfo. toNodeHandler forwards req.auth as the handler's pass-through authInfo ("never populated from request headers"). The factory receives it as McpRequestContext.authInfo, and a tool callback can read it as ctx.http?.authInfo. Graft reads it in the factory and closes the tools over the principal, so a tool never sees an AuthInfo at all.
  • © Eras. With legacy: "stateless", GET and DELETE answer 405 {"jsonrpc":"2.0","error":{"code":-32000,"message":"Method not allowed."},"id":null}. A 2025-era client (initialize with protocol 2025-11-25) is served, one fresh instance per request; the SDK's legacy client also tries a GET stream after initialize and accepts the 405. A 2026-07-28 client (versionNegotiation: { mode: { pin: "2026-07-28" } }) sends one server/discover probe and then tools/list: no initialize round trip. responseMode: "json" shapes the modern leg only; the stateless legacy leg answers a raw POST that accepts both media types with one server-sent event. Real: re-checked with real clients in HUMAN-TODO.
  • (d) Validation. A zod input failure (a wrong type, an unknown key of a .strict() object) is not JSON-RPC -32602 in 2.3.1: it is a tool result with isError: true and the text Input validation error: Invalid arguments for tool <name>: … (the issue path and zod's message; zod 4 messages carry no value, only a key name for an unknown key). -32602 is kept for a tools/call that is malformed itself (for example a non-string name). outputSchema is checked on the way out: structuredContent that does not match becomes isError "Output validation error"; an isError result is not checked against it. See the deviations.
  • (e) Client. new StreamableHTTPClientTransport(url, { requestInit: { headers } }) sends the headers on every request; fetch can be injected. ClientOptions.supportedProtocolVersions pins the legacy handshake, versionNegotiation the modern one. test/helpers/mcp-client.ts uses both.
  • (f) POST …/pulls. A second PR for the same head and base answers 422 Validation Failed with errors: [{ resource: "PullRequest", code: "custom", message: "A pull request already exists for <owner>:<branch>." }]; a head with nothing to merge answers 422 with "No commits between and ". Graft never parses these messages (D20): any 422 is followed by the D17 lookup, existing: true when it finds the PR, github_422 otherwise. GET …/pulls?head=<owner>:<branch>&base=<b>&state=open filters by the head's owner and branch and by base; Graft also checks head.ref and base.ref of what it gets back. Real: HUMAN-TODO.
  • (g) GET …/pulls/{n}/commits. author and committer are GitHub user objects, or null when the commit's email belongs to no GitHub user; the endpoint lists at most 250 commits. Graft reads pulls.get's commits count first: more than 250, or a commit with a null author (or no login), means "cannot tell" (D19).

Choices where the spec is silent

  • The principal reaches the tools through the factory (T1 b), not through ctx.http.authInfo. AuthInfo.extra also carries the repository's current full_name, read by the same D7 query, which D8 compares with the repository argument.
  • Capabilities. McpServer.registerTool advertises tools: { listChanged: true } on its own; there is no public option to clear it. Nothing ever sends a list-changed notification (the server is stateless, has no subscriptions, and the tool set is fixed), so §2 holds in behaviour. The SDK also prints one console warning per createMcpHandler ("responseMode: 'json' drops mid-call notifications"); it carries no request data.
  • Annotations. readOnlyHint: true on get_status, get_policy and report_provenance (the spec's "three reads"; report_provenance writes Graft-side data only); readOnlyHint: false, destructiveHint: false, idempotentHint: true on open_change.
  • HTTP order. Origin (D4), then the failed-auth block of the client IP, then the token, then the per-token bucket. GET and DELETE need a token too, so without one they are 401, with one 405. 415 comes from removing Fastify's text/plain parser in the plugin's encapsulated scope; 413 from the route's bodyLimit (the SDK's own 64 KiB bound is set too, for a body it reads itself).
  • D9 (b). A malformed header counts as a failure. Windows are fixed minutes per IP; once an IP has 20 failures, every request from it (a valid token included) is 429 until the window ends, with no database lookup: 20 bad tokens are looked up, the 21st and later are not. A success resets nothing. Buckets use the injected clock and hold at most 10,000 keys each.
  • The client IP is Fastify's req.ip, the connection's peer: the server configures no trustProxy (§12 says to reuse what exists). Behind a proxy all clients share the proxy's address for the failed-auth limit; HUMAN-TODO says so.
  • Token names. "Unique among the repository's active tokens": the cap and the name rule count tokens that are neither revoked nor expired. An expired, unrevoked token with the same name is revoked (system, reason expired) by the create that reuses its name, because the partial unique index covers unrevoked rows. create locks the repository row, so two concurrent creates cannot both take the last slot. An ambiguous --repo (two active rows with the name) is refused. --reason follows the column (1 to 200 printable characters), --actor the mode set rule.
  • mode show prints mcp tokens N active (newest used …) inside each repository's block ((never used) when no active token was used), and, when this shell has GRAFT_MCP=off, the note after it. JSON output is unchanged.
  • Doctor checks mcp_tokens_expiring and mcp_tokens_unused count active tokens of active repositories; both are WARN at most. I-DOC-1 and I-DOC-3 count 21 checks.
  • get_status. The card is the one the PR shows (latestPublishedCard), not the newest row; the verdict is the newest by facts_read_at, evaluated_at, then updated_at; the MCP values are those of the report for change_provenance.head_sha; conflicts are field names in order; approvals are the stored current and stale; breakGlass is applied (enforce) or would_bypass (report) when the verdict's enforced reason is break_glass. A mode is { effective, reason }, the reason followed by the missing permission when there is one (permission_missing pull_requests:write), as mcp_write_off's detail.
  • get_policy maps a policy error's location to path and keeps line when known; warnings are returned in canonical order. base that fails the D17 name rule, or a branch the API does not have, is base_not_found.
  • report_provenance. Fields are validated before the PR is looked up; the detail of invalid_argument is the argument's name (agent, model, task, sessionUrl). pr_closed (state closed or merged) is checked before stale_head. agreement is pending when no trailers were computed for that head yet. An identical repeat recomputes the agreement and enqueues nothing; a new row enqueues provenance.refresh with the singleton key prov-mcp:<row id>. The comment line omits model and task when they were not reported; the session URL is shown only in get_status (the spec's line has no session).
  • open_change. draft is always sent (default false), so the body is exactly the §7 keys; the title is trimmed; trailing whitespace of the body is dropped before the trailer block, and no block is added when no provenance value is valid. A PR found by the lookup (before the create, or after a 422) is returned with existing: true; when a bot authored it, an mcp_changes row is written for it too (ON CONFLICT DO NOTHING), so a PR Graft opened whose row was lost to a crash after pulls.create still gets D19 on the retry (commit security review). Marking another bot's PR only makes its approvals stricter; a person's PR is never marked. (Superseded by review 1, finding 5: only Graft's own bot's PR is adopted.) A mutation guard refusal other than mode_off is internal.
  • D19. listCommitLogins (src/modules/policy/facts.ts) reads up to three pages of 100 and keeps logins only; a null committer is fine, a missing author login is not. "Cannot tell" passes excludedLogins: "everyone": no approval counts (current and stale 0) and truncated is set, which enforce mode treats as unmet. The mcp_changes lookup is a query in the policy job (the policy module does not import the MCP module).
  • D12 is revokeTokensOnTransfer in src/modules/installations/store.ts, called first in upsertRepositories' loop: the installations module does not import the MCP module either. A rename within the installation keeps the tokens.
  • Imports. src/github/mutation-guard.ts takes validBranchName from the pure src/mcp/schemas.ts. src/bin/graft-ops.ts imports src/modules/mcp/cli.ts directly (as it does modules/modes/cli.ts), so the ops CLI does not load the SDK.
  • N-14 reads "no feature client of any kind" as: none was created for the open_change call, and across the MCP scenario no mcp or guard client; the report's provenance refresh signals the policy job, which builds its policy client for every evaluation since step 2.

Deviations from the spec

  • D13 and §8: the stricter of two verdicts. D13 says an unknown author "can only add matches to require and block rules: it tightens or changes nothing". It misses the policy's default, which applies only when no rule matches. Counterexample (U-PMM-3b): default: require { humans: 1, team: security } and a rule match: { agent: [codex] } → require: { humans: 1 }. With trailers saying claude-code no rule matches and the default asks for a security reviewer; with the author unknown the codex rule matches (uncertain) and asks for anyone: looser. The property §8 requires therefore does not hold for evaluatePolicy(policy, factsWithMcp) alone (U-PMM-3 counts such generated cases). Fix: buildFacts is as specified (U-PMM-2), and when mcp_report = 'disagrees' the policy job evaluates with the unknown author and with the trailers' author and keeps the stricter (evaluateWithReport, stricterVerdict in src/policy/evaluate.ts): a higher outcome wins, and two would_require verdicts merge their constraints (maximum humans per team set, union of rules), so the result requires everything either requires. U-PMM-3 tests the property on that function.
  • D20 and §7: schema failures are tool errors (T1 d). An unknown key or an out-of-range PR number is answered by the SDK as an isError result whose text starts with Input validation error, not as JSON-RPC -32602; the tool never runs. Graft does not wrap the SDK's validation. U-MCPS-1 tests the schemas directly; I-MCP-5 the SDK's answer.
  • N-15 restates N-8 for max over the whole run: the number of phase1 requests in the fake's log equals the number of allowed guard and mcp gate answers, and every POST …/pulls is a graft-revert/ head or the MCP head.

Other test changes: the migration step-down tests in db, modes, policy-enforce, break-glass, guard, guard-revert and pilot-ops (and the pilot-ops "one migration behind" test) step through 0014_mcp; I-REV-1's "a new status blocks the rollback" first rolls back 0014. I-DB-1 counts 27 tables and I-DB-3 inserts one mcp_tokens and one mcp_changes row; I-PURGE-1 seeds and counts both tables; I-DOC-1 lists the two new checks and the JSON forms count 21; I-MODE-5's block ends with mcp tokens 0 active.

Mutation checks (§16), run by the developer. Each mutation was applied alone by a script, the named test files were run against a scratch database (graft_test_s6m), then the file was restored. All were caught:

Mutation (as applied) Failing tests
The secret placed in AuthInfo.token (authorizeToken returns { ...info, token }) I-MCP-16
Token stored in clear Not applicable as such: the token_hash CHECK (^[0-9a-f]{64}$) refuses the insert, so create fails (I-MCP-17); U-MCPT-1 pins the hash of the whole string
Revocation cached (a per-process Map in front of the lookup) I-MCP-3, I-MCP-7, I-MCP-15, I-MCP-17
repository argument trusted (D8 check removed) I-MCP-4
open_change skips the early mode read I-MCP-9, N-14 [default]
mcp body rule removed U-MG-MCP-1, U-MG-MCP-2, U-MG-MCP-3
A disagreeing report leaves the author fact as the trailers say (buildFacts ignores mcp_report) U-PMM-2, I-MCP-8
A disagreeing report replaces the agent with the reported one (the job stores the reported agent and none) I-MCP-8. U-PMM-3 cannot see it: the report's values never reach the facts by construction, the mutation has to live in the job
A second report for the same head overwrites the first I-MCP-8
Commit authors of an MCP-opened PR can approve it (excludedLogins ignored) U-APP-MCP-1, I-MCP-14
A null commit author treated as nobody to exclude I-MCP-14
Hourly open cap counted in memory (per process) I-MCP-12 (two server instances), I-MCP-13
Tokens kept active across a transfer (D12 call removed) I-MCP-15
Arguments logged (the mcp call line gains args) I-MCP-16
No stricter merge (the verdict with the unknown author alone) U-PMM-3, U-PMM-3b
report_provenance skips the head check I-MCP-8
open_change sends maintainer_can_modify: true I-MCP-11, I-MCP-12, I-MCP-13 (the mutation guard refuses it)
An adopted bot PR is not recorded in mcp_changes I-MCP-11

Residual risks raised by the commit security review, left for the step 7 security review (both follow the spec's decisions; neither loosens report mode):

  • D9 (b) behind a proxy is a shared lockout. With no trustProxy, req.ip is the proxy for every client, so 20 bad tokens from anyone lock every MCP client out for the rest of the minute (429). Keying on the token's shape would not help (random well-shaped tokens are free). Options for step 7: trustProxy for the known hops (HUMAN-TODO), or a per-IP limit only when the peer is not the configured proxy.
  • D19 trusts git commit authors. The excluded logins come from GitHub's mapping of commit emails to users, which the pusher chooses: someone can push commits whose author is another user and then approve the MCP-opened PR themselves. GitHub's API does not say who pushed a branch. Options for step 7: require verified (signed) commits on MCP-opened PRs, or tie a token to a responsible login that is always excluded.

Verification. pnpm lint, pnpm typecheck, pnpm build and pnpm eval:ci (exit 0, matchBaseline: 1) pass; pnpm test passes (106 files, 1,224 tests) against TEST_DATABASE_URL=…/graft_test_s6. The DoD greps of §16 find nothing (the only feature: "mcp" is in src/modules/mcp/tools/open-change.ts), and 47 test lines carry the §14 IDs. On a scratch database graft_s6_dod: migrate applied 0001..0014, rollback rolled back only 0014_mcp, migrate re-applied it; the database was dropped. pnpm db:up was not run: the shared scionhub-postgres-1 container on port 55432 was reused. Not run: the manual smoke test of §16 (HUMAN-TODO), and the T1 checks against real clients and real GitHub.

Review 1 fixes

Finding → fix (review: docs/phase-1/reviews/step-6-review-1.md, CHANGES REQUESTED post-merge, 2 required, 3 recommended, 2 minors, 3 nits). Report mode is unchanged: no fix adds a request or a client before the D16 mode read, and the claim of finding 7 runs after it.

  1. (required) The D13 merge in the policy job had no test above the unit level → fixed. I-MCP-8b runs U-PMM-3b's policy (default: require { humans: 1, team: security }, a rule match: { agent: [codex] } → require: { humans: 1 }) through the provenance and policy jobs after a disagreeing report naming codex: the stored verdict still requires the default's team reviewer (teamCount: 1, usedDefault: true) and adds the codex rule, matched uncertain. Kills X23.
  2. (required) The hash lookup and report_provenance's scoping were unpinned → fixed. I-MCP-3 sends a token with a valid token's graft_mcp_ and 8-character prefix and one later character changed: the same 401 (X7). I-MCP-4 calls report_provenance with B's token, repository: B, and a PR number that exists only in A, with A's head: not_found, no mcp row, no provenance.refresh (X18).
  3. (recommended) D10 was tested only with errors that carry nothing → fixed. I-MCP-16 sends an mcp-protocol-version header holding the token, which the SDK echoes in the error it passes to onerror: the mcp sdk error line holds graft_mcp_[redacted] only (X64). A get_policy whose argument holds a sentinel fails with an Octokit-shaped error (the token in its message, a PR title and body in request.body), thrown by a test Kysely plugin on the modes read: the result is internal, there is one mcp tool failed line, and neither the token, the argument nor the body sentinels are logged (X63, and its variant that logs the raw error without the arguments).
  4. (recommended) Two D19 rules had no test → fixed. I-MCP-14: a commit authored by alice and committed by carol, where carol's approval does not count and bob's does (X66); pulls.get says 260 commits and the listing serves 250: no approval counts, truncated (X69).
  5. (recommended) open_change adopted any bot's PR → fixed as the review proposes. findOpenPull marks a PR byGraft only when its author is a Bot whose login equals <GITHUB_APP_SLUG>[bot] (case-insensitive, as the intent job builds appBotLogin); adopt records only those. Without the slug nothing is adopted, so a PR Graft opened whose row was lost is returned with existing: true but gets no D19 exclusion: HUMAN-TODO now asks the operator to set GITHUB_APP_SLUG before any repository turns mcp_write on, and docs/configuration.md says why. I-MCP-11: a renovate[bot] PR is returned existing: true and not recorded; a server without the slug does not restore a lost row.
  6. (minor) Nine more rules had no test → fixed, one test each:
  7. X5, X6 I-MCP-3: the installation deleted, then suspended: 401, same header and bytes.
  8. X14, X15 I-MCP-6: Origin: "" and Origin: null → 403, no token lookup.
  9. X57 I-MCP-7: while 127.0.0.1 is blocked, a request from 10.0.0.2 (Fastify inject with remoteAddress) is served.
  10. X55, X58 I-MCP-7: from 10.0.0.3, ten malformed headers and nine unknown tokens (all 401), one good call (200), then the 20th failure is 401 and the 21st 429.
  11. X28 I-MCP-8: a repeat that changes only model is already_reported.
  12. X44 I-MCP-12: an existing branch graft-revert/x as base is base_not_found, with no mcp client.
  13. X70 I-MCP-14: an mcp_changes row for the same PR number in repository B excludes nobody in A (alice's approval counts until A's own row exists).
  14. (minor) The hourly cap could be exceeded by concurrent calls → fixed with a claim under a lock (the review's first option, the step 5 pattern). claimOpenSlot (src/modules/mcp/store.ts) runs one short transaction that locks the repository row (SELECT … FOR UPDATE, as createTokenRow does), counts the rolling hour, and inserts a claim: an mcp_changes row with pr_number and head_sha null. Every process counts it, so D9 © is still "counted from mcp_changes rows". No GitHub call runs inside the lock. After pulls.create, settleOpenClaim deletes the claim and inserts the PR's row (ON CONFLICT DO NOTHING, for a concurrent call that adopted the new PR first), in one transaction; when the create fails (any error, the mcp client's creation included), the claim is deleted before the error is mapped, so a failed open does not use a slot. A claim left by a crash between the two holds its slot for an hour (fail closed), then the next claim deletes it. Migration 0015_mcp_open_claims drops NOT NULL from both columns and adds CHECK ((pr_number IS NULL) = (head_sha IS NULL)); its down deletes claims and restores NOT NULL. A claim never matches a PR number, so get_status, D19 and the purge are unchanged. I-MCP-12b: with nine opens in the hour, a call held at its create (the fake's block) keeps the tenth slot and a concurrent call is rate_limited (one POST …/pulls); a create answered 422 with no PR to adopt is github_422 and gives its slot back; a stale claim is dropped; five parallel claimOpenSlot for one free slot, one wins. I-MCP-1 covers 0015 (a half-null row is refused; down drops claims). The step-down tests in db, modes, policy-enforce, break-glass, guard, guard-revert and pilot-ops step through 0015_mcp_open_claims first.
  15. (nit) report_provenance is advertised as readOnlyHint: true → deferred: the spec binds it. §1 lists report_provenance among the "reads" that work in report mode, and §6's server.ts row sets readOnlyHint: true "on the three reads". The review is right that its effects are not reads (it stores a row, can make a verdict stricter, republishes the check and comment section); none of them can loosen anything or reach GitHub outside Phase 0's routes, so a client that runs it unasked can only make Graft stricter. To change with a spec amendment (readOnlyHint: false, destructiveHint: false, idempotentHint: true), for review 2 or step 7.
  16. (nit) The body is parsed before authentication → deferred: D3 binds the order to a preHandler chain ("The handler runs in a preHandler chain: Origin check (D4), auth (D7), rate limit (D9)"). Moving the Origin check and the token to onRequest would make every unauthenticated request a 401 before the parser and put D9 (b) in front of it; nothing leaks today (the 413, 415 and 400 bodies carry nothing, and Fastify's JSON parser is bounded by the 64 KiB bodyLimit). For the step 7 security review, with the proxy question of the residual risks.
  17. (nit) The fallback 401 in rateLimit was not the D5 response → fixed: one unauthorized(reply) helper (status, WWW-Authenticate, body) serves authenticate and the unreachable fallback.

Mutation checks of these fixes (each applied alone by a script, test/integration/mcp.test.ts run against a throwaway database, the file restored; git status clean afterwards). Every mutation the review lists as surviving is now killed:

Mutation Result
X5: lookup ignores a deleted installation Killed: I-MCP-3
X6: lookup ignores a suspended installation Killed: I-MCP-3
X7: lookup by token_prefix Killed: I-MCP-3
X14: an empty Origin skips the check Killed: I-MCP-6
X15: Origin: null allowed Killed: I-MCP-6
X18: report_provenance reads the PR in any repository Killed: I-MCP-4
X23: the policy job drops the stricter-of-two merge Killed: I-MCP-8b
X28: D14 compares the agent only Killed: I-MCP-8
X44: base checked for existence only Killed: I-MCP-12
X55: a success resets the IP's failures (a reset added to the counter, called after a good token) Killed: I-MCP-7
X57: one failure counter for every IP Killed: I-MCP-7
X58: a malformed header not counted Killed: I-MCP-7
X63: a failing tool logs { err, args } Killed: I-MCP-16
X63b: a failing tool logs the raw error Killed: I-MCP-16
X64: the SDK onerror logs the raw error Killed: I-MCP-16
X66: committers not excluded Killed: I-MCP-14
X69: more than 250 commits not refused up front Killed: I-MCP-14
X70: the mcp_changes lookup ignores the repository Killed: I-MCP-14
Finding 5: any bot's PR adopted (byGraft = type === "Bot") Killed: I-MCP-11
Finding 7: no claim row (count, then create) Killed: I-MCP-12b
Finding 7: no repository row lock in claimOpenSlot Killed: I-MCP-12b (the five parallel claims; three runs out of three)
Finding 7: a failed create keeps its slot Killed: I-MCP-11, I-MCP-12b, I-MCP-13
Finding 7: a crashed claim never expires Killed: I-MCP-12b

Verification. pnpm lint, pnpm typecheck and pnpm build pass; pnpm test passes (106 files, 1,226 tests: I-MCP-8b and I-MCP-12b are new, the other cases extend existing tests). The shared scionhub-postgres-1 container on port 55432 was stopped by another session, so the tests and mutations ran against a throwaway postgres:18-alpine on 127.0.0.1:55447 (TEST_DATABASE_URL=…/graft_test), removed afterwards; pnpm db:up was not run. On a scratch database graft_s6fix_dod: migrate applied 0001..0015, rollback rolled back only 0015_mcp_open_claims, migrate re-applied it.

Phase 1 step 7: security review, pilots, gate

Spec: phase-1/step-7-security-pilots-gate.md. Decisions D1 to D21 are in the spec; what follows is what the spec left open, where the build differs from it, the accepted items and the residual risks. The security review is phase-1/reviews/step-7-security-review.md (verdict READY FOR PILOT ENFORCEMENT, to be signed off by a person); the runbook is pilots/phase-1-runbook.md; the gate is described in features/pilots-and-gate.md.

Choices where the spec is silent

  • D2, mode show. It still computes with the resolved ceiling (the worker's stored value when there is one, else the shell's), so I-CEIL-3's "mode show reports the worker's enforce" holds; the process-level rule applies to every process that serves or works (getEffectiveModes, mutationGate, the guard's settlement).
  • D3. writePath is applied to the raw path after the API base is removed. A GraphQL request with a query string is not the GraphQL URL any more, so it falls to classifyWrite, which refuses it too.
  • D4. The lookup uses the run's default client in failed() and a fresh default client in settleFailedRun (the installation token may be what failed). A lookup error is logged by class and treated as "not found".
  • D6. The list is passed to Fastify as one comma-joined string (proxy-addr's syntax). An entry is an IPv4 or IPv6 address (node:net isIP) with an optional prefix of at most 32 or 128; the message is entry <n> must be an IP address or a CIDR range.
  • D8. Within a commit the author is checked first (no_author), then the verification, then the committer. REQUIRE_VERIFIED_COMMITS (src/modules/policy/facts.ts) is decided by the spec, not a pending product decision (review 1, nit 8); false restores step 6's rule and reopens its residual risk 2. A commit committed by web-flow is unverified (review 1, finding 2). The line is part of the policy section of the comment and of the check summary (the section text), so the facts hash changes with it.
  • D9 (b). The purge uses the database clock (now() - interval '1 hour'), as the cap's own stale delete does, and runs before the rollup computes.
  • D10. The refusal is checked inside mode set's transaction, only when the call would change policy_mode to enforce; any other key in the same call is not written either. The doctor check reads the requested value.
  • D13. The mode is computed with modesOf on the row observe already reads for statuses:read (one query, before the lock), rather than a second getEffectiveModes. An event settled at once with GRAFT_GUARD_CONFIRM=off records it at insert.
  • D14 to D19. Reasons carry { metric, code, value, required }. Per-repository enforceSince is the applied_at date of the newest applied change to enforce. last7 is the last 7 days before --until. M2's "from at least 2 repositories" counts the repositories with measured phase1 rows (projected: with any phase1 row). The M1 span is first to last merged_at of the side's rows, in days with two decimals, plus one day (as Phase 0). M3's missedBy lists, for the measured view, a planned outcome in enforce mode too. Per-repository effective modes use resolveCeiling, like mode show (review 1, nit 9: the worker's ceiling, not §8.6's literal "D2's ceiling", the lower of the shell's and the worker's; the report describes the workers, and the shell running it never writes). Retention counts an installation created at least 30 days before --until, not deleted or suspended, with a delivery in its last 7 days.
  • D14, reason codes. The spec's list has no code for a FAIL of M2 or M3 decided by the value; m2_above_target and m3_below_target are added. M4 criterion (b) has no baseline minimum in the spec; with no baseline rows at all it is INSUFFICIENT DATA (m4_below_min_baseline), since there is nothing to compare with.
  • D20, U-DOC-3. The commands the runbooks name take their options from one table, OPS_OPTIONS in src/bin/graft-ops.ts, which the commands themselves use; parseOpsArgs checks a command line with it without the database. RUNBOOK_STAGE2 holds the stage 2 numbers and the test checks that the runbook quotes them.
  • D21. The preflight's mode check runs only for run and verify (the commands that need a running Graft). e01's commits carry Graft-Agent and Graft-Model but no Graft-Task: it runs alone, without the run issue the report scenarios create. It waits for everything Graft publishes on the first head (the standard settle wait, which also decides the LLM mode), then for each expectation. The outsider may now POST …/pulls/{n}/reviews with event: APPROVE (private mode); the actor gets an addLabel act. INV-4 allows the doctor's break_glass WARN on an enforce sandbox, where e01 applies one on purpose.
  • N-17 runs both neutral profiles a second time with the stored ceiling report (the other tests are not registered for those runs). It runs the beforeAll world, the break-glass scenario (review 1, finding 7) and the MCP scenario; the guard scenarios driven by their own its are covered by the world's guard event only. "No feature client" is read as no guard or mcp client: the policy job builds its policy client for every evaluation since step 2 (as N-14 records).
  • Tests placed differently. U-RVC-1 needs the database, so it lives in test/integration/guard-revert.test.ts; U-P1G-11 runs the ops CLI on a seeded database, so it lives in test/integration/gate-phase1.test.ts.

Deviations from the spec

  • D4: no comment when the writes began. The spec says "the comment is published as today". A published comment sets comment_id, and both runRevert (step 2 of the job) and observe's re-send (eventsAwaitingComment) skip such an event, so the comment would stop the resumption D4 exists for. In the two D4 cases (adopted, resumable) the run returns without a comment; the resumed run writes it as its last step. Only a retryable error is left resumable (review 1, finding 1): a permanent one with no PR found is settled error with the comment, as before step 7. What remains (security review, finding 10): until the next observe of the repository, an adopted PR has no label and no auto-merge, and a resumable event holds its claimed cap slot. Both fail closed.
  • docs/features/guard.md's "a revert whose writes already began is finished whatever its age" is now true after a failed last attempt as well (D4 with the step 5 review 1 stale exemption).

Accepted, no code

  • D11: the 1,000-event cap on break-glass fails closed (actor_unknown); the runbook's stage 0 requires the label-lag and Link: rel="last" measurements.
  • D12: the guard's framing boundary, re-read in the security review (Q-RV-8): a review requirement on .github/workflows/ is the team's control; auto-merged reverts only as [trivial], after stage 4 conditions.
  • Security review findings 11 (the outsider's approval route in the runner) and 12 (an equivalent mutation).

Residual risks (also in docs/features/modes.md, mcp.md and guard.md)

  • An old process that never restarts keeps its environment's ceiling until a worker publishes a lower one.
  • On a public repository with --public, 21 or more outsider change requests block the check.
  • A framing workflow already merged on the default branch can still get a revert opened; auto-merge of that revert needs the D12 conditions.
  • Agents that use open_change must sign their commits, or approvals on their PRs never count.
  • D4 in a quiet repository (finding 10), for a retryable error only (review 1, finding 1).
  • During a lowering rolling restart, an old-config worker that restarts stores enforce again until the next new worker start (review 1, finding 4); the emergency ceiling drop restores required reviewers on every enforcing repository first (finding 3).
  • An MCP-opened PR edited in the web UI, or updated with "Update branch", gets web-flow commits and no approval counts on it (review 1, finding 2), until the HUMAN-TODO real-GitHub check says otherwise.

Mutation checks (§15), run by the developer. Each mutation was applied alone by a script, the named test files were run against a throwaway database (graft_mut on 127.0.0.1:55491), and the file was restored; git status was clean afterwards. 26 of 27 are killed; the survivor is equivalent.

Mutation (as applied) Result
The gate ignores the stored ceiling (modesOf passes the process ceiling alone) Killed: I-CEIL-1, N-17
A missing service_state row read as report Killed: I-CEIL-2
The stored ceiling wins over a lower process ceiling (effectiveCeiling returns the stored value) Killed: I-CEIL-3, U-CEIL-1
writePath drops the query again Killed: U-MG-1, U-MG-21
recordPulls uses writePath (the list by head no longer recorded) Killed: U-MG-19, U-MG-22
settleFailedRun settles error after writes began (settleBegunWrites returns null) Killed: I-REV-10c, I-REV-10d
isStale measures from detected_at Killed: I-REV-10e
authenticate back in preHandler Killed: I-MCP-6b
trustProxy: true in the server Killed: I-MCP-7b
GRAFT_TRUST_PROXY accepts true (the config side of the same mutation) Killed: U-CFG-40
An unverified commit ignored (REQUIRE_VERIFIED_COMMITS = false) Killed: U-FCT-1, I-MCP-14b
The MCP PR count without pr_number IS NOT NULL Survives, equivalent: the count joins changes on pr_number, and a claim's null never matches (security review, finding 12)
The MCP PR count timed by mcp_changes.created_at Killed: I-P1G-7
The rollup purge deletes claims of any age Killed: I-ROLL-5
--public not required Killed: I-MODE-PUB-1
Observe does not store guard_mode (the confirm path) Killed: I-GRD-MODE-1
flaky with a null confirm_reason counted as a flake Killed: U-P1G-6
flaky with a null confirm_reason counted as a breakage (missed) Killed: U-P1G-6
M1 counts requirements_met as no-human Killed: U-P1G-1, I-P1G-1
M1 counts break_glass as no-human Killed: U-P1G-1
The merge-head verdict is the oldest Killed: I-P1G-3
The merge-head verdict of any head Killed: I-P1G-3
Graft revert PRs counted in M1 Killed: I-P1G-4
The M2 projection applied to enforce rows Killed: U-P1G-5
M4 without the 14-day lag Killed: I-P1G-6
The gate verdict computed from projected values Killed: I-P1G-2, U-P1G-9
INV-1E accepts a neutral graft/policy Killed: U-LIVE-ENF-2

Other test changes: the migration step-down tests in db, modes, policy-enforce, break-glass, guard, guard-revert, mcp and pilot-ops step through 0016_phase1_gate; I-DOC-1 and I-DOC-3 count 22 doctor checks (public_enforce); U-MG-1 expects a write with a query to be unknown (D3); I-MCP-2 asserts the annotations of all four tools (D7); U-LIVE-PLAN-1's plan snapshot gains e01, and U-LIVE-PLAN-2 expects the preflight's one read-only mode show --json call and plans the report sandbox's scenarios only.

Verification. pnpm lint, pnpm typecheck, pnpm build and pnpm eval:ci (exit 0, matchBaseline: 1; its run directory was removed) pass; pnpm test passes (113 files, 1,282 tests). The shared container on port 55432 was not running and the local Docker engine (OrbStack) hung once during the build and was restarted, so the tests and mutations ran against a throwaway postgres:18-alpine (graft-step7-pg) on 127.0.0.1:55491, removed afterwards; pnpm db:up was not run. On a scratch database graft_s7_dod: migrate applied 0001..0016, rollback rolled back only 0016_phase1_gate, migrate re-applied it; the database was dropped. The DoD greps of §15 find nothing, the review's verdict line is present once, and 68 test lines carry the §13 IDs. Not run: the manual smoke test of §15 and the enforce sandbox against live GitHub (HUMAN-TODO).

Review 1 fixes

Finding → fix (review: docs/phase-1/reviews/step-7-review-1.md, CHANGES REQUESTED before merge, 1 required, 3 recommended, 3 minors, 3 nits). Report mode is unchanged: no fix adds a request or a client before the mode read, and N-17 now also runs break-glass.

  1. (required) A permanent error after the revert's writes began was never settled → fixed. settleBegunWrites takes the error: a PR found by head is adopted as before; otherwise only a retryable error (on the last attempt) is left resumable, and a permanent one (422, 404, 403) returns null, so failed() and settleFailedRun settle error, write the comment and release the cap slot, as before step 7. I-REV-10f: the ref is created, POST …/pulls answers 422 on a non-last attempt: outcome error, a comment, countOpenReverts 0, and a later observe sends no guard.revert; the same through settleFailedRun with a PermanentJobError (and a retryable error on the last attempt still resumable). Security review finding 10 and Q-RV-4 corrected, new finding 13; docs/features/guard.md says it.
  2. (recommended) D8 trusted the author of any web-flow commit → fixed as the review's option 2: on an MCP-opened PR a commit whose committer is web-flow is unverified (the D8 line of the spec is kept, so the policy section shows the same unverified text). U-FCT-1 now expects unverified for a web-flow commit, and logins for an all-verified PR with real committers; its helper's default committer is no longer web-flow, so the other cases fail for their own reason. I-MCP-14b uses committer carol (bob counts, alice and carol do not) and adds one web-flow commit (no approval counts, mcpExclusion unverified). I-MCP-14's commits get real committers. This differs from spec D8 and U-FCT-1's text ("or web-flow", "web-flow left out"), as the review asks. HUMAN-TODO adds the real-GitHub contents-API check before stage 6; the runbook's stage 6 requires it; docs/features/mcp.md, docs/architecture.md, security review finding 7 and Q-MCP-7 updated, new finding 14.
  3. (recommended) The emergency ceiling drop could leave other repositories unprotected → fixed. The runbook's emergency path is split: one repository rolls back as before (the fast path); a deployment-wide ceiling drop first restores required reviewers on every repository whose repositories[].modes.policy.effective is enforce, and only then lowers the ceiling.
  4. (recommended) Three statements of the security review were wrong → fixed. Finding 10 and Q-RV-4 (the permanent-error case), Q-MD-1's second bullet and its residuals (a restarted old-config worker stores enforce again until the next new worker start), Q-MCP-7 and finding 7 (web-flow); the summary names the new findings 13 and 14. The same D2 sentence is corrected in src/modes/index.ts (effectiveCeiling) and docs/features/modes.md. The verdict line is kept.
  5. (minor) Six rules had no test → fixed. X6: an I-REV-10d variant whose PR lookup fails (500) on the last attempt, left resumable. X30: I-P1G-8 rolls the policy back to report (applied): enforceSince.policy null. X39, X40, X41: a new I-P1G-11 (a paired repository with only report-mode phase1 rows is not in the measured baseline; a caught event detected in the window but created before it counts, and a missed one the other way round does not; an installation whose last delivery is 8 days before --until is not retained). X37: I-DB-16 already failed without the refusal (Postgres's CHECK error does not match its message); it now also asserts the phase1 run is kept.
  6. (minor) The trusted-proxy docs promised more than the setting gives → fixed. docs/configuration.md and docs/features/mcp.md say to list only the proxy's own addresses, never a client network, that the proxy must append (nginx $proxy_add_x_forwarded_for) or overwrite X-Forwarded-For, and that Graft must be reachable only through the proxy; .env.example uses one address. U-CFG-40 keeps the spec's fd00::/8 as a parser case.
  7. (minor) N-17 did not run every scenario → fixed for break-glass: N-17 runs breakGlassScenario() before the MCP scenario and asserts the three audit rows in report and no success check. The guard scenarios driven by their own its are not re-run (recorded above under N-17); the world's guard event is.
  8. (nit) REQUIRE_VERIFIED_COMMITS presented as a pending decision → fixed: HUMAN-TODO marks D8 decided by the spec, and the comment in facts.ts says that turning it off reopens step 6 residual risk 2.
  9. (nit) The gate's per-repository modes use the worker's ceiling → accepted and recorded above (D14 to D19 bullet), the same choice as mode show.
  10. (nit) private defaulted to true → fixed: priv.get(id) ?? false, so missing data fails stage 2 criterion 6.

Mutation checks of these fixes (each applied alone, the named test file run against a throwaway database, the file restored; git status clean afterwards). Every surviving mutation the review lists is now killed:

Mutation Result
Finding 1: a permanent error left resumable (the isRetryable(cause) check removed) Killed: I-REV-10f (both)
X6: a failed lookup settles error (the catch returns null) Killed: I-REV-10d (lookup-failure variant)
Finding 2: a web-flow commit accepted (today's line restored) Killed: U-FCT-1, I-MCP-14b
S10: REQUIRE_VERIFIED_COMMITS = false Killed: U-FCT-1, I-MCP-14b
D8: the verified check removed Killed: U-FCT-1, I-MCP-14b
X12: a null committer accepted Killed: U-FCT-1
X30: enforceSince ignores the requested mode Killed: I-P1G-8
X37: 0016 down without the refusal Killed: I-DB-16
X37b: 0016 down deletes the phase1 runs instead Killed: I-DB-16
X39: M3 window on created_at Killed: I-P1G-11
X40: M2 measured baseline takes every paired repository Killed: I-P1G-11
X41: retention ignores the 7-day delivery window Killed: I-P1G-11

Verification. pnpm lint, pnpm typecheck and pnpm build pass; pnpm test passes (113 files, 1,286 tests: I-REV-10f (two cases), the I-REV-10d lookup-failure variant and I-P1G-11 are new, the other cases extend existing tests); pnpm eval:ci exits 0 (matchBaseline: 1; its run directory was removed). The tests and mutations ran against a throwaway postgres:18-alpine (graft-s7f1-pg) on 127.0.0.1:55481, removed afterwards; pnpm db:up was not run. On a scratch database graft_s7f1_dod: migrate applied 0001..0016, rollback rolled back only 0016_phase1_gate, migrate re-applied it. The equivalent mutations of the review (S11, S22, X31) still survive, as recorded there.

Review 2 fixes

Findings from docs/phase-1/reviews/step-7-review-2.md (APPROVED, PR #48: two minors, four nits). Report mode is unchanged; the only source change is a comment.

  • A. The orphan graft-revert/ ref is never deleted → the settleBegunWrites comment and security review finding 13 now say the ref is left in place, as before step 7: the branch is named after the event, a settled event never runs again, so no stale-branch rule reaches it. It has no PR, and a person can delete it; graft guard list shows the event as error. Review 1's own text is left as it was written.
  • B. A permanent error that finds a PR had no pin → a third I-REV-10f case: a crash after POST …/pulls, then settleFailedRun with a PermanentJobError (403): the PR is adopted (revert_opened, outcome opened), no comment, countOpenReverts 1, one POST …/pulls. R4 (the isRetryable(cause) check moved before the lookup) is now killed by it, and by no other test.
  • C. The spec no longer described the code → spec D4 (a permanent error settles error with the comment), D8 (a web-flow committer is unverified) and U-FCT-1 amended as the review drafted. No decision changes, so no new spec review.
  • D. Stale lines → the security review's summary says one minor (finding 10) and two nits (11, 12) remain; its scope and "What was checked" name the re-check after the review 1 fixes; Q-MG-5 cites guard/revert.ts:1134. The HUMAN-TODO step 6 trustProxy line points at the step 7 GRAFT_TRUST_PROXY item.
  • E. The deployment-wide emergency path depended on Graft → its step 1 takes the repositories from the stage record first, and cross-checks with gate report per installation when the database is up; one sentence says that if Graft cannot come back up, the per-repository path (removing graft/policy from the required checks) is the only way to unblock merges.
  • F. The stage 6 web-flow check → kept, as recommended rather than required: the code already fails closed, so the HUMAN-TODO item is now "before the web-flow rule is relaxed (recommended before runbook stage 6)".

Verification. pnpm lint, pnpm typecheck, pnpm test (113 files, 1,287 tests) and pnpm build pass against a throwaway postgres:18-alpine (graft-s7f-pg) on 127.0.0.1:55481, removed afterwards. R4 was applied alone and guard-revert.test.ts run: only the new I-REV-10f case fails; the file was restored.

Verifier file context and the unverifiable verdict (intent-v2)

The verifier saw only GitHub's patches, which carry three lines of context per hunk. A card that said "scrolling does nothing during a journal replay" was marked unsupported because the diff added if (state.replaying) return; but not the unchanged lines that set the flag, so the card showed "the verifier disagrees" and the risk was raised to logic for a correct card.

  • Head files, verifier only. fetchIntentInputs reads up to 20 changed source files at pull.head.sha (repos.getContent, five at a time) into ChangedFile.headText, in memory only like patch. A 404 or 403, a non-file, a file over 200 KB or one with a NUL byte leaves null; any other error is thrown, as the listing does. prepareDiff turns it into a file_context block (fileContext in diff.ts): the whole file with line numbers when it fits in 16,000 characters, else windows around the hunks and around other uses of the names on the changed lines (dotted names also by their last part, so state.replaying finds replaying: false). The writer's message is unchanged: the writer describes the change, and unchanged code would tempt it to describe old behavior.
  • No context for sensitive paths. Files a path rule matches (secrets, CI, infra, migrations, GRAFT_INTENT_SENSITIVE_PATHS and graft.yaml globs) get no context: their unchanged lines, which may hold credentials, are not sent to the model. The fetch skips the built-in rules; prepareDiff also drops the configured globs. Those files are sensitive by the floor anyway.
  • Injection scan. Unchanged context lines are not scanned: scanning them would flag any repository that documents AI reviewers (Graft's own prompts). For a file that gets context, the injection rule reads the added lines of the whole patch, not only the part shown, because the context can show the hidden end of a truncated patch. The verifier prompt counts context text for instructions_in_data only on added lines.
  • unverifiable and partial views. A claim on the hidden part of a truncated or omitted file must stay unsupported; this is a prompt rule, but a model that answers unverifiable instead gains nothing: a partial view already sets the floor to logic (partial_view), which is all a disagreement would add.
  • unverifiable does not disagree. A fourth verdict for claims that rely on code outside what was shown. It is rendered as a [!NOTE] and counted in the details line, and does not set the status to disagree, so it does not raise the risk. Treating it as a disagreement would bring back the false alarm for anything defined in another file. The hidden part of a truncated or omitted file stays unsupported: it is part of the change.
  • Cost. Up to 60,000 more characters (about 20,000 tokens) on the verifier call and up to 20 more GitHub reads per card. The context is part of inputHash and of the nonce search.
  • Versioning. PROMPT_VERSION is intent-v2; U-PROMPT-1, the eval case schema (headText is optional, so v1 cases still load; the export redacts it like a description) and the synthetic baseline (metadata only) are updated. Stored claims are JSON, so no migration. Not done: a live eval run comparing the false disagreement rate of intent-v1 and intent-v2.
  • Tests. U-FETCH-⅞, U-DIFF-13/14/15/16, U-OUT-8, U-GEN-36/37/38, U-IREN-11. contentRefs in the policy tests now counts only graft.yaml reads, so I-POLH-2/4/6 still prove the policy is read at the base only.

Intent card language (report.language, intent-v3)

Teams that review in another language asked for the card in that language.

  • Key. report.language in graft.yaml, read with sensitive_paths from the base commit (D3), so a pull request cannot change the language of its own card. A closed list of tags (en, fr, de, es, it, pt, nl, pl, sv, ja, ko, zh), each mapped to an English name in REPORT_LANGUAGES; another value is language_invalid. The prompt only ever holds a name from that list, never file text. A file without report keeps its canonical form and hash; the policy engine ignores it.
  • What is translated. Only the model-written text: the goal, behavior changes, risk reason, out-of-scope reasons and the verifier's reasons and missing changes. Headings, labels, floor reasons, check text and policy messages stay English: they are fixed strings, and translating them is separate work.
  • How. English keeps both system prompts byte for byte. Another language appends one Language section to both, telling the model to write every sentence in that language and to keep paths, JSON keys, claim ids, risk_class and verdict in English (the output parsers check them). The writer and verifier get the same language, so the verifier reads claims in the language it writes its reasons in. The language is part of inputHash, so changing it gives a new card.
  • Versioning. PROMPT_VERSION is intent-v3: the fingerprint now covers the language section. U-PROMPT-1 and the synthetic baseline (metadata only; English prompts are unchanged) are updated. Not done: a live eval in another language. The synthetic cases are English, and the risk floor's injection patterns are English, so non-English injection text is caught only by the model.
  • Tests. U-PRL-1, U-PROMPT-2, U-GEN-16 (language changes the hash), U-GEN-21, I-POLH-7.

Shared prompt cache for the writer and the verifier (intent-v4)

Production usage (21 to 25 October 2026, 117 cards) was about 86% uncached input: on the usual path both the strong writer and the verifier run on Sonnet at effort medium and each paid for the whole diff, about 36K tokens a call. Only the system prompts were cached; they were different for the two roles, and the writer's message put the title and description before the diff, so the two calls shared no cached prefix.

  • One system prompt. SYSTEM_PROMPT holds the shared trust rules and risk classes, then one section per task ("Task: write the intent card", "Task: verify the intent card"). The last line of each user message names the task. The language section is appended as before.
  • Shared start of the user message. buildSharedData renders the nonce, facts, file list and diff, ending with the blank line before the next block. Both messages start with exactly these bytes; the writer then gets title, description and issue, the verifier the file context and the card. The verifier still never sees the description: the separation is by what each request holds, which did not change.
  • One output format. The API renders output_config.format ahead of the system prompt, so with a schema per role the verifier rewrote the whole prefix instead of reading the writer's (measured live: a cold verifier call read only its own system prompt and wrote the diff again). Both calls send OUTPUT_SCHEMA, anyOf of the writer and verifier schemas; the role parsers still accept only their own shape, so an answer in the wrong shape is invalid output and retried.
  • Client. LlmRequest.userCachePrefix is a prefix of user; the client sends it as a first text block with cache_control: ephemeral and the rest as a second block. A value that is empty or not a prefix of user is a programmer error and throws.
  • Expected effect. For a diff of S tokens on Sonnet, the writer pays a 1.25× write and the verifier a 0.1× read instead of two full reads (about a third less for the diff). A retry after invalid output and the escalated writer on the trivial path read from the cache too. The fast first writer (Haiku) writes an entry nobody reads; at Haiku prices that is negligible. Caches are per model, so nothing is shared between Haiku and Sonnet.
  • Live check (6 synthetic cases). Cache reads 48.9K and writes 14.6K, against 28.7K and 27.6K with a schema per role; cost $0.063 against $0.094. Final risk was right on 6 of 6, but the verifier flagged neither of the two cases that should be flagged and flagged one that should not. One call per case cannot tell noise from a regression; quality is judged on production data (verifier disagreement rate per prompt_version).
  • Versioning. PROMPT_VERSION is intent-v4; U-PROMPT-1 and the synthetic baseline (metadata only) are updated.
  • Tests. U-LLM-20, U-GEN-39, U-PROMPT-½, U-GEN-21.

Missing behavior changes are "Also changed", not a disagreement (intent-v5)

Production audit (14 to 26 October 2026, 66 PRs with a written card, read through the operator console): the verifier disagreed on 43 cards (65%), and 37 of them only because it listed behavior changes the writer left out. Those cards carried the "Read the diff instead of relying on the card" warning and a logic floor, although their claims were supported. The missing items were often the most useful line for a reviewer (a deployment that now needs a new variable, a release that a failed test run now blocks, a service now listening on every interface). One was wrong: a flag the verifier said was never set is set in the same file, outside the diff.

  • Rule. disagree means at least one claim is unsupported or contradicted. Missing behavior changes are stored as before (verifier_missing) and rendered as an Also changed list under the behavior changes. They no longer add verifier_disagrees to the risk; the verifier's own risk class still counts in the maximum, so a missing change it rates sensitive still raises the card.
  • Check title. verifier agrees · N more changes when the list is not empty.
  • Older cards. A stored intent-v4 or earlier card with status disagree and no failing claim renders the new way (no warning, the list instead). Its stored risk is not recomputed.
  • Prompt. The verifier is told that its missing items are shown as additions to the card, and to state each as a fact the changed lines show, never as a doubt about code it was not shown.
  • Evaluation. The should-flag metric counts a card as flagged when the verifier disagrees or lists missing changes, since both now alert the reviewer. syn-022 moves from disagree to agree with an unchanged final class.
  • Versioning. PROMPT_VERSION is intent-v5; U-PROMPT-1 and the synthetic baseline are updated. Not done: a live eval run. Judge it on production data: the disagreement rate per prompt_version and the 👍/👎 votes.
  • Tests. U-GEN-6, U-IREN-1, U-IREN-12, U-PROMPT-1.

@anthropic-ai/sdk 1.x

The 1.x client changes what goes on the wire. Graft keeps its own behaviour (src/llm/anthropic.ts).

  • API key header. The SDK now sends a key as Authorization: Bearer. Graft still sends x-api-key, as the configuration documents and gateways expect. A bearer token and federation are unchanged.
  • API version. The Claude API gets the SDK's anthropic-version: 2026-10-21; its breaking changes touch nothing Graft sends. Any other base URL keeps 2023-06-01: the newer version was not tested against a gateway or cloud.
  • Tracing. The SDK now makes spans, and ANTHROPIC_OPEN_TELEMETRY_* can put prompts and answers on them. Graft turns them and the SDK's trace propagation off: tracedLlm already makes one span per call, without content (U-LLM-21).
  • Beta calls. The URL no longer carries ?beta=true; the anthropic-beta header is unchanged (U-LLM-2).