fix(#3579): a pointer-less session inherits the repo active-workstream marker (#3616)

* test(3579): failing-first coverage for repo-marker inheritance

A session that carries an identity but has never run 'workstream use' reads an
absent session pointer, resolves null, and composes the flat .planning tree even
when .planning/active-workstream names a live workstream. These tests fail on that
and pin the invariants the fix must not break: a session with its own pointer is
never repointed, and a session that merely lacked a pointer must never clear the
shared marker on another session's behalf.

* fix(3579): a pointer-less session inherits the repo active-workstream marker

RED proven at 157cae26: the three inheritance tests failed while every isolation and
negative control passed on base — the gap, and nothing else.

pickActiveWorkstreamAdapter returned exactly ONE adapter: the session-scoped one
whenever a session key existed, so the shared .planning/active-workstream marker was
never consulted. getWorkstreamSessionKey resolves a key from ~13 env vars or the
controlling TTY, so on any normal interactive terminal a key almost always exists —
which is why a session that had never run 'workstream use' read an absent pointer,
resolved null, and composed the FLAT planning tree even though the repo marker named a
live workstream. Reads misreported; writes corrupted the superseded flat STATE. Silent,
because the stale tree is well-formed.

This was a genuine design fork, not an oversight: references/workstream-flag.md
documented step 4 as a fallback 'when no session key exists', and the session isolation
that buys is deliberate (#2850). The issue's Agent Brief left the choice open and said
the reference doc should match whatever semantics ship. The maintainer ruled in chat for
inheritance.

Resolution now walks an ORDERED chain — session adapter first, shared second — and only
a null from the session adapter falls through to the marker. Strictly additive: it can
only turn a null into a name, never change a name that already resolves.

The dangerous part is clear() ownership. resolveFromChain treats chain[0] as owned: only
it is ever cleared, and only under selfHeal (getActiveWorkstream, never peek). An
INHERITED marker is read-only — a stale value there resolves null and the file is left
alone. Without that, one pointer-less session's read would delete the repo marker for
every other session, which is a worse bug than the one being fixed. Covered by a test
that asserts the marker still exists on disk after such a read.

peekActiveWorkstream inherits but still mutates nothing (#2850 — the statusline draws on
every render).

references/workstream-flag.md's Resolution Priority is rewritten to match, keeping the
session-isolation rationale and noting that inheritance does not weaken it: a session
that owns a pointer is never repointed.

Fixes #3579

* fix(3579): correct the guard diagnostics and lock the clear-semantics

Three review passes; every finding fixed inline.

MISSING ACCEPTANCE CRITERION (spec pass). The brief requires refusal diagnostics that
distinguish 'marker present but the session lookup missed it' from 'no workstream set at
all', and the two workstream-mode fail-safe guards were byte-for-byte untouched — still
emitting a generic 'no active workstream is set' even when a marker exists and merely
names a missing directory. Both guards (cmdPhaseComplete, cmdInitProgress) now branch on
a new read-only diagnoseUnresolvedActiveWorkstream, which reuses the SAME
resolvesToExistingWorkstream predicate resolveFromChain uses, so the diagnosis and the
resolution cannot disagree. Two typed reasons added to ERROR_REASON; both arms still
refuse — the fail-closed behavior is unchanged, only the message is now true.

REAL TEST FAILURE, not a flake. The remote run failed 'clearing one session does not
clear another session pointer'. That describe uses before() rather than beforeEach, so
one tmpDir is shared and an earlier test writes active-workstream=beta into it; under
inheritance the just-cleared session picks that marker up and resolves beta instead of
null. The failure is a CORRECT consequence of Option A surfaced through an
order-dependent fixture. The test now establishes its own marker state explicitly — its
real intent (clearing A must not disturb B's pointer) is preserved and not weakened — and
a new test pins the semantic deliberately: clearing a session pointer returns that
session to INHERITING the marker, it does not force flat mode. Documented in
references/workstream-flag.md, including how to actually get flat behavior.

Also from review: partial activeWorkstreamAdapters injection no longer silently
synthesizes a REAL filesystem adapter for the missing half (a latent test-isolation
trap); the duplicated validate-then-existsSync logic is factored into one predicate; and
the two try/finally test bodies are converted to t.after per CONTRIBUTING.

New coverage: whitespace/empty shared marker; a session whose OWN pointer is stale while
the marker names a different valid workstream (must self-heal to null, never inherit —
the isolation guarantee at its sharpest); and both new diagnostic arms asserted on
structured --json-errors output rather than prose.

* fix(3579): read resolvability with the non-mutating peek, not the self-healing resolver

Three of our own new tests failed on 7f5e706a. All three had ONE root cause, and none
was fixed by relaxing an assertion.

gsd-tools.cjs's bootstrap called the MUTATING getActiveWorkstream unconditionally on
every invocation, purely to populate routing env. On an unresolvable pointer that
self-healed — cleared it — BEFORE the dispatched command ran its own resolution. A second
read in the same process then observed already-cleared state:

- Isolation violation: a session whose own pointer was stale had it cleared by the
  bootstrap, so cmdWorkstreamGet's own resolution found a pointer-LESS session and
  inherited the shared marker ('beta' instead of null). Exactly the guarantee #2850 exists
  to protect, defeated across two calls rather than within one.
- Guard diagnostics: the guards' own truthiness check also used the mutating resolver, so
  it cleared the invalid marker and the immediately-following read-only diagnosis found
  nothing and reported none_active instead of marker_unresolved.

So a single invocation's answer depended on how many times it resolved. The bootstrap
self-heal is PRE-EXISTING and was harmless while pointer-less meant flat — inheritance is
what made it answer-changing, so this fix belongs here.

Every call site that only CHECKS resolvability — the bootstrap, both fail-safe guards'
truthiness check, and two informational init report fields — now uses the non-mutating
peekActiveWorkstream. Self-heal is unchanged in active-workstream-store and still fires
exactly once, at whichever site actually consumes the workstream.

Verified by driving the real CLI against temp fixtures, since the suite cannot run
locally: stale-own-pointer resolves null with the marker intact; both guard arms report
marker_unresolved with missing_workstream_dir / invalid_name and the marker survives;
no-marker still reports none_active; identity-less self-heal still deletes an invalid
marker byte-identically to pre-#3579; and a session with a valid own pointer still wins.

* chore(3579): backfill changeset PR number (#3616)

* test(3579): kill the surviving mutants in the new resolution code

CI's Stryker gate failed: active-workstream-store scored 79.45% against a break
threshold of 80 — 259 killed, 67 survived, at 'Ran 1.00 tests per mutant on average'.
The survivors cluster in the code this PR added (pickActiveWorkstreamAdapterChain,
resolvesToExistingWorkstream, resolveFromChain, diagnoseUnresolvedActiveWorkstream):
the CLI-level tests exercise those paths but do not DISCRIMINATE their branches, which
is precisely what a surviving mutant means.

Raised by strengthening assertions, never by touching the threshold. 21 unit tests added
to the existing unit suite, each written to fail under a specific named mutant, using the
module's injected adapter seams and createMemoryPointerAdapter so they stay hermetic
under Stryker's per-mutant reruns:

- chain shape with and without a session key, asserting length AND element identity
  (kills the if(false), the ': []' array mutant, and the block removal)
- partial adapter injection, asserting the missing half is an inert memory adapter that
  never touches the filesystem (kills the three '??' -> '&&' mutants)
- both arms of '!name || !validateWorkstreamName(name)' as SEPARATE tests — an absent
  name and a non-empty invalid one — which is what kills the '||' -> '&&' mutant
- self-heal discrimination: getActiveWorkstream must clear an unresolvable owned pointer
  and peekActiveWorkstream must not, asserted on adapter state after each
  (kills if(selfHeal) -> if(true))
- fallback arm both ways: a fallback that resolves and one that does not
- diagnoseUnresolvedActiveWorkstream asserted as a full object per case, with the reason
  strings compared exactly (kills present:true -> false and both StringLiteral mutants)

One mutant is deliberately left: 'if (chain.length === 0)' -> 'if (false)'. The branch is
structurally unreachable — the only chain source always returns a 1- or 2-element array
literal — and resolveFromChain is not exported. Killing it would mean exporting an
internal or deleting a defensive guard; neither is worth doing for a mutant, and the
score clears 80 without it. Recorded here rather than left unexplained.

Every new assertion was evaluated against the built module with real fixtures before
committing, since the suite cannot run locally.

---------

Co-authored-by: sim <sim@local>
This commit is contained in:
Tom Boucher
2026-08-18 11:37:44 -04:00
committed by GitHub
parent 682eaae3f0
commit 9de4d67118
10 changed files with 780 additions and 46 deletions

View File

@@ -222,23 +222,142 @@ function pickActiveWorkstreamAdapter(cwd: string, opts: ActiveWorkstreamOpts = {
return createSharedPointerAdapter(cwd);
}
/**
* Read-resolution chain for getActiveWorkstream/peekActiveWorkstream (#3579).
*
* pickActiveWorkstreamAdapter (above) picks exactly one adapter and remains
* the seam for WRITE paths (set/clear), where "which pointer do I mutate" has
* only one right answer: the session pointer when a session key exists,
* otherwise the shared marker. Reads are different — a session that has
* never called `workstream use` has no opinion of its own, so it should
* inherit the repo-wide `.planning/active-workstream` marker rather than
* resolve to nothing. This returns an ORDERED chain: [owned, ...fallbacks].
* `chain[0]` ("owned") is exactly what pickActiveWorkstreamAdapter would have
* returned — resolveFromChain() self-heals only chain[0], never a fallback,
* so one session's read can never delete another scope's marker. Fallbacks
* are consulted ONLY when chain[0].read() comes back absent/empty; a session
* with its own (even stale/invalid) pointer never falls through — that is
* the isolation guarantee and it must not be weakened by inheritance.
*/
function pickActiveWorkstreamAdapterChain(cwd: string, opts: ActiveWorkstreamOpts = {}): WorkstreamPointerAdapter[] {
if (opts.activeWorkstreamAdapter) {
return [opts.activeWorkstreamAdapter];
}
// #3579 item 3: when a caller supplies `opts.activeWorkstreamAdapters` at
// all, honor ONLY what it provides. The prior `|| createXPointerAdapter(...)`
// fallback synthesized a REAL filesystem adapter for whichever half a test
// double omitted — so a test injecting only `{ session }` silently touched
// the real shared marker file, and one injecting only `{ shared }` silently
// touched the real session-scoped tmp file. A missing half now gets a
// no-op in-memory adapter (always reads null) instead — this preserves the
// chain[0]-is-owned / rest-are-fallback shape resolveFromChain relies on
// without ever reaching disk. A caller that wants a real adapter for one
// half can still construct and pass it explicitly.
const injected = opts.activeWorkstreamAdapters;
const sessionKey = getWorkstreamSessionKey();
if (!sessionKey) {
const shared = injected
? (injected.shared ?? createMemoryPointerAdapter(null))
: createSharedPointerAdapter(cwd);
return [shared];
}
const session = injected
? (injected.session ?? createMemoryPointerAdapter(null))
: createSessionScopedPointerAdapter(cwd, sessionKey);
const shared = injected
? (injected.shared ?? createMemoryPointerAdapter(null))
: createSharedPointerAdapter(cwd);
return session ? [session, shared] : [shared];
}
/**
* Shared "does this stored name resolve" predicate — format-valid AND its
* workstream directory exists. Factored out so resolveFromChain's owned/
* fallback arms (and diagnoseUnresolvedActiveWorkstream, #3579 item 1) share
* one definition of "resolvable" instead of re-deriving the same two checks.
*/
function resolvesToExistingWorkstream(cwd: string, name: string | null): name is string {
if (!name || !validateWorkstreamName(name)) return false;
return fs.existsSync(path.join(planningRoot(cwd), 'workstreams', name));
}
/**
* Resolves a stored workstream name by walking an adapter chain.
*
* chain[0] is "owned" by this resolution: an absent/empty read falls through
* to the next adapter, but a present-and-bad read (invalid name, or a name
* whose workstream dir no longer exists) is resolved right there — self-
* healed via adapter.clear() when `selfHeal` is true, and never consulted
* further. Anything after chain[0] is a read-only fallback (the inherited
* marker): a bad value there resolves to null WITHOUT ever calling clear(),
* so a pointer-less session's read can never delete the shared marker that
* other sessions/scopes still depend on.
*/
function resolveFromChain(cwd: string, chain: WorkstreamPointerAdapter[], selfHeal: boolean): string | null {
if (chain.length === 0) return null;
const [owned, ...fallbacks] = chain;
const ownedName = owned.read();
if (ownedName) {
if (!resolvesToExistingWorkstream(cwd, ownedName)) {
if (selfHeal) owned.clear();
return null;
}
return ownedName;
}
for (const adapter of fallbacks) {
const name = adapter.read();
if (resolvesToExistingWorkstream(cwd, name)) return name;
}
return null;
}
/**
* Diagnostic sibling of resolveFromChain (#3579 item 1). getActiveWorkstream/
* peekActiveWorkstream collapse EVERY unresolvable case to `null`, which is
* exactly right for routing — but a fail-safe guard reporting "no active
* workstream is set" to an operator needs to distinguish two very different
* situations that both produce that same `null`:
*
* (a) no marker/pointer exists anywhere in the chain at all, vs.
* (b) a marker/pointer EXISTS (names a value) but that value didn't
* resolve — either the name fails validateWorkstreamName, or it's a
* well-formed name whose `workstreams/<name>` directory is missing.
*
* Walks the same chain resolveFromChain uses and, for the first adapter that
* held a non-empty raw value, reports why it didn't resolve. Read-only: never
* calls adapter.clear() (mirrors peekActiveWorkstream, not getActiveWorkstream
* — a diagnostic read must not have side effects). Reuses
* resolvesToExistingWorkstream so this can never disagree with the actual
* resolution predicate above.
*/
function diagnoseUnresolvedActiveWorkstream(
cwd: string,
opts: ActiveWorkstreamOpts = {},
): { present: boolean; value: string | null; reason: 'invalid_name' | 'missing_workstream_dir' | null } {
const chain = pickActiveWorkstreamAdapterChain(cwd, opts);
for (const adapter of chain) {
const raw = adapter.read();
if (!raw) continue;
if (resolvesToExistingWorkstream(cwd, raw)) continue;
return {
present: true,
value: raw,
reason: validateWorkstreamName(raw) ? 'missing_workstream_dir' : 'invalid_name',
};
}
return { present: false, value: null, reason: null };
}
function getActiveWorkstream(cwd: string, opts: ActiveWorkstreamOpts = {}): string | null {
const adapter = pickActiveWorkstreamAdapter(cwd, opts);
if (!adapter) return null;
const name = adapter.read();
if (!name || !validateWorkstreamName(name)) {
adapter.clear();
return null;
}
const wsDir = path.join(planningRoot(cwd), 'workstreams', name);
if (!fs.existsSync(wsDir)) {
adapter.clear();
return null;
}
return name;
const chain = pickActiveWorkstreamAdapterChain(cwd, opts);
return resolveFromChain(cwd, chain, true);
}
/**
@@ -254,16 +373,8 @@ function getActiveWorkstream(cwd: string, opts: ActiveWorkstreamOpts = {}): stri
* pointer file is left exactly as it was for whatever created it to fix.
*/
function peekActiveWorkstream(cwd: string, opts: ActiveWorkstreamOpts = {}): string | null {
const adapter = pickActiveWorkstreamAdapter(cwd, opts);
if (!adapter) return null;
const name = adapter.read();
if (!name || !validateWorkstreamName(name)) return null;
const wsDir = path.join(planningRoot(cwd), 'workstreams', name);
if (!fs.existsSync(wsDir)) return null;
return name;
const chain = pickActiveWorkstreamAdapterChain(cwd, opts);
return resolveFromChain(cwd, chain, false);
}
function setActiveWorkstream(cwd: string, name: string | null | undefined, opts: ActiveWorkstreamOpts = {}): void {
@@ -381,8 +492,10 @@ export = {
createSessionScopedPointerAdapter,
createMemoryPointerAdapter,
pickActiveWorkstreamAdapter,
pickActiveWorkstreamAdapterChain,
getActiveWorkstream,
peekActiveWorkstream,
diagnoseUnresolvedActiveWorkstream,
setActiveWorkstream,
clearActiveWorkstream,
parseCliWorkstream,

View File

@@ -78,7 +78,7 @@ const {
listCodebaseMapFiles,
} = onboardProjection;
const { output, error } = io;
const { output, error, ERROR_REASON } = io;
const { loadConfig, loadConfigResolved } = configLoader;
const { resolveModelInternal, resolveGranularityInternal, assertValidGranularityOverride } = modelResolver;
const { findPhaseInternal, listMilestonePhaseDirs } = phaseLocator;
@@ -97,7 +97,9 @@ const {
planningDir,
planningRoot,
listAvailableWorkstreams,
getActiveWorkstream,
peekActiveWorkstream,
diagnoseUnresolvedActiveWorkstream,
describeUnresolvedWorkstreamReason,
findContextMdIn,
} = planningWorkspace;
@@ -1372,7 +1374,13 @@ function cmdInitNewMilestone(cwd: string, raw: boolean, options: Record<string,
// source as `cmdInitTransition`: `GSD_WORKSTREAM` env, falling back to the
// stored active-workstream pointer (mirrors `cmdInitProgress`'s own
// resolution above).
const resolvedWorkstream = process.env['GSD_WORKSTREAM'] || getActiveWorkstream(cwd);
//
// #3579 root-cause fix: this is a read-only informational field (no write
// follows), so use the non-mutating peek — getActiveWorkstream's self-heal
// would otherwise silently delete a stale/invalid pointer as a side effect
// of building a JSON report field, and (per #3579) could change what a
// LATER resolution in the same process observes.
const resolvedWorkstream = process.env['GSD_WORKSTREAM'] || peekActiveWorkstream(cwd);
const workstreamActive = !!resolvedWorkstream;
const flatMode = !workstreamActive;
@@ -2817,7 +2825,9 @@ function cmdInitUpdate(cwd: string, raw: boolean, options: Record<string, unknow
* pure JSON consumer with no `gsd_run` call of its own.
*/
function cmdInitTransition(cwd: string, raw: boolean, options: Record<string, unknown> = {}): void {
const resolvedWorkstream = process.env['GSD_WORKSTREAM'] || getActiveWorkstream(cwd);
// #3579 root-cause fix: read-only informational field — peek, don't
// self-heal (see cmdInitNewMilestone's identical rationale above).
const resolvedWorkstream = process.env['GSD_WORKSTREAM'] || peekActiveWorkstream(cwd);
const workstreamActive = !!resolvedWorkstream;
const result: Record<string, unknown> = {
@@ -2914,12 +2924,33 @@ function cmdInitProgress(cwd: string, raw: boolean, options: Record<string, unkn
// Mirror planningDir's resolution (GSD_WORKSTREAM env > stored active pointer) so
// an explicit --ws (which sets GSD_WORKSTREAM) satisfies the check.
const _availableWorkstreams = listAvailableWorkstreams(cwd);
const _resolvedWorkstream = process.env['GSD_WORKSTREAM'] || getActiveWorkstream(cwd);
// #3579 root-cause fix: this is a check, not a consuming read — use the
// non-mutating peek so an unresolvable pointer isn't self-healed (cleared)
// here and then found "absent" by diagnoseUnresolvedActiveWorkstream below,
// which would misreport a present-but-bad marker as no marker at all.
const _resolvedWorkstream = process.env['GSD_WORKSTREAM'] || peekActiveWorkstream(cwd);
if (_availableWorkstreams.length > 0 && !_resolvedWorkstream) {
// #3579: getActiveWorkstream now inherits a pointer-less session's read
// from the shared .planning/active-workstream marker, so reaching this
// branch with a marker actually present means the marker EXISTED but
// didn't resolve (invalid name, or its workstream dir is gone) — a
// materially different situation from "nothing was ever set" and one
// that deserves its own diagnostic instead of the generic message below.
const _diagnosis = diagnoseUnresolvedActiveWorkstream(cwd);
if (_diagnosis.present) {
error(
`init.progress requires a workstream in workstream mode — the active-workstream marker names '${_diagnosis.value}', but it did not resolve: ${describeUnresolvedWorkstreamReason(_diagnosis.reason)}. Root STATE.md (likely stale) would be reported otherwise. ` +
`Pass --ws <name> or run ${formatGsdSlash('workstream set', _slashRuntime) as string} to point it at an existing workstream. ` +
`Available workstreams: ${_availableWorkstreams.join(', ')}`,
ERROR_REASON.WORKSTREAM_MODE_MARKER_UNRESOLVED,
{ marker_value: _diagnosis.value, marker_reason: _diagnosis.reason },
);
}
error(
`init.progress requires a workstream in workstream mode — no active workstream is set, so root STATE.md (likely stale) would be reported. ` +
`Pass --ws <name> or run ${formatGsdSlash('workstream set', _slashRuntime) as string} first. ` +
`Available workstreams: ${_availableWorkstreams.join(', ')}`,
ERROR_REASON.WORKSTREAM_MODE_NONE_ACTIVE,
);
}

View File

@@ -192,6 +192,12 @@ const ERROR_REASON = Object.freeze({
PHASE_VERIFICATION_INCOMPLETE: 'phase_verification_incomplete',
PHASE_PLAN_COVERAGE_INCOMPLETE: 'phase_plan_coverage_incomplete',
SUMMARY_NO_PLANNING: 'summary_no_planning',
// #3579: workstream-mode fail-safe guards (init.progress, phase.complete) —
// distinguishes "no marker/pointer anywhere" from "a marker exists but
// didn't resolve" so a JSON-error-mode caller can branch on `reason`
// instead of regexing the human message.
WORKSTREAM_MODE_NONE_ACTIVE: 'workstream_mode_none_active',
WORKSTREAM_MODE_MARKER_UNRESOLVED: 'workstream_mode_marker_unresolved',
// graphify
GRAPHIFY_NO_GRAPH: 'graphify_no_graph',
GRAPHIFY_INVALID_QUERY: 'graphify_invalid_query',

View File

@@ -82,8 +82,10 @@ const { readVerificationStatus } = verificationMod;
import planDependencyGraphMod = require('./plan-dependency-graph.cjs');
const { computeHaltPropagation, buildSummaryFileIndex, isSummaryFileHalted, isSummaryFileBlocked } = planDependencyGraphMod;
const { planningDir, withPlanningLock, listAvailableWorkstreams, getActiveWorkstream } =
planningWorkspace;
const {
planningDir, withPlanningLock, listAvailableWorkstreams,
peekActiveWorkstream, diagnoseUnresolvedActiveWorkstream, describeUnresolvedWorkstreamReason,
} = planningWorkspace;
// eslint-disable-next-line @typescript-eslint/no-require-imports -- milestone-lock.cjs is an export= CommonJS module
import milestoneLockMod = require('./milestone-lock.cjs');
const { extractFrontmatter } = frontmatterMod;
@@ -2208,12 +2210,33 @@ function cmdPhaseComplete(cwd: string, phaseNum: string, raw: boolean): void {
// init.progress got (resolution: GSD_WORKSTREAM env > stored active pointer; an
// explicit --ws sets GSD_WORKSTREAM upstream and satisfies the check).
const availableWorkstreams = listAvailableWorkstreams(cwd);
const resolvedWorkstream = process.env['GSD_WORKSTREAM'] || getActiveWorkstream(cwd);
// #3579 root-cause fix: this is a check, not a consuming read — use the
// non-mutating peek so an unresolvable pointer isn't self-healed (cleared)
// here and then found "absent" by diagnoseUnresolvedActiveWorkstream below,
// which would misreport a present-but-bad marker as no marker at all.
const resolvedWorkstream = process.env['GSD_WORKSTREAM'] || peekActiveWorkstream(cwd);
if (availableWorkstreams.length > 0 && !resolvedWorkstream) {
// #3579: getActiveWorkstream now inherits a pointer-less session's read
// from the shared .planning/active-workstream marker, so reaching this
// branch with a marker actually present means the marker EXISTED but
// didn't resolve (invalid name, or its workstream dir is gone) — a
// materially different situation from "nothing was ever set" and one
// that deserves its own diagnostic instead of the generic message below.
const diagnosis = diagnoseUnresolvedActiveWorkstream(cwd);
if (diagnosis.present) {
error(
`phase.complete requires a workstream in workstream mode — the active-workstream marker names '${diagnosis.value}', but it did not resolve: ${describeUnresolvedWorkstreamReason(diagnosis.reason)}. Root STATE.md/ROADMAP.md (likely stale) would be written otherwise. ` +
`Pass --ws <name> or run ${formatGsdSlash('workstream set', resolveRuntime(cwd)) as string} to point it at an existing workstream. ` +
`Available workstreams: ${availableWorkstreams.join(', ')}`,
ERROR_REASON.WORKSTREAM_MODE_MARKER_UNRESOLVED,
{ marker_value: diagnosis.value, marker_reason: diagnosis.reason },
);
}
error(
`phase.complete requires a workstream in workstream mode — no active workstream is set, so root STATE.md/ROADMAP.md (likely stale) would be written. ` +
`Pass --ws <name> or run ${formatGsdSlash('workstream set', resolveRuntime(cwd)) as string} first. ` +
`Available workstreams: ${availableWorkstreams.join(', ')}`,
ERROR_REASON.WORKSTREAM_MODE_NONE_ACTIVE,
);
}

View File

@@ -25,8 +25,10 @@ const {
createSessionScopedPointerAdapter,
createMemoryPointerAdapter,
getActiveWorkstream: getStoredActiveWorkstream,
peekActiveWorkstream: peekStoredActiveWorkstream,
setActiveWorkstream: setStoredActiveWorkstream,
clearActiveWorkstream: clearStoredActiveWorkstream,
diagnoseUnresolvedActiveWorkstream: diagnoseUnresolvedStoredActiveWorkstream,
} = activeWorkstreamStore;
// Track .planning/.lock files held by this process so they can be removed on exit.
@@ -391,10 +393,47 @@ function getActiveWorkstream(cwd: string): string | null {
return getStoredActiveWorkstream(cwd);
}
// #3579 root-cause fix: read-only sibling of getActiveWorkstream, thin
// pass-through to active-workstream-store's non-mutating peek. Callers that
// only need to KNOW whether a workstream resolves (a guard's initial check,
// a bootstrap that will re-derive the answer anyway) must use this instead
// of getActiveWorkstream — the mutating variant self-heals (clears) a
// present-but-unresolvable chain[0] value, and a later read in the SAME
// process (another getActiveWorkstream call, or diagnoseUnresolvedActiveWorkstream)
// would then observe already-cleared state instead of the original evidence,
// silently changing the answer or losing the diagnostic reason. Self-heal
// still happens — exactly once, wherever the real consuming call site invokes
// getActiveWorkstream — this sibling just avoids triggering it prematurely.
function peekActiveWorkstream(cwd: string): string | null {
return peekStoredActiveWorkstream(cwd);
}
function setActiveWorkstream(cwd: string, name: string): void {
setStoredActiveWorkstream(cwd, name);
}
// #3579 item 1: read-only diagnostic sibling of getActiveWorkstream, thin
// pass-through to active-workstream-store's chain walk. Lets the #1912/#2028
// fail-safe guards (init.progress, phase.complete) distinguish "no marker at
// all" from "a marker exists but didn't resolve" without duplicating the
// resolution predicate.
function diagnoseUnresolvedActiveWorkstream(cwd: string): {
present: boolean;
value: string | null;
reason: 'invalid_name' | 'missing_workstream_dir' | null;
} {
return diagnoseUnresolvedStoredActiveWorkstream(cwd);
}
// #3579 item 1: human-readable clause for diagnoseUnresolvedActiveWorkstream's
// `reason`, shared by the init.progress and phase.complete fail-safe guards so
// the two error messages describe the same failure the same way instead of
// drifting (CLAUDE.md's Generative Fix Divergence anti-pattern).
function describeUnresolvedWorkstreamReason(reason: 'invalid_name' | 'missing_workstream_dir' | null): string {
if (reason === 'invalid_name') return 'the name is not a valid workstream name';
return "its workstream directory doesn't exist (it may have been renamed or removed)";
}
/**
* Locate the CONTEXT.md file in a phase directory, handling both the bare
* form (`CONTEXT.md`) and the padded-prefix convention (`NN-CONTEXT.md`,
@@ -441,7 +480,10 @@ export = {
quickDirFrom,
withPlanningLock,
getActiveWorkstream,
peekActiveWorkstream,
setActiveWorkstream,
diagnoseUnresolvedActiveWorkstream,
describeUnresolvedWorkstreamReason,
findContextMdIn,
// Test seam (audit M1): inject a deterministic isPidAlive so the liveness-gated
// steal decision is exercised without real pids. Mirrors capability-lock.cts.