Refactor SDK-first architecture seams (#3316)

* refactor: tighten sdk-first architecture seams

Refs #3312

* refactor: finish state document seam cleanup

Refs #3312

* test: harden minimal install cleanup assertion

* ci: support sdk-scoped package lock

* fix(3316): restore root package-lock.json and align changeset pr ref

Reverts dec57a83 ("ci: support sdk-scoped package lock") and restores
the root package-lock.json that c249d34d deleted. The deletion was the
wrong direction:

- The root package.json declares its own runtime and dev deps
  (@anthropic-ai/claude-agent-sdk, ws, c8). Without a root lockfile,
  `npm install --no-package-lock` resolves whatever satisfies semver at
  install time — CI today and CI in six months can install different
  transitive trees, defeating reproducibility.
- The lockfile has been part of every release on this repo (long
  history on main); removing it loses the npm audit / Dependabot
  target without compensating benefit.
- The CI workaround pattern (cache-dependency-path: sdk/package-lock.json
  + `npm install --no-package-lock`) papered over the symptom rather
  than fix the cause.

Also fix the changeset pr: from 3312 (issue) to 3316 (PR). CONTEXT.md
flags this exact failure mode as a recurring CodeRabbit finding.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* fix: address coderabbit review findings

* fix: close remaining coderabbit threads

---------

Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This commit is contained in:
Tom Boucher
2026-05-09 14:21:42 -04:00
committed by GitHub
parent 2e87c60afc
commit 26dcdb1ad0
34 changed files with 1693 additions and 738 deletions

View File

@@ -0,0 +1,39 @@
'use strict';
/**
* CJS Command Router Adapter Module
*
* Compatibility routing for gsd-tools.cjs command families. Uses generated
* command metadata for availability and small family-local argument shapers for
* CJS handler calls.
*/
function routeCjsCommandFamily({
args,
subcommands,
handlers,
defaultSubcommand,
unsupported = {},
unknownMessage,
error,
}) {
const subcommand = args[1] || defaultSubcommand;
if (subcommand && unsupported[subcommand]) {
error(unsupported[subcommand]);
return;
}
const handler = subcommand ? handlers[subcommand] : null;
if (handler) {
handler();
return;
}
const available = subcommands.filter(s => !unsupported[s]);
error(unknownMessage(subcommand, available));
}
module.exports = {
routeCjsCommandFamily,
};

View File

@@ -9,6 +9,7 @@ const { loadConfig, resolveModelInternal, findPhaseInternal, getRoadmapPhaseInte
const { planningPaths, planningDir, planningRoot } = require('./planning-workspace.cjs');
const { maskIfSecret } = require('./secrets.cjs');
const scanPhasePlans = require('./plan-scan.cjs');
const { stateExtractField } = require('./state-document.cjs');
// Accept all bold/colon variants of the Requirements header (#2769):
// **Requirements:** / **Requirements**: / **Requirements** : render the
@@ -185,12 +186,9 @@ function cmdInitExecutePhase(cwd, phase, raw, options = {}) {
// Optional --validate: run state validation and include warnings (#1627)
if (options.validate) {
try {
const { cmdStateValidate } = require('./state.cjs');
// Capture validate output by temporarily redirecting
const statePath = path.join(planningDir(cwd), 'STATE.md');
if (fs.existsSync(statePath)) {
const stateContent = fs.readFileSync(statePath, 'utf-8');
const { stateExtractField } = require('./state.cjs');
const status = stateExtractField(stateContent, 'Status') || '';
result.state_validation_ran = true;
// Simple inline validation — check for obvious drift
@@ -360,7 +358,6 @@ function cmdInitPlanPhase(cwd, phase, raw, options = {}) {
try {
const statePath = path.join(planningDir(cwd), 'STATE.md');
if (fs.existsSync(statePath)) {
const { stateExtractField } = require('./state.cjs');
const stateContent = fs.readFileSync(statePath, 'utf-8');
const warnings = [];
result.state_validation_ran = true;

View File

@@ -1,50 +1,75 @@
'use strict';
const { PHASE_SUBCOMMANDS } = require('./command-aliases.generated.cjs');
const { routeCjsCommandFamily } = require('./cjs-command-router-adapter.cjs');
function routePhaseCommand({ phase, args, cwd, raw, error }) {
const subcommand = args[1];
if (subcommand === 'next-decimal') {
phase.cmdPhaseNextDecimal(cwd, args[2], raw);
} else if (subcommand === 'add') {
let customId = null;
const descArgs = [];
for (let i = 2; i < args.length; i++) {
if (args[i] === '--id' && i + 1 < args.length) {
customId = args[i + 1];
i++;
} else {
descArgs.push(args[i]);
}
}
phase.cmdPhaseAdd(cwd, descArgs.join(' '), raw, customId);
} else if (subcommand === 'add-batch') {
const descFlagIdx = args.indexOf('--descriptions');
let descriptions;
if (descFlagIdx !== -1 && args[descFlagIdx + 1]) {
try {
descriptions = JSON.parse(args[descFlagIdx + 1]);
} catch {
error('--descriptions must be a JSON array');
}
} else {
descriptions = args.slice(2).filter(a => a !== '--raw');
}
phase.cmdPhaseAddBatch(cwd, descriptions, raw);
} else if (subcommand === 'insert') {
if (args.includes('--dry-run')) {
error('phase insert does not support --dry-run');
}
phase.cmdPhaseInsert(cwd, args[2], args.slice(3).join(' '), raw);
} else if (subcommand === 'remove') {
const forceFlag = args.includes('--force');
phase.cmdPhaseRemove(cwd, args[2], { force: forceFlag }, raw);
} else if (subcommand === 'complete') {
phase.cmdPhaseComplete(cwd, args[2], raw);
} else {
error(`Unknown phase subcommand. Available: ${PHASE_SUBCOMMANDS.filter((s) => s !== 'list-plans' && s !== 'list-artifacts' && s !== 'scaffold').join(', ')}`);
}
routeCjsCommandFamily({
args,
subcommands: PHASE_SUBCOMMANDS,
unsupported: {
'list-plans': 'phase list-plans is SDK-only. Use: gsd-sdk query phase.list-plans ...',
'list-artifacts': 'phase list-artifacts is SDK-only. Use: gsd-sdk query phase.list-artifacts ...',
scaffold: 'phase scaffold is routed through the top-level scaffold command.',
},
error,
unknownMessage: (_subcommand, available) => `Unknown phase subcommand. Available: ${available.join(', ')}`,
handlers: {
'next-decimal': () => phase.cmdPhaseNextDecimal(cwd, args[2], raw),
add: () => {
let customId = null;
const descArgs = [];
for (let i = 2; i < args.length; i++) {
const token = args[i];
if (token === '--raw') {
continue;
}
if (token === '--id') {
const id = args[i + 1];
if (!id || id.startsWith('--')) {
error('--id requires a value');
}
customId = id;
i++;
} else if (token.startsWith('--')) {
error(`phase add does not support ${token}`);
} else {
descArgs.push(token);
}
}
phase.cmdPhaseAdd(cwd, descArgs.join(' '), raw, customId);
},
'add-batch': () => {
const descFlagIdx = args.indexOf('--descriptions');
let descriptions;
if (descFlagIdx !== -1) {
const rawDescriptions = args[descFlagIdx + 1];
if (!rawDescriptions || rawDescriptions.startsWith('--')) {
error('--descriptions must be a JSON array');
}
try {
descriptions = JSON.parse(rawDescriptions);
} catch {
error('--descriptions must be a JSON array');
}
if (!Array.isArray(descriptions)) {
error('--descriptions must be a JSON array');
}
} else {
descriptions = args.slice(2).filter(a => a !== '--raw');
}
phase.cmdPhaseAddBatch(cwd, descriptions, raw);
},
insert: () => {
if (args.includes('--dry-run')) {
error('phase insert does not support --dry-run');
}
phase.cmdPhaseInsert(cwd, args[2], args.slice(3).join(' '), raw);
},
remove: () => phase.cmdPhaseRemove(cwd, args[2], { force: args.includes('--force') }, raw),
complete: () => phase.cmdPhaseComplete(cwd, args[2], raw),
},
});
}
module.exports = {

View File

@@ -1,6 +1,7 @@
'use strict';
const { PHASES_SUBCOMMANDS } = require('./command-aliases.generated.cjs');
const { routeCjsCommandFamily } = require('./cjs-command-router-adapter.cjs');
/**
* Manifest-backed phases subcommand router.
@@ -12,23 +13,25 @@ const { PHASES_SUBCOMMANDS } = require('./command-aliases.generated.cjs');
* registry). CJS `gsd-tools phases` intentionally supports list/clear only.
*/
function routePhasesCommand({ phase, milestone, args, cwd, raw, error }) {
const subcommand = args[1];
if (subcommand === 'list') {
const typeIndex = args.indexOf('--type');
const phaseIndex = args.indexOf('--phase');
const options = {
type: typeIndex !== -1 ? args[typeIndex + 1] : null,
phase: phaseIndex !== -1 ? args[phaseIndex + 1] : null,
includeArchived: args.includes('--include-archived'),
};
phase.cmdPhasesList(cwd, options, raw);
} else if (subcommand === 'clear') {
milestone.cmdPhasesClear(cwd, raw, args.slice(2));
} else {
const cjsSupported = PHASES_SUBCOMMANDS.filter((s) => s !== 'archive');
error(`Unknown phases subcommand. Available: ${cjsSupported.join(', ')}`);
}
routeCjsCommandFamily({
args,
subcommands: PHASES_SUBCOMMANDS.filter((s) => s !== 'archive'),
error,
unknownMessage: (_subcommand, available) => `Unknown phases subcommand. Available: ${available.join(', ')}`,
handlers: {
list: () => {
const typeIndex = args.indexOf('--type');
const phaseIndex = args.indexOf('--phase');
const options = {
type: typeIndex !== -1 ? args[typeIndex + 1] : null,
phase: phaseIndex !== -1 ? args[phaseIndex + 1] : null,
includeArchived: args.includes('--include-archived'),
};
phase.cmdPhasesList(cwd, options, raw);
},
clear: () => milestone.cmdPhasesClear(cwd, raw, args.slice(2)),
},
});
}
module.exports = {

View File

@@ -1,89 +1,98 @@
'use strict';
const { STATE_SUBCOMMANDS } = require('./command-aliases.generated.cjs');
const { routeCjsCommandFamily } = require('./cjs-command-router-adapter.cjs');
/**
* Manifest-backed state subcommand router.
* Keeps gsd-tools.cjs thin while preserving existing command semantics.
*/
function routeStateCommand({ state, args, cwd, raw, parseNamedArgs, error }) {
const subcommand = args[1];
const parsePlans = (plans) => {
const parsedPlans = plans == null ? null : Number.parseInt(plans, 10);
if (plans != null && Number.isNaN(parsedPlans)) {
error('Invalid --plans value. Expected an integer.');
return null;
}
return parsedPlans;
};
if (subcommand === 'json') {
state.cmdStateJson(cwd, raw);
} else if (subcommand === 'update') {
state.cmdStateUpdate(cwd, args[2], args[3]);
} else if (subcommand === 'get') {
state.cmdStateGet(cwd, args[2], raw);
} else if (subcommand === 'patch') {
const patches = {};
for (let i = 2; i < args.length; i += 2) {
const key = args[i].replace(/^--/, '');
const value = args[i + 1];
if (key && value !== undefined) {
patches[key] = value;
}
}
state.cmdStatePatch(cwd, patches, raw);
} else if (subcommand === 'advance-plan') {
state.cmdStateAdvancePlan(cwd, raw);
} else if (subcommand === 'record-metric') {
const { phase: p, plan, duration, tasks, files } = parseNamedArgs(args, ['phase', 'plan', 'duration', 'tasks', 'files']);
state.cmdStateRecordMetric(cwd, { phase: p, plan, duration, tasks, files }, raw);
} else if (subcommand === 'update-progress') {
state.cmdStateUpdateProgress(cwd, raw);
} else if (subcommand === 'add-decision') {
const { phase: p, summary, 'summary-file': summary_file, rationale, 'rationale-file': rationale_file } = parseNamedArgs(args, ['phase', 'summary', 'summary-file', 'rationale', 'rationale-file']);
state.cmdStateAddDecision(cwd, { phase: p, summary, summary_file, rationale: rationale || '', rationale_file }, raw);
} else if (subcommand === 'add-blocker') {
const { text, 'text-file': text_file } = parseNamedArgs(args, ['text', 'text-file']);
state.cmdStateAddBlocker(cwd, { text, text_file }, raw);
} else if (subcommand === 'resolve-blocker') {
state.cmdStateResolveBlocker(cwd, parseNamedArgs(args, ['text']).text, raw);
} else if (subcommand === 'record-session') {
const { 'stopped-at': stopped_at, 'resume-file': resume_file } = parseNamedArgs(args, ['stopped-at', 'resume-file']);
state.cmdStateRecordSession(cwd, { stopped_at, resume_file: resume_file || 'None' }, raw);
} else if (subcommand === 'begin-phase') {
const { phase: p, name, plans } = parseNamedArgs(args, ['phase', 'name', 'plans']);
const parsedPlans = plans == null ? null : Number.parseInt(plans, 10);
if (plans != null && Number.isNaN(parsedPlans)) {
return error('Invalid --plans value. Expected an integer.');
}
state.cmdStateBeginPhase(cwd, p, name, parsedPlans, raw);
} else if (subcommand === 'signal-waiting') {
const { type, question, options, phase: p } = parseNamedArgs(args, ['type', 'question', 'options', 'phase']);
state.cmdSignalWaiting(cwd, type, question, options, p, raw);
} else if (subcommand === 'signal-resume') {
state.cmdSignalResume(cwd, raw);
} else if (subcommand === 'planned-phase') {
const { phase: p, plans } = parseNamedArgs(args, ['phase', 'name', 'plans']);
const parsedPlans = plans == null ? null : Number.parseInt(plans, 10);
if (plans != null && Number.isNaN(parsedPlans)) {
return error('Invalid --plans value. Expected an integer.');
}
state.cmdStatePlannedPhase(cwd, p, parsedPlans, raw);
} else if (subcommand === 'validate') {
state.cmdStateValidate(cwd, raw);
} else if (subcommand === 'sync') {
const { verify } = parseNamedArgs(args, [], ['verify']);
state.cmdStateSync(cwd, { verify }, raw);
} else if (subcommand === 'prune') {
const { 'keep-recent': keepRecent, 'dry-run': dryRun } = parseNamedArgs(args, ['keep-recent'], ['dry-run']);
state.cmdStatePrune(cwd, { keepRecent: keepRecent || '3', dryRun: !!dryRun }, raw);
} else if (subcommand === 'complete-phase') {
const { phase: p } = parseNamedArgs(args, ['phase']);
state.cmdStateCompletePhase(cwd, raw, p || args[2]);
} else if (subcommand === 'milestone-switch') {
const { milestone, name } = parseNamedArgs(args, ['milestone', 'name']);
state.cmdStateMilestoneSwitch(cwd, milestone, name, raw);
} else if (subcommand === 'add-roadmap-evolution') {
error('state add-roadmap-evolution is SDK-only. Use: gsd-sdk query state.add-roadmap-evolution ...');
} else if (subcommand === undefined || subcommand === 'load') {
state.cmdStateLoad(cwd, raw);
} else {
const available = ['load', 'complete-phase', ...STATE_SUBCOMMANDS.filter((s) => s !== 'load')];
error(`Unknown state subcommand: "${subcommand}". Available: ${available.join(', ')}`);
}
routeCjsCommandFamily({
args,
subcommands: ['load', 'complete-phase', ...STATE_SUBCOMMANDS.filter((s) => s !== 'load')],
defaultSubcommand: 'load',
unsupported: {
'add-roadmap-evolution': 'state add-roadmap-evolution is SDK-only. Use: gsd-sdk query state.add-roadmap-evolution ...',
},
error,
unknownMessage: (subcommand, available) => `Unknown state subcommand: "${subcommand}". Available: ${available.join(', ')}`,
handlers: {
load: () => state.cmdStateLoad(cwd, raw),
json: () => state.cmdStateJson(cwd, raw),
update: () => state.cmdStateUpdate(cwd, args[2], args[3]),
get: () => state.cmdStateGet(cwd, args[2], raw),
patch: () => {
const patches = {};
for (let i = 2; i < args.length; i += 2) {
const key = args[i].replace(/^--/, '');
const value = args[i + 1];
if (key && value !== undefined) {
patches[key] = value;
}
}
state.cmdStatePatch(cwd, patches, raw);
},
'advance-plan': () => state.cmdStateAdvancePlan(cwd, raw),
'record-metric': () => {
const { phase: p, plan, duration, tasks, files } = parseNamedArgs(args, ['phase', 'plan', 'duration', 'tasks', 'files']);
state.cmdStateRecordMetric(cwd, { phase: p, plan, duration, tasks, files }, raw);
},
'update-progress': () => state.cmdStateUpdateProgress(cwd, raw),
'add-decision': () => {
const { phase: p, summary, 'summary-file': summary_file, rationale, 'rationale-file': rationale_file } = parseNamedArgs(args, ['phase', 'summary', 'summary-file', 'rationale', 'rationale-file']);
state.cmdStateAddDecision(cwd, { phase: p, summary, summary_file, rationale: rationale || '', rationale_file }, raw);
},
'add-blocker': () => {
const { text, 'text-file': text_file } = parseNamedArgs(args, ['text', 'text-file']);
state.cmdStateAddBlocker(cwd, { text, text_file }, raw);
},
'resolve-blocker': () => state.cmdStateResolveBlocker(cwd, parseNamedArgs(args, ['text']).text, raw),
'record-session': () => {
const { 'stopped-at': stopped_at, 'resume-file': resume_file } = parseNamedArgs(args, ['stopped-at', 'resume-file']);
state.cmdStateRecordSession(cwd, { stopped_at, resume_file: resume_file || 'None' }, raw);
},
'begin-phase': () => {
const { phase: p, name, plans } = parseNamedArgs(args, ['phase', 'name', 'plans']);
state.cmdStateBeginPhase(cwd, p, name, parsePlans(plans), raw);
},
'signal-waiting': () => {
const { type, question, options, phase: p } = parseNamedArgs(args, ['type', 'question', 'options', 'phase']);
state.cmdSignalWaiting(cwd, type, question, options, p, raw);
},
'signal-resume': () => state.cmdSignalResume(cwd, raw),
'planned-phase': () => {
const { phase: p, plans } = parseNamedArgs(args, ['phase', 'name', 'plans']);
state.cmdStatePlannedPhase(cwd, p, parsePlans(plans), raw);
},
validate: () => state.cmdStateValidate(cwd, raw),
sync: () => {
const { verify } = parseNamedArgs(args, [], ['verify']);
state.cmdStateSync(cwd, { verify }, raw);
},
prune: () => {
const { 'keep-recent': keepRecent, 'dry-run': dryRun } = parseNamedArgs(args, ['keep-recent'], ['dry-run']);
state.cmdStatePrune(cwd, { keepRecent: keepRecent || '3', dryRun: !!dryRun }, raw);
},
'complete-phase': () => {
const { phase: p } = parseNamedArgs(args, ['phase']);
state.cmdStateCompletePhase(cwd, raw, p || args[2]);
},
'milestone-switch': () => {
const { milestone, name } = parseNamedArgs(args, ['milestone', 'name']);
state.cmdStateMilestoneSwitch(cwd, milestone, name, raw);
},
},
});
}
module.exports = {

View File

@@ -0,0 +1,122 @@
'use strict';
/**
* STATE.md Document Module
*
* Pure transforms for STATE.md text. This module does not read the filesystem
* and does not own persistence or locking.
*/
function escapeRegex(str) {
return String(str).replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
}
function stateExtractField(content, fieldName) {
const escaped = escapeRegex(fieldName);
const boldPattern = new RegExp(`\\*\\*${escaped}:\\*\\*[ \\t]*(.+)`, 'i');
const boldMatch = content.match(boldPattern);
if (boldMatch) return boldMatch[1].trim();
const plainPattern = new RegExp(`^${escaped}:[ \\t]*(.+)`, 'im');
const plainMatch = content.match(plainPattern);
return plainMatch ? plainMatch[1].trim() : null;
}
function stateReplaceField(content, fieldName, newValue) {
const escaped = escapeRegex(fieldName);
const boldPattern = new RegExp(`(\\*\\*${escaped}:\\*\\*\\s*)(.*)`, 'i');
if (boldPattern.test(content)) {
return content.replace(boldPattern, (_match, prefix) => `${prefix}${newValue}`);
}
const plainPattern = new RegExp(`(^${escaped}:\\s*)(.*)`, 'im');
if (plainPattern.test(content)) {
return content.replace(plainPattern, (_match, prefix) => `${prefix}${newValue}`);
}
return null;
}
function stateReplaceFieldWithFallback(content, primary, fallback, value) {
let result = stateReplaceField(content, primary, value);
if (result) return result;
if (fallback) {
result = stateReplaceField(content, fallback, value);
if (result) return result;
}
return content;
}
function normalizeStateStatus(status, pausedAt) {
let normalizedStatus = status || 'unknown';
const statusLower = (status || '').toLowerCase();
if (statusLower.includes('paused') || statusLower.includes('stopped') || pausedAt) {
normalizedStatus = 'paused';
} else if (statusLower.includes('executing') || statusLower.includes('in progress')) {
normalizedStatus = 'executing';
} else if (statusLower.includes('planning') || statusLower.includes('ready to plan')) {
normalizedStatus = 'planning';
} else if (statusLower.includes('discussing')) {
normalizedStatus = 'discussing';
} else if (statusLower.includes('verif')) {
normalizedStatus = 'verifying';
} else if (statusLower.includes('complete') || statusLower.includes('done')) {
normalizedStatus = 'completed';
} else if (statusLower.includes('ready to execute')) {
normalizedStatus = 'executing';
}
return normalizedStatus;
}
function computeProgressPercent(completedPlans, totalPlans, completedPhases, totalPhases) {
const hasPlanData = totalPlans !== null && totalPlans > 0 && completedPlans !== null;
const hasPhaseData = totalPhases !== null && totalPhases > 0 && completedPhases !== null;
if (!hasPlanData && !hasPhaseData) return null;
const planFraction = hasPlanData ? completedPlans / totalPlans : 1;
const phaseFraction = hasPhaseData ? completedPhases / totalPhases : 1;
return Math.min(100, Math.round(Math.min(planFraction, phaseFraction) * 100));
}
function toFiniteNumber(value) {
const number = Number(value);
return Number.isFinite(number) ? number : null;
}
function existingProgressExceedsDerived(existingProgress, derivedProgress, key) {
const existing = toFiniteNumber(existingProgress[key]);
const derived = toFiniteNumber(derivedProgress[key]);
return existing !== null && derived !== null && existing > derived;
}
function shouldPreserveExistingProgress(existingProgress, derivedProgress) {
if (!existingProgress || typeof existingProgress !== 'object') return false;
if (!derivedProgress || typeof derivedProgress !== 'object') return false;
return (
existingProgressExceedsDerived(existingProgress, derivedProgress, 'total_phases') ||
existingProgressExceedsDerived(existingProgress, derivedProgress, 'completed_phases') ||
existingProgressExceedsDerived(existingProgress, derivedProgress, 'total_plans') ||
existingProgressExceedsDerived(existingProgress, derivedProgress, 'completed_plans')
);
}
function normalizeProgressNumbers(progress) {
if (!progress || typeof progress !== 'object') return progress;
const normalized = { ...progress };
for (const key of ['total_phases', 'completed_phases', 'total_plans', 'completed_plans', 'percent']) {
const number = toFiniteNumber(normalized[key]);
if (number !== null) normalized[key] = number;
}
return normalized;
}
module.exports = {
computeProgressPercent,
normalizeProgressNumbers,
normalizeStateStatus,
shouldPreserveExistingProgress,
stateExtractField,
stateReplaceField,
stateReplaceFieldWithFallback,
};

View File

@@ -8,38 +8,20 @@ const { escapeRegex, loadConfig, getMilestoneInfo, getMilestonePhaseFilter, norm
const { planningDir, planningPaths } = require('./planning-workspace.cjs');
const { extractFrontmatter, reconstructFrontmatter } = require('./frontmatter.cjs');
const scanPhasePlans = require('./plan-scan.cjs');
const {
computeProgressPercent,
normalizeProgressNumbers,
normalizeStateStatus,
shouldPreserveExistingProgress,
stateExtractField,
stateReplaceField,
} = require('./state-document.cjs');
// Cache disk scan results from buildStateFrontmatter per cwd per process (#1967).
// Avoids re-reading N+1 directories on every state write when the phase structure
// hasn't changed within the same gsd-tools invocation.
const _diskScanCache = new Map();
/**
* Compute the canonical progress percent for STATE.md frontmatter and body.
*
* Uses min(plan_fraction, phase_fraction) when both denominators are > 0.
* This prevents a false "100%" when ROADMAP declares future phases that have no
* disk dirs yet — all plans summarised only means 100% of *realized* work done,
* not 100% of the declared milestone (#3242 Bug B).
*
* @param {number|null} completedPlans
* @param {number|null} totalPlans
* @param {number|null} completedPhases
* @param {number|null} totalPhases - ROADMAP-declared count (>= realised dirs)
* @returns {number|null} 0–100, or null when there is no data
*/
function computeProgressPercent(completedPlans, totalPlans, completedPhases, totalPhases) {
const hasPlanData = totalPlans !== null && totalPlans > 0 && completedPlans !== null;
const hasPhaseData = totalPhases !== null && totalPhases > 0 && completedPhases !== null;
if (!hasPlanData && !hasPhaseData) return null;
const planFraction = hasPlanData ? completedPlans / totalPlans : 1;
const phaseFraction = hasPhaseData ? completedPhases / totalPhases : 1;
return Math.min(100, Math.round(Math.min(planFraction, phaseFraction) * 100));
}
/** Shorthand — every state command needs this path */
function getStatePath(cwd) {
return planningPaths(cwd).state;
@@ -55,19 +37,6 @@ process.on('exit', () => {
}
});
// Shared helper: extract a field value from STATE.md content.
// Supports both **Field:** bold and plain Field: format.
// Horizontal whitespace only after ':' so YAML keys like `progress:` do not match as `Progress:` (parity with sdk/helpers stateExtractField).
function stateExtractField(content, fieldName) {
const escaped = escapeRegex(fieldName);
const boldPattern = new RegExp(`\\*\\*${escaped}:\\*\\*[ \\t]*(.+)`, 'i');
const boldMatch = content.match(boldPattern);
if (boldMatch) return boldMatch[1].trim();
const plainPattern = new RegExp(`^${escaped}:[ \\t]*(.+)`, 'im');
const plainMatch = content.match(plainPattern);
return plainMatch ? plainMatch[1].trim() : null;
}
function cmdStateLoad(cwd, raw) {
const config = loadConfig(cwd);
const planDir = planningPaths(cwd).planning;
@@ -190,16 +159,9 @@ function cmdStatePatch(cwd, patches, raw) {
// Use atomic read-modify-write to prevent lost updates from concurrent agents
readModifyWriteStateMd(statePath, (content) => {
for (const [field, value] of Object.entries(patches)) {
const fieldEscaped = escapeRegex(field);
// Try **Field:** bold format first, then plain Field: format
const boldPattern = new RegExp(`(\\*\\*${fieldEscaped}:\\*\\*\\s*)(.*)`, 'i');
const plainPattern = new RegExp(`(^${fieldEscaped}:\\s*)(.*)`, 'im');
if (boldPattern.test(content)) {
content = content.replace(boldPattern, (_match, prefix) => `${prefix}${value}`);
results.updated.push(field);
} else if (plainPattern.test(content)) {
content = content.replace(plainPattern, (_match, prefix) => `${prefix}${value}`);
const result = stateReplaceField(content, field, value);
if (result) {
content = result;
results.updated.push(field);
} else {
results.failed.push(field);
@@ -229,23 +191,22 @@ function cmdStateUpdate(cwd, field, value) {
const statePath = planningPaths(cwd).state;
try {
let updated = false;
// resync: false — cmdStateUpdate only replaces a body text line.
// Triggering syncStateFrontmatter would rebuild progress.* from disk, trampling
// manually-curated cross-milestone counters stored in the frontmatter (#3242 Bug A).
const shouldResync = ['Progress', 'Total Plans in Phase', 'Total Phases'].includes(field);
// Preserve curated progress for body-only updates, but allow fields that
// directly project into progress.* frontmatter to rebuild after mutation.
readModifyWriteStateMd(statePath, (content) => {
const fieldEscaped = escapeRegex(field);
// Try **Field:** bold format first, then plain Field: format
const boldPattern = new RegExp(`(\\*\\*${fieldEscaped}:\\*\\*\\s*)(.*)`, 'i');
const plainPattern = new RegExp(`(^${fieldEscaped}:\\s*)(.*)`, 'im');
if (boldPattern.test(content)) {
const body = stripFrontmatter(content);
const result = stateReplaceField(body, field, value);
if (result) {
updated = true;
return content.replace(boldPattern, (_match, prefix) => `${prefix}${value}`);
} else if (plainPattern.test(content)) {
updated = true;
return content.replace(plainPattern, (_match, prefix) => `${prefix}${value}`);
const existingFm = extractFrontmatter(content);
if (Object.keys(existingFm).length > 0) {
return `---\n${reconstructFrontmatter(existingFm)}\n---\n\n${result}`;
}
return result;
}
return content;
}, cwd, { resync: false });
}, cwd, { resync: shouldResync });
if (updated) {
output({ updated: true });
} else {
@@ -257,21 +218,6 @@ function cmdStateUpdate(cwd, field, value) {
}
// ─── State Progression Engine ────────────────────────────────────────────────
// stateExtractField is defined above (shared helper) — do not duplicate.
function stateReplaceField(content, fieldName, newValue) {
const escaped = escapeRegex(fieldName);
// Try **Field:** bold format first, then plain Field: format
const boldPattern = new RegExp(`(\\*\\*${escaped}:\\*\\*\\s*)(.*)`, 'i');
if (boldPattern.test(content)) {
return content.replace(boldPattern, (_match, prefix) => `${prefix}${newValue}`);
}
const plainPattern = new RegExp(`(^${escaped}:\\s*)(.*)`, 'im');
if (plainPattern.test(content)) {
return content.replace(plainPattern, (_match, prefix) => `${prefix}${newValue}`);
}
return null;
}
/**
* Replace a STATE.md field with fallback field name support.
@@ -909,24 +855,7 @@ function buildStateFrontmatter(bodyContent, cwd) {
if (pctMatch) progressPercent = parseInt(pctMatch[1], 10);
}
// Normalize status to one of: planning, discussing, executing, verifying, paused, completed, unknown
let normalizedStatus = status || 'unknown';
const statusLower = (status || '').toLowerCase();
if (statusLower.includes('paused') || statusLower.includes('stopped') || pausedAt) {
normalizedStatus = 'paused';
} else if (statusLower.includes('executing') || statusLower.includes('in progress')) {
normalizedStatus = 'executing';
} else if (statusLower.includes('planning') || statusLower.includes('ready to plan')) {
normalizedStatus = 'planning';
} else if (statusLower.includes('discussing')) {
normalizedStatus = 'discussing';
} else if (statusLower.includes('verif')) {
normalizedStatus = 'verifying';
} else if (statusLower.includes('complete') || statusLower.includes('done')) {
normalizedStatus = 'completed';
} else if (statusLower.includes('ready to execute')) {
normalizedStatus = 'executing';
}
const normalizedStatus = normalizeStateStatus(status, pausedAt);
const fm = { gsd_state_version: '1.0' };
@@ -1126,6 +1055,12 @@ function cmdStateJson(cwd, raw) {
if (built.status === 'unknown' && existingFm && existingFm.status && existingFm.status !== 'unknown') {
built.status = existingFm.status;
}
// Preserve curated cross-milestone aggregates when local disk scanning sees
// only a narrower realized subset (#3242 Bug A). Stale lower counters still
// rebuild from disk because they do not exceed the derived scan.
if (existingFm && shouldPreserveExistingProgress(existingFm.progress, built.progress)) {
built.progress = normalizeProgressNumbers(existingFm.progress);
}
output(built, raw, JSON.stringify(built, null, 2));
}

View File

@@ -0,0 +1,159 @@
'use strict';
/**
* Workstream Inventory Module
*
* Owns discovery and read-only projection of .planning/workstreams/* state.
* Command handlers should render outputs from this inventory instead of
* rescanning workstream directories directly.
*/
const fs = require('fs');
const path = require('path');
const { toPosixPath, readSubdirectories } = require('./core.cjs');
const scanPhasePlans = require('./plan-scan.cjs');
const { planningPaths, planningRoot, getActiveWorkstream } = require('./planning-workspace.cjs');
const { stateExtractField } = require('./state-document.cjs');
function workstreamsRoot(cwd) {
return path.join(planningRoot(cwd), 'workstreams');
}
function countRoadmapPhases(roadmapPath, fallbackCount) {
try {
const roadmapContent = fs.readFileSync(roadmapPath, 'utf-8');
const matches = roadmapContent.match(/^#{2,4}\s+Phase\s+[\w][\w.-]*/gm);
return matches ? matches.length : fallbackCount;
} catch {
return fallbackCount;
}
}
function countPhaseFiles(phaseDir) {
const scan = scanPhasePlans(phaseDir);
return { planCount: scan.planCount, summaryCount: scan.summaryCount };
}
function readStateProjection(statePath) {
try {
const stateContent = fs.readFileSync(statePath, 'utf-8');
return {
status: stateExtractField(stateContent, 'Status') || 'unknown',
current_phase: stateExtractField(stateContent, 'Current Phase'),
last_activity: stateExtractField(stateContent, 'Last Activity'),
};
} catch {
return {
status: 'unknown',
current_phase: null,
last_activity: null,
};
}
}
function inspectWorkstream(cwd, name, options = {}) {
const wsDir = path.join(workstreamsRoot(cwd), name);
if (!fs.existsSync(wsDir)) return null;
const active = options.active === undefined ? getActiveWorkstream(cwd) : options.active;
const p = planningPaths(cwd, name);
const phaseDirs = readSubdirectories(p.phases);
const phases = [];
let completedPhases = 0;
let totalPlans = 0;
let completedPlans = 0;
for (const dir of phaseDirs.sort()) {
const counts = countPhaseFiles(path.join(p.phases, dir));
const status = counts.summaryCount >= counts.planCount && counts.planCount > 0
? 'complete'
: counts.planCount > 0
? 'in_progress'
: 'pending';
totalPlans += counts.planCount;
completedPlans += Math.min(counts.summaryCount, counts.planCount);
if (status === 'complete') completedPhases++;
phases.push({
directory: dir,
status,
plan_count: counts.planCount,
summary_count: counts.summaryCount,
});
}
const roadmapPhaseCount = countRoadmapPhases(p.roadmap, phaseDirs.length);
const state = readStateProjection(p.state);
return {
name,
path: toPosixPath(path.relative(cwd, wsDir)),
active: name === active,
files: {
roadmap: fs.existsSync(p.roadmap),
state: fs.existsSync(p.state),
requirements: fs.existsSync(p.requirements),
},
status: state.status,
current_phase: state.current_phase,
last_activity: state.last_activity,
phases,
phase_count: phases.length,
completed_phases: completedPhases,
roadmap_phase_count: roadmapPhaseCount,
total_plans: totalPlans,
completed_plans: completedPlans,
progress_percent: roadmapPhaseCount > 0 ? Math.min(100, Math.round((completedPhases / roadmapPhaseCount) * 100)) : 0,
};
}
function listWorkstreamInventories(cwd) {
const wsRoot = workstreamsRoot(cwd);
if (!fs.existsSync(wsRoot)) {
return {
mode: 'flat',
active: null,
workstreams: [],
count: 0,
message: 'No workstreams — operating in flat mode',
};
}
const active = getActiveWorkstream(cwd);
const entries = fs.readdirSync(wsRoot, { withFileTypes: true });
const workstreams = [];
for (const entry of entries) {
if (!entry.isDirectory()) continue;
const inventory = inspectWorkstream(cwd, entry.name, { active });
if (inventory) workstreams.push(inventory);
}
return {
mode: 'workstream',
active,
workstreams,
count: workstreams.length,
};
}
function isCompletedInventory(inventory) {
const status = String(inventory && inventory.status ? inventory.status : '').toLowerCase();
return status.includes('milestone complete') || status.includes('archived');
}
function getOtherActiveWorkstreamInventories(cwd, excludeWs) {
return listWorkstreamInventories(cwd).workstreams
.filter(inventory => inventory.name !== excludeWs)
.filter(inventory => !isCompletedInventory(inventory));
}
module.exports = {
countPhaseFiles,
countRoadmapPhases,
getOtherActiveWorkstreamInventories,
inspectWorkstream,
isCompletedInventory,
listWorkstreamInventories,
workstreamsRoot,
};

View File

@@ -10,10 +10,14 @@
const fs = require('fs');
const path = require('path');
const { output, error, toPosixPath, getMilestoneInfo, generateSlugInternal, filterPlanFiles, filterSummaryFiles, readSubdirectories } = require('./core.cjs');
const { planningPaths, planningRoot, setActiveWorkstream, getActiveWorkstream } = require('./planning-workspace.cjs');
const { stateExtractField } = require('./state.cjs');
const { output, error, toPosixPath, getMilestoneInfo, generateSlugInternal } = require('./core.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 ──────────────────────────────────────────────────────────────
@@ -179,52 +183,22 @@ function cmdWorkstreamCreate(cwd, name, options, 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);
const inventory = listWorkstreamInventories(cwd);
if (inventory.mode === 'flat') {
output({ mode: 'flat', workstreams: [], message: inventory.message }, 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');
const phaseDirs = readSubdirectories(phasesDir);
const phaseCount = phaseDirs.length;
let completedCount = 0;
for (const d of phaseDirs) {
try {
const phaseFiles = fs.readdirSync(path.join(phasesDir, d));
const plans = filterPlanFiles(phaseFiles);
const summaries = filterSummaryFiles(phaseFiles);
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');
status = stateExtractField(stateContent, 'Status') || 'unknown';
currentPhase = stateExtractField(stateContent, 'Current Phase');
} 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,
});
}
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);
}
@@ -239,50 +213,19 @@ function cmdWorkstreamStatus(cwd, 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 = [];
for (const dir of readSubdirectories(p.phases).sort()) {
try {
const phaseFiles = fs.readdirSync(path.join(p.phases, dir));
const plans = filterPlanFiles(phaseFiles);
const summaries = filterSummaryFiles(phaseFiles);
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');
stateInfo = {
status: stateExtractField(stateContent, 'Status') || 'unknown',
current_phase: stateExtractField(stateContent, 'Current Phase'),
last_activity: stateExtractField(stateContent, 'Last Activity'),
};
} catch {}
const inventory = inspectWorkstream(cwd, name);
output({
found: true,
workstream: name,
path: relPath,
files,
phases,
phase_count: phases.length,
completed_phases: phases.filter(ph => ph.status === 'complete').length,
...stateInfo,
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);
}
@@ -381,64 +324,23 @@ function cmdWorkstreamGet(cwd, raw) {
}
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);
const inventory = listWorkstreamInventories(cwd);
if (inventory.mode === 'flat') {
output({ mode: 'flat', workstreams: [], message: inventory.message }, raw);
return;
}
const active = getActiveWorkstream(cwd);
const entries = fs.readdirSync(wsRoot, { withFileTypes: true });
const workstreams = [];
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,
}));
for (const entry of entries) {
if (!entry.isDirectory()) continue;
const wsDir = path.join(wsRoot, entry.name);
const phasesDir = path.join(wsDir, 'phases');
const phaseDirsProgress = readSubdirectories(phasesDir);
const phaseCount = phaseDirsProgress.length;
let completedCount = 0, totalPlans = 0, completedPlans = 0;
for (const d of phaseDirsProgress) {
try {
const phaseFiles = fs.readdirSync(path.join(phasesDir, d));
const plans = filterPlanFiles(phaseFiles);
const summaries = filterSummaryFiles(phaseFiles);
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');
status = stateExtractField(stateContent, 'Status') || 'unknown';
currentPhase = stateExtractField(stateContent, 'Current Phase');
} 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);
output({ mode: 'workstream', active: inventory.active, workstreams, count: workstreams.length }, raw);
}
// ─── Collision Detection ────────────────────────────────────────────────────
@@ -449,47 +351,12 @@ function cmdWorkstreamProgress(cwd, raw) {
* 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');
status = stateExtractField(content, 'Status') || 'unknown';
currentPhase = stateExtractField(content, 'Current Phase');
} catch {}
if (status.toLowerCase().includes('milestone complete') ||
status.toLowerCase().includes('archived')) {
continue;
}
const phasesDir = path.join(wsDir, 'phases');
const phaseDirsOther = readSubdirectories(phasesDir);
const phaseCount = phaseDirsOther.length;
let completedCount = 0;
for (const d of phaseDirsOther) {
try {
const phaseFiles = fs.readdirSync(path.join(phasesDir, d));
const plans = filterPlanFiles(phaseFiles);
const summaries = filterSummaryFiles(phaseFiles);
if (plans.length > 0 && summaries.length >= plans.length) completedCount++;
} catch {}
}
others.push({ name: entry.name, status, current_phase: currentPhase, phases: `${completedCount}/${phaseCount}` });
}
return others;
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 = {