fix(#4834): gate the launcher PATH arm on runtime identity and prefer config-home installs (#4902)

* test(#4834): failing-first launcher hijack regressions

* fix(#4834): gate the launcher PATH arm on runtime identity and prefer config-home installs

A gsd_run on PATH that cannot prove it is @opengsd/gsd-core (a foreign package, or a
release older than the runtime-identity verb) is no longer accepted by the launcher
snippet's PATH arm; resolution falls through to the hard error when no path-based
candidate matches. The runtime-config-home arm now precedes the PATH arm, restoring
the documented prefer-local-over-PATH order, so an installer-managed install wins
even against a genuine global. The 16-home probe list is factored into _gsd_homes()
and the identity gate into _gsd_id_ok(), keeping the per-copy delta at +141 bytes.

The files whose frozen ceilings had no headroom (gsd-executor, gsd-plan-checker,
gsd-verifier, gsd-planner, execute-phase, execute-plan) now load the resolver by
@-include from gsd-core/references/gsd-run-resolver.md (the onboard.md pattern)
instead of carrying an inline copy. Propagated to all other inlined workflow/agent
copies via scripts/sync-runtime-launcher.cjs; the resolver reference re-copied
byte-equal (parity B2); the hard-error text, docs/how-to/diagnose-a-foreign-gsd-tools.md,
and the CONTEXT.md launcher predicate updated to match (#4834); the quick-batch row-48
guard gains the canonical-preamble sweep carve-out (#4834, per its own #3730/#2529
precedents); the compact-content benchmark baseline regenerated.

Emitted-Drift-Ack-Growth: add-backlog.md — launcher snippet resolution hardening propagates via sync-runtime-launcher (#4834)
Emitted-Drift-Ack-Growth: add-phase.md — launcher snippet resolution hardening propagates via sync-runtime-launcher (#4834)
Emitted-Drift-Ack-Growth: add-tests.md — launcher snippet resolution hardening propagates via sync-runtime-launcher (#4834)
Emitted-Drift-Ack-Growth: add-todo.md — launcher snippet resolution hardening propagates via sync-runtime-launcher (#4834)
Emitted-Drift-Ack-Growth: ai-integration-phase.md — launcher snippet resolution hardening propagates via sync-runtime-launcher (#4834)
Emitted-Drift-Ack-Growth: audit-fix.md — launcher snippet resolution hardening propagates via sync-runtime-launcher (#4834)
Emitted-Drift-Ack-Growth: audit-milestone.md — launcher snippet resolution hardening propagates via sync-runtime-launcher (#4834)
Emitted-Drift-Ack-Growth: audit-uat.md — launcher snippet resolution hardening propagates via sync-runtime-launcher (#4834)
Emitted-Drift-Ack-Growth: autonomous.md — launcher snippet resolution hardening propagates via sync-runtime-launcher (#4834)
Emitted-Drift-Ack-Growth: check-todos.md — launcher snippet resolution hardening propagates via sync-runtime-launcher (#4834)
Emitted-Drift-Ack-Growth: cleanup.md — launcher snippet resolution hardening propagates via sync-runtime-launcher (#4834)
Emitted-Drift-Ack-Growth: code-review-fix.md — launcher snippet resolution hardening propagates via sync-runtime-launcher (#4834)
Emitted-Drift-Ack-Growth: code-review.md — launcher snippet resolution hardening propagates via sync-runtime-launcher (#4834)
Emitted-Drift-Ack-Growth: complete-milestone.md — launcher snippet resolution hardening propagates via sync-runtime-launcher (#4834)
Emitted-Drift-Ack-Growth: debug.md — launcher snippet resolution hardening propagates via sync-runtime-launcher (#4834)
Emitted-Drift-Ack-Growth: diagnose-issues.md — launcher snippet resolution hardening propagates via sync-runtime-launcher (#4834)
Emitted-Drift-Ack-Growth: discuss-phase-assumptions.md — launcher snippet resolution hardening propagates via sync-runtime-launcher (#4834)
Emitted-Drift-Ack-Growth: discuss-phase.md — launcher snippet resolution hardening propagates via sync-runtime-launcher (#4834)
Emitted-Drift-Ack-Growth: do.md — launcher snippet resolution hardening propagates via sync-runtime-launcher (#4834)
Emitted-Drift-Ack-Growth: docs-update.md — launcher snippet resolution hardening propagates via sync-runtime-launcher (#4834)
Emitted-Drift-Ack-Growth: edit-phase.md — launcher snippet resolution hardening propagates via sync-runtime-launcher (#4834)
Emitted-Drift-Ack-Growth: eval-review.md — launcher snippet resolution hardening propagates via sync-runtime-launcher (#4834)
Emitted-Drift-Ack-Growth: explore.md — launcher snippet resolution hardening propagates via sync-runtime-launcher (#4834)
Emitted-Drift-Ack-Growth: extract-learnings.md — launcher snippet resolution hardening propagates via sync-runtime-launcher (#4834)
Emitted-Drift-Ack-Growth: fast.md — launcher snippet resolution hardening propagates via sync-runtime-launcher (#4834)
Emitted-Drift-Ack-Growth: forensics.md — launcher snippet resolution hardening propagates via sync-runtime-launcher (#4834)
Emitted-Drift-Ack-Growth: graduation.md — launcher snippet resolution hardening propagates via sync-runtime-launcher (#4834)
Emitted-Drift-Ack-Growth: gsd-code-fixer.compact.md — launcher snippet resolution hardening propagates via sync-runtime-launcher (#4834)
Emitted-Drift-Ack-Growth: gsd-code-fixer.md — launcher snippet resolution hardening propagates via sync-runtime-launcher (#4834)
Emitted-Drift-Ack-Growth: gsd-debug-session-manager.compact.md — launcher snippet resolution hardening propagates via sync-runtime-launcher (#4834)
Emitted-Drift-Ack-Growth: gsd-debug-session-manager.md — launcher snippet resolution hardening propagates via sync-runtime-launcher (#4834)
Emitted-Drift-Ack-Growth: gsd-debugger.md — launcher snippet resolution hardening propagates via sync-runtime-launcher (#4834)
Emitted-Drift-Ack-Growth: gsd-eval-auditor.compact.md — launcher snippet resolution hardening propagates via sync-runtime-launcher (#4834)
Emitted-Drift-Ack-Growth: gsd-eval-auditor.md — launcher snippet resolution hardening propagates via sync-runtime-launcher (#4834)
Emitted-Drift-Ack-Growth: gsd-intel-updater.compact.md — launcher snippet resolution hardening propagates via sync-runtime-launcher (#4834)
Emitted-Drift-Ack-Growth: gsd-intel-updater.md — launcher snippet resolution hardening propagates via sync-runtime-launcher (#4834)
Emitted-Drift-Ack-Growth: gsd-phase-researcher.md — launcher snippet resolution hardening propagates via sync-runtime-launcher (#4834)
Emitted-Drift-Ack-Growth: gsd-project-researcher.compact.md — launcher snippet resolution hardening propagates via sync-runtime-launcher (#4834)
Emitted-Drift-Ack-Growth: gsd-project-researcher.md — launcher snippet resolution hardening propagates via sync-runtime-launcher (#4834)
Emitted-Drift-Ack-Growth: gsd-research-synthesizer.compact.md — launcher snippet resolution hardening propagates via sync-runtime-launcher (#4834)
Emitted-Drift-Ack-Growth: gsd-research-synthesizer.md — launcher snippet resolution hardening propagates via sync-runtime-launcher (#4834)
Emitted-Drift-Ack-Growth: gsd-ui-researcher.compact.md — launcher snippet resolution hardening propagates via sync-runtime-launcher (#4834)
Emitted-Drift-Ack-Growth: gsd-ui-researcher.md — launcher snippet resolution hardening propagates via sync-runtime-launcher (#4834)
Emitted-Drift-Ack-Growth: health.md — launcher snippet resolution hardening propagates via sync-runtime-launcher (#4834)
Emitted-Drift-Ack-Growth: import.md — launcher snippet resolution hardening propagates via sync-runtime-launcher (#4834)
Emitted-Drift-Ack-Growth: inbox.md — launcher snippet resolution hardening propagates via sync-runtime-launcher (#4834)
Emitted-Drift-Ack-Growth: ingest-docs.md — launcher snippet resolution hardening propagates via sync-runtime-launcher (#4834)
Emitted-Drift-Ack-Growth: insert-phase.md — launcher snippet resolution hardening propagates via sync-runtime-launcher (#4834)
Emitted-Drift-Ack-Growth: list-seeds.md — launcher snippet resolution hardening propagates via sync-runtime-launcher (#4834)
Emitted-Drift-Ack-Growth: list-workspaces.md — launcher snippet resolution hardening propagates via sync-runtime-launcher (#4834)
Emitted-Drift-Ack-Growth: manager.md — launcher snippet resolution hardening propagates via sync-runtime-launcher (#4834)
Emitted-Drift-Ack-Growth: map-codebase.md — launcher snippet resolution hardening propagates via sync-runtime-launcher (#4834)
Emitted-Drift-Ack-Growth: milestone-summary.md — launcher snippet resolution hardening propagates via sync-runtime-launcher (#4834)
Emitted-Drift-Ack-Growth: mvp-phase.md — launcher snippet resolution hardening propagates via sync-runtime-launcher (#4834)
Emitted-Drift-Ack-Growth: new-milestone.md — launcher snippet resolution hardening propagates via sync-runtime-launcher (#4834)
Emitted-Drift-Ack-Growth: new-project.md — launcher snippet resolution hardening propagates via sync-runtime-launcher (#4834)
Emitted-Drift-Ack-Growth: new-workspace.md — launcher snippet resolution hardening propagates via sync-runtime-launcher (#4834)
Emitted-Drift-Ack-Growth: next.md — launcher snippet resolution hardening propagates via sync-runtime-launcher (#4834)
Emitted-Drift-Ack-Growth: pause-work.md — launcher snippet resolution hardening propagates via sync-runtime-launcher (#4834)
Emitted-Drift-Ack-Growth: plan-phase.md — launcher snippet resolution hardening propagates via sync-runtime-launcher (#4834)
Emitted-Drift-Ack-Growth: plan-review-convergence.md — launcher snippet resolution hardening propagates via sync-runtime-launcher (#4834)
Emitted-Drift-Ack-Growth: plant-seed.md — launcher snippet resolution hardening propagates via sync-runtime-launcher (#4834)
Emitted-Drift-Ack-Growth: pr-branch.md — launcher snippet resolution hardening propagates via sync-runtime-launcher (#4834)
Emitted-Drift-Ack-Growth: profile-user.md — launcher snippet resolution hardening propagates via sync-runtime-launcher (#4834)
Emitted-Drift-Ack-Growth: progress.md — launcher snippet resolution hardening propagates via sync-runtime-launcher (#4834)
Emitted-Drift-Ack-Growth: quick-batch.md — launcher snippet resolution hardening propagates via sync-runtime-launcher (#4834)
Emitted-Drift-Ack-Growth: quick.md — launcher snippet resolution hardening propagates via sync-runtime-launcher (#4834)
Emitted-Drift-Ack-Growth: remove-phase.md — launcher snippet resolution hardening propagates via sync-runtime-launcher (#4834)
Emitted-Drift-Ack-Growth: remove-workspace.md — launcher snippet resolution hardening propagates via sync-runtime-launcher (#4834)
Emitted-Drift-Ack-Growth: resume-project.md — launcher snippet resolution hardening propagates via sync-runtime-launcher (#4834)
Emitted-Drift-Ack-Growth: review.md — launcher snippet resolution hardening propagates via sync-runtime-launcher (#4834)
Emitted-Drift-Ack-Growth: scan.md — launcher snippet resolution hardening propagates via sync-runtime-launcher (#4834)
Emitted-Drift-Ack-Growth: secure-phase.md — launcher snippet resolution hardening propagates via sync-runtime-launcher (#4834)
Emitted-Drift-Ack-Growth: settings-advanced.md — launcher snippet resolution hardening propagates via sync-runtime-launcher (#4834)
Emitted-Drift-Ack-Growth: settings-integrations.md — launcher snippet resolution hardening propagates via sync-runtime-launcher (#4834)
Emitted-Drift-Ack-Growth: settings.md — launcher snippet resolution hardening propagates via sync-runtime-launcher (#4834)
Emitted-Drift-Ack-Growth: ship.md — launcher snippet resolution hardening propagates via sync-runtime-launcher (#4834)
Emitted-Drift-Ack-Growth: sketch-wrap-up.md — launcher snippet resolution hardening propagates via sync-runtime-launcher (#4834)
Emitted-Drift-Ack-Growth: sketch.md — launcher snippet resolution hardening propagates via sync-runtime-launcher (#4834)
Emitted-Drift-Ack-Growth: smart-entry.md — launcher snippet resolution hardening propagates via sync-runtime-launcher (#4834)
Emitted-Drift-Ack-Growth: spec-phase.md — launcher snippet resolution hardening propagates via sync-runtime-launcher (#4834)
Emitted-Drift-Ack-Growth: spike-wrap-up.md — launcher snippet resolution hardening propagates via sync-runtime-launcher (#4834)
Emitted-Drift-Ack-Growth: spike.md — launcher snippet resolution hardening propagates via sync-runtime-launcher (#4834)
Emitted-Drift-Ack-Growth: stats.md — launcher snippet resolution hardening propagates via sync-runtime-launcher (#4834)
Emitted-Drift-Ack-Growth: sync-skills.md — launcher snippet resolution hardening propagates via sync-runtime-launcher (#4834)
Emitted-Drift-Ack-Growth: thread.md — launcher snippet resolution hardening propagates via sync-runtime-launcher (#4834)
Emitted-Drift-Ack-Growth: transition.md — launcher snippet resolution hardening propagates via sync-runtime-launcher (#4834)
Emitted-Drift-Ack-Growth: ui-phase.md — launcher snippet resolution hardening propagates via sync-runtime-launcher (#4834)
Emitted-Drift-Ack-Growth: ui-review.md — launcher snippet resolution hardening propagates via sync-runtime-launcher (#4834)
Emitted-Drift-Ack-Growth: ultraplan-phase.md — launcher snippet resolution hardening propagates via sync-runtime-launcher (#4834)
Emitted-Drift-Ack-Growth: undo.md — launcher snippet resolution hardening propagates via sync-runtime-launcher (#4834)
Emitted-Drift-Ack-Growth: validate-phase.md — launcher snippet resolution hardening propagates via sync-runtime-launcher (#4834)
Emitted-Drift-Ack-Growth: verify-work.md — launcher snippet resolution hardening propagates via sync-runtime-launcher (#4834)

* docs(#4834): backfill the changeset PR number

* test(#4834): regenerate the compact-content benchmark baseline after the rebase

---------

Co-authored-by: sim <sim@local>
This commit is contained in:
Tom Boucher
2026-09-21 02:27:36 -04:00
committed by GitHub
parent fac0e9de86
commit b956bb7c67
142 changed files with 650 additions and 194 deletions

View File

@@ -8,39 +8,39 @@
"label": "PROXY-TOKENIZER DELTA — gpt-tokenizer is a stand-in; Anthropic publishes no tokenizer for Claude 3+. The on/off COMPARISON is exact under this pinned tokenizer; absolute counts are not Claude's real token counts.",
"splits": {
"complete-milestone": {
"offTokens": 13200,
"onTokens": 8360,
"reductionPct": 36.67
"offTokens": 13322,
"onTokens": 8421,
"reductionPct": 36.79
},
"docs-update": {
"offTokens": 14230,
"onTokens": 11880,
"reductionPct": 16.51
"offTokens": 14291,
"onTokens": 11941,
"reductionPct": 16.44
},
"execute-phase": {
"offTokens": 26355,
"onTokens": 24065,
"reductionPct": 8.69
"offTokens": 25495,
"onTokens": 23144,
"reductionPct": 9.22
},
"new-project": {
"offTokens": 14308,
"onTokens": 12364,
"reductionPct": 13.59
"offTokens": 14369,
"onTokens": 12425,
"reductionPct": 13.53
},
"plan-phase": {
"offTokens": 27878,
"onTokens": 24588,
"reductionPct": 11.8
"offTokens": 28000,
"onTokens": 24649,
"reductionPct": 11.97
},
"verify-work": {
"offTokens": 13384,
"onTokens": 11411,
"reductionPct": 14.74
"offTokens": 13445,
"onTokens": 11472,
"reductionPct": 14.67
}
},
"aggregate": {
"offTokens": 109355,
"onTokens": 92668,
"reductionPct": 15.26
"offTokens": 108922,
"onTokens": 92052,
"reductionPct": 15.49
}
}

View File

@@ -32,6 +32,25 @@ const {
importsDirectiveReference,
} = require('../scripts/lint-response-language-coverage.cjs');
// The canonical launcher preamble, read from its single source of truth. A
// `sync-runtime-launcher.cjs` propagation rewrites this one line inside every
// gsd_run-calling workflow — quick.md included — without touching a word of
// ordinary quick content.
const CANONICAL_LAUNCHER_PREAMBLE = require('node:fs')
.readFileSync(require('node:path').join(__dirname, '..', 'gsd-core', 'workflows', '_runtime-launcher.snippet.sh'), 'utf8')
.replace(/\r?\n$/, '');
// A diff line that swaps the launcher preamble removes the OLD canonical line
// as well as adding the new one, so equality with today's snippet is not
// enough. Recognize a launcher-preamble line structurally instead: the shim
// name assignment plus the resolver's PATH probe and function definition —
// the same definition-shape discriminator
// tests/no-bare-gsd-tools-command-position.test.cjs uses for its EXCLUSION_RE.
const looksLikeLauncherPreambleLine = (body) =>
body.startsWith('_GSD_SHIM_NAME=')
&& body.includes('command -v gsd_run')
&& body.includes('gsd_run()');
/**
* Does this path's diff say anything beyond the shared response-language
* directive (#2529)?
@@ -41,6 +60,16 @@ const {
* matching prose the lint itself no longer recognizes as coverage. A file the
* branch ADDED answers true, every line being new — which is what a real
* #3676-phase branch looks like.
*
* #4834 adds the third mechanical-sweep carve-out, in the same family as the
* #3730 and #2529-round-40 scopings below: a line that IS the canonical
* launcher preamble is a `sync-runtime-launcher.cjs` propagation, not
* quick-batch phase work. The snippet's byte changes reach every workflow in
* one mechanical pass; treating them as ordinary-quick edits would freeze the
* launcher out of quick.md forever, while the preamble's own content stays
* policed by tests/runtime-launcher-parity.test.cjs and the emitted-attribution
* gate. Any OTHER line — ordinary quick prose, steps, contracts — still trips
* this row exactly as before.
*/
function editsBeyondSharedDirective(base, file) {
const diff = git(['diff', '--unified=0', `${base}...HEAD`, '--', file]);
@@ -48,6 +77,8 @@ function editsBeyondSharedDirective(base, file) {
if (!/^[+-]/.test(line) || line.startsWith('+++') || line.startsWith('---')) return false;
const body = line.slice(1).trim();
if (body === '' || body === INLINE_RESPONSE_LANGUAGE_DIRECTIVE) return false;
if (body === CANONICAL_LAUNCHER_PREAMBLE.trim()) return false;
if (looksLikeLauncherPreambleLine(body)) return false;
return !importsDirectiveReference(body);
});
}

View File

@@ -103,11 +103,11 @@ const BARE_COMMAND_RE = new RegExp(
// Each entry MUST carry a one-line reason; the test prints the allowlist on
// failure so a reviewer can see exactly what is sanctioned.
const PROSE_ALLOWLIST = [
{ file: 'agents/gsd-executor.md', line: 825, reason: 'describes the SDK return envelope of `gsd-tools query commit`; not an instruction to run the bare word (#4670 shifted it from 823: the plan_head_after capture line added above moved the line, the mention is unchanged)' },
{ file: 'agents/gsd-executor.md', line: 826, reason: 'describes the SDK return envelope of `gsd-tools query commit`; not an instruction to run the bare word (#4670 shifted it from 823; #4834 shifted it from 825: the delegation @-include replaced the inline preamble above it, the mention is unchanged)' },
{ file: 'agents/gsd-phase-researcher.md', line: 33, reason: 'package-legitimacy provenance rule names the command as the source of an OK verdict; descriptive' },
{ file: 'agents/gsd-roadmapper.md', line: 660, reason: 'parenthetical "e.g." naming SDK queries a user *could* run; not an agent instruction (#4134 shifted it from 647: the H1 template section added above moved the line, the mention is unchanged)' },
{ file: 'agents/gsd-intel-updater.md', line: 40, reason: 'cross-platform note names the `gsd-tools intel <subcommand>` CLI surface descriptively ("CLI invocations go through..."); not an agent instruction' },
{ file: 'gsd-core/workflows/execute-plan.md', line: 419, reason: 'describes the downstream SDK validation step (`validated downstream by ...`); names the mechanism, does not instruct the agent to type it' },
{ file: 'gsd-core/workflows/execute-plan.md', line: 420, reason: 'describes the downstream SDK validation step (`validated downstream by ...`); names the mechanism, does not instruct the agent to type it (#4834 shifted it from 419: the delegation @-include replaced the inline preamble above it, the mention is unchanged)' },
// #4407: .compact.md variant siblings carry the same descriptive prose as
// their already-allowlisted canonical line above, at a different line
// number in a different file.

View File

@@ -374,7 +374,9 @@ describe('launcher resolver: PATH branch prefers the collision-free bin', () =>
test('prefers gsd_run when a foreign gsd-tools is also on PATH', (t) => {
if (skipOnWindows(t)) return;
const ours = path.join(dir, 'OURS');
writeFake('gsd_run', `: > "${ours}"`);
// #4834: the PATH arm is identity-gated, so the fake must answer
// `runtime-identity --raw` the way a real same-package install does.
writeFake('gsd_run', `if [ "$1" = "runtime-identity" ] && [ "$2" = "--raw" ]; then echo '{"packageName":"@opengsd/gsd-core","version":"1.0.0-test"}'; else : > "${ours}"; fi`);
const foreign = path.join(dir, 'FOREIGN');
writeFake('gsd-tools', `: > "${foreign}"`);
@@ -406,7 +408,9 @@ describe('launcher resolver: PATH branch prefers the collision-free bin', () =>
if (skipOnWindows(t)) return;
const ours = path.join(dir, 'OURS');
const alive = path.join(dir, 'ALIVE');
writeFake('gsd_run', `: > "${ours}"`);
// #4834: the stub must prove identity — a bare stub now falls through the
// gate and would land in the resolver's exit 1 on the second source.
writeFake('gsd_run', `if [ "$1" = "runtime-identity" ] && [ "$2" = "--raw" ]; then echo '{"packageName":"@opengsd/gsd-core","version":"1.0.0-test"}'; else : > "${ours}"; fi`);
const r = sourceAndRun(`. "${SNIPPET}"; . "${SNIPPET}"; : > "${alive}"; gsd_run query anything`);

View File

@@ -315,6 +315,40 @@ function delegatesToResolverReference(content) {
return content.includes('references/gsd-run-resolver.md');
}
/**
* Write the identity-proving LOCAL install stub shared by the #4834 fixtures:
* a `gsd-tools.cjs` at `<dir>/.claude/gsd-core/bin/` that answers
* `runtime-identity --raw` like a real same-package install and prints
* `LOCAL:<args>` for every other verb. Returns the bin dir.
*/
function writeIdentityLocalStub(homeDir) {
const localBin = path.join(homeDir, '.claude', 'gsd-core', 'bin');
fs.mkdirSync(localBin, { recursive: true });
fs.writeFileSync(
path.join(localBin, 'gsd-tools.cjs'),
'#!/usr/bin/env node\n' +
'const a = process.argv.slice(2);\n' +
'if (a[0] === "runtime-identity" && a[1] === "--raw") {\n' +
' console.log(\'{"packageName":"@opengsd/gsd-core","version":"1.14.0-test"}\');\n' +
'} else {\n' +
' console.log("LOCAL:" + a.join(","));\n' +
'}\n',
);
fs.chmodSync(path.join(localBin, 'gsd-tools.cjs'), 0o755);
return localBin;
}
/**
* Write a FOREIGN/older `gsd_run` stub (no `runtime-identity` verb) into
* `dir` — the #4834 hijacker. Returns `dir` for PATH construction.
*/
function writeForeignGsdRun(dir) {
fs.mkdirSync(dir, { recursive: true });
fs.writeFileSync(path.join(dir, 'gsd_run'), '#!/bin/sh\necho "FOREIGN:$*"\n');
fs.chmodSync(path.join(dir, 'gsd_run'), 0o755);
return dir;
}
describe('runtime-launcher-parity (#373)', () => {
// ─── (#3146) Deliberate bootstrap-only preamble placement is preserved ────
test('sync preserves a deliberate bootstrap-only preamble placement (#3146)', () => {
@@ -595,7 +629,7 @@ describe('runtime-launcher-parity (#373)', () => {
}
});
// ─── (E) PATH fallback behavioral (#3668) ────────────────────────────────
// ─── (E) PATH fallback behavioral (#3668, identity-gated since #4834) ─────
test('(E) PATH fallback: uses installed gsd_run when no local gsd-tools.cjs present', () => {
// Create a temp dir with NO local gsd-core/bin/gsd-tools.cjs.
// Place an executable gsd_run stub on a dedicated PATH dir.
@@ -605,19 +639,36 @@ describe('runtime-launcher-parity (#373)', () => {
// The predecessor package `get-shit-done-cc` publishes a colliding
// `gsd-tools` bin, so the launcher resolves `gsd_run`, which only this
// package publishes.
//
// #4834: the PATH arm is gated on runtime-identity proof, so the stub must
// answer `runtime-identity --raw` the way a real same-package install does
// — a stub without the verb now falls through to the hard error ((D2)
// pins that side). HOME is pinned to an empty fake home so the reorder
// (config homes ahead of PATH) cannot resolve through the runner's real
// $HOME before the PATH arm is reached.
const base = fs.mkdtempSync(path.join(os.tmpdir(), 'gsd 373 pathfb '));
const emptyHome = fs.mkdtempSync(path.join(os.tmpdir(), 'gsd 373 pathfb home '));
try {
const pathBinDir = path.join(base, 'bin');
fs.mkdirSync(pathBinDir, { recursive: true });
// Stub installed gsd_run binary that prints a marker
// Stub installed gsd_run binary: proves identity, then prints a marker
const stubPath = path.join(pathBinDir, 'gsd_run');
fs.writeFileSync(stubPath, '#!/bin/sh\necho "installed:$*"\n');
fs.writeFileSync(
stubPath,
'#!/bin/sh\n' +
'if [ "$1" = "runtime-identity" ] && [ "$2" = "--raw" ]; then\n' +
' echo \'{"packageName":"@opengsd/gsd-core","version":"installed-test"}\'\n' +
'else\n' +
' echo "installed:$*"\n' +
'fi\n',
);
fs.chmodSync(stubPath, 0o755);
// RUNTIME_DIR points to base — no gsd-core/bin/gsd-tools.cjs there
const snippet = fs.readFileSync(SNIPPET_FILE, 'utf8');
const scriptContent =
`unset GSD_TOOLS\n` +
`export RUNTIME_DIR=${JSON.stringify(base)}\n` +
snippet +
`\nprintf "GSD_TOOLS=%s\\n" "$GSD_TOOLS"\n` +
@@ -627,7 +678,10 @@ describe('runtime-launcher-parity (#373)', () => {
fs.writeFileSync(scriptPath, scriptContent);
const stdout = runBashFile(scriptPath, {
env: { PATH: `${pathBinDir}${path.delimiter}${process.env.PATH || ''}` },
env: {
PATH: `${pathBinDir}${path.delimiter}${process.env.PATH || ''}`,
HOME: emptyHome,
},
});
// The PATH fallback must have resolved GSD_TOOLS to the stub binary.
@@ -654,13 +708,315 @@ describe('runtime-launcher-parity (#373)', () => {
);
} finally {
cleanup(base);
cleanup(emptyHome);
}
});
// ─── (K) foreign PATH gsd_run cannot hijack a local install (#4834) ───────
test('(K) a foreign gsd_run on PATH cannot hijack a runtime-config-home install (#4834)', (t) => {
// The issue's shape: a local install (here at the $HOME/.claude config
// home, the same arm 3 the installed-copy path bakes an absolute prefix
// into) plus an older foreign gsd_run earlier on PATH. The PATH arm must
// prove identity before it may win; a tool without the runtime-identity
// verb falls through so the local install resolves instead.
const fakeHome = fs.mkdtempSync(path.join(os.tmpdir(), 'gsd-4834-home-'));
const fakeRuntime = fs.mkdtempSync(path.join(os.tmpdir(), 'gsd-4834-rt-'));
const foreignBin = writeForeignGsdRun(fs.mkdtempSync(path.join(os.tmpdir(), 'gsd-4834-foreign-')));
writeIdentityLocalStub(fakeHome);
t.after(() => { cleanup(fakeHome); cleanup(fakeRuntime); cleanup(foreignBin); });
const snippet = fs.readFileSync(SNIPPET_FILE, 'utf8');
const scriptContent =
`unset GSD_TOOLS\n` +
`export RUNTIME_DIR=${JSON.stringify(fakeRuntime)}\n` +
`export HOME=${JSON.stringify(fakeHome)}\n` +
snippet +
`\nprintf "GSD_TOOLS=%s\\n" "$GSD_TOOLS"\n` +
`gsd_run query git.base-branch --is-protected master\n`;
const scriptPath = path.join(fakeRuntime, 'test-4834-hijack.sh');
fs.writeFileSync(scriptPath, scriptContent);
const { isolatedPath, nodeBinDir } = buildIsolatedPath();
t.after(() => cleanup(nodeBinDir));
const testPath = [foreignBin, isolatedPath].join(path.delimiter);
const stdout = runBashFile(scriptPath, {
env: { PATH: testPath, HOME: fakeHome },
});
const normStdout = stdout.replace(/\\/g, '/');
assert.ok(
normStdout.includes('.claude/gsd-core/bin/'),
`Expected GSD_TOOLS to resolve into the local install at .claude/gsd-core/bin/, got:\n${stdout.trim()}`,
);
// The issue's downstream contract: the LOCAL tool is what answers
// `query git.base-branch --is-protected` (a real 1.14.0 tool then honors
// git.allow_default_branch_commits — pinned end to end by (K2)).
assert.ok(
stdout.includes('LOCAL:query,git.base-branch,--is-protected,master'),
`Expected the local tool to answer the query, got:\n${stdout.trim()}`,
);
assert.ok(
!stdout.includes('FOREIGN:'),
`Expected the foreign PATH stub never to be invoked, got:\n${stdout.trim()}`,
);
});
// ─── (K2) end-to-end: the resolved local tool honors the override (#4834) ──
test('(K2) end-to-end: the resolved local tool honors git.allow_default_branch_commits (#4834)', (t) => {
// The issue's console repro with the REAL gsd-tools: a foreign gsd_run
// first on PATH, the real binary installed at the config home, a temp
// project on its default branch `master`. With the override set, the
// launcher must reach the real local tool and report `master` as NOT
// protected; without the override the same tool reports it protected —
// the control that keeps the assertion from passing vacuously. Before
// #4834 the FOREIGN tool answered here, predating the override, and the
// executor's pre-commit guard refused the commit.
const { createTempGitProject, cleanup: cleanupDir } = require('./helpers.cjs');
const project = createTempGitProject('gsd-4834-k2-');
const projectControl = createTempGitProject('gsd-4834-k2c-');
const fakeHome = fs.mkdtempSync(path.join(os.tmpdir(), 'gsd-4834-k2-home-'));
const foreignBin = writeForeignGsdRun(fs.mkdtempSync(path.join(os.tmpdir(), 'gsd-4834-k2-path-')));
const fakeRuntime = fs.mkdtempSync(path.join(os.tmpdir(), 'gsd-4834-k2-rt-'));
t.after(() => {
cleanupDir(project); cleanupDir(projectControl);
cleanup(fakeHome); cleanup(foreignBin); cleanup(fakeRuntime);
});
// Install the REAL tool in the full install shape: gsd-tools.cjs resolves
// ensure-runtime-build.cjs and lib/ beside itself, and lib modules reach
// repo-root-relative `scripts/` helpers (`../../../scripts/...` from
// bin/lib) — so the fixture root plays the repo root: gsd-core/bin plus
// the tracked scripts tree beside it.
const fixtureRoot = path.join(fakeHome, '.claude');
fs.cpSync(path.join(__dirname, '..', 'gsd-core', 'bin'), path.join(fixtureRoot, 'gsd-core', 'bin'), { recursive: true });
fs.cpSync(path.join(__dirname, '..', 'scripts'), path.join(fixtureRoot, 'scripts'), { recursive: true });
fs.writeFileSync(
path.join(project, '.planning', 'config.json'),
JSON.stringify({ git: { branching_strategy: 'none', allow_default_branch_commits: true } }),
);
fs.writeFileSync(
path.join(projectControl, '.planning', 'config.json'),
JSON.stringify({ git: { branching_strategy: 'none' } }),
);
const snippet = fs.readFileSync(SNIPPET_FILE, 'utf8');
const runQuery = (cwd) => {
const scriptPath = path.join(cwd, 'test-4834-e2e.sh');
fs.writeFileSync(
scriptPath,
`unset GSD_TOOLS\n` +
`export RUNTIME_DIR=${JSON.stringify(fakeRuntime)}\n` +
`export HOME=${JSON.stringify(fakeHome)}\n` +
`cd ${JSON.stringify(cwd)}\n` +
snippet +
`\ngsd_run query git.base-branch --is-protected master\n`,
);
const { isolatedPath, nodeBinDir: nodeDir } = buildIsolatedPath();
t.after(() => cleanup(nodeDir));
const testPath = [foreignBin, isolatedPath].join(path.delimiter);
return runHookSeam(scriptPath, [], {
interpreter: 'bash',
env: snippetEnv({ PATH: testPath, HOME: fakeHome }),
});
};
const withOverride = runQuery(project);
assert.equal(withOverride.exitCode, 0, `launcher must resolve and run the local tool: ${(withOverride.stderr || '').trim()}`);
const withoutOverride = runQuery(projectControl);
assert.equal(withoutOverride.exitCode, 0, `control run must also resolve: ${(withoutOverride.stderr || '').trim()}`);
// The real tool's own stdout is exactly `false` / `true` (the override is
// honored, then the control proves the query can go the other way).
assert.equal(
withOverride.stdout.trim().split('\n').pop(),
'false',
`Expected the local tool to honor git.allow_default_branch_commits, got:\n${withOverride.stdout.trim()}`,
);
assert.equal(
withoutOverride.stdout.trim().split('\n').pop(),
'true',
`Expected the control project to report master as protected, got:\n${withoutOverride.stdout.trim()}`,
);
});
// ─── (D2) identity-gated PATH arm fails closed (#4834) ────────────────────
test('(D2) a foreign gsd_run on PATH with no local install still hard-errors (#4834)', (t) => {
// Without the gate, the foreign tool is accepted silently (warning only)
// and the verb runs against it. With the gate, resolution falls through
// every remaining arm and lands in the hard error — the fail-closed
// terminal the #3146 design names.
const fakeHome = fs.mkdtempSync(path.join(os.tmpdir(), 'gsd-4834-nohome-'));
const fakeRuntime = fs.mkdtempSync(path.join(os.tmpdir(), 'gsd-4834-nort-'));
const foreignBin = writeForeignGsdRun(fs.mkdtempSync(path.join(os.tmpdir(), 'gsd-4834-nofx-')));
t.after(() => { cleanup(fakeHome); cleanup(fakeRuntime); cleanup(foreignBin); });
const snippet = fs.readFileSync(SNIPPET_FILE, 'utf8');
const scriptContent =
`unset GSD_TOOLS\n` +
`export RUNTIME_DIR=${JSON.stringify(fakeRuntime)}\n` +
`export HOME=${JSON.stringify(fakeHome)}\n` +
snippet +
`\ngsd_run ping test\n`;
const scriptPath = path.join(fakeRuntime, 'test-4834-allfail.sh');
fs.writeFileSync(scriptPath, scriptContent);
const isolated = buildIsolatedPath();
t.after(() => cleanup(isolated.nodeBinDir));
const testPath = [foreignBin, isolated.isolatedPath].join(path.delimiter);
const r = runHookSeam(scriptPath, [], {
interpreter: 'bash',
env: snippetEnv({ PATH: testPath, HOME: fakeHome }),
});
assert.ok(r.exitCode !== 0, 'Expected non-zero exit when only a foreign gsd_run resolves and no local install exists');
assert.ok(
(r.stderr || '').includes('ERROR: gsd-tools.cjs not found'),
`Expected stderr to contain "ERROR: gsd-tools.cjs not found", got: ${(r.stderr || '').trim()}`,
);
});
// ─── (L) config-home install outranks an identity-proving PATH gsd_run (#4834) ──
test('(L) a runtime-config-home install outranks an identity-proving gsd_run on PATH (#4834)', (t) => {
// Reorder semantics: installer-managed config-home installs win even when
// the PATH entry is genuine (identity-proving) — a stale-but-real global
// must not shadow the local install the same way the pre-1.7.0 one did.
const fakeHome = fs.mkdtempSync(path.join(os.tmpdir(), 'gsd-4834-l-home-'));
const fakeRuntime = fs.mkdtempSync(path.join(os.tmpdir(), 'gsd-4834-l-rt-'));
const pathBinDir = fs.mkdtempSync(path.join(os.tmpdir(), 'gsd-4834-l-path-'));
writeIdentityLocalStub(fakeHome);
fs.mkdirSync(pathBinDir, { recursive: true });
fs.writeFileSync(
path.join(pathBinDir, 'gsd_run'),
'#!/bin/sh\n' +
'if [ "$1" = "runtime-identity" ] && [ "$2" = "--raw" ]; then\n' +
' echo \'{"packageName":"@opengsd/gsd-core","version":"1.13.0-global"}\'\n' +
'else\n' +
' echo "PATHSTUB:$*"\n' +
'fi\n',
);
fs.chmodSync(path.join(pathBinDir, 'gsd_run'), 0o755);
t.after(() => { cleanup(fakeHome); cleanup(fakeRuntime); cleanup(pathBinDir); });
const snippet = fs.readFileSync(SNIPPET_FILE, 'utf8');
const scriptContent =
`unset GSD_TOOLS\n` +
`export RUNTIME_DIR=${JSON.stringify(fakeRuntime)}\n` +
`export HOME=${JSON.stringify(fakeHome)}\n` +
snippet +
`\nprintf "GSD_TOOLS=%s\\n" "$GSD_TOOLS"\n` +
`gsd_run query state.json\n`;
const scriptPath = path.join(fakeRuntime, 'test-4834-local-wins.sh');
fs.writeFileSync(scriptPath, scriptContent);
const { isolatedPath, nodeBinDir } = buildIsolatedPath();
t.after(() => cleanup(nodeBinDir));
const testPath = [pathBinDir, isolatedPath].join(path.delimiter);
const stdout = runBashFile(scriptPath, {
env: { PATH: testPath, HOME: fakeHome },
});
const normStdout = stdout.replace(/\\/g, '/');
assert.ok(
normStdout.includes('.claude/gsd-core/bin/'),
`Expected the config-home install to outrank the PATH entry, got:\n${stdout.trim()}`,
);
assert.ok(
stdout.includes('LOCAL:query,state.json'),
`Expected the local tool to answer the query, got:\n${stdout.trim()}`,
);
assert.ok(
!stdout.includes('PATHSTUB:'),
`Expected the identity-proving PATH stub not to be invoked, got:\n${stdout.trim()}`,
);
});
// ─── (M) arm order and gate structure (#4834) ─────────────────────────────
test('(M) snippet arms: config homes precede the PATH arm, and the PATH arm is identity-gated (#4834)', () => {
// Structural companion to (K)/(L): the behavioral fixtures pin WHAT
// resolves; this pins the arm ORDER and the gate so a future edit cannot
// silently re-hoist PATH above the config homes or drop the identity
// proof. Shipped-text-is-the-product: the snippet's text IS the deployed
// resolver for every workflow that inlines it.
//
// allow-test-rule: structural-regression-guard (#4834)
const snippetContent = fs.readFileSync(SNIPPET_FILE, 'utf8');
const helperDefPos = snippetContent.indexOf('_gsd_homes() {');
const homesArmPos = snippetContent.indexOf('elif _gsd_homes;');
const pathArmPos = snippetContent.indexOf('command -v gsd_run');
const gatePos = snippetContent.indexOf('_gsd_id_ok "$_G"');
assert.ok(helperDefPos !== -1, 'snippet must define the _gsd_homes helper (shared config-home candidate list)');
assert.ok(homesArmPos !== -1, 'snippet must probe config homes through _gsd_homes in the elif chain');
assert.ok(pathArmPos !== -1, 'snippet must keep the PATH fallback arm');
assert.ok(gatePos !== -1, 'snippet must gate the PATH arm on _gsd_id_ok "$_G"');
assert.ok(
homesArmPos < pathArmPos,
`config-home arm (at ${homesArmPos}) must precede the PATH arm (at ${pathArmPos}) — local installs outrank PATH`,
);
const acceptPos = snippetContent.indexOf('GSD_TOOLS="$_G"', gatePos);
assert.ok(
acceptPos !== -1,
'the PATH arm must still assign GSD_TOOLS="$_G" after the gate',
);
});
// ─── (N) delegation roster: the size-capped files load the shared resolver ──
test('(N) the #4834 delegation roster loads the resolver by @-include, not inline (#4834)', () => {
// The LARGE agents and the ceiling-capped workflows sat within 3-73 bytes
// of their hard caps, so no snippet growth could ship inline. These files
// delegate instead (the onboard.md pattern): the @-include loads
// gsd-run-resolver.md — byte-equal to the snippet per (B2) — and the sync
// script neither requires nor inserts an inline preamble for them. Pin
// the roster so a future edit cannot silently re-inline (blowing the
// caps) or drop the @-include (dropping the launcher).
//
// allow-test-rule: structural-regression-guard (#4834)
const DELEGATION_ROSTER = [
'gsd-executor.md',
'gsd-plan-checker.md',
'gsd-verifier.md',
'gsd-planner.md',
];
const WORKFLOW_DELEGATION_ROSTER = [
'execute-phase.md',
'execute-plan.md',
];
const problems = [];
for (const name of DELEGATION_ROSTER) {
const content = fs.readFileSync(path.join(AGENTS_DIR, name), 'utf8');
if (!content.includes('references/gsd-run-resolver.md')) {
problems.push(`${name}: missing the gsd-run-resolver.md @-include`);
}
if (content.includes('_GSD_SHIM_NAME=')) {
problems.push(`${name}: carries an inline preamble — re-inline it only if its size cap has real headroom`);
}
}
for (const rel of WORKFLOW_DELEGATION_ROSTER) {
const content = fs.readFileSync(path.join(WORKFLOWS_DIR, rel), 'utf8');
if (!content.includes('references/gsd-run-resolver.md')) {
problems.push(`${rel}: missing the gsd-run-resolver.md @-include`);
}
if (content.includes('_GSD_SHIM_NAME=')) {
problems.push(`${rel}: carries an inline preamble — re-inline it only if its size cap has real headroom`);
}
}
assert.deepStrictEqual(problems, [], 'delegation roster violations:\n' + problems.join('\n'));
});
// ─── (G) ~/.claude fallback arm is present (#211) ───────────────────────────
test('(G) snippet and all propagated workflow .md files contain the $HOME/.claude fallback arm between PATH check and hard error', () => {
// The resolution order must be:
// (1) local/RUNTIME_DIR → (2) PATH → (3) $HOME/.claude/gsd-core/bin → (4) hard error
// (1) local/RUNTIME_DIR → (2) runtime config homes → (3) identity-gated PATH → (4) hard error
// (#4834 moved the config homes ahead of PATH and gated PATH on
// runtime-identity proof; the probe itself still sits between the
// `command -v gsd_run` elif and the hard-error else branch.)
// We probe for .claude/gsd-core/bin (using ${_GSD_SHIM_NAME} indirection)
// between the `command -v gsd_run` elif and the hard-error else branch.
const CLAUDE_HOME_PROBE = '.claude/gsd-core/bin/';
@@ -991,6 +1347,11 @@ describe('runtime-launcher-parity — agents (#1041)', () => {
for (const f of files) {
const rel = path.relative(AGENTS_DIR, f);
const content = fs.readFileSync(f, 'utf8');
// Files that delegate to the shared resolver reference (@-include) do not
// inline the preamble — exempt them, mirroring (B)'s workflow-side skip
// (#4834: the size-capped LARGE agents delegate; their resolver comes
// from the byte-equal reference pinned by (B2) and the (N) roster).
if (delegatesToResolverReference(content)) continue;
const blocks = extractShellBlocks(content);
// Collect all block lines in document order for flat analysis
@@ -1061,8 +1422,8 @@ describe('runtime-launcher-parity — agents (#1041)', () => {
* (B) A representative propagated workflow file contains the ~/.claude fallback arm.
* (C) Behavioral: when RUNTIME_DIR misses and gsd_run is NOT on PATH,
* a stub at $HOME/.claude/gsd-core/bin/gsd-tools.cjs is resolved and invoked.
* (D) The resolution order is preserved: local -> PATH -> ~/.claude -> hard error.
* When all three miss, exit non-zero.
* (D) All arms miss -> hard error (#4834 reordered: local -> config homes ->
* identity-gated PATH -> hard error). When all of them miss, exit non-zero.
*/
// allow-test-rule: structural-regression-guard (see #211)
@@ -1606,21 +1967,34 @@ describe('bug-891: non-Claude runtime home fallback arms', () => {
// ── (D) Resolution order: claude < hermes < hard-error ───────────────────
test('(D) resolution order: .claude probe comes before hermes probe, hermes before hard error', () => {
const snippetContent = fs.readFileSync(SNIPPET_FILE, 'utf8');
const claudePos = snippetContent.indexOf('.claude/gsd-core/bin/');
const hermesPos = snippetContent.indexOf('.hermes}/gsd-core/bin/');
// #4834 folded the config-home probes into the _gsd_homes() helper defined
// ahead of the if-chain, so raw first-occurrence positions no longer
// express arm order — compare the probes WITHIN the helper, and the
// helper's arm against the hard error.
const helperStart = snippetContent.indexOf('_gsd_homes() {');
assert.ok(helperStart !== -1, 'Snippet must define the _gsd_homes helper');
const helperEnd = snippetContent.indexOf('; };', helperStart);
assert.ok(helperEnd !== -1, 'Snippet _gsd_homes helper must close');
const homesBody = snippetContent.slice(helperStart, helperEnd);
// The helper's claude arm reads `${CLAUDE_CONFIG_DIR:-$HOME/.claude}/...` —
// the closing brace sits between `.claude` and the slash, so probe for the
// arm text as it is actually spelled (same style as the hermes probe below).
const claudePos = homesBody.indexOf('$HOME/.claude}/gsd-core/bin/');
const hermesPos = homesBody.indexOf('.hermes}/gsd-core/bin/');
const errorPos = snippetContent.indexOf('exit 1');
assert.ok(claudePos !== -1, 'Snippet must contain .claude/gsd-core/bin/ arm');
assert.ok(claudePos !== -1, 'Snippet must contain the claude config-home arm');
assert.ok(hermesPos !== -1, 'Snippet must contain .hermes}/gsd-core/bin/ arm');
assert.ok(errorPos !== -1, 'Snippet must contain exit 1 hard-error');
assert.ok(
claudePos < hermesPos,
`Expected .claude probe (at ${claudePos}) before .hermes probe (at ${hermesPos})`,
`Expected .claude probe (at ${claudePos}) before .hermes probe (at ${hermesPos}) among the config-home probes`,
);
assert.ok(
hermesPos < errorPos,
`Expected .hermes probe (at ${hermesPos}) before exit 1 (at ${errorPos})`,
helperEnd < errorPos,
`Expected the config-home arm (ending at ${helperEnd}) before exit 1 (at ${errorPos})`,
);
});
@@ -1747,12 +2121,14 @@ function makeTempDir() {
return fs.mkdtempSync(path.join(os.tmpdir(), 'gsd-runtime-resolution-'));
}
function runResolver({ cwd, runtimeDir, pathDir }) {
function runResolver({ cwd, runtimeDir, pathDir, home }) {
// RUNTIME_DIR='' is INDISTINGUISHABLE from unset to the resolver's
// ${RUNTIME_DIR:-$(git rev-parse --show-toplevel)} — an empty value silently
// falls back to the real repo root and resolves its real install. Fail loudly
// instead; every caller passes one.
if (!runtimeDir) throw new Error('runResolver requires runtimeDir: an empty value resolves the real repo root');
// #4834: callers reaching the config-home arm must pass an empty `home` —
// with the homes arm ahead of PATH, an ambient $HOME install would win.
const script = [
'set -e',
extractResolverSnippet(),
@@ -1766,13 +2142,15 @@ function runResolver({ cwd, runtimeDir, pathDir }) {
// suite is guarded to POSIX (matches the host suite's own bash -c guard).
if (process.platform === 'win32') return '';
const envOverrides = {
PATH: `${pathDir}${path.delimiter}${process.env.PATH || ''}`,
RUNTIME_DIR: runtimeDir,
};
if (home !== undefined) envOverrides.HOME = home;
const r = runHookSeam('-c', [script], {
interpreter: 'bash',
cwd,
env: snippetEnv({
PATH: `${pathDir}${path.delimiter}${process.env.PATH || ''}`,
RUNTIME_DIR: runtimeDir,
}),
env: snippetEnv(envOverrides),
});
throwIfFailed(r, 'bash -c <runtime resolver snippet>');
return r.stdout;
@@ -1784,7 +2162,7 @@ function writeExecutable(file, content) {
}
describe('bug-3668: workflow SDK resolver supports installed user projects', { skip: process.platform === 'win32' }, () => {
test('falls back to installed gsd_run when project-local runtime copy is absent', () => {
test('falls back to installed gsd_run when project-local runtime copy is absent', (t) => {
// Bug #3668: when a user project has no local gsd-core/bin/gsd-tools.cjs,
// the elif branch must resolve to the gsd_run binary on PATH.
// RUNTIME_DIR points to a dir that has no gsd-tools.cjs.
@@ -1800,14 +2178,27 @@ describe('bug-3668: workflow SDK resolver supports installed user projects', { s
fs.mkdirSync(project, { recursive: true });
fs.mkdirSync(runtimeNoLocal, { recursive: true });
// Place gsd_run stub on PATH (installed binary)
// Place gsd_run stub on PATH (installed binary). #4834: the PATH arm is
// identity-gated, so the stub must answer `runtime-identity --raw` the
// way a real same-package install does — a bare stub now falls through
// to the hard error (that side is pinned by (D2) above).
// HOME is pinned to an empty fake home: #4834 evaluates the config-home
// arm before PATH, and an ambient $HOME/.claude install would resolve
// there first on machines that have one.
writeExecutable(
path.join(pathBin, 'gsd_run'),
'#!/bin/sh\nprintf "installed:%s %s\\n" "$1" "$2"\n',
'#!/bin/sh\n' +
'if [ "$1" = "runtime-identity" ] && [ "$2" = "--raw" ]; then\n' +
' echo \'{"packageName":"@opengsd/gsd-core","version":"installed-test"}\'\n' +
'else\n' +
' printf "installed:%s %s\\n" "$1" "$2"\n' +
'fi\n',
);
const fakeHome = makeTempDir();
t.after(() => cleanup(fakeHome));
// NO gsd-core/bin/gsd-tools.cjs in runtimeNoLocal
const output = runResolver({ cwd: project, runtimeDir: runtimeNoLocal, pathDir: pathBin });
const output = runResolver({ cwd: project, runtimeDir: runtimeNoLocal, pathDir: pathBin, home: fakeHome });
// GSD_TOOLS must have been reassigned to the PATH binary (not the missing .cjs)
assert.match(output, /GSD_TOOLS=.+gsd_run(?:\s|$)/m);
@@ -1941,11 +2332,21 @@ describe('bug-444: resolver finds repo-local .claude install', () => {
`Snippet's Claude arm must honor CLAUDE_CONFIG_DIR via \${CLAUDE_CONFIG_DIR:-$HOME/.claude}.`,
);
// Repo-local check must appear BEFORE $HOME/.claude check (local overrides global)
// Repo-local check must run BEFORE the config-home arm (local overrides
// global). #4834 folded the $HOME/.claude probe into the _gsd_homes()
// helper defined ahead of the chain, so raw first-occurrence positions no
// longer express arm order — compare the chain positions instead: the
// repo-local `if _gsd_at` arm must precede the `elif _gsd_homes` arm.
// Behavioral precedence (repo-local wins when both exist) is pinned by
// this suite's (C).
const chainStartIdx = content.indexOf('if _gsd_at "${_GSD_RUNTIME_ROOT}/gsd-core/bin/');
const homesArmIdx = content.indexOf('elif _gsd_homes;');
assert.ok(chainStartIdx !== -1, 'Snippet must contain the repo-local if _gsd_at arm');
assert.ok(homesArmIdx !== -1, 'Snippet must contain the elif _gsd_homes config-home arm');
assert.ok(
localClaudeIdx < homeClaudeIdx,
`Repo-local .claude/ check (idx ${localClaudeIdx}) must appear BEFORE ` +
`$HOME/.claude/ check (idx ${homeClaudeIdx}) in the snippet (local overrides global).`,
chainStartIdx < homesArmIdx,
`Repo-local .claude/ arm (idx ${chainStartIdx}) must run BEFORE ` +
`the config-home arm (idx ${homesArmIdx}) in the elif chain (local overrides global).`,
);
});