fix(#3582): route every hook's compiled-module require through the self-heal build seam (#3629)

* test(3582): failing-first cold-tree coverage and the seam drift lint

On a plugin-channel install the compiled gsd-core/bin/lib/*.cjs are legitimately
absent (ADR-457 build-at-publish; the npm package builds before publishing, a raw
tree materialization never does). gsd-tools.cjs calls ensureRuntimeBuild() before
requiring ./lib; no hook does, so the isolation guard's Cannot-find-module lands in
its fail-closed catch and is misreported as an unreadable dispatch-isolation
configuration, blocking every executor dispatch.

These tests fail on that: cold-tree runs of the isolation guard, statusline, cursor
guard and update worker, plus the seam's actionable build error surfacing instead of
the generic misreport.

Also adds the drift lint the acceptance criteria require, with a fixture proving it
CAN fail — a guard never shown to fail is worthless. It is red here by design: it
flags today's unfixed hooks, which is exactly the defect.

* fix(3582): route every hook's compiled-module require through the self-heal seam

RED proven at 5b174b0d: 11 failures — the cold-tree runs for the isolation guard,
cursor guard and update worker, the fail-closed-with-actionable-message assertion, and
the lint's own real-tree check.

The compiled runtime library is produced by build:lib and gitignored (ADR-457,
build-at-publish). The npm package builds before publishing; a plugin-marketplace or
git-clone install materializes the raw tree and never does, so on that channel those
modules are legitimately absent. The self-heal seam added by #2002 exists to heal exactly
this, and the CLI entrypoint already calls it — no hook did. The isolation guard's
Cannot-find-module therefore landed in its fail-closed catch and was reported as
'could not read or resolve dispatch-isolation configuration', so an ARTIFACT ABSENCE was
misdiagnosed as an unreadable project config and every executor dispatch was blocked.

All SEVEN affected files now call the seam before their first compiled require. The issue
named four; a scan found six; implementing it surfaced a seventh — the shared isolation
sentinel helper, used by BOTH guards, which requires two compiled modules itself and
would have defeated the guards' own fix on a genuinely cold tree. Same defect class, so
fixed here rather than left as a known-broken remainder.

Failure posture is deliberately split by hook kind:
- Gates (agent isolation guard, cursor subagent start) surface the seam's actionable
  build error distinctly instead of swallowing it into the generic text, and stay
  fail-closed — a genuinely unreadable project config still DENIES exactly as before.
- Cosmetic and detached hooks (statusline, update worker, update check, update banner)
  DEGRADE rather than crash: the statusline draws on every render and the worker is a
  detached process, so a build failure there must not take down the prompt.

The npm path is untouched: the seam's already-built fast path returns immediately, so
prebuilt installs pay nothing and behave bit-for-bit as before.

Adds a drift lint, wired into the CI lint chain, so the invariant is enforced rather than
remembered — without it the next hook to add a compiled require reintroduces the class
silently. It is proven able to fail: a fixture hook requiring a compiled module without
the seam is flagged, and one that uses the seam is not. Verified directly — on the
unfixed tree it named all seven offenders; with the fix it passes.

While writing the lint's comment stripper, a naive whole-text block-comment regex ate its
own fixture, because this repo's comments legitimately spell the compiled-lib glob whose
star-slash reads as a comment opener. Rewritten as a line-based scanner with a regression
test pinning that case.

* fix(3582): test the three untested seam call sites and assert typed reason codes

Two independent reviews converged on the same major gap: the fix wired the seam into
seven files but only four had cold-tree tests. The adversarial pass put it plainly —
deleting the shared isolation-sentinel helper's seam call would not have failed any test
in the diff. That file was my own addition beyond the issue's four, so it shipped
untested; that is now closed.

- Shared isolation-sentinel helper: its seam call is only reached when .planning is NOT
  directly under cwd, and every existing cold-tree fixture puts it there, so the early
  return always fired first. Now covered, and proven load-bearing by mutation: with the
  call removed the spy records zero seam invocations and the test fails.
- update-check hook and update-banner hook: cold-tree tests added asserting the DEGRADED
  VERDICT — the fallback cache filename, and silent suppression when the package name
  degrades to null — rather than merely 'did not throw'. The banner hook previously had
  no test file at all.

Standards violation fixed: two tests asserted on free-form prose via assert.match against
a JSON reason string, which CONTRIBUTING bans by name — its own BAD example is exactly
that. The ESLint rule only covers readFileSync/spawnSync text, so tooling did not catch
it. Both isolation guards now emit a machine-readable reason_code from a frozen enum,
following the repo's existing REASON convention, and the tests assert that instead. The
human-readable message is unchanged for operators; only the assertion target moved.

The duplicated degrade boilerplate across the three cosmetic hooks was deliberately NOT
extracted, and the reason is recorded at each site: both viable shapes — a
path-parameterized helper, or a ceremony-only wrapper — defeat the drift lint's per-file
literal co-occurrence check, so extracting would require the lint to special-case its own
helper. Triplication is the lesser evil while the lint stays a co-occurrence scan.

The lint's header now states what it does and does not catch (literal quoted requires
only; hooks/ scan root), so a future reader does not over-trust a guard that a
concatenated path or a require inside a non-hooks helper would evade.

* chore(3582): regenerate the committed install-tree fixtures

Adding a new shipped hook helper changed the install tree, and those fixtures are
committed-and-derived (regen:derived / gen:install-tree), so 12 'install tree — <runtime>'
tests failed on 541a1913. Regenerated rather than hand-edited.

The delta across all 15 runtime fixtures is exactly two lines — the new helper under both
its hooks/ and gsd-hooks/ install paths — and nothing else, so the regeneration pulled in
no unrelated drift.

This is the bookkeeping ripple a new file under hooks/ carries; it was not visible from
lint:ci, which passed both before and after.

* chore(3582): backfill changeset PR number (#3629)

---------

Co-authored-by: sim <sim@local>
This commit is contained in:
Tom Boucher
2026-08-18 14:11:23 -04:00
committed by GitHub
parent cc3fd4548d
commit bf2332e67c
31 changed files with 1250 additions and 27 deletions

View File

@@ -64,6 +64,15 @@ const fs = require('fs');
const path = require('path');
const os = require('os');
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-name-policy.cjs, capability-registry.cjs
// below) 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 before the first such require (resolveRegistryIsolation, below) —
// see ensureRuntimeBuild's own header for the full rationale. This module
// itself (gsd-core/bin/ensure-runtime-build.cjs) depends on nothing under
// ./lib, so requiring it here is always safe.
const { ensureRuntimeBuild, RuntimeBuildError } = require('../gsd-core/bin/ensure-runtime-build.cjs');
// No other executor-shaped subagent_type exists in agents/ today
// (verified: only agents/gsd-executor.md). A Set, not a bare string compare,
@@ -239,6 +248,15 @@ function resolveHarnessFlag(runtimeId, runtimes) {
* run, e.g. a manual Agent() call before any sentinel has been written).
*/
function resolveRegistryIsolation(cwd, configPath) {
// #3582: self-heal the compiled runtime library BEFORE either require
// below — this is the only reaching path to both (resolveRegistryIsolation
// is the sole caller of each), so one call here covers both. Throws
// RuntimeBuildError on an unbuildable tree; the caller (resolveIsolationState)
// already wraps this whole function in try/catch and folds any error into
// its fail-closed `error` result — evaluateDispatch below distinguishes a
// RuntimeBuildError there so it surfaces this seam's actionable message
// instead of being misreported as an unreadable config.json (#3050 lesson).
ensureRuntimeBuild();
const { resolveRuntimeNameFromCandidates } = require('../gsd-core/bin/lib/runtime-name-policy.cjs');
const { runtimes } = require('../gsd-core/bin/lib/capability-registry.cjs');
@@ -416,13 +434,27 @@ function evaluateDispatch(data, { clock = Date } = {}) {
if (!state.gsdProject) return { action: 'allow' };
if (state.error) {
const reason =
`Agent isolation guard: could not read or resolve this project's dispatch-isolation ` +
`configuration ('.planning/config.json' under '${cwd}'). Refusing to dispatch ` +
`subagent_type="${subagentType}" 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.`;
return { action: 'block', reason };
// #3582: a missing/unbuildable compiled runtime library (RuntimeBuildError,
// thrown by ensureRuntimeBuild in resolveRegistryIsolation) is a DIFFERENT,
// actionable failure from an unreadable/unparsable config.json — surface
// its own message instead of misreporting it as the generic
// "could not read or resolve ... configuration" text (the exact #3050
// misreport this issue exists to fix). Both cases still fail closed
// (block); only the message differs.
const isBuildFailure = state.error instanceof RuntimeBuildError;
const reason = isBuildFailure
? `Agent isolation guard: cannot resolve this project's dispatch-isolation ` +
`configuration because the GSD runtime library failed to self-build. ` +
`${state.error.message} Refusing to dispatch subagent_type="${subagentType}" until ` +
`the runtime library is built — a guard that cannot verify must not answer "safe" ` +
`(#3050).`
: `Agent isolation guard: could not read or resolve this project's dispatch-isolation ` +
`configuration ('.planning/config.json' under '${cwd}'). Refusing to dispatch ` +
`subagent_type="${subagentType}" 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.`;
const reasonCode = isBuildFailure ? REASON_CODE.RUNTIME_BUILD_FAILED : REASON_CODE.CONFIG_UNREADABLE;
return { action: 'block', reason, reasonCode };
}
if (state.isolation !== 'harness-worktree') return { action: 'allow' };
@@ -438,7 +470,7 @@ function evaluateDispatch(data, { clock = Date } = {}) {
`${parsed.param}="${parsed.value}". Add ${parsed.param}="${parsed.value}" to the Agent() ` +
`call so the executor runs in an isolated worktree instead of the primary checkout ` +
`(gsd-core/workflows/execute-phase/steps/executor-isolation-dispatch.md).`;
return { action: 'block', reason };
return { action: 'block', reason, reasonCode: REASON_CODE.HARNESS_FLAG_MISSING };
}
/* istanbul ignore next -- stdin adapter, exercised via spawnSync in tests */
@@ -453,7 +485,7 @@ function main() {
const data = JSON.parse(input);
const decision = evaluateDispatch(data);
if (decision.action === 'block') {
const out = { decision: 'block', reason: decision.reason };
const out = { decision: 'block', reason: decision.reason, reason_code: decision.reasonCode };
process.stdout.write(JSON.stringify(out));
// Kimi feeds stderr (not stdout) back to the model on exit 2.
process.stderr.write(decision.reason);

View File

@@ -11,18 +11,61 @@
const fs = require('fs');
const path = require('path');
const { isSemverNewer } = require('../gsd-core/bin/lib/semver-compare.cjs');
// Latest-version lookup is delegated to the single deterministic adapter
// (#498). checkLatestVersion() owns the npm-view call, the timeout/semver
// policy, and the package name — sourced from the baked Package Identity seam.
// The previous `require('../package.json').name` (#378) never yielded a name in
// the installed tree — at the time it resolved to the synthetic
// {"type":"commonjs"} marker GSD wrote at the config root, which has no `.name`,
// so the background check never reported updates. Since #2544 GSD writes no
// marker there at all, so that require would now fail to resolve outright.
// Either way the name must come from the baked seam, never a walk-up.
const { checkLatestVersion } = require('../gsd-core/bin/check-latest-version.cjs');
const { PACKAGE_NAME } = require('../gsd-core/bin/lib/package-identity.cjs');
// #3582: gsd-core/bin/lib/semver-compare.cjs and package-identity.cjs (and,
// transitively, check-latest-version.cjs's own gsd-core/bin/lib/cli-exit.cjs
// + shell-command-projection.cjs) are tsc build artifacts (ADR-457),
// gitignored and absent on a raw plugin-marketplace / git-clone install that
// never ran `npm run build:lib`. This worker is a DETACHED SessionStart
// background process (spawned with stdio: 'ignore') — a build failure here
// must DEGRADE to the no-signal fallbacks below (mirroring the
// managed-hooks-registry.cjs degrade just below) so the worker still runs to
// completion and writes a result cache record, rather than dying silently
// with no visible signal and no cache-file write at all.
//
// This try/require/ensureRuntimeBuild/require/catch shape repeats (with
// different destructured names) in hooks/gsd-check-update.js and
// hooks/gsd-update-banner.js. It is deliberately NOT extracted into a shared
// hooks/lib/ helper: scripts/lint-hooks-runtime-build-seam.cjs enforces this
// exact seam textually, PER FILE — it greps each hooks/ file for its OWN
// literal `require('.../ensure-runtime-build.cjs')` + `ensureRuntimeBuild(`
// call co-occurring with its OWN literal `require('.../gsd-core/bin/lib/*.cjs')`.
// A generic helper taking the compiled module's path as a variable would move
// the literal compiled-lib require OUT of this file and into the helper,
// called with a non-literal argument — the scan's regex (see that script's
// "Known limitations") cannot see a require() called with a variable, so this
// file would then read as "requires nothing" and the lint would stop
// protecting it. A ceremony-only helper (just the ensureRuntimeBuild call,
// each caller keeping its own literal compiled-lib require) fails the SAME
// way from the other side: it would remove this file's own literal
// `require('.../ensure-runtime-build.cjs')` + `ensureRuntimeBuild(` call,
// which the lint also requires to be textually present in THIS file. Either
// shape needs the lint script itself widened to special-case the helper,
// which is a bigger, riskier change than the ~6 duplicated lines it would
// save; kept inline instead.
let isSemverNewer = () => false;
let checkLatestVersion = () => ({ ok: false });
let PACKAGE_NAME = null;
try {
const { ensureRuntimeBuild } = require('../gsd-core/bin/ensure-runtime-build.cjs');
ensureRuntimeBuild();
({ isSemverNewer } = require('../gsd-core/bin/lib/semver-compare.cjs'));
// Latest-version lookup is delegated to the single deterministic adapter
// (#498). checkLatestVersion() owns the npm-view call, the timeout/semver
// policy, and the package name — sourced from the baked Package Identity seam.
// The previous `require('../package.json').name` (#378) never yielded a name in
// the installed tree — at the time it resolved to the synthetic
// {"type":"commonjs"} marker GSD wrote at the config root, which has no `.name`,
// so the background check never reported updates. Since #2544 GSD writes no
// marker there at all, so that require would now fail to resolve outright.
// Either way the name must come from the baked seam, never a walk-up.
({ checkLatestVersion } = require('../gsd-core/bin/check-latest-version.cjs'));
({ PACKAGE_NAME } = require('../gsd-core/bin/lib/package-identity.cjs'));
} catch (e) {
// Runtime library missing/broken and could not self-build — degrade to the
// no-signal fallbacks declared above; the worker still writes a result
// cache record (package_name: null, update_available: false).
}
// Authoritative list of managed hooks — shared with tests to retire source-grep
// assertions (pending-migration-to-typed-ir [#455]).
// NOTE: managed-hooks-registry.cjs must be in HOOKS_TO_COPY (scripts/build-hooks.js)

View File

@@ -8,7 +8,25 @@ const path = require('path');
const os = require('os');
const { spawn } = require('child_process');
const { updateCacheFileName } = require('../gsd-core/bin/lib/package-identity.cjs');
// #3582: gsd-core/bin/lib/package-identity.cjs is a tsc build artifact
// (ADR-457), gitignored and absent on a raw plugin-marketplace / git-clone
// install that never ran `npm run build:lib`. This SessionStart hook must
// DEGRADE (fall back to a generic cache filename) rather than crash session
// start. gsd-check-update-worker.js — the process this hook spawns — degrades
// identically and independently, so the shared fallback literal keeps the
// cache path consistent between writer and reader even in the (rare)
// doubly-degraded case. This try/require/ensureRuntimeBuild/require/catch
// shape is deliberately duplicated (not extracted to hooks/lib/) — see
// gsd-check-update-worker.js's identical #3582 comment for why.
let updateCacheFileName = 'gsd-update-check.json';
try {
const { ensureRuntimeBuild } = require('../gsd-core/bin/ensure-runtime-build.cjs');
ensureRuntimeBuild();
({ updateCacheFileName } = require('../gsd-core/bin/lib/package-identity.cjs'));
} catch (e) {
// Runtime library missing/broken and could not self-build — degrade to the
// fallback filename above rather than crash the SessionStart hook.
}
const homeDir = os.homedir();
const cwd = process.cwd();

View File

@@ -62,6 +62,15 @@ const os = require('os');
// 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.';
@@ -458,6 +467,28 @@ function evaluateRootIsolation(root, subagentType, { clock = Date, dispatchIds =
}
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
@@ -478,6 +509,7 @@ function evaluateRootIsolation(root, subagentType, { clock = Date, dispatchIds =
`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,
};
}
@@ -494,6 +526,7 @@ function evaluateRootIsolation(root, subagentType, { clock = Date, dispatchIds =
`"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,
};
}
@@ -510,6 +543,7 @@ function evaluateRootIsolation(root, subagentType, { clock = Date, dispatchIds =
`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,
};
}
@@ -522,6 +556,7 @@ function evaluateRootIsolation(root, subagentType, { clock = Date, dispatchIds =
`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,
};
}
@@ -571,7 +606,7 @@ function main() {
decision = { action: 'allow' };
}
if (decision.action === 'deny') {
const out = { permission: 'deny', user_message: decision.reason };
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;

View File

@@ -9,6 +9,24 @@ const os = require('os');
// Namespace (not destructured) so tests can inject spawn failures by
// monkeypatching childProcess.execFileSync.
const childProcess = require('child_process');
// #3582: gsd-core/bin/lib/*.cjs (semver-compare.cjs, state-document.cjs,
// active-workstream-store.cjs, planning-workspace.cjs — required below) and
// package-identity.cjs are tsc build artifacts (ADR-457), gitignored and
// absent on a raw plugin-marketplace / git-clone install that never ran
// `npm run build:lib`. The statusline renders on EVERY prompt, so a build
// failure here must DEGRADE (print nothing, exit 0) rather than crash
// Claude Code's per-render statusline hook. Scoped to the spawned-as-a-script
// path (`require.main === module`) — a test `require()` of this module for
// its pure helpers assumes a built tree, same as every other hook test.
if (require.main === module) {
try {
const { ensureRuntimeBuild } = require('../gsd-core/bin/ensure-runtime-build.cjs');
ensureRuntimeBuild();
} catch (e) {
process.stdout.write('');
process.exit(0);
}
}
const { isSemverNewer } = require('../gsd-core/bin/lib/semver-compare.cjs');
const { PACKAGE_NAME, updateCacheFileName } = require('../gsd-core/bin/lib/package-identity.cjs');
const { normalizeStateStatus } = require('../gsd-core/bin/lib/state-document.cjs');

View File

@@ -15,7 +15,28 @@
const fs = require('fs');
const path = require('path');
const os = require('os');
const { PACKAGE_NAME, updateCacheFileName } = require('../gsd-core/bin/lib/package-identity.cjs');
// #3582: gsd-core/bin/lib/package-identity.cjs is a tsc build artifact
// (ADR-457), gitignored and absent on a raw plugin-marketplace / git-clone
// install that never ran `npm run build:lib`. This is an opt-in SessionStart
// hook — a build failure here must DEGRADE, not crash session start. With
// PACKAGE_NAME left null, buildBannerOutput's own lineage guard
// (`!cache.package_name || cache.package_name !== PACKAGE_NAME`) always
// treats the cache as untrusted, so main() falls through to its existing
// silent "print nothing" path below — no separate degrade branch needed.
// This try/require/ensureRuntimeBuild/require/catch shape is deliberately
// duplicated (not extracted to hooks/lib/) — see
// gsd-check-update-worker.js's identical #3582 comment for why.
let PACKAGE_NAME = null;
let updateCacheFileName = 'gsd-update-check.json';
try {
const { ensureRuntimeBuild } = require('../gsd-core/bin/ensure-runtime-build.cjs');
ensureRuntimeBuild();
({ PACKAGE_NAME, updateCacheFileName } = require('../gsd-core/bin/lib/package-identity.cjs'));
} catch (e) {
// Runtime library missing/broken and could not self-build — degrade to the
// fallbacks above rather than crash the SessionStart hook.
}
// Suppress repeat parse-error banners for 24 hours so a genuinely broken
// cache file doesn't nag the user every session.

View File

@@ -0,0 +1,39 @@
'use strict';
// hooks/lib/isolation-deny-reason.js — shared, frozen reason-code enum for
// the #3045 dispatch-isolation guards' block/deny decisions
// (hooks/gsd-agent-isolation-guard.js, hooks/gsd-cursor-subagent-start.js).
//
// CONTRIBUTING.md ("Prohibited: Raw Text Matching on Test Outputs") bans
// asserting on a hook's free-form, human-readable reason/user_message prose
// — that text is for the operator/model reading the denial and may change
// wording without notice. Every block/deny decision therefore ALSO carries
// one of these STABLE codes (surfaced on the hook's stdout JSON as
// `reason_code`), so tests assert `out.reason_code === REASON_CODE.X`
// instead of regexing the message (mirrors the REASON enum convention in
// gsd-core/bin/verify-reapply-patches.cjs).
//
// Adding a new code requires updating this enum AND any test that locks the
// documented set.
const REASON_CODE = Object.freeze({
// The compiled runtime library (gsd-core/bin/lib/*.cjs) is missing and
// could not be self-built (ensure-runtime-build.cjs's RuntimeBuildError).
RUNTIME_BUILD_FAILED: 'runtime_build_failed',
// The project's dispatch-isolation configuration ('.planning/config.json')
// could not be read or resolved for a reason OTHER than a runtime-build
// failure (unreadable/malformed config, unexpected resolver error).
CONFIG_UNREADABLE: 'config_unreadable',
// Isolation resolves to "harness-worktree" but the Agent()/Task() dispatch
// is missing the harness's isolation flag/kwarg.
HARNESS_FLAG_MISSING: 'harness_flag_missing',
// Isolation resolves to "harness-worktree" but the dispatch payload carries
// no usable subagent_type, so the guard cannot confirm it is a GSD executor.
NO_SUBAGENT_TYPE: 'no_subagent_type',
// Isolation resolves to "harness-worktree" but whether the workspace root
// is an isolated worktree could not be determined (e.g. git unresponsive).
CANNOT_DETERMINE_ISOLATION: 'cannot_determine_isolation',
// Isolation resolves to "harness-worktree" and the workspace root is
// confirmed NOT an isolated worktree.
NOT_ISOLATED_WORKTREE: 'not_isolated_worktree',
});
module.exports = { REASON_CODE };

View File

@@ -130,6 +130,15 @@ function resolveSentinelRoot(cwd) {
if (fs.existsSync(path.join(cwd, '.planning'))) {
return cwd;
}
// #3582: worktree-safety.cjs / project-root.cjs 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 before either
// require below; a RuntimeBuildError (or any other failure) falls through
// to the existing catch's degrade-to-raw-`cwd` — unchanged behavior, just
// now attempted-healed-first rather than silently degrading on the first
// cold-tree encounter.
const { ensureRuntimeBuild } = require('../../gsd-core/bin/ensure-runtime-build.cjs');
ensureRuntimeBuild();
const { resolveWorktreeRoot } = require('../../gsd-core/bin/lib/worktree-safety.cjs');
const { root } = resolveWorktreeRoot(cwd);
const { findProjectRoot } = require('../../gsd-core/bin/lib/project-root.cjs');