* enhance(#2483): env-guard the claude reviewer leg against CLAUDE.md injection
The claude reviewer in workflows/review.md was a bare headless `claude -p`
spawn run from the project cwd, so it inherited the invoking user's global
CLAUDE.md, the project CLAUDE.md, and Claude Code auto-memory.
That made it the only reviewer leg seeing anything beyond the prompt file.
gather_context assembles PROJECT.md, the roadmap section, every PLAN file,
CONTEXT.md, RESEARCH.md and REQUIREMENTS.md into the prompt before any
reviewer runs; the gemini leg receives only that prompt and the codex leg
runs --ephemeral. Beyond the measured ~4k tokens/spawn, the asymmetry cuts
at the workflow's own premise: "independent review" meant something
different for the claude leg than for the other two.
Guard both dispatch lines with a per-invocation
`env CLAUDE_CODE_DISABLE_CLAUDE_MDS=1`. `env`, never `export` — the flag
must not leak into the orchestrating session (which may itself be Claude
Code on the SELF_CLI="auto" path) or into any later spawn.
review.md is the only claude -p call site in the installed tree, so this is
two lines on one surface. The self-skip logic is untouched.
* enhance(#2483): fix CRLF-fragile split and regenerate workflow baselines
Two CI failures from the first push, both mine:
1. lint-tests: the new regression test split readFileSync content on a
literal "\n". On a Windows git-autocrlf checkout that leaves a trailing
"\r" on every line (local/no-crlf-fragile-split). Use .split(/\r?\n/).
2. golden-install-parity / workflow-size-budget / workflow-compat: editing
gsd-core/workflows/review.md changes its content hash and byte size, and
both are pinned in committed baselines. Regenerated via the repo's own
generators (npm run size:baseline, npm run gen:golden).
The regenerated diffs are review.md-only: exactly one hash line per
golden-install-parity fixture and one size entry in workflow-size-baseline
— no unrelated drift swept in.
Full suite now green locally: 2113 pass, 0 fail, 3 skipped (run with HOME
and CLAUDE_CONFIG_DIR overridden to throwaway dirs; live profile verified
untouched afterward).
* enhance(#2483): adapt guard-test matcher to the effort-args dispatch reshape
The effortSurface wiring (#2481) reshaped the bare-model dispatch to
`claude $CLAUDE_EFFORT_ARGS -p -`; the invocation matcher's dash-first
form could no longer see it, and the count assertion failed exactly as
designed. The matcher now tolerates variable expansions between `claude`
and its first literal flag. Negative-controlled both ways: a stripped
guard and a deleted dispatch line each still fail.
* enhance(#2483): also guard the claude leg against auto-memory injection
CLAUDE_CODE_DISABLE_CLAUDE_MDS suppresses CLAUDE.md file loading;
auto-memory is an independently-toggled mechanism with its own flag.
Add CLAUDE_CODE_DISABLE_AUTO_MEMORY=1 to both dispatch lines, correct
the docs/COMMANDS.md and changeset claims that credited the first flag
with covering auto-memory, and extend the regression test to require
both flags on every claude invocation (negative-controlled: 2/4
assertions fail with the new flag removed).
* enhance(#2483): match the claude binary in command position, not argument position
The line-oriented invocation matcher counted any line where the token
`claude` was followed by a flag. #2589 (landed on next as 920a5f3f)
reshaped the effort-args lookup from
--host claude 2>/dev/null | jq -r '.effort_argv_string // ""'
to
--host claude --pick effort_argv_string
which put a flag immediately after `claude` and made the config query
read as a third claude dispatch, failing the count assertion.
The defect class is a binary name in *argument* position being read as a
command. Fixed at the class rather than the instance: tokenise the line
and skip any `claude` whose preceding token is a flag. That also covers
the latent sibling one line away in review.md (`command -v claude`),
which escaped today only because its next token is a redirect.
Negative-controlled four ways: stripping CLAUDE_CODE_DISABLE_AUTO_MEMORY=1
fails, stripping the whole env guard fails, adding a genuine third
unguarded dispatch (`timeout 900 claude --output-format text -p -`) still
fails — so the narrowing did not blind the matcher to reshapes, which is
the property the count assertion exists for — and the pre-#2589 jq form of
the lookup still passes, so the matcher is not pinned to today's base.
* enhance(#2483): carry the claude reviewer's memory guard as declared lane data
ADR-2782 Phase 5b replaced the hand-authored per-CLI dispatch legs in
review.md with the declared lane table, so the two `env`-prefixed shell
lines this PR previously added no longer have a surface to live on. The
guard is reimplemented where the lane contract now lives.
`SpawnInvoke` gains an optional `env`, the claude lane declares the pair,
the resolver folds own string-valued entries into `SpawnPlan.env` (absent
or empty resolves to null, so the runner has one shape to test), and the
runner passes it to spawn. Production merges it OVER `process.env` into a
fresh object for that one child, so nothing reaches the orchestrating
session or any other lane in the run.
Declared data rather than a handler (D6): the pairs are static per lane,
which is precisely what the manifest vocabulary is for. The capability
manifest carries the same field, because the lane-fidelity test compares
manifest and descriptor over the union of `invoke`'s keys.
The regression test is rewritten against the resolver and runner rather
than review.md's text. It gains the property the source-text assertions
could only approximate: that `process.env` is never mutated.
Scope boundary, asserted rather than left in prose: `env` is not part of
the trust-disclosure surface, which is safe only while no manifest body
reaches the resolver — the registry's reviewer bodies contribute slugs to
the parity check and execution resolves from `REVIEWER_LANES`. The new
test fails first if that ever changes.
* enhance(#2483): restate the guard's mechanism in the docs and changeset
Both described the fix as two `env`-prefixed dispatch lines, which is the
surface ADR-2782 Phase 5b removed. The user-visible behaviour is
unchanged; the carrier is not, and a changeset that ships a description
of a mechanism the tree does not have is a CHANGELOG entry nobody can
verify against the code.
* enhance(#2483): cover the production spawn wiring end to end
The unit tests stop at the runner's `deps.spawn` seam — every one injects
a spy. Production supplies that seam in `gsd-core/bin/gsd-tools.cjs` as a
hand-written object no test constructs, so the chain could be correct all
the way to `SpawnPlan.env` and the merge could still be wrong or absent
with the suite green. Deleting those four lines was the one mutation that
left every other control silent.
This runs the real `spawnSync` through `gsd-tools review-lane invoke`,
with a `claude` shim on PATH that records the environment it was handed.
It asserts both halves in one test: the pair arrives, and an unrelated
inherited variable survives — a wiring that REPLACED the environment
rather than merging over it would satisfy the first and break every
lane's PATH and HOME.
POSIX-only; mediating a Windows `.cmd` shim is a separate concern the
repo already tests on its own.
Noted rather than fixed: `timeout`, `killSignal`, `maxBuffer` and
`shell: false` on that same object are equally uncovered. That is the
epic's gap, not this change's, and closing it is not in scope here.
* enhance(#2483): validate the invoke.env shape and register it as spawn-only
`env` was the one spawn-invoke field with no shape enforcement: every sibling in
`validateSpawnInvoke` is checked, and a manifest declaring `env` as an array, a
string, a number, or an object with non-string values passed validation in
silence. That matters more than an ordinary schema gap here, because
`resolveLanePlan` DROPS a non-string value rather than coercing it — so an
unvalidated manifest declares a pair that never reaches the spawn, which is the
failure a memory guard can least afford.
Two registrations, not one. `env` was also absent from
`SPAWN_ONLY_INVOKE_FIELDS`, which is the list the openai-http arm rejects
against — so `invoke.env` was accepted on a transport that issues an HTTP POST
and has no child environment at all. It was the only spawn-shaped field accepted
there; the other six each produce two errors. Self-found while sweeping the
class, not raised in review.
Keys are held to the portable POSIX environment-name grammar. That is a policy,
not a claim about what an environment can hold: measured, only NUL is actually
rejected by `spawnSync`, while `=`, a leading digit, a dash and a space are all
carried through to the child (an `A=B` key arrives as the raw entry `A=B=value`).
They are refused because a name outside the grammar is not portably addressable
by the program meant to read it.
`__proto__` is refused for a different and concrete reason. It passes that
grammar and is a real own key once a manifest is JSON-parsed, but assigning it
onto a plain accumulator goes through the inherited `__proto__` setter rather
than creating an own property — and for the string values this field permits the
setter is a no-op that does not even change the prototype. The pair would
validate and then simply vanish before the spawn. (An environment CAN carry a
literal `__proto__` entry; this is about the resolver's accumulator, and the
error message says so.)
Deliberately narrower than the sibling reserved-name guards in this file, which
also reject `constructor`/`prototype`: those guard bracket lookups that resolve
prototype members, whereas this reads via `Object.keys` plus an own-value read,
where `constructor` assigns as an ordinary key the spawn could carry.
`effortChannel` is deliberately left in neither field list: ADR-2782 D2 defines
it for both transports, so it is shared rather than spawn-only.
Reversion-controlled, three mutations, all three fire a named test: dropping
`env` from the discriminator fails `httpTransportRejectsEnv`; removing the
`__proto__` arm fails `envRejectsProtoKeyThatWouldSilentlyVanish`; disabling
the block fails four.
(#2483)
* enhance(#2483): amend ADR-2782 D2 for the invoke.env vocabulary widening
D2 records the spawn `invoke` shape as a closed vocabulary, and its Amendments
section carries a dated entry for every prior widening (Phase 1 #2794, Phase 2
corrections #2795, Phase 5b #2799). This change extended that vocabulary in code
without touching the ADR governing it, so the ADR contradicted the
implementation — and the repo's own convention, recorded in CONTEXT.md, is that
the ADR is amended in the same PR precisely because the prior widenings did it
correctly.
Adds the `invoke.env` row to the D2 table and a dated Amendments entry.
The entry also corrects the authority this change cited. The source comment
pointed at D6, which governs the closed `handler` enum — imperative behavior
admitted first-party — and says nothing about the `invoke` field vocabulary.
That is D2's territory, so the citation never covered the gap.
Two claims are corrected rather than restated, both about the trust boundary
that justifies leaving `env` out of the D5 disclosure signature:
- The regression test does not enforce that boundary. On one forged lane it
shows the resolver folds whatever it is handed, so a future path feeding it
manifest lanes would not make any assertion in that test fail. Its comment
claimed it "will fail first"; that was wrong, and both the comment and the
ADR now say the boundary is a property of the production call chain instead.
- The ADR is internally inconsistent on whether third-party manifest lanes
execute at all: Consequences says adding a reviewer needs "no core patch",
while `gsd-tools.cjs` rejects every slug absent from the first-party
REVIEWER_LANES map. CONTEXT.md, `workflows/review.md` and the resolver's own
header take the first view. #2483 did not create that inconsistency and does
not resolve it; the entry records it rather than settling it in its own favour.
(#2483)
* enhance(#2483): document invoke.env in the capability-manifest reference
ADR-2782 points capability and plugin authors at
`docs/reference/capability-manifest.md` as where the lane vocabulary must be
visible, and its `invoke` row enumerates the spawn sub-shape field by field.
`env` was absent from that table while being part of the real shape, so the one
document a third-party capability author would actually consult to learn the
field exists did not mention it.
Squarely Diataxis reference material — a field-by-field schema description — so
it goes here rather than in the user-facing prose, which was already updated.
States the constraints a manifest author can actually trip, and is explicit that
the name grammar is a portability policy rather than an OS limit, so a reader
does not take it for a claim about what an environment can hold.
(#2483)
* enhance(#2483): disclose and sign the reviewer lane's env and residual invoke fields
`invoke.env` was undisclosed at install time. That was defensible while manifest
lanes could not execute — the premise this PR's own ADR amendment recorded — and
#2927/#3062 retired it: `routeReviewLane` now merges installed overlay `reviewer`
bodies into its lane map via `mergeReviewerLanes`, which is a field-identical merge
by ADR-2782 D1 and deliberately does not deep-validate. An overlay's whole `invoke`
therefore reaches `resolveLanePlan`, and `env` reaches the spawned child. A consented
third-party capability could set `NODE_OPTIONS=--require ./evil.js` on a reviewer lane
with no install-time disclosure and no re-consent.
The same file already decided what `env` means in a manifest: MCP servers fold it into
the disclosure signature and render each key and value in the consent prompt, with an
inline rationale naming this exact shape. Reviewer lanes get the identical treatment.
`env` was the ninth unsigned invoke field, not the first. `defaultHost` (the manifest's
OWN fallback egress host, used whenever the config key resolves to nothing),
`path`, `outputChannel`/`outputArg`, `modelArg`, `effortChannel` and `modelDiscovery`
all reach `resolveLanePlan` and none was bound. Enumerating a ninth name leaves the
tenth open, so the lane signature carries a RESIDUAL of every other declared `invoke`
key — the completeness backstop `rawConfig` already gives the MCP line (#1459 finding 5),
and the "sign the whole object" remedy the recorded decision on this class prefers.
`defaultHost` is also rendered: `resolvedHost` comes from user config, so a lane whose
key is unset displayed "(unresolved …)" — which reads as "no destination" — while the
runtime egresses the plan and review text to the address the manifest picked.
D4.5 is preserved one level down: the extra element is appended ONLY when the lane
declares something beyond the eight already-bound fields, so an env-free lane's
signature stays byte-identical and no already-consented capability is re-prompted for
a field it does not use. A lane that does declare one re-consents, which is the point.
Execution-primitive env names are FLAGGED in the prompt, not refused in the validator.
A denylist cannot be the boundary here: `PATH` alone is a complete execution primitive
for a spawn lane and can never be refused, the child is an arbitrary third-party binary
so the true set spans every interpreter's injection vars, and the MCP `env` this mirrors
refuses nothing and discloses everything. Missing a name costs a quieter line, never a
boundary.
Refs #2483.
* enhance(#2483): exercise the real overlay merge path in the guard test
The test named for the manifest/first-party boundary did not test it. It built a
forged lane locally, handed it straight to `resolveLanePlan`, and asserted that
`REVIEWER_LANES` did not contain it — so no assertion in it depended on the claim its
name made, and a code path that fed manifest lanes to the resolver would not have made
it fail. Its own comment said as much, and named the production chain as the real
carrier of the guarantee: "gsd-tools.cjs builds its lane map solely from REVIEWER_LANES".
That sentence is now false. #3062 merged overlay reviewer bodies into that map, so the
test's premise and its subject both moved.
The replacement routes through `mergeReviewerLanes` — the real helper the production
path calls — and asserts the overlay lane is admitted, resolves, and carries its `env`
into `SpawnPlan.env`. That makes the security property falsifiable instead of narrated.
It then asserts what now backs it: the env is disclosed on the surface, rendered key
and value in the consent prompt, flagged when the name is an execution primitive, and
bound to the signature so a value change, an addition, or a removal each force
re-consent.
Three further cases, because the finding's generative half is what stops it recurring:
the residual backstop is asserted against five fields including one that does not exist
(`aFieldThatDoesNotExistYet`), so a future vocabulary widening cannot silently re-open
this; a fully-enumerated lane is pinned to its original 8-tuple, which is what keeps the
fix from re-prompting every consented capability; and an http lane's manifest-declared
`defaultHost` is asserted to reach both the prompt and the signature.
Reversion-controlled, seven mutations, all seven fail a named test: env dropped from the
surface, the prompt's env line removed, the execution-primitive warning removed, the
signature's extra element never appended, the residual emptied, the defaultHost line
removed, and the declares-something test un-widened. The last of those was SILENT on its
first run and its test was written in response, then the control re-run.
Refs #2483.
* enhance(#2483): correct the ADR amendment's manifest-lane premise
The amendment argued `env` needed no D5 disclosure because a manifest's `invoke`
fields never reach `resolveLanePlan`. That was true when written and #3062 retired it
22 hours after this branch's last commit: `routeReviewLane` now builds its lane map
from `mergeReviewerLanes(REVIEWER_LANES, loadRegistry({includeInstalled: true}))`, and
D1's no-translation-layer rule makes that a field-identical merge, so an overlay's
whole `invoke` reaches the resolver and executes.
The entry had named this exact trigger — "were manifest lanes ever made executable,
`env` must join the disclosed surface in that change, and nothing here will trip if it
does not." Nothing tripped. The premise is rewritten to current truth rather than
annotated, because an ADR is read in fragments and a superseded paragraph left standing
reads as live reasoning to the next author; a one-line dated tombstone points at git for
the withdrawn text.
The rewritten entry records four things the first draft could not: that the enumeration
itself was the defect (`env` was the ninth unbound `invoke` field, and `defaultHost` and
`path` are egress-relevant on their own), that the residual is what closes the class,
that D4.5's byte-identical-signature property is preserved by appending the residual only
when a lane declares something beyond the eight bound fields, and that consent — not
shape validation — is the boundary, since no honest env denylist can exclude `PATH`.
It also closes the internal inconsistency the previous entry could only record. This ADR,
`CONTEXT.md`, `gsd-core/workflows/review.md` and `resolveLanePlan`'s own header all said
overlay lanes reach the resolver while the runtime said otherwise; #3062 resolved that in
the documents' favour, which is what makes the disclosure mandatory rather than defensive.
Refs #2483.
* enhance(#2483): record in the manifest reference that invoke fields are consent-bound
`docs/reference/capability-manifest.md` is the field table ADR-2782 points capability
authors at, and it described `invoke` purely as a schema. A third-party author reading it
could not learn that everything they declare there is shown to the user at install and
bound to the consent signature — which is exactly what they need to know now that an
overlay reviewer lane executes (#2927/#3062).
States the two things the schema alone cannot: that `env` and `defaultHost` are named in
the consent prompt and the rest is covered by a residual, so any change to a declared
`invoke` field forces re-consent; and that `env`'s validation is a portability policy
rather than a safety boundary, since `PATH` is a complete execution primitive and cannot
be refused. Names that are execution primitives are highlighted in the prompt instead.
Refs #2483.
* enhance(#2483): add a Security changeset for the reviewer-lane disclosure
The existing fragment describes the enhancement this PR was opened for and stays as it
is. The disclosure fix is a separate user-visible change of a different type: a
capability declaring `invoke.env` or `invoke.defaultHost` will ask for consent once
more, and users are entitled to read why in the changelog rather than discover it as an
unexplained prompt.
Type is `Security` rather than `Changed` because the entry describes a closed
code-execution disclosure gap, not a behaviour adjustment.
Refs #2483.
* enhance(#2483): correct this round's own claim about who gets re-prompted
Self-found while auditing the round's claims before publishing them. The changeset and
the ADR entry both stated that a capability declaring `invoke.env` or `defaultHost`
"will ask for consent once more". That is wrong, and it overstated the cost of the fix
in the one direction a maintainer would have had to take on trust.
A code change to `disclosureSignature` re-prompts nobody. `hasProjectConsent` matches on
the recomputed bundle `contentHash` — the signature has not been the security binding
since #1459 CB-1/CB-2 — and the upgrade path's `executableSetChanged(old, new)` compares
two disclosures both computed by the CURRENT code, so widening the signature moves both
sides of that comparison equally. First-party capabilities never reach the path at all:
the install flow blocks a first-party id before trust evaluation.
What the widening actually buys is forward-looking, and is the real argument for it: an
upgrade whose manifest edits a declared `invoke` field now registers as an
executable-surface change and re-consents, where before it could change what the lane
runs in silence.
Also measured and recorded, because the D4.5 property was stated more strongly than it
deserved: of the twelve first-party reviewer capabilities, ZERO are in the
byte-identical-signature class — every real lane declares at least `effortChannel`. The
property is a guarantee about minimal lanes, not a description of the fleet, and the ADR
now says so.
Refs #2483.
* enhance(#2483): sign and disclose the probe binary and the lane's outer fields
Found by this round's own adversarial review, and it is the same defect one level out:
the `invoke` residual cannot reach the lane body's OUTER fields, and `probeLane` SPAWNS
`probe.binary` with `--help` before dispatch (`review-lane-runner.cts`, the
`command-exists`/`command-capability` arms). An overlay naming an arbitrary probe binary
therefore executes it — unsigned and undisclosed, exactly as `invoke.env` was, and
reachable on the same #3062 path.
The lane element now carries a second residual over the outer fields, and the probe
binary is shown in the consent prompt when it differs from the dispatch binary — it is a
program that runs, and the user is entitled to see it.
TWO fields stay excluded, and that is a decision rather than an omission:
`reviewsSection` and `timeoutFloorMs` are ADR-2782's cosmetic carve-outs (matrix
A10/A13), where re-consenting would present a prompt carrying no security information.
A test pins that they remain excluded, so a later widening cannot quietly reverse D4.5
while claiming to complete this fix.
Also corrects a miscount introduced by the previous commit: the source comment said the
enumeration had fallen behind by "seven fields" and omitted `fallbackModel`, while
asserting `env` was the ninth. `resolveLanePlan` reads twelve `inv.*` fields and four
were bound, so the number is eight. The comment now states the derivation rather than
just the total.
Reversion-controlled: emptying the outer residual fails "repointing the probe binary must
force re-consent"; removing the render line fails its own named assertion.
Refs #2483.
* enhance(#2483): refuse execution-primitive env names as defence in depth
Adopts the review's B5 after this round's own adversarial pass refuted my reason for
declining it. I had argued a denylist was worthless because `PATH` can never be refused.
That was wrong on the facts: no shipped reviewer manifest declares `PATH`, so it can be
refused, and it is the most complete primitive in the set — repoint it at a directory
holding a fake binary and the declared `invoke.binary` is irrelevant. A list that cannot
be exhaustive can still close the highest-confidence, lowest-legitimacy routes.
So the validator now rejects `PATH`, `NODE_OPTIONS`, `LD_PRELOAD`, `DYLD_INSERT_LIBRARIES`,
`BASH_ENV`, `PYTHONPATH`, `PERL5OPT`, `RUBYOPT`, `GIT_SSH_COMMAND`, `JAVA_TOOL_OPTIONS`
and their siblings on a reviewer lane. A lane needing a specific executable declares an
absolute `invoke.binary` instead of reshaping the child's environment.
The comment states plainly that this is defence in depth and NOT the boundary — the
boundary is install-time consent, which discloses every declared pair and binds it to the
signature, so an unlisted name is still SEEN before it runs. That framing is load-bearing:
a future reader who mistakes the denylist for the control will under-invest in the one
that is, which is the failure mode I was trying to avoid by declining it outright.
Two tests: the rejection itself across ten names, and a guard asserting no shipped
reviewer capability declares a denied key — so if the list ever outgrows its evidence,
that surfaces as a decision rather than a silent removal.
Refs #2483.
* enhance(#2483): fix two stale D5 enumerations elsewhere in the ADR
The previous commit rewrote the amendment's premise but swept only the amendment. Two
normative passages earlier in the same ADR still enumerated the old closed field list and
now contradicted it: the `executableSetChanged` trigger list, and the split-binding note
asserting the seven manifest-derived fields were "everything that is SHA-pinned".
That is the failure the rewrite-don't-annotate rule exists to prevent, one section over —
an ADR is read in fragments, and a fragment carries no supersession marker, so a reader
landing on either passage would have taken the superseded enumeration as current.
Both now name the residual as the mechanism rather than restating a list, which is also
what stops them going stale the next time the vocabulary widens.
Found by this round's adversarial review, which grepped the whole document rather than
the section under edit.
Refs #2483.
* enhance(#2483): stop the probe disclosure claiming a spawn that does not happen
The probe line added one commit ago rendered "probes by running: <binary> --help" for
every lane. That is false for `kind: "command-exists"`, which only calls `hasBinary` — a
PATH/filesystem scan that starts no process. Only `command-capability` spawns.
A false statement in a consent prompt is worse than a missing one: the prompt is the
surface a user is asked to trust, and this one overstated what a lane does. Worse, the
test I wrote to prove the fix used `command-exists` — the kind that does NOT spawn — so
it pinned the wrong claim and would have kept the error green forever.
The surface now carries `probeKind` and the two kinds render differently: a spawn is
described as a spawn, a presence check as a presence check. The test exercises both, and
asserts the `command-exists` path never emits the spawn wording.
Also corrects the field-count parenthetical to state its derivation unambiguously —
`resolveLanePlan` reads thirteen `inv.*` fields including `env` (twelve before this PR),
four were bound, so eight were unbound before `env` and nine including it. The bare
"twelve" was true only of the pre-PR tree and read as a claim about the current one.
And retires two comments that argued AGAINST the validator denylist this round then
shipped. Leaving them would have handed the next reader the reasoning for removing it.
Reversion-controlled: conflating the two probe kinds fails a named test.
Refs #2483.
* enhance(#2483): match the reviewer-lane env denylist case-insensitively
The denylist added one commit ago compared exact case, so `Path`, `path`, `node_options`
and `Node_Options` all passed it. Windows environment lookup is case-insensitive, so
those reach the child as `PATH` and `NODE_OPTIONS` — the exact inputs the list names.
An exactly-cased denylist is worse than none: it reads as a control while admitting the
input it was written to refuse, and the next reader has no reason to doubt it. Members
are stored uppercase and the key is folded before lookup; the name grammar already
constrains keys to ASCII, so a plain fold is sufficient.
Reversion-controlled: restoring the exact-case compare fails `envDenylistIsCaseInsensitive`
on `Path`.
Refs #2483.
* enhance(#2483): correct the docs that still described the denylist as absent
Both the ADR and the manifest reference still said `env` carries no denylist and that
`PATH` "can never be refused" — written when that was this round's position, and left
standing after the round reversed it. A reader landing on either passage would have taken
the superseded argument as current, which is precisely the failure the rewrite-don't-
annotate rule exists to prevent.
Both now describe the denylist, name `PATH`'s inclusion and the case-insensitive match,
and keep the limit explicit: the list cannot be complete against an arbitrary child and
disclosure runs before validation, so consent remains the boundary.
The ADR's byte-identical-signature claim is also corrected rather than softened. With the
outer residual in place, a lane producing no residual is one the validator rejects — it
declares no `flags`, `probe`, `emptyOutput`, `evidenceClass`, `requiresBinaries` or
`promptBudgetKey`. So the property is about the ENCODING, not a claim that any real
signature is unchanged, and it is not the argument for the change being safe. That
argument is that consent binds to the bundle contentHash and no existing consent is
invalidated at all.
Refs #2483.
* test(#2483): cover the three new lane disclosure fields in the injection-safety parity guard
The PARITY test in section N exists to catch a renderer field that skips
`renderValueForPrompt` (#3248). Its payload manifest is hand-maintained, so it
covers the fields that existed when it was written — slug, binary, args,
hostConfigKey, handler — and none of the fields this PR adds.
This PR renders three further manifest-supplied values into consent-prompt
lines: `invoke.env` (keys and values), `invoke.defaultHost` and `probe.binary`.
The gap was silent rather than theoretical: with the lane env line reverted to
the pre-#3248 raw form, the whole 948-test lane/capability/trust-disclosure
suite stayed green.
Two manifests, because the shapes render disjoint lines — `defaultHost` only on
the openai-http branch, `env`/`probe` only where declared, and the probe line
only when the probe binary differs from the dispatch binary.
Non-vacuity is asserted on the typed disclosure object and on structural line
counts, not by substring-matching rendered prose: CONTRIBUTING.md forbids raw
text matching on test output, and this section's own header promises structural
assertions only, so a prose match here would have made that promise false.
Negative-controlled three ways against the merged tree, each producing exactly
one named failure: env rendered raw, defaultHost rendered raw, probe binary
rendered raw.
* docs(#2483): extend the #3248 render-site comment to the fields this PR adds
The comment enumerates every manifest-supplied value that must pass through
`renderValueForPrompt`, and it stopped at `handler` — the reviewer-lane fields
that existed when #3248 landed. This PR renders three more (`defaultHost`, the
probe binary, and the env keys and values), so the list understated its own
contract in the one place a future author would check before adding a fourth.
A comment enumerating a closed set is a set that can silently fall behind the
code it describes; the parity test added alongside is what makes the omission
fail loudly rather than read as deliberate.
---------
Co-authored-by: Tom Boucher <trekkie@nomorestars.com>
1266 lines
55 KiB
TypeScript
1266 lines
55 KiB
TypeScript
/**
|
||
* Reviewer Lane Descriptor Module (ADR-2782 Phase 1, #2794 — closes #2690).
|
||
*
|
||
* ONE place where the cross-AI reviewer lane contract is declared as data.
|
||
*
|
||
* Before this module the contract lived in three unrelated surfaces: the roster
|
||
* in `review-reviewer-selection.cts`, ~640 lines of hand-authored per-CLI bash in
|
||
* `gsd-core/workflows/review.md` `invoke_reviewers`, and the hardcoded section
|
||
* headings in `write_reviews`. A cross-cutting fix therefore landed per-leg —
|
||
* #2494 and #2605 were the same empty-output defect filed twice, and #2475 /
|
||
* #2295 / #2272 are the same shape.
|
||
*
|
||
* SCOPE (ADR-2782's phase table). This module DECLARES; it does not execute.
|
||
* `invoke_reviewers` still runs hand-authored legs until Phase 5b (#2799) makes
|
||
* it iterate. What Phase 1 buys is that a leg can no longer be added, removed,
|
||
* or renamed without the table and the REVIEWS.md section moving with it —
|
||
* `checkReviewerLaneParity` below is the `DEFECT.GENERATIVE-FIX` assertion
|
||
* (`CONTEXT.md:797`) that the roster has never had.
|
||
*
|
||
* The descriptor deliberately does NOT promise uniformity. Lane divergence is
|
||
* real and frequently correct (measured timeout floors differ; three lanes are
|
||
* HTTP endpoints with no binary; Antigravity needs a three-layer fallback for an
|
||
* upstream stdout bug). The value is one place where divergence is DECLARED.
|
||
* Behaviour that data cannot express is delegated to a named `handler`
|
||
* (ADR-2782 D6 closed enum) — never to conditionals inside the table.
|
||
*
|
||
* Field names, nesting, and enum members track ADR-2782 D1/D2/D6/D7 so Phase 2
|
||
* (#2795) harvests this shape into the capability manifest without a translation
|
||
* layer — INCLUDING `transport`'s placement at the lane level (see SpawnLane).
|
||
*
|
||
* Building this table against all eleven shipped legs surfaced four cases the
|
||
* ADR's original survey did not cover. Rather than diverge silently — which is
|
||
* exactly the translation layer this module exists to avoid — ADR-2782 was
|
||
* AMENDED in the same PR (see its Amendments section, 2026-07-29). All four are
|
||
* additive widenings of closed enums, each forced by a lane that exists today:
|
||
*
|
||
* 1. `promptChannel: 'none'` — CodeRabbit reviews the working-tree diff and is
|
||
* fed no prompt at all.
|
||
* 2. `outputChannel: 'file-arg'` — Codex writes the review via its own
|
||
* `-o/--output-last-message <FILE>` and discards stdout (#1698), because on
|
||
* Windows it emits teardown noise to stdout after the final message.
|
||
* 3. `outputArg` — the companion to (2): knowing the review lands in a file is
|
||
* useless without the argument that names the file.
|
||
* 4. `flags: string[]` — Antigravity is selected by BOTH `--antigravity` and
|
||
* `--agy`, which a single-valued field cannot express. This also flattens
|
||
* D8's uniqueness invariant across every lane's flags.
|
||
*
|
||
* Phase 2 (#2795) implements the manifest validator against the amended
|
||
* vocabulary, which is the point of amending rather than leaving it to be
|
||
* rediscovered.
|
||
*/
|
||
|
||
/** ADR-2782 D2 — closed transport discriminator; selects the invoke sub-shape. */
|
||
export type LaneTransport = 'spawn' | 'openai-http';
|
||
|
||
/** ADR-2782 D2, widened by the CodeRabbit lane (see module header). */
|
||
export type PromptChannel = 'stdin' | 'argv' | 'argv-file-ref' | 'none';
|
||
|
||
/** ADR-2782 D2, widened by the Codex lane (see module header). */
|
||
export type OutputChannel = 'stdout' | 'file-arg';
|
||
|
||
/** ADR-2782 D2 — how reasoning effort reaches the tool. */
|
||
export type EffortChannel = 'none' | 'argv' | 'env';
|
||
|
||
/** ADR-2782 D2 — CodeRabbit reviews a diff, not the source tree (`review.md:367`). */
|
||
export type EvidenceClass = 'source-grounded' | 'diff-only';
|
||
|
||
/**
|
||
* ADR-2782 D6 — closed enum of first-party imperative modules. Ported in Phase 5b.
|
||
*
|
||
* `'opencode'` was added by Phase 5b (#2799) as an additive widening, forced by a lane that ships
|
||
* today. Phase 1 declared `opencode.handler = null`, but the lane's review is RECONSTRUCTED from
|
||
* assistant `text` parts of a `--format json` stream — `--format json` is the primary invocation,
|
||
* not a fallback, because the default formatter drops the text when the agent ends its turn with no
|
||
* final message (#1936). A data-driven `outputChannel: 'stdout'` copy would write the raw JSON
|
||
* envelope into REVIEWS.md as the review, straight back into #1936.
|
||
*
|
||
* The alternative — an `outputChannel: 'json-parts'` member — was rejected: it pushes a parsing
|
||
* language into the descriptor and would want a selector expression next. D6's whole point is that
|
||
* divergence escapes to NAMED FIRST-PARTY CODE rather than accreting inside data.
|
||
*/
|
||
export type LaneHandler = null | 'antigravity' | 'openai-compatible' | 'opencode';
|
||
|
||
/**
|
||
* What a lane does when it produces no usable output.
|
||
* `stub-with-stderr` is the normalized policy (#2494/#2605): write a diagnostic
|
||
* stub carrying the captured stderr, so `write_reviews` can tell a failed lane
|
||
* apart from a reviewer that ran cleanly with nothing to report.
|
||
* `handler-owned` means the lane's handler writes its own diagnostics.
|
||
*/
|
||
export type EmptyOutputPolicy = 'stub-with-stderr' | 'handler-owned';
|
||
|
||
/** ADR-2782 D7 — every probe that starts a process or connection MUST be bounded. */
|
||
export type LaneProbe =
|
||
| { kind: 'command-exists'; binary: string }
|
||
| { kind: 'command-capability'; binary: string; needle: string; timeoutMs: number }
|
||
| { kind: 'http-reachable'; hostConfigKey: string; path: string; timeoutMs: number };
|
||
|
||
/**
|
||
* Argv placeholders (Phase 5b, #2799).
|
||
*
|
||
* `args` is an argv TEMPLATE, not a prefix. The injected pieces — model, effort, output file,
|
||
* argv-borne prompt — do not all go in the same place, and no positional rule expresses that:
|
||
* `codex` injects the model in the MIDDLE (after the `exec --ephemeral` subcommand) and the output
|
||
* file later still, while `gemini` injects the model first and five lanes end with a bare `-` that
|
||
* must stay last. Splicing by position silently produced
|
||
* `codex --model M -o F exec --ephemeral …`, which is not a valid codex invocation.
|
||
*
|
||
* So each lane declares WHERE each piece goes. A placeholder expands to zero or more argv elements
|
||
* and vanishes when it has nothing to contribute (no model configured, no effort channel, prompt on
|
||
* stdin), which is what lets one template serve the configured and unconfigured cases.
|
||
*
|
||
* This is a closed four-member vocabulary with no expressions, no nesting and no conditionals — a
|
||
* placeholder set, deliberately not a template language. The moment it needs a conditional, the
|
||
* lane wants a `handler` instead (D6).
|
||
*/
|
||
export const ARGV_PLACEHOLDER = Object.freeze({
|
||
/** `modelArg` + the resolved model, or nothing. */
|
||
MODEL: '{{model}}',
|
||
/** The host's effort argv, or nothing unless `effortChannel` is `argv`. */
|
||
EFFORT: '{{effort}}',
|
||
/** `outputArg` + the review path, or nothing unless `outputChannel` is `file-arg`. */
|
||
OUTPUT: '{{output}}',
|
||
/** The argv-borne prompt, or nothing unless `promptChannel` is `argv`/`argv-file-ref`. */
|
||
PROMPT: '{{prompt}}',
|
||
} as const);
|
||
|
||
export interface SpawnInvoke {
|
||
binary: string;
|
||
/** Argv template — see `ARGV_PLACEHOLDER`. Order here is the order the tool receives. */
|
||
args: ReadonlyArray<string>;
|
||
promptChannel: PromptChannel;
|
||
outputChannel: OutputChannel;
|
||
/** Present only when `outputChannel === 'file-arg'`. */
|
||
outputArg?: string;
|
||
/** `null` when the lane accepts no model override. */
|
||
modelArg: string | null;
|
||
effortChannel: EffortChannel;
|
||
/**
|
||
* Per-invocation environment pairs, merged over the inherited environment at spawn time (#2483).
|
||
* Declared data, not a handler (D6): the pairs are static per lane. Scoped to the one spawn —
|
||
* the orchestrating session's environment is never mutated. First-party lanes only today: the
|
||
* resolver sees exactly `REVIEWER_LANES`, so no third-party manifest can reach this field; if
|
||
* manifest lanes are ever wired to execute, `env` must join the trust disclosure
|
||
* (`capability-trust`) before it is honored there.
|
||
*/
|
||
env?: Readonly<Record<string, string>>;
|
||
}
|
||
|
||
export interface HttpInvoke {
|
||
/** Dotted config key holding the base URL. */
|
||
hostConfigKey: string;
|
||
/**
|
||
* Base URL used when `hostConfigKey` resolves to empty.
|
||
*
|
||
* Added by Phase 5b (#2799). Phase 4 federated every `*_host` key with a default of `""`, so the
|
||
* REAL fallback (`http://localhost:11434` and friends) only ever existed inside the bash leg. A
|
||
* data-driven lane with an empty host and no declared default would POST to a garbage URL, so
|
||
* the fallback has to be declared somewhere — and the lane is the only thing that knows it.
|
||
*/
|
||
defaultHost: string;
|
||
path: string;
|
||
modelDiscovery: 'none' | 'first-from-models-endpoint';
|
||
/** Model used when neither config nor discovery yields one. */
|
||
fallbackModel: string;
|
||
effortChannel: 'none';
|
||
}
|
||
|
||
export type LaneInvoke = SpawnInvoke | HttpInvoke;
|
||
|
||
interface ReviewerLaneCommon {
|
||
slug: string;
|
||
/**
|
||
* Every CLI flag that selects this lane. First entry is canonical.
|
||
* ADR-2782 D1 shows a singular `flag`; see the module header's widening (3).
|
||
*/
|
||
flags: ReadonlyArray<string>;
|
||
probe: LaneProbe;
|
||
/** Outer wall-clock bound. An inner tool-native timeout lives in the handler (D6). */
|
||
timeoutFloorMs: number;
|
||
emptyOutput: EmptyOutputPolicy;
|
||
/** The `## <reviewsSection> Review` heading in write_reviews. Unique (D8). */
|
||
reviewsSection: string;
|
||
evidenceClass: EvidenceClass;
|
||
/** External tools required on PATH — `jq` for five lanes. */
|
||
requiresBinaries: ReadonlyArray<string>;
|
||
/** Dotted config key for per-lane prompt trimming, or null. */
|
||
promptBudgetKey: string | null;
|
||
/**
|
||
* Dotted config key holding this lane's model override, or null when the lane accepts none.
|
||
*
|
||
* Added by Phase 5b (#2799). Phase 1 left the model key IMPLICIT (`review.models.<slug>`), and
|
||
* that convention is wrong for a lane that ships today: `antigravity`'s slug is `antigravity` but
|
||
* its key is `review.models.agy` (`review.md:291`, and Phase 4 federated it under that exact
|
||
* name). Resolving by slug would look up `review.models.antigravity`, miss, and silently ignore a
|
||
* configured model — the pinned-model escape hatch #2073 added precisely so a 404ing default can
|
||
* be overridden.
|
||
*
|
||
* Declared rather than derived, for the same reason `promptBudgetKey` is: the key is data about
|
||
* the lane, and a naming convention that one shipped lane already breaks is not a contract.
|
||
*/
|
||
modelConfigKey: string | null;
|
||
handler: LaneHandler;
|
||
}
|
||
|
||
/**
|
||
* `transport` sits at the LANE level, a sibling of `probe` and `invoke`, exactly
|
||
* as ADR-2782 D1's manifest example places it — not nested inside `invoke`.
|
||
* Nesting it would read more naturally as a TypeScript discriminated union, and
|
||
* that is precisely the convenience Phase 2 (#2795) would have to translate away
|
||
* when harvesting this shape into the capability manifest. The union is
|
||
* discriminated at the lane level instead, which costs nothing and keeps the two
|
||
* vocabularies identical.
|
||
*/
|
||
export interface SpawnLane extends ReviewerLaneCommon {
|
||
transport: 'spawn';
|
||
invoke: SpawnInvoke;
|
||
}
|
||
|
||
export interface HttpLane extends ReviewerLaneCommon {
|
||
transport: 'openai-http';
|
||
invoke: HttpInvoke;
|
||
}
|
||
|
||
export type ReviewerLane = SpawnLane | HttpLane;
|
||
|
||
const SPAWN_STDIN_STDOUT = {
|
||
promptChannel: 'stdin',
|
||
outputChannel: 'stdout',
|
||
} as const;
|
||
|
||
/**
|
||
* The twelve declared lanes, in `write_reviews` order.
|
||
*
|
||
* `kimi-code` joined in Phase 5b (#2799, closes #2718) — ADR-2782's phase table lands it here
|
||
* rather than in 5a precisely so it arrives together with the iteration that can invoke it.
|
||
*/
|
||
export const REVIEWER_LANES: ReadonlyArray<ReviewerLane> = Object.freeze([
|
||
{
|
||
slug: 'gemini',
|
||
flags: ['--gemini'],
|
||
transport: 'spawn',
|
||
probe: { kind: 'command-exists', binary: 'gemini' },
|
||
invoke: {
|
||
binary: 'gemini',
|
||
args: ['{{model}}', '-p', '-'],
|
||
...SPAWN_STDIN_STDOUT,
|
||
modelArg: '-m',
|
||
effortChannel: 'none',
|
||
},
|
||
timeoutFloorMs: 900_000,
|
||
emptyOutput: 'stub-with-stderr',
|
||
reviewsSection: 'Gemini',
|
||
evidenceClass: 'source-grounded',
|
||
requiresBinaries: [],
|
||
promptBudgetKey: null,
|
||
modelConfigKey: 'review.models.gemini',
|
||
handler: null,
|
||
},
|
||
{
|
||
// 1_200_000 rather than the 900_000 floor: headless Claude measured ~525 s
|
||
// on a large plan set (review.md:304).
|
||
slug: 'claude',
|
||
flags: ['--claude'],
|
||
transport: 'spawn',
|
||
probe: { kind: 'command-exists', binary: 'claude' },
|
||
invoke: {
|
||
binary: 'claude',
|
||
args: ['{{model}}', '{{effort}}', '-p', '-'],
|
||
...SPAWN_STDIN_STDOUT,
|
||
modelArg: '--model',
|
||
effortChannel: 'argv',
|
||
// #2483: without these the claude leg is the only reviewer that additionally inherits the
|
||
// invoking user's global CLAUDE.md, the project CLAUDE.md, and Claude Code auto-memory —
|
||
// a context asymmetry against the independent-review premise (gemini sees only the
|
||
// assembled prompt; codex runs --ephemeral). Both flags, not just the first: CLAUDE.md
|
||
// loading and auto-memory are independently-toggled mechanisms, and an environment
|
||
// exporting CLAUDE_CODE_DISABLE_AUTO_MEMORY=0 forces auto-memory back ON — the explicit
|
||
// pair is robust against that. Applies when /gsd:review runs from a non-Claude-Code host;
|
||
// inside Claude Code the claude lane self-skips for independence.
|
||
env: { CLAUDE_CODE_DISABLE_CLAUDE_MDS: '1', CLAUDE_CODE_DISABLE_AUTO_MEMORY: '1' },
|
||
},
|
||
timeoutFloorMs: 1_200_000,
|
||
emptyOutput: 'stub-with-stderr',
|
||
reviewsSection: 'Claude',
|
||
evidenceClass: 'source-grounded',
|
||
requiresBinaries: [],
|
||
promptBudgetKey: null,
|
||
modelConfigKey: 'review.models.claude',
|
||
handler: null,
|
||
},
|
||
{
|
||
// Codex captures the review through its own `-o/--output-last-message` and
|
||
// discards stdout, because on Windows it writes process-teardown noise to
|
||
// stdout AFTER the final message, which a stdout redirect would append to a
|
||
// non-empty file and slip past the empty-output guard (#1698).
|
||
slug: 'codex',
|
||
flags: ['--codex'],
|
||
transport: 'spawn',
|
||
probe: { kind: 'command-exists', binary: 'codex' },
|
||
invoke: {
|
||
binary: 'codex',
|
||
// Leg order exactly: codex exec --ephemeral --model M $EFFORT --skip-git-repo-check -o F -
|
||
args: ['exec', '--ephemeral', '{{model}}', '{{effort}}', '--skip-git-repo-check', '{{output}}', '-'],
|
||
promptChannel: 'stdin',
|
||
outputChannel: 'file-arg',
|
||
outputArg: '-o',
|
||
modelArg: '--model',
|
||
effortChannel: 'argv',
|
||
},
|
||
timeoutFloorMs: 1_200_000,
|
||
emptyOutput: 'stub-with-stderr',
|
||
reviewsSection: 'Codex',
|
||
evidenceClass: 'source-grounded',
|
||
requiresBinaries: [],
|
||
promptBudgetKey: null,
|
||
modelConfigKey: 'review.models.codex',
|
||
handler: null,
|
||
},
|
||
{
|
||
// Fed no prompt: CodeRabbit reviews the working-tree diff and accepts
|
||
// neither a prompt nor a model flag (review.md:367). Its findings are
|
||
// deliberately down-weighted in the consensus step.
|
||
slug: 'coderabbit',
|
||
flags: ['--coderabbit'],
|
||
transport: 'spawn',
|
||
probe: { kind: 'command-exists', binary: 'coderabbit' },
|
||
invoke: {
|
||
binary: 'coderabbit',
|
||
args: ['review', '--prompt-only'],
|
||
promptChannel: 'none',
|
||
outputChannel: 'stdout',
|
||
modelArg: null,
|
||
effortChannel: 'none',
|
||
},
|
||
timeoutFloorMs: 360_000,
|
||
emptyOutput: 'stub-with-stderr',
|
||
reviewsSection: 'CodeRabbit',
|
||
evidenceClass: 'diff-only',
|
||
requiresBinaries: [],
|
||
promptBudgetKey: null,
|
||
// Accepts no model flag at all (review.md:367) — not merely "none configured".
|
||
modelConfigKey: null,
|
||
handler: null,
|
||
},
|
||
{
|
||
// `--format json` is the primary invocation, not a fallback: the review text
|
||
// lives in assistant `text` parts, which the default formatter drops when the
|
||
// agent stops with no final message (#1936). Reconstruction needs jq.
|
||
slug: 'opencode',
|
||
flags: ['--opencode'],
|
||
transport: 'spawn',
|
||
probe: { kind: 'command-exists', binary: 'opencode' },
|
||
invoke: {
|
||
binary: 'opencode',
|
||
args: ['run', '{{model}}', '{{effort}}', '--format', 'json', '-'],
|
||
...SPAWN_STDIN_STDOUT,
|
||
modelArg: '--model',
|
||
effortChannel: 'argv',
|
||
},
|
||
timeoutFloorMs: 660_000,
|
||
emptyOutput: 'stub-with-stderr',
|
||
reviewsSection: 'OpenCode',
|
||
evidenceClass: 'source-grounded',
|
||
// Phase 5b: the handler reconstructs from the JSON stream with JSON.parse, so `jq` — absent on
|
||
// stock Windows/Git-Bash (#2589) — is no longer a prerequisite for this lane.
|
||
requiresBinaries: [],
|
||
promptBudgetKey: null,
|
||
modelConfigKey: 'review.models.opencode',
|
||
// Phase 5b (#2799): was `null`. The review is REBUILT from assistant `text` parts; a plain
|
||
// stdout copy would write the raw JSON envelope as the review (#1936). See LaneHandler.
|
||
handler: 'opencode',
|
||
},
|
||
{
|
||
slug: 'qwen',
|
||
flags: ['--qwen'],
|
||
transport: 'spawn',
|
||
probe: { kind: 'command-exists', binary: 'qwen' },
|
||
invoke: {
|
||
binary: 'qwen',
|
||
args: ['-'],
|
||
...SPAWN_STDIN_STDOUT,
|
||
modelArg: null,
|
||
effortChannel: 'none',
|
||
},
|
||
timeoutFloorMs: 900_000,
|
||
emptyOutput: 'stub-with-stderr',
|
||
reviewsSection: 'Qwen',
|
||
evidenceClass: 'source-grounded',
|
||
requiresBinaries: [],
|
||
promptBudgetKey: null,
|
||
modelConfigKey: null,
|
||
handler: null,
|
||
},
|
||
{
|
||
// `cursor-agent` is a SEPARATE binary from the `cursor` IDE launcher. Print
|
||
// mode takes the prompt as an ARGUMENT, so a full plan set is passed by file
|
||
// reference to stay clear of the 32,767-char Windows execFileSync ceiling.
|
||
slug: 'cursor',
|
||
flags: ['--cursor'],
|
||
transport: 'spawn',
|
||
probe: { kind: 'command-exists', binary: 'cursor-agent' },
|
||
invoke: {
|
||
binary: 'cursor-agent',
|
||
args: ['-p', '--mode', 'ask', '--trust', '--output-format', 'text', '{{prompt}}'],
|
||
promptChannel: 'argv-file-ref',
|
||
outputChannel: 'stdout',
|
||
modelArg: null,
|
||
effortChannel: 'none',
|
||
},
|
||
timeoutFloorMs: 900_000,
|
||
emptyOutput: 'stub-with-stderr',
|
||
reviewsSection: 'Cursor',
|
||
evidenceClass: 'source-grounded',
|
||
requiresBinaries: [],
|
||
promptBudgetKey: null,
|
||
modelConfigKey: null,
|
||
handler: null,
|
||
},
|
||
{
|
||
// Handler-owned: a three-layer fallback for an upstream stdout bug, a
|
||
// two-level timeout (600 s external cap over a 540 s native --print-timeout),
|
||
// and a stale-response watermark guard. `timeoutFloorMs` carries the OUTER
|
||
// bound only; the inner one lives in the handler (ADR-2782 D6).
|
||
slug: 'antigravity',
|
||
flags: ['--antigravity', '--agy'],
|
||
transport: 'spawn',
|
||
probe: { kind: 'command-exists', binary: 'agy' },
|
||
invoke: {
|
||
binary: 'agy',
|
||
args: ['--print-timeout', '540s', '{{model}}', '-p', '{{prompt}}'],
|
||
promptChannel: 'argv-file-ref',
|
||
outputChannel: 'stdout',
|
||
modelArg: '--model',
|
||
effortChannel: 'none',
|
||
},
|
||
timeoutFloorMs: 600_000,
|
||
emptyOutput: 'handler-owned',
|
||
reviewsSection: 'Antigravity',
|
||
evidenceClass: 'source-grounded',
|
||
// Phase 5b: the handler reads the transcript with JSON.parse per line, not `jq`.
|
||
requiresBinaries: [],
|
||
promptBudgetKey: null,
|
||
// NOT `review.models.antigravity` — the shipped key is `review.models.agy` (review.md:291) and
|
||
// Phase 4 federated it under that name. This lane is why the key is declared, not derived.
|
||
modelConfigKey: 'review.models.agy',
|
||
handler: 'antigravity',
|
||
},
|
||
{
|
||
slug: 'ollama',
|
||
flags: ['--ollama'],
|
||
transport: 'openai-http',
|
||
probe: {
|
||
kind: 'http-reachable',
|
||
hostConfigKey: 'review.ollama_host',
|
||
path: '/v1/models',
|
||
timeoutMs: 2_000,
|
||
},
|
||
invoke: {
|
||
hostConfigKey: 'review.ollama_host',
|
||
defaultHost: 'http://localhost:11434',
|
||
path: '/v1/chat/completions',
|
||
modelDiscovery: 'first-from-models-endpoint',
|
||
fallbackModel: 'llama3',
|
||
effortChannel: 'none',
|
||
},
|
||
timeoutFloorMs: 120_000,
|
||
emptyOutput: 'stub-with-stderr',
|
||
reviewsSection: 'Ollama',
|
||
evidenceClass: 'source-grounded',
|
||
// Phase 5b: the openai-compatible handler speaks HTTP directly and parses with JSON.parse, so
|
||
// neither `jq` nor `curl` is a prerequisite any more (#2589's stated Windows hazard).
|
||
requiresBinaries: [],
|
||
promptBudgetKey: 'review.max_prompt_tokens_per_reviewer.ollama',
|
||
modelConfigKey: 'review.models.ollama',
|
||
handler: 'openai-compatible',
|
||
},
|
||
{
|
||
slug: 'lm_studio',
|
||
flags: ['--lm-studio'],
|
||
transport: 'openai-http',
|
||
probe: {
|
||
kind: 'http-reachable',
|
||
hostConfigKey: 'review.lm_studio_host',
|
||
path: '/v1/models',
|
||
timeoutMs: 2_000,
|
||
},
|
||
invoke: {
|
||
hostConfigKey: 'review.lm_studio_host',
|
||
defaultHost: 'http://localhost:1234',
|
||
path: '/v1/chat/completions',
|
||
modelDiscovery: 'first-from-models-endpoint',
|
||
fallbackModel: 'local-model',
|
||
effortChannel: 'none',
|
||
},
|
||
timeoutFloorMs: 120_000,
|
||
emptyOutput: 'stub-with-stderr',
|
||
reviewsSection: 'LM Studio',
|
||
evidenceClass: 'source-grounded',
|
||
requiresBinaries: [],
|
||
promptBudgetKey: 'review.max_prompt_tokens_per_reviewer.lm_studio',
|
||
modelConfigKey: 'review.models.lm_studio',
|
||
handler: 'openai-compatible',
|
||
},
|
||
{
|
||
slug: 'llama_cpp',
|
||
flags: ['--llama-cpp'],
|
||
transport: 'openai-http',
|
||
probe: {
|
||
kind: 'http-reachable',
|
||
hostConfigKey: 'review.llama_cpp_host',
|
||
path: '/v1/models',
|
||
timeoutMs: 2_000,
|
||
},
|
||
invoke: {
|
||
hostConfigKey: 'review.llama_cpp_host',
|
||
defaultHost: 'http://localhost:8080',
|
||
path: '/v1/chat/completions',
|
||
modelDiscovery: 'first-from-models-endpoint',
|
||
fallbackModel: 'local-model',
|
||
effortChannel: 'none',
|
||
},
|
||
timeoutFloorMs: 120_000,
|
||
emptyOutput: 'stub-with-stderr',
|
||
reviewsSection: 'llama.cpp',
|
||
evidenceClass: 'source-grounded',
|
||
requiresBinaries: [],
|
||
promptBudgetKey: 'review.max_prompt_tokens_per_reviewer.llama_cpp',
|
||
modelConfigKey: 'review.models.llama_cpp',
|
||
handler: 'openai-compatible',
|
||
},
|
||
{
|
||
// Phase 5b (#2799) — closes #2718. Net-new in this phase BY DESIGN (ADR-2782's phase table):
|
||
// declaring it in 5a would have made it selectable but not invocable, producing an empty
|
||
// section for the whole 5a → 5b window.
|
||
//
|
||
// The probe is `command-capability`, not `command-exists`, and that is the entire reason D7's
|
||
// vocabulary ships wider than existence: `kimi` is claimed by BOTH the Kimi Code CLI (Node) and
|
||
// the legacy Python kimi-cli, which is a separate first-party runtime capability in this repo.
|
||
// An existence-only probe registers the wrong tool. The needle `--output-format` appears in
|
||
// Kimi Code's `--help` and is absent from the legacy CLI (whose headless flags are `--print` /
|
||
// `--work-dir`). Verified in both directions against Kimi Code CLI 0.29.2 and a stub legacy
|
||
// binary in closed PR #2776 — analysis carried forward with credit to @drungrin.
|
||
//
|
||
// The original probe there was an UNBOUNDED `kimi --help | grep` that ran on EVERY /gsd:review
|
||
// regardless of flags: a live instance of this repo's named Unbounded Subprocesses defect, and
|
||
// the review blocker. Here the bound is declared (`timeoutMs`) and the runner enforces it, and
|
||
// the probe runs only for a SELECTED lane.
|
||
slug: 'kimi-code',
|
||
flags: ['--kimi-code'],
|
||
transport: 'spawn',
|
||
probe: {
|
||
kind: 'command-capability',
|
||
binary: 'kimi',
|
||
needle: '--output-format',
|
||
timeoutMs: 5_000,
|
||
},
|
||
invoke: {
|
||
// Print mode takes the prompt as an ARGUMENT, so the full plan set goes by file reference to
|
||
// stay clear of the 32,767-char Windows execFileSync ceiling — same shape as cursor.
|
||
binary: 'kimi',
|
||
args: ['{{model}}', '-p', '{{prompt}}'],
|
||
promptChannel: 'argv-file-ref',
|
||
outputChannel: 'stdout',
|
||
modelArg: '-m',
|
||
effortChannel: 'none',
|
||
},
|
||
timeoutFloorMs: 900_000,
|
||
emptyOutput: 'stub-with-stderr',
|
||
reviewsSection: 'Kimi Code',
|
||
evidenceClass: 'source-grounded',
|
||
requiresBinaries: [],
|
||
promptBudgetKey: null,
|
||
modelConfigKey: 'review.models.kimi-code',
|
||
handler: null,
|
||
},
|
||
].map((lane) => Object.freeze(lane)) as ReviewerLane[]);
|
||
|
||
/**
|
||
* Merge the first-party lane set with installed overlay `reviewer` bodies
|
||
* (ADR-2782 D8: first-party ∪ overlay, first-party wins on slug collision).
|
||
*
|
||
* `routeReviewLane` (gsd-core/bin/gsd-tools.cjs) consumes this to build the lane
|
||
* map its `sections`/`flags`/`plan`/`invoke` subcommands resolve against, so an
|
||
* installed, consented third-party reviewer capability (`role:"reviewer"` with a
|
||
* declared `reviewer` body) becomes selectable, plannable, and invocable through
|
||
* the same surface as a built-in lane — closing #2927, where the overlay was
|
||
* roster-visible (`deriveReviewerSlugs`) and disclosed at install
|
||
* (`collectReviewerLaneSurfaces`) but never reached the invocation path.
|
||
*
|
||
* ADR-2782 D1 deliberately made the manifest `reviewer` body field-identical to
|
||
* `ReviewerLaneCommon` so "Phase 2 harvests the shape into the capability manifest
|
||
* with no translation layer" (CONTEXT.md reviewer-lane-descriptor predicate). The
|
||
* overlay body IS already `ReviewerLane`-shaped; this function MERGES, it does not
|
||
* PROJECT — there is no field renaming, no vocabulary translation. That is the
|
||
* design decision the bug violated by simply never calling anything.
|
||
*
|
||
* Pure and TOTAL — never throws on any input, because third-party overlay
|
||
* manifests are untrusted data reaching this seam at load time. A cap whose
|
||
* `reviewer` body is absent, non-object, or carries an empty/grammar-invalid slug
|
||
* is SKIPPED (contributes no lane) rather than crashing, so one malformed overlay
|
||
* cannot take the whole `review-lane` surface (and every first-party lane with it)
|
||
* down. The slug grammar (`LANE_SLUG_RE`) is enforced HERE even though
|
||
* `resolveLanePlan`'s trust boundary re-checks it, because `sections`/`flags` read
|
||
* lane fields before reaching `resolveLanePlan` — defense in depth against the
|
||
* path-traversal class the invocation boundary exists for.
|
||
*
|
||
* First-party wins: an overlay declaring a slug that already names a first-party
|
||
* lane is silently superseded (the first-party entry is kept, identity-stable),
|
||
* never overwritten. The first-party object is returned by reference, not copied.
|
||
*
|
||
* @param firstParty The frozen first-party lane set (`REVIEWER_LANES`).
|
||
* @param registry The merged capability registry
|
||
* (`loadRegistry({ includeInstalled: true })`); only its
|
||
* `capabilities` map is read. A cap contributes a lane iff it
|
||
* carries an object `reviewer` body with a non-empty,
|
||
* grammar-valid `slug`. The `role:"runtime"` `reviewerCli`
|
||
* alias never contributed a lane here, and as of #2801 it no
|
||
* longer contributes to the selection roster
|
||
* (`deriveReviewerSlugs`) either — the two surfaces now agree.
|
||
* @returns A NEW array: first-party lanes (in order) followed by accepted overlay
|
||
* lanes (in registry iteration order). Callers must not mutate it.
|
||
*/
|
||
export function mergeReviewerLanes(
|
||
firstParty: ReadonlyArray<ReviewerLane>,
|
||
registry: { capabilities?: Record<string, unknown> } | null | undefined,
|
||
): ReviewerLane[] {
|
||
// First-party always wins and is returned by reference (identity-stable), so a
|
||
// collision cannot perturb the first-party entry a consumer already holds.
|
||
const bySlug = new Map<string, ReviewerLane>();
|
||
const ordered: ReviewerLane[] = [];
|
||
for (const lane of firstParty) {
|
||
const slug = typeof lane.slug === 'string' ? lane.slug.trim() : '';
|
||
if (!slug) continue; // unreachable for the shipped frozen set, but this is exported
|
||
if (!bySlug.has(slug)) {
|
||
bySlug.set(slug, lane);
|
||
ordered.push(lane);
|
||
}
|
||
}
|
||
|
||
const capabilities = (registry && registry.capabilities) || {};
|
||
for (const cap of Object.values(capabilities)) {
|
||
if (cap === null || typeof cap !== 'object' || Array.isArray(cap)) continue;
|
||
const body = (cap as { reviewer?: unknown }).reviewer;
|
||
// C1/C2 (mirroring collectReviewerLaneSurfaces): a missing, null, or
|
||
// non-object reviewer body declares no lane — never an error at this layer.
|
||
if (body === null || typeof body !== 'object' || Array.isArray(body)) continue;
|
||
const rawSlug = (body as { slug?: unknown }).slug;
|
||
const slug = typeof rawSlug === 'string' ? rawSlug.trim() : '';
|
||
// Empty/whitespace slug: nothing to key on. Grammar-invalid slug: the
|
||
// path-traversal class — skip rather than admit, even though resolveLanePlan
|
||
// would reject it downstream. Both are skips, not throws.
|
||
if (!slug || !LANE_SLUG_RE.test(slug)) continue;
|
||
if (bySlug.has(slug)) continue; // D8: first-party (or an earlier overlay) wins
|
||
// The body is already ReviewerLane-shaped per ADR-2782 D1. We do NOT
|
||
// deep-validate every field here: the invocation trust boundary
|
||
// (resolveLanePlan) is the seam that re-validates a lane before it runs, and
|
||
// `sections`/`flags` are both tolerant of a partial body (flags filters by
|
||
// shape; sections reads slug/reviewsSection which a non-string cap simply
|
||
// renders as undefined). Admitting the body keeps the merge a pure merge.
|
||
//
|
||
// The slug is normalized to its trimmed value on the stored lane so the merge
|
||
// and the selection roster (`deriveReviewerSlugs`, which trims before adding)
|
||
// agree on the canonical key — otherwise a body declaring `slug: ' x '`
|
||
// would key the map on `'x'` but emit the raw `' x '` in `sections` and fail
|
||
// to match a `--selected` value coming from the roster. (The capability
|
||
// validator's grammar check rejects surrounding whitespace before this is
|
||
// reachable through a real install, so this is belt-and-braces parity with the
|
||
// roster, not a live-input guard.)
|
||
const lane = { ...body, slug } as ReviewerLane;
|
||
bySlug.set(slug, lane);
|
||
ordered.push(lane);
|
||
}
|
||
return ordered;
|
||
}
|
||
|
||
/* ------------------------------------------------------------------ *
|
||
* DEFECT.GENERATIVE-FIX parity (CONTEXT.md:797)
|
||
* ------------------------------------------------------------------ */
|
||
|
||
/**
|
||
* Frozen reason enum. Tests assert on these values, never on rendered prose —
|
||
* CONTRIBUTING.md "Tests assert on typed structured values". Adding a reason is
|
||
* three coordinated changes: this enum, the emitting site, and the test locking
|
||
* `Object.keys(...).sort()`.
|
||
*/
|
||
export const PARITY_VIOLATION = Object.freeze({
|
||
MALFORMED_LANE: 'malformed_lane',
|
||
INVALID_SLUG: 'invalid_slug',
|
||
ROSTER_SLUG_UNDECLARED: 'roster_slug_undeclared',
|
||
DESCRIPTOR_LANE_NOT_IN_ROSTER: 'descriptor_lane_not_in_roster',
|
||
REGISTRY_LANE_UNDECLARED: 'registry_lane_undeclared',
|
||
DESCRIPTOR_LANE_NOT_IN_REGISTRY: 'descriptor_lane_not_in_registry',
|
||
BESPOKE_LEG_PRESENT: 'bespoke_leg_present',
|
||
DUPLICATE_SLUG: 'duplicate_slug',
|
||
DUPLICATE_FLAG: 'duplicate_flag',
|
||
DUPLICATE_SECTION: 'duplicate_section',
|
||
} as const);
|
||
|
||
export type ParityViolationReason =
|
||
(typeof PARITY_VIOLATION)[keyof typeof PARITY_VIOLATION];
|
||
|
||
export interface ParityViolation {
|
||
reason: ParityViolationReason;
|
||
subject: string;
|
||
}
|
||
|
||
export interface ParityResult {
|
||
ok: boolean;
|
||
violations: ParityViolation[];
|
||
}
|
||
|
||
export interface ParityInput {
|
||
descriptor: ReadonlyArray<ReviewerLane>;
|
||
roster: ReadonlyArray<string>;
|
||
/**
|
||
* Reviewer slugs declared by `reviewer` bodies in the GENERATED capability registry.
|
||
*
|
||
* Phase 5b (#2799). Once `invoke_reviewers` iterates lanes, the registry — not the workflow text —
|
||
* is what actually decides which lanes exist at runtime, so this is the surface parity has to
|
||
* bind. A missing or malformed value degrades to violations rather than silence, exactly as
|
||
* `workflowText` does: a checker that cannot tell "no registry" from "registry agrees" is worse
|
||
* than no checker.
|
||
*/
|
||
registry: ReadonlyArray<string>;
|
||
/** Full text of gsd-core/workflows/review.md. */
|
||
workflowText: string;
|
||
}
|
||
|
||
/**
|
||
* The marker that used to make a hand-authored `invoke_reviewers` leg identifiable.
|
||
*
|
||
* Phase 5b (#2799) deleted every bespoke leg, so this regex flipped polarity: matching one is now
|
||
* the VIOLATION (`BESPOKE_LEG_PRESENT`) rather than the requirement. It is retained precisely
|
||
* because deleting it would leave nothing stopping a future contributor from quietly re-adding a
|
||
* per-CLI block — which is the drift (#2718 → #2781) this whole epic exists to end.
|
||
*/
|
||
const LEG_MARKER_RE = /<!--\s*reviewer-lane:\s*([a-z0-9_-]+)\s*-->/g;
|
||
|
||
/**
|
||
* The slug grammar, and the reason it is enforced rather than assumed.
|
||
*
|
||
* `LEG_MARKER_RE` can only capture `[a-z0-9_-]`. A lane whose slug falls outside
|
||
* that class is therefore UNMATCHABLE in the workflow: its marker can be present
|
||
* and correct and the scan will still never see it, so the lane reports
|
||
* `LEG_MARKER_MISSING` forever with no indication why. All twelve shipped slugs
|
||
* sit inside the class (`lm_studio`, `llama_cpp` use the underscore), so this
|
||
* never bites today — but Phase 2 (#2795) admits third-party overlay lanes, and
|
||
* a slug like `acme.reviewer` would silently vanish from a review.
|
||
*
|
||
* ADR-2782 does not specify a slug grammar. Rather than widen the marker regex —
|
||
* which would make an HTML comment scanned out of prose more ambiguous, not less
|
||
* — the grammar is pinned here and a violating slug is reported as
|
||
* `INVALID_SLUG`. A loud, named violation beats a silent miss; that is the whole
|
||
* design principle of this module.
|
||
*/
|
||
export const LANE_SLUG_RE = /^[a-z0-9][a-z0-9_-]*$/;
|
||
|
||
/** Bounds of the step a bespoke leg marker could appear inside. */
|
||
const INVOKE_STEP_RE = /<step name="invoke_reviewers">([\s\S]*?)<\/step>/;
|
||
|
||
function sliceStep(workflowText: string, re: RegExp): string {
|
||
const m = workflowText.match(re);
|
||
return m ? m[1] : '';
|
||
}
|
||
|
||
function countOccurrences(haystack: string, re: RegExp): Map<string, number> {
|
||
const counts = new Map<string, number>();
|
||
// Fresh lastIndex per call — a module-level /g regex carries state between
|
||
// calls and would silently skip matches on the second invocation.
|
||
const scanner = new RegExp(re.source, re.flags);
|
||
let m: RegExpExecArray | null;
|
||
while ((m = scanner.exec(haystack)) !== null) {
|
||
const key = m[1].trim();
|
||
counts.set(key, (counts.get(key) ?? 0) + 1);
|
||
}
|
||
return counts;
|
||
}
|
||
|
||
/**
|
||
* Bidirectional parity across three surfaces: the descriptor, the roster
|
||
* (`KNOWN_REVIEWER_SLUGS`), and the generated capability **registry** — plus one anti-parity
|
||
* assertion against the workflow.
|
||
*
|
||
* **Re-pointed by Phase 5b (#2799).** Through Phase 5a this function also required a literal
|
||
* `<!-- reviewer-lane: <slug> -->` per lane inside `invoke_reviewers` and a literal
|
||
* `## <Section> Review` per lane inside `write_reviews`. Phase 5b deletes exactly that text: the
|
||
* workflow now iterates declared lanes and renders sections from `reviewsSection`, so there is no
|
||
* per-lane text left to scan. Those two families could not be kept without keeping the
|
||
* hand-maintained per-lane blocks this epic exists to delete.
|
||
*
|
||
* What replaced them is the parity that is actually load-bearing once lanes are data: the registry
|
||
* is what decides which lanes exist at runtime, so `descriptor ↔ registry` is checked in both
|
||
* directions. That is also the mechanical single source #2781/Phase 6 needs for its docs and locale
|
||
* gate, which per-leg text could never provide.
|
||
*
|
||
* Bidirectional is still the point. A forward-only check ("does each declared lane resolve?")
|
||
* misses the failure this exists to catch: #2718 added a lane and #2781 was the documentation drift
|
||
* that followed. A registry lane nobody declared must fail, and so must a re-added bespoke leg.
|
||
*
|
||
* Pure and total: never reads the filesystem, never throws. Empty or malformed `workflowText` /
|
||
* `registry` degrades to violations, so a caller cannot mistake a read failure for a clean bill of
|
||
* health.
|
||
*
|
||
* CRLF-insensitive: `\r` is stripped before matching, because a Windows autocrlf checkout would
|
||
* otherwise leave every marker unmatched.
|
||
*/
|
||
export function checkReviewerLaneParity(input: ParityInput): ParityResult {
|
||
const { descriptor, roster } = input;
|
||
const workflowText = String(input.workflowText ?? '').replace(/\r\n/g, '\n');
|
||
const violations: ParityViolation[] = [];
|
||
|
||
const add = (reason: ParityViolationReason, subject: string): void => {
|
||
violations.push({ reason, subject });
|
||
};
|
||
|
||
// --- D8 uniqueness within the descriptor itself ---
|
||
//
|
||
// Every field is validated before use rather than trusted. In Phase 1 the
|
||
// descriptor is a frozen in-source table and none of these guards can fire,
|
||
// but Phase 2 (#2795) feeds this same function manifest-derived data from
|
||
// third-party overlays — which is precisely where a malformed entry arrives.
|
||
// A checker that throws on bad input cannot report on it, and a parity gate
|
||
// that crashes is indistinguishable from one that was never run.
|
||
const seenSlug = new Set<string>();
|
||
const seenFlag = new Set<string>();
|
||
const seenSection = new Set<string>();
|
||
|
||
// The declared parameter type says `ReviewerLane[]`, but this function is a
|
||
// trust boundary — narrow from `unknown` rather than believing the annotation.
|
||
const rawLanes: unknown[] = Array.isArray(descriptor) ? (descriptor as unknown[]) : [];
|
||
for (const raw of rawLanes) {
|
||
if (raw === null || typeof raw !== 'object') {
|
||
add(PARITY_VIOLATION.MALFORMED_LANE, String(raw));
|
||
continue;
|
||
}
|
||
const lane = raw as Record<string, unknown>;
|
||
const slug = lane.slug;
|
||
if (typeof slug !== 'string' || !LANE_SLUG_RE.test(slug)) {
|
||
add(PARITY_VIOLATION.INVALID_SLUG, String(slug));
|
||
continue;
|
||
}
|
||
const section = typeof lane.reviewsSection === 'string' ? lane.reviewsSection : null;
|
||
|
||
if (seenSlug.has(slug)) add(PARITY_VIOLATION.DUPLICATE_SLUG, slug);
|
||
seenSlug.add(slug);
|
||
|
||
const flags: unknown[] = Array.isArray(lane.flags) ? (lane.flags as unknown[]) : [];
|
||
for (const flag of flags) {
|
||
if (typeof flag !== 'string') continue;
|
||
if (seenFlag.has(flag)) add(PARITY_VIOLATION.DUPLICATE_FLAG, flag);
|
||
seenFlag.add(flag);
|
||
}
|
||
|
||
// Two lanes sharing a heading would silently MERGE their output in
|
||
// REVIEWS.md, producing a review that appears to have consensus it does
|
||
// not have (ADR-2782 D8).
|
||
if (section !== null) {
|
||
if (seenSection.has(section)) add(PARITY_VIOLATION.DUPLICATE_SECTION, section);
|
||
seenSection.add(section);
|
||
}
|
||
}
|
||
|
||
// --- descriptor <-> roster ---
|
||
const rosterSet = new Set(
|
||
(Array.isArray(roster) ? roster : []).filter((x): x is string => typeof x === 'string'),
|
||
);
|
||
for (const slug of rosterSet) {
|
||
if (!seenSlug.has(slug)) add(PARITY_VIOLATION.ROSTER_SLUG_UNDECLARED, slug);
|
||
}
|
||
for (const slug of seenSlug) {
|
||
if (!rosterSet.has(slug)) add(PARITY_VIOLATION.DESCRIPTOR_LANE_NOT_IN_ROSTER, slug);
|
||
}
|
||
|
||
// --- descriptor <-> registry ---
|
||
//
|
||
// The registry is what decides which lanes exist at runtime once the workflow iterates, so this
|
||
// replaces the per-leg text checks Phase 5b deleted. A non-array degrades to an empty set, which
|
||
// then reports every descriptor lane as missing — loud, not silent.
|
||
const registrySet = new Set(
|
||
(Array.isArray(input.registry) ? input.registry : []).filter(
|
||
(x): x is string => typeof x === 'string',
|
||
),
|
||
);
|
||
for (const slug of registrySet) {
|
||
if (!seenSlug.has(slug)) add(PARITY_VIOLATION.REGISTRY_LANE_UNDECLARED, slug);
|
||
}
|
||
for (const slug of seenSlug) {
|
||
if (!registrySet.has(slug)) add(PARITY_VIOLATION.DESCRIPTOR_LANE_NOT_IN_REGISTRY, slug);
|
||
}
|
||
|
||
// --- anti-parity: no bespoke leg may return ---
|
||
//
|
||
// Phase 5b deleted every hand-authored per-CLI block. Nothing in the type system stops a future
|
||
// contributor from adding one back, and a re-added block is invisible to every other check here
|
||
// (it would still be declared, still be in the roster, still be in the registry). Matching a leg
|
||
// marker is therefore now the violation.
|
||
const markerSlugs = countOccurrences(sliceStep(workflowText, INVOKE_STEP_RE), LEG_MARKER_RE);
|
||
for (const slug of markerSlugs.keys()) {
|
||
add(PARITY_VIOLATION.BESPOKE_LEG_PRESENT, slug);
|
||
}
|
||
|
||
return { ok: violations.length === 0, violations };
|
||
}
|
||
|
||
/* ------------------------------------------------------------------ *
|
||
* Documentation parity (ADR-2782 Phase 6, #2800 — closes #2781/#2272)
|
||
* ------------------------------------------------------------------ */
|
||
|
||
/**
|
||
* Frozen reason enum for the DOCUMENTATION arm.
|
||
*
|
||
* Deliberately separate from `PARITY_VIOLATION` rather than an extension of it. The two functions
|
||
* answer different questions — `checkReviewerLaneParity` asks *what runs* (descriptor ↔ roster ↔
|
||
* registry), this asks *what is documented*. Fusing them would change the signature of a function
|
||
* with seven dependents and would let a stale doc make the runtime checker look red.
|
||
*
|
||
* Same three-coordinated-changes rule as its sibling: this enum, the emitting site, and the test
|
||
* locking `Object.keys(...).sort()`.
|
||
*/
|
||
export const DOCS_PARITY_VIOLATION = Object.freeze({
|
||
MALFORMED_LANE: 'malformed_lane',
|
||
DOC_FLAG_MISSING: 'doc_flag_missing',
|
||
DOC_FLAG_UNDECLARED: 'doc_flag_undeclared',
|
||
DOC_TITLE_MISSING: 'doc_title_missing',
|
||
SIGNATURE_FLAG_MISSING: 'signature_flag_missing',
|
||
DOC_UNREADABLE: 'doc_unreadable',
|
||
TABLE_ROW_MISSING: 'table_row_missing',
|
||
} as const);
|
||
|
||
export type DocsParityViolationReason =
|
||
(typeof DOCS_PARITY_VIOLATION)[keyof typeof DOCS_PARITY_VIOLATION];
|
||
|
||
export interface DocsParityViolation {
|
||
reason: DocsParityViolationReason;
|
||
/** The document the violation was found in. */
|
||
doc: string;
|
||
/** The flag or section title at fault. */
|
||
subject: string;
|
||
}
|
||
|
||
export interface DocsParityResult {
|
||
ok: boolean;
|
||
violations: DocsParityViolation[];
|
||
/**
|
||
* Documents that carry no `/gsd-review` surface at all and were therefore skipped.
|
||
*
|
||
* Reported rather than silently dropped: `docs/pt-BR/FEATURES.md` is a 77-line stub, and a
|
||
* caller that cannot tell "this mirror does not document the command" from "this mirror agrees"
|
||
* has the same blindness this whole gate exists to remove.
|
||
*/
|
||
skipped: string[];
|
||
}
|
||
|
||
export interface DocsParityInput {
|
||
descriptor: ReadonlyArray<ReviewerLane>;
|
||
/** Map of document label (repo-relative path) to its full text. */
|
||
docs: Record<string, string>;
|
||
}
|
||
|
||
/**
|
||
* Non-lane tokens that legitimately share the `/gsd-review` signature line.
|
||
*
|
||
* `--all` is a selection control, not a reviewer lane. Without this allow-list the undeclared-flag
|
||
* arm would fire on correct documentation — the gate failing on a doc that is right is the fastest
|
||
* way to get a gate deleted.
|
||
*/
|
||
const NON_LANE_SIGNATURE_FLAGS: ReadonlySet<string> = new Set(['--all']);
|
||
|
||
/**
|
||
* Is `flag` documented in `text` under one of the two structural shapes docs actually use?
|
||
*
|
||
* Backticked is the `COMMANDS.md` table-cell shape; bracketed (`[--gemini]`) is the
|
||
* `FEATURES.md` signature shape. Requiring one of those two delimiters — rather than a bare
|
||
* substring — is what keeps prose and fenced examples from satisfying the gate, and it bounds the
|
||
* token for free: a backticked `--claude` demands its closing backtick, so a backticked
|
||
* `--claude-foo` cannot satisfy it.
|
||
*
|
||
* Literal `includes`, deliberately NOT a RegExp. `new RegExp` throws `SyntaxError` on a pattern
|
||
* beyond ~100k chars, and Phase 2 (#2795) admits third-party overlay lanes whose declared strings
|
||
* are untrusted in length — a parity gate that throws on its own input is indistinguishable from
|
||
* one that never ran. Literal matching also removes the need to escape metacharacters, which is
|
||
* what `llama.cpp` needed.
|
||
*/
|
||
function flagIsDocumented(text: string, flag: string): boolean {
|
||
return text.includes('`' + flag + '`') || text.includes('[' + flag + ']');
|
||
}
|
||
|
||
/**
|
||
* Strip fenced code blocks and HTML comments before parity matching.
|
||
*
|
||
* Both are places a flag can be *mentioned* without being *documented*: a fenced block showing
|
||
* markdown syntax, or a commented-out row left behind by an edit. Counting either is a false pass
|
||
* — the gate would report a lane as documented when a reader never sees it.
|
||
*
|
||
* Lines are replaced with empty strings rather than removed so that every downstream line index
|
||
* (the signature line, the Purpose paragraph beneath it) still refers to the same physical line.
|
||
*/
|
||
function stripNonProse(text: string): string {
|
||
const lines = text.split('\n');
|
||
const out: string[] = [];
|
||
let inFence = false;
|
||
let inComment = false;
|
||
for (const line of lines) {
|
||
const trimmed = line.trim();
|
||
if (!inComment && /^(`{3,}|~{3,})/.test(trimmed)) {
|
||
inFence = !inFence;
|
||
out.push('');
|
||
continue;
|
||
}
|
||
if (inFence) {
|
||
out.push('');
|
||
continue;
|
||
}
|
||
let working = line;
|
||
if (!inComment && working.includes('<!--') && !working.includes('-->')) {
|
||
inComment = true;
|
||
working = working.slice(0, working.indexOf('<!--'));
|
||
out.push(working);
|
||
continue;
|
||
}
|
||
if (inComment) {
|
||
if (working.includes('-->')) {
|
||
inComment = false;
|
||
working = working.slice(working.indexOf('-->') + 3);
|
||
out.push(working);
|
||
} else {
|
||
out.push('');
|
||
}
|
||
continue;
|
||
}
|
||
// Single-line comments: strip to a FIXED POINT, then honor any unterminated opener.
|
||
//
|
||
// One pass is not enough. `<!--<!---->-->` strips the inner span and leaves a live `<!--`
|
||
// behind, so a commented-out row could survive and be counted as documented — the exact
|
||
// false pass this helper exists to prevent. (CodeQL flags the single-pass form as
|
||
// js/incomplete-multi-character-sanitization; here the consequence is a wrong verdict rather
|
||
// than an injection, but the fix is the same.) Iterating to a fixed point terminates because
|
||
// every pass strictly shortens the string.
|
||
let previous: string;
|
||
do {
|
||
previous = working;
|
||
working = working.replace(/<!--[\s\S]*?-->/g, '');
|
||
} while (working !== previous);
|
||
// Whatever `<!--` remains after that is unterminated, so it opens a multi-line comment that
|
||
// the `inComment` branch above will close on a later line.
|
||
const danglingOpen = working.indexOf('<!--');
|
||
if (danglingOpen !== -1) {
|
||
inComment = true;
|
||
working = working.slice(0, danglingOpen);
|
||
}
|
||
out.push(working);
|
||
}
|
||
return out.join('\n');
|
||
}
|
||
|
||
/** Every bracketed `--token` on a signature line — the line's claimed reviewer flag set. */
|
||
const BRACKETED_FLAG_RE = /\[(--[a-z0-9][a-z0-9-]*)\]/g;
|
||
|
||
/**
|
||
* Declared flags that appear in the FIRST cell of a markdown table row.
|
||
*
|
||
* The distinction is load-bearing, not cosmetic. `docs/COMMANDS.md` and every locale mirror carry
|
||
* BOTH a per-lane reviewer table (flag in cell 1) and a forwarding row that lists all 13 flags in
|
||
* cell 3. A file-scoped check is therefore satisfied by the forwarding row alone, so deleting a
|
||
* lane's actual table row — the exact #2781 regression — passes. Keying on cell 1 separates the
|
||
* two: `| `--agy` / `--antigravity` | … |` is one lane row declaring two flags, while
|
||
* `| Reviewer flags | No | … `--gemini`, `--claude` … |` is not a lane row at all.
|
||
*/
|
||
function flagsInFirstTableCell(lines: string[], declared: ReadonlySet<string>): Set<string> {
|
||
const found = new Set<string>();
|
||
for (const line of lines) {
|
||
const trimmed = line.trim();
|
||
if (!trimmed.startsWith('|')) continue;
|
||
const cells = trimmed.split('|');
|
||
// split('|') on "| a | b |" yields ['', ' a ', ' b ', ''] — cell 1 is index 1.
|
||
if (cells.length < 2) continue;
|
||
const firstCell = cells[1];
|
||
for (const flag of declared) {
|
||
if (flagIsDocumented(firstCell, flag)) found.add(flag);
|
||
}
|
||
}
|
||
return found;
|
||
}
|
||
|
||
/**
|
||
* The `**Command:** ... /gsd-review ... [--flag]` signature line, if the doc carries one.
|
||
*
|
||
* Anchored on `/gsd-review` plus a bracketed flag rather than on the bolded label, because the
|
||
* label is translated in every mirror. Structure survives translation; prose does not.
|
||
*/
|
||
function findSignatureLine(lines: string[]): number {
|
||
return lines.findIndex((l) => /\/gsd[-:]review\b/.test(l) && l.includes('[--'));
|
||
}
|
||
|
||
/**
|
||
* Documentation parity for the declared reviewer roster (#2800; closes #2781, #2272).
|
||
*
|
||
* Gates `docs/COMMANDS.md`, its four locale mirrors, `docs/FEATURES.md` and its mirrors against
|
||
* the one declared source of truth. This is the `DEFECT.GENERATIVE-FIX` parity assertion
|
||
* `CONTEXT.md:806` requires for this roster and which has never existed for it — only the Cursor
|
||
* lane ever had one (`tests/cursor-reviewer.test.cjs`).
|
||
*
|
||
* Three arms, deliberately independent so that gaming one does not green the build:
|
||
*
|
||
* 1. **flag** — every declared flag appears, delimited, somewhere in the doc. This is the arm
|
||
* that catches #2781 (`--kimi-code` present in `docs/COMMANDS.md` and absent from all four
|
||
* mirrors).
|
||
* 2. **signature** — where a `Command:` signature line exists it is held to the FULL roster, and
|
||
* any bracketed non-lane token on it is reported. This restores per-site strictness the
|
||
* file-wide arm cannot provide.
|
||
* 3. **title** — every declared `reviewsSection` appears in the Purpose paragraph. This is the
|
||
* arm that catches the class #2800 names: the `Command:` line updated and the `Purpose:` line
|
||
* one row below not.
|
||
* 4. **table row** — a doc carrying a per-lane table must carry a row for EVERY lane, keyed on
|
||
* the FIRST cell. Without this the file-wide flag arm is satisfied by the forwarding row that
|
||
* lists all flags in cell 3, and deleting a lane's own row — the #2781 regression itself —
|
||
* goes undetected.
|
||
*
|
||
* A doc carrying no `/gsd-review` surface is **skipped, not failed** — a partial mirror that never
|
||
* claimed to document the command is not drift.
|
||
*
|
||
* Pure and total: no filesystem, no clock, never throws. A non-string document is reported as
|
||
* `DOC_UNREADABLE` rather than coerced or skipped; an empty or absent `docs` map degrades to
|
||
* violations rather than a clean bill of health, because a checker that cannot distinguish
|
||
* "nothing to read" from "everything agrees" is worse than no checker.
|
||
*
|
||
* CRLF-insensitive: a Windows `autocrlf` checkout must produce an identical verdict.
|
||
*/
|
||
export function checkReviewerDocsParity(input: DocsParityInput): DocsParityResult {
|
||
const violations: DocsParityViolation[] = [];
|
||
const skipped: string[] = [];
|
||
|
||
const add = (reason: DocsParityViolationReason, doc: string, subject: string): void => {
|
||
violations.push({ reason, doc, subject });
|
||
};
|
||
|
||
// Trust boundary: narrow from `unknown` rather than believing the annotation. Phase 2 (#2795)
|
||
// admits third-party overlay lanes into this same descriptor.
|
||
const declaredFlags: string[] = [];
|
||
const declaredTitles: string[] = [];
|
||
const rawLanes: unknown[] = Array.isArray(input?.descriptor)
|
||
? (input.descriptor as unknown[])
|
||
: [];
|
||
for (const raw of rawLanes) {
|
||
if (raw === null || typeof raw !== 'object') {
|
||
add(DOCS_PARITY_VIOLATION.MALFORMED_LANE, '(descriptor)', String(raw));
|
||
continue;
|
||
}
|
||
const lane = raw as Record<string, unknown>;
|
||
const flags: unknown[] = Array.isArray(lane.flags) ? (lane.flags as unknown[]) : [];
|
||
for (const flag of flags) {
|
||
if (typeof flag === 'string' && flag.length > 0) declaredFlags.push(flag);
|
||
}
|
||
if (typeof lane.reviewsSection === 'string' && lane.reviewsSection.length > 0) {
|
||
declaredTitles.push(lane.reviewsSection);
|
||
}
|
||
}
|
||
const declaredFlagSet = new Set(declaredFlags);
|
||
|
||
// An absent or non-object map is not "no docs to check" — it is every doc missing. Reported as
|
||
// such so the caller cannot read silence as success.
|
||
const rawDocs =
|
||
input?.docs !== null && typeof input?.docs === 'object'
|
||
? (input.docs as Record<string, unknown>)
|
||
: {};
|
||
const docLabels = Object.keys(rawDocs);
|
||
if (docLabels.length === 0) {
|
||
for (const flag of declaredFlagSet) {
|
||
add(DOCS_PARITY_VIOLATION.DOC_FLAG_MISSING, '(no documents supplied)', flag);
|
||
}
|
||
return { ok: violations.length === 0, violations, skipped };
|
||
}
|
||
|
||
for (const label of docLabels) {
|
||
// A document value that is not a string is REPORTED, not coerced and not skipped.
|
||
//
|
||
// The earlier version called `String(rawValue)`, which (a) throws outright on an object with
|
||
// an own non-callable `toString` and (b) — worse — turns any other object into
|
||
// `[object Object]`, a "document" with no `/gsd-review` marker that then lands in `skipped`.
|
||
// That is a silent pass: the gate would report success for input it never actually read.
|
||
// `@typescript-eslint/no-base-to-string` flags exactly this, and it is right to.
|
||
const rawValue = rawDocs[label];
|
||
if (typeof rawValue !== 'string') {
|
||
add(DOCS_PARITY_VIOLATION.DOC_UNREADABLE, label, typeof rawValue);
|
||
continue;
|
||
}
|
||
const text = rawValue.replace(/\r\n/g, '\n');
|
||
|
||
// Fenced examples and commented-out rows mention a flag without documenting it. Stripped
|
||
// BEFORE the `/gsd-review` skip check too, so a doc whose only mention is inside a fence is
|
||
// correctly treated as not documenting the command at all.
|
||
const prose = stripNonProse(text);
|
||
|
||
// Skip-if-absent. A mirror that does not document /gsd-review is a partial translation, not
|
||
// drift — gating it would make this change responsible for authoring one.
|
||
if (!/\/gsd[-:]review\b/.test(prose)) {
|
||
skipped.push(label);
|
||
continue;
|
||
}
|
||
|
||
const lines = prose.split('\n');
|
||
|
||
// --- arm 1: every declared flag is documented somewhere in the doc ---
|
||
for (const flag of declaredFlagSet) {
|
||
if (!flagIsDocumented(prose, flag)) {
|
||
add(DOCS_PARITY_VIOLATION.DOC_FLAG_MISSING, label, flag);
|
||
}
|
||
}
|
||
|
||
// --- arm 4: a doc that carries a per-lane table must carry a row for EVERY lane ---
|
||
//
|
||
// Only applies when the doc actually has a lane table (>=1 declared flag in a first cell);
|
||
// FEATURES-shaped docs carry a signature line instead and are covered by arms 2 and 3.
|
||
const rowFlags = flagsInFirstTableCell(lines, declaredFlagSet);
|
||
if (rowFlags.size > 0) {
|
||
for (const flag of declaredFlagSet) {
|
||
if (!rowFlags.has(flag)) {
|
||
add(DOCS_PARITY_VIOLATION.TABLE_ROW_MISSING, label, flag);
|
||
}
|
||
}
|
||
}
|
||
|
||
const sigIdx = findSignatureLine(lines);
|
||
if (sigIdx === -1) continue; // COMMANDS.md-shaped docs carry a table, not a signature.
|
||
|
||
// --- arm 2: the signature line carries the FULL roster and nothing undeclared ---
|
||
const sigLine = lines[sigIdx];
|
||
for (const flag of declaredFlagSet) {
|
||
if (!flagIsDocumented(sigLine, flag)) {
|
||
add(DOCS_PARITY_VIOLATION.SIGNATURE_FLAG_MISSING, label, flag);
|
||
}
|
||
}
|
||
// Fresh RegExp per line — a module-level /g literal carries `lastIndex` between calls and
|
||
// would silently skip matches on the second document scanned.
|
||
const scanner = new RegExp(BRACKETED_FLAG_RE.source, BRACKETED_FLAG_RE.flags);
|
||
const seenUndeclared = new Set<string>();
|
||
let m: RegExpExecArray | null;
|
||
while ((m = scanner.exec(sigLine)) !== null) {
|
||
const token = m[1];
|
||
if (typeof token !== 'string') continue;
|
||
if (declaredFlagSet.has(token) || NON_LANE_SIGNATURE_FLAGS.has(token)) continue;
|
||
if (seenUndeclared.has(token)) continue;
|
||
seenUndeclared.add(token);
|
||
add(DOCS_PARITY_VIOLATION.DOC_FLAG_UNDECLARED, label, token);
|
||
}
|
||
|
||
// --- arm 3: the Purpose paragraph names every declared section title ---
|
||
//
|
||
// The Purpose paragraph is the next non-blank line after the signature. Structural, so it
|
||
// survives every translated label. Absent (signature is the last line) => title arm skipped,
|
||
// the flag arms still stand.
|
||
let p = sigIdx + 1;
|
||
while (p < lines.length && lines[p].trim() === '') p += 1;
|
||
if (p >= lines.length) continue;
|
||
const purpose = lines[p];
|
||
for (const title of declaredTitles) {
|
||
if (!purpose.includes(title)) {
|
||
add(DOCS_PARITY_VIOLATION.DOC_TITLE_MISSING, label, title);
|
||
}
|
||
}
|
||
}
|
||
|
||
return { ok: violations.length === 0, violations, skipped };
|
||
}
|