Files
msd-core/tests/graphify-auto-update.test.cjs
Tom Boucher 463cffd894 chore(#604): rename get-shit-done/ runtime directory to gsd-core/ (#615)
* chore(#604): rename get-shit-done/ runtime directory to gsd-core/

Renames the installed runtime directory `get-shit-done/` to `gsd-core/` so the
on-disk name matches the package (`@opengsd/gsd-core`), repo, and binary
(`gsd-tools`). The npm package name and binary are unchanged; npx/npm consumers
are unaffected.

Mechanical (bulk, ~90% of the diff):
- `git mv get-shit-done gsd-core`
- Swept path/identifier references across the repo via
  `perl -pe 's/get-shit-done(?!-\w)/gsd-core/g'`. The negative lookahead
  preserves the five legitimate slug variants that are NOT the directory:
  get-shit-done-{OLD,cc,classic,cli,redux} (old package/repo names).
- Build/manifest wiring: package.json (bin, files, coverage globs),
  tsconfig.build.json (outDir), ~86 .gitignore build-output entries,
  stryker.config.mjs, scan-ignore files, install.js path strings.
- Frozen (not rewritten): CHANGELOG.md history; translated docs
  (README.<locale>.md and docs/{ja-JP,ko-KR,pt-BR,zh-CN}/).

New logic (review here):
- src/installer-migrations/003-rename-get-shit-done-to-gsd-core.cts: a proper
  ADR-0008 installer migration. On upgrade it walks the legacy
  `~/.claude/get-shit-done/` tree, classifies each file via the prior install
  manifest, and emits remove-managed / backup-and-remove for managed files
  while PRESERVING unknown user-added files. Symlink-safe (skips a symlinked
  root and symlinked entries; bounds-checks every path under configDir). The
  framework rolls back on install failure. Emptied dirs may remain (framework
  has no recursive dir-removal primitive) — documented.
- scripts/lint-legacy-dir-name.cjs: CI regression guard forbidding the bare
  `get-shit-done` directory token (split token to avoid self-match; case-
  insensitive; `(?!-\w)` lookahead allows the slug variants; allowlists
  CHANGELOG, translated docs, and `gsd-allow-legacy-name` marker lines).
  Wired into the lint-tests CI job.
- Restored scripts/lint-package-identity-drift.cjs detection regexes (the
  mechanical sweep had wrongly rewritten the old-name patterns it exists to
  detect) and marked them as intentional legacy references.
- TDD tests for the migration and the guard; do.md slash-command guard regex
  tightened so a `/gsd-core/bin` path segment is not mistaken for a command;
  changeset + docs/installer-migrations.md row added.

Breaking: the installed runtime path moves `~/.claude/get-shit-done/` ->
`~/.claude/gsd-core/`. Migration 003 removes the stale legacy dir's managed
files (preserving user files) on upgrade. Users with custom hooks/configs
hardcoding the old path must update them.

Closes #604

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>

* fix(#604): unsweep pending changesets + allowlist injection-example docs

CI fixes for the rename PR:
- Do not sweep pending .changeset/*.md (ephemeral release-note fragments,
  like CHANGELOG); reverted those body edits so 5 pre-existing malformed
  fragments (missing type/pr) no longer enter the PR diff and trip docs-lint.
  Allowlisted .changeset/ in the legacy-name guard accordingly.
- Allowlisted TEST-EXAMPLES.md and docs/explanation/security-model.md in
  prompt-injection-scan.sh: they contain intentional injection examples /
  security-model prose; the path-reference rewrites are kept.

CodeQL alerts on this PR are pre-existing (alert lines unchanged by this PR;
none in the new migration/guard) and are out of scope for the rename.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>

* fix(#604): resolve CodeQL alerts surfaced on this PR

The rename diff touched files carrying pre-existing CodeQL findings; per the
no-pre-existing-dismissal rule, fixing every surfaced alert rather than waving
them off. All behavior-preserving:

- scripts/ci-test-scope.cjs: build the config-path match from string
  .includes() instead of a RegExp over an arg-derived value (js/regex-injection).
- src/profile-output.cts: escape backslashes before pipe-escaping desc/safeName
  so the table-cell escape is complete (js/incomplete-sanitization).
- tests/{bug-2643,bug-2808,docs-parity-live-registry}: two-pass HTML-comment
  strip so a bare/unclosed `<!--` cannot survive (js/incomplete-multi-character-sanitization).
- tests/inline-plan-threshold: drop the no-op `\s`->`\s` identity replace,
  keep the meaningful POSIX-class conversion (js/identity-replacement).

Verified: build:lib green; the touched test files + ci-test-scope + profile-output
suites pass; lint:legacy-name clean.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>

* fix(#604): correctly resolve remaining CodeQL alerts (regex-injection + sanitization)

The prior commit's fixes for two alerts were ineffective:
- ci-test-scope.cjs js/regex-injection: the alert is the CLI-arg-derived `file`
  reaching static regex `.test(file)` calls (not the config rule). Removed ALL
  regex over file/t — startsWith/includes/=== string checks + an isWindowsHint
  helper — so there is no regex sink for the tainted value.
- js/incomplete-multi-character-sanitization (3 test files): a single
  `.replace(/<!--...-->/g,'')` can let `<!--` re-form. Replaced with a fixpoint
  loop (replace until stable) plus a final bare-opener strip.

Verified: no regex over file/t remains; ci-test-scope + the 3 test suites pass;
lint:legacy-name clean.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>

* fix(#604): make ci-test-scope + comment-strippers regex-free to clear CodeQL

CodeQL flags the regex PATTERNS syntactically (regex-injection on the
--files arg split; incomplete-multi-character-sanitization on the <!--...-->
replace), so loop fixes do not satisfy it. Made these paths regex-free:
- ci-test-scope.cjs splitFiles: char-by-char separator tokenizer (no /[,\\s]+/).
- 3 test files: indexOf/slice HTML-comment stripper (no .replace(/<!--/)).
Behavior preserved; ci-test-scope + the 3 suites pass; guard clean.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>

* fix(#604): unblock security base64 scan on the large rename diff

The security job hit its 10m timeout: base64-scan.sh choked on the binary
test fixture tests/feat-3594-parser-property-style.test.cjs (embedded NUL/
non-UTF8 bytes -> thousands of bogus blobs + "ignored null byte" warnings),
and the ~800-file rename diff is slow to scan regardless.

- scripts/base64-scan.sh: skip binary-by-content files (grep -Iq .) — they
  can't carry base64-obfuscated *text* and feeding NUL bytes through the
  per-line scanner is pathologically slow. collect_files already filtered
  binary *extensions*; this catches binary *content* in text extensions.
- .github/workflows/security-scan.yml: raise the security job timeout 10m->30m
  to accommodate very large diffs (the scan itself is unchanged).

Verified locally: scan skips the fixture, 0 "ignored null byte" warnings,
0 findings, exit 0.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>

* fix(#604): sweep get-shit-done refs introduced by merging next

The branch was updated with next (#614/#384/#618 etc.), which reference the
get-shit-done/ dir (still named that on next). Swept the stale references in
the merged files to gsd-core so the rename stays consistent and lint:legacy-name
passes:
- commands/gsd/discuss-phase.md (runtime-launcher shim paths)
- src/core.cts (getAgentsDir layout comments)
- tests/bug-384-agents-runtime-aware.test.cjs (require path to runtime lib)

Verified: guard 0 violations; build green.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>

* fix(#604): exclude gsd-core/ path segments from bug-3683 command cross-ref invariant

The #614 runtime-launcher shim added to discuss-phase.md references
`${_GSD_RUNTIME_ROOT}/gsd-core/bin/...`. bug-3683's REF_PATTERN excluded path-y
refs only via lookbehind, but `}` precedes `/gsd-core/` in the shim, so it
mis-read the directory path as a dangling `/gsd-core` command ref (same class as
the #604 bug-2954 fix). Added a trailing `(?![\w-]*\/)` so `/gsd-<x>/...` path
segments are not treated as slash-command references.

Verified locally on BOTH platforms before pushing:
- mac (node 26) full suite: 0 failures
- gsd-test-runner (linux, node22 image) full suite: 0 failures
- bug-3683 + bug-2954 pass.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>

* fix(#604): lazily resolve findProjectRoot in gsd-tools (harden flaky CI)

CI intermittently failed state.test's gsd-tools subprocess with
"findProjectRoot is not a function" (flip-flopping across legs; not reproducible
on mac full suite, gsd-test linux full suite, test:unit, or state.test x8).
findProjectRoot is a re-export from core.cjs (sourced from project-root.cjs);
binding it via destructure at module-load can be undefined under a load-ordering
edge. Resolve it lazily at call time via a small wrapper so the lookup happens
after core.cjs is fully initialized.

Verified green on BOTH platforms before pushing:
- mac (node 26) full suite: 0 failures
- gsd-test-runner (linux, node22) full suite: 0 failures
- state.test.cjs: 106/106; gsd-tools loads cleanly.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>

* fix(#604): allowlist verification-patterns.md placeholder examples in secret scan

The rename git-mv'd references/verification-patterns.md into gsd-core/, pulling
it into the secret-scan diff. It documents stub/placeholder RED-FLAG env-var
examples (illustrative Stripe test-key / database-URL / API-key placeholders) —
not real credentials. Added it to .secretscanignore with the strict annotation,
mirroring the existing gsd-core/workflows/plan-phase.md exception.

Verified locally: secret-scan-lint --strict OK; secret-scan --diff origin/next
exits 0 with 0 findings.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-02 18:35:29 -04:00

650 lines
26 KiB
JavaScript

'use strict';
// Tests for graphify.cjs — auto-update describe block.
// Split from the consolidated 2336-LOC file. Refs #3761.
//
// Regression for #3347: opt-in auto-update of the knowledge graph after
// main HEAD advances. Two sub-concerns: config-key surface (config.test)
// and hook behavior (hook.test). Both merged here.
const { describe, test } = require('node:test');
const assert = require('node:assert/strict');
const fs = require('fs');
const path = require('path');
const os = require('node:os');
const { execFileSync, spawnSync } = require('child_process');
const { createTempProject, cleanup, runGsdTools } = require('./helpers.cjs');
const {
graphifyStatus,
} = require('../gsd-core/bin/lib/graphify.cjs');
const {
VALID_CONFIG_KEYS,
isValidConfigKey,
} = require('../gsd-core/bin/lib/config-schema.cjs');
const {
CONFIG_DEFAULTS: CANONICAL_CONFIG_DEFAULTS,
} = require('../gsd-core/bin/lib/configuration.cjs');
const {
makeStatusProject,
} = require('./helpers/graphify.cjs');
// ─── auto-update describe ─────────────────────────────────────────────────────
describe('auto-update', () => {
describe('config-key surface', () => {
// Regression for #3347
test('VALID_CONFIG_KEYS contains graphify.auto_update', () => {
assert.ok(
VALID_CONFIG_KEYS.has('graphify.auto_update'),
'graphify.auto_update must be in VALID_CONFIG_KEYS so config-set accepts it',
);
});
test('isValidConfigKey accepts graphify.auto_update', () => {
assert.ok(
isValidConfigKey('graphify.auto_update'),
'isValidConfigKey must return true for graphify.auto_update',
);
});
test('isValidConfigKey still accepts the pre-existing graphify.enabled key', () => {
assert.ok(
isValidConfigKey('graphify.enabled'),
'regression guard: graphify.enabled must remain a valid key',
);
});
test('CANONICAL_CONFIG_DEFAULTS.graphify.auto_update is false', () => {
assert.ok(
CANONICAL_CONFIG_DEFAULTS.graphify !== undefined,
'CANONICAL_CONFIG_DEFAULTS must expose a graphify section',
);
assert.strictEqual(
CANONICAL_CONFIG_DEFAULTS.graphify.auto_update,
false,
'graphify.auto_update default must be false (opt-in per issue #3347 AC)',
);
});
test('config-set graphify.auto_update true succeeds', (t) => {
const tmpDir = createTempProject();
t.after(() => cleanup(tmpDir));
const result = runGsdTools(
['config-set', 'graphify.auto_update', 'true'],
tmpDir,
);
assert.ok(
result.success,
[
'config-set graphify.auto_update true should succeed,',
'got:',
'stdout: ' + result.output,
'stderr: ' + result.error,
].join('\n'),
);
});
test('config-set graphify.auto_update true writes to config.json', (t) => {
const tmpDir = createTempProject();
t.after(() => cleanup(tmpDir));
runGsdTools(['config-set', 'graphify.auto_update', 'true'], tmpDir);
const configPath = path.join(tmpDir, '.planning', 'config.json');
const config = JSON.parse(fs.readFileSync(configPath, 'utf8'));
assert.strictEqual(
config.graphify?.auto_update,
true,
'config.json must have graphify.auto_update: true after config-set',
);
});
test('config-set graphify.auto_update false persists too', (t) => {
const tmpDir = createTempProject();
t.after(() => cleanup(tmpDir));
runGsdTools(['config-set', 'graphify.auto_update', 'true'], tmpDir);
runGsdTools(['config-set', 'graphify.auto_update', 'false'], tmpDir);
const configPath = path.join(tmpDir, '.planning', 'config.json');
const config = JSON.parse(fs.readFileSync(configPath, 'utf8'));
assert.strictEqual(
config.graphify?.auto_update,
false,
'config-set must round-trip true → false',
);
});
test('graphifyStatus folds auto-update status=failed into stale=true', (t) => {
const tmpDir = makeStatusProject({
ts: '2026-05-15T12:00:00Z',
status: 'failed',
exit_code: 1,
duration_ms: 1234,
head_at_build: 'abcdef0',
graphify_version: null,
});
t.after(() => cleanup(tmpDir));
const s = graphifyStatus(tmpDir);
assert.strictEqual(s.stale, true, 'auto-build failure must set stale=true');
assert.ok(s.last_build_auto_update, 'last_build_auto_update must be exposed');
assert.strictEqual(s.last_build_auto_update.status, 'failed');
assert.strictEqual(s.last_build_auto_update.exit_code, 1);
});
test('graphifyStatus folds auto-update status=running into stale=true', (t) => {
const tmpDir = makeStatusProject({
ts: '2026-05-15T12:00:00Z',
status: 'running',
exit_code: null,
duration_ms: null,
head_at_build: 'abcdef0',
graphify_version: null,
});
t.after(() => cleanup(tmpDir));
const s = graphifyStatus(tmpDir);
assert.strictEqual(s.stale, true, 'auto-build in-flight must set stale=true');
assert.strictEqual(s.last_build_auto_update.status, 'running');
});
test('graphifyStatus leaves stale alone when auto-update status=ok and graph is fresh', (t) => {
const tmpDir = makeStatusProject({
ts: '2026-05-15T12:00:00Z',
status: 'ok',
exit_code: 0,
duration_ms: 1234,
head_at_build: 'abcdef0',
graphify_version: null,
});
t.after(() => cleanup(tmpDir));
const s = graphifyStatus(tmpDir);
assert.strictEqual(s.stale, false, 'fresh graph + ok auto-build => not stale');
assert.strictEqual(s.last_build_auto_update.status, 'ok');
});
test('graphifyStatus exposes last_build_auto_update: null when status file absent', (t) => {
const tmpDir = makeStatusProject(null);
t.after(() => cleanup(tmpDir));
const s = graphifyStatus(tmpDir);
assert.strictEqual(s.last_build_auto_update, null);
assert.strictEqual(s.stale, false, 'no status file => stale follows mtime only');
});
test('config-set graphify.auto_update does not perturb sibling graphify.enabled', (t) => {
const tmpDir = createTempProject();
t.after(() => cleanup(tmpDir));
runGsdTools(['config-set', 'graphify.enabled', 'true'], tmpDir);
runGsdTools(['config-set', 'graphify.auto_update', 'true'], tmpDir);
const configPath = path.join(tmpDir, '.planning', 'config.json');
const config = JSON.parse(fs.readFileSync(configPath, 'utf8'));
assert.strictEqual(
config.graphify?.enabled,
true,
'graphify.enabled must be preserved when setting graphify.auto_update',
);
assert.strictEqual(
config.graphify?.auto_update,
true,
'graphify.auto_update must coexist with graphify.enabled',
);
});
});
// ─── hook tests ─────────────────────────────────────────────────────────────
const isWindows = process.platform === 'win32';
const HOOK = path.join(__dirname, '..', 'hooks', 'gsd-graphify-update.sh');
function createTempGitRepo(opts = {}) {
const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'gsd-3347-'));
spawnSync('git', ['init', '-b', opts.defaultBranch || 'main'], {
cwd: tmpDir,
stdio: 'ignore',
});
execFileSync('git', ['config', 'user.email', 'test@example.com'], { cwd: tmpDir });
execFileSync('git', ['config', 'user.name', 'Test'], { cwd: tmpDir });
fs.writeFileSync(path.join(tmpDir, 'README.md'), '# test\n');
execFileSync('git', ['add', 'README.md'], { cwd: tmpDir });
execFileSync('git', ['commit', '-m', 'init'], { cwd: tmpDir, stdio: 'ignore' });
fs.mkdirSync(path.join(tmpDir, '.planning'), { recursive: true });
if (opts.config !== undefined) {
fs.writeFileSync(
path.join(tmpDir, '.planning', 'config.json'),
JSON.stringify(opts.config, null, 2),
);
}
return tmpDir;
}
function makeMockGraphifyBin(tmpDir, { exitCode = 0, sleepMs = 0 } = {}) {
const binDir = path.join(tmpDir, '.mock-bin');
fs.mkdirSync(binDir, { recursive: true });
const script = path.join(binDir, 'graphify');
const body = [
'#!/usr/bin/env bash',
'set -u',
sleepMs ? `sleep ${(sleepMs / 1000).toFixed(3)}` : '',
'mkdir -p graphify-out',
'echo \'{"nodes":[],"edges":[]}\' > graphify-out/graph.json',
'echo "mock report" > graphify-out/GRAPH_REPORT.md',
'echo "<html></html>" > graphify-out/graph.html',
`exit ${exitCode}`,
]
.filter(Boolean)
.join('\n');
fs.writeFileSync(script, body + '\n', { mode: 0o755 });
return binDir;
}
function runHook(tmpDir, toolPayload, { env = {}, pathPrepend = '' } = {}) {
const PATH = pathPrepend
? `${pathPrepend}${path.delimiter}${process.env.PATH || ''}`
: process.env.PATH || '';
return spawnSync('bash', [HOOK], {
cwd: tmpDir,
input: JSON.stringify(toolPayload),
env: {
...process.env,
PATH,
CI: '',
...env,
},
encoding: 'utf8',
timeout: 30000,
});
}
// Shared 4-byte buffer used for Atomics.wait-based sleeps throughout the
// hook-test helpers. Atomics.wait(sai, 0, 0, ms) yields the event loop for
// exactly `ms` milliseconds without spawning an external process.
const _sleepSab = new SharedArrayBuffer(4);
const _sleepSai = new Int32Array(_sleepSab);
function atomicSleep(ms) {
Atomics.wait(_sleepSai, 0, 0, ms);
}
// Wait until the detached rebuild writes a terminal status, with a generous
// deadline. The detached subprocess can be slow under contended Docker; all
// assertions here are outcome-based, so we wait for the real terminal state
// rather than guessing a tight wall-clock budget (#382).
function waitForBuildStatus(statusPath, terminal /* e.g. new Set(['ok']) */, { deadlineMs = 30000, stepMs = 25 } = {}) {
const deadline = Date.now() + deadlineMs;
let status;
while (Date.now() < deadline) {
if (fs.existsSync(statusPath)) {
try {
const parsed = JSON.parse(fs.readFileSync(statusPath, 'utf8'));
status = parsed;
if (parsed && terminal.has(parsed.status)) return parsed;
} catch { /* detached writer can briefly expose a partial JSON write */ }
}
atomicSleep(stepMs);
}
return status; // last seen (may be undefined / non-terminal) — assertions below will report
}
function cleanupHookRepo(tmpDir) {
// The hook detaches a graphify-rebuild subprocess that may still be writing
// into tmpDir when the test body returns. Wait for the rebuild PID to exit
// (lock file disappears on subprocess EXIT trap), then retry rmSync to
// absorb any remaining transient ENOTEMPTY race.
//
// Uses Atomics.wait instead of execFileSync('sleep', ...) so we yield the
// CPU without spawning an external process per iteration. Budget: 15 s —
// bumped from 4 s to give the detached child more time to exit under
// contended Docker before we attempt removal (#382).
const lockPath = path.join(tmpDir, '.planning/graphs/.rebuild.lock');
const lockDeadline = Date.now() + 15000;
while (Date.now() < lockDeadline) {
if (!fs.existsSync(lockPath)) break;
try {
const pid = parseInt(fs.readFileSync(lockPath, 'utf8'), 10);
if (!Number.isFinite(pid) || pid <= 0) break;
execFileSync('kill', ['-0', String(pid)], { stdio: 'ignore' });
} catch {
break; // PID dead → safe to clean up
}
atomicSleep(50); // yield 50 ms, then re-check (replaces execFileSync('sleep'))
}
try {
// eslint-disable-next-line local/no-raw-rmsync-in-tests -- best-effort teardown: error is swallowed so cleanup() (which propagates) cannot be used here; a residual temp dir after a detached-subprocess race is harmless (#382)
fs.rmSync(tmpDir, { recursive: true, force: true, maxRetries: 8, retryDelay: 100 });
} catch { /* best-effort teardown: a residual temp dir is harmless; never fail the test (#382) */ }
}
describe('hook — bail paths (no side effects)',
{ skip: isWindows ? 'POSIX-only: harness spawns bash + kill -0 + sleep; the hook itself is a bash script under test' : false },
() => {
test('non-Bash tool call exits 0 with no status file', (t) => {
const tmpDir = createTempGitRepo({
config: { graphify: { enabled: true, auto_update: true } },
});
t.after(() => cleanupHookRepo(tmpDir));
const r = runHook(tmpDir, { tool_name: 'Edit', tool_input: { file_path: 'x' } });
assert.strictEqual(r.status, 0, 'hook must exit 0 on non-Bash tool');
assert.ok(
!fs.existsSync(path.join(tmpDir, '.planning/graphs/.last-build-status.json')),
'no status file should be created when bailing',
);
});
test('Bash but non-HEAD-advancing command exits 0 with no status file', (t) => {
const tmpDir = createTempGitRepo({
config: { graphify: { enabled: true, auto_update: true } },
});
t.after(() => cleanupHookRepo(tmpDir));
const r = runHook(tmpDir, { tool_name: 'Bash', tool_input: { command: 'ls -la' } });
assert.strictEqual(r.status, 0);
assert.ok(!fs.existsSync(path.join(tmpDir, '.planning/graphs/.last-build-status.json')));
});
test('git commit but graphify.enabled=false → no dispatch', (t) => {
const tmpDir = createTempGitRepo({
config: { graphify: { enabled: false, auto_update: true } },
});
t.after(() => cleanupHookRepo(tmpDir));
const r = runHook(tmpDir, { tool_name: 'Bash', tool_input: { command: 'git commit -m x' } });
assert.strictEqual(r.status, 0);
assert.ok(!fs.existsSync(path.join(tmpDir, '.planning/graphs/.last-build-status.json')));
});
test('git commit but graphify.auto_update=false → no dispatch (opt-in)', (t) => {
const tmpDir = createTempGitRepo({
config: { graphify: { enabled: true, auto_update: false } },
});
t.after(() => cleanupHookRepo(tmpDir));
const r = runHook(tmpDir, { tool_name: 'Bash', tool_input: { command: 'git commit -m x' } });
assert.strictEqual(r.status, 0);
assert.ok(
!fs.existsSync(path.join(tmpDir, '.planning/graphs/.last-build-status.json')),
'opt-in default-off: auto_update=false must suppress dispatch',
);
});
test('CI=true → no dispatch even with both gates true', (t) => {
const tmpDir = createTempGitRepo({
config: { graphify: { enabled: true, auto_update: true } },
});
t.after(() => cleanupHookRepo(tmpDir));
const mockBin = makeMockGraphifyBin(tmpDir);
const r = runHook(
tmpDir,
{ tool_name: 'Bash', tool_input: { command: 'git commit -m x' } },
{ env: { CI: 'true' }, pathPrepend: mockBin },
);
assert.strictEqual(r.status, 0);
assert.ok(!fs.existsSync(path.join(tmpDir, '.planning/graphs/.last-build-status.json')));
});
test('on non-default branch → no dispatch', (t) => {
const tmpDir = createTempGitRepo({
config: { graphify: { enabled: true, auto_update: true } },
});
t.after(() => cleanupHookRepo(tmpDir));
execFileSync('git', ['checkout', '-b', 'worktree-agent-abc'], {
cwd: tmpDir,
stdio: 'ignore',
});
const mockBin = makeMockGraphifyBin(tmpDir);
const r = runHook(
tmpDir,
{ tool_name: 'Bash', tool_input: { command: 'git commit -m x' } },
{ pathPrepend: mockBin },
);
assert.strictEqual(r.status, 0);
assert.ok(
!fs.existsSync(path.join(tmpDir, '.planning/graphs/.last-build-status.json')),
'branch check must filter worktree-agent-* (non-default-branch) commits',
);
});
test('graphify binary not on PATH → silent exit 0', (t) => {
const tmpDir = createTempGitRepo({
config: { graphify: { enabled: true, auto_update: true } },
});
t.after(() => cleanupHookRepo(tmpDir));
// Note: do NOT prepend mock bin; rely on real PATH not having graphify
const r = runHook(
tmpDir,
{ tool_name: 'Bash', tool_input: { command: 'git commit -m x' } },
{ env: { PATH: '/usr/bin:/bin' } },
);
assert.strictEqual(r.status, 0, 'must not break commits when graphify missing');
});
});
describe('hook — dispatch path (all gates pass)',
{ skip: isWindows ? 'POSIX-only: harness spawns bash + kill -0 + sleep; the hook itself is a bash script under test' : false },
() => {
test('writes status file with status=running synchronously before returning', (t) => {
const tmpDir = createTempGitRepo({
config: { graphify: { enabled: true, auto_update: true } },
});
t.after(() => cleanupHookRepo(tmpDir));
// Sleep 2s in mock so we can observe the running state before completion
const mockBin = makeMockGraphifyBin(tmpDir, { sleepMs: 2000 });
const r = runHook(
tmpDir,
{ tool_name: 'Bash', tool_input: { command: 'git commit -m x' } },
{ pathPrepend: mockBin },
);
assert.strictEqual(r.status, 0, 'hook must return 0');
const statusPath = path.join(tmpDir, '.planning/graphs/.last-build-status.json');
assert.ok(fs.existsSync(statusPath), 'status file must be written synchronously');
const status = JSON.parse(fs.readFileSync(statusPath, 'utf8'));
assert.strictEqual(status.status, 'running', 'initial status must be "running"');
assert.ok(/^[0-9a-f]{7,40}$/.test(status.head_at_build), 'head_at_build must be a commit sha');
});
test('completes to status=ok after detached graphify run succeeds', (t) => {
const tmpDir = createTempGitRepo({
config: { graphify: { enabled: true, auto_update: true } },
});
t.after(() => cleanupHookRepo(tmpDir));
const mockBin = makeMockGraphifyBin(tmpDir, { exitCode: 0, sleepMs: 200 });
runHook(
tmpDir,
{ tool_name: 'Bash', tool_input: { command: 'git commit -m x' } },
{ pathPrepend: mockBin },
);
// Wait for the detached rebuild process to write the final status file.
// Uses waitForBuildStatus with a generous 30 s deadline so contended
// Docker is never racing a tight budget (#382). All assertions are
// outcome-based; the deadline is deterministic, not a timing assertion.
const statusPath = path.join(tmpDir, '.planning/graphs/.last-build-status.json');
const status = waitForBuildStatus(statusPath, new Set(['ok']));
assert.ok(status, 'status file must exist after dispatch');
assert.strictEqual(status.status, 'ok', 'mock graphify exit=0 → status ok');
assert.strictEqual(status.exit_code, 0);
assert.ok(typeof status.duration_ms === 'number' && status.duration_ms >= 0);
});
test('completes to status=failed when graphify exits non-zero', (t) => {
const tmpDir = createTempGitRepo({
config: { graphify: { enabled: true, auto_update: true } },
});
t.after(() => cleanupHookRepo(tmpDir));
const mockBin = makeMockGraphifyBin(tmpDir, { exitCode: 1, sleepMs: 100 });
runHook(
tmpDir,
{ tool_name: 'Bash', tool_input: { command: 'git commit -m x' } },
{ pathPrepend: mockBin },
);
// Wait for the detached rebuild process to write the final status file.
// Uses waitForBuildStatus with a generous 30 s deadline so contended
// Docker is never racing a tight budget (#382). All assertions are
// outcome-based; the deadline is deterministic, not a timing assertion.
const statusPath = path.join(tmpDir, '.planning/graphs/.last-build-status.json');
const status = waitForBuildStatus(statusPath, new Set(['failed']));
assert.ok(status, 'status file must exist after dispatch');
assert.strictEqual(status.status, 'failed', 'mock graphify exit=1 → status failed');
assert.strictEqual(status.exit_code, 1);
});
test('lock file with a live PID prevents concurrent dispatch', (t) => {
const tmpDir = createTempGitRepo({
config: { graphify: { enabled: true, auto_update: true } },
});
t.after(() => cleanupHookRepo(tmpDir));
fs.mkdirSync(path.join(tmpDir, '.planning/graphs'), { recursive: true });
// Seed a live-PID lock pointing at our own process — kill -0 will succeed
fs.writeFileSync(path.join(tmpDir, '.planning/graphs/.rebuild.lock'), String(process.pid));
const mockBin = makeMockGraphifyBin(tmpDir);
const r = runHook(
tmpDir,
{ tool_name: 'Bash', tool_input: { command: 'git commit -m x' } },
{ pathPrepend: mockBin },
);
assert.strictEqual(r.status, 0);
// Status file should NOT be written because a rebuild is in flight
assert.ok(
!fs.existsSync(path.join(tmpDir, '.planning/graphs/.last-build-status.json')),
'live PID lock must suppress dispatch',
);
});
test('stale lock file (dead PID) is treated as absent', (t) => {
const tmpDir = createTempGitRepo({
config: { graphify: { enabled: true, auto_update: true } },
});
t.after(() => cleanupHookRepo(tmpDir));
fs.mkdirSync(path.join(tmpDir, '.planning/graphs'), { recursive: true });
// PID 1 is init; kill -0 1 succeeds for root but fails for non-root.
// Use a very large PID number unlikely to exist (max pid = 4194304 on linux).
fs.writeFileSync(path.join(tmpDir, '.planning/graphs/.rebuild.lock'), '4194303');
const mockBin = makeMockGraphifyBin(tmpDir, { sleepMs: 500 });
const r = runHook(
tmpDir,
{ tool_name: 'Bash', tool_input: { command: 'git commit -m x' } },
{ pathPrepend: mockBin },
);
assert.strictEqual(r.status, 0);
const statusPath = path.join(tmpDir, '.planning/graphs/.last-build-status.json');
assert.ok(fs.existsSync(statusPath), 'stale lock must not block dispatch');
});
test('respects git.base_branch config override (default branch != main)', (t) => {
const tmpDir = createTempGitRepo({
defaultBranch: 'trunk',
config: {
graphify: { enabled: true, auto_update: true },
git: { base_branch: 'trunk' },
},
});
t.after(() => cleanupHookRepo(tmpDir));
const mockBin = makeMockGraphifyBin(tmpDir, { sleepMs: 100 });
const r = runHook(
tmpDir,
{ tool_name: 'Bash', tool_input: { command: 'git commit -m x' } },
{ pathPrepend: mockBin },
);
assert.strictEqual(r.status, 0);
assert.ok(
fs.existsSync(path.join(tmpDir, '.planning/graphs/.last-build-status.json')),
'hook must honor git.base_branch when default branch is not main',
);
});
});
describe('hook — HEAD-advancing command matchers',
{ skip: isWindows ? 'POSIX-only: harness spawns bash to invoke the .sh hook under test' : false },
() => {
for (const cmd of [
'git commit -m fix',
'git merge feature',
'git pull --ff-only',
'git rebase --continue',
'git cherry-pick abc123',
// #3653 — `gsd-tools query commit` invokes git via spawnSync('git', [...]),
// so the substring "git commit" never appears in tool_input.command.
// The hook must match the user-facing SDK invocation directly.
'gsd-tools query commit "docs: probe" --files .planning/STATE.md',
'npx gsd-tools query commit "docs: probe" --files .planning/STATE.md',
]) {
test(`dispatches on: ${cmd}`, (t) => {
const tmpDir = createTempGitRepo({
config: { graphify: { enabled: true, auto_update: true } },
});
t.after(() => cleanupHookRepo(tmpDir));
const mockBin = makeMockGraphifyBin(tmpDir, { sleepMs: 100 });
runHook(
tmpDir,
{ tool_name: 'Bash', tool_input: { command: cmd } },
{ pathPrepend: mockBin },
);
const statusPath = path.join(tmpDir, '.planning/graphs/.last-build-status.json');
// Wait for any terminal status; we only assert the file exists,
// not which terminal value it holds (#382: generous deadline).
waitForBuildStatus(statusPath, new Set(['ok', 'failed']));
assert.ok(
fs.existsSync(statusPath),
`must dispatch for HEAD-advancing op: ${cmd}`,
);
});
}
test('does NOT dispatch on SDK commit-to-subrepo prefix collision', (t) => {
const tmpDir = createTempGitRepo({
config: { graphify: { enabled: true, auto_update: true } },
});
t.after(() => cleanupHookRepo(tmpDir));
const mockBin = makeMockGraphifyBin(tmpDir, { sleepMs: 100 });
const r = runHook(
tmpDir,
{
tool_name: 'Bash',
tool_input: {
command: 'gsd-tools query commit-to-subrepo "msg" --files packages/foo',
},
},
{ pathPrepend: mockBin },
);
assert.strictEqual(r.status, 0);
assert.ok(
!fs.existsSync(path.join(tmpDir, '.planning/graphs/.last-build-status.json')),
'must NOT dispatch for commit-to-subrepo, which does not advance the outer repo HEAD',
);
});
// #3653 — only the SDK `commit` verb invokes git internally. Other
// `gsd-tools query` verbs (phase.complete, roadmap.update-plan-progress,
// state.begin-phase) mutate .md files but do NOT advance HEAD; matching
// them would cause a spurious rebuild per state mutation.
for (const cmd of [
'gsd-tools query phase.complete 109',
'gsd-tools query roadmap.update-plan-progress 109 W001',
'gsd-tools query state.begin-phase 110',
]) {
test(`does NOT dispatch on non-HEAD-advancing SDK verb: ${cmd}`, (t) => {
const tmpDir = createTempGitRepo({
config: { graphify: { enabled: true, auto_update: true } },
});
t.after(() => cleanupHookRepo(tmpDir));
const r = runHook(tmpDir, { tool_name: 'Bash', tool_input: { command: cmd } });
assert.strictEqual(r.status, 0);
assert.ok(
!fs.existsSync(path.join(tmpDir, '.planning/graphs/.last-build-status.json')),
`must NOT dispatch for non-HEAD-advancing SDK verb: ${cmd}`,
);
});
}
});
});