Architecture¶
Docs index · Decisions · Configuration
Graft is one TypeScript codebase with two long-running processes, a server and a worker, that share one Postgres database. The server only receives webhooks; all GitHub API calls, model calls and publishing happen in jobs that the worker runs through pg-boss. Operator tools (pnpm graft, pnpm eval) are separate entry points in src/bin/.
Overview¶
flowchart LR
GH["GitHub"] -->|"POST /webhooks/github"| SRV
subgraph graft["Graft service"]
SRV["Server (Fastify)<br/>verify HMAC, dedup delivery"]
WRK["Worker (pg-boss)<br/>modules: installations, provenance,<br/>intent, policy, pilot"]
end
SRV -->|"webhook_deliveries row + github.webhook job<br/>(one transaction)"| PG[("Postgres 17<br/>app tables + pgboss schema")]
PG -->|"jobs"| WRK
WRK -->|"cards, verdicts, votes, metrics"| PG
WRK -->|"read PRs, commits, files, reviews, graft.yaml"| API["GitHub REST API"]
WRK -->|"check runs + one managed PR comment"| API
WRK -->|"intent writer + verifier"| LLM["Model provider<br/>(Claude API by default)"]
CLI["CLI: pnpm graft, pnpm eval"] -->|"reports, pilots, offboarding"| PG
The server verifies the HMAC, inserts the delivery into webhook_deliveries with ON CONFLICT DO NOTHING and sends the github.webhook job in the same transaction. The worker's github.webhook job dispatches the event to the handlers that modules register; handlers only validate and enqueue follow-up jobs.
Lifecycle of a pull request¶
sequenceDiagram
autonumber
participant GH as GitHub
participant S as Server
participant Q as Postgres and pg-boss
participant W as Worker
participant AI as Model provider
GH->>S: pull_request opened or synchronize
S->>Q: store delivery, queue github.webhook
S-->>GH: 202 enqueued
Q->>W: github.webhook
W->>Q: queue provenance.refresh, intent.generate, policy.evaluate
Note over W: Provenance
W->>GH: list PR commits
W->>W: parse Graft-* trailers, agent or human
W->>GH: provenance section and graft/provenance check (neutral)
Note over W: Intent card
W->>GH: read PR, files, diff, linked issue
W->>W: rule-based risk floor
W->>AI: writer (fast model if the floor is trivial)
W->>AI: verifier (strong model, diff, file context and card)
W->>GH: graft/intent check (neutral), then intent section
Note over W: Policy and review summary
W->>Q: provenance_published and intent_published signals queue policy.evaluate
W->>GH: read graft.yaml at the base branch commit
W->>GH: read the head's CI and AI review checks
W->>GH: summary and policy sections, graft/policy check (neutral in report mode)
Note over GH,W: Reviewers vote with reactions (polled every 15 min) or check-run buttons
Each publish happens under a per-change advisory lock (withChangeLock) after a freshness re-check, so concurrent or out-of-order jobs never publish stale output. The final risk class is the maximum of the floor and every model's class: the model can raise the class, never lower it.
Modules and how later steps plug in¶
How later steps plug in. Each feature is a folder src/modules/<name>/ whose index.ts exports webhookHandlers: WebhookHandler[] and jobs: JobDefinition[]. src/app/registry.ts is the only file that lists modules. Step 2 added modules/changes (the changes row and its guarded upsert; store only, no handlers) and modules/provenance (trailers, handlers, the provenance.refresh job). Step 3 added modules/intent (handlers, the intent.generate job, card generation, rendering, feedback) and src/llm/ (the model-client interface, the Anthropic client, the fake). Step 4 added eval/ with src/bin/eval.ts, and step 5 added modules/policy, the src/policy/ library and src/bin/graft.ts. Step 6 added modules/pilot (reviewer eligibility sync, label-based incident detection, the daily rollup), src/pilot/ (the CLI-side libraries: baseline, review-time arithmetic, gate, doctor, purge), src/bin/graft-ops.ts and scripts/pilot/. Phase 1 step 6 added src/mcp/ (pure token and tool-schema code) and modules/mcp (the /mcp routes and the mcp-token helpers; no handlers, no jobs). A module may also export signalListeners (see "Policy contract"). Modules import from config, core, db, github, queue and webhooks. They import another module only through its index.ts, never its internals.
Contracts¶
- Webhook handlers must be idempotent, because a failed job retries every handler for that delivery. They must also be fast: DB writes, or enqueueing a follow-up job with
ctx.queue.send(...). Slow work such as LLM calls or many GitHub API calls goes into its ownJobDefinition. - Deliveries can be processed out of order and concurrently (
WORKER_CONCURRENCY, retries with backoff, and GitHub itself does not order them), so handlers must tolerate reordering. For order-sensitive state, compare the head SHA or the payload's timestamp and ignore stale events, or use akey_strict_fifoqueue keyed by installation or PR. Step 1's installation handlers are idempotent but not order-proof (for example a lateaddedafterdeleted). - Code that would persist file contents, diffs or patches does not pass review. Only paths, SHAs, numbers and model prose go in the DB.
LLM contract (step 3)¶
- Modules never build model clients; they use
ctx.llm(LlmClient,src/llm/types.ts).complete()returns a result for every API outcome (timeout, rate limit, refusal, bad JSON, no API key, ...) and throws only on programmer errors, so failure paths are easy to fake and test. - No prompt, diff, PR title or body, issue text or raw model output is ever logged, put in job data, or stored as such. Logs carry metadata only (model, purpose, token counts, duration, outcome). The DB holds paths, SHAs, numbers and the model's own prose (goal, behavior changes, reasons), nothing else.
test/unit/log-hygiene.test.tsand I-INT-5 enforce this. - Token usage is logged per call and stored per card (
intent_cards.input_tokens,output_tokens,cache_read_tokens,cache_write_tokens,llm_calls, which describe the last run that produced the row); the daily per-repository budget is computed from the append-onlyintent_spendledger (one row per model run), not from the card rows. - The writer and the verifier share one system prompt, stable per
PROMPT_VERSION, and their user messages start with the same bytes (nonce, facts, file list, diff). Both the system prompt and that shared start (userCachePrefix) are sent withcache_control: ephemeral, so the verifier reads the diff from the cache the writer wrote seconds earlier. Title, description and issue (writer) and file context and card (verifier) come after the breakpoint. - A server-side provider registry (
src/llm/registry.ts, Choosing a model provider) points the writer and the verifier at any provider; without it they use the Claude API. Prompt caching applies where the provider supports it. - All tests use the fake LLM (
src/llm/fake.ts) or the real client with an injectedfetch. No test reaches a model provider. - Model text reaches markdown only through
escapeProseandcodeSpan(src/github/markdown.ts).
Reviewer feedback on cards (reactions and check-run buttons, and the one exception to the payload rule) is described in features/intent-cards.md.
Managed PR comment¶
Managed PR comment. Graft keeps exactly one comment per PR, created once and then updated in place (it is not pinned through the API). The contract lives in the doc comment of src/github/managed-comment.ts, which steps 3 and 5 reuse:
- The body starts with
<!-- graft:managed-comment v1 -->, then## Graft, then one block per section,<!-- graft:section:<name>:start -->...<!-- graft:section:<name>:end -->, in the ordersummary,intent,provenance,policy; unknown sections found in an existing body are kept verbatim after them. A<sub>footer closes it. - The policy job owns two sections,
summaryandpolicy, and writes them in one request. Each module writes only its own sections throughupsertManagedSection; every other section is preserved byte for byte. Section markdown may not contain<!-- graft:and is capped at 20,000 characters. - Finding the comment: the stored
changes.graft_comment_idif it still exists and is ours, else the first of the PR's comments that is ours, else a new comment. Ours means the marker is the first line andperformed_via_github_app.idequalsGITHUB_APP_ID. Because D13 (that field being present on REST comment responses) is unverified against real GitHub, there is a fallback: whenGITHUB_APP_SLUGis set, a comment authored by the bot login<slug>[bot](typeBot) with the marker also counts. A human pasting the marker is never adopted. withChangeLock(db, changeId, fn)(src/db/locks.ts): every writer of the managed comment or of per-change GitHub output (check runs) must hold this per-change advisory lock, and must store the comment id inchanges.graft_comment_idinside the same transaction. The lock is a transaction that holds a pooled connection while requests are in flight, so do no slow work (LLM calls, diff fetches) insidewithChangeLock; compute first, then lock, re-check freshness (head SHA andpr_updated_at) and publish.PermanentJobError(message, reason)(src/queue/errors.ts): a job throws it when a retry cannot help (deleted PR, lost permission, repo mismatch). The worker logs it and completes the job.toJobErrorinsrc/github/errors.tsmaps Octokit errors: 404/410/401/non-rate-limit 403/422 are permanent; 429, rate-limit 403 and 5xx/network errors are retried. It never returns the original error: Octokit errors carry the request body (a rendered card is model output) and pino and pg-boss serialize it, sosanitizeError(src/queue/errors.ts) rebuilds them as metadata only (name, short message, status, method, route template, request id). The worker sanitizes again before logging and rethrowing, so a job'spgboss.job.outputand the logs never hold request or response bodies (I-E2E-4).
Review summary and status card¶
src/modules/policy/summary.ts is pure: from the card, the policy verdict, the provenance and the head's CI and AI review checks it writes the summary section. With GRAFT_PUBLIC_URL set, the server also answers GET /summary-card/<token>.svg: the token holds the card's words, signed with a key derived from the webhook secret, so the route reads no database. See Review summary.
Retention of webhook payloads (step 6)¶
Retention of webhook payloads (step 6). github.webhook jobs carry the entire webhook payload, which includes PR titles and bodies, so the github.webhook queue alone has deleteAfterSeconds = 3600 (WEBHOOK_JOB_RETENTION_SECONDS, set through JobDefinition.options.deleteAfterSeconds): a completed or failed job is deleted one hour after it finished. Every other queue keeps 7 days. Delivery dedup does not depend on the job: the webhook_deliveries primary key (INSERT ... ON CONFLICT DO NOTHING, rows are never pruned) is the dedup, and the deterministic job id is only a second line of defence for the hour in which the job exists, so a redelivery after the job is gone is still duplicate and creates no job (I-Q-6). Nothing reads old github.webhook jobs: webhook_deliveries.job_id is informational, and no code, test or document looks a webhook job up by id after the fact. Two caveats: a job that has not run yet (for example the worker is down) stays queued with its payload until pg-boss deletes it (retentionSeconds, 14 days by default), and intent.feedback.record jobs (voter login, button) still keep their data for 7 days.
Webhook replay¶
Webhook replay. The webhook HMAC covers only the body, so X-GitHub-Event and X-GitHub-Delivery are unauthenticated: anyone holding one captured signed body can replay it under a new delivery ID (bypassing the webhook_deliveries dedup) or under another event name. Mitigations: (1) a payload is only a trigger: pull_request and check_run handlers validate the payload and enqueue a job, nothing else; the job re-fetches the PR from the API and writes only what the API returned (it also checks the PR number and repository id); (2) every handler parses its payload with a zod schema (parsePayload, logging issue paths only) and returns on a mismatch, which catches a relabeled event; (3) replays converge: the same body under a fresh delivery ID yields the same dedup key for the downstream jobs (provenance, intent, policy, ...), so none is created within 7 days (their retention), and a later or stale replay only refreshes live state. The github.webhook job itself is keyed by the delivery ID and nothing relies on finding it later: its data is the whole payload (PR titles and bodies), so since step 6 pg-boss deletes it 1 hour after it completes or finally fails (see the retention note above). The rule for later steps: handlers treat payloads as triggers; jobs write only from API data or from data Graft computed. Residual risk: an attacker with a captured body can force extra GitHub API calls after the dedup window of the downstream job (7 days), but cannot forge state. A replayed check_run.rerequested body is bounded to one re-run per PR per minute: the key is prov-rerun:{repoId}:{pr}:{floor(now/60000)} (and intent-rerun:... for the intent check), so a flood of fresh delivery IDs enqueues at most one refresh per PR per minute. The work is idempotent and never forges state; only cost is at stake.
Source layout¶
Layout: src/config (env), src/core (clock, logger, context), src/db (Kysely, migrations), src/queue (pg-boss wrapper, worker), src/webhooks (receiver, registry, dispatch job), src/github (Octokit factory, the only place an Octokit is built; managed comment; markdown safety), src/llm (model clients: the only place an Anthropic client is built), src/http, src/modules, src/eval (the evaluation tool, step 4: a tool, not a module; it imports Graft code only through modules/intent/index.ts, modules/provenance/index.ts, modules/changes/index.ts, src/llm, src/github/client-factory.ts and src/github/errors.ts, never db, queue, webhooks, http or config), src/bin (entry points, including eval.ts), and at the repo root eval/ (JSON Schemas, the synthetic set, the saved baseline and the thresholds). src/db imports nothing from src/modules. Step 5 adds src/policy (the graft.yaml library: schema, safe YAML parse, glob checks, the pure evaluator, the GitHub loader and its cache; it imports nothing from src/modules), src/modules/policy (handlers, jobs, facts, rendering, store), src/core/glob.ts (the glob semantics shared by the risk floor, GRAFT_INTENT_SENSITIVE_PATHS and graft.yaml), src/core/signals.ts (cross-module signals) and src/bin/graft.ts (the pnpm graft policy CLI). Step 6 adds src/modules/pilot (handlers, jobs, signal listener, stores), src/pilot (CLI-side libraries; it may import db, config, github, core and the modules' index.ts; src/pilot is imported by src/bin and, for normalizeEvent and writeFileAtomic, src/e2e) and src/bin/graft-ops.ts, which graft.ts loads with a dynamic import() for pilot, baseline, gate, incident and metrics, so that graft policy check still runs with an empty environment (U-CLI-6). The live e2e runner adds src/e2e (a tool like src/eval; import boundary: it imports only src/config, src/core, src/db/client.ts, src/db/migrator.ts, src/github/{client-factory,errors,rate-limit,managed-comment}.ts, src/llm/pricing.ts, src/pilot/baseline.ts (only normalizeEvent), src/pilot/atomic-write.ts, src/policy/parse.ts, src/eval/terminal.ts and the modules' index.ts, never src/bin, src/queue, src/webhooks, src/http or test/; only src/bin/graft.ts imports it, with a dynamic import(); U-LIVE-BOUND-1 enforces both), e2e/ at the repo root (the sandbox list and the fixtures) and docs/e2e/. src/modes (Phase 1 step 1: the pure effective-mode rule; it imports no db, github or modules), src/modules/modes (stores, jobs and the mutation gate) and src/github/mutation-guard.ts (the write allow-list). Phase 1 step 2 adds src/policy/enforce.ts (pure: constraint satisfaction and the enforce conclusion), src/github/collaborator.ts (the collaborator role check shared by the reviewer sync and approvals), src/modules/policy/approvals.ts (role checks and team memberships per job) and src/modules/policy/team-fanout.ts (the membership and team triggers). Phase 1 step 3 adds src/modules/audit (the audit_log store and the graft audit list helpers; no handler, no job) and src/modules/policy/break-glass.ts. Phase 1 step 4 adds src/guard/detect.ts (pure: result classes, check keys, the culprit rule and confirmation; it imports no db, github or modules) and src/modules/guard (handlers, guard.track, guard.observe, guard.confirm, guard.prune, the comment, the store and the graft guard list view). Phase 1 step 6 adds src/mcp (pure: tokens.ts, schemas.ts; it imports no db, github or modules) and src/modules/mcp (the Fastify plugin, auth, rate limits, the per-request McpServer, the four tools, the token store and the CLI helpers), mounted by src/http/server.ts.
Policy contract (step 5)¶
Policy contract (step 5). The policy is read from the base branch only: heads/<base ref> is resolved to a commit when the job runs and graft.yaml is read at that SHA, never from the PR head or a pull ref (a PR must not loosen the policy that judges it); a PR that edits the policy file is flagged and can never be would-approved. src/policy imports no module, so the intent hook, the policy module and the CLI share one parser; the module graph stays one-way through signals: the intent job emits intent_published and the provenance job emits provenance_published after a publish (outside the lock), and since step 6 the intent module emits feedback_recorded after it writes votes (the button job after recorded, the reaction poll when it wrote at least one row; the pilot module listens and syncs the change's reviewers at most once per hour, the policy listener returns at once), JobContext.signals calls the listeners that modules export as signalListeners, and the policy module listens and enqueues policy.evaluate. Payloads are triggers: handlers validate and enqueue, jobs re-read everything from the API. The graft/policy check run always concludes neutral in Phase 0, so it is not an approval. Nothing from the file is stored but the hash of the parsed policy: rows hold rule indices, reason codes, PR paths, counts, SHAs and logins. Team names are always rendered as code spans, so the comment never notifies a team.
Modes contract (Phase 1 step 1)¶
Who can set a mode. Only the operator: the server ceiling GRAFT_MODE_CEILING (the worker's environment) and pnpm graft mode set (the database, with an audit row in mode_changes). Nothing in a repository (graft.yaml, labels, PR text) can change a mode, and a mode key in graft.yaml stays unknown_key.
The effective rule. effectiveModes() in src/modes/index.ts is pure: effective = min(ceiling, requested), where the ceiling is effectiveCeiling(env, stored), the lower of the process's GRAFT_MODE_CEILING and the worker's service_state('mode_ceiling') read with the repository row (Phase 1 step 7, D2: a missing row is the process's value, an unknown value is report), then lowered to report/off when a permission the mode needs is missing or was never read, the installation is inactive or the repository was removed (report < enforce, off < on; a report ceiling also forces mcp_write off). The needs are guard_mode: contents write and mcp_write: pull_requests write; policy_mode needs nothing beyond Phase 0 in step 1. Installation permissions are read from GET /app/installations/{id}, never from a webhook payload. Every feature reads the result through getEffectiveModes(db, repositoryId, config); the policy job reads it once, outside the change lock. Since step 2 policy_mode needs no permission either; without members: read team constraints are unverified and fail.
The mutation guard. src/github/mutation-guard.ts installs a hook.before("request") on every client the factory returns (asApp() included). GET and HEAD pass; the route table in that file lists the allowed writes, classified auth, phase0 or phase1 (with the features allowed to use the route). A phase1 write needs a client made with forInstallation(id, { feature }) and a gate (mutationGate in src/modules/modes) that reads the effective mode from the database at request time. Everything not on the table, /graphql included, is refused with MutationRefusedError (mutation_refused, a PermanentJobError). A new write is added to the table by the step that needs it, with a case in test/unit/mutation-guard.test.ts and, for a Phase 1 feature, a scenario in the neutral regression suite test/integration/neutral.test.ts.
Computed vs published conclusion (step 2, D10). The policy job computes what enforce mode concludes (enforcedConclusion() in src/policy/enforce.ts, pure, the only place that names a non-neutral conclusion) in every mode, outside the lock, and stores it as policy_verdicts.enforced_conclusion and enforced_reason. check_conclusion stores what was published: neutral in report mode, otherwise the enforced conclusion, or pending when the check was published in_progress (the card wait, D9). The job passes the value through publishedCheck(mode, enforced); it never chooses a conclusion itself. Approver facts (write access, team memberships) are read from the API per job, within fixed bounds, and never stored beyond counts.
The guard reads check-run bodies (step 2, D11). POST …/check-runs and PATCH …/check-runs/{n} stay phase0 in the route table, but the hook also reads the body Octokit is about to send (endpoint.parse(options).body, so a data option cannot hide it). A body whose status is not completed or whose conclusion is not neutral is a Phase 1 write: it needs name: "graft/policy", a client made with { feature: "policy" } and a gate that finds policy_mode effective enforce; a body that is not a plain object is refused unknown_route. Neutral bodies never query the database. Only the policy job uses the policy client, so provenance and intent can never block a merge. If a rollback lands between the job's mode read and its publish, the gate refuses with mode_report, the job ends stale without an error, and the rollback's fan-out republishes (D12).
Transfers (step 2, D13). upsertRepositories resets the three modes to report/report/off, with system rows in mode_changes (applied by modes.apply), when a repository row moves to another installation or comes back after removal.
Applying a change (D6, D7). The ops CLI never enqueues. mode set writes mode_changes rows with applied_at = NULL; the worker cron modes.apply claims them with FOR UPDATE SKIP LOCKED and sends one repository-scoped policy.fanout per repository whose policy_mode changed. At start the worker compares GRAFT_MODE_CEILING with service_state('mode_ceiling') and, when it changed, fans out every active repository.
Break-glass and the audit log (step 3). A pull_request.labeled delivery for the break-glass label adds its pull_request.head.sha (breakGlassHeadSha) and its sender.id (breakGlassActorId, review 1) to the policy.evaluate job; an unlabeled delivery adds breakGlassUnlabeled. Graft uses these payload values only to refuse (D4): the job applies a break-glass only when the live head from pulls.get equals the head, and the newest label event the issue events API lists is a labeled event by that user id; an unlabel delivery only ends a bypass. A payload can refuse a break-glass but never grant one. Who added the label comes from the issue events API and their role from the collaborator API, both read outside the lock (src/modules/policy/break-glass.ts). The source of truth is audit_log (D6, as amended by review 1): a break-glass is active for (change, head) iff an applied row exists for that pair, the label is still on the PR and no removed row of the change (any head) at or after it exists. The applied row stores the issue event id it was verified from (label_event_id); every label trigger re-reads the events and ends the bypass (a removed row) when that event is no longer the newest labeled one or an unlabeled event is newer. An evaluation of another head ends it too, so a push ends it for good; nothing is written to GitHub. The job writes the audit row inside the change lock, in the transaction of the verdict upsert, so a rolled-back publish drops it too. enforcedConclusion checks break-glass before every other rule (D5), and factsHash has a breakGlass term (D10). mergedUnderBreakGlass(db, changeId, headSha) in src/modules/audit is the rule step 5 reads (D8).
D8: the mode is in the facts hash. The policy job adds the effective policy_mode to its factsHash and stores it in policy_verdicts.policy_mode, so a mode change always republishes the check even when nothing else differs (the "unchanged" short cut compares that hash).
Guard contract (Phase 1 step 4)¶
Spec: phase-1/step-4-guard-detection.md. User page: features/guard.md.
Triggers vs API reads. push to the default branch, check_run.completed, check_suite.completed and status are triggers only: the handlers check the branch hint (refs/heads/<default_branch>, check_suite.head_branch, branches[].name) and that a check run is not Graft's own, then enqueue. guard.track reads the default branch (repos.get), the commits (repos.listCommits, first parents only) and the PR behind each commit (changes, then commits/{sha}/pulls) from the API. guard.observe reads checks.listForRef (filter=latest) and, with statuses: read, the combined status. A payload never decides what is stored.
Tables. main_commits (repository, SHA, first parent, seq, chain_break, PR mapping), ci_results (repository, SHA, key, name, source, class, completed time, a GitHub link) and the step 4 columns of guard_events (last green SHA, failing checks, candidates, detection and confirmation times and reason, comment id, guard mode). No output, log, commit message or PR text is stored. Both new tables cascade from repositories, are covered by the pilot purge, and are pruned daily after GRAFT_GUARD_RETENTION_DAYS.
Lock order. Detection runs inside a per-repository advisory lock (pg_advisory_xact_lock(hashtext('guard:' || repository_id))): results are upserted, transitions found and events opened or settled in one transaction, with no GitHub call inside. The comment is written afterwards under withChangeLock(culprit change). The two locks are never held at once: repository lock, released, then change lock. guard.checks is read from graft.yaml at the transition's last green commit before the lock; a transition whose baseline was not loaded yet is set aside and the lock phase runs again.
The D10 write. For an event with a culprit only, one POST /repos/{o}/{r}/issues/{n}/comments on the culprit PR through the default installation client (a phase0 route). The first line is <!-- graft:guard-event <id> -->; inside the change lock Graft re-reads the event and searches the PR's comments (at most 10 pages, App-authored only, the managed comment's rule 3) for the marker before writing, and stores the comment id and the effective guard mode in the same transaction. Since step 5 the comment is written by guard.revert (below), as its last step.
The revert job (Phase 1 step 5)¶
Spec: phase-1/step-5-revert-prs.md. When confirmOpenEvents settles an event as culprit_found, guard.observe (or guard.confirm) enqueues guard.revert { installationId, repositoryId, owner, repo, eventId } (singleton guard:revert:<eventId>) after the repository lock is released, and so does every observe for an event still waiting for its comment. The job:
- stops unless the installation and repository are active, detection is on, and the event has a culprit, no comment yet and a status
culprit_found,needs_humanorrevert_opened; - reads the effective modes once and stores
guard_mode(the mutation guard reads them again at each write); GRAFT_GUARD_REVERT=off→skipped/revert_off; confirmationoff→confirmation_off; a culprit that is therevert_pr_numberof any event of the repository →revert_of_revert;- plans with the default client, GETs only, outside every lock: the culprit's commits from
main_commits(contiguous byseq, first-parent linked, no chain break after the first),repos.get(default branch, merge settings), the tip (git.getRef,git.getCommit),graft.yamlat the event's currentlast_green_sha(guard.checksagain,guard.auto_merge_reverts),pulls.getof the culprit, then the pureplanRevert(src/guard/revert-plan.ts) overgit.getTreeandgit.getCommit(src/modules/guard/trees.ts, cached per job, budgeted). It storesrevert_plan_pathsandrevert_conflicts(counts, never paths); - in report mode stores
plannedand the would-be auto-merge decision (auto_merge_state = 'would'), and goes to the comment. Noguardclient is made in report mode; - claims under the repository advisory lock: re-reads the event, checks the open-revert cap (events in
revert_opened, plus claimed runs without an outcome), one revert per culprit, and "already green" (a later tracked commit green on every remaining failing key), then setsrevert_claimed_at; - writes through
forInstallation(id, { feature: "guard" }), the onlyguardclient of the codebase, in this order, storing each result before the next:POST …/git/trees(base_tree= the tip's tree;beforeentries restored, added pathssha: null), then reads the new tree back and checks every changed path against the plan (tree_mismatch);POST …/git/commits(parents = [tip], no author) →revert_commit_sha;POST …/git/refs(refs/heads/graft-revert/<eventId>) →revert_branch;POST …/pulls→revert_pr_number,status = 'revert_opened',revert_outcome = 'opened'(under the change lock);POST …/issues/{n}/labels(graft:revert) →revert_labelled; the GraphQLenablePullRequestAutoMergewhen eligible →auto_merge_state; - publishes the comment (
publishGuardCommentwith the outcome's section).
Resume points (D17). A retry starts at the first result not stored. A POST …/git/refs that answers 422 (the branch exists) lists GET …/pulls?head=<owner>:graft-revert/<eventId>&state=all and adopts a PR found there; otherwise the existing branch is reused when its commit has the planned tree and the tip as parent, or deleted (DELETE …/git/refs/heads/graft-revert/<eventId>, the only deletion) and created again. A run that resumes with a commit or branch stored lists by head first, so a crash after POST …/pulls never opens a second PR. The unique index guard_events_one_revert_per_culprit keeps one revert per culprit in the database. A mutation guard refusal at any write (a rollback to report) ends the run with error / mode_changed, keeps what was created and is not retried; a permanent GitHub error ends with error / github_<status>; a transient one retries the job, and the last attempt records the error.
Lifecycle. A pull_request.closed whose head ref starts with graft-revert/ (a hint) enqueues guard.revert_closed { repositoryId, prNumber }, which finds the event by revert_pr_number, reads the PR from the API and sets reverted (merged) or revert_closed. guard.track sets reverted too when it maps a new default-branch commit to a revert PR, so a missed webhook is caught by the next push.
Body rules of the guard's routes (§12). The mutation guard reads the body of three guard routes: POST …/git/refs must create refs/heads/graft-revert/<uuid>; a guard client's POST …/pulls must have the head graft-revert/<uuid>; its POST …/issues/{n}/labels must be exactly { labels: ["graft:revert"] }. Anything else is feature_not_allowed. POST /graphql (or /api/graphql on GitHub Enterprise Server) is a guard route only when the body is { query, variables } with query exactly the exported ENABLE_AUTO_MERGE_MUTATION and variables.clientMutationId matching graft-guard:<owner>/<repo>#<n>; the gate is asked about that repository. Every other GraphQL body is an unknown route, refused in every mode. PUT …/pulls/{n}/merge, PATCH …/git/refs/…, PATCH …/pulls/{n} and POST …/git/blobs stay unknown.
MCP contract (Phase 1 step 6)¶
Spec: phase-1/step-6-mcp-server.md. User page: features/mcp.md.
The mount. buildServer registers the mcpRoutes plugin when GRAFT_MCP=on: POST, GET and DELETE on /mcp in the existing Fastify server, a 64 KiB route body limit and Fastify's JSON parser only (text/plain is removed in the plugin's scope, so other media types get 415). A preHandler chain runs the Origin check (D4), the bearer token (D5, D7) and the per-token limit (D9 a), then the route hijacks the reply and hands req.raw (with auth set) to the SDK: createMcpHandler(factory, { legacy: "stateless", responseMode: "json" }) wrapped once with toNodeHandler. The factory builds a fresh McpServer with the four tools for every request; nothing is held between requests, so several server processes can serve /mcp.
Auth per request. Authorization: Bearer graft_mcp_<43 base64url> only. The token is hashed (SHA-256) and looked up with its repository and installation in one indexed query, with no cache: unknown, expired, revoked, removed-repository and inactive-installation tokens all get the same 401. last_used_at is written at most once a minute. The AuthInfo handed to the SDK carries [redacted] as its token and the token id, repository id, installation id and full name as extra. Every tool compares its repository argument with that full name (D8): the repository always comes from the token row, PR numbers are looked up within it. Failed authentications are limited per client IP, before the lookup (D9 b). Tokens are created, listed and revoked only by pnpm graft mcp-token; a transfer or re-add of the repository revokes them in upsertRepositories' transaction (D12).
The module's one write. open_change reads getEffectiveModes first and returns mcp_write_off before any GitHub request when mcp_write is not effectively on, so report mode never creates an mcp client. Its checks are GETs through the default client; then src/modules/mcp/tools/open-change.ts, the only place that calls forInstallation(id, { feature: "mcp" }), sends pulls.create. The mutation guard allows an mcp client POST …/pulls only, with a body of title, body, head, base, draft, maintainer_can_modify (absent or false) and plain branch names (§9, mcpBodyAllowed), and its gate reads mcp_write again at the write. The hourly open cap is counted from mcp_changes, which also marks the PR for D19.
The D13 merge. report_provenance stores one provenance row with source = 'mcp' per (change, head), under the change lock, and enqueues provenance.refresh (trigger mcp_report). The job computes the trailers as before, then mcpAgreement (pure, compute.ts) against the MCP row for the head, and stores change_provenance.mcp_report (none, agrees, disagrees). buildFacts makes the author unknown when it is disagrees; the policy job then evaluates with that fact and with the trailers' author and keeps the stricter verdict (evaluateWithReport, stricterVerdict in src/policy/evaluate.ts), so a report can only add requirements. MCP values never replace trailer values; the comment shows them as unverified.
D19. For a change with an mcp_changes row, the policy job lists the PR's commits (at most 250, logins only) and passes their lowercased author and committer logins to countApprovals as excludedLogins; a commit with no author login or more than 250 commits excludes everyone and marks the count truncated (unmet in enforce mode). Since Phase 1 step 7 (D8), a commit that GitHub has not verified, or whose committer has no login or is web-flow (step 7 review 1, finding 2), excludes everyone too.
Data model¶
Defined in src/db/schema.ts (Kysely types) and created by the migrations in src/db/migrations/. Every app table cascades from installations through repositories, which is what makes pnpm graft pilot purge complete; webhook_deliveries and pilot_purges have no foreign key (the purge deletes the installation's deliveries itself, and pilot_purges outlives the purge). guard_events is written by the Phase 1 post-merge guard (steps 4 and 5), with main_commits and ci_results; step 5 adds the revert columns (outcome and reason codes, counts, the revert's commit SHA, branch and PR number, auto-merge state), never a path, title or body. Only paths, SHAs, numbers, logins or user IDs where needed, and the model's own prose are stored; never file contents, diffs, PR titles or bodies.
erDiagram
installations ||--o{ repositories : "has"
repositories ||--o{ tasks : "has"
repositories ||--o{ changes : "has"
tasks |o--o{ changes : "linked to"
changes ||--o{ provenance : "trailer rows"
changes ||--o| change_provenance : "resolved"
changes ||--o{ intent_cards : "per head"
intent_cards ||--o{ intent_feedback : "votes"
changes ||--o{ intent_feedback : "votes"
intent_cards ||--o{ intent_displays : "shown"
changes ||--o{ intent_displays : "shown"
repositories ||--o{ intent_spend : "ledger"
repositories ||--o{ mode_changes : "mode audit"
changes ||--o{ audit_log : "break-glass"
changes |o--o{ intent_spend : "ledger"
changes ||--o{ policy_verdicts : "per head"
repositories ||--o{ guard_events : "Phase 1"
repositories ||--o{ main_commits : "default-branch history"
repositories ||--o{ ci_results : "CI result classes"
changes |o--o{ guard_events : "culprit"
changes ||--o{ pr_reviewers : "eligible reviewers"
changes ||--o{ reviewer_check_denials : "403 or 404"
repositories ||--o{ review_time_runs : "baseline or shadow"
review_time_runs ||--o{ review_time_prs : "per PR numbers"
repositories ||--o{ incidents : "escaped defects"
repositories ||--o{ metrics_daily : "daily counters"
repositories ||--o{ mcp_tokens : "token hashes"
repositories ||--o{ mcp_changes : "PRs opened through MCP"
mcp_tokens ||--o{ mcp_changes : "opened with"
installations {
bigint id PK
bigint account_id
text account_login
text repository_selection
timestamptz deleted_at
}
repositories {
bigint id PK
bigint installation_id FK
text full_name
timestamptz removed_at
}
tasks {
uuid id PK
bigint repository_id FK
text external_id
int issue_number
}
changes {
uuid id PK
bigint repository_id FK
int pr_number
uuid task_id FK
text head_sha
text base_ref
bigint author_id
text state
timestamptz pr_updated_at
bigint graft_comment_id
}
provenance {
uuid id PK
uuid change_id FK
text source
text agent
text model
}
change_provenance {
uuid change_id PK
text head_sha
text author_kind
text author_kind_reason
bigint check_run_id
}
intent_cards {
uuid id PK
uuid change_id FK
text head_sha
text status
text risk_class
text risk_floor
text verifier_status
timestamptz published_at
}
intent_feedback {
uuid id PK
uuid card_id FK
uuid change_id FK
bigint user_id
text verdict
text source
}
intent_displays {
uuid id PK
uuid change_id FK
uuid card_id FK
text status
timestamptz shown_at
}
intent_spend {
uuid id PK
bigint repository_id FK
uuid change_id FK
int tokens
numeric cost_usd
timestamptz spent_at
}
policy_verdicts {
uuid id PK
uuid change_id FK
text head_sha
text policy_status
text outcome
text check_conclusion
text facts_hash
}
guard_events {
uuid id PK
bigint repository_id FK
uuid culprit_change_id FK
text status
text failing_sha
text last_green_sha
bigint comment_id
}
main_commits {
bigint repository_id FK
text sha
text parent_sha
bigint seq
boolean chain_break
text pr_source
int pr_number
}
ci_results {
bigint repository_id FK
text sha
text key
text name
text source
text class
}
webhook_deliveries {
text delivery_id PK
text event
text status
text job_id
}
pr_reviewers {
uuid change_id FK
bigint user_id
text reason
boolean verified
}
reviewer_check_denials {
uuid change_id FK
bigint user_id
smallint status
}
review_time_runs {
uuid id PK
bigint repository_id FK
text period
date from_date
date to_date
}
review_time_prs {
uuid run_id FK
int pr_number
text author_kind
text start_basis
}
incidents {
uuid id PK
bigint repository_id FK
int culprit_pr_number
int fix_pr_number
text source
}
metrics_daily {
bigint repository_id FK
date day
int rollup_version
jsonb counts
}
audit_log {
uuid id PK
bigint repository_id FK
uuid change_id FK
text head_sha
text kind
text actor_login
bigint label_event_id
text policy_mode
}
mcp_tokens {
uuid id PK
bigint repository_id FK
text name
text token_hash
text token_prefix
timestamptz expires_at
timestamptz revoked_at
}
mcp_changes {
uuid id PK
bigint repository_id FK
uuid token_id FK
int pr_number
text head_sha
}
pilot_purges {
uuid id PK
bigint installation_id
jsonb rows_deleted
}
TABLE_NAMES in src/db/schema.ts lists all 27 tables (Phase 1 added mode_changes, service_state, audit_log, main_commits, ci_results, mcp_tokens and mcp_changes); OWNED_ROWS in src/pilot/purge.ts must cover each of them (I-PURGE-2).