Files
msd-core/gsd-core/references/workstream-flag.md
Tom Boucher 9de4d67118 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>
2026-08-18 11:37:44 -04:00

5.6 KiB

Workstream Flag (--ws)

Overview

The --ws <name> flag scopes GSD operations to a specific workstream, enabling parallel milestone work by multiple Claude Code instances on the same codebase.

Resolution Priority

  1. --ws <name> flag (explicit, highest priority)
  2. GSD_WORKSTREAM environment variable (per-instance)
  3. Session-scoped active workstream pointer in temp storage (per runtime session / terminal), when that pointer exists and is non-blank
  4. .planning/active-workstream file — consulted whenever step 3 has nothing to say: either there is no session identity at all, or there is one but it has never pointed at a workstream. A session that already has its own pointer (step 3) is never overridden by this step, even if that pointer is stale.
  5. null — flat mode (no workstreams)

Why session-scoped pointers exist

The shared .planning/active-workstream file is fundamentally unsafe when multiple Claude/Codex instances are active on the same repo at the same time. One session can silently repoint another session's STATE.md, ROADMAP.md, and phase paths.

GSD now prefers a session-scoped pointer keyed by runtime/session identity (GSD_SESSION_KEY, CODEX_THREAD_ID, CLAUDE_CODE_SESSION_ID, CLAUDE_CODE_SSE_PORT, terminal session IDs, or the controlling TTY). This keeps concurrent sessions isolated while preserving legacy compatibility for runtimes that do not expose a stable session key.

A session that has never set its own pointer inherits .planning/active-workstream (step 4) rather than silently falling back to flat mode — this does not weaken the isolation guarantee above: inheritance only fires when a session's own pointer is absent, and a session that has ever set one is never repointed by the shared file.

Session Identity Resolution

When GSD resolves the session-scoped pointer in step 3 above, it uses this order:

  1. Explicit runtime/session env vars such as GSD_SESSION_KEY, CODEX_THREAD_ID, CLAUDE_SESSION_ID, CLAUDE_CODE_SESSION_ID, CLAUDE_CODE_SSE_PORT, OPENCODE_SESSION_ID, GEMINI_SESSION_ID, CURSOR_SESSION_ID, WINDSURF_SESSION_ID, TERM_SESSION_ID, WT_SESSION, TMUX_PANE, and ZELLIJ_SESSION_NAME
  2. TTY or SSH_TTY if the shell/runtime already exposes the terminal path
  3. A single best-effort tty probe, but only when stdin is interactive

If none of those produce a stable identity, GSD does not keep probing. It falls back directly to the legacy shared .planning/active-workstream file.

This matters in headless or stripped environments: when stdin is already non-interactive, GSD intentionally skips shelling out to tty because that path cannot discover a stable session identity and only adds avoidable failures on the routing hot path.

Pointer Lifecycle

Session-scoped pointers are intentionally lightweight and best-effort:

  • Clearing a workstream for one session removes only that session's pointer file. This returns that session to step 4 of Resolution Priority above — it goes back to inheriting .planning/active-workstream (if a marker exists there), not to flat mode. A cleared session with no marker present resolves to null; a cleared session with a marker present resolves to whatever that marker names. To force flat mode for a cleared session, remove the shared marker file, or use an explicit override such as --ws / GSD_WORKSTREAM on the command in question.
  • If that was the last pointer for the repo, GSD also removes the now-empty per-project temp directory
  • If sibling session pointers still exist, the temp directory is left in place
  • When a pointer refers to a workstream directory that no longer exists, GSD treats it as stale state: it removes that pointer file and resolves to null until the session explicitly sets a new active workstream again

GSD does not currently run a background garbage collector for historical temp directories. Cleanup is opportunistic at the pointer being cleared or self-healed, and broader temp hygiene is left to OS temp cleanup or future maintenance work.

Routing Propagation

All workflow routing commands include ${GSD_WS} which:

  • Expands to --ws <name> when a workstream is active
  • Expands to empty string in flat mode (backward compatible)

This ensures workstream scope chains automatically through the workflow: new-milestone → discuss-phase → plan-phase → execute-phase → transition

Directory Structure

.planning/
├── PROJECT.md          # Shared
├── config.json         # Shared
├── milestones/         # Shared
├── codebase/           # Shared
├── active-workstream   # Shared marker; inherited when a session has no pointer of its own
└── workstreams/
    ├── feature-a/      # Workstream A
    │   ├── STATE.md
    │   ├── ROADMAP.md
    │   ├── REQUIREMENTS.md
    │   └── phases/
    └── feature-b/      # Workstream B
        ├── STATE.md
        ├── ROADMAP.md
        ├── REQUIREMENTS.md
        └── phases/

CLI Usage

# All gsd-tools query commands accept --ws
gsd-tools query state.json --ws feature-a
gsd-tools query find-phase 3 --ws feature-b

# Session-local switching without --ws on every command
GSD_SESSION_KEY=my-terminal-a gsd-tools query workstream.set feature-a
GSD_SESSION_KEY=my-terminal-a gsd-tools query state.json
GSD_SESSION_KEY=my-terminal-b gsd-tools query workstream.set feature-b
GSD_SESSION_KEY=my-terminal-b gsd-tools query state.json

# Workstream CRUD
gsd-tools query workstream.create <name>
gsd-tools query workstream.list
gsd-tools query workstream.status <name>
gsd-tools query workstream.complete <name>