Files
msd-core/tests/orphan-worktree-detection.test.cjs
Tom Boucher 5b5d473e13 chore(#3465): remove 22 verified-vestigial allow-test-rule markers (#3494)
Phase 1 of #3464. Removes the `// allow-test-rule:` marker from 22 test files
where it is provably vestigial, and tightens the ratchet ceiling in
scripts/lint-allow-test-rule-refs.ceiling.json from 305 to 285.

Eligibility is decided by two independent AST discriminators, both
conservative (any doubt => keep):

(a) Read-target type. Every readFileSync/readFile call in the file resolves
    statically to a prose/config extension (.md/.json/.yml/.yaml/.toml/.txt),
    or the file performs no reads at all. Any read of a source extension
    (.cjs/.js/.mjs/.ts/.cts/.mts/.jsx/.tsx), any dynamic/unresolvable path,
    and any other extension all disqualify the file.

(b) Marker context. Every `allow-test-rule:` occurrence is a genuine comment
    node, never string- or template-literal payload. A marker that lives
    inside a RuleTester `code:` fixture is test DATA, not a suppression
    directive; stripping it corrupts the test. tests/eslint-rules.test.cjs is
    the one such fixture host and is deliberately untouched.

An earlier attempt at this phase classified markers by "strip it and see if
local/no-source-grep still passes" and was reverted in full before commit.
That oracle is unsound: the rule only fires on a literal .cjs/.js/.ts path
containing a quoted bin/lib/gsd-core/src segment, tracked one hop from the
binding, so files that genuinely source-grep real JavaScript pass it
silently -- tests/no-unbounded-spawn-allowlist.test.cjs (reads test sources
through a listTestFiles() walk) and tests/claude-imperative-reference.test.cjs
(matches bin/install.js through an intermediate variable) both cleared it
while being real source-greps. The rule's implementation is narrower than its
intent, so it cannot adjudicate whether an exemption is load-bearing.

Scope is limited to comment deletions: the diff over the test tree is 100%
line removals with zero insertions, and no executable line is altered.

On the ceiling value. The measured count at this HEAD is 283, so 285 leaves 2
slack -- deliberate, and well inside the documented grace band of 3. Pinning
the ceiling to the exact count makes this change effectively unmergeable: any
concurrent PR that lands one marker-bearing test file re-reds it. That race
fired twice while preparing this branch (once mid-rebase taking the count
304->305 on next, once between rebase and the verification run taking it
282->283), and it is the same race that broke next in #3461. A ceiling of
actual+2 preserves a merge window while still ratcheting 305 -> 285.

Known limit, disclosed rather than papered over: this clears 22 of 303
markers and does not reach #3464's trend-to-zero goal. Most of the remaining
markers sit on dynamic-path reads, commonly a hoisted `const p =
path.join(tmpDir, 'STATE.md')` whose target is prose but is unresolvable to
this classifier. A stricter one-hop const resolution would flip an estimated
95 more; that is deliberately left to a follow-up so it can be reviewed on
its own evidence.

Marker discovery reads bytes rather than shelling out to grep:
tests/security-prompt-injection.security.test.cjs carries a literal NUL byte
(an intentional injection fixture) that makes grep treat it as binary and skip
it, which is why the true marked-file count is 303 and not the 302 a shell
scan reports.

Closes #3465

Co-authored-by: sim <sim@local>
Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
2026-08-14 13:10:49 -04:00

127 lines
5.6 KiB
JavaScript

// Structural checks verify the health seam exports worktree inspection capability.
// Behavioral tests cover detection flow via validate health output.
/**
* GSD Tools Tests - Orphan/Stale Worktree Detection (W017)
*
* Tests for feat/worktree-health-w017-2167:
* - Worktree Safety Policy Module exports health inspection interface (structural)
* - No false positives on projects without linked worktrees
* - Adding the check does not regress baseline health status
*/
const { describe, test, beforeEach, afterEach } = require('node:test');
const assert = require('node:assert/strict');
const fs = require('fs');
const path = require('path');
const { runGsdTools, createTempGitProject, cleanup } = require('./helpers.cjs');
// ─── Helpers ────────────────────────────────────────────────────────────────
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 writeMinimalRoadmap(tmpDir) {
fs.writeFileSync(
path.join(tmpDir, '.planning', 'ROADMAP.md'),
'# Roadmap\n\n### Phase 1: Setup\n'
);
}
function writeMinimalStateMd(tmpDir) {
fs.writeFileSync(
path.join(tmpDir, '.planning', 'STATE.md'),
'# Session State\n\n## Current Position\n\nPhase: 1\n'
);
}
function writeValidConfigJson(tmpDir) {
fs.writeFileSync(
path.join(tmpDir, '.planning', 'config.json'),
JSON.stringify({
model_profile: 'balanced',
commit_docs: true,
workflow: { nyquist_validation: true, ai_integration_phase: true },
}, null, 2)
);
}
function setupHealthyProject(tmpDir) {
writeMinimalProjectMd(tmpDir);
writeMinimalRoadmap(tmpDir);
writeMinimalStateMd(tmpDir);
writeValidConfigJson(tmpDir);
fs.mkdirSync(path.join(tmpDir, '.planning', 'phases', '01-setup'), { recursive: true });
}
// ─────────────────────────────────────────────────────────────────────────────
// 1. Structural: Worktree Safety Policy Module exposes inspection interface
// ─────────────────────────────────────────────────────────────────────────────
describe('W017: structural presence', () => {
test('worktree-safety module exports inspectWorktreeHealth', () => {
const modulePath = path.join(__dirname, '..', 'gsd-core', 'bin', 'lib', 'worktree-safety.cjs');
const seam = require(modulePath);
assert.strictEqual(typeof seam.inspectWorktreeHealth, 'function');
});
test('worktree-safety module exports linked worktree listing interface', () => {
const modulePath = path.join(__dirname, '..', 'gsd-core', 'bin', 'lib', 'worktree-safety.cjs');
const seam = require(modulePath);
assert.strictEqual(typeof seam.listLinkedWorktreePaths, 'function');
});
});
// ─────────────────────────────────────────────────────────────────────────────
// 2. No worktrees = no W017
// ─────────────────────────────────────────────────────────────────────────────
describe('W017: no false positives', () => {
let tmpDir;
beforeEach(() => {
tmpDir = createTempGitProject();
setupHealthyProject(tmpDir);
});
afterEach(() => cleanup(tmpDir));
test('no W017 when project has no linked worktrees', () => {
const result = runGsdTools('validate health --raw', tmpDir);
assert.ok(result.success, `validate health should succeed: ${result.error || ''}`);
const parsed = JSON.parse(result.output);
// Collect all warning codes
const warningCodes = (parsed.warnings || []).map(w => w.code);
assert.ok(!warningCodes.includes('W017'), `W017 should not fire when no linked worktrees exist, got warnings: ${JSON.stringify(warningCodes)}`);
});
});
// ─────────────────────────────────────────────────────────────────────────────
// 3. Clean project still reports healthy
// ─────────────────────────────────────────────────────────────────────────────
describe('W017: no regression on healthy projects', () => {
let tmpDir;
beforeEach(() => {
tmpDir = createTempGitProject();
setupHealthyProject(tmpDir);
});
afterEach(() => cleanup(tmpDir));
test('validate health still reports healthy on a clean project', () => {
const result = runGsdTools('validate health --raw', tmpDir);
assert.ok(result.success, `validate health should succeed: ${result.error || ''}`);
const parsed = JSON.parse(result.output);
assert.equal(parsed.status, 'healthy', `Expected healthy status, got ${parsed.status}. Errors: ${JSON.stringify(parsed.errors)}. Warnings: ${JSON.stringify(parsed.warnings)}`);
});
});