Merge branch 'next' into kimi-runtime-support

This commit is contained in:
Viktorplus
2026-06-08 19:05:16 +02:00
committed by GitHub
32 changed files with 2936 additions and 846 deletions

View File

@@ -0,0 +1,46 @@
'use strict';
/**
* Regression guard — bug(#853): /gsd-manager and /gsd-autonomous --interactive
* silently skipped worktree isolation + independent verification because they
* dispatched Plan/Execute via Agent(run_in_background=true). On Claude Code a
* backgrounded agent has no Agent/Task tool, so it cannot spawn the nested
* subagents (worktree executors, plan-checker, verifier). The workflows must
* now resolve the runtime and run inline on Claude Code.
*/
const { describe, test } = require('node:test');
const assert = require('node:assert/strict');
const fs = require('node:fs');
const path = require('node:path');
const WORKFLOWS_DIR = path.join(__dirname, '..', 'gsd-core', 'workflows');
const MANAGER = fs.readFileSync(path.join(WORKFLOWS_DIR, 'manager.md'), 'utf8');
const AUTONOMOUS = fs.readFileSync(path.join(WORKFLOWS_DIR, 'autonomous.md'), 'utf8');
describe('bug-853 — manager/autonomous gate background dispatch by runtime', () => {
test('manager.md resolves the runtime before dispatching plan/execute', () => {
// Two dispatch sites (plan + execute), each must resolve the runtime.
const matches = MANAGER.match(/config-get runtime/g) || [];
assert.ok(matches.length >= 2, 'manager.md must resolve runtime for both plan and execute dispatch');
});
test('manager.md documents why Claude Code cannot background-dispatch', () => {
assert.match(MANAGER, /backgrounded agent has no `Agent`\/`Task` tool/);
});
test('manager.md runs plan/execute inline on Claude Code', () => {
assert.match(MANAGER, /If `RUNTIME` is `claude`[\s\S]{0,400}?Skill\(skill="gsd-plan-phase"/);
assert.match(MANAGER, /If `RUNTIME` is `claude`[\s\S]{0,400}?Skill\(skill="gsd-execute-phase"/);
});
test('autonomous.md gates interactive background dispatch by runtime', () => {
const autoRuntimeMatches = AUTONOMOUS.match(/config-get runtime/g) || [];
assert.ok(autoRuntimeMatches.length >= 2, 'autonomous.md must resolve runtime in both 3b (plan) and 3c (execute) interactive branches');
assert.match(AUTONOMOUS, /backgrounded agent has no `Agent`\/`Task` tool/);
});
test('autonomous.md runs plan/execute inline on Claude Code in interactive mode', () => {
assert.match(AUTONOMOUS, /On Claude Code \(`RUNTIME` is `claude`\)[\s\S]{0,400}?Skill\(skill="gsd-plan-phase"/);
assert.match(AUTONOMOUS, /On Claude Code \(`RUNTIME` is `claude`\)[\s\S]{0,400}?Skill\(skill="gsd-execute-phase"/);
});
});

View File

@@ -135,6 +135,41 @@ describe('enh-790 — installRuntimeArtifacts augment emits both commands and sk
});
});
describe('enh-790 — installRuntimeArtifacts does not leak temp dirs', () => {
test('install cleans up gsd-cmd-rewrites-* temp dirs (no leak) — #856', (t) => {
const { resolveProfile } = require('../gsd-core/bin/lib/install-profiles.cjs');
const RESOLVED_FULL = resolveProfile({ modes: ['full'], manifest: MANIFEST });
// Isolate os.tmpdir() to a private root so parallel test processes can't race
// on the shared system temp dir. os.tmpdir() resolves $TMPDIR/$TEMP/$TMP per call.
const isolatedTmp = createTempDir('gsd-enh790-tmproot-');
const prev = { TMPDIR: process.env.TMPDIR, TEMP: process.env.TEMP, TMP: process.env.TMP };
process.env.TMPDIR = isolatedTmp;
process.env.TEMP = isolatedTmp;
process.env.TMP = isolatedTmp;
const configDir = createTempDir('gsd-enh790-leak-');
t.after(() => {
for (const k of ['TMPDIR', 'TEMP', 'TMP']) {
if (prev[k] === undefined) delete process.env[k];
else process.env[k] = prev[k];
}
cleanup(configDir);
cleanup(isolatedTmp);
});
installRuntimeArtifacts('augment', configDir, 'global', RESOLVED_FULL);
// The install creates its gsd-cmd-rewrites-* temp dirs under the isolated root;
// after the fix none must remain.
const leaked = fs.readdirSync(isolatedTmp).filter(n => n.startsWith('gsd-cmd-rewrites-'));
assert.ok(
leaked.length === 0,
`installer must not leak gsd-cmd-rewrites-* temp dirs; leaked: ${leaked.join(', ')}`
);
});
});
// ─── Uninstall contract ──────────────────────────────────────────────────────
describe('enh-790 — uninstallRuntimeArtifacts removes augment commands', () => {

341
tests/io.test.cjs Normal file
View File

@@ -0,0 +1,341 @@
/**
* Tests for src/io.cts (compiled to gsd-core/bin/lib/io.cjs).
*
* Verifies behavioural contracts of the extracted CLI I/O primitives:
* - output() writes expected structure to stdout
* - error() writes expected structure to stderr and exits
* - ERROR_REASON constants have the correct wire values
* - setJsonErrorMode/getJsonErrorMode toggle behaviour
* - core.cjs re-export shims resolve to the exact same objects as io.cjs
*
* ADR-857 phase 1 / issue #859.
*/
const { test, describe, afterEach } = require('node:test');
const assert = require('node:assert/strict');
const { spawnSync } = require('node:child_process');
const path = require('node:path');
const os = require('node:os');
const fs = require('node:fs');
const io = require('../gsd-core/bin/lib/io.cjs');
const core = require('../gsd-core/bin/lib/core.cjs');
// ─── ERROR_REASON constants ───────────────────────────────────────────────────
describe('ERROR_REASON', () => {
test('is a frozen object', () => {
assert.ok(Object.isFrozen(io.ERROR_REASON));
});
test('contains expected wire values', () => {
assert.strictEqual(io.ERROR_REASON.CONFIG_KEY_NOT_FOUND, 'config_key_not_found');
assert.strictEqual(io.ERROR_REASON.CONFIG_NO_FILE, 'config_no_file');
assert.strictEqual(io.ERROR_REASON.CONFIG_PARSE_FAILED, 'config_parse_failed');
assert.strictEqual(io.ERROR_REASON.CONFIG_INVALID_KEY, 'config_invalid_key');
assert.strictEqual(io.ERROR_REASON.SDK_FAIL_FAST, 'sdk_fail_fast');
assert.strictEqual(io.ERROR_REASON.SDK_UNKNOWN_COMMAND, 'sdk_unknown_command');
assert.strictEqual(io.ERROR_REASON.SDK_MISSING_ARG, 'sdk_missing_arg');
assert.strictEqual(io.ERROR_REASON.PHASE_NOT_FOUND, 'phase_not_found');
assert.strictEqual(io.ERROR_REASON.SUMMARY_NO_PLANNING, 'summary_no_planning');
assert.strictEqual(io.ERROR_REASON.GRAPHIFY_NO_GRAPH, 'graphify_no_graph');
assert.strictEqual(io.ERROR_REASON.GRAPHIFY_INVALID_QUERY, 'graphify_invalid_query');
assert.strictEqual(io.ERROR_REASON.HOOKS_OPT_OUT, 'hooks_opt_out');
assert.strictEqual(io.ERROR_REASON.SECURITY_SCAN_FAILED, 'security_scan_failed');
assert.strictEqual(io.ERROR_REASON.USAGE, 'usage');
assert.strictEqual(io.ERROR_REASON.UNKNOWN, 'unknown');
});
});
// ─── setJsonErrorMode / getJsonErrorMode ─────────────────────────────────────
describe('setJsonErrorMode / getJsonErrorMode', () => {
// Reset to false after each test so other tests are unaffected
afterEach(() => {
io.setJsonErrorMode(false);
});
test('defaults to false', () => {
io.setJsonErrorMode(false); // ensure clean state
assert.strictEqual(io.getJsonErrorMode(), false);
});
test('setJsonErrorMode(true) enables JSON error mode', () => {
io.setJsonErrorMode(true);
assert.strictEqual(io.getJsonErrorMode(), true);
});
test('setJsonErrorMode(false) disables JSON error mode', () => {
io.setJsonErrorMode(true);
io.setJsonErrorMode(false);
assert.strictEqual(io.getJsonErrorMode(), false);
});
test('setJsonErrorMode coerces truthy values', () => {
io.setJsonErrorMode(1);
assert.strictEqual(io.getJsonErrorMode(), true);
io.setJsonErrorMode(0);
assert.strictEqual(io.getJsonErrorMode(), false);
});
test('setJsonErrorMode coerces string truthy', () => {
io.setJsonErrorMode('yes');
assert.strictEqual(io.getJsonErrorMode(), true);
io.setJsonErrorMode('');
assert.strictEqual(io.getJsonErrorMode(), false);
});
});
// ─── output() ────────────────────────────────────────────────────────────────
// output() writes directly to fd 1 and never calls process.exit, so we can
// test it by spawning a child process and capturing its stdout.
describe('output()', () => {
const ioPath = path.resolve(__dirname, '../gsd-core/bin/lib/io.cjs');
test('emits JSON-serialised result to stdout', () => {
const script = `
const io = require(${JSON.stringify(ioPath)});
io.output({ ok: true, value: 42 }, false);
`;
const result = spawnSync(process.execPath, ['-e', script], { encoding: 'utf-8' });
assert.strictEqual(result.status, 0, `process exited non-zero: ${result.stderr}`);
const parsed = JSON.parse(result.stdout);
assert.deepStrictEqual(parsed, { ok: true, value: 42 });
});
test('emits raw string value when raw=true and rawValue provided', () => {
const script = `
const io = require(${JSON.stringify(ioPath)});
io.output({ ignored: true }, true, 'raw-text-output');
`;
const result = spawnSync(process.execPath, ['-e', script], { encoding: 'utf-8' });
assert.strictEqual(result.status, 0, `process exited non-zero: ${result.stderr}`);
assert.strictEqual(result.stdout, 'raw-text-output');
});
test('falls back to JSON when raw=true but rawValue is undefined', () => {
const script = `
const io = require(${JSON.stringify(ioPath)});
io.output({ fallback: true }, true);
`;
const result = spawnSync(process.execPath, ['-e', script], { encoding: 'utf-8' });
assert.strictEqual(result.status, 0, `process exited non-zero: ${result.stderr}`);
const parsed = JSON.parse(result.stdout);
assert.deepStrictEqual(parsed, { fallback: true });
});
test('emits null correctly', () => {
const script = `
const io = require(${JSON.stringify(ioPath)});
io.output(null, false);
`;
const result = spawnSync(process.execPath, ['-e', script], { encoding: 'utf-8' });
assert.strictEqual(result.status, 0, `process exited non-zero: ${result.stderr}`);
assert.strictEqual(result.stdout, 'null');
});
test('large payload (>50000 chars) spills to @file: tempfile', (t) => {
// Build a payload whose serialized JSON exceeds 50000 chars.
// A string of 60000 'x' chars serializes to 60002 chars ("x...x").
const largeString = 'x'.repeat(60000);
const payload = { large: largeString };
const serialized = JSON.stringify(payload, null, 2);
assert.ok(serialized.length > 50000, 'precondition: payload must exceed 50000 chars');
const tmpFilesCreated = [];
t.after(() => {
for (const p of tmpFilesCreated) {
try { fs.unlinkSync(p); } catch { /* ignore */ }
}
});
const script = `
const io = require(${JSON.stringify(ioPath)});
const largeString = 'x'.repeat(60000);
io.output({ large: largeString }, false);
`;
const result = spawnSync(process.execPath, ['-e', script], { encoding: 'utf-8' });
assert.strictEqual(result.status, 0, `process exited non-zero: ${result.stderr}`);
const stdout = result.stdout.trim();
assert.ok(stdout.startsWith('@file:'), `expected stdout to start with "@file:", got: ${stdout.slice(0, 80)}`);
const tmpPath = stdout.slice('@file:'.length);
tmpFilesCreated.push(tmpPath);
assert.ok(fs.existsSync(tmpPath), `expected temp file to exist at: ${tmpPath}`);
const fileContents = fs.readFileSync(tmpPath, 'utf-8');
const parsed = JSON.parse(fileContents);
assert.deepStrictEqual(parsed, payload);
fs.unlinkSync(tmpPath);
tmpFilesCreated.length = 0; // already cleaned, skip t.after
});
});
// ─── error() ─────────────────────────────────────────────────────────────────
describe('error()', () => {
const ioPath = path.resolve(__dirname, '../gsd-core/bin/lib/io.cjs');
test('plain-text mode: writes "Error: <msg>" to stderr and exits 1', () => {
const script = `
const io = require(${JSON.stringify(ioPath)});
io.setJsonErrorMode(false);
io.error('something went wrong');
`;
const result = spawnSync(process.execPath, ['-e', script], { encoding: 'utf-8' });
assert.strictEqual(result.status, 1);
assert.ok(result.stderr.includes('Error: something went wrong'), `stderr was: ${result.stderr}`);
assert.strictEqual(result.stdout, '');
});
test('plain-text mode: default reason does not appear in stderr text', () => {
const script = `
const io = require(${JSON.stringify(ioPath)});
io.setJsonErrorMode(false);
io.error('no reason code expected');
`;
const result = spawnSync(process.execPath, ['-e', script], { encoding: 'utf-8' });
assert.strictEqual(result.status, 1);
// plain mode does NOT include the reason field
assert.ok(!result.stderr.includes('"reason"'), `stderr unexpectedly contained reason: ${result.stderr}`);
});
test('JSON-error mode: writes structured JSON to stderr and exits 1', () => {
const script = `
const io = require(${JSON.stringify(ioPath)});
io.setJsonErrorMode(true);
io.error('structured error', io.ERROR_REASON.SDK_FAIL_FAST);
`;
const result = spawnSync(process.execPath, ['-e', script], { encoding: 'utf-8' });
assert.strictEqual(result.status, 1);
assert.strictEqual(result.stdout, '');
const payload = JSON.parse(result.stderr.trim());
assert.strictEqual(payload.ok, false);
assert.strictEqual(payload.reason, 'sdk_fail_fast');
assert.strictEqual(payload.message, 'structured error');
});
test('JSON-error mode: defaults reason to UNKNOWN when not supplied', () => {
const script = `
const io = require(${JSON.stringify(ioPath)});
io.setJsonErrorMode(true);
io.error('no reason given');
`;
const result = spawnSync(process.execPath, ['-e', script], { encoding: 'utf-8' });
assert.strictEqual(result.status, 1);
const payload = JSON.parse(result.stderr.trim());
assert.strictEqual(payload.reason, 'unknown');
assert.strictEqual(payload.message, 'no reason given');
});
test('all ERROR_REASON values round-trip through JSON-error mode', () => {
// spot-check a few variants
const cases = [
['config_key_not_found', 'CONFIG_KEY_NOT_FOUND'],
['phase_not_found', 'PHASE_NOT_FOUND'],
['usage', 'USAGE'],
];
for (const [expected, key] of cases) {
const script = `
const io = require(${JSON.stringify(ioPath)});
io.setJsonErrorMode(true);
io.error('test', io.ERROR_REASON.${key});
`;
const result = spawnSync(process.execPath, ['-e', script], { encoding: 'utf-8' });
assert.strictEqual(result.status, 1, `key=${key}`);
const payload = JSON.parse(result.stderr.trim());
assert.strictEqual(payload.reason, expected, `key=${key}`);
}
});
});
// ─── GSD_TEMP_DIR / reapStaleTempFiles ───────────────────────────────────────
describe('GSD_TEMP_DIR', () => {
test('resolves to <tmpdir>/gsd', () => {
assert.strictEqual(io.GSD_TEMP_DIR, path.join(os.tmpdir(), 'gsd'));
});
});
describe('reapStaleTempFiles (via io)', () => {
const TEST_PREFIX = 'gsd-io-test-';
afterEach(() => {
// clean up any test files we created
try {
const entries = fs.readdirSync(io.GSD_TEMP_DIR);
for (const e of entries) {
if (e.startsWith(TEST_PREFIX)) {
const p = path.join(io.GSD_TEMP_DIR, e);
try { fs.unlinkSync(p); } catch { /* ignore */ }
}
}
} catch { /* ignore */ }
});
test('removes stale files beyond maxAgeMs', () => {
fs.mkdirSync(io.GSD_TEMP_DIR, { recursive: true });
const stalePath = path.join(io.GSD_TEMP_DIR, TEST_PREFIX + 'stale.json');
fs.writeFileSync(stalePath, '{}');
// backdate mtime so it looks older than 1ms
const old = new Date(Date.now() - 10000);
fs.utimesSync(stalePath, old, old);
io.reapStaleTempFiles(TEST_PREFIX, { maxAgeMs: 5000 });
assert.ok(!fs.existsSync(stalePath), 'stale file should have been removed');
});
test('keeps fresh files within maxAgeMs', () => {
fs.mkdirSync(io.GSD_TEMP_DIR, { recursive: true });
const freshPath = path.join(io.GSD_TEMP_DIR, TEST_PREFIX + 'fresh.json');
fs.writeFileSync(freshPath, '{}');
// mtime is just now — well within a 1-hour window
io.reapStaleTempFiles(TEST_PREFIX, { maxAgeMs: 60 * 60 * 1000 });
assert.ok(fs.existsSync(freshPath), 'fresh file should have been kept');
});
test('does not throw when GSD_TEMP_DIR does not exist yet', () => {
// reap against a non-existent prefix — must not throw
assert.doesNotThrow(() => {
io.reapStaleTempFiles('gsd-io-nonexistent-prefix-xyz-', { maxAgeMs: 0 });
});
});
});
// ─── core.cjs re-export shim parity ──────────────────────────────────────────
describe('core.cjs re-export shims', () => {
test('core.output is the same function as io.output', () => {
assert.strictEqual(core.output, io.output);
});
test('core.error is the same function as io.error', () => {
assert.strictEqual(core.error, io.error);
});
test('core.ERROR_REASON is the same object as io.ERROR_REASON', () => {
assert.strictEqual(core.ERROR_REASON, io.ERROR_REASON);
});
test('core.setJsonErrorMode is the same function as io.setJsonErrorMode', () => {
assert.strictEqual(core.setJsonErrorMode, io.setJsonErrorMode);
});
test('core.getJsonErrorMode is the same function as io.getJsonErrorMode', () => {
assert.strictEqual(core.getJsonErrorMode, io.getJsonErrorMode);
});
test('core.reapStaleTempFiles is the same function as io.reapStaleTempFiles', () => {
assert.strictEqual(core.reapStaleTempFiles, io.reapStaleTempFiles);
});
test('core.GSD_TEMP_DIR is the same value as io.GSD_TEMP_DIR', () => {
assert.strictEqual(core.GSD_TEMP_DIR, io.GSD_TEMP_DIR);
});
});

View File

@@ -0,0 +1,201 @@
'use strict';
// Issue #57 — Runtime Install No-Drift Tests.
//
// Protects the Runtime Install Policy Module boundary (ADR-58) and the explicit
// Runtime Config Adapter Registry (#60) now that the policy boundary (#58),
// explicit adapter registry (#60), and legacy directory-helper retirement (#56)
// have landed. These guards FAIL when:
//
// (AC1) supported-runtime metadata is added to an installer/query call site
// without going through the runtime registry projection, or
// (AC2) config-mutation dispatch bypasses the explicit adapter registry.
//
// (AC3) Assertions are behavioral (require + reflect on live exports) wherever
// behavior can cover the contract; the two source-text assertions are structural
// guards that behavioral checks cannot replace, and are annotated per repo
// convention. (AC4) The existing installer / runtime-policy / runtime-global-skills
// suites must stay green — verified by running them alongside this file, not
// asserted here.
//
// Known INTENTIONAL asymmetries — these are not drift; do not "fix" them by
// tightening the invariants:
// - `grok` appears in runtime-homes.cjs's getGlobalConfigDir switch but NOT in
// the registry / artifact-layout supported sets (it resolves a config-dir home
// but is not an installable artifact target). So runtime-homes' full switch set
// is never tied into the equality invariant — it is only probed forward, per
// installable runtime.
// - getGlobalConfigDir() falls back to ~/.claude for an UNKNOWN runtime instead
// of throwing (a deliberately liberal projection). Only the registry and
// artifact-layout projections are loud gates, so only those are asserted to
// throw on an unknown runtime.
//
// Coverage boundary (deliberate, see #57 follow-up): the structural guard below
// catches a NEW inline `runtime === '...'` branch against an UNREGISTERED runtime.
// It cannot catch a duplicate inline config write added for an ALREADY-registered
// runtime — distinguishing that from the ~169 legitimate per-runtime comparisons in
// the installer requires driving install()/finishInstall() against a mocked
// filesystem and asserting the written surfaces match resolveRuntimeConfigIntent().
// That behavioral install-driver harness is out of scope for this no-drift pass.
//
// The forward invariant `allRuntimes ⊆ artifact-layout` is already covered by
// tests/install-runtime-artifacts.test.cjs; this file does not duplicate it.
process.env.GSD_TEST_MODE = '1'; // must precede require of bin/install.js
const { describe, test } = 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 ROOT = path.join(__dirname, '..');
const LIB = path.join(ROOT, 'gsd-core', 'bin', 'lib');
const { allRuntimes, runtimeMap } = require(path.join(ROOT, 'bin', 'install.js'));
const {
resolveRuntimeConfigIntent,
ALLOWED_CONFIG_RUNTIMES,
INSTALL_SURFACES,
} = require(path.join(LIB, 'runtime-config-adapter-registry.cjs'));
const { resolveRuntimeArtifactLayout } = require(
path.join(LIB, 'runtime-artifact-layout.cjs'),
);
const { getGlobalConfigDir } = require(path.join(LIB, 'runtime-homes.cjs'));
const sorted = (iterable) => [...iterable].sort();
// A runtime name that is deliberately not real and is not a prototype-chain key.
const SENTINEL = '__drift_sentinel_runtime__';
describe('issue-57 AC1 — supported-runtime metadata has one projected source of truth', () => {
test('installer allRuntimes, interactive runtimeMap, and registry agree on the supported set', () => {
const installable = sorted(allRuntimes);
assert.deepStrictEqual(
installable,
sorted(Object.values(runtimeMap)),
'Drift: bin/install.js `allRuntimes` and the interactive `runtimeMap` selection menu '
+ 'diverged. A runtime selectable in the prompt but absent from allRuntimes (or vice '
+ 'versa) is a supported-runtime call site that skipped the projection.',
);
assert.deepStrictEqual(
installable,
sorted(ALLOWED_CONFIG_RUNTIMES),
'Drift: bin/install.js `allRuntimes` and `ALLOWED_CONFIG_RUNTIMES` (runtime config '
+ 'adapter registry) diverged. A runtime added to an installer call site without a '
+ 'registry adapter entry bypasses the registry projection — register it in '
+ 'src/runtime-config-adapter-registry.cts.',
);
});
test('every installable runtime resolves a config intent through the registry', () => {
for (const runtime of allRuntimes) {
const intent = resolveRuntimeConfigIntent(runtime);
assert.equal(
intent.runtime,
runtime,
`${runtime} must resolve its own config intent through resolveRuntimeConfigIntent`,
);
}
});
test('every installable runtime resolves a global config dir through runtime-homes', () => {
for (const runtime of allRuntimes) {
const dir = getGlobalConfigDir(runtime);
assert.equal(typeof dir, 'string', `${runtime} config dir must be a string`);
assert.ok(dir.length > 0, `${runtime} must resolve a non-empty global config dir`);
}
});
});
describe('issue-57 AC2 — config-mutation dispatch is closed over the explicit registry', () => {
test('every config intent uses a registry-declared install surface', () => {
const surfaces = new Set(INSTALL_SURFACES);
for (const runtime of allRuntimes) {
const { installSurface } = resolveRuntimeConfigIntent(runtime);
assert.ok(
surfaces.has(installSurface),
`${runtime} dispatches config via unregistered surface "${installSurface}" — add it `
+ 'to INSTALL_SURFACES in the registry instead of branching on it inline.',
);
}
});
test('every finishInstall permission writer is null or a registry-known runtime', () => {
// Registry-derived (no hand-maintained vocabulary): a permission writer either
// names a runtime that is itself in the registry, or is null. A writer pointing
// at an unregistered runtime would mean finishInstall dispatches a config mutation
// outside the registry's known set.
for (const runtime of allRuntimes) {
const { finishPermissionWriter } = resolveRuntimeConfigIntent(runtime);
assert.ok(
finishPermissionWriter === null || ALLOWED_CONFIG_RUNTIMES.has(finishPermissionWriter),
`${runtime} uses finishPermissionWriter "${finishPermissionWriter}", which is neither `
+ 'null nor a registry-known runtime — route it through a registered adapter.',
);
}
});
test('unknown runtime fails loudly through both strict projections (no silent fallthrough)', () => {
assert.throws(
() => resolveRuntimeConfigIntent(SENTINEL),
TypeError,
'config adapter registry must reject an unknown runtime, not dispatch it silently',
);
assert.throws(
() => resolveRuntimeArtifactLayout(SENTINEL, path.join(os.tmpdir(), 'gsd-57'), 'global'),
TypeError,
'artifact-layout projection must reject an unknown runtime',
);
});
test('registry rejects prototype-chain keys (no proto-pollution dispatch bypass)', () => {
for (const key of ['__proto__', 'constructor', 'prototype', 'toString']) {
assert.throws(
() => resolveRuntimeConfigIntent(key),
TypeError,
`${key} must throw, not resolve via the prototype chain`,
);
}
});
// allow-test-rule: structural guard over bin/install.js source. Behavioral assertions
// cannot observe inline `runtime === '...'` config branching, so this enforces that
// every inline per-runtime branch references a runtime the adapter registry knows
// about — a NEW branch against an unregistered runtime name fails here. It matches
// positive equality only (`runtime === '<name>'` / `runtime === "<name>"`, both quote
// styles), so `runtime !== 'string'`-style type guards are not implicated. See the
// "coverage boundary" note at the top of the file for what this can and cannot catch.
test('every inline `runtime === "..."` branch references a registry-known runtime', () => {
const src = fs.readFileSync(path.join(ROOT, 'bin', 'install.js'), 'utf8');
const literals = new Set(
[...src.matchAll(/runtime === (?:'([a-z][a-z0-9-]*)'|"([a-z][a-z0-9-]*)")/g)]
.map((m) => m[1] ?? m[2]),
);
assert.ok(literals.size > 0, 'expected to find inline runtime comparisons in bin/install.js');
const unregistered = [...literals].filter((r) => !ALLOWED_CONFIG_RUNTIMES.has(r));
assert.deepStrictEqual(
unregistered,
[],
`inline 'runtime === "..."' branch(es) reference runtimes absent from the config adapter `
+ `registry: ${unregistered.join(', ')} — register them in `
+ 'src/runtime-config-adapter-registry.cts or route the logic through '
+ 'resolveRuntimeConfigIntent instead of branching inline.',
);
});
// allow-test-rule: delegation-presence guard. Catches wholesale removal of the registry
// dispatch (a regression to scattered per-runtime config branching). Presence-style, not
// absence-grep, so it does not bite on incidental non-config `runtime === '...'` checks.
test('bin/install.js requires the config adapter registry and dispatches through it', () => {
const src = fs.readFileSync(path.join(ROOT, 'bin', 'install.js'), 'utf8');
assert.ok(
src.includes('runtime-config-adapter-registry'),
'bin/install.js no longer requires the runtime config adapter registry',
);
assert.ok(
src.includes('resolveRuntimeConfigIntent('),
'bin/install.js no longer dispatches config through resolveRuntimeConfigIntent',
);
});
});

429
tests/phase-id.test.cjs Normal file
View File

@@ -0,0 +1,429 @@
/**
* Tests for src/phase-id.cts (compiled to gsd-core/bin/lib/phase-id.cjs).
*
* Verifies behavioural contracts of the extracted pure phase-id helpers:
* - escapeRegex
* - normalizePhaseName
* - comparePhaseNum
* - extractPhaseToken
* - phaseTokenMatches
* - phaseMarkdownRegexSource
* - phaseMarkdownRegexSourceExact
* - getMilestoneFromPhaseId
* - getPhaseDirFromPhaseId
* - core.cjs re-export shims resolve to the exact same functions (single instance)
*
* ADR-857 rollout phase 2a / issue #865.
*/
'use strict';
const { test, describe } = require('node:test');
const assert = require('node:assert/strict');
const phaseId = require('../gsd-core/bin/lib/phase-id.cjs');
const core = require('../gsd-core/bin/lib/core.cjs');
// ─── escapeRegex ─────────────────────────────────────────────────────────────
describe('escapeRegex', () => {
test('escapes all regex special characters', () => {
assert.strictEqual(phaseId.escapeRegex('.'), '\\.');
assert.strictEqual(phaseId.escapeRegex('*'), '\\*');
assert.strictEqual(phaseId.escapeRegex('+'), '\\+');
assert.strictEqual(phaseId.escapeRegex('?'), '\\?');
assert.strictEqual(phaseId.escapeRegex('^'), '\\^');
assert.strictEqual(phaseId.escapeRegex('$'), '\\$');
assert.strictEqual(phaseId.escapeRegex('{'), '\\{');
assert.strictEqual(phaseId.escapeRegex('}'), '\\}');
assert.strictEqual(phaseId.escapeRegex('('), '\\(');
assert.strictEqual(phaseId.escapeRegex(')'), '\\)');
assert.strictEqual(phaseId.escapeRegex('|'), '\\|');
assert.strictEqual(phaseId.escapeRegex('['), '\\[');
assert.strictEqual(phaseId.escapeRegex(']'), '\\]');
assert.strictEqual(phaseId.escapeRegex('\\'), '\\\\');
});
test('leaves alphanumeric and hyphen characters unescaped', () => {
assert.strictEqual(phaseId.escapeRegex('abc'), 'abc');
assert.strictEqual(phaseId.escapeRegex('01-02'), '01-02');
assert.strictEqual(phaseId.escapeRegex('v1.0'), 'v1\\.0');
});
test('coerces non-string values via String()', () => {
assert.strictEqual(phaseId.escapeRegex(42), '42');
assert.strictEqual(phaseId.escapeRegex(null), 'null');
assert.strictEqual(phaseId.escapeRegex(undefined), 'undefined');
});
test('adversarial: path-traversal-like inputs are treated as literals', () => {
const result = phaseId.escapeRegex('../../../etc/passwd');
// The dots get escaped; slashes and alphanumeric pass through unchanged
assert.strictEqual(result, '\\.\\./\\.\\./\\.\\./etc/passwd');
// The result forms a valid regex (no throws)
assert.doesNotThrow(() => new RegExp(result));
});
test('unicode passthrough', () => {
assert.strictEqual(phaseId.escapeRegex('Phase Name'), 'Phase Name');
assert.strictEqual(phaseId.escapeRegex('中文'), '中文');
});
});
// ─── normalizePhaseName ───────────────────────────────────────────────────────
describe('normalizePhaseName', () => {
test('zero-pads single-digit phase', () => {
assert.strictEqual(phaseId.normalizePhaseName('1'), '01');
assert.strictEqual(phaseId.normalizePhaseName('3'), '03');
});
test('leaves two-digit phase unchanged', () => {
assert.strictEqual(phaseId.normalizePhaseName('12'), '12');
});
test('strips project_code prefix before normalizing', () => {
assert.strictEqual(phaseId.normalizePhaseName('CK-01'), '01');
assert.strictEqual(phaseId.normalizePhaseName('PROJ-3'), '03');
assert.strictEqual(phaseId.normalizePhaseName('AB-12'), '12');
});
test('handles letter suffix (preserves original case per #1962)', () => {
assert.strictEqual(phaseId.normalizePhaseName('12A'), '12A');
assert.strictEqual(phaseId.normalizePhaseName('3b'), '03b');
});
test('handles decimal phase IDs', () => {
assert.strictEqual(phaseId.normalizePhaseName('12.1'), '12.1');
assert.strictEqual(phaseId.normalizePhaseName('3.10'), '03.10');
});
test('handles milestone-prefixed IDs (M-NN form)', () => {
assert.strictEqual(phaseId.normalizePhaseName('1-1'), '01-01');
assert.strictEqual(phaseId.normalizePhaseName('2-3'), '02-03');
assert.strictEqual(phaseId.normalizePhaseName('1-2-3'), '01-02-03');
});
test('custom phase IDs: project_code prefix is stripped, then numeric part is normalized', () => {
// The regex /^[A-Z]{1,6}-(?=\d)/ matches 'PROJ-' and strips it, leaving '42'
// which is then normalized to '42' (no leading zero needed for 2+ digits)
assert.strictEqual(phaseId.normalizePhaseName('PROJ-42'), '42');
assert.strictEqual(phaseId.normalizePhaseName('AUTH-101'), '101');
});
test('custom phase IDs with non-numeric remainder pass through as-is', () => {
// No project_code pattern, no numeric match → return str as-is
assert.strictEqual(phaseId.normalizePhaseName('my-phase'), 'my-phase');
});
test('coerces non-string values', () => {
assert.strictEqual(phaseId.normalizePhaseName(5), '05');
});
});
// ─── comparePhaseNum ──────────────────────────────────────────────────────────
describe('comparePhaseNum', () => {
test('sorts numeric phases in ascending order', () => {
const phases = ['03', '01', '10', '02'];
const sorted = [...phases].sort(phaseId.comparePhaseNum);
assert.deepStrictEqual(sorted, ['01', '02', '03', '10']);
});
test('compares single-digit vs two-digit correctly', () => {
assert.ok(phaseId.comparePhaseNum('1', '02') < 0);
assert.ok(phaseId.comparePhaseNum('02', '1') > 0);
assert.strictEqual(phaseId.comparePhaseNum('1', '01'), 0);
});
test('handles decimal phases', () => {
assert.ok(phaseId.comparePhaseNum('1', '1.1') < 0);
assert.ok(phaseId.comparePhaseNum('1.1', '1.2') < 0);
assert.ok(phaseId.comparePhaseNum('1.10', '1.9') > 0);
assert.strictEqual(phaseId.comparePhaseNum('1.1', '01.1'), 0);
});
test('handles letter suffix ordering (no letter < A < B)', () => {
assert.ok(phaseId.comparePhaseNum('01', '01A') < 0);
assert.ok(phaseId.comparePhaseNum('01A', '01B') < 0);
assert.ok(phaseId.comparePhaseNum('01B', '01') > 0);
});
test('handles milestone-prefixed IDs', () => {
assert.ok(phaseId.comparePhaseNum('1-1', '1-2') < 0);
assert.ok(phaseId.comparePhaseNum('2-1', '1-10') > 0);
assert.ok(phaseId.comparePhaseNum('1-2-3', '1-2-4') < 0);
assert.strictEqual(phaseId.comparePhaseNum('01-01', '1-1'), 0);
});
test('strips project_code prefix before comparing', () => {
assert.strictEqual(phaseId.comparePhaseNum('CK-01', '01'), 0);
assert.ok(phaseId.comparePhaseNum('CK-01', 'CK-02') < 0);
});
test('handles non-parseable phase IDs via localeCompare fallback', () => {
// Should not throw on non-numeric IDs
const result = phaseId.comparePhaseNum('alpha', 'beta');
assert.strictEqual(typeof result, 'number');
});
});
// ─── extractPhaseToken ────────────────────────────────────────────────────────
describe('extractPhaseToken', () => {
test('extracts simple numeric token from directory name', () => {
assert.strictEqual(phaseId.extractPhaseToken('01-some-phase-name'), '01');
assert.strictEqual(phaseId.extractPhaseToken('12A-feature'), '12A');
});
test('extracts milestone-prefixed numeric token', () => {
assert.strictEqual(phaseId.extractPhaseToken('01-02-some-name'), '01-02');
assert.strictEqual(phaseId.extractPhaseToken('02-03-04-deep'), '02-03-04');
});
test('extracts token with project_code prefix', () => {
assert.strictEqual(phaseId.extractPhaseToken('CK-01-some-phase'), 'CK-01');
assert.strictEqual(phaseId.extractPhaseToken('PROJ-12-feature'), 'PROJ-12');
});
test('returns the full dirName when no numeric token found', () => {
assert.strictEqual(phaseId.extractPhaseToken('no-numeric'), 'no-numeric');
assert.strictEqual(phaseId.extractPhaseToken('alpha'), 'alpha');
});
test('stops at first non-numeric-starting segment', () => {
assert.strictEqual(phaseId.extractPhaseToken('01-02-name-03'), '01-02');
});
});
// ─── phaseTokenMatches ────────────────────────────────────────────────────────
describe('phaseTokenMatches', () => {
test('matches exact token (case-insensitive)', () => {
assert.ok(phaseId.phaseTokenMatches('01-some-phase', '01'));
assert.ok(phaseId.phaseTokenMatches('12A-feature', '12A'));
assert.ok(phaseId.phaseTokenMatches('12A-feature', '12a'));
});
test('matches with project_code prefix stripped', () => {
assert.ok(phaseId.phaseTokenMatches('CK-01-phase', '01'));
assert.ok(phaseId.phaseTokenMatches('PROJ-12-feature', '12'));
});
test('does not match when token differs', () => {
assert.ok(!phaseId.phaseTokenMatches('01-some-phase', '02'));
assert.ok(!phaseId.phaseTokenMatches('12A-feature', '12B'));
});
test('matches milestone-prefixed token', () => {
assert.ok(phaseId.phaseTokenMatches('01-02-feature', '01-02'));
assert.ok(!phaseId.phaseTokenMatches('01-02-feature', '01-03'));
});
});
// ─── phaseMarkdownRegexSource ─────────────────────────────────────────────────
describe('phaseMarkdownRegexSource', () => {
test('produces a regex source that matches zero-padded variants', () => {
const src = phaseId.phaseMarkdownRegexSource('1');
const re = new RegExp(src);
assert.ok(re.test('1'));
assert.ok(re.test('01'));
assert.ok(re.test('001'));
});
test('produces source matching a two-digit phase', () => {
const src = phaseId.phaseMarkdownRegexSource('12');
const re = new RegExp(src);
assert.ok(re.test('12'));
assert.ok(re.test('012'));
assert.ok(!re.test('13'));
});
test('handles letter suffix', () => {
const src = phaseId.phaseMarkdownRegexSource('12A');
const re = new RegExp(src, 'i');
assert.ok(re.test('12A'));
assert.ok(re.test('012A'));
});
test('handles decimal phases', () => {
const src = phaseId.phaseMarkdownRegexSource('3.1');
const re = new RegExp(src);
assert.ok(re.test('3.1'));
assert.ok(re.test('03.1'));
assert.ok(!re.test('3.2'));
});
test('handles milestone-prefixed phase IDs', () => {
const src = phaseId.phaseMarkdownRegexSource('1-2');
const re = new RegExp(src);
assert.ok(re.test('1-2'));
assert.ok(re.test('01-02'));
assert.ok(re.test('01-2'));
assert.ok(!re.test('1-3'));
});
test('strips project_code prefix before building regex', () => {
const withPrefix = phaseId.phaseMarkdownRegexSource('CK-01');
const withoutPrefix = phaseId.phaseMarkdownRegexSource('01');
assert.strictEqual(withPrefix, withoutPrefix);
});
test('falls back to escaped literal for unparseable input', () => {
const src = phaseId.phaseMarkdownRegexSource('v1.0');
assert.strictEqual(typeof src, 'string');
assert.ok(src.length > 0);
});
test('adversarial: phase num containing regex metacharacters is escaped', () => {
// e.g. some exotic value that shouldn't break regexp construction
const src = phaseId.phaseMarkdownRegexSource('3.1');
// The literal dot in "3.1" should be escaped so it only matches a real dot
const re = new RegExp(src);
assert.ok(!re.test('3X1'), 'unescaped dot would match any char — must be escaped');
});
});
// ─── phaseMarkdownRegexSourceExact ────────────────────────────────────────────
describe('phaseMarkdownRegexSourceExact', () => {
test('returns escaped form for project-code-prefixed IDs', () => {
const result = phaseId.phaseMarkdownRegexSourceExact('PROJ-42');
// hyphen is not a regex special char so it passes through unescaped
assert.strictEqual(result, 'PROJ-42');
// The result is a valid regex source
assert.doesNotThrow(() => new RegExp(result));
});
test('returns null for non-prefixed IDs', () => {
assert.strictEqual(phaseId.phaseMarkdownRegexSourceExact('01'), null);
assert.strictEqual(phaseId.phaseMarkdownRegexSourceExact('12A'), null);
assert.strictEqual(phaseId.phaseMarkdownRegexSourceExact('1-2'), null);
});
test('null coercion: returns null for null/undefined', () => {
assert.strictEqual(phaseId.phaseMarkdownRegexSourceExact(null), null);
assert.strictEqual(phaseId.phaseMarkdownRegexSourceExact(undefined), null);
});
test('resulting regex matches the exact prefixed ID', () => {
const src = phaseId.phaseMarkdownRegexSourceExact('AUTH-101');
assert.ok(src !== null);
const re = new RegExp(src);
assert.ok(re.test('AUTH-101'));
assert.ok(!re.test('AUTH-102'));
});
});
// ─── getMilestoneFromPhaseId ──────────────────────────────────────────────────
describe('getMilestoneFromPhaseId', () => {
test('returns vN.0 for a milestone-prefixed phase id', () => {
assert.strictEqual(phaseId.getMilestoneFromPhaseId('1-01'), 'v1.0');
assert.strictEqual(phaseId.getMilestoneFromPhaseId('02-03'), 'v2.0');
assert.strictEqual(phaseId.getMilestoneFromPhaseId('10-5'), 'v10.0');
});
test('returns null for non-milestone-prefixed IDs', () => {
assert.strictEqual(phaseId.getMilestoneFromPhaseId('01'), null);
assert.strictEqual(phaseId.getMilestoneFromPhaseId('12A'), null);
});
test('returns null for special sentinel milestones 0 and 999', () => {
assert.strictEqual(phaseId.getMilestoneFromPhaseId('0-1'), null);
assert.strictEqual(phaseId.getMilestoneFromPhaseId('999-1'), null);
});
test('strips project_code prefix before parsing', () => {
assert.strictEqual(phaseId.getMilestoneFromPhaseId('CK-2-01'), 'v2.0');
});
test('coerces non-string values', () => {
// numeric doesn't match the milestone pattern — returns null
assert.strictEqual(phaseId.getMilestoneFromPhaseId(42), null);
});
});
// ─── getPhaseDirFromPhaseId ───────────────────────────────────────────────────
describe('getPhaseDirFromPhaseId', () => {
test('returns null for non-milestone-format IDs', () => {
assert.strictEqual(phaseId.getPhaseDirFromPhaseId('01', null, null), null);
assert.strictEqual(phaseId.getPhaseDirFromPhaseId('12A', null, null), null);
});
test('constructs dir name from milestone-prefixed phase id (no name, no code)', () => {
const result = phaseId.getPhaseDirFromPhaseId('1-2', null, null);
assert.strictEqual(result, '01-02');
});
test('includes phaseName slug', () => {
const result = phaseId.getPhaseDirFromPhaseId('1-2', 'My Feature', null);
assert.strictEqual(result, '01-02-my-feature');
});
test('prepends projectCode when provided', () => {
const result = phaseId.getPhaseDirFromPhaseId('1-2', 'Auth', 'CK');
assert.strictEqual(result, 'CK-01-02-auth');
});
test('strips project_code from phaseId before parsing', () => {
const result = phaseId.getPhaseDirFromPhaseId('CK-1-2', null, null);
assert.strictEqual(result, '01-02');
});
test('handles deep decomposition IDs (M-N-N)', () => {
// m[2] is "02-03" for input "1-2-3" — split and pad each sub-part
const result = phaseId.getPhaseDirFromPhaseId('1-2-3', null, null);
assert.strictEqual(result, '01-02-03');
});
test('slug strips leading/trailing hyphens from phaseName', () => {
const result = phaseId.getPhaseDirFromPhaseId('1-1', ' --some--name-- ', null);
// normalize: replace non-alnum runs with hyphen, strip edges
assert.ok(result !== null);
assert.ok(!result.startsWith('-'));
assert.ok(!result.endsWith('-'));
});
});
// ─── core.cjs re-export shim identity assertions ──────────────────────────────
describe('core.cjs re-export shim identity (single instance)', () => {
test('core.escapeRegex === phaseId.escapeRegex', () => {
assert.strictEqual(core.escapeRegex, phaseId.escapeRegex);
});
test('core.normalizePhaseName === phaseId.normalizePhaseName', () => {
assert.strictEqual(core.normalizePhaseName, phaseId.normalizePhaseName);
});
test('core.comparePhaseNum === phaseId.comparePhaseNum', () => {
assert.strictEqual(core.comparePhaseNum, phaseId.comparePhaseNum);
});
test('core.extractPhaseToken === phaseId.extractPhaseToken', () => {
assert.strictEqual(core.extractPhaseToken, phaseId.extractPhaseToken);
});
test('core.phaseTokenMatches === phaseId.phaseTokenMatches', () => {
assert.strictEqual(core.phaseTokenMatches, phaseId.phaseTokenMatches);
});
test('core.phaseMarkdownRegexSource === phaseId.phaseMarkdownRegexSource', () => {
assert.strictEqual(core.phaseMarkdownRegexSource, phaseId.phaseMarkdownRegexSource);
});
test('core.phaseMarkdownRegexSourceExact === phaseId.phaseMarkdownRegexSourceExact', () => {
assert.strictEqual(core.phaseMarkdownRegexSourceExact, phaseId.phaseMarkdownRegexSourceExact);
});
test('core.getMilestoneFromPhaseId === phaseId.getMilestoneFromPhaseId', () => {
assert.strictEqual(core.getMilestoneFromPhaseId, phaseId.getMilestoneFromPhaseId);
});
test('core.getPhaseDirFromPhaseId === phaseId.getPhaseDirFromPhaseId', () => {
assert.strictEqual(core.getPhaseDirFromPhaseId, phaseId.getPhaseDirFromPhaseId);
});
});

View File

@@ -0,0 +1,562 @@
/**
* roadmap-parser.cjs — unit tests
*
* Covers the 6 functions extracted from core.cjs per ADR-857 rollout
* phase 2b (#870): stripShippedMilestones, extractCurrentMilestone,
* replaceInCurrentMilestone, getRoadmapPhaseInternal, getMilestoneInfo,
* getMilestonePhaseFilter.
*
* Includes:
* - Behavioral tests against realistic ROADMAP.md content
* - Adversarial fixtures (malformed frontmatter, unclosed fences,
* headings inside fences, unicode headings, repeated/decimal phase
* IDs, mixed CRLF/LF)
* - Shim-identity assertions verifying core.cjs re-exports are the
* same function objects as roadmap-parser.cjs exports
*/
'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 roadmapParser = require('../gsd-core/bin/lib/roadmap-parser.cjs');
const core = require('../gsd-core/bin/lib/core.cjs');
const { createTempProject, cleanup } = require('./helpers.cjs');
const {
stripShippedMilestones,
extractCurrentMilestone,
replaceInCurrentMilestone,
getRoadmapPhaseInternal,
getMilestoneInfo,
getMilestonePhaseFilter,
} = roadmapParser;
// ─── helpers ─────────────────────────────────────────────────────────────────
function writeRoadmap(tmpDir, content) {
fs.writeFileSync(path.join(tmpDir, '.planning', 'ROADMAP.md'), content);
}
function writeState(tmpDir, fields) {
const lines = Object.entries(fields).map(([k, v]) => `${k}: ${v}`);
fs.writeFileSync(path.join(tmpDir, '.planning', 'STATE.md'), lines.join('\n') + '\n');
}
// ─── Shim-identity assertions ─────────────────────────────────────────────────
describe('roadmap-parser: shim-identity — core.cjs re-exports same function objects', () => {
test('core.extractCurrentMilestone === roadmapParser.extractCurrentMilestone', () => {
assert.strictEqual(core.extractCurrentMilestone, roadmapParser.extractCurrentMilestone);
});
test('core.stripShippedMilestones === roadmapParser.stripShippedMilestones', () => {
assert.strictEqual(core.stripShippedMilestones, roadmapParser.stripShippedMilestones);
});
test('core.replaceInCurrentMilestone === roadmapParser.replaceInCurrentMilestone', () => {
assert.strictEqual(core.replaceInCurrentMilestone, roadmapParser.replaceInCurrentMilestone);
});
test('core.getRoadmapPhaseInternal === roadmapParser.getRoadmapPhaseInternal', () => {
assert.strictEqual(core.getRoadmapPhaseInternal, roadmapParser.getRoadmapPhaseInternal);
});
test('core.getMilestoneInfo === roadmapParser.getMilestoneInfo', () => {
assert.strictEqual(core.getMilestoneInfo, roadmapParser.getMilestoneInfo);
});
test('core.getMilestonePhaseFilter === roadmapParser.getMilestonePhaseFilter', () => {
assert.strictEqual(core.getMilestonePhaseFilter, roadmapParser.getMilestonePhaseFilter);
});
});
// ─── stripShippedMilestones ───────────────────────────────────────────────────
describe('roadmap-parser: stripShippedMilestones', () => {
test('strips a single <details> block', () => {
const input = 'before\n<details>\nsome shipped content\n</details>\nafter';
const result = stripShippedMilestones(input);
assert.ok(!result.includes('<details>'), 'details tag should be removed');
assert.ok(!result.includes('shipped content'), 'shipped content should be removed');
assert.ok(result.includes('before'), 'before content preserved');
assert.ok(result.includes('after'), 'after content preserved');
});
test('strips multiple <details> blocks', () => {
const input = '<details>\nA\n</details>\nmiddle\n<details>\nB\n</details>\nend';
const result = stripShippedMilestones(input);
assert.ok(result.includes('middle'), 'middle content preserved');
assert.ok(result.includes('end'), 'end content preserved');
assert.ok(!result.includes('<details>'), 'all details tags removed');
});
test('returns unchanged string when no <details> blocks', () => {
const input = '## v1.0: Launch\n### Phase 1: Setup\n**Goal:** init\n';
assert.strictEqual(stripShippedMilestones(input), input);
});
test('handles case-insensitive <DETAILS> tags', () => {
const input = '<DETAILS>\nclosed content\n</DETAILS>\nafter';
const result = stripShippedMilestones(input);
assert.ok(!result.includes('closed content'), 'content removed');
assert.ok(result.includes('after'), 'after content preserved');
});
});
// ─── extractCurrentMilestone ──────────────────────────────────────────────────
describe('roadmap-parser: extractCurrentMilestone', () => {
let tmpDir;
beforeEach(() => { tmpDir = createTempProject(); });
afterEach(() => { cleanup(tmpDir); });
test('no cwd — strips <details> only', () => {
const input = '<details>\nshipped\n</details>\n## v2.0: Next\n### Phase 1: Setup\n';
const result = extractCurrentMilestone(input);
assert.ok(!result.includes('<details>'), 'details stripped');
assert.ok(result.includes('v2.0'), 'version heading preserved');
});
test('reads milestone from STATE.md and extracts that section', () => {
writeState(tmpDir, { milestone: 'v2.0' });
const content = [
'<details>',
'<summary>v1.0</summary>',
'### Phase 1: Old',
'</details>',
'## v2.0: Current',
'### Phase 2-01: Setup',
'**Goal:** build',
].join('\n');
writeRoadmap(tmpDir, content);
const roadmap = fs.readFileSync(path.join(tmpDir, '.planning', 'ROADMAP.md'), 'utf-8');
const result = extractCurrentMilestone(roadmap, tmpDir);
assert.ok(result.includes('v2.0'), 'current milestone section included');
assert.ok(!result.includes('Old'), 'shipped milestone section excluded');
});
test('falls back to 🚧 marker when STATE.md has no milestone field', () => {
writeState(tmpDir, { phase: 'some-phase' });
const content = [
'## 🚧 **v2.0 Work in Progress**',
'### Phase 1: Active',
'**Goal:** do work',
].join('\n');
writeRoadmap(tmpDir, content);
const roadmap = fs.readFileSync(path.join(tmpDir, '.planning', 'ROADMAP.md'), 'utf-8');
const result = extractCurrentMilestone(roadmap, tmpDir);
assert.ok(result.includes('v2.0'), 'inferred v2.0 milestone section included');
});
test('strips shipped milestones when no STATE.md and no 🚧 marker', () => {
const content = [
'<details>',
'<summary>v1.0 done</summary>',
'### Phase 1: Done',
'</details>',
'## v2.0: Next (no WIP marker)',
'### Phase 2: Future',
].join('\n');
const result = extractCurrentMilestone(content);
assert.ok(!result.includes('<details>'), 'details stripped');
assert.ok(result.includes('v2.0'), 'remaining content preserved');
});
test('unicode heading — emoji-prefixed milestone', () => {
writeState(tmpDir, { milestone: 'v3.0' });
const content = [
'## ✅ v1.0: Shipped',
'## 🚧 v3.0: In Progress',
'### Phase 3-01: Unicode Héros',
'**Goal:** тест',
].join('\n');
writeRoadmap(tmpDir, content);
const roadmap = fs.readFileSync(path.join(tmpDir, '.planning', 'ROADMAP.md'), 'utf-8');
const result = extractCurrentMilestone(roadmap, tmpDir);
assert.ok(result.includes('v3.0'), 'v3.0 heading included');
assert.ok(result.includes('Unicode'), 'unicode phase name included');
});
test('CRLF line endings are handled', () => {
writeState(tmpDir, { milestone: 'v1.0' });
const content = '## v1.0: CRLF\r\n### Phase 1: Setup\r\n**Goal:** crlf goal\r\n';
writeRoadmap(tmpDir, content);
const roadmap = fs.readFileSync(path.join(tmpDir, '.planning', 'ROADMAP.md'), 'utf-8');
const result = extractCurrentMilestone(roadmap, tmpDir);
assert.ok(result.includes('v1.0'), 'section found despite CRLF');
});
test('heading inside fenced code block not confused for milestone boundary', () => {
writeState(tmpDir, { milestone: 'v1.0' });
const content = [
'## v1.0: Current Milestone',
'### Phase 1: Real Phase',
'**Goal:** real goal',
'```markdown',
'## v2.0: Fake Heading Inside Fence',
'```',
'### Phase 2: Also Real',
'**Goal:** also real',
].join('\n');
writeRoadmap(tmpDir, content);
const roadmap = fs.readFileSync(path.join(tmpDir, '.planning', 'ROADMAP.md'), 'utf-8');
const result = extractCurrentMilestone(roadmap, tmpDir);
// The section should include Phase 1 content; the fenced heading should not terminate section early
assert.ok(result.includes('real goal'), 'phase 1 content included');
assert.ok(result.includes('Also Real'), 'phase 2 content also included');
});
});
// ─── replaceInCurrentMilestone ────────────────────────────────────────────────
describe('roadmap-parser: replaceInCurrentMilestone', () => {
test('replaces in content after last </details> when present', () => {
const content = '<details>\nold\n</details>\n**Plans:** 0/1 plans';
const result = replaceInCurrentMilestone(content, /0\/1 plans/, '1/1 plans complete');
assert.ok(result.includes('1/1 plans complete'), 'replacement applied after </details>');
assert.ok(result.includes('<details>'), 'details block untouched');
});
test('replaces anywhere when no </details> present', () => {
const content = '**Plans:** 0/1 plans';
const result = replaceInCurrentMilestone(content, /0\/1 plans/, '1/1 plans complete');
assert.strictEqual(result, '**Plans:** 1/1 plans complete');
});
test('does not replace in shipped sections', () => {
const content = '<details>\n**Plans:** 0/1 plans\n</details>\n## v2.0\n**Plans:** 0/1 plans';
const result = replaceInCurrentMilestone(content, /0\/1 plans/, '1/1 plans complete');
// Only the SECOND occurrence (after </details>) should be replaced
assert.ok(result.includes('<details>\n**Plans:** 0/1 plans\n</details>'), 'shipped section unchanged');
assert.ok(result.includes('## v2.0\n**Plans:** 1/1 plans complete'), 'current section updated');
});
});
// ─── getRoadmapPhaseInternal ──────────────────────────────────────────────────
describe('roadmap-parser: getRoadmapPhaseInternal', () => {
let tmpDir;
beforeEach(() => { tmpDir = createTempProject(); });
afterEach(() => { cleanup(tmpDir); });
test('returns null when ROADMAP.md missing', () => {
const result = getRoadmapPhaseInternal(tmpDir, '1');
assert.strictEqual(result, null);
});
test('returns null when phaseNum is falsy', () => {
writeRoadmap(tmpDir, '### Phase 1: Foo\n**Goal:** bar\n');
assert.strictEqual(getRoadmapPhaseInternal(tmpDir, null), null);
assert.strictEqual(getRoadmapPhaseInternal(tmpDir, ''), null);
assert.strictEqual(getRoadmapPhaseInternal(tmpDir, 0), null);
});
test('finds a phase by number', () => {
writeRoadmap(tmpDir, [
'## v1.0: Current',
'### Phase 1: Foundation',
'**Goal:** Set up infrastructure',
'',
'### Phase 2: API',
'**Goal:** Build the API',
].join('\n'));
const result = getRoadmapPhaseInternal(tmpDir, '1');
assert.ok(result !== null, 'result should not be null');
assert.strictEqual(result.found, true);
assert.strictEqual(result.phase_name, 'Foundation');
assert.strictEqual(result.goal, 'Set up infrastructure');
});
test('returns null for missing phase number', () => {
writeRoadmap(tmpDir, '### Phase 1: Foo\n**Goal:** bar\n');
const result = getRoadmapPhaseInternal(tmpDir, '99');
assert.strictEqual(result, null);
});
test('finds milestone-prefixed phase ID (e.g. 2-01)', () => {
writeState(tmpDir, { milestone: 'v2.0' });
writeRoadmap(tmpDir, [
'## v2.0: Current',
'### Phase 2-01: Alpha',
'**Goal:** first alpha phase',
'',
'### Phase 2-02: Beta',
'**Goal:** beta phase',
].join('\n'));
const result = getRoadmapPhaseInternal(tmpDir, '2-01');
assert.ok(result !== null);
assert.strictEqual(result.found, true);
assert.strictEqual(result.phase_name, 'Alpha');
assert.strictEqual(result.goal, 'first alpha phase');
});
test('decimal phase ID (e.g. 1.5)', () => {
writeRoadmap(tmpDir, [
'## v1.0: Current',
'### Phase 1.5: Intermediate',
'**Goal:** interstitial step',
].join('\n'));
const result = getRoadmapPhaseInternal(tmpDir, '1.5');
assert.ok(result !== null);
assert.strictEqual(result.phase_name, 'Intermediate');
});
});
// ─── getMilestoneInfo ─────────────────────────────────────────────────────────
describe('roadmap-parser: getMilestoneInfo', () => {
let tmpDir;
beforeEach(() => { tmpDir = createTempProject(); });
afterEach(() => { cleanup(tmpDir); });
test('returns default when ROADMAP.md missing', () => {
const info = getMilestoneInfo(tmpDir);
assert.strictEqual(info.version, 'v1.0');
assert.strictEqual(info.name, 'milestone');
});
test('reads version from STATE.md and heading name', () => {
writeState(tmpDir, { milestone: 'v2.0' });
writeRoadmap(tmpDir, '## v2.0: The Big Launch\n### Phase 1: Setup\n');
const info = getMilestoneInfo(tmpDir);
assert.strictEqual(info.version, 'v2.0');
assert.match(info.name, /Big Launch/);
});
test('falls back to 🚧 WIP marker when STATE.md has no milestone', () => {
writeRoadmap(tmpDir, '## 🚧 **v1.5 Work In Progress**\n### Phase 1: Do stuff\n');
const info = getMilestoneInfo(tmpDir);
assert.strictEqual(info.version, 'v1.5');
assert.match(info.name, /Work In Progress/i);
});
test('extracts from heading when no STATE.md and no WIP marker', () => {
writeRoadmap(tmpDir, [
'## v3.0: Future Milestone',
'### Phase 1: Not started',
].join('\n'));
const info = getMilestoneInfo(tmpDir);
assert.strictEqual(info.version, 'v3.0');
assert.match(info.name, /Future Milestone/);
});
test('skips completed ✅ milestones', () => {
writeRoadmap(tmpDir, [
'## ✅ v1.0: Shipped Already',
'## v2.0: Next Up',
].join('\n'));
const info = getMilestoneInfo(tmpDir);
// Should not use the ✅-prefixed version as the current milestone
assert.strictEqual(info.version, 'v2.0');
});
});
// ─── getMilestonePhaseFilter ──────────────────────────────────────────────────
describe('roadmap-parser: getMilestonePhaseFilter', () => {
let tmpDir;
beforeEach(() => { tmpDir = createTempProject(); });
afterEach(() => { cleanup(tmpDir); });
test('returns passAll (phaseCount=0) when ROADMAP.md missing', () => {
const filter = getMilestonePhaseFilter(tmpDir);
assert.strictEqual(filter.phaseCount, 0);
assert.strictEqual(filter('anything'), true);
});
test('basic milestone phase filter — matches dirs by phase number', () => {
writeRoadmap(tmpDir, [
'## v1.0: Launch',
'### Phase 1: Setup',
'**Goal:** setup',
'',
'### Phase 2: Build',
'**Goal:** build',
].join('\n'));
const filter = getMilestonePhaseFilter(tmpDir);
assert.strictEqual(filter.phaseCount, 2);
assert.strictEqual(filter('01-setup'), true, '01-setup matches Phase 1');
assert.strictEqual(filter('02-build'), true, '02-build matches Phase 2');
assert.strictEqual(filter('03-deploy'), false, '03-deploy not in milestone');
});
test('milestone-prefixed phase IDs (e.g. 2-01)', () => {
writeState(tmpDir, { milestone: 'v2.0' });
writeRoadmap(tmpDir, [
'## v2.0: Current',
'### Phase 2-01: Alpha',
'### Phase 2-02: Beta',
].join('\n'));
const filter = getMilestonePhaseFilter(tmpDir);
assert.strictEqual(filter('02-01-alpha'), true, '02-01 matches Phase 2-01');
assert.strictEqual(filter('02-02-beta'), true, '02-02 matches Phase 2-02');
assert.strictEqual(filter('02-03-other'), false, '02-03 not in milestone');
});
test('versionOverride uses specified version slice', () => {
writeRoadmap(tmpDir, [
'## v1.0: Old',
'### Phase 1: Old Phase',
'',
'## v2.0: Current',
'### Phase 2: New Phase',
].join('\n'));
const filter = getMilestonePhaseFilter(tmpDir, 'v2.0');
assert.strictEqual(filter('02-new-phase'), true, 'phase 2 in v2.0 slice');
assert.strictEqual(filter('01-old-phase'), false, 'phase 1 not in v2.0 slice');
});
test('missingExplicitVersion set when version not found in versioned roadmap', () => {
writeRoadmap(tmpDir, [
'## v1.0: Only Milestone',
'### Phase 1: Foo',
].join('\n'));
const filter = getMilestonePhaseFilter(tmpDir, 'v9.9');
assert.strictEqual(filter.missingExplicitVersion, true, 'missingExplicitVersion should be true');
assert.strictEqual(filter.phaseCount, 0);
});
test('zero-padded phase IDs match unpadded dirs and vice versa', () => {
writeRoadmap(tmpDir, [
'## v1.0: Padded Test',
'### Phase 01: Setup',
'### Phase 02: Build',
].join('\n'));
const filter = getMilestonePhaseFilter(tmpDir);
assert.strictEqual(filter('1-setup'), true, 'unpadded dir matches padded Phase 01');
assert.strictEqual(filter('02-build'), true, 'padded dir matches padded Phase 02');
});
test('decimal phase IDs in ROADMAP filter correctly', () => {
writeRoadmap(tmpDir, [
'## v1.0: Decimal Test',
'### Phase 1.5: Interstitial',
'### Phase 2: Normal',
].join('\n'));
const filter = getMilestonePhaseFilter(tmpDir);
assert.ok(filter.phaseCount >= 1, 'at least one phase found');
// Decimal phase IDs are non-numeric so filter should handle them
assert.strictEqual(filter('1.5-interstitial'), true, 'decimal phase dir matches');
});
test('repeated phase IDs — deduplication (no double count)', () => {
writeRoadmap(tmpDir, [
'## v1.0: Repeated',
'### Phase 1: First',
'### Phase 1: Duplicate heading',
].join('\n'));
const filter = getMilestonePhaseFilter(tmpDir);
// Phase 1 appears twice but should only count once
assert.strictEqual(filter.phaseCount, 1, 'deduplication: only 1 unique phase');
});
test('adversarial: characterizes current fence-blind behavior for backtick fence (pending #875)', () => {
writeRoadmap(tmpDir, [
'## v1.0: Real',
'```',
'### Phase 999: Fake Phase Inside Fence',
'```',
'### Phase 1: Real Phase',
'**Goal:** real',
].join('\n'));
const filter = getMilestonePhaseFilter(tmpDir);
// KNOWN BUG #875: getMilestonePhaseFilter is fence-blind — phase headings inside
// fenced code blocks are incorrectly parsed as real phases. Flip to false when #875 is fixed.
assert.strictEqual(filter('01-real'), true, 'real phase matches');
assert.strictEqual(filter('999-fake'), true, 'characterization: getMilestonePhaseFilter is currently fence-blind (KNOWN BUG #875) — flip to false when #875 is fixed');
});
test('adversarial: unclosed fence block — does not crash', () => {
writeRoadmap(tmpDir, [
'## v1.0: Unclosed',
'```',
'### Phase 1: Inside unclosed fence',
'**Goal:** unreachable',
// Intentionally no closing ``` — adversarial fixture
].join('\n'));
// Should not throw regardless of fence parsing behavior
let filter;
assert.doesNotThrow(() => {
filter = getMilestonePhaseFilter(tmpDir);
}, 'unclosed fence should not throw');
assert.ok(typeof filter === 'function', 'filter is a function');
});
test('adversarial: characterizes current fence-blind behavior for tilde fence (pending #875)', () => {
writeRoadmap(tmpDir, [
'## v1.0: Tilde',
'~~~',
'### Phase 999: Fake',
'~~~',
'### Phase 1: Real',
].join('\n'));
const filter = getMilestonePhaseFilter(tmpDir);
// KNOWN BUG #875: getMilestonePhaseFilter is fence-blind — phase headings inside
// tilde-fenced code blocks are incorrectly parsed as real phases. Flip to false when #875 is fixed.
assert.strictEqual(filter('01-real'), true, 'real phase matches despite tilde fence');
assert.strictEqual(filter('999-fake'), true, 'characterization: getMilestonePhaseFilter is currently fence-blind (KNOWN BUG #875) — flip to false when #875 is fixed');
});
test('adversarial: CRLF line endings in roadmap', () => {
const crlf = '## v1.0: CRLF\r\n### Phase 1: Setup\r\n### Phase 2: Build\r\n';
writeRoadmap(tmpDir, crlf);
let filter;
assert.doesNotThrow(() => { filter = getMilestonePhaseFilter(tmpDir); });
assert.ok(filter.phaseCount >= 1, 'phases found despite CRLF');
});
test('adversarial: mixed CRLF and LF in same file', () => {
const mixed = '## v1.0: Mixed\r\n### Phase 1: A\n### Phase 2: B\r\n### Phase 3: C\n';
writeRoadmap(tmpDir, mixed);
let filter;
assert.doesNotThrow(() => { filter = getMilestonePhaseFilter(tmpDir); });
assert.ok(filter.phaseCount >= 1, 'phases found in mixed CRLF/LF');
});
test('adversarial: unicode headings', () => {
writeState(tmpDir, { milestone: 'v1.0' });
writeRoadmap(tmpDir, [
'## v1.0: 日本語マイルストーン',
'### Phase 1: Héros Réalité',
'### Phase 2: Тест',
].join('\n'));
let filter;
assert.doesNotThrow(() => { filter = getMilestonePhaseFilter(tmpDir); });
assert.strictEqual(filter.phaseCount, 2, '2 unicode phases found');
assert.strictEqual(filter('01-setup'), true, 'phase 1 dir matches');
});
test('adversarial: bracket-prefixed phase heading ### [GSD] Phase 2-01:', () => {
writeState(tmpDir, { milestone: 'v2.0' });
writeRoadmap(tmpDir, [
'## v2.0: Bracket',
'### [GSD] Phase 2-01: Setup',
'### [GSD] Phase 2-02: Build',
].join('\n'));
const filter = getMilestonePhaseFilter(tmpDir);
assert.strictEqual(filter('02-01-setup'), true, 'bracket-prefixed phase 2-01 matched');
assert.strictEqual(filter('02-02-build'), true, 'bracket-prefixed phase 2-02 matched');
});
});

View File

@@ -11,6 +11,26 @@ const fs = require('fs');
const path = require('path');
const { runGsdTools, createTempProject, cleanup } = require('./helpers.cjs');
// The planning-dir resolver (planningDir) is workstream-aware and honours
// GSD_PROJECT / GSD_WORKSTREAM. These suites write STATE.md to <tmp>/.planning
// and assume that is where it is read from, so a developer shell inside a GSD
// workstream would otherwise redirect the read and break extractCurrentMilestone.
// Isolate the vars so the file is hermetic when run directly via `node --test`.
let savedGsdProject;
let savedGsdWorkstream;
beforeEach(() => {
savedGsdProject = process.env.GSD_PROJECT;
savedGsdWorkstream = process.env.GSD_WORKSTREAM;
delete process.env.GSD_PROJECT;
delete process.env.GSD_WORKSTREAM;
});
afterEach(() => {
if (savedGsdProject !== undefined) process.env.GSD_PROJECT = savedGsdProject;
else delete process.env.GSD_PROJECT;
if (savedGsdWorkstream !== undefined) process.env.GSD_WORKSTREAM = savedGsdWorkstream;
else delete process.env.GSD_WORKSTREAM;
});
/**
* Helper: write STATE.md with a milestone version so extractCurrentMilestone
* will slice the roadmap to only that milestone's section.
@@ -365,6 +385,51 @@ This is the active milestone body.
);
});
test('(7) workstream-aware: STATE.md under GSD_WORKSTREAM is read from the workstream subdir', () => {
// Regression guard for the env-leak that made these suites pass in clean CI but
// fail in a developer's GSD_WORKSTREAM shell. planningDir() is workstream-aware,
// so STATE.md lives at <cwd>/.planning/workstreams/<ws>/STATE.md. Setting the env
// here makes clean CI exercise the polluted-env resolution path.
process.env.GSD_WORKSTREAM = 'guard-ws';
try {
const wsPlanning = path.join(tmpDir, '.planning', 'workstreams', 'guard-ws');
fs.mkdirSync(wsPlanning, { recursive: true });
fs.writeFileSync(path.join(wsPlanning, 'STATE.md'), '---\nmilestone: v8.0\n---\n');
const roadmap = `# Project Roadmap
## v8.0 Overview — v8.0-F (CLOSED FAIL 2026-05-18)
This is the closed milestone body with some text.
### Phase 24: ARCHIVED
**Goal:** This phase is done and archived.
## v8.0-B Overview (STARTED 2026-05-18)
This is the active milestone body.
### Phase 31: EVAL
**Goal:** Evaluate the new system.
## v9.0 Future Milestone
### Phase 40: FUTURE
**Goal:** Future work.
`;
const slice = core.extractCurrentMilestone(roadmap, tmpDir);
assert.ok(
slice.includes('Phase 31: EVAL'),
'workstream-scoped STATE.md must select the active v8.0-B section',
);
assert.ok(
!slice.includes('Phase 24: ARCHIVED'),
'closed section must still be excluded under a workstream env',
);
} finally {
delete process.env.GSD_WORKSTREAM;
}
});
test('(2) double-closed-skip: third sibling (active) selected when first two are closed', () => {
writeState(tmpDir, 'v9.0');
const roadmap = `# Project Roadmap

View File

@@ -260,6 +260,32 @@ test('boom', () => { throw new Error('intentional'); });
});
});
describe('env hermeticity', () => {
// Regression guard for the two `delete process.env.GSD_PROJECT/GSD_WORKSTREAM`
// lines added in scripts/run-tests.cjs main() right after ensureBuiltArtifacts().
// If those deletions are removed, the fixture's assertions fail inside the child
// node:test process → non-zero harness exit → this test fails → CI catches it.
test('harness strips GSD_PROJECT and GSD_WORKSTREAM before running child tests', () => {
// Write a fixture that asserts both vars are absent in the child process env.
const FIXTURE = `'use strict';
const { test } = require('node:test');
const assert = require('node:assert/strict');
test('ambient GSD workstream vars are stripped by the runner', () => {
assert.strictEqual(process.env.GSD_PROJECT, undefined);
assert.strictEqual(process.env.GSD_WORKSTREAM, undefined);
});
`;
fs.writeFileSync(path.join(tmpDir, 'env-hermeticity.test.cjs'), FIXTURE, 'utf8');
// Pass both vars in the ambient env given to the harness process.
// The harness must delete them before spawning the child node:test process.
const r = runHarness(tmpDir, [], {
GSD_PROJECT: 'ambient-proj',
GSD_WORKSTREAM: 'ambient-ws',
});
assert.strictEqual(r.status, 0, r.stderr);
});
});
describe('Windows argv-overflow chunking (issue #3597)', () => {
// Windows CreateProcess caps lpCommandLine at 32,767 chars. With ~550
// tests the unchunked spawn fails instantly on Windows with no test