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

677 lines
28 KiB
JavaScript

// allow-test-rule: source-text-is-the-product
// Reads .md/.json/.yml product files whose deployed text IS what the
// runtime loads — testing text content tests the deployed contract.
/**
* GSD Tools Tests - Concurrency Safety
*
* Tests for fix/concurrency-safety-1473a:
* - Planning lock integration (withPlanningLock in phase/roadmap operations)
* - readModifyWriteStateMd (atomic state updates)
* - normalizeMd behavioral equivalence (O(n) insideFence rewrite)
* - Warnings (frontmatter parse warning, stateReplaceFieldWithFallback)
* - Performance benchmarks (normalizeMd O(n) verification)
* - Snapshot tests for normalizeMd (regression detection)
* - Multi-process concurrent write tests
* - Stress tests at scale (50+ phases)
*/
const { test, describe, beforeEach, afterEach } = require('node:test');
const assert = require('node:assert/strict');
const fs = require('fs');
const path = require('path');
const os = require('os');
const { runGsdTools, createTempProject, cleanup } = require('./helpers.cjs');
const { normalizeContent } = require('../gsd-core/bin/lib/shell-command-projection.cjs');
// normalizeMd was removed from core.cjs (Phase 4 — issue #3468); the same algorithm now
// lives in the shell-command-projection seam. Wrap normalizeContent so existing
// behavioral / snapshot / perf assertions stay point-of-truth.
const normalizeMd = (input) => normalizeContent('test.md', input).content;
// ─── Helpers ────────────────────────────────────────────────────────────────
function writeMinimalRoadmap(tmpDir, phases = ['1']) {
const lines = phases.map(n => `### Phase ${n}: Phase ${n} Description`).join('\n');
fs.writeFileSync(
path.join(tmpDir, '.planning', 'ROADMAP.md'),
`# Roadmap\n\n${lines}\n`
);
}
function writeMinimalStateMd(tmpDir, content) {
const defaultContent = content || `# Session State\n\n## Current Position\n\nPhase: 1\n`;
fs.writeFileSync(
path.join(tmpDir, '.planning', 'STATE.md'),
defaultContent
);
}
function writeMinimalProjectMd(tmpDir) {
const sections = ['## What This Is', '## Core Value', '## Requirements'];
const content = sections.map(s => `${s}\n\nContent here.\n`).join('\n');
fs.writeFileSync(
path.join(tmpDir, '.planning', 'PROJECT.md'),
`# Project\n\n${content}`
);
}
function writeValidConfigJson(tmpDir, overrides = {}) {
const base = { model_profile: 'balanced', commit_docs: true };
fs.writeFileSync(
path.join(tmpDir, '.planning', 'config.json'),
JSON.stringify({ ...base, ...overrides }, null, 2)
);
}
/**
* Generate a 50-phase project structure for stress testing.
*/
function create50PhaseProject(tmpDir, completedCount = 25) {
let roadmapContent = '# Roadmap v1.0\n\n';
for (let i = 1; i <= 50; i++) {
roadmapContent += `- [${i <= completedCount ? 'x' : ' '}] Phase ${i}: Feature ${i}\n`;
}
roadmapContent += '\n';
for (let i = 1; i <= 50; i++) {
const pad = String(i).padStart(2, '0');
roadmapContent += `### Phase ${i}: Feature ${i}\n\n`;
roadmapContent += `**Goal:** Build feature ${i}\n`;
roadmapContent += `**Requirements:** REQ-${pad}\n`;
roadmapContent += `**Plans:** 1 plans\n\n`;
roadmapContent += `Plans:\n- [${i <= completedCount ? 'x' : ' '}] ${pad}-01-PLAN.md\n\n`;
}
fs.writeFileSync(
path.join(tmpDir, '.planning', 'ROADMAP.md'),
roadmapContent
);
const phasesDir = path.join(tmpDir, '.planning', 'phases');
for (let i = 1; i <= 50; i++) {
const pad = String(i).padStart(2, '0');
const dirName = `${pad}-feature-${i}`;
const phaseDir = path.join(phasesDir, dirName);
fs.mkdirSync(phaseDir, { recursive: true });
fs.writeFileSync(
path.join(phaseDir, `${pad}-01-PLAN.md`),
`# Phase ${i} Plan 1\n\nBuild feature ${i}.\n`
);
if (i <= completedCount) {
fs.writeFileSync(
path.join(phaseDir, `${pad}-01-SUMMARY.md`),
`# Phase ${i} Plan 1 Summary\n\nFeature ${i} completed.\n`
);
}
}
}
// ─────────────────────────────────────────────────────────────────────────────
// 1. Planning lock integration
// ─────────────────────────────────────────────────────────────────────────────
describe('planning lock integration', () => {
let tmpDir;
beforeEach(() => {
tmpDir = createTempProject();
});
afterEach(() => {
cleanup(tmpDir);
});
test('phase add creates and releases .planning/.lock during ROADMAP write', () => {
fs.writeFileSync(
path.join(tmpDir, '.planning', 'ROADMAP.md'),
`# Roadmap v1.0\n\n### Phase 1: Foundation\n**Goal:** Setup\n\n---\n`
);
const result = runGsdTools('phase add Testing', tmpDir);
assert.ok(result.success, `Command failed: ${result.error}`);
const lockPath = path.join(tmpDir, '.planning', '.lock');
assert.ok(!fs.existsSync(lockPath), '.lock file should be released after phase add');
const output = JSON.parse(result.output);
assert.strictEqual(output.phase_number, 2, 'should be phase 2');
});
test('phase complete creates and releases .planning/.lock', () => {
fs.writeFileSync(
path.join(tmpDir, '.planning', 'ROADMAP.md'),
`# Roadmap\n\n- [ ] Phase 1: Foundation\n\n### Phase 1: Foundation\n**Goal:** Setup\n**Plans:** 1 plans\n\n### Phase 2: API\n**Goal:** Build\n`
);
fs.writeFileSync(
path.join(tmpDir, '.planning', 'STATE.md'),
`# State\n\n**Current Phase:** 01\n**Current Phase Name:** Foundation\n**Status:** In progress\n**Current Plan:** 01-01\n**Last Activity:** 2025-01-01\n**Last Activity Description:** Working\n`
);
const p1 = path.join(tmpDir, '.planning', 'phases', '01-foundation');
fs.mkdirSync(p1, { recursive: true });
fs.writeFileSync(path.join(p1, '01-01-PLAN.md'), '# Plan');
fs.writeFileSync(path.join(p1, '01-01-SUMMARY.md'), '# Summary');
fs.mkdirSync(path.join(tmpDir, '.planning', 'phases', '02-api'), { recursive: true });
const result = runGsdTools('phase complete 1', tmpDir);
assert.ok(result.success, `Command failed: ${result.error}`);
const lockPath = path.join(tmpDir, '.planning', '.lock');
assert.ok(!fs.existsSync(lockPath), '.lock file should be released after phase complete');
const output = JSON.parse(result.output);
assert.strictEqual(output.completed_phase, '1', 'phase should be completed');
});
test('roadmap update-plan-progress creates and releases .planning/.lock', () => {
fs.writeFileSync(
path.join(tmpDir, '.planning', 'ROADMAP.md'),
`# Roadmap\n\n| Phase | Plans | Status | Updated |\n|-------|-------|--------|---------|\n| 1 | 0/0 | Not started | - |\n\n### Phase 1: Foundation\n**Goal:** Setup\n`
);
const phaseDir = path.join(tmpDir, '.planning', 'phases', '01-foundation');
fs.mkdirSync(phaseDir, { recursive: true });
fs.writeFileSync(path.join(phaseDir, '01-01-PLAN.md'), '# Plan');
fs.writeFileSync(path.join(phaseDir, '01-01-SUMMARY.md'), '# Summary');
const result = runGsdTools('roadmap update-plan-progress 1', tmpDir);
assert.ok(result.success, `Command failed: ${result.error}`);
const lockPath = path.join(tmpDir, '.planning', '.lock');
assert.ok(!fs.existsSync(lockPath), '.lock file should be released after roadmap update');
});
test('lock file does NOT persist after successful phase operations', () => {
fs.writeFileSync(
path.join(tmpDir, '.planning', 'ROADMAP.md'),
`# Roadmap v1.0\n`
);
runGsdTools('phase add First Phase', tmpDir);
runGsdTools('phase add Second Phase', tmpDir);
const lockPath = path.join(tmpDir, '.planning', '.lock');
assert.ok(!fs.existsSync(lockPath), '.lock file should not persist after multiple operations');
});
test('phase add still works correctly with lock (behavioral regression)', () => {
fs.writeFileSync(
path.join(tmpDir, '.planning', 'ROADMAP.md'),
`# Roadmap v1.0\n\n### Phase 1: Foundation\n**Goal:** Setup\n\n### Phase 2: API\n**Goal:** Build API\n\n---\n`
);
const result = runGsdTools('phase add User Dashboard', tmpDir);
assert.ok(result.success, `Command failed: ${result.error}`);
const output = JSON.parse(result.output);
assert.strictEqual(output.phase_number, 3, 'should be phase 3');
assert.strictEqual(output.slug, 'user-dashboard');
assert.ok(
fs.existsSync(path.join(tmpDir, '.planning', 'phases', '03-user-dashboard')),
'directory should be created'
);
const roadmap = fs.readFileSync(path.join(tmpDir, '.planning', 'ROADMAP.md'), 'utf-8');
assert.ok(roadmap.includes('### Phase 3: User Dashboard'), 'roadmap should include new phase');
});
});
// ─────────────────────────────────────────────────────────────────────────────
// 2. readModifyWriteStateMd (tested via CLI commands that use it)
// ─────────────────────────────────────────────────────────────────────────────
describe('readModifyWriteStateMd (via state patch)', () => {
let tmpDir;
beforeEach(() => {
tmpDir = createTempProject();
});
afterEach(() => {
cleanup(tmpDir);
});
test('transforms content atomically (read + modify + write under lock)', () => {
fs.writeFileSync(
path.join(tmpDir, '.planning', 'STATE.md'),
`# Project State\n\n**Current Phase:** 03\n**Status:** Planning\n**Current Plan:** 03-01\n`
);
const result = runGsdTools('state patch --Status "In progress" --"Current Plan" 03-02', tmpDir);
assert.ok(result.success, `Command failed: ${result.error}`);
const content = fs.readFileSync(path.join(tmpDir, '.planning', 'STATE.md'), 'utf-8');
assert.ok(content.includes('**Status:** In progress'), 'Status should be updated');
assert.ok(content.includes('03-02'), 'Current Plan should be updated');
const lockPath = path.join(tmpDir, '.planning', 'STATE.md.lock');
assert.ok(!fs.existsSync(lockPath), 'STATE.md.lock should be released after patch');
});
test('lock file cleaned up after state patch operation', () => {
fs.writeFileSync(
path.join(tmpDir, '.planning', 'STATE.md'),
`# Project State\n\n**Current Phase:** 01\n**Status:** Ready\n`
);
runGsdTools('state patch --Status "In progress"', tmpDir);
const lockPath = path.join(tmpDir, '.planning', 'STATE.md.lock');
assert.ok(!fs.existsSync(lockPath), 'STATE.md.lock should not persist after operation');
});
test('state patch still works correctly via readModifyWriteStateMd path (behavioral regression)', () => {
const stateMd = [
'# Project State',
'',
'**Current Phase:** 03',
'**Status:** Planning',
'**Current Plan:** 03-01',
'**Last Activity:** 2024-01-15',
].join('\n') + '\n';
fs.writeFileSync(path.join(tmpDir, '.planning', 'STATE.md'), stateMd);
const result = runGsdTools('state patch --Status Complete --"Current Phase" 04', tmpDir);
assert.ok(result.success, `Command failed: ${result.error}`);
const updated = fs.readFileSync(path.join(tmpDir, '.planning', 'STATE.md'), 'utf-8');
assert.ok(updated.includes('**Status:** Complete'), 'Status should be updated to Complete');
assert.ok(updated.includes('**Last Activity:** 2024-01-15'), 'Last Activity should be unchanged');
});
test('two sequential state patches both persist (patch A then patch B)', () => {
fs.writeFileSync(
path.join(tmpDir, '.planning', 'STATE.md'),
`# Project State\n\n**Current Phase:** 01\n**Status:** Planning\n**Current Plan:** 01-01\n**Last Activity:** 2024-01-01\n`
);
const resultA = runGsdTools('state patch --Status "In progress"', tmpDir);
assert.ok(resultA.success, `Patch A failed: ${resultA.error}`);
const resultB = runGsdTools('state patch --"Current Plan" 01-02', tmpDir);
assert.ok(resultB.success, `Patch B failed: ${resultB.error}`);
const content = fs.readFileSync(path.join(tmpDir, '.planning', 'STATE.md'), 'utf-8');
assert.ok(content.includes('**Status:** In progress'), 'Patch A (Status) should persist');
assert.ok(content.includes('01-02'), 'Patch B (Current Plan) should persist');
assert.ok(content.includes('**Last Activity:** 2024-01-01'), 'Untouched field should be preserved');
});
test('lock file does not persist after rapid sequential patches', () => {
fs.writeFileSync(
path.join(tmpDir, '.planning', 'STATE.md'),
`# Project State\n\n**Current Phase:** 01\n**Status:** Planning\n**Current Plan:** 01-01\n`
);
runGsdTools('state patch --Status "In progress"', tmpDir);
runGsdTools('state patch --"Current Plan" 01-02', tmpDir);
runGsdTools('state patch --Status Complete', tmpDir);
const lockPath = path.join(tmpDir, '.planning', 'STATE.md.lock');
assert.ok(!fs.existsSync(lockPath), 'STATE.md.lock should not persist after rapid sequential patches');
});
});
// ─────────────────────────────────────────────────────────────────────────────
// 3. Multi-process concurrent write tests
// ─────────────────────────────────────────────────────────────────────────────
describe('multi-process concurrent write tests', () => {
let tmpDir;
beforeEach(() => {
tmpDir = createTempProject();
});
afterEach(() => {
cleanup(tmpDir);
});
// 'two concurrent state patches to DIFFERENT fields both persist' deleted per #453 (clock-seam):
// plain Promise.all without a barrier is non-deterministic — the weakened OR assertion
// (aOk || bOk) and the vacuous assert.ok(true, ...) make the test pass even when one write
// is lost. Deterministic barrier-based coverage lives in locking-bugs-1909-1916-1925-1927:
// 'state update: both concurrent updates to different fields survive'.
// 'lock file does not persist after concurrent operations' deleted per #453 (clock-seam):
// plain Promise.all without a barrier; lock-cleanup coverage is in clock-seam.test.cjs
// describe('exit cleanup: STATE.md.lock removed on process exit').
test('three rapid sequential patches all persist', () => {
fs.writeFileSync(
path.join(tmpDir, '.planning', 'STATE.md'),
[
'# Project State',
'',
'**Current Phase:** 01',
'**Status:** Planning',
'**Current Plan:** 01-01',
'**Last Activity:** 2025-01-01',
'',
].join('\n')
);
const r1 = runGsdTools('state patch --Status "In progress"', tmpDir);
assert.ok(r1.success, `Patch 1 failed: ${r1.error}`);
const r2 = runGsdTools('state patch --"Current Plan" 01-02', tmpDir);
assert.ok(r2.success, `Patch 2 failed: ${r2.error}`);
const r3 = runGsdTools('state patch --"Last Activity" 2025-06-15', tmpDir);
assert.ok(r3.success, `Patch 3 failed: ${r3.error}`);
const content = fs.readFileSync(path.join(tmpDir, '.planning', 'STATE.md'), 'utf-8');
assert.ok(content.includes('In progress'), 'Patch 1 (Status) should persist');
assert.ok(content.includes('01-02'), 'Patch 2 (Current Plan) should persist');
assert.ok(content.includes('2025-06-15'), 'Patch 3 (Last Activity) should persist');
assert.ok(content.includes('**Current Phase:** 01'), 'Untouched field should be preserved');
});
});
// ─────────────────────────────────────────────────────────────────────────────
// 4. normalizeMd behavioral equivalence (O(n) insideFence rewrite)
// ─────────────────────────────────────────────────────────────────────────────
describe('normalizeMd behavioral equivalence', () => {
test('simple markdown with headings and paragraphs', () => {
const input = '# Title\nSome text.\n## Section\nMore text.\n';
const result = normalizeMd(input);
assert.ok(result.includes('# Title\n\nSome text.'), 'title heading should have blank line after');
assert.ok(result.includes('\n\n## Section\n\nMore text.'), 'section heading should have blank lines around it');
assert.ok(result.endsWith('\n'), 'should end with newline');
assert.ok(!result.endsWith('\n\n'), 'should not end with double newline');
});
test('single fenced code block gets blank lines before/after', () => {
const input = 'Some text\n```js\nconst x = 1;\n```\nMore text\n';
const result = normalizeMd(input);
assert.ok(result.includes('Some text\n\n```js'), 'code block should have blank line before');
assert.ok(result.includes('```\n\nMore text'), 'code block should have blank line after');
assert.ok(result.includes('const x = 1;'), 'code content should be preserved');
});
test('multiple fenced code blocks', () => {
const input = 'Intro\n```js\nfoo();\n```\nMiddle\n```py\nbar()\n```\nEnd\n';
const result = normalizeMd(input);
assert.ok(result.includes('Intro\n\n```js'), 'first code block should have blank line before');
assert.ok(result.includes('```\n\nMiddle'), 'first code block should have blank line after');
assert.ok(result.includes('Middle\n\n```py'), 'second code block should have blank line before');
assert.ok(result.includes('```\n\nEnd'), 'second code block should have blank line after');
});
test('unclosed fence at end of file (edge case)', () => {
const input = 'Some text\n```js\nconst x = 1;\n';
const result = normalizeMd(input);
assert.ok(typeof result === 'string', 'should return a string');
assert.ok(result.includes('```js'), 'fence opener should be preserved');
assert.ok(result.includes('const x = 1;'), 'content after unclosed fence should be preserved');
assert.ok(result.endsWith('\n'), 'should end with newline');
});
test('empty string input', () => {
assert.strictEqual(normalizeMd(''), '', 'empty string should return empty string');
});
test('mixed headings + lists + fences (complex case)', () => {
const input = [
'# Title',
'## Section One',
'Paragraph text.',
'- item 1',
'- item 2',
'## Section Two',
'```bash',
'echo hello',
'```',
'After code.',
'## Section Three',
'1. First',
'2. Second',
'Done.',
].join('\n') + '\n';
const result = normalizeMd(input);
assert.ok(result.includes('\n\n## Section One\n\n'), 'Section One heading needs blank lines');
assert.ok(result.includes('\n\n## Section Two\n\n'), 'Section Two heading needs blank lines');
assert.ok(result.includes('\n\n## Section Three\n\n'), 'Section Three heading needs blank lines');
assert.ok(result.includes('Paragraph text.\n\n- item 1'), 'list should have blank line before');
assert.ok(result.includes('\n\n```bash'), 'code block should have blank line before');
assert.ok(result.includes('```\n\nAfter code.'), 'code block should have blank line after');
assert.ok(result.includes('echo hello'), 'code content should be preserved');
assert.ok(!result.includes('\n\n\n'), 'should not have 3+ consecutive blank lines');
});
});
// normalizeMd performance benchmark tests deleted per #453 (clock-seam):
// wall-clock assertions (elapsed < 50ms, elapsed < 200ms) are inherently
// flaky on loaded CI runners. Correctness is covered by the snapshot tests
// in describe('normalizeMd snapshot tests') below.
// ─────────────────────────────────────────────────────────────────────────────
// 6. normalizeMd snapshot tests
// ─────────────────────────────────────────────────────────────────────────────
describe('normalizeMd snapshot tests', () => {
test('snapshot - heading spacing', () => {
const input = '# Title\nParagraph\n## Section\nMore text';
const expected = '# Title\n\nParagraph\n\n## Section\n\nMore text\n';
const result = normalizeMd(input);
assert.strictEqual(result, expected,
`Heading spacing snapshot mismatch.\nGot: ${JSON.stringify(result)}\nExpected: ${JSON.stringify(expected)}`
);
});
test('snapshot - code block spacing', () => {
const input = 'Text before\n```js\nconst x = 1;\n```\nText after\n';
const expected = 'Text before\n\n```js\nconst x = 1;\n```\n\nText after\n';
const result = normalizeMd(input);
assert.strictEqual(result, expected,
`Code block spacing snapshot mismatch.\nGot: ${JSON.stringify(result)}\nExpected: ${JSON.stringify(expected)}`
);
});
test('snapshot - list spacing', () => {
const input = 'Paragraph\n- item 1\n- item 2\nAnother paragraph';
const expected = 'Paragraph\n\n- item 1\n- item 2\n\nAnother paragraph\n';
const result = normalizeMd(input);
assert.strictEqual(result, expected,
`List spacing snapshot mismatch.\nGot: ${JSON.stringify(result)}\nExpected: ${JSON.stringify(expected)}`
);
});
test('snapshot - complex mixed document', () => {
const input = [
'# Main Title',
'Intro paragraph.',
'## Section One',
'Some text here.',
'```js',
'const a = 1;',
'```',
'- first item',
'- second item',
'## Section Two',
'Final text.',
].join('\n');
const expected = [
'# Main Title',
'',
'Intro paragraph.',
'',
'## Section One',
'',
'Some text here.',
'',
'```js',
'const a = 1;',
'```',
'',
'- first item',
'- second item',
'',
'## Section Two',
'',
'Final text.',
'',
].join('\n');
const result = normalizeMd(input);
assert.strictEqual(result, expected,
`Complex mixed document snapshot mismatch.\nGot: ${JSON.stringify(result)}\nExpected: ${JSON.stringify(expected)}`
);
});
});
// ─────────────────────────────────────────────────────────────────────────────
// 7. Warnings (frontmatter parse, state field miss)
// ─────────────────────────────────────────────────────────────────────────────
describe('warnings', () => {
let tmpDir;
beforeEach(() => {
tmpDir = createTempProject();
});
afterEach(() => {
cleanup(tmpDir);
});
test('must_haves parse warning fires for block with content but 0 items', () => {
const planDir = path.join(tmpDir, '.planning', 'phases', '01-test');
fs.mkdirSync(planDir, { recursive: true });
fs.writeFileSync(
path.join(planDir, '01-01-PLAN.md'),
`---
phase: "01"
plan: "01"
must_haves:
acceptance:
bare content without dash prefix
another line without dash prefix
---
# Plan 01-01
`
);
const result = runGsdTools(
['frontmatter', 'get', path.join(planDir, '01-01-PLAN.md'), 'must_haves'],
tmpDir
);
const stderr = result.error || '';
assert.ok(
stderr.includes('WARNING') && stderr.includes('must_haves') ||
result.output.includes('acceptance'),
`Expected WARNING about must_haves parse or valid parse result. stderr: ${stderr}, stdout: ${result.output}`
);
});
test('stateReplaceFieldWithFallback logs warning on miss', () => {
fs.writeFileSync(
path.join(tmpDir, '.planning', 'STATE.md'),
`# Project State\n\n**Current Phase:** 01\n**Current Plan:** 1\n**Total Plans in Phase:** 3\n`
);
const result = runGsdTools('state advance-plan', tmpDir);
assert.ok(result.success, `Command failed: ${result.error}`);
const output = JSON.parse(result.output);
assert.ok(output.advanced === true || output.reason === 'last_plan', 'advance should complete');
});
});
// ─────────────────────────────────────────────────────────────────────────────
// 8. Malformed input resilience
// ─────────────────────────────────────────────────────────────────────────────
describe('malformed input resilience', () => {
let tmpDir;
beforeEach(() => {
tmpDir = createTempProject();
});
afterEach(() => {
cleanup(tmpDir);
});
test('STATE.md with invalid bold format -- state patch returns gracefully', () => {
fs.writeFileSync(
path.join(tmpDir, '.planning', 'STATE.md'),
'# Project State\n\n**Current Phase: 01\n**Status:** Planning\n'
);
const result = runGsdTools('state patch --Status "In progress"', tmpDir);
const didNotCrash = result.success || (result.output !== undefined);
assert.ok(didNotCrash, `state patch should not crash on malformed bold format: ${result.error}`);
if (result.success) {
const content = fs.readFileSync(path.join(tmpDir, '.planning', 'STATE.md'), 'utf-8');
assert.ok(
content.includes('In progress'),
'Status field (with valid bold format) should be updated'
);
}
});
test('STATE.md with only frontmatter, no body -- state patch handles gracefully', () => {
fs.writeFileSync(
path.join(tmpDir, '.planning', 'STATE.md'),
'---\nphase: "01"\n---\n'
);
const result = runGsdTools('state patch --Status "In progress"', tmpDir);
const didNotCrash = result.success || (result.output !== undefined);
assert.ok(didNotCrash, `state patch should not crash on frontmatter-only STATE.md: ${result.error}`);
});
});
// ─────────────────────────────────────────────────────────────────────────────
// 9. Stress tests with 50+ phases
// ─────────────────────────────────────────────────────────────────────────────
describe('stress tests with 50+ phases', () => {
let tmpDir;
beforeEach(() => {
tmpDir = createTempProject();
});
afterEach(() => {
cleanup(tmpDir);
});
// roadmap analyze on 50-phase ROADMAP: behavioral test without timing gate.
// The elapsed < N wall-clock gate was a persistent flake source (#7, #453).
// Equivalent behavioral coverage (50 phases, 25 complete) lives in
// tests/clock-seam.test.cjs describe('roadmap analyze behavioral correctness').
test('phase complete on phase 26 of 50-phase project works correctly', () => {
create50PhaseProject(tmpDir, 25);
writeMinimalStateMd(tmpDir, '# Session State\n\n**Current Phase:** 26\n**Status:** In progress\n');
const phase26Dir = path.join(tmpDir, '.planning', 'phases', '26-feature-26');
fs.writeFileSync(
path.join(phase26Dir, '26-01-SUMMARY.md'),
'# Phase 26 Plan 1 Summary\n\nFeature 26 completed.\n'
);
const result = runGsdTools('phase complete 26', tmpDir);
assert.ok(result.success, `phase complete 26 should succeed: ${result.error}`);
const roadmapContent = fs.readFileSync(
path.join(tmpDir, '.planning', 'ROADMAP.md'),
'utf-8'
);
const phase26Checkbox = roadmapContent.match(/-\s*\[(x| )\]\s*.*Phase\s+26/i);
assert.ok(phase26Checkbox, 'Should find Phase 26 checkbox in ROADMAP');
assert.strictEqual(phase26Checkbox[1], 'x', 'Phase 26 should now be marked as complete [x]');
});
});