feat: workstream namespacing for parallel milestone work

Enable multiple Claude Code instances to work on the same codebase
simultaneously by scoping .planning/ state into workstreams.

Core changes:
- planningDir(cwd, ws?) and planningPaths(cwd, ws?) are now workstream-aware
  via GSD_WORKSTREAM env var (auto-detected from --ws flag or active-workstream file)
- All bin/lib modules use planningDir(cwd) for scoped paths (STATE.md, ROADMAP.md,
  phases/, REQUIREMENTS.md) and planningRoot(cwd) for shared paths (milestones/,
  PROJECT.md, config.json, codebase/)
- New workstream.cjs module: create, list, status, complete, set, get, progress
- gsd-tools.cjs: --ws flag parsing with priority chain
  (--ws > GSD_WORKSTREAM env > active-workstream file > flat mode)
- Collision detection: transition.md checks for other active workstreams before
  suggesting next-milestone continuation (prevents WS A from trampling WS B)
- ${GSD_WS} routing propagation across all 9 workflow files ensures workstream
  scope chains automatically through the workflow lifecycle

New files:
- get-shit-done/bin/lib/workstream.cjs (CRUD + collision detection)
- get-shit-done/commands/gsd/workstreams.md (slash command)
- get-shit-done/references/workstream-flag.md (documentation)
- tests/workstream.test.cjs (20 tests covering CRUD, env var routing, --ws flag)

All 1062 tests passing (1042 existing + 20 new workstream tests).

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
This commit is contained in:
SalesTeamToolbox
2026-03-20 14:20:23 -07:00
parent c152d1275e
commit c83b69bbb5
23 changed files with 1436 additions and 202 deletions

View File

@@ -135,7 +135,8 @@
const fs = require('fs');
const path = require('path');
const { error, findProjectRoot } = require('./lib/core.cjs');
const core = require('./lib/core.cjs');
const { error, findProjectRoot, getActiveWorkstream } = core;
const state = require('./lib/state.cjs');
const phase = require('./lib/phase.cjs');
const roadmap = require('./lib/roadmap.cjs');
@@ -148,6 +149,7 @@ const init = require('./lib/init.cjs');
const frontmatter = require('./lib/frontmatter.cjs');
const profilePipeline = require('./lib/profile-pipeline.cjs');
const profileOutput = require('./lib/profile-output.cjs');
const workstream = require('./lib/workstream.cjs');
// ─── CLI Router ───────────────────────────────────────────────────────────────
@@ -185,6 +187,29 @@ async function main() {
}
}
// Optional workstream override for parallel milestone work.
// Priority: --ws flag > GSD_WORKSTREAM env var > active-workstream file > null (flat mode)
const wsEqArg = args.find(arg => arg.startsWith('--ws='));
const wsIdx = args.indexOf('--ws');
let ws = null;
if (wsEqArg) {
ws = wsEqArg.slice('--ws='.length).trim();
if (!ws) error('Missing value for --ws');
args.splice(args.indexOf(wsEqArg), 1);
} else if (wsIdx !== -1) {
ws = args[wsIdx + 1];
if (!ws || ws.startsWith('--')) error('Missing value for --ws');
args.splice(wsIdx, 2);
} else if (process.env.GSD_WORKSTREAM) {
ws = process.env.GSD_WORKSTREAM.trim();
} else {
ws = getActiveWorkstream(cwd);
}
// Set env var so all modules (planningDir, planningPaths) auto-resolve workstream paths
if (ws) {
process.env.GSD_WORKSTREAM = ws;
}
const rawIndex = args.indexOf('--raw');
const raw = rawIndex !== -1;
if (rawIndex !== -1) args.splice(rawIndex, 1);
@@ -203,7 +228,7 @@ async function main() {
const command = args[0];
if (!command) {
error('Usage: gsd-tools <command> [args] [--raw] [--pick <field>] [--cwd <path>]\nCommands: state, resolve-model, find-phase, commit, verify-summary, verify, frontmatter, template, generate-slug, current-timestamp, list-todos, verify-path-exists, config-ensure-section, config-new-project, init');
error('Usage: gsd-tools <command> [args] [--raw] [--pick <field>] [--cwd <path>] [--ws <name>]\nCommands: state, resolve-model, find-phase, commit, verify-summary, verify, frontmatter, template, generate-slug, current-timestamp, list-todos, verify-path-exists, config-ensure-section, config-new-project, init, workstream');
}
// Multi-repo guard: resolve project root for commands that read/write .planning/.
@@ -862,6 +887,33 @@ async function runCommand(command, args, cwd, raw) {
break;
}
case 'workstream': {
const subcommand = args[1];
if (subcommand === 'create') {
const migrateNameIdx = args.indexOf('--migrate-name');
const noMigrate = args.includes('--no-migrate');
workstream.cmdWorkstreamCreate(cwd, args[2], {
migrate: !noMigrate,
migrateName: migrateNameIdx !== -1 ? args[migrateNameIdx + 1] : null,
}, raw);
} else if (subcommand === 'list') {
workstream.cmdWorkstreamList(cwd, raw);
} else if (subcommand === 'status') {
workstream.cmdWorkstreamStatus(cwd, args[2], raw);
} else if (subcommand === 'complete') {
workstream.cmdWorkstreamComplete(cwd, args[2], {}, raw);
} else if (subcommand === 'set') {
workstream.cmdWorkstreamSet(cwd, args[2], raw);
} else if (subcommand === 'get') {
workstream.cmdWorkstreamGet(cwd, raw);
} else if (subcommand === 'progress') {
workstream.cmdWorkstreamProgress(cwd, raw);
} else {
error('Unknown workstream subcommand. Available: create, list, status, complete, set, get, progress');
}
break;
}
default:
error(`Unknown command: ${command}`);
}

View File

