Files
msd-core/tests/workstream.test.cjs
Adnan 137f3fbb9c fix(#2562): scope workstream progress/status to the current milestone (#2588)
* fix(#2562): scope workstream progress/status to the current milestone

`workstream progress` / `workstream status` / `workstream list` share one
derivation that could report a workstream's CURRENT milestone as
"milestone complete" / 100% while phases in that milestone were unstarted,
in progress, or failing verification. Three coupled defects:

1. The shipped signal was project-lifetime, not milestone-scoped:
   workstreamMilestoneShipped() returned true if ANY *-ROADMAP.md snapshot
   existed or "SHIPPED" appeared anywhere in ROADMAP.md. Every prior shipped
   milestone leaves a permanent collapsed <summary>✅ … SHIPPED</summary>
   block, so any post-v1.0 workstream was pinned to "milestone complete"
   forever (over-correction from #1913).
2. The denominator dropped declared-but-unscaffolded phases, and completed
   PRIOR-milestone phase directories inflated the numerator, letting
   progress_percent round to 100 while real work remained.
3. Phase completeness ignored the VERIFICATION verdict — SUMMARY >= PLAN
   count alone marked a phase complete even with a human_needed verdict.

Fix: derive both numerator and denominator from artifacts scoped to the
current milestone. The current version comes from the workstream STATE.md
`milestone:` field (ROADMAP in-progress markers can be stale); the ROADMAP
`## Progress` table maps every phase — including dirless ones — to its
milestone, and the matching set is both the denominator and the directory
membership filter. The shipped signal now requires the CURRENT version's
archived ROADMAP snapshot (REQUIREMENTS snapshots are not accepted; they can
be written at milestone start) or the current milestone's own line marked
shipped. Phases with an explicit failing verdict (gaps_found/human_needed)
count as in_progress; missing/unknown/stale are left untouched so
verifier-disabled projects do not regress to never-complete.

Greenfield roadmaps with no versioned Progress table, and projects whose
current version cannot be determined, keep the prior behaviour.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>

* docs(#2562): add changeset for workstream milestone-scoping fix

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>

* refactor(#2562): parse the Progress table via findTableWithColumns

The ad-hoc pipe-table regex tripped the local/no-adhoc-markdown-parsing
ESLint rule. Use the canonical markdown-table helper instead: the
milestone-grouped RoadmapProgress variant is located by its required
`Phase` + `Milestone` columns and cells are addressed by column NAME,
so the parser tolerates column reordering and injected columns. The
`flat` variant (no Milestone column) yields no attribution, which is
the intended fallback to legacy counting.

Behaviour is unchanged: verified against a real multi-workstream project
(same status/percent/phase and plan counts before and after).

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>

* fix(#2562): count table-only phases in the unscoped denominator

Addresses the reporter's repro detail: a phase declared as a `## Progress`
table row with no `### Phase N` heading is missed by countRoadmapPhases
EVEN WHEN other headings exist — the heading regex counts 1 for a
"1 heading + 1 table-only" roadmap — not just in the zero-heading fallback
path. Milestone scoping did not cover this, because a flat Progress table
(no Milestone column) carries no per-phase attribution, so greenfield and
single-milestone projects kept the old heading-only denominator and the
declared phase silently vanished from it.

When milestone scoping cannot engage, the denominator is now the union of
the Progress table's declared phase numbers and the phase directories, so
neither source can shrink it. Verified against the reporter's minimal
fixture (phase 1: 1 PLAN + 1 SUMMARY + gaps_found; phase 2: table row only,
no heading, no dir), which now reports 0/2 at 0% across all four
table/STATE permutations instead of 1/1 at 100%.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>

* fix(#2562): attribute dir-only sub-phases to their parent's milestone

A sub-phase directory inserted mid-milestone (e.g. `30.1-…` under a
table-declared phase 30) usually has no ROADMAP Progress-table row, so it
had no milestone attribution and was scoped out of the rollup entirely —
its completed work was invisible and it could never hold the percentage
below 100.

It now inherits its parent phase's milestone and joins BOTH sides of the
calculation. Both sides is the load-bearing part: adding it to the
numerator alone would let completed_phases exceed a denominator that never
counted it, cap back to 100% via Math.min, and reintroduce exactly the
defect this issue reports. A regression test pins that failure mode (all
declared phases complete + an in-progress dir-only sub-phase → 75%, not
100%).

Attribution is deliberately one-directional: a sub-phase counts only when
its PARENT is in the current milestone, so a follow-up created in a later
milestone under an older parent is excluded rather than misattributed —
conservative (under-count) rather than falsely inflating.

Verified on a real project: the reported workstream moves from 2/6 (33%)
to 3/7 (43%), the 3/7 being the honest figure — a completed sub-phase that
was previously invisible now counts, and so does its plan total.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>

* docs(#2562): describe the denominator + sub-phase fixes in the changeset

The fragment was written at the first commit and only covered the three
original defects. Bring it up to date with what actually ships: the
table-only-phase denominator union (heading-only counting dropped a
declared phase even when other headings existed) and sub-phase milestone
inheritance across both sides of the calculation.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>

* refactor(#2562): promote the canonical phase-key surface to phase-id

state.cts kept `phaseKeyFromToken`/`phaseKeyFromDir` private, so every other
module that had to compare two independently-derived phase references — a
ROADMAP table cell against a phase directory, say — wrote its own regex. That
is the defect class #2562 reports: a padded `01` and an unpadded `1-slug` land
in different key spaces and the comparison silently yields nothing.

Move the pair to the phase-id owner module and add `phaseKeyFromProse` (for
ROADMAP/STATE prose, markdown emphasis stripped) and `parentPhaseKey` (a
sub-phase's parent). state.cts imports them; its call sites are unchanged.

* fix(#2562): own milestone-shipped detection and accept a workstream scope

Three changes to the module that owns milestone parsing, so its consumers stop
reimplementing it:

- `isMilestoneShippedInRoadmap(content, version)` answers "does the ROADMAP mark
  THIS milestone shipped" from heading and `<summary>` lines only. A bullet that
  merely names the version (`- [x] 03-01: ship the v2.0 login endpoint`) is prose
  about a phase, not a milestone verdict. The version token is boundary-matched
  with `(?![\w.-])` — `\b` does not bound it, since `.` is a non-word character,
  so a shipped `v2.0.1` heading would otherwise close `v2.0`.
- `extractCurrentMilestone` and `getMilestonePhaseFilter` take an optional
  trailing workstream name and thread it to `planningDir(cwd, ws)`. A caller
  iterating workstreams cannot set `GSD_WORKSTREAM` per iteration, which is what
  the existing resolution falls back to. Omitted, resolution is unchanged.
- `getMilestonePhaseFilter` exposes `versionScoped`, true only when the phase set
  really is one milestone's. On an unversioned roadmap `phaseCount` spans the
  project's lifetime and must not be read as a current-milestone denominator.

The closed/active milestone-marker patterns were kept in three byte-identical
copies; they are hoisted to module scope as one `isClosedMilestoneHeading`.

* fix(#2562): derive membership and denominator from one phase-key space

The milestone scoping added earlier in this PR derived the ROADMAP table key and
the phase-directory key with two different regexes, and dropped rows it could not
attribute. Each of those was another way to reproduce the symptom this issue
reports — a rollup contradicting its own `phases[]` listing:

- a padded `| 01. … |` row never matched a `1-slug` directory (and a bespoke
  `^0*(\d+…)` never matched `PROJ-05-…` at all), so phases fell out of the
  milestone entirely and the percentage collapsed or pinned;
- a blank or malformed Milestone cell deleted the phase from BOTH sides, letting
  an unstarted phase vanish and the remainder round to 100%;
- shipped detection scanned bullets, so any checkmarked line naming the version
  closed the milestone;
- the numerator counted per-directory while the denominator counted distinct
  phases, so a stale same-numbered directory (Bug #2445's scenario) pushed
  `completed_phases` past the denominator, where `Math.min` capped it to 100%
  and hid the unstarted phase.

Both sides now key off the phase-id owner module (`phaseKeyFromDir` /
`phaseKeyFromProse`), directory membership additionally consults
`getMilestonePhaseFilter` when that filter is genuinely version-scoped, and the
denominator is the union of the roadmap's declarations with the member
directories' keys — so `completed_phases <= denominator` holds by construction.
The Builder asserts it and throws; the `Math.min` cap survives only on the legacy
unscoped path, where the denominator is a heading count that cannot bound the
numerator. An unattributable row degrades over-inclusively (kept, never dropped),
matching the degrade direction roadmap-parser already commits to.

* test(#2562): boundary coverage for each milestone-scoping reproduction

One test per way the scoping could still report "milestone complete"/100% while
phases are incomplete: zero-padded rows vs padded dirs (and the mirror),
project-code-prefixed dirs, a blank/malformed Milestone cell, a checkmarked
bullet naming the version, a shipped `v2.0.1` heading against a current `v2.0`,
and a stale same-numbered directory. Plus the current milestone's own shipped
heading (the signal must survive the boundary fix), the Builder's
numerator-above-denominator throw, a parity check that every non-`passed`
verifier status blocks completeness, and a guard that scoping reads the
workstream's ROADMAP rather than the project root's.

Reverting only `src/` reddens six of them.

* docs(#2562): record the milestone-scoped semantics and its consumer impact

CONTEXT.md: the Workstream Inventory Module's completion fields now describe the
current milestone, not the workstream's lifetime; phase-id owns the canonical
phase-key surface; roadmap-parser owns milestone shipped/active classification
and takes an optional workstream scope.

Changeset: name the behaviour change explicitly — `roadmap_phase_count`,
`completed_phases` and `progress_percent` change meaning with no schema signal,
and `getOtherActiveWorkstreamInventories` filters on the derived status, so
consumers see real movement.

* fix(#2562): collapse every zero-padding spelling to one phase key

A property test over the key surface — table cell and directory decorated
INDEPENDENTLY, which is the point — found a divergence neither review named:
`padStart(2, '0')` is a no-op once the input is already ≥2 characters, so `5`
normalised to `05` while `005` stayed `005`. A `| 5. … |` row and a `005-slug`
directory therefore never compared equal, which is the same failure mode as the
padded-vs-unpadded blocker, one level down.

The strip belongs in `phaseKeyFromToken`, not in `normalizePhaseName`: applying
it to the latter regressed multi-decimal leading-zero plan IDs (`001.10-PLAN.md`
capture + wave assignment), which rely on its verbatim rendering. Confining it
to the key surface fixes the comparison and leaves rendering untouched.

Also tightens `isMilestoneShippedInRoadmap`'s patterns to anchored,
complementary character classes so an untrusted ROADMAP cannot drive
backtracking, and makes the project-code test discriminating — it previously
passed pre-fix, because an unresolvable key collapsed scoping to the whole
roadmap and happened to land on the same number. It now carries a
prior-milestone directory that a collapse would wrongly admit.

* fix(#2562): prefer the milestone-attributing Progress table; pin the seams

Three gaps the earlier self-check missed:

- Both RoadmapProgress variants carry a `Plans Complete` column, so probing it
  first picked a FLAT table appearing earlier in the document over the
  milestone-grouped one that actually carries the attribution. Every row came
  back unattributed, was treated as current-milestone, and silently re-admitted
  prior-milestone phases. The attributing shape is probed first; flipping the
  order reddens the new test.
- `lint-phase-id-drift` exempts phase-id.cts by design, so it is silent on
  `phaseKeyFromToken`'s own segment strip by construction — not evidence. Its
  interaction with `stripProjectCodePrefix` (which runs AFTER) is pinned across
  project codes and hyphenated ids, including the pre-existing `M1-46-6` vs
  `M1-46-6-rs` asymmetry, which is `extractPhaseToken`'s #2043/#2232 slug-word
  rule and not something to "fix" by accident.
- `listWorkstreamInventories` loops every workstream with no try/catch, so a
  REACHABLE Builder-invariant throw would take down `workstream list`/`status`/
  `progress` for all of them. The invariant test only exercised the pure Builder
  with hand-built inputs. A test now drives `inspectWorkstream` over every
  adversarial shape at once (prior-milestone dirs, three colliding duplicates,
  a dirless declaration, an unattributed row, a project-code prefix, a dir-only
  sub-phase) and asserts it does not throw and the invariant holds — so the
  throw stays a contract assertion for external callers, not a runtime path.

Also covers the active-marker-wins rule (`## v2.0 — 🚧 IN PROGRESS … ✅` must not
mark shipped), which nothing exercised.

* fix(#2562): scope a declared-but-empty current milestone instead of falling back to history

The review's open MAJOR. `STATE.md`'s `milestone:` field updates the moment
`/gsd-new-milestone` writes the heading, while the `## Progress` table and phase
sections land later. In that window nothing attributes a phase to the current
milestone, `scoped` went false, and the fallback counted the project's ENTIRE
phase history as both numerator and denominator — a milestone with zero work
done reported 100% off its predecessors'. That is #2562's own symptom reached by
a different precondition, and none of the 16 tests covered it.

Reproduced first, four ROADMAP shapes, at `inspectWorkstream` rather than the
Builder — the Builder takes the scoping decision as an input, so a Builder-level
test proves it honours a flag, not that the derivation sets it. Three of the
four reported 2/2 100% with no phase of the current milestone begun.

Which signal witnesses the state depends on the ROADMAP's shape, and no single
one covers all three:

- `## v3.0` exists but declares no phases. `getMilestonePhaseFilter` DOES locate
  the section and sets `versionScoped`, then the zero-phase pass-all degrade
  resets it to false — erasing the only evidence the milestone exists. Neither
  existing flag survives that path, so this adds `versionSectionFound`, set
  beside `versionScoped` and deliberately preserved through the degrade.
- No section for this version at all, in a roadmap that versions its others —
  the existing `missingExplicitVersion`, already exposed and tested.
- Unversioned headings, but a Progress table attributing every row elsewhere:
  neither filter flag fires and the table is the only witness.

A ROADMAP that attributes NO versions anywhere matches none of them, which is
the point. Its rows parse with `version: null`, land in `currentMilestoneKeys`,
and never reach the new branch. `readCurrentMilestoneVersion` returns a non-null
version for very nearly every project (`getMilestoneInfo` defaults to `v1.0`),
so keying off `currentVersion` alone would have zeroed out every free-form
legacy project — the condition looks fussy for that reason. A test pins it.

Within an empty milestone, membership inverts: a directory belongs unless
another milestone's row claims it. Excluding everything would have dropped a
phase scaffolded before the roadmap caught up from BOTH sides of the rollup, and
hiding real work is the same class of defect as inventing it — this codebase
degrades over-inclusive, never under.

Scoping is now stated by the caller (`milestoneScoped`) rather than inferred
from `currentMilestonePhaseCount > 0`. That inference was the root cause: it
cannot represent a milestone that is scoped AND legitimately zero-phase, so the
Builder read "no phases yet" as "no scoping" and reopened the whole-history
path. The count-derived value stays the default for callers that say nothing.

A regression test also pins that a zero denominator does not trip the Builder's
`completed_phases <= denominator` throw, since `listWorkstreamInventories` has
no try/catch and a crash on every freshly-declared milestone would be worse than
a wrong percentage.

The changeset and CONTEXT.md no longer claim membership is derived in "ONE" /
"a SINGLE" phase-key space. `getMilestonePhaseFilter` still runs its own
`normalizePhaseIdSegments`; the signals are OR'd so a divergence can only widen
membership, but two normalisers coexist and the docs now say so.

* fix(#2562): cross-validate the shipped marker against the milestone's artifacts

`status: "milestone complete"` was asserted from the shipped marker alone, so a
single payload could report it beside `progress_percent: 67` — this issue's own
symptom, reached through `status` rather than the percentage.

The marker is now a claim checked against the milestone's own artifacts, and the
two signals are checked at DIFFERENT strengths because one check cannot serve
both. A `heading` marker (operator-typed, live ROADMAP) is refused on a short
completion ratio, which also catches phases declared but never scaffolded. A
`snapshot` marker is NOT ratio-gated: `milestone complete` moves the milestone's
phase dirs into `milestones/<version>-phases/` (milestone.cts:755-762) while
copying — never truncating — the live ROADMAP (:671-674), so a correctly
archived milestone reads 0/N by construction and a ratio gate would strip
`milestone complete` from every archived milestone. It is refused instead when
an in-milestone phase dir is still live and unfinished, reachable because
`milestone complete` does not advance STATE's `milestone:` field
(state-transition.cts:1335 vs :1224). `legacy` stays ungated — only reachable
when scoping is off.

A refused marker does not fall through to a STATE field claiming the same thing;
against contradicting artifacts neither source may report completion. The
refusal surfaces as `milestone_shipped_unverified` rather than staying silent,
distinct from `status_conflict` (derived-vs-field only).

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01PpFzuEHKTN1jaypSN44rzd

* test(#2562): pin both marker strengths, the archived guard, and the owner modules

workstream-inventory: four tests, all four red against the prior src and green
with it. A live-ROADMAP SHIPPED heading over an incomplete milestone is refused;
an archived snapshot SURVIVES its phase dirs being moved out (the regression the
obvious single ratio-gate would cause — swapping the snapshot branch to that
gate reddens this AND the pre-existing `CURRENT-version snapshot marks the
milestone complete` at :321); an archived snapshot is refused once a phase is
reopened under it; and a refused marker is not re-asserted by a STATE field
claiming the same.

roadmap-parser: `isMilestoneShippedInRoadmap` gets unit coverage at its owner
module rather than only through the inventory that consumes it, plus two
characterisation tests for `getMilestonePhaseFilter`'s legacy call surface —
omitting the new trailing `ws` param is indistinguishable from `undefined`/`null`,
and the `GSD_WORKSTREAM` env fallback still resolves. These characterise the
call surface; they do not stand in for coverage of its individual callers.

phase-id: the `phaseKeyFrom*` / `parentPhaseKey` one-key-space contract, incl. a
property that padding a directory number never changes its key.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01PpFzuEHKTN1jaypSN44rzd

* docs(#2562): record the two-strength shipped cross-check + milestone_shipped_unverified

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01PpFzuEHKTN1jaypSN44rzd

* fix(#2562): refuse an archived snapshot on a DIRTY archive, not just a live-unfinished dir

The snapshot arm checked `liveIncompletePhases > 0`, which misses the shape
@davesienkowski reproduced: a COMPLETE live dir beside a phase declared in the
Progress table with no directory. Nothing is live-and-unfinished, the marker
sails through, and `cmdWorkstreamProgress` returns
`{"status":"milestone complete","progress_percent":50}` — the reported symptom
verbatim, from one payload. Reproduced at 483a3ba30 before changing anything.

His diagnosis is the right one and better than mine: an in-milestone directory
outliving the archive means the archive is not CLEAN, and once that is true the
completion ratio is meaningful again. So the check is the conjunction — any live
in-milestone dir AND `completedPhases < effectivePhaseCount`. That strictly
subsumes the old predicate (an incomplete member dir is in the denominator and
not the numerator, so the ratio is always short when one exists) and leaves the
clean-archive guard green, since a clean archive has no live dirs at all.

Also corrects the module comment: the `scoped &&` prefix ungates all three
signals, not just `legacy`. That is correct behaviour — unscoped, the
denominator is the whole-roadmap count and membership is everything, so there is
no current-milestone artifact set to check a current-milestone claim against —
but the comment claimed otherwise. And the `milestone.cts` citations were ~28
lines stale after the rebase; they are now :700-702 (copy) and :783-790 (move),
re-verified against this head.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01PpFzuEHKTN1jaypSN44rzd

* fix(#2562): project milestone_shipped_unverified from list, status and progress

The inventory carried the field and every renderer dropped it — `workstream.cts`
was not in this PR's diff at all — so at the CLI a refused marker looked exactly
like no marker: a fallback `status` and nothing saying one was seen and rejected.
That is the silent collapse this issue is about, reintroduced one layer up, and
it made the changeset's "visible rather than silent" claim false at every
surface.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01PpFzuEHKTN1jaypSN44rzd

* test(#2562): pin the dirty-archive shape and the CLI projection

Five tests, all five red against the prior src and green with it.

The reviewer's repro at the builder: an archived snapshot with a COMPLETE live
dir beside a dirless declared phase must be refused, and status must not
contradict the percentage.

Four at the CLI via runGsdTools, the surface that was dropping the field rather
than the builder that already had it: `workstream progress`/`status`/`list` each
project `milestone_shipped_unverified: true` for that workstream, and a clean
archive still reports `false` with `status: "milestone complete"`.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01PpFzuEHKTN1jaypSN44rzd

* docs(#2562): correct the snapshot check, the scoped-only caveat and the CLI claim

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01PpFzuEHKTN1jaypSN44rzd

---------

Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
Co-authored-by: Tom Boucher <trekkie@nomorestars.com>
2026-08-01 23:06:43 -04:00

934 lines
41 KiB
JavaScript

/**
* Workstream Tests — CRUD, env-var routing, collision detection
*/
const { describe, test, before, after, beforeEach, afterEach } = require('node:test');
const assert = require('node:assert/strict');
const crypto = require('crypto');
const fs = require('fs');
const os = require('os');
const path = require('path');
const { runGsdTools, cleanup } = require('./helpers.cjs');
const { createFixture, seedWorkstream } = require('./fixtures/index.cjs');
const { migrateToWorkstreams, getOtherActiveWorkstreams } = require('../gsd-core/bin/lib/workstream.cjs');
// ─── Helper ──────────────────────────────────────────────────────────────────
function createFailingTtyEnv(tmpDir) {
const binDir = path.join(tmpDir, 'fake-bin');
const markerFile = path.join(tmpDir, 'tty-invoked.log');
const inheritedPath = process.env.PATH || process.env.Path || '';
fs.mkdirSync(binDir, { recursive: true });
fs.writeFileSync(
path.join(binDir, 'tty'),
'#!/bin/sh\nif [ -n "$GSD_TTY_MARKER" ]; then printf "tty\\n" >> "$GSD_TTY_MARKER"; fi\nexit 99\n',
'utf-8'
);
fs.chmodSync(path.join(binDir, 'tty'), 0o755);
fs.writeFileSync(
path.join(binDir, 'tty.cmd'),
'@echo off\r\nif not "%GSD_TTY_MARKER%"=="" echo tty>>"%GSD_TTY_MARKER%"\r\nexit /b 99\r\n',
'utf-8'
);
return {
markerFile,
env: {
PATH: `${binDir}${path.delimiter}${inheritedPath}`,
GSD_TTY_MARKER: markerFile,
},
};
}
function getSessionPointerDir(tmpDir) {
const planningPath = fs.realpathSync.native(path.join(tmpDir, '.planning'));
const projectId = crypto
.createHash('sha1')
.update(planningPath)
.digest('hex')
.slice(0, 16);
return path.join(os.tmpdir(), 'gsd-workstream-sessions', projectId);
}
function sanitizeSessionToken(value) {
const token = String(value).trim().replace(/[^a-zA-Z0-9._-]+/g, '_').replace(/^_+|_+$/g, '');
return token ? token.slice(0, 160) : null;
}
function getSessionPointerFileName(envKey, value) {
const token = sanitizeSessionToken(value);
return `${envKey.toLowerCase().replace(/[^a-z0-9]+/g, '-')}-${token}`;
}
// ─── planningDir / planningPaths env-var awareness ──────────────────────────
describe('planningDir workstream awareness via env var', () => {
let tmpDir;
before(() => {
tmpDir = createFixture();
seedWorkstream(tmpDir, {
name: 'alpha',
state: '# State\n**Status:** In progress\n**Current Phase:** 1\n',
roadmap: '## Roadmap v1.0: Alpha\n### Phase 1: Setup\n',
active: true,
});
});
after(() => cleanup(tmpDir));
test('state json returns workstream-scoped state when GSD_WORKSTREAM is set', () => {
const result = runGsdTools(['state', 'json', '--raw'], tmpDir, { GSD_WORKSTREAM: 'alpha' });
assert.ok(result.success, `state json failed: ${result.error}`);
const data = JSON.parse(result.output);
assert.ok(data.status || data.current_phase !== undefined, 'should return state data');
});
test('state json reads from flat .planning when no workstream set', () => {
// Clear active-workstream so no auto-detection
try { fs.unlinkSync(path.join(tmpDir, '.planning', 'active-workstream')); } catch {}
const result = runGsdTools(['state', 'json', '--raw'], tmpDir, { GSD_WORKSTREAM: '' });
// Should fail or return empty state since flat .planning/ has no STATE.md
assert.ok(!result.success || result.output.includes('not found') || result.output === '{}',
'should read from flat .planning/');
// Restore
fs.writeFileSync(path.join(tmpDir, '.planning', 'active-workstream'), 'alpha\n');
});
test('--ws flag overrides GSD_WORKSTREAM env var', () => {
// Create a second workstream
const betaDir = path.join(tmpDir, '.planning', 'workstreams', 'beta');
fs.mkdirSync(path.join(betaDir, 'phases'), { recursive: true });
fs.writeFileSync(path.join(betaDir, 'STATE.md'), '# State\n**Status:** Beta active\n');
const result = runGsdTools(['state', 'json', '--raw', '--ws', 'beta'], tmpDir, { GSD_WORKSTREAM: 'alpha' });
assert.ok(result.success, `state json --ws beta failed: ${result.error}`);
});
});
describe('session-scoped active workstream routing', () => {
let tmpDir;
before(() => {
tmpDir = createFixture();
for (const [ws, status] of [['alpha', 'Alpha active'], ['beta', 'Beta active']]) {
const wsDir = path.join(tmpDir, '.planning', 'workstreams', ws);
fs.mkdirSync(path.join(wsDir, 'phases'), { recursive: true });
fs.writeFileSync(path.join(wsDir, 'STATE.md'), `# State\n**Status:** ${status}\n`);
}
});
after(() => cleanup(tmpDir));
test('stores active workstream per session instead of mutating shared pointer', () => {
const alphaSet = runGsdTools(['workstream', 'set', 'alpha', '--raw'], tmpDir, { GSD_SESSION_KEY: 'session-alpha' });
const betaSet = runGsdTools(['workstream', 'set', 'beta', '--raw'], tmpDir, { GSD_SESSION_KEY: 'session-beta' });
assert.ok(alphaSet.success, `alpha set failed: ${alphaSet.error}`);
assert.ok(betaSet.success, `beta set failed: ${betaSet.error}`);
assert.ok(!fs.existsSync(path.join(tmpDir, '.planning', 'active-workstream')),
'shared active-workstream file should not be used when session keys are available');
});
test('different sessions resolve different active workstreams without --ws', () => {
const alpha = runGsdTools(['workstream', 'get', '--raw'], tmpDir, { GSD_SESSION_KEY: 'session-alpha' });
const beta = runGsdTools(['workstream', 'get', '--raw'], tmpDir, { GSD_SESSION_KEY: 'session-beta' });
assert.ok(alpha.success, `alpha get failed: ${alpha.error}`);
assert.ok(beta.success, `beta get failed: ${beta.error}`);
assert.strictEqual(alpha.output, 'alpha');
assert.strictEqual(beta.output, 'beta');
});
test('session-scoped pointer ignores legacy shared active-workstream file', () => {
fs.writeFileSync(path.join(tmpDir, '.planning', 'active-workstream'), 'beta\n');
const alpha = runGsdTools(['workstream', 'get', '--raw'], tmpDir, { GSD_SESSION_KEY: 'session-alpha' });
const shared = runGsdTools(['workstream', 'get', '--raw'], tmpDir);
assert.ok(alpha.success, `session-scoped get failed: ${alpha.error}`);
assert.ok(shared.success, `legacy get failed: ${shared.error}`);
assert.strictEqual(alpha.output, 'alpha');
assert.strictEqual(shared.output, 'beta');
});
test('state commands route to the session-scoped workstream automatically', () => {
const alpha = runGsdTools(['state', 'json', '--raw'], tmpDir, { GSD_SESSION_KEY: 'session-alpha' });
const beta = runGsdTools(['state', 'json', '--raw'], tmpDir, { GSD_SESSION_KEY: 'session-beta' });
assert.ok(alpha.success, `alpha state failed: ${alpha.error}`);
assert.ok(beta.success, `beta state failed: ${beta.error}`);
const alphaState = JSON.parse(alpha.output);
const betaState = JSON.parse(beta.output);
assert.strictEqual(alphaState.status, 'Alpha active');
assert.strictEqual(betaState.status, 'Beta active');
});
test('clearing one session does not clear another session pointer', () => {
const clearAlpha = runGsdTools(['workstream', 'set', '--clear', '--raw'], tmpDir, { GSD_SESSION_KEY: 'session-alpha' });
const alpha = runGsdTools(['workstream', 'get'], tmpDir, { GSD_SESSION_KEY: 'session-alpha' });
const beta = runGsdTools(['workstream', 'get', '--raw'], tmpDir, { GSD_SESSION_KEY: 'session-beta' });
assert.ok(clearAlpha.success, `clear alpha failed: ${clearAlpha.error}`);
assert.ok(alpha.success, `alpha get after clear failed: ${alpha.error}`);
assert.ok(beta.success, `beta get after alpha clear failed: ${beta.error}`);
const cleared = JSON.parse(alpha.output);
assert.strictEqual(cleared.active, null);
assert.strictEqual(beta.output, 'beta');
});
});
describe('session resolution hardening', () => {
let tmpDir;
beforeEach(() => {
tmpDir = createFixture();
for (const [ws, status] of [['alpha', 'Alpha active'], ['beta', 'Beta active']]) {
const wsDir = path.join(tmpDir, '.planning', 'workstreams', ws);
fs.mkdirSync(path.join(wsDir, 'phases'), { recursive: true });
fs.writeFileSync(path.join(wsDir, 'STATE.md'), `# State\n**Status:** ${status}\n`);
}
});
afterEach(() => cleanup(tmpDir));
test('headless runs skip tty probing and use the shared active-workstream fallback', () => {
const { markerFile, env } = createFailingTtyEnv(tmpDir);
const set = runGsdTools(['workstream', 'set', 'alpha', '--raw'], tmpDir, env);
const get = runGsdTools(['workstream', 'get', '--raw'], tmpDir, env);
assert.ok(set.success, `headless set failed: ${set.error}`);
assert.ok(get.success, `headless get failed: ${get.error}`);
assert.ok(!fs.existsSync(markerFile), 'headless fallback should not invoke the tty subprocess');
assert.strictEqual(get.output, 'alpha');
assert.strictEqual(
fs.readFileSync(path.join(tmpDir, '.planning', 'active-workstream'), 'utf-8').trim(),
'alpha'
);
assert.ok(!fs.existsSync(getSessionPointerDir(tmpDir)), 'headless fallback should not create session tmp pointers');
});
test('explicit runtime session ids outrank tty-derived identities', () => {
const set = runGsdTools(['workstream', 'set', 'alpha', '--raw'], tmpDir, {
GSD_SESSION_KEY: 'shared-session',
TTY: '/dev/pts/42',
});
const get = runGsdTools(['workstream', 'get', '--raw'], tmpDir, {
GSD_SESSION_KEY: 'shared-session',
TTY: '/dev/pts/99',
});
assert.ok(set.success, `session-key set failed: ${set.error}`);
assert.ok(get.success, `session-key get failed: ${get.error}`);
assert.strictEqual(get.output, 'alpha');
assert.ok(!fs.existsSync(path.join(tmpDir, '.planning', 'active-workstream')));
});
test('TTY environment variables provide a session-scoped pointer without spawning tty', () => {
const { markerFile, env } = createFailingTtyEnv(tmpDir);
const ttyEnv = { ...env, TTY: '/dev/pts/42' };
const set = runGsdTools(['workstream', 'set', 'beta', '--raw'], tmpDir, ttyEnv);
const get = runGsdTools(['workstream', 'get', '--raw'], tmpDir, ttyEnv);
assert.ok(set.success, `TTY set failed: ${set.error}`);
assert.ok(get.success, `TTY get failed: ${get.error}`);
assert.ok(!fs.existsSync(markerFile), 'TTY env should be used directly without invoking the tty subprocess');
assert.strictEqual(get.output, 'beta');
assert.ok(!fs.existsSync(path.join(tmpDir, '.planning', 'active-workstream')));
});
});
describe('pointer lifecycle hardening', () => {
let tmpDir;
beforeEach(() => {
tmpDir = createFixture();
for (const [ws, status] of [['alpha', 'Alpha active'], ['beta', 'Beta active']]) {
const wsDir = path.join(tmpDir, '.planning', 'workstreams', ws);
fs.mkdirSync(path.join(wsDir, 'phases'), { recursive: true });
fs.writeFileSync(path.join(wsDir, 'STATE.md'), `# State\n**Status:** ${status}\n`);
}
});
afterEach(() => cleanup(tmpDir));
test('clearing one session pointer leaves sibling session pointers intact', () => {
const sessionDir = getSessionPointerDir(tmpDir);
const alphaFile = getSessionPointerFileName('GSD_SESSION_KEY', 'session-alpha');
const betaFile = getSessionPointerFileName('GSD_SESSION_KEY', 'session-beta');
runGsdTools(['workstream', 'set', 'alpha', '--raw'], tmpDir, { GSD_SESSION_KEY: 'session-alpha' });
runGsdTools(['workstream', 'set', 'beta', '--raw'], tmpDir, { GSD_SESSION_KEY: 'session-beta' });
const clearAlpha = runGsdTools(['workstream', 'set', '--clear', '--raw'], tmpDir, { GSD_SESSION_KEY: 'session-alpha' });
const beta = runGsdTools(['workstream', 'get', '--raw'], tmpDir, { GSD_SESSION_KEY: 'session-beta' });
assert.ok(clearAlpha.success, `clear alpha failed: ${clearAlpha.error}`);
assert.ok(beta.success, `beta get failed: ${beta.error}`);
assert.strictEqual(beta.output, 'beta');
assert.ok(fs.existsSync(sessionDir), 'session tmp directory should remain while a sibling pointer exists');
assert.deepStrictEqual(fs.readdirSync(sessionDir).sort(), [betaFile]);
assert.ok(!fs.existsSync(path.join(sessionDir, alphaFile)));
});
test('stale pointers self-clean without deleting sibling session pointers', () => {
const sessionDir = getSessionPointerDir(tmpDir);
const betaFile = getSessionPointerFileName('GSD_SESSION_KEY', 'session-beta');
runGsdTools(['workstream', 'set', 'alpha', '--raw'], tmpDir, { GSD_SESSION_KEY: 'session-alpha' });
runGsdTools(['workstream', 'set', 'beta', '--raw'], tmpDir, { GSD_SESSION_KEY: 'session-beta' });
// eslint-disable-next-line local/no-raw-rmsync-in-tests -- mid-test fault injection: simulates a deleted workstream to exercise stale-pointer self-cleanup
fs.rmSync(path.join(tmpDir, '.planning', 'workstreams', 'alpha'), { recursive: true, force: true });
const alpha = runGsdTools(['workstream', 'get'], tmpDir, { GSD_SESSION_KEY: 'session-alpha' });
const beta = runGsdTools(['workstream', 'get', '--raw'], tmpDir, { GSD_SESSION_KEY: 'session-beta' });
assert.ok(alpha.success, `stale alpha get failed: ${alpha.error}`);
assert.ok(beta.success, `beta get after stale cleanup failed: ${beta.error}`);
assert.strictEqual(JSON.parse(alpha.output).active, null);
assert.strictEqual(beta.output, 'beta');
assert.ok(fs.existsSync(sessionDir), 'sibling pointer should keep the session tmp directory alive');
assert.deepStrictEqual(fs.readdirSync(sessionDir).sort(), [betaFile]);
});
test('clearing the last session pointer removes the empty session tmp directory', () => {
const sessionDir = getSessionPointerDir(tmpDir);
const set = runGsdTools(['workstream', 'set', 'alpha', '--raw'], tmpDir, { GSD_SESSION_KEY: 'session-alpha' });
assert.ok(set.success, `set alpha failed: ${set.error}`);
assert.ok(fs.existsSync(sessionDir), 'session tmp directory should exist after storing a session-scoped pointer');
const clear = runGsdTools(['workstream', 'set', '--clear', '--raw'], tmpDir, { GSD_SESSION_KEY: 'session-alpha' });
assert.ok(clear.success, `clear alpha failed: ${clear.error}`);
assert.ok(!fs.existsSync(sessionDir), 'last-pointer cleanup should remove the empty session tmp directory');
});
});
// ─── Workstream CRUD ────────────────────────────────────────────────────────
describe('workstream create', () => {
let tmpDir;
before(() => {
tmpDir = createFixture();
fs.writeFileSync(path.join(tmpDir, '.planning', 'PROJECT.md'), '# Project\n');
});
after(() => cleanup(tmpDir));
test('creates a new workstream in clean project', () => {
const result = runGsdTools(['workstream', 'create', 'feature-x', '--raw'], tmpDir);
assert.ok(result.success, `create failed: ${result.error}`);
const data = JSON.parse(result.output);
assert.strictEqual(data.created, true);
assert.strictEqual(data.workstream, 'feature-x');
assert.ok(fs.existsSync(path.join(tmpDir, '.planning', 'workstreams', 'feature-x', 'STATE.md')));
assert.ok(fs.existsSync(path.join(tmpDir, '.planning', 'workstreams', 'feature-x', 'phases')));
});
test('sets created workstream as active', () => {
const active = fs.readFileSync(path.join(tmpDir, '.planning', 'active-workstream'), 'utf-8').trim();
assert.strictEqual(active, 'feature-x');
});
test('rejects duplicate workstream', () => {
const result = runGsdTools(['workstream', 'create', 'feature-x', '--raw'], tmpDir);
assert.ok(result.success); // returns success with error field
const data = JSON.parse(result.output);
assert.strictEqual(data.created, false);
assert.strictEqual(data.error, 'already_exists');
});
test('creates second workstream', () => {
const result = runGsdTools(['workstream', 'create', 'feature-y', '--raw'], tmpDir);
assert.ok(result.success);
const data = JSON.parse(result.output);
assert.strictEqual(data.created, true);
assert.strictEqual(data.workstream, 'feature-y');
});
});
describe('workstream create with migration', () => {
let tmpDir;
before(() => {
tmpDir = createFixture();
fs.writeFileSync(path.join(tmpDir, '.planning', 'PROJECT.md'), '# Project\n');
// Existing flat-mode work
fs.writeFileSync(path.join(tmpDir, '.planning', 'ROADMAP.md'), '## Roadmap v1.0: Existing\n### Phase 1: A\n');
fs.writeFileSync(path.join(tmpDir, '.planning', 'STATE.md'), '# State\n**Status:** In progress\n');
});
after(() => cleanup(tmpDir));
test('migrates existing flat work to named workstream', () => {
const result = runGsdTools(['workstream', 'create', 'new-feature', '--migrate-name', 'existing-work', '--raw'], tmpDir);
assert.ok(result.success, `create with migration failed: ${result.error}`);
const data = JSON.parse(result.output);
assert.strictEqual(data.created, true);
assert.ok(data.migration, 'should include migration info');
assert.strictEqual(data.migration.workstream, 'existing-work');
// Old flat files moved to workstream dir
assert.ok(fs.existsSync(path.join(tmpDir, '.planning', 'workstreams', 'existing-work', 'ROADMAP.md')));
assert.ok(fs.existsSync(path.join(tmpDir, '.planning', 'workstreams', 'existing-work', 'STATE.md')));
// Shared files stay
assert.ok(fs.existsSync(path.join(tmpDir, '.planning', 'PROJECT.md')));
});
test('normalizes --migrate-name to a valid workstream slug', () => {
const isolatedDir = createFixture();
try {
fs.writeFileSync(path.join(isolatedDir, '.planning', 'PROJECT.md'), '# Project\n');
fs.writeFileSync(path.join(isolatedDir, '.planning', 'ROADMAP.md'), '## Roadmap v1.0: Existing\n### Phase 1: A\n');
fs.writeFileSync(path.join(isolatedDir, '.planning', 'STATE.md'), '# State\n**Status:** In progress\n');
const result = runGsdTools(
['workstream', 'create', 'new-feature', '--migrate-name', 'Bad Name', '--raw'],
isolatedDir
);
assert.ok(result.success, `create with migrate-name normalization failed: ${result.error}`);
const data = JSON.parse(result.output);
assert.strictEqual(data.created, true);
assert.strictEqual(data.migration.workstream, 'bad-name');
assert.ok(fs.existsSync(path.join(isolatedDir, '.planning', 'workstreams', 'bad-name', 'ROADMAP.md')));
assert.ok(!fs.existsSync(path.join(isolatedDir, '.planning', 'workstreams', 'Bad Name')));
} finally {
cleanup(isolatedDir);
}
});
});
describe('migrateToWorkstreams', () => {
test('rejects invalid workstream names for migration', () => {
const tmpDir = createFixture();
try {
assert.throws(
() => migrateToWorkstreams(tmpDir, 'bad/name'),
/Invalid workstream name for migration/
);
} finally {
cleanup(tmpDir);
}
});
test('fails when already in workstream mode', () => {
const tmpDir = createFixture();
try {
fs.mkdirSync(path.join(tmpDir, '.planning', 'workstreams', 'existing'), { recursive: true });
assert.throws(
() => migrateToWorkstreams(tmpDir, 'new-stream'),
/Already in workstream mode/
);
} finally {
cleanup(tmpDir);
}
});
});
describe('workstream list', () => {
let tmpDir;
before(() => {
tmpDir = createFixture();
// Create two workstreams
for (const ws of ['alpha', 'beta']) {
const wsDir = path.join(tmpDir, '.planning', 'workstreams', ws);
fs.mkdirSync(path.join(wsDir, 'phases'), { recursive: true });
fs.writeFileSync(path.join(wsDir, 'STATE.md'), `# State\n**Status:** Working on ${ws}\n**Current Phase:** 1\n`);
}
fs.writeFileSync(path.join(tmpDir, '.planning', 'active-workstream'), 'beta\n');
});
after(() => cleanup(tmpDir));
test('lists all workstreams with active first, then lexical name', () => {
const result = runGsdTools(['workstream', 'list', '--raw'], tmpDir);
assert.ok(result.success, `list failed: ${result.error}`);
const data = JSON.parse(result.output);
assert.strictEqual(data.mode, 'workstream');
assert.strictEqual(data.count, 2);
assert.deepStrictEqual(data.workstreams.map(w => w.name), ['beta', 'alpha']);
});
describe('flat mode', () => {
let flatDir;
beforeEach(() => {
flatDir = createFixture();
});
afterEach(() => {
cleanup(flatDir);
});
test('reports flat mode when no workstreams exist', () => {
const result = runGsdTools(['workstream', 'list', '--raw'], flatDir);
assert.ok(result.success);
const data = JSON.parse(result.output);
assert.strictEqual(data.mode, 'flat');
});
});
});
describe('workstream status', () => {
let tmpDir;
before(() => {
tmpDir = createFixture();
const wsDir = path.join(tmpDir, '.planning', 'workstreams', 'alpha');
fs.mkdirSync(path.join(wsDir, 'phases', '01-setup'), { recursive: true });
fs.writeFileSync(path.join(wsDir, 'phases', '01-setup', 'PLAN.md'), '# Plan\n');
fs.writeFileSync(path.join(wsDir, 'STATE.md'), '# State\n**Status:** In progress\n**Current Phase:** 1 — Setup\n');
fs.writeFileSync(path.join(wsDir, 'ROADMAP.md'), '## Roadmap\n');
});
after(() => cleanup(tmpDir));
test('returns detailed status for workstream', () => {
const result = runGsdTools(['workstream', 'status', 'alpha', '--raw'], tmpDir);
assert.ok(result.success, `status failed: ${result.error}`);
const data = JSON.parse(result.output);
assert.strictEqual(data.found, true);
assert.strictEqual(data.workstream, 'alpha');
assert.strictEqual(data.files.roadmap, true);
assert.strictEqual(data.files.state, true);
assert.strictEqual(data.phase_count, 1);
});
test('returns not found for missing workstream', () => {
const result = runGsdTools(['workstream', 'status', 'nonexistent', '--raw'], tmpDir);
assert.ok(result.success);
const data = JSON.parse(result.output);
assert.strictEqual(data.found, false);
});
});
describe('workstream complete', () => {
let tmpDir;
before(() => {
tmpDir = createFixture();
const wsDir = path.join(tmpDir, '.planning', 'workstreams', 'done-ws');
fs.mkdirSync(path.join(wsDir, 'phases'), { recursive: true });
fs.writeFileSync(path.join(wsDir, 'STATE.md'), '# State\n**Status:** Complete\n');
fs.writeFileSync(path.join(tmpDir, '.planning', 'active-workstream'), 'done-ws\n');
});
after(() => cleanup(tmpDir));
test('archives workstream to milestones/', () => {
const result = runGsdTools(['workstream', 'complete', 'done-ws', '--raw'], tmpDir);
assert.ok(result.success, `complete failed: ${result.error}`);
const data = JSON.parse(result.output);
assert.strictEqual(data.completed, true);
assert.ok(data.archived_to.startsWith('.planning/milestones/ws-done-ws'));
// Workstream dir should be gone
assert.ok(!fs.existsSync(path.join(tmpDir, '.planning', 'workstreams', 'done-ws')));
});
test('clears active-workstream when completing active one', () => {
assert.ok(!fs.existsSync(path.join(tmpDir, '.planning', 'active-workstream')));
});
});
describe('workstream set/get', () => {
let tmpDir;
before(() => {
tmpDir = createFixture();
for (const ws of ['ws-a', 'ws-b']) {
const wsDir = path.join(tmpDir, '.planning', 'workstreams', ws);
fs.mkdirSync(path.join(wsDir, 'phases'), { recursive: true });
fs.writeFileSync(path.join(wsDir, 'STATE.md'), '# State\n');
}
});
after(() => cleanup(tmpDir));
test('sets active workstream', () => {
const result = runGsdTools(['workstream', 'set', 'ws-a', '--raw'], tmpDir);
assert.ok(result.success);
assert.strictEqual(result.output, 'ws-a');
});
test('gets active workstream', () => {
const result = runGsdTools(['workstream', 'get', '--raw'], tmpDir);
assert.ok(result.success);
assert.strictEqual(result.output, 'ws-a');
});
test('errors when set called with no name (#1527)', () => {
const result = runGsdTools(['workstream', 'set', '--raw'], tmpDir);
assert.ok(!result.success, 'should fail when no name provided');
assert.ok(result.error.includes('name required'), 'error should mention name required');
});
test('--clear explicitly unsets active workstream', () => {
// First set one
runGsdTools(['workstream', 'set', 'ws-b', '--raw'], tmpDir);
// Then clear
const result = runGsdTools(['workstream', 'set', '--clear', '--raw'], tmpDir);
assert.ok(result.success);
const data = JSON.parse(result.output);
assert.strictEqual(data.active, null);
assert.strictEqual(data.cleared, true);
assert.strictEqual(data.previous, 'ws-b');
});
});
// ─── Collision Detection ────────────────────────────────────────────────────
describe('getOtherActiveWorkstreams', () => {
let tmpDir;
before(() => {
tmpDir = createFixture();
// Create 3 workstreams: alpha (active), beta (active), gamma (completed)
for (const ws of ['alpha', 'beta', 'gamma']) {
const wsDir = path.join(tmpDir, '.planning', 'workstreams', ws);
fs.mkdirSync(path.join(wsDir, 'phases'), { recursive: true });
}
fs.writeFileSync(path.join(tmpDir, '.planning', 'workstreams', 'alpha', 'STATE.md'),
'# State\n**Status:** In progress\n**Current Phase:** 3\n');
fs.writeFileSync(path.join(tmpDir, '.planning', 'workstreams', 'beta', 'STATE.md'),
'# State\n**Status:** In progress\n**Current Phase:** 5\n');
fs.writeFileSync(path.join(tmpDir, '.planning', 'workstreams', 'gamma', 'STATE.md'),
'# State\n**Status:** 1.0 milestone complete\n');
});
after(() => cleanup(tmpDir));
test('workstream list excludes completed workstreams from active count', () => {
const result = runGsdTools(['workstream', 'list', '--raw'], tmpDir);
assert.ok(result.success);
const data = JSON.parse(result.output);
assert.strictEqual(data.count, 3); // all listed
const activeWs = data.workstreams.filter(w =>
!w.status.toLowerCase().includes('milestone complete'));
assert.strictEqual(activeWs.length, 2); // alpha and beta active
});
test('returns only non-complete siblings with phase progress metadata', () => {
const alphaPlan = path.join(tmpDir, '.planning', 'workstreams', 'alpha', 'phases', '01-alpha', 'PLAN.md');
const betaPlan = path.join(tmpDir, '.planning', 'workstreams', 'beta', 'phases', '01-beta', 'PLAN.md');
const betaSummary = path.join(tmpDir, '.planning', 'workstreams', 'beta', 'phases', '01-beta', 'SUMMARY.md');
fs.mkdirSync(path.dirname(alphaPlan), { recursive: true });
fs.mkdirSync(path.dirname(betaPlan), { recursive: true });
fs.writeFileSync(alphaPlan, '# Plan\n');
fs.writeFileSync(betaPlan, '# Plan\n');
fs.writeFileSync(betaSummary, '# Summary\n');
const others = getOtherActiveWorkstreams(tmpDir, 'alpha');
assert.strictEqual(others.length, 1);
assert.strictEqual(others[0].name, 'beta');
assert.strictEqual(others[0].phases, '1/1');
});
});
describe('workstream progress', () => {
let tmpDir;
before(() => {
tmpDir = createFixture();
const alphaDir = path.join(tmpDir, '.planning', 'workstreams', 'alpha');
fs.mkdirSync(path.join(alphaDir, 'phases'), { recursive: true });
fs.writeFileSync(path.join(alphaDir, 'STATE.md'), '# State\n**Status:** In progress\n');
fs.writeFileSync(path.join(alphaDir, 'ROADMAP.md'), '## Roadmap\n');
const wsDir = path.join(tmpDir, '.planning', 'workstreams', 'feature');
fs.mkdirSync(path.join(wsDir, 'phases', '01-init'), { recursive: true });
fs.writeFileSync(path.join(wsDir, 'phases', '01-init', 'PLAN.md'), '# Plan\n');
fs.writeFileSync(path.join(wsDir, 'phases', '01-init', 'SUMMARY.md'), '# Summary\n');
fs.writeFileSync(path.join(wsDir, 'STATE.md'), '# State\n**Status:** In progress\n**Current Phase:** 2\n');
fs.writeFileSync(path.join(wsDir, 'ROADMAP.md'), '## Roadmap\n### Phase 1: Init\n### Phase 2: Build\n');
fs.writeFileSync(path.join(tmpDir, '.planning', 'active-workstream'), 'feature\n');
});
after(() => cleanup(tmpDir));
test('returns progress summary in deterministic order', () => {
const result = runGsdTools(['workstream', 'progress', '--raw'], tmpDir);
assert.ok(result.success, `progress failed: ${result.error}`);
const data = JSON.parse(result.output);
assert.strictEqual(data.mode, 'workstream');
assert.strictEqual(data.count, 2);
assert.deepStrictEqual(data.workstreams.map(w => w.name), ['feature', 'alpha']);
assert.strictEqual(data.workstreams[0].name, 'feature');
assert.strictEqual(data.workstreams[0].active, true);
assert.strictEqual(data.workstreams[0].progress_percent, 50);
});
test('clamps progress percent when completed phase dirs exceed roadmap count', () => {
const isolatedDir = createFixture();
try {
const wsDir = path.join(isolatedDir, '.planning', 'workstreams', 'overflow');
for (const phase of ['01-one', '02-two']) {
const phaseDir = path.join(wsDir, 'phases', phase);
fs.mkdirSync(phaseDir, { recursive: true });
fs.writeFileSync(path.join(phaseDir, 'PLAN.md'), '# Plan\n');
fs.writeFileSync(path.join(phaseDir, 'SUMMARY.md'), '# Summary\n');
}
fs.writeFileSync(path.join(wsDir, 'STATE.md'), '# State\n**Status:** In progress\n');
fs.writeFileSync(path.join(wsDir, 'ROADMAP.md'), '# Roadmap\n### Phase 1: One\n');
const result = runGsdTools(['workstream', 'progress', '--raw'], isolatedDir);
assert.ok(result.success, `progress failed: ${result.error}`);
const data = JSON.parse(result.output);
assert.strictEqual(data.workstreams[0].progress_percent, 100);
} finally {
cleanup(isolatedDir);
}
});
test('returns flat mode when no workstreams exist', () => {
const emptyDir = createFixture();
try {
const result = runGsdTools(['workstream', 'progress', '--raw'], emptyDir);
assert.ok(result.success, `progress in flat mode failed: ${result.error}`);
const data = JSON.parse(result.output);
assert.strictEqual(data.mode, 'flat');
} finally {
cleanup(emptyDir);
}
});
});
// ─── Integration: gsd-tools --ws flag ────────────────────────────────────────
describe('gsd-tools --ws flag integration', () => {
let tmpDir;
before(() => {
tmpDir = createFixture();
// Create a workstream with roadmap
const wsDir = path.join(tmpDir, '.planning', 'workstreams', 'test-ws');
fs.mkdirSync(path.join(wsDir, 'phases', '01-setup'), { recursive: true });
fs.writeFileSync(path.join(wsDir, 'ROADMAP.md'),
'## Roadmap v1.0: Test\n### Phase 1: Setup\nDo setup things.\n');
fs.writeFileSync(path.join(wsDir, 'STATE.md'),
'---\nmilestone: v1.0\n---\n# State\n**Status:** In progress\n**Current Phase:** 1 — Setup\n');
fs.writeFileSync(path.join(wsDir, 'phases', '01-setup', 'PLAN.md'), '# Plan\n');
});
after(() => cleanup(tmpDir));
test('find-phase resolves to workstream-scoped phases via --ws', () => {
const result = runGsdTools(['find-phase', '1', '--raw', '--ws', 'test-ws'], tmpDir);
assert.ok(result.success, `find-phase failed: ${result.error}`);
assert.ok(result.output.includes('workstreams/test-ws'), `path should be workstream-scoped: ${result.output}`);
});
test('find-phase returns JSON with workstream path when not raw', () => {
const result = runGsdTools(['find-phase', '1', '--ws', 'test-ws'], tmpDir);
assert.ok(result.success, `find-phase failed: ${result.error}`);
const data = JSON.parse(result.output);
assert.ok(data.found, 'phase should be found');
assert.ok(data.directory.includes('workstreams/test-ws'), `path should be workstream-scoped: ${data.directory}`);
});
});
// ─── Path Traversal Rejection ────────────────────────────────────────────────
describe('path traversal rejection', () => {
let tmpDir;
before(() => {
tmpDir = createFixture();
fs.writeFileSync(path.join(tmpDir, '.planning', 'PROJECT.md'), '# Project\n');
const wsDir = path.join(tmpDir, '.planning', 'workstreams', 'legit');
fs.mkdirSync(path.join(wsDir, 'phases'), { recursive: true });
fs.writeFileSync(path.join(wsDir, 'STATE.md'), '# State\n');
});
after(() => cleanup(tmpDir));
const maliciousNames = [
'../../etc',
'../foo',
'ws/../../../passwd',
'a/b',
'ws name with spaces',
'..',
'.',
'ws..traversal',
];
describe('--ws flag rejects traversal attempts', () => {
for (const name of maliciousNames) {
test(`rejects --ws=${name}`, () => {
const result = runGsdTools(['workstream', 'list', '--raw', '--ws', name], tmpDir);
assert.ok(!result.success, `should reject --ws=${name}`);
assert.ok(result.error.includes('Invalid workstream name'), `error should mention invalid name for: ${name}`);
});
}
});
describe('GSD_WORKSTREAM env var rejects traversal attempts', () => {
for (const name of maliciousNames) {
test(`rejects GSD_WORKSTREAM=${name}`, () => {
const result = runGsdTools(['workstream', 'list', '--raw'], tmpDir, { GSD_WORKSTREAM: name });
assert.ok(!result.success, `should reject GSD_WORKSTREAM=${name}`);
assert.ok(result.error.includes('Invalid workstream name'), `error should mention invalid name for: ${name}`);
});
}
});
describe('cmdWorkstreamSet rejects traversal attempts', () => {
for (const name of maliciousNames) {
test(`rejects set ${name}`, () => {
const result = runGsdTools(['workstream', 'set', name, '--raw'], tmpDir);
// cmdWorkstreamSet validates the positional arg and returns invalid_name error
assert.ok(result.success, `command should exit cleanly for: ${name}`);
const data = JSON.parse(result.output);
assert.strictEqual(data.error, 'invalid_name', `should return invalid_name error for: ${name}`);
assert.strictEqual(data.active, null, `active should be null for: ${name}`);
});
}
});
describe('cmdWorkstreamStatus rejects invalid names consistently', () => {
for (const name of maliciousNames) {
test(`rejects status ${name}`, () => {
const result = runGsdTools(['workstream', 'status', name, '--raw'], tmpDir);
assert.ok(!result.success, `status should reject invalid name: ${name}`);
assert.ok(result.error.includes('Invalid workstream name'), `error should mention invalid name for: ${name}`);
});
}
});
describe('cmdWorkstreamComplete rejects invalid names consistently', () => {
for (const name of maliciousNames) {
test(`rejects complete ${name}`, () => {
const result = runGsdTools(['workstream', 'complete', name, '--raw'], tmpDir);
assert.ok(!result.success, `complete should reject invalid name: ${name}`);
assert.ok(result.error.includes('Invalid workstream name'), `error should mention invalid name for: ${name}`);
});
}
});
describe('getActiveWorkstream rejects poisoned active-workstream file', () => {
for (const name of maliciousNames) {
test(`rejects poisoned file containing ${name}`, () => {
// Write malicious name directly to the active-workstream file
fs.writeFileSync(path.join(tmpDir, '.planning', 'active-workstream'), name + '\n');
const result = runGsdTools(['workstream', 'get'], tmpDir, { GSD_WORKSTREAM: '' });
assert.ok(result.success, 'get should succeed');
const data = JSON.parse(result.output);
// getActiveWorkstream should return null for invalid names
assert.strictEqual(data.active, null, `should return null for poisoned name: ${name}`);
});
}
// Cleanup: remove poisoned file
test('cleanup: remove active-workstream file', () => {
try { fs.unlinkSync(path.join(tmpDir, '.planning', 'active-workstream')); } catch {}
});
});
describe('setActiveWorkstream rejects invalid names directly', () => {
const { setActiveWorkstream } = require('../gsd-core/bin/lib/planning-workspace.cjs');
for (const name of maliciousNames) {
test(`throws for ${name}`, () => {
assert.throws(
() => setActiveWorkstream(tmpDir, name),
{ message: /Invalid workstream name/ },
`should throw for: ${name}`
);
});
}
});
});
// #2562: the inventory can refuse a shipped marker its artifacts contradict, but
// a refusal that no command projects is the same silent collapse the issue is
// about — the operator sees a fallback `status` and nothing saying a marker was
// seen and rejected. These assert at the CLI, the surface that was missing it,
// not at the builder that already had the field.
describe('#2562 — a refused shipped marker reaches every workstream command', () => {
let tmpDir;
before(() => {
tmpDir = createFixture();
const wsDir = path.join(tmpDir, '.planning', 'workstreams', 'dirty-archive');
// A milestone that was archived (snapshot present) and then reopened: phase 1
// is complete and still on disk, phase 2 is declared with no directory. The
// archive is therefore not clean AND the ratio is short.
fs.mkdirSync(path.join(wsDir, 'phases', '1-foo'), { recursive: true });
fs.writeFileSync(path.join(wsDir, 'phases', '1-foo', '01-PLAN.md'), '# Plan\n');
fs.writeFileSync(path.join(wsDir, 'phases', '1-foo', '01-SUMMARY.md'), '# Summary\n');
fs.writeFileSync(path.join(wsDir, 'STATE.md'), 'milestone: v2.0\nstatus: executing\n');
fs.writeFileSync(path.join(wsDir, 'ROADMAP.md'), [
'# Roadmap', '', '## Milestone v2.0 — Two', '', '## Progress', '',
'| Phase | Milestone | Plans | Status | Done |',
'| --- | --- | --- | --- | --- |',
'| 1. Foo | v2.0 | 1/1 | Complete | - |',
'| 2. Bar | v2.0 | 0/1 | Not started | - |', '',
].join('\n'));
fs.mkdirSync(path.join(wsDir, 'milestones'), { recursive: true });
fs.writeFileSync(path.join(wsDir, 'milestones', 'v2.0-ROADMAP.md'), '# v2.0 archived\n');
fs.writeFileSync(path.join(tmpDir, '.planning', 'active-workstream'), 'dirty-archive\n');
});
after(() => cleanup(tmpDir));
test('workstream progress projects the refusal beside the percentage', () => {
const result = runGsdTools(['workstream', 'progress', '--raw'], tmpDir);
assert.ok(result.success, `progress failed: ${result.error}`);
const ws = JSON.parse(result.output).workstreams.find(w => w.name === 'dirty-archive');
assert.ok(ws, 'workstream missing from progress output');
assert.strictEqual(ws.milestone_shipped_unverified, true);
assert.notStrictEqual(ws.status, 'milestone complete', 'status must not contradict the percentage');
assert.strictEqual(ws.progress_percent, 50);
});
test('workstream status projects the refusal', () => {
const result = runGsdTools(['workstream', 'status', 'dirty-archive', '--raw'], tmpDir);
assert.ok(result.success, `status failed: ${result.error}`);
const data = JSON.parse(result.output);
assert.strictEqual(data.found, true);
assert.strictEqual(data.milestone_shipped_unverified, true);
});
test('workstream list projects the refusal', () => {
const result = runGsdTools(['workstream', 'list', '--raw'], tmpDir);
assert.ok(result.success, `list failed: ${result.error}`);
const ws = JSON.parse(result.output).workstreams.find(w => w.name === 'dirty-archive');
assert.ok(ws, 'workstream missing from list output');
assert.strictEqual(ws.milestone_shipped_unverified, true);
});
test('a clean archive reports no refusal at the CLI', () => {
const isolatedDir = createFixture();
try {
const wsDir = path.join(isolatedDir, '.planning', 'workstreams', 'clean-archive');
fs.mkdirSync(path.join(wsDir, 'phases'), { recursive: true }); // dirs moved out by the archive
fs.writeFileSync(path.join(wsDir, 'STATE.md'), 'milestone: v2.0\nstatus: executing\n');
fs.writeFileSync(path.join(wsDir, 'ROADMAP.md'), [
'# Roadmap', '', '## Milestone v2.0 — Two', '', '## Progress', '',
'| Phase | Milestone | Plans | Status | Done |',
'| --- | --- | --- | --- | --- |',
'| 1. Foo | v2.0 | 1/1 | Complete | - |',
'| 2. Bar | v2.0 | 1/1 | Complete | - |', '',
].join('\n'));
fs.mkdirSync(path.join(wsDir, 'milestones'), { recursive: true });
fs.writeFileSync(path.join(wsDir, 'milestones', 'v2.0-ROADMAP.md'), '# v2.0 archived\n');
const result = runGsdTools(['workstream', 'progress', '--raw'], isolatedDir);
assert.ok(result.success, `progress failed: ${result.error}`);
const ws = JSON.parse(result.output).workstreams.find(w => w.name === 'clean-archive');
assert.ok(ws, 'workstream missing from progress output');
assert.strictEqual(ws.milestone_shipped_unverified, false);
assert.strictEqual(ws.status, 'milestone complete');
} finally {
cleanup(isolatedDir);
}
});
});