Files
msd-core/get-shit-done/bin/lib/workstream.cjs
Tom Boucher 439d9ceacd refactor(shell-projection): migrate all fs call sites to platform* seam (Phase 3, #3467) (#3481)
* refactor(shell-projection): migrate roadmap.cjs writes to platformWriteSync (#3467)

2 atomicWriteFileSync calls → platformWriteSync. The seam owns markdown
normalization, so the explicit utf-8 encoding arg is no longer needed.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* refactor(shell-projection): migrate config.cjs writes to platformWriteSync (#3467)

- 3 atomicWriteFileSync calls → platformWriteSync
- 1 raw fs.writeFileSync (depth→granularity migration) → platformWriteSync
- 2 fs.mkdirSync(planningBase, { recursive: true }) → platformEnsureDir

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* refactor(shell-projection): migrate docs.cjs reads to platformReadSync (#3467)

6 try { fs.readFileSync } catch {} patterns → platformReadSync(path) with
explicit null guards. detectProjectType now reads package.json once and
shares it across has_cli_bin/is_monorepo/has_tests checks. JSON.parse is
still wrapped in a try (parsing is a separate failure mode from missing file).

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* refactor(shell-projection): migrate audit.cjs reads to platformReadSync (#3467)

8 try { fs.readFileSync(safeFilePath, 'utf-8') } catch { continue } patterns
→ const content = platformReadSync(safeFilePath); if (content === null) continue;

The single safeSum case (where catch set status='unreadable' rather than
continue) maps to an if/else that preserves the same semantics.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* refactor(shell-projection): migrate planning-workspace.cjs to platform* seam (#3467)

- 2 try { fs.readFileSync } catch {} → platformReadSync (null on missing)
- 2 fs.writeFileSync (workstream pointer writes) → platformWriteSync
- 3 fs.mkdirSync(..., { recursive: true }) → platformEnsureDir

The .lock file write at withPlanningLock is intentionally NOT migrated.
That call uses { flag: 'wx' } for atomic exclusive-create, which is the
correct lock-acquisition primitive. platformWriteSync's atomic-rename
pattern would silently overwrite an existing lock file and break the
locking guarantee.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* refactor(shell-projection): migrate milestone.cjs writes to platform* seam (#3467)

- 5 atomicWriteFileSync calls → platformWriteSync (4 dropped normalizeMd
  wrapper; seam handles .md normalization automatically)
- 2 raw fs.writeFileSync (archive ROADMAP.md / REQUIREMENTS.md) → platformWriteSync
- 2 fs.mkdirSync(..., { recursive: true }) → platformEnsureDir
- Dropped normalizeMd import (only used as write pre-call here)

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* refactor(shell-projection): migrate intel.cjs to platform* seam (#3467)

- 7 fs.readFileSync (existsSync+readFileSync patterns and try/catch) → platformReadSync
- 2 fs.writeFileSync → platformWriteSync
- 1 fs.mkdirSync(intelPath, { recursive: true }) → platformEnsureDir
- Consolidated dual-check (existsSync + readFileSync) into single platformReadSync
  call returning null on missing file

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* refactor(shell-projection): migrate workstream.cjs to platform* seam (#3467)

- 5 fs.mkdirSync(..., { recursive: true }) → platformEnsureDir
- 1 fs.writeFileSync (STATE.md initial scaffold) → platformWriteSync

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* refactor(shell-projection): migrate init.cjs reads/writes to platform* seam (#3467)

- 11 try/readFileSync and existsSync+readFileSync patterns → platformReadSync
- 1 fs.writeFileSync (skill-manifest.json) → platformWriteSync

Three bare fs.readFileSync calls remain (ROADMAP/STATE reads in code paths
where the file is required to exist) — these are not "Done when" violations
(no try/catch wrapping, no inline existsSync guard).

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* refactor(shell-projection): migrate commands.cjs reads/writes to platform* seam (#3467)

- 6 try/readFileSync and existsSync+readFileSync patterns → platformReadSync
- 2 fs.writeFileSync → platformWriteSync
- 3 fs.mkdirSync(..., { recursive: true }) → platformEnsureDir
- Removed unused safeReadFile import (zero call sites in this file)

Three bare fs.readFileSync calls remain (sourcePath at line 752, fullPath at
443, roadmapPath in cmdAuditOpen) — preceded by existsSync guards or in code
paths where file presence is required; not "Done when" violations.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* refactor(shell-projection): migrate profile-output.cjs to platform* seam (#3467)

- 6 safeReadFile (from core.cjs) calls preserved by aliasing platformReadSync
  as safeReadFile in the import — same semantics, zero call-site changes
- 3 try/JSON.parse(readFileSync) patterns → platformReadSync + try/JSON.parse
- 1 existsSync+readFileSync pattern (claude.md update) → platformReadSync
- 5 fs.writeFileSync → platformWriteSync
- 4 fs.mkdirSync(..., { recursive: true }) → platformEnsureDir

Two bare fs.readFileSync calls remain (template reads where file must exist
or fail loudly) — not "Done when" violations.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* refactor(shell-projection): migrate state.cjs to platform* seam (#3467)

- 4 atomicWriteFileSync calls → platformWriteSync (3 dropped normalizeMd
  wrapper; seam handles .md normalization)
- 4 try/readFileSync and existsSync+readFileSync patterns → platformReadSync
- 1 fs.writeFileSync (WAITING.json) → platformWriteSync
- 1 fs.mkdirSync(..., { recursive: true }) → platformEnsureDir
- Dropped normalizeMd and atomicWriteFileSync imports (only used as write
  pre-calls here)

Bare fs.readFileSync calls remain in code paths where STATE.md is required
to exist (statePath reads in cmd handlers, dry-run prune) — not "Done when"
violations.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* refactor(shell-projection): migrate core.cjs to platform* seam (#3467)

- 7 try/readFileSync and existsSync+readFileSync patterns → platformReadSync
- 3 fs.writeFileSync (config writes + large-payload temp file) → platformWriteSync
- 1 fs.mkdirSync (GSD_TEMP_DIR) → platformEnsureDir

Three fs calls remain — they are the internal implementations of the
safeReadFile and atomicWriteFileSync wrappers that core.cjs exports for
backward compatibility. The wrappers are scheduled for removal in Phase 4
(#3468) and will not be migrated here.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* refactor(shell-projection): migrate phase.cjs writes to platform* seam (#3467)

- 6 atomicWriteFileSync calls → platformWriteSync
- 3 fs.writeFileSync(path.join(dirPath, '.gitkeep'), '') → platformWriteSync
- 3 fs.mkdirSync(..., { recursive: true }) → platformEnsureDir

Bare fs.readFileSync calls remain for roadmapPath/planPath reads where the
file is required to exist; these are not "Done when" violations.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* refactor(shell-projection): migrate verify.cjs to platform* seam (#3467)

- 8 safeReadFile (from core.cjs) calls preserved by aliasing platformReadSync
  as safeReadFile in the import — same semantics, zero call-site changes
- 1 existsSync+readFileSync inline ternary → safeReadFile (returns null)
- 5 fs.writeFileSync (config writes + milestones writes) → platformWriteSync

Bare fs.readFileSync calls remain for code paths where the file is required
to exist (roadmap/state/config full reads); these are not "Done when"
violations.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* refactor(shell-projection): migrate frontmatter.cjs + update atomic-write test (#3467)

- frontmatter.cjs: 2 atomicWriteFileSync calls → platformWriteSync. The
  legacy normalizeMd wrapper is dropped because the seam handles markdown
  normalization. safeReadFile preserved by aliasing platformReadSync.
- atomic-write-coverage.test.cjs: update the #1972 structural invariant
  to assert on platformWriteSync. platformWriteSync uses the same
  tmp-file + atomic-rename primitive that atomicWriteFileSync did — the
  no-partial-write guarantee is preserved across the migration.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* chore(changeset): add entry for shell-projection Phase 3 migration (#3467)

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* chore(coderabbit): disable ESLint tool (repo uses custom lint scripts)

CodeRabbit's review surface emits a "skipped: no ESLint configuration"
warning because the repo doesn't ship ESLint config. The repo
intentionally does not use ESLint — it ships its own targeted lint
scripts (scripts/lint-no-source-grep.cjs, npm run lint:tests) that
enforce repo-specific test-quality invariants. Adding ESLint config
purely to satisfy CR would add an external dependency
(CONTRIBUTING.md: "No external dependencies in core") and overlap
with the existing custom lint surface.

Disable the ESLint tool in CR's tools config so the skip warning
stops appearing on every PR.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

---------

Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-13 19:34:23 -04:00

374 lines
12 KiB
JavaScript

/**
* 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, toPosixPath, getMilestoneInfo, generateSlugInternal } = require('./core.cjs');
const { platformWriteSync, platformEnsureDir } = require('./shell-command-projection.cjs');
const { planningRoot, setActiveWorkstream, getActiveWorkstream } = require('./planning-workspace.cjs');
const { toWorkstreamSlug, hasInvalidPathSegment, isValidActiveWorkstreamName } = require('./workstream-name-policy.cjs');
const {
getOtherActiveWorkstreamInventories,
inspectWorkstream,
listWorkstreamInventories,
} = require('./workstream-inventory.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 || hasInvalidPathSegment(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' },
];
platformEnsureDir(wsDir);
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 = toWorkstreamSlug(name);
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 = toWorkstreamSlug(migrateName);
if (!existingWsName) {
output({
created: false,
error: 'migration_failed',
message: 'Invalid migrate-name — must contain at least one alphanumeric character',
}, raw);
return;
}
} 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 {
platformEnsureDir(wsRoot);
}
}
platformEnsureDir(wsDir);
platformEnsureDir(path.join(wsDir, 'phases'));
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)) {
platformWriteSync(statePath, stateContent);
}
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 inventory = listWorkstreamInventories(cwd);
if (inventory.mode === 'flat') {
output({ mode: 'flat', workstreams: [], message: inventory.message }, raw);
return;
}
const workstreams = inventory.workstreams.map(ws => ({
name: ws.name,
path: ws.path,
has_roadmap: ws.files.roadmap,
has_state: ws.files.state,
status: ws.status,
current_phase: ws.current_phase,
phase_count: ws.phase_count,
completed_phases: ws.completed_phases,
}));
output({ mode: 'workstream', workstreams, count: workstreams.length }, raw);
}
function cmdWorkstreamStatus(cwd, name, raw) {
if (!name) error('workstream name required. Usage: workstream status <name>');
if (hasInvalidPathSegment(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 inventory = inspectWorkstream(cwd, name);
output({
found: true,
workstream: name,
path: inventory.path,
files: inventory.files,
phases: inventory.phases,
phase_count: inventory.phase_count,
completed_phases: inventory.completed_phases,
status: inventory.status,
current_phase: inventory.current_phase,
last_activity: inventory.last_activity,
}, raw);
}
function cmdWorkstreamComplete(cwd, name, options, raw) {
if (!name) error('workstream name required. Usage: workstream complete <name>');
if (hasInvalidPathSegment(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++}`);
}
platformEnsureDir(archivePath);
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 || name === '--clear') {
if (name !== '--clear') {
error('Workstream name required. Usage: workstream set <name> (or workstream set --clear to unset)');
}
const previous = getActiveWorkstream(cwd);
setActiveWorkstream(cwd, null);
output({ active: null, cleared: true, previous: previous || null }, raw);
return;
}
if (!isValidActiveWorkstreamName(name)) {
output({ active: null, error: 'invalid_name', message: 'Workstream name must be alphanumeric, hyphens, underscores, or dots' }, 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 inventory = listWorkstreamInventories(cwd);
if (inventory.mode === 'flat') {
output({ mode: 'flat', workstreams: [], message: inventory.message }, raw);
return;
}
const workstreams = inventory.workstreams.map(ws => ({
name: ws.name,
active: ws.active,
status: ws.status,
current_phase: ws.current_phase,
phases: `${ws.completed_phases}/${ws.roadmap_phase_count}`,
plans: `${ws.completed_plans}/${ws.total_plans}`,
progress_percent: ws.progress_percent,
}));
output({ mode: 'workstream', active: inventory.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) {
return getOtherActiveWorkstreamInventories(cwd, excludeWs).map(ws => ({
name: ws.name,
status: ws.status,
current_phase: ws.current_phase,
phases: `${ws.completed_phases}/${ws.phase_count}`,
}));
}
module.exports = {
migrateToWorkstreams,
cmdWorkstreamCreate,
cmdWorkstreamList,
cmdWorkstreamStatus,
cmdWorkstreamComplete,
cmdWorkstreamSet,
cmdWorkstreamGet,
cmdWorkstreamProgress,
getOtherActiveWorkstreams,
};