* test(01-01): define reviewer-support trait contract Add failing coverage for step.supportsReviewerLanes (#4209 DISP-02): validator rejects non-boolean values with an exact field path, accepts missing/true/false, and the real code-review capability.json steps must declare supportsReviewerLanes: true. Add loop-resolver projection coverage proving the trait reaches activeHooks verbatim for a provider-neutral synthetic step (not code-review-specific), and that omitted/false values stay inert (no key on the active hook). All 8 new assertions fail today: the validator has no such field, and loop-resolver has nothing to project. RED before GREEN. * feat(01-01): declare reviewer-capable steps Add step.supportsReviewerLanes (#4209 DISP-02): a strict optional boolean opt-in trait, step-scoped (not capability-wide). Only a literal true validates and projects; false/omitted stay inert (no key on the projected active hook), and every non-boolean type fails capability-validator.cjs with an exact field-path error. Opt both existing code-review steps (execute:post, execute:wave:post) into the trait in capabilities/code-review/capability.json. Project the validated field through src/loop-resolver.cts into activeHooks so a provider-neutral generic interpreter can read it without any code-review-specific knowledge. Document the field in docs/reference/capability-manifest.md and regenerate gsd-core/bin/lib/capability-registry.cjs via the generator (never hand-edited). Makes all 8 RED assertions from the prior commit pass. * test(01-02): define shared reviewer dispatch - Add tests/reviewer-step-dispatch.test.cjs covering dispatchReviewerLanes: inert when the supportsReviewerLanes trait is off or nothing is selected, exactly-once plan/invoke per selected lane, duplicate-alias dedup, the bounded metadata-only source-review prompt (repo root, paths+baseSha, depth, four fixed prohibitions), and capability-neutral reuse via a second synthetic step context. - RED: module under test (src/reviewer-step-dispatch.cts) does not exist yet, so require() fails and every assertion is unreached. * feat(01-02): dispatch reviewers for opted-in steps - Add src/reviewer-step-dispatch.cts: dispatchReviewerLanes(input, deps), ONE interpreter for a step's supportsReviewerLanes trait. Reuses resolveReviewerSelection for selection and resolveLanePlan for planning (both already-existing, pure building blocks); invocation is the one required, caller-injected seam (deps.invoke) since runLane needs OS-aware spawn plumbing this module does not own. - trait !== true, or a selection resolving to zero lanes, dispatches nothing (zero plan/invoke calls). Each selected lane is planned and invoked exactly once, in the selector's deduped/sorted order. - buildSourceReviewPrompt assembles a metadata-only bounded prompt (repo root, canonical paths + base SHA, depth, four fixed prohibitions) — never file contents — written once per dispatch and shared across every invoked lane. - GREEN: tests/reviewer-step-dispatch.test.cjs now passes. * test(01-02): define reviewer dispatch failures - Extend tests/reviewer-step-dispatch.test.cjs with the fail-closed matrix: an explicitly requested lane the selector could not resolve still lets the OTHER resolved lane run, but the aggregate result must never read as a clean success (and 'every explicit lane unavailable' must be distinguishable from the plain no-flags-passed inert case); request-level validation (path traversal, absolute paths outside repoRoot, empty/non-string paths, missing depth/base SHA) halts the whole dispatch before any lane is planned or invoked; a per-lane prompt-budget overflow hard-fails only that lane before invoke while its sibling still runs. - RED: src/reviewer-step-dispatch.cts does not yet implement any of these guards, so 9 of the new assertions fail against the current (Task 1) implementation. * fix(01-02): fail closed in reviewer dispatch - src/reviewer-step-dispatch.cts: add the fail-closed guards the prior commit deliberately left out. An explicitly requested lane the selector could not resolve no longer lets the aggregate read as a clean success — lanes that DID resolve still run and keep their results (never narrow the requested set), but selection.errors now flips the aggregate ok to false, and 'every explicit lane unavailable' is now distinguishable (SELECTION_FAILED) from the plain no-flags-passed inert case (NO_LANES_SELECTED). - Add request-level validation (validatePaths, depth/baseSha presence) that halts the WHOLE dispatch before any lane is planned or invoked: path traversal, absolute paths outside repoRoot, empty/non-string paths, and missing provenance are all rejected up front. - Add per-lane prompt-budget enforcement (resolveBudget, mirroring gsd-tools.cjs's budgetFor convention including budget 0 = unbounded): a lane whose resolved budget the prompt exceeds hard-fails before invoke runs for it, without cancelling a sibling lane already planned. - Document the supportsReviewerLanes trait and its dispatch-step interpreter in gsd-core/references/loop-hook-dispatch.md. - GREEN: all 19 tests in tests/reviewer-step-dispatch.test.cjs pass; no regressions in the review-lane/reviewer-selection/prompt-budget suites (356 passing). * test(01-03): define optional source reviewer flow RED: assert code-review.md dispatches roster-derived reviewer-lane flags through a single review-lane dispatch-step call (DISP-01..05), that the no-flag path stays byte-for-behavior unchanged (COMP-01), and that external evidence reaching the internal reviewer prompt is marked unverified (CONS-02). Also covers the CLI contract directly: no-op with no explicit selection, and fail-closed on an explicit unknown lane (SAFE-07) via real gsd-tools.cjs subprocess calls. * feat(01-03): route optional source reviewers GREEN: code-review.md gains a dispatch_reviewer_lanes step that matches canonical reviewer-lane flags against the merged first-party + installed roster (never a hand-maintained list) and, only when at least one is present, calls the shared reviewer-step interpreter exactly once with the already-resolved repo root, file scope, depth, and base SHA. Its evidence paths are appended to the internal reviewer prompt via ${EXTERNAL_EVIDENCE_BLOCK}, explicitly marked unverified. No reviewer-lane flag leaves the internal-only dispatch byte-for-behavior unchanged (COMP-01). Deviation (Rule 3 — blocking issue): 01-02 documented `review-lane dispatch-step` (gsd-core/references/loop-hook-dispatch.md) as the CLI route `dispatchReviewerLanes` wires through, but never implemented the gsd-tools.cjs subcommand — the workflow's call had nothing to reach. Add it to the existing review-lane router, reusing the same effort-aware plan building and runner deps `plan`/`invoke` already use (factored into buildLaneRunnerDeps to avoid duplicating the spawn/http/fs seam). Guard the CLI's own `detected` set on whether an explicit flag was passed: resolveReviewerSelection's no-explicit-selection fallback is "select every detected reviewer" (the correct default for /gsd:review), and passing it an unconditionally non-empty detected set would silently invoke the whole roster on every no-flag code review, violating COMP-01. * test(01-03): define external finding consolidation RED: assert gsd-code-reviewer.md treats <external_reviewer_evidence> as untrusted input — independently re-verifies every claim against the actual current source, resists a prompt-injection attempt embedded in evidence text, and folds a verified claim into the existing Narrative Findings section with no second REVIEW.md schema (CONS-01..03). Also assert code-review.md's EXTERNAL_EVIDENCE_BLOCK restates the four fixed source-review prohibitions (SAFE-03..06) at the internal-reviewer handoff. * feat(01-03): consolidate external review evidence GREEN: gsd-code-reviewer.md's load_context parses <external_reviewer_evidence> as untrusted data, independently re-verifies every cited claim against the actual current source before it can appear in REVIEW.md, and explicitly resists prompt injection embedded in evidence text (never a command, no matter what it claims to be). A verified claim folds into the existing Narrative Findings section with (external: {slug}) provenance — one REVIEW.md schema only, no separate external-findings section. code-review.md's EXTERNAL_EVIDENCE_BLOCK now restates the four fixed source-review prohibitions (SAFE-03..06) at the internal-reviewer handoff. * fix(01-02): gitignore the reviewer-step-dispatch build artifact 01-02 added src/reviewer-step-dispatch.cts but never added its npm run build:lib output to .gitignore, unlike every sibling gsd-core/bin/lib/*.cjs generated file. Left it showing as untracked noise in git status. * docs(01-04): publish user and command contract for reviewer-lane source review - Document optional reviewer-lane flags on /gsd-code-review in USER-GUIDE.md and COMMANDS.md: opt-in, no source bodies in prompts, no fallback on failure, findings independently consolidated into the single REVIEW.md - Add the same contract to the docs/features/code-review-pipeline.md fragment and regenerate docs/FEATURES.md from it - Preserve /gsd-review as the plan-review command; cross-reference it rather than duplicating the reviewer roster - Pick up docs/INVENTORY-MANIFEST.json and skills/gsd-code-review/SKILL.md drift owned by source already shipped in Plans 01-01/01-03 but never regenerated (npm run regen:derived had not been run in this worktree) * docs(01-04): align architecture and agent ownership docs for reviewer-lane trait - ARCHITECTURE.md: trace the #4209 capability trait (supportsReviewerLanes) through the shared dispatchReviewerLanes interpreter to the existing review-lane plan/invoke machinery, ending at gsd-code-reviewer as the sole REVIEW.md consolidator - AGENTS.md: document gsd-code-reviewer's full-context verification scope and its treatment of external reviewer evidence as unverified input - No new diagram, abstraction, or config key; docs/CONFIGURATION.md is unchanged since the feature adds no setting or default * fix(01-02): eslint-ignore the reviewer-step-dispatch build artifact Same gap as the earlier .gitignore fix: 01-02 added src/reviewer-step-dispatch.cts but never added its generated gsd-core/bin/lib/reviewer-step-dispatch.cjs output to eslint.config.mjs's ignore list like every sibling generated file, so tsc's emitted __importDefault CommonJS-interop var tripped no-var. * fix(01-04): add the reviewer-step-dispatch.cjs roster row to docs/INVENTORY.md 01-04 regenerated docs/INVENTORY-MANIFEST.json (which now lists cli_modules/reviewer-step-dispatch.cjs) but the hand-written roster row in docs/INVENTORY.md — required by design, since a role sentence cannot be generated — was never added. * fix(01-01): update the code-review capability-step fixture for supportsReviewerLanes refactor-trigger-cli.test.cjs's preservesCodeReviewHookShapeAlongsideRefactorHook strict-deep-equals the code-review step's exact shape at execute:post; 01-01 added supportsReviewerLanes: true to that step and this fixture was not updated. * chore(01-03): acknowledge emitted-doc growth for code-review.md and gsd-code-reviewer.md Both files grew as a direct, intended consequence of wiring optional reviewer lanes into /gsd:code-review (the new dispatch_reviewer_lanes step and the untrusted-evidence consolidation contract) — not incidental drift. Emitted-Drift-Ack-Growth: code-review.md — new dispatch_reviewer_lanes step and EXTERNAL_EVIDENCE_BLOCK wiring for optional reviewer lanes (#4209) Emitted-Drift-Ack-Growth: gsd-code-reviewer.md — untrusted external-evidence consolidation contract for optional reviewer lanes (#4209) * test(01-05): define WR-01/WR-02 reliability contract for dispatchReviewerLanes From internal code review: dispatched must be false when zero lanes actually reached plan(), and a throwing plan()/invoke() for one lane must not discard results already collected for a sibling lane — matching the fail-closed pattern gsd-tools.cjs already uses for the same resolveLanePlan call (#2494/#2605/#1698/#1936/#2073/#2176/#2589/#2794). Refs: gsd-core-dks.16, gsd-core-dks.17 * fix(01-05): close WR-01/WR-02/IN-01/IN-02 from internal review - WR-01: dispatched now tracks whether any lane actually reached plan(), not results.length — an unresolvable selected slug no longer reports dispatched:true. - WR-02: plan()/writePromptFile()/invoke() wrapped per-lane so a throw for one lane can never discard results already collected for a sibling lane, matching the same guard gsd-tools.cjs already has around the identical resolveLanePlan call. - IN-01: documents the intentional budget===0-is-unbounded convention (#2797) the caller already relies on. - IN-02: review-lane dispatch-step no longer blocks indefinitely on an un-piped interactive TTY; fails closed to empty paths instead. Refs: gsd-core-dks.16, gsd-core-dks.17 * docs(01-05): add changeset fragment for PR #17 * fix(01-03): allowlist prompt-injection-scan false positive on the untrusted-evidence contract agents/gsd-code-reviewer.md's untrusted-evidence section and its pinning regression test both quote injection phrases as the exact attack they defend against/detect — same DEFECT.PROMPT-INJECTION-SCAN-COLLISION class as the existing allowlist entries, not an actual injection vector. * test(01-05): extend WR-02 coverage to writePromptFile/invoke throws; DIFF_BASE-empty skip From CodeRabbit review: WR-02's earlier fix only wrapped plan() — writePromptFile()/deps.invoke() still ran unguarded, so a throw there still aborted every later selected lane. Also covers the dispatch_reviewer_lanes DIFF_BASE-empty-provenance gap (explicit lanes silently not running when no prior review and no phase-start commit exist). * fix(01-05): skip dispatch_reviewer_lanes with a clear warning when DIFF_BASE cannot be resolved Previously an explicit reviewer-lane request with no prior review and no resolvable phase-start commit reached dispatch-step with an empty --base-sha, which fails closed via missing_provenance — correct, but silent about why explicitly requested lanes didn't run. Now skip dispatch entirely in that case with a stderr warning naming the actual cause. * fix(01-05): wrap writePromptFile/invoke in the same per-lane try/catch as plan() WR-02's original fix only guarded plan() — a throw from writePromptFile() or deps.invoke() still aborted the whole dispatch, discarding results already collected for lanes processed earlier in the loop. CodeRabbit caught the gap; WR-02b/WR-02c pin it. * fix(01-05): WR-02b mock must throw only on the first writePromptFile() call The committed mock threw unconditionally, so codex's retry also threw and failed for the same reason as claude's — the test could not distinguish 'sibling still runs' from 'sibling also breaks'. Gate the throw to the first call, matching WR-02/WR-02c's single-failure intent. * fix(#4209): close review findings from adversarial + critical-code-reviewer pass Two independent reviews (agy adversarial review, Opus critical-code-reviewer + ponytail) found 6 Blocking and 7 Required issues in the reviewer-lane dispatch wiring around dispatchReviewerLanes. All 13 tracked in gsd-core-dks.18-30 and fixed here: - dispatch-step's reducer silently swallowed whole-dispatch rejections (invalid paths, missing provenance, etc); it now checks parsed.ok/reason. - spawn_reviewer recomputed its own stale DIFF_BASE, diverging from the LAST_REVIEW_COMMIT-aware value dispatch_reviewer_lanes uses on re-review; now shares the single compute_file_scope derivation. - the external reviewer prompt had no actual review request or citation requirement, only prohibitions; added both. - removed the supportsReviewerLanes trait plumbing (capability registry, validator, loop-resolver, docs, tests) — it was never consulted by the real dispatch path, which gates on explicit CLI flags instead. - flag-resolution require() was a fragile cwd-relative literal that failed silently on non-vendored installs; now resolves via GSD_TOOLS's own directory and warns instead of swallowing failure. - reducer didn't unwrap the @file: overflow protocol for large payloads. - deduplicated resolveBudget/budgetFor into one resolveLaneBudget. - lane artifacts now write to a mktemp run dir instead of $PHASE_DIR, so a second dispatch can't overwrite prior evidence. - validatePaths rejects control characters, closing a markdown-injection vector into the external prompt via crafted filenames. - reworded the one line that tripped prompt-injection-scan.sh instead of allowlisting the whole production prompt file. - fixed a stale docstring range and a dispatched-field ordering bug. - added 3 integration tests executing the actual reducer against synthetic dispatch-step JSON, replacing markdown-substring-only assertions. 771/771 tests pass across every touched suite; tsc --noEmit clean. * fix(#4209): wire supportsReviewerLanes as the maintainer's required reusable trait The maintainer's approval on issue #4209 explicitly redirected implementation shape: reviewer-lane dispatch must be a reusable capability/step-dispatch trait ("supportsReviewerLanes"), not code-review.md hand-wiring the call itself. My previous commit (e2558326) deleted that trait entirely after finding it declared-but-never-consulted, which was backwards — the fix was to wire it, not remove it. Restores the trait (capability.json, generated registry, validator, loop-resolver.cts, docs, tests) and wires it for real: dispatch_reviewer_lanes now resolves its own active hook via `gsd_run loop render-hooks` for the configured workflow.code_review_point and only proceeds to CLI-flag matching when supportsReviewerLanes reads true. Explicit flags no longer bypass the trait; a matching flag with the trait false resolves zero slugs (proven by a new integration test executing the real fence with both trait states). Emitted-Drift-Ack-Growth: gsd-core/workflows/code-review.md — the dispatch_reviewer_lanes step grows a trait-resolution fence (#4209 maintainer redirect requires the capability layer, not the workflow, own the opt-in decision). * fix(#4209): dispatch-step self-verifies the reviewer-lane trait via --cap-id/--point Both an agy adversarial review and an Opus critical-code-reviewer pass independently found the same gap in my previous commit (9b2c3773d): the trait check I wired into code-review.md only protected code-review's OWN invocation — gsd-tools.cjs's dispatch-step handler still hardcoded `trait: true` unconditionally, so a second capability declaring supportsReviewerLanes would get zero enforcement from the shared CLI unless it correctly re-implemented the ~15-line render-hooks scrape itself. That is exactly the "each workflow.md hand-wiring the call" the maintainer's redirect said to eliminate. Moves the trait check into dispatch-step itself: given --cap-id/--point, it self-invokes `loop render-hooks <point>` (relocating the one subprocess code-review.md used to spawn for this, not adding a new one) and derives the real trait from that capId's active hook, rather than trusting a caller-passed boolean. code-review.md now only passes --cap-id code-review --point "$CODE_REVIEW_POINT" and no longer resolves or gates on the trait itself — the ~20-line scrape it previously carried is gone. Any other capability opts into the identical enforcement by declaring the trait and passing the same two flags. Replaced the two tests that stipulated SUPPORTS_REVIEWER_LANES as an input variable (they proved a bash branch honors a variable, not that the variable reflects the real capability manifest) with three integration tests that invoke the real dispatch-step CLI against the real first-party capability registry: the real code-review trait resolves true, an unknown --cap-id resolves false (trait_not_enabled, fail-closed), and omitting --cap-id/--point entirely resolves false (no context means no opt-in). Also: reject \x7f/U+2028/U+2029 in validatePaths' control-character check (agy-F1 was incomplete), and delete the promptWritten per-lane coupling flag — the prompt write is idempotent, so writing it once per lane instead of gating on "did any lane write it yet" removes a latent bug where a deps.plan override that ever varies promptPath per lane would silently skip writing for a later lane. Emitted-Drift-Ack-Growth: gsd-core/workflows/code-review.md — net line count drops (the trait scrape moved into dispatch-step), but the file still grew this session across multiple commits; acknowledging per the growth-tracking convention. * fix(#4209): remove per-run token waste from the shipped prompts Runtime prompt content, not session tokens: two real, per-invocation token costs in the code that ships. 1. agents/gsd-code-reviewer.md's critical_rules restated nearly all of load_context step 5's ~180-word untrusted-evidence contract in ~90 more words, breaking this section's own established terse one-liner style (every other rule here is 1-2 sentences). This prompt loads fresh on every /gsd:code-review invocation. Shrunk to a one-line cross-reference, matching how write_review's own reference to step 5 already does it. 2. buildSourceReviewPrompt repeated the base SHA on every single file line even though it is identical for every file and already stated once at the top of the prompt — O(files) wasted tokens on every dispatched lane for a 50-file review, for zero information gain. File lines are now bare paths. * fix(#4209): resolve reviewer-lane trait in-process, fix CI failures found in review round 3 Opus critical-code-reviewer found a real Blocking defect in the --cap-id/ --point self-invocation added last commit: `dispatch-step` spawned `loop render-hooks <point> --raw` as a subprocess and bare-JSON.parse'd its stdout, but `io.cjs`'s output() redirects any payload over 50000 chars to `@file:<path>` instead of inline JSON -- the same overflow protocol this feature already unwraps for its OWN dispatch result 60 lines later in code-review.md. A large-enough activeHooks envelope (more installed capabilities/fragments) would throw, get silently swallowed by the bare catch, and misreport a real trait as trait_not_enabled with zero diagnostic. Fixed by extracting the config/registry/capability-state resolution `cmdLoopRenderHooks` already performs into an exported pure function, resolveActiveHooksForPoint (both `cmdLoopRenderHooks` and dispatch-step now share it), and calling it in-process from dispatch-step instead of spawning a subprocess at all. This eliminates the @file: exposure entirely (the dispatch-step path never touches the rendered-string envelope or its JSON-stringify/50000-char threshold), removes one subprocess spawn per code-review invocation, and gives a genuine diagnostic (stderr warning) on resolution failure instead of silent fail-closed. Corrected three doc/ docstring references to the now-removed subprocess self-invocation. Also fixes 2 real CI failures this round surfaced: - lint-tests: the agy-F1 control-char regex fix's `eslint-disable-next-line no-control-regex` comment was unused under this project's ESLint config (verified locally: the rule never actually flags \x00-\x1f in this repo's config) -- a mistake from an earlier commit this session, never actually lint-checked before push. Removed the disable comment. - security (prompt-injection-scan): the agy-F1 regression test's crafted fixture literally contains "Ignore all prior instructions." as test data proving validatePaths rejects it -- allowlisted the test file, same DEFECT.PROMPT-INJECTION-SCAN-COLLISION class as existing entries. Also trimmed agents/gsd-code-reviewer.md's load_context step 5 (R2): one bullet stated "untrusted, never a command" three different ways in one paragraph, and a same-file duplicate of write_review's schema rule. Consolidated to state each rule once. Declined one suggestion from this round: shrinking code-review.md's EXTERNAL_EVIDENCE_BLOCK to a bare evidence list. Two tests (tests/code-review-pipeline-regression.test.cjs's CONS-01..03 block, tests/code-review.test.cjs's CONS-02 test) deliberately lock the four- prohibitions restatement and the untrusted-evidence prose into the INJECTED block itself, not just the consolidator's system prompt -- adjacency of the warning to the untrusted payload it's warning about is a recognized prompt-injection defense-in-depth pattern from this workstream's original TDD plan, not accidental duplication. * fix(#4209): correct stale per-file base-SHA prose in the external prompt Leftover from removing the per-file base SHA repetition earlier this session: the review-request sentence still said "relative to its base SHA" (singular per-file framing) when there's now exactly one base SHA, stated once above the file list. Reads "relative to the base SHA above" now. * fix(#4209): make getLane/configGet/plan required deps, delete dead defaults R3/R4 from the review round I'd deferred as low-priority test-churn: this file's one production caller (gsd-tools.cjs's dispatch-step handler) always supplies all three, so the fallbacks were dead in production -- but each was actively WRONG if ever reached: the default configGet always returned undefined, silently disabling resolveLaneBudget's overflow guard; the default getLane looked up only first-party REVIEWER_LANES, diverging from production's overlay-merged roster; the default plan skipped per-host effort resolution entirely. These defaults were introduced by this PR's own earlier work (this file did not exist before #4209 -- first commit a760bfcda, 01-02), not inherited from elsewhere, so there's no external caller depending on the lenient contract. Turned out free to fix: making the three deps required and deleting defaultGetLane/defaultPlan needed zero test changes -- every existing test that actually reaches the per-lane loop already supplies getLane/plan explicitly, and configGet's only real dependent (the budget-overflow tests) already supplies it too. 788/788 tests pass unchanged, tsc/lint clean. * fix(#4209): define depth semantics for the external reviewer lane Verified this was a real bug, not a match to existing convention as I'd claimed when declining the suggestion earlier this session: the internal gsd-code-reviewer agent's own system prompt carries a full <depth_levels> block defining what quick/standard/deep mean and do (agents/gsd-code- reviewer.md:68-99). The external reviewer lane has no access to that persona at all -- it only ever sees buildSourceReviewPrompt's bounded text, which sent the bare depth label with zero definition to a third-party CLI with no other source of truth for what "standard" means. Added depthMeaning(), condensed from the internal reviewer's own <depth_levels> definitions so the two stay consistent, and interpolated it into the review-request sentence. 150/150 tests pass, tsc/lint clean. * fix(#4209): merge dispatch_reviewer_lanes' split fences into one shell invocation CR-01 (Opus critical-code-reviewer, confirmed by direct execution): the roster-matching fence set EXPLICIT_JOINED/EXPLICIT_REVIEWER_SLUGS, and a SEPARATE later fence read them via ${#EXPLICIT_REVIEWER_SLUGS[@]} to decide whether to dispatch at all. This file's own documented rule (its depth-resolution guard, stated explicitly a few hundred lines earlier) is that a guard and the extraction it protects must run as one shell control-flow decision, because markdown-fenced blocks do not share shell state -- this step violated its own file's rule for the entire feature's gating condition. Merged the roster-resolution fence and the dispatch-decision fence into one continuous bash block, removing the intervening prose that split them. Fixed the stderr-based failure detection in the same edit (RQ-01: checking whether stderr is non-empty misfires on any benign Node warning; now checks the actual exit status of the roster-resolution command). Verified by extracting the merged fence and executing it standalone, driving both branches: --codex resolves EXPLICIT_JOINED=codex, SLUGS_COUNT=1, and a real dispatch-step call succeeds; no flags resolves EXPLICIT_JOINED empty, SLUGS_COUNT=0, dispatch-step never invoked (COMP-01). 141/141 workflow tests pass, tsc/lint clean. * fix(#4209): depthMeaning accuracy, injection defense on all embedded fields, hoisted prompt write Batch of Required/Suggestion fixes from the Opus critical-code-reviewer + writing-for-agents pass: - CR-02/CR-03: depthMeaning() dropped real categories from quick (empty catch blocks, commented-out code) and deep (error propagation, state mutation consistency, circular dependencies) relative to the real <depth_levels> block, and had zero test coverage. Restored full accuracy and added tests that read the real agents/gsd-code-reviewer.md file directly, so drift between the two can't recur silently. Unrecognised depth now normalizes to standard's definition, matching that agent's own documented rule, instead of rendering an undefined bare label. - RQ-04: depth/baseSha/repoRoot/runDir land in the same markdown prompt `paths` does, but weren't checked for control characters like paths were (agy-F1's original finding). Hoisted CONTROL_CHAR to module scope and applied it to all four fields at the same provenance-check boundary. runDir previously had zero validation at all. - S1: deleted the dead `identity` parameter on `invoke` -- the one production caller already ignores it, no test read it by name. - S2: hoisted the shared prompt write above the per-lane loop -- promptPath is derived from runDir alone (constant across lanes by construction), so writing it once is both correct and cheaper than the per-lane write R1 introduced earlier this session. Discovered and fixed a real regression from the naive version of this hoist: an unguarded throw would have escaped dispatchReviewerLanes as an uncaught exception instead of a clean per-lane failure. Added a new PROMPT_WRITE_FAILED whole-dispatch reason, matching the existing validatePaths/MISSING_PROVENANCE halt pattern, with a dedicated regression test. - S3: moved `planned = true` past the budget-overflow gate, so `dispatched` only reports true once a lane has cleared BOTH plan and budget checks. - S5: relayed gsd-code-reviewer.md's own "performance issues are out of scope unless also correctness issues" policy into the external-lane prompt, which previously had no such guidance and could return findings the internal reviewer's own contract excludes. - RQ-05 (partial): shrunk this file's own header docstring's restatement of the trait-reuse architecture to a pointer at gsd-core/references/loop-hook-dispatch.md, the canonical home. 234/234 tests pass across the full reviewer-lane test suite, tsc/lint clean. * fix(#4209): dedupe roster-merge logic, consolidate trait architecture prose, add step completion criterion RQ-02: added a `review-lane explicit-from-argv` subcommand that reuses the SAME merged-roster logic (`laneBySlug`) `dispatch-step`/`plan`/`invoke` already share. code-review.md's ~18-line inline `node -e` reimplementing `loadRegistry`+`mergeReviewerLanes` (a rename-only copy of the block in gsd-tools.cjs) is now a single call to this subcommand -- the exact violation code-review-flags.cjs's own header warns against ("this is the canonical flag-parsing surface -- do not replicate inline bash parsing"). RQ-03: an empty --cap-id XOR --point now warns distinctly from the legitimate no-context opt-out (both absent) -- a caller that named a capability without its point was silently indistinguishable from a correct opt-out. Also hardened the CODE_REVIEW_POINT config-get fallback: it only ever fires when the config-get COMMAND ITSELF fails (config-get already resolves the manifest's own schema default in the normal case), but that failure was previously silent. RQ-05/W-01/W-12/W-13: the "supportsReviewerLanes is a reusable trait resolved inside dispatch-step" explanation was restated in full in 5 places across this session's own review cycles. Consolidated to ONE canonical statement in gsd-core/references/loop-hook-dispatch.md; the other 4 (this file's own header, gsd-tools.cjs's comment, docs/ARCHITECTURE.md, code-review.md's step-opening comment) now point at it instead. W-05/W-06: loop-hook-dispatch.md described "false or non-boolean" as two inert cases when capability-validator.cjs already rejects non-boolean at load -- restated as the two cases that actually reach this code. Removed a "do not hand-roll trait resolution" prohibition whose target no longer exists once the positive description precedes it. W-04: deleted a no-op sentence in agents/gsd-code-reviewer.md ("missing block means proceed as normal") -- an absent optional block already means proceed as normal without being told. W-08/W-09: replaced longhand "zero selection/plan/invoke calls" and the made-up compound "byte-for-behavior [un]changed" with the token this session's own docs already coined for this concept (inert) and the word that means what byte-for-behavior was reaching for (unchanged). W-10: dispatch_reviewer_lanes had no completion criterion -- added one sentence naming the checkable end state (EXTERNAL_EVIDENCE_BLOCK is set, either populated or empty). This exact sentence would have caught the cross-fence bug fixed two commits ago at authoring time. Declined from this round, with reasoning: W-02/W-03 (trim the untrusted-evidence restatement in EXTERNAL_EVIDENCE_BLOCK/critical_rules) -- two tests deliberately lock this as intentional adjacency-based prompt-injection defense-in-depth, not accidental duplication (see this branch's own earlier commit). S4 (wrap LANE_RUN_DIR in a creation-site `trap ... EXIT`) -- would fire at the end of the CREATING fence, before spawn_reviewer's agent ever reads the evidence files, given this file's own documented fenced-block execution model; the existing named cross-reference between creation and cleanup already satisfies the co-location concern without introducing that regression. 853/853 tests pass across the full reviewer-lane test suite, tsc/lint clean. * fix(#4209): merge CODE_REVIEW_POINT into dispatch_reviewer_lanes' one fence, stop test from spawning real codex Round-5 review (agy) found the same cross-fence-split bug CR-01 already fixed for EXPLICIT_JOINED/EXPLICIT_REVIEWER_SLUGS: CODE_REVIEW_POINT's config-get fallback lived in an earlier, separate fence from the fence that consumes it via --point, split only by prose (not a guard, per this step's own documented rule). Merged into the single continuous fence and added a structural test asserting exactly one bash fence in the step. The new end-to-end regression test for this used --codex, which drives the fence's real `review-lane dispatch-step` call and, with the codex binary present on PATH, spawns the real external CLI — which then blocks on interactive auth with no stdin (BL-01). Stubbed gsd_run for `review-lane dispatch-step` only (captures argv instead of executing), keeping the real config-get/explicit-from-argv calls the test is actually about. * fix(#4209): split control-char vs missing provenance reason, realpath-check path escapes, stale comment Round-5 review (Opus) warning-tier findings: - WR-04: MISSING_PROVENANCE covered both "field absent" and "field present but a control-character injection attempt" — a caller distinguishing a config problem from a security event couldn't tell them apart. Split into MISSING_PROVENANCE (absent) and INVALID_PROVENANCE (present but invalid). - WR-05: validatePaths' containment check was lexical only (path.resolve), so a symlink whose own path sits inside repoRoot could still point outside it. Added an fs.realpathSync check (ENOENT-tolerant — a git-diff path can legitimately name a file already deleted in a stale worktree), realpathing repoRoot itself too so a symlinked repoRoot (e.g. /tmp on macOS) doesn't false-positive-reject its own real children. - WR-08: a comment in the per-lane loop still said a throwing writePromptFile() was caught there — stale since the prompt write was hoisted above the loop in an earlier round. WR-03 (validate depth against the quick/standard/deep enum) was considered and declined: this dispatcher is deliberately capability-neutral (see the existing "synthetic step context" test, which passes a non-code-review depth label on purpose to prove no code-review-specific special-casing exists). WR-01 (double registry load), WR-02 (trim-vs-hard-fail budget semantics), and WR-07 (reason omitted on the aggregate return) were verified against source and are not bugs — see review notes. * docs(#4209): document LANE_RUN_DIR's early-exit trade-off as accepted, not a gap Round-5 review (Opus, BL-03) flagged that an early exit between dispatch_reviewer_lanes and commit_review leaks the run-scoped temp dir. A trap-based cleanup was considered and rejected: if a step genuinely runs as a separate process, a trap set at creation time would fire at the end of that SAME fence, deleting the directory before spawn_reviewer/commit_review ever read it — worse than the leak it would fix. review.md's own gather_context/cleanup pair for the identical resource class (a run-scoped reviewer temp dir) already makes and documents this exact trade-off: cleanup runs only on a documented success path, and a leftover $TMPDIR entry is explicitly called cheaper than destroyed evidence. Recording that precedent here so this isn't re-raised as a live gap in a future review. * fix(#4209): register the WR-05 symlink-escape test's synthetic docs/ path reviewer-step-dispatch.test.cjs's "capability-neutral reuse" fixture passes paths: ['docs/spec.md'] as a synthetic, never-read path proving the dispatcher has no code-review-specific special-casing. lint-docs-guard- registration correctly flagged this as an unregistered docs/ path reference — add the docs-guard-exempt marker and its pinned baseline entry, the same pattern every other synthetic docs/ literal in this test suite already uses. * fix(#4209): backfill changeset pr: field with the real upstream PR number changeset-lint's fail_pr_field_drift caught the fragment still pointing at the fork PR (17) instead of the upstream one (open-gsd/gsd-core#4323) this branch is now also open against. * docs(#4209): amend ADR-2782 for the supportsReviewerLanes step-trait seam trek-e's review (2026-09-07, gsd-core#4323) found a real ADR gap: every decision in ADR-2782 (D1-D9) and every prior dated amendment governs the `role: "reviewer"` capability body and its one consumer, /gsd:review. This PR's actual new seam - a `supportsReviewerLanes: true` trait on an ordinary feature capability's `steps[]` entry, projected through loop-resolver.cts and resolved in-process via resolveActiveHooksForPoint - is a different capability axis (steps/gates/contributions) that the ADR's own scope note explicitly places out of reach. Per docs/contributor-standards.md's "Amending an accepted ADR", an in-place dated section is the established, lighter-weight path for an addition that stays within the ADR's existing decisions - used twice already in this same file - so this appends a third dated entry documenting the new seam, its consumer, and why it reuses the existing D1-D9-governed plan/invoke machinery rather than adding a second one. No decision is reversed; no new Amends/Amended-by pair is needed since the steps/gates/contributions axis already carries reciprocal links to ADR-857 and ADR-894. * fix(#4209): close two test-quality gaps trek-e's review found Minor 1: validatePaths (a path-shape parser guarding the prompt- injection/path-traversal trust boundary) had only example-based coverage, violating ADR-456's rule that parsers/budget limits carry at least one fast-check property test. Adds three: safe-segment paths are never rejected, a single leading "../" always escapes the one-segment repoRoot, and a control character anywhere is always rejected - one property per rejection reason validatePaths owns. Minor 2: the budget-overflow check (`estimatedTokens > budget`) was only ever exercised far below budget or at budget:0 (unbounded), never at the exact threshold crossing where a `>` vs `>=` off-by-one would hide. Adds three exact-boundary tests using the real estimateTokens/ buildSourceReviewPrompt the module calls internally, so the resolved token count is exact rather than approximated: budget == estimate (must pass), budget == estimate - 1 (must fail), budget == estimate + 1 (must pass). Also extracts okPlan()'s fixture timeoutMs into a named constant - local/no-adhoc-timeout-literal (#4446) landed on next after this branch was authored and flagged the pre-existing literal on rebase; it is fixture data for a synthetic plan object dispatchReviewerLanes never waits on, a distinct class from tests/helpers/timeouts.cjs's real subprocess norms. * fix(#4209): update docs-guard-registration baseline for the new ADR citation reviewer-step-dispatch.test.cjs's new fast-check property tests cite docs/adr/456-test-rigor-architecture.md in a justifying comment (never a real read). lint-docs-guard-registration fingerprints every docs/ path string an exempted test file mentions and fails on drift so a human re-confirms the exemption still holds - re-confirmed, and the baseline is updated to match. * fix(#4209): point changeset pr: field at the fork PR for CI validation changeset-lint's fail_pr_field_drift check compares the fragment's pr: field against the PR the CI run is actually attached to (GITHUB_EVENT_PATH), not a fixed target. Rehearsing this branch on fork PR davdittrich/gsd-core#17 needs pr: 17 to pass that check; the prior commit's pr: 4323 (the real open-gsd upstream PR number) is correct for that PR but fails here. Backfill to 4323 happens again, as the last commit, immediately before the approved push to open-gsd#4323 - never leaving pr: 17 on the branch that ships upstream. * fix(#4209): reject promptChannel:none lanes from source-review dispatch CodeRabbit found a real scope mismatch: coderabbit's lane declares promptChannel: 'none' and reviews the working tree on its own terms, fed nothing (review.md:367). Silently dispatching it through dispatchReviewerLanes would ignore the bounded paths/depth/baseSha scope buildSourceReviewPrompt promises and let the lane review whatever it independently sees fit, violating this interpreter's own scoped, metadata-only contract. Reject before plan()/invoke(), same as an unresolved slug. * fix(#4209): scope CONS-02 test to the evidence-block line, not the whole file CodeRabbit found the whole-file match on workflowContent would still pass if UNVERIFIED and re-open/reopen appeared in two unrelated parts of this 1000+-line workflow, proving nothing about the actual evidence block's contract. Line-filtered via splitLines (not a bare-\n regex spanning readFileSync content) so this stays CRLF-portable and passes local/no-unbounded-quantifier and local/no-crlf-fragile-split. * fix(#4209): guard DISPATCH_JSON substitution and capture its stderr CodeRabbit found the dispatch-step command substitution unguarded: a non-zero exit could leave DISPATCH_JSON empty (or halt the step under errexit with no warning), and the downstream reducer would only ever report the generic unparseable_dispatch_output reason, discarding the command's own diagnostic. Guarded like the existing CODE_REVIEW_POINT/ EXPLICIT_JOINED calls above it: capture stderr to a temp file, surface it in a warning on failure, and fall back to a parseable dispatch_ command_failed JSON stub so the reducer's existing reason-reporting path still fires. * docs(#4209): fix byte-for-behavior wording and missing colon, regenerate CodeRabbit found "byte-for-behavior" should read "byte-for-byte" (the established repo term for output-identical unchanged behavior) and a missing colon after the bold "Optional external reviewer lanes (#4209)" lead-in in docs/features/code-review-pipeline.md. Fixed in the two hand-authored sources (commands/gsd/code-review.md, docs/features/ code-review-pipeline.md) and regenerated the two derived projections (skills/gsd-code-review/SKILL.md via gen-plugin-skills.cjs, docs/ FEATURES.md via gen-features.cjs) so they stay in sync. * fix(#4209): drop the fabricated DISPATCH_JSON fallback stub (Windows CI) The prior fix's fallback `DISPATCH_JSON='{"ok":false,...}'` embeds double-quoted JSON keys inside a single-quoted shell literal. That extra quote density, inside an already quote-heavy ~8KB driver string, passed bash -n and the full local suite on Linux but broke Windows Git-Bash: `dispatch_reviewer_lanes computes CODE_REVIEW_POINT ... end to end (#4209 round 5)` failed on two Windows CI shards with `bash -c: unexpected EOF while looking for matching '''` — a Windows argv-to- command-line re-quoting edge case, reproducible on rerun, not a flake. Root-caused via gh api job logs plus a byte-identical local reconstruction of the test's own driver script. Fix: drop the fabricated stub. The downstream node -e reducer already falls back to reason `unparseable_dispatch_output` on any JSON.parse failure, so an empty/partial DISPATCH_JSON on command failure is still handled correctly, with zero new quoting risk. * revert(#4209): drop the DISPATCH_JSON stderr-guard nitpick (Windows CI) Two materially different mechanisms for the same CodeRabbit Nitpick ("Trivial | Quick win") both broke Windows Git-Bash reproducibly: a single-quoted JSON-literal fallback ("bash -c: unexpected EOF ... matching '''") and, after removing that, a plain `head -1 "$VAR"` inside a nested command substitution ("unexpected EOF ... matching '"'"). Both passed bash -n and the full local suite on Linux every time; both failed the SAME test deterministically on Windows CI. Two attempts at the same class of fix (nested-quote construction near this exact step) is the retry limit - reverting to the original, already-shipped, Windows-verified unguarded form rather than continuing to guess at a third quoting mechanism for a Trivial- severity nitpick. Logged as bug-221/bug-222 in .wolf/buglog.json for anyone attempting this again: the fix belongs outside this specific markdown-fence-driver test harness (e.g., a real .sh helper script) if it's worth doing at all. * fix(#4209): backfill changeset pr: field to the real upstream PR before push Fork validation (davdittrich/gsd-core#17) needed pr: 17 to satisfy changeset-lint's PR-number check while rehearsing there; this is the last commit before the approved push to the real upstream PR (open-gsd/gsd-core#4323), so the field points at that PR number again. --------- Co-authored-by: Test <test@test.com> Co-authored-by: Tom Boucher <trekkie@nomorestars.com>
4022 lines
182 KiB
JavaScript
4022 lines
182 KiB
JavaScript
'use strict';
|
||
|
||
/**
|
||
* capability-validator.cjs — shared, runtime-callable capability validator.
|
||
*
|
||
* Extracted from scripts/gen-capability-registry.cjs per ADR-1244 D2 so that
|
||
* both the build-time generator and the runtime overlay loader can require the
|
||
* validator WITHOUT pulling in the generator's build-time-only machinery
|
||
* (ExitError, config-schema.manifest.json, install-profiles.cjs, clusters.cjs,
|
||
* gen-loop-host-contract.cjs, etc.).
|
||
*
|
||
* This is a COMMITTED plain .cjs (not built from .cts) so it is available on a
|
||
* fresh worktree before `npm run build:lib` has run.
|
||
*/
|
||
|
||
const path = require('node:path');
|
||
|
||
const { LOOP_HOST_CONTRACT } = require('./loop-host-contract.cjs');
|
||
|
||
// ─── Shared schema-version constant ──────────────────────────────────────────
|
||
|
||
const SCHEMA_VERSION = '1';
|
||
|
||
// ─── Loop Host Contract ───────────────────────────────────────────────────────
|
||
|
||
// Canonical point order — explicit constant (do NOT rely on Set insertion order).
|
||
// Used for point-ordering semantics in consumes-satisfiability validation and topo-sort.
|
||
const POINT_ORDER = [
|
||
'discuss:pre',
|
||
'discuss:post',
|
||
'plan:pre',
|
||
'plan:post',
|
||
'execute:pre',
|
||
'execute:wave:pre',
|
||
'execute:wave:post',
|
||
'execute:post',
|
||
'verify:pre',
|
||
'verify:post',
|
||
'ship:pre',
|
||
'ship:post',
|
||
];
|
||
|
||
// C1: Artifact availability — host-produced artifacts become available at their step's :post
|
||
// point. Build a map: artifact → earliest POINT_ORDER index at which it is available.
|
||
// (discuss produces CONTEXT.md → discuss:post = index 1;
|
||
// plan produces PLAN.md → plan:post = index 3;
|
||
// execute produces SUMMARY.md → execute:post = index 7;
|
||
// verify produces UAT.md → verify:post = index 9)
|
||
//
|
||
// NOTE: this map covers ONLY host artifacts. Hook-produced artifacts are handled per-run
|
||
// during consumes-satisfiability validation (C2 global pass).
|
||
const HOST_ARTIFACT_EARLIEST_POINT_IDX = (() => {
|
||
const m = Object.create(null);
|
||
for (const entry of LOOP_HOST_CONTRACT) {
|
||
// The :post point is the last point in each step's points array.
|
||
const postPoint = entry.points[entry.points.length - 1];
|
||
const postIdx = POINT_ORDER.indexOf(postPoint);
|
||
for (const artifact of entry.coreArtifacts.produces) {
|
||
// Only record the earliest (should be unique, but take min to be safe).
|
||
if (m[artifact] === undefined || postIdx < m[artifact]) {
|
||
m[artifact] = postIdx;
|
||
}
|
||
}
|
||
}
|
||
return m;
|
||
})();
|
||
|
||
// Flatten all valid loop points into a Set for O(1) validation
|
||
const VALID_LOOP_POINTS = new Set(POINT_ORDER);
|
||
|
||
// Map point → step contract (agentRoles + coreArtifacts)
|
||
const POINT_TO_CONTRACT = new Map();
|
||
for (const entry of LOOP_HOST_CONTRACT) {
|
||
for (const point of entry.points) {
|
||
POINT_TO_CONTRACT.set(point, entry);
|
||
}
|
||
}
|
||
|
||
// ─── Config-slice validation ──────────────────────────────────────────────────
|
||
|
||
const VALID_CONFIG_SLICE_TYPES = new Set(['boolean', 'string', 'number', 'enum']);
|
||
|
||
/**
|
||
* Validate a single config-slice entry (one key's { type, default, description }).
|
||
* Returns an array of error strings. Empty = valid.
|
||
*
|
||
* @param {string} capId Capability id (for error messages)
|
||
* @param {string} key Config key (for error messages)
|
||
* @param {object} slice The slice object from cap.config[key]
|
||
* @returns {string[]}
|
||
*/
|
||
function validateConfigSliceEntry(capId, key, slice) {
|
||
const errors = [];
|
||
|
||
if (typeof slice !== 'object' || slice === null || Array.isArray(slice)) {
|
||
errors.push('capability "' + capId + '" config["' + key + '"]: slice must be a non-null object');
|
||
return errors;
|
||
}
|
||
|
||
// type must be one of the allowed set
|
||
if (!VALID_CONFIG_SLICE_TYPES.has(slice.type)) {
|
||
errors.push(
|
||
'capability "' + capId + '" config["' + key + '"]: type must be one of ' +
|
||
[...VALID_CONFIG_SLICE_TYPES].join(', ') + ' (got: ' + JSON.stringify(slice.type) + ')',
|
||
);
|
||
}
|
||
|
||
// default must be present
|
||
if (!Object.prototype.hasOwnProperty.call(slice, 'default')) {
|
||
errors.push(
|
||
'capability "' + capId + '" config["' + key + '"]: default is required',
|
||
);
|
||
} else {
|
||
// type-consistency check
|
||
const def = slice.default;
|
||
if (slice.type === 'boolean') {
|
||
if (typeof def !== 'boolean') {
|
||
errors.push(
|
||
'capability "' + capId + '" config["' + key + '"]: default must be a boolean for type:"boolean" (got: ' + typeof def + ')',
|
||
);
|
||
}
|
||
} else if (slice.type === 'string') {
|
||
if (typeof def !== 'string') {
|
||
errors.push(
|
||
'capability "' + capId + '" config["' + key + '"]: default must be a string for type:"string" (got: ' + typeof def + ')',
|
||
);
|
||
}
|
||
} else if (slice.type === 'number') {
|
||
if (typeof def !== 'number') {
|
||
errors.push(
|
||
'capability "' + capId + '" config["' + key + '"]: default must be a number for type:"number" (got: ' + typeof def + ')',
|
||
);
|
||
} else if (!Number.isFinite(def)) {
|
||
// FIX 6a: Reject NaN and non-finite number defaults
|
||
errors.push(
|
||
'capability "' + capId + '" config["' + key + '"]: default for type:"number" must be a finite number (got: ' + String(def) + ')',
|
||
);
|
||
}
|
||
} else if (slice.type === 'enum') {
|
||
// FIX 5a: enum REQUIRES a non-empty values array (all strings), and default must be in it
|
||
if (!Array.isArray(slice.values) || slice.values.length === 0) {
|
||
errors.push(
|
||
'capability "' + capId + '" config["' + key + '"]: type:"enum" requires a non-empty "values" array of strings',
|
||
);
|
||
} else if (!slice.values.every((v) => typeof v === 'string')) {
|
||
errors.push(
|
||
'capability "' + capId + '" config["' + key + '"]: type:"enum" values array must contain only strings',
|
||
);
|
||
}
|
||
if (typeof def !== 'string') {
|
||
errors.push(
|
||
'capability "' + capId + '" config["' + key + '"]: default must be a string for type:"enum" (got: ' + typeof def + ')',
|
||
);
|
||
} else if (Array.isArray(slice.values) && slice.values.length > 0 && !slice.values.includes(def)) {
|
||
errors.push(
|
||
'capability "' + capId + '" config["' + key + '"]: default "' + def +
|
||
'" is not one of the declared enum values [' + slice.values.join(', ') + ']',
|
||
);
|
||
}
|
||
}
|
||
}
|
||
|
||
// description must be a non-empty string
|
||
if (typeof slice.description !== 'string' || slice.description.length === 0) {
|
||
errors.push(
|
||
'capability "' + capId + '" config["' + key + '"]: description must be a non-empty string (got: ' + JSON.stringify(slice.description) + ')',
|
||
);
|
||
}
|
||
|
||
return errors;
|
||
}
|
||
|
||
// ─── Per-capability validation ────────────────────────────────────────────────
|
||
|
||
const KEBAB_RE = /^[a-z][a-z0-9-]*$/;
|
||
// ADR-2782 D3: a third role for reviewer lanes that are NOT install targets
|
||
// (gemini, coderabbit, ollama, lm_studio, llama_cpp). A `role: "reviewer"`
|
||
// capability carries a reviewer body, no runtime body, and no install surface.
|
||
const VALID_ROLES = new Set(['feature', 'runtime', 'reviewer']);
|
||
const VALID_TIERS = new Set(['core', 'standard', 'full']);
|
||
const VALID_ON_ERROR = new Set(['skip', 'halt']);
|
||
const RUNTIME_COMPAT_WILDCARD = '*';
|
||
|
||
// ── ADR-1244 D1: versioned-manifest envelope ─────────────────────────────────
|
||
// Official strict SemVer 2.0.0 grammar (https://semver.org). Rejects partials
|
||
// ("1.0"), prefixes ("v1.0.0"), leading-zero segments ("01.2.3"), numeric
|
||
// prerelease identifiers with leading zeros ("1.2.3-01"), empty identifiers
|
||
// ("1.2.3-..") and — critically — prerelease/build identifiers containing
|
||
// anything outside [0-9A-Za-z-] (so a version can never smuggle shell
|
||
// metacharacters, spaces or unicode into a downstream `git tag v<version>` or
|
||
// path). Accepts "1.2.3-dev.0", "1.2.3-rc.1", "1.2.3+build.5".
|
||
const SEMVER_RE = /^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-((?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*)(?:\.(?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*))*))?(?:\+([0-9a-zA-Z-]+(?:\.[0-9a-zA-Z-]+)*))?$/;
|
||
// Permissive *shape* check for a semver range (engines.gsd / compatVersions
|
||
// values). Range SATISFACTION is enforced by the runtime overlay (ADR-1244 D2);
|
||
// here we only reject empty/garbage and shell metacharacters.
|
||
const SEMVER_RANGE_RE = /^[0-9A-Za-z.\-+ |<>=~^*()]+$/;
|
||
// Subresource-integrity hash: "sha512-" + base64 of a 64-byte digest (86 base64
|
||
// chars + "==" padding). Exact length so malformed pins ("sha512-abc") fail.
|
||
const SHA512_INTEGRITY_RE = /^sha512-[A-Za-z0-9+/]{86}==$/;
|
||
|
||
// #1460 (R) HIGH — shell-safe hook-script allowlist. A hook `script` is resolved to an
|
||
// ABSOLUTE path and written verbatim as the hook `command` STRING in settings.json, which a
|
||
// host runtime consumes through a shell (first-party hooks emit `node "${...}/hooks/x.js"`).
|
||
// A manifest-controlled name like `run.sh; touch /tmp/pwn` (filenames may legally contain
|
||
// `;`, spaces, `$`, backtick, `|`, newline on POSIX) would inject a second command — even
|
||
// though the file genuinely exists inside the bundle and so passes path-confinement. We
|
||
// therefore restrict the relative script path to a CONSERVATIVE allowlist: only
|
||
// [A-Za-z0-9._/-], with no leading `-` on any segment (option-injection), no `..` segment,
|
||
// and not absolute. Anything else (whitespace, any shell metacharacter, control/NUL) is a
|
||
// hard validation error — fail closed so the capability install/load is rejected loudly.
|
||
const SAFE_HOOK_SCRIPT_RE = /^[A-Za-z0-9._/-]+$/;
|
||
|
||
// #3631 (defense-in-depth, mirrors capability-lifecycle.cts — KEEP BOTH IN SYNC): a declared script
|
||
// path must not point into the space bundleContentHash (capability-consent.cts) excludes from the
|
||
// consent-binding digest. A file whose basename ends `.pyc`/`.pyo` can contain perfectly valid
|
||
// JavaScript and would be executed by `node` regardless of extension, and a `__pycache__`/
|
||
// `.pytest_cache` segment marks a directory whose digest marker is suppressed — so a MANIFEST-DECLARED
|
||
// executable surface must never be able to reach either, or the exclusion becomes reachable from a
|
||
// path an attacker fully controls at declare-time rather than only via post-consent tamper.
|
||
// Regex asymmetry is DELIBERATE, KEEP BOTH RULES IN SYNC WITH capability-lifecycle.cts (byte-identical
|
||
// text, verified by the isSafeHookScriptPath parity test in tests/capability-registry.test.cjs):
|
||
// (i) PYCACHE_SUFFIX_RE is case-INSENSITIVE (`/i`) on purpose — a validator should be STRICTER than
|
||
// the digest it defends, so it rejects `x.PYC` too even though bundleContentHash's own suffix
|
||
// match (hasPycacheFileSuffix, capability-consent.cts) is byte-exact and would still hash it.
|
||
// (ii) The __pycache__/.pytest_cache SEGMENT match is case-SENSITIVE to match the digest's own
|
||
// byte-exact, case-sensitive directory-basename comparison (CPython always writes a lowercase
|
||
// `__pycache__`) — a validator segment match looser than the digest here would reject paths the
|
||
// digest would still hash, which is over-strict in the wrong direction for a defense-in-depth
|
||
// check layered on top of an already-correct digest.
|
||
// (iii) The `[/\\]` backslash alternations in both regexes are defensive/UNREACHABLE in practice:
|
||
// SAFE_HOOK_SCRIPT_RE (above) already rejects any backslash character outright, so a script
|
||
// string containing `\` never reaches either PYCACHE_*_RE check.
|
||
const PYCACHE_SEGMENT_RE = /(?:^|[/\\])(__pycache__|\.pytest_cache)(?:[/\\]|$)/;
|
||
const PYCACHE_SUFFIX_RE = /\.(pyc|pyo)$/i;
|
||
|
||
/**
|
||
* #1460 (R): true when a relative hook-script path is shell-safe (see SAFE_HOOK_SCRIPT_RE).
|
||
* Rejects absolute paths, `..` segments, a leading `-` on any path segment, and any char
|
||
* outside the allowlist (whitespace / shell metacharacters / control / NUL). #3631: also rejects a
|
||
* path with a `__pycache__`/`.pytest_cache` segment or a `.pyc`/`.pyo` basename suffix (defense in
|
||
* depth — keeps a declared executable surface out of the digest-excluded space).
|
||
*/
|
||
function isSafeHookScriptPath(script) {
|
||
if (typeof script !== 'string' || script.length === 0) return false;
|
||
if (!SAFE_HOOK_SCRIPT_RE.test(script)) return false;
|
||
if (path.isAbsolute(script)) return false;
|
||
const segments = script.split(/[/\\]/);
|
||
if (segments.includes('..')) return false;
|
||
// A leading '-' on any segment would be parsed as an option by the shell/`node`.
|
||
for (const seg of segments) {
|
||
if (seg.startsWith('-')) return false;
|
||
}
|
||
if (PYCACHE_SEGMENT_RE.test(script)) return false;
|
||
if (PYCACHE_SUFFIX_RE.test(path.basename(script))) return false;
|
||
return true;
|
||
}
|
||
|
||
// A syntactically plausible semver range (shape-only — see SEMVER_RANGE_RE).
|
||
// Requires a digit or a bare wildcard so pure-alpha garbage ("abcx", "()x") is
|
||
// rejected; full range satisfaction is the runtime overlay's job (ADR-1244 D2).
|
||
function isPlausibleRange(s) {
|
||
if (typeof s !== 'string') return false;
|
||
const t = s.trim();
|
||
if (t.length === 0 || !SEMVER_RANGE_RE.test(s)) return false;
|
||
return /\d/.test(t) || t === '*' || t === 'x' || t === 'X';
|
||
}
|
||
|
||
/**
|
||
* ADR-1244 D1: validate the versioned-manifest envelope.
|
||
* - version REQUIRED semver string (the registry rejects a manifest
|
||
* without one).
|
||
* - engines optional object; engines.gsd optional semver-range string.
|
||
* - compatVersions optional object mapping a capability version (semver) to a
|
||
* gsd version range.
|
||
* - integrity optional "sha512-<base64>" string.
|
||
* - provenance optional { sourceRepo, commit } strings.
|
||
*
|
||
* Shape only — range satisfaction and integrity verification are enforced by
|
||
* the source resolver / runtime overlay (ADR-1244 D2/D3).
|
||
*
|
||
* @param {object} cap The parsed JSON object.
|
||
* @returns {string[]} Array of error strings; empty = valid.
|
||
*/
|
||
function validateVersionEnvelope(cap) {
|
||
const errors = [];
|
||
|
||
if (typeof cap.version !== 'string' || !SEMVER_RE.test(cap.version)) {
|
||
errors.push('version must be a semver string (e.g. "1.2.3"); got: ' + JSON.stringify(cap.version));
|
||
}
|
||
|
||
if (cap.engines !== undefined) {
|
||
if (typeof cap.engines !== 'object' || cap.engines === null || Array.isArray(cap.engines)) {
|
||
errors.push('engines must be an object (e.g. { "gsd": ">=1.6.0" })');
|
||
} else if (cap.engines.gsd !== undefined && !isPlausibleRange(cap.engines.gsd)) {
|
||
errors.push('engines.gsd must be a semver range string; got: ' + JSON.stringify(cap.engines.gsd));
|
||
}
|
||
}
|
||
|
||
if (cap.compatVersions !== undefined) {
|
||
if (typeof cap.compatVersions !== 'object' || cap.compatVersions === null || Array.isArray(cap.compatVersions)) {
|
||
errors.push('compatVersions must be an object mapping capability versions to gsd version ranges');
|
||
} else {
|
||
for (const [k, v] of Object.entries(cap.compatVersions)) {
|
||
if (!SEMVER_RE.test(k)) errors.push('compatVersions key "' + k + '" must be a semver string');
|
||
if (!isPlausibleRange(v)) errors.push('compatVersions["' + k + '"] must be a semver range string');
|
||
}
|
||
}
|
||
}
|
||
|
||
if (cap.integrity !== undefined && (typeof cap.integrity !== 'string' || !SHA512_INTEGRITY_RE.test(cap.integrity))) {
|
||
errors.push('integrity must be a "sha512-<base64>" string');
|
||
}
|
||
|
||
if (cap.provenance !== undefined) {
|
||
const p = cap.provenance;
|
||
if (typeof p !== 'object' || p === null || Array.isArray(p)) {
|
||
errors.push('provenance must be an object { sourceRepo, commit }');
|
||
} else {
|
||
if (typeof p.sourceRepo !== 'string' || p.sourceRepo.length === 0) {
|
||
errors.push('provenance.sourceRepo must be a non-empty string');
|
||
}
|
||
if (typeof p.commit !== 'string' || p.commit.length === 0) {
|
||
errors.push('provenance.commit must be a non-empty string');
|
||
}
|
||
}
|
||
}
|
||
|
||
return errors;
|
||
}
|
||
|
||
/**
|
||
* Validate a single capability declaration.
|
||
*
|
||
* @param {object} cap The parsed JSON object.
|
||
* @param {string} folderId The folder name (must equal cap.id).
|
||
* @returns {string[]} Array of error strings; empty = valid.
|
||
*/
|
||
function validateCapability(cap, folderId) {
|
||
const errors = [];
|
||
|
||
if (typeof cap !== 'object' || cap === null || Array.isArray(cap)) {
|
||
return ['capability must be a JSON object'];
|
||
}
|
||
|
||
// ── Common envelope ────────────────────────────────────────────────────────
|
||
|
||
if (typeof cap.id !== 'string' || !KEBAB_RE.test(cap.id)) {
|
||
errors.push('id must be a kebab-case string');
|
||
} else if (cap.id !== folderId) {
|
||
errors.push('id "' + cap.id + '" must equal the folder name "' + folderId + '"');
|
||
}
|
||
|
||
if (!VALID_ROLES.has(cap.role)) {
|
||
errors.push('role must be one of: ' + [...VALID_ROLES].join(', ') + ' (got: ' + cap.role + ')');
|
||
}
|
||
|
||
if (typeof cap.title !== 'string' || cap.title.length === 0) {
|
||
errors.push('title must be a non-empty string');
|
||
}
|
||
|
||
// C4: description is required
|
||
if (typeof cap.description !== 'string' || cap.description.length === 0) {
|
||
errors.push('description must be a non-empty string');
|
||
}
|
||
|
||
if (!VALID_TIERS.has(cap.tier)) {
|
||
errors.push('tier must be one of: core, standard, full (got: ' + cap.tier + ')');
|
||
}
|
||
|
||
if (!Array.isArray(cap.requires)) {
|
||
errors.push('requires must be an array of capability ids');
|
||
} else {
|
||
for (const req of cap.requires) {
|
||
if (typeof req !== 'string') {
|
||
errors.push('requires entries must be strings (got: ' + JSON.stringify(req) + ')');
|
||
}
|
||
}
|
||
}
|
||
|
||
// ── Versioned-manifest envelope (ADR-1244 D1) ──────────────────────────────
|
||
errors.push(...validateVersionEnvelope(cap));
|
||
|
||
// ── Role-specific body ────────────────────────────────────────────────────
|
||
|
||
if (cap.role === 'feature') {
|
||
errors.push(...validateFeatureBody(cap));
|
||
// ADR-2782 D1 admits the reviewer body on `runtime` and `reviewer` ONLY. A
|
||
// feature capability owns loop artefacts, not an external review CLI. This is
|
||
// an ERROR rather than an ignored field because declaring a body is an
|
||
// ASSERTION of lane-ness (D4's Postel boundary), and a manifest built for a
|
||
// GSD that admits it declares `engines.gsd` and is gated before reaching here.
|
||
if (cap.reviewer !== undefined) {
|
||
errors.push('role:feature capability must not have a "reviewer" body (admissible on role runtime or reviewer only)');
|
||
}
|
||
} else if (cap.role === 'runtime') {
|
||
errors.push(...validateRuntimeBody(cap));
|
||
// A host that is ALSO a reviewer keeps exactly one manifest (ADR-2782 D1).
|
||
errors.push(...validateReviewerBody(cap));
|
||
// ADR-3646: a runtime capability installs a host CLI, it does not resolve
|
||
// task content — taskContentResolver is feature-only.
|
||
if (cap.taskContentResolver !== undefined) {
|
||
errors.push('role:runtime capability must not have a "taskContentResolver" body (feature-only field)');
|
||
}
|
||
} else if (cap.role === 'reviewer') {
|
||
// ADR-2782 D3 — a lane that is not an install target. No runtime body, no
|
||
// install surface, no runtimeCompat (it surfaces through no host runtime).
|
||
if (cap.reviewer === undefined) {
|
||
errors.push('role:reviewer capability must have a "reviewer" body — the role asserts a lane');
|
||
}
|
||
if (cap.runtime !== undefined) {
|
||
errors.push('role:reviewer capability must not have a "runtime" body (it is not an install target)');
|
||
}
|
||
for (const field of FEATURE_FIELDS_FORBIDDEN_ON_REVIEWER) {
|
||
if (cap[field] !== undefined) {
|
||
errors.push('role:reviewer capability must not have "' + field + '" (feature-only field)');
|
||
}
|
||
}
|
||
errors.push(...validateReviewerBody(cap));
|
||
}
|
||
|
||
return errors;
|
||
}
|
||
|
||
/**
|
||
* ADR-959: Validate a single commands[] entry on a feature-role capability.
|
||
* { family: string, module: string, router: string, subcommands?: string[] }
|
||
*
|
||
* - family: non-empty string, no reserved names
|
||
* - module: non-empty string, no path traversal, no absolute paths, no "/"
|
||
* segments other than a bare basename (expected form: "foo.cjs")
|
||
* - router: non-empty string
|
||
* - subcommands: optional array of strings (doc/introspection only)
|
||
*
|
||
* @param {string} capId Capability id (for error messages)
|
||
* @param {*} entry The entry to validate
|
||
* @param {string} prefix Path prefix (e.g. "commands[0]")
|
||
* @returns {string[]} Array of error strings; empty = valid.
|
||
*/
|
||
function validateCommandEntry(capId, entry, prefix) {
|
||
const errors = [];
|
||
const ctx = 'capability "' + capId + '" ' + prefix;
|
||
|
||
if (typeof entry !== 'object' || entry === null || Array.isArray(entry)) {
|
||
errors.push(ctx + ' must be an object with family, module, and router');
|
||
return errors;
|
||
}
|
||
|
||
// family: non-empty string, no reserved names
|
||
if (typeof entry.family !== 'string' || entry.family.length === 0) {
|
||
errors.push(ctx + '.family must be a non-empty string');
|
||
} else if (entry.family === '__proto__' || entry.family === 'constructor' || entry.family === 'prototype') {
|
||
// S2a: inline literal reserved-name guard (CodeQL barrier)
|
||
errors.push(ctx + '.family "' + entry.family + '" is a reserved name');
|
||
}
|
||
|
||
// module: must be a safe bare basename matching /^[A-Za-z0-9._-]+\.cjs$/ —
|
||
// no path separators, no "..", no NUL bytes, no absolute paths, ends in .cjs.
|
||
// This conservative pattern subsumes all earlier traversal/absolute/separator checks.
|
||
if (typeof entry.module !== 'string' || entry.module.length === 0) {
|
||
errors.push(ctx + '.module must be a non-empty string');
|
||
} else {
|
||
const mod = entry.module;
|
||
const SAFE_BASENAME = /^[A-Za-z0-9._-]+\.cjs$/;
|
||
if (!SAFE_BASENAME.test(mod)) {
|
||
errors.push(
|
||
ctx + '.module must be a safe bare basename (pattern: /^[A-Za-z0-9._-]+\\.cjs$/, no path separators, no "..", no NUL bytes, must end in ".cjs"); got: ' +
|
||
JSON.stringify(mod),
|
||
);
|
||
}
|
||
}
|
||
|
||
// router: non-empty string
|
||
if (typeof entry.router !== 'string' || entry.router.length === 0) {
|
||
errors.push(ctx + '.router must be a non-empty string');
|
||
}
|
||
|
||
// subcommands: optional array of non-empty strings (doc/introspection only)
|
||
if (entry.subcommands !== undefined) {
|
||
if (!Array.isArray(entry.subcommands)) {
|
||
errors.push(ctx + '.subcommands must be an array of strings if present');
|
||
} else {
|
||
for (let i = 0; i < entry.subcommands.length; i++) {
|
||
if (typeof entry.subcommands[i] !== 'string') {
|
||
errors.push(ctx + '.subcommands[' + i + '] must be a string');
|
||
} else if (entry.subcommands[i].length === 0) {
|
||
errors.push(ctx + '.subcommands[' + i + '] must be a non-empty string');
|
||
}
|
||
}
|
||
}
|
||
}
|
||
|
||
return errors;
|
||
}
|
||
|
||
function validateRuntimeCompat(capId, runtimeCompat) {
|
||
const errors = [];
|
||
const ctx = 'capability "' + capId + '" runtimeCompat';
|
||
|
||
if (typeof runtimeCompat !== 'object' || runtimeCompat === null || Array.isArray(runtimeCompat)) {
|
||
errors.push(ctx + ' must be an object with supported and unsupported arrays');
|
||
return errors;
|
||
}
|
||
|
||
const validateRuntimeArray = (field, { allowWildcard }) => {
|
||
const value = runtimeCompat[field];
|
||
if (!Array.isArray(value)) {
|
||
errors.push(ctx + '.' + field + ' must be an array of runtime ids' + (allowWildcard ? ' or ["*"]' : ''));
|
||
return;
|
||
}
|
||
if (field === 'supported' && value.length === 0) {
|
||
errors.push(ctx + '.supported must be a non-empty array');
|
||
}
|
||
let hasWildcard = false;
|
||
for (let i = 0; i < value.length; i++) {
|
||
const entry = value[i];
|
||
if (typeof entry !== 'string' || entry.length === 0) {
|
||
errors.push(ctx + '.' + field + '[' + i + '] must be a non-empty string');
|
||
continue;
|
||
}
|
||
if (entry === '__proto__' || entry === 'constructor' || entry === 'prototype') {
|
||
errors.push(ctx + '.' + field + '[' + i + '] "' + entry + '" is a reserved name');
|
||
}
|
||
if (entry === RUNTIME_COMPAT_WILDCARD) {
|
||
if (!allowWildcard) {
|
||
errors.push(ctx + '.' + field + ' must not include wildcard "*"');
|
||
}
|
||
hasWildcard = true;
|
||
} else if (!KEBAB_RE.test(entry)) {
|
||
errors.push(ctx + '.' + field + '[' + i + '] must be a kebab-case runtime id or "*"');
|
||
}
|
||
}
|
||
if (hasWildcard && value.length > 1) {
|
||
errors.push(ctx + '.' + field + ' wildcard "*" cannot be mixed with runtime ids');
|
||
}
|
||
};
|
||
|
||
validateRuntimeArray('supported', { allowWildcard: true });
|
||
validateRuntimeArray('unsupported', { allowWildcard: false });
|
||
|
||
if (runtimeCompat.notes !== undefined) {
|
||
if (typeof runtimeCompat.notes !== 'object' || runtimeCompat.notes === null || Array.isArray(runtimeCompat.notes)) {
|
||
errors.push(ctx + '.notes must be an object of runtime id to string if present');
|
||
} else {
|
||
for (const [key, value] of Object.entries(runtimeCompat.notes)) {
|
||
if (key !== RUNTIME_COMPAT_WILDCARD && !KEBAB_RE.test(key)) {
|
||
errors.push(ctx + '.notes key "' + key + '" must be a kebab-case runtime id or "*"');
|
||
}
|
||
if (typeof value !== 'string' || value.length === 0) {
|
||
errors.push(ctx + '.notes["' + key + '"] must be a non-empty string');
|
||
}
|
||
}
|
||
}
|
||
}
|
||
|
||
return errors;
|
||
}
|
||
|
||
function validateFeatureBody(cap) {
|
||
const errors = [];
|
||
|
||
errors.push(...validateRuntimeCompat(cap.id || '(unknown)', cap.runtimeCompat));
|
||
|
||
if (!Array.isArray(cap.skills)) {
|
||
errors.push('skills must be an array of strings');
|
||
} else {
|
||
for (const s of cap.skills) {
|
||
if (typeof s !== 'string') {
|
||
errors.push('skills entries must be strings');
|
||
} else if (s === '__proto__' || s === 'constructor' || s === 'prototype') {
|
||
// S2a: inline literal reserved-name guard (CodeQL barrier)
|
||
errors.push('skills entry "' + s + '" is a reserved name');
|
||
}
|
||
}
|
||
}
|
||
|
||
// ADR-959: optional commands array
|
||
if (cap.commands !== undefined) {
|
||
if (!Array.isArray(cap.commands)) {
|
||
errors.push('commands must be an array of {family, module, router} objects');
|
||
} else {
|
||
for (let i = 0; i < cap.commands.length; i++) {
|
||
errors.push(...validateCommandEntry(cap.id || cap.role, cap.commands[i], 'commands[' + i + ']'));
|
||
}
|
||
}
|
||
}
|
||
|
||
if (!Array.isArray(cap.agents)) {
|
||
errors.push('agents must be an array of strings');
|
||
} else {
|
||
for (const a of cap.agents) {
|
||
if (typeof a !== 'string') {
|
||
errors.push('agents entries must be strings');
|
||
} else if (a === '__proto__' || a === 'constructor' || a === 'prototype') {
|
||
// S2a: inline literal reserved-name guard (CodeQL barrier)
|
||
errors.push('agents entry "' + a + '" is a reserved name');
|
||
}
|
||
}
|
||
}
|
||
|
||
if (typeof cap.config !== 'object' || cap.config === null || Array.isArray(cap.config)) {
|
||
errors.push('config must be an object');
|
||
} else {
|
||
// C5: validate config key names and value shapes
|
||
for (const key of Object.keys(cap.config)) {
|
||
if (key === '' ) {
|
||
errors.push('config keys must be non-empty strings');
|
||
} else if (key === '__proto__' || key === 'constructor' || key === 'prototype') {
|
||
// S2a: inline literal reserved-name guard (CodeQL barrier)
|
||
errors.push('config key "' + key + '" is a reserved name');
|
||
}
|
||
const val = cap.config[key];
|
||
if (val === null || typeof val !== 'object' || Array.isArray(val)) {
|
||
errors.push('config["' + key + '"] must be an object (got: ' + (val === null ? 'null' : typeof val) + ')');
|
||
} else if (typeof val.type !== 'string' || val.type.length === 0) {
|
||
errors.push('config["' + key + '"] must have a string "type" field (e.g. "boolean", "string", "number", "enum")');
|
||
}
|
||
}
|
||
}
|
||
|
||
// C4: hooks, when present, must be an array of {event: string, script: string}
|
||
if (cap.hooks !== undefined) {
|
||
if (!Array.isArray(cap.hooks)) {
|
||
errors.push('hooks must be an array of {event, script} objects');
|
||
} else {
|
||
for (let i = 0; i < cap.hooks.length; i++) {
|
||
const h = cap.hooks[i];
|
||
if (typeof h !== 'object' || h === null || Array.isArray(h)) {
|
||
errors.push('hooks[' + i + '] must be an object with event and script keys');
|
||
} else {
|
||
if (typeof h.event !== 'string' || h.event.length === 0) {
|
||
errors.push('hooks[' + i + '].event must be a non-empty string');
|
||
}
|
||
if (typeof h.script !== 'string' || h.script.length === 0) {
|
||
errors.push('hooks[' + i + '].script must be a non-empty string');
|
||
} else if (!isSafeHookScriptPath(h.script)) {
|
||
// #1460 (R) HIGH: the script becomes an absolute hook `command` consumed by a shell;
|
||
// reject any unsafe character (shell metacharacters/whitespace/control), a leading `-`,
|
||
// an absolute path, or a `..` segment so a manifest can never inject a second command.
|
||
errors.push(
|
||
'hooks[' + i + '].script must be a relative path containing only [A-Za-z0-9._/-] ' +
|
||
'(no whitespace, shell metacharacters (e.g. ; | & $ ` ( ) < > * ? newline), leading "-", ' +
|
||
'absolute path, or ".." segment) — it contains unsafe characters: ' + JSON.stringify(h.script),
|
||
);
|
||
}
|
||
// #1634: optional tool-scoping `matcher` (a settings.json concept — exact tool name,
|
||
// pipe-separated list, wildcard, or regex; e.g. "Write|Edit"). When present it must be a
|
||
// non-empty string without control characters; absent => match-all (omitted at projection
|
||
// so existing shipped capabilities are unchanged).
|
||
if (h.matcher !== undefined) {
|
||
if (typeof h.matcher !== 'string' || h.matcher.length === 0) {
|
||
errors.push('hooks[' + i + '].matcher must be a non-empty string when present');
|
||
} else {
|
||
// Reject ASCII control characters (0x00-0x1f and 0x7f DEL) via char codes — a literal
|
||
// control-char range regex trips ESLint's no-control-regex rule, and char codes are
|
||
// equally precise.
|
||
let hasControl = false;
|
||
for (let c = 0; c < h.matcher.length; c++) {
|
||
const code = h.matcher.charCodeAt(c);
|
||
if (code < 0x20 || code === 0x7f) { hasControl = true; break; }
|
||
}
|
||
if (hasControl) {
|
||
errors.push('hooks[' + i + '].matcher must not contain control characters');
|
||
}
|
||
}
|
||
}
|
||
}
|
||
}
|
||
}
|
||
}
|
||
|
||
// Build the declared skill/agent sets for ref membership checks (used in validateStep).
|
||
// Only build these if the arrays are valid (already validated above).
|
||
const declaredSkills = Array.isArray(cap.skills) ? new Set(cap.skills.filter((s) => typeof s === 'string')) : null;
|
||
const declaredAgents = Array.isArray(cap.agents) ? new Set(cap.agents.filter((a) => typeof a === 'string')) : null;
|
||
|
||
if (!Array.isArray(cap.steps)) {
|
||
errors.push('steps must be an array');
|
||
} else {
|
||
for (let i = 0; i < cap.steps.length; i++) {
|
||
errors.push(...validateStep(cap.steps[i], 'steps[' + i + ']', declaredSkills, declaredAgents));
|
||
}
|
||
}
|
||
|
||
if (!Array.isArray(cap.contributions)) {
|
||
errors.push('contributions must be an array');
|
||
} else {
|
||
for (let i = 0; i < cap.contributions.length; i++) {
|
||
errors.push(...validateContribution(cap.contributions[i], 'contributions[' + i + ']'));
|
||
}
|
||
}
|
||
|
||
if (!Array.isArray(cap.gates)) {
|
||
errors.push('gates must be an array');
|
||
} else {
|
||
for (let i = 0; i < cap.gates.length; i++) {
|
||
errors.push(...validateGate(cap.gates[i], 'gates[' + i + ']'));
|
||
}
|
||
}
|
||
|
||
// activationKey: optional string naming the dotted config key that gates this capability.
|
||
// If present: must be a non-empty string that is declared in this capability's own config slice.
|
||
if (cap.activationKey !== undefined) {
|
||
if (typeof cap.activationKey !== 'string' || cap.activationKey.length === 0) {
|
||
errors.push(
|
||
'capability "' + (cap.id || '(unknown)') + '" activationKey must be a non-empty string (got: ' +
|
||
JSON.stringify(cap.activationKey) + ')',
|
||
);
|
||
} else if (cap.activationKey === '__proto__' || cap.activationKey === 'constructor' || cap.activationKey === 'prototype') {
|
||
// Prototype-pollution guard (inline literal, CodeQL barrier)
|
||
errors.push(
|
||
'capability "' + (cap.id || '(unknown)') + '" activationKey "' + cap.activationKey +
|
||
'" is a reserved JavaScript property name and cannot be used as an activationKey',
|
||
);
|
||
} else if (
|
||
typeof cap.config !== 'object' ||
|
||
cap.config === null ||
|
||
!Object.prototype.hasOwnProperty.call(cap.config, cap.activationKey)
|
||
) {
|
||
errors.push(
|
||
'capability "' + (cap.id || '(unknown)') + '" activationKey "' + cap.activationKey +
|
||
'" is not declared in this capability\'s config slice — add it to the "config" object or use a key that is declared there',
|
||
);
|
||
}
|
||
}
|
||
|
||
// ADR-3646: optional per-task external-tracker content-resolution seam.
|
||
errors.push(...validateTaskContentResolver(cap));
|
||
|
||
return errors;
|
||
}
|
||
|
||
/**
|
||
* ADR-3646 — validate an OPTIONAL `taskContentResolver` body on a `role:
|
||
* "feature"` capability. Absence is never an error (most manifests won't
|
||
* have one); presence is strictly validated.
|
||
*
|
||
* Wrapped in try/catch to degrade any unexpected throw (a hostile Proxy, a
|
||
* throwing getter, etc.) to a single validation error rather than crashing
|
||
* every consumer of loadRegistry, per the #1461 OVL-1 discipline that
|
||
* `validateReviewerBody` follows.
|
||
*
|
||
* @param {object} cap The parsed capability manifest.
|
||
* @returns {string[]} Array of error strings; empty = valid or absent.
|
||
*/
|
||
function validateTaskContentResolver(cap) {
|
||
try {
|
||
return validateTaskContentResolverFields(cap);
|
||
} catch (err) {
|
||
return ['capability taskContentResolver body could not be validated: ' + safeErrorMessage(err)];
|
||
}
|
||
}
|
||
|
||
/**
|
||
* Upper bound for `taskContentResolver.invoke.timeoutMs`, specific to this
|
||
* field only. `isPositiveIntegerMs()` has no ceiling and stays that way — it
|
||
* is shared with the reviewer lane's `timeoutFloorMs` and probe `timeoutMs`,
|
||
* which may legitimately need a longer or unbounded value. Without a ceiling
|
||
* here, a manifest could declare `Number.MAX_SAFE_INTEGER` and let
|
||
* `resolve-content` hang near-indefinitely on a stuck/malicious resolver,
|
||
* defeating the feature's "bounded subprocess" design intent.
|
||
*/
|
||
const TASK_CONTENT_RESOLVER_TIMEOUT_CEILING_MS = 120000;
|
||
|
||
function validateTaskContentResolverFields(cap) {
|
||
const errors = [];
|
||
if (typeof cap !== 'object' || cap === null || Array.isArray(cap)) return errors;
|
||
|
||
const tcr = cap.taskContentResolver;
|
||
if (tcr === undefined) return errors; // optional — never an error to omit
|
||
|
||
const ctx = 'capability "' + (typeof cap.id === 'string' ? cap.id : '(unknown)') + '"';
|
||
|
||
if (typeof tcr !== 'object' || tcr === null || Array.isArray(tcr)) {
|
||
const got = tcr === null ? 'null' : Array.isArray(tcr) ? 'array' : typeof tcr;
|
||
errors.push(
|
||
ctx + ' taskContentResolver must be an object (got: ' + got + '). ' +
|
||
'Omit the key entirely to declare no resolver — an explicit null is not an omission.',
|
||
);
|
||
return errors; // cannot validate fields of a non-object
|
||
}
|
||
|
||
// ── trackerPrefix — same grammar as a capability id ─────────────────────
|
||
if (typeof tcr.trackerPrefix !== 'string' || tcr.trackerPrefix.length === 0 || !KEBAB_RE.test(tcr.trackerPrefix)) {
|
||
errors.push(
|
||
ctx + ' taskContentResolver.trackerPrefix must be a non-empty kebab-case string matching ' +
|
||
String(KEBAB_RE) + ' (got: ' + describeValue(tcr.trackerPrefix) + ')',
|
||
);
|
||
}
|
||
|
||
// ── invoke ────────────────────────────────────────────────────────────
|
||
const inv = tcr.invoke;
|
||
if (typeof inv !== 'object' || inv === null || Array.isArray(inv)) {
|
||
const got = inv === null ? 'null' : Array.isArray(inv) ? 'array' : typeof inv;
|
||
errors.push(ctx + ' taskContentResolver.invoke must be an object (got: ' + got + ')');
|
||
return errors; // cannot validate sub-fields of a non-object
|
||
}
|
||
|
||
if (typeof inv.binary !== 'string' || inv.binary.length === 0) {
|
||
errors.push(ctx + ' taskContentResolver.invoke.binary must be a non-empty string');
|
||
}
|
||
|
||
if (!Array.isArray(inv.args)) {
|
||
errors.push(ctx + ' taskContentResolver.invoke.args must be an array of strings');
|
||
} else {
|
||
let hasPlaceholder = false;
|
||
for (const a of inv.args) {
|
||
if (typeof a !== 'string') {
|
||
errors.push(ctx + ' taskContentResolver.invoke.args entries must be strings (got: ' + describeValue(a) + ')');
|
||
} else if (a === '{{id}}') {
|
||
hasPlaceholder = true;
|
||
}
|
||
}
|
||
if (!hasPlaceholder) {
|
||
errors.push(
|
||
ctx + ' taskContentResolver.invoke.args must contain a "{{id}}" placeholder — ' +
|
||
'without it the resolved tracker id could never reach the resolver subprocess',
|
||
);
|
||
}
|
||
}
|
||
|
||
if (!isPositiveIntegerMs(inv.timeoutMs)) {
|
||
errors.push(
|
||
ctx + ' taskContentResolver.invoke.timeoutMs must be a positive integer of milliseconds — ' +
|
||
'an unbounded resolver call could hang task execution indefinitely ' +
|
||
'(got: ' + describeValue(inv.timeoutMs) + ')',
|
||
);
|
||
} else if (inv.timeoutMs > TASK_CONTENT_RESOLVER_TIMEOUT_CEILING_MS) {
|
||
// Ceiling specific to this field — `isPositiveIntegerMs()` itself stays
|
||
// unbounded because it is shared with the reviewer lane's
|
||
// `timeoutFloorMs`/probe `timeoutMs`, which have no such ceiling.
|
||
errors.push(
|
||
ctx + ' taskContentResolver.invoke.timeoutMs must not exceed ' +
|
||
TASK_CONTENT_RESOLVER_TIMEOUT_CEILING_MS + 'ms — an unbounded-in-practice value defeats the ' +
|
||
'"bounded subprocess" design intent (got: ' + inv.timeoutMs + ')',
|
||
);
|
||
}
|
||
|
||
return errors;
|
||
}
|
||
|
||
// ADR-857 phase 5e: Closed ConverterName enum — complete set used across 16 runtime descriptors,
|
||
// all exported by bin/install.js (commands/skills) and src/runtime-artifact-conversion.cts (agents).
|
||
// Any ArtifactKind with a non-null converter must use one of these.
|
||
const VALID_CONVERTER_NAMES = new Set([
|
||
// commands / skills converters (pre-existing)
|
||
'convertClaudeCommandToAntigravitySkill',
|
||
'convertClaudeCommandToAugmentSkill',
|
||
'convertClaudeCommandToClineSkill',
|
||
'convertClaudeCommandToClaudeSkill',
|
||
'convertClaudeCommandToCodebuddyCommand',
|
||
'convertClaudeCommandToCodebuddySkill',
|
||
'convertClaudeCommandToCodexSkill',
|
||
'convertClaudeCommandToCopilotSkill',
|
||
'convertClaudeCommandToCursorSkill',
|
||
'convertClaudeCommandToKiloSkill',
|
||
'convertClaudeCommandToKimiSkill',
|
||
'convertClaudeCommandToKimiCodeSkill',
|
||
'convertClaudeCommandToOpencodeSkill',
|
||
'convertClaudeCommandToTraeSkill',
|
||
'convertClaudeCommandToWindsurfSkill',
|
||
'convertClaudeCommandToWindsurfWorkflow',
|
||
// agent converters (#1173 — descriptor-driven agent conversion wiring)
|
||
'convertClaudeAgentToCopilotAgent',
|
||
'convertClaudeAgentToAntigravityAgent',
|
||
'convertClaudeAgentToCursorAgent',
|
||
'convertClaudeAgentToWindsurfAgent',
|
||
'convertClaudeAgentToAugmentAgent',
|
||
'convertClaudeAgentToTraeAgent',
|
||
'convertClaudeAgentToCodebuddyAgent',
|
||
'convertClaudeAgentToClineAgent',
|
||
'convertClaudeAgentToCodexAgent',
|
||
// ADR-1239 / #2092 Phase B Upgrade 1 — native .qwen/agents/*.md subagent projection.
|
||
'convertClaudeAgentToQwenAgent',
|
||
// #3384 — ZCode agents are Claude-shaped but its dispatcher treats mcp__* tools
|
||
// grants as required MCP servers; this converter strips them at install time.
|
||
'convertClaudeAgentToZcodeAgent',
|
||
// #2875 Part 2 (the agents-bypass closure) — data-driven Hermes branding
|
||
// converter (reads hostBehaviors.brandingRewrites rather than a hardcode),
|
||
// and the kilo/opencode agent converters (shared with those runtimes'
|
||
// commands-kind entries, options-bag signature `(content, {isAgent, modelOverride})`).
|
||
'convertClaudeAgentToHermesAgent',
|
||
'convertClaudeToKiloFrontmatter',
|
||
'convertClaudeToOpencodeFrontmatter',
|
||
]);
|
||
|
||
// C3: Validate role:runtime body
|
||
const VALID_CONFIG_FORMATS = new Set(['settings-json', 'toml', 'markdown', 'markdown-dir', 'none']);
|
||
// 'none' added #2103 — Marketplace/VSIX-distributed hosts (e.g. VS Code) with
|
||
// no file-projected config directory at all.
|
||
const VALID_CONFIG_HOME_KINDS = new Set(['dot-home', 'dot-home-nested', 'xdg', 'generic-agents-root', 'none']);
|
||
const VALID_COMMAND_STYLES = new Set(['slash-hyphen', 'shell-var']);
|
||
const VALID_HOOKS_SURFACES = new Set(['settings-json', 'codex-hooks-json', 'cursor-hooks-json', 'copilot-inline', 'cline-rules', 'kimi-hooks-toml', 'windsurf-hooks-json', 'none']);
|
||
const VALID_HOOK_EVENTS = new Set(['claude', 'gemini']);
|
||
// extensionEvents — the plugin/extension-system event dialect (ADR-1239 amendment / #1943).
|
||
// DISTINCT from hookEvents (managed-hook dialect): extensionEvents describes the
|
||
// plugin-owned event subset imperative hosts expose (opencode / pi); 'none' = the
|
||
// host exposes no extension surface (engine owns the bus, e.g. VS Code).
|
||
const VALID_EXTENSION_EVENTS = new Set(['opencode', 'pi', 'hermes', 'kilo', 'none']);
|
||
const VALID_SANDBOX_TIERS = new Set(['none', 'codex-agent-sandbox']);
|
||
const VALID_ARTIFACT_KIND_NAMES = new Set(['commands', 'agents', 'skills', 'kimi-agents']);
|
||
const VALID_ARTIFACT_NESTINGS = new Set(['flat', 'nested']);
|
||
// #2871 Phase 2 — only `commands` and `skills` are trigger-bearing (a `/gsd-<name>`
|
||
// the USER types). `agents` and `kimi-agents` are a separate dispatch interface
|
||
// point (subagent invocation via `subagent_type`/named dispatch), never a trigger —
|
||
// see 40-design.md's "agents are not trigger-bearing" correction. A narrower set
|
||
// than VALID_ARTIFACT_KIND_NAMES on purpose: an artifact KIND can be agents; a
|
||
// trigger-precedence MEMBER never can.
|
||
const VALID_TRIGGER_PRECEDENCE_KINDS = new Set(['commands', 'skills']);
|
||
// The default runtime.triggerPrecedence (highest priority first) applied when a
|
||
// descriptor omits the axis (see validateRuntimeBody's required-with-default
|
||
// handling below). Not invented: `['skills', 'commands']` is the ordering every
|
||
// in-tree runtime that emits both kinds (from the same trigger stems) wants —
|
||
// claude's local/global collision and the same-scope collision (codebuddy, kilo,
|
||
// opencode, zcode) all resolve to skills winning. claude's shipped descriptor
|
||
// declares this SAME value explicitly, and
|
||
// tests/runtime-artifact-layout-trigger-surface.test.cjs asserts the two agree
|
||
// (a parity assertion — two surfaces reading one rule must not silently drift).
|
||
const DEFAULT_TRIGGER_PRECEDENCE = Object.freeze(['skills', 'commands']);
|
||
const FEATURE_FIELDS_FORBIDDEN_ON_RUNTIME = ['skills', 'agents', 'steps', 'contributions', 'gates', 'hooks', 'activationKey'];
|
||
// 'none' added #2103 — Marketplace/VSIX-distributed hosts (e.g. VS Code) that
|
||
// are never CLI-installed (no allRuntimes membership, no install flag).
|
||
const VALID_INSTALL_SURFACES = new Set(['settings-json', 'codex-toml', 'copilot-instructions', 'cline-rules', 'cursor-hooks-json', 'profile-marker-only', 'none']);
|
||
// 'antigravity' added #2096 Phase B Upgrade 1 — settings.json permissions.allow writer.
|
||
const VALID_PERMISSION_WRITERS = new Set(['opencode', 'kilo', 'antigravity']);
|
||
// SubagentStart added #2092 Phase B Upgrade 2 (qwen-only today — see
|
||
// capabilities/qwen/capability.json's extendedHookEvents).
|
||
const VALID_EXTENDED_HOOK_EVENTS = new Set(['SubagentStop', 'Stop', 'PreCompact', 'FileChanged', 'BeforeAgent', 'AfterAgent', 'BeforeModel', 'SubagentStart']);
|
||
|
||
// ADR-1239 Phase A: hostIntegration axes (MUST stay parity-identical to HOST_INTEGRATION_AXES in src/host-integration.cts)
|
||
const VALID_EMBEDDING_MODES = new Set(['imperative', 'declarative']);
|
||
const VALID_COMMAND_SURFACES = new Set(['slash-file', 'slash-programmatic', 'slash-toml', 'palette', 'prose-only']);
|
||
const VALID_MODEL_MODES = new Set(['active', 'passive']);
|
||
const VALID_HOOK_BUSES = new Set(['host', 'engine', 'none']);
|
||
const VALID_STATE_IO = new Set(['filesystem', 'sandboxed-storage', 'session-log-append']);
|
||
const VALID_TRANSPORTS = new Set(['mcp', 'native-extension']);
|
||
const VALID_HOST_RUNTIMES = new Set(['node', 'bun', 'sandboxed-web', 'python', 'go', 'rust', 'electron', 'other']);
|
||
const VALID_SUBAGENT_TOOLKITS = new Set(['full', 'read-only', 'built-in-only']);
|
||
// ADR-1239 amendment (#2481): how reasoning effort reaches the host.
|
||
const VALID_EFFORT_SURFACES = new Set(['argv', 'none']);
|
||
// ADR-1239 Codex-binding amendment (#2584): how a host isolates concurrent
|
||
// same-wave executors — a dispatch sub-field, not a top-level axis.
|
||
const VALID_DISPATCH_ISOLATION = new Set(['harness-worktree', 'orchestrator-worktree', 'none']);
|
||
|
||
// ─── Reviewer lane body (ADR-2782 D1/D2/D3/D7/D8) ────────────────────────────
|
||
//
|
||
// A reviewer lane is one external CLI or model endpoint that /gsd:review hands a
|
||
// plan to. The body is admissible on `role: "runtime"` (a host that is ALSO a
|
||
// reviewer) and on `role: "reviewer"` (a lane that is not an install target).
|
||
//
|
||
// The vocabulary below tracks src/review-lane-descriptor.cts (Phase 1, #2794)
|
||
// field-for-field INCLUDING nesting, so no translation layer exists between the
|
||
// core descriptor and the manifest. Four members were added by Phase 1's ADR
|
||
// amendment, each forced by a lane that ships today: `promptChannel: 'none'`
|
||
// (CodeRabbit is fed no prompt), `outputChannel: 'file-arg'` + `outputArg`
|
||
// (Codex writes via -o and discards stdout, #1698), and `flags[]` (Antigravity
|
||
// answers to both --antigravity and --agy).
|
||
//
|
||
// EVERY error message below enumerates its valid members. That is deliberate:
|
||
// the prose reference lands in Phase 6 (#2800), so until then the validator's
|
||
// own errors ARE the documentation — the same gap that left `hostBehaviors`
|
||
// discoverable only by grepping a source line is not repeated here.
|
||
|
||
// A slug is NOT a capability id. Ids are kebab (KEBAB_RE, which rejects "_");
|
||
// slugs carry the shipped roster's snake forms (`lm_studio`, `llama_cpp`) and
|
||
// name the config keys (`review.lm_studio_host`) that ADR-2782 D9 leaves
|
||
// unchanged. Reusing KEBAB_RE here would reject two shipped lanes.
|
||
//
|
||
// ⚠ DEFECT.GENERATIVE-FIX — this grammar is DUPLICATED, by necessity, from
|
||
// `LANE_SLUG_RE` in src/review-lane-descriptor.cts (Phase 1, #2794). It cannot be
|
||
// imported: that module compiles to gsd-core/bin/lib/review-lane-descriptor.cjs,
|
||
// which is gitignored build output, and THIS file is a committed plain .cjs that
|
||
// must load on a fresh worktree before `npm run build:lib` has ever run (see the
|
||
// header). Two surfaces sharing one parser therefore require a parity assertion
|
||
// that fails when they diverge — `laneSlugGrammarMatchesPhase1Descriptor` in
|
||
// tests/reviewer-manifest-body.test.cjs.
|
||
//
|
||
// A LEADING DIGIT IS PERMITTED. Phase 1 allows it and a manifest validator that
|
||
// did not would reject a slug the core descriptor accepts — a model-named lane
|
||
// such as `4o-mini` — which is exactly the translation layer ADR-2782 exists to
|
||
// delete. Keep the two grammars byte-identical.
|
||
const LANE_SLUG_RE = /^[a-z0-9][a-z0-9_-]*$/;
|
||
// Flags are kebab even when the slug is snake: `lm_studio` → `--lm-studio`.
|
||
// Phase 1 declares flags but does not constrain their grammar, so this is the
|
||
// first and only definition — no parity partner to track.
|
||
const LANE_FLAG_RE = /^--[a-z0-9][a-z0-9-]*$/;
|
||
|
||
const VALID_LANE_TRANSPORTS = new Set(['spawn', 'openai-http']);
|
||
const VALID_LANE_PROBE_KINDS = new Set(['command-exists', 'command-capability', 'http-reachable']);
|
||
const VALID_PROMPT_CHANNELS = new Set(['stdin', 'argv', 'argv-file-ref', 'none']);
|
||
const VALID_OUTPUT_CHANNELS = new Set(['stdout', 'file-arg']);
|
||
const VALID_LANE_EFFORT_CHANNELS = new Set(['none', 'argv', 'env']);
|
||
const VALID_MODEL_DISCOVERY = new Set(['none', 'first-from-models-endpoint']);
|
||
const VALID_EMPTY_OUTPUT = new Set(['stub-with-stderr', 'handler-owned']);
|
||
const VALID_EVIDENCE_CLASSES = new Set(['source-grounded', 'diff-only']);
|
||
|
||
// ADR-2782 D6 — a CLOSED enum of FIRST-PARTY module names, never a path and
|
||
// never third-party code. `null` is the default and covers 7 of the 11 shipped
|
||
// lanes; it is checked separately because a Set cannot hold the "declared
|
||
// absent" case distinctly from an unknown string.
|
||
//
|
||
// ADMISSION RULE for a new member — this enum is the pressure valve that keeps
|
||
// the descriptor from becoming an ad-hoc interpreter, and it only works while
|
||
// membership stays scarce. A new member requires EITHER >=2 lanes that share the
|
||
// behaviour, OR a documented upstream defect that data provably cannot express.
|
||
// Today: `openai-compatible` serves 3 lanes (healthy); `antigravity` serves 1,
|
||
// justified solely by a documented upstream stdout bug. An enum that grows one
|
||
// member per lane has stopped being a vocabulary and become a dispatch table for
|
||
// bespoke code — at which point the descriptor is a plugin system wearing a
|
||
// manifest, and that is a decision for an ADR, not for a downstream phase.
|
||
// `opencode` admitted by Phase 5b (#2799) under the SECOND arm of the rule above:
|
||
// it serves 1 lane, justified by a documented upstream defect data cannot express.
|
||
// OpenCode's default `build` agent is an agentic coder, not a prompt→completion
|
||
// API; on a large review prompt it can end its turn with ZERO output tokens, and
|
||
// `--format default` then drops the assistant text entirely, silently losing the
|
||
// reviewer (#1936). The review must therefore be RECONSTRUCTED from the assistant
|
||
// `text` parts of a `--format json` stream — a parse, not a copy. Expressing that
|
||
// as data would need an `outputChannel: 'json-parts'` plus a selector expression,
|
||
// i.e. exactly the ad-hoc interpreter the admission rule exists to prevent.
|
||
const VALID_LANE_HANDLERS = new Set(['antigravity', 'openai-compatible', 'opencode']);
|
||
|
||
// D2 — `transport` selects the invoke sub-shape. A manifest carrying fields from
|
||
// BOTH sub-shapes, or from NEITHER, has undefined meaning and fails validation.
|
||
// The discriminator is explicit rather than inferred from field presence, which
|
||
// is precisely the ambiguity these two sets exist to detect.
|
||
// `env` added by #2483. It belongs in THIS set and not merely in validateSpawnInvoke: an environment
|
||
// pair has no meaning for a transport that issues an HTTP POST, so a manifest declaring it alongside
|
||
// `openai-http` fields is the undefined-meaning case the comment above describes. Registering it here
|
||
// is what makes that case reportable — the openai-http arm rejects exactly the members of this list,
|
||
// so a field absent from it is silently accepted on the wrong transport. Note `effortChannel` is
|
||
// deliberately in NEITHER set: D2 defines it for both transports, so it is shared, not spawn-only.
|
||
const SPAWN_ONLY_INVOKE_FIELDS = ['binary', 'args', 'promptChannel', 'outputChannel', 'outputArg', 'modelArg', 'env'];
|
||
// Environment names refused outright on a reviewer lane (#2483): each one turns a declared pair into
|
||
// arbitrary code execution in the spawned child. DEFENCE IN DEPTH, NOT THE BOUNDARY — say so plainly,
|
||
// because a future reader who mistakes this for the control will under-invest in the one that is.
|
||
// The boundary is install-time consent: `capability-trust` discloses every declared env pair, shows
|
||
// its value, and binds it to the consent signature, so an unlisted name is still SEEN before it runs.
|
||
//
|
||
// Deliberately incomplete, and it cannot be otherwise: the spawned binary is arbitrary third-party
|
||
// code, so the exhaustive set is every interpreter's injection variables. What this list buys is that
|
||
// the highest-confidence, lowest-legitimacy routes cannot be taken quietly. `PATH` is included — it is
|
||
// the most complete primitive of the set (repoint it at a directory holding a fake binary) and no
|
||
// shipped reviewer manifest declares it; a lane that needs a specific executable declares an absolute
|
||
// `invoke.binary` rather than reshaping the child's `PATH`.
|
||
//
|
||
// Matched CASE-INSENSITIVELY (members stored uppercase) — Windows environment lookup is
|
||
// case-insensitive, so an exact-case set is bypassed by declaring `Path` or `node_options`.
|
||
const DENIED_LANE_ENV_KEYS = new Set([
|
||
'PATH', 'NODE_OPTIONS', 'NODE_REPL_EXTERNAL_MODULE', 'NODE_PATH',
|
||
'LD_PRELOAD', 'LD_AUDIT', 'LD_LIBRARY_PATH',
|
||
'DYLD_INSERT_LIBRARIES', 'DYLD_LIBRARY_PATH',
|
||
'PYTHONSTARTUP', 'PYTHONPATH', 'BASH_ENV', 'ENV',
|
||
'PERL5OPT', 'RUBYOPT', 'JAVA_TOOL_OPTIONS', '_JAVA_OPTIONS', 'CLASSPATH',
|
||
'GIT_SSH_COMMAND', 'GIT_EXTERNAL_DIFF',
|
||
]);
|
||
// `defaultHost` / `fallbackModel` added by Phase 5b (#2799). Phase 4 federated every
|
||
// `review.*_host` key with a default of `""`, so the REAL fallback destination and model
|
||
// (`http://localhost:11434` / `llama3` and friends) existed only inside the bash leg. Once the
|
||
// lane is invoked from data, an unset host with no declared default would POST to a garbage URL.
|
||
const HTTP_ONLY_INVOKE_FIELDS = ['hostConfigKey', 'defaultHost', 'path', 'modelDiscovery', 'fallbackModel'];
|
||
|
||
// Feature-only fields are as forbidden on a lane-only capability as on a runtime
|
||
// one; a `role: "reviewer"` capability owns no artefacts and wires no loop point.
|
||
const FEATURE_FIELDS_FORBIDDEN_ON_REVIEWER = ['skills', 'agents', 'steps', 'contributions', 'gates', 'hooks', 'activationKey', 'taskContentResolver'];
|
||
|
||
// GATE A: installSurface → allowed hooksSurface values (DEFECT.GENERATIVE-FIX: parity invariant)
|
||
// Derived from the actual pairings in the 16 real runtime descriptors.
|
||
const INSTALL_SURFACE_TO_ALLOWED_HOOKS_SURFACES = new Map([
|
||
['settings-json', new Set(['settings-json', 'none'])],
|
||
['codex-toml', new Set(['codex-hooks-json'])],
|
||
['copilot-instructions', new Set(['copilot-inline'])],
|
||
['cline-rules', new Set(['cline-rules'])],
|
||
['cursor-hooks-json', new Set(['cursor-hooks-json'])],
|
||
['profile-marker-only', new Set(['none', 'kimi-hooks-toml', 'windsurf-hooks-json'])],
|
||
// 'none' added #2103 — VS Code has no CLI install surface at all; its only
|
||
// valid hooksSurface pairing is the other 'none' (engine owns the hook bus).
|
||
['none', new Set(['none'])],
|
||
]);
|
||
|
||
// GATE B: extended hook event families → required hookEvents value
|
||
// Gemini agent-events require hookEvents='gemini'; Claude-family events require hookEvents='claude'.
|
||
const GEMINI_AGENT_EVENTS = new Set(['BeforeAgent', 'AfterAgent', 'BeforeModel']);
|
||
// SubagentStart added #2092 Phase B Upgrade 2 — Claude hook-event dialect
|
||
// counterpart of SubagentStop (qwen-only today).
|
||
const CLAUDE_FAMILY_EVENTS = new Set(['SubagentStop', 'Stop', 'PreCompact', 'FileChanged', 'SubagentStart']);
|
||
|
||
/**
|
||
* Validate a runtime.configHome object per ADR-1016 Decision 1.
|
||
* Returns an array of error strings.
|
||
*
|
||
* @param {string} capId Capability id (for error messages)
|
||
* @param {*} ch The configHome value
|
||
* @returns {string[]}
|
||
*/
|
||
function validateConfigHome(capId, ch) {
|
||
const errors = [];
|
||
const ctx = 'capability "' + capId + '" runtime.configHome';
|
||
|
||
if (typeof ch !== 'object' || ch === null || Array.isArray(ch)) {
|
||
errors.push(ctx + ' must be an object (got: ' + (ch === null ? 'null' : typeof ch) + ')');
|
||
return errors;
|
||
}
|
||
|
||
// kind — must be in closed vocab; inline literal guard (CodeQL barrier)
|
||
if (ch.kind === '__proto__' || ch.kind === 'constructor' || ch.kind === 'prototype') {
|
||
errors.push(ctx + '.kind "' + ch.kind + '" is a reserved name');
|
||
} else if (!VALID_CONFIG_HOME_KINDS.has(ch.kind)) {
|
||
errors.push(
|
||
ctx + '.kind must be one of: ' + [...VALID_CONFIG_HOME_KINDS].join(', ') +
|
||
' (got: ' + JSON.stringify(ch.kind) + ')',
|
||
);
|
||
}
|
||
|
||
// name — required string, except when kind === 'none': the runtime has no
|
||
// file-projected config directory at all, so a descriptive name is
|
||
// optional (a carve-out mirroring the dot-home-nested⇒parent conditional
|
||
// below, not a new validation mechanism). If present it must still be a
|
||
// non-empty string (e.g. vscode's configHome.name stays a descriptive
|
||
// "vscode" string even though it is never used to build a path).
|
||
if (ch.kind !== 'none') {
|
||
if (typeof ch.name !== 'string' || ch.name.length === 0) {
|
||
errors.push(ctx + '.name must be a non-empty string');
|
||
}
|
||
} else if (ch.name !== undefined && (typeof ch.name !== 'string' || ch.name.length === 0)) {
|
||
errors.push(ctx + '.name must be a non-empty string if present when kind is "none"');
|
||
}
|
||
|
||
// parent — required when kind == dot-home-nested
|
||
if (ch.kind === 'dot-home-nested') {
|
||
if (typeof ch.parent !== 'string' || ch.parent.length === 0) {
|
||
errors.push(ctx + '.parent must be a non-empty string when kind is "dot-home-nested"');
|
||
}
|
||
}
|
||
|
||
// env — required; must be an array of strings (every runtime has ≥0 env overrides)
|
||
if (!Array.isArray(ch.env)) {
|
||
errors.push(ctx + '.env is required and must be an array of strings (got: ' + JSON.stringify(ch.env) + ')');
|
||
} else {
|
||
for (let i = 0; i < ch.env.length; i++) {
|
||
if (typeof ch.env[i] !== 'string') {
|
||
errors.push(ctx + '.env[' + i + '] must be a string');
|
||
}
|
||
}
|
||
}
|
||
|
||
// probe — optional; if present must be an array of strings
|
||
if (ch.probe !== undefined) {
|
||
if (!Array.isArray(ch.probe)) {
|
||
errors.push(ctx + '.probe must be an array of strings if present');
|
||
} else {
|
||
for (let i = 0; i < ch.probe.length; i++) {
|
||
if (typeof ch.probe[i] !== 'string') {
|
||
errors.push(ctx + '.probe[' + i + '] must be a string');
|
||
}
|
||
}
|
||
}
|
||
}
|
||
|
||
// probeExists — optional; if present must be a non-empty string (sub-path existence check for probe)
|
||
if (ch.probeExists !== undefined) {
|
||
if (typeof ch.probeExists !== 'string' || ch.probeExists.length === 0) {
|
||
errors.push(ctx + '.probeExists must be a non-empty string if present (got: ' + JSON.stringify(ch.probeExists) + ')');
|
||
}
|
||
}
|
||
|
||
// skillsHome — optional; if present must be a full valid configHome object (recursive validation)
|
||
if (ch.skillsHome !== undefined) {
|
||
// Recursive call: validate skillsHome as a nested configHome.
|
||
// Use a synthetic capId to surface the sub-path in error messages.
|
||
const skillsHomeErrors = validateConfigHome(capId + '.skillsHome', ch.skillsHome);
|
||
// Rewrite the inner ctx prefix so errors read as "...runtime.configHome.skillsHome..."
|
||
for (const e of skillsHomeErrors) {
|
||
errors.push(e.replace(
|
||
'capability "' + capId + '.skillsHome" runtime.configHome',
|
||
ctx + '.skillsHome',
|
||
));
|
||
}
|
||
}
|
||
|
||
return errors;
|
||
}
|
||
|
||
/**
|
||
* Validate a single ArtifactKind entry per ADR-1016 Decision 3.
|
||
* Returns an array of error strings.
|
||
*
|
||
* @param {string} capId Capability id (for error messages)
|
||
* @param {*} entry The ArtifactKind object
|
||
* @param {string} prefix Path prefix for error messages (e.g. "artifactLayout.global[0]")
|
||
* @returns {string[]}
|
||
*/
|
||
function validateArtifactKindEntry(capId, entry, prefix) {
|
||
const errors = [];
|
||
const ctx = 'capability "' + capId + '" runtime.' + prefix;
|
||
|
||
if (typeof entry !== 'object' || entry === null || Array.isArray(entry)) {
|
||
errors.push(ctx + ' must be an object');
|
||
return errors;
|
||
}
|
||
|
||
// kind — must be in closed vocab; inline literal guard (CodeQL barrier)
|
||
if (entry.kind === '__proto__' || entry.kind === 'constructor' || entry.kind === 'prototype') {
|
||
errors.push(ctx + '.kind "' + entry.kind + '" is a reserved name');
|
||
} else if (!VALID_ARTIFACT_KIND_NAMES.has(entry.kind)) {
|
||
errors.push(
|
||
ctx + '.kind must be one of: ' + [...VALID_ARTIFACT_KIND_NAMES].join(', ') +
|
||
' (got: ' + JSON.stringify(entry.kind) + ')',
|
||
);
|
||
}
|
||
|
||
// destSubpath — required non-empty string
|
||
if (typeof entry.destSubpath !== 'string' || entry.destSubpath.length === 0) {
|
||
errors.push(ctx + '.destSubpath must be a non-empty string');
|
||
}
|
||
|
||
// nesting — required; must be in closed vocab (ADR-857 §5d: now drives install)
|
||
if (entry.nesting === undefined || entry.nesting === null) {
|
||
errors.push(ctx + '.nesting is required and must be one of: ' + [...VALID_ARTIFACT_NESTINGS].join(', '));
|
||
} else if (!VALID_ARTIFACT_NESTINGS.has(entry.nesting)) {
|
||
errors.push(
|
||
ctx + '.nesting must be one of: ' + [...VALID_ARTIFACT_NESTINGS].join(', ') +
|
||
' (got: ' + JSON.stringify(entry.nesting) + ')',
|
||
);
|
||
}
|
||
|
||
// prefix — required; must be a string (may be empty string '')
|
||
if (entry.prefix === undefined || entry.prefix === null) {
|
||
errors.push(ctx + '.prefix is required (must be a string, may be empty)');
|
||
} else if (typeof entry.prefix !== 'string') {
|
||
errors.push(ctx + '.prefix must be a string (got: ' + typeof entry.prefix + ')');
|
||
}
|
||
|
||
// recursive — optional; if present must be a boolean
|
||
if (entry.recursive !== undefined) {
|
||
if (typeof entry.recursive !== 'boolean') {
|
||
errors.push(ctx + '.recursive must be a boolean if present (got: ' + typeof entry.recursive + ')');
|
||
}
|
||
}
|
||
|
||
// converter — required; must be a string or null (closed ConverterName enum — now enforced in phase 5e)
|
||
if (!Object.prototype.hasOwnProperty.call(entry, 'converter')) {
|
||
errors.push(ctx + '.converter is required (must be a string or null)');
|
||
} else if (entry.converter !== null && typeof entry.converter !== 'string') {
|
||
errors.push(ctx + '.converter must be a string or null (got: ' + typeof entry.converter + ')');
|
||
} else if (entry.converter !== null && typeof entry.converter === 'string' &&
|
||
!VALID_CONVERTER_NAMES.has(entry.converter)) {
|
||
// Closed ConverterName enum (ADR-857 phase 5e): reject unknown converter names
|
||
errors.push(ctx + '.converter "' + entry.converter + '" is not a known ConverterName');
|
||
}
|
||
|
||
return errors;
|
||
}
|
||
|
||
/**
|
||
* Validate runtime.artifactLayout per ADR-1016 Decision 3.
|
||
* Accepts the structured { global, local } shape.
|
||
* Returns an array of error strings.
|
||
*
|
||
* @param {string} capId Capability id (for error messages)
|
||
* @param {*} layout The artifactLayout value
|
||
* @returns {string[]}
|
||
*/
|
||
function validateArtifactLayout(capId, layout) {
|
||
const errors = [];
|
||
const ctx = 'capability "' + capId + '" runtime.artifactLayout';
|
||
|
||
if (typeof layout !== 'object' || layout === null || Array.isArray(layout)) {
|
||
errors.push(ctx + ' must be an object with "global" and "local" arrays');
|
||
return errors;
|
||
}
|
||
|
||
for (const scope of ['global', 'local']) {
|
||
const arr = layout[scope];
|
||
if (!Array.isArray(arr)) {
|
||
errors.push(ctx + '.' + scope + ' must be an array');
|
||
} else {
|
||
for (let i = 0; i < arr.length; i++) {
|
||
const entry = arr[i];
|
||
errors.push(...validateArtifactKindEntry(capId, entry, 'artifactLayout.' + scope + '[' + i + ']'));
|
||
if (
|
||
scope === 'local' &&
|
||
typeof entry === 'object' && entry !== null && !Array.isArray(entry) &&
|
||
Object.prototype.hasOwnProperty.call(entry, 'home')
|
||
) {
|
||
errors.push(
|
||
ctx + '.local[' + i + '].home is not allowed; ' +
|
||
'local artifact layout entries must remain project-scoped',
|
||
);
|
||
}
|
||
}
|
||
}
|
||
}
|
||
|
||
return errors;
|
||
}
|
||
|
||
function validateRuntimeBody(cap) {
|
||
const errors = [];
|
||
|
||
// C3: feature-only fields must NOT appear on a runtime cap
|
||
for (const field of FEATURE_FIELDS_FORBIDDEN_ON_RUNTIME) {
|
||
if (cap[field] !== undefined) {
|
||
errors.push('role:runtime capability must not have "' + field + '" (feature-only field)');
|
||
}
|
||
}
|
||
|
||
// C3: require a runtime object
|
||
if (typeof cap.runtime !== 'object' || cap.runtime === null || Array.isArray(cap.runtime)) {
|
||
errors.push('role:runtime capability must have a "runtime" object');
|
||
return errors; // can't validate further without the object
|
||
}
|
||
|
||
const r = cap.runtime;
|
||
|
||
// configHome — must be a structured object (ADR-1016 Decision 1)
|
||
errors.push(...validateConfigHome(cap.id || '(unknown)', r.configHome));
|
||
|
||
// configFormat — closed 5-enum (unchanged)
|
||
if (!VALID_CONFIG_FORMATS.has(r.configFormat)) {
|
||
errors.push('runtime.configFormat must be one of: ' + [...VALID_CONFIG_FORMATS].join(', ') + ' (got: ' + r.configFormat + ')');
|
||
}
|
||
|
||
// artifactLayout — structured { global, local } per ADR-1016 Decision 3
|
||
errors.push(...validateArtifactLayout(cap.id || '(unknown)', r.artifactLayout));
|
||
|
||
// commandStyle — closed 2-enum (ADR-1016 Decision 4); inline literal guard (CodeQL barrier)
|
||
if (r.commandStyle === '__proto__' || r.commandStyle === 'constructor' || r.commandStyle === 'prototype') {
|
||
errors.push('runtime.commandStyle "' + r.commandStyle + '" is a reserved name');
|
||
} else if (!VALID_COMMAND_STYLES.has(r.commandStyle)) {
|
||
errors.push(
|
||
'runtime.commandStyle must be one of: ' + [...VALID_COMMAND_STYLES].join(', ') +
|
||
' (got: ' + JSON.stringify(r.commandStyle) + ')',
|
||
);
|
||
}
|
||
|
||
// hooksSurface — closed 7-enum (ADR-1016 Decision 5); inline literal guard (CodeQL barrier)
|
||
if (r.hooksSurface === '__proto__' || r.hooksSurface === 'constructor' || r.hooksSurface === 'prototype') {
|
||
errors.push('runtime.hooksSurface "' + r.hooksSurface + '" is a reserved name');
|
||
} else if (!VALID_HOOKS_SURFACES.has(r.hooksSurface)) {
|
||
errors.push(
|
||
'runtime.hooksSurface must be one of: ' + [...VALID_HOOKS_SURFACES].join(', ') +
|
||
' (got: ' + JSON.stringify(r.hooksSurface) + ')',
|
||
);
|
||
}
|
||
|
||
// hookEvents — optional; if present must be in closed enum (ADR-1016 Decision 5).
|
||
// Managed-hook dialect only (claude/gemini). The OpenCode extension-system event
|
||
// subset is NOT a hookEvents value — it is `extensionEvents` (ADR-1239 / #1943).
|
||
if (r.hookEvents !== undefined) {
|
||
if (r.hookEvents === '__proto__' || r.hookEvents === 'constructor' || r.hookEvents === 'prototype') {
|
||
errors.push('runtime.hookEvents "' + r.hookEvents + '" is a reserved name');
|
||
} else if (!VALID_HOOK_EVENTS.has(r.hookEvents)) {
|
||
errors.push(
|
||
'runtime.hookEvents must be one of: ' + [...VALID_HOOK_EVENTS].join(', ') +
|
||
' (got: ' + JSON.stringify(r.hookEvents) + ')',
|
||
);
|
||
}
|
||
}
|
||
|
||
// extensionEvents — optional; the extension-system event dialect (ADR-1239 amendment / #1943).
|
||
// Distinct from hookEvents. Only imperative-embedding hosts (with a plugin/extension
|
||
// API) set it; declarative hosts do not.
|
||
if (r.extensionEvents !== undefined) {
|
||
if (r.extensionEvents === '__proto__' || r.extensionEvents === 'constructor' || r.extensionEvents === 'prototype') {
|
||
errors.push('runtime.extensionEvents "' + r.extensionEvents + '" is a reserved name');
|
||
} else if (!VALID_EXTENSION_EVENTS.has(r.extensionEvents)) {
|
||
errors.push(
|
||
'runtime.extensionEvents must be one of: ' + [...VALID_EXTENSION_EVENTS].join(', ') +
|
||
' (got: ' + JSON.stringify(r.extensionEvents) + ')',
|
||
);
|
||
}
|
||
}
|
||
|
||
// sandboxTier — closed 2-enum (ADR-1016 Decision 6); inline literal guard (CodeQL barrier)
|
||
if (r.sandboxTier === '__proto__' || r.sandboxTier === 'constructor' || r.sandboxTier === 'prototype') {
|
||
errors.push('runtime.sandboxTier "' + r.sandboxTier + '" is a reserved name');
|
||
} else if (!VALID_SANDBOX_TIERS.has(r.sandboxTier)) {
|
||
errors.push(
|
||
'runtime.sandboxTier must be one of: ' + [...VALID_SANDBOX_TIERS].join(', ') +
|
||
' (got: ' + JSON.stringify(r.sandboxTier) + ')',
|
||
);
|
||
}
|
||
|
||
// supportTier — 1 or 2 (unchanged)
|
||
if (r.supportTier !== 1 && r.supportTier !== 2) {
|
||
errors.push('runtime.supportTier must be 1 or 2 (got: ' + r.supportTier + ')');
|
||
}
|
||
|
||
// installSurface — required string in closed enum
|
||
if (!VALID_INSTALL_SURFACES.has(r.installSurface)) {
|
||
errors.push(
|
||
'runtime.installSurface must be one of: ' + [...VALID_INSTALL_SURFACES].join(', ') +
|
||
' (got: ' + JSON.stringify(r.installSurface) + ')',
|
||
);
|
||
}
|
||
|
||
// writesSharedSettings — required boolean
|
||
if (typeof r.writesSharedSettings !== 'boolean') {
|
||
errors.push(
|
||
'runtime.writesSharedSettings must be a boolean (got: ' + JSON.stringify(r.writesSharedSettings) + ')',
|
||
);
|
||
}
|
||
|
||
// permissionWriter — required key; value must be null or a string in VALID_PERMISSION_WRITERS
|
||
if (!Object.prototype.hasOwnProperty.call(r, 'permissionWriter')) {
|
||
errors.push('runtime.permissionWriter is required (must be null or one of: ' + [...VALID_PERMISSION_WRITERS].join(', ') + ')');
|
||
} else if (r.permissionWriter !== null && !VALID_PERMISSION_WRITERS.has(r.permissionWriter)) {
|
||
errors.push(
|
||
'runtime.permissionWriter must be null or one of: ' + [...VALID_PERMISSION_WRITERS].join(', ') +
|
||
' (got: ' + JSON.stringify(r.permissionWriter) + ')',
|
||
);
|
||
}
|
||
|
||
// localConfigDir — REQUIRED non-empty dot-dir string (ADR-1239 Phase B #1679)
|
||
// Must start with '.' (e.g. ".claude", ".cursor"). Validated here so the registry
|
||
// generator catches any descriptor missing the field before regenerating.
|
||
//
|
||
// #2103: conditional on configHome.kind !== 'none' — a Marketplace/VSIX
|
||
// host with no file-projected config directory (e.g. VS Code) has no
|
||
// local dir to name; localConfigDir may be null/absent for such runtimes.
|
||
const configHomeKind = (r.configHome && typeof r.configHome === 'object') ? r.configHome.kind : undefined;
|
||
if (configHomeKind !== 'none') {
|
||
if (typeof r.localConfigDir !== 'string' || r.localConfigDir.length === 0) {
|
||
errors.push(
|
||
'runtime.localConfigDir is required and must be a non-empty string (e.g. ".claude"); ' +
|
||
'got: ' + JSON.stringify(r.localConfigDir),
|
||
);
|
||
} else if (!r.localConfigDir.startsWith('.')) {
|
||
errors.push(
|
||
'runtime.localConfigDir must start with "." (a dot-dir); got: ' + JSON.stringify(r.localConfigDir),
|
||
);
|
||
}
|
||
} else if (r.localConfigDir !== null && r.localConfigDir !== undefined) {
|
||
errors.push(
|
||
'runtime.localConfigDir must be null or absent when configHome.kind is "none"; ' +
|
||
'got: ' + JSON.stringify(r.localConfigDir),
|
||
);
|
||
}
|
||
|
||
// extendedHookEvents — required array; every element must be in closed enum
|
||
if (!Array.isArray(r.extendedHookEvents)) {
|
||
errors.push(
|
||
'runtime.extendedHookEvents must be an array (got: ' + JSON.stringify(r.extendedHookEvents) + ')',
|
||
);
|
||
} else {
|
||
for (let i = 0; i < r.extendedHookEvents.length; i++) {
|
||
const ev = r.extendedHookEvents[i];
|
||
if (typeof ev !== 'string' || !VALID_EXTENDED_HOOK_EVENTS.has(ev)) {
|
||
errors.push(
|
||
'runtime.extendedHookEvents[' + i + '] must be one of: ' + [...VALID_EXTENDED_HOOK_EVENTS].join(', ') +
|
||
' (got: ' + JSON.stringify(ev) + ')',
|
||
);
|
||
}
|
||
}
|
||
}
|
||
|
||
// hostIntegration — ADR-1239 Phase A: required object with closed-enum axes
|
||
if (typeof r.hostIntegration !== 'object' || r.hostIntegration === null || Array.isArray(r.hostIntegration)) {
|
||
errors.push('runtime.hostIntegration is required and must be an object');
|
||
} else {
|
||
const hi = r.hostIntegration;
|
||
|
||
// S2b: reserved-OWN-KEY guard on hostIntegration (CodeQL barrier — inline literal comparisons)
|
||
if (Object.prototype.hasOwnProperty.call(hi, '__proto__')) {
|
||
errors.push('runtime.hostIntegration must not contain reserved key "__proto__"');
|
||
}
|
||
if (Object.prototype.hasOwnProperty.call(hi, 'constructor')) {
|
||
errors.push('runtime.hostIntegration must not contain reserved key "constructor"');
|
||
}
|
||
if (Object.prototype.hasOwnProperty.call(hi, 'prototype')) {
|
||
errors.push('runtime.hostIntegration must not contain reserved key "prototype"');
|
||
}
|
||
|
||
// embeddingMode
|
||
if (hi.embeddingMode === '__proto__' || hi.embeddingMode === 'constructor' || hi.embeddingMode === 'prototype') {
|
||
errors.push('runtime.hostIntegration.embeddingMode "' + hi.embeddingMode + '" is a reserved name');
|
||
} else if (hi.embeddingMode !== 'undocumented' && !VALID_EMBEDDING_MODES.has(hi.embeddingMode)) {
|
||
errors.push(
|
||
'runtime.hostIntegration.embeddingMode must be one of: ' + [...VALID_EMBEDDING_MODES].join(', ') +
|
||
' (or "undocumented") (got: ' + JSON.stringify(hi.embeddingMode) + ')',
|
||
);
|
||
}
|
||
|
||
// commandSurface
|
||
if (hi.commandSurface === '__proto__' || hi.commandSurface === 'constructor' || hi.commandSurface === 'prototype') {
|
||
errors.push('runtime.hostIntegration.commandSurface "' + hi.commandSurface + '" is a reserved name');
|
||
} else if (hi.commandSurface !== 'undocumented' && !VALID_COMMAND_SURFACES.has(hi.commandSurface)) {
|
||
errors.push(
|
||
'runtime.hostIntegration.commandSurface must be one of: ' + [...VALID_COMMAND_SURFACES].join(', ') +
|
||
' (or "undocumented") (got: ' + JSON.stringify(hi.commandSurface) + ')',
|
||
);
|
||
}
|
||
|
||
// modelMode
|
||
if (hi.modelMode === '__proto__' || hi.modelMode === 'constructor' || hi.modelMode === 'prototype') {
|
||
errors.push('runtime.hostIntegration.modelMode "' + hi.modelMode + '" is a reserved name');
|
||
} else if (hi.modelMode !== 'undocumented' && !VALID_MODEL_MODES.has(hi.modelMode)) {
|
||
errors.push(
|
||
'runtime.hostIntegration.modelMode must be one of: ' + [...VALID_MODEL_MODES].join(', ') +
|
||
' (or "undocumented") (got: ' + JSON.stringify(hi.modelMode) + ')',
|
||
);
|
||
}
|
||
|
||
// hookBus
|
||
if (hi.hookBus === '__proto__' || hi.hookBus === 'constructor' || hi.hookBus === 'prototype') {
|
||
errors.push('runtime.hostIntegration.hookBus "' + hi.hookBus + '" is a reserved name');
|
||
} else if (hi.hookBus !== 'undocumented' && !VALID_HOOK_BUSES.has(hi.hookBus)) {
|
||
errors.push(
|
||
'runtime.hostIntegration.hookBus must be one of: ' + [...VALID_HOOK_BUSES].join(', ') +
|
||
' (or "undocumented") (got: ' + JSON.stringify(hi.hookBus) + ')',
|
||
);
|
||
}
|
||
|
||
// stateIO
|
||
if (hi.stateIO === '__proto__' || hi.stateIO === 'constructor' || hi.stateIO === 'prototype') {
|
||
errors.push('runtime.hostIntegration.stateIO "' + hi.stateIO + '" is a reserved name');
|
||
} else if (hi.stateIO !== 'undocumented' && !VALID_STATE_IO.has(hi.stateIO)) {
|
||
errors.push(
|
||
'runtime.hostIntegration.stateIO must be one of: ' + [...VALID_STATE_IO].join(', ') +
|
||
' (or "undocumented") (got: ' + JSON.stringify(hi.stateIO) + ')',
|
||
);
|
||
}
|
||
|
||
// transport
|
||
if (hi.transport === '__proto__' || hi.transport === 'constructor' || hi.transport === 'prototype') {
|
||
errors.push('runtime.hostIntegration.transport "' + hi.transport + '" is a reserved name');
|
||
} else if (hi.transport !== 'undocumented' && !VALID_TRANSPORTS.has(hi.transport)) {
|
||
errors.push(
|
||
'runtime.hostIntegration.transport must be one of: ' + [...VALID_TRANSPORTS].join(', ') +
|
||
' (or "undocumented") (got: ' + JSON.stringify(hi.transport) + ')',
|
||
);
|
||
}
|
||
|
||
// runtime (axis)
|
||
if (hi.runtime === '__proto__' || hi.runtime === 'constructor' || hi.runtime === 'prototype') {
|
||
errors.push('runtime.hostIntegration.runtime "' + hi.runtime + '" is a reserved name');
|
||
} else if (hi.runtime !== 'undocumented' && !VALID_HOST_RUNTIMES.has(hi.runtime)) {
|
||
errors.push(
|
||
'runtime.hostIntegration.runtime must be one of: ' + [...VALID_HOST_RUNTIMES].join(', ') +
|
||
' (or "undocumented") (got: ' + JSON.stringify(hi.runtime) + ')',
|
||
);
|
||
}
|
||
|
||
// effortSurface (axis) — ADR-1239 amendment (#2481).
|
||
// OPTIONAL, unlike the Phase-A axes. It was added after descriptors already
|
||
// existed, so requiring it would invalidate every descriptor written before it —
|
||
// including third-party ones, breaking the "purely additive" property ADR-1239
|
||
// promises for external descriptors. An omitted axis is legitimate: negotiation
|
||
// degrades it to the safe floor ('none') and warns, exactly as for any
|
||
// undeclared axis. Only a PRESENT value is checked against the vocabulary.
|
||
if (hi.effortSurface === undefined) {
|
||
// absent — nothing to validate; negotiateHostCapabilities fails it closed.
|
||
} else if (hi.effortSurface === '__proto__' || hi.effortSurface === 'constructor' || hi.effortSurface === 'prototype') {
|
||
errors.push('runtime.hostIntegration.effortSurface "' + hi.effortSurface + '" is a reserved name');
|
||
} else if (hi.effortSurface !== 'undocumented' && !VALID_EFFORT_SURFACES.has(hi.effortSurface)) {
|
||
errors.push(
|
||
'runtime.hostIntegration.effortSurface must be one of: ' + [...VALID_EFFORT_SURFACES].join(', ') +
|
||
' (or "undocumented") (got: ' + JSON.stringify(hi.effortSurface) + ')',
|
||
);
|
||
}
|
||
|
||
// dispatch — required object
|
||
if (typeof hi.dispatch !== 'object' || hi.dispatch === null || Array.isArray(hi.dispatch)) {
|
||
errors.push('runtime.hostIntegration.dispatch must be an object');
|
||
} else {
|
||
const d = hi.dispatch;
|
||
|
||
// S2b: reserved-OWN-KEY guard on dispatch (CodeQL barrier — inline literal comparisons)
|
||
if (Object.prototype.hasOwnProperty.call(d, '__proto__')) {
|
||
errors.push('runtime.hostIntegration.dispatch must not contain reserved key "__proto__"');
|
||
}
|
||
if (Object.prototype.hasOwnProperty.call(d, 'constructor')) {
|
||
errors.push('runtime.hostIntegration.dispatch must not contain reserved key "constructor"');
|
||
}
|
||
if (Object.prototype.hasOwnProperty.call(d, 'prototype')) {
|
||
errors.push('runtime.hostIntegration.dispatch must not contain reserved key "prototype"');
|
||
}
|
||
|
||
// namedDispatch — boolean or 'undocumented'
|
||
if (typeof d.namedDispatch !== 'boolean' && d.namedDispatch !== 'undocumented') {
|
||
errors.push(
|
||
'runtime.hostIntegration.dispatch.namedDispatch must be a boolean or "undocumented" (got: ' + JSON.stringify(d.namedDispatch) + ')',
|
||
);
|
||
}
|
||
|
||
// nested — boolean or 'undocumented'
|
||
if (typeof d.nested !== 'boolean' && d.nested !== 'undocumented') {
|
||
errors.push(
|
||
'runtime.hostIntegration.dispatch.nested must be a boolean or "undocumented" (got: ' + JSON.stringify(d.nested) + ')',
|
||
);
|
||
}
|
||
|
||
// background — boolean or 'undocumented'
|
||
if (typeof d.background !== 'boolean' && d.background !== 'undocumented') {
|
||
errors.push(
|
||
'runtime.hostIntegration.dispatch.background must be a boolean or "undocumented" (got: ' + JSON.stringify(d.background) + ')',
|
||
);
|
||
}
|
||
|
||
// subagentToolkit — closed enum or 'undocumented'
|
||
if (d.subagentToolkit === '__proto__' || d.subagentToolkit === 'constructor' || d.subagentToolkit === 'prototype') {
|
||
errors.push('runtime.hostIntegration.dispatch.subagentToolkit "' + d.subagentToolkit + '" is a reserved name');
|
||
} else if (d.subagentToolkit !== 'undocumented' && !VALID_SUBAGENT_TOOLKITS.has(d.subagentToolkit)) {
|
||
errors.push(
|
||
'runtime.hostIntegration.dispatch.subagentToolkit must be one of: ' + [...VALID_SUBAGENT_TOOLKITS].join(', ') +
|
||
' (or "undocumented") (got: ' + JSON.stringify(d.subagentToolkit) + ')',
|
||
);
|
||
}
|
||
|
||
// maxDepth — integer >= -1 or 'undocumented'
|
||
if (d.maxDepth !== 'undocumented' && (!Number.isInteger(d.maxDepth) || d.maxDepth < -1)) {
|
||
errors.push(
|
||
'runtime.hostIntegration.dispatch.maxDepth must be an integer >= -1 or "undocumented" (got: ' + JSON.stringify(d.maxDepth) + ')',
|
||
);
|
||
}
|
||
|
||
// backgroundDispatch — REQUIRED (all 16 runtime descriptors carry it, matching the sibling fields
|
||
// namedDispatch/nested/background/subagentToolkit/maxDepth which are all required).
|
||
if (!Object.prototype.hasOwnProperty.call(d, 'backgroundDispatch')) {
|
||
errors.push(
|
||
'runtime.hostIntegration.dispatch.backgroundDispatch is required (must be a boolean or "undocumented")',
|
||
);
|
||
} else if (typeof d.backgroundDispatch !== 'boolean' && d.backgroundDispatch !== 'undocumented') {
|
||
errors.push(
|
||
'runtime.hostIntegration.dispatch.backgroundDispatch must be a boolean or "undocumented" (got: ' + JSON.stringify(d.backgroundDispatch) + ')',
|
||
);
|
||
}
|
||
|
||
// isolation — ADR-1239 Codex-binding amendment (#2584).
|
||
// OPTIONAL, like effortSurface: added after descriptors already existed,
|
||
// so requiring it would invalidate every descriptor authored before it —
|
||
// including third-party ones, breaking the "purely additive" property
|
||
// ADR-1239 promises for external descriptors. An omitted isolation is
|
||
// legitimate: negotiation degrades it to 'none' (the safe floor) and
|
||
// warns, exactly as for any other undeclared dispatch sub-field. Only a
|
||
// PRESENT value is checked against the closed vocabulary.
|
||
if (d.isolation === undefined) {
|
||
// absent — nothing to validate; negotiateHostCapabilities fails it closed.
|
||
} else if (d.isolation === '__proto__' || d.isolation === 'constructor' || d.isolation === 'prototype') {
|
||
errors.push('runtime.hostIntegration.dispatch.isolation "' + d.isolation + '" is a reserved name');
|
||
} else if (d.isolation !== 'undocumented' && !VALID_DISPATCH_ISOLATION.has(d.isolation)) {
|
||
errors.push(
|
||
'runtime.hostIntegration.dispatch.isolation must be one of: ' + [...VALID_DISPATCH_ISOLATION].join(', ') +
|
||
' (or "undocumented") (got: ' + JSON.stringify(d.isolation) + ')',
|
||
);
|
||
}
|
||
|
||
// maxConcurrency — ADR-1239 Phase 1 (#3673). A numeric dispatch
|
||
// sub-field (not a closed-vocabulary enum member — same numeric
|
||
// dispatch sub-field treatment as maxDepth above; unlike maxDepth,
|
||
// 0 and negative values are invalid — 1 is the fail-closed floor, not
|
||
// a legitimate "no concurrency" declaration).
|
||
// OPTIONAL, like isolation: added after existing descriptors, so an
|
||
// omitted maxConcurrency is legitimate — negotiateHostCapabilities
|
||
// degrades it to 1 (the safe floor) and warns, exactly as for any
|
||
// other undeclared dispatch sub-field. Only a PRESENT value is
|
||
// checked against the positive-safe-integer contract.
|
||
if (d.maxConcurrency === undefined) {
|
||
// absent — nothing to validate; negotiateHostCapabilities fails it closed.
|
||
} else if (
|
||
d.maxConcurrency !== 'undocumented' &&
|
||
(!Number.isSafeInteger(d.maxConcurrency) || d.maxConcurrency < 1)
|
||
) {
|
||
errors.push(
|
||
'runtime.hostIntegration.dispatch.maxConcurrency must be a positive safe integer or "undocumented" ' +
|
||
'(got: ' + JSON.stringify(d.maxConcurrency) + ')',
|
||
);
|
||
}
|
||
}
|
||
}
|
||
|
||
// orchestratorExec — ADR-1239 Codex-binding amendment (#2584), Phase 2.
|
||
// OPTIONAL top-level field (sibling of hostBehaviors), like hookEvents:
|
||
// only hosts whose hostIntegration.dispatch.isolation is
|
||
// 'orchestrator-worktree' need it, so it is not required on every runtime
|
||
// descriptor. When present it must be a well-formed exec descriptor for
|
||
// src/host-integration.cts's resolveOrchestratorExec.
|
||
if (r.orchestratorExec !== undefined) {
|
||
if (typeof r.orchestratorExec !== 'object' || r.orchestratorExec === null || Array.isArray(r.orchestratorExec)) {
|
||
errors.push(
|
||
'runtime.orchestratorExec must be an object (got: ' +
|
||
(r.orchestratorExec === null ? 'null' : (Array.isArray(r.orchestratorExec) ? 'array' : typeof r.orchestratorExec)) + ')',
|
||
);
|
||
} else {
|
||
const oe = r.orchestratorExec;
|
||
|
||
// S2b: reserved-OWN-KEY guard (CodeQL barrier — inline literal comparisons)
|
||
if (Object.prototype.hasOwnProperty.call(oe, '__proto__')) {
|
||
errors.push('runtime.orchestratorExec must not contain reserved key "__proto__"');
|
||
}
|
||
if (Object.prototype.hasOwnProperty.call(oe, 'constructor')) {
|
||
errors.push('runtime.orchestratorExec must not contain reserved key "constructor"');
|
||
}
|
||
if (Object.prototype.hasOwnProperty.call(oe, 'prototype')) {
|
||
errors.push('runtime.orchestratorExec must not contain reserved key "prototype"');
|
||
}
|
||
|
||
// command — required non-empty string; reserved-name guard (CodeQL barrier)
|
||
if (oe.command === '__proto__' || oe.command === 'constructor' || oe.command === 'prototype') {
|
||
errors.push('runtime.orchestratorExec.command "' + oe.command + '" is a reserved name');
|
||
} else if (typeof oe.command !== 'string' || oe.command.length === 0) {
|
||
errors.push(
|
||
'runtime.orchestratorExec.command must be a non-empty string (got: ' + JSON.stringify(oe.command) + ')',
|
||
);
|
||
}
|
||
|
||
// args — optional array of strings
|
||
if (oe.args !== undefined) {
|
||
if (!Array.isArray(oe.args) || !oe.args.every((a) => typeof a === 'string')) {
|
||
errors.push(
|
||
'runtime.orchestratorExec.args must be an array of strings (got: ' + JSON.stringify(oe.args) + ')',
|
||
);
|
||
}
|
||
}
|
||
|
||
// cwdFlag — optional; string or null
|
||
if (oe.cwdFlag !== undefined && oe.cwdFlag !== null && typeof oe.cwdFlag !== 'string') {
|
||
errors.push(
|
||
'runtime.orchestratorExec.cwdFlag must be a string or null (got: ' + JSON.stringify(oe.cwdFlag) + ')',
|
||
);
|
||
}
|
||
|
||
// promptFlag — optional; string or null (#2627, Phase 3). `null`/absent
|
||
// means the host takes the executor prompt positionally (codex, opencode);
|
||
// a string names the flag that carries it (kimi/kimi-code: --prompt).
|
||
if (oe.promptFlag !== undefined && oe.promptFlag !== null && typeof oe.promptFlag !== 'string') {
|
||
errors.push(
|
||
'runtime.orchestratorExec.promptFlag must be a string or null (got: ' + JSON.stringify(oe.promptFlag) + ')',
|
||
);
|
||
}
|
||
|
||
// modelFlag — optional; string or null (#3714). `null`/absent means the
|
||
// host offers no per-invocation model override on this exec path; a
|
||
// string names the flag that pins the executor's model (codex: --model).
|
||
// Deliberately asymmetric: only codex declares this today.
|
||
if (oe.modelFlag !== undefined && oe.modelFlag !== null && typeof oe.modelFlag !== 'string') {
|
||
errors.push(
|
||
'runtime.orchestratorExec.modelFlag must be a string or null (got: ' + JSON.stringify(oe.modelFlag) + ')',
|
||
);
|
||
}
|
||
}
|
||
}
|
||
|
||
// harnessIsolationFlag — ADR-1239 Codex-binding amendment (#2584), Phase 3
|
||
// (#2627). OPTIONAL top-level field: the counterpart of orchestratorExec for
|
||
// `dispatch.isolation: 'harness-worktree'` hosts, naming the host's OWN
|
||
// isolation flag that GSD passes on dispatch (claude: isolation="worktree";
|
||
// cursor: --worktree). Descriptor data so the scheduler passes a declared
|
||
// token instead of branching on a runtime id (ADR-1239: "the per-host
|
||
// dispatch invocation ... is descriptor data, not a scheduler branch").
|
||
if (r.harnessIsolationFlag !== undefined && (typeof r.harnessIsolationFlag !== 'string' || r.harnessIsolationFlag.length === 0)) {
|
||
errors.push(
|
||
'runtime.harnessIsolationFlag must be a non-empty string (got: ' + JSON.stringify(r.harnessIsolationFlag) + ')',
|
||
);
|
||
}
|
||
|
||
// GATE A: installSurface ↔ hooksSurface consistency (DEFECT.GENERATIVE-FIX)
|
||
// Only check if both fields are valid strings (individual field validators above report type errors).
|
||
if (typeof r.installSurface === 'string' && typeof r.hooksSurface === 'string') {
|
||
const allowedHooksSurfaces = INSTALL_SURFACE_TO_ALLOWED_HOOKS_SURFACES.get(r.installSurface);
|
||
if (allowedHooksSurfaces !== undefined && !allowedHooksSurfaces.has(r.hooksSurface)) {
|
||
errors.push(
|
||
'runtime.hooksSurface "' + r.hooksSurface + '" is not valid for installSurface "' + r.installSurface + '"' +
|
||
' — allowed: ' + [...allowedHooksSurfaces].join(', ') +
|
||
' (src: INSTALL_SURFACE_TO_ALLOWED_HOOKS_SURFACES in scripts/gen-capability-registry.cjs)',
|
||
);
|
||
}
|
||
}
|
||
|
||
// GATE B: extendedHookEvents ↔ hookEvents consistency (DEFECT.GENERATIVE-FIX)
|
||
// If extendedHookEvents contains Gemini agent-events, hookEvents must be 'gemini'.
|
||
// If it contains Claude-family events, hookEvents must be 'claude'.
|
||
// Empty extendedHookEvents imposes no constraint.
|
||
if (Array.isArray(r.extendedHookEvents) && r.extendedHookEvents.length > 0) {
|
||
const hasGeminiEvents = r.extendedHookEvents.some((ev) => GEMINI_AGENT_EVENTS.has(ev));
|
||
const hasClaudeEvents = r.extendedHookEvents.some((ev) => CLAUDE_FAMILY_EVENTS.has(ev));
|
||
if (hasGeminiEvents && r.hookEvents !== 'gemini') {
|
||
errors.push(
|
||
'runtime.extendedHookEvents contains Gemini agent-events (' +
|
||
r.extendedHookEvents.filter((ev) => GEMINI_AGENT_EVENTS.has(ev)).join(', ') +
|
||
') but runtime.hookEvents is "' + r.hookEvents + '" — must be "gemini"',
|
||
);
|
||
}
|
||
if (hasClaudeEvents && r.hookEvents !== 'claude') {
|
||
errors.push(
|
||
'runtime.extendedHookEvents contains Claude-family events (' +
|
||
r.extendedHookEvents.filter((ev) => CLAUDE_FAMILY_EVENTS.has(ev)).join(', ') +
|
||
') but runtime.hookEvents is "' + r.hookEvents + '" — must be "claude"',
|
||
);
|
||
}
|
||
}
|
||
|
||
// triggerPrecedence — #2871 Phase 2 amendment to ADR-1016's runtime body.
|
||
// REQUIRED-WITH-DEFAULT: no other axis in this validator uses this shape —
|
||
// every axis above either hard-requires the field (throws when absent) or
|
||
// treats absence as fully unconstrained (effortSurface/isolation: "nothing to
|
||
// validate" when undefined). This axis does neither: an ABSENT value is
|
||
// substituted with DEFAULT_TRIGGER_PRECEDENCE and then validated exactly as
|
||
// if it HAD been supplied, so a third-party capability.json authored before
|
||
// this phase keeps validating (ADR-894 additive-only / Hyrum's Law, ADR-1244)
|
||
// while a PRESENT-but-malformed value still fails loudly instead of silently
|
||
// passing through unchecked.
|
||
const triggerPrecedenceValue = Object.prototype.hasOwnProperty.call(r, 'triggerPrecedence')
|
||
? r.triggerPrecedence
|
||
: DEFAULT_TRIGGER_PRECEDENCE;
|
||
if (!Array.isArray(triggerPrecedenceValue)) {
|
||
errors.push(
|
||
'runtime.triggerPrecedence must be an array of trigger-bearing kind names (' +
|
||
[...VALID_TRIGGER_PRECEDENCE_KINDS].join(', ') + ') (got: ' + JSON.stringify(triggerPrecedenceValue) + ')',
|
||
);
|
||
} else if (triggerPrecedenceValue.length === 0) {
|
||
errors.push('runtime.triggerPrecedence must not be empty');
|
||
} else {
|
||
const seenKinds = new Set();
|
||
for (let i = 0; i < triggerPrecedenceValue.length; i++) {
|
||
const k = triggerPrecedenceValue[i];
|
||
if (k === '__proto__' || k === 'constructor' || k === 'prototype') {
|
||
errors.push('runtime.triggerPrecedence[' + i + '] "' + k + '" is a reserved name');
|
||
} else if (typeof k !== 'string' || !VALID_TRIGGER_PRECEDENCE_KINDS.has(k)) {
|
||
errors.push(
|
||
'runtime.triggerPrecedence[' + i + '] must be one of: ' + [...VALID_TRIGGER_PRECEDENCE_KINDS].join(', ') +
|
||
' (got: ' + JSON.stringify(k) + ')',
|
||
);
|
||
} else if (seenKinds.has(k)) {
|
||
errors.push('runtime.triggerPrecedence contains a duplicate kind: ' + JSON.stringify(k));
|
||
} else {
|
||
seenKinds.add(k);
|
||
}
|
||
}
|
||
}
|
||
|
||
return errors;
|
||
}
|
||
|
||
/**
|
||
* ADR-2782 D2/D7 — every declared reviewer field is a known key. Anything else
|
||
* inside the body is IGNORED WITH A WARNING (D4.3), never a validation error:
|
||
* a capability authored for a newer GSD must degrade to discovered-but-inactive
|
||
* rather than failing the build of a repo that merely reads it.
|
||
*/
|
||
const KNOWN_REVIEWER_FIELDS = new Set([
|
||
'slug', 'flags', 'transport', 'probe', 'invoke', 'timeoutFloorMs', 'emptyOutput',
|
||
'reviewsSection', 'evidenceClass', 'requiresBinaries', 'promptBudgetKey',
|
||
// `modelConfigKey` added by Phase 5b (#2799). The model key was IMPLICIT
|
||
// (`review.models.<slug>`) until a shipped lane broke the convention: antigravity's
|
||
// slug is `antigravity` but its key is `review.models.agy`, so resolving by slug
|
||
// missed a configured model and silently disabled the pinned-model escape hatch
|
||
// #2073 added. A convention one shipped lane already violates is not a contract.
|
||
'modelConfigKey',
|
||
// `timeoutConfigKey` added by #3274, same optional/backward-compatible shape as
|
||
// `modelConfigKey` above: a manifest authored before this field existed must keep validating.
|
||
'timeoutConfigKey',
|
||
// `effortConfigKey` / `defaultEffort` added by #4255, same optional/backward-compatible shape
|
||
// as the two above. Lane effort used to be resolved by querying the `gsd-plan-checker` AGENT
|
||
// through a hardcoded id, so every prompt-fed lane ran at that verifier's frontmatter effort;
|
||
// it is a property of the review, so the lane declares it. A manifest authored before these
|
||
// fields existed must keep validating — absent is read as "this lane declares no review
|
||
// effort", which emits no effort argument at all.
|
||
'effortConfigKey',
|
||
'defaultEffort',
|
||
'handler',
|
||
]);
|
||
|
||
/**
|
||
* The effort levels a lane may declare as its review default (#4255, #3533 vocabulary).
|
||
*
|
||
* `inherit` is deliberately NOT a member. It is a legitimate CONFIGURED value — it selects "emit
|
||
* no argument, the CLI's own configuration decides" — but as a DECLARED default it would be a
|
||
* second spelling of `null` and split one behaviour across two shapes.
|
||
*/
|
||
const REVIEWER_EFFORT_LEVELS = new Set(['minimal', 'low', 'medium', 'high', 'xhigh', 'max']);
|
||
|
||
/**
|
||
* The closed `runtime.hostBehaviors` vocabulary (ADR-1016, closed via #2801).
|
||
*
|
||
* ADR-1016's core principle is that every per-runtime difference is a value over
|
||
* a closed primitive vocabulary, and that a host needing a new shape gets a
|
||
* reviewed first-party primitive rather than "an open escape hatch in the
|
||
* descriptor" (§Alternatives #2 rejects exactly that). `hostBehaviors` was the
|
||
* one hole left in that closure: 59 keys across 18 manifests, 39 of them set by
|
||
* a single capability, validated by nothing. It was described in the reference
|
||
* docs as a deliberate open seam sanctioned by ADR-1016 — ADR-1016 does not
|
||
* mention `hostBehaviors` at all, and its stated principle is the opposite.
|
||
*
|
||
* Adding a key here is deliberate and reviewed. That friction IS the decision
|
||
* (ADR-1016 §Consequences: "the closed vocabulary must grow (reviewed) when a
|
||
* genuinely new host shape appears — intentional friction, the trust boundary").
|
||
*
|
||
* WARNING, never error. Two reasons:
|
||
* 1. It matches the ADR-2782 D4.3 treatment of an unknown `reviewer` field, so
|
||
* a manifest built against a newer GSD degrades visibly instead of failing
|
||
* the build of a repo that merely reads it.
|
||
* 2. An error would hard-break an out-of-tree descriptor carrying a bespoke
|
||
* key, with no deprecation window — the exact mistake #2801's own alias
|
||
* removal spent a full release avoiding. Escalating to an error is a later
|
||
* step and needs its own window.
|
||
*
|
||
* Kept in sorted order, and `tests/reviewer-manifest-body.test.cjs` asserts this
|
||
* set equals the keys the shipped manifests actually declare, so the list cannot
|
||
* silently rot away from reality (DEFECT.GENERATIVE-FIX).
|
||
*/
|
||
const KNOWN_HOST_BEHAVIORS = new Set([
|
||
'agentFileExtension',
|
||
'agentFrontmatterExtensions',
|
||
'agentManifestStyle',
|
||
'agentTomlFiles',
|
||
'attributionConfigResolver',
|
||
'attributionSource',
|
||
'authorsCanonicalWorkflow',
|
||
'brandingRewrites',
|
||
'cleanupSkillSidecars',
|
||
'clineRulesSurface',
|
||
'combinedFamilyInstall',
|
||
'commandBodyConverter',
|
||
'doneBannerStyle',
|
||
'flatCommandDir',
|
||
'frontmatterDialect',
|
||
'globalDirResolver',
|
||
'hookPathStyle',
|
||
'hooksJsonSurface',
|
||
'hyphenNameAgentBody',
|
||
'installsCommandBodiesForWorkflowDelegation',
|
||
'legacyCommandsGsdCleanup',
|
||
'legacyCommandsGsdInstallMigration',
|
||
'legacyCommandsGsdUninstall',
|
||
'legacyDevinSkillsCleanup',
|
||
'localCommandsViaRules',
|
||
'localInstallDeferred',
|
||
'localInstallStyle',
|
||
'localTargetIsProjectRoot',
|
||
'managedHookEvents',
|
||
'mcpCompanion',
|
||
'namedSubagentsSupported',
|
||
'nativeModelAliases',
|
||
'nativePlugin',
|
||
'noPathRewrite',
|
||
'ownsClaudePaths',
|
||
'permissionsSchema',
|
||
'pluginOnlyInstall',
|
||
'projectInstructionFile',
|
||
'reapplyCommand',
|
||
'reportCommandsDir',
|
||
'reportSkillsCount',
|
||
'retiredArtifacts',
|
||
'settingsFileByScope',
|
||
'sharedHooksDirName',
|
||
'skillFrontmatterVersion',
|
||
'skillPriorityFrontmatter',
|
||
'skillsGlobalOnboarding',
|
||
'skillsManifestPrefix',
|
||
'skipCodexSkillsManifest',
|
||
'skipHomePrefixSubstitution',
|
||
'skipSettingsUi',
|
||
'skipSharedHooksInstall',
|
||
'skipUpdateBannerCommand',
|
||
'soloStageMetadata',
|
||
'sourceMarkerFile',
|
||
'tomlConfigInstall',
|
||
'trackCategoryDescription',
|
||
// #2586: declares runtime-level feature axes GSD does not/cannot support on
|
||
// this host (e.g. Codex's `["context-warnings","phase-lifecycle-display"]`)
|
||
// — present-and-populated / absent-is-unsupported-empty convention, so
|
||
// omitting the key on every other runtime carries no inverted meaning.
|
||
'unsupportedFeatures',
|
||
'verificationStyle',
|
||
'writeCategoryDescription',
|
||
]);
|
||
|
||
/**
|
||
* Frozen reason codes for the non-fatal reviewer diagnostics (ADR-2782 D4.3).
|
||
*
|
||
* The IR behind `collectReviewerWarnings`' rendered strings. Tests assert on
|
||
* these codes; the rendered `message` is operator console output and tests must
|
||
* not depend on it (CONTRIBUTING.md, "Prohibited: Raw Text Matching on Test
|
||
* Outputs"), which is the same split `bin/verify-reapply-patches.cjs` uses.
|
||
*
|
||
* Adding a code is THREE coordinated changes: this enum, the emitting site in
|
||
* `collectReviewerWarningRecordFields`, and the test that locks
|
||
* `Object.keys(REVIEWER_WARNING).sort()`. That coupling is the point — it stops
|
||
* the code surface drifting from the test surface.
|
||
*/
|
||
const REVIEWER_WARNING = Object.freeze({
|
||
/** A key inside a `reviewer` body that this GSD version does not know. */
|
||
UNKNOWN_REVIEWER_FIELD: 'unknown_reviewer_field',
|
||
/** A `runtime.hostBehaviors` key that was removed from the vocabulary. */
|
||
REMOVED_HOST_BEHAVIOR: 'removed_host_behavior',
|
||
/** A `runtime.hostBehaviors` key outside the closed vocabulary. */
|
||
UNKNOWN_HOST_BEHAVIOR: 'unknown_host_behavior',
|
||
});
|
||
|
||
/** Dotted path of the field removed by ADR-2782 D9 / #2801. */
|
||
const REMOVED_REVIEWER_CLI_FIELD = 'runtime.hostBehaviors.reviewerCli';
|
||
|
||
const KNOWN_PROBE_FIELDS = new Set(['kind', 'binary', 'needle', 'timeoutMs', 'hostConfigKey', 'path']);
|
||
|
||
/** A bounded probe timeout must be a finite, positive INTEGER of milliseconds. */
|
||
function isPositiveIntegerMs(v) {
|
||
return typeof v === 'number' && Number.isInteger(v) && v > 0;
|
||
}
|
||
|
||
/**
|
||
* Render any value for an error message WITHOUT ever throwing.
|
||
*
|
||
* `JSON.stringify` throws on a BigInt and on a circular structure, and a value
|
||
* carrying a throwing `toJSON` propagates that throw. Interpolating a rejected
|
||
* value into its own rejection message must never itself become the failure —
|
||
* these validators are contracted to RETURN errors, and #1461 OVL-1 records a
|
||
* validator that threw and would have crashed every consumer of loadRegistry.
|
||
*
|
||
* @param {*} v
|
||
* @returns {string}
|
||
*/
|
||
function describeValue(v) {
|
||
if (typeof v === 'bigint') return String(v) + 'n';
|
||
if (typeof v === 'symbol') return String(v);
|
||
if (typeof v === 'function') return '[function]';
|
||
try {
|
||
const json = JSON.stringify(v);
|
||
// stringify returns undefined for undefined and for non-serializable roots.
|
||
return json === undefined ? String(v) : json;
|
||
} catch {
|
||
// Circular structure, a nested BigInt, or a throwing toJSON.
|
||
try {
|
||
return Object.prototype.toString.call(v);
|
||
} catch {
|
||
return '[unserializable]';
|
||
}
|
||
}
|
||
}
|
||
|
||
/**
|
||
* Ceiling on how many undeclared-key diagnostics one capability may produce.
|
||
*
|
||
* The loops below iterate MANIFEST-SUPPLIED keys, and an installed third-party
|
||
* manifest is bounded only by MANIFEST_MAX_BYTES (8MB). Unbounded, one manifest
|
||
* of 800k keys yields 800k records and ~139MB of message text, retained for the
|
||
* registry's lifetime in OverlayMeta.diagnostics. Ten is enough to act on; the
|
||
* rest are summarized. Mirrors the existing truncation idiom in
|
||
* `capability-loader.cts` (`crossErrs.slice(0, 3)`).
|
||
*/
|
||
const MAX_REPORTED_UNKNOWN_KEYS = 10;
|
||
|
||
/** Ceiling on how much of one manifest-supplied key name a diagnostic repeats. */
|
||
const MAX_REPORTED_KEY_CHARS = 80;
|
||
|
||
/**
|
||
* Render a manifest-supplied KEY for a diagnostic: control-safe and bounded.
|
||
*
|
||
* Key names carry no grammar anywhere — unlike `cap.id`, which `validateCapability`
|
||
* gates on KEBAB_RE before these diagnostics run — so a key is fully
|
||
* attacker-controlled text heading for stderr and OverlayMeta.warnings. C0/C1
|
||
* controls (ESC, CR, LF) become U+FFFD so a key cannot emit terminal escapes or
|
||
* forge a log line, and the result is clipped so one key cannot carry megabytes
|
||
* into a retained diagnostic.
|
||
*
|
||
* @param {*} key
|
||
* @returns {string}
|
||
*/
|
||
function describeKey(key) {
|
||
const raw = typeof key === 'string' ? key : String(key);
|
||
// eslint-disable-next-line no-control-regex
|
||
const safe = raw.replace(/[\x00-\x1f\x7f-\x9f]/g, '<27>');
|
||
return safe.length > MAX_REPORTED_KEY_CHARS ? safe.slice(0, MAX_REPORTED_KEY_CHARS) + '…' : safe;
|
||
}
|
||
|
||
/** Extract a message from an unknown thrown value without throwing again. */
|
||
function safeErrorMessage(err) {
|
||
try {
|
||
if (err instanceof Error && typeof err.message === 'string') return err.message;
|
||
return describeValue(err);
|
||
} catch {
|
||
return '[unprintable error]';
|
||
}
|
||
}
|
||
|
||
/** House CodeQL barrier — inline literal guard at every key-derived read/write site. */
|
||
function isReservedName(v) {
|
||
return v === '__proto__' || v === 'constructor' || v === 'prototype';
|
||
}
|
||
|
||
/**
|
||
* One closed-enum membership check, with the members always enumerated in the
|
||
* error.
|
||
*
|
||
* The enumeration is the point, not the deduplication. The prose reference for
|
||
* the reviewer body lands in Phase 6 (#2800), so until then these errors are the
|
||
* only documentation of the vocabulary — exactly the gap that left
|
||
* `hostBehaviors` discoverable solely by grepping a source line. Routing every
|
||
* enum through one helper makes "the error names the valid members" structural
|
||
* rather than a convention repeated at nine call sites, where it would drift.
|
||
*
|
||
* No reserved-name pre-check: a `VALID_*` set never contains `__proto__`,
|
||
* `constructor` or `prototype`, so membership alone already rejects them, and
|
||
* "must be one of: …" tells an author more than "is a reserved name". The
|
||
* literal guards stay where they do real work — the key-derived write sites.
|
||
*
|
||
* @param {string} ctx Error-message prefix.
|
||
* @param {string} label Dotted field path, e.g. "reviewer.transport".
|
||
* @param {*} value The declared value.
|
||
* @param {Set} validSet The closed vocabulary.
|
||
* @returns {string[]}
|
||
*/
|
||
function validateEnumField(ctx, label, value, validSet) {
|
||
if (validSet.has(value)) return [];
|
||
return [
|
||
ctx + ' ' + label + ' must be one of: ' + [...validSet].join(', ') +
|
||
' (got: ' + describeValue(value) + ')',
|
||
];
|
||
}
|
||
|
||
/**
|
||
* Collect NON-FATAL reviewer diagnostics for a capability manifest as TYPED
|
||
* RECORDS (ADR-2782 D4.3, plus the D9 `hostBehaviors.reviewerCli` removal
|
||
* notice, #2801).
|
||
*
|
||
* This is the IR. `collectReviewerWarnings` below renders it to strings for the
|
||
* two production consumers; tests assert on these records instead of matching
|
||
* the rendered prose (CONTRIBUTING.md, "Prohibited: Raw Text Matching on Test
|
||
* Outputs").
|
||
*
|
||
* Record shape — `code` and `capId` are always present; the rest is per-code:
|
||
* { code: REVIEWER_WARNING.UNKNOWN_REVIEWER_FIELD,
|
||
* capId, field: 'reviewer.<key>', knownFields: string[], message }
|
||
* { code: REVIEWER_WARNING.REMOVED_HOST_BEHAVIOR,
|
||
* capId, field: 'runtime.hostBehaviors.reviewerCli',
|
||
* replacement: 'reviewer', docs: '<how-to path>', message }
|
||
*
|
||
* TOTAL: returns an array for ANY input and never throws. It runs on
|
||
* loadRegistry's ACCEPT path, so a diagnostic that throws would cost the user a
|
||
* lane that is otherwise perfectly valid (#1461 OVL-1).
|
||
*
|
||
* @param {object} cap A capability manifest.
|
||
* @returns {Array<object>} Warning records; empty when there is nothing to say.
|
||
*/
|
||
function collectReviewerWarningRecords(cap) {
|
||
try {
|
||
return collectReviewerWarningRecordFields(cap);
|
||
} catch {
|
||
return [];
|
||
}
|
||
}
|
||
|
||
/**
|
||
* Render the IR for operator console output.
|
||
*
|
||
* Kept separate from validateReviewerBody so validateCapability's contract
|
||
* (`=> string[]` of ERRORS) is unchanged for its two existing callers. The
|
||
* build-time generator writes these to stderr; the overlay loader surfaces them
|
||
* through OverlayMeta.warnings. A warning written only to a build log nobody
|
||
* reads is not a warning (ADR-2782 D4, "Where warnings surface").
|
||
*
|
||
* The `string[]` shape is load-bearing for both consumers and does not change.
|
||
*
|
||
* @param {object} cap A capability manifest.
|
||
* @returns {string[]} Warning strings; empty when there is nothing to say.
|
||
*/
|
||
function collectReviewerWarnings(cap) {
|
||
return collectReviewerWarningRecords(cap).map((record) => record.message);
|
||
}
|
||
|
||
function collectReviewerWarningRecordFields(cap) {
|
||
const records = [];
|
||
if (typeof cap !== 'object' || cap === null || Array.isArray(cap)) return records;
|
||
|
||
const capId = typeof cap.id === 'string' ? cap.id : '(unknown)';
|
||
|
||
// ADR-2782 D9 / #2801 — the REMOVED `runtime.hostBehaviors.reviewerCli` alias.
|
||
//
|
||
// Emitted BEFORE the `reviewer`-body early-return below, deliberately. The
|
||
// manifest this notice exists for is the ALIAS-ONLY one, which by definition
|
||
// carries no body; after that guard the check would fire only for
|
||
// capabilities that already declare a lane — exactly the set that does not
|
||
// need telling.
|
||
//
|
||
// Presence-based, not `=== true`: the key is unknown at ANY value now, which
|
||
// is the same rule the unknown-`reviewer.*`-field loop below applies. Own-key
|
||
// read, so a polluted prototype cannot manufacture this warning on every
|
||
// otherwise-innocent manifest. This is ONE keyed removal notice, not general
|
||
// `hostBehaviors` validation — the closed vocabulary below handles that (#2801).
|
||
const runtimeBody = cap.runtime;
|
||
if (typeof runtimeBody === 'object' && runtimeBody !== null && !Array.isArray(runtimeBody)) {
|
||
const hostBehaviors = runtimeBody.hostBehaviors;
|
||
if (
|
||
typeof hostBehaviors === 'object'
|
||
&& hostBehaviors !== null
|
||
&& !Array.isArray(hostBehaviors)
|
||
&& Object.prototype.hasOwnProperty.call(hostBehaviors, 'reviewerCli')
|
||
) {
|
||
records.push({
|
||
code: REVIEWER_WARNING.REMOVED_HOST_BEHAVIOR,
|
||
capId,
|
||
field: REMOVED_REVIEWER_CLI_FIELD,
|
||
replacement: 'reviewer',
|
||
docs: 'docs/how-to/ship-a-reviewer-lane.md',
|
||
message:
|
||
'⚠ capability "' + capId + '" ' + REMOVED_REVIEWER_CLI_FIELD + ' was removed (ADR-2782 D9) ' +
|
||
'— ignored, and it contributes no reviewer lane. Declare a `reviewer` body instead; see ' +
|
||
'docs/how-to/ship-a-reviewer-lane.md',
|
||
});
|
||
}
|
||
|
||
// #2801 — the closed `hostBehaviors` vocabulary (ADR-1016). `reviewerCli` is
|
||
// excluded here: it already drew its own removal notice above, and a second,
|
||
// generic "unknown key" record for the same key would be noise, not signal.
|
||
if (typeof hostBehaviors === 'object' && hostBehaviors !== null && !Array.isArray(hostBehaviors)) {
|
||
let reported = 0;
|
||
let omitted = 0;
|
||
for (const key of Object.keys(hostBehaviors)) {
|
||
if (isReservedName(key) || key === 'reviewerCli' || KNOWN_HOST_BEHAVIORS.has(key)) continue;
|
||
if (reported >= MAX_REPORTED_UNKNOWN_KEYS) {
|
||
omitted += 1;
|
||
continue;
|
||
}
|
||
reported += 1;
|
||
const safeKey = describeKey(key);
|
||
records.push({
|
||
code: REVIEWER_WARNING.UNKNOWN_HOST_BEHAVIOR,
|
||
capId,
|
||
field: 'runtime.hostBehaviors.' + safeKey,
|
||
message:
|
||
'⚠ capability "' + capId + '" runtime.hostBehaviors.' + safeKey + ' is not a known host behavior ' +
|
||
'in this GSD version — ignored. Adding one is a reviewed first-party change (ADR-1016).',
|
||
});
|
||
}
|
||
if (omitted > 0) {
|
||
records.push({
|
||
code: REVIEWER_WARNING.UNKNOWN_HOST_BEHAVIOR,
|
||
capId,
|
||
field: 'runtime.hostBehaviors',
|
||
truncated: true,
|
||
omittedCount: omitted,
|
||
message:
|
||
'⚠ capability "' + capId + '" declares ' + omitted + ' further unknown runtime.hostBehaviors ' +
|
||
'key(s), not listed. A manifest this far outside the vocabulary is likely built for a ' +
|
||
'different GSD version.',
|
||
});
|
||
}
|
||
}
|
||
}
|
||
|
||
const r = cap.reviewer;
|
||
if (typeof r !== 'object' || r === null || Array.isArray(r)) return records;
|
||
|
||
// Same ceiling and the same key sanitization as the hostBehaviors sweep above.
|
||
// This loop predates #2801 and carried both defects; fixing only the new copy
|
||
// would leave the identical defect one screen away from its own fix.
|
||
let reportedFields = 0;
|
||
let omittedFields = 0;
|
||
for (const key of Object.keys(r)) {
|
||
if (isReservedName(key) || KNOWN_REVIEWER_FIELDS.has(key)) continue;
|
||
if (reportedFields >= MAX_REPORTED_UNKNOWN_KEYS) {
|
||
omittedFields += 1;
|
||
continue;
|
||
}
|
||
reportedFields += 1;
|
||
const safeKey = describeKey(key);
|
||
records.push({
|
||
code: REVIEWER_WARNING.UNKNOWN_REVIEWER_FIELD,
|
||
capId,
|
||
field: 'reviewer.' + safeKey,
|
||
knownFields: [...KNOWN_REVIEWER_FIELDS],
|
||
message:
|
||
'⚠ capability "' + capId + '" reviewer.' + safeKey + ' is not a known reviewer field ' +
|
||
'in this GSD version — ignored. Known fields: ' + [...KNOWN_REVIEWER_FIELDS].join(', '),
|
||
});
|
||
}
|
||
if (omittedFields > 0) {
|
||
records.push({
|
||
code: REVIEWER_WARNING.UNKNOWN_REVIEWER_FIELD,
|
||
capId,
|
||
field: 'reviewer',
|
||
knownFields: [...KNOWN_REVIEWER_FIELDS],
|
||
truncated: true,
|
||
omittedCount: omittedFields,
|
||
message:
|
||
'⚠ capability "' + capId + '" declares ' + omittedFields + ' further unknown reviewer field(s), ' +
|
||
'not listed.',
|
||
});
|
||
}
|
||
return records;
|
||
}
|
||
|
||
/**
|
||
* Validate a `reviewer` lane body (ADR-2782 D1/D2/D3/D6/D7).
|
||
*
|
||
* TOTAL: returns an array of error strings for ANY input and never throws. The
|
||
* overlay loader contracts every validator to RETURN errors — #1461 OVL-1
|
||
* records a validator that THREW and would have crashed every consumer of
|
||
* loadRegistry. That contract is load-bearing, not stylistic.
|
||
*
|
||
* ABSENT-SAFE (D4.1): a capability with no `reviewer` key is simply not a lane.
|
||
* That is NEVER an error — 39 of 39 shipped capabilities are in this state, and
|
||
* a validator that errors here breaks the entire registry. `undefined` is the
|
||
* ONLY permissive case: `null`, `{}`, `[]`, `false` and `0` are all assertions
|
||
* of a body, and a malformed assertion is an error (Postel's Law with a
|
||
* boundary — liberal in what a manifest may OMIT, strict in what it ASSERTS).
|
||
*
|
||
* Totality is enforced STRUCTURALLY by the wrapper below, not by auditing every
|
||
* field read. Serialization is made safe via describeValue(), but that alone is
|
||
* not enough: a value carrying a throwing getter, or a Proxy with a throwing
|
||
* `get`/`ownKeys` trap, throws on the READ itself, before any message is built.
|
||
* A caller cannot be asked to re-derive today's reachability analysis — the
|
||
* contract says "any input", so the guarantee is absolute rather than argued.
|
||
*
|
||
* @param {object} cap The parsed capability manifest.
|
||
* @returns {string[]} Array of error strings; empty = valid.
|
||
*/
|
||
function validateReviewerBody(cap) {
|
||
try {
|
||
return validateReviewerBodyFields(cap);
|
||
} catch (err) {
|
||
// A malformed body must degrade to a validation ERROR, never to a crash of
|
||
// every consumer of loadRegistry (#1461 OVL-1).
|
||
return ['capability reviewer body could not be validated: ' + safeErrorMessage(err)];
|
||
}
|
||
}
|
||
|
||
function validateReviewerBodyFields(cap) {
|
||
const errors = [];
|
||
if (typeof cap !== 'object' || cap === null || Array.isArray(cap)) return errors;
|
||
|
||
const r = cap.reviewer;
|
||
if (r === undefined) return errors; // D4.1 — not a lane. Never an error.
|
||
|
||
const ctx = 'capability "' + (typeof cap.id === 'string' ? cap.id : '(unknown)') + '"';
|
||
|
||
if (typeof r !== 'object' || r === null || Array.isArray(r)) {
|
||
const got = r === null ? 'null' : Array.isArray(r) ? 'array' : typeof r;
|
||
errors.push(
|
||
ctx + ' reviewer must be an object (got: ' + got + '). ' +
|
||
'Omit the key entirely to declare no lane — an explicit null is not an omission.',
|
||
);
|
||
return errors; // cannot validate fields of a non-object
|
||
}
|
||
|
||
// ── slug ───────────────────────────────────────────────────────────────────
|
||
// NOT a capability id: ids are kebab, slugs carry the roster's snake forms.
|
||
if (typeof r.slug !== 'string' || r.slug.length === 0) {
|
||
errors.push(ctx + ' reviewer.slug must be a non-empty string');
|
||
} else if (isReservedName(r.slug)) {
|
||
errors.push(ctx + ' reviewer.slug "' + r.slug + '" is a reserved name');
|
||
} else if (!LANE_SLUG_RE.test(r.slug)) {
|
||
errors.push(
|
||
ctx + ' reviewer.slug "' + r.slug + '" must match ' + String(LANE_SLUG_RE) +
|
||
' (lower-case; "_" and "-" permitted — a slug is not a capability id and not a flag)',
|
||
);
|
||
}
|
||
|
||
// ── flags ──────────────────────────────────────────────────────────────────
|
||
if (!Array.isArray(r.flags)) {
|
||
errors.push(ctx + ' reviewer.flags must be an array of CLI flags');
|
||
} else if (r.flags.length === 0) {
|
||
errors.push(
|
||
ctx + ' reviewer.flags must declare at least one flag — a lane nobody can name ' +
|
||
'cannot be explicitly selected, so ADR-2782 D4\'s explicit-selection rule is unreachable for it',
|
||
);
|
||
} else {
|
||
const seen = new Set();
|
||
for (const flag of r.flags) {
|
||
if (typeof flag !== 'string' || !LANE_FLAG_RE.test(flag)) {
|
||
errors.push(
|
||
ctx + ' reviewer.flags entry ' + describeValue(flag) +
|
||
' must match ' + String(LANE_FLAG_RE) + ' (e.g. "--lm-studio")',
|
||
);
|
||
continue;
|
||
}
|
||
if (seen.has(flag)) {
|
||
errors.push(ctx + ' reviewer.flags lists "' + flag + '" more than once');
|
||
}
|
||
seen.add(flag);
|
||
}
|
||
}
|
||
|
||
// ── transport (D2) — explicit discriminator, never inferred ────────────────
|
||
errors.push(...validateEnumField(ctx, 'reviewer.transport', r.transport, VALID_LANE_TRANSPORTS));
|
||
|
||
errors.push(...validateLaneProbe(ctx, r.probe));
|
||
errors.push(...validateLaneInvoke(ctx, r.transport, r.invoke));
|
||
|
||
// ── lane scalars ───────────────────────────────────────────────────────────
|
||
if (!isPositiveIntegerMs(r.timeoutFloorMs)) {
|
||
errors.push(
|
||
ctx + ' reviewer.timeoutFloorMs must be a positive integer of milliseconds ' +
|
||
'(got: ' + describeValue(r.timeoutFloorMs) + ')',
|
||
);
|
||
}
|
||
|
||
errors.push(...validateEnumField(ctx, 'reviewer.emptyOutput', r.emptyOutput, VALID_EMPTY_OUTPUT));
|
||
|
||
if (typeof r.reviewsSection !== 'string' || r.reviewsSection.length === 0) {
|
||
errors.push(ctx + ' reviewer.reviewsSection must be a non-empty string');
|
||
}
|
||
|
||
errors.push(...validateEnumField(ctx, 'reviewer.evidenceClass', r.evidenceClass, VALID_EVIDENCE_CLASSES));
|
||
|
||
if (!Array.isArray(r.requiresBinaries)) {
|
||
errors.push(
|
||
ctx + ' reviewer.requiresBinaries must be an array (use [] when the lane needs no ' +
|
||
'external tool on PATH). Note the name: the envelope\'s "requires" is capability ids',
|
||
);
|
||
} else {
|
||
for (const bin of r.requiresBinaries) {
|
||
if (typeof bin !== 'string' || bin.length === 0) {
|
||
errors.push(ctx + ' reviewer.requiresBinaries entry ' + describeValue(bin) + ' must be a non-empty string');
|
||
}
|
||
}
|
||
}
|
||
|
||
// OPTIONAL, and that is required by D4 rather than a convenience: `modelConfigKey` did not exist
|
||
// before Phase 5b, so demanding it would fail validation on every reviewer manifest authored
|
||
// against an earlier GSD — exactly the forward/backward-compatibility break D4 rule 2 forbids.
|
||
// Absent is read as `null` (this lane accepts no model override). `null` is explicit; an empty
|
||
// string is neither, and is rejected.
|
||
if (r.modelConfigKey !== undefined && r.modelConfigKey !== null &&
|
||
(typeof r.modelConfigKey !== 'string' || r.modelConfigKey.length === 0)) {
|
||
errors.push(
|
||
ctx + ' reviewer.modelConfigKey must be a dotted config key or null ' +
|
||
'(got: ' + describeValue(r.modelConfigKey) + ')',
|
||
);
|
||
}
|
||
|
||
// OPTIONAL, mirroring modelConfigKey's D4 forward/backward-compat treatment (#3274): a manifest
|
||
// authored before this field existed must keep validating. Absent/null means "no override for
|
||
// this lane, use timeoutFloorMs". An empty string is neither absent nor a key, and is rejected.
|
||
if (r.timeoutConfigKey !== undefined && r.timeoutConfigKey !== null &&
|
||
(typeof r.timeoutConfigKey !== 'string' || r.timeoutConfigKey.length === 0)) {
|
||
errors.push(
|
||
ctx + ' reviewer.timeoutConfigKey must be a dotted config key or null ' +
|
||
'(got: ' + describeValue(r.timeoutConfigKey) + ')',
|
||
);
|
||
}
|
||
|
||
// OPTIONAL, mirroring the two keys above (#4255). Absent/null means "this lane declares no
|
||
// review effort", which is the shape that emits no effort argument at all — the correct state
|
||
// for the nine lanes with no effort channel to feed. An empty string is neither.
|
||
if (r.effortConfigKey !== undefined && r.effortConfigKey !== null &&
|
||
(typeof r.effortConfigKey !== 'string' || r.effortConfigKey.length === 0)) {
|
||
errors.push(
|
||
ctx + ' reviewer.effortConfigKey must be a dotted config key or null ' +
|
||
'(got: ' + describeValue(r.effortConfigKey) + ')',
|
||
);
|
||
}
|
||
|
||
// A declared default must be a level the effort axis knows, or the lane would render an
|
||
// argument the reviewer CLI rejects and kill itself on every run. Closed vocabulary, checked
|
||
// here rather than at resolution time so a malformed manifest fails at the trust boundary.
|
||
if (r.defaultEffort !== undefined && r.defaultEffort !== null
|
||
&& !(typeof r.defaultEffort === 'string' && REVIEWER_EFFORT_LEVELS.has(r.defaultEffort))) {
|
||
errors.push(
|
||
ctx + ' reviewer.defaultEffort must be one of ' +
|
||
Array.from(REVIEWER_EFFORT_LEVELS).join('/') + ' or null ' +
|
||
'(got: ' + describeValue(r.defaultEffort) + ')',
|
||
);
|
||
}
|
||
|
||
// A default with nothing to configure it through is a value the operator cannot change — the
|
||
// shape #4255 exists to end. Declared together or not at all.
|
||
if ((r.defaultEffort !== undefined && r.defaultEffort !== null)
|
||
&& (r.effortConfigKey === undefined || r.effortConfigKey === null)) {
|
||
errors.push(
|
||
ctx + ' reviewer.defaultEffort is declared without an effortConfigKey, so the level ' +
|
||
'could never be overridden',
|
||
);
|
||
}
|
||
|
||
// `null` is the declared "no per-lane budget"; an empty string is not.
|
||
if (r.promptBudgetKey !== null && (typeof r.promptBudgetKey !== 'string' || r.promptBudgetKey.length === 0)) {
|
||
errors.push(
|
||
ctx + ' reviewer.promptBudgetKey must be a dotted config key or null ' +
|
||
'(got: ' + describeValue(r.promptBudgetKey) + ')',
|
||
);
|
||
}
|
||
|
||
// ── handler (D6) — closed first-party enum; null is the default ────────────
|
||
if (r.handler !== null && !VALID_LANE_HANDLERS.has(r.handler)) {
|
||
errors.push(
|
||
ctx + ' reviewer.handler must be null or one of: ' + [...VALID_LANE_HANDLERS].join(', ') +
|
||
' (got: ' + describeValue(r.handler) + '). Handlers are first-party module NAMES, ' +
|
||
'never paths and never third-party code — a lane needing a shape the vocabulary lacks ' +
|
||
'files an issue naming the missing primitive (ADR-2782 D6)',
|
||
);
|
||
}
|
||
|
||
return errors;
|
||
}
|
||
|
||
/**
|
||
* ADR-2782 D7 — probe.kind is a closed enum WIDER than existence, and every
|
||
* probe that starts a process or a connection MUST be bounded.
|
||
*
|
||
* `command-exists` alone is structurally insufficient: `kimi` is claimed by both
|
||
* Kimi Code CLI and the legacy Python kimi-cli (a separate first-party runtime
|
||
* capability in this repo), so an existence-only probe registers the wrong tool.
|
||
* The unbounded form of that probe was a live instance of this repo's named
|
||
* Unbounded Subprocesses defect — it ran on EVERY /gsd:review invocation
|
||
* regardless of which flags were passed, so a binary waiting on a first-run auth
|
||
* prompt hung every future review, including reviews that never asked for it.
|
||
*
|
||
* @param {string} ctx Error-message prefix.
|
||
* @param {*} probe The probe value.
|
||
* @returns {string[]}
|
||
*/
|
||
function validateLaneProbe(ctx, probe) {
|
||
const errors = [];
|
||
|
||
if (typeof probe !== 'object' || probe === null || Array.isArray(probe)) {
|
||
errors.push(ctx + ' reviewer.probe must be an object with a "kind" from: ' + [...VALID_LANE_PROBE_KINDS].join(', '));
|
||
return errors;
|
||
}
|
||
|
||
const kindErrors = validateEnumField(ctx, 'reviewer.probe.kind', probe.kind, VALID_LANE_PROBE_KINDS);
|
||
if (kindErrors.length > 0) {
|
||
errors.push(...kindErrors);
|
||
return errors; // sub-shape is meaningless without a known kind
|
||
}
|
||
|
||
for (const key of Object.keys(probe)) {
|
||
if (!isReservedName(key) && !KNOWN_PROBE_FIELDS.has(key)) {
|
||
errors.push(ctx + ' reviewer.probe.' + key + ' is not a known probe field');
|
||
}
|
||
}
|
||
|
||
const needsBound = probe.kind === 'command-capability' || probe.kind === 'http-reachable';
|
||
|
||
if (probe.kind === 'command-exists' || probe.kind === 'command-capability') {
|
||
if (typeof probe.binary !== 'string' || probe.binary.length === 0) {
|
||
errors.push(ctx + ' reviewer.probe.binary must be a non-empty string for kind "' + probe.kind + '"');
|
||
}
|
||
} else if (probe.binary !== undefined) {
|
||
errors.push(ctx + ' reviewer.probe.binary is not permitted for kind "' + probe.kind + '"');
|
||
}
|
||
|
||
if (probe.kind === 'command-capability') {
|
||
if (typeof probe.needle !== 'string' || probe.needle.length === 0) {
|
||
errors.push(ctx + ' reviewer.probe.needle must be a non-empty string for kind "command-capability"');
|
||
}
|
||
} else if (probe.needle !== undefined) {
|
||
errors.push(ctx + ' reviewer.probe.needle is not permitted for kind "' + probe.kind + '"');
|
||
}
|
||
|
||
if (probe.kind === 'http-reachable') {
|
||
if (typeof probe.hostConfigKey !== 'string' || probe.hostConfigKey.length === 0) {
|
||
errors.push(ctx + ' reviewer.probe.hostConfigKey must be a non-empty string for kind "http-reachable"');
|
||
}
|
||
if (typeof probe.path !== 'string' || probe.path.length === 0) {
|
||
errors.push(ctx + ' reviewer.probe.path must be a non-empty string for kind "http-reachable"');
|
||
}
|
||
} else {
|
||
if (probe.hostConfigKey !== undefined) {
|
||
errors.push(ctx + ' reviewer.probe.hostConfigKey is not permitted for kind "' + probe.kind + '"');
|
||
}
|
||
if (probe.path !== undefined) {
|
||
errors.push(ctx + ' reviewer.probe.path is not permitted for kind "' + probe.kind + '"');
|
||
}
|
||
}
|
||
|
||
if (needsBound) {
|
||
if (!isPositiveIntegerMs(probe.timeoutMs)) {
|
||
errors.push(
|
||
ctx + ' reviewer.probe.timeoutMs must be a positive integer of milliseconds for kind "' +
|
||
probe.kind + '" — an unbounded probe hangs every /gsd:review invocation ' +
|
||
'(got: ' + describeValue(probe.timeoutMs) + ')',
|
||
);
|
||
}
|
||
} else if (probe.timeoutMs !== undefined) {
|
||
errors.push(
|
||
ctx + ' reviewer.probe.timeoutMs is not permitted for kind "command-exists" — ' +
|
||
'no process is started, so there is nothing to bound',
|
||
);
|
||
}
|
||
|
||
return errors;
|
||
}
|
||
|
||
/**
|
||
* ADR-2782 D2 — the invoke sub-shape is selected by `transport`. A manifest
|
||
* declaring fields from BOTH sub-shapes, or from NEITHER, fails validation:
|
||
* inference from field presence leaves those two cases carrying undefined
|
||
* meaning, which is exactly what a closed vocabulary exists to prevent.
|
||
*
|
||
* @param {string} ctx Error-message prefix.
|
||
* @param {*} transport The (already enum-checked) transport value.
|
||
* @param {*} invoke The invoke value.
|
||
* @returns {string[]}
|
||
*/
|
||
function validateLaneInvoke(ctx, transport, invoke) {
|
||
const errors = [];
|
||
|
||
if (typeof invoke !== 'object' || invoke === null || Array.isArray(invoke)) {
|
||
errors.push(ctx + ' reviewer.invoke must be an object');
|
||
return errors;
|
||
}
|
||
|
||
const hasSpawnField = SPAWN_ONLY_INVOKE_FIELDS.some((f) => invoke[f] !== undefined);
|
||
const hasHttpField = HTTP_ONLY_INVOKE_FIELDS.some((f) => invoke[f] !== undefined);
|
||
|
||
if (hasSpawnField && hasHttpField) {
|
||
errors.push(
|
||
ctx + ' reviewer.invoke mixes spawn-only fields (' + SPAWN_ONLY_INVOKE_FIELDS.join(', ') +
|
||
') with openai-http-only fields (' + HTTP_ONLY_INVOKE_FIELDS.join(', ') +
|
||
') — a lane is one transport or the other',
|
||
);
|
||
}
|
||
|
||
if (transport === 'spawn') {
|
||
for (const f of HTTP_ONLY_INVOKE_FIELDS) {
|
||
if (invoke[f] !== undefined) {
|
||
errors.push(ctx + ' reviewer.invoke.' + f + ' is not permitted for transport "spawn"');
|
||
}
|
||
}
|
||
errors.push(...validateSpawnInvoke(ctx, invoke));
|
||
} else if (transport === 'openai-http') {
|
||
for (const f of SPAWN_ONLY_INVOKE_FIELDS) {
|
||
if (invoke[f] !== undefined) {
|
||
errors.push(ctx + ' reviewer.invoke.' + f + ' is not permitted for transport "openai-http"');
|
||
}
|
||
}
|
||
errors.push(...validateHttpInvoke(ctx, invoke));
|
||
}
|
||
// transport already reported as invalid upstream — do not double-report here.
|
||
|
||
return errors;
|
||
}
|
||
|
||
function validateSpawnInvoke(ctx, invoke) {
|
||
const errors = [];
|
||
|
||
if (typeof invoke.binary !== 'string' || invoke.binary.length === 0) {
|
||
errors.push(ctx + ' reviewer.invoke.binary must be a non-empty string for transport "spawn"');
|
||
}
|
||
|
||
if (!Array.isArray(invoke.args)) {
|
||
errors.push(ctx + ' reviewer.invoke.args must be an array (use [] when the lane takes no arguments)');
|
||
} else {
|
||
for (const a of invoke.args) {
|
||
if (typeof a !== 'string') {
|
||
errors.push(ctx + ' reviewer.invoke.args entry ' + describeValue(a) + ' must be a string');
|
||
}
|
||
}
|
||
}
|
||
|
||
errors.push(...validateEnumField(ctx, 'reviewer.invoke.promptChannel', invoke.promptChannel, VALID_PROMPT_CHANNELS));
|
||
|
||
const outputChannelErrors = validateEnumField(ctx, 'reviewer.invoke.outputChannel', invoke.outputChannel, VALID_OUTPUT_CHANNELS);
|
||
if (outputChannelErrors.length > 0) {
|
||
errors.push(...outputChannelErrors);
|
||
} else if (invoke.outputChannel === 'file-arg') {
|
||
// Knowing the review lands in a file is useless without the argument naming it.
|
||
if (typeof invoke.outputArg !== 'string' || invoke.outputArg.length === 0) {
|
||
errors.push(
|
||
ctx + ' reviewer.invoke.outputArg is required (non-empty string) when outputChannel is "file-arg"',
|
||
);
|
||
}
|
||
} else if (invoke.outputArg !== undefined) {
|
||
// Forbidden rather than ignored: a manifest carrying an outputArg it does not
|
||
// use is data a later reader may honour.
|
||
errors.push(
|
||
ctx + ' reviewer.invoke.outputArg is only permitted when outputChannel is "file-arg" ' +
|
||
'(got outputChannel: ' + describeValue(invoke.outputChannel) + ')',
|
||
);
|
||
}
|
||
|
||
// `null` declares "this lane accepts no model override". An empty string does not.
|
||
if (invoke.modelArg !== null && (typeof invoke.modelArg !== 'string' || invoke.modelArg.length === 0)) {
|
||
errors.push(
|
||
ctx + ' reviewer.invoke.modelArg must be a non-empty string or null ' +
|
||
'(got: ' + describeValue(invoke.modelArg) + ')',
|
||
);
|
||
}
|
||
|
||
errors.push(...validateEnumField(ctx, 'reviewer.invoke.effortChannel', invoke.effortChannel, VALID_LANE_EFFORT_CHANNELS));
|
||
|
||
// `env` — per-invocation environment pairs (#2483). OPTIONAL, unlike every field above: only a lane
|
||
// that needs to shape its child's environment declares it, and absent is the common case. Validated
|
||
// when present, because `resolveLanePlan` DROPS a non-string value rather than coercing it — so an
|
||
// unvalidated manifest declares a pair that silently never reaches the spawn, which is the failure
|
||
// mode a shipped env-guard can least afford. Keys are held to the portable POSIX
|
||
// environment-name grammar, which is a POLICY — not a claim about what an environment can physically
|
||
// hold. Measured: of the names refused below only NUL is actually rejected by `spawnSync`; `=`, 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`, and reads back via `process.env['A=B']`). They are refused because a
|
||
// name outside the grammar is not portably addressable by the program meant to read it.
|
||
if (invoke.env !== undefined) {
|
||
if (typeof invoke.env !== 'object' || invoke.env === null || Array.isArray(invoke.env)) {
|
||
errors.push(
|
||
ctx + ' reviewer.invoke.env must be an object of environment name/value pairs ' +
|
||
'(got: ' + describeValue(invoke.env) + ')',
|
||
);
|
||
} else {
|
||
for (const key of Object.keys(invoke.env)) {
|
||
// `__proto__` passes the grammar below 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
|
||
// instead of creating an own property. For the string values this field permits the setter is
|
||
// a no-op — the prototype is not even changed — so the pair would validate and then simply
|
||
// vanish before the spawn: the declared-but-never-delivered failure this block exists to catch.
|
||
// Refused by name, because the grammar cannot see it.
|
||
//
|
||
// Only `__proto__` needs this. Sibling reserved-name guards in this file reject
|
||
// `constructor`/`prototype` alongside it, but those guard bracket LOOKUPS that resolve
|
||
// prototype members; here the read is `Object.keys` + an own-value read, and `constructor`
|
||
// assigns as an ordinary own key. Refusing it too would reject a name the spawn could carry.
|
||
// CASE-INSENSITIVE, and that is not pedantry: Windows environment lookups are
|
||
// case-insensitive, so `Path` / `node_options` reach the child as `PATH` / `NODE_OPTIONS`
|
||
// and an exact-case set is bypassed by changing one letter. The grammar above already
|
||
// constrains keys to ASCII, so a plain uppercase fold is sufficient here.
|
||
if (DENIED_LANE_ENV_KEYS.has(key.toUpperCase())) {
|
||
errors.push(
|
||
ctx + ' reviewer.invoke.env key "' + key + '" is not permitted ' +
|
||
'(it makes the spawned reviewer run code of the manifest\'s choosing; ' +
|
||
'declare an absolute `invoke.binary` instead of reshaping the child\'s environment)',
|
||
);
|
||
} else if (key === '__proto__') {
|
||
errors.push(
|
||
ctx + ' reviewer.invoke.env key "__proto__" is not permitted ' +
|
||
'(it is silently dropped when the spawn plan is assembled, so it would never reach the child)',
|
||
);
|
||
} else if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(key)) {
|
||
errors.push(
|
||
ctx + ' reviewer.invoke.env key ' + describeValue(key) +
|
||
' is not a valid environment variable name',
|
||
);
|
||
}
|
||
if (typeof invoke.env[key] !== 'string') {
|
||
errors.push(
|
||
ctx + ' reviewer.invoke.env.' + key + ' must be a string ' +
|
||
'(got: ' + describeValue(invoke.env[key]) + ')',
|
||
);
|
||
}
|
||
}
|
||
}
|
||
}
|
||
|
||
return errors;
|
||
}
|
||
|
||
function validateHttpInvoke(ctx, invoke) {
|
||
const errors = [];
|
||
|
||
if (typeof invoke.hostConfigKey !== 'string' || invoke.hostConfigKey.length === 0) {
|
||
errors.push(
|
||
ctx + ' reviewer.invoke.hostConfigKey must be a non-empty dotted config key ' +
|
||
'for transport "openai-http" (it names the config key holding the base URL)',
|
||
);
|
||
}
|
||
|
||
if (typeof invoke.path !== 'string' || invoke.path.length === 0) {
|
||
errors.push(ctx + ' reviewer.invoke.path must be a non-empty string for transport "openai-http" (e.g. "/v1/chat/completions")');
|
||
}
|
||
|
||
errors.push(...validateEnumField(ctx, 'reviewer.invoke.modelDiscovery', invoke.modelDiscovery, VALID_MODEL_DISCOVERY));
|
||
|
||
// D2 fixes effortChannel to 'none' for this transport — an HTTP lane has no
|
||
// argv to carry an effort flag and no env of its own.
|
||
if (invoke.effortChannel !== 'none') {
|
||
errors.push(
|
||
ctx + ' reviewer.invoke.effortChannel must be "none" for transport "openai-http" ' +
|
||
'(got: ' + describeValue(invoke.effortChannel) + ')',
|
||
);
|
||
}
|
||
|
||
return errors;
|
||
}
|
||
|
||
// #1459 CONVERGENCE finding 1(b) — GENEROUS DoS backstop on a (possibly project-plantable) hook
|
||
// fragment file. A real fragment is a few KiB of markdown; 8 MiB is wildly more than any legitimate
|
||
// fragment. The bounded reader refuses a non-regular (FIFO/device/symlink-to-nonregular) or oversized
|
||
// fragment WITHOUT a raw blocking read, so a forged in-bundle FIFO/oversized fragment.path becomes an
|
||
// un-materializable fragment (a validation error / skip) instead of hanging or OOM-ing the loop.
|
||
const FRAGMENT_MAX_BYTES = 8 * 1024 * 1024;
|
||
|
||
function materializeHookFragments(cap, capDir) {
|
||
const errors = [];
|
||
const hookGroups = [
|
||
['steps', Array.isArray(cap.steps) ? cap.steps : []],
|
||
['contributions', Array.isArray(cap.contributions) ? cap.contributions : []],
|
||
];
|
||
|
||
// #1459 CONVERGENCE finding 1(b): the fragment body is read via the SHARED bounded fd reader (open →
|
||
// fstat → require regular file → size cap → read exactly size), NOT a raw fs.readFileSync(abs,'utf8')
|
||
// which BLOCKS forever on a forged in-bundle FIFO and reads an oversized fragment unbounded into memory.
|
||
// Required lazily so the committed plain-.cjs validator does not hard-depend on the built ledger artifact
|
||
// at module-load time (materialize is a runtime path, reached only after build:lib). A bounded-reader
|
||
// throw (non-regular/oversized/IO) → an un-materializable-fragment validation error, not a hang.
|
||
let readSmallRegularFile;
|
||
try {
|
||
({ readSmallRegularFile } = require('./capability-ledger.cjs'));
|
||
} catch {
|
||
// Defensive: if the bounded reader is unavailable, fall back to a fail-CLOSED stub so we never
|
||
// silently revert to an unbounded raw read. A null-returning stub turns every path fragment into an
|
||
// "could not be read" error rather than a hang (declarative-only fragments use `inline` and skip this).
|
||
readSmallRegularFile = () => null;
|
||
}
|
||
|
||
for (const [groupName, hooks] of hookGroups) {
|
||
for (let i = 0; i < hooks.length; i++) {
|
||
const hook = hooks[i];
|
||
if (!hook || typeof hook !== 'object' || Array.isArray(hook)) continue;
|
||
const fragment = hook.fragment;
|
||
if (!fragment || typeof fragment !== 'object' || Array.isArray(fragment)) continue;
|
||
if (typeof fragment.inline === 'string') continue;
|
||
if (typeof fragment.path !== 'string') continue;
|
||
|
||
const abs = path.resolve(capDir, fragment.path);
|
||
const capRoot = path.resolve(capDir);
|
||
if (abs !== capRoot && !abs.startsWith(capRoot + path.sep)) {
|
||
errors.push(
|
||
cap.id + '/' + groupName + '[' + i + '].fragment.path escapes capability directory: ' +
|
||
fragment.path,
|
||
);
|
||
continue;
|
||
}
|
||
|
||
try {
|
||
const body = readSmallRegularFile(abs, FRAGMENT_MAX_BYTES);
|
||
if (body === null) {
|
||
// null = genuinely missing (ENOENT) OR refused as non-regular/oversized via the stub fallback.
|
||
errors.push(
|
||
cap.id + '/' + groupName + '[' + i + '].fragment.path could not be read (missing, non-regular ' +
|
||
'(FIFO/device), or exceeds the size cap): ' + fragment.path,
|
||
);
|
||
continue;
|
||
}
|
||
fragment.inline = body;
|
||
} catch (err) {
|
||
// Bounded-reader fail-closed throw (non-regular/oversized/IO) — an un-materializable fragment.
|
||
errors.push(
|
||
cap.id + '/' + groupName + '[' + i + '].fragment.path could not be read: ' +
|
||
fragment.path + ' (' + err.message + ')',
|
||
);
|
||
}
|
||
}
|
||
}
|
||
|
||
return errors;
|
||
}
|
||
|
||
function validateFragment(fragment, prefix) {
|
||
const errors = [];
|
||
|
||
if (typeof fragment !== 'object' || fragment === null || Array.isArray(fragment)) {
|
||
errors.push(prefix + ' must be an object with path or inline key');
|
||
return errors;
|
||
}
|
||
|
||
const hasPath = Object.prototype.hasOwnProperty.call(fragment, 'path');
|
||
const hasInline = Object.prototype.hasOwnProperty.call(fragment, 'inline');
|
||
if (!hasPath && !hasInline) {
|
||
errors.push(prefix + ' must have a "path" or "inline" key');
|
||
}
|
||
if (hasInline) {
|
||
const inline = fragment.inline;
|
||
if (typeof inline !== 'string') {
|
||
errors.push(prefix + '.inline must be a string');
|
||
} else if (inline === '') {
|
||
errors.push(prefix + '.inline must be a non-empty string');
|
||
}
|
||
}
|
||
// S1: fragment.path traversal guard — must be a relative path with no ".." segments
|
||
if (hasPath) {
|
||
const p = fragment.path;
|
||
if (typeof p !== 'string' || p === '' || path.isAbsolute(p) || p.split(/[\\/]/).includes('..')) {
|
||
errors.push(prefix + '.path must be a relative path with no ".." segments');
|
||
}
|
||
}
|
||
|
||
return errors;
|
||
}
|
||
|
||
/**
|
||
* Validate a single step entry.
|
||
*
|
||
* @param {object} step The step to validate.
|
||
* @param {string} prefix Path prefix for error messages (e.g. "steps[0]").
|
||
* @param {Set|null} declaredSkills Set of skill stems declared in this capability's skills array,
|
||
* or null if the skills array was not valid (skip membership check).
|
||
* @param {Set|null} declaredAgents Set of agent names declared in this capability's agents array,
|
||
* or null if the agents array was not valid (skip membership check).
|
||
* @returns {string[]}
|
||
*/
|
||
function validateStep(step, prefix, declaredSkills, declaredAgents) {
|
||
const errors = [];
|
||
|
||
if (!VALID_LOOP_POINTS.has(step.point)) {
|
||
errors.push(prefix + '.point "' + step.point + '" is not a valid loop point');
|
||
}
|
||
|
||
if (typeof step.ref !== 'object' || step.ref === null) {
|
||
errors.push(prefix + '.ref must be an object with skill, agent, or command key');
|
||
} else {
|
||
const hasSkill = Object.prototype.hasOwnProperty.call(step.ref, 'skill');
|
||
const hasAgent = Object.prototype.hasOwnProperty.call(step.ref, 'agent');
|
||
const hasCommand = Object.prototype.hasOwnProperty.call(step.ref, 'command');
|
||
const dispatchCount = [hasSkill, hasAgent, hasCommand].filter(Boolean).length;
|
||
if (dispatchCount === 0) {
|
||
errors.push(prefix + '.ref must have a "skill", "agent", or "command" key');
|
||
} else if (dispatchCount > 1) {
|
||
// ref must be exclusive: skill XOR agent XOR command
|
||
errors.push(prefix + '.ref must have exactly one of "skill", "agent", or "command", not multiple');
|
||
}
|
||
if (hasSkill && typeof step.ref.skill !== 'string') {
|
||
errors.push(prefix + '.ref.skill must be a string');
|
||
} else if (hasSkill && typeof step.ref.skill === 'string' && step.ref.skill.startsWith('gsd-')) {
|
||
// Double-prefix guard: ref.skill is an unprefixed stem (e.g. "ui-review").
|
||
// Workflow dispatch prepends "gsd-" at runtime → "gsd-ui-review".
|
||
// A stem that already starts with "gsd-" would produce "gsd-gsd-..." at dispatch.
|
||
errors.push(
|
||
prefix + '.ref.skill "' + step.ref.skill + '" must not start with "gsd-" ' +
|
||
'(it is an unprefixed stem; the workflow prepends "gsd-" at dispatch — ' +
|
||
'starting with "gsd-" would produce "gsd-' + step.ref.skill + '")',
|
||
);
|
||
} else if (hasSkill && typeof step.ref.skill === 'string' && declaredSkills !== null && !declaredSkills.has(step.ref.skill)) {
|
||
// Membership check: ref.skill must be declared in this capability's skills array.
|
||
// This catches typos and ensures every dispatched skill is owned by this capability.
|
||
errors.push(
|
||
prefix + '.ref.skill "' + step.ref.skill + '" is not declared in this capability\'s skills: [' +
|
||
[...declaredSkills].join(', ') + ']',
|
||
);
|
||
}
|
||
if (hasAgent && typeof step.ref.agent !== 'string') {
|
||
errors.push(prefix + '.ref.agent must be a string');
|
||
} else if (hasAgent && typeof step.ref.agent === 'string' && declaredAgents !== null && !declaredAgents.has(step.ref.agent)) {
|
||
// Membership check: ref.agent must be declared in this capability's agents array.
|
||
errors.push(
|
||
prefix + '.ref.agent "' + step.ref.agent + '" is not declared in this capability\'s agents: [' +
|
||
[...declaredAgents].join(', ') + ']',
|
||
);
|
||
}
|
||
if (hasCommand && typeof step.ref.command !== 'string') {
|
||
errors.push(prefix + '.ref.command must be a string');
|
||
}
|
||
}
|
||
|
||
if (!Array.isArray(step.produces)) {
|
||
errors.push(prefix + '.produces must be an array');
|
||
} else {
|
||
for (const p of step.produces) {
|
||
if (typeof p !== 'string') errors.push(prefix + '.produces entries must be strings');
|
||
}
|
||
}
|
||
|
||
if (!Array.isArray(step.consumes)) {
|
||
errors.push(prefix + '.consumes must be an array');
|
||
} else {
|
||
for (const c of step.consumes) {
|
||
if (typeof c !== 'string') errors.push(prefix + '.consumes entries must be strings');
|
||
}
|
||
}
|
||
|
||
if (step.when !== undefined && typeof step.when !== 'string') {
|
||
errors.push(prefix + '.when must be a string if present');
|
||
}
|
||
|
||
if (step.pointFrom !== undefined && typeof step.pointFrom !== 'string') {
|
||
errors.push(prefix + '.pointFrom must be a string if present');
|
||
}
|
||
|
||
// #4209 DISP-02: strict optional boolean opt-in trait. Absent or false is
|
||
// inert; only a literal `true` reaches the projected active hook. Reject
|
||
// every other type (including truthy non-boolean values) so a typo can
|
||
// never silently opt a step into reviewer-lane dispatch.
|
||
if (step.supportsReviewerLanes !== undefined && typeof step.supportsReviewerLanes !== 'boolean') {
|
||
errors.push(prefix + '.supportsReviewerLanes must be a boolean if present');
|
||
}
|
||
|
||
if (step.fragment !== undefined) {
|
||
errors.push(...validateFragment(step.fragment, prefix + '.fragment'));
|
||
}
|
||
|
||
if (!VALID_ON_ERROR.has(step.onError)) {
|
||
errors.push(prefix + '.onError must be "skip" or "halt" (got: ' + step.onError + ')');
|
||
}
|
||
|
||
return errors;
|
||
}
|
||
|
||
function validateContribution(contrib, prefix) {
|
||
const errors = [];
|
||
|
||
if (!VALID_LOOP_POINTS.has(contrib.point)) {
|
||
errors.push(prefix + '.point "' + contrib.point + '" is not a valid loop point');
|
||
}
|
||
|
||
if (typeof contrib.into !== 'string') {
|
||
errors.push(prefix + '.into must be a string (agent role name)');
|
||
}
|
||
|
||
if (!Array.isArray(contrib.produces)) {
|
||
errors.push(prefix + '.produces must be an array');
|
||
} else {
|
||
for (const p of contrib.produces) {
|
||
if (typeof p !== 'string') errors.push(prefix + '.produces entries must be strings');
|
||
}
|
||
}
|
||
|
||
if (!Array.isArray(contrib.consumes)) {
|
||
errors.push(prefix + '.consumes must be an array');
|
||
} else {
|
||
for (const c of contrib.consumes) {
|
||
if (typeof c !== 'string') errors.push(prefix + '.consumes entries must be strings');
|
||
}
|
||
}
|
||
|
||
errors.push(...validateFragment(contrib.fragment, prefix + '.fragment'));
|
||
|
||
if (contrib.when !== undefined && typeof contrib.when !== 'string') {
|
||
errors.push(prefix + '.when must be a string if present');
|
||
}
|
||
|
||
if (contrib.onError !== undefined && !VALID_ON_ERROR.has(contrib.onError)) {
|
||
errors.push(prefix + '.onError must be "skip" or "halt" if present');
|
||
}
|
||
|
||
return errors;
|
||
}
|
||
|
||
function validateGate(gate, prefix) {
|
||
const errors = [];
|
||
|
||
if (!VALID_LOOP_POINTS.has(gate.point)) {
|
||
errors.push(prefix + '.point "' + gate.point + '" is not a valid loop point');
|
||
}
|
||
|
||
if (typeof gate.check !== 'object' || gate.check === null) {
|
||
errors.push(prefix + '.check must be an object');
|
||
} else {
|
||
const hasQuery = Object.prototype.hasOwnProperty.call(gate.check, 'query');
|
||
const hasPredicate = Object.prototype.hasOwnProperty.call(gate.check, 'predicate');
|
||
const hasAgentVerdict = Object.prototype.hasOwnProperty.call(gate.check, 'agentVerdict');
|
||
const count = [hasQuery, hasPredicate, hasAgentVerdict].filter(Boolean).length;
|
||
if (count !== 1) {
|
||
errors.push(prefix + '.check must have exactly one of: query, predicate, agentVerdict');
|
||
}
|
||
// agentVerdict forces blocking: false (advisory only)
|
||
if (hasAgentVerdict && gate.blocking === true) {
|
||
errors.push(
|
||
prefix + '.check.agentVerdict forces blocking: false (non-deterministic checks may not halt the loop)',
|
||
);
|
||
}
|
||
}
|
||
|
||
if (gate.when !== undefined && typeof gate.when !== 'string') {
|
||
errors.push(prefix + '.when must be a string if present');
|
||
}
|
||
|
||
if (typeof gate.blocking !== 'boolean') {
|
||
errors.push(prefix + '.blocking must be a boolean');
|
||
}
|
||
|
||
if (!VALID_ON_ERROR.has(gate.onError)) {
|
||
errors.push(prefix + '.onError must be "skip" or "halt" (got: ' + gate.onError + ')');
|
||
}
|
||
|
||
return errors;
|
||
}
|
||
|
||
// ─── Contract validation ──────────────────────────────────────────────────────
|
||
|
||
/**
|
||
* Validate per-capability contract constraints against the Loop Host Contract.
|
||
* This covers:
|
||
* - contribution.into ∈ step's agentRoles
|
||
* - when references a config key in cap.config
|
||
*
|
||
* NOTE: step.consumes satisfiability is NOT checked here — it requires the full
|
||
* set of validated capabilities (cross-capability produces). It runs in
|
||
* validateConsumesGlobal() after loadAndValidate builds capMap.
|
||
*
|
||
* @param {object} cap Validated capability object
|
||
* @param {string} capId Capability id (for error messages)
|
||
*/
|
||
function validateAgainstContract(cap, capId) {
|
||
if (cap.role !== 'feature') return [];
|
||
const errors = [];
|
||
const prefix = 'capability "' + capId + '"';
|
||
|
||
// contribution.into must be in the step's agentRoles
|
||
for (const contrib of cap.contributions) {
|
||
if (!VALID_LOOP_POINTS.has(contrib.point)) continue; // already reported
|
||
const contract = POINT_TO_CONTRACT.get(contrib.point);
|
||
if (contract && !contract.agentRoles.includes(contrib.into)) {
|
||
errors.push(
|
||
prefix + ' contribution.into "' + contrib.into + '" at point "' + contrib.point +
|
||
'" is not in the step\'s agentRoles [' + contract.agentRoles.join(', ') + ']',
|
||
);
|
||
}
|
||
}
|
||
|
||
// when references a plausibly-valid config key (string — we require it's in cap.config)
|
||
for (const step of cap.steps) {
|
||
if (step.when !== undefined) {
|
||
if (typeof step.when !== 'string') continue; // already reported above
|
||
if (
|
||
typeof cap.config === 'object' &&
|
||
cap.config !== null &&
|
||
!Object.prototype.hasOwnProperty.call(cap.config, step.when)
|
||
) {
|
||
errors.push(
|
||
prefix + ' step.when "' + step.when + '" is not defined in capability config keys',
|
||
);
|
||
}
|
||
}
|
||
}
|
||
|
||
// pointFrom (#3661): selects which of possibly several same-capability steps is
|
||
// active for its own `point`, based on an enum config key. Require it references
|
||
// an enum key in cap.config whose values include THIS step's own point — otherwise
|
||
// the step could never activate (a silently-dead step).
|
||
for (const step of cap.steps) {
|
||
if (step.pointFrom !== undefined) {
|
||
if (typeof step.pointFrom !== 'string') continue; // already reported above
|
||
const slice = typeof cap.config === 'object' && cap.config !== null ? cap.config[step.pointFrom] : undefined;
|
||
if (!slice || typeof slice !== 'object') {
|
||
errors.push(
|
||
prefix + ' step.pointFrom "' + step.pointFrom + '" is not defined in capability config keys',
|
||
);
|
||
} else if (slice.type !== 'enum') {
|
||
errors.push(
|
||
prefix + ' step.pointFrom "' + step.pointFrom + '" must reference an enum config key (got type: ' + slice.type + ')',
|
||
);
|
||
} else if (!Array.isArray(slice.values) || !slice.values.includes(step.point)) {
|
||
errors.push(
|
||
prefix + ' step.pointFrom "' + step.pointFrom + '" enum values do not include this step\'s own point "' +
|
||
step.point + '" — the step could never activate',
|
||
);
|
||
}
|
||
}
|
||
}
|
||
|
||
for (const contrib of cap.contributions) {
|
||
if (contrib.when !== undefined) {
|
||
if (typeof contrib.when !== 'string') continue;
|
||
if (
|
||
typeof cap.config === 'object' &&
|
||
cap.config !== null &&
|
||
!Object.prototype.hasOwnProperty.call(cap.config, contrib.when)
|
||
) {
|
||
errors.push(
|
||
prefix + ' contribution.when "' + contrib.when + '" is not defined in capability config keys',
|
||
);
|
||
}
|
||
}
|
||
}
|
||
|
||
for (const gate of cap.gates) {
|
||
if (gate.when !== undefined) {
|
||
if (typeof gate.when !== 'string') continue;
|
||
if (
|
||
typeof cap.config === 'object' &&
|
||
cap.config !== null &&
|
||
!Object.prototype.hasOwnProperty.call(cap.config, gate.when)
|
||
) {
|
||
errors.push(
|
||
prefix + ' gate.when "' + gate.when + '" is not defined in capability config keys',
|
||
);
|
||
}
|
||
}
|
||
}
|
||
|
||
return errors;
|
||
}
|
||
|
||
/**
|
||
* C1+C2: Global consumes-satisfiability validation.
|
||
*
|
||
* A hook at point P consuming artifact A is satisfiable iff:
|
||
* - A is a host-produced artifact available from its step's :post point (C1), and
|
||
* that :post point's POINT_ORDER index ≤ P's index; OR
|
||
* - A is produced by any capability hook step at a point whose POINT_ORDER index ≤ P's index
|
||
* (same-point is OK — topoSortSteps enforces intra-point order); OR
|
||
* - A is never produced anywhere → rejected.
|
||
*
|
||
* Runs after capMap is fully built so cross-capability produces are visible.
|
||
*
|
||
* @param {Map<string, object>} capMap Fully-validated capability map.
|
||
* @returns {string[]} Array of error strings.
|
||
*/
|
||
function validateConsumesGlobal(capMap) {
|
||
const errors = [];
|
||
|
||
// Build producedAtPoint: artifact → earliest POINT_ORDER index at which it is produced.
|
||
// Seed with host artifacts (C1: available from their step's :post point).
|
||
// Host-artifact entries are tagged {pointIdx, isHost:true} so they are never excluded by
|
||
// the self-consume check.
|
||
const producedAtPoint = Object.create(null);
|
||
for (const [artifact, postIdx] of Object.entries(HOST_ARTIFACT_EARLIEST_POINT_IDX)) {
|
||
if (artifact === '__proto__' || artifact === 'constructor' || artifact === 'prototype') continue;
|
||
producedAtPoint[artifact] = postIdx;
|
||
}
|
||
|
||
// Build a richer per-artifact producer list for the self-consume check.
|
||
// Each entry: { pointIdx, capId, stepIdx } — identifies which cap+step produced the artifact.
|
||
// Host artifacts are seeded separately (no capId) and always satisfy the consume check.
|
||
// capHookProducers[artifact] = [{pointIdx, capId, stepIdx}, ...]
|
||
const capHookProducers = Object.create(null);
|
||
|
||
// Add hook-produced artifacts from all capabilities.
|
||
for (const [capId, cap] of capMap) {
|
||
if (cap.role !== 'feature') continue;
|
||
for (let si = 0; si < (cap.steps || []).length; si++) {
|
||
const step = cap.steps[si];
|
||
if (!VALID_LOOP_POINTS.has(step.point)) continue;
|
||
const pointIdx = POINT_ORDER.indexOf(step.point);
|
||
for (const artifact of (step.produces || [])) {
|
||
if (typeof artifact !== 'string') continue;
|
||
if (artifact === '__proto__' || artifact === 'constructor' || artifact === 'prototype') continue;
|
||
if (producedAtPoint[artifact] === undefined || pointIdx < producedAtPoint[artifact]) {
|
||
producedAtPoint[artifact] = pointIdx;
|
||
}
|
||
if (!capHookProducers[artifact]) capHookProducers[artifact] = [];
|
||
capHookProducers[artifact].push({ pointIdx, capId, stepIdx: si });
|
||
}
|
||
}
|
||
}
|
||
|
||
// Duplicate-producer invariant: two capability steps may not produce the same artifact
|
||
// at the same Loop Extension Point. Same-point dual production makes data-flow resolution
|
||
// ambiguous and is rejected at gen time (Decision #6).
|
||
for (const artifact of Object.keys(capHookProducers)) {
|
||
if (artifact === '__proto__' || artifact === 'constructor' || artifact === 'prototype') continue;
|
||
const producers = capHookProducers[artifact];
|
||
// Group by pointIdx
|
||
const byPoint = Object.create(null);
|
||
for (const entry of producers) {
|
||
if (!byPoint[entry.pointIdx]) byPoint[entry.pointIdx] = [];
|
||
byPoint[entry.pointIdx].push(entry);
|
||
}
|
||
for (const pointIdxStr of Object.keys(byPoint)) {
|
||
const group = byPoint[pointIdxStr];
|
||
// Count distinct (capId, stepIdx) producer steps — a single step listing the same
|
||
// artifact twice in its produces array pushes duplicate entries but represents only
|
||
// ONE producer step and must not false-positive the cross-step gate.
|
||
const distinctProducers = new Set(group.map((e) => e.capId + ' ' + e.stepIdx));
|
||
if (distinctProducers.size >= 2) {
|
||
const pointIdx = Number(pointIdxStr);
|
||
const pointName = POINT_ORDER[pointIdx];
|
||
const capIds = [...new Set(group.map((e) => e.capId))].sort().join(', ');
|
||
throw new Error(
|
||
'duplicate-producer invariant violated: artifact "' + artifact + '" is produced by ' +
|
||
'two or more capability steps at the same Loop Extension Point "' + pointName + '" ' +
|
||
'(capabilities: ' + capIds + '). ' +
|
||
'Two capability steps producing the same artifact at the same Loop Extension Point ' +
|
||
'makes data-flow resolution ambiguous and is rejected at gen time.',
|
||
);
|
||
}
|
||
}
|
||
}
|
||
|
||
// Now check every hook step's consumes.
|
||
// Self-consume rule: a step H cannot satisfy its own consumes[A] from its own produces[A].
|
||
// A is satisfiable for H iff:
|
||
// (a) A is a host artifact with pointIdx <= stepPointIdx, OR
|
||
// (b) A is produced by a DIFFERENT cap/step at pointIdx <= stepPointIdx.
|
||
// "Different" means capId != H.capId OR stepIdx != H.stepIdx.
|
||
for (const [capId, cap] of capMap) {
|
||
if (cap.role !== 'feature') continue;
|
||
const prefix = 'capability "' + capId + '"';
|
||
for (let si = 0; si < (cap.steps || []).length; si++) {
|
||
const step = cap.steps[si];
|
||
if (!VALID_LOOP_POINTS.has(step.point)) continue;
|
||
const stepPointIdx = POINT_ORDER.indexOf(step.point);
|
||
for (const artifact of (step.consumes || [])) {
|
||
if (typeof artifact !== 'string') continue;
|
||
|
||
// Check host-artifact satisfaction first (never excluded by self-consume).
|
||
const hostIdx = HOST_ARTIFACT_EARLIEST_POINT_IDX[artifact];
|
||
const hostSatisfied = hostIdx !== undefined && hostIdx <= stepPointIdx;
|
||
if (hostSatisfied) continue; // fast-path: host artifact is available
|
||
|
||
// Check cap-hook producers, excluding this step itself.
|
||
const producers = capHookProducers[artifact];
|
||
if (!producers || producers.length === 0) {
|
||
// Not a host artifact and never produced by any hook.
|
||
errors.push(
|
||
prefix + ' step at point "' + step.point + '" consumes "' + artifact +
|
||
'" which is never produced by any host artifact or capability hook',
|
||
);
|
||
continue;
|
||
}
|
||
|
||
// Find any non-self producer at pointIdx <= stepPointIdx.
|
||
const otherEarliestIdx = producers.reduce((best, p) => {
|
||
const isSelf = p.capId === capId && p.stepIdx === si;
|
||
if (isSelf) return best;
|
||
return (best === undefined || p.pointIdx < best) ? p.pointIdx : best;
|
||
}, undefined);
|
||
|
||
if (otherEarliestIdx === undefined) {
|
||
// Only producer is this step itself — self-consume violation.
|
||
errors.push(
|
||
prefix + ' step at point "' + step.point + '" consumes "' + artifact +
|
||
'" which is only produced by this step itself (a step cannot consume its own output)',
|
||
);
|
||
} else if (otherEarliestIdx > stepPointIdx) {
|
||
errors.push(
|
||
prefix + ' step at point "' + step.point + '" consumes "' + artifact +
|
||
'" which is only produced after this point (earliest available at POINT_ORDER index ' +
|
||
otherEarliestIdx + ' = "' + POINT_ORDER[otherEarliestIdx] + '")',
|
||
);
|
||
}
|
||
// else: satisfied by another cap/step at an earlier-or-same point — OK.
|
||
}
|
||
}
|
||
}
|
||
|
||
return errors;
|
||
}
|
||
|
||
// ─── Cross-capability invariants ──────────────────────────────────────────────
|
||
|
||
const TIER_RANK = { core: 0, standard: 1, full: 2 };
|
||
|
||
/**
|
||
* Enforce cross-capability invariants.
|
||
*
|
||
* @param {Map<string, object>} capMap id → validated capability object
|
||
* @param {Set<string>} centralKeys Set of keys in the central config-schema
|
||
* @returns {string[]} Array of error strings; empty = all pass.
|
||
*/
|
||
function validateCrossCapability(capMap, centralKeys, centralPatterns = []) {
|
||
const errors = [];
|
||
|
||
// Ownership: one owner per skill stem + agent name
|
||
const skillOwner = new Map(); // skill → capId
|
||
const agentOwner = new Map(); // agent → capId
|
||
const familyOwner = new Map(); // command family → capId (ADR-959)
|
||
for (const [capId, cap] of capMap) {
|
||
if (cap.role !== 'feature') continue;
|
||
for (const skill of cap.skills) {
|
||
if (skillOwner.has(skill)) {
|
||
errors.push(
|
||
'skill "' + skill + '" is owned by both "' + skillOwner.get(skill) + '" and "' + capId + '"',
|
||
);
|
||
} else {
|
||
skillOwner.set(skill, capId);
|
||
}
|
||
}
|
||
for (const agent of cap.agents) {
|
||
if (agentOwner.has(agent)) {
|
||
errors.push(
|
||
'agent "' + agent + '" is owned by both "' + agentOwner.get(agent) + '" and "' + capId + '"',
|
||
);
|
||
} else {
|
||
agentOwner.set(agent, capId);
|
||
}
|
||
}
|
||
// ADR-959: single family ownership across the whole registry
|
||
if (Array.isArray(cap.commands)) {
|
||
for (const cmd of cap.commands) {
|
||
if (typeof cmd.family !== 'string' || cmd.family.length === 0) continue; // already reported
|
||
if (cmd.family === '__proto__' || cmd.family === 'constructor' || cmd.family === 'prototype') continue;
|
||
if (familyOwner.has(cmd.family)) {
|
||
errors.push(
|
||
'command family "' + cmd.family + '" is owned by both "' + familyOwner.get(cmd.family) + '" and "' + capId + '"',
|
||
);
|
||
} else {
|
||
familyOwner.set(cmd.family, capId);
|
||
}
|
||
}
|
||
}
|
||
}
|
||
|
||
// Config key ownership: exclusive AND absent from central schema.
|
||
//
|
||
// ADR-2782 D1/D9: the role filter was `role !== 'feature'`, which silently
|
||
// exempted every non-feature capability from ownership AND from the
|
||
// central-schema collision check — the reason reviewer config keys were
|
||
// stranded centrally. Ownership is a property of DECLARING a config slice, not
|
||
// of being a feature, so the filter is now purely on the slice's presence.
|
||
// Verified inert at introduction: no shipped capability declares `config` on a
|
||
// non-feature role, so this widening changes no existing key — it stops a
|
||
// latent silent drop and unblocks Phase 4 (#2797).
|
||
const configKeyOwner = new Map(); // key → capId
|
||
for (const [capId, cap] of capMap) {
|
||
if (typeof cap.config !== 'object' || cap.config === null) continue;
|
||
for (const key of Object.keys(cap.config)) {
|
||
if (configKeyOwner.has(key)) {
|
||
errors.push(
|
||
'config key "' + key + '" is owned by both "' + configKeyOwner.get(key) + '" and "' + capId + '"',
|
||
);
|
||
} else {
|
||
configKeyOwner.set(key, capId);
|
||
}
|
||
if (centralKeys.has(key)) {
|
||
errors.push(
|
||
'config key "' + key + '" is declared in capability "' + capId +
|
||
'" AND exists in the central config-schema — migration mid-flight: ' +
|
||
'remove from central config-schema before adding to the capability',
|
||
);
|
||
}
|
||
// #2797: exact-key membership is not the whole central schema. A key may
|
||
// also be claimed by a central DYNAMIC PATTERN, and until now that
|
||
// collision was invisible here — `centralKeys` is built from
|
||
// `manifest.validKeys` alone.
|
||
//
|
||
// Why that mattered enough to fix rather than note: `isCentralConfigKey`
|
||
// DOES consult the patterns, and `mergeFederatedConfig` skips every key
|
||
// for which it returns true. So a federated slice overlapping a central
|
||
// pattern is INERT — it carries no traffic — while the build stays green.
|
||
// Two of the four key families Phase 4 migrates (`review.models.<slug>`
|
||
// and `review.max_prompt_tokens_per_reviewer.<slug>`) were pattern-backed,
|
||
// so the invariant was blind to exactly the migration it exists to police.
|
||
const collidingPattern = centralPatterns.find((p) => p.test(key));
|
||
if (collidingPattern) {
|
||
errors.push(
|
||
'config key "' + key + '" is declared in capability "' + capId +
|
||
'" AND is matched by central config-schema pattern /' + collidingPattern.source +
|
||
'/ — the federated slice would be inert (mergeFederatedConfig skips central keys): ' +
|
||
'remove the pattern from the central config-schema in the SAME commit',
|
||
);
|
||
}
|
||
}
|
||
}
|
||
|
||
// ── Reviewer lane uniqueness (ADR-2782 D8) ─────────────────────────────────
|
||
//
|
||
// slug, every flag, and reviewsSection are each unique across the MERGED
|
||
// first-party ∪ overlay set. reviewsSection uniqueness is not cosmetic: two
|
||
// lanes sharing a heading silently merge their output in REVIEWS.md, producing
|
||
// a review that appears to have consensus it does not have.
|
||
//
|
||
// This runs in validateCrossCapability rather than in the generator because
|
||
// BOTH callers reach it: the build-time generator over first-party, and
|
||
// capability-loader's loadRegistry over `acceptedMap` (first-party ∪ accepted
|
||
// overlays) per candidate. First-party is already in the map when an overlay
|
||
// candidate is added, so the OVERLAY is the collider that gets dropped —
|
||
// which is exactly D8's "first-party wins", with no provenance check here.
|
||
//
|
||
// Reviewer INSTANCES (review.reviewer_instances.<name>, ADR-1517) resolve
|
||
// THROUGH a lane and are not lanes; they never enter these sets.
|
||
const laneSlugClaims = new Map(); // slug → capId[]
|
||
const laneFlagClaims = new Map(); // flag → capId[]
|
||
const laneSectionClaims = new Map(); // reviewsSection → capId[]
|
||
// ADR-3646: task-content resolver tracker-prefix uniqueness across the
|
||
// MERGED first-party ∪ overlay set, mirroring the reviewer-lane collision
|
||
// pattern above — two resolvers claiming the same prefix would make
|
||
// `execute:task` dispatch ambiguous (which capability's resolver runs?).
|
||
const trackerPrefixClaims = new Map(); // trackerPrefix → capId[]
|
||
|
||
// Claims are ACCUMULATED and reported after the sweep, never reported on the
|
||
// second claimant. Reporting pairwise-on-collision looks equivalent and is not:
|
||
// with three lanes on one key it names whichever pair happened to arrive first,
|
||
// so the message text depends on Map insertion order — which is readdir order
|
||
// at build time and candidate order at load time. A cross-platform CI lane
|
||
// would then disagree with a local run about the text of the same failure.
|
||
// Accumulating makes the output a pure function of the input set for ANY N.
|
||
const claim = (claims, key, capId) => {
|
||
if (typeof key !== 'string' || key.length === 0) return;
|
||
if (isReservedName(key)) return;
|
||
let claimants = claims.get(key);
|
||
if (claimants === undefined) {
|
||
claimants = [];
|
||
claims.set(key, claimants);
|
||
}
|
||
if (!claimants.includes(capId)) claimants.push(capId);
|
||
};
|
||
|
||
for (const [capId, cap] of capMap) {
|
||
// ADR-3646: a MALFORMED taskContentResolver body was already reported by
|
||
// validateCapability — do not double-report; only claim well-shaped
|
||
// bodies. Independent of the reviewer-lane checks below, so it runs even
|
||
// for capabilities that carry no `reviewer` body at all.
|
||
const tcr = cap.taskContentResolver;
|
||
if (typeof tcr === 'object' && tcr !== null && !Array.isArray(tcr)) {
|
||
claim(trackerPrefixClaims, tcr.trackerPrefix, capId);
|
||
}
|
||
|
||
const r = cap.reviewer;
|
||
// A capability with no lane contributes to no uniqueness set. A MALFORMED
|
||
// body was already reported by validateCapability — do not double-report.
|
||
if (typeof r !== 'object' || r === null || Array.isArray(r)) continue;
|
||
claim(laneSlugClaims, r.slug, capId);
|
||
claim(laneSectionClaims, r.reviewsSection, capId);
|
||
if (Array.isArray(r.flags)) {
|
||
// Flattened across arrays: Antigravity answers to --antigravity AND --agy,
|
||
// so uniqueness is per-flag, not per-lane.
|
||
for (const flag of r.flags) claim(laneFlagClaims, flag, capId);
|
||
}
|
||
}
|
||
|
||
// One error per colliding key naming EVERY claimant, ids sorted; the whole
|
||
// block is sorted before it is appended, so both the messages and their order
|
||
// are independent of how the capabilities were enumerated.
|
||
const laneCollisions = [];
|
||
for (const [claims, label] of [
|
||
[laneSlugClaims, 'slug'],
|
||
[laneFlagClaims, 'flag'],
|
||
[laneSectionClaims, 'reviewsSection'],
|
||
[trackerPrefixClaims, 'taskContentResolver.trackerPrefix'],
|
||
]) {
|
||
for (const [key, claimants] of claims) {
|
||
if (claimants.length < 2) continue;
|
||
laneCollisions.push(
|
||
'reviewer ' + label + ' "' + key + '" is declared by ' +
|
||
[...claimants].sort().map((i) => '"' + i + '"').join(' and '),
|
||
);
|
||
}
|
||
}
|
||
laneCollisions.sort();
|
||
errors.push(...laneCollisions);
|
||
|
||
// requires: all ids exist
|
||
for (const [capId, cap] of capMap) {
|
||
if (!Array.isArray(cap.requires)) continue;
|
||
for (const req of cap.requires) {
|
||
if (!capMap.has(req)) {
|
||
errors.push(
|
||
'capability "' + capId + '" requires "' + req + '" which does not exist',
|
||
);
|
||
}
|
||
}
|
||
}
|
||
|
||
// runtimeCompat: explicit runtime ids must reference runtime capabilities.
|
||
// The wildcard "*" means descriptor-backed runtimes are supported by default.
|
||
const runtimeIds = new Set();
|
||
for (const [id, cap] of capMap) {
|
||
if (cap.role === 'runtime') runtimeIds.add(id);
|
||
}
|
||
for (const [capId, cap] of capMap) {
|
||
if (cap.role !== 'feature' || typeof cap.runtimeCompat !== 'object' || cap.runtimeCompat === null) continue;
|
||
for (const field of ['supported', 'unsupported']) {
|
||
const entries = Array.isArray(cap.runtimeCompat[field]) ? cap.runtimeCompat[field] : [];
|
||
for (const runtimeId of entries) {
|
||
if (runtimeId === RUNTIME_COMPAT_WILDCARD) continue;
|
||
if (typeof runtimeId !== 'string' || runtimeId.length === 0) continue;
|
||
if (!runtimeIds.has(runtimeId)) {
|
||
errors.push(
|
||
'capability "' + capId + '" runtimeCompat.' + field +
|
||
' references unknown runtime "' + runtimeId + '"',
|
||
);
|
||
}
|
||
}
|
||
}
|
||
if (cap.runtimeCompat.notes && typeof cap.runtimeCompat.notes === 'object') {
|
||
for (const runtimeId of Object.keys(cap.runtimeCompat.notes)) {
|
||
if (runtimeId === RUNTIME_COMPAT_WILDCARD) continue;
|
||
if (!runtimeIds.has(runtimeId)) {
|
||
errors.push(
|
||
'capability "' + capId + '" runtimeCompat.notes references unknown runtime "' + runtimeId + '"',
|
||
);
|
||
}
|
||
}
|
||
}
|
||
}
|
||
|
||
// requires: acyclic
|
||
const cycleErrors = detectRequiresCycles(capMap);
|
||
errors.push(...cycleErrors);
|
||
|
||
// requires: tier-monotone (core may not require standard/full; standard may not require full)
|
||
for (const [capId, cap] of capMap) {
|
||
if (!Array.isArray(cap.requires) || !VALID_TIERS.has(cap.tier)) continue;
|
||
const myRank = TIER_RANK[cap.tier];
|
||
for (const req of cap.requires) {
|
||
const reqCap = capMap.get(req);
|
||
if (!reqCap || !VALID_TIERS.has(reqCap.tier)) continue;
|
||
const reqRank = TIER_RANK[reqCap.tier];
|
||
if (reqRank > myRank) {
|
||
errors.push(
|
||
'tier-monotone violation: capability "' + capId + '" (tier: ' + cap.tier +
|
||
') requires "' + req + '" (tier: ' + reqCap.tier +
|
||
') — a capability may not require a higher-tier capability',
|
||
);
|
||
}
|
||
}
|
||
}
|
||
|
||
return errors;
|
||
}
|
||
|
||
/**
|
||
* Detect cycles in the requires graph using DFS.
|
||
*/
|
||
function detectRequiresCycles(capMap) {
|
||
const errors = [];
|
||
const WHITE = 0, GRAY = 1, BLACK = 2;
|
||
const color = new Map([...capMap.keys()].map((k) => [k, WHITE]));
|
||
|
||
function dfs(id, stack) {
|
||
if (color.get(id) === GRAY) {
|
||
const cycleStr = [...stack, id].join(' → ');
|
||
errors.push('requires cycle detected: ' + cycleStr);
|
||
return;
|
||
}
|
||
if (color.get(id) === BLACK) return;
|
||
color.set(id, GRAY);
|
||
stack.push(id);
|
||
const cap = capMap.get(id);
|
||
if (cap && Array.isArray(cap.requires)) {
|
||
for (const req of cap.requires) {
|
||
if (capMap.has(req)) dfs(req, stack);
|
||
}
|
||
}
|
||
stack.pop();
|
||
color.set(id, BLACK);
|
||
}
|
||
|
||
for (const id of capMap.keys()) {
|
||
if (color.get(id) === WHITE) dfs(id, []);
|
||
}
|
||
|
||
return errors;
|
||
}
|
||
|
||
// ─── requiresClosure ─────────────────────────────────────────────────────────
|
||
|
||
/**
|
||
* Compute the transitive requires closure for a capability id.
|
||
* Returns a Set<string> of all transitively required capability ids.
|
||
*
|
||
* @param {string} id
|
||
* @param {Map<string, object>} capMap
|
||
*/
|
||
function computeRequiresClosure(id, capMap) {
|
||
const visited = new Set();
|
||
const queue = [id];
|
||
while (queue.length > 0) {
|
||
const current = queue.shift();
|
||
const cap = capMap.get(current);
|
||
if (!cap || !Array.isArray(cap.requires)) continue;
|
||
for (const req of cap.requires) {
|
||
if (!visited.has(req)) {
|
||
visited.add(req);
|
||
queue.push(req);
|
||
}
|
||
}
|
||
}
|
||
return visited;
|
||
}
|
||
|
||
// ─── Topological ordering ─────────────────────────────────────────────────────
|
||
|
||
function topoSortHookEntries(entries, hookKey, hookKind) {
|
||
if (entries.length <= 1) return entries;
|
||
|
||
// Build adjacency: entry A must come before entry B if B consumes something A produces
|
||
const n = entries.length;
|
||
const inDegree = new Array(n).fill(0);
|
||
const adj = Array.from({ length: n }, () => []);
|
||
|
||
for (let i = 0; i < n; i++) {
|
||
const producesI = new Set(entries[i][hookKey].produces || []);
|
||
for (let j = 0; j < n; j++) {
|
||
if (i === j) continue;
|
||
const consumesJ = entries[j][hookKey].consumes || [];
|
||
for (const artifact of consumesJ) {
|
||
if (producesI.has(artifact)) {
|
||
adj[i].push(j);
|
||
inDegree[j]++;
|
||
break;
|
||
}
|
||
}
|
||
}
|
||
}
|
||
|
||
// Kahn's algorithm with stable tiebreak on capId
|
||
const queue = [];
|
||
for (let i = 0; i < n; i++) {
|
||
if (inDegree[i] === 0) queue.push(i);
|
||
}
|
||
// Sort queue by capId for determinism
|
||
queue.sort((a, b) => entries[a].capId.localeCompare(entries[b].capId));
|
||
|
||
const result = [];
|
||
while (queue.length > 0) {
|
||
// Take the first (sorted) ready node
|
||
const idx = queue.shift();
|
||
result.push(entries[idx]);
|
||
const newReady = [];
|
||
for (const neighbor of adj[idx]) {
|
||
inDegree[neighbor]--;
|
||
if (inDegree[neighbor] === 0) newReady.push(neighbor);
|
||
}
|
||
newReady.sort((a, b) => entries[a].capId.localeCompare(entries[b].capId));
|
||
queue.push(...newReady);
|
||
}
|
||
|
||
// Fix #2: if result.length < n, Kahn's could not complete — there is a produces/consumes
|
||
// cycle. Do NOT silently fall back to declaration order; throw a clear error.
|
||
if (result.length < n) {
|
||
const sortedIds = entries.map((e) => e.capId).join(', ');
|
||
throw new Error(
|
||
'produces/consumes cycle detected in ' + hookKind + ' at point "' +
|
||
(entries[0] && entries[0][hookKey] ? entries[0][hookKey].point : '?') +
|
||
'" among capabilities [' + sortedIds + ']: ' +
|
||
'a cycle in hook produces/consumes prevents deterministic ordering',
|
||
);
|
||
}
|
||
return result;
|
||
}
|
||
|
||
/**
|
||
* Topologically sort steps at a given point by produces/consumes.
|
||
* Capability-id tiebreak for determinism.
|
||
*
|
||
* @param {{ capId: string, step: object }[]} entries
|
||
* @returns {{ capId: string, step: object }[]}
|
||
*/
|
||
function topoSortSteps(entries) {
|
||
return topoSortHookEntries(entries, 'step', 'steps');
|
||
}
|
||
|
||
function topoSortContributions(entries) {
|
||
return topoSortHookEntries(entries, 'contrib', 'contributions');
|
||
}
|
||
|
||
// ─── Gen-time wired guard ─────────────────────────────────────────────────────
|
||
|
||
/**
|
||
* Hook group (capability.json array name) → hook kind (dispatch discriminator).
|
||
* Single source of truth for both validateHooksWired and the scanner-parity
|
||
* test in tests/capability-registry.test.cjs (#3606).
|
||
*/
|
||
const HOOK_GROUP_KINDS = Object.freeze({
|
||
steps: 'step',
|
||
contributions: 'contribution',
|
||
gates: 'gate',
|
||
});
|
||
|
||
/**
|
||
* Validate that every hook point declared by a capability has a corresponding
|
||
* `loop render-hooks <point>` call site in one of the host-loop workflow files,
|
||
* AND — #3606 — that the call site's dispatch text covers the hook's KIND.
|
||
*
|
||
* A call site proves hooks are rendered, not dispatched: a consumer that
|
||
* iterates only `kind == "gate"` (or narrows `kind == "step"` to one
|
||
* `ref.skill`) silently drops every other registered kind — a capability can
|
||
* be wired, enabled, resolved active, and never run. See
|
||
* gsd-core/references/loop-hook-dispatch.md ("A point whose workflow
|
||
* hand-rolls one kind does not implement this contract").
|
||
*
|
||
* Only valid loop points (in VALID_LOOP_POINTS) are checked here. Invalid points
|
||
* are already caught by validateStep/validateContribution/validateGate — do not
|
||
* double-report.
|
||
*
|
||
* KNOWN LIMITATION (#3606): coverage is the UNION across all call sites for a
|
||
* point in HOST_LOOP_FILES. Quick's plan:pre planner contribution seam has an
|
||
* additional generator-owned per-file check. Other consumers outside that
|
||
* universe (autonomous.md, code-review*.md, audit-milestone.md,
|
||
* secure-phase.md, validate-phase.md) are not per-file checked — a narrowed
|
||
* consumer there passes as long as one host file covers the point. More
|
||
* per-file coverage maps are the tightening path.
|
||
*
|
||
* @param {object} cap Validated capability object.
|
||
* @param {Map<string, Set<string>>} wiredKinds Per point, the hook kinds the
|
||
* host workflows' call-site dispatch text covers (getWiredKinds). A point
|
||
* absent from the map is unwired.
|
||
* @returns {string[]} Array of error strings; empty means all points
|
||
* are wired and every registered kind is covered.
|
||
*/
|
||
function validateHooksWired(cap, wiredKinds) {
|
||
const errors = [];
|
||
const capId = cap.id || '(unknown)';
|
||
|
||
function checkPoint(point, groupName, kind, idx) {
|
||
// Only flag valid points that are unwired — invalid points are schema-validator's job.
|
||
if (!VALID_LOOP_POINTS.has(point)) return;
|
||
if (!wiredKinds.has(point)) {
|
||
errors.push(
|
||
'capability "' + capId + '" ' + groupName + '[' + idx + '].point "' + point +
|
||
'" is declared but not wired in any host-loop workflow ' +
|
||
'(no `loop render-hooks ' + point + '` call site). ' +
|
||
'Wire the call site in the host workflow ' +
|
||
'(see scripts/gen-loop-host-contract.cjs STEP_WORKFLOWS) or remove the hook.',
|
||
);
|
||
return;
|
||
}
|
||
const covered = wiredKinds.get(point);
|
||
if (covered.size === 0) {
|
||
errors.push(
|
||
'capability "' + capId + '" ' + groupName + '[' + idx + '].point "' + point +
|
||
'" has `loop render-hooks ' + point + '` call site(s), but their dispatch text covers NO ' +
|
||
'hook kind — every consumer is narrowed to specific hooks. Dispatch every registered kind ' +
|
||
'per gsd-core/references/loop-hook-dispatch.md.',
|
||
);
|
||
return;
|
||
}
|
||
if (!covered.has(kind)) {
|
||
errors.push(
|
||
'capability "' + capId + '" ' + groupName + '[' + idx + '].point "' + point +
|
||
'" registers a ' + kind + ' hook, but the host call site\'s dispatch text never ' +
|
||
'covers `kind == "' + kind + '"` (it covers: ' + [...covered].sort().join(', ') + '). ' +
|
||
'A hand-rolled single-kind consumer silently never dispatches the other kinds — ' +
|
||
'dispatch every registered kind per gsd-core/references/loop-hook-dispatch.md.',
|
||
);
|
||
}
|
||
}
|
||
|
||
for (const [group, kind] of Object.entries(HOOK_GROUP_KINDS)) {
|
||
for (let i = 0; i < (cap[group] || []).length; i++) {
|
||
const hook = cap[group][i];
|
||
if (hook.point !== undefined) checkPoint(hook.point, group, kind, i);
|
||
}
|
||
}
|
||
|
||
return errors;
|
||
}
|
||
|
||
// ─── classifyCrossErrors ──────────────────────────────────────────────────────
|
||
|
||
/**
|
||
* Fix #3: Emit pending-migration WARNINGs for config keys that collide with the central
|
||
* config-schema. Per ADR-894 staged cutover, a collision during the registry-only phase is
|
||
* NOT a hard error — the capability pipeline is being established before the atomic cutover
|
||
* PR for each feature. The registry still generates; the warning tells the maintainer which
|
||
* keys need to be moved out of the central schema at cutover time.
|
||
*
|
||
* A NEW unexpected collision (a key that shouldn't be in both) is also surfaced — the
|
||
* maintainer sees it in build output rather than it being silently swallowed.
|
||
*
|
||
* Reference: ADR-894 §4 "config-key ownership exclusive AND complete — presence in both =
|
||
* collision = a mid-flight migration; finish the move."
|
||
*
|
||
* @param {string[]} crossErrors Errors from validateCrossCapability (may include collision msgs)
|
||
* @returns {{ hardErrors: string[], pendingMigrationWarnings: string[] }}
|
||
*/
|
||
function classifyCrossErrors(crossErrors) {
|
||
const hardErrors = [];
|
||
const pendingMigrationWarnings = [];
|
||
const collisionRe = /config key "([^"]+)" is declared in capability "([^"]+)" AND exists in the central config-schema/;
|
||
|
||
for (const e of crossErrors) {
|
||
const m = collisionRe.exec(e);
|
||
if (m) {
|
||
// Collision = pending-migration warning, not a hard error during 3a-impl staged cutover
|
||
pendingMigrationWarnings.push(
|
||
'⚠ pending-migration: capability \'' + m[2] + '\' declares config key \'' + m[1] +
|
||
'\' still present in central config-schema; finish the move at cutover',
|
||
);
|
||
} else {
|
||
hardErrors.push(e);
|
||
}
|
||
}
|
||
return { hardErrors, pendingMigrationWarnings };
|
||
}
|
||
|
||
// ─── ADR-857 phase 5e: configFormat ↔ installSurface parity gate ─────────────
|
||
|
||
// Map: installSurface → expected configFormat
|
||
// Derived from the pairing of capability.json descriptors (installSurface)
|
||
// and capability.json descriptors (configFormat). DEFECT.GENERATIVE-FIX: this map
|
||
// is the single parity contract between the two generated surfaces.
|
||
// NOTE: both values come from the descriptor bodies in capMap — no dependency on
|
||
// runtime-config-adapter-registry.cjs, which now requires capability-registry.cjs
|
||
// (the file this gen-script produces), and thus must not be required here.
|
||
const INSTALL_SURFACE_TO_CONFIG_FORMAT = new Map([
|
||
['settings-json', 'settings-json'],
|
||
['codex-toml', 'toml'],
|
||
['copilot-instructions', 'markdown'],
|
||
['cline-rules', 'markdown-dir'],
|
||
['cursor-hooks-json', 'none'],
|
||
['profile-marker-only', 'none'],
|
||
// 'none' added #2103 — a runtime with NO CLI install surface at all (e.g.
|
||
// VS Code) has no config-file format to write either.
|
||
['none', 'none'],
|
||
]);
|
||
|
||
/**
|
||
* ADR-857 phase 5e: configFormat ↔ installSurface parity gate.
|
||
*
|
||
* For each runtime capability that has an installSurface in its descriptor,
|
||
* assert that its configFormat matches the expected value derived from its
|
||
* installSurface. Both values are read directly from the capMap descriptor
|
||
* bodies — no dependency on runtime-config-adapter-registry.cjs.
|
||
*
|
||
* HARD gate — throws on mismatch (DEFECT.GENERATIVE-FIX: this invariant is
|
||
* derived from two parallel generated surfaces and must fail loudly).
|
||
*
|
||
* @param {Map<string, object>} capMap Fully-validated capability map.
|
||
* @returns {void} Throws on mismatch; returns normally on success.
|
||
*/
|
||
function runConfigFormatParityGate(capMap) {
|
||
// Read installSurface directly from the descriptor bodies already loaded into
|
||
// capMap — eliminates the require cycle introduced when adapter-registry was
|
||
// changed to require capability-registry.cjs (ADR-857 phase 5g drive 2).
|
||
for (const [capId, cap] of capMap) {
|
||
if (cap.role !== 'runtime') continue;
|
||
|
||
const r = cap.runtime;
|
||
if (!r || typeof r.configFormat !== 'string') continue; // already validated above
|
||
|
||
// Only check runtimes that have an installSurface (i.e. are config-adapter runtimes)
|
||
if (typeof r.installSurface !== 'string') continue; // grok etc. excluded — no installSurface
|
||
|
||
const installSurface = r.installSurface;
|
||
const expectedConfigFormat = INSTALL_SURFACE_TO_CONFIG_FORMAT.get(installSurface);
|
||
|
||
if (expectedConfigFormat === undefined) {
|
||
// Unknown installSurface — the mapping needs to be updated
|
||
throw new Error(
|
||
'configFormat parity gate: runtime "' + capId + '" has installSurface "' + installSurface +
|
||
'" which is not in the INSTALL_SURFACE_TO_CONFIG_FORMAT mapping — ' +
|
||
'update the mapping in scripts/gen-capability-registry.cjs',
|
||
);
|
||
}
|
||
|
||
if (r.configFormat !== expectedConfigFormat) {
|
||
throw new Error(
|
||
'configFormat parity gate FAILED for runtime "' + capId + '":\n' +
|
||
' installSurface: ' + installSurface + '\n' +
|
||
' expected configFormat: ' + expectedConfigFormat + '\n' +
|
||
' actual configFormat: ' + r.configFormat + '\n' +
|
||
'The capability.json configFormat must match the value derived from installSurface ' +
|
||
'(src: scripts/gen-capability-registry.cjs INSTALL_SURFACE_TO_CONFIG_FORMAT)',
|
||
);
|
||
}
|
||
}
|
||
}
|
||
|
||
// ─── Exports ──────────────────────────────────────────────────────────────────
|
||
|
||
module.exports = {
|
||
// Constants
|
||
SCHEMA_VERSION,
|
||
POINT_ORDER,
|
||
HOST_ARTIFACT_EARLIEST_POINT_IDX,
|
||
VALID_LOOP_POINTS,
|
||
POINT_TO_CONTRACT,
|
||
VALID_CONFIG_SLICE_TYPES,
|
||
KEBAB_RE,
|
||
VALID_ROLES,
|
||
VALID_TIERS,
|
||
VALID_ON_ERROR,
|
||
RUNTIME_COMPAT_WILDCARD,
|
||
SEMVER_RE,
|
||
SEMVER_RANGE_RE,
|
||
SHA512_INTEGRITY_RE,
|
||
VALID_CONVERTER_NAMES,
|
||
VALID_CONFIG_FORMATS,
|
||
VALID_CONFIG_HOME_KINDS,
|
||
VALID_COMMAND_STYLES,
|
||
VALID_HOOKS_SURFACES,
|
||
VALID_HOOK_EVENTS,
|
||
VALID_EXTENSION_EVENTS,
|
||
VALID_SANDBOX_TIERS,
|
||
VALID_ARTIFACT_KIND_NAMES,
|
||
VALID_ARTIFACT_NESTINGS,
|
||
VALID_TRIGGER_PRECEDENCE_KINDS,
|
||
DEFAULT_TRIGGER_PRECEDENCE,
|
||
FEATURE_FIELDS_FORBIDDEN_ON_RUNTIME,
|
||
// ADR-2782 D1/D2/D3/D6/D7/D8 — reviewer lane body
|
||
FEATURE_FIELDS_FORBIDDEN_ON_REVIEWER,
|
||
LANE_SLUG_RE,
|
||
LANE_FLAG_RE,
|
||
VALID_LANE_TRANSPORTS,
|
||
VALID_LANE_PROBE_KINDS,
|
||
VALID_PROMPT_CHANNELS,
|
||
VALID_OUTPUT_CHANNELS,
|
||
VALID_LANE_EFFORT_CHANNELS,
|
||
VALID_MODEL_DISCOVERY,
|
||
VALID_EMPTY_OUTPUT,
|
||
VALID_EVIDENCE_CLASSES,
|
||
VALID_LANE_HANDLERS,
|
||
KNOWN_REVIEWER_FIELDS,
|
||
KNOWN_HOST_BEHAVIORS,
|
||
MAX_REPORTED_UNKNOWN_KEYS,
|
||
MAX_REPORTED_KEY_CHARS,
|
||
validateReviewerBody,
|
||
collectReviewerWarnings,
|
||
collectReviewerWarningRecords,
|
||
REVIEWER_WARNING,
|
||
REMOVED_REVIEWER_CLI_FIELD,
|
||
VALID_INSTALL_SURFACES,
|
||
VALID_PERMISSION_WRITERS,
|
||
VALID_EXTENDED_HOOK_EVENTS,
|
||
VALID_EMBEDDING_MODES,
|
||
VALID_COMMAND_SURFACES,
|
||
VALID_MODEL_MODES,
|
||
VALID_HOOK_BUSES,
|
||
VALID_STATE_IO,
|
||
VALID_TRANSPORTS,
|
||
VALID_HOST_RUNTIMES,
|
||
VALID_SUBAGENT_TOOLKITS,
|
||
VALID_DISPATCH_ISOLATION,
|
||
_HOST_INTEGRATION_VOCAB: {
|
||
embeddingMode: [...VALID_EMBEDDING_MODES],
|
||
commandSurface: [...VALID_COMMAND_SURFACES],
|
||
modelMode: [...VALID_MODEL_MODES],
|
||
hookBus: [...VALID_HOOK_BUSES],
|
||
stateIO: [...VALID_STATE_IO],
|
||
transport: [...VALID_TRANSPORTS],
|
||
runtime: [...VALID_HOST_RUNTIMES],
|
||
subagentToolkit: [...VALID_SUBAGENT_TOOLKITS],
|
||
effortSurface: [...VALID_EFFORT_SURFACES],
|
||
isolation: [...VALID_DISPATCH_ISOLATION],
|
||
},
|
||
INSTALL_SURFACE_TO_ALLOWED_HOOKS_SURFACES,
|
||
GEMINI_AGENT_EVENTS,
|
||
CLAUDE_FAMILY_EVENTS,
|
||
TIER_RANK,
|
||
INSTALL_SURFACE_TO_CONFIG_FORMAT,
|
||
// Functions
|
||
isPlausibleRange,
|
||
validateVersionEnvelope,
|
||
validateCapability,
|
||
validateCommandEntry,
|
||
validateRuntimeCompat,
|
||
validateFeatureBody,
|
||
validateTaskContentResolver,
|
||
validateConfigHome,
|
||
validateArtifactKindEntry,
|
||
validateArtifactLayout,
|
||
validateRuntimeBody,
|
||
materializeHookFragments,
|
||
validateFragment,
|
||
validateStep,
|
||
validateContribution,
|
||
validateGate,
|
||
validateAgainstContract,
|
||
validateConsumesGlobal,
|
||
validateCrossCapability,
|
||
detectRequiresCycles,
|
||
computeRequiresClosure,
|
||
topoSortHookEntries,
|
||
topoSortSteps,
|
||
topoSortContributions,
|
||
validateHooksWired,
|
||
HOOK_GROUP_KINDS,
|
||
validateConfigSliceEntry,
|
||
classifyCrossErrors,
|
||
runConfigFormatParityGate,
|
||
};
|