chore(#191): retire sdk package seam

This commit is contained in:
Tom Boucher
2026-05-25 10:58:36 -04:00
parent 04b3be6833
commit 11918dcc37
389 changed files with 109 additions and 84177 deletions

View File

@@ -13,10 +13,10 @@ function read(rel) {
test('bridge collapse removes cjs-sdk-bridge and runtime-bridge-sync seam', () => {
const bridgePath = path.join(ROOT, 'get-shit-done', 'bin', 'lib', 'cjs-sdk-bridge.cjs');
const runtimeSyncDir = path.join(ROOT, 'sdk', 'src', 'runtime-bridge-sync');
const sdkDir = path.join(ROOT, 'sdk');
assert.equal(fs.existsSync(bridgePath), false, 'cjs-sdk-bridge.cjs must be removed');
assert.equal(fs.existsSync(runtimeSyncDir), false, 'sdk/src/runtime-bridge-sync must be removed');
assert.equal(fs.existsSync(sdkDir), false, 'sdk directory must be removed');
const routers = [
'get-shit-done/bin/lib/init-command-router.cjs',
@@ -36,10 +36,10 @@ test('bridge collapse removes cjs-sdk-bridge and runtime-bridge-sync seam', () =
);
}
const sdkPkg = JSON.parse(read('sdk/package.json'));
const rootPkg = JSON.parse(read('package.json'));
assert.equal(
Object.prototype.hasOwnProperty.call(sdkPkg.dependencies || {}, 'synckit'),
Object.prototype.hasOwnProperty.call(rootPkg.dependencies || {}, 'synckit'),
false,
'sdk/package.json must not include synckit',
'package.json must not include synckit',
);
});

View File

@@ -27,7 +27,6 @@ const REPO_ROOT = path.join(__dirname, '..');
const TEMPLATE_PATHS = [
path.join(REPO_ROOT, 'get-shit-done', 'templates', 'state.md'),
path.join(REPO_ROOT, 'sdk', 'prompts', 'templates', 'state.md'),
];
/**
@@ -185,16 +184,4 @@ describe('bug #21 — STATE.md template must carry YAML frontmatter', () => {
});
}
test('both templates produce byte-equal File Template blocks', () => {
const [bodyA, bodyB] = TEMPLATE_PATHS.map((p) =>
extractFileTemplate(fs.readFileSync(p, 'utf-8')),
);
assert.strictEqual(
bodyA,
bodyB,
'File Template code blocks in get-shit-done/templates/state.md and ' +
'sdk/prompts/templates/state.md must be identical. ' +
'Edit both files together to keep them in sync.',
);
});
});

View File

@@ -1,75 +0,0 @@
/**
* Regression test for bug #2334
*
* /gsd-quick crashed with `command not found: gsd-sdk` (exit code 127) when
* the gsd-sdk binary was not installed or not in PATH. The workflow's Step 2
* called `gsd-sdk query init.quick` directly with no pre-flight check and no
* fallback, so missing gsd-sdk caused an immediate abort with no helpful message.
*
* Fix: Step 2 must check for gsd-sdk in PATH before invoking it. If absent,
* emit a human-readable error pointing users to the install command.
*/
'use strict';
const { test, describe } = require('node:test');
const assert = require('node:assert/strict');
const fs = require('fs');
const path = require('path');
const WORKFLOW_PATH = path.join(__dirname, '..', 'get-shit-done', 'workflows', 'quick.md');
// allow-test-rule: source-text-is-the-product
// quick.md is the AI instruction workflow — the `command -v gsd-sdk` guard IS the fix.
// There is no behavioral equivalent: the check runs inside the AI agent, not in gsd-tools.
describe('bug #2334: quick workflow gsd-sdk pre-flight check', () => {
let content;
test('workflow file exists', () => {
assert.ok(fs.existsSync(WORKFLOW_PATH), 'workflows/quick.md should exist');
content = fs.readFileSync(WORKFLOW_PATH, 'utf-8');
});
test('Step 2 checks for gsd-sdk before invoking it', () => {
content = content || fs.readFileSync(WORKFLOW_PATH, 'utf-8');
// The check must appear before the first gsd-sdk invocation in Step 2.
// After the #3797 architectural fix, callsites use $GSD_SDK (not bare gsd-sdk),
// so we search for the $GSD_SDK form of the init.quick call.
const step2Start = content.indexOf('**Step 2:');
assert.ok(step2Start !== -1, 'Step 2 must exist in quick workflow');
// Accept either the bare form (legacy) or the $GSD_SDK form (post-#3797)
let firstSdkCall = content.indexOf('$GSD_SDK query init.quick', step2Start);
if (firstSdkCall === -1) {
firstSdkCall = content.indexOf('gsd-sdk query init.quick', step2Start);
}
assert.ok(firstSdkCall !== -1, 'gsd-sdk query init.quick must be present in Step 2');
// Find any gsd-sdk availability check between the Step 2 heading and the first call
const step2Section = content.slice(step2Start, firstSdkCall);
const hasCommandCheck = step2Section.includes('command -v gsd-sdk') || step2Section.includes('which gsd-sdk');
assert.ok(
hasCommandCheck,
'Step 2 must check for gsd-sdk in PATH (via `command -v gsd-sdk` or `which gsd-sdk`) ' +
'before calling `gsd-sdk query init.quick`. Without this guard, the workflow crashes ' +
'with exit code 127 when gsd-sdk is not installed (root cause of #2334).'
);
});
test('pre-flight error message references the install command', () => {
content = content || fs.readFileSync(WORKFLOW_PATH, 'utf-8');
const step2Start = content.indexOf('**Step 2:');
// Accept either form of the SDK call (bare or $GSD_SDK)
let firstSdkCall = content.indexOf('$GSD_SDK query init.quick', step2Start);
if (firstSdkCall === -1) {
firstSdkCall = content.indexOf('gsd-sdk query init.quick', step2Start);
}
const step2Section = content.slice(step2Start, firstSdkCall);
const hasInstallHint = step2Section.includes('@opengsd/get-shit-done-redux') || step2Section.includes('gsd-update') || step2Section.includes('/gsd-update');
assert.ok(
hasInstallHint,
'Pre-flight error must include a hint on how to install query-capable gsd-sdk (npm install -g @opengsd/get-shit-done-redux or /gsd-update)'
);
});
});

View File

@@ -1,86 +0,0 @@
// allow-test-rule: pending-migration-to-typed-ir [#2974]
// Tracked in #2974 for migration to typed-IR assertions per CONTRIBUTING.md
// "Prohibited: Raw Text Matching on Test Outputs". Per-file review may
// reclassify some entries as source-text-is-the-product during migration.
/**
* Regression test for bug #2439
*
* /gsd-set-profile crashed with `command not found: gsd-sdk` when the
* gsd-sdk binary was not installed or not in PATH. The command body
* invoked `gsd-sdk query config-set-model-profile` directly with no
* pre-flight check, so missing gsd-sdk produced an opaque shell error.
*
* Fix mirrors bug #2334: guard the invocation with `command -v gsd-sdk`
* and emit an install hint when absent.
*/
'use strict';
const { test, describe } = require('node:test');
const assert = require('node:assert/strict');
const fs = require('fs');
const path = require('path');
// #2790: set-profile.md was consolidated into config.md as the --profile flag.
// The gsd-sdk pre-flight check logic moved to config.md body.
const COMMAND_PATH = path.join(__dirname, '..', 'commands', 'gsd', 'config.md');
describe('bug #2439: /gsd-set-profile gsd-sdk pre-flight check', () => {
test('command file exists (config.md — absorbed set-profile in #2790)', () => {
assert.ok(fs.existsSync(COMMAND_PATH), 'commands/gsd/config.md should exist (absorbed set-profile)');
});
test('config.md --profile flag references gsd-sdk config-set-model-profile', () => {
const content = fs.readFileSync(COMMAND_PATH, 'utf-8');
assert.ok(
content.includes('gsd-sdk query config-set-model-profile') || content.includes('config-set-model-profile'),
'config.md must reference gsd-sdk query config-set-model-profile for --profile flag'
);
});
test('pre-flight guard for #2439 is explicitly documented in config.md --profile path', () => {
// The original #2439 bug: gsd-sdk was invoked with no pre-flight check, producing
// an opaque "command not found: gsd-sdk" error.
//
// Structural assertion (no raw .includes() on the whole file): isolate the
// <context> block, locate the --profile branch, then verify it documents both
// (a) the pre-flight check (`command -v gsd-sdk`) and (b) the install hint
// BEFORE the gsd-sdk invocation. Otherwise the regression returns silently.
const content = fs.readFileSync(COMMAND_PATH, 'utf-8');
const ctxMatch = content.match(/<context>([\s\S]*?)<\/context>/);
assert.ok(ctxMatch, 'config.md must contain a <context> block describing flag routing');
const ctx = ctxMatch[1];
// Find the --profile bullet (everything from the --profile mention up to the
// next top-level `- ` bullet that does not start with `--profile`).
const profileBranchMatch = ctx.match(/- If it starts with `--profile`[\s\S]*?(?=\n- (?!\s)[A-Z])/);
assert.ok(profileBranchMatch, 'config.md <context> must contain a --profile branch');
const profileBranch = profileBranchMatch[0];
// (a) pre-flight check token
assert.ok(
/command -v gsd-sdk/.test(profileBranch),
'config.md --profile branch must document `command -v gsd-sdk` pre-flight check (#2439)'
);
// (b) install hint near the guard, not after the invocation
assert.ok(
/install/i.test(profileBranch),
'config.md --profile branch must surface an install hint when gsd-sdk is absent (#2439)'
);
// (c) #2439 reference so future maintainers can trace the contract
assert.ok(
/#2439/.test(profileBranch),
'config.md --profile branch must cite #2439 so the regression contract is discoverable'
);
// (d) ordering: the pre-flight guard text must appear BEFORE the actual
// `gsd-sdk query config-set-model-profile` invocation in the same branch.
const guardIdx = profileBranch.indexOf('command -v gsd-sdk');
const invokeIdx = profileBranch.indexOf('gsd-sdk query config-set-model-profile');
assert.notEqual(guardIdx, -1, 'guard token missing');
assert.notEqual(invokeIdx, -1, 'invocation token missing');
assert.ok(guardIdx < invokeIdx, 'pre-flight guard must appear before the gsd-sdk invocation (#2439 contract)');
});
});

View File

@@ -1,170 +0,0 @@
// allow-test-rule: pending-migration-to-typed-ir [#2974]
// Tracked in #2974 for migration to typed-IR assertions per CONTRIBUTING.md
// "Prohibited: Raw Text Matching on Test Outputs". Per-file review may
// reclassify some entries as source-text-is-the-product during migration.
/**
* Regression tests for fix/2441-sdk-decouple
*
* Verifies the architectural invariants introduced by the SDK decouple:
*
* (a) bin/install.js does NOT invoke `npm install -g` for the SDK at all.
* The old `installSdkIfNeeded()` built from source and ran `npm install -g .`
* in sdk/; the new version only verifies the prebuilt dist.
*
* (b) The parent package.json declares a `gsd-sdk` bin entry pointing at
* bin/gsd-sdk.js (the back-compat shim), so npm chmods it correctly.
*
* (c) sdk/dist/ is in the parent package `files` so it ships in the tarball.
*
* (d) sdk/package.json `prepublishOnly` runs `rm -rf dist && tsc && chmod +x dist/cli.js`
* (guards against the mode-644 bug and npm's stale-prepublishOnly issue).
*/
'use strict';
const { test, describe } = require('node:test');
const assert = require('node:assert/strict');
const fs = require('fs');
const path = require('path');
const INSTALL_JS = path.join(__dirname, '..', 'bin', 'install.js');
const ROOT_PKG = path.join(__dirname, '..', 'package.json');
const SDK_PKG = path.join(__dirname, '..', 'sdk', 'package.json');
const GSD_SDK_SHIM = path.join(__dirname, '..', 'bin', 'gsd-sdk.js');
const installContent = fs.readFileSync(INSTALL_JS, 'utf-8');
const rootPkg = JSON.parse(fs.readFileSync(ROOT_PKG, 'utf-8'));
const sdkPkg = JSON.parse(fs.readFileSync(SDK_PKG, 'utf-8'));
describe('fix #2441: SDK decouple — installer no longer builds from source', () => {
test('bin/install.js does not call npm install -g in sdk/', () => {
// The old approach ran `npm install -g .` from sdk/. This must be gone.
// We check for the specific pattern that installed the SDK globally.
const hasGlobalInstallFromSdk =
/spawnSync\(npmCmd,\s*\[['"]install['"],\s*['"](-g|--global)['"]/m.test(installContent) &&
/cwd:\s*sdkDir/.test(installContent);
assert.ok(
!hasGlobalInstallFromSdk,
'bin/install.js must not run `npm install -g .` from sdk/. ' +
'The SDK is shipped prebuilt in the tarball (fix #2441).'
);
});
test('bin/install.js does not run npm run build in sdk/', () => {
// The old approach ran `npm run build` (tsc) at install time.
const hasBuildStep =
/spawnSync\(npmCmd,\s*\[['"]run['"],\s*['"]build['"]\]/m.test(installContent) &&
/cwd:\s*sdkDir/.test(installContent);
assert.ok(
!hasBuildStep,
'bin/install.js must not run `npm run build` in sdk/ at install time. ' +
'TypeScript compilation happens at publish time via prepublishOnly.'
);
});
test('installSdkIfNeeded checks sdk/dist/cli.js exists instead of building', () => {
assert.ok(
installContent.includes('sdk/dist/cli.js') || installContent.includes("'dist', 'cli.js'"),
'installSdkIfNeeded() must reference sdk/dist/cli.js to verify the prebuilt dist.'
);
});
});
describe('fix #2441: back-compat shim — parent package bin entry', () => {
test('root package.json declares gsd-sdk bin entry', () => {
assert.ok(
rootPkg.bin && rootPkg.bin['gsd-sdk'],
'root package.json must have a bin["gsd-sdk"] entry for the back-compat shim.'
);
});
test('gsd-sdk bin entry points at bin/gsd-sdk.js', () => {
assert.equal(
rootPkg.bin['gsd-sdk'],
'bin/gsd-sdk.js',
'bin["gsd-sdk"] must point at bin/gsd-sdk.js'
);
});
test('bin/gsd-sdk.js shim file exists', () => {
assert.ok(
fs.existsSync(GSD_SDK_SHIM),
'bin/gsd-sdk.js must exist as the back-compat PATH shim.'
);
});
test('bin/gsd-sdk.js resolves sdk/dist/cli.js relative to itself', () => {
const shimContent = fs.readFileSync(GSD_SDK_SHIM, 'utf-8');
// Require the actual path.resolve call with the expected segments, not
// loose substring matches that would pass from comments or shebangs.
assert.match(
shimContent,
/path\.resolve\(\s*__dirname\s*,\s*['"]\.\.['"]\s*,\s*['"]sdk['"]\s*,\s*['"]dist['"]\s*,\s*['"]cli\.js['"]\s*\)/,
'bin/gsd-sdk.js must call path.resolve(__dirname, "..", "sdk", "dist", "cli.js") to locate the prebuilt CLI.'
);
});
test('bin/gsd-sdk.js invokes cli.js via spawnSync(process.execPath, ...)', () => {
const shimContent = fs.readFileSync(GSD_SDK_SHIM, 'utf-8');
// The shim must invoke via node (not rely on execute bit), which means
// spawnSync(process.execPath, [cliPath, ...args]).
assert.match(
shimContent,
/spawnSync\(\s*process\.execPath\s*,/,
'bin/gsd-sdk.js must spawn node via process.execPath so the execute bit on cli.js is irrelevant (#2453).'
);
assert.match(
shimContent,
/process\.argv\.slice\(\s*2\s*\)/,
'bin/gsd-sdk.js must forward user args via process.argv.slice(2).'
);
assert.match(
shimContent,
/process\.exit\(/,
'bin/gsd-sdk.js must propagate the child exit status via process.exit.'
);
});
});
describe('fix #2441: sdk/dist shipped in tarball', () => {
test('root package.json files includes sdk/dist', () => {
assert.ok(
Array.isArray(rootPkg.files) && rootPkg.files.some(f => f === 'sdk/dist' || f.startsWith('sdk/dist')),
'root package.json files must include "sdk/dist" so the prebuilt CLI ships in the tarball.'
);
});
test('root package.json files still includes sdk/src (for dev/clone builds)', () => {
assert.ok(
Array.isArray(rootPkg.files) && rootPkg.files.some(f => f === 'sdk/src' || f.startsWith('sdk/src')),
'root package.json files should still include sdk/src for developer builds.'
);
});
});
describe('fix #2453: sdk/package.json prepublishOnly guards execute bit', () => {
test('sdk prepublishOnly deletes old dist before build (npm stale-prepublishOnly guard)', () => {
const prepub = sdkPkg.scripts && sdkPkg.scripts.prepublishOnly;
assert.ok(
prepub && prepub.includes('rm -rf dist'),
'sdk/package.json prepublishOnly must start with `rm -rf dist` to avoid stale build output.'
);
});
test('sdk prepublishOnly chmods dist/cli.js after tsc', () => {
const prepub = sdkPkg.scripts && sdkPkg.scripts.prepublishOnly;
assert.ok(
prepub && prepub.includes('chmod +x dist/cli.js'),
'sdk/package.json prepublishOnly must run `chmod +x dist/cli.js` after tsc to fix mode-644 (#2453).'
);
});
test('sdk prepublishOnly runs tsc', () => {
const prepub = sdkPkg.scripts && sdkPkg.scripts.prepublishOnly;
assert.ok(
prepub && prepub.includes('tsc'),
'sdk/package.json prepublishOnly must include tsc to compile TypeScript.'
);
});
});

View File

@@ -21,13 +21,7 @@ const path = require('path');
const PLAN_PHASE = path.join(__dirname, '..', 'get-shit-done', 'workflows', 'plan-phase.md');
const VERIFY_PHASE = path.join(__dirname, '..', 'get-shit-done', 'workflows', 'verify-phase.md');
const CONFIG_TS = path.join(__dirname, '..', 'sdk', 'src', 'config.ts');
const CONFIG_MUTATION_TS = path.join(__dirname, '..', 'sdk', 'src', 'query', 'config-mutation.ts');
// #2653 — allowlist moved to shared schema module.
const CONFIG_SCHEMA_TS = path.join(__dirname, '..', 'sdk', 'src', 'query', 'config-schema.ts');
const CONFIG_GATES_TS = path.join(__dirname, '..', 'sdk', 'src', 'query', 'config-gates.ts');
const QUERY_INDEX_TS = path.join(__dirname, '..', 'sdk', 'src', 'query', 'registry-assembly.ts');
const QUERY_ASSEMBLY_DESCRIPTOR_TS = path.join(__dirname, '..', 'sdk', 'src', 'query', 'registry-assembly-descriptor.ts');
const SCHEMA_MANIFEST_JSON = path.join(__dirname, '..', 'get-shit-done', 'bin', 'shared', 'config-schema.manifest.json');
describe('plan-phase decision-coverage gate (#2492)', () => {
const md = fs.readFileSync(PLAN_PHASE, 'utf-8');
@@ -142,41 +136,12 @@ describe('verify-phase decision-coverage gate (#2492)', () => {
});
});
describe('SDK wiring for #2492 gates', () => {
test('config.ts WorkflowConfig has context_coverage_gate key', () => {
const c = fs.readFileSync(CONFIG_TS, 'utf-8');
assert.ok(c.includes('context_coverage_gate'), 'WorkflowConfig must declare context_coverage_gate');
assert.ok(
/context_coverage_gate:\s*true/.test(c),
'CONFIG_DEFAULTS.workflow.context_coverage_gate must default to true',
);
});
test('config-schema.ts VALID_CONFIG_KEYS allows workflow.context_coverage_gate', () => {
// #2653 — allowlist moved out of config-mutation.ts into shared config-schema.ts.
// After Cycle 5 (#3536), config-schema.ts is a thin adapter; verify via the
// manifest (the single source of truth for both CJS and SDK).
const manifestPath = path.join(__dirname, '..', 'sdk', 'shared', 'config-schema.manifest.json');
const manifest = JSON.parse(fs.readFileSync(manifestPath, 'utf-8'));
describe('runtime wiring for #2492 gates', () => {
test('schema manifest includes context_coverage_gate', () => {
const manifest = JSON.parse(fs.readFileSync(SCHEMA_MANIFEST_JSON, 'utf-8'));
assert.ok(
manifest.validKeys.includes('workflow.context_coverage_gate'),
'workflow.context_coverage_gate must be in manifest validKeys (SDK config-schema.ts sources from manifest)',
'workflow.context_coverage_gate must be present in config-schema manifest',
);
});
test('config-gates.ts surfaces context_coverage_gate', () => {
const c = fs.readFileSync(CONFIG_GATES_TS, 'utf-8');
assert.ok(
c.includes('context_coverage_gate'),
'check.config-gates must expose context_coverage_gate to workflows',
);
});
test('query registry assembly registers the new handlers', () => {
const c = fs.readFileSync(QUERY_INDEX_TS, 'utf-8');
const d = fs.readFileSync(QUERY_ASSEMBLY_DESCRIPTOR_TS, 'utf-8');
assert.ok(c.includes('REGISTRY_ASSEMBLY_PLAN'), 'registry assembly must be driven by declarative plan');
assert.ok(d.includes('VERIFY_DECISION_STATIC_CATALOG'), 'decision-coverage handlers must be sourced from verify-decision catalog');
assert.ok(d.includes("{ kind: 'static', key: 'VERIFY_DECISION_STATIC_CATALOG' }"), 'verify-decision catalog must be present in assembly plan');
});
});

View File

@@ -1,77 +0,0 @@
/**
* Regression test for #2519: @opengsd/gsd-sdk tarball shipped without dist/
*
* The published 0.1.0 tarball lacked a `files` whitelist including `dist/` and
* a `prepublishOnly` hook to build `dist/` before publish. As a result the
* tarball contained only source and the declared `bin` target `./dist/cli.js`
* was absent at install time, breaking every `gsd-sdk query …` call.
*
* This test guards sdk/package.json so future edits cannot silently drop
* either safeguard.
*/
'use strict';
const { describe, test } = require('node:test');
const assert = require('node:assert/strict');
const fs = require('fs');
const path = require('path');
const SDK_PACKAGE_JSON = path.join(__dirname, '..', 'sdk', 'package.json');
describe('bug #2519: sdk/package.json ships dist/ in tarball', () => {
const pkg = JSON.parse(fs.readFileSync(SDK_PACKAGE_JSON, 'utf-8'));
test('has a files whitelist (array) so publish is explicit', () => {
assert.ok(
Array.isArray(pkg.files),
'sdk/package.json must declare a `files` array so the tarball contents are explicit',
);
assert.ok(
pkg.files.length > 0,
'`files` array must not be empty',
);
});
test('files whitelist includes dist/ so compiled output is published', () => {
assert.ok(Array.isArray(pkg.files), '`files` must be an array');
const includesDist = pkg.files.some((entry) => {
if (typeof entry !== 'string') return false;
const normalized = entry.replace(/\\/g, '/').replace(/^\.\//, '');
return /^dist(?:$|\/|\/\*\*|\/\*\*\/\*)/.test(normalized);
});
assert.ok(
includesDist,
`sdk/package.json \`files\` must include "dist" so the published tarball contains the compiled CLI (bin target ./dist/cli.js). Found: ${JSON.stringify(pkg.files)}`,
);
});
test('has prepublishOnly script that runs a build', () => {
assert.ok(
pkg.scripts && typeof pkg.scripts === 'object',
'sdk/package.json must have a `scripts` object',
);
const prepub = pkg.scripts.prepublishOnly;
assert.ok(
typeof prepub === 'string' && prepub.length > 0,
'sdk/package.json must define `scripts.prepublishOnly` so dist/ is (re)built before every publish',
);
// Must invoke a build — either `npm run build`, `tsc`, or similar.
const looksLikeBuild = /\b(build|tsc)\b/.test(prepub);
assert.ok(
looksLikeBuild,
`scripts.prepublishOnly must run a build command (e.g. "npm run build" or "tsc"). Got: ${JSON.stringify(prepub)}`,
);
});
test('bin target lives under dist/ (sanity: the thing files+prepublish must ship)', () => {
assert.ok(pkg.bin, 'sdk/package.json must declare a `bin` field');
const binValues = typeof pkg.bin === 'string'
? [pkg.bin]
: Object.values(pkg.bin);
assert.ok(
binValues.some((p) => typeof p === 'string' && p.includes('dist/')),
`bin target must reference dist/ — otherwise the files+prepublishOnly guard is pointless. Got: ${JSON.stringify(pkg.bin)}`,
);
});
});

View File

@@ -1,108 +0,0 @@
'use strict';
// allow-test-rule: pending-migration-to-typed-ir [#2974]
// Tracked in #2974 for migration to typed-IR assertions per CONTRIBUTING.md
// "Prohibited: Raw Text Matching on Test Outputs". Do not copy this pattern.
/**
* Bug #2524: gsd-sdk query --ws <name> silently ignores the workstream flag.
*
* This file is structural/static coverage only (source-file assertions).
* Runtime forwarding coverage for the query adapter path lives in:
* sdk/src/query/query-cli-adapter.test.ts
*
* Uses static source-file text assertions (no sdk/dist/ build required in CI).
*/
const { test, describe } = require('node:test');
const assert = require('node:assert/strict');
const fs = require('node:fs');
const path = require('node:path');
const helpersTs = fs.readFileSync(
path.join(__dirname, '../sdk/src/query/helpers.ts'),
'utf-8',
);
const registryTs = fs.readFileSync(
path.join(__dirname, '../sdk/src/query/registry.ts'),
'utf-8',
);
const cliTs = fs.readFileSync(
path.join(__dirname, '../sdk/src/cli.ts'),
'utf-8',
);
// ─── Layer 3: planningPaths() accepts workstream ───────────────────────────
describe('planningPaths() workstream support', () => {
test('planningPaths signature includes optional workstream parameter', () => {
assert.ok(
helpersTs.includes('planningPaths(projectDir: string, workstream?: string)'),
'planningPaths must accept an optional workstream parameter',
);
});
test('planningPaths uses relPlanningPath(workstream) to compute the base path', () => {
assert.ok(
helpersTs.includes('relPlanningPath(workstream)'),
'planningPaths must call relPlanningPath(workstream) to scope the base path',
);
});
test('planningPaths imports relPlanningPath from workstream-utils', () => {
assert.ok(
helpersTs.includes('relPlanningPath'),
'helpers.ts must import/use relPlanningPath from workstream-utils',
);
});
});
// ─── Layer 2: QueryRegistry.dispatch() accepts workstream ─────────────────
describe('QueryRegistry.dispatch() workstream threading', () => {
test('dispatch method signature includes workstream parameter', () => {
assert.ok(
registryTs.includes('workstream?: string'),
'dispatch() must accept an optional workstream parameter',
);
});
test('dispatch forwards workstream to the handler as third argument', () => {
assert.ok(
registryTs.includes('handler(args, projectDir, workstream)'),
'dispatch() must pass workstream as the third argument to the handler',
);
});
test('QueryHandler type accepts a third workstream argument', () => {
// QueryHandler type is defined in utils.ts, but registry.ts imports and uses it
const utilsTs = fs.readFileSync(
path.join(__dirname, '../sdk/src/query/utils.ts'),
'utf-8',
);
assert.ok(
utilsTs.includes('workstream?: string') && utilsTs.includes('QueryHandler'),
'QueryHandler type must include an optional workstream parameter',
);
});
});
// ─── Layer 1: CLI forwards args.ws to registry.dispatch() ─────────────────
describe('CLI forwards --ws to registry.dispatch()', () => {
test('cli.ts defines a ws field in ParsedCliArgs', () => {
assert.ok(
cliTs.includes('ws: string | undefined'),
'ParsedCliArgs must have a ws field typed as string | undefined',
);
});
test('cli.ts parses --ws flag from query argv', () => {
assert.ok(
cliTs.includes("if (a === '--ws' && argv[i + 1])"),
'cli.ts query permissive parser must handle the --ws flag',
);
});
});

View File

@@ -1,73 +0,0 @@
/**
* Regression guard for #2636 — `gsd-sdk query agent-skills <slug>` calls in
* workflows must NOT silently swallow failures via a bare `2>/dev/null`.
*
* Root cause of #2636: when the installed npm `@opengsd/gsd-sdk` was stale and
* the `agent-skills` handler was missing, every workflow line of the form
* AGENT_SKILLS_X=$(gsd-sdk query agent-skills <slug> 2>/dev/null)
* resolved to empty string, and the `agent_skills.<slug>` config was never
* injected into spawn prompts. No error ever surfaced.
*
* Fix: remove `2>/dev/null` from `agent-skills` calls so any SDK failure
* (stale binary, unregistered handler, runtime error) prints to the
* workflow's stderr and is visible to the user.
*
* Test scope: ONLY `gsd-sdk query agent-skills …` (the exact noun implicated
* in #2636). Other `gsd-sdk query config-get …` patterns commonly use
* `2>/dev/null || echo "default"` which IS exit-code aware (the `||` branch
* only runs on non-zero exit) and is a documented fallback pattern.
*
* Scans: get-shit-done/workflows/**\/*.md and commands/**\/*.md
*/
const { describe, test } = require('node:test');
const assert = require('node:assert/strict');
const fs = require('fs');
const path = require('path');
const REPO_ROOT = path.join(__dirname, '..');
const SCAN_ROOTS = [
path.join(REPO_ROOT, 'get-shit-done', 'workflows'),
path.join(REPO_ROOT, 'commands'),
path.join(REPO_ROOT, 'agents'),
];
function walk(dir, out) {
let entries;
try { entries = fs.readdirSync(dir, { withFileTypes: true }); } catch { return; }
for (const entry of entries) {
if (entry.name === 'node_modules' || entry.name === '.git') continue;
const full = path.join(dir, entry.name);
if (entry.isDirectory()) walk(full, out);
else if (entry.isFile() && entry.name.endsWith('.md')) out.push(full);
}
}
describe('bug #2636 — agent-skills query must not silently swallow failures', () => {
test('no `gsd-sdk query agent-skills ... 2>/dev/null` in workflows', () => {
const files = [];
for (const root of SCAN_ROOTS) walk(root, files);
assert.ok(files.length > 0, 'expected to scan some workflow/command files');
// Match `gsd-sdk query agent-skills <slug>` followed (on the same line)
// by `2>/dev/null` — the silent-swallow anti-pattern.
const ANTI = /gsd-sdk\s+query\s+agent-skills\b[^\n]*2>\/dev\/null/;
const offenders = [];
for (const file of files) {
const lines = fs.readFileSync(file, 'utf8').split('\n');
for (let i = 0; i < lines.length; i++) {
if (ANTI.test(lines[i])) {
offenders.push(path.relative(REPO_ROOT, file) + ':' + (i + 1) + ': ' + lines[i].trim());
}
}
}
assert.strictEqual(
offenders.length, 0,
'Found `gsd-sdk query agent-skills ... 2>/dev/null` (silent swallow — ' +
'root cause of #2636). Remove `2>/dev/null` so SDK failures surface.\n\n' +
offenders.join('\n'),
);
});
});

View File

@@ -1,155 +0,0 @@
/**
* Regression test for bug #2647 (also partial fix for #2649).
*
* v1.38.3 of get-shit-done-redux shipped with:
* - `files` array missing `sdk/dist`
* - `prepublishOnly` only running `build:hooks`, not `build:sdk`
*
* Result: the published tarball had no `sdk/dist/cli.js`. The `gsd-sdk`
* bin shim in `bin/gsd-sdk.js` resolves `<pkg>/sdk/dist/cli.js`, which
* didn't exist, so PATH fell through to the separately installed
* `@opengsd/gsd-sdk@0.1.0` (predates the `query` subcommand).
*
* Every `gsd-sdk query <noun>` call in workflow docs thus failed on
* fresh installs of 1.38.3.
*
* This test guards the OUTER package.json (get-shit-done-redux) so future
* edits cannot silently drop either safeguard. A sibling test at
* tests/bug-2519-sdk-tarball-dist.test.cjs guards the inner sdk package.
*
* The `npm pack` dry-run assertion makes the guard concrete: if the
* files whitelist, the prepublishOnly chain, or the shim target ever
* drift out of alignment, this fails.
*/
'use strict';
const { describe, test } = require('node:test');
const assert = require('node:assert/strict');
const fs = require('fs');
const path = require('path');
const os = require('os');
const { execFileSync } = require('child_process');
const REPO_ROOT = path.join(__dirname, '..');
const PKG_PATH = path.join(REPO_ROOT, 'package.json');
const SHIM_PATH = path.join(REPO_ROOT, 'bin', 'gsd-sdk.js');
describe('bug #2647: outer tarball ships sdk/dist so gsd-sdk query works', () => {
const pkg = JSON.parse(fs.readFileSync(PKG_PATH, 'utf-8'));
const filesField = Array.isArray(pkg.files) ? pkg.files : [];
const scripts = pkg.scripts || {};
test('package.json `files` includes sdk/dist', () => {
const hasDist = filesField.some((entry) => {
if (typeof entry !== 'string') return false;
const norm = entry.replace(/\\/g, '/').replace(/^\.\//, '');
return /^sdk\/dist(?:$|\/|\/\*\*|\/\*\*\/\*)/.test(norm);
});
assert.ok(
hasDist,
`package.json "files" must include "sdk/dist" so the compiled CLI ships in the tarball. Found: ${JSON.stringify(filesField)}`,
);
});
test('package.json declares a build:sdk script', () => {
assert.ok(
typeof scripts['build:sdk'] === 'string' && scripts['build:sdk'].length > 0,
'package.json must define scripts["build:sdk"] to compile sdk/dist before publish',
);
assert.ok(
/\bbuild\b|\btsc\b/.test(scripts['build:sdk']),
`scripts["build:sdk"] must run a build. Got: ${JSON.stringify(scripts['build:sdk'])}`,
);
});
test('package.json `prepublishOnly` invokes build:sdk', () => {
const prepub = scripts.prepublishOnly;
assert.ok(
typeof prepub === 'string' && prepub.length > 0,
'package.json must define scripts.prepublishOnly',
);
assert.ok(
/build:sdk\b/.test(prepub),
`scripts.prepublishOnly must invoke "build:sdk" so sdk/dist exists at pack time. Got: ${JSON.stringify(prepub)}`,
);
});
test('gsd-sdk bin shim resolves sdk/dist/cli.js', () => {
assert.ok(
pkg.bin && pkg.bin['gsd-sdk'] === 'bin/gsd-sdk.js',
`package.json bin["gsd-sdk"] must point at bin/gsd-sdk.js. Got: ${JSON.stringify(pkg.bin)}`,
);
const shim = fs.readFileSync(SHIM_PATH, 'utf-8');
assert.ok(
/sdk['"],\s*['"]dist['"],\s*['"]cli\.js/.test(shim) ||
/sdk\/dist\/cli\.js/.test(shim),
'bin/gsd-sdk.js must resolve ../sdk/dist/cli.js — otherwise shipping sdk/dist does not help',
);
});
test('npm pack dry-run includes sdk/dist/cli.js after build:sdk', { timeout: 180_000 }, () => {
const npmCache = fs.mkdtempSync(path.join(os.tmpdir(), 'gsd-npm-cache-'));
const npmEnv = { ...process.env, npm_config_cache: npmCache };
// Ensure the sdk is built so the pack reflects what publish would ship.
// The outer prepublishOnly chains through build:sdk, which does `npm ci && npm run build`
// inside sdk/. We emulate that here without full ci to keep the test fast:
// if sdk/dist/cli.js already exists, use it; otherwise build.
const sdkDir = path.join(REPO_ROOT, 'sdk');
const cliJs = path.join(sdkDir, 'dist', 'cli.js');
// On Windows `npm` is the shell script `npm.cmd`; without {shell:true}
// execFileSync only finds literal-name binaries and errors with ENOENT.
const isWindows = process.platform === 'win32';
const npmCmd = isWindows ? 'npm.cmd' : 'npm';
if (!fs.existsSync(cliJs)) {
// Build requires node_modules; install if missing, then build.
const sdkNodeModules = path.join(sdkDir, 'node_modules');
if (!fs.existsSync(sdkNodeModules)) {
execFileSync(npmCmd, ['ci', '--silent'], { cwd: sdkDir, stdio: 'pipe', env: npmEnv, shell: isWindows });
}
execFileSync(npmCmd, ['run', 'build'], { cwd: sdkDir, stdio: 'pipe', env: npmEnv, shell: isWindows });
}
assert.ok(fs.existsSync(cliJs), 'sdk build must produce sdk/dist/cli.js');
try {
const out = execFileSync(
npmCmd,
['pack', '--dry-run', '--json', '--ignore-scripts'],
{ cwd: REPO_ROOT, stdio: ['ignore', 'pipe', 'pipe'], env: npmEnv, shell: isWindows },
).toString('utf-8');
const manifest = JSON.parse(out);
const files = manifest[0].files.map((f) => f.path);
const cliPresent = files.includes('sdk/dist/cli.js');
assert.ok(
cliPresent,
`npm pack must include sdk/dist/cli.js in the tarball (so "gsd-sdk query" resolves after install). sdk/dist entries found: ${files.filter((p) => p.startsWith('sdk/dist')).length}`,
);
} finally {
fs.rmSync(npmCache, { recursive: true, force: true });
}
});
test('built sdk CLI exposes the `query` subcommand', { timeout: 60_000 }, () => {
const cliJs = path.join(REPO_ROOT, 'sdk', 'dist', 'cli.js');
if (!fs.existsSync(cliJs)) {
assert.fail('sdk/dist/cli.js missing — the previous test should have built it');
}
let stdout = '';
let stderr = '';
let status = 0;
try {
stdout = execFileSync(process.execPath, [cliJs, 'query', '--help'], {
stdio: ['ignore', 'pipe', 'pipe'],
}).toString('utf-8');
} catch (err) {
stdout = err.stdout ? err.stdout.toString('utf-8') : '';
stderr = err.stderr ? err.stderr.toString('utf-8') : '';
status = err.status ?? 1;
}
const combined = `${stdout}\n${stderr}`;
assert.ok(
/query/i.test(combined) && !/unknown command|unrecognized/i.test(combined),
`sdk/dist/cli.js must expose a "query" subcommand. status=${status} output=${combined.slice(0, 500)}`,
);
});
});

View File

@@ -1,194 +0,0 @@
/**
* Regression test for #2649 — installer must fail fast with a clear,
* actionable error when `sdk/dist/cli.js` is missing, and must NOT attempt
* a nested `npm install` inside the sdk directory (which, on Windows, lives
* in the read-only npx cache `%LOCALAPPDATA%\\npm-cache\\_npx\\<hash>\\...`).
*
* Shares a root cause with #2647 (packaging drops sdk/dist/). This test
* covers the installer's defensive behavior when that packaging bug — or
* any future regression that loses the prebuilt dist — reaches users.
*/
'use strict';
// Migrated to typed-IR (#2974): the previous shape used regex assertions
// against stderr to verify fix-command and missing-artifact phrases. Now
// the test calls buildSdkFailFastReport(sdkDir) directly and asserts on
// the structured IR fields (reason, context, fix_command, missing_artifact,
// attempted_nested_install). The renderer's text shape is now an
// implementation detail.
const { test, describe, before } = require('node:test');
const assert = require('node:assert/strict');
const fs = require('fs');
const os = require('os');
const path = require('path');
const INSTALL_PATH = path.join(__dirname, '..', 'bin', 'install.js');
function loadInstaller() {
process.env.GSD_TEST_MODE = '1';
delete require.cache[require.resolve(INSTALL_PATH)];
return require(INSTALL_PATH);
}
function makeTempSdk({ npxCache = false } = {}) {
let root;
if (npxCache) {
root = path.join(os.tmpdir(), `gsd-npx-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`, 'npm-cache', '_npx', 'deadbeefcafe0001', 'node_modules', 'get-shit-done-redux');
fs.mkdirSync(root, { recursive: true });
} else {
root = fs.mkdtempSync(path.join(os.tmpdir(), 'gsd-clone-'));
}
const sdkDir = path.join(root, 'sdk');
fs.mkdirSync(sdkDir, { recursive: true });
// Note: intentionally no sdk/dist/ directory.
return { root, sdkDir };
}
function cleanup(dir) {
try { fs.rmSync(dir, { recursive: true, force: true }); } catch {}
}
function runWithIntercepts(fn) {
const stderr = [];
const stdout = [];
const origErr = console.error;
const origLog = console.log;
console.error = (...a) => stderr.push(a.join(' '));
console.log = (...a) => stdout.push(a.join(' '));
const origExit = process.exit;
let exitCode = null;
process.exit = (code) => { exitCode = code; throw new Error('__EXIT__'); };
const cp = require('child_process');
const origSpawnSync = cp.spawnSync;
const origExecSync = cp.execSync;
const spawnCalls = [];
cp.spawnSync = (cmd, argv, opts) => {
spawnCalls.push({ cmd, argv, opts });
return { status: 0, stdout: Buffer.from(''), stderr: Buffer.from('') };
};
cp.execSync = (cmd, opts) => {
spawnCalls.push({ cmd, opts, via: 'execSync' });
return Buffer.from('');
};
try {
try { fn(); } catch (e) { if (e.message !== '__EXIT__') throw e; }
} finally {
console.error = origErr;
console.log = origLog;
process.exit = origExit;
cp.spawnSync = origSpawnSync;
cp.execSync = origExecSync;
}
return {
stderr: stderr.join('\n'),
stdout: stdout.join('\n'),
exitCode,
spawnCalls,
};
}
describe('installer SDK dist-missing fail-fast (#2649)', () => {
let installer;
before(() => { installer = loadInstaller(); });
test('exposes test hooks for SDK check', () => {
assert.ok(typeof installer.installSdkIfNeeded === 'function',
'installSdkIfNeeded must be exported in test mode');
assert.ok(typeof installer.classifySdkInstall === 'function',
'classifySdkInstall must be exported in test mode');
});
test('classifySdkInstall tags npx cache paths as tarball + npxCache', () => {
const { root, sdkDir } = makeTempSdk({ npxCache: true });
try {
const c = installer.classifySdkInstall(sdkDir);
assert.strictEqual(c.mode, 'tarball');
assert.strictEqual(c.npxCache, true);
assert.ok('readOnly' in c);
} finally {
cleanup(root);
}
});
test('classifySdkInstall tags plain git-clone dirs as dev-clone', () => {
const { root, sdkDir } = makeTempSdk({ npxCache: false });
try {
fs.mkdirSync(path.join(root, '.git'), { recursive: true });
const c = installer.classifySdkInstall(sdkDir);
assert.strictEqual(c.mode, 'dev-clone');
assert.strictEqual(c.npxCache, false);
} finally {
cleanup(root);
}
});
test('missing dist in npx cache: fail fast, no nested npm install', () => {
const { root, sdkDir } = makeTempSdk({ npxCache: true });
try {
// Behavioral check 1: installSdkIfNeeded exits 1 and never spawns nested npm.
const result = runWithIntercepts(() => {
installer.installSdkIfNeeded({ sdkDir });
});
assert.strictEqual(result.exitCode, 1, 'must exit non-zero');
const nestedInstall = result.spawnCalls.find((c) => {
const argv = Array.isArray(c.argv) ? c.argv : [];
const cwd = c.opts && c.opts.cwd;
const isNpm = /\bnpm(\.cmd)?$/i.test(String(c.cmd || ''));
const isInstall = argv.includes('install') || argv.includes('i');
const isInSdk = typeof cwd === 'string' && cwd.includes(sdkDir);
return isNpm && isInstall && isInSdk;
});
assert.strictEqual(nestedInstall, undefined,
'must NOT spawn `npm install` inside the npx-cache sdk dir');
// Behavioral check 2: the structured fail-fast IR identifies the npx-cache
// context, points at the right fix command, and asserts the no-nested-install
// contract via a typed boolean (no stderr grepping).
const ir = installer.buildSdkFailFastReport(sdkDir, path.join(sdkDir, 'dist', 'cli.js'));
assert.strictEqual(ir.ok, false);
assert.strictEqual(ir.reason, 'sdk_fail_fast');
assert.strictEqual(ir.context, 'npx-cache');
assert.strictEqual(ir.missing_artifact, 'sdk/dist');
assert.strictEqual(ir.fix_command, 'npm install -g @opengsd/get-shit-done-redux@latest');
assert.strictEqual(ir.attempted_nested_install, false,
'IR contract: nested-install must always be false (this is a hard invariant)');
} finally {
cleanup(root);
}
});
test('missing dist in a dev clone: fail fast with clone build hint', () => {
const { root, sdkDir } = makeTempSdk({ npxCache: false });
try {
fs.mkdirSync(path.join(root, '.git'), { recursive: true });
const result = runWithIntercepts(() => {
installer.installSdkIfNeeded({ sdkDir });
});
assert.strictEqual(result.exitCode, 1);
// Typed-IR migration #2974: dev-clone context surfaces the local-build
// fix command (not the global-install one).
const ir = installer.buildSdkFailFastReport(sdkDir, path.join(sdkDir, 'dist', 'cli.js'));
assert.strictEqual(ir.context, 'dev-clone');
assert.strictEqual(ir.fix_command, 'cd sdk && npm install && npm run build');
assert.strictEqual(ir.attempted_nested_install, false);
const nestedInstall = result.spawnCalls.find((c) => {
const argv = Array.isArray(c.argv) ? c.argv : [];
const isNpm = /\bnpm(\.cmd)?$/i.test(String(c.cmd || ''));
const isInstall = argv.includes('install') || argv.includes('i');
return isNpm && isInstall;
});
assert.strictEqual(nestedInstall, undefined,
'installer itself must never shell out to `npm install`; the user does that');
} finally {
cleanup(root);
}
});
});

View File

@@ -1,182 +0,0 @@
/**
* Regression tests for bug #2676:
* `gsd-sdk query phase.complete <N>` returns is_last_phase: true
* when the completed phase belongs to a milestone that is not the
* primary milestone recorded in STATE.md's `milestone:` field.
*
* Root cause: Step E of phaseComplete applies getMilestonePhaseFilter
* unconditionally. getMilestonePhaseFilter extracts phases from the
* milestone slice selected by STATE.md's `milestone:` field. When
* completing phase 41.2 (which belongs to vB) but STATE.md points at
* vA, all 41.x directories are excluded from the candidate set and
* the empty set causes isLastPhase = true.
*
* Fix: before applying the filter, check if the completed phase itself
* passes it. If not (parallel-milestone case), skip the filter entirely
* so all filesystem phases are visible for next-phase detection.
*/
const { describe, test, beforeEach, afterEach } = require('node:test');
const assert = require('node:assert/strict');
const fs = require('fs');
const path = require('path');
const { createTempProject, cleanup } = require('./helpers.cjs');
const SDK_CLI = path.join(__dirname, '..', 'sdk', 'dist', 'cli.js');
const { execFileSync } = require('child_process');
function runSdkQuery(args, cwd) {
try {
const result = execFileSync(process.execPath, [SDK_CLI, 'query', ...args], {
cwd,
encoding: 'utf-8',
stdio: ['pipe', 'pipe', 'pipe'],
});
const parsed = JSON.parse(result.trim());
return { success: true, data: parsed };
} catch (err) {
const stderr = err.stderr?.toString().trim() || '';
const stdout = err.stdout?.toString().trim() || '';
try {
const parsed = JSON.parse(stdout);
return { success: true, data: parsed };
} catch {
/* not JSON */
}
return { success: false, error: stderr || err.message };
}
}
// ROADMAP.md with two active milestones: v1.0 (phases 10, 11) and v2.0 (phases 41.1, 41.2, 41.3).
// Using numeric version IDs so extractCurrentMilestone can correctly detect milestone boundaries.
const PARALLEL_ROADMAP = `# Roadmap
## v1.0 Milestone (Primary)
### Phase 10: Foo
**Goal:** Foo work
### Phase 11: Bar
**Goal:** Bar work
## v2.0 Milestone (Parallel)
### Phase 41.1: Baz
**Goal:** Baz work
### Phase 41.2: Qux
**Goal:** Qux work
### Phase 41.3: Quux
**Goal:** Quux work
`;
// STATE.md with milestone pointing at v1.0 (not v2.0).
// Uses YAML frontmatter so extractCurrentMilestone can read the `milestone:` field.
const STATE_POINTING_V1 = `---
milestone: v1.0
milestone_name: Primary Milestone
---
# State
**Current Phase:** 41.2
**Status:** In progress
**Last Activity:** 2026-04-25
**Last Activity Description:** Working on qux
`;
describe('bug #2676: phase.complete respects parallel milestone routing', () => {
let tmpDir;
beforeEach(() => {
tmpDir = createTempProject();
// Write ROADMAP.md and STATE.md
fs.writeFileSync(path.join(tmpDir, '.planning', 'ROADMAP.md'), PARALLEL_ROADMAP);
fs.writeFileSync(path.join(tmpDir, '.planning', 'STATE.md'), STATE_POINTING_V1);
// Create filesystem phase directories for vA (primary milestone)
fs.mkdirSync(path.join(tmpDir, '.planning', 'phases', '10-foo'), { recursive: true });
fs.mkdirSync(path.join(tmpDir, '.planning', 'phases', '11-bar'), { recursive: true });
// Create filesystem phase directories for vB (parallel milestone)
fs.mkdirSync(path.join(tmpDir, '.planning', 'phases', '41.1-baz'), { recursive: true });
const phase412 = path.join(tmpDir, '.planning', 'phases', '41.2-qux');
fs.mkdirSync(phase412, { recursive: true });
fs.writeFileSync(path.join(phase412, '41.2-01-PLAN.md'), '# Plan');
fs.writeFileSync(path.join(phase412, '41.2-01-SUMMARY.md'), '# Summary');
fs.mkdirSync(path.join(tmpDir, '.planning', 'phases', '41.3-quux'), { recursive: true });
});
afterEach(() => {
cleanup(tmpDir);
});
test('phase.complete 41.2 returns is_last_phase: false when 41.3 exists', () => {
// BUG: before the fix this returns is_last_phase: true because the
// milestone filter (built from vA's phases: 10, 11) excludes all 41.x dirs,
// leaving an empty candidate set and defaulting isLastPhase to true.
const result = runSdkQuery(['phase.complete', '41.2'], tmpDir);
assert.ok(result.success, `phase.complete failed: ${result.error}`);
assert.strictEqual(
result.data.is_last_phase,
false,
`expected is_last_phase: false but got true — parallel milestone filter not bypassed. ` +
`next_phase was: ${result.data.next_phase}`
);
});
test('phase.complete 41.2 returns next_phase pointing at 41.3', () => {
const result = runSdkQuery(['phase.complete', '41.2'], tmpDir);
assert.ok(result.success, `phase.complete failed: ${result.error}`);
assert.ok(
result.data.next_phase !== null,
`next_phase should not be null when 41.3 exists — got: ${JSON.stringify(result.data.next_phase)}`
);
// next_phase may be returned as "41.3" or "41" depending on dir name matching
assert.match(
String(result.data.next_phase),
/^41\.3/,
`next_phase should start with 41.3, got: ${result.data.next_phase}`
);
});
test('phase.complete for vA phase still uses milestone filter normally', () => {
// Completing phase 10 (in vA): the filter includes it, so the candidate
// set for next-phase is {10, 11} and next should be 11.
const phase10 = path.join(tmpDir, '.planning', 'phases', '10-foo');
fs.writeFileSync(path.join(phase10, '10-01-PLAN.md'), '# Plan');
fs.writeFileSync(path.join(phase10, '10-01-SUMMARY.md'), '# Summary');
const result = runSdkQuery(['phase.complete', '10'], tmpDir);
assert.ok(result.success, `phase.complete 10 failed: ${result.error}`);
assert.strictEqual(result.data.is_last_phase, false, 'phase 10 should not be last (11 follows)');
assert.match(
String(result.data.next_phase ?? ''),
/^11/,
`next_phase should point to 11, got: ${result.data.next_phase}`
);
});
test('phase.complete for actual last phase of vA still returns is_last_phase: true', () => {
// Completing phase 11 (last in vA): the filter includes phases 10 and 11,
// nothing higher in the vA milestone, so is_last_phase should be true
// (even though 41.x dirs exist on disk for vB).
const phase11 = path.join(tmpDir, '.planning', 'phases', '11-bar');
fs.writeFileSync(path.join(phase11, '11-01-PLAN.md'), '# Plan');
fs.writeFileSync(path.join(phase11, '11-01-SUMMARY.md'), '# Summary');
const result = runSdkQuery(['phase.complete', '11'], tmpDir);
assert.ok(result.success, `phase.complete 11 failed: ${result.error}`);
assert.strictEqual(
result.data.is_last_phase,
true,
`phase 11 is last in vA; is_last_phase should be true even with vB dirs on disk`
);
});
});

View File

@@ -1,103 +0,0 @@
/**
* Regression test for #2678: --local install tries to globally install the SDK
*
* `installSdkIfNeeded()` is called unconditionally inside `installAllRuntimes()`,
* even when `--local` is passed. When sdk/dist/cli.js is missing, it calls
* process.exit(1) regardless of whether this is a local project install or a
* global install. On Linux without sudo, users can't install globally, so a
* local install that fails on SDK check is incorrect behavior.
*
* Fix: when isLocal is true, skip the SDK global-install check and print a
* clear message that the SDK is not verified for local installs.
*
* The exported `installSdkIfNeeded(opts)` function should accept an `isLocal`
* option. When opts.isLocal is true and sdk/dist/cli.js is missing, it should
* print a warning and return (not process.exit(1)).
*/
'use strict';
process.env.GSD_TEST_MODE = '1';
const { describe, test } = require('node:test');
const assert = require('node:assert/strict');
const fs = require('fs');
const path = require('path');
const os = require('os');
const INSTALL_SRC = path.join(__dirname, '..', 'bin', 'install.js');
const { installSdkIfNeeded } = require(INSTALL_SRC);
describe('#2678: --local install does not exit when SDK is missing', () => {
test('installSdkIfNeeded with isLocal=true and missing sdk/dist/cli.js returns without exiting', () => {
// Point sdkDir at a temp directory that has no dist/cli.js — simulates missing SDK
const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'gsd-sdk-local-2678-'));
try {
// Capture stderr to verify a warning is printed
const stderrChunks = [];
const origWrite = process.stderr.write.bind(process.stderr);
process.stderr.write = (chunk, ...args) => {
stderrChunks.push(String(chunk));
return origWrite(chunk, ...args);
};
let exited = false;
const origExit = process.exit.bind(process);
process.exit = (code) => {
exited = true;
process.exit = origExit;
process.stderr.write = origWrite;
throw new Error(`process.exit(${code}) called — local install must not exit on missing SDK (#2678)`);
};
try {
installSdkIfNeeded({ sdkDir: tmpDir, isLocal: true });
} finally {
process.exit = origExit;
process.stderr.write = origWrite;
}
assert.strictEqual(
exited,
false,
'installSdkIfNeeded with isLocal=true must not call process.exit when SDK is missing (#2678)'
);
} finally {
fs.rmSync(tmpDir, { recursive: true, force: true });
}
});
test('installSdkIfNeeded with isLocal=true and missing SDK prints a local-install message', () => {
const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'gsd-sdk-local-msg-2678-'));
try {
const stderrOutput = [];
const origWrite = process.stderr.write.bind(process.stderr);
process.stderr.write = (chunk, ...args) => {
stderrOutput.push(String(chunk));
return origWrite(chunk, ...args);
};
const origExit = process.exit.bind(process);
process.exit = () => {
process.exit = origExit;
process.stderr.write = origWrite;
};
try {
installSdkIfNeeded({ sdkDir: tmpDir, isLocal: true });
} finally {
process.exit = origExit;
process.stderr.write = origWrite;
}
const combined = stderrOutput.join('');
assert.ok(
combined.length > 0 || true,
// We don't strictly require output; main assertion is no exit above.
'SDK check with isLocal=true should handle gracefully'
);
} finally {
fs.rmSync(tmpDir, { recursive: true, force: true });
}
});
});

View File

@@ -1,318 +0,0 @@
/**
* Bug #2767: Workflows pass paths positionally to `gsd-sdk query commit`.
*
* Runtime behavior under the buggy form (paths positional, no `--files`):
* 1. positional path tokens are joined into the commit subject (commit.ts:110); and
* 2. `filePaths` is empty, so the handler falls back to staging `.planning/`
* wholesale (commit.ts:136), silently swapping the user's intent.
*
* Under the well-formed form (`--files <path...>`):
* - subject is the message arg only;
* - exactly the listed files are staged;
* - `commit-to-subrepo` rejects when `--files` is absent (commit.ts:258).
*
* Note: the supplementary doc-lint's `isWellFormed` accepts any invocation that
* has no positional path args after the message — i.e. message-only commits pass
* regardless of any trailing comment. There is no required marker (`# message-only`
* or otherwise); the absence of positional path tokens is the sole signal.
*
* Primary test: invoke the actual `gsd-sdk query commit[-to-subrepo]` binary
* against a real tmp git project and assert the runtime behavior. Supplementary
* test: a doc-lint that scans every shipped .md file to catch regressions of
* the 50-file invocation cleanup landed in this PR. The behavioral tests are
* the contract; the lint is a defense-in-depth guard.
*/
const { describe, test, beforeEach, afterEach } = require('node:test');
const assert = require('node:assert/strict');
const fs = require('node:fs');
const path = require('node:path');
const { execFileSync } = require('node:child_process');
const { createTempGitProject, cleanup } = require('./helpers.cjs');
const REPO_ROOT = path.join(__dirname, '..');
const SDK_CLI = path.join(REPO_ROOT, 'sdk', 'dist', 'cli.js');
/**
* Run a git command with hardcoded argv (no shell). Returns trimmed stdout.
*/
function git(projectDir, args) {
return execFileSync('git', args, { cwd: projectDir, encoding: 'utf-8' }).trim();
}
/**
* Invoke `gsd-sdk query <subcommand> <...args>` against a project dir.
* Returns { exitCode, stdout, stderr, json } where json is the parsed handler
* payload (the SDK prints a single JSON object to stdout for query handlers).
*/
function runSdkQuery(subcommand, args, projectDir) {
const argv = ['query', subcommand, ...args, '--project-dir', projectDir];
let stdout = '';
let stderr = '';
let exitCode = 0;
try {
stdout = execFileSync(process.execPath, [SDK_CLI, ...argv], {
encoding: 'utf-8',
stdio: ['pipe', 'pipe', 'pipe'],
env: { ...process.env, GSD_SESSION_KEY: '' },
});
} catch (err) {
exitCode = err.status ?? 1;
stdout = err.stdout?.toString() ?? '';
stderr = err.stderr?.toString() ?? '';
}
// Extract the trailing JSON object — the CLI prints status lines before it.
let json = null;
const lastBrace = stdout.lastIndexOf('{');
if (lastBrace >= 0) {
try { json = JSON.parse(stdout.slice(lastBrace).trim()); } catch { /* leave null */ }
if (!json) {
try { json = JSON.parse(stdout.trim()); } catch { /* leave null */ }
}
}
return { exitCode, stdout, stderr, json };
}
function gitSubject(projectDir) {
return git(projectDir, ['log', '-1', '--pretty=%s']);
}
function gitFilesAt(projectDir) {
return git(projectDir, ['show', '--pretty=', '--name-only', 'HEAD'])
.split('\n').filter(Boolean).sort();
}
// ─── Behavioral SDK tests ────────────────────────────────────────────────────
describe('bug #2767 (behavioral): gsd-sdk query commit --files', () => {
let tmpDir;
beforeEach(() => {
tmpDir = createTempGitProject('gsd-2767-');
fs.writeFileSync(path.join(tmpDir, 'foo.md'), 'foo body\n');
fs.writeFileSync(path.join(tmpDir, 'bar.md'), 'bar body\n');
// .planning/ change that MUST NOT leak into the commit when --files is used.
fs.writeFileSync(path.join(tmpDir, '.planning', 'STATE.md'), 'state\n');
});
afterEach(() => {
cleanup(tmpDir);
});
test('well-formed: --files <paths> stages exactly those files with clean subject', (t) => {
if (!fs.existsSync(SDK_CLI)) {
t.skip('sdk/dist/cli.js not built — run `cd sdk && npm run build` to enable this integration test');
return;
}
const message = 'test(#2767): well-formed commit';
const result = runSdkQuery('commit', [message, '--files', 'foo.md', 'bar.md'], tmpDir);
assert.equal(result.exitCode, 0, `cli failed: ${result.stderr}`);
assert.ok(result.json, `expected JSON body in stdout, got:\n${result.stdout}`);
assert.equal(result.json.committed, true, `commit failed: ${JSON.stringify(result.json)}`);
assert.equal(result.json.message, message, 'subject must be message-only — no path leakage');
assert.deepEqual(result.json.files.slice().sort(), ['bar.md', 'foo.md']);
// Cross-check via git itself.
assert.equal(gitSubject(tmpDir), message);
assert.deepEqual(gitFilesAt(tmpDir), ['bar.md', 'foo.md']);
// The .planning/STATE.md change must remain unstaged/unrelated.
const stillDirty = git(tmpDir, ['status', '--porcelain']);
assert.ok(stillDirty.includes('.planning/STATE.md'),
`.planning/STATE.md should remain unstaged, got status:\n${stillDirty}`);
});
test('buggy form (positional, no --files): paths leak into subject AND .planning/ fallback fires', (t) => {
if (!fs.existsSync(SDK_CLI)) {
t.skip('sdk/dist/cli.js not built — run `cd sdk && npm run build` to enable this integration test');
return;
}
// Documents the misbehavior #2767 prevents at every workflow call site.
// Any future change that makes the buggy form silently "do the right thing"
// trips this test and must justify the change.
const message = 'test(#2767): positional buggy';
const result = runSdkQuery('commit', [message, 'foo.md', 'bar.md'], tmpDir);
assert.equal(result.exitCode, 0);
assert.ok(result.json, `expected JSON body, got:\n${result.stdout}`);
assert.equal(result.json.committed, true);
// Subject got polluted with the path tokens.
assert.equal(result.json.message, `${message} foo.md bar.md`,
'paths leak into the commit subject under the buggy form (commit.ts:110)');
assert.equal(gitSubject(tmpDir), `${message} foo.md bar.md`);
// Fallback staged .planning/STATE.md, NOT foo.md/bar.md.
assert.deepEqual(gitFilesAt(tmpDir), ['.planning/STATE.md'],
'positional form triggers the .planning/ wholesale fallback (commit.ts:136)');
const dirty = git(tmpDir, ['status', '--porcelain']);
assert.ok(dirty.includes('foo.md') && dirty.includes('bar.md'),
`foo.md/bar.md should remain unstaged under the buggy form, got:\n${dirty}`);
});
test('positional form with no .planning/ change: returns "nothing staged"', (t) => {
if (!fs.existsSync(SDK_CLI)) {
t.skip('sdk/dist/cli.js not built — run `cd sdk && npm run build` to enable this integration test');
return;
}
// Reset the .planning/STATE.md change so the fallback has nothing to stage.
fs.rmSync(path.join(tmpDir, '.planning', 'STATE.md'), { force: true });
const result = runSdkQuery('commit', ['msg', 'foo.md'], tmpDir);
assert.equal(result.exitCode, 0);
assert.ok(result.json, `expected JSON body, got:\n${result.stdout}`);
assert.equal(result.json.committed, false);
assert.equal(result.json.reason, 'nothing staged',
'positional form ignores foo.md and finds nothing under .planning/ to fall back to');
});
});
describe('bug #2767 (behavioral): commit-to-subrepo requires --files', () => {
let tmpDir;
beforeEach(() => {
tmpDir = createTempGitProject('gsd-2767-sub-');
fs.writeFileSync(
path.join(tmpDir, '.planning', 'config.json'),
JSON.stringify({ sub_repos: ['vendor/lib'] }, null, 2),
);
fs.mkdirSync(path.join(tmpDir, 'vendor', 'lib'), { recursive: true });
fs.writeFileSync(path.join(tmpDir, 'vendor', 'lib', 'README.md'), 'sub\n');
});
afterEach(() => {
cleanup(tmpDir);
});
test('rejects with explicit error when --files is omitted', (t) => {
if (!fs.existsSync(SDK_CLI)) {
t.skip('sdk/dist/cli.js not built — run `cd sdk && npm run build` to enable this integration test');
return;
}
const result = runSdkQuery('commit-to-subrepo', ['only message, no files'], tmpDir);
assert.equal(result.exitCode, 0);
assert.ok(result.json, `expected JSON body, got:\n${result.stdout}`);
assert.equal(result.json.committed, false);
assert.equal(result.json.reason, '--files required for commit-to-subrepo',
'commit-to-subrepo enforces --files at runtime (commit.ts:258)');
});
});
// ─── Supplementary doc-lint (defense-in-depth) ───────────────────────────────
//
// The behavioral tests above prove the SDK semantics. This lint scans every
// shipped .md invocation to catch regressions in the 50-file workflow cleanup
// landed by this PR — without it, a future contributor adding a new workflow
// could reintroduce the positional form silently. allow-test-rule: doc-text
// invocations cannot be exercised end-to-end (they are agent-prompt strings
// rendered into chat, not invoked by gsd-tools.cjs), so a textual guard is
// the only available enforcement layer.
const SCAN_DIRS = ['agents', 'commands', 'get-shit-done', 'docs', 'scripts'];
const KNOWN_FLAGS = new Set(['--force', '--amend', '--no-verify', '--files']);
function walk(dir, out = []) {
if (!fs.existsSync(dir)) return out;
for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
const full = path.join(dir, entry.name);
if (entry.isDirectory()) {
if (entry.name === 'node_modules' || entry.name.startsWith('.')) continue;
walk(full, out);
} else if (entry.isFile() && entry.name.endsWith('.md')) {
out.push(full);
}
}
return out;
}
function extractInvocations(filePath) {
const text = fs.readFileSync(filePath, 'utf-8');
const lines = text.split(/\r?\n/);
const invocations = [];
for (let i = 0; i < lines.length; i++) {
const m = lines[i].match(/(gsd-sdk\s+query\s+commit(?:-to-subrepo)?\b.*)$/);
if (!m) continue;
const tail = m[1].match(/^gsd-sdk\s+query\s+commit(?:-to-subrepo)?(.?)/);
if (tail && tail[1] === '`') continue;
let cmd = m[1];
let j = i;
while (cmd.endsWith('\\') && j + 1 < lines.length) {
cmd = cmd.slice(0, -1).trimEnd() + ' ' + lines[j + 1].trim();
j++;
}
invocations.push({ line: i + 1, cmd, file: filePath });
}
return invocations;
}
function stripTail(cmd) {
let inSingle = false, inDouble = false;
for (let i = 0; i < cmd.length; i++) {
const c = cmd[i];
if (c === "'" && !inDouble) inSingle = !inSingle;
else if (c === '"' && !inSingle) inDouble = !inDouble;
else if (!inSingle && !inDouble) {
if (c === '#' && (i === 0 || /\s/.test(cmd[i - 1]))) return cmd.slice(0, i);
if (c === '|' || c === ';' || c === '>' || c === '<') return cmd.slice(0, i);
if (c === '&' && cmd[i + 1] === '&') return cmd.slice(0, i);
}
}
return cmd;
}
function tokenize(cmd) {
const out = [];
let cur = '', inSingle = false, inDouble = false;
for (let i = 0; i < cmd.length; i++) {
const c = cmd[i];
if (c === "'" && !inDouble) { inSingle = !inSingle; cur += c; continue; }
if (c === '"' && !inSingle) { inDouble = !inDouble; cur += c; continue; }
if (/\s/.test(c) && !inSingle && !inDouble) {
if (cur) { out.push(cur); cur = ''; }
continue;
}
cur += c;
}
if (cur) out.push(cur);
return out;
}
function isWellFormed(cmd) {
const truncated = stripTail(cmd);
const parts = tokenize(truncated);
if (parts.length < 3) return true;
const args = parts.slice(3);
if (args.length === 0) return true;
if (args.includes('--files')) return true;
let sawMessage = false;
for (const tok of args) {
if (KNOWN_FLAGS.has(tok)) continue;
if (!sawMessage) { sawMessage = true; continue; }
return false;
}
return true;
}
describe('bug #2767 (supplementary doc-lint): no positional invocations in shipped .md', () => {
const allFiles = SCAN_DIRS.flatMap(d => walk(path.join(REPO_ROOT, d)));
const allInvocations = allFiles.flatMap(extractInvocations);
test('lint scanned at least one invocation (sanity)', () => {
assert.ok(allInvocations.length > 0, 'lint scanned 0 invocations — globs are wrong');
});
test('every gsd-sdk query commit invocation either uses --files or has no path args', () => {
const broken = allInvocations.filter(({ cmd }) => !isWellFormed(cmd));
if (broken.length > 0) {
const detail = broken.map(({ file, line, cmd }) => {
const rel = path.relative(REPO_ROOT, file);
return ` ${rel}:${line}\n ${cmd}`;
}).join('\n');
assert.fail(
`${broken.length} \`gsd-sdk query commit\` invocation(s) pass paths positionally.\n` +
`The behavioral test above proves what goes wrong at runtime; this lint catches\n` +
`regressions in shipped workflow markdown.\n${detail}`
);
}
});
});

View File

@@ -1,210 +0,0 @@
// allow-test-rule: pending-migration-to-typed-ir [#2974]
// Tracked in #2974 for migration to typed-IR assertions per CONTRIBUTING.md
// "Prohibited: Raw Text Matching on Test Outputs". Per-file review may
// reclassify some entries as source-text-is-the-product during migration.
/**
* Regression test for bug #2775
*
* `npx @opengsd/get-shit-done-redux@latest --global` runs the installer, which prints
* `✓ GSD SDK ready` even though the secondary `gsd-sdk` bin is not on the
* user's PATH. Root cause: `npx` only links the package's primary bin into
* the ephemeral cache; secondary bins are not symlinked. The installer's
* `installSdkIfNeeded` only verified that `sdk/dist/cli.js` exists on disk
* — a strictly weaker invariant than `command -v gsd-sdk` resolving.
*
* The fix tightens the success gate: after confirming the dist is present,
* the installer must verify `gsd-sdk` resolves on PATH. If it does not, the
* installer attempts to materialize the shim into a user-writable PATH
* location (`~/.local/bin/gsd-sdk`) and re-checks. Only when the PATH probe
* succeeds does it print `✓ GSD SDK ready`. Otherwise it emits a clear
* warning + remediation and does NOT lie about readiness.
*
* This test exercises `installSdkIfNeeded` against a synthetic npx-cache
* shape: sdk/dist/cli.js present, but PATH does not contain any directory
* with a `gsd-sdk` shim. The legacy code printed the success line in this
* shape; the fixed code must not.
*/
'use strict';
process.env.GSD_TEST_MODE = '1';
const { describe, test, beforeEach, afterEach } = require('node:test');
const assert = require('node:assert/strict');
const fs = require('fs');
const path = require('path');
const installModule = require('../bin/install.js');
const isWindows = process.platform === 'win32';
const { installSdkIfNeeded } = installModule;
const { createTempDir, cleanup, captureConsole } = require('./helpers.cjs');
describe('bug #2775: installSdkIfNeeded must verify gsd-sdk on PATH before reporting ready',
{ skip: isWindows ? 'POSIX-only: asserts ~/.local/bin shebang shim with mode 0o755; Windows uses gsd-sdk.cmd + PATHEXT + registry Path' : false },
() => {
let tmpRoot;
let sdkDir;
let pathDir;
let homeDir;
let savedEnv;
beforeEach(() => {
tmpRoot = createTempDir('gsd-2775-');
sdkDir = path.join(tmpRoot, 'sdk');
fs.mkdirSync(path.join(sdkDir, 'dist'), { recursive: true });
fs.writeFileSync(
path.join(sdkDir, 'dist', 'cli.js'),
'#!/usr/bin/env node\nconsole.log("0.0.0-test");\n',
{ mode: 0o755 },
);
pathDir = path.join(tmpRoot, 'somebin');
fs.mkdirSync(pathDir, { recursive: true });
homeDir = path.join(tmpRoot, 'home');
fs.mkdirSync(homeDir, { recursive: true });
savedEnv = { PATH: process.env.PATH, HOME: process.env.HOME };
// PATH does NOT contain anything with a gsd-sdk shim — simulates npx-cache.
process.env.PATH = pathDir;
process.env.HOME = homeDir;
});
afterEach(() => {
if (savedEnv.PATH == null) delete process.env.PATH;
else process.env.PATH = savedEnv.PATH;
if (savedEnv.HOME == null) delete process.env.HOME;
else process.env.HOME = savedEnv.HOME;
cleanup(tmpRoot);
});
test('does NOT print "GSD SDK ready" when gsd-sdk is not callable on PATH and cannot be linked', () => {
// Make ~/.local/bin not on PATH and not creatable-friendly: PATH stays
// as a single dir with no gsd-sdk. The installer may attempt to create
// ~/.local/bin/gsd-sdk, but that location isn't on PATH either, so the
// post-link probe should still fail and the success line must be withheld.
const { stdout, stderr } = captureConsole(() => {
installSdkIfNeeded({ sdkDir });
});
const combined = `${stdout}\n${stderr}`;
const hasReady = /GSD SDK ready/.test(combined);
const mentionsPath = /not on (your )?PATH|gsd-sdk.*PATH|PATH.*gsd-sdk/i.test(combined);
assert.ok(
!hasReady,
`installer must not print "GSD SDK ready" when gsd-sdk is not on PATH. Output:\n${combined}`,
);
assert.ok(
mentionsPath,
`installer must surface a PATH-related warning when gsd-sdk is not callable. Output:\n${combined}`,
);
});
test('DOES print "GSD SDK ready" after self-linking into a directory that IS on PATH', () => {
// Put ~/.local/bin on PATH; the installer should create the shim there
// and the post-link callability probe should succeed.
const localBin = path.join(homeDir, '.local', 'bin');
fs.mkdirSync(localBin, { recursive: true });
process.env.PATH = `${localBin}${path.delimiter}${pathDir}`;
const { stdout, stderr } = captureConsole(() => {
installSdkIfNeeded({ sdkDir });
});
const combined = `${stdout}\n${stderr}`;
assert.ok(
/GSD SDK ready/.test(combined),
`installer must print "GSD SDK ready" after self-linking to a dir on PATH. Output:\n${combined}`,
);
// And the link must actually exist + resolve back to the shim.
const linkPath = path.join(localBin, 'gsd-sdk');
assert.ok(fs.existsSync(linkPath), `installer must materialize ${linkPath}`);
});
test('symlink-fallback writes a wrapper that require()s the real shim by absolute path (preserves __dirname)', () => {
// Simulate a symlink-hostile filesystem by forcing fs.symlinkSync to throw.
// The fallback must NOT copy bin/gsd-sdk.js into ~/.local/bin (which would
// break the shim's `path.resolve(__dirname, '..', 'sdk', 'dist', 'cli.js')`
// resolution). Instead it must write a tiny wrapper script that
// require()s the real shim by absolute path so __dirname stays correct.
const localBin = path.join(homeDir, '.local', 'bin');
fs.mkdirSync(localBin, { recursive: true });
process.env.PATH = `${localBin}${path.delimiter}${pathDir}`;
const realShimSrc = path.resolve(__dirname, '..', 'bin', 'gsd-sdk.js');
const origSymlink = fs.symlinkSync;
fs.symlinkSync = () => {
const err = new Error('EPERM: simulated symlink-hostile filesystem');
err.code = 'EPERM';
throw err;
};
try {
captureConsole(() => {
installSdkIfNeeded({ sdkDir });
});
} finally {
fs.symlinkSync = origSymlink;
}
const target = path.join(localBin, 'gsd-sdk');
assert.ok(fs.existsSync(target), `fallback must materialize ${target}`);
// Critical: it must NOT be a verbatim copy of bin/gsd-sdk.js.
const targetContent = fs.readFileSync(target, 'utf8');
const realShimContent = fs.readFileSync(realShimSrc, 'utf8');
assert.notStrictEqual(
targetContent,
realShimContent,
'fallback must not copyFileSync bin/gsd-sdk.js — that breaks __dirname-based CLI resolution',
);
// It must be a wrapper that require()s the real shim by absolute path.
assert.ok(
targetContent.includes('require(') && targetContent.includes(realShimSrc),
`fallback wrapper must require() the real shim by absolute path. Got:\n${targetContent}`,
);
// And it must be executable.
const st = fs.statSync(target);
assert.ok(
(st.mode & 0o111) !== 0,
`fallback wrapper must have execute bit set (mode=${st.mode.toString(8)})`,
);
// (Earlier assertions on targetContent already verify the wrapper points
// at the real shim by absolute path, which is what guarantees __dirname
// resolves correctly. A separate "does <pkg>/sdk/dist exist?" check would
// be tautological — that path is true regardless of what the wrapper
// wrote.) (#2775 CodeRabbit follow-up)
});
test('self-link prefers a PATH-backed HOME dir over ~/.local/bin when ~/.local/bin is off-PATH', () => {
// Regression for #2775 CodeRabbit follow-up: the candidate ordering must
// try PATH-backed HOME dirs FIRST, falling back to ~/.local/bin only when
// it's not on PATH. Otherwise we self-link to ~/.local/bin (off-PATH) and
// warn — when we could have linked to ~/bin (on-PATH) and printed success.
const homeBin = path.join(homeDir, 'bin');
fs.mkdirSync(homeBin, { recursive: true });
// PATH contains ~/bin (a HOME dir) but NOT ~/.local/bin.
process.env.PATH = `${homeBin}${path.delimiter}${pathDir}`;
const { stdout, stderr } = captureConsole(() => {
installSdkIfNeeded({ sdkDir });
});
const combined = `${stdout}\n${stderr}`;
assert.ok(
/GSD SDK ready/.test(combined),
`installer must self-link into the on-PATH HOME dir and print success. Output:\n${combined}`,
);
assert.ok(
fs.existsSync(path.join(homeBin, 'gsd-sdk')),
`installer must materialize the link in the on-PATH HOME dir (~/bin), not ~/.local/bin`,
);
});
test('DOES print "GSD SDK ready" when gsd-sdk is already resolvable on PATH', () => {
// Pre-populate PATH with a `gsd-sdk` shim so the probe finds one.
const preexisting = path.join(pathDir, 'gsd-sdk');
fs.writeFileSync(preexisting, '#!/bin/sh\nexit 0\n', { mode: 0o755 });
const { stdout } = captureConsole(() => {
installSdkIfNeeded({ sdkDir });
});
assert.ok(
/GSD SDK ready/.test(stdout),
`installer must print "GSD SDK ready" when gsd-sdk is already on PATH. Output:\n${stdout}`,
);
});
});

View File

@@ -1,175 +0,0 @@
/**
* Regression test for bug #2788
*
* `gsd-sdk query audit-uat` returned total_items: 0 for VERIFICATION.md
* files where human-needed items were encoded in the frontmatter
* `human_verification:` YAML array (the format written by gsd-verifier),
* or where the body section heading used `## human_verification` (underscore)
* instead of `## Human Verification` (space).
*
* Root cause:
* 1. parseVerificationItems only searched the body for "## Human Verification"
* (space, case-insensitive) — never read frontmatter.
* 2. The body-section regex did not accept underscore in the heading name.
*
* Fix: parseVerificationItems now reads the frontmatter human_verification:
* array first (via extractFrontmatter). Falls back to body-section scan
* with a relaxed regex that accepts underscore and parenthetical suffixes.
*/
'use strict';
const { describe, test, beforeEach, afterEach } = require('node:test');
const assert = require('node:assert/strict');
const fs = require('node:fs');
const path = require('node:path');
const { execFileSync } = require('node:child_process');
const { createTempProject, cleanup } = require('./helpers.cjs');
const REPO_ROOT = path.join(__dirname, '..');
const SDK_CLI = path.join(REPO_ROOT, 'sdk', 'dist', 'cli.js');
function runAuditUat(projectDir) {
const argv = ['query', 'audit-uat', '--project-dir', projectDir];
let stdout = '';
let exitCode = 0;
try {
stdout = execFileSync(process.execPath, [SDK_CLI, ...argv], {
encoding: 'utf-8',
stdio: ['pipe', 'pipe', 'pipe'],
env: { ...process.env, GSD_SESSION_KEY: '' },
});
} catch (err) {
exitCode = err.status ?? 1;
stdout = err.stdout?.toString() ?? '';
}
let json = null;
try { json = JSON.parse(stdout.trim()); } catch { /* ok */ }
return { exitCode, json };
}
/** Set up a project with a ROADMAP.md milestone and a phase VERIFICATION.md */
function setupProject(tmpDir, verificationContent) {
const planningDir = path.join(tmpDir, '.planning');
const phaseDir = path.join(planningDir, 'phases', '03-invoicing');
fs.mkdirSync(phaseDir, { recursive: true });
// Write a minimal ROADMAP.md so getMilestonePhaseFilter works
fs.writeFileSync(
path.join(planningDir, 'ROADMAP.md'),
[
'# Roadmap',
'',
'## v1.0 — MVP',
'',
'### Phase 3: Invoicing',
].join('\n')
);
// Write STATE.md with current milestone
fs.writeFileSync(
path.join(planningDir, 'STATE.md'),
[
'---',
'version: "v1.0"',
'---',
'# State',
].join('\n')
);
fs.writeFileSync(
path.join(phaseDir, '03-invoicing-VERIFICATION.md'),
verificationContent
);
}
describe('bug-2788: audit-uat reads frontmatter human_verification array', () => {
let tmpDir;
beforeEach(() => {
tmpDir = createTempProject('gsd-test-2788-');
});
afterEach(() => {
cleanup(tmpDir);
});
test('frontmatter human_verification: array items are reported', () => {
// This is the format gsd-verifier writes; before fix total_items was 0
const content = [
'---',
'phase: 03-invoicing',
'status: human_needed',
'human_verification:',
' - test: "Manual frontend smoke — /invoices, /invoices/new"',
' expected: "All four routes render correctly"',
' why_human: "Visual rendering cannot be verified by static code inspection"',
' - test: "Run integration test suite against a real Postgres"',
' expected: "105 currently-skipped tests pass green"',
' why_human: "Docker not installed locally"',
'---',
'',
'# Phase 3 Verification Report',
'',
'No body Human Verification section here.',
].join('\n');
setupProject(tmpDir, content);
const result = runAuditUat(tmpDir);
assert.strictEqual(result.exitCode, 0, 'should exit 0');
assert.ok(result.json !== null, 'should emit JSON');
assert.ok(
result.json.summary.total_items >= 2,
`total_items should be >= 2, got ${result.json.summary.total_items}`
);
});
test('body ## human_verification (underscore) heading is parsed', () => {
const content = [
'---',
'phase: 03-invoicing',
'status: human_needed',
'---',
'',
'# Phase 3 Verification Report',
'',
'## human_verification (action required by Sammy)',
'',
'- Manual frontend smoke — /invoices, /invoices/new: verify all four routes render',
'- Run integration test suite against a real Postgres database',
].join('\n');
setupProject(tmpDir, content);
const result = runAuditUat(tmpDir);
assert.strictEqual(result.exitCode, 0, 'should exit 0');
assert.ok(result.json !== null, 'should emit JSON');
assert.ok(
result.json.summary.total_items >= 2,
`total_items should be >= 2, got ${result.json.summary.total_items}`
);
});
test('body ## Human Verification (space) heading still works', () => {
const content = [
'---',
'phase: 03-invoicing',
'status: human_needed',
'---',
'',
'# Phase 3 Verification Report',
'',
'## Human Verification',
'',
'- Manual frontend smoke test — verify all four routes render correctly or describe what breaks',
'- Run integration test suite: 105 tests must pass green',
].join('\n');
setupProject(tmpDir, content);
const result = runAuditUat(tmpDir);
assert.strictEqual(result.exitCode, 0, 'should exit 0');
assert.ok(result.json?.summary.total_items >= 2, `total_items should be >= 2`);
});
});

View File

@@ -1,170 +0,0 @@
/**
* Regression test for bug #2791 (Issue 2 — query registry not workstream-aware)
*
* When GSD_WORKSTREAM is set in the environment, `gsd-sdk query` commands must
* route .planning/ reads to `.planning/workstreams/<name>/` — matching the
* behaviour of `gsd-tools.cjs` which reads the same env var via planningDir().
*
* Before the fix: the SDK CLI only respected `--ws <name>` flag; GSD_WORKSTREAM
* was ignored, so `gsd-sdk query roadmap.analyze` always read the root
* `.planning/ROADMAP.md` even when a workstream was active.
*
* After the fix: the SDK CLI falls back to GSD_WORKSTREAM when --ws is absent.
*
* This test also verifies:
* - The `gsd-tools` bin alias maps to the same SDK shim as `gsd-sdk` (#2791 Issue 1)
*/
'use strict';
const { describe, test, beforeEach, afterEach } = require('node:test');
const assert = require('node:assert/strict');
const fs = require('node:fs');
const path = require('node:path');
const childProc = require('node:child_process');
const { cleanup } = require('./helpers.cjs');
const os = require('node:os');
const REPO_ROOT = path.join(__dirname, '..');
const SDK_CLI = path.join(REPO_ROOT, 'sdk', 'dist', 'cli.js');
const PKG_JSON = path.join(REPO_ROOT, 'package.json');
function runSdkQuery(args, projectDir, extraEnv = {}) {
let stdout = '';
let exitCode = 0;
try {
stdout = childProc.execFileSync(
process.execPath,
[SDK_CLI, 'query', ...args, '--project-dir', projectDir],
{
encoding: 'utf-8',
stdio: ['pipe', 'pipe', 'pipe'],
env: { ...process.env, GSD_SESSION_KEY: '', ...extraEnv },
}
);
} catch (err) {
exitCode = err.status ?? 1;
stdout = (err.stdout?.toString() ?? '') + (err.stderr?.toString() ?? '');
}
let json = null;
try { json = JSON.parse(stdout.trim()); } catch { /* ok */ }
return { exitCode, stdout, json };
}
describe('bug-2791: GSD_WORKSTREAM env var respected by gsd-sdk query', () => {
let tmpDir;
beforeEach(() => {
tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'gsd-test-2791-'));
// Create root .planning/ with a minimal config
fs.mkdirSync(path.join(tmpDir, '.planning', 'phases'), { recursive: true });
fs.writeFileSync(path.join(tmpDir, '.planning', 'config.json'), JSON.stringify({ mode: 'balanced' }));
// Create workstream .planning/workstreams/my-ws/ with its own ROADMAP
const wsDir = path.join(tmpDir, '.planning', 'workstreams', 'my-ws');
fs.mkdirSync(path.join(wsDir, 'phases'), { recursive: true });
fs.writeFileSync(
path.join(wsDir, 'config.json'),
JSON.stringify({ mode: 'balanced' })
);
fs.writeFileSync(
path.join(wsDir, 'STATE.md'),
'---\nmilestone: v1.0\n---\n\n# GSD State\n\n**Current Phase:** 1\n'
);
fs.writeFileSync(
path.join(wsDir, 'ROADMAP.md'),
[
'## Roadmap v1.0: Workstream Work',
'',
'### Phase 1: Workstream Phase',
'**Goal:** Test workstream routing',
'- [ ] Task A',
].join('\n')
);
// Also create a root ROADMAP that is intentionally empty of phases
fs.writeFileSync(
path.join(tmpDir, '.planning', 'ROADMAP.md'),
'## Roadmap v1.0: Root\n\n(no phases in root)\n'
);
fs.writeFileSync(
path.join(tmpDir, '.planning', 'STATE.md'),
'---\nmilestone: v1.0\n---\n\n# GSD State\n'
);
});
afterEach(() => {
cleanup(tmpDir);
});
test('without GSD_WORKSTREAM: roadmap.analyze reads root .planning/ROADMAP.md', () => {
const result = runSdkQuery(['roadmap.analyze'], tmpDir);
assert.strictEqual(result.exitCode, 0, `expected exit 0: ${result.stdout}`);
assert.ok(result.json !== null, 'expected JSON output');
// Root ROADMAP has no phases
assert.strictEqual(
result.json.phase_count,
0,
`expected 0 phases from root ROADMAP, got ${result.json.phase_count}`
);
});
test('with GSD_WORKSTREAM set: roadmap.analyze reads workstream ROADMAP.md', () => {
const result = runSdkQuery(['roadmap.analyze'], tmpDir, { GSD_WORKSTREAM: 'my-ws' });
assert.strictEqual(result.exitCode, 0, `expected exit 0: ${result.stdout}`);
assert.ok(result.json !== null, 'expected JSON output');
// Workstream ROADMAP has 1 phase
assert.strictEqual(
result.json.phase_count,
1,
`expected 1 phase from workstream ROADMAP, got ${result.json.phase_count}`
);
});
test('--ws flag takes precedence over GSD_WORKSTREAM env var', () => {
// Set GSD_WORKSTREAM to a non-existent workstream; --ws should override it.
// This verifies flag-wins-over-env precedence, not just that --ws works.
const result = runSdkQuery(['roadmap.analyze', '--ws', 'my-ws'], tmpDir, {
GSD_WORKSTREAM: 'nonexistent-ws',
});
assert.strictEqual(result.exitCode, 0, `expected exit 0: ${result.stdout}`);
assert.ok(result.json !== null, 'expected JSON output');
// --ws my-ws should route to the workstream ROADMAP which has 1 phase,
// proving the flag overrides the env var (nonexistent-ws has no phases).
assert.strictEqual(
result.json.phase_count,
1,
`expected 1 phase via --ws flag (overriding GSD_WORKSTREAM), got ${result.json.phase_count}`
);
});
test('invalid GSD_WORKSTREAM value is silently ignored and falls back to root', () => {
const result = runSdkQuery(['roadmap.analyze'], tmpDir, { GSD_WORKSTREAM: '../evil' });
// Should not crash; invalid name is silently ignored and falls back to root ROADMAP.
assert.strictEqual(result.exitCode, 0, `expected exit 0 (invalid GSD_WORKSTREAM ignored): ${result.stdout}`);
assert.ok(result.json !== null, 'expected JSON output after invalid GSD_WORKSTREAM fallback');
// Root ROADMAP has no phases — confirming root fallback, not an error path.
assert.strictEqual(
result.json.phase_count,
0,
`expected 0 phases from root ROADMAP fallback (invalid GSD_WORKSTREAM), got ${result.json.phase_count}`
);
});
});
describe('bug-2791: package.json declares gsd-tools bin alias (#2791 Issue 1)', () => {
test('package.json bin has gsd-tools entry', () => {
const pkg = JSON.parse(fs.readFileSync(PKG_JSON, 'utf-8'));
assert.ok(
Object.prototype.hasOwnProperty.call(pkg.bin ?? {}, 'gsd-tools'),
'package.json bin must include "gsd-tools" to provide collision-free alternative to gsd-sdk'
);
});
test('gsd-tools bin entry points to same file as gsd-sdk', () => {
const pkg = JSON.parse(fs.readFileSync(PKG_JSON, 'utf-8'));
assert.strictEqual(
pkg.bin['gsd-tools'],
pkg.bin['gsd-sdk'],
'gsd-tools and gsd-sdk must point to the same bin shim'
);
});
});

View File

@@ -1,156 +0,0 @@
/**
* Regression test for bug #2796
*
* roadmap.update-plan-progress used positional-only arg destructuring:
* `const phaseNum = args[0]`. When called with the flag form documented in
* execute-phase.md:228 (`--phase "TEST" --plan "01" --status "complete"`),
* args[0] was the literal string "--phase", which was passed to findPhase().
* findPhase found no phase named "--phase" and returned `updated: false` with
* `reason: "no matching checkbox found"`, silently no-oping. ROADMAP.md plan
* checkboxes never advanced.
*
* The stateBeginPhase handler already uses parseNamedArgs and is NOT affected.
*
* Fix: roadmap-update-plan-progress.ts now checks for --phase <value> before
* falling back to positional arg[0] (filtering out flag tokens).
*/
'use strict';
const { describe, test, beforeEach, afterEach } = require('node:test');
const assert = require('node:assert/strict');
const fs = require('node:fs');
const path = require('node:path');
const { execFileSync } = require('node:child_process');
const { createTempGitProject, cleanup } = require('./helpers.cjs');
const REPO_ROOT = path.join(__dirname, '..');
const SDK_CLI = path.join(REPO_ROOT, 'sdk', 'dist', 'cli.js');
function runSdkQuery(subcommand, args, projectDir) {
const argv = ['query', subcommand, ...args, '--project-dir', projectDir];
let stdout = '';
let stderr = '';
let exitCode = 0;
try {
stdout = execFileSync(process.execPath, [SDK_CLI, ...argv], {
encoding: 'utf-8',
stdio: ['pipe', 'pipe', 'pipe'],
env: { ...process.env, GSD_SESSION_KEY: '' },
});
} catch (err) {
exitCode = err.status ?? 1;
stdout = err.stdout?.toString() ?? '';
stderr = err.stderr?.toString() ?? '';
}
let json = null;
try { json = JSON.parse(stdout.trim()); } catch { /* ok */ }
return { exitCode, stdout: stdout.trim(), stderr: stderr.trim(), json };
}
/** Create a minimal ROADMAP.md with a phase checkbox */
function createRoadmap(projectDir, phaseNum, planLabel) {
const planningDir = path.join(projectDir, '.planning');
fs.mkdirSync(path.join(planningDir, 'phases'), { recursive: true });
const roadmap = [
'# My Project Roadmap',
'',
'## v1.0 — MVP',
'',
`### Phase ${phaseNum}: Test Phase`,
'',
`**Plans:** 1/1 plans complete`,
'',
`| # | Phase | Plans | Status | Date |`,
`|---|-------|-------|--------|------|`,
`| ${phaseNum} | Test Phase | 0/1 | Planned | |`,
'',
`- [ ] ${planLabel}: Do the thing`,
'',
].join('\n');
fs.writeFileSync(path.join(planningDir, 'ROADMAP.md'), roadmap);
// Create the phase directory so findPhase finds it
const phaseDir = path.join(
planningDir, 'phases',
`${String(phaseNum).padStart(2, '0')}-test-phase`
);
fs.mkdirSync(phaseDir, { recursive: true });
// Create a plan file and a summary so progress = 1/1
fs.writeFileSync(path.join(phaseDir, `${planLabel}-PLAN.md`), '# Plan\n');
fs.writeFileSync(path.join(phaseDir, `${planLabel}-SUMMARY.md`), '# Summary\n');
return phaseDir;
}
describe('bug-2796: roadmap update-plan-progress accepts --phase flag', () => {
let tmpDir;
beforeEach(() => {
tmpDir = createTempGitProject('gsd-test-2796-');
});
afterEach(() => {
cleanup(tmpDir);
});
test('flag form --phase <N> resolves the correct phase (not literal "--phase")', () => {
createRoadmap(tmpDir, '9', '01');
// Flag form: this is the form execute-phase.md:228 uses
const result = runSdkQuery(
'roadmap.update-plan-progress',
['--phase', '9'],
tmpDir
);
// Before fix: exitCode=1 with "phase --phase not found" or updated:false
// After fix: should succeed with phase="9" and updated:true
assert.strictEqual(result.exitCode, 0, `should exit 0; stderr: ${result.stderr}`);
assert.ok(result.json !== null, 'should emit JSON');
assert.ok(result.json.updated === true, 'updated should be true');
assert.strictEqual(String(result.json.phase), '9', 'phase should be "9", not "--phase"');
});
test('positional form still works (backward compat)', () => {
createRoadmap(tmpDir, '9', '01');
const result = runSdkQuery(
'roadmap.update-plan-progress',
['9'],
tmpDir
);
assert.strictEqual(result.exitCode, 0, `should exit 0; stderr: ${result.stderr}`);
assert.ok(result.json?.updated === true, 'updated should be true');
assert.strictEqual(String(result.json.phase), '9', 'phase should be "9"');
});
test('flag form does not pass "--phase" as the phase value to findPhase', () => {
// Before fix: findPhase("--phase") returned found:false, causing updated:false.
// Migrated #2974: assert on the typed JSON outcome (updated:true, exit 0)
// instead of grepping stderr for the failure message. If the parser had
// mis-fed "--phase" as the value, updated would be false and the structured
// result would surface the failure typed.
createRoadmap(tmpDir, '5', '01');
const result = runSdkQuery(
'roadmap.update-plan-progress',
['--phase', '5'],
tmpDir
);
assert.strictEqual(result.exitCode, 0,
`arg parser must accept --phase 5 cleanly; exitCode=${result.exitCode} stderr=${result.stderr}`);
assert.ok(result.json?.updated === true,
`expected updated:true (phase 5 found and progress updated); got json=${JSON.stringify(result.json)}`);
// The structured result also exposes the phase number that WAS resolved.
// It must be the numeric phase, not the flag name "--phase".
assert.strictEqual(String(result.json.phase), '5',
`result.phase must be the resolved phase value, not the flag literal; got ${result.json.phase}`);
});
});

View File

@@ -1,132 +0,0 @@
/**
* Regression test for bug #2803
*
* `gsd-sdk query config-get <key> --default <value>` silently ignored the
* --default flag. When the key was missing, the SDK threw "Error: Key not found"
* and exited 1, identical to calling it without --default.
*
* The CJS path (gsd-tools.cjs config-get <key> --default <value>) honored
* --default correctly since #1893. The SDK handler was never ported.
*
* Fix: configGet in sdk/src/query/config-query.ts now strips --default <value>
* from args before key lookup and returns { data: defaultValue } instead of
* throwing when the key is absent (config missing, key missing, or nested
* object missing).
*/
'use strict';
const { describe, test, beforeEach, afterEach } = require('node:test');
const assert = require('node:assert/strict');
const fs = require('node:fs');
const path = require('node:path');
const { execFileSync } = require('node:child_process');
const { createTempProject, cleanup } = require('./helpers.cjs');
const REPO_ROOT = path.join(__dirname, '..');
const SDK_CLI = path.join(REPO_ROOT, 'sdk', 'dist', 'cli.js');
/**
* Invoke `gsd-sdk query config-get <...args>` against a project dir.
* Returns { exitCode, stdout, stderr }.
*/
function runConfigGet(args, projectDir) {
const argv = ['query', 'config-get', ...args, '--project-dir', projectDir];
let stdout = '';
let stderr = '';
let exitCode = 0;
try {
stdout = execFileSync(process.execPath, [SDK_CLI, ...argv], {
encoding: 'utf-8',
stdio: ['pipe', 'pipe', 'pipe'],
env: { ...process.env, GSD_SESSION_KEY: '' },
});
} catch (err) {
exitCode = err.status ?? 1;
stdout = err.stdout?.toString() ?? '';
stderr = err.stderr?.toString() ?? '';
}
let json = null;
try { json = JSON.parse(stdout.trim()); } catch { /* ok */ }
return { exitCode, stdout: stdout.trim(), stderr: stderr.trim(), json };
}
describe('bug-2803: config-get --default flag honored in SDK', () => {
let tmpDir;
beforeEach(() => {
tmpDir = createTempProject('gsd-test-2803-');
});
afterEach(() => {
cleanup(tmpDir);
});
test('--default returns fallback value when key absent, exit 0', () => {
// Write a config without the key
fs.writeFileSync(
path.join(tmpDir, '.planning', 'config.json'),
JSON.stringify({ mode: 'balanced' })
);
const result = runConfigGet(
['workflow.test_command', '--default', 'FALLBACK'],
tmpDir
);
assert.strictEqual(result.exitCode, 0, 'should exit 0 when --default provided');
assert.ok(result.json !== null, 'should emit JSON');
assert.strictEqual(result.json, 'FALLBACK', 'data should be the default value');
});
test('--default not consumed as key path', () => {
// The key path should still be the first positional, not --default
fs.writeFileSync(
path.join(tmpDir, '.planning', 'config.json'),
JSON.stringify({ mode: 'quality' })
);
const result = runConfigGet(['mode', '--default', 'balanced'], tmpDir);
assert.strictEqual(result.exitCode, 0, 'should exit 0 for found key');
assert.strictEqual(result.json, 'quality', 'should return actual value when key exists');
});
test('--default with empty string value works', () => {
fs.writeFileSync(
path.join(tmpDir, '.planning', 'config.json'),
JSON.stringify({})
);
const result = runConfigGet(['missing.key', '--default', ''], tmpDir);
assert.strictEqual(result.exitCode, 0, 'should exit 0 with empty default');
assert.strictEqual(result.json, '', 'data should be empty string');
});
test('without --default: missing key still exits 1', () => {
fs.writeFileSync(
path.join(tmpDir, '.planning', 'config.json'),
JSON.stringify({ mode: 'balanced' })
);
const result = runConfigGet(['workflow.missing_key'], tmpDir);
assert.strictEqual(result.exitCode, 1, 'should exit 1 when key absent and no --default');
});
test('--default with nested missing path', () => {
fs.writeFileSync(
path.join(tmpDir, '.planning', 'config.json'),
JSON.stringify({ workflow: {} })
);
const result = runConfigGet(
['workflow.test_command', '--default', 'npm test'],
tmpDir
);
assert.strictEqual(result.exitCode, 0, 'should exit 0 with default for nested missing key');
assert.strictEqual(result.json, 'npm test', 'data should be the default value');
});
});

View File

@@ -1,145 +0,0 @@
/**
* Regression test for bug #2805
*
* `gsd-sdk query init.plan-phase <N>` returned the archived prior-milestone
* directory when the current milestone had a phase with the same number but
* no directory yet. getPhaseInfoWithFallback did not treat an archived hit as
* "not yet created" when the current ROADMAP listed the phase.
*
* Root cause: findPhase searches archived milestones as a fallback. When the
* archive matched (found:true, archived:"vX"), getPhaseInfoWithFallback
* treated it as a valid disk match and never consulted the current ROADMAP.
*
* Fix: in getPhaseInfoWithFallback, when phaseInfo.archived is set AND
* roadmapPhase.found is true, discard the archived hit and fall through to
* the ROADMAP-based fallback (directory:null, current phase metadata).
*/
'use strict';
const { describe, test, beforeEach, afterEach } = require('node:test');
const assert = require('node:assert/strict');
const fs = require('node:fs');
const path = require('node:path');
const { execFileSync } = require('node:child_process');
const { createTempGitProject, cleanup } = require('./helpers.cjs');
const REPO_ROOT = path.join(__dirname, '..');
const SDK_CLI = path.join(REPO_ROOT, 'sdk', 'dist', 'cli.js');
function runSdkQuery(subcommand, args, projectDir) {
const argv = ['query', subcommand, ...args, '--project-dir', projectDir];
let stdout = '';
let stderr = '';
let exitCode = 0;
try {
stdout = execFileSync(process.execPath, [SDK_CLI, ...argv], {
encoding: 'utf-8',
stdio: ['pipe', 'pipe', 'pipe'],
env: { ...process.env, GSD_SESSION_KEY: '' },
});
} catch (err) {
exitCode = err.status ?? 1;
stdout = err.stdout?.toString() ?? '';
stderr = err.stderr?.toString() ?? '';
}
let json = null;
try { json = JSON.parse(stdout.trim()); } catch { /* ok */ }
return { exitCode, json, stderr: stderr.trim() };
}
/**
* Create a project with:
* - An archived prior milestone vX with a phase 02
* - A current milestone vX+1 with phase 02 in ROADMAP.md but NO directory yet
*/
function setupArchivedAndCurrent(tmpDir) {
const planningDir = path.join(tmpDir, '.planning');
// Archived prior milestone phase 02
const archivePhaseDir = path.join(
planningDir, 'milestones', 'v1.0-phases', '02-auth'
);
fs.mkdirSync(archivePhaseDir, { recursive: true });
fs.writeFileSync(path.join(archivePhaseDir, '01-PLAN.md'), '# Plan\n');
// Current milestone ROADMAP.md with phase 02 (no directory yet)
const roadmap = [
'# My Project Roadmap',
'',
'## v2.0 — Phase 2',
'',
'### Phase 2: New Auth Refactor',
'',
'**Requirements:** REQ-010, REQ-011',
'',
'| # | Phase | Plans | Status | Date |',
'|---|-------|-------|--------|------|',
'| 2 | New Auth Refactor | 0/3 | Planned | |',
'',
].join('\n');
fs.mkdirSync(path.join(planningDir, 'phases'), { recursive: true });
fs.writeFileSync(path.join(planningDir, 'ROADMAP.md'), roadmap);
// STATE.md pointing at v2.0
fs.writeFileSync(
path.join(planningDir, 'STATE.md'),
[
'---',
'version: "v2.0"',
'---',
'# State',
].join('\n')
);
}
describe('bug-2805: init.plan-phase prefers current ROADMAP over archived dir', () => {
let tmpDir;
beforeEach(() => {
tmpDir = createTempGitProject('gsd-test-2805-');
});
afterEach(() => {
cleanup(tmpDir);
});
test('phase_dir is null (not archived dir) when current milestone has the phase', () => {
setupArchivedAndCurrent(tmpDir);
const result = runSdkQuery('init.plan-phase', ['2'], tmpDir);
assert.strictEqual(result.exitCode, 0, `should exit 0; stderr: ${result.stderr}`);
assert.ok(result.json !== null, 'should emit JSON');
// Before fix: phase_dir was ".planning/milestones/v1.0-phases/02-auth"
// After fix: phase_dir must be null (no directory yet for current milestone)
assert.strictEqual(
result.json.phase_dir,
null,
`phase_dir should be null (current milestone has no dir yet), got: ${result.json.phase_dir}`
);
});
test('phase_found is true (phase exists in ROADMAP) even without a disk directory', () => {
setupArchivedAndCurrent(tmpDir);
const result = runSdkQuery('init.plan-phase', ['2'], tmpDir);
assert.ok(result.json?.phase_found === true, 'phase_found should be true (ROADMAP has it)');
});
test('phase_name comes from current ROADMAP, not archived dir name', () => {
setupArchivedAndCurrent(tmpDir);
const result = runSdkQuery('init.plan-phase', ['2'], tmpDir);
// Archived dir is named "02-auth"; current ROADMAP says "New Auth Refactor"
// Assert the exact value from the ROADMAP fixture to fully protect the regression.
assert.strictEqual(
result.json?.phase_name,
'New Auth Refactor',
`phase_name should come from ROADMAP ("New Auth Refactor"), not the archived dir slug "02-auth", got: "${result.json?.phase_name}"`
);
});
});

View File

@@ -1,142 +0,0 @@
/**
* Regression test for #2829: `command not found: gsd-sdk` with local-mode install.
*
* Repro: a fresh `npx @opengsd/get-shit-done-redux@latest` install with the runtime set
* to local mode left every `gsd-sdk query …` call site unable to resolve the
* binary because the installer's previous behavior was to skip SDK linking
* entirely for local installs (#2678 over-corrected). The published tarball
* actually carries `sdk/dist/cli.js` and `bin/gsd-sdk.js` regardless of mode,
* and the shim resolves the CLI relative to its own __dirname — so the same
* self-link strategy that powers npx-cache global installs (#2775) also works
* for local installs.
*
* Fix: when `installSdkIfNeeded({ isLocal: true })` runs and `sdk/dist/cli.js`
* is present, the installer must NOT silently skip — it must verify
* `gsd-sdk` is on PATH and self-link the shim into a user-writable PATH dir
* if not, so `/gsd-plan` and friends can call `gsd-sdk query …` directly.
*
* Pre-existing #2678 contract preserved: when the dist is missing in local
* mode, the installer warns and returns instead of process.exit(1).
*/
'use strict';
process.env.GSD_TEST_MODE = '1';
const { describe, test, beforeEach, afterEach } = require('node:test');
const assert = require('node:assert/strict');
const fs = require('fs');
const path = require('path');
const { installSdkIfNeeded } = require('../bin/install.js');
const { createTempDir, cleanup, captureConsole } = require('./helpers.cjs');
const isWindows = process.platform === 'win32';
describe('bug #2829: local-mode install must materialize gsd-sdk on PATH',
{ skip: isWindows ? 'POSIX-only: asserts ~/.local/bin shebang shim; Windows uses gsd-sdk.cmd + USERPROFILE + PATHEXT' : false },
() => {
let tmpRoot;
let sdkDir;
let pathDir;
let homeDir;
let savedEnv;
beforeEach(() => {
tmpRoot = createTempDir('gsd-2829-');
sdkDir = path.join(tmpRoot, 'sdk');
fs.mkdirSync(path.join(sdkDir, 'dist'), { recursive: true });
fs.writeFileSync(
path.join(sdkDir, 'dist', 'cli.js'),
'#!/usr/bin/env node\nconsole.log("0.0.0-test");\n',
{ mode: 0o755 },
);
pathDir = path.join(tmpRoot, 'somebin');
fs.mkdirSync(pathDir, { recursive: true });
homeDir = path.join(tmpRoot, 'home');
fs.mkdirSync(homeDir, { recursive: true });
savedEnv = { PATH: process.env.PATH, HOME: process.env.HOME };
process.env.PATH = pathDir;
process.env.HOME = homeDir;
});
afterEach(() => {
if (savedEnv.PATH == null) delete process.env.PATH;
else process.env.PATH = savedEnv.PATH;
if (savedEnv.HOME == null) delete process.env.HOME;
else process.env.HOME = savedEnv.HOME;
cleanup(tmpRoot);
});
test('isLocal=true with sdk/dist/cli.js present self-links gsd-sdk into an on-PATH HOME bin dir', () => {
const localBin = path.join(homeDir, '.local', 'bin');
fs.mkdirSync(localBin, { recursive: true });
process.env.PATH = `${localBin}${path.delimiter}${pathDir}`;
const { stdout, stderr } = captureConsole(() => {
installSdkIfNeeded({ sdkDir, isLocal: true });
});
const combined = `${stdout}\n${stderr}`;
// The shim must be materialized so `gsd-sdk query …` resolves.
const linkPath = path.join(localBin, 'gsd-sdk');
assert.ok(
fs.existsSync(linkPath),
`local install must self-link gsd-sdk into ${linkPath}. Output:\n${combined}`,
);
// And the installer must report ready (matches the global-mode UX).
assert.ok(
/GSD SDK ready/.test(combined),
`local install must print "GSD SDK ready" once gsd-sdk is on PATH. Output:\n${combined}`,
);
// It must NOT print the legacy "Skipping SDK check for local install" line —
// that's exactly the regression #2829 reports.
assert.ok(
!/Skipping SDK check for local install/.test(combined),
`local install must NOT silently skip when the dist is present (#2829). Output:\n${combined}`,
);
});
test('isLocal=true preserves #2678 contract when sdk/dist/cli.js is missing — warn, do not exit', () => {
// Wipe the staged dist to simulate a missing-SDK shape.
fs.rmSync(path.join(sdkDir, 'dist'), { recursive: true, force: true });
let exitCalled = false;
const origExit = process.exit;
process.exit = (code) => {
exitCalled = true;
throw new Error(`process.exit(${code}) — local install must not exit on missing SDK (#2678)`);
};
try {
const { stderr } = captureConsole(() => {
installSdkIfNeeded({ sdkDir, isLocal: true });
});
assert.strictEqual(exitCalled, false, 'must not call process.exit in local mode');
assert.ok(
/Skipping SDK check for local install/.test(stderr),
`installer must surface a local-install warning when dist is missing. stderr:\n${stderr}`,
);
} finally {
process.exit = origExit;
}
});
test('isLocal=true with dist present and no on-PATH HOME bin still warns rather than lying about readiness', () => {
// PATH stays as a single non-HOME dir; any HOME bin candidate remains off-PATH.
// Mirrors the #2775 invariant: do not print "ready" when the post-link
// probe still cannot find gsd-sdk on PATH.
const { stdout, stderr } = captureConsole(() => {
installSdkIfNeeded({ sdkDir, isLocal: true });
});
const combined = `${stdout}\n${stderr}`;
assert.ok(
!/GSD SDK ready/.test(combined),
`installer must not falsely claim ready when gsd-sdk is not callable. Output:\n${combined}`,
);
assert.ok(
/not on (your )?PATH/i.test(combined),
`installer must surface a PATH warning. Output:\n${combined}`,
);
});
});

View File

@@ -1,150 +0,0 @@
'use strict';
process.env.GSD_TEST_MODE = '1';
/**
* Bug #2962: --sdk install flag on Windows leaves gsd-sdk un-shimmed.
*
* Tests are split into two layers, each at the right level of abstraction:
*
* 1. buildWindowsShimTriple — pure IR builder. Tests assert on TYPED
* FIELDS of the returned record (interpreter, target, eol, fileNames).
* No filesystem, no spawn, no text reads. This is the level where
* structural correctness lives.
*
* 2. trySelfLinkGsdSdkWindows — fs/spawn driver that calls the IR builder
* and writes the rendered shims to disk. Tests assert FILESYSTEM FACTS
* (file exists, file is non-empty, file mtime advanced after replace,
* function return value). No reads, no parsing, no substring matching.
*
* Per the repo's no-source-grep testing standard (CONTRIBUTING.md): the
* test must NEVER read shim file contents and pattern-match against them.
* The IR is the contract; the rendered text is an implementation detail of
* the renderer.
*/
const { test, describe, before, after } = require('node:test');
const assert = require('node:assert/strict');
const fs = require('node:fs');
const os = require('node:os');
const path = require('node:path');
const cp = require('node:child_process');
const ROOT = path.join(__dirname, '..');
const installModule = require(path.join(ROOT, 'bin', 'install.js'));
describe('Bug #2962: buildWindowsShimTriple — pure IR builder', () => {
test('resolves shimSrc to an absolute path on the invocation.target field', () => {
const shimSrc = path.join(ROOT, 'bin', 'gsd-sdk.js');
const triple = installModule.buildWindowsShimTriple(shimSrc);
assert.equal(triple.invocation.target, path.resolve(shimSrc));
assert.equal(triple.invocation.interpreter, 'node');
});
test('produces a structured IR with the documented shape', () => {
const triple = installModule.buildWindowsShimTriple(path.join(ROOT, 'bin', 'gsd-sdk.js'));
// Lock the public IR shape — adding/removing a key requires updating this assertion.
assert.deepEqual(Object.keys(triple).sort(), ['eol', 'fileNames', 'invocation', 'render']);
assert.deepEqual(Object.keys(triple.invocation).sort(), ['interpreter', 'target']);
assert.deepEqual(Object.keys(triple.eol).sort(), ['cmd', 'ps1', 'sh']);
assert.deepEqual(Object.keys(triple.fileNames).sort(), ['cmd', 'ps1', 'sh']);
assert.deepEqual(Object.keys(triple.render).sort(), ['cmd', 'ps1', 'sh']);
});
test('declares CRLF line endings on the .cmd file, LF on .ps1 and bash wrapper', () => {
const triple = installModule.buildWindowsShimTriple(path.join(ROOT, 'bin', 'gsd-sdk.js'));
assert.deepEqual(triple.eol, { cmd: '\r\n', ps1: '\n', sh: '\n' });
});
test('declares the standard npm-style filenames for the shim triple', () => {
const triple = installModule.buildWindowsShimTriple(path.join(ROOT, 'bin', 'gsd-sdk.js'));
assert.deepEqual(triple.fileNames, { cmd: 'gsd-sdk.cmd', ps1: 'gsd-sdk.ps1', sh: 'gsd-sdk' });
});
test('IR is purely a function of shimSrc — no fs / spawn side effects', () => {
// If buildWindowsShimTriple touched the filesystem, calling it twice with
// different shimSrc paths would leave two different artifacts. Asserting
// pure-function behavior structurally: same input → identical IR.
const shimSrc = path.join(ROOT, 'bin', 'gsd-sdk.js');
const a = installModule.buildWindowsShimTriple(shimSrc);
const b = installModule.buildWindowsShimTriple(shimSrc);
assert.deepEqual(a.invocation, b.invocation);
assert.deepEqual(a.eol, b.eol);
assert.deepEqual(a.fileNames, b.fileNames);
});
});
describe('Bug #2962: trySelfLinkGsdSdkWindows — fs/spawn driver', () => {
let tmpDir;
let origExecSync;
before(() => {
tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'gsd-2962-'));
origExecSync = cp.execSync;
cp.execSync = (cmd) => {
if (typeof cmd === 'string' && cmd.trim() === 'npm prefix -g') {
return tmpDir + '\n';
}
return origExecSync.call(cp, cmd);
};
});
after(() => {
cp.execSync = origExecSync;
fs.rmSync(tmpDir, { recursive: true, force: true });
});
test('returns the .cmd path on success and writes all three shim files', () => {
const shimSrc = path.join(ROOT, 'bin', 'gsd-sdk.js');
const triple = installModule.buildWindowsShimTriple(shimSrc);
const result = installModule.trySelfLinkGsdSdkWindows(shimSrc);
assert.equal(result, path.join(tmpDir, triple.fileNames.cmd));
for (const fileName of Object.values(triple.fileNames)) {
const target = path.join(tmpDir, fileName);
const stat = fs.statSync(target);
assert.ok(stat.isFile(), `${fileName} must be a regular file`);
assert.ok(stat.size > 0, `${fileName} must be non-empty`);
}
});
test('the rendered file size matches the IR renderer\'s output length (renderer drives the writer)', () => {
// Asserts the writer writes exactly what the renderer produces — no mutation,
// no double-write, no truncation. We compare BYTE LENGTHS, not contents:
// length is a structural property; content equality would re-introduce text matching.
const shimSrc = path.join(ROOT, 'bin', 'gsd-sdk.js');
const triple = installModule.buildWindowsShimTriple(shimSrc);
installModule.trySelfLinkGsdSdkWindows(shimSrc);
for (const kind of ['cmd', 'ps1', 'sh']) {
const target = path.join(tmpDir, triple.fileNames[kind]);
const expected = Buffer.byteLength(triple.render[kind](), 'utf8');
assert.equal(fs.statSync(target).size, expected, `${kind} byte length matches renderer`);
}
});
test('replaces stale shims atomically (mtime advances on rewrite)', () => {
const shimSrc = path.join(ROOT, 'bin', 'gsd-sdk.js');
installModule.trySelfLinkGsdSdkWindows(shimSrc);
const cmdPath = path.join(tmpDir, 'gsd-sdk.cmd');
const beforeMtime = fs.statSync(cmdPath).mtimeMs;
// Wait at least 10ms so mtime granularity (1ms on most fs, 1s on some) records the change.
const wait = Date.now() + 20;
while (Date.now() < wait) { /* busy-wait, intentional */ }
installModule.trySelfLinkGsdSdkWindows(shimSrc);
const afterMtime = fs.statSync(cmdPath).mtimeMs;
assert.ok(afterMtime > beforeMtime, `mtime must advance: before=${beforeMtime} after=${afterMtime}`);
});
test('returns null when npm prefix -g fails', () => {
const restore = cp.execSync;
cp.execSync = () => { throw new Error('npm not on PATH'); };
try {
const result = installModule.trySelfLinkGsdSdkWindows(path.join(ROOT, 'bin', 'gsd-sdk.js'));
assert.equal(result, null);
} finally {
cp.execSync = restore;
}
});
});

View File

@@ -1,144 +0,0 @@
/**
* Regression test for bug #2964
*
* The release-sdk hotfix workflow's auto_cherry_pick loop aborted the entire
* run if any commit between the base tag and origin/main had an empty diff
* against its parent (e.g. a squash-merge whose contents were already merged
* via an earlier PR). `git cherry-pick -x` exits non-zero on empty commits
* with "The previous cherry-pick is now empty", and the workflow's loop
* (`if ! git cherry-pick -x "$SHA"; then ... exit 1`) treated any non-zero
* as a hard conflict — bricking every hotfix the moment a no-op commit
* landed on main.
*
* Fix: pass `--allow-empty --keep-redundant-commits` so empty picks are
* preserved on the hotfix branch (with `-x` provenance, matching main 1:1)
* and picks whose diff resolves to empty after applying to the new base
* also pass cleanly. Real conflicts still surface — the flags only change
* the empty-commit exit code.
*
* This test asserts both:
* 1. Static — the workflow YAML carries the flags on the cherry-pick call
* inside the auto_cherry_pick loop. If a future edit drops them, this
* regresses immediately.
* 2. Behavioral — `git cherry-pick -x --allow-empty --keep-redundant-commits`
* against a real empty commit in a throwaway repo exits 0 (proves the
* flags semantically do what we claim), while plain `git cherry-pick -x`
* exits non-zero against the same commit (proves the bug exists without
* the flags).
*/
'use strict';
// allow-test-rule: source-text-is-the-product
// The release-sdk.yml workflow IS the product for hotfix automation —
// GitHub Actions executes the YAML's shell verbatim. Testing the text
// content tests the deployed contract: if the flags are absent, the
// empty-commit guarantee is absent.
const { describe, test } = require('node:test');
const assert = require('node:assert/strict');
const fs = require('node:fs');
const os = require('node:os');
const path = require('node:path');
const { spawnSync } = require('node:child_process');
const WORKFLOW_PATH = path.join(__dirname, '..', '.github', 'workflows', 'release-sdk.yml');
function git(cwd, args, env = {}) {
// Force-disable signing inline so a developer's global gpgsign / sshsign
// config can't fail commits in this throwaway repo. Don't rely on env
// because gpg.format/user.signingkey live in gitconfig, not env vars.
const signingOff = ['-c', 'commit.gpgsign=false', '-c', 'tag.gpgsign=false', '-c', 'gpg.format=openpgp', '-c', 'user.signingkey='];
return spawnSync('git', [...signingOff, ...args], {
cwd,
encoding: 'utf8',
env: { ...process.env, ...env, GIT_AUTHOR_NAME: 'test', GIT_AUTHOR_EMAIL: 't@t', GIT_COMMITTER_NAME: 'test', GIT_COMMITTER_EMAIL: 't@t' },
});
}
describe('bug-2964: release-sdk hotfix cherry-pick survives empty commits', () => {
test('release-sdk.yml passes --allow-empty --keep-redundant-commits in the auto_cherry_pick loop', () => {
const yaml = fs.readFileSync(WORKFLOW_PATH, 'utf8');
// Find the auto_cherry_pick block by anchoring on a line unique to it,
// then assert the cherry-pick invocation inside that block carries both
// flags. We deliberately scope to the loop — a stray `git cherry-pick`
// elsewhere in the file (none today) would not satisfy this contract.
const loopAnchor = yaml.indexOf('CANDIDATES=$(git cherry HEAD origin/main');
assert.ok(
loopAnchor !== -1,
'release-sdk.yml must contain the auto_cherry_pick loop that derives candidates via `git cherry HEAD origin/main` (#2964)'
);
// The cherry-pick call lives within the auto_cherry_pick loop. Bound
// the slice generously after the anchor so future pre-skip guards /
// classification scaffolding (e.g. the merge-commit pre-skip added
// on PR #2970, the workflow-file pre-skip added on PR for #2980,
// the PIPESTATUS-snapshot hardening added on PR for #2984's CR
// findings) don't push the call out of range, but still tight
// enough to avoid matching unrelated cherry-pick refs elsewhere in
// the workflow file.
// Allow arbitrary git options between `git` and `cherry-pick` (e.g.
// `git -c merge.conflictStyle=merge cherry-pick ...` added for #2966)
// so this test doesn't false-fail on legitimate option additions.
const window = yaml.slice(loopAnchor, loopAnchor + 8000);
const pickMatch = /git\b[^\n]*?cherry-pick[^\n]*"\$SHA"/.exec(window);
assert.ok(
pickMatch,
'auto_cherry_pick loop must invoke `git ... cherry-pick ... "$SHA"` (#2964)'
);
const pickLine = pickMatch[0];
assert.ok(
pickLine.includes('--allow-empty'),
`auto_cherry_pick must pass --allow-empty so empty no-op commits on main do not abort the hotfix (#2964). Found: ${pickLine}`
);
assert.ok(
pickLine.includes('--keep-redundant-commits'),
`auto_cherry_pick must pass --keep-redundant-commits so commits whose diff resolves to empty after rebasing onto the base tag do not abort the hotfix (#2964). Found: ${pickLine}`
);
});
test('git cherry-pick with --allow-empty --keep-redundant-commits succeeds on an empty commit; without them it fails', () => {
const tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'bug-2964-'));
try {
// Build a synthetic repo with one real commit on main and one truly
// empty commit on top — same shape as the real upstream artifact
// (b328f326 on origin/main has tree == its parent's tree).
assert.equal(git(tmp, ['init', '-q', '-b', 'main']).status, 0, 'git init');
fs.writeFileSync(path.join(tmp, 'README.md'), 'base\n');
assert.equal(git(tmp, ['add', 'README.md']).status, 0, 'git add');
assert.equal(git(tmp, ['commit', '-q', '-m', 'base']).status, 0, 'base commit');
assert.equal(git(tmp, ['tag', 'v0.0.0']).status, 0, 'tag base');
// Make a genuinely empty commit on main.
assert.equal(git(tmp, ['commit', '--allow-empty', '-q', '-m', 'fix: noop on main']).status, 0, 'empty commit');
const empty = git(tmp, ['rev-parse', 'HEAD']).stdout.trim();
assert.ok(empty.length === 40, `expected sha, got ${empty}`);
// Reset to the base tag (simulates the hotfix branch starting from v0.0.0).
assert.equal(git(tmp, ['checkout', '-q', '-b', 'hotfix/0.0.1', 'v0.0.0']).status, 0, 'checkout hotfix');
// Without the flags: cherry-pick of an empty commit fails.
const without = git(tmp, ['cherry-pick', '-x', empty]);
assert.notEqual(
without.status,
0,
'plain `git cherry-pick -x` MUST fail on an empty commit — if this passes, git semantics changed and the bug premise is gone (#2964)'
);
// Reset cherry-pick state for the next run.
git(tmp, ['cherry-pick', '--abort']);
// git may have already auto-resolved to a clean state; ensure we're back to v0.0.0.
git(tmp, ['reset', '--hard', 'v0.0.0']);
// With the flags (matching what the workflow now uses): success.
const withFlags = git(tmp, ['cherry-pick', '-x', '--allow-empty', '--keep-redundant-commits', empty]);
assert.equal(
withFlags.status,
0,
`git cherry-pick -x --allow-empty --keep-redundant-commits MUST succeed on an empty commit (#2964). stderr: ${withFlags.stderr}`
);
} finally {
fs.rmSync(tmp, { recursive: true, force: true });
}
});
});

View File

@@ -1,191 +0,0 @@
'use strict';
process.env.GSD_TEST_MODE = '1';
/**
* Regression test for #3011: SDK not found.
*
* Reporter (Windows / PowerShell 7) ran `npx @opengsd/get-shit-done-redux@latest`,
* upgrade reported success, but `gsd-sdk` could not be resolved by Claude
* Code, Git Bash, PowerShell, or WSL. The previous diagnostic was a
* generic "not on your PATH" with no actionable info; the user couldn't
* find where the shim was written or how to add it to PATH for each shell.
*
* Fix: formatSdkPathDiagnostic() returns a typed IR with the shim
* location, platform-specific PATH-export commands, and an npx-note
* when running under an `_npx` cache. The console renderer in install.js
* just emits each line; tests assert on the IR fields directly.
*/
const { test, describe } = require('node:test');
const assert = require('node:assert/strict');
const path = require('node:path');
const { formatSdkPathDiagnostic } = require(path.join(__dirname, '..', 'bin', 'install.js'));
describe('Bug #3011: formatSdkPathDiagnostic — Windows shim location and PATH commands', () => {
test('emits shim location line when shimDir is provided', () => {
const ir = formatSdkPathDiagnostic({
shimDir: 'C:\\Users\\me\\AppData\\Roaming\\npm',
platform: 'win32',
runDir: 'C:\\Users\\me\\AppData\\Roaming\\npm\\node_modules\\get-shit-done-redux\\bin',
});
assert.equal(ir.shimLocationLine,
'Shim written to: C:\\Users\\me\\AppData\\Roaming\\npm');
});
test('Windows action lines include all three shell flavors (PowerShell, cmd.exe, Git Bash)', () => {
const ir = formatSdkPathDiagnostic({
shimDir: 'C:\\Users\\me\\AppData\\Roaming\\npm',
platform: 'win32',
runDir: 'C:\\some\\path',
});
const labels = ir.actionLines.map(l => l.split(':')[0].trim());
assert.ok(labels.some(l => l === 'PowerShell'), `expected PowerShell line, got: ${JSON.stringify(labels)}`);
assert.ok(labels.some(l => l === 'cmd.exe'), `expected cmd.exe line, got: ${JSON.stringify(labels)}`);
assert.ok(labels.some(l => l === 'Git Bash'), `expected Git Bash line, got: ${JSON.stringify(labels)}`);
});
test('Git Bash command translates Windows backslashes to forward slashes', () => {
const ir = formatSdkPathDiagnostic({
shimDir: 'C:\\Users\\me\\AppData\\Roaming\\npm',
platform: 'win32',
runDir: 'C:\\some\\path',
});
const gitBash = ir.actionLines.find(l => l.startsWith('Git Bash'));
assert.ok(gitBash);
// Git Bash uses POSIX path syntax; backslashes would not work in bash.
assert.equal(gitBash.includes('\\'), false,
`Git Bash line must not contain backslashes: ${gitBash}`);
assert.ok(gitBash.includes('C:/Users/me/AppData/Roaming/npm'),
`Git Bash line must contain forward-slash path: ${gitBash}`);
});
test('PowerShell command preserves Windows backslashes in the embedded path', () => {
const ir = formatSdkPathDiagnostic({
shimDir: 'C:\\Users\\me\\AppData\\Roaming\\npm',
platform: 'win32',
runDir: 'C:\\some\\path',
});
const ps = ir.actionLines.find(l => l.startsWith('PowerShell'));
assert.ok(ps);
// PowerShell uses native Windows paths.
assert.ok(ps.includes('C:\\Users\\me\\AppData\\Roaming\\npm'),
`PowerShell line must contain Windows-style path: ${ps}`);
});
test("paths containing a single quote are escaped for each shell (#3014 CR)", () => {
// CR finding: a real Windows username like "O'Neil" would generate
// unparseable commands. PowerShell single-quote escape is '' (doubled);
// bash within outer single-quotes uses '\'' to embed a literal quote;
// POSIX export within double-quotes leaves single quotes alone.
const ir = formatSdkPathDiagnostic({
shimDir: "C:\\Users\\O'Neil\\AppData\\Roaming\\npm",
platform: 'win32',
runDir: 'C:\\some\\path',
});
const ps = ir.actionLines.find(l => l.startsWith('PowerShell'));
const cmd = ir.actionLines.find(l => l.startsWith('cmd.exe'));
const gitBash = ir.actionLines.find(l => l.startsWith('Git Bash'));
// PowerShell: literal quote escape is doubled
assert.ok(ps.includes("C:\\Users\\O''Neil\\AppData\\Roaming\\npm"),
`PowerShell line must double single quotes: ${ps}`);
// cmd.exe (which delegates to powershell) uses the same PS-escape
assert.ok(cmd.includes("C:\\Users\\O''Neil\\AppData\\Roaming\\npm"),
`cmd.exe line must double single quotes (delegates to PowerShell): ${cmd}`);
// Git Bash: '\'' escape inside outer single-quoted echo
assert.ok(gitBash.includes("C:/Users/O'\\''Neil/AppData/Roaming/npm"),
`Git Bash line must escape single quote with '\\\\'': ${gitBash}`);
});
});
describe('Bug #3011: formatSdkPathDiagnostic — POSIX action lines', () => {
test('emits a single export PATH line on Linux', () => {
const ir = formatSdkPathDiagnostic({
shimDir: '/home/me/.local/bin',
platform: 'linux',
runDir: '/home/me/.local/lib/node_modules/get-shit-done-redux/bin',
});
const exports_ = ir.actionLines.filter(l => l.startsWith('export PATH='));
assert.equal(exports_.length, 1, `expected 1 export line, got: ${JSON.stringify(ir.actionLines)}`);
assert.equal(exports_[0], 'export PATH="/home/me/.local/bin:$PATH"');
});
test('emits a single export PATH line on macOS (darwin)', () => {
const ir = formatSdkPathDiagnostic({
shimDir: '/usr/local/bin',
platform: 'darwin',
runDir: '/usr/local/lib/node_modules/get-shit-done-redux/bin',
});
assert.ok(ir.actionLines.some(l => l === 'export PATH="/usr/local/bin:$PATH"'));
});
});
describe('Bug #3011: formatSdkPathDiagnostic — fallback when shimDir is null', () => {
test('shimLocationLine is empty', () => {
const ir = formatSdkPathDiagnostic({
shimDir: null,
platform: 'win32',
runDir: 'C:\\some\\path',
});
assert.equal(ir.shimLocationLine, '');
});
test('action lines fall back to npm install -g advice', () => {
const ir = formatSdkPathDiagnostic({
shimDir: null,
platform: 'win32',
runDir: 'C:\\some\\path',
});
assert.ok(ir.actionLines.some(l => l.includes('npm install -g @opengsd/get-shit-done-redux')));
});
});
describe('Bug #3011: formatSdkPathDiagnostic — npx-cache detection', () => {
test('detects POSIX npx cache path', () => {
const ir = formatSdkPathDiagnostic({
shimDir: '/home/me/.local/bin',
platform: 'linux',
runDir: '/home/me/.npm/_npx/abc123/node_modules/get-shit-done-redux/bin',
});
assert.equal(ir.isNpx, true);
assert.ok(ir.npxNoteLines.length >= 2,
`expected npx note lines, got: ${JSON.stringify(ir.npxNoteLines)}`);
assert.ok(ir.npxNoteLines.some(l => l.includes('npx')));
assert.ok(ir.npxNoteLines.some(l => l.includes('npm install -g')));
});
test('detects Windows npx cache path', () => {
const ir = formatSdkPathDiagnostic({
shimDir: 'C:\\Users\\me\\AppData\\Roaming\\npm',
platform: 'win32',
runDir: 'C:\\Users\\me\\AppData\\Local\\npm-cache\\_npx\\abc123\\node_modules\\get-shit-done-redux\\bin',
});
assert.equal(ir.isNpx, true);
});
test('non-npx invocation leaves npxNoteLines empty', () => {
const ir = formatSdkPathDiagnostic({
shimDir: 'C:\\Users\\me\\AppData\\Roaming\\npm',
platform: 'win32',
runDir: 'C:\\Users\\me\\AppData\\Roaming\\npm\\node_modules\\get-shit-done-redux\\bin',
});
assert.equal(ir.isNpx, false);
assert.deepEqual(ir.npxNoteLines, []);
});
});
describe('Bug #3011: formatSdkPathDiagnostic — actionable shape contract', () => {
test('returns the documented IR shape for any input', () => {
const ir = formatSdkPathDiagnostic({
shimDir: '/x',
platform: 'linux',
runDir: '/y',
});
assert.equal(typeof ir.shimLocationLine, 'string');
assert.ok(Array.isArray(ir.actionLines));
assert.ok(Array.isArray(ir.npxNoteLines));
assert.equal(typeof ir.isNpx, 'boolean');
assert.equal(typeof ir.isWin32, 'boolean');
});
});

View File

@@ -1,172 +0,0 @@
/**
* Regression test for #3033: --sdk flag parsed but never used.
*
* `hasSdk` was set in bin/install.js but never passed to `installSdkIfNeeded`,
* so `npx @opengsd/get-shit-done-redux@latest --sdk` produced a misleading "✓ GSD SDK ready"
* message while still silently skipping SDK deployment for local installs.
*
* Fix: `installSdkIfNeeded` now accepts `opts.forceSdk`. When true, the
* early-return for `isLocal=true` + missing dist is bypassed and the
* fail-fast diagnostic fires (same as a global install with missing dist),
* and when dist IS present the full shim-link path runs regardless of
* install mode.
*
* Tests here call `installSdkIfNeeded` directly with `forceSdk: true`
* and assert on filesystem state and console output — no source-grep.
*/
'use strict';
process.env.GSD_TEST_MODE = '1';
const { describe, test, beforeEach, afterEach } = require('node:test');
const assert = require('node:assert/strict');
const fs = require('fs');
const path = require('path');
const os = require('os');
const { installSdkIfNeeded } = require('../bin/install.js');
const { createTempDir, cleanup, captureConsole } = require('./helpers.cjs');
const isWindows = process.platform === 'win32';
describe('bug #3033: --sdk flag (opts.forceSdk) must be wired into installSdkIfNeeded',
{ skip: isWindows ? 'POSIX-only: forces shebang gsd-sdk shim into ~/.local/bin and asserts mode 0o755' : false },
() => {
let tmpRoot;
let sdkDir;
let pathDir;
let homeDir;
let savedEnv;
beforeEach(() => {
tmpRoot = createTempDir('gsd-3033-');
sdkDir = path.join(tmpRoot, 'sdk');
pathDir = path.join(tmpRoot, 'somebin');
homeDir = path.join(tmpRoot, 'home');
fs.mkdirSync(pathDir, { recursive: true });
fs.mkdirSync(homeDir, { recursive: true });
savedEnv = { PATH: process.env.PATH, HOME: process.env.HOME };
process.env.PATH = pathDir;
process.env.HOME = homeDir;
});
afterEach(() => {
if (savedEnv.PATH == null) delete process.env.PATH;
else process.env.PATH = savedEnv.PATH;
if (savedEnv.HOME == null) delete process.env.HOME;
else process.env.HOME = savedEnv.HOME;
cleanup(tmpRoot);
});
test('forceSdk=true + isLocal=true + dist present: self-links gsd-sdk into PATH dir', () => {
// Stage a valid dist so the installer can proceed past the missing-dist gate.
fs.mkdirSync(path.join(sdkDir, 'dist'), { recursive: true });
fs.writeFileSync(
path.join(sdkDir, 'dist', 'cli.js'),
'#!/usr/bin/env node\nconsole.log("0.0.0-test");\n',
{ mode: 0o755 },
);
// Put ~/.local/bin on PATH so the shim-link step can succeed.
const localBin = path.join(homeDir, '.local', 'bin');
fs.mkdirSync(localBin, { recursive: true });
process.env.PATH = `${localBin}${path.delimiter}${pathDir}`;
const { stdout, stderr } = captureConsole(() => {
installSdkIfNeeded({ sdkDir, isLocal: true, forceSdk: true });
});
const combined = `${stdout}\n${stderr}`;
// Shim must be materialized on PATH.
const linkPath = path.join(localBin, 'gsd-sdk');
assert.ok(
fs.existsSync(linkPath),
`forceSdk=true must materialize gsd-sdk shim at ${linkPath}. Output:\n${combined}`,
);
// Must report "GSD SDK ready" — not the legacy "Skipping SDK check" message.
assert.ok(
/GSD SDK ready/.test(combined),
`forceSdk=true must print "GSD SDK ready" once shim is on PATH. Output:\n${combined}`,
);
assert.ok(
!/Skipping SDK check for local install/.test(combined),
`forceSdk=true must NOT print the local-skip message. Output:\n${combined}`,
);
});
test('forceSdk=true + isLocal=true + dist missing: fails fast instead of silently skipping', () => {
// No dist directory — simulate a broken/missing SDK.
fs.mkdirSync(sdkDir, { recursive: true });
// dist/cli.js intentionally absent.
let exitCode = null;
const origExit = process.exit;
process.exit = (code) => {
exitCode = code;
throw new Error(`process.exit(${code})`);
};
let threw = false;
try {
captureConsole(() => {
installSdkIfNeeded({ sdkDir, isLocal: true, forceSdk: true });
});
} catch {
threw = true;
} finally {
process.exit = origExit;
}
// With forceSdk=true the missing-dist early-return is bypassed and the
// fail-fast path fires, calling process.exit(1).
assert.ok(
threw && exitCode === 1,
`forceSdk=true with missing dist must call process.exit(1) — exitCode=${exitCode}, threw=${threw}`,
);
});
test('throwOnFailure=true converts missing SDK dist into catchable error', () => {
fs.mkdirSync(sdkDir, { recursive: true });
assert.throws(
() => captureConsole(() => {
installSdkIfNeeded({ sdkDir, isLocal: true, forceSdk: true, throwOnFailure: true });
}),
(error) => {
assert.equal(error.code, 'GSD_SDK_MISSING_DIST');
assert.equal(error.exitCode, 1);
return true;
}
);
});
test('forceSdk=false (default) + isLocal=true + dist missing: retains #2678 soft-skip', () => {
// Verify the #2678 contract is not broken for the default (no --sdk) path.
fs.mkdirSync(sdkDir, { recursive: true });
let exitCalled = false;
const origExit = process.exit;
process.exit = (code) => {
exitCalled = true;
throw new Error(`process.exit(${code}) — local install without --sdk must not exit`);
};
try {
captureConsole(() => {
installSdkIfNeeded({ sdkDir, isLocal: true });
});
} catch (e) {
if (!exitCalled) throw e;
} finally {
process.exit = origExit;
}
assert.strictEqual(
exitCalled,
false,
'isLocal=true without forceSdk must not call process.exit (preserves #2678 contract)',
);
});
});

View File

@@ -1,39 +0,0 @@
'use strict';
const { test, describe } = require('node:test');
const assert = require('node:assert/strict');
const fs = require('node:fs');
const path = require('node:path');
const ROOT = path.join(__dirname, '..');
function read(rel) {
return fs.readFileSync(path.join(ROOT, rel), 'utf8');
}
describe('bug #3091: sdk install guidance and agent fallbacks use query-capable CLI', () => {
test('quick workflow install hint references @opengsd/get-shit-done-redux (not @opengsd/gsd-sdk)', () => {
const content = read('get-shit-done/workflows/quick.md');
// After #3668: quick.md uses local-first preflight which references
// @opengsd/get-shit-done-redux via npx for the --local fallback.
const referencesGsdRedux = content.includes('npm install -g @opengsd/get-shit-done-redux') ||
content.includes('npx @opengsd/get-shit-done-redux');
assert.ok(referencesGsdRedux, 'quick.md install hint must reference @opengsd/get-shit-done-redux');
assert.ok(!content.includes('@gsd-redux/sdk'));
assert.ok(!content.includes('@gsd-build/sdk'));
assert.ok(!content.includes('npm install -g get-shit-done-redux'));
assert.ok(!content.includes('npx get-shit-done-redux@'));
});
test('agent docs no longer reference node_modules/@opengsd/gsd-sdk/dist/cli.js query fallback', () => {
const files = [
'agents/gsd-planner.md',
'agents/gsd-executor.md',
'agents/gsd-plan-checker.md',
'agents/gsd-roadmapper.md',
];
const offenders = files.filter((f) => read(f).includes('@opengsd/gsd-sdk/dist/cli.js query'));
assert.deepStrictEqual(offenders, [], `stale @opengsd/gsd-sdk query fallback references: ${offenders.join(', ')}`);
});
});

View File

@@ -1,393 +0,0 @@
'use strict';
process.env.GSD_TEST_MODE = '1';
/**
* Regression tests for bug #3211.
*
* Windows 11 + PowerShell 7 + Node v22.22.1, fresh
* `npx @opengsd/get-shit-done-redux@latest --global --claude`:
* gsd-sdk: The term 'gsd-sdk' is not recognized
*
* Root causes (Windows sibling of #3231):
*
* A. filterNpxFromPath must handle Windows-style backslash paths (e.g.
* C:\Users\user\AppData\Local\npm-cache\_npx\abc123\node_modules\.bin).
* After replace(/\\/g, '/') the norm contains /_npx/ and should be
* stripped. We verify this explicitly because the Linux tests only exercised
* POSIX-style paths.
*
* B. isGsdSdkOnPath (zero-arg fallback) reads `process.env.PATH || ''`. On
* Windows, Node.js normalises PATH case so `process.env.PATH` always
* returns the right value in production. But in a cross-platform test
* running on macOS/Linux that simulates Windows by writing to
* `process.env.PATH`, the filter must still strip `_npx` dirs expressed
* with Windows backslash separators so the helper returns false when only
* transient dirs are present.
*
* C. getUserShellWindowsPersistentPath() — new Windows equivalent of
* getUserShellPath(). Probes the user's persistent 'Path' from the Windows
* registry via:
* powershell -NoProfile -Command
* "[Environment]::GetEnvironmentVariable('Path', 'User')"
* Returns the persistent Path string or null on failure. Must be exported
* and must apply filterNpxFromPath before returning.
*
* D. installSdkIfNeeded on Windows must invoke getUserShellWindowsPersistentPath
* (instead of the always-null getUserShellPath) for cross-shell verification
* — parallel to the POSIX userShellPath guard.
*
* All assertions use typed-IR / behavioral testing — no source-grep, no
* readFileSync on install.js source.
*/
const { describe, test, beforeEach, afterEach, before, after } = require('node:test');
const assert = require('node:assert/strict');
const fs = require('node:fs');
const os = require('node:os');
const path = require('node:path');
const cp = require('node:child_process');
const ROOT = path.join(__dirname, '..');
const installModule = require(path.join(ROOT, 'bin', 'install.js'));
const { captureConsole } = require('./helpers.cjs');
const isWindows = process.platform === 'win32';
const {
filterNpxFromPath,
isLegacyGsdSdkShim,
isGsdSdkOnPath,
installSdkIfNeeded,
getUserShellWindowsPersistentPath,
} = installModule;
// ---------------------------------------------------------------------------
// A. filterNpxFromPath — Windows backslash paths
// ---------------------------------------------------------------------------
describe('bug #3211-A: filterNpxFromPath handles Windows backslash _npx paths', () => {
test('strips a Windows-style _npx dir expressed with backslashes', () => {
assert.equal(typeof filterNpxFromPath, 'function', 'filterNpxFromPath must be exported');
// Windows npm-cache path with backslash separators, semicolon delimiter
const winNpxDir = 'C:\\Users\\user\\AppData\\Local\\npm-cache\\_npx\\abc123\\node_modules\\.bin';
const winPersistentDir = 'C:\\Users\\user\\AppData\\Roaming\\npm';
const winSystemDir = 'C:\\Windows\\System32';
// On macOS path.delimiter is ':', not ';'. We pass an explicit string
// so the test validates the normalize logic, not the local path.delimiter.
const inputPath = [winNpxDir, winPersistentDir, winSystemDir].join(';');
const result = filterNpxFromPath(inputPath);
// Regardless of delimiter used, the _npx segment must be stripped
assert.ok(
!result.includes('_npx'),
'filterNpxFromPath must strip Windows _npx dirs. Got: ' + result,
);
assert.ok(
result.includes('Roaming\\npm') || result.includes('Roaming/npm'),
'filterNpxFromPath must preserve the persistent npm dir. Got: ' + result,
);
});
test('strips a mixed-separator Windows _npx path (forward + backward slashes)', () => {
const mixedNpxDir = 'C:/Users/user/AppData/Local/npm-cache/_npx/abc/node_modules/.bin';
const persistentDir = 'C:/Users/user/AppData/Roaming/npm';
const result = filterNpxFromPath([mixedNpxDir, persistentDir].join(';'));
assert.ok(!result.includes('_npx'), 'must strip mixed-separator _npx dir. Got: ' + result);
assert.ok(result.includes('Roaming/npm'), 'must keep persistent dir. Got: ' + result);
});
test('does NOT strip a Windows user dir that merely contains "npx" as a substring', () => {
// A user-named dir like C:\my-npx-tools\bin must NOT be filtered.
const userNpxLikeDir = 'C:\\Users\\user\\my-npx-tools\\bin';
const realNpxDir = 'C:\\Users\\user\\AppData\\Local\\npm-cache\\_npx\\abc\\node_modules\\.bin';
const result = filterNpxFromPath([userNpxLikeDir, realNpxDir].join(';'));
assert.ok(
result.includes('my-npx-tools'),
'must not strip user dirs that merely contain "npx". Got: ' + result,
);
assert.ok(!result.includes('_npx'), 'must strip the real _npx dir. Got: ' + result);
});
});
// ---------------------------------------------------------------------------
// B. isGsdSdkOnPath — does not return true when only a Windows _npx dir has
// gsd-sdk.cmd (using filterNpxFromPath on the passed pathString)
// ---------------------------------------------------------------------------
describe('bug #3211-B: isGsdSdkOnPath rejects Windows _npx-only transient PATH', () => {
let tmpRoot;
before(() => {
tmpRoot = fs.mkdtempSync(path.join(os.tmpdir(), 'gsd-3211-b-'));
});
after(() => {
try { fs.rmSync(tmpRoot, { recursive: true, force: true }); } catch {}
});
test('returns false when a gsd-sdk.cmd exists only in an _npx-style transient dir', () => {
// On POSIX we name the dir with _npx/ to match the filter pattern.
// We can't set process.platform, but we CAN call isGsdSdkOnPath with an
// explicit pathString that contains an _npx segment — the fix must
// ensure callers pre-filter via filterNpxFromPath before calling
// isGsdSdkOnPath. We test filterNpxFromPath(pathString) produces an
// empty result, which means isGsdSdkOnPath of the filtered path returns false.
const npxBinDir = path.join(tmpRoot, '_npx', 'abc123', 'node_modules', '.bin');
fs.mkdirSync(npxBinDir, { recursive: true });
// Write a gsd-sdk shim (named .cmd for the Windows scenario — on POSIX
// isGsdSdkOnPath won't find .cmd; we validate the filter, not the exec check).
const shimPath = path.join(npxBinDir, 'gsd-sdk.cmd');
fs.writeFileSync(
shimPath,
['@ECHO OFF', '@node "C:\\path\\to\\gsd-sdk.js" %*', ''].join('\r\n'),
);
// The raw pathString contains an _npx segment — it MUST be filtered.
const rawPath = npxBinDir;
const persistentPath = filterNpxFromPath(rawPath);
// After filtering, the _npx dir must be gone so isGsdSdkOnPath returns false.
const onPath = isGsdSdkOnPath(persistentPath);
assert.equal(
onPath,
false,
'isGsdSdkOnPath(filterNpxFromPath(path)) must return false when only _npx dir has gsd-sdk. persistentPath=' + persistentPath,
);
});
});
// ---------------------------------------------------------------------------
// C. getUserShellWindowsPersistentPath — new export
// ---------------------------------------------------------------------------
describe('bug #3211-C: getUserShellWindowsPersistentPath export', () => {
test('is exported from install.js', () => {
assert.equal(
typeof getUserShellWindowsPersistentPath,
'function',
'getUserShellWindowsPersistentPath must be exported from install.js',
);
});
test('returns a string or null — never throws', () => {
// We can call it on macOS/Linux; it must handle non-Windows gracefully
// (return null or a string). Must never throw.
let result;
let threw = null;
try {
result = getUserShellWindowsPersistentPath();
} catch (e) {
threw = e;
}
assert.equal(threw, null, 'getUserShellWindowsPersistentPath must not throw. Error: ' + threw);
assert.ok(
result === null || typeof result === 'string',
'must return string or null. Got: ' + typeof result,
);
});
test('on non-Windows, returns null (Windows-only probe)', () => {
if (process.platform === 'win32') {
// On actual Windows, any non-null string is acceptable.
const result = getUserShellWindowsPersistentPath();
assert.ok(
result === null || typeof result === 'string',
'on Windows must return string or null',
);
} else {
// On POSIX, the Windows probe is meaningless — must return null.
const result = getUserShellWindowsPersistentPath();
assert.equal(result, null, 'on POSIX, getUserShellWindowsPersistentPath must return null');
}
});
test('when the PowerShell probe is mocked to return a path, strips _npx dirs',
{ skip: isWindows ? 'cp.execSync reassignment is not picked up by install.js on Windows; real registry Path is returned. POSIX coverage in mock; live Windows path is covered by 3211-D.' : false },
() => {
// Mock cp.execSync to return a Windows Path with both persistent and _npx dirs.
const savedExecSync = cp.execSync;
const winPersistentDir = 'C:\\Users\\user\\AppData\\Roaming\\npm';
const winNpxDir = 'C:\\Users\\user\\AppData\\Local\\npm-cache\\_npx\\abc\\node_modules\\.bin';
const mockPath = [winPersistentDir, winNpxDir].join(';');
cp.execSync = (cmd, opts) => {
if (typeof cmd === 'string' && cmd.includes('GetEnvironmentVariable')) {
return mockPath + '\n';
}
return savedExecSync.call(cp, cmd, opts);
};
let result;
try {
result = getUserShellWindowsPersistentPath();
} finally {
cp.execSync = savedExecSync;
}
// On non-Windows this returns null (the function guards on process.platform).
// On Windows it returns the filtered path. Since we can't be on both,
// we verify the filter would work correctly by directly calling filterNpxFromPath.
if (result !== null) {
assert.ok(
!result.includes('_npx'),
'getUserShellWindowsPersistentPath must filter _npx dirs from the returned Path. Got: ' + result,
);
assert.ok(
result.includes('Roaming\\npm') || result.includes('Roaming/npm'),
'must keep persistent npm dir. Got: ' + result,
);
}
});
});
// ---------------------------------------------------------------------------
// D. installSdkIfNeeded Windows false-positive: transient _npx + npm-prefix
// NOT on PATH → must NOT print "GSD SDK ready"
// ---------------------------------------------------------------------------
describe('bug #3211-D: installSdkIfNeeded — Windows _npx false-positive', () => {
let tmpRoot;
let sdkDir;
let savedEnv;
let origExecSync;
function makeSdkDir(root) {
const dir = path.join(root, 'sdk');
fs.mkdirSync(path.join(dir, 'dist'), { recursive: true });
fs.writeFileSync(
path.join(dir, 'dist', 'cli.js'),
['#!/usr/bin/env node', "console.log('0.0.0-test');", ''].join('\n'),
{ mode: 0o755 },
);
return dir;
}
beforeEach(() => {
tmpRoot = fs.mkdtempSync(path.join(os.tmpdir(), 'gsd-3211-d-'));
sdkDir = makeSdkDir(tmpRoot);
// Simulate: install-time PATH contains only a transient _npx dir
// with a gsd-sdk shim. The persistent npm prefix dir is separate and
// NOT in process.env.PATH during the npx run.
const npxBinDir = path.join(tmpRoot, '_npx', 'abc123', 'node_modules', '.bin');
fs.mkdirSync(npxBinDir, { recursive: true });
// Write a gsd-sdk shim in the transient dir (executable on POSIX)
const shimName = 'gsd-sdk';
fs.writeFileSync(
path.join(npxBinDir, shimName),
['#!/bin/sh', 'exec node /path/to/gsd-sdk.js "$@"', ''].join('\n'),
{ mode: 0o755 },
);
const homeDir = path.join(tmpRoot, 'home');
fs.mkdirSync(homeDir, { recursive: true });
savedEnv = {
PATH: process.env.PATH,
HOME: process.env.HOME,
SHELL: process.env.SHELL,
};
// Only the transient _npx dir is on PATH — nothing persistent.
// On POSIX this simulates the false-positive scenario.
process.env.PATH = npxBinDir;
process.env.HOME = homeDir;
delete process.env.SHELL;
// Mock cp.execSync for npm prefix -g — return a separate dir that is
// NOT in process.env.PATH (simulating Windows: npm prefix is on the
// user's registry Path but not on the npx-injected subprocess PATH).
const npmPrefixDir = path.join(tmpRoot, 'npm-global');
fs.mkdirSync(npmPrefixDir, { recursive: true });
origExecSync = cp.execSync;
cp.execSync = (cmd, opts) => {
if (typeof cmd === 'string' && cmd.trim() === 'npm prefix -g') {
return npmPrefixDir + '\n';
}
return origExecSync.call(cp, cmd, opts);
};
});
afterEach(() => {
cp.execSync = origExecSync;
if (savedEnv.PATH == null) delete process.env.PATH;
else process.env.PATH = savedEnv.PATH;
if (savedEnv.HOME == null) delete process.env.HOME;
else process.env.HOME = savedEnv.HOME;
if (savedEnv.SHELL == null) delete process.env.SHELL;
else process.env.SHELL = savedEnv.SHELL;
try { fs.rmSync(tmpRoot, { recursive: true, force: true }); } catch {}
});
test('does NOT print "GSD SDK ready" when the only gsd-sdk entry is in a transient _npx dir and npm-prefix is off-PATH', () => {
const { stdout, stderr } = captureConsole(() => {
installSdkIfNeeded({ sdkDir });
});
const combined = `${stdout}\n${stderr}`;
assert.ok(
!/GSD SDK ready/.test(combined),
'installer must NOT print "GSD SDK ready" when gsd-sdk is only in a transient _npx dir. Got:\n' + combined,
);
// Must emit SOME output (warning or diagnostic), not silently succeed.
assert.ok(
combined.trim().length > 0,
'installer must emit a diagnostic when self-link fails or shim is in transient dir. Got empty output.',
);
});
});
// ---------------------------------------------------------------------------
// E. isLegacyGsdSdkShim — Windows .cmd shim detection
// ---------------------------------------------------------------------------
describe('bug #3211-E: isLegacyGsdSdkShim detects legacy marker in .cmd files', () => {
let tmpRoot;
before(() => {
tmpRoot = fs.mkdtempSync(path.join(os.tmpdir(), 'gsd-3211-e-'));
});
after(() => {
try { fs.rmSync(tmpRoot, { recursive: true, force: true }); } catch {}
});
test('detects @deprecated + gsd-tools.cjs in a .cmd shim', () => {
assert.equal(typeof isLegacyGsdSdkShim, 'function');
const legacyCmd = path.join(tmpRoot, 'gsd-sdk.cmd');
fs.writeFileSync(
legacyCmd,
[
'@ECHO OFF',
':: @deprecated — use gsd-tools.cjs directly',
'@node "C:\\path\\to\\gsd-tools.cjs" %*',
'',
].join('\r\n'),
);
assert.equal(isLegacyGsdSdkShim(legacyCmd), true, 'must detect @deprecated gsd-tools.cjs in .cmd shim');
});
test('returns false for a modern .cmd shim pointing at gsd-sdk.js', () => {
const modernCmd = path.join(tmpRoot, 'gsd-sdk-modern.cmd');
fs.writeFileSync(
modernCmd,
[
'@ECHO OFF',
'@SETLOCAL',
'@node "C:\\path\\to\\get-shit-done-redux\\bin\\gsd-sdk.js" %*',
'',
].join('\r\n'),
);
assert.equal(isLegacyGsdSdkShim(modernCmd), false, 'must not flag modern .cmd shim as legacy');
});
test('returns false for a missing file', () => {
assert.equal(isLegacyGsdSdkShim(path.join(tmpRoot, 'no-such-file.cmd')), false);
});
});

View File

@@ -29,7 +29,7 @@ describe('bug #3212 execute-phase stall detection and safe resume', () => {
// Use the CJS runtime Set for CJS; use the manifest directly for SDK-side
// verification (since config-schema.ts no longer has inline literals).
const { VALID_CONFIG_KEYS: cjsKeys } = require('../get-shit-done/bin/lib/config-schema.cjs');
const manifest = JSON.parse(read('sdk/shared/config-schema.manifest.json'));
const manifest = JSON.parse(read('get-shit-done/bin/shared/config-schema.manifest.json'));
const manifestKeys = new Set(manifest.validKeys);
for (const key of ['executor.stall_detect_interval_minutes', 'executor.stall_threshold_minutes']) {

View File

@@ -1,403 +0,0 @@
/**
* Regression tests for bug #3231.
*
* `npx @opengsd/get-shit-done-redux@latest` prints `✓ GSD SDK ready (sdk/dist/cli.js)` on
* Linux but no persistent `gsd-sdk` shim is created. Two sub-bugs:
*
* 1. Transient npx PATH + null login-shell PATH → false success
* The initial isGsdSdkOnPath() call uses process.env.PATH, which includes
* `~/.npm/_npx/<hash>/node_modules/.bin` — a transient dir npx injects.
* If that dir has a `gsd-sdk` entry, onPath = true and trySelfLinkGsdSdk
* is skipped (no persistent shim). Then getUserShellPath() returns null
* (Linux, slow rc files or unset $SHELL). The guard
* `onPath && userShellPath !== null` is FALSE, leaving onPath = true →
* false `✓ GSD SDK ready` is printed.
*
* 2. Stale legacy symlink → installer treats gsd-sdk as "on PATH" and skips
* materializing a modern SDK shim. The legacy binary (`gsd-tools.cjs`) has
* an `@deprecated` marker in its first bytes, lacks the `query` registry,
* and causes "Unknown command: query" for every workflow call.
*
* 3. Clean path: sdk/dist/cli.js present + gsd-sdk self-linked into a
* persistent PATH dir → installer DOES print success.
*
* All assertions use typed-IR / behavioral testing. No source-grep, no
* readFileSync on install.js.
*/
'use strict';
process.env.GSD_TEST_MODE = '1';
const { describe, test, beforeEach, afterEach } = require('node:test');
const assert = require('node:assert/strict');
const fs = require('node:fs');
const os = require('node:os');
const path = require('node:path');
const installModule = require('../bin/install.js');
const { captureConsole } = require('./helpers.cjs');
const isWindows = process.platform === 'win32';
const {
installSdkIfNeeded,
isGsdSdkOnPath,
filterNpxFromPath,
isLegacyGsdSdkShim,
} = installModule;
// ---------------------------------------------------------------------------
// Console capture helper (no ANSI)
// ---------------------------------------------------------------------------
// ---------------------------------------------------------------------------
// Shared fixture helpers
// ---------------------------------------------------------------------------
function makeSdkDir(root) {
const sdkDir = path.join(root, 'sdk');
fs.mkdirSync(path.join(sdkDir, 'dist'), { recursive: true });
fs.writeFileSync(
path.join(sdkDir, 'dist', 'cli.js'),
['#!/usr/bin/env node', "console.log('0.0.0-test');", ''].join('\n'),
{ mode: 0o755 },
);
return sdkDir;
}
// ---------------------------------------------------------------------------
// Bug 1: transient npx PATH hit + null login-shell PATH → false "GSD SDK ready"
// ---------------------------------------------------------------------------
describe('bug #3231: transient npx PATH + null login-shell PATH',
{ skip: isWindows ? 'Linux-specific: simulates getUserShellPath()=null + POSIX shebang shim; Windows path is covered by #3211' : false },
() => {
let tmpRoot;
let sdkDir;
let savedEnv;
beforeEach(() => {
tmpRoot = fs.mkdtempSync(path.join(os.tmpdir(), 'gsd-3231-a-'));
sdkDir = makeSdkDir(tmpRoot);
// Simulate an npx-injected PATH: a transient _npx directory that happens
// to contain a gsd-sdk executable. This is NOT a persistent user location.
const npxBinDir = path.join(tmpRoot, '.npm', '_npx', 'abc123', 'node_modules', '.bin');
fs.mkdirSync(npxBinDir, { recursive: true });
const shimName = process.platform === 'win32' ? 'gsd-sdk.cmd' : 'gsd-sdk';
const shimPath = path.join(npxBinDir, shimName);
fs.writeFileSync(
shimPath,
['#!/bin/sh', 'exit 0', ''].join('\n'),
{ mode: 0o755 },
);
const homeDir = path.join(tmpRoot, 'home');
fs.mkdirSync(homeDir, { recursive: true });
savedEnv = {
PATH: process.env.PATH,
HOME: process.env.HOME,
SHELL: process.env.SHELL,
};
// Install-subprocess PATH contains ONLY the npx transient dir — nothing
// persistent. $SHELL is unset to simulate getUserShellPath() → null.
process.env.PATH = npxBinDir;
process.env.HOME = homeDir;
delete process.env.SHELL;
});
afterEach(() => {
if (savedEnv.PATH == null) delete process.env.PATH;
else process.env.PATH = savedEnv.PATH;
if (savedEnv.HOME == null) delete process.env.HOME;
else process.env.HOME = savedEnv.HOME;
if (savedEnv.SHELL == null) delete process.env.SHELL;
else process.env.SHELL = savedEnv.SHELL;
try { fs.rmSync(tmpRoot, { recursive: true, force: true }); } catch {}
});
test('does NOT print "GSD SDK ready" when only a transient _npx PATH entry has gsd-sdk', () => {
// Pre-fix: isGsdSdkOnPath() finds gsd-sdk in the npx-injected dir,
// onPath = true, trySelfLinkGsdSdk is skipped, getUserShellPath() returns
// null (SHELL unset), the guard is short-circuited, and the false ✓ is
// printed. Post-fix: _npx dirs must be excluded from the initial check
// so the installer attempts self-link and re-probes.
const { stdout, stderr } = captureConsole(() => {
installSdkIfNeeded({ sdkDir });
});
const combined = `${stdout}\n${stderr}`;
// Primary behavioral assertion: the installer must NOT falsely report
// "GSD SDK ready" when gsd-sdk is only reachable via a transient npx
// cache directory (not a persistent user PATH entry).
assert.ok(
!/GSD SDK ready/.test(combined),
'installer must NOT print "GSD SDK ready" when only the transient _npx dir has gsd-sdk. Got: ' + combined,
);
// Secondary assertion: the installer must emit a warning or fallback
// diagnostic rather than silently succeeding. The warning path prints
// "GSD SDK files are present but gsd-sdk is not on your PATH" when
// self-link fails; a successful self-link into a non-PATH dir prints the
// same warning. Either way, some output must be produced.
assert.ok(
combined.trim().length > 0,
'installer must emit a diagnostic (warning or fallback) instead of silent no-op. Got empty output.',
);
});
test('filterNpxFromPath is exported and strips /_npx/ segments', () => {
// The fix adds a helper that removes any PATH segment whose absolute path
// contains /_npx/ (POSIX) or \\_npx\\ (Windows).
assert.equal(typeof filterNpxFromPath, 'function', 'filterNpxFromPath must be exported');
const npxDir = '/home/user/.npm/_npx/abc123/node_modules/.bin';
const persistentDir = '/home/user/.local/bin';
const unrelatedDir = '/usr/local/bin';
const result = filterNpxFromPath(
[npxDir, persistentDir, unrelatedDir].join(path.delimiter),
);
const segments = result.split(path.delimiter);
assert.ok(!segments.includes(npxDir), 'filtered PATH must not include the _npx dir');
assert.ok(segments.includes(persistentDir), 'filtered PATH must keep persistent dirs');
assert.ok(segments.includes(unrelatedDir), 'filtered PATH must keep unrelated dirs');
});
test('filterNpxFromPath must not strip a user-named directory that merely contains "npx" as substring', () => {
// Containment guard: only strip when the segment truly contains /_npx/
// (between separators), not when "npx" appears as part of a user dir name.
assert.equal(typeof filterNpxFromPath, 'function');
const npxLikeUserDir = '/home/user/scripts/my-npx-wrapper/bin';
const realNpxDir = '/home/user/.npm/_npx/abc/node_modules/.bin';
const result = filterNpxFromPath(
[npxLikeUserDir, realNpxDir].join(path.delimiter),
);
const segments = result.split(path.delimiter);
assert.ok(
segments.includes(npxLikeUserDir),
'must not strip user dirs that merely contain "npx" as a substring',
);
assert.ok(!segments.includes(realNpxDir), 'must strip real _npx dirs');
});
});
// ---------------------------------------------------------------------------
// Bug 2: stale legacy symlink pointing at gsd-tools.cjs (deprecated binary)
// ---------------------------------------------------------------------------
describe('bug #3231: stale legacy symlink to deprecated gsd-tools.cjs',
{ skip: isWindows ? 'POSIX-only: relies on fs.symlinkSync + mode bits + bare shim filename' : false },
() => {
let tmpRoot;
let sdkDir;
let savedEnv;
beforeEach(() => {
tmpRoot = fs.mkdtempSync(path.join(os.tmpdir(), 'gsd-3231-b-'));
sdkDir = makeSdkDir(tmpRoot);
const homeDir = path.join(tmpRoot, 'home');
fs.mkdirSync(homeDir, { recursive: true });
savedEnv = {
PATH: process.env.PATH,
HOME: process.env.HOME,
SHELL: process.env.SHELL,
};
process.env.HOME = homeDir;
delete process.env.SHELL;
});
afterEach(() => {
if (savedEnv.PATH == null) delete process.env.PATH;
else process.env.PATH = savedEnv.PATH;
if (savedEnv.HOME == null) delete process.env.HOME;
else process.env.HOME = savedEnv.HOME;
if (savedEnv.SHELL == null) delete process.env.SHELL;
else process.env.SHELL = savedEnv.SHELL;
try { fs.rmSync(tmpRoot, { recursive: true, force: true }); } catch {}
});
test('isLegacyGsdSdkShim detects the deprecated gsd-tools.cjs marker', () => {
// The legacy binary starts with or contains the @deprecated marker
// referencing gsd-tools.cjs in the first 512 bytes.
assert.equal(typeof isLegacyGsdSdkShim, 'function', 'isLegacyGsdSdkShim must be exported');
const legacyFile = path.join(tmpRoot, 'gsd-sdk-legacy');
fs.writeFileSync(
legacyFile,
[
'#!/usr/bin/env node',
'// @deprecated — use gsd-tools.cjs directly',
"require('/usr/local/lib/gsd-tools.cjs');",
'',
].join('\n'),
);
assert.equal(isLegacyGsdSdkShim(legacyFile), true, 'must detect legacy marker');
});
test('isLegacyGsdSdkShim returns false for a modern SDK shim', () => {
assert.equal(typeof isLegacyGsdSdkShim, 'function');
const modernFile = path.join(tmpRoot, 'gsd-sdk-modern');
fs.writeFileSync(
modernFile,
[
'#!/usr/bin/env node',
"require('/usr/local/lib/node_modules/@opengsd/get-shit-done-redux/bin/gsd-sdk.js');",
'',
].join('\n'),
);
assert.equal(isLegacyGsdSdkShim(modernFile), false, 'must not flag modern shims as legacy');
});
test('isLegacyGsdSdkShim returns false for a non-existent file', () => {
assert.equal(typeof isLegacyGsdSdkShim, 'function');
const missing = path.join(tmpRoot, 'does-not-exist');
assert.equal(isLegacyGsdSdkShim(missing), false, 'missing file is not a legacy shim');
});
test('installer replaces a stale legacy symlink and attempts self-link with modern SDK', () => {
// Set up: persistent PATH dir exists and contains a gsd-sdk symlink
// pointing at a fake "legacy" gsd-tools.cjs binary with the @deprecated
// marker. The installer must detect this, treat it as "not the right SDK",
// and replace it with a modern shim.
const persistentBin = path.join(tmpRoot, 'localbin');
fs.mkdirSync(persistentBin, { recursive: true });
// Write a fake legacy binary
const legacyBin = path.join(tmpRoot, 'gsd-tools.cjs');
fs.writeFileSync(
legacyBin,
[
'#!/usr/bin/env node',
'// @deprecated — use gsd-tools.cjs directly',
"console.log('legacy');",
'',
].join('\n'),
{ mode: 0o755 },
);
// Place a gsd-sdk symlink in the persistent dir pointing at the legacy binary.
const legacyShimPath = path.join(persistentBin, 'gsd-sdk');
try {
fs.symlinkSync(legacyBin, legacyShimPath);
} catch {
// On Windows or symlink-hostile FS, write a file that mimics the legacy content
fs.writeFileSync(
legacyShimPath,
[
'#!/usr/bin/env node',
'// @deprecated — use gsd-tools.cjs directly',
"console.log('legacy');",
'',
].join('\n'),
{ mode: 0o755 },
);
}
process.env.PATH = persistentBin;
const { stdout, stderr } = captureConsole(() => {
installSdkIfNeeded({ sdkDir });
});
const combined = `${stdout}\n${stderr}`;
// After replacement the installer should succeed; if replacement fails (e.g.
// because the link dir is truly persistent), it must at minimum NOT report
// "GSD SDK ready" with the legacy binary still in place — it must warn.
const shimWasReplaced = !isLegacyGsdSdkShim(legacyShimPath);
if (shimWasReplaced) {
// Self-link succeeded: the shim is modern, so the installer must have
// reported readiness.
assert.ok(
stdout.length > 0,
'installer must emit output after successful self-link',
);
} else {
// Self-link failed or was skipped: the installer must NOT have falsely
// reported "GSD SDK ready" while the legacy binary is still in place.
assert.ok(
!/GSD SDK ready/.test(combined),
'installer must NOT report ready while the legacy shim is still in place',
);
// It must also have emitted a diagnostic (not silently swallowed).
assert.ok(
stdout.length > 0,
'when self-link is skipped, installer should emit a PATH diagnostic',
);
}
});
});
// ---------------------------------------------------------------------------
// Test 3: clean install with gsd-sdk self-linked into a persistent PATH dir
// ---------------------------------------------------------------------------
describe('bug #3231: clean install — gsd-sdk self-linked into persistent PATH dir',
{ skip: isWindows ? 'POSIX-only: asserts bare gsd-sdk shim in ~/.local/bin' : false },
() => {
let tmpRoot;
let sdkDir;
let savedEnv;
beforeEach(() => {
tmpRoot = fs.mkdtempSync(path.join(os.tmpdir(), 'gsd-3231-c-'));
sdkDir = makeSdkDir(tmpRoot);
const homeDir = path.join(tmpRoot, 'home');
fs.mkdirSync(homeDir, { recursive: true });
savedEnv = {
PATH: process.env.PATH,
HOME: process.env.HOME,
SHELL: process.env.SHELL,
};
process.env.HOME = homeDir;
delete process.env.SHELL;
});
afterEach(() => {
if (savedEnv.PATH == null) delete process.env.PATH;
else process.env.PATH = savedEnv.PATH;
if (savedEnv.HOME == null) delete process.env.HOME;
else process.env.HOME = savedEnv.HOME;
if (savedEnv.SHELL == null) delete process.env.SHELL;
else process.env.SHELL = savedEnv.SHELL;
try { fs.rmSync(tmpRoot, { recursive: true, force: true }); } catch {}
});
test('prints "GSD SDK ready" when gsd-sdk is self-linked into a persistent dir on PATH', () => {
const homeDir = process.env.HOME;
const localBin = path.join(homeDir, '.local', 'bin');
fs.mkdirSync(localBin, { recursive: true });
// PATH contains only the persistent localBin (no npx dirs)
process.env.PATH = localBin;
const { stdout, stderr } = captureConsole(() => {
installSdkIfNeeded({ sdkDir });
});
const combined = `${stdout}\n${stderr}`;
const shimPath = path.join(localBin, 'gsd-sdk');
// Behavioral assertions: shim exists and is recognized as a modern (non-legacy) shim
// reachable from the persistent filtered PATH.
assert.ok(
fs.existsSync(shimPath),
'installer must materialize gsd-sdk shim in the persistent PATH dir',
);
assert.equal(
isGsdSdkOnPath(filterNpxFromPath(localBin)),
true,
'installer must make gsd-sdk reachable on the persistent filtered PATH',
);
// Primary behavioral assertion: the installer MUST print "GSD SDK ready"
// after successfully self-linking into a persistent PATH dir. This is the
// positive counterpart to the bug #3231 fix — we confirm the success path
// works correctly, not just that the false-positive path is blocked.
assert.ok(
/GSD SDK ready/.test(stdout),
'installer must print "GSD SDK ready" after a successful self-link into a persistent PATH dir. Got stdout: ' + stdout,
);
});
});

View File

@@ -14,7 +14,7 @@
* 1. model-catalog.cjs must use a resolve-chain that checks a co-located
* path first (bin/shared/model-catalog.json) before the legacy
* source-repo path.
* 2. bin/install.js must copy sdk/shared/model-catalog.json into
* 2. bin/install.js must copy shared model-catalog.json into
* get-shit-done/bin/shared/model-catalog.json (co-located inside the
* get-shit-done/ payload).
*
@@ -33,7 +33,7 @@ const os = require('node:os');
const REPO_ROOT = path.join(__dirname, '..');
const MODEL_CATALOG_CJS = path.join(REPO_ROOT, 'get-shit-done', 'bin', 'lib', 'model-catalog.cjs');
const MODEL_CATALOG_JSON = path.join(REPO_ROOT, 'sdk', 'shared', 'model-catalog.json');
const MODEL_CATALOG_JSON = path.join(REPO_ROOT, 'get-shit-done', 'bin', 'shared', 'model-catalog.json');
const { install } = require('../bin/install.js');

View File

@@ -9,7 +9,7 @@
* model_profile UI shows 4 options, schema has 5 — `adaptive` missing from
* `settings.md` AskUserQuestion.
*
* The schema (sdk/shared/model-catalog.json `profiles` array) defines 5 valid
* The schema (get-shit-done/bin/shared/model-catalog.json `profiles` array) defines 5 valid
* model_profile values: quality, balanced, budget, adaptive, inherit. The
* settings.md AskUserQuestion block for model_profile originally listed only 4
* options (Quality, Balanced, Budget, Inherit) — `adaptive` was missing.
@@ -29,7 +29,7 @@ const path = require('node:path');
const REPO_ROOT = path.join(__dirname, '..');
const SETTINGS_PATH = path.join(REPO_ROOT, 'get-shit-done', 'workflows', 'settings.md');
const CATALOG_PATH = path.join(REPO_ROOT, 'sdk', 'shared', 'model-catalog.json');
const CATALOG_PATH = path.join(REPO_ROOT, 'get-shit-done', 'bin', 'shared', 'model-catalog.json');
/**
* Collect every label: "..." value within a text block, lowercased.
@@ -62,7 +62,7 @@ describe('issue #33: model_profile schema and settings.md UI are in sync', () =>
test('schema includes the adaptive model_profile value', () => {
assert.ok(
Array.isArray(catalog.profiles),
'sdk/shared/model-catalog.json must have a "profiles" array'
'model-catalog.json must have a "profiles" array'
);
assert.ok(
catalog.profiles.includes('adaptive'),
@@ -73,7 +73,7 @@ describe('issue #33: model_profile schema and settings.md UI are in sync', () =>
test('schema includes adaptive as a model_profile value', () => {
assert.ok(
catalog.profiles.includes('adaptive'),
'"adaptive" must be in sdk/shared/model-catalog.json profiles. Got: [' + catalog.profiles.join(', ') + ']'
'"adaptive" must be in model-catalog.json profiles. Got: [' + catalog.profiles.join(', ') + ']'
);
});

View File

@@ -1,146 +0,0 @@
/**
* Regression test for bug #3359.
*
* `npx @opengsd/get-shit-done-redux@latest` can refresh runtime files while an older
* global `gsd-sdk` earlier on PATH remains the executable workflows call.
* The installer must not report SDK readiness when the resolved `gsd-sdk`
* version differs from the package/runtime version being installed.
*/
'use strict';
process.env.GSD_TEST_MODE = '1';
const { describe, test, beforeEach, afterEach } = require('node:test');
const assert = require('node:assert/strict');
const fs = require('fs');
const path = require('path');
const { installSdkIfNeeded, readGsdSdkVersion } = require('../bin/install.js');
const cp = require('node:child_process');
const pkg = require('../package.json');
const { createTempDir, cleanup, captureConsole } = require('./helpers.cjs');
const isWindows = process.platform === 'win32';
describe('bug #3359: installer detects stale gsd-sdk earlier on PATH',
{ skip: isWindows ? 'POSIX-only: stages bare gsd-sdk shebang shims in a PATH dir; Windows uses .cmd + PATHEXT resolution' : false },
() => {
let tmpRoot;
let sdkDir;
let pathDir;
let homeDir;
let savedEnv;
beforeEach(() => {
tmpRoot = createTempDir('gsd-3359-');
sdkDir = path.join(tmpRoot, 'sdk');
pathDir = path.join(tmpRoot, 'global-bin');
homeDir = path.join(tmpRoot, 'home');
fs.mkdirSync(path.join(sdkDir, 'dist'), { recursive: true });
fs.writeFileSync(
path.join(sdkDir, 'dist', 'cli.js'),
'#!/usr/bin/env node\nconsole.log("sdk cli");\n',
{ mode: 0o755 },
);
fs.mkdirSync(pathDir, { recursive: true });
fs.mkdirSync(homeDir, { recursive: true });
savedEnv = {
PATH: process.env.PATH,
HOME: process.env.HOME,
SHELL: process.env.SHELL,
};
process.env.PATH = pathDir;
process.env.HOME = homeDir;
delete process.env.SHELL;
});
afterEach(() => {
if (savedEnv.PATH == null) delete process.env.PATH;
else process.env.PATH = savedEnv.PATH;
if (savedEnv.HOME == null) delete process.env.HOME;
else process.env.HOME = savedEnv.HOME;
if (savedEnv.SHELL == null) delete process.env.SHELL;
else process.env.SHELL = savedEnv.SHELL;
cleanup(tmpRoot);
});
test('does not print ready when resolved gsd-sdk version differs from installer package version', () => {
const staleSdk = path.join(pathDir, 'gsd-sdk');
fs.writeFileSync(
staleSdk,
'#!/bin/sh\nprintf "%s\\n" "gsd-sdk v0.0.1"\n',
{ mode: 0o755 },
);
const { stdout, stderr } = captureConsole(() => {
installSdkIfNeeded({ sdkDir });
});
const combined = `${stdout}\n${stderr}`;
assert.ok(
/version mismatch|different version|stale/i.test(combined),
`installer must warn that resolved gsd-sdk is stale. Output:\n${combined}`,
);
assert.ok(
combined.includes(staleSdk),
`warning must include resolved gsd-sdk path. Output:\n${combined}`,
);
assert.ok(
combined.includes('0.0.1') && combined.includes(pkg.version),
`warning must include detected and installer versions. Output:\n${combined}`,
);
assert.ok(
/npm install -g @opengsd\/get-shit-done-redux@latest/.test(combined),
`warning must include global update remediation. Output:\n${combined}`,
);
assert.ok(
!/GSD SDK ready/.test(combined),
`installer must not report ready while PATH resolves a stale gsd-sdk. Output:\n${combined}`,
);
});
test('prints ready when no stale gsd-sdk is on PATH', () => {
const currentSdk = path.join(pathDir, 'gsd-sdk');
fs.writeFileSync(
currentSdk,
`#!/bin/sh\nprintf "%s\\n" "gsd-sdk v${pkg.version}"\n`,
{ mode: 0o755 },
);
const { stdout, stderr } = captureConsole(() => {
installSdkIfNeeded({ sdkDir });
});
const combined = `${stdout}\n${stderr}`;
assert.ok(
/GSD SDK ready/.test(combined),
`installer must report ready when no stale gsd-sdk exists. Output:\n${combined}`,
);
});
test('reads Windows cmd shim versions through cmd.exe', () => {
const originalSpawnSync = cp.spawnSync;
const platformDescriptor = Object.getOwnPropertyDescriptor(process, 'platform');
const calls = [];
cp.spawnSync = (command, args, options) => {
calls.push({ command, args, options });
return { status: 0, stdout: `gsd-sdk v${pkg.version}\n`, stderr: '' };
};
Object.defineProperty(process, 'platform', { value: 'win32' });
try {
assert.equal(readGsdSdkVersion('C:\\tools\\gsd-sdk.cmd'), pkg.version);
} finally {
cp.spawnSync = originalSpawnSync;
Object.defineProperty(process, 'platform', platformDescriptor);
}
assert.deepEqual(calls.map(({ command, args }) => ({ command, args })), [{
command: 'cmd.exe',
args: ['/c', 'C:\\tools\\gsd-sdk.cmd', '--version'],
}]);
assert.equal(calls[0].options.encoding, 'utf8');
assert.equal(calls[0].options.timeout, 2000);
});
});

View File

@@ -1,169 +0,0 @@
'use strict';
/**
* Regression tests for #3406 — stale globally-installed `@opengsd/gsd-sdk@0.1.0`
* shadows the `gsd-sdk` shim that `get-shit-done-redux` installs. The standalone
* 0.1.0 binary only knows `run | auto | init` (no `query` subcommand), so
* every workflow that calls `gsd-sdk query <command>` fails until the user
* runs `npm uninstall -g @opengsd/gsd-sdk`.
*
* Maintainer decision (per triage): option 2 — detect-and-warn during
* install. This test pins the pure detection helper so the install-time
* warning fires on the right input and stays silent otherwise.
*
* Test surface is the exported helper `detectStaleStandaloneSdk(runNpmLs)`.
* `runNpmLs` is an injected executor: in production it spawns
* `npm ls -g @opengsd/gsd-sdk --json --depth=0`; in tests we hand it a stub
* that returns canned stdout / throws, so the test never touches the host
* npm state.
*/
const { test, describe } = require('node:test');
const assert = require('node:assert/strict');
process.env.GSD_TEST_MODE = '1';
const installer = require('../bin/install.js');
const { detectStaleStandaloneSdk } = installer;
describe('#3406: detectStaleStandaloneSdk', () => {
test('is exported from bin/install.js under GSD_TEST_MODE', () => {
assert.strictEqual(
typeof detectStaleStandaloneSdk,
'function',
'detectStaleStandaloneSdk must be exported for install-time wiring + tests'
);
});
test('returns { stale: false } when npm ls reports the package is not installed', () => {
// `npm ls -g @opengsd/gsd-sdk --json --depth=0` exit code 1 with this
// JSON shape is the standard "not present" signal.
const stub = () => JSON.stringify({
name: 'lib',
dependencies: {},
});
const result = detectStaleStandaloneSdk(stub);
assert.deepStrictEqual(result, { stale: false });
});
test('returns { stale: true, version, path? } when @opengsd/gsd-sdk is present', () => {
const stub = () => JSON.stringify({
name: 'lib',
dependencies: {
'@opengsd/gsd-sdk': {
version: '0.1.0',
resolved: 'file:/Users/REDACTED/.nvm/versions/node/v24.15.0/lib/node_modules/@opengsd/gsd-sdk',
},
},
});
const result = detectStaleStandaloneSdk(stub);
assert.strictEqual(result.stale, true);
assert.strictEqual(result.version, '0.1.0');
});
test('returns { stale: false } when runNpmLs throws (npm missing / EACCES)', () => {
const stub = () => { throw new Error('npm: command not found'); };
const result = detectStaleStandaloneSdk(stub);
assert.deepStrictEqual(result, { stale: false });
});
test('returns { stale: false } when runNpmLs returns malformed JSON', () => {
const stub = () => 'not-json-at-all';
const result = detectStaleStandaloneSdk(stub);
assert.deepStrictEqual(result, { stale: false });
});
test('returns { stale: false } when the JSON has no dependencies field', () => {
const stub = () => JSON.stringify({ name: 'lib' });
const result = detectStaleStandaloneSdk(stub);
assert.deepStrictEqual(result, { stale: false });
});
test('returns { stale: false } when runNpmLs returns null/undefined', () => {
const resultNull = detectStaleStandaloneSdk(() => null);
const resultUndef = detectStaleStandaloneSdk(() => undefined);
assert.deepStrictEqual(resultNull, { stale: false });
assert.deepStrictEqual(resultUndef, { stale: false });
});
test('returns { stale: false } for non-0.1.0 versions (CR #3406)', () => {
// Only 0.1.0 is the known-bad shadow. Any newer or unrelated published
// version is an intentional install (or a future republish) and must
// NOT be flagged. Without this gate, every maintainer with a local-link
// or any future publish would trigger a misleading warning on install.
const stubNewer = () => JSON.stringify({ dependencies: { '@opengsd/gsd-sdk': { version: '1.50.0-canary.0' } } });
const stubFuture = () => JSON.stringify({ dependencies: { '@opengsd/gsd-sdk': { version: '2.0.0' } } });
assert.deepStrictEqual(detectStaleStandaloneSdk(stubNewer), { stale: false });
assert.deepStrictEqual(detectStaleStandaloneSdk(stubFuture), { stale: false });
});
});
describe('#3406: install-time wiring stays silent when no stale package is found', () => {
// We can't easily stub npm inside a spawned install subprocess without
// shelling around it, so the install-side coverage here verifies the
// negative case: when @opengsd/gsd-sdk is NOT installed globally (the npm
// dependency tree on CI is irrelevant — we use a doctored PATH that points
// npm at an empty prefix), the install run prints NO #3406 warning. The
// positive case is exhaustively covered by detectStaleStandaloneSdk above.
const path = require('node:path');
const fs = require('node:fs');
const os = require('node:os');
const { execFileSync } = require('node:child_process');
test('install does not emit the stale-SDK warning on a clean npm prefix', () => {
const installScript = path.resolve(__dirname, '..', 'bin', 'install.js');
const tmpHome = fs.mkdtempSync(path.join(os.tmpdir(), 'gsd-3406-home-'));
const tmpPrefix = fs.mkdtempSync(path.join(os.tmpdir(), 'gsd-3406-npm-'));
try {
const stdout = execFileSync(
process.execPath,
[installScript, '--claude', '--global', '--yes', '--no-sdk'],
{
encoding: 'utf-8',
stdio: ['ignore', 'pipe', 'pipe'],
env: {
...process.env,
CLAUDE_CONFIG_DIR: tmpHome,
npm_config_prefix: tmpPrefix,
// Detect-and-warn must execute, just find nothing — so do NOT set
// GSD_SKIP_STALE_SDK_CHECK here.
},
timeout: 60_000,
}
);
assert.ok(
!stdout.includes('@opengsd/gsd-sdk'),
'install output must not mention @opengsd/gsd-sdk when the package is absent'
);
assert.ok(
!stdout.includes('#3406'),
'install output must not reference #3406 when no stale shadow is present'
);
} finally {
try { fs.rmSync(tmpHome, { recursive: true, force: true }); } catch { /* ignore */ }
try { fs.rmSync(tmpPrefix, { recursive: true, force: true }); } catch { /* ignore */ }
}
});
});
describe('#3406: formatStaleStandaloneSdkWarning', () => {
const { formatStaleStandaloneSdkWarning } = installer;
test('is exported from bin/install.js under GSD_TEST_MODE', () => {
assert.strictEqual(
typeof formatStaleStandaloneSdkWarning,
'function',
'formatStaleStandaloneSdkWarning must be exported for tests'
);
});
test('message names the stale package, the version, and the uninstall command', () => {
const out = formatStaleStandaloneSdkWarning({ stale: true, version: '0.1.0' });
assert.ok(out.includes('@opengsd/gsd-sdk'), 'must name the shadowing package');
assert.ok(out.includes('0.1.0'), 'must show the stale version');
assert.ok(
out.includes('npm uninstall -g @opengsd/gsd-sdk'),
'must include the remediation command verbatim'
);
assert.ok(out.includes('#3406'), 'must reference the issue for traceability');
});
});

View File

@@ -16,7 +16,7 @@ const path = require('node:path');
const REPO_ROOT = path.join(__dirname, '..');
const CONFIGURATION_CJS = path.join(REPO_ROOT, 'get-shit-done', 'bin', 'lib', 'configuration.cjs');
const SDK_SHARED_DIR = path.join(REPO_ROOT, 'sdk', 'shared');
const SHARED_DIR = path.join(REPO_ROOT, 'get-shit-done', 'bin', 'shared');
const { install } = require('../bin/install.js');
@@ -78,11 +78,11 @@ describe('bug #3571: configuration generated manifests resolve in install layout
const installedCjs = path.join(gsdLibDir, 'configuration.cjs');
fs.copyFileSync(CONFIGURATION_CJS, installedCjs);
fs.copyFileSync(
path.join(SDK_SHARED_DIR, 'config-defaults.manifest.json'),
path.join(SHARED_DIR, 'config-defaults.manifest.json'),
path.join(gsdSharedDir, 'config-defaults.manifest.json')
);
fs.copyFileSync(
path.join(SDK_SHARED_DIR, 'config-schema.manifest.json'),
path.join(SHARED_DIR, 'config-schema.manifest.json'),
path.join(gsdSharedDir, 'config-schema.manifest.json')
);

View File

@@ -1,476 +0,0 @@
// allow-test-rule: reads workflow .md files (product content, not source .cjs) to assert structural invariants — file-presence check is the only viable IR for markdown guard patterns
/**
* Regression test for #3668: --local install has soft dependency on global gsd-sdk
*
* Two defects confirmed by code inspection:
*
* Defect 1 — `buildGsdSdkVersionMismatchReport` emits `npm install -g get-shit-done-cc@latest`
* unconditionally, even when the caller is a local install. For local installs the
* correct remediation is to run `/gsd:update` (or `npx get-shit-done-cc@latest --local`),
* not to install globally.
*
* Defect 2 — 69 of 72 workflow files that call `gsd-sdk query …` do so without a
* `[ -f "$GSD_TOOLS" ] … elif command -v gsd-sdk` fallback, so uninstalling the
* global `gsd-sdk` breaks every workflow on a fresh local session.
*
* Defect 3 — No CI guard prevents future workflow regressions.
*
* Acceptance criteria (from confirmed-bug triage comment):
* - `renderGsdSdkVersionMismatchReport` does NOT emit `npm install -g` for isLocal=true.
* - All SDK-invoking workflow files (recursively) use the local-first guard pattern.
* - A CI guard (Defect 3) blocks any future workflow file from invoking bare `gsd-sdk`
* without a resolution guard. The guard also catches untyped fences, not just bash/sh.
*/
'use strict';
process.env.GSD_TEST_MODE = '1';
const { describe, test } = require('node:test');
const assert = require('node:assert/strict');
const fs = require('fs');
const path = require('path');
const { buildGsdSdkVersionMismatchReport, renderGsdSdkVersionMismatchReport } = require('../bin/install.js');
const { captureConsole } = require('./helpers.cjs');
const WORKFLOWS_DIR = path.join(__dirname, '..', 'get-shit-done', 'workflows');
/**
* Find all .md files under a directory (recursively).
*/
function findMdFiles(dir) {
const results = [];
for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
const fullPath = path.join(dir, entry.name);
if (entry.isDirectory()) results.push(...findMdFiles(fullPath));
else if (entry.isFile() && entry.name.endsWith('.md')) results.push(fullPath);
}
return results;
}
// ---------------------------------------------------------------------------
// Defect 1: version-mismatch report should not suggest `npm install -g` for
// local installs.
// ---------------------------------------------------------------------------
describe('#3668 Defect 1: version-mismatch report respects isLocal', () => {
test('buildGsdSdkVersionMismatchReport accepts isLocal=true and sets local fix_command', () => {
// Simulate a version mismatch report built for a local install.
const ir = buildGsdSdkVersionMismatchReport('/fake/path/gsd-sdk', '1.42.0', { isLocal: true });
// Without a real gsd-sdk binary the function may return null — that's fine,
// the important contract is: when it DOES return a report for isLocal=true,
// the fix_command must NOT be the global install command.
if (ir === null) return; // no mismatch detected (no real binary) — skip assertion
assert.ok(
!ir.fix_command.includes('npm install -g'),
[
'buildGsdSdkVersionMismatchReport with isLocal=true must NOT produce',
'`npm install -g …` as the fix_command — local installs should be told',
`to run /gsd:update instead. Got: ${ir.fix_command}`,
].join(' '),
);
});
test('renderGsdSdkVersionMismatchReport does not print npm install -g when isLocal=true', () => {
// Construct an IR that represents a local-install mismatch (what the
// fixed buildGsdSdkVersionMismatchReport must produce for isLocal=true).
const localIr = {
ok: false,
reason: 'gsd_sdk_version_mismatch',
sdk_path: '/fake/path/gsd-sdk',
actual_version: '1.41.0',
expected_version: '1.42.0',
fix_command: 'npx get-shit-done-cc@latest --claude --local',
is_local: true,
};
const { stdout } = captureConsole(() => {
renderGsdSdkVersionMismatchReport(localIr);
});
assert.ok(
!stdout.includes('npm install -g'),
[
'renderGsdSdkVersionMismatchReport must not emit `npm install -g` when',
`is_local=true. Stdout:\n${stdout}`,
].join(' '),
);
assert.ok(
stdout.includes(localIr.fix_command),
[
'renderGsdSdkVersionMismatchReport must print the fix_command from the IR.',
`Expected to find: ${localIr.fix_command}`,
`Stdout:\n${stdout}`,
].join('\n'),
);
});
test('buildGsdSdkVersionMismatchReport with isLocal=false still uses global fix_command', () => {
// Verifies the global install path is unchanged (regression guard).
const ir = buildGsdSdkVersionMismatchReport('/fake/path/gsd-sdk', '1.42.0', { isLocal: false });
if (ir === null) return; // no real binary available — skip
assert.ok(
ir.fix_command.includes('npm install -g'),
[
'buildGsdSdkVersionMismatchReport with isLocal=false must keep',
`\`npm install -g …\` as the fix_command. Got: ${ir.fix_command}`,
].join(' '),
);
});
});
// ---------------------------------------------------------------------------
// Shared helpers: structural markdown parsing (used by Defect 2, Defect 3,
// and the integration test below).
// ---------------------------------------------------------------------------
/**
* Parse a markdown string into segments.
* Returns an array of { type: 'prose' | 'bash-fence' | 'other-fence', content: string }.
*/
function parseMarkdownSegments(content) {
const segments = [];
const lines = content.split('\n');
let i = 0;
while (i < lines.length) {
const line = lines[i];
const fenceMatch = line.match(/^```(bash|sh|[a-zA-Z0-9_-]*)(\s*)$/);
if (fenceMatch) {
const lang = fenceMatch[1].toLowerCase();
const fenceLines = [line];
i++;
while (i < lines.length && !lines[i].match(/^```\s*$/)) {
fenceLines.push(lines[i]);
i++;
}
if (i < lines.length) {
fenceLines.push(lines[i]);
i++;
}
// Treat untyped fences (lang === '') as bash-fence: they frequently contain
// shell commands (e.g. verify-work.md:118) and must be checked for bare
// gsd-sdk invocations (#3668 F7).
const isBash = lang === 'bash' || lang === 'sh' || lang === '';
segments.push({ type: isBash ? 'bash-fence' : 'other-fence', content: fenceLines.join('\n') });
} else {
const proseLines = [line];
i++;
while (i < lines.length && !lines[i].match(/^```/)) {
proseLines.push(lines[i]);
i++;
}
segments.push({ type: 'prose', content: proseLines.join('\n') });
}
}
return segments;
}
/**
* Determine if a line invokes `gsd-sdk` as a bare command (not via $GSD_SDK).
*
* Returns true for invocation lines like:
* INIT=$(gsd-sdk query ...)
* gsd-sdk query commit ...
*
* Returns false for:
* # comment lines
* - [ ] checklist/bullet lines
* GSD_SDK="gsd-sdk" (assignment inside the resolution guard)
* command -v gsd-sdk (availability check, not an invocation)
* echo "...gsd-sdk..." (error message string)
* $GSD_SDK query ... (already routed through the variable)
*/
function isBareGsdSdkInvocation(line) {
const trimmed = line.trimStart();
// Comment lines
if (trimmed.startsWith('#')) return false;
// Bullet/checklist lines (prose in a bash block)
if (/^[-*]\s/.test(trimmed)) return false;
// Availability check — not an invocation
if (trimmed.includes('command -v gsd-sdk')) return false;
// Assignment inside the guard: GSD_SDK="gsd-sdk"
if (/^\s*GSD_SDK\s*=/.test(line)) return false;
// echo/print lines containing gsd-sdk as a string in an error message
if (/^\s*(echo|printf)\s/.test(trimmed)) return false;
// Match bare gsd-sdk as an executable token (not preceded by $)
return /(?<!\$)\bgsd-sdk\b/.test(line);
}
/**
* Return true if the file has any bash-fence content that invokes gsd-sdk
* (i.e., the file actually EXECUTES gsd-sdk, not just mentions it in prose).
* Used by Defect 2 to skip files where gsd-sdk only appears in documentation
* text or inline code spans (#3668 — e.g. discuss-phase/modes/text.md).
*/
function fileHasExecutableGsdSdkInvocation(content) {
const segments = parseMarkdownSegments(content);
return segments.some(
(seg) =>
seg.type === 'bash-fence' &&
seg.content.split('\n').some((line) => /(?<!\$)\bgsd-sdk\b/.test(line)),
);
}
// ---------------------------------------------------------------------------
// Defect 2: Every workflow file that calls `gsd-sdk` must use the
// local-first `[ -f "$GSD_TOOLS" ] … elif command -v gsd-sdk` guard pattern.
// Uses findMdFiles (recursive) to cover workflow subdirectories (#3668 F6).
// Uses bash-fence check (not raw content) to skip docs-only references (#3668).
// ---------------------------------------------------------------------------
describe('#3668 Defect 2: workflow files must guard every gsd-sdk invocation', () => {
test('every workflow file that calls gsd-sdk has a resolution guard', () => {
const allFiles = findMdFiles(WORKFLOWS_DIR);
const bare = [];
for (const filePath of allFiles) {
const content = fs.readFileSync(filePath, 'utf-8');
// Does this file *execute* gsd-sdk (in a bash fence), not just mention it?
if (!fileHasExecutableGsdSdkInvocation(content)) continue;
// Must have either a local-first guard (GSD_TOOLS check) or a command-v guard.
// Both patterns set $GSD_SDK so downstream callsites use $GSD_SDK.
if (!content.includes('GSD_TOOLS') && !content.includes('command -v gsd-sdk')) {
bare.push(path.relative(WORKFLOWS_DIR, filePath));
}
}
assert.strictEqual(
bare.length,
0,
[
`${bare.length} workflow file(s) call gsd-sdk without a resolution guard.`,
'Every workflow must use (local-first pattern — #3668):',
' GSD_TOOLS="$(git rev-parse --show-toplevel 2>/dev/null || pwd)/get-shit-done/bin/gsd-tools.cjs"',
' if [ -f "$GSD_TOOLS" ]; then',
' GSD_SDK="node $GSD_TOOLS"',
' elif command -v gsd-sdk >/dev/null 2>&1; then',
' GSD_SDK="gsd-sdk"',
' fi',
' RESULT=$($GSD_SDK query <key>) # use $GSD_SDK, never bare gsd-sdk',
'',
'Missing guard in:',
...bare.map((f) => ` - ${f}`),
].join('\n'),
);
});
});
// ---------------------------------------------------------------------------
// Defect 3: CI guard — callsite routing, not just guard presence.
//
// The original Defect 3 test only checked that `command -v gsd-sdk` appeared
// as a string in the file. That assertion passes even when the preflight block
// is present but every downstream callsite still uses the bare `gsd-sdk`
// command — which is exactly the state that caused the bug. This upgraded test
// parses shell fenced blocks structurally and verifies that no block outside
// a resolution guard invokes `gsd-sdk` as a bare command.
//
// allow-test-rule: structural markdown parse is the only viable IR for
// shell-routing invariants in LLM-consumed workflow files (#3668 architectural
// constraint — source files cannot expose a typed runtime surface).
// ---------------------------------------------------------------------------
describe('#3668 Defect 3 (upgraded): CI guard — every gsd-sdk callsite routes through $GSD_SDK', () => {
test('no shell block outside a resolution guard invokes bare gsd-sdk', () => {
// allow-test-rule: structural parse of markdown shell blocks to assert
// callsite routing — file-content parse is the only viable surface for
// LLM-consumed workflow markdown (#3668 architectural constraint).
const allFiles = findMdFiles(WORKFLOWS_DIR);
const violations = [];
for (const filePath of allFiles) {
const content = fs.readFileSync(filePath, 'utf-8');
if (!content.includes('gsd-sdk')) continue;
const segments = parseMarkdownSegments(content);
for (const seg of segments) {
if (seg.type !== 'bash-fence') continue;
// A block is a "resolution guard block" if it contains the command-v check.
// Within that block, the guard lines are left alone; callsites after the fi
// must use $GSD_SDK. However, some files use an inline guard (update.md)
// where each branch explicitly guards its own gsd-sdk call — also acceptable.
// We flag only blocks with NO command -v guard that contain bare invocations.
const blockHasGuard = seg.content.includes('command -v gsd-sdk');
if (blockHasGuard) continue; // guard block — handled by resolution logic
const blockLines = seg.content.split('\n');
for (const line of blockLines) {
if (isBareGsdSdkInvocation(line)) {
const rel = path.relative(WORKFLOWS_DIR, filePath);
violations.push(`${rel}: ${line.trim().slice(0, 80)}`);
}
}
}
}
assert.strictEqual(
violations.length,
0,
[
`CI GUARD FAIL (#3668): ${violations.length} bare gsd-sdk invocation(s) found`,
'in shell blocks that have no resolution guard.',
'All SDK calls must use $GSD_SDK (set by the preflight block — local-first):',
' GSD_TOOLS="$(git rev-parse --show-toplevel 2>/dev/null || pwd)/get-shit-done/bin/gsd-tools.cjs"',
' if [ -f "$GSD_TOOLS" ]; then',
' GSD_SDK="node $GSD_TOOLS"',
' elif command -v gsd-sdk >/dev/null 2>&1; then',
' GSD_SDK="gsd-sdk"',
' fi',
' RESULT=$($GSD_SDK query <key>) # <-- use $GSD_SDK, not bare gsd-sdk',
'',
'Violations:',
...violations.map((v) => ` ${v}`),
].join('\n'),
);
});
// Counter-test (Contract 6): verify the filter correctly identifies callsites
// and correctly excludes guard/preflight lines.
test('isBareGsdSdkInvocation correctly identifies callsite lines', () => {
// These must be flagged as bare invocations
const mustFlag = [
'INIT=$(gsd-sdk query init.milestone-op)',
'RESULT=$(gsd-sdk query phase.add "${description}")',
'gsd-sdk query commit "docs: add item" --files foo',
'ANALYZE=$(gsd-sdk query roadmap.analyze)',
];
for (const line of mustFlag) {
assert.ok(
isBareGsdSdkInvocation(line),
`Expected line to be flagged as bare invocation: ${line}`,
);
}
// These must NOT be flagged
const mustNotFlag = [
' GSD_SDK="gsd-sdk"', // assignment in guard
'if command -v gsd-sdk >/dev/null 2>&1; then', // availability check
' echo "ERROR: gsd-sdk not found" >&2', // error message
'# SDK resolution: prefer local gsd-sdk', // comment
'- [ ] `gsd-sdk query phase.add` executed', // checklist
'INIT=$($GSD_SDK query init.milestone-op)', // already using $GSD_SDK
];
for (const line of mustNotFlag) {
assert.ok(
!isBareGsdSdkInvocation(line),
`Expected line NOT to be flagged: ${line}`,
);
}
});
// F8: Propagation test — verify the Defect 3 guard would catch a regression
// if a new file with a bare gsd-sdk invocation in an unguarded block were added.
test('Defect 3 guard catches bare gsd-sdk in unguarded bash fence (regression canary)', () => {
// Construct synthetic markdown with a bare gsd-sdk invocation in an unguarded bash block.
const syntheticContent = [
'# Test file',
'',
'```bash',
'RESULT=$(gsd-sdk query phase.list)',
'```',
].join('\n');
const segments = parseMarkdownSegments(syntheticContent);
let caught = false;
for (const seg of segments) {
if (seg.type !== 'bash-fence') continue;
const blockHasGuard = seg.content.includes('command -v gsd-sdk');
if (blockHasGuard) continue;
for (const line of seg.content.split('\n')) {
if (isBareGsdSdkInvocation(line)) {
caught = true;
}
}
}
assert.ok(
caught,
'Defect 3 guard failed to catch bare gsd-sdk in an unguarded bash fence — regression detector is broken',
);
});
// F8 (untyped fence): also catches bare gsd-sdk in an untyped (no lang) fence.
test('Defect 3 guard catches bare gsd-sdk in untyped fence (verify-work.md pattern)', () => {
const syntheticContent = [
'# Test file',
'',
'```',
'UI_FLAG=$(gsd-sdk query config-get workflow.ui_phase --raw 2>/dev/null || echo "true")',
'```',
].join('\n');
const segments = parseMarkdownSegments(syntheticContent);
let caught = false;
for (const seg of segments) {
if (seg.type !== 'bash-fence') continue;
const blockHasGuard = seg.content.includes('command -v gsd-sdk');
if (blockHasGuard) continue;
for (const line of seg.content.split('\n')) {
if (isBareGsdSdkInvocation(line)) {
caught = true;
}
}
}
assert.ok(
caught,
'Defect 3 guard failed to catch bare gsd-sdk in an untyped fence — untyped fences must be treated as bash (#3668 F7)',
);
});
});
// ---------------------------------------------------------------------------
// Integration: local-only scenario — verify resolution order prefers local
//
// Structural test: with no global gsd-sdk on PATH, a --local install only has
// $GSD_TOOLS (gsd-tools.cjs). Every workflow must check for $GSD_TOOLS first
// so that local-only installs work without any global gsd-sdk (#3668 F9).
// ---------------------------------------------------------------------------
describe('#3668 Integration: local-only scenario — $GSD_TOOLS checked before command -v gsd-sdk', () => {
test('every workflow preflight block checks GSD_TOOLS file existence before global gsd-sdk', () => {
// allow-test-rule: structural parse of markdown shell blocks to assert
// local-first resolution order (#3668 F9 — prefer local over global).
const allFiles = findMdFiles(WORKFLOWS_DIR);
const wrongOrder = [];
for (const filePath of allFiles) {
const content = fs.readFileSync(filePath, 'utf-8');
if (!content.includes('GSD_TOOLS')) continue;
const segments = parseMarkdownSegments(content);
for (const seg of segments) {
if (seg.type !== 'bash-fence') continue;
if (!seg.content.includes('GSD_TOOLS') || !seg.content.includes('command -v gsd-sdk')) continue;
// This is a resolution block. The GSD_TOOLS file check must appear BEFORE
// the command -v gsd-sdk check.
const gtPos = seg.content.indexOf('[ -f "$GSD_TOOLS"');
const cvPos = seg.content.indexOf('command -v gsd-sdk');
if (gtPos === -1 || cvPos === -1) continue;
// One-liner style (discuss-phase.md): check the same way
if (gtPos > cvPos) {
const rel = path.relative(WORKFLOWS_DIR, filePath);
wrongOrder.push(`${rel}: local GSD_TOOLS check (pos ${gtPos}) comes after command -v gsd-sdk (pos ${cvPos})`);
}
}
}
assert.strictEqual(
wrongOrder.length,
0,
[
`${wrongOrder.length} workflow file(s) check global gsd-sdk BEFORE local GSD_TOOLS.`,
'Local-first resolution (#3668 F9): check [ -f "$GSD_TOOLS" ] first so that',
'--local-only installs (no global gsd-sdk) work without modification.',
'Pattern must be:',
' if [ -f "$GSD_TOOLS" ]; then',
' GSD_SDK="node $GSD_TOOLS" # local first',
' elif command -v gsd-sdk >/dev/null 2>&1; then',
' GSD_SDK="gsd-sdk" # global fallback',
' fi',
'',
'Violations (prefer-local order broken):',
...wrongOrder.map((v) => ` - ${v}`),
].join('\n'),
);
});
});

View File

@@ -1,175 +0,0 @@
'use strict';
/**
* Integration test for bug #3749 — behavioral verification of `commit` handler
* with `branching_strategy: phase`.
*
* Follows the pattern of tests/bug-2767-gsd-sdk-commit-files-flag.test.cjs.
* Builds on a real temp git repo, writes a phase directory, configures
* `branching_strategy: phase` with a `phase_branch_template`, invokes the SDK
* CLI for `gsd commit`, and asserts the resulting branch matches the resolved
* strategy-branch name.
*
* These tests are skipped when sdk/dist/cli.js is not built.
*/
const { describe, test, beforeEach, afterEach } = require('node:test');
const assert = require('node:assert/strict');
const fs = require('node:fs');
const path = require('node:path');
const { execFileSync } = require('node:child_process');
const { createTempGitProject, cleanup } = require('./helpers.cjs');
const REPO_ROOT = path.join(__dirname, '..');
const SDK_CLI = path.join(REPO_ROOT, 'sdk', 'dist', 'cli.js');
/**
* Run a git command in the given directory and return trimmed stdout.
*/
function git(projectDir, args) {
return execFileSync('git', args, { cwd: projectDir, encoding: 'utf-8' }).trim();
}
/**
* Invoke `gsd-sdk query <subcommand> <...args>` against a project dir.
* Returns { exitCode, stdout, stderr, json } where json is the parsed handler
* payload (the SDK prints a single JSON object to stdout for query handlers).
*/
function runSdkQuery(subcommand, args, projectDir) {
const argv = ['query', subcommand, ...args, '--project-dir', projectDir];
let stdout = '';
let stderr = '';
let exitCode = 0;
try {
stdout = execFileSync(process.execPath, [SDK_CLI, ...argv], {
encoding: 'utf-8',
stdio: ['pipe', 'pipe', 'pipe'],
env: { ...process.env, GSD_SESSION_KEY: '' },
});
} catch (err) {
exitCode = err.status ?? 1;
stdout = err.stdout?.toString() ?? '';
stderr = err.stderr?.toString() ?? '';
}
// Extract the trailing JSON object — the CLI may print status lines before it.
let json = null;
const lastBrace = stdout.lastIndexOf('{');
if (lastBrace >= 0) {
try { json = JSON.parse(stdout.slice(lastBrace).trim()); } catch { /* leave null */ }
if (!json) {
try { json = JSON.parse(stdout.trim()); } catch { /* leave null */ }
}
}
return { exitCode, stdout, stderr, json };
}
// ─── Integration: commit handler with branching_strategy: phase ──────────────
describe('bug #3749 (integration): gsd-sdk commit with branching_strategy: phase', () => {
let tmpDir;
beforeEach(() => {
tmpDir = createTempGitProject('gsd-3749-');
// Write a phase directory that parsePhasesFromFiles can detect.
const phaseDir = path.join(tmpDir, '.planning', 'phases', '1-setup');
fs.mkdirSync(phaseDir, { recursive: true });
fs.writeFileSync(path.join(phaseDir, 'STATE.md'), '# Phase 1 state\n');
// Write config with branching_strategy: phase and a phase_branch_template.
const config = {
git: {
branching_strategy: 'phase',
phase_branch_template: 'phase/{phase}-{slug}',
},
};
fs.writeFileSync(
path.join(tmpDir, '.planning', 'config.json'),
JSON.stringify(config, null, 2),
);
// Stage an initial commit so HEAD exists, then stage the new files.
execFileSync('git', ['-C', tmpDir, 'add', '-A'], { stdio: 'pipe' });
execFileSync('git', ['-C', tmpDir, 'commit', '--allow-empty', '-m', 'chore: add phase 1 scaffold'], { stdio: 'pipe' });
});
afterEach(() => {
cleanup(tmpDir);
});
test('commit with --files in a phase dir switches to the strategy branch', (t) => {
if (!fs.existsSync(SDK_CLI)) {
t.skip('sdk/dist/cli.js not built — run `cd sdk && npm run build` to enable this integration test');
return;
}
// Write a file inside the phase directory and stage it.
const phaseFile = path.join('.planning', 'phases', '1-setup', 'PLAN.md');
fs.writeFileSync(path.join(tmpDir, phaseFile), '# Plan\n');
execFileSync('git', ['-C', tmpDir, 'add', '--', phaseFile], { stdio: 'pipe' });
// Invoke the commit handler.
const result = runSdkQuery(
'commit',
['test(3749): strategy branch integration', '--files', phaseFile],
tmpDir,
);
assert.equal(result.exitCode, 0, `cli failed with stderr: ${result.stderr}`);
assert.ok(result.json, `expected JSON body in stdout, got:\n${result.stdout}`);
if (result.json.committed === false && result.json.reason === 'nothing staged') {
// The --files flag caused the handler to re-stage; if git add succeeded
// inside the handler the commit should have gone through. If the test
// helper's pre-stage was consumed we may get this — skip rather than fail.
t.skip('nothing staged after handler re-stage — skipping result assertions');
return;
}
assert.equal(result.json.committed, true, `commit failed: ${JSON.stringify(result.json)}`);
// The handler should have switched the branch before committing.
// The resolved branch name is phase/1-setup (template: phase/{phase}-{slug},
// phase_number=1, phase_slug=setup from the "1-setup" directory name).
const currentBranch = git(tmpDir, ['rev-parse', '--abbrev-ref', 'HEAD']);
assert.equal(
currentBranch,
'phase/1-setup',
`expected branch phase/1-setup after strategy switch, got: ${currentBranch}`,
);
});
test('commit with --files outside a phase dir skips branch switch', (t) => {
if (!fs.existsSync(SDK_CLI)) {
t.skip('sdk/dist/cli.js not built — run `cd sdk && npm run build` to enable this integration test');
return;
}
// Write a file outside any phase directory.
const rootFile = '.planning/PROJECT.md';
fs.writeFileSync(path.join(tmpDir, rootFile), '# Updated Project\n');
execFileSync('git', ['-C', tmpDir, 'add', '--', rootFile], { stdio: 'pipe' });
const branchBefore = git(tmpDir, ['rev-parse', '--abbrev-ref', 'HEAD']);
const result = runSdkQuery(
'commit',
['test(3749): no-strategy skip', '--files', rootFile],
tmpDir,
);
assert.equal(result.exitCode, 0, `cli failed: ${result.stderr}`);
assert.ok(result.json, `expected JSON body, got:\n${result.stdout}`);
if (result.json.committed === false && result.json.reason === 'nothing staged') {
t.skip('nothing staged after handler re-stage — skipping result assertions');
return;
}
assert.equal(result.json.committed, true, `expected committed: true, got: ${JSON.stringify(result.json)}`);
// Branch should be unchanged — no phase token found in the file path.
const branchAfter = git(tmpDir, ['rev-parse', '--abbrev-ref', 'HEAD']);
assert.equal(branchAfter, branchBefore, `branch should not have changed when --files has no phase token`);
});
});

View File

@@ -1,342 +0,0 @@
// allow-test-rule: structural-regression-guard
// Rationale: This file verifies SDK-seam structural contracts (export names,
// guard patterns, checkout idioms) that cannot be exercised behaviorally
// without a live git repo + multi-process harness. The behavioral tests
// (runHelper + parsePhasesFromFiles/validateBranchTemplate/resolveStrategyBranchName)
// cover the majority of code paths; this residual structural block guards
// the wiring points that span TS/CJS parity (#1278, PR #1279).
'use strict';
/**
* Regression test for bug #3749
*
* PR #1279 added strategy-branch creation logic to cmdCommit() in
* get-shit-done/bin/lib/commands.cjs (lines 285-320) so pre-execution
* workflows (discuss-phase, plan-phase, etc.) would create the configured
* phase/milestone branch before their first commit. That fix only landed in
* the CJS path; sdk/src/query/commit.ts — the live production path for
* `gsd-sdk query commit` — has zero branching logic.
*
* Post codex adversarial review (findings 1-4), this test file has been
* upgraded from structural source-includes assertions ("grep theater") to
* typed-IR unit tests against the pure helper functions exported from
* commit.ts. These helpers are compiled to CJS via ts-node and tested
* against controlled inputs/outputs — satisfying test-rigor Contract 1.
*
* Structural invariants that cannot be exercised without a full git repo are
* preserved in the `ensureStrategyBranch (structural)` describe block below.
*/
const { describe, test } = require('node:test');
const assert = require('node:assert/strict');
const fs = require('node:fs');
const path = require('node:path');
const { execFileSync } = require('node:child_process');
const COMMIT_TS = path.join(__dirname, '..', 'sdk', 'src', 'query', 'commit.ts');
const source = fs.readFileSync(COMMIT_TS, 'utf-8');
// ─── Load the typed-IR helpers via ts-node ────────────────────────────────
//
// We compile the three exported pure functions via ts-node so the tests run
// against the actual TypeScript source, not a stale dist/. If ts-node is
// not available we skip the typed-IR tests rather than fail the whole suite.
let parsePhasesFromFiles;
let validateBranchTemplate;
let resolveStrategyBranchName;
let helpersAvailable = false;
try {
const helperScript = `
const { parsePhasesFromFiles, validateBranchTemplate, resolveStrategyBranchName } =
require(${JSON.stringify(COMMIT_TS.replace(/\\/g, '/'))});
process.stdout.write(JSON.stringify({ ok: true }));
`;
// Quick smoke-check that ts-node can load the module
const tsNodeBin = path.join(__dirname, '..', 'node_modules', '.bin', 'ts-node');
const sdkDir = path.join(__dirname, '..', 'sdk');
execFileSync(tsNodeBin, ['--skip-project', '--transpile-only', '-e', helperScript], {
cwd: sdkDir,
stdio: ['ignore', 'pipe', 'pipe'],
timeout: 15000,
env: { ...process.env, TS_NODE_TRANSPILE_ONLY: '1' },
});
// ts-node is available — helpers are loaded per-test via runHelper() child processes
// that write JSON results back so we can test them hermetically.
helpersAvailable = true;
} catch {
// ts-node not available — typed-IR tests will be skipped
helpersAvailable = false;
}
/**
* Run a typed-IR helper via ts-node in a child process and return the JSON result.
* This avoids ESM/CJS module boundary issues in the test runner.
*/
function runHelper(helperName, argsJson) {
const tsNodeBin = path.join(__dirname, '..', 'node_modules', '.bin', 'ts-node');
const sdkDir = path.join(__dirname, '..', 'sdk');
const script = `
require('ts-node').register({
transpileOnly: true,
skipProject: true,
compilerOptions: { module: 'commonjs', esModuleInterop: true, resolveJsonModule: true },
});
const mod = require(${JSON.stringify(COMMIT_TS)});
const args = ${argsJson};
const result = mod[${JSON.stringify(helperName)}](...args);
if (result instanceof Set) {
process.stdout.write(JSON.stringify({ type: 'Set', values: [...result] }));
} else {
process.stdout.write(JSON.stringify(result));
}
`;
const out = execFileSync(tsNodeBin, ['--skip-project', '-e', script], {
cwd: sdkDir,
stdio: ['ignore', 'pipe', 'pipe'],
timeout: 15000,
env: { ...process.env, TS_NODE_TRANSPILE_ONLY: '1' },
});
return JSON.parse(out.toString());
}
// ─── Typed-IR: parsePhasesFromFiles ──────────────────────────────────────
describe('typed-IR: parsePhasesFromFiles(filePaths) — Finding 1', { skip: !helpersAvailable ? 'ts-node not available' : false }, () => {
test('empty array → empty Set', () => {
const result = runHelper('parsePhasesFromFiles', '[[]]');
assert.equal(result.type, 'Set');
assert.deepEqual(result.values, []);
});
test('paths with no phase segment → empty Set', () => {
const result = runHelper('parsePhasesFromFiles', '[["output-results.md", "README.md"]]');
assert.equal(result.type, 'Set');
assert.deepEqual(result.values, []);
});
test('single-phase paths → Set with one element', () => {
const result = runHelper('parsePhasesFromFiles', '[["1-setup/plan.md", "1-setup/state.md"]]');
assert.equal(result.type, 'Set');
assert.deepEqual(result.values.sort(), ['1']);
});
test('mixed-phase paths → Set with multiple elements', () => {
const result = runHelper('parsePhasesFromFiles', '[["1-setup/plan.md", "2-build/state.md"]]');
assert.equal(result.type, 'Set');
assert.deepEqual(result.values.sort(), ['1', '2']);
});
test('dotted phase numbers (e.g. 1.2) are captured', () => {
const result = runHelper('parsePhasesFromFiles', '[["1.2-feature/plan.md"]]');
assert.equal(result.type, 'Set');
assert.deepEqual(result.values, ['1.2']);
});
test('path with numeric filename prefix that is NOT a phase dir does NOT match', () => {
// e.g. root-level file "output-2-results.md" should not infer phase "2"
// because the convention is anchored to the START of a path segment
const result = runHelper('parsePhasesFromFiles', '[["output-2-results.md"]]');
// The file sits at root with no leading separator before "output" — should not match
// NB: depending on the regex, "output-2-results.md" may or may not produce "2".
// The important contract: phase dirs like "2-build" DO match. Root numeric
// tokens in filenames are ambiguous; this test documents current behavior.
assert.equal(result.type, 'Set');
// Accept either: no match (ideal) or a match (acceptable — documented behavior)
assert.ok(Array.isArray(result.values));
});
});
// ─── Typed-IR: validateBranchTemplate ────────────────────────────────────
describe('typed-IR: validateBranchTemplate(template) — Finding 3', { skip: !helpersAvailable ? 'ts-node not available' : false }, () => {
test('undefined template → ok: false', () => {
const result = runHelper('validateBranchTemplate', '[undefined]');
assert.equal(result.ok, false);
assert.ok(result.reason.includes('missing') || result.reason.includes('empty'));
});
test('empty string template → ok: false', () => {
const result = runHelper('validateBranchTemplate', '[""]');
assert.equal(result.ok, false);
});
test('whitespace-only template → ok: false', () => {
const result = runHelper('validateBranchTemplate', '[" "]');
assert.equal(result.ok, false);
});
test('valid template → ok: true', () => {
const result = runHelper('validateBranchTemplate', '["phase/{phase}-{slug}"]');
assert.equal(result.ok, true);
});
});
// ─── Typed-IR: resolveStrategyBranchName ─────────────────────────────────
describe('typed-IR: resolveStrategyBranchName(template, phaseNum, slug) — Finding 1 + 3', { skip: !helpersAvailable ? 'ts-node not available' : false }, () => {
test('well-formed template + phase + slug → ok: true with resolved branch', () => {
const result = runHelper('resolveStrategyBranchName', '["phase/{phase}-{slug}", "1", "setup"]');
assert.equal(result.ok, true);
assert.equal(result.branch, 'phase/1-setup');
});
test('template with unresolved placeholder → ok: false', () => {
// Template that still contains an unknown {token} after substitution.
// Note: {phase} and {milestone} are both replaced by firstToken (the function
// covers both phase and milestone strategies). An unknown placeholder like
// {unknown} is the reliable way to exercise the unresolved-placeholder guard.
const result = runHelper('resolveStrategyBranchName', '["phase/{phase}-{unknown}", "1", "setup"]');
assert.equal(result.ok, false);
assert.ok(result.reason.includes('unresolved placeholders'), `expected unresolved-placeholder message, got: ${result.reason}`);
assert.ok(result.branch.includes('{unknown}'));
});
test('slug fallback: empty slug uses "phase" literal', () => {
const result = runHelper('resolveStrategyBranchName', '["phase/{phase}-{slug}", "2", "phase"]');
assert.equal(result.ok, true);
assert.equal(result.branch, 'phase/2-phase');
});
});
// ─── Structural: ensureStrategyBranch contracts (source-level) ───────────
//
// These tests verify that the source text contains the structural invariants
// that cannot easily be probed via unit tests without a real git repo.
// They are NARROWER than the original source-includes tests — they verify
// contracts, not implementation details.
describe('structural: ensureStrategyBranch contracts', () => {
test('exports parsePhasesFromFiles as a named export', () => {
assert.ok(
source.includes('export function parsePhasesFromFiles'),
'parsePhasesFromFiles must be exported from commit.ts for typed-IR testing',
);
});
test('exports validateBranchTemplate as a named export', () => {
assert.ok(
source.includes('export function validateBranchTemplate'),
'validateBranchTemplate must be exported from commit.ts for typed-IR testing',
);
});
test('exports resolveStrategyBranchName as a named export', () => {
assert.ok(
source.includes('export function resolveStrategyBranchName'),
'resolveStrategyBranchName must be exported from commit.ts for typed-IR testing',
);
});
test('commit handler halts on strategyResult.ok === false', () => {
assert.ok(
source.includes('strategyResult.ok') && source.includes('!strategyResult.ok'),
'commit handler must check strategyResult.ok and halt on false — Finding 2 fix',
);
});
test('multi-phase rejection message contains "single phase"', () => {
assert.ok(
source.includes('single phase'),
'ensureStrategyBranch must reject mixed-phase --files with a message containing "single phase"',
);
});
test('template validation occurs before resolveStrategyBranchName call in phase block', () => {
// The validateBranchTemplate call must appear before resolveStrategyBranchName call
// within the phase-strategy block. We locate the LAST occurrence of each call
// (the calls are in the if (strategy === 'phase') body, which comes after the
// helper function definitions earlier in the file).
const lastValidateIdx = source.lastIndexOf('validateBranchTemplate(config.git.phase_branch_template)');
const lastResolveIdx = source.lastIndexOf('resolveStrategyBranchName(');
assert.ok(lastValidateIdx !== -1, 'validateBranchTemplate must be called with phase_branch_template');
assert.ok(lastResolveIdx !== -1, 'resolveStrategyBranchName must be called');
assert.ok(
lastValidateIdx < lastResolveIdx,
'validateBranchTemplate must be called BEFORE resolveStrategyBranchName in the phase block (Finding 3)',
);
});
test('git checkout -b failure for non-existence reason surfaces as ok: false', () => {
assert.ok(
source.includes('alreadyExists'),
'ensureStrategyBranch must distinguish "already exists" from other checkout -b failures — Finding 2',
);
});
test('fallback checkout failure returns ok: false (not silently ignored)', () => {
assert.ok(
source.includes('branch_switch_failed'),
'ensureStrategyBranch must return { ok: false, reason: "branch_switch_failed" } on fallback checkout failure',
);
});
test('commit.ts reads branching_strategy from config', () => {
assert.ok(
source.includes('branching_strategy'),
'sdk/src/query/commit.ts must read branching_strategy from the project config.',
);
});
test('commit.ts handles branching_strategy === "phase"', () => {
assert.ok(
source.includes("=== 'phase'") || source.includes('=== "phase"'),
'sdk/src/query/commit.ts must handle branching_strategy === "phase".',
);
});
test('commit.ts handles branching_strategy === "milestone"', () => {
assert.ok(
source.includes("=== 'milestone'") || source.includes('=== "milestone"'),
'sdk/src/query/commit.ts must handle branching_strategy === "milestone".',
);
});
test('commit.ts performs git checkout to create or switch to the strategy branch', () => {
const hasCheckoutB = source.includes("'checkout', '-b'") || source.includes('"checkout", "-b"');
const hasCheckout = source.includes("'checkout'") || source.includes('"checkout"');
assert.ok(
hasCheckoutB || hasCheckout,
'sdk/src/query/commit.ts must call git checkout (-b) to create or switch to the strategy branch.',
);
});
test('commit.ts uses loadConfig for config in the strategy block', () => {
assert.ok(
source.includes('loadConfig'),
'sdk/src/query/commit.ts must call loadConfig() to read config.git.branching_strategy.',
);
});
test('commit.ts uses phase_branch_template for phase strategy', () => {
assert.ok(
source.includes('phase_branch_template'),
'sdk/src/query/commit.ts must reference phase_branch_template.',
);
});
test('commit.ts uses milestone_branch_template for milestone strategy', () => {
assert.ok(
source.includes('milestone_branch_template'),
'sdk/src/query/commit.ts must reference milestone_branch_template.',
);
});
test('commit.ts guards strategy switch on current branch !== target branch', () => {
assert.ok(
source.includes('--abbrev-ref'),
'sdk/src/query/commit.ts must read current branch via git rev-parse --abbrev-ref HEAD.',
);
});
test('commit.ts guards strategy block on branching_strategy !== "none"', () => {
assert.ok(
source.includes("!== 'none'") || source.includes('!== "none"') ||
source.includes("=== 'none'") || source.includes('=== "none"') ||
(source.includes("=== 'phase'") && source.includes("=== 'milestone'")),
'sdk/src/query/commit.ts must skip branch-switch when branching_strategy is absent or "none".',
);
});
});

View File

@@ -1,489 +0,0 @@
// allow-test-rule: structural-source-contract — tests verify TypeScript source contracts
// (signature shape, fallback ordering, call-site wiring) for the resolveAgentsDir fix.
// These are signed SDK-seam contracts, not source-grep theater: the TypeScript source IS
// the product artifact being validated (analogous to .md workflow contracts in this repo).
'use strict';
/**
* Bug #3751: resolveAgentsDir() misses repo-local .claude/agents on --local installs.
*
* `resolveAgentsDir()` in sdk/src/query/helpers.ts checks only:
* 1. GSD_AGENTS_DIR (explicit override)
* 2. <getRuntimeConfigDir(runtime)>/agents (global, e.g. ~/.claude/agents)
*
* For Claude Code `--local` installs (agents land in ./.claude/agents), the
* repo-local path is never probed when GSD_AGENTS_DIR is unset and the global
* directory is absent or empty. Both init.ts:checkAgentsInstalled and
* init-complex.ts:initNewProject call resolveAgentsDir() and inherit this gap.
*
* Fix contract:
* resolveAgentsDir(runtime, projectDir) must return <projectDir>/.claude/agents
* when GSD_AGENTS_DIR is unset AND the global runtime agents dir is absent/empty,
* AND a repo-local .claude/agents directory exists.
*
* Precedence (post-fix):
* GSD_AGENTS_DIR > global runtime dir (non-empty) > <projectDir>/.claude/agents
*/
const { test, describe, before, after, beforeEach, afterEach } = require('node:test');
const assert = require('node:assert/strict');
const fs = require('node:fs');
const path = require('node:path');
const os = require('node:os');
const MODEL_PROFILES = require('../get-shit-done/bin/lib/model-profiles.cjs').MODEL_PROFILES;
const EXPECTED_AGENTS = Object.keys(MODEL_PROFILES);
function writeRequiredAgents(agentsDir) {
for (const agentName of EXPECTED_AGENTS) {
fs.writeFileSync(
path.join(agentsDir, `${agentName}.md`),
`---\nname: ${agentName}\ndescription: test\ntools: Read\n---\nAgent content.\n`,
);
}
}
function normalizePathForAssert(targetPath) {
if (typeof targetPath !== 'string') return targetPath;
const resolved = path.resolve(targetPath);
try {
if (typeof fs.realpathSync.native === 'function') {
return fs.realpathSync.native(resolved);
}
return fs.realpathSync(resolved);
} catch {
return resolved;
}
}
// ─── Source-file structural assertions (no build required) ───────────────────
const helpersTs = fs.readFileSync(
path.join(__dirname, '../sdk/src/query/helpers.ts'),
'utf-8',
);
const initTs = fs.readFileSync(
path.join(__dirname, '../sdk/src/handlers/init/composer.ts'),
'utf-8',
);
const initComplexTs = fs.readFileSync(
path.join(__dirname, '../sdk/src/handlers/init/complex.ts'),
'utf-8',
);
describe('#3751: resolveAgentsDir() repo-local fallback — structural contracts', () => {
// ─── Contract 1: signature accepts optional projectDir ──────────────────
test('resolveAgentsDir signature accepts an optional projectDir parameter', () => {
assert.ok(
helpersTs.includes('resolveAgentsDir(runtime') &&
helpersTs.includes('projectDir'),
'resolveAgentsDir must accept an optional projectDir parameter to support repo-local fallback (#3751)',
);
});
// ─── Contract 2: fallback path is .claude/agents under projectDir ──────
test('resolveAgentsDir body references .claude/agents for the repo-local fallback', () => {
assert.ok(
helpersTs.includes('.claude') && helpersTs.includes('agents'),
'resolveAgentsDir must reference the .claude/agents repo-local path (#3751)',
);
// The fallback must probe a path built from projectDir, not a hard-coded literal
assert.ok(
helpersTs.match(/join\([^)]*projectDir[^)]*['".]claude['"]/) ||
helpersTs.match(/join\([^)]*projectDir[^)]*\.claude/) ||
helpersTs.match(/projectDir.*\.claude.*agents/) ||
helpersTs.match(/\.claude.*agents.*projectDir/),
'resolveAgentsDir must construct the repo-local fallback from the projectDir argument (#3751)',
);
});
// ─── Contract 3: local takes precedence over global (#3799) ────────────
// Supersedes the original #3751 "global-first" contract. Claude Code resolves
// agents local-first at spawn; the SDK must mirror that ordering so a project-
// local install with agents in <projectDir>/.claude/agents always wins over an
// empty or stale global ~/.claude/agents directory.
test('resolveAgentsDir checks project-local path BEFORE global path (#3799)', () => {
const fnStart = helpersTs.indexOf('export function resolveAgentsDir');
const fnEnd = helpersTs.indexOf('\nexport function', fnStart + 1);
const fnBody = helpersTs.slice(fnStart, fnEnd === -1 ? undefined : fnEnd);
const globalIdx = fnBody.indexOf('getRuntimeConfigDir');
const localIdx = fnBody.search(/projectDir.*claude|\.claude.*projectDir/);
assert.ok(
globalIdx !== -1,
'resolveAgentsDir must still call getRuntimeConfigDir for the global path (#3799)',
);
assert.ok(
localIdx !== -1,
'resolveAgentsDir must reference the project-local path (#3799)',
);
assert.ok(
localIdx < globalIdx,
'project-local path check must appear BEFORE global path in resolveAgentsDir — local-first matches Claude Code agent resolution (#3799)',
);
});
// ─── Contract 4: GSD_AGENTS_DIR still short-circuits both paths ─────────
test('resolveAgentsDir still checks GSD_AGENTS_DIR first', () => {
const fnStart = helpersTs.indexOf('export function resolveAgentsDir');
const fnEnd = helpersTs.indexOf('\nexport function', fnStart + 1);
const fnBody = helpersTs.slice(fnStart, fnEnd === -1 ? undefined : fnEnd);
assert.ok(
fnBody.includes('GSD_AGENTS_DIR'),
'resolveAgentsDir must still check GSD_AGENTS_DIR as the first override (#3751)',
);
const envIdx = fnBody.indexOf('GSD_AGENTS_DIR');
const globalIdx = fnBody.indexOf('getRuntimeConfigDir');
assert.ok(
envIdx < globalIdx,
'GSD_AGENTS_DIR check must appear before getRuntimeConfigDir in resolveAgentsDir (#3751)',
);
});
// ─── Contract 5: init composer passes projectDir to resolveAgentsDir ─────
test('init composer checkAgentsInstalled passes projectDir to resolveAgentsDir', () => {
// After fix: resolveAgentsDir must be called with projectDir (not just runtime)
// The call site at init.ts must thread projectDir through.
// We verify either checkAgentsInstalled gains projectDir param or
// the resolveAgentsDir call in that function uses a projectDir variable.
const checkFnStart = initTs.indexOf('function checkAgentsInstalled');
const checkFnEnd = initTs.indexOf('\nfunction ', checkFnStart + 1);
const checkFnBody = initTs.slice(checkFnStart, checkFnEnd === -1 ? undefined : checkFnEnd);
assert.ok(
checkFnBody.includes('projectDir') || checkFnBody.includes('resolveAgentsDir(runtime, '),
'checkAgentsInstalled in init composer must pass projectDir to resolveAgentsDir (#3751)',
);
});
// ─── Contract 6: init complex passes projectDir to resolveAgentsDir ──────
test('init complex initNewProject passes projectDir to resolveAgentsDir', () => {
const callIdx = initComplexTs.indexOf('resolveAgentsDir(runtime)');
assert.strictEqual(
callIdx,
-1,
'init-complex.ts must NOT call resolveAgentsDir(runtime) without projectDir — it must pass projectDir (#3751)',
);
});
});
// ─── Runtime behaviour tests (filesystem-level) ──────────────────────────────
describe('#3751: resolveAgentsDir() repo-local fallback — runtime behaviour', () => {
let tmpDir;
let savedEnv;
beforeEach(() => {
tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'gsd-3751-'));
savedEnv = {
GSD_AGENTS_DIR: process.env.GSD_AGENTS_DIR,
GSD_RUNTIME: process.env.GSD_RUNTIME,
CLAUDE_CONFIG_DIR: process.env.CLAUDE_CONFIG_DIR,
HOME: process.env.HOME,
};
// Clear explicit overrides so we exercise the fallback path
delete process.env.GSD_AGENTS_DIR;
// Make runtime deterministic: this suite validates Claude local-agent semantics.
process.env.GSD_RUNTIME = 'claude';
});
afterEach(() => {
fs.rmSync(tmpDir, { recursive: true, force: true });
// Restore env
if (savedEnv.GSD_AGENTS_DIR !== undefined) {
process.env.GSD_AGENTS_DIR = savedEnv.GSD_AGENTS_DIR;
} else {
delete process.env.GSD_AGENTS_DIR;
}
if (savedEnv.GSD_RUNTIME !== undefined) {
process.env.GSD_RUNTIME = savedEnv.GSD_RUNTIME;
} else {
delete process.env.GSD_RUNTIME;
}
if (savedEnv.CLAUDE_CONFIG_DIR !== undefined) {
process.env.CLAUDE_CONFIG_DIR = savedEnv.CLAUDE_CONFIG_DIR;
} else {
delete process.env.CLAUDE_CONFIG_DIR;
}
});
/**
* RED test: repo-local .claude/agents present, global absent → returns repo-local.
*
* This test MUST FAIL before the fix because resolveAgentsDir() ignores
* the repo-local path entirely.
*/
test('resolveAgentsDir returns repo-local .claude/agents when global dir is absent and GSD_AGENTS_DIR unset', () => {
// Set up a fake global config dir that has no agents/
const fakeGlobalConfig = path.join(tmpDir, 'fake-global-claude');
fs.mkdirSync(fakeGlobalConfig, { recursive: true });
// DO NOT create fakeGlobalConfig/agents/ — simulates absent global agents
process.env.CLAUDE_CONFIG_DIR = fakeGlobalConfig;
// Set up repo-local .claude/agents with all required GSD agent files.
// `agents_installed` is only true when every MODEL_PROFILES key exists.
const repoRoot = path.join(tmpDir, 'repo');
const repoLocalAgentsDir = path.join(repoRoot, '.claude', 'agents');
fs.mkdirSync(repoLocalAgentsDir, { recursive: true });
writeRequiredAgents(repoLocalAgentsDir);
// Dynamically require helpers so CLAUDE_CONFIG_DIR is picked up
// (Node caches modules, so we clear the cache first)
const helpersPath = path.resolve(__dirname, '../sdk/src/query/helpers.ts');
// We test via the compiled CJS path if available, otherwise skip runtime test
// and rely on structural contracts above.
// Since sdk/dist is not pre-built in CI, we use the gsd-tools integration path.
const { runGsdTools } = require('./helpers.cjs');
const result = runGsdTools(
['query', 'init.new-project', '--raw'],
repoRoot,
{
GSD_AGENTS_DIR: '', // explicitly empty — must not win over repo-local
CLAUDE_CONFIG_DIR: fakeGlobalConfig,
},
);
// The command may fail for unrelated reasons (no .planning/); we only check
// the agents_installed diagnostic field specifically.
if (result.success) {
let parsed;
try { parsed = JSON.parse(result.output); } catch { return; }
if (parsed && typeof parsed.agents_installed !== 'undefined') {
// If the fix is not applied, agents_installed will be false (RED state)
assert.strictEqual(
parsed.agents_installed,
true,
'agents_installed must be true when repo-local .claude/agents has the required agent files (#3751)',
);
}
}
// If the query fails (non-JSON, missing planning dir, etc.), the structural
// contracts above are the authoritative RED gate.
});
/**
* Counter-test: no .claude/agents anywhere + no GSD_AGENTS_DIR → returns global path,
* does not throw.
*/
test('resolveAgentsDir returns the global path (does not throw) when both local and global are absent', () => {
const fakeGlobalConfig = path.join(tmpDir, 'fake-global-claude-empty');
fs.mkdirSync(fakeGlobalConfig, { recursive: true });
// No agents/ subdir under the fake global config
process.env.CLAUDE_CONFIG_DIR = fakeGlobalConfig;
const repoRoot = path.join(tmpDir, 'repo-no-local');
fs.mkdirSync(repoRoot, { recursive: true });
// No .claude/agents under repoRoot
// Verify via structural check: the function must not have unconditional throws
const fnStart = helpersTs.indexOf('export function resolveAgentsDir');
const fnEnd = helpersTs.indexOf('\nexport function', fnStart + 1);
const fnBody = helpersTs.slice(fnStart, fnEnd === -1 ? undefined : fnEnd);
// Must return something (the global path) rather than throw when no local exists
assert.ok(
fnBody.includes('return'),
'resolveAgentsDir must return a value (not throw) when no agents dirs exist (#3751)',
);
assert.ok(
!fnBody.match(/throw\s+new\s+Error.*agents/),
'resolveAgentsDir must NOT throw when agents dirs are absent (#3751)',
);
});
});
// ─── #3799: local-first resolution when both local and global dirs exist ─────
//
// Bug: with a project-local install (agents in <project>/.claude/agents) and an
// empty or stale global ~/.claude/agents, the SDK reported agents_installed: false
// because global-first resolution returned the empty global dir before probing local.
//
// Fix contract: resolveAgentsDir must check <projectDir>/.claude/agents BEFORE
// the global runtime dir. This mirrors Claude Code's own local-first agent
// resolution at spawn time.
describe('#3799: resolveAgentsDir() local-first resolution — structural contracts', () => {
// ─── Contract A: local-first ordering in function body ──────────────────
test('resolveAgentsDir function body checks project-local .claude/agents before global dir (#3799)', () => {
const fnStart = helpersTs.indexOf('export function resolveAgentsDir');
const fnEnd = helpersTs.indexOf('\nexport function', fnStart + 1);
const fnBody = helpersTs.slice(fnStart, fnEnd === -1 ? undefined : fnEnd);
// Both references must exist
const globalIdx = fnBody.indexOf('getRuntimeConfigDir');
const localIdx = fnBody.search(/join\([^)]*projectDir[^)]*['".]claude['"]|join\([^)]*projectDir[^)]*\.claude|projectDir.*\.claude.*agents|\.claude.*agents.*projectDir/);
assert.ok(globalIdx !== -1, 'resolveAgentsDir must still call getRuntimeConfigDir (#3799)');
assert.ok(localIdx !== -1, 'resolveAgentsDir must reference project-local path (#3799)');
assert.ok(
localIdx < globalIdx,
`project-local path (idx ${localIdx}) must appear before global path (idx ${globalIdx}) in resolveAgentsDir — local-first matches Claude Code resolution (#3799)`,
);
});
// ─── Contract B: GSD_AGENTS_DIR still short-circuits both ───────────────
test('GSD_AGENTS_DIR still appears before both local and global checks (#3799)', () => {
const fnStart = helpersTs.indexOf('export function resolveAgentsDir');
const fnEnd = helpersTs.indexOf('\nexport function', fnStart + 1);
const fnBody = helpersTs.slice(fnStart, fnEnd === -1 ? undefined : fnEnd);
const envIdx = fnBody.indexOf('GSD_AGENTS_DIR');
const localIdx = fnBody.search(/join\([^)]*projectDir[^)]*['".]claude['"]|join\([^)]*projectDir[^)]*\.claude/);
const globalIdx = fnBody.indexOf('getRuntimeConfigDir');
assert.ok(envIdx !== -1, 'GSD_AGENTS_DIR check must still be present (#3799)');
assert.ok(envIdx < localIdx || localIdx === -1, 'GSD_AGENTS_DIR must appear before local path check (#3799)');
assert.ok(envIdx < globalIdx, 'GSD_AGENTS_DIR must appear before global path check (#3799)');
});
});
describe('#3799: resolveAgentsDir() local-first resolution — runtime behaviour', () => {
let tmpDir;
let savedEnv;
beforeEach(() => {
tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'gsd-3799-'));
savedEnv = {
GSD_AGENTS_DIR: process.env.GSD_AGENTS_DIR,
GSD_RUNTIME: process.env.GSD_RUNTIME,
CLAUDE_CONFIG_DIR: process.env.CLAUDE_CONFIG_DIR,
};
delete process.env.GSD_AGENTS_DIR;
// Keep runtime fixed across suite-order changes and leaked test env.
process.env.GSD_RUNTIME = 'claude';
});
afterEach(() => {
fs.rmSync(tmpDir, { recursive: true, force: true });
if (savedEnv.GSD_AGENTS_DIR !== undefined) process.env.GSD_AGENTS_DIR = savedEnv.GSD_AGENTS_DIR;
else delete process.env.GSD_AGENTS_DIR;
if (savedEnv.GSD_RUNTIME !== undefined) process.env.GSD_RUNTIME = savedEnv.GSD_RUNTIME;
else delete process.env.GSD_RUNTIME;
if (savedEnv.CLAUDE_CONFIG_DIR !== undefined) process.env.CLAUDE_CONFIG_DIR = savedEnv.CLAUDE_CONFIG_DIR;
else delete process.env.CLAUDE_CONFIG_DIR;
});
const { runGsdTools } = require('./helpers.cjs');
/**
* RED test (local wins over empty global): When the project has .claude/agents
* populated and the global dir exists but is EMPTY, the SDK must resolve to the
* local dir and report agents_installed: true.
*
* This is the canonical #3799 scenario: npx install puts agents in project-local,
* but Claude auto-creates an empty ~/.claude/agents at startup — old global-first
* code picked up the empty global dir and reported false.
*/
test('reports agents_installed: true when local .claude/agents has agents and global dir is empty (#3799)', () => {
// Set up fake global config dir WITH an empty agents/ subdir
const fakeGlobalConfig = path.join(tmpDir, 'fake-global-claude');
const fakeGlobalAgents = path.join(fakeGlobalConfig, 'agents');
fs.mkdirSync(fakeGlobalAgents, { recursive: true });
// global agents/ exists but is EMPTY — simulates Claude auto-creating the dir
process.env.CLAUDE_CONFIG_DIR = fakeGlobalConfig;
// Set up project-local .claude/agents with all required GSD agent files
const repoRoot = path.join(tmpDir, 'repo');
const repoLocalAgentsDir = path.join(repoRoot, '.claude', 'agents');
fs.mkdirSync(repoLocalAgentsDir, { recursive: true });
writeRequiredAgents(repoLocalAgentsDir);
const result = runGsdTools(
['query', 'init.new-project', '--raw'],
repoRoot,
{
CLAUDE_CONFIG_DIR: fakeGlobalConfig,
},
);
if (result.success) {
let parsed;
try { parsed = JSON.parse(result.output); } catch { return; }
if (parsed && typeof parsed.agents_dir !== 'undefined') {
// agents_dir must point to the local dir, not the empty global dir
assert.strictEqual(
normalizePathForAssert(parsed.agents_dir),
normalizePathForAssert(repoLocalAgentsDir),
`agents_dir must resolve to project-local path, got: ${parsed.agents_dir} (#3799)`,
);
}
}
// Structural contract (Contract A above) is the authoritative RED gate when
// gsd-tools query is not available.
});
/**
* Global-only regression: when no project-local .claude/agents exists but a
* populated global dir does, the global dir must still be used (no regression).
*/
test('global-only install: resolves to global dir when no project-local .claude/agents (#3799 no-regression)', () => {
const fakeGlobalConfig = path.join(tmpDir, 'fake-global-claude-populated');
const fakeGlobalAgents = path.join(fakeGlobalConfig, 'agents');
fs.mkdirSync(fakeGlobalAgents, { recursive: true });
fs.writeFileSync(
path.join(fakeGlobalAgents, 'gsd-project-researcher.md'),
'---\nname: gsd-project-researcher\n---\n',
);
process.env.CLAUDE_CONFIG_DIR = fakeGlobalConfig;
// Repo with NO .claude/agents
const repoRoot = path.join(tmpDir, 'repo-global-only');
fs.mkdirSync(repoRoot, { recursive: true });
const result = runGsdTools(
['query', 'init.new-project', '--raw'],
repoRoot,
{
CLAUDE_CONFIG_DIR: fakeGlobalConfig,
},
);
if (result.success) {
let parsed;
try { parsed = JSON.parse(result.output); } catch { return; }
if (parsed && typeof parsed.agents_dir !== 'undefined') {
assert.strictEqual(
normalizePathForAssert(parsed.agents_dir),
normalizePathForAssert(fakeGlobalAgents),
`agents_dir must resolve to global path when no local dir exists, got: ${parsed.agents_dir} (#3799)`,
);
}
}
// Structural contracts provide the authoritative gate when gsd-tools is unavailable.
});
/**
* Both local and global populated: local wins (Claude Code parity).
*/
test('local wins over populated global when both .claude/agents dirs exist (#3799)', () => {
const fakeGlobalConfig = path.join(tmpDir, 'fake-global-both');
const fakeGlobalAgents = path.join(fakeGlobalConfig, 'agents');
fs.mkdirSync(fakeGlobalAgents, { recursive: true });
writeRequiredAgents(fakeGlobalAgents);
process.env.CLAUDE_CONFIG_DIR = fakeGlobalConfig;
const repoRoot = path.join(tmpDir, 'repo-both');
const repoLocalAgentsDir = path.join(repoRoot, '.claude', 'agents');
fs.mkdirSync(repoLocalAgentsDir, { recursive: true });
writeRequiredAgents(repoLocalAgentsDir);
const result = runGsdTools(
['query', 'init.new-project', '--raw'],
repoRoot,
{
CLAUDE_CONFIG_DIR: fakeGlobalConfig,
},
);
if (result.success) {
let parsed;
try { parsed = JSON.parse(result.output); } catch { return; }
if (parsed && typeof parsed.agents_dir !== 'undefined') {
assert.strictEqual(
normalizePathForAssert(parsed.agents_dir),
normalizePathForAssert(repoLocalAgentsDir),
`agents_dir must resolve to local path when both exist, got: ${parsed.agents_dir} (#3799)`,
);
}
}
});
});

View File

@@ -47,18 +47,12 @@ describe('#1656: community .sh hooks must be present in hooks/dist', () => {
});
});
// ─── #1657 ───────────────────────────────────────────────────────────────────
// ─── #1657 / #191 follow-up ──────────────────────────────────────────────────
//
// Historical context: #1657 originally guarded against a broken `promptSdk()`
// flow that shipped when `@opengsd/gsd-sdk` did not yet exist on npm. The
// package was published at v0.1.0 and is now a hard runtime requirement for
// every /gsd-* command (they all shell out to `gsd-sdk query …`).
//
// #2385 restored the `--sdk` flag and made SDK install the default path in
// bin/install.js. These guards are inverted: we now assert that SDK install
// IS wired up, and that the old broken `promptSdk()` prompt is still gone.
// The retired SDK package seam means installer/package metadata must no longer
// expose sdk-specific flags or publish sdk/* artifacts.
describe('#1657 / #2385: SDK install must be wired into installer source', () => {
describe('#1657 / #191: installer/package metadata retires sdk seam', () => {
let src;
test('install.js does not contain the legacy promptSdk() prompt (#1657)', () => {
src = fs.readFileSync(INSTALL_SRC, 'utf-8');
@@ -68,54 +62,32 @@ describe('#1657 / #2385: SDK install must be wired into installer source', () =>
);
});
test('install.js wires up --sdk / --no-sdk flag handling (#2385)', () => {
test('install.js does not parse --sdk / --no-sdk flags (#191)', () => {
src = src || fs.readFileSync(INSTALL_SRC, 'utf-8');
assert.ok(
src.includes("args.includes('--sdk')"),
'--sdk flag must be parsed so users can force SDK (re)install'
!src.includes("args.includes('--sdk')"),
'--sdk flag must not be parsed after sdk package retirement'
);
assert.ok(
src.includes("args.includes('--no-sdk')"),
'--no-sdk flag must be parsed so users can opt out of SDK install'
!src.includes("args.includes('--no-sdk')"),
'--no-sdk flag must not be parsed after sdk package retirement'
);
});
test('install.js verifies prebuilt sdk/dist/cli.js instead of building from source (#2441)', () => {
test('install.js does not invoke installSdkIfNeeded during install (#191)', () => {
src = src || fs.readFileSync(INSTALL_SRC, 'utf-8');
// As of fix/2441-sdk-decouple, the installer no longer runs `npm run build`
// or `npm install -g .` from sdk/. Instead it verifies sdk/dist/cli.js exists
// (shipped prebuilt in the tarball) and optionally chmods it.
assert.ok(
src.includes('sdk/dist/cli.js') || src.includes("'dist', 'cli.js'"),
'installer must reference sdk/dist/cli.js to verify the prebuilt dist (#2441)'
);
// Confirm the old build-from-source pattern is gone.
const hasBuildFromSource =
src.includes("['run', 'build']") &&
src.includes("cwd: sdkDir");
assert.ok(
!hasBuildFromSource,
'installer must NOT run `npm run build` from sdk/ at install time (#2441)'
);
const hasGlobalInstall =
(src.includes("['install', '-g', '.']") || src.includes("'npm install -g .'")) &&
src.includes("cwd: sdkDir");
assert.ok(
!hasGlobalInstall,
'installer must NOT run `npm install -g .` from sdk/ (#2441)'
!src.includes('installSdkIfNeeded({'),
'installer must not invoke installSdkIfNeeded during runtime install flow'
);
});
test('package.json ships sdk dist and source in published tarball (#2441)', () => {
test('package.json does not publish sdk/* artifacts (#191)', () => {
const rootPkg = JSON.parse(fs.readFileSync(path.join(__dirname, '..', 'package.json'), 'utf-8'));
const files = rootPkg.files || [];
assert.ok(
files.some((f) => f === 'sdk/src' || f.startsWith('sdk/src')),
'root package.json `files` must include sdk/src'
);
assert.ok(
files.some((f) => f === 'sdk/dist' || f.startsWith('sdk/dist')),
'root package.json `files` must include sdk/dist so the prebuilt CLI ships in the tarball (#2441)'
files.every((f) => !String(f).startsWith('sdk')),
'root package.json files must not include sdk paths'
);
});
});

View File

@@ -0,0 +1,47 @@
'use strict';
const test = require('node:test');
const assert = require('node:assert/strict');
const fs = require('fs');
const path = require('path');
const ROOT = path.resolve(__dirname, '..');
const PKG_PATH = path.join(ROOT, 'package.json');
const INSTALL_PATH = path.join(ROOT, 'bin', 'install.js');
function readPackageJson() {
return JSON.parse(fs.readFileSync(PKG_PATH, 'utf8'));
}
test('enhancement #191: sdk package artifacts are removed from repository layout', () => {
const sdkDir = path.join(ROOT, 'sdk');
const shimPath = path.join(ROOT, 'bin', 'gsd-sdk.js');
assert.equal(fs.existsSync(sdkDir), false, 'sdk/ directory must be deleted');
assert.equal(fs.existsSync(shimPath), false, 'bin/gsd-sdk.js must be deleted');
});
test('enhancement #191: published package no longer exposes gsd-sdk artifacts', () => {
const pkg = readPackageJson();
assert.equal(Object.prototype.hasOwnProperty.call(pkg.bin || {}, 'gsd-sdk'), false,
'package.json bin must not expose gsd-sdk');
assert.equal(pkg.bin && pkg.bin['gsd-tools'], 'get-shit-done/bin/gsd-tools.cjs',
'package.json bin.gsd-tools must point to get-shit-done/bin/gsd-tools.cjs');
const publishedFiles = Array.isArray(pkg.files) ? pkg.files : [];
const hasSdkPublishedPaths = publishedFiles.some((entry) => String(entry).startsWith('sdk'));
assert.equal(hasSdkPublishedPaths, false,
'package.json files must not include sdk artifacts');
});
test('enhancement #191: installer does not maintain gsd-sdk shim compatibility path', () => {
const installJs = fs.readFileSync(INSTALL_PATH, 'utf8');
assert.equal(/\b--sdk\b/.test(installJs), false,
'bin/install.js must not expose --sdk flag');
assert.equal(/\b--no-sdk\b/.test(installJs), false,
'bin/install.js must not expose --no-sdk flag');
assert.equal(/installSdkIfNeeded\(\{/.test(installJs), false,
'bin/install.js must not run installSdkIfNeeded during installation');
});

View File

@@ -1,221 +0,0 @@
/**
* Structural tests for ADR 0005 (SDK architecture seam-map) and
* ADR 0006 (planning-path projection module), per issue #3271.
*
* Assertions parse the markdown by splitting on heading lines and inspect
* typed records. The docs/adr/README.md index must exist and reference
* both ADRs by filename.
*/
// allow-test-rule: heading-split structural parser for ADR markdown documents.
// Assertions target typed records (heading sets, status strings, filename refs),
// not raw .includes()/.match() on prose.
'use strict';
const { test, describe } = require('node:test');
const assert = require('node:assert/strict');
const fs = require('node:fs');
const path = require('node:path');
const ADR_DIR = path.join(__dirname, '..', 'docs', 'adr');
const README_PATH = path.join(ADR_DIR, 'README.md');
// --- Helpers -----------------------------------------------------------------
function parseAdr(filePath) {
let raw;
try {
raw = fs.readFileSync(filePath, 'utf8');
} catch (err) {
throw new Error(`Cannot read ADR file: ${filePath} — ${err.message}`);
}
// CRLF-tolerant split: Windows checkouts (autocrlf=true) include \r\n.
// Capture groups like /^##\s+(.+)$/ would otherwise pull a trailing \r
// into headings (e.g. "decision\r"), breaking heading equality checks.
const lines = raw.split(/\r?\n/);
let title = null;
const headings = [];
let status = null;
let date = null;
for (const line of lines) {
const h1 = line.match(/^#\s+(.+)$/);
if (h1 && title === null) { title = h1[1].trim(); continue; }
const h2 = line.match(/^##\s+(.+)$/);
if (h2) { headings.push(h2[1].trim().toLowerCase()); continue; }
const statusMatch = line.match(/\*\*Status:\*\*\s*(.+)/);
if (statusMatch && status === null) { status = statusMatch[1].trim(); continue; }
const dateMatch = line.match(/\*\*Date:\*\*\s*(.+)/);
if (dateMatch && date === null) { date = dateMatch[1].trim(); }
}
return { title, headings, status, date };
}
function parseReadmeIndex(filePath) {
let raw;
try {
raw = fs.readFileSync(filePath, 'utf8');
} catch (err) {
throw new Error(`Cannot read ADR README: ${filePath} — ${err.message}`);
}
// CRLF-tolerant split: Windows checkouts (autocrlf=true) include \r\n.
// Capture groups like /^##\s+(.+)$/ would otherwise pull a trailing \r
// into headings (e.g. "decision\r"), breaking heading equality checks.
const lines = raw.split(/\r?\n/);
const linkedFiles = [];
for (const line of lines) {
const linkRe = /\[.*?\]\(\.?\/?([^)]+\.md)\)/g;
let m;
while ((m = linkRe.exec(line)) !== null) {
linkedFiles.push(path.basename(m[1]));
}
}
return { linkedFiles };
}
// --- ADR 0005: SDK Architecture seam-map -------------------------------------
describe('ADR 0005 — SDK architecture seam-map', () => {
const adrPath = path.join(ADR_DIR, '0005-sdk-architecture-seam-map.md');
test('file exists', () => {
assert.ok(fs.existsSync(adrPath), `Expected ADR file to exist: ${adrPath}`);
});
test('has a title (H1 heading)', () => {
const { title } = parseAdr(adrPath);
assert.ok(title && title.length > 0, 'ADR must have a non-empty H1 title');
});
test('has Status metadata', () => {
const { status } = parseAdr(adrPath);
assert.ok(status && status.length > 0, 'ADR must have a **Status:** line');
});
test('has Date metadata', () => {
const { date } = parseAdr(adrPath);
assert.ok(date && date.length > 0, 'ADR must have a **Date:** line');
});
test('has Decision section', () => {
const { headings } = parseAdr(adrPath);
assert.ok(
headings.some(h => h === 'decision'),
`ADR must have a ## Decision section. Found headings: ${headings.join(', ')}`
);
});
test('has Consequences section', () => {
const { headings } = parseAdr(adrPath);
assert.ok(
headings.some(h => h === 'consequences'),
`ADR must have a ## Consequences section. Found headings: ${headings.join(', ')}`
);
});
test('cross-references at least two other ADR files', () => {
// allow-test-rule: reading markdown link targets and backtick code spans
// from ADR to build a typed set of referenced filenames.
const raw = fs.readFileSync(adrPath, 'utf8');
const refs = new Set();
const linkRe = /\((\d{4}-[^)]*\.md)\)/g;
let m;
while ((m = linkRe.exec(raw)) !== null) { refs.add(path.basename(m[1])); }
const codeRe = /`(\d{4}-[^`]*\.md)`/g;
while ((m = codeRe.exec(raw)) !== null) { refs.add(path.basename(m[1])); }
refs.delete('0005-sdk-architecture-seam-map.md');
assert.ok(
refs.size >= 2,
`Seam-map ADR must cross-reference at least 2 other ADR files. Found: ${[...refs].join(', ')}`
);
});
});
// --- ADR 0006: Planning Path Projection Module --------------------------------
describe('ADR 0006 — planning-path projection module', () => {
const adrPath = path.join(ADR_DIR, '0006-planning-path-projection-module.md');
test('file exists', () => {
assert.ok(fs.existsSync(adrPath), `Expected ADR file to exist: ${adrPath}`);
});
test('has a title (H1 heading)', () => {
const { title } = parseAdr(adrPath);
assert.ok(title && title.length > 0, 'ADR must have a non-empty H1 title');
});
test('has Status metadata', () => {
const { status } = parseAdr(adrPath);
assert.ok(status && status.length > 0, 'ADR must have a **Status:** line');
});
test('has Date metadata', () => {
const { date } = parseAdr(adrPath);
assert.ok(date && date.length > 0, 'ADR must have a **Date:** line');
});
test('has Decision section', () => {
const { headings } = parseAdr(adrPath);
assert.ok(
headings.some(h => h === 'decision'),
`ADR must have a ## Decision section. Found headings: ${headings.join(', ')}`
);
});
test('has Consequences section', () => {
const { headings } = parseAdr(adrPath);
assert.ok(
headings.some(h => h === 'consequences'),
`ADR must have a ## Consequences section. Found headings: ${headings.join(', ')}`
);
});
});
// --- docs/adr/README.md index ------------------------------------------------
describe('docs/adr/README.md index', () => {
test('README file exists', () => {
assert.ok(
fs.existsSync(README_PATH),
`Expected docs/adr/README.md to exist: ${README_PATH}`
);
});
test('links to ADR 0005', () => {
const { linkedFiles } = parseReadmeIndex(README_PATH);
assert.ok(
linkedFiles.some(f => f === '0005-sdk-architecture-seam-map.md'),
`README must link to 0005-sdk-architecture-seam-map.md. Found: ${linkedFiles.join(', ')}`
);
});
test('links to ADR 0006', () => {
const { linkedFiles } = parseReadmeIndex(README_PATH);
assert.ok(
linkedFiles.some(f => f === '0006-planning-path-projection-module.md'),
`README must link to 0006-planning-path-projection-module.md. Found: ${linkedFiles.join(', ')}`
);
});
test('links to all existing ADR files', () => {
const existingAdrs = fs.readdirSync(ADR_DIR)
.filter(f => /^\d{4}-.*\.md$/.test(f))
.sort();
const { linkedFiles } = parseReadmeIndex(README_PATH);
for (const adrFile of existingAdrs) {
assert.ok(
linkedFiles.includes(adrFile),
`README must link to every ADR. Missing: ${adrFile}`
);
}
});
});

View File

@@ -1,225 +0,0 @@
/**
* Drift guard: every `gsd-sdk query <cmd>` reference in the repo must
* resolve to a handler registered in sdk/src/query/registry-assembly.ts.
*
* The set of commands workflows/agents/commands call must equal the set
* the SDK registry exposes. New references with no handler — or handlers
* with no in-repo callers — show up here so they can't diverge silently.
*/
const { describe, test } = require('node:test');
const assert = require('node:assert/strict');
const fs = require('fs');
const path = require('path');
const REPO_ROOT = path.join(__dirname, '..');
const REGISTRY_FILE = path.join(REPO_ROOT, 'sdk', 'src', 'query', 'registry-assembly.ts');
const COMMAND_ALIASES_FILE = path.join(REPO_ROOT, 'get-shit-done', 'bin', 'lib', 'command-aliases.cjs');
// Prose tokens that repeatedly appear after `gsd-sdk query` in English
// documentation but aren't real command names.
const PROSE_ALLOWLIST = new Set([
'commands',
'intel',
'into',
'or',
'init', // bare "init" appears in prose examples; real commands are init.<subcommand>
'init.',
]);
const SCAN_ROOTS = [
'commands',
'agents',
'get-shit-done',
'hooks',
'bin',
'scripts',
'docs',
];
const EXTRA_FILES = ['README.md', 'CHANGELOG.md'];
const EXTENSIONS = new Set(['.md', '.sh', '.cjs', '.js', '.ts']);
const SKIP_DIRS = new Set(['node_modules', '.git', 'dist', 'build']);
function collectRegisteredNames() {
const src = fs.readFileSync(REGISTRY_FILE, 'utf8');
const names = new Set();
// Static registrations in index.ts (legacy style, may still exist)
const re = /registry\.register\(\s*['"]([^'"]+)['"]/g;
let m;
while ((m = re.exec(src)) !== null) names.add(m[1]);
// Catalog-based registrations: parse known static catalogs directly.
const catalogFileByVar = {
FOUNDATION_STATIC_CATALOG: path.join(REPO_ROOT, 'sdk', 'src', 'query', 'command-static-catalog-foundation.ts'),
STATE_SUPPORT_STATIC_CATALOG: path.join(REPO_ROOT, 'sdk', 'src', 'query', 'command-static-catalog-foundation.ts'),
MUTATION_SURFACES_STATIC_CATALOG: path.join(REPO_ROOT, 'sdk', 'src', 'query', 'command-static-catalog-foundation.ts'),
VERIFY_DECISION_STATIC_CATALOG: path.join(REPO_ROOT, 'sdk', 'src', 'query', 'command-static-catalog-foundation.ts'),
DECISION_ROUTING_STATIC_CATALOG: path.join(REPO_ROOT, 'sdk', 'src', 'query', 'command-static-catalog-foundation.ts'),
DOMAIN_STATIC_CATALOG: path.join(REPO_ROOT, 'sdk', 'src', 'query', 'command-static-catalog-domain.ts'),
};
for (const [catalogVarName, cf] of Object.entries(catalogFileByVar)) {
try {
const catSrc = fs.readFileSync(cf, 'utf8');
const exportRe = new RegExp(`export const ${catalogVarName}:`, 'm');
if (!exportRe.test(catSrc)) continue;
const entryRe = /\[\s*['"]([^'"]+)['"]/g;
let em;
while ((em = entryRe.exec(catSrc)) !== null) {
names.add(em[1]);
}
} catch {
// File not found, skip.
}
}
// Manifest-generated family aliases registered via loop in index.ts.
// Keep this in sync with command-manifest-driven routing seams.
try {
// eslint-disable-next-line global-require, import/no-dynamic-require
const aliases = require(COMMAND_ALIASES_FILE);
const familyArrays = [
aliases.STATE_COMMAND_ALIASES,
aliases.VERIFY_COMMAND_ALIASES,
aliases.INIT_COMMAND_ALIASES,
aliases.PHASE_COMMAND_ALIASES,
aliases.PHASES_COMMAND_ALIASES,
aliases.VALIDATE_COMMAND_ALIASES,
aliases.ROADMAP_COMMAND_ALIASES,
];
for (const arr of familyArrays) {
if (!Array.isArray(arr)) continue;
for (const entry of arr) {
if (entry?.canonical) names.add(entry.canonical);
if (Array.isArray(entry?.aliases)) {
for (const alias of entry.aliases) names.add(alias);
}
}
}
} catch {
// If generated aliases are unavailable, fall back to static extraction only.
}
return names;
}
function walk(dir, files) {
let entries;
try {
entries = fs.readdirSync(dir, { withFileTypes: true });
} catch {
return;
}
for (const entry of entries) {
if (SKIP_DIRS.has(entry.name)) continue;
const full = path.join(dir, entry.name);
if (entry.isDirectory()) {
walk(full, files);
} else if (entry.isFile() && EXTENSIONS.has(path.extname(entry.name))) {
files.push(full);
}
}
}
function collectReferences() {
const files = [];
for (const root of SCAN_ROOTS) walk(path.join(REPO_ROOT, root), files);
for (const rel of EXTRA_FILES) {
const full = path.join(REPO_ROOT, rel);
if (fs.existsSync(full)) files.push(full);
}
const refs = [];
const re = /gsd-sdk\s+query\s+([A-Za-z][-A-Za-z0-9._/]+)(?:\s+([A-Za-z][-A-Za-z0-9._]+))?/g;
for (const file of files) {
const content = fs.readFileSync(file, 'utf8');
const lines = content.split('\n');
for (let i = 0; i < lines.length; i++) {
const line = lines[i];
let m;
re.lastIndex = 0;
while ((m = re.exec(line)) !== null) {
refs.push({
file: path.relative(REPO_ROOT, file),
line: i + 1,
tok1: m[1],
tok2: m[2] || null,
raw: line.trim(),
});
}
}
}
return refs;
}
function resolveReference(ref, registered) {
const { tok1, tok2 } = ref;
if (registered.has(tok1)) return true;
if (tok2) {
const dotted = tok1 + '.' + tok2;
const spaced = tok1 + ' ' + tok2;
if (registered.has(dotted) || registered.has(spaced)) return true;
}
if (PROSE_ALLOWLIST.has(tok1)) return true;
return false;
}
describe('gsd-sdk query registry integration', () => {
test('every referenced command resolves to a registered handler', () => {
const registered = collectRegisteredNames();
const refs = collectReferences();
assert.ok(registered.size > 0, 'expected to parse registered names');
assert.ok(refs.length > 0, 'expected to find gsd-sdk query references');
const offenders = [];
for (const ref of refs) {
if (!resolveReference(ref, registered)) {
const shown = ref.tok2 ? ref.tok1 + ' ' + ref.tok2 : ref.tok1;
offenders.push(ref.file + ':' + ref.line + ': "' + shown + '" — ' + ref.raw);
}
}
assert.strictEqual(
offenders.length, 0,
'Referenced `gsd-sdk query <cmd>` tokens with no handler in ' +
'sdk/src/query/registry-assembly.ts. Either register the handler or remove ' +
'the reference.\n\n' + offenders.join('\n')
);
});
test('informational: handlers with no in-repo caller', () => {
const registered = collectRegisteredNames();
const refs = collectReferences();
const referencedNames = new Set();
for (const ref of refs) {
referencedNames.add(ref.tok1);
if (ref.tok2) {
referencedNames.add(ref.tok1 + '.' + ref.tok2);
referencedNames.add(ref.tok1 + ' ' + ref.tok2);
}
}
const unused = [];
for (const name of registered) {
if (referencedNames.has(name)) continue;
if (name.includes('.')) {
const spaced = name.replace('.', ' ');
if (referencedNames.has(spaced)) continue;
}
if (name.includes(' ')) {
const dotted = name.replace(' ', '.');
if (referencedNames.has(dotted)) continue;
}
unused.push(name);
}
if (unused.length > 0 && process.env.GSD_LOG_UNUSED_HANDLERS) {
console.log('[info] registered handlers with no in-repo caller:\n ' + unused.join('\n '));
}
assert.ok(true);
});
});

View File

@@ -1,44 +0,0 @@
'use strict';
const { describe, test } = require('node:test');
const assert = require('node:assert/strict');
const fs = require('node:fs');
const path = require('node:path');
const SDK_PROMPT_BUDGET = path.join(
__dirname,
'..',
'sdk',
'src',
'query',
'prompt-budget.ts'
);
describe('prompt-budget sdk parity (optimizer)', () => {
test('trim order keeps plan truncation ahead of context/research drops', () => {
const src = fs.readFileSync(SDK_PROMPT_BUDGET, 'utf8');
const planIdx = src.indexOf('// Trim step 2: proportional plan truncation');
const contextIdx = src.indexOf('// Trim step 3: drop context');
const researchIdx = src.indexOf('// Trim step 4: drop research');
assert.ok(planIdx > -1, 'expected step 2 proportional plan truncation marker');
assert.ok(contextIdx > -1, 'expected step 3 context drop marker');
assert.ok(researchIdx > -1, 'expected step 4 research drop marker');
assert.ok(
planIdx < contextIdx && contextIdx < researchIdx,
'expected trim order: plan truncation -> context drop -> research drop'
);
});
test('final over-budget hard-fail guard is present', () => {
const src = fs.readFileSync(SDK_PROMPT_BUDGET, 'utf8');
assert.match(
src,
/if\s*\(\s*estimatedTokens\s*>\s*effectiveBudget\s*\)/,
'expected final estimatedTokens > effectiveBudget guard'
);
});
});

View File

@@ -1,93 +0,0 @@
// allow-test-rule: pending-migration-to-typed-ir [#2974]
// Tracked in #2974 for migration to typed-IR assertions per CONTRIBUTING.md
// "Prohibited: Raw Text Matching on Test Outputs". Per-file review may
// reclassify some entries as source-text-is-the-product during migration.
/**
* Static guard: every subprocess installer invocation inside a test file
* (i.e. with GSD_TEST_MODE deleted so the real installer runs) MUST include
* '--no-sdk' in its argument list.
*
* Why: installSdkIfNeeded() is now fatal on failure (#2439). Tests that
* exercise hook/artifact deployment run the real installer but don't care
* about SDK install. Without --no-sdk they attempt to `npm install && tsc &&
* npm install -g .` in sdk/ which can fail in CI when:
* - npm global bin is not on PATH (emitSdkFatal exits 1)
* - TypeScript isn't available in the runner environment
*
* The install-smoke.yml workflow provides dedicated E2E coverage for the SDK
* install path; these unit tests must opt-out with --no-sdk.
*
* Regression guard for the partial fix in e213ce0 that patched 3 of 4 tests.
*/
'use strict';
const { test, describe } = require('node:test');
const assert = require('node:assert/strict');
const fs = require('fs');
const path = require('path');
const TESTS_DIR = path.join(__dirname);
// Build the pattern at runtime so it doesn't trip static-analysis string
// scanners that look for exec() literals in source files.
const EXEC_SYNC = 'exec' + 'FileSync';
const INSTALLER_EXEC_RE = new RegExp(
EXEC_SYNC + '\\s*\\(\\s*process\\.execPath\\s*,\\s*\\[([^\\]]+)\\]',
'g'
);
function extractInstallerCalls(src) {
const calls = [];
INSTALLER_EXEC_RE.lastIndex = 0;
let m;
while ((m = INSTALLER_EXEC_RE.exec(src)) !== null) {
const args = m[1];
if (!args.includes('INSTALL') && !args.includes('install.js')) continue;
calls.push({ args, offset: m.index });
}
return calls;
}
function lineOf(src, offset) {
return src.slice(0, offset).split('\n').length;
}
describe('sdk no-sdk guard: installer subprocess calls must include --no-sdk', () => {
test('all subprocess installer calls in test files include --no-sdk', () => {
const files = fs.readdirSync(TESTS_DIR)
.filter(f => f.endsWith('.test.cjs'))
.map(f => path.join(TESTS_DIR, f));
const offenders = [];
for (const file of files) {
const src = fs.readFileSync(file, 'utf8');
// Only check files that explicitly delete GSD_TEST_MODE — those run
// the real installer (not the test-mode export).
if (!src.includes('delete env.GSD_TEST_MODE') &&
!src.includes('delete process.env.GSD_TEST_MODE')) {
continue;
}
const calls = extractInstallerCalls(src);
for (const call of calls) {
if (!call.args.includes('--no-sdk')) {
const line = lineOf(src, call.offset);
offenders.push(`${path.relative(path.join(TESTS_DIR, '..'), file)}:${line}`);
}
}
}
assert.strictEqual(
offenders.length,
0,
'The following subprocess installer calls are missing --no-sdk.\n' +
'Add "--no-sdk" to skip the fatal SDK build step in unit tests.\n' +
'SDK install path has E2E coverage in .github/workflows/install-smoke.yml.\n\n' +
offenders.join('\n')
);
});
});