Files
msd-core/tests/graphify.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

654 lines
22 KiB
JavaScript

'use strict';
// Tests for graphify.cjs — status and build describe blocks.
// Split from the consolidated 2336-LOC file. Refs #3761.
//
// Migrated to typed-IR (#2974): execGraphify now returns a typed
// `reason` field (GRAPHIFY_REASON enum) alongside exitCode/stdout/stderr.
// Tests assert on result.reason instead of grepping stderr for failure
// phrases like 'not found' or 'timed out'.
/**
* Tests for gsd-core/bin/lib/graphify.cjs
*
* Covers: config gate on/off (TEST-03), graceful degradation (TEST-04),
* subprocess helper (FOUND-04), presence detection (FOUND-02),
* version checking (FOUND-03), and disabled response (FOUND-01).
*/
const { describe, test, beforeEach, afterEach, mock } = require('node:test');
const assert = require('node:assert/strict');
const fs = require('fs');
const path = require('path');
const childProcess = require('child_process');
const { createTempProject, cleanup } = require('./helpers.cjs');
const {
isGraphifyEnabled,
disabledResponse,
execGraphify,
GRAPHIFY_REASON,
checkGraphifyInstalled,
checkGraphifyVersion,
graphifyStatus,
// Build (Phase 3)
graphifyBuild,
writeSnapshot,
} = require('../gsd-core/bin/lib/graphify.cjs');
const {
enableGraphify,
writeGraphJson,
SAMPLE_GRAPH,
} = require('./helpers/graphify.cjs');
// ─── status describe ─────────────────────────────────────────────────────────
describe('status', () => {
describe('isGraphifyEnabled', () => {
let tmpDir;
let planningDir;
beforeEach(() => {
tmpDir = createTempProject();
planningDir = path.join(tmpDir, '.planning');
});
afterEach(() => {
cleanup(tmpDir);
});
test('returns false when no config.json exists', () => {
// Remove config.json if createTempProject wrote one
const configPath = path.join(planningDir, 'config.json');
if (fs.existsSync(configPath)) fs.unlinkSync(configPath);
assert.strictEqual(isGraphifyEnabled(planningDir), false);
});
test('returns false when graphify key is not set', () => {
fs.writeFileSync(
path.join(planningDir, 'config.json'),
JSON.stringify({ model_profile: 'balanced' }),
'utf8'
);
assert.strictEqual(isGraphifyEnabled(planningDir), false);
});
test('returns false when graphify.enabled is false', () => {
fs.writeFileSync(
path.join(planningDir, 'config.json'),
JSON.stringify({ graphify: { enabled: false } }),
'utf8'
);
assert.strictEqual(isGraphifyEnabled(planningDir), false);
});
test('returns true when graphify.enabled is true', () => {
enableGraphify(planningDir);
assert.strictEqual(isGraphifyEnabled(planningDir), true);
});
test('returns false when config.json is malformed', () => {
fs.writeFileSync(
path.join(planningDir, 'config.json'),
'not json',
'utf8'
);
assert.strictEqual(isGraphifyEnabled(planningDir), false);
});
});
describe('disabledResponse', () => {
test('returns disabled:true with enable instructions', () => {
const result = disabledResponse();
assert.strictEqual(result.disabled, true);
assert.ok(result.message.includes('gsd-tools config-set graphify.enabled true'));
});
});
describe('graphifyStatus', () => {
let tmpDir;
let planningDir;
beforeEach(() => {
tmpDir = createTempProject();
planningDir = path.join(tmpDir, '.planning');
});
afterEach(() => {
cleanup(tmpDir);
});
// STAT-01: returns disabled response when not enabled
test('returns disabled response when not enabled', () => {
const result = graphifyStatus(tmpDir);
assert.strictEqual(result.disabled, true);
});
// STAT-02: returns exists:false when no graph.json
test('returns exists:false when no graph.json (STAT-02)', () => {
enableGraphify(planningDir);
const result = graphifyStatus(tmpDir);
assert.strictEqual(result.exists, false);
assert.ok(result.message.includes('No graph built yet'));
});
// STAT-01: returns status with counts when graph exists
test('returns status with counts when graph exists (STAT-01)', () => {
enableGraphify(planningDir);
writeGraphJson(planningDir, SAMPLE_GRAPH);
const result = graphifyStatus(tmpDir);
assert.strictEqual(result.exists, true);
assert.strictEqual(result.node_count, 5);
assert.strictEqual(result.edge_count, 5);
assert.strictEqual(typeof result.last_build, 'string');
assert.strictEqual(typeof result.stale, 'boolean');
assert.strictEqual(typeof result.age_hours, 'number');
});
// STAT-01: reports hyperedge_count
test('reports hyperedge_count', () => {
enableGraphify(planningDir);
const graphWithHyperedges = {
...SAMPLE_GRAPH,
hyperedges: [{ id: 'h1', nodes: ['n1', 'n2', 'n3'], label: 'auth_flow' }],
};
writeGraphJson(planningDir, graphWithHyperedges);
const result = graphifyStatus(tmpDir);
assert.strictEqual(result.hyperedge_count, 1);
});
// LINKS-02: status edge_count must read graph.links when graph.edges is absent
test('reports correct edge_count when graph uses links key (LINKS-02)', () => {
enableGraphify(planningDir);
const graphWithLinks = {
nodes: SAMPLE_GRAPH.nodes,
links: SAMPLE_GRAPH.edges,
hyperedges: [],
};
writeGraphJson(planningDir, graphWithLinks);
const result = graphifyStatus(tmpDir);
assert.strictEqual(result.edge_count, 5, 'edge_count must equal links array length');
});
});
});
// ─── build describe ──────────────────────────────────────────────────────────
describe('build', () => {
describe('execGraphify', () => {
afterEach(() => {
mock.restoreAll();
});
test('returns structured output on success', () => {
mock.method(childProcess, 'spawnSync', () => ({
status: 0,
stdout: '{"nodes": 42}',
stderr: '',
error: undefined,
signal: null,
}));
const result = execGraphify('/tmp', ['build']);
assert.strictEqual(result.exitCode, 0);
assert.strictEqual(result.stdout, '{"nodes": 42}');
assert.strictEqual(result.stderr, '');
});
test('returns exitCode 127 when graphify not on PATH', () => {
mock.method(childProcess, 'spawnSync', () => ({
status: null,
stdout: '',
stderr: '',
error: { code: 'ENOENT' },
signal: null,
}));
const result = execGraphify('/tmp', ['build']);
assert.strictEqual(result.exitCode, 127);
// Migrated #2974: assert on the typed `reason` field instead of
// grepping stderr for 'not found'.
assert.strictEqual(result.reason, GRAPHIFY_REASON.ENOENT);
});
test('returns exitCode 124 on timeout', () => {
mock.method(childProcess, 'spawnSync', () => ({
status: null,
stdout: 'partial',
stderr: '',
error: undefined,
signal: 'SIGTERM',
}));
const result = execGraphify('/tmp', ['build']);
assert.strictEqual(result.exitCode, 124);
// Migrated #2974: typed reason instead of stderr grep.
assert.strictEqual(result.reason, GRAPHIFY_REASON.TIMEOUT);
assert.strictEqual(result.timeout_ms, 30000);
});
test('passes PYTHONUNBUFFERED=1 in env', () => {
let captured;
mock.method(childProcess, 'spawnSync', (_cmd, _args, opts) => {
captured = opts;
return { status: 0, stdout: '', stderr: '', error: undefined, signal: null };
});
execGraphify('/tmp', ['build']);
assert.strictEqual(captured.env.PYTHONUNBUFFERED, '1');
});
test('uses 30000ms default timeout', () => {
let captured;
mock.method(childProcess, 'spawnSync', (_cmd, _args, opts) => {
captured = opts;
return { status: 0, stdout: '', stderr: '', error: undefined, signal: null };
});
execGraphify('/tmp', ['build']);
assert.strictEqual(captured.timeout, 30000);
});
test('allows timeout override', () => {
let captured;
mock.method(childProcess, 'spawnSync', (_cmd, _args, opts) => {
captured = opts;
return { status: 0, stdout: '', stderr: '', error: undefined, signal: null };
});
execGraphify('/tmp', ['build'], { timeout: 60000 });
assert.strictEqual(captured.timeout, 60000);
});
test('trims stdout and stderr whitespace', () => {
mock.method(childProcess, 'spawnSync', () => ({
status: 0,
stdout: ' hello \n',
stderr: ' warn \n',
error: undefined,
signal: null,
}));
const result = execGraphify('/tmp', ['build']);
assert.strictEqual(result.stdout, 'hello');
assert.strictEqual(result.stderr, 'warn');
});
});
describe('checkGraphifyInstalled', () => {
afterEach(() => {
mock.restoreAll();
});
test('returns installed:true when graphify is on PATH', () => {
mock.method(childProcess, 'spawnSync', () => ({
status: 0,
stdout: 'Usage: graphify...',
stderr: '',
error: undefined,
signal: null,
}));
const result = checkGraphifyInstalled();
assert.strictEqual(result.installed, true);
});
test('returns installed:false with install instructions when not on PATH', () => {
mock.method(childProcess, 'spawnSync', () => ({
status: null,
stdout: '',
stderr: '',
error: { code: 'ENOENT' },
signal: null,
}));
const result = checkGraphifyInstalled();
assert.strictEqual(result.installed, false);
assert.ok(result.message.includes('uv pip install graphifyy && graphify install'));
});
test('uses --help not --version for detection', () => {
let capturedArgs;
mock.method(childProcess, 'spawnSync', (_cmd, args) => {
capturedArgs = args;
return { status: 0, stdout: '', stderr: '', error: undefined, signal: null };
});
checkGraphifyInstalled();
assert.deepStrictEqual(capturedArgs, ['--help']);
});
});
describe('checkGraphifyVersion', () => {
afterEach(() => {
mock.restoreAll();
});
test('returns compatible:true for version 0.4.0', () => {
mock.method(childProcess, 'spawnSync', () => ({
status: 0,
stdout: '0.4.0\n',
stderr: '',
error: undefined,
signal: null,
}));
const result = checkGraphifyVersion();
assert.strictEqual(result.version, '0.4.0');
assert.strictEqual(result.compatible, true);
assert.strictEqual(result.warning, null);
});
test('returns compatible:true for version 0.9.5', () => {
mock.method(childProcess, 'spawnSync', () => ({
status: 0,
stdout: '0.9.5\n',
stderr: '',
error: undefined,
signal: null,
}));
const result = checkGraphifyVersion();
assert.strictEqual(result.version, '0.9.5');
assert.strictEqual(result.compatible, true);
});
test('returns compatible:false for version 0.3.0', () => {
mock.method(childProcess, 'spawnSync', () => ({
status: 0,
stdout: '0.3.0\n',
stderr: '',
error: undefined,
signal: null,
}));
const result = checkGraphifyVersion();
assert.strictEqual(result.compatible, false);
assert.ok(result.warning.includes('outside tested range'));
});
test('returns compatible:false for version 1.0.0', () => {
mock.method(childProcess, 'spawnSync', () => ({
status: 0,
stdout: '1.0.0\n',
stderr: '',
error: undefined,
signal: null,
}));
const result = checkGraphifyVersion();
assert.strictEqual(result.compatible, false);
assert.ok(result.warning.includes('outside tested range'));
});
test('handles python3 not found', () => {
mock.method(childProcess, 'spawnSync', () => ({
status: null,
stdout: '',
stderr: '',
error: { code: 'ENOENT' },
signal: null,
}));
const result = checkGraphifyVersion();
assert.strictEqual(result.version, null);
assert.ok(result.warning.includes('Could not determine'));
});
test('handles unparseable version string', () => {
mock.method(childProcess, 'spawnSync', () => ({
status: 0,
stdout: 'unknown\n',
stderr: '',
error: undefined,
signal: null,
}));
const result = checkGraphifyVersion();
assert.strictEqual(result.compatible, null);
assert.ok(result.warning.includes('Could not parse'));
});
test('tries graphify --version first before python3', () => {
const calls = [];
mock.method(childProcess, 'spawnSync', (cmd, args) => {
calls.push({ cmd, args });
return { status: 0, stdout: '0.4.3\n', stderr: '', error: undefined, signal: null };
});
checkGraphifyVersion();
assert.strictEqual(calls.length, 1, 'exactly one spawnSync call — no python3 fallback');
assert.strictEqual(calls[0].cmd, 'graphify');
assert.ok(calls[0].args.includes('--version'), 'graphify called with --version');
const python3Calls = calls.filter(c => c.cmd === 'python3');
assert.strictEqual(python3Calls.length, 0, 'no python3 fallback when graphify --version succeeds');
});
test('falls back to python3 importlib.metadata when graphify --version fails', () => {
const calls = [];
mock.method(childProcess, 'spawnSync', (cmd, args) => {
calls.push({ cmd, args });
if (cmd === 'graphify') {
return { status: 1, stdout: '', stderr: 'unknown option', error: undefined, signal: null };
}
// python3 fallback
return { status: 0, stdout: '0.4.3\n', stderr: '', error: undefined, signal: null };
});
const result = checkGraphifyVersion();
assert.strictEqual(result.version, '0.4.3');
assert.strictEqual(result.compatible, true);
assert.ok(calls.length >= 2, 'at least two spawnSync calls (graphify attempt + python3 fallback)');
assert.strictEqual(calls[0].cmd, 'graphify', 'graphify call precedes python3 fallback');
assert.ok(calls[0].args.includes('--version'), 'graphify --version attempted first');
const lastCall = calls[calls.length - 1];
assert.strictEqual(lastCall.cmd, 'python3', 'python3 fallback fires last');
assert.ok(lastCall.args.some(arg => arg.includes('importlib.metadata')));
});
});
describe('graphifyBuild', () => {
let tmpDir;
let planningDir;
beforeEach(() => {
tmpDir = createTempProject();
planningDir = path.join(tmpDir, '.planning');
enableGraphify(planningDir);
});
afterEach(() => {
cleanup(tmpDir);
mock.restoreAll();
});
test('returns disabled response when graphify not enabled', () => {
const tmpDir2 = createTempProject();
const result = graphifyBuild(tmpDir2);
assert.strictEqual(result.disabled, true);
cleanup(tmpDir2);
});
test('returns error when graphify not installed', () => {
mock.method(childProcess, 'spawnSync', () => ({
status: null,
stdout: '',
stderr: '',
error: { code: 'ENOENT' },
signal: null,
}));
const result = graphifyBuild(tmpDir);
assert.ok(result.error);
assert.ok(result.error.includes('not installed') || result.error.includes('pip install'));
});
test('returns spawn_agent action on successful pre-flight', () => {
mock.method(childProcess, 'spawnSync', (_cmd, args) => {
if (args && args[0] === '--help') {
return { status: 0, stdout: 'Usage', stderr: '', error: undefined, signal: null };
}
// version check via python3
return { status: 0, stdout: '0.4.3\n', stderr: '', error: undefined, signal: null };
});
const result = graphifyBuild(tmpDir);
assert.strictEqual(result.action, 'spawn_agent');
assert.ok(result.graphs_dir);
assert.ok(result.graphify_out);
assert.strictEqual(result.timeout_seconds, 300);
assert.strictEqual(result.version, '0.4.3');
assert.strictEqual(result.version_warning, null);
assert.deepStrictEqual(result.artifacts, ['graph.json', 'graph.html', 'GRAPH_REPORT.md']);
});
test('creates .planning/graphs/ directory if missing', () => {
mock.method(childProcess, 'spawnSync', (_cmd, args) => {
if (args && args[0] === '--help') {
return { status: 0, stdout: 'Usage', stderr: '', error: undefined, signal: null };
}
return { status: 0, stdout: '0.4.3\n', stderr: '', error: undefined, signal: null };
});
const graphsDir = path.join(planningDir, 'graphs');
assert.strictEqual(fs.existsSync(graphsDir), false);
graphifyBuild(tmpDir);
assert.strictEqual(fs.existsSync(graphsDir), true);
});
test('reads graphify.build_timeout from config', () => {
// Write config with custom timeout
const configPath = path.join(planningDir, 'config.json');
const config = JSON.parse(fs.readFileSync(configPath, 'utf8'));
config.graphify.build_timeout = 600;
fs.writeFileSync(configPath, JSON.stringify(config, null, 2), 'utf8');
mock.method(childProcess, 'spawnSync', (_cmd, args) => {
if (args && args[0] === '--help') {
return { status: 0, stdout: 'Usage', stderr: '', error: undefined, signal: null };
}
return { status: 0, stdout: '0.4.3\n', stderr: '', error: undefined, signal: null };
});
const result = graphifyBuild(tmpDir);
assert.strictEqual(result.timeout_seconds, 600);
});
test('includes version warning when outside tested range', () => {
mock.method(childProcess, 'spawnSync', (_cmd, args) => {
if (args && args[0] === '--help') {
return { status: 0, stdout: 'Usage', stderr: '', error: undefined, signal: null };
}
return { status: 0, stdout: '1.2.0\n', stderr: '', error: undefined, signal: null };
});
const result = graphifyBuild(tmpDir);
assert.strictEqual(result.action, 'spawn_agent');
assert.ok(result.version_warning);
assert.ok(result.version_warning.includes('outside tested range'));
});
});
describe('writeSnapshot', () => {
let tmpDir;
let planningDir;
beforeEach(() => {
tmpDir = createTempProject();
planningDir = path.join(tmpDir, '.planning');
});
afterEach(() => {
cleanup(tmpDir);
});
test('writes snapshot from existing graph.json', () => {
const graphData = {
nodes: [{ id: 'A', label: 'Node A' }, { id: 'B', label: 'Node B' }],
edges: [{ source: 'A', target: 'B', label: 'relates' }],
};
writeGraphJson(planningDir, graphData);
const result = writeSnapshot(tmpDir);
assert.strictEqual(result.saved, true);
assert.strictEqual(result.node_count, 2);
assert.strictEqual(result.edge_count, 1);
assert.ok(result.timestamp);
// Verify file was actually written
const snapshotPath = path.join(planningDir, 'graphs', '.last-build-snapshot.json');
assert.strictEqual(fs.existsSync(snapshotPath), true);
const snapshot = JSON.parse(fs.readFileSync(snapshotPath, 'utf8'));
assert.strictEqual(snapshot.version, 1);
assert.strictEqual(snapshot.nodes.length, 2);
assert.strictEqual(snapshot.edges.length, 1);
assert.ok(snapshot.timestamp);
});
test('returns error when graph.json does not exist', () => {
// graphs directory exists but no graph.json
fs.mkdirSync(path.join(planningDir, 'graphs'), { recursive: true });
const result = writeSnapshot(tmpDir);
assert.ok(result.error);
assert.ok(result.error.includes('not parseable'));
});
test('returns error when graph.json is invalid JSON', () => {
const graphsDir = path.join(planningDir, 'graphs');
fs.mkdirSync(graphsDir, { recursive: true });
fs.writeFileSync(path.join(graphsDir, 'graph.json'), 'not valid json{{{', 'utf8');
const result = writeSnapshot(tmpDir);
assert.ok(result.error);
assert.ok(result.error.includes('not parseable'));
});
test('handles graph.json with empty nodes and edges', () => {
writeGraphJson(planningDir, { nodes: [], edges: [] });
const result = writeSnapshot(tmpDir);
assert.strictEqual(result.saved, true);
assert.strictEqual(result.node_count, 0);
assert.strictEqual(result.edge_count, 0);
});
test('handles graph.json missing nodes/edges keys gracefully', () => {
writeGraphJson(planningDir, { metadata: { tool: 'graphify' } });
const result = writeSnapshot(tmpDir);
assert.strictEqual(result.saved, true);
assert.strictEqual(result.node_count, 0);
assert.strictEqual(result.edge_count, 0);
});
test('overwrites existing snapshot on rebuild', () => {
// Write initial graph and snapshot
writeGraphJson(planningDir, {
nodes: [{ id: 'A' }],
edges: [],
});
writeSnapshot(tmpDir);
// Write updated graph with more nodes
writeGraphJson(planningDir, {
nodes: [{ id: 'A' }, { id: 'B' }, { id: 'C' }],
edges: [{ source: 'A', target: 'B' }],
});
const result = writeSnapshot(tmpDir);
assert.strictEqual(result.saved, true);
assert.strictEqual(result.node_count, 3);
assert.strictEqual(result.edge_count, 1);
// Verify file reflects latest data
const snapshotPath = path.join(planningDir, 'graphs', '.last-build-snapshot.json');
const snapshot = JSON.parse(fs.readFileSync(snapshotPath, 'utf8'));
assert.strictEqual(snapshot.nodes.length, 3);
});
});
});