* fix(#3951): two lint rules that could not reach the code they govern B6 names two widenings. Measuring them first turned up a defect the criterion did not know about, and refuted the reason it gave for one of them. 1. no-adhoc-markdown-parsing self-gates on its own filename. Lines 107-110 short-circuit create() to {} unless the path matches /(?:^|\/)src\/[^/]+\.cts$/. B6 says to widen the files: glob in eslint.config.mjs - but doing only that ships an INERT rule, because the gate still returns {} for every new path. Both halves have to change, and the gate is the load-bearing one. That same regex hides a live hole: [^/]+ is FLAT-ONLY, so it requires the file to sit directly in src/. The registered glob is src/**/*.cts, which includes subdirectories. 28 .cts files - health-diagnostic-rules/ (10), installer-migrations/ (11), observability/ (3), host-integration-adapters/ (2), vendor/ (2) - are inside the registered glob and silently skipped. Measured with the gate neutralized: 0 violations there today. The hole is hiding nothing right now, and is fixed anyway, because "no violations today" is not a property that keeps holding. The fix is not invented: require-subprocess-timeout.cjs:196 already carries the correct form of this guard, /(?:^|\/)src\/.*\.cts$/ with .*, one directory over. Checked the other 21 rules for the same bug - no-adhoc-regex-escape and no-private-binary-resolution short-circuit only to exempt their own seam file, which is the right shape, and no-crlf-fragile-split has no filename gate at all. This bug is unique to the one rule. 2. no-adhoc-regex-escape could not see the shape that actually occurs. Line 396 gated the whole UNSAFE-NEW-REGEXP arm on arg.type === 'Identifier'. Every check below it - the _SOURCE provenance check, the isSoleReturnOfOwnParameter shape - lives inside that branch, so new RegExp(obj['key']) and new RegExp(cfg.pattern) were never examined at all. Runtime data arrives as a property access far more often than as a bare identifier, which is exactly why this rule never fired on the #3477 ReDoS. Widened to MemberExpression, measured by AST walk across all five registered blocks rather than by grep. 27 sites, zero TSAsExpression: 18 safe new RegExp(X.source, flags) -> exempted, keyed strictly on the PROPERTY being `source`, never on the object. Keying on the object would wave through X.anything and buy nothing. B6 estimated ~10; that was an undercount. 3 _SOURCE-suffixed constants reached through a required module namespace (phaseId.BRACKET_PHASE_TOKEN_SOURCE) -> the same provenance-exempt class the rule already recognizes for bare identifiers, extended to reach them. Without this the widening produces 3 false flags. 6 real findings -> marked, each a test extracting a pattern from a shipped file at test time, where the runtime contract IS the product. Deliberately the NARROW MemberExpression form. The rule's own isSoleReturnOfOwnParameter doc comment records that an earlier broad "any non-literal identifier" heuristic produced ~25 false positives and was rejected; a re-run of the census after this change flags exactly the 6 above and nothing else. Verified by execution, not by reading: the gate now accepts src/<subdir>/x.cts, still accepts flat src/x.cts, and still exempts paths outside src/ - each pinned by a test proven to fail against the old regex. build:lib, lint and lint:ci all exit 0. Refs #3951 Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> * fix(#3951): give no-adhoc-markdown-parsing its reach, and fix the 80 parses it finds The rule self-gates on filename AND is registered on one glob, so widening either half alone is inert. Both move here: the gate now accepts tests/**/*.cjs and scripts/**/*.cjs alongside src/**/*.cts, and eslint.config.mjs registers it on the same two. A test pins that the gate and the registration AGREE, in both directions. The original defect was a gate narrower than its registration; the failure mode of this fix is a gate wider than its registration. Both are silent, so the test asserts the pair rather than either half. 80 violations across 43 files, all in tests/, zero in scripts/. 70 are routed through the existing seams - scanFencedBlocks, collectSection, stripFencedCode, tokenizeHeadings from markdown-sectionizer; splitTableRow, parseMarkdownTable, findTableWithColumns from markdown-table. Headerless STATE.md tables use splitTableRow per line, because parseMarkdownTable needs a real delimiter row. 10 are suppressed, 12.5%, well under the third that would have meant the rule is mis-scoped for tests/ rather than the tests carrying debt. Each names its reason: three regression guards (#3873 / bug-#21) are deliberately independent of the generator's own fence handling, and routing them through the seam would have them test the generator against itself; one is a negative-text probe that extracts nothing; six are a shell-pipe-to-jq detector whose regex coincidentally matches the table fingerprint and is not markdown parsing at all. All ten sit in tests whose subject is .md content, which is normally a reason to prefer the seam. The marker used is allow-adhoc-markdown, distinct from no-source-grep's allow-test-rule, and lint:ci's lint-allow-test-rule-refs reports the same 280/280 unverified count as before - checked rather than assumed, because those two markers are easy to conflate. The widening earned its keep immediately: it found a test that passed for the wrong reason. tests/config-field-docs.test.cjs asserted notEqual(<cell>, '600') against the TYPE column instead of the DEFAULT column. notEqual('number', '600') is true forever, so the guard against workflow.subagent_timeout regressing to the old seconds default could never fire. docs/CONFIGURATION.md:434 is `| workflow.subagent_timeout | number | 300000 | ... |`, so the default is cell index 2; the assertion is now row-scoped through splitTableRow and reads 300000. That is the argument for the widening in one case: the violation was invisible to lint, the suite was green, and the assertion was vacuous. A rule that cannot reach a file cannot tell you the file is lying. Not fixed here, and recorded rather than assumed: #3426/#3239 are NOT reachable by this widening. tests/package-legitimacy-gate.test.cjs yields zero violations even with the gate bypassed - its hand-rolled scans are real, but built from line filters and split('|') rather than the regex-literal fingerprints this rule detects. They need new detectors. The epic assumed a wider glob would catch them. build:lib, lint and lint:ci all exit 0; the post-fix census across tests/** and scripts/** is 0 violations. Refs #3951 Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> * fix(#3951): B7 — and #3356's defects were still live in the code B7 asks that each closed child be driven fail-first with a behavioral identity test at the CONSUMER's output. Four of eleven children had no test citing their issue number. Auditing them by BEHAVIOR rather than by number-grep changed the answer for three of the four. #3364 and #2540 — traceability only. Both were implemented by #3941 and their consumer-output tests exist and were shown failing-first; neither cited its originating issue, so an audit that greps for the number reports them uncovered. Tagged the specific asserting test in each file, following the citation form those files already use. #3372 — covered, but only at helper level, and the triage narrowed it. Of the four commands the issue names, only estimate-cli's collectCalibrationSamples actually enumerates phase dirs from disk; smart-entry, audit and roadmap-upgrade derive from ROADMAP/body text and never reach the sentinel path, so they are benign by construction and were left alone rather than "fixed" into churn. The existing #3882 rows asserted the helper's return value. Added a consumer-output test driving `query estimate-calibrate` and asserting sample_count and the persisted document. RED proof: reverted collectCalibrationSamples to a raw readdirSync and ran the real CLI - sample_count 3, sentinel leaked; restored - sample_count 2. #3356 — NOT covered, and BOTH halves of the defect were still live in source. The issue is closed; the bug was not fixed. Fixed here rather than writing tests that document a bug as correct. Defect 1, the contradicted row. quick.md:627 claimed `quick-tasks-append` performs "the equivalent write" to the Step 7c row. It did not: the `#` cell was a positional ordinal and `Directory` read `—`, because the route had no way to receive a quick id or task directory. Added OPTIONAL `--quick-id` / `--slug` / `--directory`. A caller with neither - fast.md, the original #2133 caller - omits them and gets the byte-identical prior row, so nothing existing changes. A caller that HAS a real id and directory now gets the canonical row quick.md:632 renders. The false-equivalence sentence itself is corrected rather than left to mislead the next reader. Defect 2, the forced re-derive. The route called readModifyWriteStateMd with no options, so a body-only append to the Quick Tasks table triggered a full re-derive of the disk-derived progress.* frontmatter. Every other body-only writer passes { resync: false } - src/state.cts's own docstring prescribes it - and this route was the lone outlier. RED proof: reverted the option, seeded a project with 2 real phase dirs and a curated total_phases of 25, ran quick-tasks-append; total_phases collapsed to 2. Restored; it stayed 25. That second one is the shape this epic exists to close: a silent write that replaces curated state with a re-derivation nobody asked for, exit 0 throughout. build:lib, lint and lint:ci all exit 0. Refs #3951 Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> * docs(#3951): amend B6's ledger to what was measured, and document the new flags The ADR gains a ledger amendment in its own correction style - the sixth wrong premise it records, found the same way as the other five, by measuring before building. B6 says the net guard count must fall. It rose: 62 -> 69, +7, measured from the epic's filing commit to origin/next. The attribution is the point, though. Five of the seven came from PRs unrelated to this epic, one was added by a phase of it, and the epic did retire something sub-file - #3884 removed a detector with an explicit "net: -1 detector, 0 added" ledger. Every named casualty is load-bearing, two already carry retractions in this same document, and a sweep of all 22 rules plus every scripts/lint-* found no provably dead guard. There is no honest way to make the count fall; forcing it would trade coverage for a number, which is the Goodhart outcome Decision 6 exists to prevent. The amendment also records that B6's own prescribed fix for one widening was inert. no-adhoc-markdown-parsing self-gates on its filename, so widening only the files: glob - which is what the criterion says to do - ships a rule that still returns {} for every new path. And #3426/#3239 are not reachable by that widening at all; their scans use line filters and split('|'), not the regex fingerprints the rule detects. The roster row tracked them against the wrong mechanism. Three roster rows updated from aspiration to fact: the two widenings are DONE with their measured counts, and lint-phase-enumeration-drift is marked RETAINED rather than "expected casualty - verify before retiring", because Phase 5 verified it and kept it. The rule Decision 6 should carry forward is stated plainly: a guard ledger is a claim about COVERAGE, not about COUNT. "Net count must fall" is measurable and wrong. "Every guard is reachable, and each retirement names what makes its defect unrepresentable" is the property that was actually wanted. CLI-TOOLS.md documents the optional --quick-id/--slug/--directory flags and says plainly that omitting them keeps the pre-#3356 row byte-identical, plus that the append no longer re-derives progress frontmatter. New features fragment (id 3951); FEATURES.md regenerated rather than hand-edited. Changeset is Changed, pr:0 pending backfill. Refs #3951 Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> * test(#3951): correct four rows that pinned the lint rule's old narrow reach The remote suite came back RED with 5 failures, all in tests/eslint-rules.test.cjs. They are stale tests, not a regression: four rows assert that no-adhoc-markdown-parsing is inert outside src/*.cts, which is exactly the contract this deliverable changes. Confirmed by reading rather than inferred from the names - the row at :1981 used filename: 'tests/some.test.cjs' and filename: 'scripts/helper.cjs', the two roots the rule now covers on purpose. Worth recording WHY local gates missed this. npm run lint and lint:ci were green, and the touched test files passed standalone. Lint only reports violations in real files; these rows assert the rule's REACH using synthetic RuleTester filenames, so nothing but the full suite could see them. Local green on a rule change says nothing about the rule's own tests. Each row is rewritten with BOTH halves rather than flipped from valid to invalid: - the same fingerprint under tests/ or scripts/ is now flagged, with the right messageId - the negative space is preserved - the same fingerprint under a path outside all three roots (gsd-core/bin/lib/foo.cjs) is still NOT flagged The second half is the one that matters. Without it the rule has no boundary and nothing would catch an over-wide gate later, which is the mirror image of the bug this deliverable just fixed. Each row is renamed to state the current contract; the old names said "non-src/*.cts ... is not flagged" and would have been actively misleading once the bodies changed. Proven to test the widening rather than restate it: every flagged half was run against HEAD~2's pre-widening rule and does NOT fire there, then against the current rule and does. 12/12 on that probe; the full file is 178/178. Swept for the same staleness elsewhere and found none. require-subprocess-timeout's own "inert outside src/*.cts" row is untouched - that rule's gate was not widened here - and no-adhoc-regex-escape's test file already carries correctly-targeted rows. Refs #3951 Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> * test(#3951): acknowledge the quick.md growth the attribution guard reported The full suite came back RED with one failure, and it is mine: 1 file(s) grew without an acknowledgment: quick.md grew 364 bytes gsd-core/workflows/quick.md is runtime-loaded emitted content, so correcting its false 'performs the equivalent write' claim trips emitted-attribution by construction. This is the acknowledgment, not a workaround - there is nothing to regenerate. The fragment names ONE path, which is the only one the guard reported. The four spent acknowledgments it also listed (audit-uat, plan-phase, progress, review) belong to other fragments whose ripple the base already absorbs; they are inert, not failures, and are deliberately NOT copied here - naming paths I did not change would make this record false in the other direction. Byte figure corrected before committing: the guard reported 37220 -> 37584 (+364), but origin/next has since moved and quick.md is 37232 there now, so the measured delta is +352. The reason text says so and names the base as a moving figure rather than pinning a number that is already stale. Refs #3951 Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> * test(#3951): move the quick.md growth ack to a trailer, delete the obsolete fragment The acknowledgment mechanism changed under this branch. Merging next brought in the redesign - it also deleted .github/workflows/ack-fragment-sweep.yml, which was in the merge status and which I did not register at the time - and the guard now says so directly: Add a trailer to a commit in this PR (never a new file). Emitted-Drift-Ack-Growth: quick.md - <why this growth is deliberate> So tests/emitted-drift-acks/3951-quick-append-equivalence.json is obsolete on arrival. A fragment file is no longer read by anything, and leaving it would be a dead record that looks like an active one. It is deleted here rather than kept "just in case". The byte figure moved again with the merge: 37232 -> 37596, +364. The earlier fragment said +352, measured before the merge auto-merged quick.md itself. The trailer carries no number, which is the better design - the figure was stale twice in two attempts. Refs #3951 Emitted-Drift-Ack-Growth: quick.md — #3356/#3951 replaces a false claim with an accurate one. Line 627 said the `quick-tasks-append` shortcut "performs the equivalent write" to the Step 7c row rendered above it; it did not, and that was the documented half of #3356 — with no quick id or task directory the route emitted a positional ordinal in `#` and an em-dash in `Directory`, a visibly different row. The corrected sentence has to carry three facts the original elided: what the shortcut actually writes when it has neither input, that this is honest behavior for its real caller (`fast.md`, which has neither), and how a caller with both now gets the byte-identical canonical row via the new optional `--quick-id`/`--slug`/`--directory` flags. Prose is the product here — an executing agent reads this line to decide whether the shortcut is safe for its case, and a shorter correction would either drop the flags (leaving the reader unable to act on the fix) or drop the limitation (recreating the false claim in gentler words). Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> * chore(#3951): backfill changeset pr number Refs #3951 Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> --------- Co-authored-by: sim <sim@local> Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
792 lines
37 KiB
JavaScript
792 lines
37 KiB
JavaScript
/**
|
|
* GSD Tools Tests - New Milestone Clear Phases (#1588, #1447)
|
|
*
|
|
* Verifies that `phases clear` removes all phase subdirectories from
|
|
* .planning/phases/, leaving the directory itself intact.
|
|
*
|
|
* Also covers the #1447 uncommitted-changes guard: phases clear must refuse
|
|
* to delete phase directories that contain uncommitted work.
|
|
*/
|
|
|
|
const { test, describe, beforeEach, afterEach } = require('node:test');
|
|
const assert = require('node:assert/strict');
|
|
const fs = require('fs');
|
|
const path = require('path');
|
|
const { runHook: runHookSeam } = require('./helpers/process-seam.cjs');
|
|
const { gitOrThrow, throwIfFailed } = require('./helpers/git-fixture.cjs');
|
|
const { runGsdTools, createTempProject, createTempGitProject, cleanup, readFileNormalized } = require('./helpers.cjs');
|
|
const { writeState } = require('./fixtures/index.cjs');
|
|
const { scanFencedBlocks } = require('../gsd-core/bin/lib/markdown-sectionizer.cjs');
|
|
|
|
/** Return the raw text of every ```bash fenced block in `content`. */
|
|
function extractBashBlocks(content) {
|
|
const lines = content.split(/\r?\n/);
|
|
const blocks = [];
|
|
for (const block of scanFencedBlocks(lines)) {
|
|
if (block.closeLineIdx === -1) continue;
|
|
if ((block.infoString || '').trim() !== 'bash') continue;
|
|
blocks.push(lines.slice(block.openLineIdx + 1, block.closeLineIdx).join('\n'));
|
|
}
|
|
return blocks;
|
|
}
|
|
|
|
describe('phases clear command', () => {
|
|
let tmpDir;
|
|
|
|
beforeEach(() => {
|
|
tmpDir = createTempProject();
|
|
});
|
|
|
|
afterEach(() => {
|
|
cleanup(tmpDir);
|
|
});
|
|
|
|
test('clears all phase subdirectories from .planning/phases/', () => {
|
|
const phasesDir = path.join(tmpDir, '.planning', 'phases');
|
|
|
|
// Simulate phases left over from a previous milestone
|
|
const phase1 = path.join(phasesDir, '01-foundation');
|
|
const phase2 = path.join(phasesDir, '02-api');
|
|
const phase3 = path.join(phasesDir, '03-ui');
|
|
fs.mkdirSync(phase1, { recursive: true });
|
|
fs.mkdirSync(phase2, { recursive: true });
|
|
fs.mkdirSync(phase3, { recursive: true });
|
|
fs.writeFileSync(path.join(phase1, '01-01-PLAN.md'), '# Plan');
|
|
fs.writeFileSync(path.join(phase2, '02-01-SUMMARY.md'), '# Summary');
|
|
|
|
const result = runGsdTools('phases clear --confirm', tmpDir);
|
|
assert.ok(result.success, `Command failed: ${result.error}`);
|
|
|
|
const output = JSON.parse(result.output);
|
|
assert.strictEqual(output.cleared, 3, 'should report 3 directories cleared');
|
|
|
|
// phases/ directory itself must still exist
|
|
assert.ok(fs.existsSync(phasesDir), '.planning/phases/ directory should still exist');
|
|
|
|
// all subdirectories must be gone
|
|
const remaining = fs.readdirSync(phasesDir, { withFileTypes: true })
|
|
.filter(e => e.isDirectory());
|
|
assert.strictEqual(remaining.length, 0, 'no phase subdirectories should remain');
|
|
});
|
|
|
|
test('succeeds with cleared=0 when phases directory is already empty', () => {
|
|
const phasesDir = path.join(tmpDir, '.planning', 'phases');
|
|
// createTempProject creates the directory but leaves it empty
|
|
|
|
const result = runGsdTools('phases clear --confirm', tmpDir);
|
|
assert.ok(result.success, `Command failed: ${result.error}`);
|
|
|
|
const output = JSON.parse(result.output);
|
|
assert.strictEqual(output.cleared, 0, 'should report 0 cleared when already empty');
|
|
assert.ok(fs.existsSync(phasesDir), '.planning/phases/ directory should still exist');
|
|
});
|
|
|
|
test('succeeds with cleared=0 when phases directory does not exist', () => {
|
|
// Remove the phases directory entirely
|
|
// eslint-disable-next-line local/no-raw-rmsync-in-tests -- mid-test removal to simulate absent phases dir (SUT behavior, not teardown)
|
|
fs.rmSync(path.join(tmpDir, '.planning', 'phases'), { recursive: true, force: true });
|
|
|
|
const result = runGsdTools('phases clear --confirm', tmpDir);
|
|
assert.ok(result.success, `Command failed: ${result.error}`);
|
|
|
|
const output = JSON.parse(result.output);
|
|
assert.strictEqual(output.cleared, 0, 'should report 0 cleared when directory absent');
|
|
});
|
|
|
|
test('does not remove files (only directories) at the phases root', () => {
|
|
const phasesDir = path.join(tmpDir, '.planning', 'phases');
|
|
|
|
// Put a stray file directly in phases/ (edge case)
|
|
fs.writeFileSync(path.join(phasesDir, 'README.md'), '# Phases');
|
|
|
|
const phase1 = path.join(phasesDir, '01-foundation');
|
|
fs.mkdirSync(phase1, { recursive: true });
|
|
fs.writeFileSync(path.join(phase1, '01-01-PLAN.md'), '# Plan');
|
|
|
|
const result = runGsdTools('phases clear --confirm', tmpDir);
|
|
assert.ok(result.success, `Command failed: ${result.error}`);
|
|
|
|
const output = JSON.parse(result.output);
|
|
assert.strictEqual(output.cleared, 1, 'should report 1 directory cleared (not the file)');
|
|
|
|
// File must survive
|
|
assert.ok(
|
|
fs.existsSync(path.join(phasesDir, 'README.md')),
|
|
'files at phases root should be preserved'
|
|
);
|
|
});
|
|
|
|
test('archives nested phase content (moved, not deleted) (#1871)', () => {
|
|
const phasesDir = path.join(tmpDir, '.planning', 'phases');
|
|
const phase1 = path.join(phasesDir, '01-foundation');
|
|
const nested = path.join(phase1, 'subdir');
|
|
fs.mkdirSync(nested, { recursive: true });
|
|
fs.writeFileSync(path.join(nested, 'deep-file.md'), '# Deep');
|
|
|
|
const result = runGsdTools('phases clear --confirm', tmpDir);
|
|
assert.ok(result.success, `Command failed: ${result.error}`);
|
|
|
|
// Source is cleared (moved away)...
|
|
assert.ok(!fs.existsSync(phase1), 'phase directory should be moved out of .planning/phases/');
|
|
// ...but the nested content SURVIVES in the archive (not destroyed).
|
|
const archive = findPhasesArchive(tmpDir);
|
|
assert.ok(archive, 'an archive dir milestones/*-phases/ should exist');
|
|
assert.ok(
|
|
fs.existsSync(path.join(archive, '01-foundation', 'subdir', 'deep-file.md')),
|
|
'nested phase content must be preserved in the archive, not deleted',
|
|
);
|
|
});
|
|
});
|
|
|
|
// Locate the `milestones/<version>-phases/` archive directory created by phases clear.
|
|
function findPhasesArchive(tmpDir) {
|
|
const milestonesDir = path.join(tmpDir, '.planning', 'milestones');
|
|
try {
|
|
for (const entry of fs.readdirSync(milestonesDir, { withFileTypes: true })) {
|
|
if (entry.isDirectory() && /-phases$/.test(entry.name)) {
|
|
return path.join(milestonesDir, entry.name);
|
|
}
|
|
}
|
|
} catch {
|
|
/* no milestones dir */
|
|
}
|
|
return null;
|
|
}
|
|
|
|
// ─── #1447: uncommitted-changes guard ───────────────────────────────────────
|
|
|
|
describe('phases clear: uncommitted-changes guard (#1447)', () => {
|
|
let tmpDir;
|
|
|
|
beforeEach(() => {
|
|
tmpDir = createTempGitProject();
|
|
});
|
|
|
|
afterEach(() => {
|
|
cleanup(tmpDir);
|
|
});
|
|
|
|
test('aborts with error when phase dirs contain uncommitted files', () => {
|
|
// Add a phase directory with an untracked (uncommitted) file
|
|
const phasesDir = path.join(tmpDir, '.planning', 'phases');
|
|
const phase1 = path.join(phasesDir, '01-foundation');
|
|
fs.mkdirSync(phase1, { recursive: true });
|
|
fs.writeFileSync(path.join(phase1, 'PLAN.md'), '# Plan (uncommitted)');
|
|
// Do NOT commit — leave as untracked/uncommitted changes
|
|
|
|
const result = runGsdTools('phases clear --confirm', tmpDir);
|
|
assert.ok(!result.success, 'phases clear should fail when uncommitted changes exist');
|
|
assert.ok(
|
|
result.error.includes('uncommitted') || result.error.includes('aborted'),
|
|
`expected error about uncommitted changes, got: ${result.error}`
|
|
);
|
|
// Phase directory must still exist (was not deleted)
|
|
assert.ok(fs.existsSync(phase1), 'phase directory must survive when guard fires');
|
|
});
|
|
|
|
test('aborts when phase dirs have staged but uncommitted changes', () => {
|
|
const phasesDir = path.join(tmpDir, '.planning', 'phases');
|
|
const phase1 = path.join(phasesDir, '01-foundation');
|
|
fs.mkdirSync(phase1, { recursive: true });
|
|
fs.writeFileSync(path.join(phase1, 'PLAN.md'), '# Plan (staged)');
|
|
// Stage the file but do not commit
|
|
gitOrThrow(['add', '.planning/phases/'], { cwd: tmpDir });
|
|
|
|
const result = runGsdTools('phases clear --confirm', tmpDir);
|
|
assert.ok(!result.success, 'phases clear should fail when staged-but-uncommitted changes exist');
|
|
assert.ok(
|
|
result.error.includes('uncommitted') || result.error.includes('aborted'),
|
|
`expected error about uncommitted changes, got: ${result.error}`
|
|
);
|
|
assert.ok(fs.existsSync(phase1), 'phase directory must survive when guard fires');
|
|
});
|
|
|
|
test('--force bypasses the uncommitted-changes guard and deletes anyway', () => {
|
|
const phasesDir = path.join(tmpDir, '.planning', 'phases');
|
|
const phase1 = path.join(phasesDir, '01-foundation');
|
|
fs.mkdirSync(phase1, { recursive: true });
|
|
fs.writeFileSync(path.join(phase1, 'PLAN.md'), '# Plan (uncommitted)');
|
|
// Do NOT commit
|
|
|
|
const result = runGsdTools('phases clear --confirm --force', tmpDir);
|
|
assert.ok(result.success, `--force should bypass guard and succeed: ${result.error}`);
|
|
const output = JSON.parse(result.output);
|
|
assert.strictEqual(output.cleared, 1, 'should clear 1 phase directory');
|
|
assert.ok(!fs.existsSync(phase1), 'phase directory must be removed when --force is passed');
|
|
});
|
|
|
|
test('succeeds without --force when all phase files are committed', () => {
|
|
const phasesDir = path.join(tmpDir, '.planning', 'phases');
|
|
const phase1 = path.join(phasesDir, '01-foundation');
|
|
fs.mkdirSync(phase1, { recursive: true });
|
|
fs.writeFileSync(path.join(phase1, 'PLAN.md'), '# Plan (committed)');
|
|
// Commit the phase files
|
|
gitOrThrow(['add', '.planning/phases/'], { cwd: tmpDir });
|
|
gitOrThrow(['commit', '-m', 'add phase'], { cwd: tmpDir });
|
|
|
|
const result = runGsdTools('phases clear --confirm', tmpDir);
|
|
assert.ok(result.success, `should succeed when phase files are committed: ${result.error}`);
|
|
const output = JSON.parse(result.output);
|
|
assert.strictEqual(output.cleared, 1, 'should clear 1 phase directory');
|
|
// #1871: a committed phase dir is ARCHIVED (moved to milestones/*-phases/), not destroyed.
|
|
assert.ok(!fs.existsSync(phase1), 'committed phase directory should be moved out of .planning/phases/');
|
|
const archive = findPhasesArchive(tmpDir);
|
|
assert.ok(archive, 'a milestones/*-phases/ archive should be created for committed phase dirs');
|
|
assert.ok(
|
|
fs.existsSync(path.join(archive, '01-foundation', 'PLAN.md')),
|
|
'committed phase content must be preserved in the archive, not hard-deleted',
|
|
);
|
|
});
|
|
|
|
test('guard skips gracefully when not in a git repo (no guard, proceeds normally)', () => {
|
|
// Non-git project: createTempProject creates a plain project without git
|
|
const nonGitDir = createTempProject();
|
|
try {
|
|
const phasesDir = path.join(nonGitDir, '.planning', 'phases');
|
|
const phase1 = path.join(phasesDir, '01-foundation');
|
|
fs.mkdirSync(phase1, { recursive: true });
|
|
fs.writeFileSync(path.join(phase1, 'PLAN.md'), '# Plan');
|
|
|
|
// Without git, the guard cannot check status — it should skip and proceed
|
|
const result = runGsdTools('phases clear --confirm', nonGitDir);
|
|
assert.ok(result.success, `should succeed in non-git repo: ${result.error}`);
|
|
const output = JSON.parse(result.output);
|
|
assert.strictEqual(output.cleared, 1, 'should clear 1 phase directory in non-git project');
|
|
} finally {
|
|
cleanup(nonGitDir);
|
|
}
|
|
});
|
|
});
|
|
|
|
// ─── #2288: --archive-version override ──────────────────────────────────────
|
|
|
|
describe('phases clear: archive-version override (#2288)', () => {
|
|
let tmpDir;
|
|
|
|
beforeEach(() => {
|
|
tmpDir = createTempProject();
|
|
});
|
|
|
|
afterEach(() => {
|
|
cleanup(tmpDir);
|
|
});
|
|
|
|
test('override wins over live milestone state (new-milestone switches STATE before phases.clear)', () => {
|
|
fs.writeFileSync(
|
|
path.join(tmpDir, '.planning', 'ROADMAP.md'),
|
|
'# Roadmap\n\n## v2.0 — Active Milestone\n'
|
|
);
|
|
writeState(tmpDir, '---\nmilestone: v2.0\n---\n\n# State\n');
|
|
|
|
const phasesDir = path.join(tmpDir, '.planning', 'phases');
|
|
const phase1 = path.join(phasesDir, '01-foundation');
|
|
fs.mkdirSync(phase1, { recursive: true });
|
|
fs.writeFileSync(path.join(phase1, '01-01-PLAN.md'), '# Plan');
|
|
|
|
const result = runGsdTools('phases clear --confirm --archive-version v1.0', tmpDir);
|
|
assert.ok(result.success, `Command failed: ${result.error}`);
|
|
|
|
const output = JSON.parse(result.output);
|
|
assert.strictEqual(output.cleared, 1, 'should report 1 directory cleared');
|
|
|
|
assert.ok(
|
|
fs.existsSync(path.join(tmpDir, '.planning', 'milestones', 'v1.0-phases', '01-foundation')),
|
|
'phase history should archive under the OLD (override) version'
|
|
);
|
|
assert.ok(
|
|
!fs.existsSync(path.join(tmpDir, '.planning', 'milestones', 'v2.0-phases')),
|
|
'phase history must NOT be misfiled under the live-read NEW version'
|
|
);
|
|
});
|
|
|
|
test('no override falls back to live milestone version (no behavior change)', () => {
|
|
fs.writeFileSync(
|
|
path.join(tmpDir, '.planning', 'ROADMAP.md'),
|
|
'# Roadmap\n\n## v2.0 — Active Milestone\n'
|
|
);
|
|
writeState(tmpDir, '---\nmilestone: v2.0\n---\n\n# State\n');
|
|
|
|
const phasesDir = path.join(tmpDir, '.planning', 'phases');
|
|
const phase1 = path.join(phasesDir, '01-foundation');
|
|
fs.mkdirSync(phase1, { recursive: true });
|
|
fs.writeFileSync(path.join(phase1, '01-01-PLAN.md'), '# Plan');
|
|
|
|
const result = runGsdTools('phases clear --confirm', tmpDir);
|
|
assert.ok(result.success, `Command failed: ${result.error}`);
|
|
|
|
assert.ok(
|
|
fs.existsSync(path.join(tmpDir, '.planning', 'milestones', 'v2.0-phases', '01-foundation')),
|
|
'without an override, the live-read milestone version should still be used'
|
|
);
|
|
});
|
|
|
|
test('override with unchanged version (boundary: old === new)', () => {
|
|
fs.writeFileSync(
|
|
path.join(tmpDir, '.planning', 'ROADMAP.md'),
|
|
'# Roadmap\n\n## v3.0 — Active Milestone\n'
|
|
);
|
|
writeState(tmpDir, '---\nmilestone: v3.0\n---\n\n# State\n');
|
|
|
|
const phasesDir = path.join(tmpDir, '.planning', 'phases');
|
|
const phase1 = path.join(phasesDir, '01-foundation');
|
|
fs.mkdirSync(phase1, { recursive: true });
|
|
fs.writeFileSync(path.join(phase1, '01-01-PLAN.md'), '# Plan');
|
|
|
|
const result = runGsdTools('phases clear --confirm --archive-version v3.0', tmpDir);
|
|
assert.ok(result.success, `Command failed: ${result.error}`);
|
|
|
|
assert.ok(
|
|
fs.existsSync(path.join(tmpDir, '.planning', 'milestones', 'v3.0-phases', '01-foundation')),
|
|
'override equal to the live version should archive normally'
|
|
);
|
|
});
|
|
|
|
test('override omitted with no ROADMAP archives under the dated fallback label (#3216: getMilestoneInfo default deleted)', () => {
|
|
// #3216 (ADR-3180 §7.2 Decision, roadmap-parser.cjs:788-791): getMilestoneInfo's
|
|
// plausible-looking {version:'v1.0', name:'milestone'} default — output-identical
|
|
// to a genuine v1.0 project — was deleted. With no ROADMAP.md, getMilestoneInfo
|
|
// now returns {value:null, scope:SCOPE.UNREADABLE}; archivePhaseDirectories only
|
|
// trusts a SCOPE.COMPLETE identity as a directory-name-safe version
|
|
// (milestone.cjs:959-965), so a non-COMPLETE scope falls through to the dated
|
|
// `archived-<YYYYMMDD>` label (milestone.cjs:977-978) instead of 'v1.0'. This
|
|
// was previously misfiled under 'v1.0-phases', which read as a genuine v1.0
|
|
// milestone's archive rather than "no resolvable milestone identity".
|
|
// eslint-disable-next-line local/no-raw-rmsync-in-tests -- ensure no ROADMAP.md (SUT fallback path, not teardown)
|
|
fs.rmSync(path.join(tmpDir, '.planning', 'ROADMAP.md'), { recursive: true, force: true });
|
|
|
|
const phasesDir = path.join(tmpDir, '.planning', 'phases');
|
|
const phase1 = path.join(phasesDir, '01-foundation');
|
|
fs.mkdirSync(phase1, { recursive: true });
|
|
fs.writeFileSync(path.join(phase1, '01-01-PLAN.md'), '# Plan');
|
|
|
|
const result = runGsdTools('phases clear --confirm', tmpDir);
|
|
assert.ok(result.success, `Command failed: ${result.error}`);
|
|
|
|
assert.ok(
|
|
!fs.existsSync(path.join(tmpDir, '.planning', 'milestones', 'v1.0-phases')),
|
|
'no version identity is resolvable — must NOT be misfiled under a plausible-looking v1.0-phases'
|
|
);
|
|
const archive = findPhasesArchive(tmpDir);
|
|
assert.ok(archive, 'a milestones/*-phases/ archive should still be created');
|
|
assert.match(
|
|
path.basename(archive),
|
|
/^archived-\d{8}-phases$/,
|
|
'no resolvable milestone identity — must use the dated archived-<YYYYMMDD> fallback label'
|
|
);
|
|
assert.ok(
|
|
fs.existsSync(path.join(archive, '01-foundation')),
|
|
'the phase directory must still be archived (moved, not deleted) under the dated label'
|
|
);
|
|
});
|
|
|
|
test('rejects an --archive-version containing path traversal (no phase dir escapes .planning) (#2288 security)', () => {
|
|
const phasesDir = path.join(tmpDir, '.planning', 'phases');
|
|
const phase1 = path.join(phasesDir, '01-foundation');
|
|
fs.mkdirSync(phase1, { recursive: true });
|
|
fs.writeFileSync(path.join(phase1, '01-01-PLAN.md'), '# Plan');
|
|
|
|
// A traversal payload as the archive-version must be rejected outright — the
|
|
// value becomes a MOVED directory name, so accepting it would relocate phase
|
|
// history outside .planning/milestones/.
|
|
const result = runGsdTools(
|
|
'phases clear --confirm --archive-version ../../../gsd-poc-escape',
|
|
tmpDir,
|
|
);
|
|
assert.ok(!result.success, 'phases clear must FAIL on a path-traversal --archive-version');
|
|
|
|
// The phase directory must NOT have moved anywhere — it stays put.
|
|
assert.ok(
|
|
fs.existsSync(phase1),
|
|
'phase dir must remain in place when the archive-version is rejected',
|
|
);
|
|
// Nothing may have been created outside the project's milestones dir.
|
|
assert.ok(
|
|
!fs.existsSync(path.join(tmpDir, '..', 'gsd-poc-escape-phases')),
|
|
'no directory may be created outside the project via traversal',
|
|
);
|
|
assert.ok(
|
|
!fs.existsSync(path.join(tmpDir, '.planning', 'milestones')),
|
|
'no archive dir should be created at all when the override is rejected',
|
|
);
|
|
});
|
|
|
|
test('rejects backslash path separators in --archive-version (#2288 security)', () => {
|
|
const phasesDir = path.join(tmpDir, '.planning', 'phases');
|
|
const phase1 = path.join(phasesDir, '01-foundation');
|
|
fs.mkdirSync(phase1, { recursive: true });
|
|
fs.writeFileSync(path.join(phase1, '01-01-PLAN.md'), '# Plan');
|
|
|
|
// Starts with an alphanumeric so it clears the leading-char anchor — this
|
|
// proves the backslash (Windows path separator) itself is rejected, not just
|
|
// a leading-dot traversal.
|
|
const result = runGsdTools(
|
|
'phases clear --confirm --archive-version v1\\\\..\\\\evil',
|
|
tmpDir,
|
|
);
|
|
assert.ok(!result.success, 'phases clear must FAIL on a backslash-separator --archive-version');
|
|
assert.ok(fs.existsSync(phase1), 'phase dir must remain in place');
|
|
});
|
|
|
|
test('errors when --archive-version is present but its value is missing (does not silently drop the override) (#2288)', () => {
|
|
// A truncated invocation must fail loud, not fall through to the live read
|
|
// (which would silently re-file under the new milestone — the #2288 bug).
|
|
fs.writeFileSync(
|
|
path.join(tmpDir, '.planning', 'ROADMAP.md'),
|
|
'# Roadmap\n\n## v2.0 — Active Milestone\n'
|
|
);
|
|
writeState(tmpDir, '---\nmilestone: v2.0\n---\n\n# State\n');
|
|
const phasesDir = path.join(tmpDir, '.planning', 'phases');
|
|
const phase1 = path.join(phasesDir, '01-foundation');
|
|
fs.mkdirSync(phase1, { recursive: true });
|
|
fs.writeFileSync(path.join(phase1, '01-01-PLAN.md'), '# Plan');
|
|
|
|
// --archive-version as the final token with no value following it.
|
|
const result = runGsdTools('phases clear --confirm --archive-version', tmpDir);
|
|
assert.ok(!result.success, 'a value-less --archive-version must be an error, not a silent fallback');
|
|
assert.ok(fs.existsSync(phase1), 'phase dir must remain in place when the flag is rejected');
|
|
});
|
|
});
|
|
|
|
// ─── #2288: sibling sink — `milestone complete <version>` path safety ───────
|
|
|
|
describe('milestone complete: version path-traversal guard (#2288 security)', () => {
|
|
let tmpDir;
|
|
|
|
beforeEach(() => {
|
|
tmpDir = createTempProject();
|
|
});
|
|
|
|
afterEach(() => {
|
|
cleanup(tmpDir);
|
|
});
|
|
|
|
test('rejects a milestone-complete version containing path traversal (no write/move escapes .planning)', () => {
|
|
const phasesDir = path.join(tmpDir, '.planning', 'phases');
|
|
const phase1 = path.join(phasesDir, '01-foundation');
|
|
fs.mkdirSync(phase1, { recursive: true });
|
|
fs.writeFileSync(path.join(phase1, '01-01-PLAN.md'), '# Plan');
|
|
|
|
// `version` is interpolated into `${version}-ROADMAP.md`, `${version}-phases`,
|
|
// etc. as a MOVED/written path component — a traversal value must be rejected
|
|
// before any filesystem mutation.
|
|
const result = runGsdTools('milestone complete ../../../gsd-ms-escape', tmpDir);
|
|
assert.ok(!result.success, 'milestone complete must FAIL on a path-traversal version');
|
|
|
|
// No artifact created outside the project via traversal.
|
|
assert.ok(
|
|
!fs.existsSync(path.join(tmpDir, '..', 'gsd-ms-escape-phases')),
|
|
'no directory may be created outside the project via a traversal version',
|
|
);
|
|
assert.ok(
|
|
!fs.existsSync(path.join(tmpDir, '..', 'gsd-ms-escape-ROADMAP.md')),
|
|
'no file may be written outside the project via a traversal version',
|
|
);
|
|
// Phase dir untouched.
|
|
assert.ok(fs.existsSync(phase1), 'phase dir must remain in place when the version is rejected');
|
|
});
|
|
|
|
test('rejects a backslash-separator milestone-complete version (#2288 security)', () => {
|
|
const phasesDir = path.join(tmpDir, '.planning', 'phases');
|
|
const phase1 = path.join(phasesDir, '01-foundation');
|
|
fs.mkdirSync(phase1, { recursive: true });
|
|
fs.writeFileSync(path.join(phase1, '01-01-PLAN.md'), '# Plan');
|
|
|
|
const result = runGsdTools('milestone complete v1\\\\..\\\\evil', tmpDir);
|
|
assert.ok(!result.success, 'milestone complete must FAIL on a backslash-separator version');
|
|
assert.ok(fs.existsSync(phase1), 'phase dir must remain in place');
|
|
});
|
|
});
|
|
|
|
// ────────────────────────────────────────────────────────────────────────
|
|
// Folded from tests/enh-2433-todo-phase-linking.test.cjs — consolidation epic #1969 (B4 #1973)
|
|
// ────────────────────────────────────────────────────────────────────────
|
|
{
|
|
const { describe: __foldDescribe } = require('node:test');
|
|
__foldDescribe("folded:enh-2433-todo-phase-linking (consolidation epic #1969 B4 #1973)", () => {
|
|
'use strict';
|
|
|
|
// allow-test-rule: source-text-is-the-product (see #2433)
|
|
// Reads .md/.json/.yml product files whose deployed text IS what the
|
|
// runtime loads — testing text content tests the deployed contract.
|
|
|
|
/**
|
|
* Tests for gsd-new-milestone todo-to-phase linking (#2433).
|
|
* Verifies the workflow text contains the correct linking and auto-close steps.
|
|
*/
|
|
|
|
const { test } = require('node:test');
|
|
const assert = require('node:assert/strict');
|
|
const fs = require('node:fs');
|
|
const path = require('node:path');
|
|
|
|
const ROOT = path.resolve(__dirname, '..');
|
|
|
|
const NEW_MILESTONE = fs.readFileSync(
|
|
path.join(ROOT, 'gsd-core/workflows/new-milestone.md'), 'utf-8'
|
|
);
|
|
const EXECUTE_PHASE = fs.readFileSync(
|
|
path.join(ROOT, 'gsd-core/workflows/execute-phase.md'), 'utf-8'
|
|
);
|
|
|
|
test('new-milestone.md: step 10.5 links pending todos to roadmap phases', () => {
|
|
assert.ok(NEW_MILESTONE.includes('10.5'), 'step 10.5 should exist');
|
|
assert.ok(NEW_MILESTONE.includes('resolves_phase'), 'should reference resolves_phase field');
|
|
assert.ok(NEW_MILESTONE.includes('.planning/todos/pending'), 'should scan pending todos directory');
|
|
});
|
|
|
|
test('new-milestone.md: todo linking runs after roadmap commit', () => {
|
|
const roadmapCommitIdx = NEW_MILESTONE.indexOf('docs: create milestone v[X.Y] roadmap');
|
|
const step105Idx = NEW_MILESTONE.indexOf('10.5. Link Pending Todos');
|
|
const step11Idx = NEW_MILESTONE.indexOf('## 11. Done');
|
|
assert.ok(roadmapCommitIdx < step105Idx, 'step 10.5 should come after roadmap commit');
|
|
assert.ok(step105Idx < step11Idx, 'step 10.5 should come before step 11');
|
|
});
|
|
|
|
test('new-milestone.md: todo linking is best-effort and leaves unmatched todos unmodified', () => {
|
|
assert.ok(NEW_MILESTONE.includes('best-effort'), 'should describe best-effort matching');
|
|
assert.ok(NEW_MILESTONE.includes('unmatched'), 'should mention leaving unmatched todos alone');
|
|
assert.ok(NEW_MILESTONE.includes('confident match'), 'should gate on confident match');
|
|
});
|
|
|
|
test('new-milestone.md: step 10.5 commits tagged todos', () => {
|
|
// After #3797 architectural fix, callsites use gsd_run
|
|
assert.ok(NEW_MILESTONE.includes('gsd_run query commit'), 'should commit tagged todos');
|
|
assert.ok(NEW_MILESTONE.includes('resolves_phase after milestone'), 'commit message should mention resolves_phase');
|
|
});
|
|
|
|
test('new-milestone.md: success_criteria includes todo linking', () => {
|
|
assert.ok(NEW_MILESTONE.includes('resolves_phase: N'), 'success_criteria should mention resolves_phase tagging');
|
|
});
|
|
|
|
test('execute-phase.md: close_phase_todos step exists', () => {
|
|
assert.ok(EXECUTE_PHASE.includes('close_phase_todos'), 'close_phase_todos step should exist');
|
|
assert.ok(EXECUTE_PHASE.includes('resolves_phase'), 'should check resolves_phase in todos');
|
|
});
|
|
|
|
test('execute-phase.md: auto-close moves todos to completed directory', () => {
|
|
assert.ok(EXECUTE_PHASE.includes('.planning/todos/completed'), 'should move to completed dir');
|
|
assert.ok(EXECUTE_PHASE.includes('.planning/todos/pending'), 'should scan pending dir');
|
|
assert.ok(EXECUTE_PHASE.includes('mv "$TODO_FILE" "$COMPLETED_DIR/"'), 'should use mv to move files');
|
|
});
|
|
|
|
test('execute-phase.md: close_phase_todos runs after update_roadmap', () => {
|
|
const updateRoadmapIdx = EXECUTE_PHASE.indexOf('name="update_roadmap"');
|
|
const closeTodosIdx = EXECUTE_PHASE.indexOf('name="close_phase_todos"');
|
|
assert.ok(updateRoadmapIdx < closeTodosIdx, 'close_phase_todos should run after update_roadmap');
|
|
});
|
|
|
|
test('execute-phase.md: auto-close never blocks phase completion', () => {
|
|
const closeTodosSection = EXECUTE_PHASE.slice(
|
|
EXECUTE_PHASE.indexOf('name="close_phase_todos"'),
|
|
EXECUTE_PHASE.indexOf('name="delegate_post_completion_to_transition"')
|
|
);
|
|
assert.ok(
|
|
closeTodosSection.includes('never blocks') || closeTodosSection.includes('additive'),
|
|
'close_phase_todos should be non-blocking'
|
|
);
|
|
});
|
|
|
|
test('execute-phase.md: awk extracts resolves_phase from YAML frontmatter', () => {
|
|
assert.ok(EXECUTE_PHASE.includes('awk'), 'should use awk for frontmatter extraction');
|
|
assert.ok(EXECUTE_PHASE.includes('resolves_phase:'), 'awk pattern should match resolves_phase key');
|
|
});
|
|
});
|
|
}
|
|
|
|
// ────────────────────────────────────────────────────────────────────────
|
|
// #2308 / #2334 follow-up: new-milestone.md must not clobber the shared
|
|
// PROJECT.md when a workstream is active, and must propagate ${GSD_WS} to
|
|
// downstream routing. Step 1 and Step 6's bash fences are extracted and
|
|
// EXECUTED (not grepped) so these tests fail on an inert guard — e.g. the
|
|
// step-6 conditional merely being PRESENT (`if [ -n "$GSD_WS" ]`) is not
|
|
// enough if GSD_WS was never re-derived and is always empty at runtime.
|
|
// ────────────────────────────────────────────────────────────────────────
|
|
describe('new-milestone.md: workstream-aware PROJECT.md guard (#2308)', () => {
|
|
const workflowPath = path.join(__dirname, '..', 'gsd-core', 'workflows', 'new-milestone.md');
|
|
// readFileNormalized() strips \r\n -> \n before either extractor below slices
|
|
// a fence out of `content` — both fences are handed to execFileSync('bash', ...)
|
|
// in runStep1/runStep6Commit, so an un-normalized read on a Windows checkout
|
|
// would break bash mid-script (DEFECT.TEST-SHELL-PIPELINE-NONPORTABLE, #2650).
|
|
const content = readFileNormalized(workflowPath);
|
|
|
|
// #2994 fragmentization moved the 7.5 reset-phase-safety section (including
|
|
// its "/gsd:new-milestone --reset-phase-numbers ${GSD_WS}" rerun hint) out
|
|
// of new-milestone.md into gsd-core/workflows/new-milestone/steps/reset-phase-safety.md
|
|
// behind a section marker. Only the routing-interpolation test below needs
|
|
// that moved text, so it reads host + step file combined instead of
|
|
// widening `content` (used for host-only fence extraction elsewhere in
|
|
// this describe block).
|
|
const contentWithSteps = content + '\n' + fs.readFileSync(
|
|
path.join(__dirname, '..', 'gsd-core', 'workflows', 'new-milestone', 'steps', 'reset-phase-safety.md'),
|
|
'utf8'
|
|
);
|
|
|
|
// #2994 final slice: Step 4's "Part A" milestone-state write moved out of
|
|
// new-milestone.md into gsd-core/workflows/new-milestone/steps/
|
|
// project-md-milestone-write.md behind a section marker. The
|
|
// "step 4 scopes the workstream skip" test below asserts on Part A's
|
|
// actual body (GSD_WS mentions, the workstream skip description) — rather
|
|
// than widen `content` for every test in this block, SPLICE the step
|
|
// file's content into the marker's exact position so partAIdx/partBIdx
|
|
// position-sensitive slicing below still works. A non-vacuity check
|
|
// (blank the step file, confirm the splice fails, restore) backs this.
|
|
const PROJECT_MD_STEP_PATH = path.join(
|
|
__dirname, '..', 'gsd-core', 'workflows', 'new-milestone', 'steps', 'project-md-milestone-write.md'
|
|
);
|
|
const PROJECT_MD_MARKER_RE = /<!-- gsd:section id="project-md-milestone-write"[\s\S]*?<!-- \/gsd:section -->/;
|
|
function contentWithProjectMdStepSpliced() {
|
|
const stepBody = fs.readFileSync(PROJECT_MD_STEP_PATH, 'utf8');
|
|
assert.match(content, PROJECT_MD_MARKER_RE, 'project-md-milestone-write marker not found in new-milestone.md');
|
|
return content.replace(PROJECT_MD_MARKER_RE, stepBody);
|
|
}
|
|
|
|
// Locate the first ```bash fence strictly between two headings.
|
|
function extractFenceBetween(markdown, startHeading, endHeading) {
|
|
const startIdx = markdown.indexOf(startHeading);
|
|
const endIdx = markdown.indexOf(endHeading);
|
|
assert.ok(startIdx !== -1, `heading not found: ${startHeading}`);
|
|
assert.ok(endIdx !== -1, `heading not found: ${endHeading}`);
|
|
assert.ok(startIdx < endIdx, `${startHeading} must precede ${endHeading}`);
|
|
const section = markdown.slice(startIdx, endIdx);
|
|
const bashBlocks = extractBashBlocks(section);
|
|
assert.ok(bashBlocks.length > 0, `no bash fence found between "${startHeading}" and "${endHeading}"`);
|
|
return bashBlocks[0];
|
|
}
|
|
|
|
// Step 6 has multiple ```bash fences; locate the one containing `marker`.
|
|
function extractFenceContaining(markdown, startHeading, endHeading, marker) {
|
|
const startIdx = markdown.indexOf(startHeading);
|
|
const endIdx = markdown.indexOf(endHeading);
|
|
assert.ok(startIdx !== -1 && endIdx !== -1 && startIdx < endIdx, 'headings not found in order');
|
|
const section = markdown.slice(startIdx, endIdx);
|
|
for (const block of extractBashBlocks(section)) {
|
|
if (block.includes(marker)) return block;
|
|
}
|
|
assert.fail(`no bash fence containing "${marker}" found between "${startHeading}" and "${endHeading}"`);
|
|
return null;
|
|
}
|
|
|
|
describe('step 1: --ws parsing is real, executable shell (not prose)', () => {
|
|
const step1Fence = extractFenceBetween(content, '## 1. Load Context', '## 2. Gather Milestone Goals');
|
|
|
|
function runStep1(argumentsValue) {
|
|
const script = `ARGUMENTS=${JSON.stringify(argumentsValue)}\n${step1Fence}\n` +
|
|
'printf \'GSD_WS=[%s]\\nMILESTONE_ARG=[%s]\\n\' "$GSD_WS" "$MILESTONE_ARG"';
|
|
const r = runHookSeam('-c', [script], { interpreter: 'bash' });
|
|
throwIfFailed(r, 'bash <step1 fence>');
|
|
const out = r.stdout;
|
|
return {
|
|
gsdWs: /GSD_WS=\[(.*)\]/.exec(out)[1],
|
|
milestoneArg: /MILESTONE_ARG=\[(.*)\]/.exec(out)[1],
|
|
};
|
|
}
|
|
|
|
test('parses --ws <name> into GSD_WS and strips it from the milestone name (finding 6)', () => {
|
|
const { gsdWs, milestoneArg } = runStep1('--ws search v2.0 Search');
|
|
assert.strictEqual(gsdWs, '--ws search');
|
|
assert.strictEqual(milestoneArg, 'v2.0 Search');
|
|
});
|
|
|
|
test('leaves GSD_WS empty when --ws is absent, milestone name unaffected', () => {
|
|
const { gsdWs, milestoneArg } = runStep1('v2.0 Search');
|
|
assert.strictEqual(gsdWs, '');
|
|
assert.strictEqual(milestoneArg, 'v2.0 Search');
|
|
});
|
|
});
|
|
|
|
describe('step 6: commit stages PROJECT.md in both modes, with no cross-step guard', () => {
|
|
const step6CommitFence = extractFenceContaining(
|
|
content,
|
|
'## 6. Cleanup and Commit',
|
|
'## 7. Load Context and Resolve Models',
|
|
'docs: start milestone v[X.Y] [Name]'
|
|
);
|
|
|
|
function runStep6Commit(argumentsValue) {
|
|
const gsdRunStub = 'gsd_run() { printf "%s\\n" "gsd_run_call:$*"; }\n';
|
|
const script = `ARGUMENTS=${JSON.stringify(argumentsValue)}\n${gsdRunStub}${step6CommitFence}`;
|
|
const r = runHookSeam('-c', [script], { interpreter: 'bash' });
|
|
throwIfFailed(r, 'bash <step6 commit fence>');
|
|
return r.stdout;
|
|
}
|
|
|
|
// Step 4 Part A's guard — not this commit — is what protects the shared
|
|
// heading. Part B's Evolution backfill DOES write PROJECT.md in workstream
|
|
// mode, so a ws-mode branch that dropped PROJECT.md from --files would
|
|
// strand that edit uncommitted.
|
|
for (const [mode, args] of [['ws', '--ws search v2.0 Search'], ['flat', 'v2.0 Search']]) {
|
|
test(`${mode} mode: --files stages PROJECT.md so Part B's Evolution backfill is committed`, () => {
|
|
const out = runStep6Commit(args);
|
|
assert.ok(
|
|
out.includes('--files .planning/PROJECT.md .planning/STATE.md'),
|
|
`expected PROJECT.md + STATE.md --files in ${mode} mode, got: ${out}`
|
|
);
|
|
});
|
|
}
|
|
|
|
test('does not guard the commit on GSD_WS — a cross-step variable is always empty here', () => {
|
|
// Regression guard for the inert-guard trap: GSD_WS is assigned in Step
|
|
// 1's shell, and each step's bash block runs in its own shell (the same
|
|
// reason Step 5 round-trips OUTGOING_MILESTONE through a file). A
|
|
// `[ -n "$GSD_WS" ]` branch here reads an unset variable, always takes
|
|
// the flat branch, and only appears to work.
|
|
assert.ok(
|
|
!/\[\s*-n\s*"\$GSD_WS"\s*\]/.test(step6CommitFence),
|
|
`step 6 must not branch on a cross-step GSD_WS; got fence:\n${step6CommitFence}`
|
|
);
|
|
});
|
|
});
|
|
|
|
test('routing interpolations still propagate ${GSD_WS} at the documented lines', () => {
|
|
assert.ok(
|
|
contentWithSteps.includes('/gsd:new-milestone --reset-phase-numbers ${GSD_WS}'),
|
|
'reset-phase-numbers rerun hint should propagate ${GSD_WS}'
|
|
);
|
|
assert.ok(
|
|
content.includes('/gsd:discuss-phase [N] ${GSD_WS}'),
|
|
'discuss-phase routing hint should propagate ${GSD_WS}'
|
|
);
|
|
assert.ok(
|
|
content.includes('/gsd:plan-phase [N] ${GSD_WS}'),
|
|
'plan-phase routing hint should propagate ${GSD_WS}'
|
|
);
|
|
});
|
|
|
|
test('success criteria reflects PROJECT.md update is skipped in workstream mode', () => {
|
|
assert.match(
|
|
content,
|
|
/PROJECT\.md updated with Current Milestone section.*skipped.*workstream/i,
|
|
'success criteria should note the PROJECT.md step is skipped in workstream mode'
|
|
);
|
|
});
|
|
|
|
test('step 4 scopes the workstream skip to the milestone-state write only; Evolution repair always runs (finding 2)', () => {
|
|
const splicedContent = contentWithProjectMdStepSpliced();
|
|
const step4Idx = splicedContent.indexOf('## 4. Update PROJECT.md');
|
|
const step5Idx = splicedContent.indexOf('## 5. Update STATE.md');
|
|
assert.ok(step4Idx !== -1 && step5Idx !== -1 && step4Idx < step5Idx, 'steps 4 and 5 should be locatable');
|
|
const step4Body = splicedContent.slice(step4Idx, step5Idx);
|
|
|
|
const partAIdx = step4Body.indexOf('Part A');
|
|
const partBIdx = step4Body.indexOf('Part B');
|
|
assert.ok(partAIdx !== -1 && partBIdx !== -1 && partAIdx < partBIdx, 'step 4 should have distinct Part A / Part B sections');
|
|
|
|
const partABody = step4Body.slice(partAIdx, partBIdx);
|
|
const partBBody = step4Body.slice(partBIdx);
|
|
|
|
assert.match(partABody, /skip/i, 'Part A should describe the workstream skip');
|
|
assert.ok(partABody.includes('GSD_WS'), 'Part A guard should be keyed on GSD_WS');
|
|
assert.match(
|
|
step4Body,
|
|
/shared/i,
|
|
'step 4 should justify the guard by pointing at PROJECT.md being the shared file'
|
|
);
|
|
|
|
// The Evolution structural repair must be reachable OUTSIDE Part A's skip,
|
|
// and Part B's own text must state it is unconditional.
|
|
assert.ok(!partABody.includes('## Evolution'), 'Evolution repair must NOT be nested inside the guarded Part A');
|
|
assert.ok(partBBody.includes('## Evolution'), 'Part B must contain the Evolution section template');
|
|
assert.match(partBBody, /always runs/i, 'Part B must state it always runs regardless of GSD_WS');
|
|
});
|
|
});
|