* test(#3897): failing-first coverage for §8.3 rungs 2-4 ADR-3473 §8.3 has four rungs; #3883/PR #3896 shipped the first. This pins the other three RED before any fix. Rung 2 — the install marker has four readers and resolveRuntime is not one. resolveRuntime resolves GSD_RUNTIME > config.runtime > 'claude' and reads no marker at all, while bin/install.js writes one (#2297) and FOUR hand-rolled readInstallRuntimeMarker copies exist: src/model-resolver.cts:65 (cached, with test seams), hooks/gsd-agent-isolation-guard.js:112, and TWICE in hooks/gsd-cursor-subagent-start.js at :346 and :355. Four copies of one rule. Fixtures and seam names mined from PR #3382 rather than re-derived; it implemented this rung and was closed "not on the merits". Rung 3 — the sandbox map, and the fallback that was the real defect. Measured across all 35 files in agents/, deriving workspace-write iff tools: declares Write or Edit: - all 11 CODEX_AGENT_SANDBOX entries derive to their mapped value exactly, zero disagreements — the map carries nothing the contract does not - 24 roles fall through `|| 'read-only'`, of which 16 declare Write or Edit So the map is redundant and the silent fallback is the defect. The maintainer chose to derive but hold those 16 at read-only pending the question of whether Codex enforces sandbox_mode or merely advises; HALT.md records it. T20 asserts the emitted sandbox_mode PER ROLE against a captured baseline, not in aggregate — an aggregate passes while one role silently widens, which is the proxy-instead-of-identity shape this repo names. T24 and T25 fail on a stale hold, so the hold list cannot rot into the subset map being deleted. Rung 4 — shortFormToId, recovered rather than invented. I nearly reported this as another wrong §8.3 claim: `git log -S shortFormToId` returns only documentation commits. That was the wrong instrument. Direct inspection of sdk/src/query/phase.ts at 11918dcc3^ shows five occurrences, and the tests match that code rather than a guess at its semantics — including first-write-wins on a duplicate short form. T43 asserts at the consumer's output: the emitted `waves` map from the real CLI, which pre-fix collapses to {"1":[...]} because every short-form edge is dropped. A unit assertion on resolveDependencyId would have passed throughout this defect's life. Observed RED, this tree: rung 2 11/11 fail — no marker rung, no seams rung 3 T23,T24,T25,T26,T30 fail; T28 fails (validate agents passes a TOML whose sandbox_mode disagrees — it checks presence only) rung 4 T42,T44 fail; T43,T49 fail with waves collapsed to a single wave 1 Green and staying green: T20/T21/T22/T27 as captured baselines, #3885's unresolvable-token warning and wave-verdict suppression, and #3785's display-mapping passthrough. If the third tier over-reaches, those go red — that is their job. Disclosed weakness: T45 (a canonical id with no dash is not short-form indexed) cannot be isolated behaviorally, because planMap always masks it. It is a non-crash boundary pin, weaker than the other rows, and is recorded as such rather than presented as equivalent. Design: .gsd/phase/feat-3897-adr3473-83-rungs/40-design.md Test matrix: .gsd/phase/feat-3897-adr3473-83-rungs/50-test-matrix.md Decision: .gsd/phase/feat-3897-adr3473-83-rungs/HALT.md Refs #3897 Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> * enhance(#3897): §8.3 rungs 2-4 — one marker reader, a derived sandbox, the third depends_on tier ADR-3473 §8.3 has four rungs. #3883/PR #3896 shipped the first. These are the other three. Rung 2 — the install marker had four readers, and resolveRuntime was not one. resolveRuntime resolved GSD_RUNTIME > config.runtime > 'claude' and read no marker, while bin/install.js writes one (#2297) and four hand-rolled readInstallRuntimeMarker copies existed: src/model-resolver.cts (cached, with seams), hooks/gsd-agent-isolation-guard.js, and twice in hooks/gsd-cursor-subagent-start.js. model-resolver's was already the house idiom, so it was promoted rather than replaced: src/runtime-slash.cts now owns it, and model-resolver plus both hooks delegate. The hooks reach it through ensureRuntimeBuild(), the seam lint-hooks-runtime-build-seam enforces. No import cycle existed - checked both directions before moving anything. The marker is the THIRD rung: env > project config > marker > 'claude'. N1 was checked rather than assumed, and my first reading of it was wrong. A marker holding an unknown name comes back essentially verbatim, which looked like a validation gap. Measured against the env rung with the same inputs - including "../../etc/passwd" and "claude;rm -rf /" - the two are identical, because they share resolveRuntimeNameFromCandidates. N1 asks for exactly that, and it is met. The residual (the shared normalizer normalizes shape, it does not validate against the known-runtime set) is pre-existing on the env rung and plausibly deliberate, since a new runtime should not need a code change. The marker also does not widen the trust boundary in any real sense: it lives inside the install tree beside the code, so anyone who can write it can write runtime-slash.cjs itself. Rung 3 — the map was redundant; the silent fallback was the defect. Measured across all 35 files in agents/, deriving workspace-write iff tools: declares Write or Edit: all 11 CODEX_AGENT_SANDBOX entries derive to their mapped value exactly, zero disagreements. The map carried nothing the contract did not already have, so it is DELETED rather than reconciled. What was actually broken is `|| 'read-only'`, which silently under-granted 24 of 35 roles. 16 of those 24 declare Write or Edit and would widen under derivation. Per the maintainer's decision (HALT.md), they are held at read-only pending the question of whether Codex enforces sandbox_mode or merely advises. Emitted TOML is therefore byte-identical for all 35 roles - asserted per role, not in aggregate, because an aggregate passes while one role silently widens. The hold list self-invalidates. A hold whose role no longer derives broader fails, and so does a hold naming a role with no agents/<name>.md. Without that it would rot into exactly the hand-maintained subset map being deleted, and this commit's own ledger claim would become false over time. Both cases were proved by injecting them and watching them throw. Two committed tests asserted the deleted map's existence and contents. They were pinning the thing being removed, so the tests moved rather than the production code: the 11 role-value pairs survive as a test-local PRE_3897_CODEX_AGENT_SANDBOX baseline, and the assertions now drive the real derivation against real agents/*.md. The coverage is preserved; only its source moved out of production code. validate agents gains checkCodexSandboxPosture, mirroring the existing checkCodexModelPosture: each installed TOML's sandbox_mode must equal the role's expected value, failing with role, expected and found. It previously checked file presence and manifest completeness only, so a TOML whose sandbox_mode disagreed passed. Rung 4 — shortFormToId, recovered rather than invented. I nearly reported this as another wrong §8.3 claim: git log -S returns only documentation commits. Wrong instrument. sdk/src/query/phase.ts at 11918dcc3^ carries five occurrences, and the implementation here matches that code rather than a guess at its semantics - including first-write-wins on a duplicate short form, deterministic from the sorted plan order. It resolves the bare plan number: depends_on: ["01"] now reaches 26-01-auth-hardening. That is a control-flow change, not a diagnostic one - plans that silently collapsed into a single wave 1 now execute in their declared waves, and execute-phase.md consumes those wave values. In-phase only, by construction: the map is built from this phase's rawPlans, so a same-named short form in another phase does not resolve. #3785's display-mapping passthrough and #3885's unresolvable-token warning and wave-verdict suppression are untouched and stay green. If the third tier had over-reached, those are what would have caught it. Refs #3897 Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> * fix(#3897): close a fail-open I introduced, and wire the posture check to its command Two blockers from review. Both are mine, and one is a security regression my own change created. 1. A held role could escape its hold by editing its own frontmatter. The Codex install loop set the sandbox identity from the agent's frontmatter `name:` field rather than from its filename, so the hold lookup keyed off a value the file itself declares: deriveCodexSandboxMode('gsd-doc-writer', <real file>) -> read-only deriveCodexSandboxMode('gsd-doc-writer-x', <same file, name: edited>) -> workspace-write deriveCodexSandboxMode('GSD-Doc-Writer', <same file, name: recased>) -> workspace-write What makes this a blocker rather than a nit is the DIRECTION. The deleted CODEX_AGENT_SANDBOX map had the identical lookup-key quirk, but it was an allowlist: an unmatched key fell back to read-only, which is safe. The new scheme derives workspace-write from the tool contract and uses the hold as a subtraction, so the same mismatch fails OPEN. I converted a fail-closed quirk into a fail-open one and did not notice; the isolated reviewer proved it by execution. Neither safety net caught it. validateCodexSandboxHolds only checks that <key>.md exists, never that a file's derived identity matches its key. checkCodexSandboxPosture looks the canonical source up by the installed TOML's filename, finds nothing for a renamed agent, and treats it as a custom non-roster agent — silently no violation. The identity is now the FILENAME STEM, which is what validateCodexSandboxHolds already validates and what an attacker editing frontmatter cannot change without renaming the file — at which point the existing validator catches it. The lookup is case-insensitive so a recase does not slip past either. The frontmatter name still drives the TOML body and filename, unchanged; only the sandbox identity moved. All 35 roster files were checked: name matches filename stem everywhere, so a stricter "they must agree or throw" invariant would have been safe against real content. It is deliberately NOT added — it would abort an install on a tampered file where emitting a correctly-derived read-only TOML is the safer outcome. Recorded as a fork rather than decided silently. 2. checkCodexSandboxPosture was exported and never called. cmdValidateAgents (src/verify.cts) called checkAgentsInstalled and checkCodexModelPosture only; grep for the sandbox check in that file returned nothing. So criterion 3 — "validate agents fails on semantic drift, not only on missing files" — was unmet, and `validate agents` behaved exactly as before. That is ADR-3473 Decision 2's named shape: a declared policy with no executor. It also meant the T28 test asserted at the helper's return value while the COMMAND stayed broken — the ADR-3180 Decision 4(b) failure this epic exists to close, committed by me while enforcing it elsewhere in the same epic. Now wired as an additive `sandbox_posture` field beside `codex_posture`, following the sibling precedent exactly. Drift is report-only, not a non-zero exit, because that is what checkCodexModelPosture does — two sibling posture checks disagreeing about whether a violation is fatal would be its own defect. The choice is recorded in a comment rather than left implicit. A consumer-output test now drives the real CLI and asserts on the emitted JSON, and was shown failing before the wiring and passing after. Also corrected a stale artifact: the design's Known limit L1 still claimed rung 3 was not in this deliverable, written while it was halted and false once the maintainer unblocked it. Verified after both fixes: the three bypass probes all return read-only, the per-role table is 35/35 byte-identical, and both hold self-invalidation cases still throw. Refs #3897 Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> * docs(#3897): the marker rung, the derived sandbox, and the bare plan-number depends_on Reference: the runtime precedence ladder in docs/CLI-TOOLS.md gains the install marker rung; docs/COMMANDS.md documents validate agents' new sandbox_posture field; docs/reference/plan-md.md documents that depends_on accepts the bare plan number. Explanation: a docs/features fragment keyed id 3897, so it cannot collide with a concurrent PR hand-allocating a section number, regenerated into FEATURES.md. ADR-3473 §8.3 gains an ANSWER blockquote in the document's own correction style, recording what was measured and built against the section's 2026-08-26 correction - including the qualification that checkAgentsInstalled itself still checks presence only, and the semantic assertion lives in a sibling wired into validate agents rather than folded into it. No how-to. Both user-visible changes are zero-step: a non-Claude install resolving its own runtime, and plans executing in their declared waves, both happen without the user doing anything. docs/how-to/control-the-reported-host-runtime.md covers a DIFFERENT ladder (resolveReportedRuntime / agent_runtime) that this change does not touch, and was deliberately left alone rather than edited by association. No tutorial - nothing multi-step to walk through. docs/AGENTS.md unchanged: it documents Claude-side tools frontmatter, never Codex sandbox_mode, and the emitted tools contract did not change. The prompt layer documents depends_on only by example, not by schema, so nothing there needed editing - and few-shot-examples/plan-checker.md already showed depends_on: ['01'], which now actually resolves. Translated copies of plan-md.md are untouched; the project treats translations as community-maintained. Refs #3897 Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> * fix(#3897): move the sandbox derivation out of the installer, off the install path, and off a third parser The full suite came back with 26 failures across four files. Three distinct causes, mapped individually rather than assuming the first explained the rest. A. Requiring bin/install.js printed the GSD banner to stdout and corrupted `validate agents` JSON. Unexpected token '', "[36m ██"... is not valid JSON checkCodexSandboxPosture reached deriveCodexSandboxMode by lazily requiring bin/install.js, whose module load prints the ASCII banner. So the command emitted banner bytes before its JSON and every JSON consumer broke, including ten tests that predate this branch. src/ reaching into bin/ was backwards layering that happened to also be loud. The derivation now lives in src/codex-agent-toml.cts - the existing Codex TOML domain module, no new module and no six-gate ripple - and both bin/install.js and src/agent-install-check.cts import it. One owner, which is §8.3's rule applied to the fix for §8.3. B. The stale-hold throw fired on a legitimate partial source dir, and masked a security assertion. validateCodexSandboxHolds treated "this hold's .md is absent from the install SOURCE dir" as a stale hold and threw. A test fixture, or any partial install source, legitimately contains a couple of agents. Worse, it threw BEFORE the path-escape check, so a test asserting that a `../../evil` frontmatter name is rejected got my unrelated error instead of the traversal rejection it was written for. A fail-closed check of mine was hiding a real security check. The "no stale holds, shrink-only" invariant is a property of the repo's canonical agents/ roster, not of whatever directory an install happens to read. It is off the runtime path and enforced where it belongs, in the tests that already existed for it. A partial source dir now installs cleanly, and the evil-name case throws with its own escapes-configHome message again. C. T8 depended on ambient process.env state. The marker/env parity assertion round-tripped through live process.env. It now compares against resolveExplicitRuntime's already-exported dependency-injection parameter - deterministic and hermetic, same claim. Proven still falsifiable rather than assumed: with the marker rung's normalization temporarily bypassed the two rungs diverge ("codex\n../../etc/passwd" vs "codex-../../etc/passwd") and the assertion fails, then passes again once reverted. One correction folded in along the way. The first version of the move added private _extractFrontmatterAndBody/_extractFrontmatterField helpers to codex-agent-toml.cts - a THIRD copy of frontmatter extraction, where the graph already shows two (bin/install.js:2348, runtime-artifact-conversion.cts:893). Adding a third inside the epic whose thesis is one implementation per rule is not defensible. deriveCodexSandboxMode no longer parses anything: it takes (identity, toolsValue) and each caller supplies the tools value using the extractor it already has. Both helpers are deleted. The identity argument is still the filename stem, so the fail-open fix is untouched. Verified after all three: `validate agents --raw` emits parseable JSON with no banner and both posture fields; the four hold-bypass probes still return read-only; the per-role table is 35/35 byte-identical at 26 read-only / 9 workspace-write; the hold list is still 16. Refs #3897 Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> * fix(#3897): drop a dev-only transitive dep, make the derivation total, retire a stale fallback test Suite down to 7 failures from 26. Three more causes, mapped individually. A. My extractor import dragged in a script that does not exist in an installed tree. Cannot find module '../../../scripts/fix-slash-commands.cjs' Chain: src/agent-install-check.cts imported runtime-artifact-conversion.cjs, which requires command-roster.cjs, whose line 36 requires ../../../scripts/fix-slash-commands.cjs. That path exists in the repo and not in an install, so every test exercising a synthetic install dir died at module load. I picked that extractor for convenience without checking what it pulls in - the same mistake that produced the banner bug, one layer further out. agent-install-check now uses a single-purpose extractToolsLine on codex-agent-toml.cts. That is deliberately NOT a general frontmatter parser: we deleted those helpers a commit ago for good reason, and this reads one line. Verified from outside the repo root that requiring either module prints nothing and does not throw. B. A test pinned the deleted name-based fallback. 'defaults unknown agents to read-only' called generateCodexAgentToml with a fixture declaring tools: Read, Write, Edit. Under derivation an unknown agent with a writing contract correctly derives workspace-write - design row S6, a new writing role gets the contract, not the pin. The behavior it asserted was the silent fallback this rung deleted; identity no longer decides the sandbox. Replaced with two rows rather than a flipped string: no tools declared -> read-only (absence is not a grant), and Write/Edit declared -> workspace-write. Strictly more coverage than the row it replaces. C. The stale-hold check still threw per derivation call. Last commit took the roster-existence check off the install path, but deriveCodexSandboxMode itself still threw when a hold's role did not derive broader FOR THE CONTENT IT WAS HANDED - so it fired on any synthetic fixture for a held role. The throw is gone, and it cost nothing: if a held role's content does not derive broader, the hold pins read-only and derivation returns read-only anyway, so the hold is a no-op and there is nothing to fail about. The staleness invariant is a property of the real agents/ roster, and validateCodexSandboxHolds still enforces it there - confirmed against the real roster after the change, not assumed. deriveCodexSandboxMode is now total: every (identity, toolsValue) including undefined and null returns read-only or workspace-write, never throws. Verified: validate agents emits parseable JSON; the four hold-bypass probes return read-only; the per-role table is 35/35 at 26 read-only / 9 workspace-write. Refs #3897 Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> * docs(#3897): put the rung-3 decision in the shipped docs instead of pointing at an ignored path The ADR entry and the feature fragment both ended their rung-3 explanation with "see .gsd/phase/feat-3897-adr3473-83-rungs/45-decision-rung3-sandbox.md". That directory is gitignored (.gitignore:55), so the rationale for holding 16 roles at read-only was reachable only from the machine that produced it. A reader of the ADR got a pointer to nothing. Both now carry the reasoning inline: the criterion asks both that the sandbox derive from the declared tool contract and that no role gain a broader sandbox, and those cannot both hold, because a faithful derivation widens 16 roles the deleted map never listed and that fell through its silent read-only default. The resolution is derive-and-hold - the derivation owns the rule now, each hold is released as its enforcement question is answered, and a hold is reversible where a widened sandbox that turns out to be enforced is not. Checked before assuming this was a defect class: CONTEXT.md cites .gsd/phase/<slug>/40-design.md as its standard Design: provenance line in eight module entries, and four other shipped docs do the same. Citing a phase artifact is an established convention here, so those are left alone. What was wrong was specific to these two: they put load-bearing rationale behind the pointer instead of provenance. docs/FEATURES.md regenerated from the fragment via scripts/gen-features.cjs rather than hand-edited. Refs #3897 Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> * fix(#3897): close a fail-open, stop a silent mis-resolution, and read a declaration as a declaration Two orthogonal reviews on the shipped sha. Three of the findings are the same failure class this epic exists to close, committed inside it. 1. BLOCKER - the sandbox was decided for one identity and applied to another. bin/install.js derived sandbox_mode for the filename stem and then wrote the result to `${name}.toml`, where name comes from the file's own frontmatter. Make the two disagree and a HELD role's artifact goes wide: rename gsd-doc-writer.md -> gsd-doc-writer-v2.md, keep name: gsd-doc-writer -> stem is unheld, derives workspace-write, lands on gsd-doc-writer.toml add any gsd-*.md whose frontmatter name: is a held role -> clobbers that role's toml with workspace-write Both emit read-only on origin/next, because the deleted map was an allowlist and a miss fell back safe. This is a regression my change introduced. The previous review round moved the HOLD KEY off frontmatter to the filename stem and left the OUTPUT PATH on frontmatter; my own comment at install.js:6985 calls that value attacker-editable, four lines above the line that uses it as the filename. The decision is now made over BOTH candidate identities, most-restrictive wins: if either the stem or the emitted name is held, the mode is read-only. 2. MAJOR - hold matching was toLowerCase() only, so confusables escaped. Turkish dotted/dotless i, fullwidth, NFD, trailing space/NBSP/dot/newline, ./ and ../agents/ all slipped the hold and emitted workspace-write. Identities are now basenamed, trimmed of NBSP/zero-width/control characters, NFKC-normalized and lowercased - and anything still carrying a character outside [a-z0-9._-] is treated as suspicious and derives read-only. We do not enumerate confusables; every shipped roster file is ASCII, so refusing to widen on an identity we cannot recognize is fail-closed with no false positives on real content. 3. MAJOR - the short-form depends_on tier mis-resolved SILENTLY. shortFormToId keyed on the last dash-segment of any canonical id with no constraint that it is a plan number, so a phase holding 09-FIX-auth-PLAN.md made depends_on: ["auth"] bind at wave 2 with zero warnings. This is the worst shape in the epic: the unresolvable-token warning fires on a DROPPED token, so a MIS-RESOLVED one is invisible and the tool reports a confident wave assignment built from a wrong edge. A wrong edge is worse than a missing one. The segment must now match /^\d+$/, which is exactly the contract docs/reference/plan-md.md already documents. This tier was recovered verbatim from the retired SDK lineage, which carried the same defect; we are deliberately NOT preserving it bug-for-bug, and the comment says so, so the next reader does not "restore" it. 4. MAJOR - the derivation was reading a declaration as an absence. extractToolsLine read one line, so a YAML list-form tools: block returned only its first item. Two roster files use list form, and gsd-nyquist-auditor declares Write and Edit there - parsed as "- Read", found no write tool, and emitted read-only. Rung 3's headline claim is that sandbox_mode derives from the declared tool contract; that claim was false for 2 of 35 roles and materially wrong for 1. Reading a declaration as an absence is the silent-drop class this epic exists to close. Renamed extractToolsValue and taught it both shapes. gsd-nyquist-auditor now derives workspace-write and joins CODEX_SANDBOX_HOLDS as its 17th entry, per the standing derive-and-hold decision - so emitted TOML stays byte-identical at 26 read-only / 9 workspace-write while the hold list finally records every role that would widen. A previous pass declined this fix because it moved the count; that inverts the priority. Byte-identity is preserved THROUGH the hold, not by leaving a parser broken. Divergence check, because this is where that bug hides: both paths feeding sandbox derivation - install.js's emitter and checkCodexSandboxPosture - now route through the one extractor. The tools readers in runtime-artifact-conversion and install.js's other frontmatter call sites serve Claude-side emission and do not feed sandbox derivation. Also fixed, each real: the posture check's `found` used a naive whole-file regex where its own sibling uses the block-aware scanner, so prose inside developer_instructions produced a false violation; `found` skipped truncatePostureValue and leaked a 300-char value into validate agents output; deriveCodexSandboxMode's absolute never-throws claim was false for an object with a throwing toString; T49 could not falsify cross-phase leakage (its target phase had its own 01, so a globally-scoped map passed too); T20/N6 iterated a hardcoded table and pinned the FIXTURE size, so a 36th agent would be silently unchecked; three tests reimplemented the code they were testing instead of importing it; and T2-T4 deleted GSD_RUNTIME without restoring it. Verified: hold list 17, gsd-nyquist-auditor derives workspace-write unheld and emits read-only held, roster 35/35 at 26/9, depends_on ["auth"] no longer resolves while ["01"] still does, both identity-bypass cases and every confusable vector emit read-only. Refs #3897 Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> * docs(#3897): the hold list is 17, and the reason the 17th was missing The count read 16 because the derivation could not read the declaration it claimed to derive from: the tools reader was single-line, so a YAML list-form tools: block returned only its first item and gsd-nyquist-auditor's declared Write and Edit were read as an absence. Both the ADR entry and the feature fragment now carry the corrected count and the reason for it, rather than a silently updated number. Deriving from a declaration you cannot parse is not deriving, and a flattering count is worse than a wrong one because it looks settled. docs/FEATURES.md regenerated from the fragment. Refs #3897 Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> * chore(#3897): backfill changeset pr number Refs #3897 Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> --------- Co-authored-by: sim <sim@local> Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
640 lines
32 KiB
JavaScript
640 lines
32 KiB
JavaScript
#!/usr/bin/env node
|
|
// gsd-hook-version: {{GSD_VERSION}}
|
|
// gsd-cursor-subagent-start.js — Cursor subagentStart hook (ADR-1239 / #2089,
|
|
// isolation guard #3045)
|
|
//
|
|
// Cursor invokes this script when a subagent session starts.
|
|
// Protocol: JSON from Cursor on stdin; JSON response on stdout.
|
|
//
|
|
// Input schema (cursor subagentStart) — Cursor's hooks contract is a COMMON
|
|
// envelope shared by every hook, PLUS event-specific fields layered on top
|
|
// (cursor.com/docs/hooks, "Reference > Common schema"). A prior version of
|
|
// this comment documented only the envelope and omitted the event-specific
|
|
// fields entirely — that omission is exactly what caused #3045's isolation
|
|
// guard work to stall on a false schema conflict, so every field below is
|
|
// still read defensively (assume any of them may be absent/malformed):
|
|
// Common envelope (all hooks): conversation_id, generation_id, model,
|
|
// model_id, model_params, hook_event_name, cursor_version,
|
|
// workspace_roots (array of paths), user_email, transcript_path.
|
|
// (Some fields are omitted for app-lifecycle hooks; this script's own
|
|
// prior comment listed session_id/is_background_agent instead of
|
|
// model_id/model_params — the exact set observed is not guaranteed.)
|
|
// subagentStart-specific additions: subagent_id, subagent_type, task,
|
|
// parent_conversation_id, tool_call_id, subagent_model,
|
|
// is_parallel_worker, git_branch (optional).
|
|
//
|
|
// Output schema (cursor subagentStart):
|
|
// { additional_context?: string, permission?: "allow"|"deny", user_message?: string }
|
|
// "ask" is NOT a supported permission value for subagentStart — Cursor
|
|
// treats it as "deny". This script only ever emits "allow" (by omitting
|
|
// `permission`, preserving the pre-#3045 output shape) or an explicit
|
|
// "deny" with `user_message`.
|
|
//
|
|
// Behaviour:
|
|
// - Injects a brief GSD state reminder so subagents (planner, executor,
|
|
// verifier) have the current phase context (unchanged since #2587).
|
|
// - NEW (#3045): denies spawning a GSD executor subagent when this
|
|
// project's dispatch isolation resolves to "harness-worktree" but the
|
|
// session is NOT actually running isolated from the user's primary
|
|
// checkout. Cursor's `--worktree` is a SESSION-level flag (no per-call
|
|
// isolation parameter exists on `subagentStart`, unlike Claude's
|
|
// `Agent(isolation=...)` kwarg), so this guard verifies EFFECTIVE STATE
|
|
// instead of looking for a flag — see resolveIsolationDecision() below.
|
|
// - Fails open on a payload it cannot parse or that carries fields it does
|
|
// not need: never throws, never blocks a call it cannot evaluate.
|
|
// Isolation resolution itself fails CLOSED (denies) for the two cases
|
|
// that are load-bearing and are NOT the same as "cannot parse": (a) a
|
|
// GSD project resolved to harness-worktree whose isolation state cannot
|
|
// be verified, and (b) a harness-worktree GSD project dispatch with no
|
|
// usable subagent_type — a guard that cannot verify must not answer
|
|
// "safe" (#3050).
|
|
//
|
|
// Cursor docs: https://cursor.com/docs/hooks
|
|
|
|
'use strict';
|
|
|
|
const fs = require('fs');
|
|
const path = require('path');
|
|
const os = require('os');
|
|
|
|
// Workspace resolution is shared across the Cursor hooks (#2587) — see
|
|
// hooks/lib/cursor-workspace.js. Staged next to these scripts by
|
|
// writeCursorHooksJson so the require always resolves post-install.
|
|
const { resolveStatePath } = require('./lib/cursor-workspace.js');
|
|
const { readSentinel, VALID_ISOLATION, extractDispatchIdentifiers, sentinelAppliesToDispatch } = require('./lib/isolation-sentinel.js');
|
|
const { REASON_CODE } = require('./lib/isolation-deny-reason.js');
|
|
// #3582: gsd-core/bin/lib/*.cjs (runtime-homes.cjs, worktree-safety.cjs,
|
|
// runtime-name-policy.cjs, capability-registry.cjs — required below, inside
|
|
// resolveIsolationEvidence and resolveFallbackIsolation) are tsc build
|
|
// artifacts (ADR-457), gitignored and absent on a raw plugin-marketplace /
|
|
// git-clone install that never ran `npm run build:lib`. Self-heal once, in
|
|
// evaluateRootIsolation, before any of those four requires run — see the
|
|
// call site below. This module itself depends on nothing under ./lib.
|
|
const { ensureRuntimeBuild, RuntimeBuildError } = require('../gsd-core/bin/ensure-runtime-build.cjs');
|
|
|
|
const MSG_PRESENT =
|
|
'GSD: Subagent session started — review .planning/STATE.md for the current phase and any blockers before acting.';
|
|
const MSG_ABSENT =
|
|
'GSD: Subagent session started — no .planning/ workflow found.';
|
|
|
|
// GSD's Cursor agent artifacts install with `destSubpath: "agents"`,
|
|
// `prefix: "gsd-"`, flat nesting, via the `convertClaudeAgentToCursorAgent`
|
|
// converter, and `hostIntegration.dispatch.namedDispatch === true`
|
|
// (gsd-core/bin/lib/capability-registry.cjs, runtimes.cursor) — i.e. Cursor
|
|
// dispatches named subagents by their real agent name, identically to
|
|
// Claude. So GSD's executor surfaces as subagent_type === "gsd-executor" on
|
|
// Cursor too, the same identifier hooks/gsd-agent-isolation-guard.js checks
|
|
// for on Claude. A Set, not a bare string compare, so a future sibling
|
|
// executor role can be added here without touching the matching logic below.
|
|
const EXECUTOR_SUBAGENT_TYPES = new Set(['gsd-executor']);
|
|
|
|
/**
|
|
* Runs `realpathFn`, never throwing. A path that cannot be resolved (does not
|
|
* exist, dangling symlink, ELOOP, ...) yields `null` rather than an
|
|
* exception — the caller decides what "cannot resolve" means for its own
|
|
* verdict (#3045 finding 2).
|
|
*
|
|
* `realpathFn` is injectable (defaults to `fs.realpathSync`), per the repo's
|
|
* dependency-injection seam convention (mirrors the `clock` seam elsewhere in
|
|
* these hooks) — this lets tests exercise the realpath-based spoof-resistance
|
|
* logic below with a fabricated symlink-resolution mapping, without ever
|
|
* creating a real filesystem symlink (directory symlinks require elevated
|
|
* privileges on unprivileged Windows CI).
|
|
*/
|
|
function realpathOrNull(p, realpathFn) {
|
|
try {
|
|
return realpathFn(p);
|
|
} catch {
|
|
return null;
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Resolve whether `root` is running in a session Cursor ISOLATED FOR THIS
|
|
* DISPATCH — i.e. a worktree the harness itself created and manages, not
|
|
* merely "some linked git worktree".
|
|
*
|
|
* #3045 security review (finding 3): "is a linked git worktree" is NOT "is
|
|
* isolated from the tree the human is using". A developer who opens Cursor
|
|
* directly in a hand-made `git worktree add` checkout — routine, see
|
|
* `.claude/worktrees/` in this very repo — is not protected by anything;
|
|
* nothing stops them from also editing that same checkout by hand. The ONLY
|
|
* signal that actually proves harness isolation is that `root` resolves
|
|
* under Cursor's OWN managed worktree root (`<cursor config dir>/worktrees`,
|
|
* i.e. `~/.cursor/worktrees` by default — `getGlobalConfigDir('cursor')`
|
|
* honors the `CURSOR_CONFIG_DIR` env override and `~` expansion for free).
|
|
* That is made NECESSARY AND SUFFICIENT below. Do NOT reinstate
|
|
* `resolveWorktreeLinkage`'s `linked_worktree_root` mode as an alternative
|
|
* OR'd proof of isolation — that is precisely the bypass finding 3 closed;
|
|
* a future "simplification" that merges it back in re-opens unconsented
|
|
* writes to the human's active checkout.
|
|
*
|
|
* `resolveWorktreeLinkage` is still called, but ONLY as a diagnostic: it
|
|
* distinguishes "confidently not isolated" from "git could not answer
|
|
* (timeout) — cannot determine" so the eventual deny reason stays
|
|
* actionable. Its result never flips `isolated`.
|
|
*
|
|
* Both the workspace root and the managed root are realpath'd before
|
|
* comparison (#3045 finding 2) — lexical `path.relative` alone is spoofable
|
|
* by a symlink or bind mount at either location, plantable by any process
|
|
* running with the user's permissions (including an agent already inside a
|
|
* legitimately isolated worktree, which has shell access by design).
|
|
* `fs.realpathSync` throwing (nonexistent path) never propagates — it
|
|
* degrades to "cannot resolve", never to "isolated". realpath also resolves
|
|
* the `CURSOR_CONFIG_DIR`-derived managed root itself (not just `root`), so a
|
|
* symlinked or case-differing `CURSOR_CONFIG_DIR` (case-insensitive
|
|
* filesystems normalize to on-disk casing via realpath's dirent walk, not
|
|
* string comparison) is covered on BOTH sides of the comparison, not only
|
|
* `root`'s.
|
|
*
|
|
* Returns `{ isolated: true|false, cannotDetermine: bool, notApplicable: bool }`.
|
|
* `notApplicable` (#3045 MAJOR 3) is true only for a confidently-not-a-git-repo
|
|
* root — see the `not_git_repo` branch below.
|
|
*
|
|
* `realpath` is injectable (`(p: string) => string`, throws like
|
|
* `fs.realpathSync` on an unresolvable path; defaults to the real
|
|
* `fs.realpathSync`) per the repo's clock-seam-style dependency-injection
|
|
* convention. This lets tests drive the exact spoof-resistance logic this
|
|
* function exists for (a symlink at the managed root pointing OUTSIDE it)
|
|
* with an injected resolution mapping, in-process, on every platform —
|
|
* without creating a real directory symlink, which requires elevated
|
|
* privileges on unprivileged Windows CI.
|
|
*/
|
|
function resolveIsolationEvidence(root, { realpath = fs.realpathSync } = {}) {
|
|
let managedRoot = null;
|
|
try {
|
|
// Sibling data/policy module, staged alongside this hook at install time
|
|
// (same pattern as hooks/gsd-statusline.js's requires of gsd-core/bin/lib/*).
|
|
const { getGlobalConfigDir } = require('../gsd-core/bin/lib/runtime-homes.cjs');
|
|
managedRoot = path.join(getGlobalConfigDir('cursor'), 'worktrees');
|
|
} catch {
|
|
managedRoot = null;
|
|
}
|
|
|
|
const realRoot = realpathOrNull(root, realpath);
|
|
const realManagedRoot = managedRoot === null ? null : realpathOrNull(managedRoot, realpath);
|
|
|
|
if (realRoot !== null && realManagedRoot !== null) {
|
|
const rel = path.relative(realManagedRoot, realRoot);
|
|
const underManagedRoot = rel === '' || (!rel.startsWith('..') && !path.isAbsolute(rel));
|
|
if (underManagedRoot) return { isolated: true, cannotDetermine: false, notApplicable: false };
|
|
}
|
|
|
|
// Not proven isolated by the only signal that counts. Resolve the
|
|
// diagnostic-only linkage check purely to make the deny reason legible —
|
|
// see the doc comment above; this NEVER flips `isolated`.
|
|
let linkageReason = null;
|
|
try {
|
|
// Sibling data/policy module, staged alongside this hook at install time.
|
|
const { resolveWorktreeLinkage } = require('../gsd-core/bin/lib/worktree-safety.cjs');
|
|
linkageReason = resolveWorktreeLinkage(root).reason;
|
|
} catch {
|
|
linkageReason = null;
|
|
}
|
|
|
|
if (realRoot === null) {
|
|
// `root` itself could not be resolved on disk. In the live hook this is
|
|
// defense in depth rather than a reachable path today: the GSD-project
|
|
// existence gate in resolveIsolationDecision already requires `root` to
|
|
// resolve (it must contain a readable `.planning/config.json`) before
|
|
// evidence is ever consulted, so a workspace root that plainly does not
|
|
// exist allows earlier as "not a GSD project" — never here. Kept anyway
|
|
// per finding 2's explicit directive: an unresolvable path must never
|
|
// silently read as "isolated".
|
|
return { isolated: false, cannotDetermine: true, notApplicable: false };
|
|
}
|
|
if (linkageReason === 'git_timed_out') {
|
|
return { isolated: false, cannotDetermine: true, notApplicable: false };
|
|
}
|
|
if (linkageReason === 'not_git_repo') {
|
|
// #3045 MAJOR 3: a confidently-non-git `root` has no primary git
|
|
// checkout to protect from an isolated-worktree bypass — Cursor's
|
|
// `--worktree` / `/worktree` (the deny message's own remediation) create
|
|
// a GIT worktree, so telling the user to start one is unactionable
|
|
// advice for a directory that isn't a git repo at all. Treat as INERT
|
|
// (allow) rather than a confident negative; this is distinct from
|
|
// `cannotDetermine` (git responded definitively here, it just said "not
|
|
// a repo") and from `isolated` (nothing was proven isolated) — it is its
|
|
// own "this guard's threat model does not apply" outcome.
|
|
return { isolated: false, cannotDetermine: false, notApplicable: true };
|
|
}
|
|
return { isolated: false, cannotDetermine: false, notApplicable: false };
|
|
}
|
|
|
|
/**
|
|
* Resolve every non-empty string entry of `workspace_roots` — ALL checkout
|
|
* paths Cursor is operating on for this hook invocation, not just the first.
|
|
*
|
|
* #3045 security review (finding 1): a multi-root Cursor workspace whose
|
|
* FIRST root is a non-GSD directory (or an isolated worktree) and whose
|
|
* SECOND root is the GSD project in the primary checkout must still be
|
|
* caught — every root is a directory the dispatched subagent can reach and
|
|
* write to, regardless of position. `hooks/lib/cursor-workspace.js` already
|
|
* established the "scan every root" precedent for its own (different)
|
|
* purpose; this is a parallel scan for isolation applicability, not a
|
|
* duplicate of that module's single-root-resolution job (it resolves ONE
|
|
* root to report state-file presence; this resolves the full set to decide
|
|
* whether ANY of them is an unconsented write target).
|
|
*
|
|
* Cursor runs hooks with cwd set to its own config dir (~/.cursor), NOT the
|
|
* workspace (hooks/lib/cursor-workspace.js), so `workspace_roots` is the
|
|
* only reliable source for "what directories is this dispatch actually in".
|
|
*
|
|
* #3045 MINOR: a RELATIVE entry is rejected (`path.isAbsolute`), not merely
|
|
* accepted-and-hoped — every downstream consumer (`.planning/config.json`
|
|
* existence check, `realpathOrNull`, `resolveWorktreeLinkage`) joins/resolves
|
|
* it against whatever the CURRENT PROCESS cwd happens to be, which for this
|
|
* hook is Cursor's own config dir (~/.cursor per the comment above), NOT the
|
|
* workspace. A relative root would therefore resolve against the wrong
|
|
* directory and — because a wrong/nonexistent `.planning/config.json` path
|
|
* reads as "not a GSD project" — silently ALLOW a dispatch this guard should
|
|
* have evaluated (fail OPEN). Filtering it out here instead makes it "not a
|
|
* resolvable workspace root", which degrades the SAME way (allow, step 2 of
|
|
* resolveIsolationDecision's applicability list) but for the honest reason.
|
|
*/
|
|
function getWorkspaceRoots(data) {
|
|
const roots = Array.isArray(data.workspace_roots) ? data.workspace_roots : [];
|
|
return roots.filter((r) => typeof r === 'string' && r.length > 0 && path.isAbsolute(r));
|
|
}
|
|
|
|
/**
|
|
* Decide whether to deny this subagentStart. Returns
|
|
* `{ action: 'allow' } | { action: 'deny', reason: string }`.
|
|
*
|
|
* Applicability (must positively determine all of the following to deny —
|
|
* otherwise allow):
|
|
* 1. `subagent_type` is not confidently a NON-executor (a present,
|
|
* non-empty string that isn't in EXECUTOR_SUBAGENT_TYPES short-circuits
|
|
* to allow immediately, before any project/isolation resolution runs —
|
|
* mirrors hooks/gsd-agent-isolation-guard.js checking subagent_type
|
|
* first, and matters here specifically: an unreadable config must never
|
|
* deny a dispatch this guard was never going to enforce against),
|
|
* 2. a workspace root is resolvable from `workspace_roots`,
|
|
* 3. that root is a GSD project (`.planning/config.json` exists there),
|
|
* 4. the resolved dispatch isolation is `harness-worktree`,
|
|
* 5. `subagent_type` identifies a GSD executor (or is missing/malformed —
|
|
* see the cannot-determine case below),
|
|
* 6. the session is NOT actually isolated (resolveIsolationEvidence).
|
|
*
|
|
* No workspace root at all degrades to allow (step 2), mirroring
|
|
* hooks/gsd-agent-isolation-guard.js's own "not a GSD project → allow"
|
|
* branch: project-existence is the gate that makes fail-closed apply in the
|
|
* first place, so being unable to even locate a candidate project is not
|
|
* itself a fail-closed trigger — it is the same "not a GSD project" shape
|
|
* that guard already treats as inert.
|
|
*
|
|
* Two DISTINCT fail-closed ("cannot determine") reasons per #3050's lesson
|
|
* that a guard which cannot verify must not answer "safe" — both scoped to
|
|
* "GSD project resolved to harness-worktree", never to a dispatch already
|
|
* confirmed to be a non-executor:
|
|
* - this project's dispatch-isolation configuration cannot be read/resolved
|
|
* (registry require/parse failure, or config.json unreadable),
|
|
* - `subagent_type` is missing or not a usable non-empty string on a
|
|
* dispatch this guard could not rule out as an executor.
|
|
*
|
|
* Isolation resolution (#3045 BLOCKER fix, see hooks/lib/isolation-sentinel.js):
|
|
* prefers the workflow's own PERSISTED per-dispatch decision (the sentinel
|
|
* `record-dispatch-isolation` writes) over re-deriving a host CAPABILITY from
|
|
* the registry. `none`/`orchestrator-worktree` from a fresh sentinel ALLOW
|
|
* immediately — sequential/orchestrator-managed dispatch is legitimate. An
|
|
* absent/stale sentinel falls back to `resolveFallbackIsolation` (registry +
|
|
* `workflow.use_worktrees`, runtime resolved GSD_RUNTIME env >
|
|
* .planning/config.json `runtime` key > 'cursor'). The default is
|
|
* confidently "cursor" here — UNLIKE hooks/gsd-agent-isolation-guard.js's own
|
|
* fallback, which must treat "no explicit signal" as cannot-determine
|
|
* because that hook installs across every `hostIntegration.hooksSurface ===
|
|
* 'settings-json'` runtime — because THIS script only ever runs as Cursor's
|
|
* own subagentStart hook; there is no other host it could be executing
|
|
* under, so defaulting to 'cursor' is a confirmed fact of the execution
|
|
* context, not a guess (#3045 MINOR — this note replaces a prior comment
|
|
* that inaccurately claimed to "mirror" runtime-slash.cjs's resolveRuntime,
|
|
* which defaults to 'claude'; the two intentionally diverge).
|
|
*
|
|
* #3045 security review (finding 1): applicability step 2 above now means
|
|
* "a workspace root is resolvable", plural — resolveIsolationDecision
|
|
* evaluates EVERY entry of `workspace_roots` via evaluateRootIsolation() and
|
|
* denies on the first one that fails. `subagent_type` is still resolved
|
|
* exactly once, up front, before any root is touched (applicability step 1
|
|
* stays a single check, not per-root — an unreadable config on one root must
|
|
* never even be attempted for a confirmed non-executor dispatch).
|
|
*/
|
|
function resolveIsolationDecision(data, { clock = Date, realpath = fs.realpathSync } = {}) {
|
|
const subagentType = data.subagent_type;
|
|
const isConfirmedNonExecutor = typeof subagentType === 'string'
|
|
&& subagentType.length > 0
|
|
&& !EXECUTOR_SUBAGENT_TYPES.has(subagentType);
|
|
if (isConfirmedNonExecutor) return { action: 'allow' };
|
|
|
|
const roots = getWorkspaceRoots(data);
|
|
if (roots.length === 0) return { action: 'allow' };
|
|
|
|
// #3045 SECURITY F2: best-effort plan/phase extraction from this
|
|
// dispatch's own `task` text (Cursor carries the same prompt content the
|
|
// Claude Agent() dispatch does — see extractDispatchIdentifiers), so a
|
|
// fresh sentinel that disagrees with THIS dispatch is treated as
|
|
// inapplicable rather than trusted.
|
|
const dispatchIds = extractDispatchIdentifiers(data.task);
|
|
|
|
for (const root of roots) {
|
|
const verdict = evaluateRootIsolation(root, subagentType, { clock, dispatchIds, realpath });
|
|
if (verdict.action === 'deny') return verdict;
|
|
}
|
|
return { action: 'allow' };
|
|
}
|
|
|
|
// ─── #3897 rung 2: per-install runtime marker, single canonical owner ────────
|
|
// bin/install.js writes `<install>/gsd-core/.gsd-runtime` beside VERSION for
|
|
// every runtime install (#2297); this hook ships at `<install>/hooks/`, so the
|
|
// marker is the `gsd-core` sibling of this file's own directory. Previously
|
|
// this hook held its own private reader/cache (one of four #3897 found); it
|
|
// now delegates to the single canonical owner, `src/runtime-slash.cts`
|
|
// (compiled to gsd-core/bin/lib/runtime-slash.cjs), reached through
|
|
// `ensureRuntimeBuild()` like the other compiled-lib requires in this file
|
|
// (`scripts/lint-hooks-runtime-build-seam.cjs`).
|
|
function readInstallRuntimeMarker() {
|
|
try {
|
|
ensureRuntimeBuild();
|
|
const runtimeSlash = require('../gsd-core/bin/lib/runtime-slash.cjs');
|
|
return runtimeSlash.readInstallRuntimeMarker();
|
|
} catch {
|
|
// Unbuilt runtime library, or any other failure reaching the canonical
|
|
// owner — "no signal from this rung", never a resolution failure.
|
|
return null;
|
|
}
|
|
}
|
|
|
|
// Test seam — forwards to the canonical owner's seam so this hook and
|
|
// runtime-slash.cjs always share one cache (#3897 rung 2). Spawned-hook tests
|
|
// (fresh process, no marker) are unaffected.
|
|
function _setInstallRuntimeMarkerForTests(value) {
|
|
try {
|
|
ensureRuntimeBuild();
|
|
const runtimeSlash = require('../gsd-core/bin/lib/runtime-slash.cjs');
|
|
runtimeSlash._setInstallRuntimeMarkerForTests(value);
|
|
} catch {
|
|
// Test-only seam; an unbuilt library here means the test itself will fail
|
|
// downstream, which is a louder and more actionable signal than throwing here.
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Conservative fallback resolution used when the #3045 sentinel is absent or
|
|
* stale for `root`: re-derive isolation from the registry CAPABILITY, gated
|
|
* by `workflow.use_worktrees` (config-schema key confirmed present in
|
|
* gsd-core/bin/shared/config-schema.manifest.json's validKeys, so it survives
|
|
* loadConfig's whitelist; read directly from the raw config.json here, same
|
|
* side-effect-free approach cmdConfigGet itself uses).
|
|
*
|
|
* #3045 MAJOR fix ("Cursor residual false-deny"): previously defaulted
|
|
* confidently to 'cursor' whenever no `GSD_RUNTIME`/config.json `runtime`
|
|
* signal existed, purely because this script only ever executes as Cursor's
|
|
* OWN `subagentStart` hook — true of the PROCESS, but not evidence the
|
|
* PROJECT itself declared an isolation requirement this guard can verify.
|
|
* Combined with a stale/absent sentinel (outside `execute-phase`, after
|
|
* `.gsd` cleanup, a phase running past the sentinel's staleness window, or a
|
|
* base-check-degraded run whose sentinel went stale before a fresh one was
|
|
* recorded), that default made every such `gsd-executor` dispatch resolve to
|
|
* "harness-worktree" and then hard-DENY unless the session happened to be
|
|
* running under Cursor's own managed worktree root — a false-deny of
|
|
* otherwise legitimate dispatches, unlike `hooks/gsd-agent-isolation-guard.js`,
|
|
* which degrades an undeterminable runtime to inert (#3045 MAJOR 2). Aligned
|
|
* here: an explicit signal is now required — `GSD_RUNTIME` > config.json
|
|
* `runtime` key > the per-install `.gsd-runtime` marker (#3566) >
|
|
* `~/.gsd/defaults.json` `runtime` (mirrors the Claude hook's
|
|
* `resolveRuntimeIdentity`; `bin/install.js`'s `writeNonClaudeDefaults`
|
|
* persists the installed runtime there for every non-Claude install,
|
|
* including Cursor, so a REAL Cursor+GSD install still resolves confidently
|
|
* — this only stops GUESSING 'cursor' for a project that never declared any
|
|
* runtime signal at all).
|
|
*/
|
|
function resolveFallbackIsolation(root, configPath) {
|
|
const { resolveRuntimeNameFromCandidates } = require('../gsd-core/bin/lib/runtime-name-policy.cjs');
|
|
const { runtimes } = require('../gsd-core/bin/lib/capability-registry.cjs');
|
|
|
|
let runtimeId = resolveRuntimeNameFromCandidates(process.env.GSD_RUNTIME);
|
|
const rawConfig = fs.readFileSync(configPath, 'utf-8');
|
|
const parsedConfig = JSON.parse(rawConfig);
|
|
if (!runtimeId && parsedConfig && typeof parsedConfig === 'object' && 'runtime' in parsedConfig) {
|
|
runtimeId = resolveRuntimeNameFromCandidates(parsedConfig.runtime) || null;
|
|
}
|
|
if (!runtimeId) {
|
|
// #3566: the per-install marker, above the host-wide defaults — same fix as
|
|
// hooks/gsd-agent-isolation-guard.js's resolveRuntimeIdentity. defaults.json
|
|
// is host-wide and names whichever runtime installed LAST (#2840's poison);
|
|
// the marker describes THIS install (written for every runtime since #2297).
|
|
runtimeId = resolveRuntimeNameFromCandidates(readInstallRuntimeMarker()) || null;
|
|
}
|
|
if (!runtimeId) {
|
|
try {
|
|
const defaultsPath = path.join(os.homedir(), '.gsd', 'defaults.json');
|
|
const defaultsParsed = JSON.parse(fs.readFileSync(defaultsPath, 'utf-8'));
|
|
if (defaultsParsed && typeof defaultsParsed === 'object' && 'runtime' in defaultsParsed) {
|
|
runtimeId = resolveRuntimeNameFromCandidates(defaultsParsed.runtime) || null;
|
|
}
|
|
} catch {
|
|
// Absent/unreadable ~/.gsd/defaults.json — no signal, fall through.
|
|
}
|
|
}
|
|
if (!runtimeId) {
|
|
// No explicit signal anywhere confirms this project resolved
|
|
// harness-worktree — degrade to inert rather than guess 'cursor'.
|
|
return 'none';
|
|
}
|
|
|
|
const runtimeEntry = runtimes != null ? runtimes[runtimeId] : null;
|
|
const declared = runtimeEntry?.runtime?.hostIntegration?.dispatch?.isolation ?? null;
|
|
let declaredIsolation = (typeof declared === 'string' && VALID_ISOLATION.has(declared)) ? declared : 'none';
|
|
|
|
if (declaredIsolation === 'harness-worktree' &&
|
|
parsedConfig && typeof parsedConfig === 'object' && parsedConfig.workflow &&
|
|
typeof parsedConfig.workflow === 'object' && parsedConfig.workflow.use_worktrees === false) {
|
|
declaredIsolation = 'none';
|
|
}
|
|
|
|
return declaredIsolation;
|
|
}
|
|
|
|
/**
|
|
* Applicability + isolation verdict for a SINGLE workspace root. Returns
|
|
* `{ action: 'allow' } | { action: 'deny', reason: string }`. Extracted from
|
|
* resolveIsolationDecision (#3045 finding 1) so every root in a multi-root
|
|
* workspace runs the identical check.
|
|
*/
|
|
function evaluateRootIsolation(root, subagentType, { clock = Date, dispatchIds = null, realpath = fs.realpathSync } = {}) {
|
|
const configPath = path.join(root, '.planning', 'config.json');
|
|
let isGsdProject;
|
|
try {
|
|
fs.accessSync(configPath, fs.constants.F_OK);
|
|
isGsdProject = true;
|
|
} catch {
|
|
isGsdProject = false;
|
|
}
|
|
if (!isGsdProject) return { action: 'allow' };
|
|
|
|
// #3582: self-heal the compiled runtime library BEFORE any of its four
|
|
// downstream requires (resolveFallbackIsolation's two, resolveIsolationEvidence's
|
|
// two — reached only below this point). Checked separately from the
|
|
// sentinel/fallback try block below so a build failure surfaces its own
|
|
// actionable RuntimeBuildError message rather than being folded into the
|
|
// generic "could not read or resolve ... configuration" deny reason (the
|
|
// #3050 misreport this issue exists to fix). Still fails closed either way.
|
|
try {
|
|
ensureRuntimeBuild();
|
|
} catch (err) {
|
|
return {
|
|
action: 'deny',
|
|
reason:
|
|
`GSD subagent isolation guard: cannot resolve this project's dispatch-isolation ` +
|
|
`configuration because the GSD runtime library failed to self-build. ` +
|
|
`${err instanceof RuntimeBuildError ? err.message : String(err && err.message || err)} ` +
|
|
`Refusing to allow this subagent to spawn until the runtime library is built — a guard ` +
|
|
`that cannot verify must not answer "safe" (#3050).`,
|
|
reasonCode: REASON_CODE.RUNTIME_BUILD_FAILED,
|
|
};
|
|
}
|
|
|
|
let declaredIsolation;
|
|
try {
|
|
// #3045 BLOCKER fix: a fresh sentinel is authoritative for THIS
|
|
// dispatch's actual resolved isolation — see the doc comment above.
|
|
// #3045 SECURITY F2: a fresh sentinel that names a DIFFERENT
|
|
// plan/phase than this dispatch is not applicable to it — fall through
|
|
// to the conservative fallback exactly as a stale sentinel would.
|
|
const sentinel = readSentinel(root, { clock });
|
|
declaredIsolation = (sentinel.present && !sentinel.stale && sentinelAppliesToDispatch(sentinel, dispatchIds))
|
|
? sentinel.isolation
|
|
: resolveFallbackIsolation(root, configPath);
|
|
} catch {
|
|
return {
|
|
action: 'deny',
|
|
reason:
|
|
`GSD subagent isolation guard: could not read or resolve this project's ` +
|
|
`dispatch-isolation configuration ('.planning/config.json' exists under "${root}"). ` +
|
|
`Refusing to allow this subagent to spawn without being able to verify whether ` +
|
|
`isolation is required — a guard that cannot verify must not answer "safe" (#3050). ` +
|
|
`Retry once the project configuration is readable.`,
|
|
reasonCode: REASON_CODE.CONFIG_UNREADABLE,
|
|
};
|
|
}
|
|
|
|
if (declaredIsolation !== 'harness-worktree') return { action: 'allow' };
|
|
|
|
// isConfirmedNonExecutor already excluded "present, non-empty, unrecognized
|
|
// string" above — reaching here means subagentType is either the confirmed
|
|
// executor or missing/malformed (cannot rule it out).
|
|
if (typeof subagentType !== 'string' || subagentType.length === 0) {
|
|
return {
|
|
action: 'deny',
|
|
reason:
|
|
`GSD subagent isolation guard: this project's dispatch isolation resolves to ` +
|
|
`"harness-worktree", but the subagentStart payload for this dispatch carries no usable ` +
|
|
`subagent_type. Refusing to allow it to spawn without being able to confirm whether it ` +
|
|
`is a GSD executor — a guard that cannot verify must not answer "safe" (#3050).`,
|
|
reasonCode: REASON_CODE.NO_SUBAGENT_TYPE,
|
|
};
|
|
}
|
|
|
|
const evidence = resolveIsolationEvidence(root, { realpath });
|
|
if (evidence.isolated) return { action: 'allow' };
|
|
if (evidence.notApplicable) return { action: 'allow' };
|
|
|
|
if (evidence.cannotDetermine) {
|
|
return {
|
|
action: 'deny',
|
|
reason:
|
|
`GSD subagent isolation guard: this project's dispatch isolation resolves to ` +
|
|
`"harness-worktree", but whether "${root}" is running in an isolated Cursor worktree ` +
|
|
`could not be determined (git did not respond). Refusing to allow subagent_type=` +
|
|
`"${subagentType}" to spawn without being able to verify isolation — a guard that ` +
|
|
`cannot verify must not answer "safe" (#3050). Retry once git is responsive.`,
|
|
reasonCode: REASON_CODE.CANNOT_DETERMINE_ISOLATION,
|
|
};
|
|
}
|
|
|
|
return {
|
|
action: 'deny',
|
|
reason:
|
|
`GSD subagent isolation guard: this project's dispatch isolation resolves to ` +
|
|
`"harness-worktree", but subagent_type="${subagentType}" is about to spawn in "${root}", ` +
|
|
`which is not an isolated Cursor worktree — it would edit the user's primary checkout ` +
|
|
`directly, with no consent and no warning. Start an isolated session first (the ` +
|
|
`"--worktree" CLI flag or the "/worktree" chat command; Cursor manages these worktrees ` +
|
|
`under "~/.cursor/worktrees/") and retry.`,
|
|
reasonCode: REASON_CODE.NOT_ISOLATED_WORKTREE,
|
|
};
|
|
}
|
|
|
|
/* istanbul ignore next -- stdin adapter, exercised via spawnSync in tests */
|
|
function main() {
|
|
let raw = '';
|
|
const stdinTimeout = setTimeout(() => {
|
|
process.exit(0);
|
|
}, 10000);
|
|
|
|
process.stdin.setEncoding('utf8');
|
|
process.stdin.on('data', (chunk) => { raw += chunk; });
|
|
process.stdin.on('end', () => {
|
|
clearTimeout(stdinTimeout);
|
|
|
|
let data = null;
|
|
try {
|
|
data = JSON.parse(raw);
|
|
} catch {
|
|
data = null;
|
|
}
|
|
|
|
// Resolve the state-reminder context ONCE, up front, so it can ride along
|
|
// with EITHER outcome below (#3045 MINOR: a deny previously dropped this
|
|
// reminder entirely — process.stdout.write for the deny branch returned
|
|
// before the additional_context block ever ran — instead of preserving it
|
|
// alongside the deny; the subagent still benefits from phase/blocker
|
|
// context even when its dispatch is refused).
|
|
let additionalContext = null;
|
|
try {
|
|
const statePath = resolveStatePath(raw);
|
|
const statePresent = fs.existsSync(statePath);
|
|
additionalContext = statePresent ? MSG_PRESENT : MSG_ABSENT;
|
|
} catch {
|
|
additionalContext = null;
|
|
}
|
|
|
|
if (data && typeof data === 'object') {
|
|
let decision = { action: 'allow' };
|
|
try {
|
|
decision = resolveIsolationDecision(data);
|
|
} catch {
|
|
// Defense in depth only: every verify-and-deny path above has its own
|
|
// explicit try/catch that resolves to a deny with a distinct reason.
|
|
// Anything reaching here is an unexpected failure outside those paths
|
|
// (e.g. malformed workspace_roots entries) — never crash the hook.
|
|
decision = { action: 'allow' };
|
|
}
|
|
if (decision.action === 'deny') {
|
|
const out = { permission: 'deny', user_message: decision.reason, reason_code: decision.reasonCode };
|
|
if (additionalContext !== null) out.additional_context = additionalContext;
|
|
process.stdout.write(JSON.stringify(out));
|
|
return;
|
|
}
|
|
}
|
|
|
|
process.stdout.write(JSON.stringify(additionalContext !== null ? { additional_context: additionalContext } : {}));
|
|
});
|
|
}
|
|
|
|
if (require.main === module) {
|
|
main();
|
|
}
|
|
|
|
// #3045 MAJOR ("clock seam is dead code" fix): exported so tests can
|
|
// `require()` this module and inject a `clock` (`{now(): number}`) directly
|
|
// per the repo's clock-seam convention, instead of racing real `Date.now()`
|
|
// across a spawned subprocess boundary.
|
|
module.exports = {
|
|
resolveIsolationDecision,
|
|
evaluateRootIsolation,
|
|
resolveFallbackIsolation,
|
|
resolveIsolationEvidence,
|
|
getWorkspaceRoots,
|
|
_setInstallRuntimeMarkerForTests,
|
|
};
|