Plan: the gate’s stages as one table, its allow checks asked once
Closes: #901. Relates to: #884 (the audit), #888, #923, #222, #168. Branch: refactor/gate-stage-table. Status: Done (2026-11-25) — the gate runs as one table, its allow checks asked once, every verdict names its decider; follow-ups #934, #935
Context: what is wrong with the present order
Ruled by the operator (2026-11-24): #901 is a design question, and the plan says what is wrong with the present order of decisions before proposing another. Approach agreed in conversation (2026-11-25): keep the order; ask the shared checks once; make source required; count and log in the runner; state the order once.
The order itself is not wrong. authorizeAsk (packages/pi-modes/authorize.ts) is already one first-answer-wins sequence. Of the 68 fix commits to the eight approval-path files in the 60 days to 2026-11-24, 52 were about what a stage knows (path naming 13, the judge 15, the queue and host 14, rules, texts) and a different order would not have touched them. The other 16 were sequencing or bookkeeping: 9 where an allow skipped a check another stage makes, 7 where a verdict named the wrong decider. Four defects in the present code produce that class. All were read from source; none was run.
-
Each allow stage carries its own copy of the stand-back checks, and the copies differ.
Allow stage Safety valve Secret-shaped value Credential-shaped name ruleAllowyes
yes
write and edit only
plainLineOutcomeyes
yes (line text)
per argument
scratchWriteAllowno
no
yes
workspaceWriteAllowno
no
yes
workspaceReadAllowno
no
yes
planDraftCarveno
no
no
judge.adocandmodes.adocsay no allow passes the valve. The 101 shipped valve patterns are command-shaped, so the gap does not fire today; an operator’s path-shaped pattern is skipped by three stages. -
The loop guard and the review log are fed by hand in each stage.
authorize.tscallsdeps.denials.recordat seven sites.judge.adocsays every deny counts; the plan-draft deny outside plan mode (planDraftCarve) does not call it. -
A verdict need not say who decided, and each reader guesses differently.
AttributedVerdict.sourceis optional. A missing one is read as"judge"at five sites injudge-wiring.ts,nullindebugVerdict,"policy"inmonitor-tools.ts,"rule"inotel-export.ts. Two verdicts carry none: the delegation gate’s allow (exported as a rule’s) and the defer when no model registry was given. Separately,VerdictSourcehas"mode"andTraceSource(trace.ts) does not, so manual mode’s defer renders its mark asundefined. -
The order is written three times and no two agree. The code runs 13 steps; the
authorize.tsheader numbers 10 and describes the pending lookup in a paragraph beside them;architecture.adoc("The life of one action") lists 9. Neither names the registry check, and the page omits the pending lookup too.
Out of scope, by the agreed approach: the judge (judge.ts), everything after the gate in judge-wiring.ts (queueForHuman, askBeyondTheGate, confirmAtHost, and its four humanIntervened calls), the pending queue, and the order itself.
Design
The stage table
authorizeAsk becomes a loop over one exported constant, GATE_STAGES, in authorize.ts. The array’s order is the order. Each row:
interface Stage {
name: string; // the name the docs list
guarded: boolean; // skipped when the ask is held for the judge (below)
run(ask: GateAsk): Promise<StageResult> | StageResult;
}
// settled: the gate's answer. next: nothing decided, the ask carried on with these details. undefined: nothing.
type StageResult = Settled | { next: AskDetails } | undefined;
interface GateAsk { deps: AuthorizeDeps; mode: ModeDescriptor; details: AskDetails; line: LineVerdict }
interface Settled {
verdict: AttributedVerdict;
guard: "count" | "break" | "leave"; // what the loop guard is told; required
event?: { name: string; details: Record<string, unknown> }; // the review-log record
}
GateAsk is built once, after the three spelling normalisations, which stay where they are. line is a memoised getter over evaluateLine(mode.permission, details, longSpellingFor(deps)), first read by row 3: rows 1 and 2 never read it, so the line is not analysed for a spawn or a plan-draft write, as now. mode === undefined is answered before the table (defer, source mode), as now. The registry stage, the one stage that adds to the ask, returns { next: details } with the package facts added, and the runner builds the following rows' GateAsk from it; no stage mutates GateAsk.
The rows, in today’s order (unchanged):
| # | name |
guarded |
Function today |
|---|---|---|---|
1 |
delegation gate |
no |
|
2 |
plan draft |
no |
|
3 |
rule deny |
no |
|
4 |
registry |
no |
|
5 |
pending |
no |
|
6 |
high consequence |
no |
|
7 |
rule allow |
yes |
|
8 |
plain line |
yes |
|
9 |
scratch write |
yes |
|
10 |
workspace write |
yes |
|
11 |
workspace read |
yes |
|
12 |
no judge |
no |
the two inline returns before the judge |
13 |
denial threshold |
no |
|
14 |
judge |
no |
|
Row 12 answers defer/mode when the mode has no judge, and defer/judge with the reason "no model registry to run the judge" when the registry is absent (today a source-less defer, which every reader but two already reads as the judge’s).
Erratum (2026-11-25): the registry-absent defer carries the text as failure, not reason, as runJudge reports a judge it could not run (failed() in judge.ts): the host then says "the judge could not decide it", as it did for the source-less defer, rather than "the judge asks a human: no model registry…".
Erratum (2026-11-25): the loop is runGate(stages, deps, raw), exported, and authorizeAsk hands it GATE_STAGES, so a test can run the runner over rows of its own; with no row answering it resolves to a defer (judge, failure "no stage of the gate answered").
The shared checks: heldForJudge
One exported function, heldForJudge(mode, details, units): "valve" | "secret" | "credential" | undefined, computed by the runner once per ask, lazily before the first guarded row. When it answers, rows 7–11 are skipped and the ask goes on to rows 12–14, where the valve caps a judge allow to a defer as it does now. It asks, in order:
-
valve:
mode.judge !== undefined && hitsSafetyValve(mode.judge, { …details, units }), the expressionruleAllowuses now; -
secret:
holdsSecretShaped([fullCommand, command, value, path, toolInputPreview]), `ruleAllow’s list; -
credential: the ask’s tool (
toolName ?? surface) is one of read, grep, find, ls, write, edit andcredentialShaped(basename(toolPath(path))).
The copies in ruleAllow and plainLineOutcome’s valve and secret lines are deleted. `plainLineOutcome stays exported for tools/lib/plain-line-field.mjs and calls heldForJudge for its why (valve, secret), so the field tool’s tallies keep their meaning. Checks that need the path’s real location stay in their stage: isPlainWorkspaceRead’s and `isPlainRemoteRead’s resolved-name check, the plain line’s per-argument `readable, the remote stages' remoteTarget.
Erratum (2026-11-25): the scratch-write and workspace-write rows' own credential-name checks are deleted too. Each read the basename of an unresolved spelling of the path, the host’s toolPath or, in a remote session, the POSIX remoteTarget; heldForJudge reads the host’s toolPath, whose basename is the same for a POSIX path on either platform. Neither collapses a trailing . or .., a gap that predates this plan (#935). The why union gains credential, which a bash line never produces.
Every cell, decided:
| Allow | Valve | Secret | Credential | Why |
|---|---|---|---|---|
rule allow |
held |
held |
held, reads too |
today a rule-allowed read of |
plain line |
held |
held |
n/a (no path; per argument stays) |
the valve is unchanged; the secret check widens from the line’s text to `ruleAllow’s list, which for a bash ask adds the preview (B7) |
scratch write |
held |
held |
held |
the docs' claim made true |
workspace write |
held |
held |
held |
the docs' claim made true |
workspace read |
held |
held |
held |
the docs' claim made true |
plan draft |
exempt |
exempt |
exempt |
one file the harness names, in plan mode only; it already precedes the rule deny. Stated in |
delegation gate allow |
exempt |
exempt |
exempt |
structural; names an agent, not an action |
pending approval ( |
exempt |
exempt |
exempt |
the human answered; |
What a write’s check can see: the permission system’s preview of a write or edit carries the path and counts, never the content, so secret on rows 9–11 reads the path and a search pattern only. The plan does not claim more.
The loop guard and the log, in the runner
The runner, after a row settles: guard === "count" calls denials.record("deny"); "break" calls denials.record("allow"); "leave" calls nothing; then emits event if present. No stage calls denials.record. The values, which reproduce today’s calls except the one marked:
| Settled by | guard |
|---|---|
a deny from the delegation gate, a rule, the registry, the judge |
count |
the plan-draft deny outside plan mode |
count (changed: uncounted today, against |
a judge allow or defer; a |
break |
a rule or stage allow; high consequence; threshold; no judge; waiting with no reply |
leave |
pendingStage’s `denials.release() and its gadhs_pending.threshold_settled record are not a verdict’s and stay inline. The judge’s own records still go through runJudge’s `log. Event names and payloads are unchanged: they are public surface (public-surface.adoc, task verdicts).
source is required
AttributedVerdict.source loses its ?. The delegation gate’s allow gets source: "gate". The eight defaults for a missing source are deleted (judge-wiring.ts five, debugVerdict, monitor-tools.ts, otel-export.ts). attributeDeny keeps its default row: it takes unknown from outside the type. TraceSource gains "mode", with a MARK entry and a remedy line ("this mode runs no judge and no rule decides it; answer the prompt, or add a rule").
Erratum (2026-11-25): no remedy line for "mode". The trace states a remedy only for a deny, and a mode verdict is always a defer, so the line could never be shown. The MARK entry is mode (no judge).
The order, stated once
The authorize.ts header’s numbered list is replaced by a pointer to GATE_STAGES. In architecture.adoc the nine stage lines inside the diagram’s source block are replaced by fourteen, each of the form <n>. <name> <gloss>: the number 1 to 14 with a full stop, the stage’s name exactly as in the constant, then at least two spaces and the gloss (3b, 5a, 5b go). The rest of the diagram is untouched. A test holds the page to the constant.
Behaviour that changes
| # | Change | Seen in real sessions |
|---|---|---|
B1 |
A valve hit holds scratch, workspace-write and workspace-read allows for the judge |
cannot fire with shipped patterns |
B2 |
A secret-shaped path or pattern holds those three |
0 of 12,420 file-tool calls (pi, canopy, craig) |
B3 |
A rule-allowed read of a credential-shaped name goes to the judge |
0 of 994 rule-allowed reads |
B4 |
The plan-draft deny outside plan mode counts toward the loop guard |
— |
B5 |
A spawn allow is attributed to the gate, not a rule, in the decision span |
— |
B6 |
Manual mode’s defer shows a mark in the trace instead of |
— |
B7 |
A plain line whose preview, not its text, holds a secret-shaped value goes to the judge |
the characterisation fixture shows any corpus case that moves |
Nothing else changes; the characterisation test below is what says so.
Scope
One MR, four commits, each green on its own.
-
Characterise.
packages/pi-modes/test/gate-characterisation.test.tsand a committed fixturetest/fixtures/gate-verdicts.json: every case ofeval/corpus.json(294) throughauthorizeAskin the case’s own mode, set up aseval-rules.test.tssets it up (real temporary workspace, warmed parser, published redactor, its counting proxy for a model registry, a freshDenialTracker), recordingkind,source,pattern, the review events' names, and the tracker’ssnapshot()after the ask. Written against today’s code, before any change. -
Source required. The type, the two verdicts,
TraceSource, the eight defaults, and test literals handed to typed readers. Fixture diff: B5 and the registry-absent defer only. -
Stage table,
heldForJudge, runner bookkeeping. Fixture diff: none on the corpus (B1–B4 are pinned by their own tests). -
Docs and note:
architecture.adoc,judge.adoc(valve section, denial guard),modes.adoc(the rule-allow stand-back cases, the plan-draft exception), theauthorize.tsheader,CHANGELOG.adoc.
Not in this plan: moving the 485 lines of path helpers out of authorize.ts (all 13 path fixes landed there). It is a pure move with its own review cost; filed as #934.
Tests
All in packages/pi-modes/test/, vitest.
| Category | Test | Pins |
|---|---|---|
regression |
|
"nothing else changes": any verdict, source, event or count that moves fails |
regression |
|
"every allow in rows 7–11 is held" (B1–B3); fails on today’s code for scratch, workspace write, workspace read, and a rule-allowed read |
regression |
same file: the plan draft in plan mode, a spawn allow and a |
the three exemptions |
regression |
same file: the plan-draft deny outside plan mode raises |
B4 |
regression |
same file: the guard value for one verdict of each row of the loop-guard table |
"no stage calls |
contract |
|
"the order is stated once" |
contract |
|
B6, and the two source types never drift again |
contract |
|
B5 |
contract |
typecheck: a verdict literal without |
"`source` is required" |
regression |
|
the field tool’s |
Existing suites (authorize.test.ts 135, rule-precedence.test.ts 35, plain-line.test.ts 21, eval-rules.test.ts) pass with only the two changed expectations: the registry-absent defer (authorize.test.ts) and the source-less literal in human-requests.test.ts. No test is weakened or removed. Coverage bar for pi-modes (97 lines / 90 branches) holds. Mutants: each of B1–B4 reverted in turn must fail its test.
Risks
| Risk | Fails | Mitigation |
|---|---|---|
A guarded row is mislabelled |
fail-open |
|
|
fail-closed |
0 hits in 12,420 real calls; the characterisation fixture shows any corpus case that moves |
A stage’s |
silent |
the fixture records |
An event name or payload changes and |
silent |
the fixture records event names; existing event assertions in |
The registry stage’s added facts are lost between rows |
silent |
existing registry tests in |
A reader of |
fail-closed |
|
An operator’s path-shaped valve pattern now queues ordinary in-tree writes |
fail-closed |
that is what the docs promised; named in the release note |
Delivery
-
Canonical page:
architecture.adoc("The life of one action") for the order; `judge.adoc’s valve section for what an allow must pass. -
CHANGELOG.adoc== Unreleased: B1–B6, in the operator’s terms. -
This plan committed as
docs/modules/ROOT/pages/plans/gate-stage-table.adoc, listed innav.adoc, Status In progress at start and Done at merge. -
Validate, consumer-sim, MR with
Closes #901, merge with squash off, merge SHA on the issue. pi-modes minor bump at the next release; pi-remote follows.