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.

  1. 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

    ruleAllow

    yes

    yes

    write and edit only

    plainLineOutcome

    yes

    yes (line text)

    per argument

    scratchWriteAllow

    no

    no

    yes

    workspaceWriteAllow

    no

    no

    yes

    workspaceReadAllow

    no

    no

    yes

    planDraftCarve

    no

    no

    no

    judge.adoc and modes.adoc say 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.

  2. The loop guard and the review log are fed by hand in each stage. authorize.ts calls deps.denials.record at seven sites. judge.adoc says every deny counts; the plan-draft deny outside plan mode (planDraftCarve) does not call it.

  3. A verdict need not say who decided, and each reader guesses differently. AttributedVerdict.source is optional. A missing one is read as "judge" at five sites in judge-wiring.ts, null in debugVerdict, "policy" in monitor-tools.ts, "rule" in otel-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, VerdictSource has "mode" and TraceSource (trace.ts) does not, so manual mode’s defer renders its mark as undefined.

  4. The order is written three times and no two agree. The code runs 13 steps; the authorize.ts header 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

adjudicateSpawn

2

plan draft

no

planDraftCarve

3

rule deny

no

ruleDeny

4

registry

no

registryStage

5

pending

no

pendingStage

6

high consequence

no

highConsequence

7

rule allow

yes

ruleAllow

8

plain line

yes

plainLineAllow

9

scratch write

yes

scratchWriteAllow

10

workspace write

yes

workspaceWriteAllow

11

workspace read

yes

workspaceReadAllow

12

no judge

no

the two inline returns before the judge

13

denial threshold

no

thresholdDefer

14

judge

no

judgeStage

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 expression ruleAllow uses 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 and credentialShaped(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 /tmp/x/.env skips the judge while the same write does not

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 modes.adoc as the one exception

delegation gate allow

exempt

exempt

exempt

structural; names an agent, not an action

pending approval (takeApproved)

exempt

exempt

exempt

the human answered; finalVerdict already exempts it

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 judge.adoc)

a judge allow or defer; a /pending approval; a reply the judge read, any outcome but deny

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 undefined

—

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.

  1. Characterise. packages/pi-modes/test/gate-characterisation.test.ts and a committed fixture test/fixtures/gate-verdicts.json: every case of eval/corpus.json (294) through authorizeAsk in the case’s own mode, set up as eval-rules.test.ts sets it up (real temporary workspace, warmed parser, published redactor, its counting proxy for a model registry, a fresh DenialTracker), recording kind, source, pattern, the review events' names, and the tracker’s snapshot() after the ask. Written against today’s code, before any change.

  2. 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.

  3. Stage table, heldForJudge, runner bookkeeping. Fixture diff: none on the corpus (B1–B4 are pinned by their own tests).

  4. Docs and note: architecture.adoc, judge.adoc (valve section, denial guard), modes.adoc (the rule-allow stand-back cases, the plan-draft exception), the authorize.ts header, 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

gate-characterisation.test.ts against the fixture

"nothing else changes": any verdict, source, event or count that moves fails

regression

gate-stages.test.ts: for each guarded row × each heldForJudge reason that applies to it (all three, except plain line × credential, which the design table marks n/a and the test names as its one skipped cell), an ask that row allows today is not allowed by it (verdict source is the judge’s or the valve’s). Built from GATE_STAGES.filter(s ⇒ s.guarded), so a new guarded row is covered without a new test; a row with no sample ask fails the test

"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 /pending approval are allowed with a valve pattern naming them

the three exemptions

regression

same file: the plan-draft deny outside plan mode raises snapshot().consecutive by one

B4

regression

same file: the guard value for one verdict of each row of the loop-guard table

"no stage calls denials.record`" is pinned by a source assertion: `authorize.ts holds exactly two denials.record( calls, both in the runner

contract

gate-order.test.ts: reads docs/modules/ROOT/pages/architecture.adoc with readFileSync (path from import.meta.dirname, three levels up to the repository root), takes the text between the heading == The life of one action and the next == heading, and collects from each line matching /^\s+(\d+)\.\s+(.+?)\s{2,}\S/ the number and the name. The numbers must be 1..14 in sequence and the names must equal GATE_STAGES.map(s ⇒ s.name). No stage name contains two consecutive spaces (asserted)

"the order is stated once"

contract

trace.test.ts: formatTrace of a mode defer contains no undefined; MARK has a key for every VerdictSource member, from a shared list

B6, and the two source types never drift again

contract

otel-export.test.ts: a spawn allow’s span carries the gate as source

B5

contract

typecheck: a verdict literal without source does not compile (@ts-expect-error in authorize.test.ts)

"`source` is required"

regression

tools/lib/test/plain-line-field.test.mjs, unchanged, still passes

the field tool’s why

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 guarded: false, so an allow skips the checks

fail-open

gate-stages.test.ts iterates the rows and requires a sample ask per allow-capable row; the design table above is asserted row by row

heldForJudge holds asks that were free, so the judge is called more and auto mode slows

fail-closed

0 hits in 12,420 real calls; the characterisation fixture shows any corpus case that moves

A stage’s guard value differs from today’s call, so the loop guard trips early or late

silent

the fixture records snapshot() per case; the loop-guard table is tested value by value

An event name or payload changes and task verdicts miscounts

silent

the fixture records event names; existing event assertions in authorize.test.ts are unchanged

The registry stage’s added facts are lost between rows

silent

existing registry tests in authorize.test.ts assert the judge receives packages; they pass unchanged

A reader of source outside pi-modes relied on a missing one

fail-closed

source is a compile error when absent; attributeDeny keeps its default for untyped input

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 in nav.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.

Edit this page · latest