Merge upstream/main and resolve conflicts
Integrate upstream workspace features (new-workspace, list-workspaces, remove-workspace) alongside manager feature. Bump copilot skill count 53 → 54 and agent count to 18 to account for both upstream additions and the new manager skill. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
This commit is contained in:
@@ -20,6 +20,7 @@
|
||||
* resolve-model <agent-type> Get model for agent based on profile
|
||||
* find-phase <phase> Find phase directory by number
|
||||
* commit <message> [--files f1 f2] [--no-verify] Commit planning docs
|
||||
* commit-to-subrepo <msg> --files f1 f2 Route commits to sub-repos
|
||||
* verify-summary <path> Verify a SUMMARY.md file
|
||||
* generate-slug <text> Convert text to URL-safe slug
|
||||
* current-timestamp [format] Get timestamp (full|date|filename)
|
||||
@@ -134,7 +135,7 @@
|
||||
|
||||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
const { error } = require('./lib/core.cjs');
|
||||
const { error, findProjectRoot } = require('./lib/core.cjs');
|
||||
const state = require('./lib/state.cjs');
|
||||
const phase = require('./lib/phase.cjs');
|
||||
const roadmap = require('./lib/roadmap.cjs');
|
||||
@@ -173,6 +174,13 @@ async function main() {
|
||||
error(`Invalid --cwd: ${cwd}`);
|
||||
}
|
||||
|
||||
// Resolve worktree root: in a linked worktree, .planning/ lives in the main worktree
|
||||
const { resolveWorktreeRoot } = require('./lib/core.cjs');
|
||||
const worktreeRoot = resolveWorktreeRoot(cwd);
|
||||
if (worktreeRoot !== cwd) {
|
||||
cwd = worktreeRoot;
|
||||
}
|
||||
|
||||
const rawIndex = args.indexOf('--raw');
|
||||
const raw = rawIndex !== -1;
|
||||
if (rawIndex !== -1) args.splice(rawIndex, 1);
|
||||
@@ -180,7 +188,18 @@ async function main() {
|
||||
const command = args[0];
|
||||
|
||||
if (!command) {
|
||||
error('Usage: gsd-tools <command> [args] [--raw] [--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, init');
|
||||
error('Usage: gsd-tools <command> [args] [--raw] [--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');
|
||||
}
|
||||
|
||||
// Multi-repo guard: resolve project root for commands that read/write .planning/.
|
||||
// Skip for pure-utility commands that don't touch .planning/ to avoid unnecessary
|
||||
// filesystem traversal on every invocation.
|
||||
const SKIP_ROOT_RESOLUTION = new Set([
|
||||
'generate-slug', 'current-timestamp', 'verify-path-exists',
|
||||
'verify-summary', 'template', 'frontmatter',
|
||||
]);
|
||||
if (!SKIP_ROOT_RESOLUTION.has(command)) {
|
||||
cwd = findProjectRoot(cwd);
|
||||
}
|
||||
|
||||
switch (command) {
|
||||
@@ -306,6 +325,14 @@ async function main() {
|
||||
break;
|
||||
}
|
||||
|
||||
case 'commit-to-subrepo': {
|
||||
const message = args[1];
|
||||
const filesIndex = args.indexOf('--files');
|
||||
const files = filesIndex !== -1 ? args.slice(filesIndex + 1).filter(a => !a.startsWith('--')) : [];
|
||||
commands.cmdCommitToSubrepo(cwd, message, files, raw);
|
||||
break;
|
||||
}
|
||||
|
||||
case 'verify-summary': {
|
||||
const summaryPath = args[1];
|
||||
const countIndex = args.indexOf('--check-count');
|
||||
@@ -332,7 +359,12 @@ async function main() {
|
||||
name: nameIdx !== -1 ? args[nameIdx + 1] : null,
|
||||
type: typeIdx !== -1 ? args[typeIdx + 1] : 'execute',
|
||||
wave: waveIdx !== -1 ? args[waveIdx + 1] : '1',
|
||||
fields: fieldsIdx !== -1 ? JSON.parse(args[fieldsIdx + 1]) : {},
|
||||
fields: fieldsIdx !== -1 ? (() => {
|
||||
const { safeJsonParse } = require('./lib/security.cjs');
|
||||
const result = safeJsonParse(args[fieldsIdx + 1], { label: '--fields' });
|
||||
if (!result.ok) error(result.error);
|
||||
return result.value;
|
||||
})() : {},
|
||||
}, raw);
|
||||
} else {
|
||||
error('Unknown template subcommand. Available: select, fill');
|
||||
@@ -422,6 +454,11 @@ async function main() {
|
||||
break;
|
||||
}
|
||||
|
||||
case 'config-new-project': {
|
||||
config.cmdConfigNewProject(cwd, args[1], raw);
|
||||
break;
|
||||
}
|
||||
|
||||
case 'history-digest': {
|
||||
commands.cmdHistoryDigest(cwd, raw);
|
||||
break;
|
||||
@@ -617,8 +654,17 @@ async function main() {
|
||||
case 'manager':
|
||||
init.cmdInitManager(cwd, raw);
|
||||
break;
|
||||
case 'new-workspace':
|
||||
init.cmdInitNewWorkspace(cwd, raw);
|
||||
break;
|
||||
case 'list-workspaces':
|
||||
init.cmdInitListWorkspaces(cwd, raw);
|
||||
break;
|
||||
case 'remove-workspace':
|
||||
init.cmdInitRemoveWorkspace(cwd, args[2], raw);
|
||||
break;
|
||||
default:
|
||||
error(`Unknown init workflow: ${workflow}\nAvailable: execute-phase, plan-phase, new-project, new-milestone, quick, resume, verify-work, phase-op, todos, milestone-op, map-codebase, progress, manager`);
|
||||
error(`Unknown init workflow: ${workflow}\nAvailable: execute-phase, plan-phase, new-project, new-milestone, quick, resume, verify-work, phase-op, todos, milestone-op, map-codebase, progress, manager, new-workspace, list-workspaces, remove-workspace`);
|
||||
}
|
||||
break;
|
||||
}
|
||||
|
||||
@@ -84,6 +84,11 @@ function cmdVerifyPathExists(cwd, targetPath, raw) {
|
||||
error('path required for verification');
|
||||
}
|
||||
|
||||
// Reject null bytes and validate path does not contain traversal attempts
|
||||
if (targetPath.includes('\0')) {
|
||||
error('path contains null bytes');
|
||||
}
|
||||
|
||||
const fullPath = path.isAbsolute(targetPath) ? targetPath : path.join(cwd, targetPath);
|
||||
|
||||
try {
|
||||
@@ -219,6 +224,13 @@ function cmdCommit(cwd, message, files, raw, amend, noVerify) {
|
||||
error('commit message required');
|
||||
}
|
||||
|
||||
// Sanitize commit message: strip invisible chars and injection markers
|
||||
// that could hijack agent context when commit messages are read back
|
||||
if (message) {
|
||||
const { sanitizeForPrompt } = require('./security.cjs');
|
||||
message = sanitizeForPrompt(message);
|
||||
}
|
||||
|
||||
const config = loadConfig(cwd);
|
||||
|
||||
// Check commit_docs config
|
||||
@@ -235,6 +247,43 @@ function cmdCommit(cwd, message, files, raw, amend, noVerify) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Ensure branching strategy branch exists before first commit (#1278).
|
||||
// Pre-execution workflows (discuss, plan, research) commit artifacts but the branch
|
||||
// was previously only created during execute-phase — too late.
|
||||
if (config.branching_strategy && config.branching_strategy !== 'none') {
|
||||
let branchName = null;
|
||||
if (config.branching_strategy === 'phase') {
|
||||
// Determine which phase we're committing for from the file paths
|
||||
const phaseMatch = (files || []).join(' ').match(/(\d+)-/);
|
||||
if (phaseMatch) {
|
||||
const phaseNum = phaseMatch[1];
|
||||
const phaseInfo = findPhaseInternal(cwd, phaseNum);
|
||||
if (phaseInfo) {
|
||||
branchName = config.phase_branch_template
|
||||
.replace('{phase}', phaseInfo.phase_number)
|
||||
.replace('{slug}', phaseInfo.phase_slug || 'phase');
|
||||
}
|
||||
}
|
||||
} else if (config.branching_strategy === 'milestone') {
|
||||
const milestone = getMilestoneInfo(cwd);
|
||||
if (milestone && milestone.version) {
|
||||
branchName = config.milestone_branch_template
|
||||
.replace('{milestone}', milestone.version)
|
||||
.replace('{slug}', generateSlugInternal(milestone.name) || 'milestone');
|
||||
}
|
||||
}
|
||||
if (branchName) {
|
||||
const currentBranch = execGit(cwd, ['rev-parse', '--abbrev-ref', 'HEAD']);
|
||||
if (currentBranch.exitCode === 0 && currentBranch.stdout.trim() !== branchName) {
|
||||
// Create branch if it doesn't exist, or switch to it if it does
|
||||
const create = execGit(cwd, ['checkout', '-b', branchName]);
|
||||
if (create.exitCode !== 0) {
|
||||
execGit(cwd, ['checkout', branchName]);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Stage files
|
||||
const filesToStage = files && files.length > 0 ? files : ['.planning/'];
|
||||
for (const file of filesToStage) {
|
||||
@@ -269,6 +318,74 @@ function cmdCommit(cwd, message, files, raw, amend, noVerify) {
|
||||
output(result, raw, hash || 'committed');
|
||||
}
|
||||
|
||||
function cmdCommitToSubrepo(cwd, message, files, raw) {
|
||||
if (!message) {
|
||||
error('commit message required');
|
||||
}
|
||||
|
||||
const config = loadConfig(cwd);
|
||||
const subRepos = config.sub_repos;
|
||||
|
||||
if (!subRepos || subRepos.length === 0) {
|
||||
error('no sub_repos configured in .planning/config.json');
|
||||
}
|
||||
|
||||
if (!files || files.length === 0) {
|
||||
error('--files required for commit-to-subrepo');
|
||||
}
|
||||
|
||||
// Group files by sub-repo prefix
|
||||
const grouped = {};
|
||||
const unmatched = [];
|
||||
for (const file of files) {
|
||||
const match = subRepos.find(repo => file.startsWith(repo + '/'));
|
||||
if (match) {
|
||||
if (!grouped[match]) grouped[match] = [];
|
||||
grouped[match].push(file);
|
||||
} else {
|
||||
unmatched.push(file);
|
||||
}
|
||||
}
|
||||
|
||||
if (unmatched.length > 0) {
|
||||
process.stderr.write(`Warning: ${unmatched.length} file(s) did not match any sub-repo prefix: ${unmatched.join(', ')}\n`);
|
||||
}
|
||||
|
||||
const repos = {};
|
||||
for (const [repo, repoFiles] of Object.entries(grouped)) {
|
||||
const repoCwd = path.join(cwd, repo);
|
||||
|
||||
// Stage files (strip sub-repo prefix for paths relative to that repo)
|
||||
for (const file of repoFiles) {
|
||||
const relativePath = file.slice(repo.length + 1);
|
||||
execGit(repoCwd, ['add', relativePath]);
|
||||
}
|
||||
|
||||
// Commit
|
||||
const commitResult = execGit(repoCwd, ['commit', '-m', message]);
|
||||
if (commitResult.exitCode !== 0) {
|
||||
if (commitResult.stdout.includes('nothing to commit') || commitResult.stderr.includes('nothing to commit')) {
|
||||
repos[repo] = { committed: false, hash: null, files: repoFiles, reason: 'nothing_to_commit' };
|
||||
continue;
|
||||
}
|
||||
repos[repo] = { committed: false, hash: null, files: repoFiles, reason: 'error', error: commitResult.stderr };
|
||||
continue;
|
||||
}
|
||||
|
||||
// Get hash
|
||||
const hashResult = execGit(repoCwd, ['rev-parse', '--short', 'HEAD']);
|
||||
const hash = hashResult.exitCode === 0 ? hashResult.stdout : null;
|
||||
repos[repo] = { committed: true, hash, files: repoFiles };
|
||||
}
|
||||
|
||||
const result = {
|
||||
committed: Object.values(repos).some(r => r.committed),
|
||||
repos,
|
||||
unmatched: unmatched.length > 0 ? unmatched : undefined,
|
||||
};
|
||||
output(result, raw, Object.entries(repos).map(([r, v]) => `${r}:${v.hash || 'skip'}`).join(' '));
|
||||
}
|
||||
|
||||
function cmdSummaryExtract(cwd, summaryPath, fields, raw) {
|
||||
if (!summaryPath) {
|
||||
error('summary-path required for summary-extract');
|
||||
@@ -831,6 +948,7 @@ module.exports = {
|
||||
cmdHistoryDigest,
|
||||
cmdResolveModel,
|
||||
cmdCommit,
|
||||
cmdCommitToSubrepo,
|
||||
cmdSummaryExtract,
|
||||
cmdWebsearch,
|
||||
cmdProgressRender,
|
||||
|
||||
@@ -13,13 +13,15 @@ const {
|
||||
|
||||
const VALID_CONFIG_KEYS = new Set([
|
||||
'mode', 'granularity', 'parallelization', 'commit_docs', 'model_profile',
|
||||
'search_gitignored', 'brave_search',
|
||||
'search_gitignored', 'brave_search', 'firecrawl', 'exa_search',
|
||||
'workflow.research', 'workflow.plan_check', 'workflow.verifier',
|
||||
'workflow.nyquist_validation', 'workflow.ui_phase', 'workflow.ui_safety_gate',
|
||||
'workflow.auto_advance', 'workflow.node_repair', 'workflow.node_repair_budget',
|
||||
'workflow.text_mode',
|
||||
'workflow._auto_chain_active',
|
||||
'git.branching_strategy', 'git.phase_branch_template', 'git.milestone_branch_template', 'git.quick_branch_template',
|
||||
'planning.commit_docs', 'planning.search_gitignored',
|
||||
'hooks.context_warnings',
|
||||
]);
|
||||
|
||||
const CONFIG_KEY_SUGGESTIONS = {
|
||||
@@ -35,6 +37,154 @@ function validateKnownConfigKeyPath(keyPath) {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Build a fully-materialized config object for a new project.
|
||||
*
|
||||
* Merges (increasing priority):
|
||||
* 1. Hardcoded defaults — every key that loadConfig() resolves, plus mode/granularity
|
||||
* 2. User-level defaults from ~/.gsd/defaults.json (if present)
|
||||
* 3. userChoices — the settings the user explicitly selected during /gsd:new-project
|
||||
*
|
||||
* Uses the canonical `git` namespace for branching keys (consistent with VALID_CONFIG_KEYS
|
||||
* and the settings workflow). loadConfig() handles both flat and nested formats, so this
|
||||
* is backward-compatible with existing projects that have flat keys.
|
||||
*
|
||||
* Returns a plain object — does NOT write any files.
|
||||
*/
|
||||
function buildNewProjectConfig(userChoices) {
|
||||
const choices = userChoices || {};
|
||||
const homedir = require('os').homedir();
|
||||
|
||||
// Detect API key availability
|
||||
const braveKeyFile = path.join(homedir, '.gsd', 'brave_api_key');
|
||||
const hasBraveSearch = !!(process.env.BRAVE_API_KEY || fs.existsSync(braveKeyFile));
|
||||
const firecrawlKeyFile = path.join(homedir, '.gsd', 'firecrawl_api_key');
|
||||
const hasFirecrawl = !!(process.env.FIRECRAWL_API_KEY || fs.existsSync(firecrawlKeyFile));
|
||||
const exaKeyFile = path.join(homedir, '.gsd', 'exa_api_key');
|
||||
const hasExaSearch = !!(process.env.EXA_API_KEY || fs.existsSync(exaKeyFile));
|
||||
|
||||
// Load user-level defaults from ~/.gsd/defaults.json if available
|
||||
const globalDefaultsPath = path.join(homedir, '.gsd', 'defaults.json');
|
||||
let userDefaults = {};
|
||||
try {
|
||||
if (fs.existsSync(globalDefaultsPath)) {
|
||||
userDefaults = JSON.parse(fs.readFileSync(globalDefaultsPath, 'utf-8'));
|
||||
// Migrate deprecated "depth" key to "granularity"
|
||||
if ('depth' in userDefaults && !('granularity' in userDefaults)) {
|
||||
const depthToGranularity = { quick: 'coarse', standard: 'standard', comprehensive: 'fine' };
|
||||
userDefaults.granularity = depthToGranularity[userDefaults.depth] || userDefaults.depth;
|
||||
delete userDefaults.depth;
|
||||
try {
|
||||
fs.writeFileSync(globalDefaultsPath, JSON.stringify(userDefaults, null, 2), 'utf-8');
|
||||
} catch { /* intentionally empty */ }
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
// Ignore malformed global defaults
|
||||
}
|
||||
|
||||
const hardcoded = {
|
||||
model_profile: 'balanced',
|
||||
commit_docs: true,
|
||||
parallelization: true,
|
||||
search_gitignored: false,
|
||||
brave_search: hasBraveSearch,
|
||||
firecrawl: hasFirecrawl,
|
||||
exa_search: hasExaSearch,
|
||||
git: {
|
||||
branching_strategy: 'none',
|
||||
phase_branch_template: 'gsd/phase-{phase}-{slug}',
|
||||
milestone_branch_template: 'gsd/{milestone}-{slug}',
|
||||
quick_branch_template: null,
|
||||
},
|
||||
workflow: {
|
||||
research: true,
|
||||
plan_check: true,
|
||||
verifier: true,
|
||||
nyquist_validation: true,
|
||||
auto_advance: false,
|
||||
node_repair: true,
|
||||
node_repair_budget: 2,
|
||||
ui_phase: true,
|
||||
ui_safety_gate: true,
|
||||
text_mode: false,
|
||||
},
|
||||
hooks: {
|
||||
context_warnings: true,
|
||||
},
|
||||
};
|
||||
|
||||
// Three-level deep merge: hardcoded <- userDefaults <- choices
|
||||
return {
|
||||
...hardcoded,
|
||||
...userDefaults,
|
||||
...choices,
|
||||
git: {
|
||||
...hardcoded.git,
|
||||
...(userDefaults.git || {}),
|
||||
...(choices.git || {}),
|
||||
},
|
||||
workflow: {
|
||||
...hardcoded.workflow,
|
||||
...(userDefaults.workflow || {}),
|
||||
...(choices.workflow || {}),
|
||||
},
|
||||
hooks: {
|
||||
...hardcoded.hooks,
|
||||
...(userDefaults.hooks || {}),
|
||||
...(choices.hooks || {}),
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Command: create a fully-materialized .planning/config.json for a new project.
|
||||
*
|
||||
* Accepts user-chosen settings as a JSON string (the keys the user explicitly
|
||||
* configured during /gsd:new-project). All remaining keys are filled from
|
||||
* hardcoded defaults and optional ~/.gsd/defaults.json.
|
||||
*
|
||||
* 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');
|
||||
|
||||
// Idempotent: don't overwrite existing config
|
||||
if (fs.existsSync(configPath)) {
|
||||
output({ created: false, reason: 'already_exists' }, raw, 'exists');
|
||||
return;
|
||||
}
|
||||
|
||||
// Parse user choices
|
||||
let userChoices = {};
|
||||
if (choicesJson && choicesJson.trim() !== '') {
|
||||
try {
|
||||
userChoices = JSON.parse(choicesJson);
|
||||
} catch (err) {
|
||||
error('Invalid JSON for config-new-project: ' + err.message);
|
||||
}
|
||||
}
|
||||
|
||||
// Ensure .planning directory exists
|
||||
try {
|
||||
if (!fs.existsSync(planningDir)) {
|
||||
fs.mkdirSync(planningDir, { recursive: true });
|
||||
}
|
||||
} catch (err) {
|
||||
error('Failed to create .planning directory: ' + err.message);
|
||||
}
|
||||
|
||||
const config = buildNewProjectConfig(userChoices);
|
||||
|
||||
try {
|
||||
fs.writeFileSync(configPath, JSON.stringify(config, null, 2), 'utf-8');
|
||||
output({ created: true, path: '.planning/config.json' }, raw, 'created');
|
||||
} catch (err) {
|
||||
error('Failed to write config.json: ' + err.message);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Ensures the config file exists (creates it if needed).
|
||||
*
|
||||
@@ -59,57 +209,10 @@ function ensureConfigFile(cwd) {
|
||||
return { created: false, reason: 'already_exists' };
|
||||
}
|
||||
|
||||
// Detect Brave Search API key availability
|
||||
const homedir = require('os').homedir();
|
||||
const braveKeyFile = path.join(homedir, '.gsd', 'brave_api_key');
|
||||
const hasBraveSearch = !!(process.env.BRAVE_API_KEY || fs.existsSync(braveKeyFile));
|
||||
|
||||
// Load user-level defaults from ~/.gsd/defaults.json if available
|
||||
const globalDefaultsPath = path.join(homedir, '.gsd', 'defaults.json');
|
||||
let userDefaults = {};
|
||||
try {
|
||||
if (fs.existsSync(globalDefaultsPath)) {
|
||||
userDefaults = JSON.parse(fs.readFileSync(globalDefaultsPath, 'utf-8'));
|
||||
// Migrate deprecated "depth" key to "granularity"
|
||||
if ('depth' in userDefaults && !('granularity' in userDefaults)) {
|
||||
const depthToGranularity = { quick: 'coarse', standard: 'standard', comprehensive: 'fine' };
|
||||
userDefaults.granularity = depthToGranularity[userDefaults.depth] || userDefaults.depth;
|
||||
delete userDefaults.depth;
|
||||
try {
|
||||
fs.writeFileSync(globalDefaultsPath, JSON.stringify(userDefaults, null, 2), 'utf-8');
|
||||
} catch { /* intentionally empty */ }
|
||||
}
|
||||
}
|
||||
} catch (err) {
|
||||
// Ignore malformed global defaults, fall back to hardcoded
|
||||
}
|
||||
|
||||
// Create default config (user-level defaults override hardcoded defaults)
|
||||
const hardcoded = {
|
||||
model_profile: 'balanced',
|
||||
commit_docs: true,
|
||||
search_gitignored: false,
|
||||
branching_strategy: 'none',
|
||||
phase_branch_template: 'gsd/phase-{phase}-{slug}',
|
||||
milestone_branch_template: 'gsd/{milestone}-{slug}',
|
||||
quick_branch_template: null,
|
||||
workflow: {
|
||||
research: true,
|
||||
plan_check: true,
|
||||
verifier: true,
|
||||
nyquist_validation: true,
|
||||
},
|
||||
parallelization: true,
|
||||
brave_search: hasBraveSearch,
|
||||
};
|
||||
const defaults = {
|
||||
...hardcoded,
|
||||
...userDefaults,
|
||||
workflow: { ...hardcoded.workflow, ...(userDefaults.workflow || {}) },
|
||||
};
|
||||
const config = buildNewProjectConfig({});
|
||||
|
||||
try {
|
||||
fs.writeFileSync(configPath, JSON.stringify(defaults, null, 2), 'utf-8');
|
||||
fs.writeFileSync(configPath, JSON.stringify(config, null, 2), 'utf-8');
|
||||
return { created: true, path: '.planning/config.json' };
|
||||
} catch (err) {
|
||||
error('Failed to create config.json: ' + err.message);
|
||||
@@ -306,4 +409,5 @@ module.exports = {
|
||||
cmdConfigSet,
|
||||
cmdConfigGet,
|
||||
cmdConfigSetModelProfile,
|
||||
cmdConfigNewProject,
|
||||
};
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
|
||||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
const { execSync, spawnSync } = require('child_process');
|
||||
const { execSync, execFileSync, spawnSync } = require('child_process');
|
||||
const { MODEL_PROFILES } = require('./model-profiles.cjs');
|
||||
|
||||
// ─── Path helpers ────────────────────────────────────────────────────────────
|
||||
@@ -14,28 +14,164 @@ function toPosixPath(p) {
|
||||
return p.split(path.sep).join('/');
|
||||
}
|
||||
|
||||
/**
|
||||
* Scan immediate child directories for separate git repos.
|
||||
* Returns a sorted array of directory names that have their own `.git`.
|
||||
* Excludes hidden directories and node_modules.
|
||||
*/
|
||||
function detectSubRepos(cwd) {
|
||||
const results = [];
|
||||
try {
|
||||
const entries = fs.readdirSync(cwd, { withFileTypes: true });
|
||||
for (const entry of entries) {
|
||||
if (!entry.isDirectory()) continue;
|
||||
if (entry.name.startsWith('.') || entry.name === 'node_modules') continue;
|
||||
const gitPath = path.join(cwd, entry.name, '.git');
|
||||
try {
|
||||
if (fs.existsSync(gitPath)) {
|
||||
results.push(entry.name);
|
||||
}
|
||||
} catch {}
|
||||
}
|
||||
} catch {}
|
||||
return results.sort();
|
||||
}
|
||||
|
||||
/**
|
||||
* Walk up from `startDir` to find the project root that owns `.planning/`.
|
||||
*
|
||||
* In multi-repo workspaces, Claude may open inside a sub-repo (e.g. `backend/`)
|
||||
* instead of the project root. This function prevents `.planning/` from being
|
||||
* created inside the sub-repo by locating the nearest ancestor that already has
|
||||
* a `.planning/` directory.
|
||||
*
|
||||
* Detection strategy (checked in order for each ancestor):
|
||||
* 1. Parent has `.planning/config.json` with `sub_repos` listing this directory
|
||||
* 2. Parent has `.planning/config.json` with `multiRepo: true` (legacy format)
|
||||
* 3. Parent has `.planning/` and current dir has its own `.git` (heuristic)
|
||||
*
|
||||
* Returns `startDir` unchanged when no ancestor `.planning/` is found (first-run
|
||||
* or single-repo projects).
|
||||
*/
|
||||
function findProjectRoot(startDir) {
|
||||
const resolved = path.resolve(startDir);
|
||||
const root = path.parse(resolved).root;
|
||||
const homedir = require('os').homedir();
|
||||
|
||||
// Check if startDir or any of its ancestors (up to but not including a
|
||||
// candidate project root) contains a .git directory. This handles both
|
||||
// `backend/` (direct sub-repo) and `backend/src/modules/` (nested inside).
|
||||
function isInsideGitRepo(candidateParent) {
|
||||
let d = resolved;
|
||||
while (d !== candidateParent && d !== root) {
|
||||
if (fs.existsSync(path.join(d, '.git'))) return true;
|
||||
d = path.dirname(d);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
let dir = resolved;
|
||||
while (dir !== root) {
|
||||
const parent = path.dirname(dir);
|
||||
if (parent === dir) break; // filesystem root
|
||||
if (parent === homedir) break; // never go above home
|
||||
|
||||
const parentPlanning = path.join(parent, '.planning');
|
||||
if (fs.existsSync(parentPlanning) && fs.statSync(parentPlanning).isDirectory()) {
|
||||
const configPath = path.join(parentPlanning, 'config.json');
|
||||
try {
|
||||
const config = JSON.parse(fs.readFileSync(configPath, 'utf-8'));
|
||||
const subRepos = config.sub_repos || config.planning?.sub_repos || [];
|
||||
|
||||
// Check explicit sub_repos list
|
||||
if (Array.isArray(subRepos) && subRepos.length > 0) {
|
||||
const relPath = path.relative(parent, resolved);
|
||||
const topSegment = relPath.split(path.sep)[0];
|
||||
if (subRepos.includes(topSegment)) {
|
||||
return parent;
|
||||
}
|
||||
}
|
||||
|
||||
// Check legacy multiRepo flag
|
||||
if (config.multiRepo === true && isInsideGitRepo(parent)) {
|
||||
return parent;
|
||||
}
|
||||
} catch {
|
||||
// config.json missing or malformed — fall back to .git heuristic
|
||||
}
|
||||
|
||||
// Heuristic: parent has .planning/ and we're inside a git repo
|
||||
if (isInsideGitRepo(parent)) {
|
||||
return parent;
|
||||
}
|
||||
}
|
||||
dir = parent;
|
||||
}
|
||||
return startDir;
|
||||
}
|
||||
|
||||
// ─── Output helpers ───────────────────────────────────────────────────────────
|
||||
|
||||
/**
|
||||
* Remove stale gsd-* temp files/dirs older than maxAgeMs (default: 5 minutes).
|
||||
* Runs opportunistically before each new temp file write to prevent unbounded accumulation.
|
||||
* @param {string} prefix - filename prefix to match (e.g., 'gsd-')
|
||||
* @param {object} opts
|
||||
* @param {number} opts.maxAgeMs - max age in ms before removal (default: 5 min)
|
||||
* @param {boolean} opts.dirsOnly - if true, only remove directories (default: false)
|
||||
*/
|
||||
function reapStaleTempFiles(prefix = 'gsd-', { maxAgeMs = 5 * 60 * 1000, dirsOnly = false } = {}) {
|
||||
try {
|
||||
const tmpDir = require('os').tmpdir();
|
||||
const now = Date.now();
|
||||
const entries = fs.readdirSync(tmpDir);
|
||||
for (const entry of entries) {
|
||||
if (!entry.startsWith(prefix)) continue;
|
||||
const fullPath = path.join(tmpDir, entry);
|
||||
try {
|
||||
const stat = fs.statSync(fullPath);
|
||||
if (now - stat.mtimeMs > maxAgeMs) {
|
||||
if (stat.isDirectory()) {
|
||||
fs.rmSync(fullPath, { recursive: true, force: true });
|
||||
} else if (!dirsOnly) {
|
||||
fs.unlinkSync(fullPath);
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
// File may have been removed between readdir and stat — ignore
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
// Non-critical — don't let cleanup failures break output
|
||||
}
|
||||
}
|
||||
|
||||
function output(result, raw, rawValue) {
|
||||
let data;
|
||||
if (raw && rawValue !== undefined) {
|
||||
process.stdout.write(String(rawValue));
|
||||
data = String(rawValue);
|
||||
} else {
|
||||
const json = JSON.stringify(result, null, 2);
|
||||
// Large payloads exceed Claude Code's Bash tool buffer (~50KB).
|
||||
// Write to tmpfile and output the path prefixed with @file: so callers can detect it.
|
||||
if (json.length > 50000) {
|
||||
reapStaleTempFiles();
|
||||
const tmpPath = path.join(require('os').tmpdir(), `gsd-${Date.now()}.json`);
|
||||
fs.writeFileSync(tmpPath, json, 'utf-8');
|
||||
process.stdout.write('@file:' + tmpPath);
|
||||
data = '@file:' + tmpPath;
|
||||
} else {
|
||||
process.stdout.write(json);
|
||||
data = json;
|
||||
}
|
||||
}
|
||||
process.exit(0);
|
||||
// process.stdout.write() is async when stdout is a pipe — process.exit()
|
||||
// can tear down the process before the reader consumes the buffer.
|
||||
// fs.writeSync(1, ...) blocks until the kernel accepts the bytes, and
|
||||
// skipping process.exit() lets the event loop drain naturally.
|
||||
fs.writeSync(1, data);
|
||||
}
|
||||
|
||||
function error(message) {
|
||||
process.stderr.write('Error: ' + message + '\n');
|
||||
fs.writeSync(2, 'Error: ' + message + '\n');
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
@@ -65,8 +201,11 @@ function loadConfig(cwd) {
|
||||
nyquist_validation: true,
|
||||
parallelization: true,
|
||||
brave_search: false,
|
||||
firecrawl: false,
|
||||
exa_search: false,
|
||||
text_mode: false, // when true, use plain-text numbered lists instead of AskUserQuestion menus
|
||||
resolve_model_ids: false, // when true, resolve aliases (opus/sonnet/haiku) to full model IDs
|
||||
sub_repos: [],
|
||||
resolve_model_ids: false, // false: return alias as-is | true: map to full Claude model ID | "omit": return '' (runtime uses its default)
|
||||
context_window: 200000, // default 200k; set to 1000000 for Opus/Sonnet 4.6 1M models
|
||||
phase_naming: 'sequential', // 'sequential' (default, auto-increment) or 'custom' (arbitrary string IDs)
|
||||
};
|
||||
@@ -83,6 +222,39 @@ function loadConfig(cwd) {
|
||||
try { fs.writeFileSync(configPath, JSON.stringify(parsed, null, 2), 'utf-8'); } catch { /* intentionally empty */ }
|
||||
}
|
||||
|
||||
// Auto-detect and sync sub_repos: scan for child directories with .git
|
||||
let configDirty = false;
|
||||
|
||||
// Migrate legacy "multiRepo: true" boolean → sub_repos array
|
||||
if (parsed.multiRepo === true && !parsed.sub_repos && !parsed.planning?.sub_repos) {
|
||||
const detected = detectSubRepos(cwd);
|
||||
if (detected.length > 0) {
|
||||
parsed.sub_repos = detected;
|
||||
if (!parsed.planning) parsed.planning = {};
|
||||
parsed.planning.commit_docs = false;
|
||||
delete parsed.multiRepo;
|
||||
configDirty = true;
|
||||
}
|
||||
}
|
||||
|
||||
// Keep sub_repos in sync with actual filesystem
|
||||
const currentSubRepos = parsed.sub_repos || parsed.planning?.sub_repos || [];
|
||||
if (Array.isArray(currentSubRepos) && currentSubRepos.length > 0) {
|
||||
const detected = detectSubRepos(cwd);
|
||||
if (detected.length > 0) {
|
||||
const sorted = [...currentSubRepos].sort();
|
||||
if (JSON.stringify(sorted) !== JSON.stringify(detected)) {
|
||||
parsed.sub_repos = detected;
|
||||
configDirty = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Persist sub_repos changes (migration or sync)
|
||||
if (configDirty) {
|
||||
try { fs.writeFileSync(configPath, JSON.stringify(parsed, null, 2), 'utf-8'); } catch {}
|
||||
}
|
||||
|
||||
const get = (key, nested) => {
|
||||
if (parsed[key] !== undefined) return parsed[key];
|
||||
if (nested && parsed[nested.section] && parsed[nested.section][nested.field] !== undefined) {
|
||||
@@ -100,7 +272,15 @@ function loadConfig(cwd) {
|
||||
|
||||
return {
|
||||
model_profile: get('model_profile') ?? defaults.model_profile,
|
||||
commit_docs: get('commit_docs', { section: 'planning', field: 'commit_docs' }) ?? defaults.commit_docs,
|
||||
commit_docs: (() => {
|
||||
const explicit = get('commit_docs', { section: 'planning', field: 'commit_docs' });
|
||||
// If explicitly set in config, respect the user's choice
|
||||
if (explicit !== undefined) return explicit;
|
||||
// Auto-detection: when no explicit value and .planning/ is gitignored,
|
||||
// default to false instead of true
|
||||
if (isGitIgnored(cwd, '.planning/')) return false;
|
||||
return defaults.commit_docs;
|
||||
})(),
|
||||
search_gitignored: get('search_gitignored', { section: 'planning', field: 'search_gitignored' }) ?? defaults.search_gitignored,
|
||||
branching_strategy: get('branching_strategy', { section: 'git', field: 'branching_strategy' }) ?? defaults.branching_strategy,
|
||||
phase_branch_template: get('phase_branch_template', { section: 'git', field: 'phase_branch_template' }) ?? defaults.phase_branch_template,
|
||||
@@ -112,7 +292,10 @@ function loadConfig(cwd) {
|
||||
nyquist_validation: get('nyquist_validation', { section: 'workflow', field: 'nyquist_validation' }) ?? defaults.nyquist_validation,
|
||||
parallelization,
|
||||
brave_search: get('brave_search') ?? defaults.brave_search,
|
||||
firecrawl: get('firecrawl') ?? defaults.firecrawl,
|
||||
exa_search: get('exa_search') ?? defaults.exa_search,
|
||||
text_mode: get('text_mode', { section: 'workflow', field: 'text_mode' }) ?? defaults.text_mode,
|
||||
sub_repos: get('sub_repos', { section: 'planning', field: 'sub_repos' }) ?? defaults.sub_repos,
|
||||
resolve_model_ids: get('resolve_model_ids') ?? defaults.resolve_model_ids,
|
||||
context_window: get('context_window') ?? defaults.context_window,
|
||||
phase_naming: get('phase_naming') ?? defaults.phase_naming,
|
||||
@@ -131,7 +314,9 @@ function isGitIgnored(cwd, targetPath) {
|
||||
// Without it, git check-ignore returns "not ignored" for tracked files even when
|
||||
// .gitignore explicitly lists them — a common source of confusion when .planning/
|
||||
// was committed before being added to .gitignore.
|
||||
execSync('git check-ignore -q --no-index -- ' + targetPath.replace(/[^a-zA-Z0-9._\-/]/g, ''), {
|
||||
// Use execFileSync (array args) to prevent shell interpretation of special characters
|
||||
// in file paths — avoids command injection via crafted path names.
|
||||
execFileSync('git', ['check-ignore', '-q', '--no-index', '--', targetPath], {
|
||||
cwd,
|
||||
stdio: 'pipe',
|
||||
});
|
||||
@@ -260,6 +445,84 @@ function execGit(cwd, args) {
|
||||
|
||||
// ─── Common path helpers ──────────────────────────────────────────────────────
|
||||
|
||||
/**
|
||||
* Resolve the main worktree root when running inside a git worktree.
|
||||
* In a linked worktree, .planning/ lives in the main worktree, not in the linked one.
|
||||
* Returns the main worktree path, or cwd if not in a worktree.
|
||||
*/
|
||||
function resolveWorktreeRoot(cwd) {
|
||||
// Check if we're in a linked worktree
|
||||
const gitDir = execGit(cwd, ['rev-parse', '--git-dir']);
|
||||
const commonDir = execGit(cwd, ['rev-parse', '--git-common-dir']);
|
||||
|
||||
if (gitDir.exitCode !== 0 || commonDir.exitCode !== 0) return cwd;
|
||||
|
||||
// In a linked worktree, .git is a file pointing to .git/worktrees/<name>
|
||||
// and git-common-dir points to the main repo's .git directory
|
||||
const gitDirResolved = path.resolve(cwd, gitDir.stdout);
|
||||
const commonDirResolved = path.resolve(cwd, commonDir.stdout);
|
||||
|
||||
if (gitDirResolved !== commonDirResolved) {
|
||||
// We're in a linked worktree — resolve main worktree root
|
||||
// The common dir is the main repo's .git, so its parent is the main worktree root
|
||||
return path.dirname(commonDirResolved);
|
||||
}
|
||||
|
||||
return cwd;
|
||||
}
|
||||
|
||||
/**
|
||||
* Acquire a file-based lock for .planning/ writes.
|
||||
* Prevents concurrent worktrees from corrupting shared planning files.
|
||||
* Lock is auto-released after the callback completes.
|
||||
*/
|
||||
function withPlanningLock(cwd, fn) {
|
||||
const lockPath = path.join(planningDir(cwd), '.lock');
|
||||
const lockTimeout = 10000; // 10 seconds
|
||||
const retryDelay = 100;
|
||||
const start = Date.now();
|
||||
|
||||
// Ensure .planning/ exists
|
||||
try { fs.mkdirSync(planningDir(cwd), { recursive: true }); } catch { /* ok */ }
|
||||
|
||||
while (Date.now() - start < lockTimeout) {
|
||||
try {
|
||||
// Atomic create — fails if file exists
|
||||
fs.writeFileSync(lockPath, JSON.stringify({
|
||||
pid: process.pid,
|
||||
cwd,
|
||||
acquired: new Date().toISOString(),
|
||||
}), { flag: 'wx' });
|
||||
|
||||
// Lock acquired — run the function
|
||||
try {
|
||||
return fn();
|
||||
} finally {
|
||||
try { fs.unlinkSync(lockPath); } catch { /* already released */ }
|
||||
}
|
||||
} catch (err) {
|
||||
if (err.code === 'EEXIST') {
|
||||
// Lock exists — check if stale (>30s old)
|
||||
try {
|
||||
const stat = fs.statSync(lockPath);
|
||||
if (Date.now() - stat.mtimeMs > 30000) {
|
||||
fs.unlinkSync(lockPath);
|
||||
continue; // retry
|
||||
}
|
||||
} catch { continue; }
|
||||
|
||||
// Wait and retry
|
||||
spawnSync('sleep', ['0.1'], { stdio: 'ignore' });
|
||||
continue;
|
||||
}
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
// Timeout — force acquire (stale lock recovery)
|
||||
try { fs.unlinkSync(lockPath); } catch { /* ok */ }
|
||||
return fn();
|
||||
}
|
||||
|
||||
/** Get the .planning directory path */
|
||||
function planningDir(cwd) {
|
||||
return path.join(cwd, '.planning');
|
||||
@@ -355,6 +618,7 @@ function searchPhaseInDir(baseDir, relBase, normalized) {
|
||||
const hasResearch = phaseFiles.some(f => f.endsWith('-RESEARCH.md') || f === 'RESEARCH.md');
|
||||
const hasContext = phaseFiles.some(f => f.endsWith('-CONTEXT.md') || f === 'CONTEXT.md');
|
||||
const hasVerification = phaseFiles.some(f => f.endsWith('-VERIFICATION.md') || f === 'VERIFICATION.md');
|
||||
const hasReviews = phaseFiles.some(f => f.endsWith('-REVIEWS.md') || f === 'REVIEWS.md');
|
||||
|
||||
const completedPlanIds = new Set(
|
||||
summaries.map(s => s.replace('-SUMMARY.md', '').replace('SUMMARY.md', ''))
|
||||
@@ -376,6 +640,7 @@ function searchPhaseInDir(baseDir, relBase, normalized) {
|
||||
has_research: hasResearch,
|
||||
has_context: hasContext,
|
||||
has_verification: hasVerification,
|
||||
has_reviews: hasReviews,
|
||||
};
|
||||
} catch {
|
||||
return null;
|
||||
@@ -620,12 +885,20 @@ const MODEL_ALIAS_MAP = {
|
||||
function resolveModelInternal(cwd, agentType) {
|
||||
const config = loadConfig(cwd);
|
||||
|
||||
// Check per-agent override first
|
||||
// Check per-agent override first — always respected regardless of resolve_model_ids.
|
||||
// Users who set fully-qualified model IDs (e.g., "openai/gpt-5.4") get exactly that.
|
||||
const override = config.model_overrides?.[agentType];
|
||||
if (override) {
|
||||
return override;
|
||||
}
|
||||
|
||||
// resolve_model_ids: "omit" — return empty string so the runtime uses its configured
|
||||
// default model. For non-Claude runtimes (OpenCode, Codex, etc.) that don't recognize
|
||||
// Claude aliases (opus/sonnet/haiku/inherit). Set automatically during install. See #1156.
|
||||
if (config.resolve_model_ids === 'omit') {
|
||||
return '';
|
||||
}
|
||||
|
||||
// Fall back to profile lookup
|
||||
const profile = String(config.model_profile || 'balanced').toLowerCase();
|
||||
const agentModels = MODEL_PROFILES[agentType];
|
||||
@@ -633,8 +906,8 @@ function resolveModelInternal(cwd, agentType) {
|
||||
if (profile === 'inherit') return 'inherit';
|
||||
const alias = agentModels[profile] || agentModels['balanced'] || 'sonnet';
|
||||
|
||||
// If resolve_model_ids is true, map alias to full model ID
|
||||
// This prevents 404s when the Task tool passes aliases directly to the API
|
||||
// resolve_model_ids: true — map alias to full Claude model ID
|
||||
// Prevents 404s when the Task tool passes aliases directly to the API
|
||||
if (config.resolve_model_ids) {
|
||||
return MODEL_ALIAS_MAP[alias] || alias;
|
||||
}
|
||||
@@ -778,6 +1051,11 @@ module.exports = {
|
||||
replaceInCurrentMilestone,
|
||||
toPosixPath,
|
||||
extractOneLinerFromBody,
|
||||
resolveWorktreeRoot,
|
||||
withPlanningLock,
|
||||
findProjectRoot,
|
||||
detectSubRepos,
|
||||
reapStaleTempFiles,
|
||||
MODEL_ALIAS_MAP,
|
||||
planningDir,
|
||||
planningPaths,
|
||||
|
||||
@@ -236,6 +236,8 @@ const FRONTMATTER_SCHEMAS = {
|
||||
|
||||
function cmdFrontmatterGet(cwd, filePath, field, raw) {
|
||||
if (!filePath) { error('file path required'); }
|
||||
// Path traversal guard: reject null bytes
|
||||
if (filePath.includes('\0')) { error('file path contains null bytes'); }
|
||||
const fullPath = path.isAbsolute(filePath) ? filePath : path.join(cwd, filePath);
|
||||
const content = safeReadFile(fullPath);
|
||||
if (!content) { output({ error: 'File not found', path: filePath }, raw); return; }
|
||||
@@ -251,6 +253,8 @@ function cmdFrontmatterGet(cwd, filePath, field, raw) {
|
||||
|
||||
function cmdFrontmatterSet(cwd, filePath, field, value, raw) {
|
||||
if (!filePath || !field || value === undefined) { error('file, field, and value required'); }
|
||||
// Path traversal guard: reject null bytes
|
||||
if (filePath.includes('\0')) { error('file path contains null bytes'); }
|
||||
const fullPath = path.isAbsolute(filePath) ? filePath : path.join(cwd, filePath);
|
||||
if (!fs.existsSync(fullPath)) { output({ error: 'File not found', path: filePath }, raw); return; }
|
||||
const content = fs.readFileSync(fullPath, 'utf-8');
|
||||
|
||||
@@ -24,16 +24,45 @@ function getLatestCompletedMilestone(cwd) {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Inject `project_root` into an init result object.
|
||||
* Workflows use this to prefix `.planning/` paths correctly when Claude's CWD
|
||||
* differs from the project root (e.g., inside a sub-repo).
|
||||
*/
|
||||
function withProjectRoot(cwd, result) {
|
||||
result.project_root = cwd;
|
||||
return result;
|
||||
}
|
||||
|
||||
function cmdInitExecutePhase(cwd, phase, raw) {
|
||||
if (!phase) {
|
||||
error('phase required for init execute-phase');
|
||||
}
|
||||
|
||||
const config = loadConfig(cwd);
|
||||
const phaseInfo = findPhaseInternal(cwd, phase);
|
||||
let phaseInfo = findPhaseInternal(cwd, phase);
|
||||
const milestone = getMilestoneInfo(cwd);
|
||||
|
||||
const roadmapPhase = getRoadmapPhaseInternal(cwd, phase);
|
||||
|
||||
// Fallback to ROADMAP.md if no phase directory exists yet
|
||||
if (!phaseInfo && roadmapPhase?.found) {
|
||||
const phaseName = roadmapPhase.phase_name;
|
||||
phaseInfo = {
|
||||
found: true,
|
||||
directory: null,
|
||||
phase_number: roadmapPhase.phase_number,
|
||||
phase_name: phaseName,
|
||||
phase_slug: phaseName ? phaseName.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-+|-+$/g, '') : null,
|
||||
plans: [],
|
||||
summaries: [],
|
||||
incomplete_plans: [],
|
||||
has_research: false,
|
||||
has_context: false,
|
||||
has_verification: false,
|
||||
has_reviews: false,
|
||||
};
|
||||
}
|
||||
const reqMatch = roadmapPhase?.section?.match(/^\*\*Requirements\*\*:[^\S\n]*([^\n]*)$/m);
|
||||
const reqExtracted = reqMatch
|
||||
? reqMatch[1].replace(/[\[\]]/g, '').split(',').map(s => s.trim()).filter(Boolean).join(', ')
|
||||
@@ -47,6 +76,7 @@ function cmdInitExecutePhase(cwd, phase, raw) {
|
||||
|
||||
// Config flags
|
||||
commit_docs: config.commit_docs,
|
||||
sub_repos: config.sub_repos,
|
||||
parallelization: config.parallelization,
|
||||
context_window: config.context_window,
|
||||
branching_strategy: config.branching_strategy,
|
||||
@@ -95,7 +125,7 @@ function cmdInitExecutePhase(cwd, phase, raw) {
|
||||
config_path: '.planning/config.json',
|
||||
};
|
||||
|
||||
output(result, raw);
|
||||
output(withProjectRoot(cwd, result), raw);
|
||||
}
|
||||
|
||||
function cmdInitPlanPhase(cwd, phase, raw) {
|
||||
@@ -104,9 +134,28 @@ function cmdInitPlanPhase(cwd, phase, raw) {
|
||||
}
|
||||
|
||||
const config = loadConfig(cwd);
|
||||
const phaseInfo = findPhaseInternal(cwd, phase);
|
||||
let phaseInfo = findPhaseInternal(cwd, phase);
|
||||
|
||||
const roadmapPhase = getRoadmapPhaseInternal(cwd, phase);
|
||||
|
||||
// Fallback to ROADMAP.md if no phase directory exists yet
|
||||
if (!phaseInfo && roadmapPhase?.found) {
|
||||
const phaseName = roadmapPhase.phase_name;
|
||||
phaseInfo = {
|
||||
found: true,
|
||||
directory: null,
|
||||
phase_number: roadmapPhase.phase_number,
|
||||
phase_name: phaseName,
|
||||
phase_slug: phaseName ? phaseName.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-+|-+$/g, '') : null,
|
||||
plans: [],
|
||||
summaries: [],
|
||||
incomplete_plans: [],
|
||||
has_research: false,
|
||||
has_context: false,
|
||||
has_verification: false,
|
||||
has_reviews: false,
|
||||
};
|
||||
}
|
||||
const reqMatch = roadmapPhase?.section?.match(/^\*\*Requirements\*\*:[^\S\n]*([^\n]*)$/m);
|
||||
const reqExtracted = reqMatch
|
||||
? reqMatch[1].replace(/[\[\]]/g, '').split(',').map(s => s.trim()).filter(Boolean).join(', ')
|
||||
@@ -137,6 +186,7 @@ function cmdInitPlanPhase(cwd, phase, raw) {
|
||||
// Existing artifacts
|
||||
has_research: phaseInfo?.has_research || false,
|
||||
has_context: phaseInfo?.has_context || false,
|
||||
has_reviews: phaseInfo?.has_reviews || false,
|
||||
has_plans: (phaseInfo?.plans?.length || 0) > 0,
|
||||
plan_count: phaseInfo?.plans?.length || 0,
|
||||
|
||||
@@ -171,10 +221,14 @@ function cmdInitPlanPhase(cwd, phase, raw) {
|
||||
if (uatFile) {
|
||||
result.uat_path = toPosixPath(path.join(phaseInfo.directory, uatFile));
|
||||
}
|
||||
const reviewsFile = files.find(f => f.endsWith('-REVIEWS.md') || f === 'REVIEWS.md');
|
||||
if (reviewsFile) {
|
||||
result.reviews_path = toPosixPath(path.join(phaseInfo.directory, reviewsFile));
|
||||
}
|
||||
} catch { /* intentionally empty */ }
|
||||
}
|
||||
|
||||
output(result, raw);
|
||||
output(withProjectRoot(cwd, result), raw);
|
||||
}
|
||||
|
||||
function cmdInitNewProject(cwd, raw) {
|
||||
@@ -185,6 +239,14 @@ function cmdInitNewProject(cwd, raw) {
|
||||
const braveKeyFile = path.join(homedir, '.gsd', 'brave_api_key');
|
||||
const hasBraveSearch = !!(process.env.BRAVE_API_KEY || fs.existsSync(braveKeyFile));
|
||||
|
||||
// Detect Firecrawl API key availability
|
||||
const firecrawlKeyFile = path.join(homedir, '.gsd', 'firecrawl_api_key');
|
||||
const hasFirecrawl = !!(process.env.FIRECRAWL_API_KEY || fs.existsSync(firecrawlKeyFile));
|
||||
|
||||
// Detect Exa API key availability
|
||||
const exaKeyFile = path.join(homedir, '.gsd', 'exa_api_key');
|
||||
const hasExaSearch = !!(process.env.EXA_API_KEY || fs.existsSync(exaKeyFile));
|
||||
|
||||
// Detect existing code (cross-platform — no Unix `find` dependency)
|
||||
let hasCode = false;
|
||||
let hasPackageFile = false;
|
||||
@@ -237,12 +299,14 @@ function cmdInitNewProject(cwd, raw) {
|
||||
|
||||
// Enhanced search
|
||||
brave_search_available: hasBraveSearch,
|
||||
firecrawl_available: hasFirecrawl,
|
||||
exa_search_available: hasExaSearch,
|
||||
|
||||
// File paths
|
||||
project_path: '.planning/PROJECT.md',
|
||||
};
|
||||
|
||||
output(result, raw);
|
||||
output(withProjectRoot(cwd, result), raw);
|
||||
}
|
||||
|
||||
function cmdInitNewMilestone(cwd, raw) {
|
||||
@@ -289,7 +353,7 @@ function cmdInitNewMilestone(cwd, raw) {
|
||||
state_path: '.planning/STATE.md',
|
||||
};
|
||||
|
||||
output(result, raw);
|
||||
output(withProjectRoot(cwd, result), raw);
|
||||
}
|
||||
|
||||
function cmdInitQuick(cwd, description, raw) {
|
||||
@@ -347,7 +411,7 @@ function cmdInitQuick(cwd, description, raw) {
|
||||
|
||||
};
|
||||
|
||||
output(result, raw);
|
||||
output(withProjectRoot(cwd, result), raw);
|
||||
}
|
||||
|
||||
function cmdInitResume(cwd, raw) {
|
||||
@@ -379,7 +443,7 @@ function cmdInitResume(cwd, raw) {
|
||||
commit_docs: config.commit_docs,
|
||||
};
|
||||
|
||||
output(result, raw);
|
||||
output(withProjectRoot(cwd, result), raw);
|
||||
}
|
||||
|
||||
function cmdInitVerifyWork(cwd, phase, raw) {
|
||||
@@ -388,7 +452,28 @@ function cmdInitVerifyWork(cwd, phase, raw) {
|
||||
}
|
||||
|
||||
const config = loadConfig(cwd);
|
||||
const phaseInfo = findPhaseInternal(cwd, phase);
|
||||
let phaseInfo = findPhaseInternal(cwd, phase);
|
||||
|
||||
// Fallback to ROADMAP.md if no phase directory exists yet
|
||||
if (!phaseInfo) {
|
||||
const roadmapPhase = getRoadmapPhaseInternal(cwd, phase);
|
||||
if (roadmapPhase?.found) {
|
||||
const phaseName = roadmapPhase.phase_name;
|
||||
phaseInfo = {
|
||||
found: true,
|
||||
directory: null,
|
||||
phase_number: roadmapPhase.phase_number,
|
||||
phase_name: phaseName,
|
||||
phase_slug: phaseName ? phaseName.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-+|-+$/g, '') : null,
|
||||
plans: [],
|
||||
summaries: [],
|
||||
incomplete_plans: [],
|
||||
has_research: false,
|
||||
has_context: false,
|
||||
has_verification: false,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
const result = {
|
||||
// Models
|
||||
@@ -408,7 +493,7 @@ function cmdInitVerifyWork(cwd, phase, raw) {
|
||||
has_verification: phaseInfo?.has_verification || false,
|
||||
};
|
||||
|
||||
output(result, raw);
|
||||
output(withProjectRoot(cwd, result), raw);
|
||||
}
|
||||
|
||||
function cmdInitPhaseOp(cwd, phase, raw) {
|
||||
@@ -463,6 +548,8 @@ function cmdInitPhaseOp(cwd, phase, raw) {
|
||||
// Config
|
||||
commit_docs: config.commit_docs,
|
||||
brave_search: config.brave_search,
|
||||
firecrawl: config.firecrawl,
|
||||
exa_search: config.exa_search,
|
||||
|
||||
// Phase info
|
||||
phase_found: !!phaseInfo,
|
||||
@@ -477,6 +564,7 @@ function cmdInitPhaseOp(cwd, phase, raw) {
|
||||
has_context: phaseInfo?.has_context || false,
|
||||
has_plans: (phaseInfo?.plans?.length || 0) > 0,
|
||||
has_verification: phaseInfo?.has_verification || false,
|
||||
has_reviews: phaseInfo?.has_reviews || false,
|
||||
plan_count: phaseInfo?.plans?.length || 0,
|
||||
|
||||
// File existence
|
||||
@@ -509,10 +597,14 @@ function cmdInitPhaseOp(cwd, phase, raw) {
|
||||
if (uatFile) {
|
||||
result.uat_path = toPosixPath(path.join(phaseInfo.directory, uatFile));
|
||||
}
|
||||
const reviewsFile = files.find(f => f.endsWith('-REVIEWS.md') || f === 'REVIEWS.md');
|
||||
if (reviewsFile) {
|
||||
result.reviews_path = toPosixPath(path.join(phaseInfo.directory, reviewsFile));
|
||||
}
|
||||
} catch { /* intentionally empty */ }
|
||||
}
|
||||
|
||||
output(result, raw);
|
||||
output(withProjectRoot(cwd, result), raw);
|
||||
}
|
||||
|
||||
function cmdInitTodos(cwd, area, raw) {
|
||||
@@ -571,7 +663,7 @@ function cmdInitTodos(cwd, area, raw) {
|
||||
pending_dir_exists: pathExistsInternal(cwd, '.planning/todos/pending'),
|
||||
};
|
||||
|
||||
output(result, raw);
|
||||
output(withProjectRoot(cwd, result), raw);
|
||||
}
|
||||
|
||||
function cmdInitMilestoneOp(cwd, raw) {
|
||||
@@ -632,7 +724,7 @@ function cmdInitMilestoneOp(cwd, raw) {
|
||||
phases_dir_exists: pathExistsInternal(cwd, '.planning/phases'),
|
||||
};
|
||||
|
||||
output(result, raw);
|
||||
output(withProjectRoot(cwd, result), raw);
|
||||
}
|
||||
|
||||
function cmdInitMapCodebase(cwd, raw) {
|
||||
@@ -666,7 +758,7 @@ function cmdInitMapCodebase(cwd, raw) {
|
||||
codebase_dir_exists: pathExistsInternal(cwd, '.planning/codebase'),
|
||||
};
|
||||
|
||||
output(result, raw);
|
||||
output(withProjectRoot(cwd, result), raw);
|
||||
}
|
||||
|
||||
function cmdInitManager(cwd, raw) {
|
||||
@@ -1059,6 +1151,165 @@ function cmdInitProgress(cwd, raw) {
|
||||
config_path: '.planning/config.json',
|
||||
};
|
||||
|
||||
output(withProjectRoot(cwd, result), raw);
|
||||
}
|
||||
|
||||
/**
|
||||
* Detect child git repos in a directory (one level deep).
|
||||
* Returns array of { name, path, has_uncommitted } objects.
|
||||
*/
|
||||
function detectChildRepos(dir) {
|
||||
const repos = [];
|
||||
let entries;
|
||||
try { entries = fs.readdirSync(dir, { withFileTypes: true }); } catch { return repos; }
|
||||
for (const entry of entries) {
|
||||
if (!entry.isDirectory()) continue;
|
||||
if (entry.name.startsWith('.')) continue;
|
||||
const fullPath = path.join(dir, entry.name);
|
||||
const gitDir = path.join(fullPath, '.git');
|
||||
if (fs.existsSync(gitDir)) {
|
||||
let hasUncommitted = false;
|
||||
try {
|
||||
const status = execSync('git status --porcelain', { cwd: fullPath, encoding: 'utf8', timeout: 5000 });
|
||||
hasUncommitted = status.trim().length > 0;
|
||||
} catch { /* best-effort */ }
|
||||
repos.push({ name: entry.name, path: fullPath, has_uncommitted: hasUncommitted });
|
||||
}
|
||||
}
|
||||
return repos;
|
||||
}
|
||||
|
||||
function cmdInitNewWorkspace(cwd, raw) {
|
||||
const homedir = process.env.HOME || require('os').homedir();
|
||||
const defaultBase = path.join(homedir, 'gsd-workspaces');
|
||||
|
||||
// Detect child git repos for interactive selection
|
||||
const childRepos = detectChildRepos(cwd);
|
||||
|
||||
// Check if git worktree is available
|
||||
let worktreeAvailable = false;
|
||||
try {
|
||||
execSync('git --version', { encoding: 'utf8', timeout: 5000, stdio: 'pipe' });
|
||||
worktreeAvailable = true;
|
||||
} catch { /* no git at all */ }
|
||||
|
||||
const result = {
|
||||
default_workspace_base: defaultBase,
|
||||
child_repos: childRepos,
|
||||
child_repo_count: childRepos.length,
|
||||
worktree_available: worktreeAvailable,
|
||||
is_git_repo: pathExistsInternal(cwd, '.git'),
|
||||
cwd_repo_name: path.basename(cwd),
|
||||
};
|
||||
|
||||
output(withProjectRoot(cwd, result), raw);
|
||||
}
|
||||
|
||||
function cmdInitListWorkspaces(cwd, raw) {
|
||||
const homedir = process.env.HOME || require('os').homedir();
|
||||
const defaultBase = path.join(homedir, 'gsd-workspaces');
|
||||
|
||||
const workspaces = [];
|
||||
if (fs.existsSync(defaultBase)) {
|
||||
let entries;
|
||||
try { entries = fs.readdirSync(defaultBase, { withFileTypes: true }); } catch { entries = []; }
|
||||
for (const entry of entries) {
|
||||
if (!entry.isDirectory()) continue;
|
||||
const wsPath = path.join(defaultBase, entry.name);
|
||||
const manifestPath = path.join(wsPath, 'WORKSPACE.md');
|
||||
if (!fs.existsSync(manifestPath)) continue;
|
||||
|
||||
let repoCount = 0;
|
||||
let hasProject = false;
|
||||
let strategy = 'unknown';
|
||||
try {
|
||||
const manifest = fs.readFileSync(manifestPath, 'utf8');
|
||||
const strategyMatch = manifest.match(/^Strategy:\s*(.+)$/m);
|
||||
if (strategyMatch) strategy = strategyMatch[1].trim();
|
||||
// Count table rows (lines starting with |, excluding header and separator)
|
||||
const tableRows = manifest.split('\n').filter(l => l.match(/^\|\s*\w/) && !l.includes('Repo') && !l.includes('---'));
|
||||
repoCount = tableRows.length;
|
||||
} catch { /* best-effort */ }
|
||||
hasProject = fs.existsSync(path.join(wsPath, '.planning', 'PROJECT.md'));
|
||||
|
||||
workspaces.push({
|
||||
name: entry.name,
|
||||
path: wsPath,
|
||||
repo_count: repoCount,
|
||||
strategy,
|
||||
has_project: hasProject,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
const result = {
|
||||
workspace_base: defaultBase,
|
||||
workspaces,
|
||||
workspace_count: workspaces.length,
|
||||
};
|
||||
|
||||
output(result, raw);
|
||||
}
|
||||
|
||||
function cmdInitRemoveWorkspace(cwd, name, raw) {
|
||||
const homedir = process.env.HOME || require('os').homedir();
|
||||
const defaultBase = path.join(homedir, 'gsd-workspaces');
|
||||
|
||||
if (!name) {
|
||||
error('workspace name required for init remove-workspace');
|
||||
}
|
||||
|
||||
const wsPath = path.join(defaultBase, name);
|
||||
const manifestPath = path.join(wsPath, 'WORKSPACE.md');
|
||||
|
||||
if (!fs.existsSync(wsPath)) {
|
||||
error(`Workspace not found: ${wsPath}`);
|
||||
}
|
||||
|
||||
// Parse manifest for repo info
|
||||
const repos = [];
|
||||
let strategy = 'unknown';
|
||||
if (fs.existsSync(manifestPath)) {
|
||||
try {
|
||||
const manifest = fs.readFileSync(manifestPath, 'utf8');
|
||||
const strategyMatch = manifest.match(/^Strategy:\s*(.+)$/m);
|
||||
if (strategyMatch) strategy = strategyMatch[1].trim();
|
||||
|
||||
// Parse table rows for repo names and source paths
|
||||
const lines = manifest.split('\n');
|
||||
for (const line of lines) {
|
||||
const match = line.match(/^\|\s*(\S+)\s*\|\s*(\S+)\s*\|\s*(\S+)\s*\|\s*(\S+)\s*\|$/);
|
||||
if (match && match[1] !== 'Repo' && !match[1].includes('---')) {
|
||||
repos.push({ name: match[1], source: match[2], branch: match[3], strategy: match[4] });
|
||||
}
|
||||
}
|
||||
} catch { /* best-effort */ }
|
||||
}
|
||||
|
||||
// Check for uncommitted changes in workspace repos
|
||||
const dirtyRepos = [];
|
||||
for (const repo of repos) {
|
||||
const repoPath = path.join(wsPath, repo.name);
|
||||
if (!fs.existsSync(repoPath)) continue;
|
||||
try {
|
||||
const status = execSync('git status --porcelain', { cwd: repoPath, encoding: 'utf8', timeout: 5000, stdio: 'pipe' });
|
||||
if (status.trim().length > 0) {
|
||||
dirtyRepos.push(repo.name);
|
||||
}
|
||||
} catch { /* best-effort */ }
|
||||
}
|
||||
|
||||
const result = {
|
||||
workspace_name: name,
|
||||
workspace_path: wsPath,
|
||||
has_manifest: fs.existsSync(manifestPath),
|
||||
strategy,
|
||||
repos,
|
||||
repo_count: repos.length,
|
||||
dirty_repos: dirtyRepos,
|
||||
has_dirty_repos: dirtyRepos.length > 0,
|
||||
};
|
||||
|
||||
output(result, raw);
|
||||
}
|
||||
|
||||
@@ -1076,4 +1327,8 @@ module.exports = {
|
||||
cmdInitMapCodebase,
|
||||
cmdInitProgress,
|
||||
cmdInitManager,
|
||||
cmdInitNewWorkspace,
|
||||
cmdInitListWorkspaces,
|
||||
cmdInitRemoveWorkspace,
|
||||
detectChildRepos,
|
||||
};
|
||||
|
||||
@@ -6,7 +6,7 @@ const fs = require('fs');
|
||||
const path = require('path');
|
||||
const { escapeRegex, getMilestonePhaseFilter, extractOneLinerFromBody, normalizeMd, planningPaths, output, error } = require('./core.cjs');
|
||||
const { extractFrontmatter } = require('./frontmatter.cjs');
|
||||
const { writeStateMd } = require('./state.cjs');
|
||||
const { writeStateMd, stateReplaceFieldWithFallback } = require('./state.cjs');
|
||||
|
||||
function cmdRequirementsMarkComplete(cwd, reqIdsRaw, raw) {
|
||||
if (!reqIdsRaw || reqIdsRaw.length === 0) {
|
||||
@@ -194,21 +194,15 @@ function cmdMilestoneComplete(cwd, version, options, raw) {
|
||||
fs.writeFileSync(milestonesPath, normalizeMd(`# Milestones\n\n${milestoneEntry}`), 'utf-8');
|
||||
}
|
||||
|
||||
// Update STATE.md
|
||||
// Update STATE.md — use shared helpers that handle both **bold:** and plain Field: formats
|
||||
if (fs.existsSync(statePath)) {
|
||||
let stateContent = fs.readFileSync(statePath, 'utf-8');
|
||||
stateContent = stateContent.replace(
|
||||
/(\*\*Status:\*\*\s*).*/,
|
||||
`$1${version} milestone complete`
|
||||
);
|
||||
stateContent = stateContent.replace(
|
||||
/(\*\*Last Activity:\*\*\s*).*/,
|
||||
`$1${today}`
|
||||
);
|
||||
stateContent = stateContent.replace(
|
||||
/(\*\*Last Activity Description:\*\*\s*).*/,
|
||||
`$1${version} milestone completed and archived`
|
||||
);
|
||||
|
||||
stateContent = stateReplaceFieldWithFallback(stateContent, 'Status', null, `${version} milestone complete`);
|
||||
stateContent = stateReplaceFieldWithFallback(stateContent, 'Last Activity', 'Last activity', today);
|
||||
stateContent = stateReplaceFieldWithFallback(stateContent, 'Last Activity Description', null,
|
||||
`${version} milestone completed and archived`);
|
||||
|
||||
writeStateMd(statePath, stateContent, cwd);
|
||||
}
|
||||
|
||||
|
||||
@@ -6,7 +6,7 @@ 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 { extractFrontmatter } = require('./frontmatter.cjs');
|
||||
const { writeStateMd } = require('./state.cjs');
|
||||
const { writeStateMd, stateExtractField, stateReplaceField, stateReplaceFieldWithFallback } = require('./state.cjs');
|
||||
|
||||
function cmdPhasesList(cwd, options, raw) {
|
||||
const phasesDir = path.join(cwd, '.planning', 'phases');
|
||||
@@ -685,12 +685,11 @@ function cmdPhaseRemove(cwd, targetPhase, options, raw) {
|
||||
const statePath = path.join(cwd, '.planning', 'STATE.md');
|
||||
if (fs.existsSync(statePath)) {
|
||||
let stateContent = fs.readFileSync(statePath, 'utf-8');
|
||||
// Update "Total Phases" field
|
||||
const totalPattern = /(\*\*Total Phases:\*\*\s*)(\d+)/;
|
||||
const totalMatch = stateContent.match(totalPattern);
|
||||
if (totalMatch) {
|
||||
const oldTotal = parseInt(totalMatch[2], 10);
|
||||
stateContent = stateContent.replace(totalPattern, `$1${oldTotal - 1}`);
|
||||
// Update "Total Phases" field — supports both bold and plain formats
|
||||
const totalRaw = stateExtractField(stateContent, 'Total Phases');
|
||||
if (totalRaw) {
|
||||
const oldTotal = parseInt(totalRaw, 10);
|
||||
stateContent = stateReplaceField(stateContent, 'Total Phases', String(oldTotal - 1)) || stateContent;
|
||||
}
|
||||
// Update "Phase: X of Y" pattern
|
||||
const ofPattern = /(\bof\s+)(\d+)(\s*(?:\(|phases?))/i;
|
||||
@@ -882,67 +881,58 @@ function cmdPhaseComplete(cwd, phaseNum, raw) {
|
||||
} catch { /* intentionally empty */ }
|
||||
}
|
||||
|
||||
// Update STATE.md
|
||||
// Update STATE.md — use shared helpers that handle both **bold:** and plain Field: formats
|
||||
if (fs.existsSync(statePath)) {
|
||||
let stateContent = fs.readFileSync(statePath, 'utf-8');
|
||||
|
||||
// Update Current Phase
|
||||
stateContent = stateContent.replace(
|
||||
/(\*\*Current Phase:\*\*\s*).*/,
|
||||
`$1${nextPhaseNum || phaseNum}`
|
||||
);
|
||||
// Update Current Phase — preserve "X of Y (Name)" compound format
|
||||
const phaseValue = nextPhaseNum || phaseNum;
|
||||
const existingPhaseField = stateExtractField(stateContent, 'Current Phase')
|
||||
|| stateExtractField(stateContent, 'Phase');
|
||||
let newPhaseValue = String(phaseValue);
|
||||
if (existingPhaseField) {
|
||||
const totalMatch = existingPhaseField.match(/of\s+(\d+)/);
|
||||
const nameMatch = existingPhaseField.match(/\(([^)]+)\)/);
|
||||
if (totalMatch) {
|
||||
const total = totalMatch[1];
|
||||
const nameStr = nextPhaseName ? ` (${nextPhaseName.replace(/-/g, ' ')})` : (nameMatch ? ` (${nameMatch[1]})` : '');
|
||||
newPhaseValue = `${phaseValue} of ${total}${nameStr}`;
|
||||
}
|
||||
}
|
||||
stateContent = stateReplaceFieldWithFallback(stateContent, 'Current Phase', 'Phase', newPhaseValue);
|
||||
|
||||
// Update Current Phase Name
|
||||
if (nextPhaseName) {
|
||||
stateContent = stateContent.replace(
|
||||
/(\*\*Current Phase Name:\*\*\s*).*/,
|
||||
`$1${nextPhaseName.replace(/-/g, ' ')}`
|
||||
);
|
||||
stateContent = stateReplaceFieldWithFallback(stateContent, 'Current Phase Name', null, nextPhaseName.replace(/-/g, ' '));
|
||||
}
|
||||
|
||||
// Update Status
|
||||
stateContent = stateContent.replace(
|
||||
/(\*\*Status:\*\*\s*).*/,
|
||||
`$1${isLastPhase ? 'Milestone complete' : 'Ready to plan'}`
|
||||
);
|
||||
stateContent = stateReplaceFieldWithFallback(stateContent, 'Status', null,
|
||||
isLastPhase ? 'Milestone complete' : 'Ready to plan');
|
||||
|
||||
// Update Current Plan
|
||||
stateContent = stateContent.replace(
|
||||
/(\*\*Current Plan:\*\*\s*).*/,
|
||||
`$1Not started`
|
||||
);
|
||||
stateContent = stateReplaceFieldWithFallback(stateContent, 'Current Plan', 'Plan', 'Not started');
|
||||
|
||||
// Update Last Activity
|
||||
stateContent = stateContent.replace(
|
||||
/(\*\*Last Activity:\*\*\s*).*/,
|
||||
`$1${today}`
|
||||
);
|
||||
stateContent = stateReplaceFieldWithFallback(stateContent, 'Last Activity', 'Last activity', today);
|
||||
|
||||
// Update Last Activity Description
|
||||
stateContent = stateContent.replace(
|
||||
/(\*\*Last Activity Description:\*\*\s*).*/,
|
||||
`$1Phase ${phaseNum} complete${nextPhaseNum ? `, transitioned to Phase ${nextPhaseNum}` : ''}`
|
||||
);
|
||||
stateContent = stateReplaceFieldWithFallback(stateContent, 'Last Activity Description', null,
|
||||
`Phase ${phaseNum} complete${nextPhaseNum ? `, transitioned to Phase ${nextPhaseNum}` : ''}`);
|
||||
|
||||
// Increment Completed Phases counter (#956)
|
||||
const completedMatch = stateContent.match(/\*\*Completed Phases:\*\*\s*(\d+)/);
|
||||
if (completedMatch) {
|
||||
const newCompleted = parseInt(completedMatch[1], 10) + 1;
|
||||
stateContent = stateContent.replace(
|
||||
/(\*\*Completed Phases:\*\*\s*)\d+/,
|
||||
`$1${newCompleted}`
|
||||
);
|
||||
const completedRaw = stateExtractField(stateContent, 'Completed Phases');
|
||||
if (completedRaw) {
|
||||
const newCompleted = parseInt(completedRaw, 10) + 1;
|
||||
stateContent = stateReplaceField(stateContent, 'Completed Phases', String(newCompleted)) || stateContent;
|
||||
|
||||
// Recalculate percent based on completed / total (#956)
|
||||
const totalMatch = stateContent.match(/\*\*Total Phases:\*\*\s*(\d+)/);
|
||||
if (totalMatch) {
|
||||
const totalPhases = parseInt(totalMatch[1], 10);
|
||||
const totalRaw = stateExtractField(stateContent, 'Total Phases');
|
||||
if (totalRaw) {
|
||||
const totalPhases = parseInt(totalRaw, 10);
|
||||
if (totalPhases > 0) {
|
||||
const newPercent = Math.round((newCompleted / totalPhases) * 100);
|
||||
stateContent = stateContent.replace(
|
||||
/(\*\*Progress:\*\*\s*)\d+%/,
|
||||
`$1${newPercent}%`
|
||||
);
|
||||
stateContent = stateReplaceField(stateContent, 'Progress', `${newPercent}%`) || stateContent;
|
||||
// Also update percent field if it exists separately
|
||||
stateContent = stateContent.replace(
|
||||
/(percent:\s*)\d+/,
|
||||
|
||||
@@ -12,7 +12,7 @@ const fs = require('fs');
|
||||
const path = require('path');
|
||||
const os = require('os');
|
||||
const readline = require('readline');
|
||||
const { output, error, safeReadFile } = require('./core.cjs');
|
||||
const { output, error, safeReadFile, reapStaleTempFiles } = require('./core.cjs');
|
||||
|
||||
// ─── Session I/O Helpers ──────────────────────────────────────────────────────
|
||||
|
||||
@@ -333,6 +333,7 @@ async function cmdExtractMessages(projectArg, options, raw, overridePath) {
|
||||
sessions = sessions.slice(0, options.limit);
|
||||
}
|
||||
|
||||
reapStaleTempFiles('gsd-pipeline-', { dirsOnly: true });
|
||||
const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'gsd-pipeline-'));
|
||||
const outputPath = path.join(tmpDir, 'extracted-messages.jsonl');
|
||||
|
||||
@@ -511,6 +512,7 @@ async function cmdProfileSample(overridePath, options, raw) {
|
||||
}
|
||||
}
|
||||
|
||||
reapStaleTempFiles('gsd-profile-', { dirsOnly: true });
|
||||
const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'gsd-profile-'));
|
||||
const outputPath = path.join(tmpDir, 'profile-sample.jsonl');
|
||||
for (const msg of allMessages) {
|
||||
|
||||
356
get-shit-done/bin/lib/security.cjs
Normal file
356
get-shit-done/bin/lib/security.cjs
Normal file
@@ -0,0 +1,356 @@
|
||||
/**
|
||||
* Security — Input validation, path traversal prevention, and prompt injection guards
|
||||
*
|
||||
* This module centralizes security checks for GSD tooling. Because GSD generates
|
||||
* markdown files that become LLM system prompts (agent instructions, workflow state,
|
||||
* phase plans), any user-controlled text that flows into these files is a potential
|
||||
* indirect prompt injection vector.
|
||||
*
|
||||
* Threat model:
|
||||
* 1. Path traversal: user-supplied file paths escape the project directory
|
||||
* 2. Prompt injection: malicious text in arguments/PRDs embeds LLM instructions
|
||||
* 3. Shell metacharacter injection: user text interpreted by shell
|
||||
* 4. JSON injection: malformed JSON crashes or corrupts state
|
||||
* 5. Regex DoS: crafted input causes catastrophic backtracking
|
||||
*/
|
||||
'use strict';
|
||||
|
||||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
|
||||
// ─── Path Traversal Prevention ──────────────────────────────────────────────
|
||||
|
||||
/**
|
||||
* Validate that a file path resolves within an allowed base directory.
|
||||
* Prevents path traversal attacks via ../ sequences, symlinks, or absolute paths.
|
||||
*
|
||||
* @param {string} filePath - The user-supplied file path
|
||||
* @param {string} baseDir - The allowed base directory (e.g., project root)
|
||||
* @param {object} [opts] - Options
|
||||
* @param {boolean} [opts.allowAbsolute=false] - Allow absolute paths (still must be within baseDir)
|
||||
* @returns {{ safe: boolean, resolved: string, error?: string }}
|
||||
*/
|
||||
function validatePath(filePath, baseDir, opts = {}) {
|
||||
if (!filePath || typeof filePath !== 'string') {
|
||||
return { safe: false, resolved: '', error: 'Empty or invalid file path' };
|
||||
}
|
||||
|
||||
if (!baseDir || typeof baseDir !== 'string') {
|
||||
return { safe: false, resolved: '', error: 'Empty or invalid base directory' };
|
||||
}
|
||||
|
||||
// Reject null bytes (can bypass path checks in some environments)
|
||||
if (filePath.includes('\0')) {
|
||||
return { safe: false, resolved: '', error: 'Path contains null bytes' };
|
||||
}
|
||||
|
||||
// Resolve symlinks in base directory to handle macOS /var -> /private/var
|
||||
// and similar platform-specific symlink chains
|
||||
let resolvedBase;
|
||||
try {
|
||||
resolvedBase = fs.realpathSync(path.resolve(baseDir));
|
||||
} catch {
|
||||
resolvedBase = path.resolve(baseDir);
|
||||
}
|
||||
|
||||
let resolvedPath;
|
||||
|
||||
if (path.isAbsolute(filePath)) {
|
||||
if (!opts.allowAbsolute) {
|
||||
return { safe: false, resolved: '', error: 'Absolute paths not allowed' };
|
||||
}
|
||||
resolvedPath = path.resolve(filePath);
|
||||
} else {
|
||||
resolvedPath = path.resolve(baseDir, filePath);
|
||||
}
|
||||
|
||||
// Resolve symlinks in the target path too
|
||||
try {
|
||||
resolvedPath = fs.realpathSync(resolvedPath);
|
||||
} catch {
|
||||
// File may not exist yet (e.g., about to be created) — use logical resolution
|
||||
// but still resolve the parent directory if it exists
|
||||
const parentDir = path.dirname(resolvedPath);
|
||||
try {
|
||||
const realParent = fs.realpathSync(parentDir);
|
||||
resolvedPath = path.join(realParent, path.basename(resolvedPath));
|
||||
} catch {
|
||||
// Parent doesn't exist either — keep the resolved path as-is
|
||||
}
|
||||
}
|
||||
|
||||
// Normalize both paths and check containment
|
||||
const normalizedBase = resolvedBase + path.sep;
|
||||
const normalizedPath = resolvedPath + path.sep;
|
||||
|
||||
// The resolved path must start with the base directory
|
||||
// (or be exactly the base directory)
|
||||
if (resolvedPath !== resolvedBase && !normalizedPath.startsWith(normalizedBase)) {
|
||||
return {
|
||||
safe: false,
|
||||
resolved: resolvedPath,
|
||||
error: `Path escapes allowed directory: ${resolvedPath} is outside ${resolvedBase}`,
|
||||
};
|
||||
}
|
||||
|
||||
return { safe: true, resolved: resolvedPath };
|
||||
}
|
||||
|
||||
/**
|
||||
* Validate a file path and throw on traversal attempt.
|
||||
* Convenience wrapper around validatePath for use in CLI commands.
|
||||
*/
|
||||
function requireSafePath(filePath, baseDir, label, opts = {}) {
|
||||
const result = validatePath(filePath, baseDir, opts);
|
||||
if (!result.safe) {
|
||||
throw new Error(`${label || 'Path'} validation failed: ${result.error}`);
|
||||
}
|
||||
return result.resolved;
|
||||
}
|
||||
|
||||
// ─── Prompt Injection Detection ─────────────────────────────────────────────
|
||||
|
||||
/**
|
||||
* Patterns that indicate prompt injection attempts in user-supplied text.
|
||||
* These patterns catch common indirect prompt injection techniques where
|
||||
* an attacker embeds LLM instructions in text that will be read by an agent.
|
||||
*
|
||||
* Note: This is defense-in-depth — not a complete solution. The primary defense
|
||||
* is proper input/output boundaries in agent prompts.
|
||||
*/
|
||||
const INJECTION_PATTERNS = [
|
||||
// Direct instruction override attempts
|
||||
/ignore\s+(all\s+)?previous\s+instructions/i,
|
||||
/ignore\s+(all\s+)?above\s+instructions/i,
|
||||
/disregard\s+(all\s+)?previous/i,
|
||||
/forget\s+(all\s+)?(your\s+)?instructions/i,
|
||||
/override\s+(system|previous)\s+(prompt|instructions)/i,
|
||||
|
||||
// Role/identity manipulation
|
||||
/you\s+are\s+now\s+(?:a|an|the)\s+/i,
|
||||
/act\s+as\s+(?:a|an|the)\s+(?!plan|phase|wave)/i, // allow "act as a plan"
|
||||
/pretend\s+(?:you(?:'re| are)\s+|to\s+be\s+)/i,
|
||||
/from\s+now\s+on,?\s+you\s+(?:are|will|should|must)/i,
|
||||
|
||||
// System prompt extraction
|
||||
/(?:print|output|reveal|show|display|repeat)\s+(?:your\s+)?(?:system\s+)?(?:prompt|instructions)/i,
|
||||
/what\s+(?:are|is)\s+your\s+(?:system\s+)?(?:prompt|instructions)/i,
|
||||
|
||||
// Hidden instruction markers (XML/HTML tags that mimic system messages)
|
||||
// Note: <instructions> is excluded — GSD uses it as legitimate prompt structure
|
||||
// Requires > to close the tag (not just whitespace) to avoid matching generic types like Promise<User | null>
|
||||
/<\/?(?:system|assistant|human)>/i,
|
||||
/\[SYSTEM\]/i,
|
||||
/\[INST\]/i,
|
||||
/<<\s*SYS\s*>>/i,
|
||||
|
||||
// Exfiltration attempts
|
||||
/(?:send|post|fetch|curl|wget)\s+(?:to|from)\s+https?:\/\//i,
|
||||
/(?:base64|btoa|encode)\s+(?:and\s+)?(?:send|exfiltrate|output)/i,
|
||||
|
||||
// Tool manipulation
|
||||
/(?:run|execute|call|invoke)\s+(?:the\s+)?(?:bash|shell|exec|spawn)\s+(?:tool|command)/i,
|
||||
];
|
||||
|
||||
/**
|
||||
* Scan text for potential prompt injection patterns.
|
||||
* Returns an array of findings (empty = clean).
|
||||
*
|
||||
* @param {string} text - The text to scan
|
||||
* @param {object} [opts] - Options
|
||||
* @param {boolean} [opts.strict=false] - Enable stricter matching (more false positives)
|
||||
* @returns {{ clean: boolean, findings: string[] }}
|
||||
*/
|
||||
function scanForInjection(text, opts = {}) {
|
||||
if (!text || typeof text !== 'string') {
|
||||
return { clean: true, findings: [] };
|
||||
}
|
||||
|
||||
const findings = [];
|
||||
|
||||
for (const pattern of INJECTION_PATTERNS) {
|
||||
if (pattern.test(text)) {
|
||||
findings.push(`Matched injection pattern: ${pattern.source}`);
|
||||
}
|
||||
}
|
||||
|
||||
if (opts.strict) {
|
||||
// Check for suspicious Unicode that could hide instructions
|
||||
// (zero-width chars, RTL override, homoglyph attacks)
|
||||
if (/[\u200B-\u200F\u2028-\u202F\uFEFF\u00AD]/.test(text)) {
|
||||
findings.push('Contains suspicious zero-width or invisible Unicode characters');
|
||||
}
|
||||
|
||||
// Check for extremely long strings that could be prompt stuffing
|
||||
if (text.length > 50000) {
|
||||
findings.push(`Suspicious text length: ${text.length} chars (potential prompt stuffing)`);
|
||||
}
|
||||
}
|
||||
|
||||
return { clean: findings.length === 0, findings };
|
||||
}
|
||||
|
||||
/**
|
||||
* Sanitize text that will be embedded in agent prompts or planning documents.
|
||||
* Strips known injection markers while preserving legitimate content.
|
||||
*
|
||||
* This does NOT alter user intent — it neutralizes control characters and
|
||||
* instruction-mimicking patterns that could hijack agent behavior.
|
||||
*
|
||||
* @param {string} text - Text to sanitize
|
||||
* @returns {string} Sanitized text
|
||||
*/
|
||||
function sanitizeForPrompt(text) {
|
||||
if (!text || typeof text !== 'string') return text;
|
||||
|
||||
let sanitized = text;
|
||||
|
||||
// Strip zero-width characters that could hide instructions
|
||||
sanitized = sanitized.replace(/[\u200B-\u200F\u2028-\u202F\uFEFF\u00AD]/g, '');
|
||||
|
||||
// Neutralize XML/HTML tags that mimic system boundaries
|
||||
// Replace < > with full-width equivalents to prevent tag interpretation
|
||||
// Note: <instructions> is excluded — GSD uses it as legitimate prompt structure
|
||||
sanitized = sanitized.replace(/<(\/?)(?:system|assistant|human)>/gi,
|
||||
(_, slash) => `<${slash || ''}system-text>`);
|
||||
|
||||
// Neutralize [SYSTEM] / [INST] markers
|
||||
sanitized = sanitized.replace(/\[(SYSTEM|INST)\]/gi, '[$1-TEXT]');
|
||||
|
||||
// Neutralize <<SYS>> markers
|
||||
sanitized = sanitized.replace(/<<\s*SYS\s*>>/gi, '«SYS-TEXT»');
|
||||
|
||||
return sanitized;
|
||||
}
|
||||
|
||||
// ─── Shell Safety ───────────────────────────────────────────────────────────
|
||||
|
||||
/**
|
||||
* Validate that a string is safe to use as a shell argument when quoted.
|
||||
* This is a defense-in-depth check — callers should always use array-based
|
||||
* exec (spawnSync) where possible.
|
||||
*
|
||||
* @param {string} value - The value to check
|
||||
* @param {string} label - Description for error messages
|
||||
* @returns {string} The validated value
|
||||
*/
|
||||
function validateShellArg(value, label) {
|
||||
if (!value || typeof value !== 'string') {
|
||||
throw new Error(`${label || 'Argument'}: empty or invalid value`);
|
||||
}
|
||||
|
||||
// Reject null bytes
|
||||
if (value.includes('\0')) {
|
||||
throw new Error(`${label || 'Argument'}: contains null bytes`);
|
||||
}
|
||||
|
||||
// Reject command substitution attempts
|
||||
if (/[$`]/.test(value) && /\$\(|`/.test(value)) {
|
||||
throw new Error(`${label || 'Argument'}: contains potential command substitution`);
|
||||
}
|
||||
|
||||
return value;
|
||||
}
|
||||
|
||||
// ─── JSON Safety ────────────────────────────────────────────────────────────
|
||||
|
||||
/**
|
||||
* Safely parse JSON with error handling and optional size limits.
|
||||
* Wraps JSON.parse to prevent uncaught exceptions from malformed input.
|
||||
*
|
||||
* @param {string} text - JSON string to parse
|
||||
* @param {object} [opts] - Options
|
||||
* @param {number} [opts.maxLength=1048576] - Maximum input length (1MB default)
|
||||
* @param {string} [opts.label='JSON'] - Description for error messages
|
||||
* @returns {{ ok: boolean, value?: any, error?: string }}
|
||||
*/
|
||||
function safeJsonParse(text, opts = {}) {
|
||||
const maxLength = opts.maxLength || 1048576;
|
||||
const label = opts.label || 'JSON';
|
||||
|
||||
if (!text || typeof text !== 'string') {
|
||||
return { ok: false, error: `${label}: empty or invalid input` };
|
||||
}
|
||||
|
||||
if (text.length > maxLength) {
|
||||
return { ok: false, error: `${label}: input exceeds ${maxLength} byte limit (got ${text.length})` };
|
||||
}
|
||||
|
||||
try {
|
||||
const value = JSON.parse(text);
|
||||
return { ok: true, value };
|
||||
} catch (err) {
|
||||
return { ok: false, error: `${label}: parse error — ${err.message}` };
|
||||
}
|
||||
}
|
||||
|
||||
// ─── Phase/Argument Validation ──────────────────────────────────────────────
|
||||
|
||||
/**
|
||||
* Validate a phase number argument.
|
||||
* Phase numbers must match: integer, decimal (2.1), or letter suffix (12A).
|
||||
* Rejects arbitrary strings that could be used for injection.
|
||||
*
|
||||
* @param {string} phase - The phase number to validate
|
||||
* @returns {{ valid: boolean, normalized?: string, error?: string }}
|
||||
*/
|
||||
function validatePhaseNumber(phase) {
|
||||
if (!phase || typeof phase !== 'string') {
|
||||
return { valid: false, error: 'Phase number is required' };
|
||||
}
|
||||
|
||||
const trimmed = phase.trim();
|
||||
|
||||
// Standard numeric: 1, 01, 12A, 12.1, 12A.1.2
|
||||
if (/^\d{1,4}[A-Z]?(?:\.\d{1,3})*$/i.test(trimmed)) {
|
||||
return { valid: true, normalized: trimmed };
|
||||
}
|
||||
|
||||
// Custom project IDs: PROJ-42, AUTH-101 (uppercase alphanumeric with hyphens)
|
||||
if (/^[A-Z][A-Z0-9]*(?:-[A-Z0-9]+){1,4}$/i.test(trimmed) && trimmed.length <= 30) {
|
||||
return { valid: true, normalized: trimmed };
|
||||
}
|
||||
|
||||
return { valid: false, error: `Invalid phase number format: "${trimmed}"` };
|
||||
}
|
||||
|
||||
/**
|
||||
* Validate a STATE.md field name to prevent injection into regex patterns.
|
||||
* Field names must be alphanumeric with spaces, hyphens, underscores, or dots.
|
||||
*
|
||||
* @param {string} field - The field name to validate
|
||||
* @returns {{ valid: boolean, error?: string }}
|
||||
*/
|
||||
function validateFieldName(field) {
|
||||
if (!field || typeof field !== 'string') {
|
||||
return { valid: false, error: 'Field name is required' };
|
||||
}
|
||||
|
||||
// Allow typical field names: "Current Phase", "active_plan", "Phase 1.2"
|
||||
if (/^[A-Za-z][A-Za-z0-9 _.\-/]{0,60}$/.test(field)) {
|
||||
return { valid: true };
|
||||
}
|
||||
|
||||
return { valid: false, error: `Invalid field name: "${field}"` };
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
// Path safety
|
||||
validatePath,
|
||||
requireSafePath,
|
||||
|
||||
// Prompt injection
|
||||
INJECTION_PATTERNS,
|
||||
scanForInjection,
|
||||
sanitizeForPrompt,
|
||||
|
||||
// Shell safety
|
||||
validateShellArg,
|
||||
|
||||
// JSON safety
|
||||
safeJsonParse,
|
||||
|
||||
// Input validation
|
||||
validatePhaseNumber,
|
||||
validateFieldName,
|
||||
};
|
||||
@@ -115,15 +115,30 @@ function cmdStateGet(cwd, section, raw) {
|
||||
function readTextArgOrFile(cwd, value, filePath, label) {
|
||||
if (!filePath) return value;
|
||||
|
||||
const resolvedPath = path.isAbsolute(filePath) ? filePath : path.join(cwd, filePath);
|
||||
// Path traversal guard: ensure file resolves within project directory
|
||||
const { validatePath } = require('./security.cjs');
|
||||
const pathCheck = validatePath(filePath, cwd, { allowAbsolute: true });
|
||||
if (!pathCheck.safe) {
|
||||
throw new Error(`${label} path rejected: ${pathCheck.error}`);
|
||||
}
|
||||
|
||||
try {
|
||||
return fs.readFileSync(resolvedPath, 'utf-8').trimEnd();
|
||||
return fs.readFileSync(pathCheck.resolved, 'utf-8').trimEnd();
|
||||
} catch {
|
||||
throw new Error(`${label} file not found: ${filePath}`);
|
||||
}
|
||||
}
|
||||
|
||||
function cmdStatePatch(cwd, patches, raw) {
|
||||
// Validate all field names before processing
|
||||
const { validateFieldName } = require('./security.cjs');
|
||||
for (const field of Object.keys(patches)) {
|
||||
const fieldCheck = validateFieldName(field);
|
||||
if (!fieldCheck.valid) {
|
||||
error(`state patch: ${fieldCheck.error}`);
|
||||
}
|
||||
}
|
||||
|
||||
const statePath = planningPaths(cwd).state;
|
||||
try {
|
||||
let content = fs.readFileSync(statePath, 'utf-8');
|
||||
@@ -161,6 +176,13 @@ function cmdStateUpdate(cwd, field, value) {
|
||||
error('field and value required for state update');
|
||||
}
|
||||
|
||||
// Validate field name to prevent regex injection via crafted field names
|
||||
const { validateFieldName } = require('./security.cjs');
|
||||
const fieldCheck = validateFieldName(field);
|
||||
if (!fieldCheck.valid) {
|
||||
error(`state update: ${fieldCheck.error}`);
|
||||
}
|
||||
|
||||
const statePath = planningPaths(cwd).state;
|
||||
try {
|
||||
let content = fs.readFileSync(statePath, 'utf-8');
|
||||
@@ -201,6 +223,22 @@ function stateReplaceField(content, fieldName, newValue) {
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Replace a STATE.md field with fallback field name support.
|
||||
* Tries `primary` first, then `fallback` (if provided), returns content unchanged
|
||||
* if neither matches. This consolidates the replaceWithFallback pattern that was
|
||||
* previously duplicated inline across phase.cjs, milestone.cjs, and state.cjs.
|
||||
*/
|
||||
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 cmdStateAdvancePlan(cwd, raw) {
|
||||
const statePath = planningPaths(cwd).state;
|
||||
if (!fs.existsSync(statePath)) { output({ error: 'STATE.md not found' }, raw); return; }
|
||||
@@ -232,16 +270,9 @@ function cmdStateAdvancePlan(cwd, raw) {
|
||||
return;
|
||||
}
|
||||
|
||||
const replaceField = (c, primary, fallback, value) => {
|
||||
let r = stateReplaceField(c, primary, value);
|
||||
if (r) return r;
|
||||
if (fallback) { r = stateReplaceField(c, fallback, value); if (r) return r; }
|
||||
return c;
|
||||
};
|
||||
|
||||
if (currentPlan >= totalPlans) {
|
||||
content = replaceField(content, 'Status', null, 'Phase complete — ready for verification');
|
||||
content = replaceField(content, 'Last Activity', 'Last activity', today);
|
||||
content = stateReplaceFieldWithFallback(content, 'Status', null, 'Phase complete — ready for verification');
|
||||
content = stateReplaceFieldWithFallback(content, 'Last Activity', 'Last activity', today);
|
||||
writeStateMd(statePath, content, cwd);
|
||||
output({ advanced: false, reason: 'last_plan', current_plan: currentPlan, total_plans: totalPlans, status: 'ready_for_verification' }, raw, 'false');
|
||||
} else {
|
||||
@@ -253,8 +284,8 @@ function cmdStateAdvancePlan(cwd, raw) {
|
||||
} else {
|
||||
content = stateReplaceField(content, 'Current Plan', String(newPlan)) || content;
|
||||
}
|
||||
content = replaceField(content, 'Status', null, 'Ready to execute');
|
||||
content = replaceField(content, 'Last Activity', 'Last activity', today);
|
||||
content = stateReplaceFieldWithFallback(content, 'Status', null, 'Ready to execute');
|
||||
content = stateReplaceFieldWithFallback(content, 'Last Activity', 'Last activity', today);
|
||||
writeStateMd(statePath, content, cwd);
|
||||
output({ advanced: true, previous_plan: currentPlan, current_plan: newPlan, total_plans: totalPlans }, raw, 'true');
|
||||
}
|
||||
@@ -702,9 +733,20 @@ function stripFrontmatter(content) {
|
||||
}
|
||||
|
||||
function syncStateFrontmatter(content, cwd) {
|
||||
// Read existing frontmatter BEFORE stripping — it may contain values
|
||||
// that the body no longer has (e.g., Status field removed by an agent).
|
||||
const existingFm = extractFrontmatter(content);
|
||||
const body = stripFrontmatter(content);
|
||||
const fm = buildStateFrontmatter(body, cwd);
|
||||
const yamlStr = reconstructFrontmatter(fm);
|
||||
const derivedFm = buildStateFrontmatter(body, cwd);
|
||||
|
||||
// Preserve existing frontmatter status when body-derived status is 'unknown'.
|
||||
// This prevents a missing Status: field in the body from overwriting a
|
||||
// previously valid status (e.g., 'executing' → 'unknown').
|
||||
if (derivedFm.status === 'unknown' && existingFm.status && existingFm.status !== 'unknown') {
|
||||
derivedFm.status = existingFm.status;
|
||||
}
|
||||
|
||||
const yamlStr = reconstructFrontmatter(derivedFm);
|
||||
return `---\n${yamlStr}\n---\n\n${body}`;
|
||||
}
|
||||
|
||||
@@ -906,6 +948,7 @@ function cmdSignalResume(cwd, raw) {
|
||||
module.exports = {
|
||||
stateExtractField,
|
||||
stateReplaceField,
|
||||
stateReplaceFieldWithFallback,
|
||||
writeStateMd,
|
||||
cmdStateLoad,
|
||||
cmdStateGet,
|
||||
|
||||
Reference in New Issue
Block a user