Decisions, library versions and deviations¶
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), notretryDelaySeconds(ourJobDefinition.options.retryDelaySecondsis mapped to it); retention isdeleteAfterSeconds(7 days on every queue, exceptgithub.webhookwith 1 hour since step 6; it is a per-job option,JobDefinition.options.deleteAfterSeconds);work()takes{ localConcurrency, batchSize }and a handler overJob[]; the transaction option isdbwith anexecuteSql(text, values)adapter (type exported asDb), which is whatcreatePgBossQueuebuilds 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 increateQueue. Queue options are re-applied withupdateQueueon every start, becausecreateQueuedoes nothing for an existing queue (I-Q-3). singletonKeydoes not deduplicate on pg-boss v12 standard queues. Since v10 the key is only enforced by queue policiesshort,singleton,stately,exclusive,key_strict_fifo(or together withsingletonSeconds); on ourstandardqueues it is stored and ignored.JobQueue.send(..., { singletonKey })therefore also sets a deterministic jobid(UUIDv5-style SHA-1 of job name and key;singletonJobIdinsrc/queue/queue.ts). pg-boss inserts withON CONFLICT DO NOTHING, so a second send with the same name and key inserts nothing andsendreturnsnull(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 forgithub.webhook). A caller that needs a re-run (for example acheck_run.rerequestedfor the same SHA) must use a different key, such as one that includes an attempt number or a timestamp. Anullreturn means "already enqueued". For webhooks thewebhook_deliveriesprimary key is the first line of defence; if the job send returnsnull(job exists, delivery row gone) the existing job id is stored and the outcome isduplicate.- 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 loggedtry. - Kysely 0.29 exports
Migratorfromkysely/migration. - zod 4:
z.ZodType<T>works as in the spec; config defaults are applied before validation (string form). - Fastify 5.12:
disableRequestLoggingis deprecated in favour ofLogController, whichbuildServeruses (request logging is off; the receiver logs its own outcome line). githubWebhookJobis built by a factory. The job needs the registry's handler lookup and the registry lists the job, socreateRegistrybuilds it withcreateGithubWebhookJob(registry)and exposes it asregistry.webhookJob(also present inregistry.jobs). The receiver sendsregistry.webhookJob.createPgBossQueuereturnsPgBossJobQueue(aJobQueueplus thebossinstance the worker needs) and takes asuperviseflag (false for the server, true for the worker).buildServerisasyncand returns the instance without listening.- Store functions (
getActiveRepository,listActiveRepositories, ...) take a KyselyDborTransactionas their first argument. - Extra files not in the layout:
src/bin/bootstrap.tsandsrc/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-schemasand contain no mergedpull_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/rest22 includespaginate.iterator(used for commits and comments; the iterator is stopped early after 3 and 10 pages).checks.updatetakes the check run id and nohead_sha, so the PATCH body omits it. Nothing else differed from the spec's assumptions. pg-boss 12 only marks a failed jobretryand bumpsretry_countwhen it is next fetched, so I-Q-4 asserts theretrystate, not the count. - D13 fallback (added). New optional env
GITHUB_APP_SLUG(Config.githubAppSlug). When set, a comment authored by<slug>[bot](typeBot) that starts with the marker is accepted as ours whenperformed_via_github_app.iddoes 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_atand the action. (Step 3 appended:{action}; see T18.) D6 as written would swallow any return to an earlier state within 7 days:closed/reopenedafteropened, 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 isprov:{repo}:{pr}:{head}:{base}:{bodyHash}:{pull_request.updated_at}for all five actions, andpull_request.updated_atis required in the payload schema (a payload without it enqueues nothing). A replayed body has the sameupdated_at, so replay protection is kept. The cost is one redundant, idempotent job for a title-only edit (the comment comes backunchanged, the check run gets one PATCH). - In-lock staleness check. Inside
withChangeLockthe job publishes only if the stored head SHA equals the live head and the storedpr_updated_atis not newer than the liveupdated_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_athas 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 exampleclosedthenreopened) is now closed byactionin the dedup key. The title-edit plus close case remains: a title-only edit and a close inside one second shareupdated_at, head and body, and only the action tells them apart. - Session host is plain LDH (D14 hardening).
validateSessionUrladditionally 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 andlocalhost.is rejected), because the hostname is the link text and WHATWGURLaccepts` * _ ~ ! $ & ' { } =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.
upsertManagedSectionthrowsPermanentJobError(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
upsertChangeFromPullreportsapplied: false(storedupdated_atis newer), the job logsstaleand stops before any commit fetch or publish. That is what I-PROV-3 requires; T14 does not say it. parseTrailerBlockalso returnsblockTooLong(P7 needs a way to reach theblock_too_longwarning);ProvenanceResultalso carriestruncated(the renderer needs it andcountscannot express it);persistProvenancealso takesrepositoryFullName(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>), orunknown Graft key ignored (unknown_graft_key)for an unknown key. When there are no trailers and the PR is truncated, the "noGraft-*trailers found" footer still gets the truncation sentence appended. - U-REN-7 uses the agent value
octo@bot/@team: the spec's@octo/botstarts with@, which the agent character set rejects (a separate assertion checks that it is rejected and never rendered). - I-SEC-3 posts the
installation.createdbody aspull_requesttwice: unchanged (the receiver ignores it, since the actioncreatedis not handled) and withaction: "opened"so the handler really runs and logspayload_shape_mismatch. pnpm db:rollbackreverts one migration (the latest), as T1 requires; in step 1 it rolled back everything. The test helpermigrateDownstill 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.sourcegainspr_body;changes.pr_updated_atandgraft_comment_idare optional on insert so step 1 tests compile unchanged; acontinueinstead ofreturnlets 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/sdk0.133.0,picomatch4.0.7,@types/picomatch4.0.3 (dev; picomatch ships no types). - SDK verified against
node_modules(T1). Everything the spec names exists and behaves as assumed: the constructor optionsapiKey,maxRetries,timeout,fetch(andbaseURL, used by the tests); per-request{ timeout, maxRetries };output_config: { effort, format: { type: "json_schema", schema } }on the plainmessages.create(effort islow | medium | high | xhigh | max); system text blocks withcache_control;client.beta.messages.createwithbetasandfallbacks: "default"(server-side-fallback-2026-07-01is a listed beta);usage.{input_tokens, output_tokens, cache_read_input_tokens, cache_creation_input_tokens}(the cache counters can benull);stop_reason"refusal"and"max_tokens";response.model; the error classesAPIConnectionTimeoutError,APIConnectionError,RateLimitError,InternalServerError,AuthenticationError,PermissionDeniedError,BadRequestErrorandAPIError.status. Detail the spec did not state: the beta call putsbetasinto theanthropic-betaheader and adds?beta=trueto the URL, whilefallbacksstays in the JSON body (U-LLM-2 asserts exactly that). A 529 arrives as anInternalServerError-styleAPIErrorwith status 529 and is retried by the SDK (U-LLM-10). Errors that are notAnthropicErrors 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 optionschedule: booleanexist as named.scheduleneeds the queue to exist (the queue wrapper creates all queues instart()), calling it again for the same name replaces the cron (unscheduleremoves it), and the cron expression is only validated by pg-boss atschedule()time:GRAFT_FEEDBACK_POLL_CRONis checked for shape only (5 fields of digits,*,/,,,-), so a cron that passes the shape but is invalid stops the worker at startup.JobQueue.unscheduletakes the job definition, likeschedule. - 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.stringifyof the validated writer output"; the parsed JSON is identical. - Injection rule (R15) ignores format characters. Before matching,
computeRiskFloorremoves UnicodeCfcharacters and the visible[U+XXXX]form thatneutralizeUntrustedwrites for them, soig\u200bnore previous instructionsstill counts. The spec's patterns are unchanged. - Floor reasons.
FloorReason.pathsholds 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 andcountis the number of matching texts; size and listing reasons have none andcount0 (the renderer takes line and file counts frominputs). - 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.truncatedis 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?)indiff.tstakes 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 saidsensitive.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
sensitiveis 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.
saveCardwritescreated_atandupdated_atfromctx.clock(not the database default), so the daily budget and the tests follow the injected time. intent.feedback.sweepdata is the empty object, validated strictly. The sweep reads owner and repo fromrepositories.full_name, skips removed repositories, and the poll job re-checks the installation.- Feedback summary
sinceapplies to the effective vote'sreacted_at(the vote that wins first, then the time filter). - Reactions with a
nulluser are dropped when read; reactions of any user type other thanBotcount (MannequinandOrganizationincluded). - Models in the card row are
response.modelas returned by the API (often a dated id), not the requested alias. - Pure
generate.tsexports alsoRETRYABLE(used by the store to rebuildretryablefrom a stored row) andEFFORTS,MAX_OUTPUT_TOKENS. - Test changes outside the spec's list.
test/unit/fixtures.test.tslists the newcheck_run.requested_actionfixture (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 ofopenedfor 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), becausecomputeRiskFloorreceives 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 incodeSpanfails it. New helper files:test/helpers/intent-inputs.ts(pure builders) next to the specifiedintent-scenario.ts.test/unit/log-hygiene.test.ts(U-LOG-2) is an extra grep-style test that no logger call insrc/llmorsrc/modules/intentmentions 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}inrefreshKey,WarningCodeandGraftFieldmoved tosrc/db/schema.ts(fields.tsre-exports them;grep -rn "modules/" src/db/finds nothing), I-PROV-10c isolated by clearingchanges.pr_updated_atbefore 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 fromprovenance/job.tsthe test now fails (the same holds for I-INT-9 andintent/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.tsfails I-INT-9; dropping the floor term incombineRiskfails 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 inmarkdown.tsfails 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 andsaveCardwrites one row per model run before the card upsert, so retries, re-runs, in-place regeneration of anunavailablerow and a dropped concurrentoksave all count.tokensUsedTodaysums the ledger for the UTC day (bounded on both sides), notintent_cards.created_at. The card's token columns still describe only the run that produced the row. Migration0003_intent(not yet committed) was edited in place;TABLE_NAMESnow 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 withctx.clock.now()taken right beforemarkPublished(not the job start). Reactions are attributed to the display with the greatestshown_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_atkeeps the first display only (the sweep still uses it, andpublishedCheckRunForHead);latestPublishedCard(the D11 note) follows the latest display.markPublishedtakes{ 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
sendreturned an id. The retry key ended with the triggeringdeliveryIdin 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 anAbortSignal.timeouton the SDK request, so SDK retries and their backoff end at the deadline; the abort maps totimeout. 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
fallbackblock 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 currentexternal_idis rejected (feedback_rejected). I-FB-9. - Nits fixed. Output strings made only of
Cfcharacters 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);intentRepoSettingstakes{ repositoryId, installationId, owner, repo, baseSha }for step 5 (LivePull.base.shais optional). - Nits not fixed. Paths in R15 (spec change: file names like
ai-reviewer.mdwould raise the floor on ordinary repositories). Pure rename classifiedno_patch_from_api(needsdiff.tsto 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 storedFloorReasonshape 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
saveCardfails I-INT-17, I-INT-18, I-INT-19; makingtoJobErrorreturn 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 theexternal_idguard fails I-FB-9; removing the in-lock head check inprovenance/job.tsfails 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)}, withnowMsfromctx.clock. A pending-only singleton is not available on ourstandardqueues (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 injob.tssays 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_pendingwidensintent_displays.statustook | unavailable | pending(down: deletespendingrows, restores the old CHECK). After the note's comment write, inside the same lock, the job records apendingdisplay of the previous card.attributeReactionsalready treated every non-okdisplay as a dropped one, so a reaction made while the note is shown is not credited to any card.latestPublishedCardskipspendingdisplays.markPublishedstill compares with the last display of any status, so the nextokorunavailablepublish 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
markPublishedwith anowtaken 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. 0003down (T17.4) usesDROP TABLE IF EXISTSforintent_displaysandintent_spend.escapeProse(T17.5) keeps the<!--rewrite with the "unreachable, defence in depth" comment; no behavior change.- New exports.
modules/intent/index.tsalso exportsfetchIntentInputs,promptFingerprint,maxRisk,RISK_ORDER,DOCS_GLOBS,TEST_GLOBS,globMatcherandMAX_OUTPUT_TOKENS;modules/provenance/index.tsexportscomputeProvenanceandfetchPrCommits. U-PROMPT-1 also assertspromptFingerprint()equals the pinned hash. - No new dependency. zod 4's
z.toJSONSchema(draft 2020-12, verified againstnode_modules) generates the schemas; dates and timestamps are checked with regular expressions instead offormat, so that a plain JSON Schema validator needs no format plugin. Refinements JSON Schema cannot express are listed in the case schema's top-leveldescription. - Report details the spec left open.
statusof a row isok | unavailable | skipped(a case skipped by the budget has statusskipped). Report thresholds carry aprovisionalboolean;report.passis 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 fieldsthresholdsandpass(they depend on the baseline itself) and the per-rowcachedflag; everything else must be equal. Cached rows keep the cost of the result they reuse,costUsdThisRuncounts only the rows that were not cached. A baseline that does not exist is a usage error with--checkon the synthetic set, and an explicit--baselinethat does not exist is always one. - Run options added.
RunOptions.gitis not part of the harness: the CLI fillsreport.gititself.maxTokensalso gates the pre-run estimate. Budgets and the confirmation apply to--liveonly (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 taggedsize-s|m|l|xlandpath-sensitive|tests|docs|sourceso that the report's per-tag under-classification shows the strata.--author botfilters on the list response (user.type,--agent-logins) and makes no commit request;--author anyfetches commits only to classify. Pull requests with more than 20,000 changed lines or 1,000 files are classified without a file listing (stratumsource).source.baseShafalls back to forty zeros if the API omitsbase.sha.--redactaccepts onlyemails.
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).
yaml2.9.1 (added withpnpm add yaml; it is a CommonJS package with types). Checked againstnode_modulesand by running it:parseAllDocumentsreturns an array ofDocument(zero for an empty or comment-only text, which becomesnot_a_mapping);LineCounteranderror.posgive lines and columns, butlinePosis only filled withprettyErrors: true, so the parser usesprettyErrors: falseand theLineCounter;node.rangeis[start, valueEnd, nodeEnd];uniqueKeys: truereportsDUPLICATE_KEYas an error, a tab indent isTAB_AS_INDENT, a bad indent or an open flow collection isBAD_INDENTor similar.maxAliasCountis atoJSoption, not a parse option (D6 puts it on the parser): it is passed totoJS, where0makes any alias throw "Alias resolution is disabled"; the real defence is that every anchor and alias is rejected by avisitbeforetoJSruns (U-PY-3 spies onDocument.prototype.toJS).merge: falsemakes<<an ordinary key whose*aliasvalue is still caught.!customand!!python/objectgive a warning (TAG_RESOLVE_FAILED), not an error;!!binary,!!setand even!!strresolve silently and only show innode.tag; so the parser ignoresTAG_RESOLVE_FAILEDas a warning, reports every other warning asyaml_syntax, and rejects any explicit tag (yaml_tag), a little stricter than D6's "outside the core set".logLevel: "silent"stopstoJSfrom 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" })sendsGET /git/ref/heads%2Fmain(Octokit percent-encodes the slash; GitHub accepts it; the fake API matches both forms), anddata.object.shais the commit;repos.getContentreturns an array for a directory, a base64contentfor a file,encoding: "none"above 1 MB, andtype: "symlink"/"submodule"for those. That GitHub follows a symlink to an in-repo file and reports the target'spathis taken from GitHub's documentation and not verified against a real repository (the checktype === "file" && path === "graft.yaml"is correct either way).@octokit/webhookshas types forpull_request_reviewandpush; the handlers validate with their own zodlooseObjectschemas instead, like the other handlers, and@octokit/webhooks-schemasnames the push definitionpush$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_unionis resolved by looking at whether the raw value is a list). The cross-field rules (exactly one action, non-emptymatch, approve restrictions, size bounds, unique names, glob validity, the 500-glob cap, emptyrequire) live incrossChecksand always run on the raw value instead of a zodsuperRefine: zod skips a root refinement when a sibling already has a structural error, which would hide errors. They emit the same codes.policyJsonSchema()additionally writesoneOf(exactly one action) andminProperties: 1formatch,requireandsizeinto the generated schema, so editors flag those too; the rules it still cannot express are in itsdescription.too_many_errorscounts inside the 50: 49 errors plus the marker.glob_invalidreason 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 asyaml_syntax, soparsePolicyTextnever throws. - Spec examples that the helpers do not produce. E12 as written (
Docs/A.md) would match rule 1, because*.mdmatchesA.mdwith the extension's case; the test usesDocs/A.MD. The spec's rendered examples showinfra\-and\-auth, butescapeProsedoes not escape a hyphen inside a word; the output isinfra-and-auth(byte-for-byte tests use the real helper output). The closing(code)of an error line is added afterescapeProse, so its parentheses stay literal and the underscore is escaped ((glob\_invalid)), as in the spec's example.EffectiveRisk.raisedBylists a raise only when it changed the class. - Loader.
src/policy/load.tsis the one file ofsrc/policythat importssrc/githuband the error classes ofsrc/queue/errors.ts(PermanentJobError); the CLI never imports it. U-CLI-6 checks the CLI's whole import closure, and that nothing else insrc/policyreachesmodules,db,configorqueue.loadBasePolicytakes an optionallogand also shares an in-flight request between concurrent callers.resolveBaseCommittreats a 404 asbase_missingand sends other errors throughtoJobError; a 403 readinggraft.yamlis permanent (toJobError). facts_hashis 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'sfacts_read_atandevaluated_atforward (a database write only), so an older job cannot overtake it.rules_matchedkeeps the PR paths of apathsreason (at most 5) and only the count for alabelsreason (a label also appears in the policy).- Signals. The intent job emits
intent_publishedwhenever a card is on screen after a successful publish (a new card or a cached one);test/helpers/fake-queue.tsneeded no change because unit contexts usenoSignals. - Fixtures.
pull_request.labeledclonesopenedwith ahotfixlabel; thepull_request_reviewfixtures keep upstream's slimmerpull_requestobject moved onto the fixture PR's number and head;pushis a push to the fixture PR's base branch (master) that modifiesgraft.yaml. The upstream catalog has no usablepushcommits, 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.tsnow 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 insidevalidateGlob(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 itsonLimitoption, which the callers set to the strict side (trueforsensitive_paths, tighteningpaths, the policy-file check and the risk floor's R1 to R7 path rules;falseforonly_pathsand 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 answersonLimitwhen it is spent; (3)***(three or more stars in a row) and]+are rejected withglob_invaliddetail 7, because picomatch gives them regex meanings ([ab]+repeats,a/**/***matchesa) that the segment matcher does not model; (4) the quirks that are kept on purpose: a trailing/**matches the directory itself (docs/**matchesdocs) 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 thepolicy_file_changedbuilt-in also when!listingComplete; the verdict iswould_requirewith 1 human and is neverwould_approve.policyFileChangedstaysfalse(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,filesempty); U-PE-24 is the same withoutgraft.yamlin the visible part. Arequireorblockmatch is unaffected (it already needs at least 1 human), the default already requires at least 1, and the effective risk is not raised (raisedBywould claim something unknown). - T14 empty values (minor). The
emptycontinuation 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:andcase "password":stay readable (U-RED-15 negatives). An empty value after=(password =) no longer starts it either. The eval baseline is unchanged (pnpm eval:cireports equal): the synthetic set has no such blocks. - Nits. The CLI rejects
size > 32768fromlstatbefore reading (U-CLI-7, with a 3 GB sparse file that could not be read); thepushfixture now targets the fixture PR's base (refs/heads/master) so the smoke fan-out finds the PR (U-FIX-3; the integration suite'spushEventhelper keepsmain, which is its world's base); I-POL-21 catches mutation 8 on its own (an approving policy plus a PR that editsgraft.yamlgives "Would require 1 human"); the loader's missing-blob-SHA failure is aPermanentJobError(U-LOAD-7). - Review 2 changes (step 5).
- Total work is bounded (major). Measured before: a valid 32 KB policy (132 block rules of
*+ 194a+b?*) against 1,000 renamed 1,024-character paths took about 6 minutes. Two defences. (a) A cost cap invalidateGlob: at most 48 characters other than*per segment and 96 per glob (**segments and stars are free),glob_invaliddetail 8 ("too costly"). The worst accepted glob costs about 0.37 ms per 1,024-character path, not 1.3 ms. (b) One sharedGlobBudgetof 50,000,000 work units (review 3 lowered this to 20,000,000 and made the model structural) perevaluatePolicycall and percomputeRiskFloorcall (prepareDiffhas 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 tighteningpathskey counts as matched and uncertain,sensitive_pathsraise the risk,only_pathsand approve rules do not match, and the verdict getslimits: ["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 hostilesensitive_paths) against 1,000 files with 1,024-characterpathandpreviousPathtakes about 0.5 s and endswould_blockwithbudget_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 tograft.yaml. /inside[...](minor). Rejected (glob_invaliddetail 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).onLimitsides are pinned (minor). U-PE-25 fails ifpathsorsensitive_pathsuse the loose side or ifonly_pathsuses 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: truefor those terms; the "no longer a test" term keepsfalse). U-RISK-20. path_too_long(nit). An over-long path is no longer reported as a change tograft.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) OneGlobBudgetper 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 bybuildFacts'scomputeRiskFloorandevaluatePolicyof the same policy job (evaluatePolicy(policy, facts, { budget })); when either is spent every later answer is the strict side andexhaustedis 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 inbootstrap.ts). - Measured, no network (1,000 files, 1,024-character
pathandpreviousPath, 200 rules plus 20sensitive_paths, 32 KB): literal shape about 0.19 s forevaluatePolicyand 0.42 s forcomputeRiskFloor; 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 reusinglisting_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:cireports equal), andlisting_truncatedmetrics no longer count budget stops. - Uncertain hits (nit). A
pathskey whose answer came from a limit (a path over the caps, a per-call fuel hit or a spent budget) is reported asuncertain: true; a real match staysfalse. An approve oronly_pathskey that hit a limit does not match. Reviewers can tell an assumed hit from a real one (U-PE-29). mayChangePolicyterms (nit).evaluatePolicytakes 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
pathandpreviousPath: 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 likearea3/part1/**, 7sensitive_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;pairsUsedstays as a statistic. The derivation is also in the comment onEVALUATION_FUEL. - Hostile timings after the change (1,000 files, 1,024-character
pathandpreviousPath, 200 rules + 20sensitive_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_pathswithonLimit: true) is equivalent: any limit hit already makes that key not match. M17a (pathswithonLimit: 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
GlobBudgetafter 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 forarea3/part1/**againstsrc/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 (secretsof**/secrets/**, against a per-path segment set built once, only for floating globs), required literal runs inside parts with stars (part3of*part3*, one native substring search on the folded path) and the literal tail of the last segment (.mdof**/*.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 **/*.eN6.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 endwould_blockwithbudget_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-levelstampClockstored inInt32Arrays; 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 afinally(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 longGRAFT_INTENT_SENSITIVE_PATHSglob 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 assertsmatcherScratchClean(), the matches of**/secrets/**,*.ts,infra/**anddocs/**before and after, a 100-part glob, and, as a structural guard, that the source has nostampClockor 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-jobpreparedmap (on the budget) and the backstop hook hold no fixed-width counter. - Minor: glued**rejected./**.ts,a**b,x/**y/zgiveglob_invaliddetail 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.**.tswithout 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 namedx[Ab](an attacker could otherwise name a file to evade asecret[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.labeledis now handled by the policy module, so the test sendsassignedfor 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-apply0005too), U-FIX-1's expected list, and the contexts that build aJobContextby hand (they gainedsignals). No assertion was weakened. - Not done / left open. Real GitHub behaviour is unverified (symlink path,git/refencoding, 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 asendoption. A job copies the queue'sdeletion_secondswhen it is inserted, soupdateQueuechanges only jobs created afterwards. Maintenance deletes a job whencompleted_on + deletion_secondshas passed; failed and cancelled jobs havecompleted_ontoo, so one rule covers completed and failed jobs. A job that never ran is bounded byretentionSeconds(14 days by default), which is left alone. - Table and column names used by the doctor and the purge:
<schema>.jobis a partitioned table by queue name (job_commonis the default partition; deleting from the parent reaches every queue), withname,state(enumcreated,retry,active,completed,cancelled,failed),data(jsonb),created_on,completed_on,deletion_seconds;<schema>.scheduleholdsnameandcron;<schema>.queueholdsnameanddeletion_seconds.boss.supervise(name)runs the maintenance for a queue on demand (used by I-Q-6). - Octokit:
pulls.listRequestedReviewersanswers{ users, teams };issues.listEventsForTimelineevents are normalized bynormalizeEvent(reviewedevents carrysubmitted_atandcommit_id, the otherscreated_at; a review request hasrequested_reviewerorrequested_team); the paginate iterator exposes the response headers, which is how a 10-page timeline cap is detected fromrel="next". github.webhookretention is 1 hour (the extra task).JobDefinition.optionsgaineddeleteAfterSeconds; the queue maps it throughresolveJobOptions(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 runsUPDATE <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 inintent.feedback.recorddata for 7 days). U-Q-6 pins the retention of every registered job.- Dates are strings.
src/db/client.tsnow parses the Postgresdatetype (OID 1082) toYYYY-MM-DD; the default would build aDateat local midnight. Onlyreview_time_runs.from_date,to_dateandmetrics_daily.dayare dates. CardResult.costUsdis a top-level optional field and not part ofusage: the eval harness copiesusageinto its report rows (the saved baseline would change).saveCardwritescost_usdfrom it; an absent value (a result cached before step 6) is stored asNULL. 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).effectiveVotesreads the votes of the installations and reduces them in memory with the exported purepickEffectiveVotes(thefeedbackSummaryrule), then applies the[since, until)window to the effective vote. This keeps U-GATE-3 a unit test; aDISTINCT ONquery would be equivalent.feedback_recordedcarries 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
Botare not stored; the job throws aPermanentJobErroron a 404 (the worker completes it), andsyncReviewersis called as it is bypilot sync-reviewers, which counts such a PR as skipped.getChangeByNumberwas added tomodules/changes. - Cron wiring moved from
bootstrap.tsintosrc/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_triviallooks at the card of the merge head: anokcard is preferred, the newest first, and it counts when its final class istrivial. The verdict at merge is the one of the merge head with the greatestfacts_read_at(ties: the latest created).cost_usdis the sum of the priced rows as a decimal string; rows withNULLareunpriced_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_dailyfor the window, androllup_incompleteis 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_synccounts changes with a non-author vote and nopr_reviewersrow. - Review-time choices. A review that shares the merge's second counts as before the merge (
<=formerged_without_review; timeline timestamps have one-second resolution).paused_minutesis the paused time inside[S, merge or close or now]. Onlyexcluded_authorandtimeline_truncatedrows are produced;commits_truncatedexists 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 toready_for_review, then to creation. - Doctor. Without GitHub calls, so the budget check uses
GRAFT_LLM_DAILY_TOKEN_BUDGETandintent_spend; thefeedbackcheck reports the first of its two warnings;cronswarns 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.
--confirmis 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-activeis given; a--dry-rundeletes 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 thepilot_purgesrow stores them (pluspgboss_jobs). - Globs. (1)
ALLOWEDnow accepts combining marks (\p{M}) as the spec'scafé/**example with a combining accent requires;glob_non_asciistill 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 oneOtherbucket. (3) The spec'ssensitive_paths[0]in U-PY-12 is the 0-based index; locations are 1-based everywhere (sensitive_paths[1]). (4)warnings[].line/columnpoint at the glob's own scalar. - Exact-text shortcut (picomatch 4.0.7).
lib/picomatch.jstest()setsmatch = input === globbefore running the regular expression, whereglobis the pattern as it was passed (here the normalized glob,normalizeGlob) andinputthe path unchanged: a case-sensitive comparison that ignoresnocase, with noformat(nowindowsoption).src/core/glob.tsstoresexact = normalizeGlob(glob)per compiled glob and answerstruefor 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).
validateGlobrejects (detail 2) anyDefault_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 tograft.yaml,sensitive_pathsand the env globs, which sharevalidateGlob. Deliberately not done: telling two unlisted scripts apart (Ogham and Runic share theOtherbucket and may mix); every segment that mixesOtherwith 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 apassreason (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 forAPPROVEDandCHANGES_REQUESTEDonly. Not configurable (the spec does not ask for it). Previously stored comment-only rows stay (the table is never pruned): clear them withdelete from pr_reviewers where reason = 'reviewed'and runpilot sync-reviewersif 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_associationisOWNER,MEMBERorCOLLABORATOR, its state isAPPROVED,CHANGES_REQUESTEDorDISMISSED, and the author holds triage-or-higher permission, checked like a request's (security review 1, finding 2): any member of an organisation is aMEMBERof its public repositories and aCOLLABORATORmay 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_nameisadmin,maintain,writeortriage, or the legacypermissionisadminorwrite, 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: readcovers 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
permissionForbiddenandpermissionNotFound, and the last answer per (change, user) is kept inreviewer_check_denials(ids and status; migration 0007; cleared when a later check passes; purged with the installation).pilot doctor'sfeedbackcheck 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/adminpass; a role built on triage or read fails closed) and a role namedTriageis not the built-intriage(the match is case-sensitive; I-REV-10). - Exclusions by id.
changes.author_id(filled frompulls.geton 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 andGRAFT_AGENT_LOGINSare 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 aGRAFT_AGENT_IDSsetting (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
1234alone means id 1234, not the login). A numeric login is written@1234(login-only, like@alice) andresolvewrites1234:<id>;1234:<id>is also accepted directly (U-GATE-15, I-ALLOW-1).resolvedoes not look up bare IDs to confirm their owner: check each ID with the person. - Atomic
resolvewrite.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 onlyverifiedrows, andpilot sync-reviewersre-verifies (it upserts only users who pass the checks, settingverified = 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 asnot_reviewerand the report warnsvotes_without_reviewer_sync(I-GATE-10, I-REV-9, I-DB-12). The old rows are kept as an audit trail, not deleted.pilot doctorcounts 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) andpilot allow-list resolverewrites it. ThelatestLoginrename lookup is gone (I-GATE-9, U-GATE-2, U-GATE-12 to U-GATE-15, I-ALLOW-1).resolvetakes--installation <id>because an App JWT is meant for/appendpoints only, so it borrows an installation token (public data only). The report line reads "N user IDs (sha256 ...)".
- Reviews need standing. A review makes its author a reviewer only if its
- 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 listis in the weekly ritual andincident removedeletes 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_loginand qualifies the 14 days. - Skipped nits.
votes_without_reviewer_synconly 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 withGRAFT_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 budgetexhausted); 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.
dataSpanDaysis the exact first-to-last-vote span (two decimals), and the 14-day rule isspan + 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.
DISMISSEDjoinsAPPROVEDandCHANGES_REQUESTEDinpr_reviewers(it was a real approval until a push dismissed it; I-REV-2). - Existing tests changed. U-CLI-3 (
--jsonnow also printswarnings), the registry test (two signal listeners), I-FB-3 (its cards now haveintent_displaysrows, 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-apply0006too; 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), thedecideGateand I-GATE-1 PASS expectations (apassreason), I-REV-2 (a comment-only review is not stored) and the incident tests (their culprits are seeded as merged PRs). Step 6's ownI-DB-10shares its ID with step 5's two tests (the spec reused it); its name starts withI-DB-10 0006. - Added beyond the spec.
U-Q-6andI-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.mddocuments detail 9, combining marks and the warning..env.examplelists the three new variables. - Not done / left open. Real GitHub behaviour is unverified: the shape of timeline events (
requested_team,reviewed),issues.listEventsForTimelineon pull requests with theissues: readpermission, 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--untilafter 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 theGraft-Taskissue (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 (fetchPrCommitsandcomputeProvenance, throughmodules/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; readingchange_provenanceonly for a matching head would still need a fallback. The extra cost is onepulls.listCommitscall 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 assertsintent_cards.linked_issue_number, and s07 (d) carriesGraft-Taskagain. (2) Reviewer requests.pull_request.review_requestedarrives withopened; its sync job could run before thechangesrow existed and returnedskipped, and once the reviewer reviewed GitHub no longer listed them as requested. Design choice: the job now creates the change frompulls.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 recordsrequestedonly if the PR's issue timeline holds areview_requestedevent 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 callsensureRepositorylike provenance and intent (a removed repository is skipped; an unknown one gets its row), and theprovenance_publishedsignal 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 viapr_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_publishedenqueues one sync per change; the listener is nowonChangeSignal). 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>/platformis in the policy section, and no@...platformmention 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 theappandprobeclients only, and only for the run's installation. Every other non-GET of theprobeclient 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 thegh[pousr]_,github_pat_,sk-ant-, JWT, PEM and smee patterns are as specified. - Installation scope (review 1, finding 1). The preflight of
run,verifyandsetuprefuses (exit 3, checkinstallation_scope) unless the App's installation hasrepository_selection: "selected"andGET /installation/repositories(installation token) lists exactly the sandbox, by id and name; a protected repository or asourcein 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 branchesgraft-e2e/<runId>/...and move or delete them (in public mode: the same on its verified fork, plusmerge-upstream). Writes are sent withredirect: "manual"and any 3xx answer is aGuardRefusal; the preflight requires the repository to answer under the sandbox's own name (sandbox_renamedotherwise, also insetup) and pins its id,setupchecks that the created repository is the sandbox before pushing and closes repository creation in afinally, andopenPrchecksbase.repo.idagainst it. - HUMAN-TODO ticking (review 1, finding 4).
--update-human-todoticks 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-outputsneeds 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=1andGIT_TERMINAL_PROMPT=0; clone and push resetcredential.helper; the push authenticates through aGIT_ASKPASSscript 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 thefull_nameGitHub returned for the created repository. Children start fromchildEnv(src/e2e/child-env.ts): noGRAFT_E2E_*variable, and forgitno inheritedGIT_*variable at all (GIT_CONFIG_COUNT,GIT_ASKPASS, ... could inject configuration or credentials). --only-offlineruns the live variant only unless--llm noneis given, redacts the child's output and passes it only the three offline variables. A plainpnpm testalso 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.openeddeliveries andgithub.webhookjobs 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*/15feedback sweep fired and sent oneintent.feedback.pollfor PR 1's change, and that job carries the installation id, sojobsSincemoved. Reproduced locally withGRAFT_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 outintent.feedback.poll,installations.refresh_permissions(the daily fan-out) andpilot.reviewers.syncsent under the vote keyrev-sync:(a poll that records a vote sends it). The window and the rest of the fingerprint are unchanged; apolicy.fanoutfrommodes.applystill counts, as no mode changes during a run.jobsSinceis now a list ofqueue: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; removingintent.feedback.pollfrom the list fails it. - I-E2E-1 no longer forbids every GitHub call (same PR). Since Phase 1 step 1,
installation.createdalso queuesinstallations.refresh_permissions, whose job callsasApp(); on CI the worker sometimes ran it before the test'scalls: 0assertion.forbiddenGitHub()now also countsinstallationCalls. 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). E2eDepsadditions: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.GitPusheris 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.
runandverifyneed Graft running (installation rows,readyz, no stale queued job,graft.yamlequal to the starter);setupchecks the database and migrations but not the App, the marker or the policy before it acts;cleanupneeds 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,ghfailing) is exit 2, as U-LIVE-SEC-3 asks; a token that exists but failsGET /useris exit 3. - Cleanup also lists
git/matching-refsunderheads/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.
createFakeGitHubApigainsowner,repo, per-issue comments,completed_aton check runs, paged comments and check runs, and response URLs. The world supportsbase_treeingit/trees(the spec said full trees only; the runner usesbase_treeas the real API allows) and a minimal line diff (common prefix and suffix trimmed). Webhook review payloads spellstatein 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.jsonalso holds the evaluated assumptions soreportre-renders without a network;verifyappends a syntheticverifyscenario 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_URLpoints 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_TOKENsendsAuthorization: Bearerinstead ofx-api-key; at most one of the two may be set. The client passesnullfor every credential and base URL it is not given, so the SDK never falls back to readingANTHROPIC_*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_IDinsrc/llm/types.ts) is shared bysrc/configandsrc/eval/env.ts. Such IDs have no entry insrc/llm/pricing.ts: the service records the run as unpriced (costUsdnull), andpnpm eval --liverefuses until a price is added. - Server-side refusal fallback on the Claude API only. The
server-side-fallback-2026-07-01beta exists on the Claude API alone, soGRAFT_LLM_REFUSAL_FALLBACKis ignored whenANTHROPIC_BASE_URLis set to any host other thanapi.anthropic.com(isClaudeApi, U-LLM-14). - Client-side refusal fallback.
GRAFT_LLM_REFUSAL_FALLBACK_MODEL(off by default, so nothing changes without it): onrefusal,callValidatedrepeats the call once on that model, unless the client reports through the new optionalLlmClient.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
classifyFilealready leaves lockfiles, binaries andGENERATED_GLOBSpaths (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 tologic(R13partial_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_IDandANTHROPIC_IDENTITY_TOKEN_FILE(plus the optionalANTHROPIC_WORKSPACE_ID) are validated by Graft (src/llm/federation.ts, shared bysrc/configandsrc/eval/env.ts) and passed to the SDK ascredentials: oidcFederationProvider({ identityTokenProvider: identityTokenFromFile(path), ... }). The SDK's own environment resolution (federation variables,ANTHROPIC_PROFILE,~/.config/anthropic) is never used:apiKeyandauthTokenstaynull, andcredentialsis 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_KEYcannot 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(defaulthttps://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
jtiare 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(anAnthropicError, not anAPIError) from inside the request, before any HTTP call, andAnthropicErrorfor an unreadable token file;classifywould have rethrown both as programmer errors. A wrapper maps them toFederationErrorwith a failure: 400, 401, 403, a missingaccess_tokenand an unreadable or empty file areauth; 429 israte_limited; 5xx and a network failure (detected in the wrappedfetch, not from the message) areunavailable(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 redactsanthropicFederation,organizationId,serviceAccountId,identityTokenFile,identityToken,assertionandaccess_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)inhook.before("request")returns the expandedmethodandurl(full URL, base included) foroctokit.rest.checks.create, foroctokit.request("PATCH /repos/{owner}/{repo}/check-runs/{check_run_id}", …)and foroctokit.paginate(octokit.rest.pulls.list, …). It does not return abaseUrl; the guard readsoptions.baseUrland strips it (a GitHub Enterprise…/api/v3prefix) before matching.options.urlin the hook is the route template forrest.*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/xbecomesheads%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 withrest.git.deleteRef({ ref }). - (b) The installation-token request does pass through the installation client's
hook.before:POST /app/installations/{id}/access_tokensis seen by the hook (once per client use, lazily, after the caller's own before-hooks), andasApp().request("POST /app/installations/…")passes it too. So theauthrow is reachable and exercised by every write. - © A throw in
hook.beforerejects 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 })), somodes.applysends itspolicy.fanoutjobs in the transaction that claims themode_changesrows and marks them applied. A rollback sends nothing; a repeated run cannot happen for the same rows. mode setoutput. When nothing changes it printsno changeand nothing else. After a change it prints theshowblock, then onenote: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 isunknown or removed repositoryon stderr, exit 1, forshow,setandhistory.--jsonprintspermissions: {}when they were never read (permissionsReadAtis thennull), and the text line sayspermissions not read.pilot doctoris per installation, so the two new checks (appended aftercrons, always WARN, never FAIL) count for the installation being examined:permissionsis a WARN when its permissions were not read in the last 48 hours;modesis a WARN when a requested mode is not effective (counted by reason).modesuses the worker's ceiling fromservice_statewhen 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 anallinstall 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
renderPolicyDetailsreturns a string and nevernull. Two Phase 0 render assertions changed accordingly (U-PR-1 gains the line, U-PR-2 expects the line where it expectednull). PolicyView.modeis 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 carriesceilingAt(epoch ms of the change, null for amode_change) and the key ispolicy:mode:<repo>:<pr>:ceiling-<ceilingAt>.modes.ceiling_fanouttakes{ at }for the same reason. - The factory's
gateis optional and defaults to a gate that allows no Phase 1 write. The spec says the factory "gainsgate" and callers pass one.src/e2emay 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 realmutationGate(db, config)and a logger for refusals;graft-ops.tsandeval/export.tspass the refuse-all gate explicitly. - One route is added to the table:
POST /app/hook/deliveries/{n}/attempts, classauth. 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 classauthis not tied to an installation. installations.refresh_permissionslives insrc/modules/modes/permissions.ts, notjobs.ts: the installation handler enqueues it and the modes jobs import the policy job, which imports the installations module, so keeping it injobs.tswould 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
reportceiling the effective mode cannot change, so the mode line cannot change either; the suite asserts that the line staysreportand that the extramodes.applypublishes nothing. Under themaxprofile the repository starts atenforce, 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.mockofrenderPolicyDetails) because in step 1 the mode line is part of the rendered details, which are already in the facts hash: without the freeze, droppingpolicyModefrom 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).
- Octokit outside the factory →
buildExportClient --auth tokennow buildsmakeGetOnly(forToken(...)); the DoD grep is empty without an exemption. - Ceiling fan-out lost on a failed enqueue →
casServiceStatetakes aninTxcallback that runs in the same transaction;publishModeCeilingenqueuesmodes.ceiling_fanoutthere (queue.send(..., { tx })). If the send throws, the stored ceiling rolls back and the next start fans out (I-MODE-7, new case). - Unknown permission level failed open →
effectiveModestreats a level that is not an own key ofLEVELas missing (permission_missing); U-MODE-8 covers unknown strings,toString, numbers, null and non-object permissions. - Guard ignored the host → a write whose parsed URL does not start with
${baseUrl}/is refusedunknown_route; the fallback branch is gone (U-MG-9). - Redelivery route passed for every client → new class
app(route table kind andWriteClass): it passes only wheninstallationId === null; installation clients getunknown_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. - 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.
- Phase 1 route on the App client → refused
app_client(U-MG-7 now expects it) before the feature check. refuseAllGatereadsrepository_unknown→ commented: the reason union is fixed by the spec; it means "no gate wired in".routeTemplatekept 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).mode set --repoambiguity → 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).
- Per-request
baseUrlbypassed the host check -> the guard takes the factory's configured base URL (baseUrloption, trailing slashes trimmed) instead of reading it from the request options. A write whose per-requestbaseUrldiffers, or whose resolved URL is not under the configured one, is refusedunknown_route(U-MG-9b). - Trailing slash in
GITHUB_API_URLrefused every write ->loadConfigstrips trailing slashes fromgithubApiUrl(U-CFG-1b). - Follow-up (nit): the ceiling send without
txcan survive a mutation. Harmless: it runs before the commit, so the fan-out is only enqueued early. Left as is. - 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"). Foroctokit.rest.checks.create,octokit.rest.checks.updateandoctokit.request("PATCH /repos/{owner}/{repo}/check-runs/{check_run_id}", …)(template or literal URL),status,conclusionandnameare top-level keys of the hook'soptions, next toowner,repoand the URL parameters; they are not nested. But a caller may passdata, and then Octokit sendsdataas the body and ignores the other parameters:request("POST …/check-runs", { data: { conclusion: "success" } })has no top-levelconclusion, and{ conclusion: "success", data: { conclusion: "neutral" } }sendsneutral. Readingoptions.*as the spec says would therefore both miss a non-neutral body and refuse a neutral one. Deviation: the guard readsoctokit.request.endpoint.parse(options).body, which is exactly the body sent (a plain object for every JSON call, afterdatasubstitution and URL-parameter removal). A body that is not a plain object (a string, an array, a class instance) is refusedunknown_route, never assumed neutral (U-MG-13, U-MG-17). A key whose value isundefinedis 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 organizationmemberspermission ("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 asmaintainer), 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 onlystate: "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 withstateotherwise. 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) carriesaction,scope: "team",member,team,organization,senderand, for an App,installation: { id, node_id };team(created,deleted,edited,added_to_repository,removed_from_repository) carriesaction,team,organization,sender, sometimesrepository, andinstallation. The handlers' zod schema readsinstallation.idonly (test/fixtures/webhooks/membership.added.jsonandteam.deleted.jsonare built from the package's examples and validate against@octokit/webhooks-schemas, U-FIX-1).
Choices where the spec is silent
ApproverFactsandUnverifiedlive insrc/policy/enforce.ts(re-exported bysrc/modules/policy/approvals.ts): the spec puts them inapprovals.ts, but the pureenforce.tsneeds them and may not importmodules.ConstraintStatus.approvedCountis added:approvedByis cut to 10 for display (§6) while the storedapproved: nandmetneed 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_limitas 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 ascheck_limit;resolveApproversalways fills every named team, so this only matters for hand-built facts. enforcedConclusionwithapprovers: nullon a valid policy concludesapprovals_missing(nothing could be verified); the job never passes null there.- The card wait is computed with the job's clock.
headFirstEvaluatedAtisMIN(policy_verdicts.created_at)for (change, head), andupsertVerdictnow setscreated_atfrom the job's clock on insert (the database default wasnow()), so the window is measured on one clock (I-ENF-8 uses an injected clock). Thecard_waitjob is sent after the lock, in every mode, withstartAfterSeconds= seconds left (at least 1) and singletonpolicy: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 provisionalsuffix. Several unmet constraints readNeeds 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 shownote is printed indented inside the repository block.pilot doctorgains a 13th check,teams(OK or WARN), aftermodes; the Phase 0 and step 1 doctor tests now expect thirteen checks.- Team fan-out.
policy.team_fanoutlives in the policy module (team-fanout.ts) and is registered throughmodules/policy/index.ts, sosrc/app/registry.tsneeds no new line (the registry lists modules, not jobs). Each re-evaluation it sends is keyedpolicy:team:<repo>:<pr>:<window>, wherewindowis the fan-out's own 5-minute window from its payload (review 1, finding 1). hasMembersRead(thememberslevel isreador above, never-read permissions count as missing) is insrc/modes/index.ts, shared by the approvals,mode showand the doctor.- The neutral suite's
drainignores 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 postingmembership.added, and transfers the repository away and back at the end, followed by onemodes.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
publishedhash term. With the rendering frozen, a mode flip changes bothpolicyMode(step 1 D8) andpublishedin 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 fromjob.ts): two inputs that differ only inpublishedmust 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 (countApprovalshas 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 (
memberevent) 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).
- (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)>withstartAfterSeconds: 60is a leading-edge debounce, and our singleton is a deterministic job id that also deduplicates completed jobs (7 days): amembership.removedafter the window's fan-out had run was lost, and a PR could keepsuccessin 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 keyedpolicy: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.fanoutTeamChangenow 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. - A status-less check-run create passed the guard as neutral →
checkRunBodyKind(body, method): aPOST …/check-runsis a Phase 0 write only withstatus: "completed"andconclusion: "neutral"(GitHub creates a run without a status asqueued); anything else needs thepolicyclient and the gate. APATCHkeeps 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 throughdata; 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. - Team slugs and logins in error routes →
sanitizeError's route template replaces the segment afterteams,memberships,members,collaboratorsanduserswith:name, so a retryable team, membership or permission error logs/orgs/acme/teams/:name/memberships/:name(U-GHE-5, also throughtoJobError). - 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 (listReviewskeeps 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, oneMEMBERapprover,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. - Two fail-closed rules had no test → I-ENF-6b: a
pendingmembership 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). - Transfer race read the previous owner's modes →
ensureRepositoryreturnsother_installationfor an active row that belongs to another installation (it neither moves nor resets it). The policy job then reads the modes under areportceiling, which is what the D13 reset gives the new owner, so it never acts on the old owner'senforce: it publishesneutraland nothing is refused (I-ENF-15). This differs from the reviewer's suggestion (skip withrepository moved): a skip would leave the PR with no check for this event when the old modes were alreadyreport, because the D13 reset then writes nomode_changesrow and nothing republishes. The other callers ofensureRepositorycompare with"removed"only and keep their behaviour. - 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_statechanges step 1's ceiling model (publishModeCeiling,service_state), which is beyond step 2. Documented instead:docs/features/modes.mdand HUMAN-TODO say that loweringGRAFT_MODE_CEILINGrequires stopping every worker before the new one starts (no rolling restart). - (nit) A non-neutral PATCH could rename another run → accepted, commented in the guard: only the policy job holds a
policyclient, and it PATCHes only a run id it found asgraft/policy(its stored id, orlistForRefwithcheck_name). - (nit) A role answer with no
userpassed →collaboratorRolereturnsnonewhen 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 hasid,node_id,url,actor(a simple user:login,id,typeUserorBot;nullfor a deleted account),event(labeled,unlabeled, …),commit_id,commit_url,created_at,performed_via_github_appand, for label events,label: { name, color }. Theactorof alabeledevent is the account that added the label; a label added by an App appears as its<slug>[bot]user withtype: "Bot". - Ordering. Events are listed oldest first. The endpoint takes only
per_page(at most 100) andpage: there is nosort,directionorsince. 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 theLink: 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 withpull_requests: readfor a pull request number. Both manifests already grantissues: readandpull_requests: write, so no manifest change. The role is read withcollaboratorRole(step 2 D16; 404 for a non-collaborator). - Fakes.
test/helpers/fake-github-api.tsservesstate.issueEvents(oldest first, paginated like the other lists, 404 for an unknown issue or PR), and the fake world records alabeledevent with the acting user whenever it labels a PR.
Choices where the spec is silent
- Label setting.
GRAFT_BREAK_GLASS_LABELaccepts 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.offis matched case-insensitively (OFFdisables too), so a typo in case never turns the feature on under a strange name. Empty means the default. - Only
labeledcarries the head. The handler handles bothlabeledandunlabeled, but setsbreakGlassHeadShaonly forlabeled: 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
appliedrow 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 isignoredorstale, is shown again (no API call); otherwise nothing. - Removal on any trigger. A
removedrow is written by any evaluation that finds the label gone while anappliedrow matches the head, not only by theunlabeledtrigger, so a lost webhook is still caught. Its actor is whoever the newestunlabeledevent names, bots included; the role is not checked (actor_roleNULL). - Stale needs no read. A D4 mismatch is refused before any issue-events or role request; the
stalerow has no actor. - Ties. "Later" between two rows of the same (change, head) compares
created_at; aremovedrow with the same time as anappliedone counts as later, so an ambiguous order never keeps a bypass alive. - Dedup in the store, under the lock.
insertAuditRowchecks before inserting: no secondappliedwhile one is active,removedonly while one is active, oneignoredper (change, head, actor) and onestaleper (change, head). The partial unique indexes back it (ON CONFLICT DO NOTHING), butaudit_log_ignored_oncetreats a NULLactor_idas distinct, so the store also deduplicatesactor_unknownrows 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(triggerpr, singletonpolicy: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.breakGlassis 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_lowshows the role GitHub reported (nonefor a recycled login). The details block comes right after the mode line, before the matched rules, forapplied,ignoredandstale. graft audit list.--sincetakes a date (midnight UTC) or an ISO timestamp with a zone.--repois matched case-insensitively and includes removed repositories (the trail outlives a removal untilpilot purge); rows of several matching repository ids are merged. An unknown name isunknown repository, exit 1.[self]prints asself, a null reason is left out, an unknown actor printsunknown. The argument parsing lives ingraft-ops.tslike themodegroup;src/modules/audit/cli.tshas the query and formatting helpers.- Doctor. A fourteenth check,
break_glass(OK or WARN), countsappliedrows 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=offthe job does not resolve anything, so anappliedrow written before the switch no longer applies. - The audit module is not in the registry: it has no handler and no job (its
index.tsexports empty lists, likechanges). - Fixture.
pull_request.labeled.break-glass.jsonis a variant ofpull_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 "
breakGlassremoved fromfactsHash". 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
writeuser. A triage user alone cannot catch the mutation "writeaccepted as enough". - N-11. Under the
maxprofile the normal conclusion of the scenario's PR is itself non-neutral (failure), so "the only non-neutral conclusion issuccesson the labelled head" is checked as: everysuccesswritten during the scenario is on the labelled head, every non-neutral write went through thepolicyclient with an allowed gate answer, and the next head's conclusion is the normal one (notsuccess, notbreak_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.
- (major) The actor was not bound to the label action that queued the run → D2 amended. The
labeledhandler adds the delivery'ssender.idto the job (breakGlassActorId, a positive integer; the handler's schema readssender.idonly, and no login enters the job).readLabelEventsreturns the newest event of either kind for the label, by list position. A verification needs the newest listed event to be alabeledevent whose actor id equalsbreakGlassActorId. Anunlabelednewest 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 retryableLabelEventsBehindbefore anything is published; on the last attempt it recordsignored actor_unknownand 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 olderlabeledevent 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_unknownwith 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. - (major) Revocation drifted → D6, D8 and D9 amended.
audit_log.label_event_id(0012,bigint,> 0) holds the issue event id anappliedrow was verified from.- Every label trigger reads the events once (D12), even with an active row. The bypass stays only when its event is still the newest
labeledone and nounlabeledevent is newer, and the newest event is the delivery's user'slabeledaction (finding 1). Otherwise the job writesremoved(actor: the newestunlabeledevent after the bound one, else none), then judges the current labeller from scratch in the same run. The newappliedrow is stamped 1 ms after thatremovedrow, 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. - An
unlabeleddelivery of the label setsbreakGlassUnlabeled(a refuse-only flag): the job ends an active bypass whateverpulls.getshows 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. - A
removedrow ends everyappliedrow of the change at or before it, whatever head (activeBreakGlass,activeBreakGlassForChange,mergedUnderBreakGlass).insertAuditRowrefuses anappliedrow while any row of the change is active, and aremovedrow unless one is active for its head (the head of the bypass it ends). - Other triggers still make no read (I-BG-11 unchanged for them; the label trigger again costs one events read and no role read).
- Tests: I-BG-18 (R3-B1:
failure,removedfor maya,ignoredfor tom,mergedUnderBreakGlassfalse), I-BG-18b (the unlabel job runs after the re-label:removedfrom the flag; the handler sets the flag), I-BG-19 (R3-B2:failureon A after the force push,mergedUnderBreakGlass(A)false), I-BG-13 (aremovedrow at another head ends the bypass), I-BG-25 (another maintainer re-labels while a bypass is active:removed, thenapplied1 ms later, which holds on later triggers), I-BG-11 (a redelivery keeps the bypass with one events read). - (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
removedfor 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 theremovedrow), 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 indocs/features/policy.md). - (minor) A label-triggered verification could be dropped silently → a run that carries
breakGlassHeadShaand endsstalebefore 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), singletonpolicy: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 firstpulls.get; the run endsstale, the re-run is queued with its filters and applies). - (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 itsappliedrow and queues onepolicy:breakglass:…job, which publishessuccess. Mutation X5 (no row in that branch) fails it. - (nit) The fakes could not express findings 1 and 2 → the fake world has
DELETE /issues/{n}/labels/{name}(anunlabeledevent and the webhook), label events carry the actor's real type (the App's bot for an installation token), and the fake API hasissueEventsLag(the newest N events are not listed) andafterNext(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. - (nit) The unknown-actor dedup and the tie rule → 0012 recreates
audit_log_ignored_oncewithNULLS NOT DISTINCT(Postgres 15+), soON CONFLICT DO NOTHINGcoversactor_unknowntoo; itsupfails if duplicates exist, which the store has always prevented.downrestores 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 aremovedrow at the same instant ends a bypass: kills X4). I-BG-1 now steps down through 0012. - (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 theLink: 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.
- "A delivery without a sender id never applies" had no test → I-BG-26: a label run with
breakGlassHeadShaand nobreakGlassActorId, 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). - Two defence-in-depth guards had no test → kept, both fail closed. I-BG-27 (F2f,
!ev.unlabeledLaterinbound): 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 (removedfor maya) and is not replayed. I-BG-28 (F2g): twoappliedrows for different heads of one change in one transaction, and the store refuses the second. - The late re-send had no test → I-BG-29: the mode is set to
reportbetween the facts read and the check-run write, so the mutation gate refuses withmode_reportand the transaction rolls back. The run isstalewith no audit row, and the label run is queued again aspolicy:breakglass:<change>:<head>:<deliveryId>with its filters. Kills F4b (noresendLabelRunafter an uncommitted publish). canRetryread the definition'sretryLimit→ the worker passesincludeMetadata: trueto pg-boss and gives the handler the job's ownretryLimit, 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, socanRetrymatches 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 seesretryLimit: 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
checkspermission (read or above;writesubscribes automatically) receives thecreatedandcompletedactions ofcheck_runandcheck_suitefor every check run and suite in the repositories it is installed on, whichever app created them. Onlyrequested,rerequested(suites and runs) andrequested_action(runs) go to the App that owns the run or suite. Socheck_run.completedandcheck_suite.completedfrom GitHub Actions and other CI apps reach Graft, and the spec's fallback (observes scheduled fromguard.trackwith 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,pushandstatusare still triggers andguard.confirmre-observes at the deadline. - (b) Results.
GET /repos/{o}/{r}/commits/{ref}/check-runsanswers{ total_count, check_runs: [...] },per_pageup to 100, paginated withpage(and aLinkheader);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 requestsfilter=alland reduces the runs itself (review 2, finding B). A run carriesid,name,head_sha,status,conclusion(null until completed),completed_at,html_url,app { id, slug }andcheck_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_pageup to 100 withpage. Because that body is an object with several keys,octokit.paginatecannot page it; both reads page by hand (page1 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 asignored(review 2 fixes, below). - ©
GET /repos/{o}/{r}/commits/{sha}/pullslists 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 onmerge_commit_shaalone. Graft keeps PRs withmerged_atset andbase.refequal to the default branch. - (d) Branch hints. The
statuspayload carriessha,context,state,target_urlandbranches: [{ 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(alsocheck_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.observebyfloor(now/30 s)and starts it afterGRAFT_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 startsdelayseconds 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.trackkeyguard:track:<repo>:<before>:<after>: a replayed push is one job; another push has another pair.guard.confirmis keyed per event (one per event by construction).guard.trackdata has abranch(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_shaback from the failing commit to the nearest break (or a parent that is not stored), notseqorder 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}/pullslookups go to the newest new commits (the ones detection looks at); older ones areunresolved. A lookup that answers 404 isunresolved. Thepulls.getandupsertChangeFromPullfor a single PR are not counted. - Upsert of results. A result that has not completed (
completed_atnull: 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
truncatedentry, 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_idis set at detection for a culprit classification (also whileconfirming); it is what the change lock is taken on.guard.confirmre-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), andpilot doctorwarns after twice the window.- Comment publication is retried by every observe:
culprit_foundevents 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 atx." The window reads "2 hours", "90 minutes" or "45 seconds". - Links.
html_url(check run) andtarget_url(status) are stored only under the GitHub web root derived fromGITHUB_API_URL(https://github.com/forapi.github.com, the host root for GitHub Enterprise Server), at most 500 characters, without spaces, parentheses, angle brackets or@. guard.checkserror codes. No new code: an empty list, an empty or 201-character name, a control character or a wrong type arewrong_type; 51 itemstoo_many_items; any other keyunknown_key. Policy hashes: a file withoutguardkeeps its hash; U-PGD-1 pins the hashes of the example and every valid fixture computed with the code before this step.guard: {}andguard.checksare part of the canonical form when present.mode shownotes. The statuses note is printed whenever the stored permissions lackstatuses: read(never read counts as lacking); the detection-off note whenever this shell'sGRAFT_GUARD_DETECTIONis off. Both are indented in the repository block, after the permissions line and the teams note.- Doctor. The two new checks are
guard_statusesandguard_confirming, appended afterteams(fifteen checks now), always OK or WARN. Not-read permissions count as lackingstatuses: read. graft guard listprintsno guard eventsfor an empty list; check names are joined with,and+Nafter 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 queuedguard.confirmdirectly. 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 teamgraft.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.checksis read from the baseline, not from N (security review). An automated security review of the first build found that readinggraft.yamlat the failing commit N lets the culprit itself drop its failing check fromguard.checksand hide its breakage: a candidate must not be able to filter its own failure. Results are now stored unfiltered (ci_results.filteredstays false), and the allow-list is applied when a transition is judged, fromgraft.yamlat 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 removestestfromguard.checkswhile turningtestred 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 takes0010. 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 name0011_guardas the top migration. Since step 3 review 1 (#27) merged,0012_audit_label_eventsits on0011, 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).
- (major) The neutral suite's break-glass scenarios ran over
no_policy→ the guard scenario merges its own PR 3 (asMERGE_SHA), so PR 2 is never merged and the reopen block of57c1baeis gone;NEXT_SHAserves the same teamgraft.yamlasB2, so the default branch's tip still has the team policy when break-glass runs.breakGlassScenarionow asserts that every verdict it produced (thebreak_glassones and the next head's) haspolicy_status = "ok",policy_commit_sha = NEXT_SHA,would_requireand 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 forwould_blockonly is caught by U-BG-1 and I-BG-2/6/⅞/10/11, not by N-10/N-11, whose PR is awould_requireone; making the neutral scenario a block would mean changing step 3's scenario, which a parallel branch is editing. - A late green on the parent did not narrow an open event →
confirmOpenEventsfirst re-judges eachconfirmingevent's keys on the current line (detectTransitionat 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,candidatesandculprit_change_idas the move of I-GRD-10b does. The baseline'sguard.checksis not read again for a narrowed event (the key already passed it at the older baseline). I-GRD-10c (the reviewer's P1:ambiguousbefore,culprit_found #8now). - The
statusbranch 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 withoutmainenqueue, 9 do not. - An event undecided at its deadline was never examined again →
guard.confirmstarts at the window plus 60 seconds (clock skew between workers). A run that leaves the eventconfirmingre-sendsguard.confirmwith{ eventId, attempt: n + 1 }, keyedguard:confirm:<id>:<n + 1>, a window later, at most twice (CONFIRM_RETRIES). Each key is new, so the 7-daysingletonJobIddeduplication of completed jobs never swallows one; attempt 0 keeps the step 4 key. The last attempt settles an event that is still undecided asflakywithconfirm_reasonnull: 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:0012stays 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 settlesculprit_found), I-GRD-8c (a cancelled re-run: two re-sends, thenflaky). - A transient error inside the D17 attempt loop lost the event → a lock pass that sets a transition aside now throws a private
BaselinesMissingout 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 cachedredKeysis 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 atC3withC2as the last green). - Retention pruned a quiet repository's tip →
pruneOlderThanalso keeps each repository's newest commit (highestseq) 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). - D17's principle was narrower than the docs said → documented:
docs/features/guard.mdhas 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 forguard.checksonly. Hardening:readCheckRunskeeps 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 givingflaky_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. - Five rules had no test → X3 I-GRD-11 (a
graft/policyfailure 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 (lintred on the failing commit joins the event; the comment liststest,lint); X9 I-GRD-4 (a SHA the inline track does not reach:not_on_default_branch, nocheck-runsread, noci_resultsrow); X11 I-GRD-3 (a PR merged intoreleaseis not mapped to the commit). All five mutations re-run: each is killed by the test named. - (nit) A status link could point anywhere on github.com → a status
target_urlis kept only under<web root><owner>/<repo>/(check-runhtml_urlkeeps the web-root rule; GitHub writes it). I-GRD-11. - (nit)
filteredwas dead code →KeyResult.filteredandwhy: "filtered"are removed fromdetect.ts; the allow-list is the pureallowedByGuardChecks, whichobserve.tsuses and U-DET-12 tests. Theci_results.filteredcolumn stays (always false) to avoid a migration. - (nit) A fork PR from a branch named like the default branch costs an inline track → accepted: bounded (two
repos.get, onegit.getRefandlistCommitsper 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. - (nit) The guard's
changesrows and step 3 → forwarded to step 5: its spec must read a culprit's break-glass verdict bychange_idand 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
testturns green late on the parent: the event keeps[C2, C3]and no culprit; kills F2c, narrowing to the narrowest key), I-GRD-10e (lintjoins 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=latestcould hide the red run →readCheckRunsrequestsfilter: "all". The D4 reduction per suite and "red wins across suites" then give the right answer under either reading oflatest. The fake GitHub API now applieslatestunlessfilter=allis passed, so I-GRD-17 fails withlatest. - 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 asignoredand 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
observeafter 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
flakycould not be seen →graft guard listprintsflaky (unconfirmed)whenconfirm_reasonis null, and--jsonaddsconfirmReason. I-GRD-7 (plainflaky), 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 indocs/features/guard.md), and finding B's HUMAN-TODO sandbox items and itsworkflow_dispatchtrade-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}withoutrecursiveanswers{ sha, url, tree: [{ path, mode, type, sha, size?, url }], truncated }, wherepathis the entry's name (one level),modeone of100644,100755,040000,160000,120000andtypeone ofblob,tree,commit(a submodule).truncated: truemeans 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 astoo_large, and refuses an entry name with a/,.or..(alsotoo_large). - (b)
POST …/git/treeswithbase_tree. Documented: "If bothtree.shaandcontentare null, the file will be deleted." The documentation speaks of files only. Whethersha: nullon atype: treeentry 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 aserror/tree_mismatchbefore 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
workflowspermission. 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 theworkflowspermission ("refusing to allow a GitHub App to create or update workflow … withoutworkflowspermission"). Graft does not request it, so such a revert isneeds_human/workflow_filesbefore any write (D8), including a directory change that contains.github/workflows. - (d)
POST …/issues/{n}/labelsworks on a pull request (every PR is an issue) withissues: writeorpull_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 creategraft:revertwith a description. - (e)
enablePullRequestAutoMergetakes{ pullRequestId: ID!, mergeMethod, commitHeadline, commitBody, authorEmail, expectedHeadOid, clientMutationId }and answers{ actor, clientMutationId, pullRequest }. Errors come back as GraphQL errors (HTTP 200 witherrors, Octokit'sGraphqlResponseError):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" asenabled, any other GraphQL error asunavailable(itstypelogged), and an HTTP error like any other GitHub error.clientMutationIdis echoed (Relay convention); Graft checks the answer'spullRequest { number repository { nameWithOwner } }instead, which is what D15 asks. - (f) Workflows on a Graft PR. Events caused by the repository's
GITHUB_TOKENdo not start workflows, but events caused by a GitHub App installation token do: a revert PR opened by Graft runs the repository'spull_requestworkflows, so its required checks run. - (g)
GET …/pulls?head=<owner>:<branch>&state=allfilters by the head's owner and branch and, withstate=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.tsis pure and the definition of done forbids imports fromsrc/githubthere, but it needscodeSpan(step 4 §8). The helpers moved tosrc/core/markdown.ts(unchanged);src/github/markdown.tsre-exports them, so no other import changed. needs_humanis set in both modes. In report mode too the event's revert story ends there (the plan says a human is needed);skippedanderrorkeepculprit_found(§14). The guard comment,eventsAwaitingCommentandpublishGuardCommentacceptculprit_found,needs_human,revert_opened,revertedandrevert_closed.- Report mode stores
planned,revert_plan_paths,auto_merge_state = 'would'andauto_merge_reason(null when it would be enabled); eligibility is computed as if the PR were opened. Aneeds_humanorskippedplan stores no auto-merge state. already_revertedis checked before conflicts. Every tip entry equal tobeforeis also unequal toafter, so D7's conflict test would fire first; the plan checks "all back tobefore" 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 onlytouched_laterlists 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_cardsrow of the change at the merged head (pulls.get→head.sha), whatever its prompt version; provenance (task, session) is used only whenchange_provenance.head_shais that head. policyPathsis["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_openedplus 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
seqthan the failing commit's, and needs every remaining failing keygreenon one of them. - A merge method is the first of squash, merge, rebase that
repos.getallows; a repository that allows none counts asrepo_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, includingoff: GitHub did not enable itforunavailable. Anerrorafter 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=offwrites step 4's comment verbatim (its paragraph and the report line), as D19 says, also in enforce mode. §10'srevert_offsentence is kept in the text module;graft guard listshowsskipped: 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
revertedorrevert_closedfrom its state, notrevert_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.revertandguard.revert_closedretry 3 times; a transient GitHub error retries, and the last attempt recordserror/github_<status>.guard.revert_closedis keyedguard:revert_closed:<repo>:<pr>. reverted_atis the PR'smerged_atfrom the API, or the timeguard.trackmapped the merge commit. The doctor's 72 hours run fromrevert_claimed_at(there is no "opened at" column).guard.auto_merge_revertsparsing. A repeated item counts once (as every list ofgraft.yaml); three items aretoo_many_itemsbefore deduplication; an empty list or a scalar iswrong_type. Zod 4 also runs a list's length rule on a string value (it reads the string's length), which reportedtoo_many_itemsnext towrong_typeforauto_merge_reverts: logic;structuralIssuesnow drops a length issue at a path whose value failed the "array" type check. No existing code changes.- The fake GitHub API gives every
historycommit 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()inguard-revert.test.ts).
Deviations from the spec
- I-REV-20 allows
GET …/contents/graft.yaml. The spec's list forbids/contents/, but D16 readsguard.auto_merge_revertsandguard.checksthrough the existing policy loader, which readsgraft.yamlwithrepos.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 insrc/policy). autoMergeEligibilityreturns the risk class witheligible: true(the PR body needs it); the spec's type has{ eligible: true }only.- N-1 and N-1g are restated for
maxtoo, 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 aphase1route only when it is a guard route; N-1g [max] expects the comment's "Graft opened #N" paragraph andGraft mode: enforce.. N-2b [max] acceptsguardgate questions next topolicyones. N-5 creates agraft-revert/<uuid>ref (the §12 body rule refusesgraft-revert/n5withfeature_not_allowed) and counts only its own ref. - The existing guard tests run
guard.revertinline.guard.test.tstakes the queued jobs out of pg-boss after each observe and confirm (no worker runs there), itshistory()pointsmainat the newest commit (the plan reads the tip), and I-GRD-13 now expects the revert's writes andGraft mode: enforce.: the step 4 enforce line ("Revert PRs are not available in this version…") is gone (§10). I-GRD-16's list line gainsskipped: confirmation offand its JSON therevertkey; 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).
- (required) A
#in the route string skipped the §12 body rules →mutation-guard.tshas onenormalisedPath(query dropped, one trailing slash dropped;#,%,\or no leading/give null), used byclassifyWrite,checkRunWriteandguardBodyAllowed. A write whose URL contains#anywhere is nowunknown_route, like%and\; a fragment is never stripped.guardBodyAllowedfails closed: it returnsfalsefor 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#xvariants of the ref, pulls and labels routes, with good and bad bodies, areunknown_route;guardBodyAllowedrefuses an unknown route, a#and a%). - (required) The D9 check had no test → the fake tree writer has
quirks(test/helpers/git-trees.ts,writeTree, used byPOST …/git/treesonly):keepNullTreesignoressha: nullon atype: treeentry, as GitHub might;extrawrites entries the request did not name. The check itself is nowtreeMatchesPlan: every plan path holds itsbeforeentry (as before) anddiffTreesfrom the tip's tree to the written tree gives exactly the plan's paths, each with the tip's entry before and the plan'sbeforeafter. 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, endserror/tree_mismatchwith onePOST …/git/trees, no commit, no ref, no PR, and the comment "Graft could not open the revert (tree_mismatch)…". - D15's response check and "already enabled" had no test → the fake GraphQL handler can answer for another PR (
graphqlAnswer); "already enabled" uses the queuedgraphqlErrors. I-REV-13b: another number and another repository each giveerror/auto_merge_mismatch(one GraphQL request, no retry, the "could not finish" comment); "Pull request auto merge is already enabled" givesauto_merge_state = enabled. - A failed
guard.revertcould not run again for 7 days; a stuck claim held a cap slot → guardRevertJob.handlecatches an error that will not be retried (permanent, or the last attempt) and callssettleFailedRun: an event with no outcome getserrorwith 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 atwarn, and the job still fails.guard.revertkeeps its job row one hour (deleteAfterSeconds: 3600), not 7 days, so the deterministic singleton id of D1 expires and the nextguard.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 andcomment_iddo. This also covers a worker killed during the last attempt, which nocatchcan see.- The bounded age is
GRAFT_GUARD_REVERT_MAX_AGE_HOURS(1–168, default 24): an event whose culprit was confirmed (confirmed_at, elsedetected_at, elsecreated_at) longer ago isskipped/stalebefore the plan, in both modes. The confirmation time, not the detection, is used becauseGRAFT_GUARD_CONFIRM_SECONDSmay be 24 hours itself. An event whose writes began (revert_commit_shaorrevert_branchset) 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." - Doctor:
guard_revert_claimswarns 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. - 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 isstale; 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 iscap_reached), I-REV-22 (the claim warning), U-Q-6 (the job's retention). - Every refusal was
mode_changed→refusalClass:mode_reportandmode_offaremode_changed; any other refusal isrefused_<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). - A run resumed in report mode after a write began recorded
planned→ in report mode, an event withrevert_commit_shaorrevert_branchlooks its PR up by head with the default client (a GET), adopts it (storePr), and recordserror/mode_changedeither 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 giveserror mode_changed. Not handled: a resumed run whose plan becomesneeds_humanorskipped(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. - The GraphQL rule gated the repository of
clientMutationId, not the PR's → bound (option 1 of the review). Aguardclient records, in anafterhook, the node ids and numbers of the pull requests in its own…/pullsresponses (create, get, list), with the owner and repository of the route (at most 200 per client). The GraphQL rule requiresvariables.pullRequestIdto be one of them, with the number and repository its client mutation id names; otherwisefeature_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 byheadonly, 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). - Five rules had no test → X22 I-REV-14 (a
logiccard 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 (arevertedevent and a late webhook:settled, no API read,reverted_atunchanged); 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', returningsettledwhen nothing changed), asmarkRevertedis. A revert PR reopened afterrevert_closedstaysrevert_closedand is not counted by the cap again;pull_request.reopenedis not handled (accepted: the cap bounds Graft's own runaway, and a human who reopens the PR owns it). - (nit) Two guard routes were wider than needed → a guard client's
POST …/pullsneeds abasethat is a plain branch name ([A-Za-z0-9._/-]{1,255}, noowner: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. - (nit) The baseline fell back to the failing commit → no fallback: with no
last_green_shathe baseline is{ checks: null, autoMerge: "not_configured" }(every key counts, auto-merge off). Not reachable today (detect.tsalways sets it), so no test. - (nit) A late comment mixed the two modes → a
plannedoutcome 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 (anopenedrevert commented in report mode is alreadyerror mode_changed). - (nit) U-RVT-2's bot case → a
Botauthorci-helper(a valid mention) is a code span, and only@bobis 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.1and@modelcontextprotocol/client@2.3.1are still the npmlatesttags (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.1and, throughnode,honoand@hono/node-server; the server'szod ^4.2.0resolves to the project'szod@4.6.7(one copy).createMcpHandler(factory, { legacy, responseMode, maxRequestBodySize, onerror }),toNodeHandler(handler, { onerror, maxRequestBodySize }),legacy: "stateless",responseMode: "json"andMcpHandlerRequestOptions.authInfoexist with the meaning D2 and D3 give them. No name changed. - (b) AuthInfo.
toNodeHandlerforwardsreq.authas the handler's pass-throughauthInfo("never populated from request headers"). The factory receives it asMcpRequestContext.authInfo, and a tool callback can read it asctx.http?.authInfo. Graft reads it in the factory and closes the tools over the principal, so a tool never sees anAuthInfoat all. - © Eras. With
legacy: "stateless",GETandDELETEanswer405{"jsonrpc":"2.0","error":{"code":-32000,"message":"Method not allowed."},"id":null}. A 2025-era client (initializewith protocol2025-11-25) is served, one fresh instance per request; the SDK's legacy client also tries aGETstream afterinitializeand accepts the405. A 2026-07-28 client (versionNegotiation: { mode: { pin: "2026-07-28" } }) sends oneserver/discoverprobe and thentools/list: noinitializeround trip.responseMode: "json"shapes the modern leg only; the stateless legacy leg answers a rawPOSTthat 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-32602in 2.3.1: it is a tool result withisError: trueand the textInput 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).-32602is kept for atools/callthat is malformed itself (for example a non-stringname).outputSchemais checked on the way out:structuredContentthat does not match becomesisError"Output validation error"; anisErrorresult is not checked against it. See the deviations. - (e) Client.
new StreamableHTTPClientTransport(url, { requestInit: { headers } })sends the headers on every request;fetchcan be injected.ClientOptions.supportedProtocolVersionspins the legacy handshake,versionNegotiationthe modern one.test/helpers/mcp-client.tsuses both. - (f)
POST …/pulls. A second PR for the same head and base answers 422Validation Failedwitherrors: [{ resource: "PullRequest", code: "custom", message: "A pull request already exists for <owner>:<branch>." }]; a head with nothing to merge answers 422 with "No commits betweenand ". Graft never parses these messages (D20): any 422 is followed by the D17 lookup, existing: truewhen it finds the PR,github_422otherwise.GET …/pulls?head=<owner>:<branch>&base=<b>&state=openfilters by the head's owner and branch and by base; Graft also checkshead.refandbase.refof what it gets back. Real: HUMAN-TODO. - (g)
GET …/pulls/{n}/commits.authorandcommitterare GitHub user objects, ornullwhen the commit's email belongs to no GitHub user; the endpoint lists at most 250 commits. Graft readspulls.get'scommitscount first: more than 250, or a commit with anullauthor (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.extraalso carries the repository's currentfull_name, read by the same D7 query, which D8 compares with therepositoryargument. - Capabilities.
McpServer.registerTooladvertisestools: { 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 percreateMcpHandler("responseMode: 'json'drops mid-call notifications"); it carries no request data. - Annotations.
readOnlyHint: trueonget_status,get_policyandreport_provenance(the spec's "three reads";report_provenancewrites Graft-side data only);readOnlyHint: false,destructiveHint: false,idempotentHint: trueonopen_change. - HTTP order. Origin (D4), then the failed-auth block of the client IP, then the token, then the per-token bucket.
GETandDELETEneed a token too, so without one they are401, with one405.415comes from removing Fastify'stext/plainparser in the plugin's encapsulated scope;413from the route'sbodyLimit(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
429until 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 notrustProxy(§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, reasonexpired) by thecreatethat reuses its name, because the partial unique index covers unrevoked rows.createlocks the repository row, so two concurrent creates cannot both take the last slot. An ambiguous--repo(two active rows with the name) is refused.--reasonfollows the column (1 to 200 printable characters),--actorthemode setrule. mode showprintsmcp tokens N active (newest used …)inside each repository's block ((never used)when no active token was used), and, when this shell hasGRAFT_MCP=off, the note after it. JSON output is unchanged.- Doctor checks
mcp_tokens_expiringandmcp_tokens_unusedcount active tokens of active repositories; both areWARNat 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 byfacts_read_at,evaluated_at, thenupdated_at; the MCP values are those of the report forchange_provenance.head_sha;conflictsare field names in order;approvalsare the storedcurrentandstale;breakGlassisapplied(enforce) orwould_bypass(report) when the verdict's enforced reason isbreak_glass. A mode is{ effective, reason }, the reason followed by the missing permission when there is one (permission_missing pull_requests:write), asmcp_write_off's detail.get_policymaps a policy error'slocationtopathand keepslinewhen known; warnings are returned in canonical order.basethat fails the D17 name rule, or a branch the API does not have, isbase_not_found.report_provenance. Fields are validated before the PR is looked up; the detail ofinvalid_argumentis the argument's name (agent,model,task,sessionUrl).pr_closed(stateclosedormerged) is checked beforestale_head.agreementispendingwhen no trailers were computed for that head yet. An identical repeat recomputes the agreement and enqueues nothing; a new row enqueuesprovenance.refreshwith the singleton keyprov-mcp:<row id>. The comment line omits model and task when they were not reported; the session URL is shown only inget_status(the spec's line has no session).open_change.draftis always sent (defaultfalse), 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 withexisting: true; when a bot authored it, anmcp_changesrow is written for it too (ON CONFLICT DO NOTHING), so a PR Graft opened whose row was lost to a crash afterpulls.createstill 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 thanmode_offisinternal.- D19.
listCommitLogins(src/modules/policy/facts.ts) reads up to three pages of 100 and keeps logins only; anullcommitter is fine, a missing author login is not. "Cannot tell" passesexcludedLogins: "everyone": no approval counts (current and stale 0) andtruncatedis set, which enforce mode treats as unmet. Themcp_changeslookup is a query in the policy job (the policy module does not import the MCP module). - D12 is
revokeTokensOnTransferinsrc/modules/installations/store.ts, called first inupsertRepositories' loop: the installations module does not import the MCP module either. A rename within the installation keeps the tokens. - Imports.
src/github/mutation-guard.tstakesvalidBranchNamefrom the puresrc/mcp/schemas.ts.src/bin/graft-ops.tsimportssrc/modules/mcp/cli.tsdirectly (as it doesmodules/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_changecall, and across the MCP scenario nomcporguardclient; the report's provenance refresh signals the policy job, which builds itspolicyclient for every evaluation since step 2.
Deviations from the spec
- D13 and §8: the stricter of two verdicts. D13 says an
unknownauthor "can only add matches torequireandblockrules: it tightens or changes nothing". It misses the policy'sdefault, which applies only when no rule matches. Counterexample (U-PMM-3b):default: require { humans: 1, team: security }and a rulematch: { agent: [codex] }→require: { humans: 1 }. With trailers sayingclaude-codeno rule matches and the default asks for a security reviewer; with the authorunknownthe codex rule matches (uncertain) and asks for anyone: looser. The property §8 requires therefore does not hold forevaluatePolicy(policy, factsWithMcp)alone (U-PMM-3 counts such generated cases). Fix:buildFactsis as specified (U-PMM-2), and whenmcp_report = 'disagrees'the policy job evaluates with the unknown author and with the trailers' author and keeps the stricter (evaluateWithReport,stricterVerdictinsrc/policy/evaluate.ts): a higher outcome wins, and twowould_requireverdicts 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
isErrorresult whose text starts withInput 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
maxover the whole run: the number ofphase1requests in the fake's log equals the number of allowedguardandmcpgate answers, and everyPOST …/pullsis agraft-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.ipis 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:trustProxyfor 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.
- (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 rulematch: { agent: [codex] }→require: { humans: 1 }) through the provenance and policy jobs after a disagreeing report namingcodex: the stored verdict still requires the default's team reviewer (teamCount: 1,usedDefault: true) and adds the codex rule, matched uncertain. Kills X23. - (required) The hash lookup and
report_provenance's scoping were unpinned → fixed. I-MCP-3 sends a token with a valid token'sgraft_mcp_and 8-character prefix and one later character changed: the same401(X7). I-MCP-4 callsreport_provenancewith B's token,repository: B, and a PR number that exists only in A, with A's head:not_found, nomcprow, noprovenance.refresh(X18). - (recommended) D10 was tested only with errors that carry nothing → fixed. I-MCP-16 sends an
mcp-protocol-versionheader holding the token, which the SDK echoes in the error it passes toonerror: themcp sdk errorline holdsgraft_mcp_[redacted]only (X64). Aget_policywhose argument holds a sentinel fails with an Octokit-shaped error (the token in its message, a PR title and body inrequest.body), thrown by a test Kysely plugin on the modes read: the result isinternal, there is onemcp tool failedline, and neither the token, the argument nor the body sentinels are logged (X63, and its variant that logs the raw error without the arguments). - (recommended) Two D19 rules had no test → fixed. I-MCP-14: a commit authored by
aliceand committed bycarol, wherecarol's approval does not count andbob's does (X66);pulls.getsays 260 commits and the listing serves 250: no approval counts,truncated(X69). - (recommended)
open_changeadopted any bot's PR → fixed as the review proposes.findOpenPullmarks a PRbyGraftonly when its author is aBotwhose login equals<GITHUB_APP_SLUG>[bot](case-insensitive, as the intent job buildsappBotLogin);adoptrecords only those. Without the slug nothing is adopted, so a PR Graft opened whose row was lost is returned withexisting: truebut gets no D19 exclusion: HUMAN-TODO now asks the operator to setGITHUB_APP_SLUGbefore any repository turnsmcp_writeon, anddocs/configuration.mdsays why. I-MCP-11: arenovate[bot]PR is returnedexisting: trueand not recorded; a server without the slug does not restore a lost row. - (minor) Nine more rules had no test → fixed, one test each:
- X5, X6 I-MCP-3: the installation deleted, then suspended:
401, same header and bytes. - X14, X15 I-MCP-6:
Origin: ""andOrigin: null→403, no token lookup. - X57 I-MCP-7: while
127.0.0.1is blocked, a request from10.0.0.2(FastifyinjectwithremoteAddress) is served. - X55, X58 I-MCP-7: from
10.0.0.3, ten malformed headers and nine unknown tokens (all401), one good call (200), then the 20th failure is401and the 21st429. - X28 I-MCP-8: a repeat that changes only
modelisalready_reported. - X44 I-MCP-12: an existing branch
graft-revert/xasbaseisbase_not_found, with nomcpclient. - X70 I-MCP-14: an
mcp_changesrow for the same PR number in repository B excludes nobody in A (alice's approval counts until A's own row exists). - (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, ascreateTokenRowdoes), counts the rolling hour, and inserts a claim: anmcp_changesrow withpr_numberandhead_shanull. Every process counts it, so D9 © is still "counted frommcp_changesrows". No GitHub call runs inside the lock. Afterpulls.create,settleOpenClaimdeletes 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, themcpclient'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. Migration0015_mcp_open_claimsdropsNOT NULLfrom both columns and addsCHECK ((pr_number IS NULL) = (head_sha IS NULL)); its down deletes claims and restoresNOT NULL. A claim never matches a PR number, soget_status, D19 and the purge are unchanged. I-MCP-12b: with nine opens in the hour, a call held at its create (the fake'sblock) keeps the tenth slot and a concurrent call israte_limited(onePOST …/pulls); a create answered422with no PR to adopt isgithub_422and gives its slot back; a stale claim is dropped; five parallelclaimOpenSlotfor one free slot, one wins. I-MCP-1 covers 0015 (a half-null row is refused; down drops claims). The step-down tests indb,modes,policy-enforce,break-glass,guard,guard-revertandpilot-opsstep through0015_mcp_open_claimsfirst. - (nit)
report_provenanceis advertised asreadOnlyHint: true→ deferred: the spec binds it. §1 listsreport_provenanceamong the "reads" that work in report mode, and §6'sserver.tsrow setsreadOnlyHint: 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. - (nit) The body is parsed before authentication → deferred: D3 binds the order to a
preHandlerchain ("The handler runs in apreHandlerchain: Origin check (D4), auth (D7), rate limit (D9)"). Moving the Origin check and the token toonRequestwould make every unauthenticated request a401before the parser and put D9 (b) in front of it; nothing leaks today (the413,415and400bodies carry nothing, and Fastify's JSON parser is bounded by the 64 KiBbodyLimit). For the step 7 security review, with the proxy question of the residual risks. - (nit) The fallback
401inrateLimitwas not the D5 response → fixed: oneunauthorized(reply)helper (status,WWW-Authenticate, body) servesauthenticateand 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'senforce" holds; the process-level rule applies to every process that serves or works (getEffectiveModes,mutationGate, the guard's settlement). - D3.
writePathis 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 toclassifyWrite, which refuses it too. - D4. The lookup uses the run's default client in
failed()and a fresh default client insettleFailedRun(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:netisIP) with an optional prefix of at most 32 or 128; the message isentry <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);falserestores step 6's rule and reopens its residual risk 2. A commit committed byweb-flowisunverified(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 changepolicy_modetoenforce; any other key in the same call is not written either. The doctor check reads the requested value. - D13. The mode is computed with
modesOfon the row observe already reads forstatuses:read(one query, before the lock), rather than a secondgetEffectiveModes. An event settled at once withGRAFT_GUARD_CONFIRM=offrecords it at insert. - D14 to D19. Reasons carry
{ metric, code, value, required }. Per-repositoryenforceSinceis theapplied_atdate of the newest applied change toenforce.last7is the last 7 days before--until. M2's "from at least 2 repositories" counts the repositories with measuredphase1rows (projected: with anyphase1row). The M1 span is first to lastmerged_atof the side's rows, in days with two decimals, plus one day (as Phase 0). M3'smissedBylists, for the measured view, aplannedoutcome in enforce mode too. Per-repository effective modes useresolveCeiling, likemode 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_targetandm3_below_targetare 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_OPTIONSinsrc/bin/graft-ops.ts, which the commands themselves use;parseOpsArgschecks a command line with it without the database.RUNBOOK_STAGE2holds the stage 2 numbers and the test checks that the runbook quotes them. - D21. The preflight's mode check runs only for
runandverify(the commands that need a running Graft). e01's commits carryGraft-AgentandGraft-Modelbut noGraft-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 nowPOST …/pulls/{n}/reviewswithevent: APPROVE(private mode); the actor gets anaddLabelact. INV-4 allows the doctor'sbreak_glassWARN 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 thebeforeAllworld, the break-glass scenario (review 1, finding 7) and the MCP scenario; the guard scenarios driven by their ownits are covered by the world's guard event only. "No feature client" is read as noguardormcpclient: the policy job builds itspolicyclient 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 intest/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 bothrunRevert(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 settlederrorwith 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 andLink: 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_changemust 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
enforceagain 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-flowcommits 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.
- (required) A permanent error after the revert's writes began was never settled → fixed.
settleBegunWritestakes 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, sofailed()andsettleFailedRunsettleerror, write the comment and release the cap slot, as before step 7. I-REV-10f: the ref is created,POST …/pullsanswers 422 on a non-last attempt: outcomeerror, a comment,countOpenReverts0, and a later observe sends noguard.revert; the same throughsettleFailedRunwith aPermanentJobError(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.mdsays it. - (recommended) D8 trusted the author of any
web-flowcommit → fixed as the review's option 2: on an MCP-opened PR a commit whose committer isweb-flowisunverified(the D8 line of the spec is kept, so the policy section shows the sameunverifiedtext). U-FCT-1 now expectsunverifiedfor aweb-flowcommit, and logins for an all-verified PR with real committers; its helper's default committer is no longerweb-flow, so the other cases fail for their own reason. I-MCP-14b uses committercarol(bobcounts,aliceandcaroldo not) and adds oneweb-flowcommit (no approval counts,mcpExclusionunverified). I-MCP-14's commits get real committers. This differs from spec D8 and U-FCT-1's text ("orweb-flow", "web-flowleft 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. - (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.effectiveisenforce, and only then lowers the ceiling. - (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
enforceagain 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 insrc/modes/index.ts(effectiveCeiling) anddocs/features/modes.md. The verdict line is kept. - (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.policynull. X39, X40, X41: a new I-P1G-11 (a paired repository with only report-modephase1rows 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--untilis not retained). X37: I-DB-16 already failed without the refusal (Postgres's CHECK error does not match its message); it now also asserts thephase1run is kept. - (minor) The trusted-proxy docs promised more than the setting gives → fixed.
docs/configuration.mdanddocs/features/mcp.mdsay to list only the proxy's own addresses, never a client network, that the proxy must append (nginx$proxy_add_x_forwarded_for) or overwriteX-Forwarded-For, and that Graft must be reachable only through the proxy;.env.exampleuses one address. U-CFG-40 keeps the spec'sfd00::/8as a parser case. - (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 inreportand nosuccesscheck. The guard scenarios driven by their ownits are not re-run (recorded above under N-17); the world's guard event is. - (nit)
REQUIRE_VERIFIED_COMMITSpresented as a pending decision → fixed: HUMAN-TODO marks D8 decided by the spec, and the comment infacts.tssays that turning it off reopens step 6 residual risk 2. - (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. - (nit)
privatedefaulted totrue→ 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 → thesettleBegunWritescomment 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 listshows the event aserror. 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, thensettleFailedRunwith aPermanentJobError(403): the PR is adopted (revert_opened, outcomeopened), no comment,countOpenReverts1, onePOST …/pulls. R4 (theisRetryable(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
errorwith the comment), D8 (aweb-flowcommitter 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 6trustProxyline points at the step 7GRAFT_TRUST_PROXYitem. - 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 reportper installation when the database is up; one sentence says that if Graft cannot come back up, the per-repository path (removinggraft/policyfrom the required checks) is the only way to unblock merges. - F. The stage 6
web-flowcheck → kept, as recommended rather than required: the code already fails closed, so the HUMAN-TODO item is now "before theweb-flowrule 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.
fetchIntentInputsreads up to 20 changed source files atpull.head.sha(repos.getContent, five at a time) intoChangedFile.headText, in memory only likepatch. A 404 or 403, a non-file, a file over 200 KB or one with a NUL byte leavesnull; any other error is thrown, as the listing does.prepareDiffturns it into afile_contextblock (fileContextindiff.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, sostate.replayingfindsreplaying: 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_PATHSandgraft.yamlglobs) get no context: their unchanged lines, which may hold credentials, are not sent to the model. The fetch skips the built-in rules;prepareDiffalso drops the configured globs. Those files aresensitiveby 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_dataonly on added lines. unverifiableand partial views. A claim on the hidden part of a truncated or omitted file must stayunsupported; this is a prompt rule, but a model that answersunverifiableinstead gains nothing: a partial view already sets the floor tologic(partial_view), which is all a disagreement would add.unverifiabledoes 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 todisagree, 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 staysunsupported: 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
inputHashand of the nonce search. - Versioning.
PROMPT_VERSIONisintent-v2; U-PROMPT-1, the eval case schema (headTextis 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 ofintent-v1andintent-v2. - Tests. U-FETCH-⅞, U-DIFF-13/14/15/16, U-OUT-8, U-GEN-36/37/38, U-IREN-11.
contentRefsin the policy tests now counts onlygraft.yamlreads, 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.languageingraft.yaml, read withsensitive_pathsfrom 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 inREPORT_LANGUAGES; another value islanguage_invalid. The prompt only ever holds a name from that list, never file text. A file withoutreportkeeps 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
Languagesection to both, telling the model to write every sentence in that language and to keep paths, JSON keys, claim ids,risk_classandverdictin 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 ofinputHash, so changing it gives a new card. - Versioning.
PROMPT_VERSIONisintent-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_PROMPTholds 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.
buildSharedDatarenders 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.formatahead 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 sendOUTPUT_SCHEMA,anyOfof 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.userCachePrefixis a prefix ofuser; the client sends it as a first text block withcache_control: ephemeraland the rest as a second block. A value that is empty or not a prefix ofuseris 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_VERSIONisintent-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.
disagreemeans at least one claim isunsupportedorcontradicted. Missing behavior changes are stored as before (verifier_missing) and rendered as an Also changed list under the behavior changes. They no longer addverifier_disagreesto the risk; the verifier's own risk class still counts in the maximum, so a missing change it ratessensitivestill raises the card. - Check title.
verifier agrees · N more changeswhen the list is not empty. - Older cards. A stored
intent-v4or earlier card with statusdisagreeand 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
disagreetoagreewith an unchanged final class. - Versioning.
PROMPT_VERSIONisintent-v5; U-PROMPT-1 and the synthetic baseline are updated. Not done: a live eval run. Judge it on production data: the disagreement rate perprompt_versionand 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 sendsx-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 keeps2023-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:tracedLlmalready makes one span per call, without content (U-LLM-21). - Beta calls. The URL no longer carries
?beta=true; theanthropic-betaheader is unchanged (U-LLM-2).