@@ -4,7 +4,7 @@
const fs = require('fs');
const path = require('path');
const { execSync } = require('child_process');
const { safeReadFile, loadConfig, isGitIgnored, execGit, normalizePhaseName, comparePhaseNum, getArchivedPhaseDirs, generateSlugInternal, getMilestoneInfo, getMilestonePhaseFilter, resolveModelInternal, stripShippedMilestones, extractCurrentMilestone, planningPaths, toPosixPath, output, error, findPhaseInternal, extractOneLinerFromBody, getRoadmapPhaseInternal } = require('./core.cjs');
const { safeReadFile, loadConfig, isGitIgnored, execGit, normalizePhaseName, comparePhaseNum, getArchivedPhaseDirs, generateSlugInternal, getMilestoneInfo, getMilestonePhaseFilter, resolveModelInternal, stripShippedMilestones, extractCurrentMilestone, planningDir, planningPaths, toPosixPath, output, error, findPhaseInternal, extractOneLinerFromBody, getRoadmapPhaseInternal } = require('./core.cjs');
const { extractFrontmatter } = require('./frontmatter.cjs');
const { MODEL_PROFILES } = require('./model-profiles.cjs');
@@ -43,7 +43,7 @@ function cmdCurrentTimestamp(format, raw) {
}
function cmdListTodos(cwd, area, raw) {
const pendingDir = path.join(cwd, '.planning', 'todos', 'pending');
const pendingDir = path.join(planningDir(cwd), 'todos', 'pending');
let count = 0;
const todos = [];
@@ -69,7 +69,7 @@ function cmdListTodos(cwd, area, raw) {
created: createdMatch ? createdMatch[1].trim() : 'unknown',
title: titleMatch ? titleMatch[1].trim() : 'Untitled',
area: todoArea,
path: toPosixPath(path.join('.planning', 'todos', 'pending', file)),
path: toPosixPath(path.relative(cwd, path.join(pendingDir, file))),
});
} catch { /* intentionally empty */ }
}
@@ -580,7 +580,7 @@ function cmdProgressRender(cwd, format, raw) {
function cmdTodoMatchPhase(cwd, phase, raw) {
if (!phase) { error('phase required for todo match-phase'); }
const pendingDir = path.join(cwd, '.planning', 'todos', 'pending');
const pendingDir = path.join(planningDir(cwd), 'todos', 'pending');
const todos = [];
// Load pending todos
@@ -701,8 +701,8 @@ function cmdTodoComplete(cwd, filename, raw) {
error('filename required for todo complete');
}
const pendingDir = path.join(cwd, '.planning', 'todos', 'pending');
const completedDir = path.join(cwd, '.planning', 'todos', 'completed');
const pendingDir = path.join(planningDir(cwd), 'todos', 'pending');
const completedDir = path.join(planningDir(cwd), 'todos', 'completed');
const sourcePath = path.join(pendingDir, filename);
if (!fs.existsSync(sourcePath)) {
@@ -764,7 +764,7 @@ function cmdScaffold(cwd, type, options, raw) {
fs.mkdirSync(phasesParent, { recursive: true });
const dirPath = path.join(phasesParent, dirName);
fs.mkdirSync(dirPath, { recursive: true });
output({ created: true, directory: `.planning/phases/${dirName}`, path: dirPath }, raw, dirPath);
output({ created: true, directory: toPosixPath(path.relative(cwd, dirPath)), path: dirPath }, raw, dirPath);
return;
}
default:

View File

@@ -4,7 +4,7 @@
const fs = require('fs');
const path = require('path');
const { output, error } = require('./core.cjs');
const { output, error, planningRoot } = require('./core.cjs');
const {
VALID_PROFILES,
getAgentToModelMapForProfile,
@@ -153,8 +153,8 @@ function buildNewProjectConfig(userChoices) {
* Idempotent: if config.json already exists, returns { created: false }.
*/
function cmdConfigNewProject(cwd, choicesJson, raw) {
const configPath = path.join(cwd, '.planning', 'config.json');
const planningDir = path.join(cwd, '.planning');
const planningBase = planningRoot(cwd);
const configPath = path.join(planningBase, 'config.json');
// Idempotent: don't overwrite existing config
if (fs.existsSync(configPath)) {
@@ -174,8 +174,8 @@ function cmdConfigNewProject(cwd, choicesJson, raw) {
// Ensure .planning directory exists
try {
if (!fs.existsSync(planningDir)) {
fs.mkdirSync(planningDir, { recursive: true });
if (!fs.existsSync(planningBase)) {
fs.mkdirSync(planningBase, { recursive: true });
}
} catch (err) {
error('Failed to create .planning directory: ' + err.message);
@@ -198,13 +198,13 @@ function cmdConfigNewProject(cwd, choicesJson, raw) {
* the happy path. But note that `error()` will still `exit(1)` out of the process.
*/
function ensureConfigFile(cwd) {
const configPath = path.join(cwd, '.planning', 'config.json');
const planningDir = path.join(cwd, '.planning');
const planningBase = planningRoot(cwd);
const configPath = path.join(planningBase, 'config.json');
// Ensure .planning directory exists
try {
if (!fs.existsSync(planningDir)) {
fs.mkdirSync(planningDir, { recursive: true });
if (!fs.existsSync(planningBase)) {
fs.mkdirSync(planningBase, { recursive: true });
}
} catch (err) {
error('Failed to create .planning directory: ' + err.message);
@@ -248,7 +248,7 @@ function cmdConfigEnsureSection(cwd, raw) {
* the happy path. But note that `error()` will still `exit(1)` out of the process.
*/
function setConfigValue(cwd, keyPath, parsedValue) {
const configPath = path.join(cwd, '.planning', 'config.json');
const configPath = path.join(planningRoot(cwd), 'config.json');
// Load existing config or start with empty object
let config = {};
@@ -311,7 +311,7 @@ function cmdConfigSet(cwd, keyPath, value, raw) {
}
function cmdConfigGet(cwd, keyPath, raw) {
const configPath = path.join(cwd, '.planning', 'config.json');
const configPath = path.join(planningRoot(cwd), 'config.json');
if (!keyPath) {
error('Usage: config-get <key.path>');

View File

@@ -523,25 +523,75 @@ function withPlanningLock(cwd, fn) {
return fn();
}
/** Get the .planning directory path */
function planningDir(cwd) {
/**
* Get the .planning directory path, workstream-aware.
* When a workstream is active (via explicit ws arg or GSD_WORKSTREAM env var),
* returns `.planning/workstreams/{ws}/`. Otherwise returns `.planning/`.
*
* @param {string} cwd - project root
* @param {string} [ws] - explicit workstream name; if omitted, checks GSD_WORKSTREAM env var
*/
function planningDir(cwd, ws) {
if (ws === undefined) ws = process.env.GSD_WORKSTREAM || null;
if (!ws) return path.join(cwd, '.planning');
return path.join(cwd, '.planning', 'workstreams', ws);
}
/** Always returns the root .planning/ path, ignoring workstreams. For shared resources. */
function planningRoot(cwd) {
return path.join(cwd, '.planning');
}
/** Get common .planning file paths */
function planningPaths(cwd) {
const base = path.join(cwd, '.planning');
/**
* Get common .planning file paths, workstream-aware.
* Scoped paths (state, roadmap, phases, requirements) resolve to the active workstream.
* Shared paths (project, config) always resolve to the root .planning/.
*/
function planningPaths(cwd, ws) {
const base = planningDir(cwd, ws);
const root = path.join(cwd, '.planning');
return {
planning: base,
state: path.join(base, 'STATE.md'),
roadmap: path.join(base, 'ROADMAP.md'),
project: path.join(base, 'PROJECT.md'),
config: path.join(base, 'config.json'),
project: path.join(root, 'PROJECT.md'),
config: path.join(root, 'config.json'),
phases: path.join(base, 'phases'),
requirements: path.join(base, 'REQUIREMENTS.md'),
};
}
// ─── Active Workstream Detection ─────────────────────────────────────────────
/**
* Get the active workstream name from .planning/active-workstream file.
* Returns null if no active workstream or file doesn't exist.
*/
function getActiveWorkstream(cwd) {
const filePath = path.join(cwd, '.planning', 'active-workstream');
try {
const name = fs.readFileSync(filePath, 'utf-8').trim();
if (!name) return null;
const wsDir = path.join(cwd, '.planning', 'workstreams', name);
if (!fs.existsSync(wsDir)) return null;
return name;
} catch {
return null;
}
}
/**
* Set the active workstream. Pass null to clear.
*/
function setActiveWorkstream(cwd, name) {
const filePath = path.join(cwd, '.planning', 'active-workstream');
if (!name) {
try { fs.unlinkSync(filePath); } catch {}
return;
}
fs.writeFileSync(filePath, name + '\n', 'utf-8');
}
// ─── Phase utilities ──────────────────────────────────────────────────────────
function escapeRegex(value) {
@@ -650,11 +700,12 @@ function searchPhaseInDir(baseDir, relBase, normalized) {
function findPhaseInternal(cwd, phase) {
if (!phase) return null;
const phasesDir = path.join(cwd, '.planning', 'phases');
const phasesDir = path.join(planningDir(cwd), 'phases');
const normalized = normalizePhaseName(phase);
// Search current phases first
const current = searchPhaseInDir(phasesDir, '.planning/phases', normalized);
const relPhasesDir = toPosixPath(path.relative(cwd, phasesDir));
const current = searchPhaseInDir(phasesDir, relPhasesDir, normalized);
if (current) return current;
// Search archived milestone phases (newest first)
@@ -753,7 +804,7 @@ function extractCurrentMilestone(content, cwd) {
// 1. Get current milestone version from STATE.md frontmatter
let version = null;
try {
const statePath = path.join(cwd, '.planning', 'STATE.md');
const statePath = path.join(planningDir(cwd), 'STATE.md');
if (fs.existsSync(statePath)) {
const stateRaw = fs.readFileSync(statePath, 'utf-8');
const milestoneMatch = stateRaw.match(/^milestone:\s*(.+)/m);
@@ -836,7 +887,7 @@ function replaceInCurrentMilestone(content, pattern, replacement) {
function getRoadmapPhaseInternal(cwd, phaseNum) {
if (!phaseNum) return null;
const roadmapPath = path.join(cwd, '.planning', 'ROADMAP.md');
const roadmapPath = path.join(planningDir(cwd), 'ROADMAP.md');
if (!fs.existsSync(roadmapPath)) return null;
try {
@@ -951,7 +1002,7 @@ function generateSlugInternal(text) {
function getMilestoneInfo(cwd) {
try {
const roadmap = fs.readFileSync(path.join(cwd, '.planning', 'ROADMAP.md'), 'utf-8');
const roadmap = fs.readFileSync(path.join(planningDir(cwd), 'ROADMAP.md'), 'utf-8');
// First: check for list-format roadmaps using 🚧 (in-progress) marker
// e.g. "- 🚧 **v2.1 Belgium** — Phases 24-28 (in progress)"
@@ -994,7 +1045,7 @@ function getMilestoneInfo(cwd) {
function getMilestonePhaseFilter(cwd) {
const milestonePhaseNums = new Set();
try {
const roadmap = extractCurrentMilestone(fs.readFileSync(path.join(cwd, '.planning', 'ROADMAP.md'), 'utf-8'), cwd);
const roadmap = extractCurrentMilestone(fs.readFileSync(path.join(planningDir(cwd), 'ROADMAP.md'), 'utf-8'), cwd);
// Match both numeric phases (Phase 1:) and custom IDs (Phase PROJ-42:)
const phasePattern = /#{2,4}\s*Phase\s+([\w][\w.-]*)\s*:/gi;
let m;
@@ -1058,5 +1109,8 @@ module.exports = {
reapStaleTempFiles,
MODEL_ALIAS_MAP,
planningDir,
planningRoot,
planningPaths,
getActiveWorkstream,
setActiveWorkstream,
};

View File

@@ -5,10 +5,10 @@
const fs = require('fs');
const path = require('path');
const { execSync } = require('child_process');
const { loadConfig, resolveModelInternal, findPhaseInternal, getRoadmapPhaseInternal, pathExistsInternal, generateSlugInternal, getMilestoneInfo, getMilestonePhaseFilter, stripShippedMilestones, extractCurrentMilestone, normalizePhaseName, planningPaths, toPosixPath, output, error } = require('./core.cjs');
const { loadConfig, resolveModelInternal, findPhaseInternal, getRoadmapPhaseInternal, pathExistsInternal, generateSlugInternal, getMilestoneInfo, getMilestonePhaseFilter, stripShippedMilestones, extractCurrentMilestone, normalizePhaseName, planningPaths, planningDir, planningRoot, toPosixPath, output, error } = require('./core.cjs');
function getLatestCompletedMilestone(cwd) {
const milestonesPath = path.join(cwd, '.planning', 'MILESTONES.md');
const milestonesPath = path.join(planningRoot(cwd), 'MILESTONES.md');
if (!fs.existsSync(milestonesPath)) return null;
try {
@@ -116,13 +116,13 @@ function cmdInitExecutePhase(cwd, phase, raw) {
milestone_slug: generateSlugInternal(milestone.name),
// File existence
state_exists: pathExistsInternal(cwd, '.planning/STATE.md'),
roadmap_exists: pathExistsInternal(cwd, '.planning/ROADMAP.md'),
config_exists: pathExistsInternal(cwd, '.planning/config.json'),
state_exists: fs.existsSync(path.join(planningDir(cwd), 'STATE.md')),
roadmap_exists: fs.existsSync(path.join(planningDir(cwd), 'ROADMAP.md')),
config_exists: fs.existsSync(path.join(planningDir(cwd), 'config.json')),
// File paths
state_path: '.planning/STATE.md',
roadmap_path: '.planning/ROADMAP.md',
config_path: '.planning/config.json',
state_path: toPosixPath(path.relative(cwd, path.join(planningDir(cwd), 'STATE.md'))),
roadmap_path: toPosixPath(path.relative(cwd, path.join(planningDir(cwd), 'ROADMAP.md'))),
config_path: toPosixPath(path.relative(cwd, path.join(planningDir(cwd), 'config.json'))),
};
output(withProjectRoot(cwd, result), raw);
@@ -191,13 +191,13 @@ function cmdInitPlanPhase(cwd, phase, raw) {
plan_count: phaseInfo?.plans?.length || 0,
// Environment
planning_exists: pathExistsInternal(cwd, '.planning'),
roadmap_exists: pathExistsInternal(cwd, '.planning/ROADMAP.md'),
planning_exists: fs.existsSync(planningDir(cwd)),
roadmap_exists: fs.existsSync(path.join(planningDir(cwd), 'ROADMAP.md')),
// File paths
state_path: '.planning/STATE.md',
roadmap_path: '.planning/ROADMAP.md',
requirements_path: '.planning/REQUIREMENTS.md',
state_path: toPosixPath(path.relative(cwd, path.join(planningDir(cwd), 'STATE.md'))),
roadmap_path: toPosixPath(path.relative(cwd, path.join(planningDir(cwd), 'ROADMAP.md'))),
requirements_path: toPosixPath(path.relative(cwd, path.join(planningDir(cwd), 'REQUIREMENTS.md'))),
};
if (phaseInfo?.directory) {
@@ -313,7 +313,7 @@ function cmdInitNewMilestone(cwd, raw) {
const config = loadConfig(cwd);
const milestone = getMilestoneInfo(cwd);
const latestCompleted = getLatestCompletedMilestone(cwd);
const phasesDir = path.join(cwd, '.planning', 'phases');
const phasesDir = path.join(planningDir(cwd), 'phases');
let phaseDirCount = 0;
try {
@@ -340,17 +340,17 @@ function cmdInitNewMilestone(cwd, raw) {
latest_completed_milestone: latestCompleted?.version || null,
latest_completed_milestone_name: latestCompleted?.name || null,
phase_dir_count: phaseDirCount,
phase_archive_path: latestCompleted ? `.planning/milestones/${latestCompleted.version}-phases` : null,
phase_archive_path: latestCompleted ? toPosixPath(path.relative(cwd, path.join(planningRoot(cwd), 'milestones', `${latestCompleted.version}-phases`))) : null,
// File existence
project_exists: pathExistsInternal(cwd, '.planning/PROJECT.md'),
roadmap_exists: pathExistsInternal(cwd, '.planning/ROADMAP.md'),
state_exists: pathExistsInternal(cwd, '.planning/STATE.md'),
roadmap_exists: fs.existsSync(path.join(planningDir(cwd), 'ROADMAP.md')),
state_exists: fs.existsSync(path.join(planningDir(cwd), 'STATE.md')),
// File paths
project_path: '.planning/PROJECT.md',
roadmap_path: '.planning/ROADMAP.md',
state_path: '.planning/STATE.md',
roadmap_path: toPosixPath(path.relative(cwd, path.join(planningDir(cwd), 'ROADMAP.md'))),
state_path: toPosixPath(path.relative(cwd, path.join(planningDir(cwd), 'STATE.md'))),
};
output(withProjectRoot(cwd, result), raw);
@@ -406,8 +406,8 @@ function cmdInitQuick(cwd, description, raw) {
task_dir: slug ? `.planning/quick/${quickId}-${slug}` : null,
// File existence
roadmap_exists: pathExistsInternal(cwd, '.planning/ROADMAP.md'),
planning_exists: pathExistsInternal(cwd, '.planning'),
roadmap_exists: fs.existsSync(path.join(planningDir(cwd), 'ROADMAP.md')),
planning_exists: fs.existsSync(planningRoot(cwd)),
};
@@ -420,19 +420,19 @@ function cmdInitResume(cwd, raw) {
// Check for interrupted agent
let interruptedAgentId = null;
try {
interruptedAgentId = fs.readFileSync(path.join(cwd, '.planning', 'current-agent-id.txt'), 'utf-8').trim();
interruptedAgentId = fs.readFileSync(path.join(planningRoot(cwd), 'current-agent-id.txt'), 'utf-8').trim();
} catch { /* intentionally empty */ }
const result = {
// File existence
state_exists: pathExistsInternal(cwd, '.planning/STATE.md'),
roadmap_exists: pathExistsInternal(cwd, '.planning/ROADMAP.md'),
state_exists: fs.existsSync(path.join(planningDir(cwd), 'STATE.md')),
roadmap_exists: fs.existsSync(path.join(planningDir(cwd), 'ROADMAP.md')),
project_exists: pathExistsInternal(cwd, '.planning/PROJECT.md'),
planning_exists: pathExistsInternal(cwd, '.planning'),
planning_exists: fs.existsSync(planningRoot(cwd)),
// File paths
state_path: '.planning/STATE.md',
roadmap_path: '.planning/ROADMAP.md',
state_path: toPosixPath(path.relative(cwd, path.join(planningDir(cwd), 'STATE.md'))),
roadmap_path: toPosixPath(path.relative(cwd, path.join(planningDir(cwd), 'ROADMAP.md'))),
project_path: '.planning/PROJECT.md',
// Agent state
@@ -568,13 +568,13 @@ function cmdInitPhaseOp(cwd, phase, raw) {
plan_count: phaseInfo?.plans?.length || 0,
// File existence
roadmap_exists: pathExistsInternal(cwd, '.planning/ROADMAP.md'),
planning_exists: pathExistsInternal(cwd, '.planning'),
roadmap_exists: fs.existsSync(path.join(planningDir(cwd), 'ROADMAP.md')),
planning_exists: fs.existsSync(planningDir(cwd)),
// File paths
state_path: '.planning/STATE.md',
roadmap_path: '.planning/ROADMAP.md',
requirements_path: '.planning/REQUIREMENTS.md',
state_path: toPosixPath(path.relative(cwd, path.join(planningDir(cwd), 'STATE.md'))),
roadmap_path: toPosixPath(path.relative(cwd, path.join(planningDir(cwd), 'ROADMAP.md'))),
requirements_path: toPosixPath(path.relative(cwd, path.join(planningDir(cwd), 'REQUIREMENTS.md'))),
};
if (phaseInfo?.directory) {
@@ -612,7 +612,7 @@ function cmdInitTodos(cwd, area, raw) {
const now = new Date();
// List todos (reuse existing logic)
const pendingDir = path.join(cwd, '.planning', 'todos', 'pending');
const pendingDir = path.join(planningDir(cwd), 'todos', 'pending');
let count = 0;
const todos = [];
@@ -634,7 +634,7 @@ function cmdInitTodos(cwd, area, raw) {
created: createdMatch ? createdMatch[1].trim() : 'unknown',
title: titleMatch ? titleMatch[1].trim() : 'Untitled',
area: todoArea,
path: '.planning/todos/pending/' + file,
path: toPosixPath(path.relative(cwd, path.join(planningDir(cwd), 'todos', 'pending', file))),
});
} catch { /* intentionally empty */ }
}
@@ -654,13 +654,13 @@ function cmdInitTodos(cwd, area, raw) {
area_filter: area || null,
// Paths
pending_dir: '.planning/todos/pending',
completed_dir: '.planning/todos/completed',
pending_dir: toPosixPath(path.relative(cwd, path.join(planningDir(cwd), 'todos', 'pending'))),
completed_dir: toPosixPath(path.relative(cwd, path.join(planningDir(cwd), 'todos', 'completed'))),
// File existence
planning_exists: pathExistsInternal(cwd, '.planning'),
todos_dir_exists: pathExistsInternal(cwd, '.planning/todos'),
pending_dir_exists: pathExistsInternal(cwd, '.planning/todos/pending'),
planning_exists: fs.existsSync(planningDir(cwd)),
todos_dir_exists: fs.existsSync(path.join(planningDir(cwd), 'todos')),
pending_dir_exists: fs.existsSync(path.join(planningDir(cwd), 'todos', 'pending')),
};
output(withProjectRoot(cwd, result), raw);
@@ -673,7 +673,7 @@ function cmdInitMilestoneOp(cwd, raw) {
// Count phases
let phaseCount = 0;
let completedPhases = 0;
const phasesDir = path.join(cwd, '.planning', 'phases');
const phasesDir = path.join(planningDir(cwd), 'phases');
try {
const entries = fs.readdirSync(phasesDir, { withFileTypes: true });
const dirs = entries.filter(e => e.isDirectory()).map(e => e.name);
@@ -690,7 +690,7 @@ function cmdInitMilestoneOp(cwd, raw) {
} catch { /* intentionally empty */ }
// Check archive
const archiveDir = path.join(cwd, '.planning', 'archive');
const archiveDir = path.join(planningRoot(cwd), 'archive');
let archivedMilestones = [];
try {
archivedMilestones = fs.readdirSync(archiveDir, { withFileTypes: true })
@@ -718,10 +718,10 @@ function cmdInitMilestoneOp(cwd, raw) {
// File existence
project_exists: pathExistsInternal(cwd, '.planning/PROJECT.md'),
roadmap_exists: pathExistsInternal(cwd, '.planning/ROADMAP.md'),
state_exists: pathExistsInternal(cwd, '.planning/STATE.md'),
archive_exists: pathExistsInternal(cwd, '.planning/archive'),
phases_dir_exists: pathExistsInternal(cwd, '.planning/phases'),
roadmap_exists: fs.existsSync(path.join(planningDir(cwd), 'ROADMAP.md')),
state_exists: fs.existsSync(path.join(planningDir(cwd), 'STATE.md')),
archive_exists: fs.existsSync(path.join(planningRoot(cwd), 'archive')),
phases_dir_exists: fs.existsSync(path.join(planningDir(cwd), 'phases')),
};
output(withProjectRoot(cwd, result), raw);
@@ -731,7 +731,7 @@ function cmdInitMapCodebase(cwd, raw) {
const config = loadConfig(cwd);
// Check for existing codebase maps
const codebaseDir = path.join(cwd, '.planning', 'codebase');
const codebaseDir = path.join(planningRoot(cwd), 'codebase');
let existingMaps = [];
try {
existingMaps = fs.readdirSync(codebaseDir).filter(f => f.endsWith('.md'));
@@ -1013,7 +1013,7 @@ function cmdInitProgress(cwd, raw) {
const milestone = getMilestoneInfo(cwd);
// Analyze phases — filter to current milestone and include ROADMAP-only phases
const phasesDir = path.join(cwd, '.planning', 'phases');
const phasesDir = path.join(planningDir(cwd), 'phases');
const phases = [];
let currentPhase = null;
let nextPhase = null;
@@ -1023,7 +1023,7 @@ function cmdInitProgress(cwd, raw) {
const roadmapPhaseNames = new Map();
try {
const roadmapContent = extractCurrentMilestone(
fs.readFileSync(path.join(cwd, '.planning', 'ROADMAP.md'), 'utf-8'), cwd
fs.readFileSync(path.join(planningDir(cwd), 'ROADMAP.md'), 'utf-8'), cwd
);
const headingPattern = /#{2,4}\s*Phase\s+(\d+[A-Z]?(?:\.\d+)*)\s*:\s*([^\n]+)/gi;
let hm;
@@ -1067,7 +1067,7 @@ function cmdInitProgress(cwd, raw) {
const phaseInfo = {
number: phaseNumber,
name: phaseName,
directory: '.planning/phases/' + dir,
directory: toPosixPath(path.relative(cwd, path.join(planningDir(cwd), 'phases', dir))),
status,
plan_count: plans.length,
summary_count: summaries.length,
@@ -1112,7 +1112,7 @@ function cmdInitProgress(cwd, raw) {
// Check for paused work
let pausedAt = null;
try {
const state = fs.readFileSync(path.join(cwd, '.planning', 'STATE.md'), 'utf-8');
const state = fs.readFileSync(path.join(planningDir(cwd), 'STATE.md'), 'utf-8');
const pauseMatch = state.match(/\*\*Paused At:\*\*\s*(.+)/);
if (pauseMatch) pausedAt = pauseMatch[1].trim();
} catch { /* intentionally empty */ }
@@ -1143,13 +1143,13 @@ function cmdInitProgress(cwd, raw) {
// File existence
project_exists: pathExistsInternal(cwd, '.planning/PROJECT.md'),
roadmap_exists: pathExistsInternal(cwd, '.planning/ROADMAP.md'),
state_exists: pathExistsInternal(cwd, '.planning/STATE.md'),
roadmap_exists: fs.existsSync(path.join(planningDir(cwd), 'ROADMAP.md')),
state_exists: fs.existsSync(path.join(planningDir(cwd), 'STATE.md')),
// File paths
state_path: '.planning/STATE.md',
roadmap_path: '.planning/ROADMAP.md',
state_path: toPosixPath(path.relative(cwd, path.join(planningDir(cwd), 'STATE.md'))),
roadmap_path: toPosixPath(path.relative(cwd, path.join(planningDir(cwd), 'ROADMAP.md'))),
project_path: '.planning/PROJECT.md',
config_path: '.planning/config.json',
config_path: toPosixPath(path.relative(cwd, path.join(planningDir(cwd), 'config.json'))),
};
output(withProjectRoot(cwd, result), raw);

View File

@@ -4,12 +4,12 @@
const fs = require('fs');
const path = require('path');
const { escapeRegex, loadConfig, normalizePhaseName, comparePhaseNum, findPhaseInternal, getArchivedPhaseDirs, generateSlugInternal, getMilestonePhaseFilter, stripShippedMilestones, extractCurrentMilestone, replaceInCurrentMilestone, toPosixPath, output, error } = require('./core.cjs');
const { escapeRegex, loadConfig, normalizePhaseName, comparePhaseNum, findPhaseInternal, getArchivedPhaseDirs, generateSlugInternal, getMilestonePhaseFilter, stripShippedMilestones, extractCurrentMilestone, replaceInCurrentMilestone, toPosixPath, planningDir, output, error } = require('./core.cjs');
const { extractFrontmatter } = require('./frontmatter.cjs');
const { writeStateMd, stateExtractField, stateReplaceField, stateReplaceFieldWithFallback } = require('./state.cjs');
function cmdPhasesList(cwd, options, raw) {
const phasesDir = path.join(cwd, '.planning', 'phases');
const phasesDir = path.join(planningDir(cwd), 'phases');
const { type, phase, includeArchived } = options;
// If no phases directory, return empty
@@ -85,7 +85,7 @@ function cmdPhasesList(cwd, options, raw) {
}
function cmdPhaseNextDecimal(cwd, basePhase, raw) {
const phasesDir = path.join(cwd, '.planning', 'phases');
const phasesDir = path.join(planningDir(cwd), 'phases');
const normalized = normalizePhaseName(basePhase);
// Check if phases directory exists
@@ -154,7 +154,7 @@ function cmdFindPhase(cwd, phase, raw) {
error('phase identifier required');
}
const phasesDir = path.join(cwd, '.planning', 'phases');
const phasesDir = path.join(planningDir(cwd), 'phases');
const normalized = normalizePhaseName(phase);
const notFound = { found: false, directory: null, phase_number: null, phase_name: null, plans: [], summaries: [] };
@@ -180,7 +180,7 @@ function cmdFindPhase(cwd, phase, raw) {
const result = {
found: true,
directory: toPosixPath(path.join('.planning', 'phases', match)),
directory: toPosixPath(path.join(path.relative(cwd, planningDir(cwd)), 'phases', match)),
phase_number: phaseNumber,
phase_name: phaseName,
plans,
@@ -203,7 +203,7 @@ function cmdPhasePlanIndex(cwd, phase, raw) {
error('phase required for phase-plan-index');
}
const phasesDir = path.join(cwd, '.planning', 'phases');
const phasesDir = path.join(planningDir(cwd), 'phases');
const normalized = normalizePhaseName(phase);
// Find phase directory
@@ -314,7 +314,7 @@ function cmdPhaseAdd(cwd, description, raw, customId) {
}
const config = loadConfig(cwd);
const roadmapPath = path.join(cwd, '.planning', 'ROADMAP.md');
const roadmapPath = path.join(planningDir(cwd), 'ROADMAP.md');
if (!fs.existsSync(roadmapPath)) {
error('ROADMAP.md not found');
}
@@ -346,7 +346,7 @@ function cmdPhaseAdd(cwd, description, raw, customId) {
dirName = `${paddedNum}-${slug}`;
}
const dirPath = path.join(cwd, '.planning', 'phases', dirName);
const dirPath = path.join(planningDir(cwd), 'phases', dirName);
// Create directory with .gitkeep so git tracks empty folders
fs.mkdirSync(dirPath, { recursive: true });
@@ -372,7 +372,7 @@ function cmdPhaseAdd(cwd, description, raw, customId) {
padded: typeof newPhaseId === 'number' ? String(newPhaseId).padStart(2, '0') : String(newPhaseId),
name: description,
slug,
directory: `.planning/phases/${dirName}`,
directory: toPosixPath(path.join(path.relative(cwd, planningDir(cwd)), 'phases', dirName)),
naming_mode: config.phase_naming,
};
@@ -384,7 +384,7 @@ function cmdPhaseInsert(cwd, afterPhase, description, raw) {
error('after-phase and description required for phase insert');
}
const roadmapPath = path.join(cwd, '.planning', 'ROADMAP.md');
const roadmapPath = path.join(planningDir(cwd), 'ROADMAP.md');
if (!fs.existsSync(roadmapPath)) {
error('ROADMAP.md not found');
}
@@ -403,7 +403,7 @@ function cmdPhaseInsert(cwd, afterPhase, description, raw) {
}
// Calculate next decimal using existing logic
const phasesDir = path.join(cwd, '.planning', 'phases');
const phasesDir = path.join(planningDir(cwd), 'phases');
const normalizedBase = normalizePhaseName(afterPhase);
let existingDecimals = [];
@@ -420,7 +420,7 @@ function cmdPhaseInsert(cwd, afterPhase, description, raw) {
const nextDecimal = existingDecimals.length === 0 ? 1 : Math.max(...existingDecimals) + 1;
const decimalPhase = `${normalizedBase}.${nextDecimal}`;
const dirName = `${decimalPhase}-${slug}`;
const dirPath = path.join(cwd, '.planning', 'phases', dirName);
const dirPath = path.join(planningDir(cwd), 'phases', dirName);
// Create directory with .gitkeep so git tracks empty folders
fs.mkdirSync(dirPath, { recursive: true });
@@ -455,7 +455,7 @@ function cmdPhaseInsert(cwd, afterPhase, description, raw) {
after_phase: afterPhase,
name: description,
slug,
directory: `.planning/phases/${dirName}`,
directory: toPosixPath(path.join(path.relative(cwd, planningDir(cwd)), 'phases', dirName)),
};
output(result, raw, decimalPhase);
@@ -466,8 +466,8 @@ function cmdPhaseRemove(cwd, targetPhase, options, raw) {
error('phase number required for phase remove');
}
const roadmapPath = path.join(cwd, '.planning', 'ROADMAP.md');
const phasesDir = path.join(cwd, '.planning', 'phases');
const roadmapPath = path.join(planningDir(cwd), 'ROADMAP.md');
const phasesDir = path.join(planningDir(cwd), 'phases');
const force = options.force || false;
if (!fs.existsSync(roadmapPath)) {
@@ -682,7 +682,7 @@ function cmdPhaseRemove(cwd, targetPhase, options, raw) {
fs.writeFileSync(roadmapPath, roadmapContent, 'utf-8');
// Update STATE.md phase count
const statePath = path.join(cwd, '.planning', 'STATE.md');
const statePath = path.join(planningDir(cwd), 'STATE.md');
if (fs.existsSync(statePath)) {
let stateContent = fs.readFileSync(statePath, 'utf-8');
// Update "Total Phases" field — supports both bold and plain formats
@@ -718,9 +718,9 @@ function cmdPhaseComplete(cwd, phaseNum, raw) {
error('phase number required for phase complete');
}
const roadmapPath = path.join(cwd, '.planning', 'ROADMAP.md');
const statePath = path.join(cwd, '.planning', 'STATE.md');
const phasesDir = path.join(cwd, '.planning', 'phases');
const roadmapPath = path.join(planningDir(cwd), 'ROADMAP.md');
const statePath = path.join(planningDir(cwd), 'STATE.md');
const phasesDir = path.join(planningDir(cwd), 'phases');
const normalized = normalizePhaseName(phaseNum);
const today = new Date().toISOString().split('T')[0];
@@ -799,7 +799,7 @@ function cmdPhaseComplete(cwd, phaseNum, raw) {
fs.writeFileSync(roadmapPath, roadmapContent, 'utf-8');
// Update REQUIREMENTS.md traceability for this phase's requirements
const reqPath = path.join(cwd, '.planning', 'REQUIREMENTS.md');
const reqPath = path.join(planningDir(cwd), 'REQUIREMENTS.md');
if (fs.existsSync(reqPath)) {
// Extract the current phase section from roadmap (scoped to avoid cross-phase matching)
const phaseEsc = escapeRegex(phaseNum);

View File

@@ -4,7 +4,7 @@
const fs = require('fs');
const path = require('path');
const { escapeRegex, loadConfig, getMilestoneInfo, getMilestonePhaseFilter, normalizeMd, planningPaths, output, error } = require('./core.cjs');
const { escapeRegex, loadConfig, getMilestoneInfo, getMilestonePhaseFilter, normalizeMd, planningDir, planningPaths, output, error } = require('./core.cjs');
const { extractFrontmatter, reconstructFrontmatter } = require('./frontmatter.cjs');
/** Shorthand — every state command needs this path */
@@ -905,7 +905,7 @@ function cmdStateBeginPhase(cwd, phaseNumber, phaseName, planCount, raw) {
* Fixes #1034.
*/
function cmdSignalWaiting(cwd, type, question, options, phase, raw) {
const gsdDir = fs.existsSync(path.join(cwd, '.gsd')) ? path.join(cwd, '.gsd') : path.join(cwd, '.planning');
const gsdDir = fs.existsSync(path.join(cwd, '.gsd')) ? path.join(cwd, '.gsd') : planningDir(cwd);
const waitingPath = path.join(gsdDir, 'WAITING.json');
const signal = {
@@ -932,7 +932,7 @@ function cmdSignalWaiting(cwd, type, question, options, phase, raw) {
function cmdSignalResume(cwd, raw) {
const paths = [
path.join(cwd, '.gsd', 'WAITING.json'),
path.join(cwd, '.planning', 'WAITING.json'),
path.join(planningDir(cwd), 'WAITING.json'),
];
let removed = false;

View File

@@ -7,13 +7,13 @@
const fs = require('fs');
const path = require('path');
const { output, error, getMilestonePhaseFilter } = require('./core.cjs');
const { output, error, getMilestonePhaseFilter, planningDir, toPosixPath } = require('./core.cjs');
const { extractFrontmatter } = require('./frontmatter.cjs');
function cmdAuditUat(cwd, raw) {
const phasesDir = path.join(cwd, '.planning', 'phases');
const phasesDir = path.join(planningDir(cwd), 'phases');
if (!fs.existsSync(phasesDir)) {
error('No .planning/phases directory found');
error('No phases directory found in planning directory');
}
const isDirInMilestone = getMilestonePhaseFilter(cwd);
@@ -41,7 +41,7 @@ function cmdAuditUat(cwd, raw) {
phase: phaseNum,
phase_dir: dir,
file,
file_path: `.planning/phases/${dir}/${file}`,
file_path: toPosixPath(path.relative(cwd, path.join(phaseDir, file))),
type: 'uat',
status: (extractFrontmatter(content).status || 'unknown'),
items,
@@ -60,7 +60,7 @@ function cmdAuditUat(cwd, raw) {
phase: phaseNum,
phase_dir: dir,
file,
file_path: `.planning/phases/${dir}/${file}`,
file_path: toPosixPath(path.relative(cwd, path.join(phaseDir, file))),
type: 'verification',
status,
items,

View File

@@ -5,7 +5,7 @@
const fs = require('fs');
const path = require('path');
const os = require('os');
const { safeReadFile, loadConfig, normalizePhaseName, execGit, findPhaseInternal, getMilestoneInfo, stripShippedMilestones, extractCurrentMilestone, output, error } = require('./core.cjs');
const { safeReadFile, loadConfig, normalizePhaseName, execGit, findPhaseInternal, getMilestoneInfo, stripShippedMilestones, extractCurrentMilestone, planningDir, planningRoot, output, error } = require('./core.cjs');
const { extractFrontmatter, parseMustHavesBlock } = require('./frontmatter.cjs');
const { writeStateMd } = require('./state.cjs');
@@ -396,8 +396,8 @@ function cmdVerifyKeyLinks(cwd, planFilePath, raw) {
}
function cmdValidateConsistency(cwd, raw) {
const roadmapPath = path.join(cwd, '.planning', 'ROADMAP.md');
const phasesDir = path.join(cwd, '.planning', 'phases');
const roadmapPath = path.join(planningDir(cwd), 'ROADMAP.md');
const phasesDir = path.join(planningDir(cwd), 'phases');
const errors = [];
const warnings = [];
@@ -533,12 +533,13 @@ function cmdValidateHealth(cwd, options, raw) {
return;
}
const planningDir = path.join(cwd, '.planning');
const projectPath = path.join(planningDir, 'PROJECT.md');
const roadmapPath = path.join(planningDir, 'ROADMAP.md');
const statePath = path.join(planningDir, 'STATE.md');
const configPath = path.join(planningDir, 'config.json');
const phasesDir = path.join(planningDir, 'phases');
const planBase = planningDir(cwd);
const planRoot = planningRoot(cwd);
const projectPath = path.join(planRoot, 'PROJECT.md');
const roadmapPath = path.join(planBase, 'ROADMAP.md');
const statePath = path.join(planBase, 'STATE.md');
const configPath = path.join(planRoot, 'config.json');
const phasesDir = path.join(planBase, 'phases');
const errors = [];
const warnings = [];
@@ -554,7 +555,7 @@ function cmdValidateHealth(cwd, options, raw) {
};
// ─── Check 1: .planning/ exists ───────────────────────────────────────────
if (!fs.existsSync(planningDir)) {
if (!fs.existsSync(planBase)) {
addIssue('error', 'E001', '.planning/ directory not found', 'Run /gsd:new-project to initialize');
output({
status: 'broken',

View File

@@ -0,0 +1,497 @@
/**
* Workstream — CRUD operations for workstream namespacing
*
* Workstreams enable parallel milestones by scoping ROADMAP.md, STATE.md,
* REQUIREMENTS.md, and phases/ into .planning/workstreams/{name}/ directories.
*
* When no workstreams/ directory exists, GSD operates in "flat mode" with
* everything at .planning/ — backward compatible with pre-workstream installs.
*/
const fs = require('fs');
const path = require('path');
const { output, error, planningPaths, planningRoot, toPosixPath, getMilestoneInfo, generateSlugInternal, setActiveWorkstream, getActiveWorkstream } = require('./core.cjs');
// ─── Migration ──────────────────────────────────────────────────────────────
/**
* Migrate flat .planning/ layout to workstream mode.
* Moves per-workstream files (ROADMAP.md, STATE.md, REQUIREMENTS.md, phases/)
* into .planning/workstreams/{name}/. Shared files (PROJECT.md, config.json,
* milestones/, research/, codebase/, todos/) stay in place.
*/
function migrateToWorkstreams(cwd, workstreamName) {
if (!workstreamName || /[/\\]/.test(workstreamName) || workstreamName === '.' || workstreamName === '..') {
throw new Error('Invalid workstream name for migration');
}
const baseDir = planningRoot(cwd);
const wsDir = path.join(baseDir, 'workstreams', workstreamName);
if (fs.existsSync(path.join(baseDir, 'workstreams'))) {
throw new Error('Already in workstream mode — .planning/workstreams/ exists');
}
const toMove = [
{ name: 'ROADMAP.md', type: 'file' },
{ name: 'STATE.md', type: 'file' },
{ name: 'REQUIREMENTS.md', type: 'file' },
{ name: 'phases', type: 'dir' },
];
fs.mkdirSync(wsDir, { recursive: true });
const filesMoved = [];
try {
for (const item of toMove) {
const src = path.join(baseDir, item.name);
if (fs.existsSync(src)) {
const dest = path.join(wsDir, item.name);
fs.renameSync(src, dest);
filesMoved.push(item.name);
}
}
} catch (err) {
for (const name of filesMoved) {
try { fs.renameSync(path.join(wsDir, name), path.join(baseDir, name)); } catch {}
}
try { fs.rmSync(wsDir, { recursive: true }); } catch {}
try { fs.rmdirSync(path.join(baseDir, 'workstreams')); } catch {}
throw err;
}
return { migrated: true, workstream: workstreamName, files_moved: filesMoved };
}
// ─── CRUD Commands ──────────────────────────────────────────────────────────
function cmdWorkstreamCreate(cwd, name, options, raw) {
if (!name) {
error('workstream name required. Usage: workstream create <name>');
}
const slug = name.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-+|-+$/g, '');
if (!slug) {
error('Invalid workstream name — must contain at least one alphanumeric character');
}
const baseDir = planningRoot(cwd);
if (!fs.existsSync(baseDir)) {
error('.planning/ directory not found — run /gsd:new-project first');
}
const wsRoot = path.join(baseDir, 'workstreams');
const wsDir = path.join(wsRoot, slug);
if (fs.existsSync(wsDir) && fs.existsSync(path.join(wsDir, 'STATE.md'))) {
output({ created: false, error: 'already_exists', workstream: slug, path: toPosixPath(path.relative(cwd, wsDir)) }, raw);
return;
}
const isFlatMode = !fs.existsSync(wsRoot);
let migration = null;
if (isFlatMode && options.migrate !== false) {
const hasExistingWork = fs.existsSync(path.join(baseDir, 'ROADMAP.md')) ||
fs.existsSync(path.join(baseDir, 'STATE.md')) ||
fs.existsSync(path.join(baseDir, 'phases'));
if (hasExistingWork) {
const migrateName = options.migrateName || null;
let existingWsName;
if (migrateName) {
existingWsName = migrateName;
} else {
try {
const milestone = getMilestoneInfo(cwd);
existingWsName = generateSlugInternal(milestone.name) || 'default';
} catch {
existingWsName = 'default';
}
}
try {
migration = migrateToWorkstreams(cwd, existingWsName);
} catch (e) {
output({ created: false, error: 'migration_failed', message: e.message }, raw);
return;
}
} else {
fs.mkdirSync(wsRoot, { recursive: true });
}
}
fs.mkdirSync(wsDir, { recursive: true });
fs.mkdirSync(path.join(wsDir, 'phases'), { recursive: true });
const today = new Date().toISOString().split('T')[0];
const stateContent = [
'---',
`workstream: ${slug}`,
`created: ${today}`,
'---',
'',
'# Project State',
'',
'## Current Position',
'**Status:** Not started',
'**Current Phase:** None',
`**Last Activity:** ${today}`,
'**Last Activity Description:** Workstream created',
'',
'## Progress',
'**Phases Complete:** 0',
'**Current Plan:** N/A',
'',
'## Session Continuity',
'**Stopped At:** N/A',
'**Resume File:** None',
'',
].join('\n');
const statePath = path.join(wsDir, 'STATE.md');
if (!fs.existsSync(statePath)) {
fs.writeFileSync(statePath, stateContent, 'utf-8');
}
setActiveWorkstream(cwd, slug);
const relPath = toPosixPath(path.relative(cwd, wsDir));
output({
created: true,
workstream: slug,
path: relPath,
state_path: relPath + '/STATE.md',
phases_path: relPath + '/phases',
migration: migration || null,
active: true,
}, raw);
}
function cmdWorkstreamList(cwd, raw) {
const wsRoot = path.join(planningRoot(cwd), 'workstreams');
if (!fs.existsSync(wsRoot)) {
output({ mode: 'flat', workstreams: [], message: 'No workstreams — operating in flat mode' }, raw);
return;
}
const entries = fs.readdirSync(wsRoot, { withFileTypes: true });
const workstreams = [];
for (const entry of entries) {
if (!entry.isDirectory()) continue;
const wsDir = path.join(wsRoot, entry.name);
const phasesDir = path.join(wsDir, 'phases');
let phaseCount = 0, completedCount = 0;
try {
const dirs = fs.readdirSync(phasesDir, { withFileTypes: true }).filter(e => e.isDirectory());
phaseCount = dirs.length;
for (const d of dirs) {
const files = fs.readdirSync(path.join(phasesDir, d.name));
const plans = files.filter(f => f.endsWith('-PLAN.md') || f === 'PLAN.md');
const summaries = files.filter(f => f.endsWith('-SUMMARY.md') || f === 'SUMMARY.md');
if (plans.length > 0 && summaries.length >= plans.length) completedCount++;
}
} catch {}
let status = 'unknown', currentPhase = null;
try {
const stateContent = fs.readFileSync(path.join(wsDir, 'STATE.md'), 'utf-8');
const statusMatch = stateContent.match(/\*\*Status:\*\*\s*(.+)/);
if (statusMatch) status = statusMatch[1].trim();
const phaseMatch = stateContent.match(/\*\*Current Phase:\*\*\s*(.+)/);
if (phaseMatch) currentPhase = phaseMatch[1].trim();
} catch {}
workstreams.push({
name: entry.name,
path: toPosixPath(path.relative(cwd, wsDir)),
has_roadmap: fs.existsSync(path.join(wsDir, 'ROADMAP.md')),
has_state: fs.existsSync(path.join(wsDir, 'STATE.md')),
status,
current_phase: currentPhase,
phase_count: phaseCount,
completed_phases: completedCount,
});
}
output({ mode: 'workstream', workstreams, count: workstreams.length }, raw);
}
function cmdWorkstreamStatus(cwd, name, raw) {
if (!name) error('workstream name required. Usage: workstream status <name>');
if (/[/\\]/.test(name) || name === '.' || name === '..') error('Invalid workstream name');
const wsDir = path.join(planningRoot(cwd), 'workstreams', name);
if (!fs.existsSync(wsDir)) {
output({ found: false, workstream: name }, raw);
return;
}
const p = planningPaths(cwd, name);
const relPath = toPosixPath(path.relative(cwd, wsDir));
const files = {
roadmap: fs.existsSync(p.roadmap),
state: fs.existsSync(p.state),
requirements: fs.existsSync(p.requirements),
};
const phases = [];
try {
const dirs = fs.readdirSync(p.phases, { withFileTypes: true })
.filter(e => e.isDirectory()).map(e => e.name).sort();
for (const dir of dirs) {
const phasePath = path.join(p.phases, dir);
const phaseFiles = fs.readdirSync(phasePath);
const plans = phaseFiles.filter(f => f.endsWith('-PLAN.md') || f === 'PLAN.md');
const summaries = phaseFiles.filter(f => f.endsWith('-SUMMARY.md') || f === 'SUMMARY.md');
phases.push({
directory: dir,
status: summaries.length >= plans.length && plans.length > 0 ? 'complete' :
plans.length > 0 ? 'in_progress' : 'pending',
plan_count: plans.length,
summary_count: summaries.length,
});
}
} catch {}
let stateInfo = {};
try {
const stateContent = fs.readFileSync(p.state, 'utf-8');
const statusMatch = stateContent.match(/\*\*Status:\*\*\s*(.+)/);
const phaseMatch = stateContent.match(/\*\*Current Phase:\*\*\s*(.+)/);
const activityMatch = stateContent.match(/\*\*Last Activity:\*\*\s*(.+)/);
stateInfo = {
status: statusMatch ? statusMatch[1].trim() : 'unknown',
current_phase: phaseMatch ? phaseMatch[1].trim() : null,
last_activity: activityMatch ? activityMatch[1].trim() : null,
};
} catch {}
output({
found: true,
workstream: name,
path: relPath,
files,
phases,
phase_count: phases.length,
completed_phases: phases.filter(ph => ph.status === 'complete').length,
...stateInfo,
}, raw);
}
function cmdWorkstreamComplete(cwd, name, options, raw) {
if (!name) error('workstream name required. Usage: workstream complete <name>');
if (/[/\\]/.test(name) || name === '.' || name === '..') error('Invalid workstream name');
const root = planningRoot(cwd);
const wsRoot = path.join(root, 'workstreams');
const wsDir = path.join(wsRoot, name);
if (!fs.existsSync(wsDir)) {
output({ completed: false, error: 'not_found', workstream: name }, raw);
return;
}
const active = getActiveWorkstream(cwd);
if (active === name) setActiveWorkstream(cwd, null);
const archiveDir = path.join(root, 'milestones');
const today = new Date().toISOString().split('T')[0];
let archivePath = path.join(archiveDir, `ws-${name}-${today}`);
let suffix = 1;
while (fs.existsSync(archivePath)) {
archivePath = path.join(archiveDir, `ws-${name}-${today}-${suffix++}`);
}
fs.mkdirSync(archivePath, { recursive: true });
const filesMoved = [];
try {
const entries = fs.readdirSync(wsDir, { withFileTypes: true });
for (const entry of entries) {
fs.renameSync(path.join(wsDir, entry.name), path.join(archivePath, entry.name));
filesMoved.push(entry.name);
}
} catch (err) {
for (const fname of filesMoved) {
try { fs.renameSync(path.join(archivePath, fname), path.join(wsDir, fname)); } catch {}
}
try { fs.rmSync(archivePath, { recursive: true }); } catch {}
if (active === name) setActiveWorkstream(cwd, name);
output({ completed: false, error: 'archive_failed', message: err.message, workstream: name }, raw);
return;
}
try { fs.rmdirSync(wsDir); } catch {}
let remainingWs = 0;
try {
remainingWs = fs.readdirSync(wsRoot, { withFileTypes: true }).filter(e => e.isDirectory()).length;
if (remainingWs === 0) fs.rmdirSync(wsRoot);
} catch {}
output({
completed: true,
workstream: name,
archived_to: toPosixPath(path.relative(cwd, archivePath)),
remaining_workstreams: remainingWs,
reverted_to_flat: remainingWs === 0,
}, raw);
}
// ─── Active Workstream Commands ──────────────────────────────────────────────
function cmdWorkstreamSet(cwd, name, raw) {
if (!name) {
setActiveWorkstream(cwd, null);
output({ active: null, cleared: true }, raw);
return;
}
const wsDir = path.join(planningRoot(cwd), 'workstreams', name);
if (!fs.existsSync(wsDir)) {
output({ active: null, error: 'not_found', workstream: name }, raw);
return;
}
setActiveWorkstream(cwd, name);
output({ active: name, set: true }, raw, name);
}
function cmdWorkstreamGet(cwd, raw) {
const active = getActiveWorkstream(cwd);
const wsRoot = path.join(planningRoot(cwd), 'workstreams');
output({ active, mode: fs.existsSync(wsRoot) ? 'workstream' : 'flat' }, raw, active || 'none');
}
function cmdWorkstreamProgress(cwd, raw) {
const root = planningRoot(cwd);
const wsRoot = path.join(root, 'workstreams');
if (!fs.existsSync(wsRoot)) {
output({ mode: 'flat', workstreams: [], message: 'No workstreams — operating in flat mode' }, raw);
return;
}
const active = getActiveWorkstream(cwd);
const entries = fs.readdirSync(wsRoot, { withFileTypes: true });
const workstreams = [];
for (const entry of entries) {
if (!entry.isDirectory()) continue;
const wsDir = path.join(wsRoot, entry.name);
const phasesDir = path.join(wsDir, 'phases');
let phaseCount = 0, completedCount = 0, totalPlans = 0, completedPlans = 0;
try {
const dirs = fs.readdirSync(phasesDir, { withFileTypes: true }).filter(e => e.isDirectory());
phaseCount = dirs.length;
for (const d of dirs) {
const files = fs.readdirSync(path.join(phasesDir, d.name));
const plans = files.filter(f => f.endsWith('-PLAN.md') || f === 'PLAN.md');
const summaries = files.filter(f => f.endsWith('-SUMMARY.md') || f === 'SUMMARY.md');
totalPlans += plans.length;
completedPlans += Math.min(summaries.length, plans.length);
if (plans.length > 0 && summaries.length >= plans.length) completedCount++;
}
} catch {}
let roadmapPhaseCount = phaseCount;
try {
const roadmapContent = fs.readFileSync(path.join(wsDir, 'ROADMAP.md'), 'utf-8');
const phaseMatches = roadmapContent.match(/^###?\s+Phase\s+\d/gm);
if (phaseMatches) roadmapPhaseCount = phaseMatches.length;
} catch {}
let status = 'unknown', currentPhase = null;
try {
const stateContent = fs.readFileSync(path.join(wsDir, 'STATE.md'), 'utf-8');
const statusMatch = stateContent.match(/\*\*Status:\*\*\s*(.+)/);
if (statusMatch) status = statusMatch[1].trim();
const phaseMatch = stateContent.match(/\*\*Current Phase:\*\*\s*(.+)/);
if (phaseMatch) currentPhase = phaseMatch[1].trim();
} catch {}
workstreams.push({
name: entry.name,
active: entry.name === active,
status,
current_phase: currentPhase,
phases: `${completedCount}/${roadmapPhaseCount}`,
plans: `${completedPlans}/${totalPlans}`,
progress_percent: roadmapPhaseCount > 0 ? Math.round((completedCount / roadmapPhaseCount) * 100) : 0,
});
}
output({ mode: 'workstream', active, workstreams, count: workstreams.length }, raw);
}
// ─── Collision Detection ────────────────────────────────────────────────────
/**
* Return other workstreams that are NOT complete.
* Used to detect whether the milestone has active parallel work
* when a workstream finishes its last phase.
*/
function getOtherActiveWorkstreams(cwd, excludeWs) {
const wsRoot = path.join(planningRoot(cwd), 'workstreams');
if (!fs.existsSync(wsRoot)) return [];
const entries = fs.readdirSync(wsRoot, { withFileTypes: true });
const others = [];
for (const entry of entries) {
if (!entry.isDirectory() || entry.name === excludeWs) continue;
const wsDir = path.join(wsRoot, entry.name);
const statePath = path.join(wsDir, 'STATE.md');
let status = 'unknown', currentPhase = null;
try {
const content = fs.readFileSync(statePath, 'utf-8');
const statusMatch = content.match(/\*\*Status:\*\*\s*(.+)/);
if (statusMatch) status = statusMatch[1].trim();
const phaseMatch = content.match(/\*\*Current Phase:\*\*\s*(.+)/);
if (phaseMatch) currentPhase = phaseMatch[1].trim();
} catch {}
if (status.toLowerCase().includes('milestone complete') ||
status.toLowerCase().includes('archived')) {
continue;
}
let phaseCount = 0, completedCount = 0;
try {
const phasesDir = path.join(wsDir, 'phases');
const dirs = fs.readdirSync(phasesDir, { withFileTypes: true }).filter(e => e.isDirectory());
phaseCount = dirs.length;
for (const d of dirs) {
const files = fs.readdirSync(path.join(phasesDir, d.name));
const plans = files.filter(f => f.endsWith('-PLAN.md') || f === 'PLAN.md');
const summaries = files.filter(f => f.endsWith('-SUMMARY.md') || f === 'SUMMARY.md');
if (plans.length > 0 && summaries.length >= plans.length) completedCount++;
}
} catch {}
others.push({ name: entry.name, status, current_phase: currentPhase, phases: `${completedCount}/${phaseCount}` });
}
return others;
}
module.exports = {
migrateToWorkstreams,
cmdWorkstreamCreate,
cmdWorkstreamList,
cmdWorkstreamStatus,
cmdWorkstreamComplete,
cmdWorkstreamSet,
cmdWorkstreamGet,
cmdWorkstreamProgress,
getOtherActiveWorkstreams,
};