* test(#3003): failing-first suite for declared deletions in cleanup-wave Binds the guard's opt-in before it exists, so the suite is RED against next. The rows that carry the weight are the over-authorization set: a directory declaration must not authorize its children, a glob declaration must authorize nothing, and a declaration must not act as a string prefix of another path. Each of those BLOCKS, and each would PASS under a prefix, glob, or startsWith matcher — which is how a path list quietly degrades into the boolean opt-in #3003 explicitly rejected. The glob row matters most: declaredScopePrefix already returns null ("matches everything") for a glob-leading pattern, correct for the advisory it serves and catastrophic for a gate. Also pinned: a failed deletion check blocks on its own reason rather than being filtered into a pass; the block detail names only the undeclared residue so the operator is not misdirected by paths that were fine; an entry with no declaration blocks exactly as before; junk and non-array declarations do not authorize; and a blocked entry still isolates rather than aborting the wave (#2852, which must stay fixed). Two advisory rows cover an interaction found while designing: git diff --name-only includes deleted paths, so without unioning the declaration into the #2596 scope check, authorizing a deletion would raise SCOPE_OUT_OF_DECLARED against the very path just authorized. A seeded property states the whole invariant the three over-authorization rows sample: a deletion merges iff its normalized path is in the declared set. * feat(#3003): declared deletions opt-in for the cleanup-wave guard The deletions guard blocked the merge-back of any executor branch whose diff removed a file, with no way to say a removal was intended. A plan that folded one test file into a sibling could not be merged by the tool meant to merge it, forcing a manual --no-ff outside the tool -- strictly less safe than what the guard protects against. A plan now declares removals in its own frontmatter (files_deleted), and that list rides the same path files_modified already travels: plan-document parse -> phase plan JSON -> the per-plan worktree gate -> record-agent/create --deletions -> declared_deletions on the manifest entry -> the guard. The guard blocks only the deletions NOT in that list. A path list rather than a boolean, per the pinned decision: a boolean disarms the guard for the whole entry, so an unexpected deletion riding along with a declared one would pass unnoticed. Matching is exact after the module's shared normalizer -- never a prefix, never a glob. Both would let one declaration authorize a whole set, which is the mass-deletion accident the guard exists to catch. That also means declaredScopePrefix is deliberately NOT reused here: it returns null ("matches everything") for a glob-leading pattern, which is right for the advisory it serves and would silently disarm a gate. The block detail now carries only the undeclared residue, so an operator is not sent looking at paths that were fine. A failed deletion check still blocks on its own reason and is never filtered into a pass. A blocked entry still isolates rather than aborting the wave (#2852). The #2596 scope advisory unions the declaration into its declared set -- git diff --name-only includes deleted paths, so without that, authorizing a deletion would immediately warn that the same path was out of declared scope. Optional and additive throughout: files_deleted is absent from PLAN_REQUIRED_FIELDS, a manifest entry without declared_deletions keeps the original unconditional block, and omitting --deletions leaves the on-disk entry shape untouched. Supersedes the spent #2856 emitted-drift ack entry for execute-phase.md, the same supersede that entry performed on #3370 and #3370 on #3324. * fix(#3003): wire --deletions on every dispatch surface, not just one Review found the feature inert on two of three dispatch paths. execute-phase.md (harness inline) passed --deletions, but the orchestrator-worktree path (executor-isolation-dispatch.md, worktree.create) and the Fleet-parallel batch path (capabilities/claude-orchestration/fragments/execute-wave-pre.md, worktree.record-agent) still passed only --files. A plan declaring files_deleted would have merged on one path and been blocked on the other two -- the exact bug #3003 exists to fix, left unfixed where most of the isolation actually runs. Worse, per-plan-worktree-gate.md already claimed --deletions was passed 'on the same worktree.record-agent / worktree.create calls', which was false for both untouched sites. A doc asserting coverage that does not exist is how a gap survives review. All four surfaces now pass the flag, verified by sweeping every .md under gsd-core/, capabilities/, commands/, skills/ and agents/ that invokes worktree.record-agent or worktree.create: each one that passes --files now also passes --deletions. The isolation-dispatch note explains why this flag, unlike --files, is not advisory -- omitting it does not skip a check, it blocks a merge the plan declared. Regenerates capability-registry.cjs, which the fragment edit made stale. Neither newly-grown file needs an emitted-drift ack: executor-isolation-dispatch.md sits under workflows/execute-phase/steps/ and execute-wave-pre.md under capabilities/, both outside currentSizes()'s non-recursive scan of gsd-core/workflows/ and agents/. * docs(#3003): document files_deleted where a plan author will actually find it The feature's entire user surface is one plan-frontmatter field, and the canonical reference for that frontmatter -- docs/reference/plan-md.md, the table that documents every other key -- never mentioned it. A field nobody can discover ships as a field nobody uses. Adds the files_deleted row and an example entry in all five locales (en, ja-JP, zh-CN, ko-KR, pt-BR), stating the property that makes the opt-in safe: matching is exact per path after separator normalization, with no globs and no directory prefixes, so a declaration can never authorize more than it literally lists, and omitting the field keeps the guard's original unconditional block. Also corrects two claims in the scope-conformance how-to that this change made false. Its opening paragraph described the recorded declared scope as files_modified alone; declared_deletions is now unioned into that comparison. Its "Renames are not detected specially" bullet asserted the deletions guard blocks any entry whose diff contains a deletion, full stop -- which was the whole point of #3003 and is no longer true. Reworked to say what now decides a rename's fate: declare the old path in files_deleted and both halves become ordinary paths for the advisory check, which is also why the old path needs no separate files_modified entry. Documentation that describes the pre-change behavior of the thing being changed is worse than no documentation, because a reader trusts it. * fix(#3003): close every review finding on the declared-deletions opt-in Two independent isolated reviewers, correctness and security. Neither found a blocker; both found real defects, and the directive treats a finding at any severity as blocking. All of them are fixed here. MAJOR -- the submodule worktree gate could not see a deletion-only plan. per-plan-worktree-gate.md intersected $SUBMODULE_PATHS against $PLAN_FILES alone, while $PLAN_DELETIONS was extracted and then never used. Before files_deleted existed, a path had to appear in files_modified to be planned at all, so the gate saw it; the new field plus the new docs telling authors a deleted path needs no files_modified entry opened a hole where a plan whose only submodule touch is a removal kept worktree isolation on -- the exact case #2772 disabled it for. Both channels now feed the intersection. Note the posture is deliberately the OPPOSITE of the cleanup-wave guard: there the channels stay apart because a deletion AUTHORIZATION must never be inferred; here they merge because a safety fallback must never MISS a touch. MAJOR -- same-wave conflict detection could not see a deletion. The planner's implicit-dependency rule compared files_modified only, so plan A editing src/x.ts and plan B declaring files_deleted: [src/x.ts] scored as conflict-free and ran in parallel: one branch removing what the other is writing, which is the sharpest conflict there is. Overlap is now computed across both channels. MINOR (both reviewers, one root cause) -- the advisory union gave one field two matching rules. declared_deletions was unioned into the scope list handed to planWaveScopeConformance, which reads it with prefix-and-glob semantics. So a field that is exact-match-only at the gate silently became wider at the advisory: ["*.md"], inert at the gate, yielded a null prefix meaning "matches everything" and muted the advisory completely, and ["src"] muted all of src/. The union also activated the advisory on plans that declared no modification scope at all, warning on every modified path. Replaced with subtraction from the findings, gated on files_modified alone. One field, one rule, everywhere. MINOR -- core.quotepath made the feature silently inert for non-ASCII paths. git emits "tests/\303\251.ts" C-escaped and quoted, which never equals the declared plain path, so a correctly declared deletion of tests/é.ts would block forever with nothing pointing at the encoding. Both diffs now pass -c core.quotepath=false. NIT -- flag() consumed a following flag as a value, so --deletions --files x swallowed --files and dropped both. Now treated as a missing declaration, which fails closed. Fixed at both call sites; the helper is duplicated verbatim in cmdWorktreeRecordAgent and cmdWorktreeCreate and leaving one would reintroduce it. TEST -- one test passed for the wrong reason. "a declared deletion is in scope for the advisory" asserted only that warnings omit the deleted path; under a full revert the entry blocks first, warnings come back empty, and the negative assertion passes anyway. It now asserts the entry actually merged, which is the load-bearing half. Four regressions added, one per fix above. Docs corrected rather than extended. The rename bullet in the scope-conformance how-to claimed a rename whose delete side is undeclared never reaches the advisory. Verified false: git's rename detection is on by default, so a pure rename is a single R entry that appears in no --diff-filter=D output and was never gated, before or after #3003. Only a rename that edits enough to fall below the similarity threshold decomposes into add+delete. The pre-existing sentence made the same wrong claim; this restates it correctly instead of sharpening the error. The localized plan-md.md reference edits are reverted: the PR template requires docs content added here to be English, and the translations already lag by three fields, so English-only is the repo's standing posture, not an oversight. Agent-file size caps respected: gsd-planner.md is XL-tier by bytes but carries a separate 49152-LF-CHAR cap asserted by four suites, so its edit is deliberately terse and lands at 49141 with 11 chars of headroom, with the rationale moved to docs/reference/plan-md.md, which has no cap. gsd-plan-checker.md lands at 49107 bytes, 45 under the LARGE cap. Both acks merged into the existing fragments that already name those paths, since two ack sources may never name the same path. * fix(#3003): decode git's path quoting instead of changing the git argv The previous commit's non-ASCII fix turned the remote suite red: 44 failures, 42 of them "unexpected git call: -c core.quotepath=false diff --diff-filter=D --name-only ...". The suite's git mocks match on exact argv, so adding two flags to the deletions diff and the advisory diff invalidated every existing fixture in tests/worktree-safety.test.cjs. Rewriting dozens of fixtures to accommodate one flag would be paying a large Hyrum's-law bill to fix a small defect. Both execGit calls are reverted to their original argv. The C-quoting is now decoded in normalizeScopePath instead, via a new decodeGitQuotedPath helper. That is the better fix on its own merits, not merely the cheaper one: the git argv is untouched so no fixture moves, the decode lands on the ONE normalizer already applied to both sides of the comparison so the declared and reported paths cannot disagree, and it holds regardless of the user's own core.quotepath setting rather than only when we remember to override it. A value not wrapped in a leading AND trailing quote is returned completely untouched, so the plain-ASCII path -- the overwhelmingly common case -- is byte-identical to before. Escapes decode to BYTES collected into a Buffer and UTF-8 decoded only at the end, because \303\251 is two bytes forming one character and decoding them separately yields mojibake. Malformed input never throws: a trailing lone backslash or a short octal escape degrades to the literal character, since one bad path must not take down a cleanup wave. Caught while reviewing the helper: the non-escape branch pushed a UTF-16 code unit rather than UTF-8 bytes. Git always escapes non-ASCII so its own output was fine, but this normalizer runs on the DECLARED side too, and an author may write a quoted path holding a literal é -- pushing 0xE9 alone is invalid UTF-8, so the declaration would decode to a replacement character and silently stop matching. That is precisely the failure this change removes, reintroduced on the other side of the comparison. Now converts whole code points, surrogate pairs intact. The other 2 failures: tests/parallel-dependent-plans.test.cjs pins the exact unbackticked substring "files_modified overlap" in gsd-planner.md, and rewording that comment to "declared-scope overlap" deleted it. The comment is restored verbatim and the files_deleted change rides in the pseudocode and the Rule sentence instead. Recorded in the ack fragment so the next contributor does not rediscover it the same way. Four regression tests cover the decode through the public cleanup-wave seam (the helper is module-private): a declared non-ASCII deletion merges against a C-quoted git report, the symmetric case where the DECLARATION is the quoted form, an undeclared non-ASCII deletion still blocks with the residue naming the decoded path an operator can act on, and a path merely containing a quote is left alone. Plain ASCII was already covered and is not duplicated. * fix(#3003): revert the leading-dash flag guard, the review nit was wrong The remote suite came back with 2 failures, down from 44, and both point at the same thing: tests/worktree-safety.test.cjs:7045 already pins the opposite contract, deliberately. test('a flag-shaped --files value is not re-parsed as a flag', ...) recordAgent(['--files', '--branch']) -> files_modified === ['--branch'] -> branch === 'worktree-agent-a1' ("the real --branch value must be untouched") So consuming the next argv element positionally, whatever its shape, is the tested intent of this parser, not an oversight. The security reviewer's nit claimed --deletions --files x would "swallow --files and drop both". It does not: each flag runs its own indexOf, so --deletions records the literal '--files' while --files independently still resolves to x. And that literal is a path git never reports as deleted, so it authorizes nothing -- already fail-closed with no guard at all. The guard bought no safety and silently changed --files behavior along the way, outside this issue's scope. Reverted at both call sites, which are byte-identical again, along with the test asserting the reverted behavior and the docs sentence describing it. The nit is recorded as REJECTED in the review artifact with the reasoning above, rather than as fixed -- a finding that turns out to be wrong should leave a trace of why, or the next reviewer files it again. docs/CLI-TOOLS.md now states the positional-read behavior plainly instead, so the next person meets it as documented intent rather than rediscovering it through a red suite. * chore(#3003): backfill changeset pr number to 3757 * test(#3003): cover parsePlanDocument's filesDeleted branch to clear the mutation gate CI's Stryker shard for plan-document failed at 73.28 against a break threshold of 75: 170 killed, 62 survived, 232 total. Eight of those survivors are the filesDeleted block this issue added to parsePlanDocument, which shipped with no direct coverage at all -- the field was exercised end to end through the cleanup-wave tests, but the parser itself was never called with a plan that declares it, so every mutant in the block lived. Four tests, each pinned to specific mutants rather than written for coverage percentage: - absent key yields exactly [] -- kills the array-literal seed (["Stryker was here"]) and the `fmDeleted = true` conditional, which would otherwise produce ["true"] - a scalar underscore `files_deleted:` wraps into a one-element array -- kills `fmDeleted = false`, the `&&` logical-operator swap, the `fm[""]` string mutation on the first operand, the emptied if-block, and the ternary's non-array branch - an array-valued hyphenated `files-deleted:` maps element-wise -- kills the `fm[""]` mutation on the SECOND operand (only reachable when the legacy hyphen alias is the one carrying the value) and the ternary's array branch - an empty list yields [] -- boundary case, and a genuinely distinct one from the absent key: [] is truthy in JS so it ENTERS the if, and only Array.isArray's true branch mapping over nothing produces the same [] Threshold arithmetic: 174 of 232 are needed for 75%, and these take it to about 178, so the shard clears with margin rather than landing on the line. Every expected value was confirmed by executing the built parser before being asserted, not inferred from reading the source. --------- Co-authored-by: sim <sim@local>
801 lines
35 KiB
JavaScript
801 lines
35 KiB
JavaScript
'use strict';
|
|
|
|
/**
|
|
* FAST, IN-PROCESS mutation-testing surface for `planning-inspect.cjs`,
|
|
* `plan-document.cjs`, and `planning-command-router.cjs` (#2790).
|
|
*
|
|
* Root cause this file exists to fix: `tests/planning-inspect.test.cjs` is
|
|
* INTEGRATION-shaped — it spawns a `gsd-tools` child process per case via
|
|
* `runGsdTools`. Stryker's command runner treats a `node --test <file>`
|
|
* invocation as ONE test costing whatever the slowest case costs (measured in
|
|
* CI: ~20s), and re-runs that whole file once per mutant. 640 mutants x 20s
|
|
* cannot finish inside a 15-minute shard cap — CI evidence: two shards were
|
|
* CANCELLED at 4% (27/640) after ~3 elapsed minutes. This file is the
|
|
* dedicated, spawn-free mutation surface `scripts/mutation-matrix.cjs`
|
|
* repoints those three modules' shards at; the integration suite keeps
|
|
* running unmodified in the normal (non-mutation) test job.
|
|
*
|
|
* NEVER spawn a child process here — no `runGsdTools`, `spawnSync`,
|
|
* `execFileSync`, or CLI invocation of any kind. Every case below requires
|
|
* the BUILT `.cjs` artifacts directly and calls their exports in-process.
|
|
* `plan-document.cjs` needs no filesystem at all (pure `(content) -> object`
|
|
* parser); `planning-command-router.cjs` is driven with a recording mock and
|
|
* needs no filesystem; `planning-inspect.cjs` needs small `.planning/`
|
|
* fixtures on disk (cheap disk I/O, not the cost this file exists to avoid)
|
|
* under `os.tmpdir()`.
|
|
*
|
|
* Every fixture shape and every asserted value below was verified by
|
|
* requiring the built libs directly and inspecting the real returned object
|
|
* — never guessed from reading the source alone (CLAUDE.md "verify
|
|
* assertions by executing, not retyping").
|
|
*/
|
|
|
|
const { test, describe } = require('node:test');
|
|
const assert = require('node:assert/strict');
|
|
const fs = require('node:fs');
|
|
const os = require('node:os');
|
|
const path = require('node:path');
|
|
|
|
const { cleanup } = require('./helpers.cjs');
|
|
|
|
const {
|
|
parsePlanDocument,
|
|
planIdFromFile,
|
|
TASK_KIND,
|
|
} = require('../gsd-core/bin/lib/plan-document.cjs');
|
|
|
|
const {
|
|
routePlanningCommand,
|
|
PLANNING_SUBCOMMANDS,
|
|
} = require('../gsd-core/bin/lib/planning-command-router.cjs');
|
|
|
|
const planningInspectLib = require('../gsd-core/bin/lib/planning-inspect.cjs');
|
|
const {
|
|
buildPlanningInspect,
|
|
INSPECT_DIAGNOSTIC,
|
|
TASK_STATUS,
|
|
PROVENANCE,
|
|
AGREEMENT,
|
|
} = planningInspectLib;
|
|
|
|
// ─── Shared fs fixture helpers (planning-inspect only) ────────────────────────
|
|
|
|
function writeAbs(fullPath, content) {
|
|
fs.mkdirSync(path.dirname(fullPath), { recursive: true });
|
|
fs.writeFileSync(fullPath, content);
|
|
}
|
|
|
|
function writeFile(cwd, relPath, content) {
|
|
writeAbs(path.join(cwd, relPath), content);
|
|
}
|
|
|
|
function mkCwd() {
|
|
return fs.mkdtempSync(path.join(os.tmpdir(), 'planning-inspect-unit-'));
|
|
}
|
|
|
|
function frontmatterDoc(fmLines, bodyLines) {
|
|
return ['---', ...fmLines, '---', '', ...bodyLines].join('\n');
|
|
}
|
|
|
|
function phaseDirOf(cwd, token) {
|
|
return path.join(cwd, '.planning', 'phases', token);
|
|
}
|
|
|
|
function diagnosticCodes(payload) {
|
|
return payload.diagnostics.map((d) => d.code);
|
|
}
|
|
|
|
// ═══════════════════════════════════════════════════════════════════════════
|
|
// plan-document.cjs — pure, in-memory parser
|
|
// ═══════════════════════════════════════════════════════════════════════════
|
|
|
|
describe('plan-document — objective extraction', () => {
|
|
test('extracts the first line after an <objective> tag', () => {
|
|
const parsed = parsePlanDocument(['<objective>', 'Ship the thing', '</objective>'].join('\n'));
|
|
assert.strictEqual(parsed.objective, 'Ship the thing');
|
|
});
|
|
|
|
test('falls back to frontmatter objective when no <objective> tag is present', () => {
|
|
const parsed = parsePlanDocument(frontmatterDoc(['objective: From frontmatter'], ['no objective tag here']));
|
|
assert.strictEqual(parsed.objective, 'From frontmatter');
|
|
});
|
|
|
|
test('is null when neither the tag nor frontmatter carries an objective', () => {
|
|
const parsed = parsePlanDocument('no objective anywhere');
|
|
assert.strictEqual(parsed.objective, null);
|
|
});
|
|
|
|
test('prefers the <objective> tag over frontmatter when both are present', () => {
|
|
const parsed = parsePlanDocument(frontmatterDoc(['objective: From frontmatter'], ['<objective>', 'From tag', '</objective>']));
|
|
assert.strictEqual(parsed.objective, 'From tag');
|
|
});
|
|
});
|
|
|
|
describe('plan-document — task grammar', () => {
|
|
test('parses one <task> block with name/files/acceptance/done', () => {
|
|
const parsed = parsePlanDocument([
|
|
'<tasks>',
|
|
'<task type="auto">',
|
|
' <name> Task One </name>',
|
|
' <files>a.ts, b.ts</files>',
|
|
' <acceptance_criteria>',
|
|
'- criterion one',
|
|
'* criterion two',
|
|
' </acceptance_criteria>',
|
|
' <done> All done </done>',
|
|
'</task>',
|
|
'</tasks>',
|
|
].join('\n'));
|
|
assert.strictEqual(parsed.tasks.length, 1);
|
|
const [task] = parsed.tasks;
|
|
assert.strictEqual(task.index, 1);
|
|
assert.strictEqual(task.kind, TASK_KIND.AUTO);
|
|
assert.strictEqual(task.type, 'auto');
|
|
assert.strictEqual(task.name, 'Task One');
|
|
assert.deepStrictEqual(task.plannedFiles, ['a.ts', 'b.ts']);
|
|
assert.deepStrictEqual(task.acceptanceCriteria, ['criterion one', 'criterion two']);
|
|
assert.strictEqual(task.done, 'All done');
|
|
assert.strictEqual(parsed.taskCount, parsed.tasks.length);
|
|
});
|
|
|
|
test('splits <files> on newlines as well as commas', () => {
|
|
const parsed = parsePlanDocument([
|
|
'<task type="auto">',
|
|
' <files>',
|
|
'a.ts',
|
|
'b.ts',
|
|
' </files>',
|
|
'</task>',
|
|
].join('\n'));
|
|
assert.deepStrictEqual(parsed.tasks[0].plannedFiles, ['a.ts', 'b.ts']);
|
|
});
|
|
|
|
test('falls back to ## Task N headings when no <task> blocks exist', () => {
|
|
const parsed = parsePlanDocument([
|
|
'## Task 1: Do the thing',
|
|
'some body text',
|
|
'## Task 2: Do another thing',
|
|
].join('\n'));
|
|
assert.strictEqual(parsed.tasks.length, 2);
|
|
assert.strictEqual(parsed.taskCount, 2);
|
|
assert.strictEqual(parsed.tasks[0].name, 'Task 1: Do the thing');
|
|
assert.strictEqual(parsed.tasks[0].type, null);
|
|
assert.deepStrictEqual(parsed.tasks[0].plannedFiles, []);
|
|
assert.strictEqual(parsed.tasks[1].index, 2);
|
|
assert.strictEqual(parsed.tasks[1].name, 'Task 2: Do another thing');
|
|
});
|
|
|
|
test('prefers <task> blocks over ## Task N headings when both are present', () => {
|
|
const parsed = parsePlanDocument([
|
|
'## Task 1: Legacy heading',
|
|
'<task type="auto">',
|
|
' <name>Real task</name>',
|
|
'</task>',
|
|
].join('\n'));
|
|
assert.strictEqual(parsed.tasks.length, 1);
|
|
assert.strictEqual(parsed.tasks[0].name, 'Real task');
|
|
});
|
|
|
|
test('a checkpoint task carries no name/files/acceptance/done, even if present in the tag', () => {
|
|
const parsed = parsePlanDocument([
|
|
'<task type="checkpoint:manual">',
|
|
' <decision>Ship it?</decision>',
|
|
' <name>Should be ignored</name>',
|
|
'</task>',
|
|
].join('\n'));
|
|
const [task] = parsed.tasks;
|
|
assert.strictEqual(task.kind, TASK_KIND.CHECKPOINT);
|
|
assert.strictEqual(task.type, 'checkpoint:manual');
|
|
assert.strictEqual(task.name, null);
|
|
assert.deepStrictEqual(task.plannedFiles, []);
|
|
assert.deepStrictEqual(task.acceptanceCriteria, []);
|
|
assert.strictEqual(task.done, null);
|
|
});
|
|
|
|
test('checkpoint type detection is case-insensitive and prefix-only', () => {
|
|
const parsed = parsePlanDocument('<task type="CHECKPOINT:Manual"></task>');
|
|
assert.strictEqual(parsed.tasks[0].kind, TASK_KIND.CHECKPOINT);
|
|
});
|
|
|
|
test('an unclosed <task> block is bounded by the next opening tag, never swallowing siblings', () => {
|
|
const parsed = parsePlanDocument([
|
|
'<task type="auto">',
|
|
' <name>First (unclosed)</name>',
|
|
'<task type="auto">',
|
|
' <name>Second</name>',
|
|
'</task>',
|
|
].join('\n'));
|
|
assert.strictEqual(parsed.tasks.length, 2);
|
|
assert.strictEqual(parsed.taskCount, 2);
|
|
assert.strictEqual(parsed.tasks[0].name, 'First (unclosed)');
|
|
assert.strictEqual(parsed.tasks[1].name, 'Second');
|
|
});
|
|
|
|
test('an unclosed final <task> block runs to end of document', () => {
|
|
const parsed = parsePlanDocument(['<task type="auto">', ' <name>Only task</name>'].join('\n'));
|
|
assert.strictEqual(parsed.tasks.length, 1);
|
|
assert.strictEqual(parsed.tasks[0].name, 'Only task');
|
|
});
|
|
|
|
test('taskCount always equals tasks.length', () => {
|
|
const noTasks = parsePlanDocument('no tasks here at all');
|
|
assert.strictEqual(noTasks.taskCount, 0);
|
|
assert.deepStrictEqual(noTasks.tasks, []);
|
|
});
|
|
});
|
|
|
|
describe('plan-document — frontmatter scheduling metadata', () => {
|
|
test('invalid wave, string depends_on, autonomous false, agent_hint set, scalar files_modified', () => {
|
|
const parsed = parsePlanDocument(frontmatterDoc([
|
|
'wave: not-a-number',
|
|
'depends_on: 1-01-PLAN.md',
|
|
'autonomous: false',
|
|
'agent_hint: backend-specialist',
|
|
'files_modified: src/single.ts',
|
|
], ['body']));
|
|
assert.strictEqual(parsed.declaredWave, null);
|
|
assert.deepStrictEqual(parsed.dependsOn, ['1-01-PLAN.md']);
|
|
assert.strictEqual(parsed.autonomous, false);
|
|
assert.strictEqual(parsed.agentHint, 'backend-specialist');
|
|
assert.deepStrictEqual(parsed.filesModified, ['src/single.ts']);
|
|
});
|
|
|
|
test('valid wave, array depends_on, empty agent_hint, files-modified (hyphen) array', () => {
|
|
const parsed = parsePlanDocument(frontmatterDoc([
|
|
'wave: 3',
|
|
'depends_on: [1-01-PLAN.md, 1-02-PLAN.md]',
|
|
'agent_hint: ""',
|
|
'files-modified: [a.ts, b.ts]',
|
|
], ['body']));
|
|
assert.strictEqual(parsed.declaredWave, 3);
|
|
assert.deepStrictEqual(parsed.dependsOn, ['1-01-PLAN.md', '1-02-PLAN.md']);
|
|
assert.strictEqual(parsed.agentHint, null);
|
|
assert.deepStrictEqual(parsed.filesModified, ['a.ts', 'b.ts']);
|
|
});
|
|
|
|
test('no frontmatter at all defaults wave/dependsOn/agentHint/filesModified and autonomous true', () => {
|
|
const parsed = parsePlanDocument('plain body, no frontmatter');
|
|
assert.strictEqual(parsed.declaredWave, null);
|
|
assert.deepStrictEqual(parsed.dependsOn, []);
|
|
assert.strictEqual(parsed.autonomous, true);
|
|
assert.strictEqual(parsed.agentHint, null);
|
|
assert.deepStrictEqual(parsed.filesModified, []);
|
|
});
|
|
|
|
test('empty depends_on string is dropped, not turned into a single blank entry', () => {
|
|
const parsed = parsePlanDocument(frontmatterDoc(['depends_on: ""'], ['body']));
|
|
assert.deepStrictEqual(parsed.dependsOn, []);
|
|
});
|
|
|
|
test('autonomous absent defaults to true', () => {
|
|
const parsed = parsePlanDocument(frontmatterDoc(['wave: 1'], ['body']));
|
|
assert.strictEqual(parsed.autonomous, true);
|
|
});
|
|
});
|
|
|
|
describe('plan-document — frontmatter filesDeleted', () => {
|
|
test('no frontmatter at all defaults filesDeleted to []', () => {
|
|
const parsed = parsePlanDocument('plain body, no frontmatter');
|
|
assert.deepStrictEqual(parsed.filesDeleted, []);
|
|
});
|
|
|
|
test('scalar files_deleted (underscore key) is wrapped into a one-element array', () => {
|
|
const parsed = parsePlanDocument(frontmatterDoc(['files_deleted: src/gone.ts'], ['body']));
|
|
assert.deepStrictEqual(parsed.filesDeleted, ['src/gone.ts']);
|
|
});
|
|
|
|
test('array files-deleted (hyphen key) is mapped element-wise', () => {
|
|
const parsed = parsePlanDocument(frontmatterDoc(['files-deleted: [a.ts, b.ts]'], ['body']));
|
|
assert.deepStrictEqual(parsed.filesDeleted, ['a.ts', 'b.ts']);
|
|
});
|
|
|
|
test('empty files_deleted list yields []', () => {
|
|
const parsed = parsePlanDocument(frontmatterDoc(['files_deleted: []'], ['body']));
|
|
assert.deepStrictEqual(parsed.filesDeleted, []);
|
|
});
|
|
});
|
|
|
|
describe('plan-document — planIdFromFile / TASK_KIND', () => {
|
|
test('strips the -PLAN.md suffix from a root-form plan file', () => {
|
|
assert.strictEqual(planIdFromFile('1-01-PLAN.md'), '1-01');
|
|
});
|
|
|
|
test('strips a bare PLAN.md to an empty id', () => {
|
|
assert.strictEqual(planIdFromFile('PLAN.md'), '');
|
|
});
|
|
|
|
test('a nested numbered plan file (plans/PLAN-01-foo.md) is left unchanged', () => {
|
|
// Neither the `-PLAN.md` nor bare `PLAN.md` suffix matches this shape —
|
|
// characterised, byte-for-behaviour-preserved limit (see module doc).
|
|
assert.strictEqual(planIdFromFile('plans/PLAN-01-foo.md'), 'plans/PLAN-01-foo.md');
|
|
});
|
|
|
|
test('a nested bare plan file (plans/PLAN.md) strips to its directory prefix', () => {
|
|
assert.strictEqual(planIdFromFile('plans/PLAN.md'), 'plans/');
|
|
});
|
|
|
|
test('TASK_KIND is the frozen two-member vocabulary', () => {
|
|
assert.deepStrictEqual(TASK_KIND, { AUTO: 'auto', CHECKPOINT: 'checkpoint' });
|
|
assert.ok(Object.isFrozen(TASK_KIND));
|
|
});
|
|
});
|
|
|
|
// ═══════════════════════════════════════════════════════════════════════════
|
|
// planning-command-router.cjs — pure dispatch, recording mocks, no fs
|
|
// ═══════════════════════════════════════════════════════════════════════════
|
|
|
|
describe('planning-command-router', () => {
|
|
function mockError() {
|
|
const calls = [];
|
|
const fn = (message, reason) => calls.push({ message, reason });
|
|
fn.calls = calls;
|
|
return fn;
|
|
}
|
|
|
|
function mockInspect() {
|
|
const calls = [];
|
|
return {
|
|
calls,
|
|
cmdPlanningInspect(cwd, raw) {
|
|
calls.push({ cwd, raw });
|
|
},
|
|
};
|
|
}
|
|
|
|
test('PLANNING_SUBCOMMANDS is exactly ["inspect"]', () => {
|
|
assert.deepStrictEqual(PLANNING_SUBCOMMANDS, ['inspect']);
|
|
});
|
|
|
|
test('dispatches "planning inspect" and forwards cwd/raw verbatim', () => {
|
|
const error = mockError();
|
|
const mod = mockInspect();
|
|
routePlanningCommand({ args: ['planning', 'inspect'], cwd: '/some/cwd', raw: true, error, _planningInspect: mod });
|
|
assert.deepStrictEqual(error.calls, []);
|
|
assert.deepStrictEqual(mod.calls, [{ cwd: '/some/cwd', raw: true }]);
|
|
});
|
|
|
|
test('forwards a falsy raw and a different cwd verbatim (not defaulted)', () => {
|
|
const error = mockError();
|
|
const mod = mockInspect();
|
|
routePlanningCommand({ args: ['planning', 'inspect'], cwd: '/other', raw: false, error, _planningInspect: mod });
|
|
assert.deepStrictEqual(mod.calls, [{ cwd: '/other', raw: false }]);
|
|
});
|
|
|
|
test('a missing subcommand yields sdk_unknown_command and never calls the mock', () => {
|
|
const error = mockError();
|
|
const mod = mockInspect();
|
|
routePlanningCommand({ args: ['planning'], cwd: '/x', raw: false, error, _planningInspect: mod });
|
|
assert.strictEqual(error.calls.length, 1);
|
|
assert.strictEqual(error.calls[0].reason, 'sdk_unknown_command');
|
|
assert.strictEqual(error.calls[0].message, 'Unknown planning subcommand. Available: inspect');
|
|
assert.deepStrictEqual(mod.calls, []);
|
|
});
|
|
|
|
test('an unknown subcommand yields sdk_unknown_command and never calls the mock', () => {
|
|
const error = mockError();
|
|
const mod = mockInspect();
|
|
routePlanningCommand({ args: ['planning', 'bogus'], cwd: '/x', raw: false, error, _planningInspect: mod });
|
|
assert.strictEqual(error.calls.length, 1);
|
|
assert.strictEqual(error.calls[0].reason, 'sdk_unknown_command');
|
|
assert.deepStrictEqual(mod.calls, []);
|
|
});
|
|
|
|
test('a stray positional argument is a usage error naming the offender, never dispatched', () => {
|
|
const error = mockError();
|
|
const mod = mockInspect();
|
|
routePlanningCommand({ args: ['planning', 'inspect', 'extra'], cwd: '/x', raw: false, error, _planningInspect: mod });
|
|
assert.strictEqual(error.calls.length, 1);
|
|
assert.strictEqual(error.calls[0].reason, 'usage');
|
|
assert.strictEqual(
|
|
error.calls[0].message,
|
|
'planning inspect takes no arguments; got positional argument: extra. Usage: gsd-tools query planning inspect',
|
|
);
|
|
assert.deepStrictEqual(mod.calls, []);
|
|
});
|
|
|
|
test('an unknown flag is a usage error naming it as a flag, never dispatched', () => {
|
|
const error = mockError();
|
|
const mod = mockInspect();
|
|
routePlanningCommand({ args: ['planning', 'inspect', '--nope'], cwd: '/x', raw: false, error, _planningInspect: mod });
|
|
assert.strictEqual(error.calls.length, 1);
|
|
assert.strictEqual(error.calls[0].reason, 'usage');
|
|
assert.strictEqual(
|
|
error.calls[0].message,
|
|
'planning inspect takes no arguments; got flag: --nope. Usage: gsd-tools query planning inspect',
|
|
);
|
|
assert.deepStrictEqual(mod.calls, []);
|
|
});
|
|
|
|
test('defaults to the real planning-inspect module when no mock is injected', (t) => {
|
|
// No fixtures — buildPlanningInspect degrades gracefully on an absent
|
|
// .planning/ dir, so this proves the `mod ?? planningInspect` fallback
|
|
// wiring without spawning anything.
|
|
const cwd = mkCwd();
|
|
t.after(() => cleanup(cwd));
|
|
const error = mockError();
|
|
routePlanningCommand({ args: ['planning', 'inspect'], cwd, raw: true, error });
|
|
assert.deepStrictEqual(error.calls, []);
|
|
});
|
|
});
|
|
|
|
// ═══════════════════════════════════════════════════════════════════════════
|
|
// planning-inspect.cjs — small on-disk fixtures, in-process buildPlanningInspect
|
|
// ═══════════════════════════════════════════════════════════════════════════
|
|
|
|
describe('planning-inspect — planning root absent', () => {
|
|
test('degrades every section to a non-answer with PLANNING_ROOT_ABSENT', (t) => {
|
|
const cwd = mkCwd();
|
|
t.after(() => cleanup(cwd));
|
|
|
|
const result = buildPlanningInspect(cwd);
|
|
|
|
assert.strictEqual(result.schema_version, 1);
|
|
assert.strictEqual(result.generated_from.planning_root, null);
|
|
assert.deepStrictEqual(result.phases, []);
|
|
assert.deepStrictEqual(result.orphan_phase_dirs, []);
|
|
assert.deepStrictEqual(result.requirements, []);
|
|
assert.deepStrictEqual(result.progress.accepted_phases, { completed: 0, total: 0, percent: null, scope: 'unreadable' });
|
|
assert.deepStrictEqual(result.progress.completed_plans, { completed: 0, total: 0, percent: null, scope: 'unreadable' });
|
|
assert.strictEqual(result.milestone.scope, 'unreadable');
|
|
assert.deepStrictEqual(diagnosticCodes(result), [
|
|
INSPECT_DIAGNOSTIC.PLANNING_ROOT_ABSENT,
|
|
INSPECT_DIAGNOSTIC.ROADMAP_UNSCOPED,
|
|
INSPECT_DIAGNOSTIC.REQUIREMENTS_ABSENT,
|
|
INSPECT_DIAGNOSTIC.PERCENT_WITHHELD,
|
|
INSPECT_DIAGNOSTIC.PERCENT_WITHHELD,
|
|
]);
|
|
});
|
|
});
|
|
|
|
describe('planning-inspect — healthy two-phase project', () => {
|
|
function buildHealthy(cwd) {
|
|
writeFile(cwd, '.planning/STATE.md', frontmatterDoc(
|
|
["gsd_state_version: '1.0'", 'status: planning', 'milestone: v1.0'],
|
|
['## Current Position', '', 'Plan: 1-01-PLAN.md', ''],
|
|
));
|
|
writeFile(cwd, '.planning/ROADMAP.md', [
|
|
'## v1.0 Current 🚧', '', '## Phases', '',
|
|
'- [x] **Phase 1: Foo** - stub',
|
|
'- [ ] **Phase 2: Bar** - stub',
|
|
'',
|
|
'### Phase 1: Foo', '', 'Ship the foo module end to end.', '',
|
|
'**Depends on:** Phase 0', '',
|
|
'### Phase 2: Bar', '', 'Ship the bar module.', '',
|
|
].join('\n'));
|
|
writeFile(cwd, '.planning/REQUIREMENTS.md', [
|
|
'# Requirements: Test', '', '## v1 Requirements', '',
|
|
'- [x] **AUTH-01**: User can sign up',
|
|
'- [ ] **AUTH-02**: User can log in',
|
|
'',
|
|
'## Traceability', '',
|
|
'| Requirement | Phase | Status |',
|
|
'|-------------|-------|--------|',
|
|
'| AUTH-01 | Phase 1 | Complete |',
|
|
'| AUTH-02 | Phase 2 | Pending |',
|
|
'',
|
|
].join('\n'));
|
|
for (const [token, name] of [['1', 'foo'], ['2', 'bar']]) {
|
|
const phaseDir = phaseDirOf(cwd, `0${token}-${name}`);
|
|
writeAbs(path.join(phaseDir, `${token}-01-PLAN.md`), frontmatterDoc(['wave: 1'], [
|
|
'<objective>', `Ship ${name}`, '</objective>', '',
|
|
'<tasks>', '',
|
|
'<task type="auto">',
|
|
` <name>Task 1: Build ${name}</name>`,
|
|
` <files>src/${name}.ts</files>`,
|
|
' <done>Done</done>',
|
|
'</task>', '',
|
|
'</tasks>',
|
|
]));
|
|
writeAbs(path.join(phaseDir, `${token}-01-SUMMARY.md`), frontmatterDoc(['status: complete'], [
|
|
'# Summary', '', '## Files Created/Modified', `- \`src/${name}.ts\` - ${name}`,
|
|
]));
|
|
writeAbs(path.join(phaseDir, `${token}-VERIFICATION.md`), ['---', 'status: passed', '---', ''].join('\n'));
|
|
}
|
|
}
|
|
|
|
test('reports exact scope, percent, requirement, plan-metadata and phase-goal values', (t) => {
|
|
const cwd = mkCwd();
|
|
t.after(() => cleanup(cwd));
|
|
buildHealthy(cwd);
|
|
|
|
const result = buildPlanningInspect(cwd);
|
|
|
|
assert.strictEqual(result.phases.length, 2);
|
|
assert.strictEqual(result.milestone.version, 'v1.0');
|
|
|
|
const [foo, bar] = result.phases;
|
|
assert.strictEqual(foo.dir, '01-foo');
|
|
assert.strictEqual(foo.phase_id, '01');
|
|
assert.strictEqual(foo.complete, true);
|
|
assert.strictEqual(foo.scope, 'complete');
|
|
assert.deepStrictEqual(foo.goal, { value: 'Ship the foo module end to end.', scope: 'complete' });
|
|
assert.deepStrictEqual(foo.dependencies, { value: ['0'], scope: 'complete' });
|
|
assert.deepStrictEqual(foo.verification, { status: 'passed', next_action: 'Verification passed — continue.' });
|
|
assert.deepStrictEqual(foo.roadmap_acceptance, { checkbox: true, authoritative: false });
|
|
|
|
assert.strictEqual(bar.dir, '02-bar');
|
|
assert.deepStrictEqual(bar.dependencies, { value: [], scope: 'complete' });
|
|
assert.deepStrictEqual(bar.roadmap_acceptance, { checkbox: false, authoritative: false });
|
|
|
|
const [plan] = foo.plans;
|
|
assert.strictEqual(plan.id, '1-01');
|
|
assert.strictEqual(plan.wave, 1);
|
|
assert.deepStrictEqual(plan.dependsOn, []);
|
|
assert.strictEqual(plan.hasSummary, true);
|
|
assert.deepStrictEqual(plan.changedFiles, ['src/foo.ts']);
|
|
|
|
// The SUMMARY carries only `## Files Created/Modified` (plan-level), with
|
|
// no `## Deviations from Plan` block naming a task — so provenance is
|
|
// PLAN_SCOPED, not TASK_SCOPED, and status/agreement are UNKNOWN.
|
|
const [task] = plan.tasks;
|
|
assert.strictEqual(task.provenance, PROVENANCE.PLAN_SCOPED);
|
|
assert.strictEqual(task.agreement, AGREEMENT.UNKNOWN);
|
|
assert.strictEqual(task.status, TASK_STATUS.UNKNOWN);
|
|
assert.strictEqual(task.changedFiles, null);
|
|
|
|
assert.deepStrictEqual(result.requirements.map((r) => [r.id, r.complete, r.mappedPhases]), [
|
|
['AUTH-01', true, ['1']],
|
|
['AUTH-02', false, ['2']],
|
|
]);
|
|
|
|
assert.deepStrictEqual(result.progress.accepted_phases, { completed: 2, total: 2, percent: 100, scope: 'complete' });
|
|
assert.deepStrictEqual(result.progress.completed_plans, { completed: 2, total: 2, percent: 100, scope: 'complete' });
|
|
assert.strictEqual(diagnosticCodes(result).includes(INSPECT_DIAGNOSTIC.PERCENT_WITHHELD), false);
|
|
});
|
|
});
|
|
|
|
describe('planning-inspect — task provenance/agreement variety, checkpoint, orphan dirs, requirement diagnostics', () => {
|
|
function build(cwd) {
|
|
writeFile(cwd, '.planning/STATE.md', frontmatterDoc(["gsd_state_version: '1.0'", 'status: planning', 'milestone: v1.0'], []));
|
|
writeFile(cwd, '.planning/ROADMAP.md', [
|
|
'## v1.0 Current 🚧', '', '## Phases', '',
|
|
'- [x] **Phase 1: Foo** - stub', '',
|
|
'### Phase 1: Foo', '', 'Ship the foo module.', '',
|
|
].join('\n'));
|
|
writeFile(cwd, '.planning/REQUIREMENTS.md', [
|
|
'# Requirements: Test', '', '## v1 Requirements', '',
|
|
'- [x] **AUTH-01**: User can sign up',
|
|
'- [x] **AUTH-01**: Duplicate row',
|
|
'- [ ] **AUTH-02**: Unmapped requirement',
|
|
'- [ ] **AUTH-03**: Maps to missing phase',
|
|
'', '## Traceability', '',
|
|
'| Requirement | Phase | Status |',
|
|
'|-------------|-------|--------|',
|
|
'| AUTH-01 | Phase 1 | Complete |',
|
|
'| AUTH-03 | Phase 9 | Pending |',
|
|
'',
|
|
].join('\n'));
|
|
const p1 = phaseDirOf(cwd, '01-foo');
|
|
writeAbs(path.join(p1, '1-01-PLAN.md'), frontmatterDoc(['wave: 1'], [
|
|
'<objective>', 'Ship foo', '</objective>', '',
|
|
'<tasks>', '',
|
|
'<task type="auto">',
|
|
' <name>Task 1: Agreed task</name>',
|
|
' <files>src/a.ts</files>',
|
|
' <done>Done</done>',
|
|
'</task>', '',
|
|
'<task type="auto">',
|
|
' <name>Task 2: Conflicting task</name>',
|
|
' <files>src/b.ts</files>',
|
|
' <done>Done</done>',
|
|
'</task>', '',
|
|
'<task type="checkpoint:manual">',
|
|
' <decision>Ship it?</decision>',
|
|
'</task>', '',
|
|
'</tasks>',
|
|
]));
|
|
writeAbs(path.join(p1, '1-01-SUMMARY.md'), frontmatterDoc(['status: complete'], [
|
|
'# Summary', '', '## Files Created/Modified', '- `src/a.ts` - a', '',
|
|
'## Deviations from Plan', '',
|
|
'**Found during:** Task 1',
|
|
'**Files modified:** `src/a.ts`', '',
|
|
'**Found during:** Task 2',
|
|
'**Files modified:** `src/other.ts`',
|
|
]));
|
|
writeAbs(path.join(p1, '1-VERIFICATION.md'), ['---', 'status: passed', '---', ''].join('\n'));
|
|
fs.mkdirSync(phaseDirOf(cwd, '99-orphan'), { recursive: true });
|
|
}
|
|
|
|
test('agreed vs conflicting task provenance, checkpoint shape, orphan dir, and every requirement diagnostic code', (t) => {
|
|
const cwd = mkCwd();
|
|
t.after(() => cleanup(cwd));
|
|
build(cwd);
|
|
|
|
const result = buildPlanningInspect(cwd);
|
|
|
|
assert.deepStrictEqual(result.orphan_phase_dirs, ['99-orphan']);
|
|
assert.strictEqual(result.phases.length, 1);
|
|
|
|
const [agreedTask, conflictingTask, checkpointTask] = result.phases[0].plans[0].tasks;
|
|
assert.strictEqual(agreedTask.provenance, PROVENANCE.TASK_SCOPED);
|
|
assert.strictEqual(agreedTask.agreement, AGREEMENT.AGREED);
|
|
assert.strictEqual(agreedTask.status, TASK_STATUS.DONE);
|
|
assert.deepStrictEqual(agreedTask.changedFiles, ['src/a.ts']);
|
|
|
|
assert.strictEqual(conflictingTask.provenance, PROVENANCE.TASK_SCOPED);
|
|
assert.strictEqual(conflictingTask.agreement, AGREEMENT.CONFLICTING);
|
|
assert.deepStrictEqual(conflictingTask.changedFiles, ['src/other.ts']);
|
|
assert.deepStrictEqual(conflictingTask.plannedFiles, ['src/b.ts']);
|
|
|
|
assert.strictEqual(checkpointTask.kind, TASK_KIND.CHECKPOINT);
|
|
assert.strictEqual(checkpointTask.provenance, PROVENANCE.PLAN_SCOPED);
|
|
assert.strictEqual(checkpointTask.agreement, AGREEMENT.UNKNOWN);
|
|
|
|
assert.deepStrictEqual(
|
|
result.requirements.map((r) => ({ id: r.id, complete: r.complete, mappedPhases: r.mappedPhases, diagnostics: r.diagnostics })),
|
|
[
|
|
{ id: 'AUTH-01', complete: true, mappedPhases: ['1'], diagnostics: [INSPECT_DIAGNOSTIC.REQUIREMENT_DUPLICATE] },
|
|
{ id: 'AUTH-02', complete: false, mappedPhases: [], diagnostics: [INSPECT_DIAGNOSTIC.REQUIREMENT_UNMAPPED] },
|
|
{ id: 'AUTH-03', complete: false, mappedPhases: ['9'], diagnostics: [INSPECT_DIAGNOSTIC.REQUIREMENT_PHASE_UNKNOWN] },
|
|
],
|
|
);
|
|
|
|
const codes = diagnosticCodes(result);
|
|
assert.ok(codes.includes(INSPECT_DIAGNOSTIC.ORPHAN_PHASE_DIR));
|
|
assert.ok(codes.includes(INSPECT_DIAGNOSTIC.TASK_CHANGED_FILES_CONFLICTING));
|
|
assert.ok(codes.includes(INSPECT_DIAGNOSTIC.TASK_SHAPE_CHECKPOINT));
|
|
assert.ok(codes.includes(INSPECT_DIAGNOSTIC.TASK_CHANGED_FILES_PLAN_SCOPED));
|
|
assert.ok(codes.includes(INSPECT_DIAGNOSTIC.REQUIREMENT_DUPLICATE));
|
|
assert.ok(codes.includes(INSPECT_DIAGNOSTIC.REQUIREMENT_UNMAPPED));
|
|
assert.ok(codes.includes(INSPECT_DIAGNOSTIC.REQUIREMENT_PHASE_UNKNOWN));
|
|
assert.strictEqual(codes.includes(INSPECT_DIAGNOSTIC.PERCENT_WITHHELD), false);
|
|
});
|
|
});
|
|
|
|
describe('planning-inspect — percent withheld, unreadable plan/summary, completion-unknown requirement', () => {
|
|
function build(cwd) {
|
|
writeFile(cwd, '.planning/STATE.md', frontmatterDoc(["gsd_state_version: '1.0'", 'status: planning', 'milestone: v1.0'], []));
|
|
writeFile(cwd, '.planning/ROADMAP.md', [
|
|
'## v1.0 Current 🚧', '', '## Phases', '',
|
|
'- [x] **Phase 1: Foo** - stub',
|
|
'- [ ] **Phase 2: Bar** - stub',
|
|
'',
|
|
'### Phase 1: Foo', '', 'Ship the foo module.', '',
|
|
// Deliberately NO section for Phase 2 -> ROADMAP_UNSCOPED for it.
|
|
].join('\n'));
|
|
writeFile(cwd, '.planning/REQUIREMENTS.md', [
|
|
'# Requirements: Test', '', '## v1 Requirements', '',
|
|
'- [x] **AUTH-01**: User can sign up',
|
|
'',
|
|
'## Other', '',
|
|
'| AUTH-05 | some description |',
|
|
'',
|
|
'## Traceability', '',
|
|
'| Requirement | Phase | Status |',
|
|
'|-------------|-------|--------|',
|
|
'| AUTH-01 | Phase 1 | Complete |',
|
|
'| AUTH-05 | Phase 1 | Pending |',
|
|
'',
|
|
].join('\n'));
|
|
const p1 = phaseDirOf(cwd, '01-foo');
|
|
writeAbs(path.join(p1, '1-01-PLAN.md'), frontmatterDoc(['wave: 1'], [
|
|
'<objective>', 'Ship foo', '</objective>', '',
|
|
'<tasks>', '', '<task type="auto">', ' <name>Task 1</name>', ' <files>src/a.ts</files>', ' <done>Done</done>', '</task>', '', '</tasks>',
|
|
]));
|
|
// Directory-in-file-position (cross-platform, no chmod): readDocument sees
|
|
// !stat.isFile() and reports unreadable, never a permissions hack.
|
|
fs.mkdirSync(path.join(p1, '1-01-SUMMARY.md'), { recursive: true });
|
|
const p2 = phaseDirOf(cwd, '02-bar');
|
|
fs.mkdirSync(p2, { recursive: true });
|
|
fs.mkdirSync(path.join(p2, '2-01-PLAN.md'), { recursive: true });
|
|
}
|
|
|
|
test('withholds percent when a windowed phase has no ROADMAP section, and reports unreadable plan/summary + completion-unknown', (t) => {
|
|
const cwd = mkCwd();
|
|
t.after(() => cleanup(cwd));
|
|
build(cwd);
|
|
|
|
const result = buildPlanningInspect(cwd);
|
|
|
|
const [foo, bar] = result.phases;
|
|
assert.deepStrictEqual(foo.goal, { value: 'Ship the foo module.', scope: 'complete' });
|
|
assert.deepStrictEqual(bar.goal, { value: null, scope: 'unscoped' });
|
|
assert.deepStrictEqual(bar.dependencies, { value: [], scope: 'unscoped' });
|
|
assert.strictEqual(bar.scope, 'unscoped');
|
|
assert.strictEqual(bar.plans[0].scope, 'unreadable');
|
|
assert.strictEqual(bar.plans[0].tasks.length, 0);
|
|
|
|
assert.deepStrictEqual(result.progress.accepted_phases, { completed: 0, total: 2, percent: null, scope: 'unscoped' });
|
|
assert.strictEqual(result.progress.completed_plans.percent, null);
|
|
|
|
const auth05 = result.requirements.find((r) => r.id === 'AUTH-05');
|
|
assert.strictEqual(auth05.complete, 'unknown');
|
|
assert.deepStrictEqual(auth05.mappedPhases, ['1']);
|
|
assert.deepStrictEqual(auth05.diagnostics, [INSPECT_DIAGNOSTIC.REQUIREMENT_COMPLETION_UNKNOWN]);
|
|
|
|
const codes = diagnosticCodes(result);
|
|
assert.ok(codes.includes(INSPECT_DIAGNOSTIC.SUMMARY_UNREADABLE));
|
|
assert.ok(codes.includes(INSPECT_DIAGNOSTIC.PLAN_UNREADABLE));
|
|
assert.ok(codes.includes(INSPECT_DIAGNOSTIC.ROADMAP_UNSCOPED));
|
|
assert.ok(codes.includes(INSPECT_DIAGNOSTIC.PHASE_SCOPE_DEGRADED));
|
|
assert.ok(codes.includes(INSPECT_DIAGNOSTIC.REQUIREMENT_COMPLETION_UNKNOWN));
|
|
assert.strictEqual(codes.filter((c) => c === INSPECT_DIAGNOSTIC.PERCENT_WITHHELD).length, 2);
|
|
});
|
|
});
|
|
|
|
describe('planning-inspect — UAT unreadable, UAT items, requirements unreadable, containment escape', () => {
|
|
test('a directory-in-file-position UAT document is UAT_UNREADABLE and degrades phase scope', (t) => {
|
|
const cwd = mkCwd();
|
|
t.after(() => cleanup(cwd));
|
|
writeFile(cwd, '.planning/STATE.md', frontmatterDoc(["gsd_state_version: '1.0'", 'status: planning', 'milestone: v1.0'], []));
|
|
writeFile(cwd, '.planning/ROADMAP.md', [
|
|
'## v1.0 Current 🚧', '', '## Phases', '', '- [ ] **Phase 1: Foo** - stub', '',
|
|
'### Phase 1: Foo', '', 'Ship the foo module.', '',
|
|
].join('\n'));
|
|
const p1 = phaseDirOf(cwd, '01-foo');
|
|
fs.mkdirSync(path.join(p1, '1-UAT.md'), { recursive: true });
|
|
|
|
const result = buildPlanningInspect(cwd);
|
|
assert.deepStrictEqual(result.phases[0].uat, { unresolved: [], scope: 'truncated' });
|
|
assert.strictEqual(result.phases[0].scope, 'truncated');
|
|
const codes = diagnosticCodes(result);
|
|
assert.ok(codes.includes(INSPECT_DIAGNOSTIC.UAT_UNREADABLE));
|
|
assert.ok(codes.includes(INSPECT_DIAGNOSTIC.PHASE_SCOPE_DEGRADED));
|
|
});
|
|
|
|
test('a pending UAT test item is surfaced verbatim in phases[].uat.unresolved', (t) => {
|
|
const cwd = mkCwd();
|
|
t.after(() => cleanup(cwd));
|
|
writeFile(cwd, '.planning/STATE.md', frontmatterDoc(["gsd_state_version: '1.0'", 'status: planning', 'milestone: v1.0'], []));
|
|
writeFile(cwd, '.planning/ROADMAP.md', [
|
|
'## v1.0 Current 🚧', '', '## Phases', '', '- [ ] **Phase 1: Foo** - stub', '',
|
|
'### Phase 1: Foo', '', 'Ship the foo module.', '',
|
|
].join('\n'));
|
|
const p1 = phaseDirOf(cwd, '01-foo');
|
|
fs.mkdirSync(p1, { recursive: true });
|
|
writeAbs(path.join(p1, '1-UAT.md'), [
|
|
'# UAT: Phase 1', '',
|
|
'## Current Test', '[testing complete]', '',
|
|
'## Tests', '',
|
|
'### 1. Sign up flow',
|
|
'expected: user can sign up',
|
|
'result: pending',
|
|
'',
|
|
].join('\n'));
|
|
|
|
const result = buildPlanningInspect(cwd);
|
|
assert.deepStrictEqual(result.phases[0].uat, {
|
|
scope: 'complete',
|
|
unresolved: [{ test: 1, name: 'Sign up flow', expected: 'user can sign up', result: 'pending', category: 'pending' }],
|
|
});
|
|
});
|
|
|
|
test('REQUIREMENTS.md as a directory-in-file-position is unreadable, not absent, and yields zero rows', (t) => {
|
|
const cwd = mkCwd();
|
|
t.after(() => cleanup(cwd));
|
|
writeFile(cwd, '.planning/STATE.md', frontmatterDoc(["gsd_state_version: '1.0'", 'status: planning', 'milestone: v1.0'], []));
|
|
writeFile(cwd, '.planning/ROADMAP.md', ['## v1.0 Current 🚧', '', '## Phases', ''].join('\n'));
|
|
fs.mkdirSync(path.join(cwd, '.planning/REQUIREMENTS.md'), { recursive: true });
|
|
|
|
const result = buildPlanningInspect(cwd);
|
|
assert.deepStrictEqual(result.requirements, []);
|
|
assert.ok(diagnosticCodes(result).includes(INSPECT_DIAGNOSTIC.REQUIREMENTS_UNREADABLE));
|
|
assert.strictEqual(diagnosticCodes(result).includes(INSPECT_DIAGNOSTIC.REQUIREMENTS_ABSENT), false);
|
|
});
|
|
|
|
test('a plan file symlinked outside the planning root degrades to unreadable, never leaking the escaped content', (t) => {
|
|
const cwd = mkCwd();
|
|
t.after(() => cleanup(cwd));
|
|
writeFile(cwd, '.planning/STATE.md', frontmatterDoc(["gsd_state_version: '1.0'", 'status: planning', 'milestone: v1.0'], []));
|
|
writeFile(cwd, '.planning/ROADMAP.md', [
|
|
'## v1.0 Current 🚧', '', '## Phases', '', '- [ ] **Phase 1: Foo** - stub', '',
|
|
'### Phase 1: Foo', '', 'Ship the foo module.', '',
|
|
].join('\n'));
|
|
const p1 = phaseDirOf(cwd, '01-foo');
|
|
fs.mkdirSync(p1, { recursive: true });
|
|
const outside = path.join(os.tmpdir(), `planning-inspect-unit-outside-${process.pid}.md`);
|
|
fs.writeFileSync(outside, 'SECRET CONTENT');
|
|
t.after(() => cleanup(outside));
|
|
fs.symlinkSync(outside, path.join(p1, '1-01-PLAN.md'));
|
|
|
|
const result = buildPlanningInspect(cwd);
|
|
const [plan] = result.phases[0].plans;
|
|
assert.strictEqual(plan.scope, 'unreadable');
|
|
assert.strictEqual(plan.objective, null);
|
|
assert.deepStrictEqual(plan.tasks, []);
|
|
const json = JSON.stringify(result);
|
|
assert.strictEqual(json.includes('SECRET CONTENT'), false);
|
|
assert.ok(diagnosticCodes(result).includes(INSPECT_DIAGNOSTIC.PLAN_UNREADABLE));
|
|
});
|
|
});
|