fix: resolve merge conflict in execute-phase argument-hint
Combine all three flags (--wave N, --gaps-only, --interactive) in the argument-hint after merging main into the PR branch. https://claude.ai/code/session_01Maa4rFLGVsFiLWynSbaVS8
This commit is contained in:
@@ -15,9 +15,12 @@
|
||||
* state get [section] Get STATE.md content or section
|
||||
* state patch --field val ... Batch update STATE.md fields
|
||||
* state begin-phase --phase N --name S --plans C Update STATE.md for new phase start
|
||||
* state signal-waiting --type T --question Q --options "A|B" --phase P Write WAITING.json signal
|
||||
* state signal-resume Remove WAITING.json signal
|
||||
* resolve-model <agent-type> Get model for agent based on profile
|
||||
* find-phase <phase> Find phase directory by number
|
||||
* commit <message> [--files f1 f2] Commit planning docs
|
||||
* 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)
|
||||
@@ -33,7 +36,7 @@
|
||||
*
|
||||
* Phase Operations:
|
||||
* phase next-decimal <phase> Calculate next decimal phase number
|
||||
* phase add <description> Append new phase to roadmap + create dir
|
||||
* phase add <description> [--id ID] Append new phase to roadmap + create dir
|
||||
* phase insert <after> <description> Insert decimal phase after existing
|
||||
* phase remove <phase> [--force] Remove phase, renumber all subsequent
|
||||
* phase complete <phase> Mark phase done, update state + roadmap
|
||||
@@ -62,6 +65,9 @@
|
||||
* Todos:
|
||||
* todo complete <filename> Move todo from pending to completed
|
||||
*
|
||||
* UAT Audit:
|
||||
* audit-uat Scan all phases for unresolved UAT/verification items
|
||||
*
|
||||
* Scaffolding:
|
||||
* scaffold context --phase <N> Create CONTEXT.md template
|
||||
* scaffold uat --phase <N> Create UAT.md template
|
||||
@@ -129,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');
|
||||
@@ -168,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);
|
||||
@@ -178,6 +191,17 @@ async function main() {
|
||||
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');
|
||||
}
|
||||
|
||||
// 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) {
|
||||
case 'state': {
|
||||
const subcommand = args[1];
|
||||
@@ -255,6 +279,21 @@ async function main() {
|
||||
plansIdx !== -1 ? parseInt(args[plansIdx + 1], 10) : null,
|
||||
raw
|
||||
);
|
||||
} else if (subcommand === 'signal-waiting') {
|
||||
const typeIdx = args.indexOf('--type');
|
||||
const qIdx = args.indexOf('--question');
|
||||
const optIdx = args.indexOf('--options');
|
||||
const phaseIdx = args.indexOf('--phase');
|
||||
state.cmdSignalWaiting(
|
||||
cwd,
|
||||
typeIdx !== -1 ? args[typeIdx + 1] : null,
|
||||
qIdx !== -1 ? args[qIdx + 1] : null,
|
||||
optIdx !== -1 ? args[optIdx + 1] : null,
|
||||
phaseIdx !== -1 ? args[phaseIdx + 1] : null,
|
||||
raw
|
||||
);
|
||||
} else if (subcommand === 'signal-resume') {
|
||||
state.cmdSignalResume(cwd, raw);
|
||||
} else {
|
||||
state.cmdStateLoad(cwd, raw);
|
||||
}
|
||||
@@ -273,6 +312,7 @@ async function main() {
|
||||
|
||||
case 'commit': {
|
||||
const amend = args.includes('--amend');
|
||||
const noVerify = args.includes('--no-verify');
|
||||
const filesIndex = args.indexOf('--files');
|
||||
// Collect all positional args between command name and first flag,
|
||||
// then join them — handles both quoted ("multi word msg") and
|
||||
@@ -281,7 +321,15 @@ async function main() {
|
||||
const messageArgs = args.slice(1, endIndex).filter(a => !a.startsWith('--'));
|
||||
const message = messageArgs.join(' ') || undefined;
|
||||
const files = filesIndex !== -1 ? args.slice(filesIndex + 1).filter(a => !a.startsWith('--')) : [];
|
||||
commands.cmdCommit(cwd, message, files, raw, amend);
|
||||
commands.cmdCommit(cwd, message, files, raw, amend, noVerify);
|
||||
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;
|
||||
}
|
||||
|
||||
@@ -452,7 +500,18 @@ async function main() {
|
||||
if (subcommand === 'next-decimal') {
|
||||
phase.cmdPhaseNextDecimal(cwd, args[2], raw);
|
||||
} else if (subcommand === 'add') {
|
||||
phase.cmdPhaseAdd(cwd, args.slice(2).join(' '), raw);
|
||||
const idIdx = args.indexOf('--id');
|
||||
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++; // skip value
|
||||
} else {
|
||||
descArgs.push(args[i]);
|
||||
}
|
||||
}
|
||||
phase.cmdPhaseAdd(cwd, descArgs.join(' '), raw, customId);
|
||||
} else if (subcommand === 'insert') {
|
||||
phase.cmdPhaseInsert(cwd, args[2], args.slice(3).join(' '), raw);
|
||||
} else if (subcommand === 'remove') {
|
||||
@@ -507,6 +566,12 @@ async function main() {
|
||||
break;
|
||||
}
|
||||
|
||||
case 'audit-uat': {
|
||||
const uat = require('./lib/uat.cjs');
|
||||
uat.cmdAuditUat(cwd, raw);
|
||||
break;
|
||||
}
|
||||
|
||||
case 'stats': {
|
||||
const subcommand = args[1] || 'json';
|
||||
commands.cmdStats(cwd, subcommand, raw);
|
||||
@@ -517,8 +582,10 @@ async function main() {
|
||||
const subcommand = args[1];
|
||||
if (subcommand === 'complete') {
|
||||
commands.cmdTodoComplete(cwd, args[2], raw);
|
||||
} else if (subcommand === 'match-phase') {
|
||||
commands.cmdTodoMatchPhase(cwd, args[2], raw);
|
||||
} else {
|
||||
error('Unknown todo subcommand. Available: complete');
|
||||
error('Unknown todo subcommand. Available: complete, match-phase');
|
||||
}
|
||||
break;
|
||||
}
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
const { execSync } = require('child_process');
|
||||
const { safeReadFile, loadConfig, isGitIgnored, execGit, normalizePhaseName, comparePhaseNum, getArchivedPhaseDirs, generateSlugInternal, getMilestoneInfo, getMilestonePhaseFilter, resolveModelInternal, stripShippedMilestones, toPosixPath, output, error, findPhaseInternal } = require('./core.cjs');
|
||||
const { safeReadFile, loadConfig, isGitIgnored, execGit, normalizePhaseName, comparePhaseNum, getArchivedPhaseDirs, generateSlugInternal, getMilestoneInfo, getMilestonePhaseFilter, resolveModelInternal, stripShippedMilestones, extractCurrentMilestone, planningPaths, toPosixPath, output, error, findPhaseInternal, extractOneLinerFromBody, getRoadmapPhaseInternal } = require('./core.cjs');
|
||||
const { extractFrontmatter } = require('./frontmatter.cjs');
|
||||
const { MODEL_PROFILES } = require('./model-profiles.cjs');
|
||||
|
||||
@@ -71,9 +71,9 @@ function cmdListTodos(cwd, area, raw) {
|
||||
area: todoArea,
|
||||
path: toPosixPath(path.join('.planning', 'todos', 'pending', file)),
|
||||
});
|
||||
} catch {}
|
||||
} catch { /* intentionally empty */ }
|
||||
}
|
||||
} catch {}
|
||||
} catch { /* intentionally empty */ }
|
||||
|
||||
const result = { count, todos };
|
||||
output(result, raw, count.toString());
|
||||
@@ -98,7 +98,7 @@ function cmdVerifyPathExists(cwd, targetPath, raw) {
|
||||
}
|
||||
|
||||
function cmdHistoryDigest(cwd, raw) {
|
||||
const phasesDir = path.join(cwd, '.planning', 'phases');
|
||||
const phasesDir = planningPaths(cwd).phases;
|
||||
const digest = { phases: {}, decisions: [], tech_stack: new Set() };
|
||||
|
||||
// Collect all phase directories: archived + current
|
||||
@@ -120,7 +120,7 @@ function cmdHistoryDigest(cwd, raw) {
|
||||
for (const dir of currentDirs) {
|
||||
allPhaseDirs.push({ name: dir, fullPath: path.join(phasesDir, dir), milestone: null });
|
||||
}
|
||||
} catch {}
|
||||
} catch { /* intentionally empty */ }
|
||||
}
|
||||
|
||||
if (allPhaseDirs.length === 0) {
|
||||
@@ -214,7 +214,7 @@ function cmdResolveModel(cwd, agentType, raw) {
|
||||
output(result, raw, model);
|
||||
}
|
||||
|
||||
function cmdCommit(cwd, message, files, raw, amend) {
|
||||
function cmdCommit(cwd, message, files, raw, amend, noVerify) {
|
||||
if (!message && !amend) {
|
||||
error('commit message required');
|
||||
}
|
||||
@@ -238,11 +238,18 @@ function cmdCommit(cwd, message, files, raw, amend) {
|
||||
// Stage files
|
||||
const filesToStage = files && files.length > 0 ? files : ['.planning/'];
|
||||
for (const file of filesToStage) {
|
||||
execGit(cwd, ['add', file]);
|
||||
const fullPath = path.join(cwd, file);
|
||||
if (!fs.existsSync(fullPath)) {
|
||||
// File was deleted/moved — stage the deletion
|
||||
execGit(cwd, ['rm', '--cached', '--ignore-unmatch', file]);
|
||||
} else {
|
||||
execGit(cwd, ['add', file]);
|
||||
}
|
||||
}
|
||||
|
||||
// Commit
|
||||
// Commit (--no-verify skips pre-commit hooks, used by parallel executor agents)
|
||||
const commitArgs = amend ? ['commit', '--amend', '--no-edit'] : ['commit', '-m', message];
|
||||
if (noVerify) commitArgs.push('--no-verify');
|
||||
const commitResult = execGit(cwd, commitArgs);
|
||||
if (commitResult.exitCode !== 0) {
|
||||
if (commitResult.stdout.includes('nothing to commit') || commitResult.stderr.includes('nothing to commit')) {
|
||||
@@ -262,6 +269,74 @@ function cmdCommit(cwd, message, files, raw, amend) {
|
||||
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');
|
||||
@@ -295,7 +370,7 @@ function cmdSummaryExtract(cwd, summaryPath, fields, raw) {
|
||||
// Build full result
|
||||
const fullResult = {
|
||||
path: summaryPath,
|
||||
one_liner: fm['one-liner'] || null,
|
||||
one_liner: fm['one-liner'] || extractOneLinerFromBody(content) || null,
|
||||
key_files: fm['key-files'] || [],
|
||||
tech_added: (fm['tech-stack'] && fm['tech-stack'].added) || [],
|
||||
patterns: fm['patterns-established'] || [],
|
||||
@@ -381,8 +456,8 @@ async function cmdWebsearch(query, options, raw) {
|
||||
}
|
||||
|
||||
function cmdProgressRender(cwd, format, raw) {
|
||||
const phasesDir = path.join(cwd, '.planning', 'phases');
|
||||
const roadmapPath = path.join(cwd, '.planning', 'ROADMAP.md');
|
||||
const phasesDir = planningPaths(cwd).phases;
|
||||
const roadmapPath = planningPaths(cwd).roadmap;
|
||||
const milestone = getMilestoneInfo(cwd);
|
||||
|
||||
const phases = [];
|
||||
@@ -412,7 +487,7 @@ function cmdProgressRender(cwd, format, raw) {
|
||||
|
||||
phases.push({ number: phaseNum, name: phaseName, plans, summaries, status });
|
||||
}
|
||||
} catch {}
|
||||
} catch { /* intentionally empty */ }
|
||||
|
||||
const percent = totalPlans > 0 ? Math.min(100, Math.round((totalSummaries / totalPlans) * 100)) : 0;
|
||||
|
||||
@@ -448,6 +523,130 @@ function cmdProgressRender(cwd, format, raw) {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Match pending todos against a phase's goal/name/requirements.
|
||||
* Returns todos with relevance scores based on keyword, area, and file overlap.
|
||||
* Used by discuss-phase to surface relevant todos before scope-setting.
|
||||
*/
|
||||
function cmdTodoMatchPhase(cwd, phase, raw) {
|
||||
if (!phase) { error('phase required for todo match-phase'); }
|
||||
|
||||
const pendingDir = path.join(cwd, '.planning', 'todos', 'pending');
|
||||
const todos = [];
|
||||
|
||||
// Load pending todos
|
||||
try {
|
||||
const files = fs.readdirSync(pendingDir).filter(f => f.endsWith('.md'));
|
||||
for (const file of files) {
|
||||
try {
|
||||
const content = fs.readFileSync(path.join(pendingDir, file), 'utf-8');
|
||||
const titleMatch = content.match(/^title:\s*(.+)$/m);
|
||||
const areaMatch = content.match(/^area:\s*(.+)$/m);
|
||||
const filesMatch = content.match(/^files:\s*(.+)$/m);
|
||||
const body = content.replace(/^(title|area|files|created|priority):.*$/gm, '').trim();
|
||||
|
||||
todos.push({
|
||||
file,
|
||||
title: titleMatch ? titleMatch[1].trim() : 'Untitled',
|
||||
area: areaMatch ? areaMatch[1].trim() : 'general',
|
||||
files: filesMatch ? filesMatch[1].trim().split(/[,\s]+/).filter(Boolean) : [],
|
||||
body: body.slice(0, 200), // first 200 chars for context
|
||||
});
|
||||
} catch {}
|
||||
}
|
||||
} catch {}
|
||||
|
||||
if (todos.length === 0) {
|
||||
output({ phase, matches: [], todo_count: 0 }, raw);
|
||||
return;
|
||||
}
|
||||
|
||||
// Load phase goal/name from ROADMAP
|
||||
const phaseInfo = getRoadmapPhaseInternal(cwd, phase);
|
||||
const phaseName = phaseInfo ? (phaseInfo.phase_name || '') : '';
|
||||
const phaseGoal = phaseInfo ? (phaseInfo.goal || '') : '';
|
||||
const phaseSection = phaseInfo ? (phaseInfo.section || '') : '';
|
||||
|
||||
// Build keyword set from phase name + goal + section text
|
||||
const phaseText = `${phaseName} ${phaseGoal} ${phaseSection}`.toLowerCase();
|
||||
const stopWords = new Set(['the', 'and', 'for', 'with', 'from', 'that', 'this', 'will', 'are', 'was', 'has', 'have', 'been', 'not', 'but', 'all', 'can', 'into', 'each', 'when', 'any', 'use', 'new']);
|
||||
const phaseKeywords = new Set(
|
||||
phaseText.split(/[\s\-_/.,;:()\[\]{}|]+/)
|
||||
.map(w => w.replace(/[^a-z0-9]/g, ''))
|
||||
.filter(w => w.length > 2 && !stopWords.has(w))
|
||||
);
|
||||
|
||||
// Find phase directory to get expected file paths
|
||||
const phaseInfoDisk = findPhaseInternal(cwd, phase);
|
||||
const phasePlans = [];
|
||||
if (phaseInfoDisk && phaseInfoDisk.found) {
|
||||
try {
|
||||
const phaseDir = path.join(cwd, phaseInfoDisk.directory);
|
||||
const planFiles = fs.readdirSync(phaseDir).filter(f => f.endsWith('-PLAN.md'));
|
||||
for (const pf of planFiles) {
|
||||
try {
|
||||
const planContent = fs.readFileSync(path.join(phaseDir, pf), 'utf-8');
|
||||
const fmFiles = planContent.match(/files_modified:\s*\[([^\]]*)\]/);
|
||||
if (fmFiles) {
|
||||
phasePlans.push(...fmFiles[1].split(',').map(s => s.trim().replace(/['"]/g, '')).filter(Boolean));
|
||||
}
|
||||
} catch {}
|
||||
}
|
||||
} catch {}
|
||||
}
|
||||
|
||||
// Score each todo for relevance
|
||||
const matches = [];
|
||||
for (const todo of todos) {
|
||||
let score = 0;
|
||||
const reasons = [];
|
||||
|
||||
// Keyword match: todo title/body terms in phase text
|
||||
const todoWords = `${todo.title} ${todo.body}`.toLowerCase()
|
||||
.split(/[\s\-_/.,;:()\[\]{}|]+/)
|
||||
.map(w => w.replace(/[^a-z0-9]/g, ''))
|
||||
.filter(w => w.length > 2 && !stopWords.has(w));
|
||||
|
||||
const matchedKeywords = todoWords.filter(w => phaseKeywords.has(w));
|
||||
if (matchedKeywords.length > 0) {
|
||||
score += Math.min(matchedKeywords.length * 0.2, 0.6);
|
||||
reasons.push(`keywords: ${[...new Set(matchedKeywords)].slice(0, 5).join(', ')}`);
|
||||
}
|
||||
|
||||
// Area match: todo area appears in phase text
|
||||
if (todo.area !== 'general' && phaseText.includes(todo.area.toLowerCase())) {
|
||||
score += 0.3;
|
||||
reasons.push(`area: ${todo.area}`);
|
||||
}
|
||||
|
||||
// File match: todo files overlap with phase plan files
|
||||
if (todo.files.length > 0 && phasePlans.length > 0) {
|
||||
const fileOverlap = todo.files.filter(f =>
|
||||
phasePlans.some(pf => pf.includes(f) || f.includes(pf))
|
||||
);
|
||||
if (fileOverlap.length > 0) {
|
||||
score += 0.4;
|
||||
reasons.push(`files: ${fileOverlap.slice(0, 3).join(', ')}`);
|
||||
}
|
||||
}
|
||||
|
||||
if (score > 0) {
|
||||
matches.push({
|
||||
file: todo.file,
|
||||
title: todo.title,
|
||||
area: todo.area,
|
||||
score: Math.round(score * 100) / 100,
|
||||
reasons,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// Sort by score descending
|
||||
matches.sort((a, b) => b.score - a.score);
|
||||
|
||||
output({ phase, matches, todo_count: todos.length }, raw);
|
||||
}
|
||||
|
||||
function cmdTodoComplete(cwd, filename, raw) {
|
||||
if (!filename) {
|
||||
error('filename required for todo complete');
|
||||
@@ -512,7 +711,7 @@ function cmdScaffold(cwd, type, options, raw) {
|
||||
}
|
||||
const slug = generateSlugInternal(name);
|
||||
const dirName = `${padded}-${slug}`;
|
||||
const phasesParent = path.join(cwd, '.planning', 'phases');
|
||||
const phasesParent = planningPaths(cwd).phases;
|
||||
fs.mkdirSync(phasesParent, { recursive: true });
|
||||
const dirPath = path.join(phasesParent, dirName);
|
||||
fs.mkdirSync(dirPath, { recursive: true });
|
||||
@@ -534,10 +733,10 @@ function cmdScaffold(cwd, type, options, raw) {
|
||||
}
|
||||
|
||||
function cmdStats(cwd, format, raw) {
|
||||
const phasesDir = path.join(cwd, '.planning', 'phases');
|
||||
const roadmapPath = path.join(cwd, '.planning', 'ROADMAP.md');
|
||||
const reqPath = path.join(cwd, '.planning', 'REQUIREMENTS.md');
|
||||
const statePath = path.join(cwd, '.planning', 'STATE.md');
|
||||
const phasesDir = planningPaths(cwd).phases;
|
||||
const roadmapPath = planningPaths(cwd).roadmap;
|
||||
const reqPath = planningPaths(cwd).requirements;
|
||||
const statePath = planningPaths(cwd).state;
|
||||
const milestone = getMilestoneInfo(cwd);
|
||||
const isDirInMilestone = getMilestonePhaseFilter(cwd);
|
||||
|
||||
@@ -547,7 +746,7 @@ function cmdStats(cwd, format, raw) {
|
||||
let totalSummaries = 0;
|
||||
|
||||
try {
|
||||
const roadmapContent = stripShippedMilestones(fs.readFileSync(roadmapPath, 'utf-8'));
|
||||
const roadmapContent = extractCurrentMilestone(fs.readFileSync(roadmapPath, 'utf-8'), cwd);
|
||||
const headingPattern = /#{2,4}\s*Phase\s+(\d+[A-Z]?(?:\.\d+)*)\s*:\s*([^\n]+)/gi;
|
||||
let match;
|
||||
while ((match = headingPattern.exec(roadmapContent)) !== null) {
|
||||
@@ -559,7 +758,7 @@ function cmdStats(cwd, format, raw) {
|
||||
status: 'Not Started',
|
||||
});
|
||||
}
|
||||
} catch {}
|
||||
} catch { /* intentionally empty */ }
|
||||
|
||||
try {
|
||||
const entries = fs.readdirSync(phasesDir, { withFileTypes: true });
|
||||
@@ -595,7 +794,7 @@ function cmdStats(cwd, format, raw) {
|
||||
status,
|
||||
});
|
||||
}
|
||||
} catch {}
|
||||
} catch { /* intentionally empty */ }
|
||||
|
||||
const phases = [...phasesByNumber.values()].sort((a, b) => comparePhaseNum(a.number, b.number));
|
||||
const completedPhases = phases.filter(p => p.status === 'Complete').length;
|
||||
@@ -613,7 +812,7 @@ function cmdStats(cwd, format, raw) {
|
||||
requirementsComplete = checked ? checked.length : 0;
|
||||
requirementsTotal = requirementsComplete + (unchecked ? unchecked.length : 0);
|
||||
}
|
||||
} catch {}
|
||||
} catch { /* intentionally empty */ }
|
||||
|
||||
// Last activity from STATE.md
|
||||
let lastActivity = null;
|
||||
@@ -626,7 +825,7 @@ function cmdStats(cwd, format, raw) {
|
||||
|| stateContent.match(/^Last activity:\s*(.+)$/im);
|
||||
if (activityMatch) lastActivity = activityMatch[1].trim();
|
||||
}
|
||||
} catch {}
|
||||
} catch { /* intentionally empty */ }
|
||||
|
||||
// Git stats
|
||||
let gitCommits = 0;
|
||||
@@ -700,10 +899,12 @@ module.exports = {
|
||||
cmdHistoryDigest,
|
||||
cmdResolveModel,
|
||||
cmdCommit,
|
||||
cmdCommitToSubrepo,
|
||||
cmdSummaryExtract,
|
||||
cmdWebsearch,
|
||||
cmdProgressRender,
|
||||
cmdTodoComplete,
|
||||
cmdTodoMatchPhase,
|
||||
cmdScaffold,
|
||||
cmdStats,
|
||||
};
|
||||
|
||||
@@ -16,8 +16,9 @@ const VALID_CONFIG_KEYS = new Set([
|
||||
'search_gitignored', 'brave_search',
|
||||
'workflow.research', 'workflow.plan_check', 'workflow.verifier',
|
||||
'workflow.nyquist_validation', 'workflow.ui_phase', 'workflow.ui_safety_gate',
|
||||
'workflow.text_mode',
|
||||
'workflow._auto_chain_active',
|
||||
'git.branching_strategy', 'git.phase_branch_template', 'git.milestone_branch_template',
|
||||
'git.branching_strategy', 'git.phase_branch_template', 'git.milestone_branch_template', 'git.quick_branch_template',
|
||||
'planning.commit_docs', 'planning.search_gitignored',
|
||||
]);
|
||||
|
||||
@@ -76,7 +77,7 @@ function ensureConfigFile(cwd) {
|
||||
delete userDefaults.depth;
|
||||
try {
|
||||
fs.writeFileSync(globalDefaultsPath, JSON.stringify(userDefaults, null, 2), 'utf-8');
|
||||
} catch {}
|
||||
} catch { /* intentionally empty */ }
|
||||
}
|
||||
}
|
||||
} catch (err) {
|
||||
@@ -91,6 +92,7 @@ function ensureConfigFile(cwd) {
|
||||
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,
|
||||
|
||||
@@ -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,6 +14,102 @@ 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 ───────────────────────────────────────────────────────────
|
||||
|
||||
function output(result, raw, rawValue) {
|
||||
@@ -58,12 +154,18 @@ function loadConfig(cwd) {
|
||||
branching_strategy: 'none',
|
||||
phase_branch_template: 'gsd/phase-{phase}-{slug}',
|
||||
milestone_branch_template: 'gsd/{milestone}-{slug}',
|
||||
quick_branch_template: null,
|
||||
research: true,
|
||||
plan_checker: true,
|
||||
verifier: true,
|
||||
nyquist_validation: true,
|
||||
parallelization: true,
|
||||
brave_search: false,
|
||||
text_mode: false, // when true, use plain-text numbered lists instead of AskUserQuestion menus
|
||||
sub_repos: [],
|
||||
resolve_model_ids: false, // when true, resolve aliases (opus/sonnet/haiku) to full model IDs
|
||||
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)
|
||||
};
|
||||
|
||||
try {
|
||||
@@ -75,6 +177,39 @@ function loadConfig(cwd) {
|
||||
const depthToGranularity = { quick: 'coarse', standard: 'standard', comprehensive: 'fine' };
|
||||
parsed.granularity = depthToGranularity[parsed.depth] || parsed.depth;
|
||||
delete parsed.depth;
|
||||
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 {}
|
||||
}
|
||||
|
||||
@@ -100,12 +235,18 @@ function loadConfig(cwd) {
|
||||
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,
|
||||
milestone_branch_template: get('milestone_branch_template', { section: 'git', field: 'milestone_branch_template' }) ?? defaults.milestone_branch_template,
|
||||
quick_branch_template: get('quick_branch_template', { section: 'git', field: 'quick_branch_template' }) ?? defaults.quick_branch_template,
|
||||
research: get('research', { section: 'workflow', field: 'research' }) ?? defaults.research,
|
||||
plan_checker: get('plan_checker', { section: 'workflow', field: 'plan_check' }) ?? defaults.plan_checker,
|
||||
verifier: get('verifier', { section: 'workflow', field: 'verifier' }) ?? defaults.verifier,
|
||||
nyquist_validation: get('nyquist_validation', { section: 'workflow', field: 'nyquist_validation' }) ?? defaults.nyquist_validation,
|
||||
parallelization,
|
||||
brave_search: get('brave_search') ?? defaults.brave_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,
|
||||
model_overrides: parsed.model_overrides || null,
|
||||
};
|
||||
} catch {
|
||||
@@ -121,7 +262,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',
|
||||
});
|
||||
@@ -248,6 +391,105 @@ 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');
|
||||
}
|
||||
|
||||
/** Get common .planning file paths */
|
||||
function planningPaths(cwd) {
|
||||
const base = path.join(cwd, '.planning');
|
||||
return {
|
||||
planning: base,
|
||||
state: path.join(base, 'STATE.md'),
|
||||
roadmap: path.join(base, 'ROADMAP.md'),
|
||||
project: path.join(base, 'PROJECT.md'),
|
||||
config: path.join(base, 'config.json'),
|
||||
phases: path.join(base, 'phases'),
|
||||
requirements: path.join(base, 'REQUIREMENTS.md'),
|
||||
};
|
||||
}
|
||||
|
||||
// ─── Phase utilities ──────────────────────────────────────────────────────────
|
||||
|
||||
function escapeRegex(value) {
|
||||
@@ -255,17 +497,23 @@ function escapeRegex(value) {
|
||||
}
|
||||
|
||||
function normalizePhaseName(phase) {
|
||||
const match = String(phase).match(/^(\d+)([A-Z])?((?:\.\d+)*)/i);
|
||||
if (!match) return phase;
|
||||
const padded = match[1].padStart(2, '0');
|
||||
const letter = match[2] ? match[2].toUpperCase() : '';
|
||||
const decimal = match[3] || '';
|
||||
return padded + letter + decimal;
|
||||
const str = String(phase);
|
||||
// Standard numeric phases: 1, 01, 12A, 12.1
|
||||
const match = str.match(/^(\d+)([A-Z])?((?:\.\d+)*)/i);
|
||||
if (match) {
|
||||
const padded = match[1].padStart(2, '0');
|
||||
const letter = match[2] ? match[2].toUpperCase() : '';
|
||||
const decimal = match[3] || '';
|
||||
return padded + letter + decimal;
|
||||
}
|
||||
// Custom phase IDs (e.g. PROJ-42, AUTH-101): return as-is
|
||||
return str;
|
||||
}
|
||||
|
||||
function comparePhaseNum(a, b) {
|
||||
const pa = String(a).match(/^(\d+)([A-Z])?((?:\.\d+)*)/i);
|
||||
const pb = String(b).match(/^(\d+)([A-Z])?((?:\.\d+)*)/i);
|
||||
// If either is non-numeric (custom ID), fall back to string comparison
|
||||
if (!pa || !pb) return String(a).localeCompare(String(b));
|
||||
const intDiff = parseInt(pa[1], 10) - parseInt(pb[1], 10);
|
||||
if (intDiff !== 0) return intDiff;
|
||||
@@ -295,10 +543,19 @@ function searchPhaseInDir(baseDir, relBase, normalized) {
|
||||
try {
|
||||
const entries = fs.readdirSync(baseDir, { withFileTypes: true });
|
||||
const dirs = entries.filter(e => e.isDirectory()).map(e => e.name).sort((a, b) => comparePhaseNum(a, b));
|
||||
const match = dirs.find(d => d.startsWith(normalized));
|
||||
// Match: starts with normalized (numeric) OR contains normalized as prefix segment (custom ID)
|
||||
const match = dirs.find(d => {
|
||||
if (d.startsWith(normalized)) return true;
|
||||
// For custom IDs like PROJ-42, match case-insensitively
|
||||
if (d.toUpperCase().startsWith(normalized.toUpperCase())) return true;
|
||||
return false;
|
||||
});
|
||||
if (!match) return null;
|
||||
|
||||
const dirMatch = match.match(/^(\d+[A-Z]?(?:\.\d+)*)-?(.*)/i);
|
||||
// Extract phase number and name — supports both numeric (01-name) and custom (PROJ-42-name)
|
||||
const dirMatch = match.match(/^(\d+[A-Z]?(?:\.\d+)*)-?(.*)/i)
|
||||
|| match.match(/^([A-Z][A-Z0-9]*(?:-[A-Z0-9]+)*)-(.+)/i)
|
||||
|| [null, match, null];
|
||||
const phaseNumber = dirMatch ? dirMatch[1] : normalized;
|
||||
const phaseName = dirMatch && dirMatch[2] ? dirMatch[2] : null;
|
||||
const phaseDir = path.join(baseDir, match);
|
||||
@@ -368,7 +625,7 @@ function findPhaseInternal(cwd, phase) {
|
||||
return result;
|
||||
}
|
||||
}
|
||||
} catch {}
|
||||
} catch { /* intentionally empty */ }
|
||||
|
||||
return null;
|
||||
}
|
||||
@@ -403,7 +660,7 @@ function getArchivedPhaseDirs(cwd) {
|
||||
});
|
||||
}
|
||||
}
|
||||
} catch {}
|
||||
} catch { /* intentionally empty */ }
|
||||
|
||||
return results;
|
||||
}
|
||||
@@ -420,6 +677,91 @@ function stripShippedMilestones(content) {
|
||||
return content.replace(/<details>[\s\S]*?<\/details>/gi, '');
|
||||
}
|
||||
|
||||
/**
|
||||
* Extract the current milestone section from ROADMAP.md by positive lookup.
|
||||
*
|
||||
* Instead of stripping <details> blocks (negative heuristic that breaks if
|
||||
* agents wrap the current milestone in <details>), this finds the section
|
||||
* matching the current milestone version and returns only that content.
|
||||
*
|
||||
* Falls back to stripShippedMilestones() if:
|
||||
* - cwd is not provided
|
||||
* - STATE.md doesn't exist or has no milestone field
|
||||
* - Version can't be found in ROADMAP.md
|
||||
*
|
||||
* @param {string} content - Full ROADMAP.md content
|
||||
* @param {string} [cwd] - Working directory for reading STATE.md
|
||||
* @returns {string} Content scoped to current milestone
|
||||
*/
|
||||
function extractCurrentMilestone(content, cwd) {
|
||||
if (!cwd) return stripShippedMilestones(content);
|
||||
|
||||
// 1. Get current milestone version from STATE.md frontmatter
|
||||
let version = null;
|
||||
try {
|
||||
const statePath = path.join(cwd, '.planning', 'STATE.md');
|
||||
if (fs.existsSync(statePath)) {
|
||||
const stateRaw = fs.readFileSync(statePath, 'utf-8');
|
||||
const milestoneMatch = stateRaw.match(/^milestone:\s*(.+)/m);
|
||||
if (milestoneMatch) {
|
||||
version = milestoneMatch[1].trim();
|
||||
}
|
||||
}
|
||||
} catch {}
|
||||
|
||||
// 2. Fallback: derive version from getMilestoneInfo pattern in ROADMAP.md itself
|
||||
if (!version) {
|
||||
// Check for 🚧 in-progress marker
|
||||
const inProgressMatch = content.match(/🚧\s*\*\*v(\d+\.\d+)\s/);
|
||||
if (inProgressMatch) {
|
||||
version = 'v' + inProgressMatch[1];
|
||||
}
|
||||
}
|
||||
|
||||
if (!version) return stripShippedMilestones(content);
|
||||
|
||||
// 3. Find the section matching this version
|
||||
// Match headings like: ## Roadmap v3.0: Name, ## v3.0 Name, etc.
|
||||
const escapedVersion = escapeRegex(version);
|
||||
const sectionPattern = new RegExp(
|
||||
`(^#{1,3}\\s+.*${escapedVersion}[^\\n]*)`,
|
||||
'mi'
|
||||
);
|
||||
const sectionMatch = content.match(sectionPattern);
|
||||
|
||||
if (!sectionMatch) return stripShippedMilestones(content);
|
||||
|
||||
const sectionStart = sectionMatch.index;
|
||||
|
||||
// Find the end: next milestone heading at same or higher level, or EOF
|
||||
// Milestone headings look like: ## v2.0, ## Roadmap v2.0, ## ✅ v1.0, etc.
|
||||
const headingLevel = sectionMatch[1].match(/^(#{1,3})\s/)[1].length;
|
||||
const restContent = content.slice(sectionStart + sectionMatch[0].length);
|
||||
const nextMilestonePattern = new RegExp(
|
||||
`^#{1,${headingLevel}}\\s+(?:.*v\\d+\\.\\d+|✅|📋|🚧)`,
|
||||
'mi'
|
||||
);
|
||||
const nextMatch = restContent.match(nextMilestonePattern);
|
||||
|
||||
let sectionEnd;
|
||||
if (nextMatch) {
|
||||
sectionEnd = sectionStart + sectionMatch[0].length + nextMatch.index;
|
||||
} else {
|
||||
sectionEnd = content.length;
|
||||
}
|
||||
|
||||
// Return everything before the current milestone section (non-milestone content
|
||||
// like title, overview) plus the current milestone section
|
||||
const beforeMilestones = content.slice(0, sectionStart);
|
||||
const currentSection = content.slice(sectionStart, sectionEnd);
|
||||
|
||||
// Also include any content before the first milestone heading (title, overview, etc.)
|
||||
// but strip any <details> blocks in it (these are definitely shipped)
|
||||
const preamble = beforeMilestones.replace(/<details>[\s\S]*?<\/details>/gi, '');
|
||||
|
||||
return preamble + currentSection;
|
||||
}
|
||||
|
||||
/**
|
||||
* Replace a pattern only in the current milestone section of ROADMAP.md
|
||||
* (everything after the last </details> close tag). Used for write operations
|
||||
@@ -444,8 +786,9 @@ function getRoadmapPhaseInternal(cwd, phaseNum) {
|
||||
if (!fs.existsSync(roadmapPath)) return null;
|
||||
|
||||
try {
|
||||
const content = stripShippedMilestones(fs.readFileSync(roadmapPath, 'utf-8'));
|
||||
const content = extractCurrentMilestone(fs.readFileSync(roadmapPath, 'utf-8'), cwd);
|
||||
const escapedPhase = escapeRegex(phaseNum.toString());
|
||||
// Match both numeric (Phase 1:) and custom (Phase PROJ-42:) headers
|
||||
const phasePattern = new RegExp(`#{2,4}\\s*Phase\\s+${escapedPhase}:\\s*([^\\n]+)`, 'i');
|
||||
const headerMatch = content.match(phasePattern);
|
||||
if (!headerMatch) return null;
|
||||
@@ -453,7 +796,7 @@ function getRoadmapPhaseInternal(cwd, phaseNum) {
|
||||
const phaseName = headerMatch[1].trim();
|
||||
const headerIndex = headerMatch.index;
|
||||
const restOfContent = content.slice(headerIndex);
|
||||
const nextHeaderMatch = restOfContent.match(/\n#{2,4}\s+Phase\s+\d/i);
|
||||
const nextHeaderMatch = restOfContent.match(/\n#{2,4}\s+Phase\s+[\w]/i);
|
||||
const sectionEnd = nextHeaderMatch ? headerIndex + nextHeaderMatch.index : content.length;
|
||||
const section = content.slice(headerIndex, sectionEnd).trim();
|
||||
|
||||
@@ -472,6 +815,19 @@ function getRoadmapPhaseInternal(cwd, phaseNum) {
|
||||
}
|
||||
}
|
||||
|
||||
// ─── Model alias resolution ───────────────────────────────────────────────────
|
||||
|
||||
/**
|
||||
* Map short model aliases to full model IDs.
|
||||
* Updated each release to match current model versions.
|
||||
* Users can override with model_overrides in config.json for custom/latest models.
|
||||
*/
|
||||
const MODEL_ALIAS_MAP = {
|
||||
'opus': 'claude-opus-4-0',
|
||||
'sonnet': 'claude-sonnet-4-5',
|
||||
'haiku': 'claude-haiku-3-5',
|
||||
};
|
||||
|
||||
function resolveModelInternal(cwd, agentType) {
|
||||
const config = loadConfig(cwd);
|
||||
|
||||
@@ -486,7 +842,32 @@ function resolveModelInternal(cwd, agentType) {
|
||||
const agentModels = MODEL_PROFILES[agentType];
|
||||
if (!agentModels) return 'sonnet';
|
||||
if (profile === 'inherit') return 'inherit';
|
||||
return agentModels[profile] || agentModels['balanced'] || 'sonnet';
|
||||
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
|
||||
if (config.resolve_model_ids) {
|
||||
return MODEL_ALIAS_MAP[alias] || alias;
|
||||
}
|
||||
|
||||
return alias;
|
||||
}
|
||||
|
||||
// ─── Summary body helpers ─────────────────────────────────────────────────
|
||||
|
||||
/**
|
||||
* Extract a one-liner from the summary body when it's not in frontmatter.
|
||||
* The summary template defines one-liner as a bold markdown line after the heading:
|
||||
* # Phase X: Name Summary
|
||||
* **[substantive one-liner text]**
|
||||
*/
|
||||
function extractOneLinerFromBody(content) {
|
||||
if (!content) return null;
|
||||
// Strip frontmatter first
|
||||
const body = content.replace(/^---\n[\s\S]*?\n---\n*/, '');
|
||||
// Find the first **...** line after a # heading
|
||||
const match = body.match(/^#[^\n]*\n+\*\*([^*]+)\*\*/m);
|
||||
return match ? match[1].trim() : null;
|
||||
}
|
||||
|
||||
// ─── Misc utilities ───────────────────────────────────────────────────────────
|
||||
@@ -512,7 +893,8 @@ function getMilestoneInfo(cwd) {
|
||||
|
||||
// First: check for list-format roadmaps using 🚧 (in-progress) marker
|
||||
// e.g. "- 🚧 **v2.1 Belgium** — Phases 24-28 (in progress)"
|
||||
const inProgressMatch = roadmap.match(/🚧\s*\*\*v(\d+\.\d+)\s+([^*]+)\*\*/);
|
||||
// e.g. "- 🚧 **v1.2.1 Tech Debt** — Phases 1-8 (in progress)"
|
||||
const inProgressMatch = roadmap.match(/🚧\s*\*\*v(\d+(?:\.\d+)+)\s+([^*]+)\*\*/);
|
||||
if (inProgressMatch) {
|
||||
return {
|
||||
version: 'v' + inProgressMatch[1],
|
||||
@@ -523,15 +905,16 @@ function getMilestoneInfo(cwd) {
|
||||
// Second: heading-format roadmaps — strip shipped milestones in <details> blocks
|
||||
const cleaned = stripShippedMilestones(roadmap);
|
||||
// Extract version and name from the same ## heading for consistency
|
||||
const headingMatch = cleaned.match(/## .*v(\d+\.\d+)[:\s]+([^\n(]+)/);
|
||||
// Supports 2+ segment versions: v1.2, v1.2.1, v2.0.1, etc.
|
||||
const headingMatch = cleaned.match(/## .*v(\d+(?:\.\d+)+)[:\s]+([^\n(]+)/);
|
||||
if (headingMatch) {
|
||||
return {
|
||||
version: 'v' + headingMatch[1],
|
||||
name: headingMatch[2].trim(),
|
||||
};
|
||||
}
|
||||
// Fallback: try bare version match
|
||||
const versionMatch = cleaned.match(/v(\d+\.\d+)/);
|
||||
// Fallback: try bare version match (greedy — capture longest version string)
|
||||
const versionMatch = cleaned.match(/v(\d+(?:\.\d+)+)/);
|
||||
return {
|
||||
version: versionMatch ? versionMatch[0] : 'v1.0',
|
||||
name: 'milestone',
|
||||
@@ -549,13 +932,14 @@ function getMilestoneInfo(cwd) {
|
||||
function getMilestonePhaseFilter(cwd) {
|
||||
const milestonePhaseNums = new Set();
|
||||
try {
|
||||
const roadmap = stripShippedMilestones(fs.readFileSync(path.join(cwd, '.planning', 'ROADMAP.md'), 'utf-8'));
|
||||
const phasePattern = /#{2,4}\s*Phase\s+(\d+[A-Z]?(?:\.\d+)*)\s*:/gi;
|
||||
const roadmap = extractCurrentMilestone(fs.readFileSync(path.join(cwd, '.planning', 'ROADMAP.md'), 'utf-8'), cwd);
|
||||
// Match both numeric phases (Phase 1:) and custom IDs (Phase PROJ-42:)
|
||||
const phasePattern = /#{2,4}\s*Phase\s+([\w][\w.-]*)\s*:/gi;
|
||||
let m;
|
||||
while ((m = phasePattern.exec(roadmap)) !== null) {
|
||||
milestonePhaseNums.add(m[1]);
|
||||
}
|
||||
} catch {}
|
||||
} catch { /* intentionally empty */ }
|
||||
|
||||
if (milestonePhaseNums.size === 0) {
|
||||
const passAll = () => true;
|
||||
@@ -568,9 +952,13 @@ function getMilestonePhaseFilter(cwd) {
|
||||
);
|
||||
|
||||
function isDirInMilestone(dirName) {
|
||||
// Try numeric match first
|
||||
const m = dirName.match(/^0*(\d+[A-Za-z]?(?:\.\d+)*)/);
|
||||
if (!m) return false;
|
||||
return normalized.has(m[1].toLowerCase());
|
||||
if (m && normalized.has(m[1].toLowerCase())) return true;
|
||||
// Try custom ID match (e.g. PROJ-42-description → PROJ-42)
|
||||
const customMatch = dirName.match(/^([A-Za-z][A-Za-z0-9]*(?:-[A-Za-z0-9]+)*)/);
|
||||
if (customMatch && normalized.has(customMatch[1].toLowerCase())) return true;
|
||||
return false;
|
||||
}
|
||||
isDirInMilestone.phaseCount = milestonePhaseNums.size;
|
||||
return isDirInMilestone;
|
||||
@@ -597,6 +985,15 @@ module.exports = {
|
||||
getMilestoneInfo,
|
||||
getMilestonePhaseFilter,
|
||||
stripShippedMilestones,
|
||||
extractCurrentMilestone,
|
||||
replaceInCurrentMilestone,
|
||||
toPosixPath,
|
||||
extractOneLinerFromBody,
|
||||
resolveWorktreeRoot,
|
||||
withPlanningLock,
|
||||
findProjectRoot,
|
||||
detectSubRepos,
|
||||
MODEL_ALIAS_MAP,
|
||||
planningDir,
|
||||
planningPaths,
|
||||
};
|
||||
|
||||
@@ -10,7 +10,11 @@ const { safeReadFile, normalizeMd, output, error } = require('./core.cjs');
|
||||
|
||||
function extractFrontmatter(content) {
|
||||
const frontmatter = {};
|
||||
const match = content.match(/^---\r?\n([\s\S]+?)\r?\n---/);
|
||||
// Find ALL frontmatter blocks at the start of the file.
|
||||
// If multiple blocks exist (corruption from CRLF mismatch), use the LAST one
|
||||
// since it represents the most recent state sync.
|
||||
const allBlocks = [...content.matchAll(/(?:^|\n)\s*---\r?\n([\s\S]+?)\r?\n---/g)];
|
||||
const match = allBlocks.length > 0 ? allBlocks[allBlocks.length - 1] : null;
|
||||
if (!match) return frontmatter;
|
||||
|
||||
const yaml = match[1];
|
||||
|
||||
@@ -5,7 +5,34 @@
|
||||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
const { execSync } = require('child_process');
|
||||
const { loadConfig, resolveModelInternal, findPhaseInternal, getRoadmapPhaseInternal, pathExistsInternal, generateSlugInternal, getMilestoneInfo, getMilestonePhaseFilter, stripShippedMilestones, normalizePhaseName, toPosixPath, output, error } = require('./core.cjs');
|
||||
const { loadConfig, resolveModelInternal, findPhaseInternal, getRoadmapPhaseInternal, pathExistsInternal, generateSlugInternal, getMilestoneInfo, getMilestonePhaseFilter, stripShippedMilestones, extractCurrentMilestone, normalizePhaseName, toPosixPath, output, error } = require('./core.cjs');
|
||||
|
||||
function getLatestCompletedMilestone(cwd) {
|
||||
const milestonesPath = path.join(cwd, '.planning', 'MILESTONES.md');
|
||||
if (!fs.existsSync(milestonesPath)) return null;
|
||||
|
||||
try {
|
||||
const content = fs.readFileSync(milestonesPath, 'utf-8');
|
||||
const match = content.match(/^##\s+(v[\d.]+)\s+(.+?)\s+\(Shipped:/m);
|
||||
if (!match) return null;
|
||||
return {
|
||||
version: match[1],
|
||||
name: match[2].trim(),
|
||||
};
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 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) {
|
||||
@@ -30,7 +57,9 @@ 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,
|
||||
phase_branch_template: config.phase_branch_template,
|
||||
milestone_branch_template: config.milestone_branch_template,
|
||||
@@ -77,7 +106,7 @@ function cmdInitExecutePhase(cwd, phase, raw) {
|
||||
config_path: '.planning/config.json',
|
||||
};
|
||||
|
||||
output(result, raw);
|
||||
output(withProjectRoot(cwd, result), raw);
|
||||
}
|
||||
|
||||
function cmdInitPlanPhase(cwd, phase, raw) {
|
||||
@@ -153,10 +182,10 @@ function cmdInitPlanPhase(cwd, phase, raw) {
|
||||
if (uatFile) {
|
||||
result.uat_path = toPosixPath(path.join(phaseInfo.directory, uatFile));
|
||||
}
|
||||
} catch {}
|
||||
} catch { /* intentionally empty */ }
|
||||
}
|
||||
|
||||
output(result, raw);
|
||||
output(withProjectRoot(cwd, result), raw);
|
||||
}
|
||||
|
||||
function cmdInitNewProject(cwd, raw) {
|
||||
@@ -167,17 +196,26 @@ function cmdInitNewProject(cwd, raw) {
|
||||
const braveKeyFile = path.join(homedir, '.gsd', 'brave_api_key');
|
||||
const hasBraveSearch = !!(process.env.BRAVE_API_KEY || fs.existsSync(braveKeyFile));
|
||||
|
||||
// Detect existing code
|
||||
// Detect existing code (cross-platform — no Unix `find` dependency)
|
||||
let hasCode = false;
|
||||
let hasPackageFile = false;
|
||||
try {
|
||||
const files = execSync('find . -maxdepth 3 \\( -name "*.ts" -o -name "*.js" -o -name "*.py" -o -name "*.go" -o -name "*.rs" -o -name "*.swift" -o -name "*.java" \\) 2>/dev/null | grep -v node_modules | grep -v .git | head -5', {
|
||||
cwd,
|
||||
encoding: 'utf-8',
|
||||
stdio: ['pipe', 'pipe', 'pipe'],
|
||||
});
|
||||
hasCode = files.trim().length > 0;
|
||||
} catch {}
|
||||
const codeExtensions = new Set(['.ts', '.js', '.py', '.go', '.rs', '.swift', '.java']);
|
||||
const skipDirs = new Set(['node_modules', '.git', '.planning', '.claude', '__pycache__', 'target', 'dist', 'build']);
|
||||
function findCodeFiles(dir, depth) {
|
||||
if (depth > 3) return false;
|
||||
let entries;
|
||||
try { entries = fs.readdirSync(dir, { withFileTypes: true }); } catch { return false; }
|
||||
for (const entry of entries) {
|
||||
if (entry.isFile() && codeExtensions.has(path.extname(entry.name))) return true;
|
||||
if (entry.isDirectory() && !skipDirs.has(entry.name)) {
|
||||
if (findCodeFiles(path.join(dir, entry.name), depth + 1)) return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
hasCode = findCodeFiles(cwd, 0);
|
||||
} catch { /* intentionally empty — best-effort detection */ }
|
||||
|
||||
hasPackageFile = pathExistsInternal(cwd, 'package.json') ||
|
||||
pathExistsInternal(cwd, 'requirements.txt') ||
|
||||
@@ -215,12 +253,23 @@ function cmdInitNewProject(cwd, raw) {
|
||||
project_path: '.planning/PROJECT.md',
|
||||
};
|
||||
|
||||
output(result, raw);
|
||||
output(withProjectRoot(cwd, result), raw);
|
||||
}
|
||||
|
||||
function cmdInitNewMilestone(cwd, raw) {
|
||||
const config = loadConfig(cwd);
|
||||
const milestone = getMilestoneInfo(cwd);
|
||||
const latestCompleted = getLatestCompletedMilestone(cwd);
|
||||
const phasesDir = path.join(cwd, '.planning', 'phases');
|
||||
let phaseDirCount = 0;
|
||||
|
||||
try {
|
||||
if (fs.existsSync(phasesDir)) {
|
||||
phaseDirCount = fs.readdirSync(phasesDir, { withFileTypes: true })
|
||||
.filter(entry => entry.isDirectory())
|
||||
.length;
|
||||
}
|
||||
} catch {}
|
||||
|
||||
const result = {
|
||||
// Models
|
||||
@@ -235,6 +284,10 @@ function cmdInitNewMilestone(cwd, raw) {
|
||||
// Current milestone
|
||||
current_milestone: milestone.version,
|
||||
current_milestone_name: milestone.name,
|
||||
latest_completed_milestone: latestCompleted?.version || null,
|
||||
latest_completed_milestone_name: latestCompleted?.name || null,
|
||||
phase_dir_count: phaseDirCount,
|
||||
phase_archive_path: latestCompleted ? `.planning/milestones/${latestCompleted.version}-phases` : null,
|
||||
|
||||
// File existence
|
||||
project_exists: pathExistsInternal(cwd, '.planning/PROJECT.md'),
|
||||
@@ -247,7 +300,7 @@ function cmdInitNewMilestone(cwd, raw) {
|
||||
state_path: '.planning/STATE.md',
|
||||
};
|
||||
|
||||
output(result, raw);
|
||||
output(withProjectRoot(cwd, result), raw);
|
||||
}
|
||||
|
||||
function cmdInitQuick(cwd, description, raw) {
|
||||
@@ -267,6 +320,13 @@ function cmdInitQuick(cwd, description, raw) {
|
||||
const timeBlocks = Math.floor(secondsSinceMidnight / 2);
|
||||
const timeEncoded = timeBlocks.toString(36).padStart(3, '0');
|
||||
const quickId = dateStr + '-' + timeEncoded;
|
||||
const branchSlug = slug || 'quick';
|
||||
const quickBranchName = config.quick_branch_template
|
||||
? config.quick_branch_template
|
||||
.replace('{num}', quickId)
|
||||
.replace('{quick}', quickId)
|
||||
.replace('{slug}', branchSlug)
|
||||
: null;
|
||||
|
||||
const result = {
|
||||
// Models
|
||||
@@ -277,6 +337,7 @@ function cmdInitQuick(cwd, description, raw) {
|
||||
|
||||
// Config
|
||||
commit_docs: config.commit_docs,
|
||||
branch_name: quickBranchName,
|
||||
|
||||
// Quick task info
|
||||
quick_id: quickId,
|
||||
@@ -297,7 +358,7 @@ function cmdInitQuick(cwd, description, raw) {
|
||||
|
||||
};
|
||||
|
||||
output(result, raw);
|
||||
output(withProjectRoot(cwd, result), raw);
|
||||
}
|
||||
|
||||
function cmdInitResume(cwd, raw) {
|
||||
@@ -307,7 +368,7 @@ function cmdInitResume(cwd, raw) {
|
||||
let interruptedAgentId = null;
|
||||
try {
|
||||
interruptedAgentId = fs.readFileSync(path.join(cwd, '.planning', 'current-agent-id.txt'), 'utf-8').trim();
|
||||
} catch {}
|
||||
} catch { /* intentionally empty */ }
|
||||
|
||||
const result = {
|
||||
// File existence
|
||||
@@ -329,7 +390,7 @@ function cmdInitResume(cwd, raw) {
|
||||
commit_docs: config.commit_docs,
|
||||
};
|
||||
|
||||
output(result, raw);
|
||||
output(withProjectRoot(cwd, result), raw);
|
||||
}
|
||||
|
||||
function cmdInitVerifyWork(cwd, phase, raw) {
|
||||
@@ -358,7 +419,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) {
|
||||
@@ -459,10 +520,10 @@ function cmdInitPhaseOp(cwd, phase, raw) {
|
||||
if (uatFile) {
|
||||
result.uat_path = toPosixPath(path.join(phaseInfo.directory, uatFile));
|
||||
}
|
||||
} catch {}
|
||||
} catch { /* intentionally empty */ }
|
||||
}
|
||||
|
||||
output(result, raw);
|
||||
output(withProjectRoot(cwd, result), raw);
|
||||
}
|
||||
|
||||
function cmdInitTodos(cwd, area, raw) {
|
||||
@@ -494,9 +555,9 @@ function cmdInitTodos(cwd, area, raw) {
|
||||
area: todoArea,
|
||||
path: '.planning/todos/pending/' + file,
|
||||
});
|
||||
} catch {}
|
||||
} catch { /* intentionally empty */ }
|
||||
}
|
||||
} catch {}
|
||||
} catch { /* intentionally empty */ }
|
||||
|
||||
const result = {
|
||||
// Config
|
||||
@@ -521,7 +582,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) {
|
||||
@@ -543,9 +604,9 @@ function cmdInitMilestoneOp(cwd, raw) {
|
||||
const phaseFiles = fs.readdirSync(path.join(phasesDir, dir));
|
||||
const hasSummary = phaseFiles.some(f => f.endsWith('-SUMMARY.md') || f === 'SUMMARY.md');
|
||||
if (hasSummary) completedPhases++;
|
||||
} catch {}
|
||||
} catch { /* intentionally empty */ }
|
||||
}
|
||||
} catch {}
|
||||
} catch { /* intentionally empty */ }
|
||||
|
||||
// Check archive
|
||||
const archiveDir = path.join(cwd, '.planning', 'archive');
|
||||
@@ -554,7 +615,7 @@ function cmdInitMilestoneOp(cwd, raw) {
|
||||
archivedMilestones = fs.readdirSync(archiveDir, { withFileTypes: true })
|
||||
.filter(e => e.isDirectory())
|
||||
.map(e => e.name);
|
||||
} catch {}
|
||||
} catch { /* intentionally empty */ }
|
||||
|
||||
const result = {
|
||||
// Config
|
||||
@@ -582,7 +643,7 @@ function cmdInitMilestoneOp(cwd, raw) {
|
||||
phases_dir_exists: pathExistsInternal(cwd, '.planning/phases'),
|
||||
};
|
||||
|
||||
output(result, raw);
|
||||
output(withProjectRoot(cwd, result), raw);
|
||||
}
|
||||
|
||||
function cmdInitMapCodebase(cwd, raw) {
|
||||
@@ -593,7 +654,7 @@ function cmdInitMapCodebase(cwd, raw) {
|
||||
let existingMaps = [];
|
||||
try {
|
||||
existingMaps = fs.readdirSync(codebaseDir).filter(f => f.endsWith('.md'));
|
||||
} catch {}
|
||||
} catch { /* intentionally empty */ }
|
||||
|
||||
const result = {
|
||||
// Models
|
||||
@@ -616,7 +677,7 @@ function cmdInitMapCodebase(cwd, raw) {
|
||||
codebase_dir_exists: pathExistsInternal(cwd, '.planning/codebase'),
|
||||
};
|
||||
|
||||
output(result, raw);
|
||||
output(withProjectRoot(cwd, result), raw);
|
||||
}
|
||||
|
||||
function cmdInitProgress(cwd, raw) {
|
||||
@@ -633,8 +694,8 @@ function cmdInitProgress(cwd, raw) {
|
||||
const roadmapPhaseNums = new Set();
|
||||
const roadmapPhaseNames = new Map();
|
||||
try {
|
||||
const roadmapContent = stripShippedMilestones(
|
||||
fs.readFileSync(path.join(cwd, '.planning', 'ROADMAP.md'), 'utf-8')
|
||||
const roadmapContent = extractCurrentMilestone(
|
||||
fs.readFileSync(path.join(cwd, '.planning', 'ROADMAP.md'), 'utf-8'), cwd
|
||||
);
|
||||
const headingPattern = /#{2,4}\s*Phase\s+(\d+[A-Z]?(?:\.\d+)*)\s*:\s*([^\n]+)/gi;
|
||||
let hm;
|
||||
@@ -642,7 +703,7 @@ function cmdInitProgress(cwd, raw) {
|
||||
roadmapPhaseNums.add(hm[1]);
|
||||
roadmapPhaseNames.set(hm[1], hm[2].replace(/\(INSERTED\)/i, '').trim());
|
||||
}
|
||||
} catch {}
|
||||
} catch { /* intentionally empty */ }
|
||||
|
||||
const isDirInMilestone = getMilestonePhaseFilter(cwd);
|
||||
const seenPhaseNums = new Set();
|
||||
@@ -695,7 +756,7 @@ function cmdInitProgress(cwd, raw) {
|
||||
nextPhase = phaseInfo;
|
||||
}
|
||||
}
|
||||
} catch {}
|
||||
} catch { /* intentionally empty */ }
|
||||
|
||||
// Add phases defined in ROADMAP but not yet scaffolded to disk
|
||||
for (const [num, name] of roadmapPhaseNames) {
|
||||
@@ -726,7 +787,7 @@ function cmdInitProgress(cwd, raw) {
|
||||
const state = fs.readFileSync(path.join(cwd, '.planning', 'STATE.md'), 'utf-8');
|
||||
const pauseMatch = state.match(/\*\*Paused At:\*\*\s*(.+)/);
|
||||
if (pauseMatch) pausedAt = pauseMatch[1].trim();
|
||||
} catch {}
|
||||
} catch { /* intentionally empty */ }
|
||||
|
||||
const result = {
|
||||
// Models
|
||||
@@ -763,7 +824,7 @@ function cmdInitProgress(cwd, raw) {
|
||||
config_path: '.planning/config.json',
|
||||
};
|
||||
|
||||
output(result, raw);
|
||||
output(withProjectRoot(cwd, result), raw);
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
|
||||
@@ -4,9 +4,9 @@
|
||||
|
||||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
const { escapeRegex, getMilestonePhaseFilter, normalizeMd, output, error } = require('./core.cjs');
|
||||
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) {
|
||||
@@ -25,7 +25,7 @@ function cmdRequirementsMarkComplete(cwd, reqIdsRaw, raw) {
|
||||
error('no valid requirement IDs found');
|
||||
}
|
||||
|
||||
const reqPath = path.join(cwd, '.planning', 'REQUIREMENTS.md');
|
||||
const reqPath = planningPaths(cwd).requirements;
|
||||
if (!fs.existsSync(reqPath)) {
|
||||
output({ updated: false, reason: 'REQUIREMENTS.md not found', ids: reqIds }, raw, 'no requirements file');
|
||||
return;
|
||||
@@ -90,12 +90,12 @@ function cmdMilestoneComplete(cwd, version, options, raw) {
|
||||
error('version required for milestone complete (e.g., v1.0)');
|
||||
}
|
||||
|
||||
const roadmapPath = path.join(cwd, '.planning', 'ROADMAP.md');
|
||||
const reqPath = path.join(cwd, '.planning', 'REQUIREMENTS.md');
|
||||
const statePath = path.join(cwd, '.planning', 'STATE.md');
|
||||
const roadmapPath = planningPaths(cwd).roadmap;
|
||||
const reqPath = planningPaths(cwd).requirements;
|
||||
const statePath = planningPaths(cwd).state;
|
||||
const milestonesPath = path.join(cwd, '.planning', 'MILESTONES.md');
|
||||
const archiveDir = path.join(cwd, '.planning', 'milestones');
|
||||
const phasesDir = path.join(cwd, '.planning', 'phases');
|
||||
const phasesDir = planningPaths(cwd).phases;
|
||||
const today = new Date().toISOString().split('T')[0];
|
||||
const milestoneName = options.name || version;
|
||||
|
||||
@@ -131,16 +131,24 @@ function cmdMilestoneComplete(cwd, version, options, raw) {
|
||||
try {
|
||||
const content = fs.readFileSync(path.join(phasesDir, dir, s), 'utf-8');
|
||||
const fm = extractFrontmatter(content);
|
||||
if (fm['one-liner']) {
|
||||
accomplishments.push(fm['one-liner']);
|
||||
const oneLiner = fm['one-liner'] || extractOneLinerFromBody(content);
|
||||
if (oneLiner) {
|
||||
accomplishments.push(oneLiner);
|
||||
}
|
||||
// Count tasks
|
||||
const taskMatches = content.match(/##\s*Task\s*\d+/gi) || [];
|
||||
totalTasks += taskMatches.length;
|
||||
} catch {}
|
||||
// Count tasks: prefer **Tasks:** N from Performance section,
|
||||
// then <task XML tags, then ## Task N markdown headers
|
||||
const tasksFieldMatch = content.match(/\*\*Tasks:\*\*\s*(\d+)/);
|
||||
if (tasksFieldMatch) {
|
||||
totalTasks += parseInt(tasksFieldMatch[1], 10);
|
||||
} else {
|
||||
const xmlTaskMatches = content.match(/<task[\s>]/gi) || [];
|
||||
const mdTaskMatches = content.match(/##\s*Task\s*\d+/gi) || [];
|
||||
totalTasks += xmlTaskMatches.length || mdTaskMatches.length;
|
||||
}
|
||||
} catch { /* intentionally empty */ }
|
||||
}
|
||||
}
|
||||
} catch {}
|
||||
} catch { /* intentionally empty */ }
|
||||
|
||||
// Archive ROADMAP.md
|
||||
if (fs.existsSync(roadmapPath)) {
|
||||
@@ -186,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);
|
||||
}
|
||||
|
||||
@@ -220,7 +222,7 @@ function cmdMilestoneComplete(cwd, version, options, raw) {
|
||||
archivedCount++;
|
||||
}
|
||||
phasesArchived = archivedCount > 0;
|
||||
} catch {}
|
||||
} catch { /* intentionally empty */ }
|
||||
}
|
||||
|
||||
const result = {
|
||||
|
||||
@@ -4,9 +4,9 @@
|
||||
|
||||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
const { escapeRegex, normalizePhaseName, comparePhaseNum, findPhaseInternal, getArchivedPhaseDirs, generateSlugInternal, getMilestonePhaseFilter, stripShippedMilestones, replaceInCurrentMilestone, toPosixPath, output, error } = require('./core.cjs');
|
||||
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');
|
||||
@@ -308,32 +308,44 @@ function cmdPhasePlanIndex(cwd, phase, raw) {
|
||||
output(result, raw);
|
||||
}
|
||||
|
||||
function cmdPhaseAdd(cwd, description, raw) {
|
||||
function cmdPhaseAdd(cwd, description, raw, customId) {
|
||||
if (!description) {
|
||||
error('description required for phase add');
|
||||
}
|
||||
|
||||
const config = loadConfig(cwd);
|
||||
const roadmapPath = path.join(cwd, '.planning', 'ROADMAP.md');
|
||||
if (!fs.existsSync(roadmapPath)) {
|
||||
error('ROADMAP.md not found');
|
||||
}
|
||||
|
||||
const rawContent = fs.readFileSync(roadmapPath, 'utf-8');
|
||||
const content = stripShippedMilestones(rawContent);
|
||||
const content = extractCurrentMilestone(rawContent, cwd);
|
||||
const slug = generateSlugInternal(description);
|
||||
|
||||
// Find highest integer phase number (in current milestone only)
|
||||
const phasePattern = /#{2,4}\s*Phase\s+(\d+)[A-Z]?(?:\.\d+)*:/gi;
|
||||
let maxPhase = 0;
|
||||
let m;
|
||||
while ((m = phasePattern.exec(content)) !== null) {
|
||||
const num = parseInt(m[1], 10);
|
||||
if (num > maxPhase) maxPhase = num;
|
||||
let newPhaseId;
|
||||
let dirName;
|
||||
|
||||
if (customId || config.phase_naming === 'custom') {
|
||||
// Custom phase naming: use provided ID or generate from description
|
||||
newPhaseId = customId || slug.toUpperCase().replace(/-/g, '-');
|
||||
if (!newPhaseId) error('--id required when phase_naming is "custom"');
|
||||
dirName = `${newPhaseId}-${slug}`;
|
||||
} else {
|
||||
// Sequential mode: find highest integer phase number (in current milestone only)
|
||||
const phasePattern = /#{2,4}\s*Phase\s+(\d+)[A-Z]?(?:\.\d+)*:/gi;
|
||||
let maxPhase = 0;
|
||||
let m;
|
||||
while ((m = phasePattern.exec(content)) !== null) {
|
||||
const num = parseInt(m[1], 10);
|
||||
if (num > maxPhase) maxPhase = num;
|
||||
}
|
||||
|
||||
newPhaseId = maxPhase + 1;
|
||||
const paddedNum = String(newPhaseId).padStart(2, '0');
|
||||
dirName = `${paddedNum}-${slug}`;
|
||||
}
|
||||
|
||||
const newPhaseNum = maxPhase + 1;
|
||||
const paddedNum = String(newPhaseNum).padStart(2, '0');
|
||||
const dirName = `${paddedNum}-${slug}`;
|
||||
const dirPath = path.join(cwd, '.planning', 'phases', dirName);
|
||||
|
||||
// Create directory with .gitkeep so git tracks empty folders
|
||||
@@ -341,7 +353,8 @@ function cmdPhaseAdd(cwd, description, raw) {
|
||||
fs.writeFileSync(path.join(dirPath, '.gitkeep'), '');
|
||||
|
||||
// Build phase entry
|
||||
const phaseEntry = `\n### Phase ${newPhaseNum}: ${description}\n\n**Goal:** [To be planned]\n**Requirements**: TBD\n**Depends on:** Phase ${maxPhase}\n**Plans:** 0 plans\n\nPlans:\n- [ ] TBD (run /gsd:plan-phase ${newPhaseNum} to break down)\n`;
|
||||
const dependsOn = config.phase_naming === 'custom' ? '' : `\n**Depends on:** Phase ${typeof newPhaseId === 'number' ? newPhaseId - 1 : 'TBD'}`;
|
||||
const phaseEntry = `\n### Phase ${newPhaseId}: ${description}\n\n**Goal:** [To be planned]\n**Requirements**: TBD${dependsOn}\n**Plans:** 0 plans\n\nPlans:\n- [ ] TBD (run /gsd:plan-phase ${newPhaseId} to break down)\n`;
|
||||
|
||||
// Find insertion point: before last "---" or at end
|
||||
let updatedContent;
|
||||
@@ -355,14 +368,15 @@ function cmdPhaseAdd(cwd, description, raw) {
|
||||
fs.writeFileSync(roadmapPath, updatedContent, 'utf-8');
|
||||
|
||||
const result = {
|
||||
phase_number: newPhaseNum,
|
||||
padded: paddedNum,
|
||||
phase_number: typeof newPhaseId === 'number' ? newPhaseId : String(newPhaseId),
|
||||
padded: typeof newPhaseId === 'number' ? String(newPhaseId).padStart(2, '0') : String(newPhaseId),
|
||||
name: description,
|
||||
slug,
|
||||
directory: `.planning/phases/${dirName}`,
|
||||
naming_mode: config.phase_naming,
|
||||
};
|
||||
|
||||
output(result, raw, paddedNum);
|
||||
output(result, raw, result.padded);
|
||||
}
|
||||
|
||||
function cmdPhaseInsert(cwd, afterPhase, description, raw) {
|
||||
@@ -376,7 +390,7 @@ function cmdPhaseInsert(cwd, afterPhase, description, raw) {
|
||||
}
|
||||
|
||||
const rawContent = fs.readFileSync(roadmapPath, 'utf-8');
|
||||
const content = stripShippedMilestones(rawContent);
|
||||
const content = extractCurrentMilestone(rawContent, cwd);
|
||||
const slug = generateSlugInternal(description);
|
||||
|
||||
// Normalize input then strip leading zeros for flexible matching
|
||||
@@ -401,7 +415,7 @@ function cmdPhaseInsert(cwd, afterPhase, description, raw) {
|
||||
const dm = dir.match(decimalPattern);
|
||||
if (dm) existingDecimals.push(parseInt(dm[1], 10));
|
||||
}
|
||||
} catch {}
|
||||
} catch { /* intentionally empty */ }
|
||||
|
||||
const nextDecimal = existingDecimals.length === 0 ? 1 : Math.max(...existingDecimals) + 1;
|
||||
const decimalPhase = `${normalizedBase}.${nextDecimal}`;
|
||||
@@ -470,7 +484,7 @@ function cmdPhaseRemove(cwd, targetPhase, options, raw) {
|
||||
const entries = fs.readdirSync(phasesDir, { withFileTypes: true });
|
||||
const dirs = entries.filter(e => e.isDirectory()).map(e => e.name).sort((a, b) => comparePhaseNum(a, b));
|
||||
targetDir = dirs.find(d => d.startsWith(normalized + '-') || d === normalized);
|
||||
} catch {}
|
||||
} catch { /* intentionally empty */ }
|
||||
|
||||
// Check for executed work (SUMMARY.md files)
|
||||
if (targetDir && !force) {
|
||||
@@ -538,7 +552,7 @@ function cmdPhaseRemove(cwd, targetPhase, options, raw) {
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch {}
|
||||
} catch { /* intentionally empty */ }
|
||||
|
||||
} else {
|
||||
// Integer removal: renumber all subsequent integer phases
|
||||
@@ -598,7 +612,7 @@ function cmdPhaseRemove(cwd, targetPhase, options, raw) {
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch {}
|
||||
} catch { /* intentionally empty */ }
|
||||
}
|
||||
|
||||
// Update ROADMAP.md
|
||||
@@ -671,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;
|
||||
@@ -721,6 +734,27 @@ function cmdPhaseComplete(cwd, phaseNum, raw) {
|
||||
const summaryCount = phaseInfo.summaries.length;
|
||||
let requirementsUpdated = false;
|
||||
|
||||
// Check for unresolved verification debt (non-blocking warnings)
|
||||
const warnings = [];
|
||||
try {
|
||||
const phaseFullDir = path.join(cwd, phaseInfo.directory);
|
||||
const phaseFiles = fs.readdirSync(phaseFullDir);
|
||||
|
||||
for (const file of phaseFiles.filter(f => f.includes('-UAT') && f.endsWith('.md'))) {
|
||||
const content = fs.readFileSync(path.join(phaseFullDir, file), 'utf-8');
|
||||
if (/result: pending/.test(content)) warnings.push(`${file}: has pending tests`);
|
||||
if (/result: blocked/.test(content)) warnings.push(`${file}: has blocked tests`);
|
||||
if (/status: partial/.test(content)) warnings.push(`${file}: testing incomplete (partial)`);
|
||||
if (/status: diagnosed/.test(content)) warnings.push(`${file}: has diagnosed gaps`);
|
||||
}
|
||||
|
||||
for (const file of phaseFiles.filter(f => f.includes('-VERIFICATION') && f.endsWith('.md'))) {
|
||||
const content = fs.readFileSync(path.join(phaseFullDir, file), 'utf-8');
|
||||
if (/status: human_needed/.test(content)) warnings.push(`${file}: needs human verification`);
|
||||
if (/status: gaps_found/.test(content)) warnings.push(`${file}: has unresolved gaps`);
|
||||
}
|
||||
} catch {}
|
||||
|
||||
// Update ROADMAP.md: mark phase complete
|
||||
if (fs.existsSync(roadmapPath)) {
|
||||
let roadmapContent = fs.readFileSync(roadmapPath, 'utf-8');
|
||||
@@ -732,16 +766,25 @@ function cmdPhaseComplete(cwd, phaseNum, raw) {
|
||||
);
|
||||
roadmapContent = replaceInCurrentMilestone(roadmapContent, checkboxPattern, `$1x$2 (completed ${today})`);
|
||||
|
||||
// Progress table: update Status to Complete, add date
|
||||
// Progress table: update Status to Complete, add date (handles 4 or 5 column tables)
|
||||
const phaseEscaped = escapeRegex(phaseNum);
|
||||
const tablePattern = new RegExp(
|
||||
`(\\|\\s*${phaseEscaped}\\.?\\s[^|]*\\|[^|]*\\|)\\s*[^|]*(\\|)\\s*[^|]*(\\|)`,
|
||||
'i'
|
||||
);
|
||||
roadmapContent = replaceInCurrentMilestone(
|
||||
roadmapContent, tablePattern,
|
||||
`$1 Complete $2 ${today} $3`
|
||||
const tableRowPattern = new RegExp(
|
||||
`^(\\|\\s*${phaseEscaped}\\.?\\s[^|]*(?:\\|[^\\n]*))$`,
|
||||
'im'
|
||||
);
|
||||
roadmapContent = roadmapContent.replace(tableRowPattern, (fullRow) => {
|
||||
const cells = fullRow.split('|').slice(1, -1);
|
||||
if (cells.length === 5) {
|
||||
// 5-col: Phase | Milestone | Plans | Status | Completed
|
||||
cells[3] = ' Complete ';
|
||||
cells[4] = ` ${today} `;
|
||||
} else if (cells.length === 4) {
|
||||
// 4-col: Phase | Plans | Status | Completed
|
||||
cells[2] = ' Complete ';
|
||||
cells[3] = ` ${today} `;
|
||||
}
|
||||
return '|' + cells.join('|') + '|';
|
||||
});
|
||||
|
||||
// Update plan count in phase section
|
||||
const planCountPattern = new RegExp(
|
||||
@@ -760,7 +803,7 @@ function cmdPhaseComplete(cwd, phaseNum, raw) {
|
||||
if (fs.existsSync(reqPath)) {
|
||||
// Extract the current phase section from roadmap (scoped to avoid cross-phase matching)
|
||||
const phaseEsc = escapeRegex(phaseNum);
|
||||
const currentMilestoneRoadmap = stripShippedMilestones(roadmapContent);
|
||||
const currentMilestoneRoadmap = extractCurrentMilestone(roadmapContent, cwd);
|
||||
const phaseSectionMatch = currentMilestoneRoadmap.match(
|
||||
new RegExp(`(#{2,4}\\s*Phase\\s+${phaseEsc}[:\\s][\\s\\S]*?)(?=#{2,4}\\s*Phase\\s+|$)`, 'i')
|
||||
);
|
||||
@@ -818,13 +861,13 @@ function cmdPhaseComplete(cwd, phaseNum, raw) {
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch {}
|
||||
} catch { /* intentionally empty */ }
|
||||
|
||||
// Fallback: if filesystem found no next phase, check ROADMAP.md
|
||||
// for phases that are defined but not yet planned (no directory on disk)
|
||||
if (isLastPhase && fs.existsSync(roadmapPath)) {
|
||||
try {
|
||||
const roadmapForPhases = stripShippedMilestones(fs.readFileSync(roadmapPath, 'utf-8'));
|
||||
const roadmapForPhases = extractCurrentMilestone(fs.readFileSync(roadmapPath, 'utf-8'), cwd);
|
||||
const phasePattern = /#{2,4}\s*Phase\s+(\d+[A-Z]?(?:\.\d+)*)\s*:\s*([^\n]+)/gi;
|
||||
let pm;
|
||||
while ((pm = phasePattern.exec(roadmapForPhases)) !== null) {
|
||||
@@ -835,50 +878,69 @@ function cmdPhaseComplete(cwd, phaseNum, raw) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
} catch {}
|
||||
} 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 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 totalRaw = stateExtractField(stateContent, 'Total Phases');
|
||||
if (totalRaw) {
|
||||
const totalPhases = parseInt(totalRaw, 10);
|
||||
if (totalPhases > 0) {
|
||||
const newPercent = Math.round((newCompleted / totalPhases) * 100);
|
||||
stateContent = stateReplaceField(stateContent, 'Progress', `${newPercent}%`) || stateContent;
|
||||
// Also update percent field if it exists separately
|
||||
stateContent = stateContent.replace(
|
||||
/(percent:\s*)\d+/,
|
||||
`$1${newPercent}`
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
writeStateMd(statePath, stateContent, cwd);
|
||||
}
|
||||
@@ -894,6 +956,8 @@ function cmdPhaseComplete(cwd, phaseNum, raw) {
|
||||
roadmap_updated: fs.existsSync(roadmapPath),
|
||||
state_updated: fs.existsSync(statePath),
|
||||
requirements_updated: requirementsUpdated,
|
||||
warnings,
|
||||
has_warnings: warnings.length > 0,
|
||||
};
|
||||
|
||||
output(result, raw);
|
||||
|
||||
@@ -179,6 +179,17 @@ const CLAUDE_MD_FALLBACKS = {
|
||||
architecture: 'Architecture not yet mapped. Follow existing patterns found in the codebase.',
|
||||
};
|
||||
|
||||
const CLAUDE_MD_WORKFLOW_ENFORCEMENT = [
|
||||
'Before using Edit, Write, or other file-changing tools, start work through a GSD command so planning artifacts and execution context stay in sync.',
|
||||
'',
|
||||
'Use these entry points:',
|
||||
'- `/gsd:quick` for small fixes, doc updates, and ad-hoc tasks',
|
||||
'- `/gsd:debug` for investigation and bug fixing',
|
||||
'- `/gsd:execute-phase` for planned phase work',
|
||||
'',
|
||||
'Do not make direct repo edits outside a GSD workflow unless the user explicitly asks to bypass it.',
|
||||
].join('\n');
|
||||
|
||||
const CLAUDE_MD_PROFILE_PLACEHOLDER = [
|
||||
'<!-- GSD:profile-start -->',
|
||||
'## Developer Profile',
|
||||
@@ -356,6 +367,14 @@ function generateArchitectureSection(cwd) {
|
||||
return { content: summary, source: 'ARCHITECTURE.md', hasFallback: false };
|
||||
}
|
||||
|
||||
function generateWorkflowSection() {
|
||||
return {
|
||||
content: CLAUDE_MD_WORKFLOW_ENFORCEMENT,
|
||||
source: 'GSD defaults',
|
||||
hasFallback: false,
|
||||
};
|
||||
}
|
||||
|
||||
// ─── Commands ─────────────────────────────────────────────────────────────────
|
||||
|
||||
function cmdWriteProfile(cwd, options, raw) {
|
||||
@@ -796,18 +815,20 @@ function cmdGenerateClaudeProfile(cwd, options, raw) {
|
||||
}
|
||||
|
||||
function cmdGenerateClaudeMd(cwd, options, raw) {
|
||||
const MANAGED_SECTIONS = ['project', 'stack', 'conventions', 'architecture'];
|
||||
const MANAGED_SECTIONS = ['project', 'stack', 'conventions', 'architecture', 'workflow'];
|
||||
const generators = {
|
||||
project: generateProjectSection,
|
||||
stack: generateStackSection,
|
||||
conventions: generateConventionsSection,
|
||||
architecture: generateArchitectureSection,
|
||||
workflow: generateWorkflowSection,
|
||||
};
|
||||
const sectionHeadings = {
|
||||
project: '## Project',
|
||||
stack: '## Technology Stack',
|
||||
conventions: '## Conventions',
|
||||
architecture: '## Architecture',
|
||||
workflow: '## GSD Workflow Enforcement',
|
||||
};
|
||||
|
||||
const generated = {};
|
||||
|
||||
@@ -4,10 +4,10 @@
|
||||
|
||||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
const { escapeRegex, normalizePhaseName, output, error, findPhaseInternal, stripShippedMilestones, replaceInCurrentMilestone } = require('./core.cjs');
|
||||
const { escapeRegex, normalizePhaseName, planningPaths, output, error, findPhaseInternal, stripShippedMilestones, extractCurrentMilestone, replaceInCurrentMilestone } = require('./core.cjs');
|
||||
|
||||
function cmdRoadmapGetPhase(cwd, phaseNum, raw) {
|
||||
const roadmapPath = path.join(cwd, '.planning', 'ROADMAP.md');
|
||||
const roadmapPath = planningPaths(cwd).roadmap;
|
||||
|
||||
if (!fs.existsSync(roadmapPath)) {
|
||||
output({ found: false, error: 'ROADMAP.md not found' }, raw, '');
|
||||
@@ -15,7 +15,7 @@ function cmdRoadmapGetPhase(cwd, phaseNum, raw) {
|
||||
}
|
||||
|
||||
try {
|
||||
const content = stripShippedMilestones(fs.readFileSync(roadmapPath, 'utf-8'));
|
||||
const content = extractCurrentMilestone(fs.readFileSync(roadmapPath, 'utf-8'), cwd);
|
||||
|
||||
// Escape special regex chars in phase number, handle decimal
|
||||
const escapedPhase = escapeRegex(phaseNum);
|
||||
@@ -91,7 +91,7 @@ function cmdRoadmapGetPhase(cwd, phaseNum, raw) {
|
||||
}
|
||||
|
||||
function cmdRoadmapAnalyze(cwd, raw) {
|
||||
const roadmapPath = path.join(cwd, '.planning', 'ROADMAP.md');
|
||||
const roadmapPath = planningPaths(cwd).roadmap;
|
||||
|
||||
if (!fs.existsSync(roadmapPath)) {
|
||||
output({ error: 'ROADMAP.md not found', milestones: [], phases: [], current_phase: null }, raw);
|
||||
@@ -99,8 +99,8 @@ function cmdRoadmapAnalyze(cwd, raw) {
|
||||
}
|
||||
|
||||
const rawContent = fs.readFileSync(roadmapPath, 'utf-8');
|
||||
const content = stripShippedMilestones(rawContent);
|
||||
const phasesDir = path.join(cwd, '.planning', 'phases');
|
||||
const content = extractCurrentMilestone(rawContent, cwd);
|
||||
const phasesDir = planningPaths(cwd).phases;
|
||||
|
||||
// Extract all phase headings: ## Phase N: Name or ### Phase N: Name
|
||||
const phasePattern = /#{2,4}\s*Phase\s+(\d+[A-Z]?(?:\.\d+)*)\s*:\s*([^\n]+)/gi;
|
||||
@@ -151,7 +151,7 @@ function cmdRoadmapAnalyze(cwd, raw) {
|
||||
else if (hasContext) diskStatus = 'discussed';
|
||||
else diskStatus = 'empty';
|
||||
}
|
||||
} catch {}
|
||||
} catch { /* intentionally empty */ }
|
||||
|
||||
// Check ROADMAP checkbox status
|
||||
const checkboxPattern = new RegExp(`-\\s*\\[(x| )\\]\\s*.*Phase\\s+${escapeRegex(phaseNum)}[:\\s]`, 'i');
|
||||
@@ -181,7 +181,7 @@ function cmdRoadmapAnalyze(cwd, raw) {
|
||||
|
||||
// Extract milestone info
|
||||
const milestones = [];
|
||||
const milestonePattern = /##\s*(.*v(\d+\.\d+)[^(\n]*)/gi;
|
||||
const milestonePattern = /##\s*(.*v(\d+(?:\.\d+)+)[^(\n]*)/gi;
|
||||
let mMatch;
|
||||
while ((mMatch = milestonePattern.exec(content)) !== null) {
|
||||
milestones.push({
|
||||
@@ -230,7 +230,7 @@ function cmdRoadmapUpdatePlanProgress(cwd, phaseNum, raw) {
|
||||
error('phase number required for roadmap update-plan-progress');
|
||||
}
|
||||
|
||||
const roadmapPath = path.join(cwd, '.planning', 'ROADMAP.md');
|
||||
const roadmapPath = planningPaths(cwd).roadmap;
|
||||
|
||||
const phaseInfo = findPhaseInternal(cwd, phaseNum);
|
||||
if (!phaseInfo) {
|
||||
@@ -257,16 +257,27 @@ function cmdRoadmapUpdatePlanProgress(cwd, phaseNum, raw) {
|
||||
let roadmapContent = fs.readFileSync(roadmapPath, 'utf-8');
|
||||
const phaseEscaped = escapeRegex(phaseNum);
|
||||
|
||||
// Progress table row: update Plans column (summaries/plans) and Status column
|
||||
const tablePattern = new RegExp(
|
||||
`(\\|\\s*${phaseEscaped}\\.?\\s[^|]*\\|)[^|]*(\\|)\\s*[^|]*(\\|)\\s*[^|]*(\\|)`,
|
||||
'i'
|
||||
// Progress table row: update Plans/Status/Date columns (handles 4 or 5 column tables)
|
||||
const tableRowPattern = new RegExp(
|
||||
`^(\\|\\s*${phaseEscaped}\\.?\\s[^|]*(?:\\|[^\\n]*))$`,
|
||||
'im'
|
||||
);
|
||||
const dateField = isComplete ? ` ${today} ` : ' ';
|
||||
roadmapContent = replaceInCurrentMilestone(
|
||||
roadmapContent, tablePattern,
|
||||
`$1 ${summaryCount}/${planCount} $2 ${status.padEnd(11)}$3${dateField}$4`
|
||||
);
|
||||
roadmapContent = roadmapContent.replace(tableRowPattern, (fullRow) => {
|
||||
const cells = fullRow.split('|').slice(1, -1); // drop leading/trailing empty from split
|
||||
if (cells.length === 5) {
|
||||
// 5-col: Phase | Milestone | Plans | Status | Completed
|
||||
cells[2] = ` ${summaryCount}/${planCount} `;
|
||||
cells[3] = ` ${status.padEnd(11)}`;
|
||||
cells[4] = dateField;
|
||||
} else if (cells.length === 4) {
|
||||
// 4-col: Phase | Plans | Status | Completed
|
||||
cells[1] = ` ${summaryCount}/${planCount} `;
|
||||
cells[2] = ` ${status.padEnd(11)}`;
|
||||
cells[3] = dateField;
|
||||
}
|
||||
return '|' + cells.join('|') + '|';
|
||||
});
|
||||
|
||||
// Update plan count in phase detail section
|
||||
const planCountPattern = new RegExp(
|
||||
@@ -287,6 +298,18 @@ function cmdRoadmapUpdatePlanProgress(cwd, phaseNum, raw) {
|
||||
roadmapContent = replaceInCurrentMilestone(roadmapContent, checkboxPattern, `$1x$2 (completed ${today})`);
|
||||
}
|
||||
|
||||
// Mark completed plan checkboxes (e.g. "- [ ] 50-01-PLAN.md" or "- [ ] 50-01:")
|
||||
for (const summaryFile of phaseInfo.summaries) {
|
||||
const planId = summaryFile.replace('-SUMMARY.md', '').replace('SUMMARY.md', '');
|
||||
if (!planId) continue;
|
||||
const planEscaped = escapeRegex(planId);
|
||||
const planCheckboxPattern = new RegExp(
|
||||
`(-\\s*\\[) (\\]\\s*${planEscaped})`,
|
||||
'i'
|
||||
);
|
||||
roadmapContent = roadmapContent.replace(planCheckboxPattern, '$1x$2');
|
||||
}
|
||||
|
||||
fs.writeFileSync(roadmapPath, roadmapContent, 'utf-8');
|
||||
|
||||
output({
|
||||
|
||||
@@ -4,9 +4,14 @@
|
||||
|
||||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
const { escapeRegex, loadConfig, getMilestoneInfo, getMilestonePhaseFilter, normalizeMd, output, error } = require('./core.cjs');
|
||||
const { escapeRegex, loadConfig, getMilestoneInfo, getMilestonePhaseFilter, normalizeMd, planningPaths, output, error } = require('./core.cjs');
|
||||
const { extractFrontmatter, reconstructFrontmatter } = require('./frontmatter.cjs');
|
||||
|
||||
/** Shorthand — every state command needs this path */
|
||||
function getStatePath(cwd) {
|
||||
return planningPaths(cwd).state;
|
||||
}
|
||||
|
||||
// Shared helper: extract a field value from STATE.md content.
|
||||
// Supports both **Field:** bold and plain Field: format.
|
||||
function stateExtractField(content, fieldName) {
|
||||
@@ -21,15 +26,15 @@ function stateExtractField(content, fieldName) {
|
||||
|
||||
function cmdStateLoad(cwd, raw) {
|
||||
const config = loadConfig(cwd);
|
||||
const planningDir = path.join(cwd, '.planning');
|
||||
const planDir = planningPaths(cwd).planning;
|
||||
|
||||
let stateRaw = '';
|
||||
try {
|
||||
stateRaw = fs.readFileSync(path.join(planningDir, 'STATE.md'), 'utf-8');
|
||||
} catch {}
|
||||
stateRaw = fs.readFileSync(path.join(planDir, 'STATE.md'), 'utf-8');
|
||||
} catch { /* intentionally empty */ }
|
||||
|
||||
const configExists = fs.existsSync(path.join(planningDir, 'config.json'));
|
||||
const roadmapExists = fs.existsSync(path.join(planningDir, 'ROADMAP.md'));
|
||||
const configExists = fs.existsSync(path.join(planDir, 'config.json'));
|
||||
const roadmapExists = fs.existsSync(path.join(planDir, 'ROADMAP.md'));
|
||||
const stateExists = stateRaw.length > 0;
|
||||
|
||||
const result = {
|
||||
@@ -65,7 +70,7 @@ function cmdStateLoad(cwd, raw) {
|
||||
}
|
||||
|
||||
function cmdStateGet(cwd, section, raw) {
|
||||
const statePath = path.join(cwd, '.planning', 'STATE.md');
|
||||
const statePath = planningPaths(cwd).state;
|
||||
try {
|
||||
const content = fs.readFileSync(statePath, 'utf-8');
|
||||
|
||||
@@ -75,7 +80,7 @@ function cmdStateGet(cwd, section, raw) {
|
||||
}
|
||||
|
||||
// Try to find markdown section or field
|
||||
const fieldEscaped = section.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
|
||||
const fieldEscaped = escapeRegex(section);
|
||||
|
||||
// Check for **field:** value (bold format)
|
||||
const boldPattern = new RegExp(`\\*\\*${fieldEscaped}:\\*\\*\\s*(.*)`, 'i');
|
||||
@@ -119,13 +124,13 @@ function readTextArgOrFile(cwd, value, filePath, label) {
|
||||
}
|
||||
|
||||
function cmdStatePatch(cwd, patches, raw) {
|
||||
const statePath = path.join(cwd, '.planning', 'STATE.md');
|
||||
const statePath = planningPaths(cwd).state;
|
||||
try {
|
||||
let content = fs.readFileSync(statePath, 'utf-8');
|
||||
const results = { updated: [], failed: [] };
|
||||
|
||||
for (const [field, value] of Object.entries(patches)) {
|
||||
const fieldEscaped = field.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
|
||||
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');
|
||||
@@ -156,10 +161,10 @@ function cmdStateUpdate(cwd, field, value) {
|
||||
error('field and value required for state update');
|
||||
}
|
||||
|
||||
const statePath = path.join(cwd, '.planning', 'STATE.md');
|
||||
const statePath = planningPaths(cwd).state;
|
||||
try {
|
||||
let content = fs.readFileSync(statePath, 'utf-8');
|
||||
const fieldEscaped = field.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
|
||||
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');
|
||||
@@ -180,21 +185,10 @@ function cmdStateUpdate(cwd, field, value) {
|
||||
}
|
||||
|
||||
// ─── State Progression Engine ────────────────────────────────────────────────
|
||||
|
||||
function stateExtractField(content, fieldName) {
|
||||
const escaped = fieldName.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
|
||||
// Try **Field:** bold format first
|
||||
const boldPattern = new RegExp(`\\*\\*${escaped}:\\*\\*\\s*(.+)`, 'i');
|
||||
const boldMatch = content.match(boldPattern);
|
||||
if (boldMatch) return boldMatch[1].trim();
|
||||
// Fall back to plain Field: format
|
||||
const plainPattern = new RegExp(`^${escaped}:\\s*(.+)`, 'im');
|
||||
const plainMatch = content.match(plainPattern);
|
||||
return plainMatch ? plainMatch[1].trim() : null;
|
||||
}
|
||||
// stateExtractField is defined above (shared helper) — do not duplicate.
|
||||
|
||||
function stateReplaceField(content, fieldName, newValue) {
|
||||
const escaped = fieldName.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
|
||||
const escaped = escapeRegex(fieldName);
|
||||
// Try **Field:** bold format first, then plain Field: format
|
||||
const boldPattern = new RegExp(`(\\*\\*${escaped}:\\*\\*\\s*)(.*)`, 'i');
|
||||
if (boldPattern.test(content)) {
|
||||
@@ -207,37 +201,76 @@ 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 = path.join(cwd, '.planning', 'STATE.md');
|
||||
const statePath = planningPaths(cwd).state;
|
||||
if (!fs.existsSync(statePath)) { output({ error: 'STATE.md not found' }, raw); return; }
|
||||
|
||||
let content = fs.readFileSync(statePath, 'utf-8');
|
||||
const currentPlan = parseInt(stateExtractField(content, 'Current Plan'), 10);
|
||||
const totalPlans = parseInt(stateExtractField(content, 'Total Plans in Phase'), 10);
|
||||
const today = new Date().toISOString().split('T')[0];
|
||||
|
||||
// Try legacy separate fields first, then compound "Plan: X of Y" format
|
||||
const legacyPlan = stateExtractField(content, 'Current Plan');
|
||||
const legacyTotal = stateExtractField(content, 'Total Plans in Phase');
|
||||
const planField = stateExtractField(content, 'Plan');
|
||||
|
||||
let currentPlan, totalPlans;
|
||||
let useCompoundFormat = false;
|
||||
|
||||
if (legacyPlan && legacyTotal) {
|
||||
currentPlan = parseInt(legacyPlan, 10);
|
||||
totalPlans = parseInt(legacyTotal, 10);
|
||||
} else if (planField) {
|
||||
// Compound format: "2 of 6 in current phase" or "2 of 6"
|
||||
currentPlan = parseInt(planField, 10);
|
||||
const ofMatch = planField.match(/of\s+(\d+)/);
|
||||
totalPlans = ofMatch ? parseInt(ofMatch[1], 10) : NaN;
|
||||
useCompoundFormat = true;
|
||||
}
|
||||
|
||||
if (isNaN(currentPlan) || isNaN(totalPlans)) {
|
||||
output({ error: 'Cannot parse Current Plan or Total Plans in Phase from STATE.md' }, raw);
|
||||
return;
|
||||
}
|
||||
|
||||
if (currentPlan >= totalPlans) {
|
||||
content = stateReplaceField(content, 'Status', 'Phase complete — ready for verification') || content;
|
||||
content = stateReplaceField(content, 'Last Activity', today) || content;
|
||||
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 {
|
||||
const newPlan = currentPlan + 1;
|
||||
content = stateReplaceField(content, 'Current Plan', String(newPlan)) || content;
|
||||
content = stateReplaceField(content, 'Status', 'Ready to execute') || content;
|
||||
content = stateReplaceField(content, 'Last Activity', today) || content;
|
||||
if (useCompoundFormat) {
|
||||
// Preserve compound format: "X of Y in current phase" → replace X only
|
||||
const newPlanValue = planField.replace(/^\d+/, String(newPlan));
|
||||
content = stateReplaceField(content, 'Plan', newPlanValue) || content;
|
||||
} else {
|
||||
content = stateReplaceField(content, 'Current Plan', String(newPlan)) || content;
|
||||
}
|
||||
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');
|
||||
}
|
||||
}
|
||||
|
||||
function cmdStateRecordMetric(cwd, options, raw) {
|
||||
const statePath = path.join(cwd, '.planning', 'STATE.md');
|
||||
const statePath = planningPaths(cwd).state;
|
||||
if (!fs.existsSync(statePath)) { output({ error: 'STATE.md not found' }, raw); return; }
|
||||
|
||||
let content = fs.readFileSync(statePath, 'utf-8');
|
||||
@@ -271,13 +304,13 @@ function cmdStateRecordMetric(cwd, options, raw) {
|
||||
}
|
||||
|
||||
function cmdStateUpdateProgress(cwd, raw) {
|
||||
const statePath = path.join(cwd, '.planning', 'STATE.md');
|
||||
const statePath = planningPaths(cwd).state;
|
||||
if (!fs.existsSync(statePath)) { output({ error: 'STATE.md not found' }, raw); return; }
|
||||
|
||||
let content = fs.readFileSync(statePath, 'utf-8');
|
||||
|
||||
// Count summaries across current milestone phases only
|
||||
const phasesDir = path.join(cwd, '.planning', 'phases');
|
||||
const phasesDir = planningPaths(cwd).phases;
|
||||
let totalPlans = 0;
|
||||
let totalSummaries = 0;
|
||||
|
||||
@@ -316,7 +349,7 @@ function cmdStateUpdateProgress(cwd, raw) {
|
||||
}
|
||||
|
||||
function cmdStateAddDecision(cwd, options, raw) {
|
||||
const statePath = path.join(cwd, '.planning', 'STATE.md');
|
||||
const statePath = planningPaths(cwd).state;
|
||||
if (!fs.existsSync(statePath)) { output({ error: 'STATE.md not found' }, raw); return; }
|
||||
|
||||
const { phase, summary, summary_file, rationale, rationale_file } = options;
|
||||
@@ -354,7 +387,7 @@ function cmdStateAddDecision(cwd, options, raw) {
|
||||
}
|
||||
|
||||
function cmdStateAddBlocker(cwd, text, raw) {
|
||||
const statePath = path.join(cwd, '.planning', 'STATE.md');
|
||||
const statePath = planningPaths(cwd).state;
|
||||
if (!fs.existsSync(statePath)) { output({ error: 'STATE.md not found' }, raw); return; }
|
||||
const blockerOptions = typeof text === 'object' && text !== null ? text : { text };
|
||||
let blockerText = null;
|
||||
@@ -387,7 +420,7 @@ function cmdStateAddBlocker(cwd, text, raw) {
|
||||
}
|
||||
|
||||
function cmdStateResolveBlocker(cwd, text, raw) {
|
||||
const statePath = path.join(cwd, '.planning', 'STATE.md');
|
||||
const statePath = planningPaths(cwd).state;
|
||||
if (!fs.existsSync(statePath)) { output({ error: 'STATE.md not found' }, raw); return; }
|
||||
if (!text) { output({ error: 'text required' }, raw); return; }
|
||||
|
||||
@@ -419,7 +452,7 @@ function cmdStateResolveBlocker(cwd, text, raw) {
|
||||
}
|
||||
|
||||
function cmdStateRecordSession(cwd, options, raw) {
|
||||
const statePath = path.join(cwd, '.planning', 'STATE.md');
|
||||
const statePath = planningPaths(cwd).state;
|
||||
if (!fs.existsSync(statePath)) { output({ error: 'STATE.md not found' }, raw); return; }
|
||||
|
||||
let content = fs.readFileSync(statePath, 'utf-8');
|
||||
@@ -454,7 +487,7 @@ function cmdStateRecordSession(cwd, options, raw) {
|
||||
}
|
||||
|
||||
function cmdStateSnapshot(cwd, raw) {
|
||||
const statePath = path.join(cwd, '.planning', 'STATE.md');
|
||||
const statePath = planningPaths(cwd).state;
|
||||
|
||||
if (!fs.existsSync(statePath)) {
|
||||
output({ error: 'STATE.md not found' }, raw);
|
||||
@@ -576,7 +609,7 @@ function buildStateFrontmatter(bodyContent, cwd) {
|
||||
const info = getMilestoneInfo(cwd);
|
||||
milestone = info.version;
|
||||
milestoneName = info.name;
|
||||
} catch {}
|
||||
} catch { /* intentionally empty */ }
|
||||
}
|
||||
|
||||
let totalPhases = totalPhasesRaw ? parseInt(totalPhasesRaw, 10) : null;
|
||||
@@ -586,7 +619,7 @@ function buildStateFrontmatter(bodyContent, cwd) {
|
||||
|
||||
if (cwd) {
|
||||
try {
|
||||
const phasesDir = path.join(cwd, '.planning', 'phases');
|
||||
const phasesDir = planningPaths(cwd).phases;
|
||||
if (fs.existsSync(phasesDir)) {
|
||||
const isDirInMilestone = getMilestonePhaseFilter(cwd);
|
||||
const phaseDirs = fs.readdirSync(phasesDir, { withFileTypes: true })
|
||||
@@ -611,7 +644,7 @@ function buildStateFrontmatter(bodyContent, cwd) {
|
||||
totalPlans = diskTotalPlans;
|
||||
completedPlans = diskTotalSummaries;
|
||||
}
|
||||
} catch {}
|
||||
} catch { /* intentionally empty */ }
|
||||
}
|
||||
|
||||
let progressPercent = null;
|
||||
@@ -664,7 +697,17 @@ function buildStateFrontmatter(bodyContent, cwd) {
|
||||
}
|
||||
|
||||
function stripFrontmatter(content) {
|
||||
return content.replace(/^---\n[\s\S]*?\n---\n*/, '');
|
||||
// Strip ALL frontmatter blocks at the start of the file.
|
||||
// Handles CRLF line endings and multiple stacked blocks (corruption recovery).
|
||||
// Greedy: keeps stripping ---...--- blocks separated by optional whitespace.
|
||||
let result = content;
|
||||
// eslint-disable-next-line no-constant-condition
|
||||
while (true) {
|
||||
const stripped = result.replace(/^\s*---\r?\n[\s\S]*?\r?\n---\s*/, '');
|
||||
if (stripped === result) break;
|
||||
result = stripped;
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
function syncStateFrontmatter(content, cwd) {
|
||||
@@ -677,14 +720,58 @@ function syncStateFrontmatter(content, cwd) {
|
||||
/**
|
||||
* Write STATE.md with synchronized YAML frontmatter.
|
||||
* All STATE.md writes should use this instead of raw writeFileSync.
|
||||
* Uses a simple lockfile to prevent parallel agents from overwriting
|
||||
* each other's changes (race condition with read-modify-write cycle).
|
||||
*/
|
||||
function writeStateMd(statePath, content, cwd) {
|
||||
const synced = syncStateFrontmatter(content, cwd);
|
||||
fs.writeFileSync(statePath, normalizeMd(synced), 'utf-8');
|
||||
const lockPath = statePath + '.lock';
|
||||
const maxRetries = 10;
|
||||
const retryDelay = 200; // ms
|
||||
|
||||
// Acquire lock (spin with backoff)
|
||||
for (let i = 0; i < maxRetries; i++) {
|
||||
try {
|
||||
// O_EXCL fails if file already exists — atomic lock
|
||||
const fd = fs.openSync(lockPath, fs.constants.O_CREAT | fs.constants.O_EXCL | fs.constants.O_WRONLY);
|
||||
fs.writeSync(fd, String(process.pid));
|
||||
fs.closeSync(fd);
|
||||
break;
|
||||
} catch (err) {
|
||||
if (err.code === 'EEXIST') {
|
||||
// Check for stale lock (> 10s old)
|
||||
try {
|
||||
const stat = fs.statSync(lockPath);
|
||||
if (Date.now() - stat.mtimeMs > 10000) {
|
||||
fs.unlinkSync(lockPath);
|
||||
continue; // retry immediately after clearing stale lock
|
||||
}
|
||||
} catch { /* lock was released between check — retry */ }
|
||||
|
||||
if (i === maxRetries - 1) {
|
||||
// Last resort: write anyway rather than losing data
|
||||
try { fs.unlinkSync(lockPath); } catch {}
|
||||
break;
|
||||
}
|
||||
// Spin-wait with small jitter
|
||||
const jitter = Math.floor(Math.random() * 50);
|
||||
const start = Date.now();
|
||||
while (Date.now() - start < retryDelay + jitter) { /* busy wait */ }
|
||||
continue;
|
||||
}
|
||||
break; // non-EEXIST error — proceed without lock
|
||||
}
|
||||
}
|
||||
|
||||
try {
|
||||
fs.writeFileSync(statePath, normalizeMd(synced), 'utf-8');
|
||||
} finally {
|
||||
try { fs.unlinkSync(lockPath); } catch { /* lock already gone */ }
|
||||
}
|
||||
}
|
||||
|
||||
function cmdStateJson(cwd, raw) {
|
||||
const statePath = path.join(cwd, '.planning', 'STATE.md');
|
||||
const statePath = planningPaths(cwd).state;
|
||||
if (!fs.existsSync(statePath)) {
|
||||
output({ error: 'STATE.md not found' }, raw, 'STATE.md not found');
|
||||
return;
|
||||
@@ -710,7 +797,7 @@ function cmdStateJson(cwd, raw) {
|
||||
* Fixes: #1102 (plan counts), #1103 (status/last_activity), #1104 (body text).
|
||||
*/
|
||||
function cmdStateBeginPhase(cwd, phaseNumber, phaseName, planCount, raw) {
|
||||
const statePath = path.join(cwd, '.planning', 'STATE.md');
|
||||
const statePath = planningPaths(cwd).state;
|
||||
if (!fs.existsSync(statePath)) {
|
||||
output({ error: 'STATE.md not found' }, raw);
|
||||
return;
|
||||
@@ -778,9 +865,57 @@ function cmdStateBeginPhase(cwd, phaseNumber, phaseName, planCount, raw) {
|
||||
output({ updated, phase: phaseNumber, phase_name: phaseName || null, plan_count: planCount || null }, raw, updated.length > 0 ? 'true' : 'false');
|
||||
}
|
||||
|
||||
/**
|
||||
* Write a WAITING.json signal file when GSD hits a decision point.
|
||||
* External watchers (fswatch, polling, orchestrators) can detect this.
|
||||
* File is written to .planning/WAITING.json (or .gsd/WAITING.json if .gsd exists).
|
||||
* Fixes #1034.
|
||||
*/
|
||||
function cmdSignalWaiting(cwd, type, question, options, phase, raw) {
|
||||
const gsdDir = fs.existsSync(path.join(cwd, '.gsd')) ? path.join(cwd, '.gsd') : path.join(cwd, '.planning');
|
||||
const waitingPath = path.join(gsdDir, 'WAITING.json');
|
||||
|
||||
const signal = {
|
||||
status: 'waiting',
|
||||
type: type || 'decision_point',
|
||||
question: question || null,
|
||||
options: options ? options.split('|').map(o => o.trim()) : [],
|
||||
since: new Date().toISOString(),
|
||||
phase: phase || null,
|
||||
};
|
||||
|
||||
try {
|
||||
fs.mkdirSync(gsdDir, { recursive: true });
|
||||
fs.writeFileSync(waitingPath, JSON.stringify(signal, null, 2), 'utf-8');
|
||||
output({ signaled: true, path: waitingPath }, raw, 'true');
|
||||
} catch (e) {
|
||||
output({ signaled: false, error: e.message }, raw, 'false');
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Remove the WAITING.json signal file when user answers and agent resumes.
|
||||
*/
|
||||
function cmdSignalResume(cwd, raw) {
|
||||
const paths = [
|
||||
path.join(cwd, '.gsd', 'WAITING.json'),
|
||||
path.join(cwd, '.planning', 'WAITING.json'),
|
||||
];
|
||||
|
||||
let removed = false;
|
||||
for (const p of paths) {
|
||||
if (fs.existsSync(p)) {
|
||||
try { fs.unlinkSync(p); removed = true; } catch {}
|
||||
}
|
||||
}
|
||||
|
||||
output({ resumed: true, removed }, raw, removed ? 'true' : 'false');
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
stateExtractField,
|
||||
stateReplaceField,
|
||||
stateReplaceFieldWithFallback,
|
||||
writeStateMd,
|
||||
cmdStateLoad,
|
||||
cmdStateGet,
|
||||
@@ -796,4 +931,6 @@ module.exports = {
|
||||
cmdStateSnapshot,
|
||||
cmdStateJson,
|
||||
cmdStateBeginPhase,
|
||||
cmdSignalWaiting,
|
||||
cmdSignalResume,
|
||||
};
|
||||
|
||||
189
get-shit-done/bin/lib/uat.cjs
Normal file
189
get-shit-done/bin/lib/uat.cjs
Normal file
@@ -0,0 +1,189 @@
|
||||
/**
|
||||
* UAT Audit — Cross-phase UAT/VERIFICATION scanner
|
||||
*
|
||||
* Reads all *-UAT.md and *-VERIFICATION.md files across all phases.
|
||||
* Extracts non-passing items. Returns structured JSON for workflow consumption.
|
||||
*/
|
||||
|
||||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
const { output, error, getMilestonePhaseFilter } = require('./core.cjs');
|
||||
const { extractFrontmatter } = require('./frontmatter.cjs');
|
||||
|
||||
function cmdAuditUat(cwd, raw) {
|
||||
const phasesDir = path.join(cwd, '.planning', 'phases');
|
||||
if (!fs.existsSync(phasesDir)) {
|
||||
error('No .planning/phases directory found');
|
||||
}
|
||||
|
||||
const isDirInMilestone = getMilestonePhaseFilter(cwd);
|
||||
const results = [];
|
||||
|
||||
// Scan all phase directories
|
||||
const dirs = fs.readdirSync(phasesDir, { withFileTypes: true })
|
||||
.filter(e => e.isDirectory())
|
||||
.map(e => e.name)
|
||||
.filter(isDirInMilestone)
|
||||
.sort();
|
||||
|
||||
for (const dir of dirs) {
|
||||
const phaseMatch = dir.match(/^(\d+[A-Z]?(?:\.\d+)*)/i);
|
||||
const phaseNum = phaseMatch ? phaseMatch[1] : dir;
|
||||
const phaseDir = path.join(phasesDir, dir);
|
||||
const files = fs.readdirSync(phaseDir);
|
||||
|
||||
// Process UAT files
|
||||
for (const file of files.filter(f => f.includes('-UAT') && f.endsWith('.md'))) {
|
||||
const content = fs.readFileSync(path.join(phaseDir, file), 'utf-8');
|
||||
const items = parseUatItems(content);
|
||||
if (items.length > 0) {
|
||||
results.push({
|
||||
phase: phaseNum,
|
||||
phase_dir: dir,
|
||||
file,
|
||||
file_path: `.planning/phases/${dir}/${file}`,
|
||||
type: 'uat',
|
||||
status: (extractFrontmatter(content).status || 'unknown'),
|
||||
items,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// Process VERIFICATION files
|
||||
for (const file of files.filter(f => f.includes('-VERIFICATION') && f.endsWith('.md'))) {
|
||||
const content = fs.readFileSync(path.join(phaseDir, file), 'utf-8');
|
||||
const status = extractFrontmatter(content).status || 'unknown';
|
||||
if (status === 'human_needed' || status === 'gaps_found') {
|
||||
const items = parseVerificationItems(content, status);
|
||||
if (items.length > 0) {
|
||||
results.push({
|
||||
phase: phaseNum,
|
||||
phase_dir: dir,
|
||||
file,
|
||||
file_path: `.planning/phases/${dir}/${file}`,
|
||||
type: 'verification',
|
||||
status,
|
||||
items,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Compute summary
|
||||
const summary = {
|
||||
total_files: results.length,
|
||||
total_items: results.reduce((sum, r) => sum + r.items.length, 0),
|
||||
by_category: {},
|
||||
by_phase: {},
|
||||
};
|
||||
|
||||
for (const r of results) {
|
||||
if (!summary.by_phase[r.phase]) summary.by_phase[r.phase] = 0;
|
||||
for (const item of r.items) {
|
||||
summary.by_phase[r.phase]++;
|
||||
const cat = item.category || 'unknown';
|
||||
summary.by_category[cat] = (summary.by_category[cat] || 0) + 1;
|
||||
}
|
||||
}
|
||||
|
||||
output({ results, summary }, raw);
|
||||
}
|
||||
|
||||
function parseUatItems(content) {
|
||||
const items = [];
|
||||
// Match test blocks: ### N. Name\nexpected: ...\nresult: ...\n
|
||||
const testPattern = /###\s*(\d+)\.\s*([^\n]+)\nexpected:\s*([^\n]+)\nresult:\s*(\w+)(?:\n(?:reported|reason|blocked_by):\s*[^\n]*)?/g;
|
||||
let match;
|
||||
while ((match = testPattern.exec(content)) !== null) {
|
||||
const [, num, name, expected, result] = match;
|
||||
if (result === 'pending' || result === 'skipped' || result === 'blocked') {
|
||||
// Extract optional fields — limit to current test block (up to next ### or EOF)
|
||||
const afterMatch = content.slice(match.index);
|
||||
const nextHeading = afterMatch.indexOf('\n###', 1);
|
||||
const blockText = nextHeading > 0 ? afterMatch.slice(0, nextHeading) : afterMatch;
|
||||
const reasonMatch = blockText.match(/reason:\s*(.+)/);
|
||||
const blockedByMatch = blockText.match(/blocked_by:\s*(.+)/);
|
||||
|
||||
const item = {
|
||||
test: parseInt(num, 10),
|
||||
name: name.trim(),
|
||||
expected: expected.trim(),
|
||||
result,
|
||||
category: categorizeItem(result, reasonMatch?.[1], blockedByMatch?.[1]),
|
||||
};
|
||||
if (reasonMatch) item.reason = reasonMatch[1].trim();
|
||||
if (blockedByMatch) item.blocked_by = blockedByMatch[1].trim();
|
||||
items.push(item);
|
||||
}
|
||||
}
|
||||
return items;
|
||||
}
|
||||
|
||||
function parseVerificationItems(content, status) {
|
||||
const items = [];
|
||||
if (status === 'human_needed') {
|
||||
// Extract from human_verification section — look for numbered items or table rows
|
||||
const hvSection = content.match(/##\s*Human Verification.*?\n([\s\S]*?)(?=\n##\s|\n---\s|$)/i);
|
||||
if (hvSection) {
|
||||
const lines = hvSection[1].split('\n');
|
||||
for (const line of lines) {
|
||||
// Match table rows: | N | description | ... |
|
||||
const tableMatch = line.match(/\|\s*(\d+)\s*\|\s*([^|]+)/);
|
||||
// Match bullet items: - description
|
||||
const bulletMatch = line.match(/^[-*]\s+(.+)/);
|
||||
// Match numbered items: 1. description
|
||||
const numberedMatch = line.match(/^(\d+)\.\s+(.+)/);
|
||||
|
||||
if (tableMatch) {
|
||||
items.push({
|
||||
test: parseInt(tableMatch[1], 10),
|
||||
name: tableMatch[2].trim(),
|
||||
result: 'human_needed',
|
||||
category: 'human_uat',
|
||||
});
|
||||
} else if (numberedMatch) {
|
||||
items.push({
|
||||
test: parseInt(numberedMatch[1], 10),
|
||||
name: numberedMatch[2].trim(),
|
||||
result: 'human_needed',
|
||||
category: 'human_uat',
|
||||
});
|
||||
} else if (bulletMatch && bulletMatch[1].length > 10) {
|
||||
items.push({
|
||||
name: bulletMatch[1].trim(),
|
||||
result: 'human_needed',
|
||||
category: 'human_uat',
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
// gaps_found items are already handled by plan-phase --gaps pipeline
|
||||
return items;
|
||||
}
|
||||
|
||||
function categorizeItem(result, reason, blockedBy) {
|
||||
if (result === 'blocked' || blockedBy) {
|
||||
if (blockedBy) {
|
||||
if (/server/i.test(blockedBy)) return 'server_blocked';
|
||||
if (/device|physical/i.test(blockedBy)) return 'device_needed';
|
||||
if (/build|release|preview/i.test(blockedBy)) return 'build_needed';
|
||||
if (/third.party|twilio|stripe/i.test(blockedBy)) return 'third_party';
|
||||
}
|
||||
return 'blocked';
|
||||
}
|
||||
if (result === 'skipped') {
|
||||
if (reason) {
|
||||
if (/server|not running|not available/i.test(reason)) return 'server_blocked';
|
||||
if (/simulator|physical|device/i.test(reason)) return 'device_needed';
|
||||
if (/build|release|preview/i.test(reason)) return 'build_needed';
|
||||
}
|
||||
return 'skipped_unresolved';
|
||||
}
|
||||
if (result === 'pending') return 'pending';
|
||||
if (result === 'human_needed') return 'human_uat';
|
||||
return 'unknown';
|
||||
}
|
||||
|
||||
module.exports = { cmdAuditUat };
|
||||
@@ -5,7 +5,7 @@
|
||||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
const os = require('os');
|
||||
const { safeReadFile, normalizePhaseName, execGit, findPhaseInternal, getMilestoneInfo, stripShippedMilestones, output, error } = require('./core.cjs');
|
||||
const { safeReadFile, loadConfig, normalizePhaseName, execGit, findPhaseInternal, getMilestoneInfo, stripShippedMilestones, extractCurrentMilestone, output, error } = require('./core.cjs');
|
||||
const { extractFrontmatter, parseMustHavesBlock } = require('./frontmatter.cjs');
|
||||
const { writeStateMd } = require('./state.cjs');
|
||||
|
||||
@@ -409,7 +409,7 @@ function cmdValidateConsistency(cwd, raw) {
|
||||
}
|
||||
|
||||
const roadmapContentRaw = fs.readFileSync(roadmapPath, 'utf-8');
|
||||
const roadmapContent = stripShippedMilestones(roadmapContentRaw);
|
||||
const roadmapContent = extractCurrentMilestone(roadmapContentRaw, cwd);
|
||||
|
||||
// Extract phases from ROADMAP (archived milestones already stripped)
|
||||
const roadmapPhases = new Set();
|
||||
@@ -428,7 +428,7 @@ function cmdValidateConsistency(cwd, raw) {
|
||||
const dm = dir.match(/^(\d+[A-Z]?(?:\.\d+)*)/i);
|
||||
if (dm) diskPhases.add(dm[1]);
|
||||
}
|
||||
} catch {}
|
||||
} catch { /* intentionally empty */ }
|
||||
|
||||
// Check: phases in ROADMAP but not on disk
|
||||
for (const p of roadmapPhases) {
|
||||
@@ -445,15 +445,18 @@ function cmdValidateConsistency(cwd, raw) {
|
||||
}
|
||||
}
|
||||
|
||||
// Check: sequential phase numbers (integers only)
|
||||
const integerPhases = [...diskPhases]
|
||||
.filter(p => !p.includes('.'))
|
||||
.map(p => parseInt(p, 10))
|
||||
.sort((a, b) => a - b);
|
||||
// Check: sequential phase numbers (integers only, skip in custom naming mode)
|
||||
const config = loadConfig(cwd);
|
||||
if (config.phase_naming !== 'custom') {
|
||||
const integerPhases = [...diskPhases]
|
||||
.filter(p => !p.includes('.'))
|
||||
.map(p => parseInt(p, 10))
|
||||
.sort((a, b) => a - b);
|
||||
|
||||
for (let i = 1; i < integerPhases.length; i++) {
|
||||
if (integerPhases[i] !== integerPhases[i - 1] + 1) {
|
||||
warnings.push(`Gap in phase numbering: ${integerPhases[i - 1]} → ${integerPhases[i]}`);
|
||||
for (let i = 1; i < integerPhases.length; i++) {
|
||||
if (integerPhases[i] !== integerPhases[i - 1] + 1) {
|
||||
warnings.push(`Gap in phase numbering: ${integerPhases[i - 1]} → ${integerPhases[i]}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -490,7 +493,7 @@ function cmdValidateConsistency(cwd, raw) {
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch {}
|
||||
} catch { /* intentionally empty */ }
|
||||
|
||||
// Check: frontmatter in plans has required fields
|
||||
try {
|
||||
@@ -510,7 +513,7 @@ function cmdValidateConsistency(cwd, raw) {
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch {}
|
||||
} catch { /* intentionally empty */ }
|
||||
|
||||
const passed = errors.length === 0;
|
||||
output({ passed, errors, warnings, warning_count: warnings.length }, raw, passed ? 'passed' : 'failed');
|
||||
@@ -599,15 +602,19 @@ function cmdValidateHealth(cwd, options, raw) {
|
||||
if (m) diskPhases.add(m[1]);
|
||||
}
|
||||
}
|
||||
} catch {}
|
||||
} catch { /* intentionally empty */ }
|
||||
// Check for invalid references
|
||||
for (const ref of phaseRefs) {
|
||||
const normalizedRef = String(parseInt(ref, 10)).padStart(2, '0');
|
||||
if (!diskPhases.has(ref) && !diskPhases.has(normalizedRef) && !diskPhases.has(String(parseInt(ref, 10)))) {
|
||||
// Only warn if phases dir has any content (not just an empty project)
|
||||
if (diskPhases.size > 0) {
|
||||
addIssue('warning', 'W002', `STATE.md references phase ${ref}, but only phases ${[...diskPhases].sort().join(', ')} exist`, 'Run /gsd:health --repair to regenerate STATE.md', true);
|
||||
if (!repairs.includes('regenerateState')) repairs.push('regenerateState');
|
||||
addIssue(
|
||||
'warning',
|
||||
'W002',
|
||||
`STATE.md references phase ${ref}, but only phases ${[...diskPhases].sort().join(', ')} exist`,
|
||||
'Review STATE.md manually before changing it; /gsd:health --repair will not overwrite an existing STATE.md for phase mismatches'
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -641,7 +648,7 @@ function cmdValidateHealth(cwd, options, raw) {
|
||||
addIssue('warning', 'W008', 'config.json: workflow.nyquist_validation absent (defaults to enabled but agents may skip)', 'Run /gsd:health --repair to add key', true);
|
||||
if (!repairs.includes('addNyquistKey')) repairs.push('addNyquistKey');
|
||||
}
|
||||
} catch {}
|
||||
} catch { /* intentionally empty */ }
|
||||
}
|
||||
|
||||
// ─── Check 6: Phase directory naming (NN-name format) ─────────────────────
|
||||
@@ -652,7 +659,7 @@ function cmdValidateHealth(cwd, options, raw) {
|
||||
addIssue('warning', 'W005', `Phase directory "${e.name}" doesn't follow NN-name format`, 'Rename to match pattern (e.g., 01-setup)');
|
||||
}
|
||||
}
|
||||
} catch {}
|
||||
} catch { /* intentionally empty */ }
|
||||
|
||||
// ─── Check 7: Orphaned plans (PLAN without SUMMARY) ───────────────────────
|
||||
try {
|
||||
@@ -671,7 +678,7 @@ function cmdValidateHealth(cwd, options, raw) {
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch {}
|
||||
} catch { /* intentionally empty */ }
|
||||
|
||||
// ─── Check 7b: Nyquist VALIDATION.md consistency ────────────────────────
|
||||
try {
|
||||
@@ -689,13 +696,13 @@ function cmdValidateHealth(cwd, options, raw) {
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch {}
|
||||
} catch { /* intentionally empty */ }
|
||||
|
||||
// ─── Check 8: Run existing consistency checks ─────────────────────────────
|
||||
// Inline subset of cmdValidateConsistency
|
||||
if (fs.existsSync(roadmapPath)) {
|
||||
const roadmapContentRaw = fs.readFileSync(roadmapPath, 'utf-8');
|
||||
const roadmapContent = stripShippedMilestones(roadmapContentRaw);
|
||||
const roadmapContent = extractCurrentMilestone(roadmapContentRaw, cwd);
|
||||
const roadmapPhases = new Set();
|
||||
const phasePattern = /#{2,4}\s*Phase\s+(\d+[A-Z]?(?:\.\d+)*)\s*:/gi;
|
||||
let m;
|
||||
@@ -712,7 +719,7 @@ function cmdValidateHealth(cwd, options, raw) {
|
||||
if (dm) diskPhases.add(dm[1]);
|
||||
}
|
||||
}
|
||||
} catch {}
|
||||
} catch { /* intentionally empty */ }
|
||||
|
||||
// Phases in ROADMAP but not on disk
|
||||
for (const p of roadmapPhases) {
|
||||
@@ -746,6 +753,7 @@ function cmdValidateHealth(cwd, options, raw) {
|
||||
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,
|
||||
|
||||
@@ -50,7 +50,7 @@ Plans execute autonomously. Checkpoints formalize interaction points where human
|
||||
<task type="auto">
|
||||
<name>Start dev server for verification</name>
|
||||
<action>Run `npm run dev` in background, wait for "ready" message, capture port</action>
|
||||
<verify>curl http://localhost:3000 returns 200</verify>
|
||||
<verify>fetch http://localhost:3000 returns 200</verify>
|
||||
<done>Dev server running at http://localhost:3000</done>
|
||||
</task>
|
||||
|
||||
@@ -240,7 +240,7 @@ Plans execute autonomously. Checkpoints formalize interaction points where human
|
||||
<name>Deploy to Vercel</name>
|
||||
<files>.vercel/, vercel.json</files>
|
||||
<action>Run `vercel --yes` to deploy</action>
|
||||
<verify>vercel ls shows deployment, curl returns 200</verify>
|
||||
<verify>vercel ls shows deployment, fetch returns 200</verify>
|
||||
</task>
|
||||
|
||||
<!-- If vercel returns "Error: Not authenticated", Claude creates checkpoint on the fly -->
|
||||
@@ -261,7 +261,7 @@ Plans execute autonomously. Checkpoints formalize interaction points where human
|
||||
<task type="auto">
|
||||
<name>Retry Vercel deployment</name>
|
||||
<action>Run `vercel --yes` (now authenticated)</action>
|
||||
<verify>vercel ls shows deployment, curl returns 200</verify>
|
||||
<verify>vercel ls shows deployment, fetch returns 200</verify>
|
||||
</task>
|
||||
```
|
||||
|
||||
@@ -455,8 +455,8 @@ I'll verify: vercel whoami returns your account
|
||||
npm run dev &
|
||||
DEV_SERVER_PID=$!
|
||||
|
||||
# Wait for ready (max 30s)
|
||||
timeout 30 bash -c 'until curl -s localhost:3000 > /dev/null 2>&1; do sleep 1; done'
|
||||
# Wait for ready (max 30s) — uses fetch() for cross-platform compatibility
|
||||
timeout 30 bash -c 'until node -e "fetch(\"http://localhost:3000\").then(r=>{process.exit(r.ok?0:1)}).catch(()=>process.exit(1))" 2>/dev/null; do sleep 1; done'
|
||||
```
|
||||
|
||||
**Port conflicts:** Kill stale process (`lsof -ti:3000 | xargs kill`) or use alternate port (`--port 3001`).
|
||||
@@ -489,7 +489,9 @@ timeout 30 bash -c 'until curl -s localhost:3000 > /dev/null 2>&1; do sleep 1; d
|
||||
| Auth error | Create auth gate checkpoint |
|
||||
| Network timeout | Retry with backoff, then checkpoint if persistent |
|
||||
|
||||
**Never present a checkpoint with broken verification environment.** If `curl localhost:3000` fails, don't ask user to "visit localhost:3000".
|
||||
**Never present a checkpoint with broken verification environment.** If the local server isn't responding, don't ask user to "visit localhost:3000".
|
||||
|
||||
> **Cross-platform note:** Use `node -e "fetch('http://localhost:3000').then(r=>console.log(r.status))"` instead of `curl` for health checks. `curl` is broken on Windows MSYS/Git Bash due to SSL/path mangling issues.
|
||||
|
||||
```xml
|
||||
<!-- WRONG: Checkpoint with broken environment -->
|
||||
@@ -502,7 +504,7 @@ timeout 30 bash -c 'until curl -s localhost:3000 > /dev/null 2>&1; do sleep 1; d
|
||||
<task type="auto">
|
||||
<name>Fix server startup issue</name>
|
||||
<action>Investigate error, fix root cause, restart server</action>
|
||||
<verify>curl http://localhost:3000 returns 200</verify>
|
||||
<verify>fetch http://localhost:3000 returns 200</verify>
|
||||
</task>
|
||||
|
||||
<task type="checkpoint:human-verify">
|
||||
@@ -608,7 +610,7 @@ timeout 30 bash -c 'until curl -s localhost:3000 > /dev/null 2>&1; do sleep 1; d
|
||||
<task type="auto">
|
||||
<name>Start dev server for auth testing</name>
|
||||
<action>Run `npm run dev` in background, wait for ready signal</action>
|
||||
<verify>curl http://localhost:3000 returns 200</verify>
|
||||
<verify>fetch http://localhost:3000 returns 200</verify>
|
||||
<done>Dev server running at http://localhost:3000</done>
|
||||
</task>
|
||||
|
||||
@@ -651,7 +653,7 @@ timeout 30 bash -c 'until curl -s localhost:3000 > /dev/null 2>&1; do sleep 1; d
|
||||
<task type="auto">
|
||||
<name>Start dev server</name>
|
||||
<action>Run `npm run dev` in background</action>
|
||||
<verify>curl localhost:3000 returns 200</verify>
|
||||
<verify>fetch http://localhost:3000 returns 200</verify>
|
||||
</task>
|
||||
|
||||
<task type="checkpoint:human-verify" gate="blocking">
|
||||
@@ -677,7 +679,7 @@ timeout 30 bash -c 'until curl -s localhost:3000 > /dev/null 2>&1; do sleep 1; d
|
||||
<task type="auto">
|
||||
<name>Deploy to Vercel</name>
|
||||
<action>Run `vercel --yes`. Capture URL.</action>
|
||||
<verify>vercel ls shows deployment, curl returns 200</verify>
|
||||
<verify>vercel ls shows deployment, fetch returns 200</verify>
|
||||
</task>
|
||||
|
||||
<task type="checkpoint:human-verify">
|
||||
|
||||
@@ -61,6 +61,10 @@ node "$HOME/.claude/get-shit-done/bin/gsd-tools.cjs" commit "docs: initialize [p
|
||||
|
||||
Each task gets its own commit immediately after completion.
|
||||
|
||||
> **Parallel agents:** When running as a parallel executor (spawned by execute-phase),
|
||||
> use `--no-verify` on all commits to avoid pre-commit hook lock contention.
|
||||
> The orchestrator validates hooks once after all agents complete.
|
||||
|
||||
```
|
||||
{type}({phase}-{plan}): {task-name}
|
||||
|
||||
@@ -246,3 +250,46 @@ Each plan produces 2-4 commits (tasks + metadata). Clear, granular, bisectable.
|
||||
- "Commit noise" irrelevant when consumer is Claude, not humans
|
||||
|
||||
</commit_strategy_rationale>
|
||||
|
||||
<sub_repos_support>
|
||||
|
||||
## Multi-Repo Workspace Support (sub_repos)
|
||||
|
||||
For workspaces with separate git repos (e.g., `backend/`, `frontend/`, `shared/`), GSD routes commits to each repo independently.
|
||||
|
||||
### Configuration
|
||||
|
||||
In `.planning/config.json`, list sub-repo directories under `planning.sub_repos`:
|
||||
|
||||
```json
|
||||
{
|
||||
"planning": {
|
||||
"commit_docs": false,
|
||||
"sub_repos": ["backend", "frontend", "shared"]
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Set `commit_docs: false` so planning docs stay local and are not committed to any sub-repo.
|
||||
|
||||
### How It Works
|
||||
|
||||
1. **Auto-detection:** During `/gsd:new-project`, directories with their own `.git` folder are detected and offered for selection as sub-repos. On subsequent runs, `loadConfig` auto-syncs the `sub_repos` list with the filesystem — adding newly created repos and removing deleted ones. This means `config.json` may be rewritten automatically when repos change on disk.
|
||||
2. **File grouping:** Code files are grouped by their sub-repo prefix (e.g., `backend/src/api/users.ts` belongs to the `backend/` repo).
|
||||
3. **Independent commits:** Each sub-repo receives its own atomic commit via `gsd-tools.cjs commit-to-subrepo`. File paths are made relative to the sub-repo root before staging.
|
||||
4. **Planning stays local:** The `.planning/` directory is not committed; it acts as cross-repo coordination.
|
||||
|
||||
### Commit Routing
|
||||
|
||||
Instead of the standard `commit` command, use `commit-to-subrepo` when `sub_repos` is configured:
|
||||
|
||||
```bash
|
||||
node ~/.claude/get-shit-done/bin/gsd-tools.cjs commit-to-subrepo "feat(02-01): add user API" \
|
||||
--files backend/src/api/users.ts backend/src/types/user.ts frontend/src/components/UserForm.tsx
|
||||
```
|
||||
|
||||
This stages `src/api/users.ts` and `src/types/user.ts` in the `backend/` repo, and `src/components/UserForm.tsx` in the `frontend/` repo, then commits each independently with the same message.
|
||||
|
||||
Files that don't match any configured sub-repo are reported as unmatched.
|
||||
|
||||
</sub_repos_support>
|
||||
|
||||
@@ -40,8 +40,26 @@ Model profiles control which Claude model each GSD agent uses. This allows balan
|
||||
**inherit** - Follow the current session model
|
||||
- All agents resolve to `inherit`
|
||||
- Best when you switch models interactively (for example OpenCode `/model`)
|
||||
- **Required when using non-Anthropic providers** (OpenRouter, local models, etc.) — otherwise GSD may call Anthropic models directly, incurring unexpected costs
|
||||
- Use when: you want GSD to follow your currently selected runtime model
|
||||
|
||||
## Using Non-Anthropic Models (OpenRouter, Local, etc.)
|
||||
|
||||
If you're using Claude Code with OpenRouter, a local model, or any non-Anthropic provider, set the `inherit` profile to prevent GSD from calling Anthropic models for subagents:
|
||||
|
||||
```bash
|
||||
# Via settings command
|
||||
/gsd:settings
|
||||
# → Select "Inherit" for model profile
|
||||
|
||||
# Or manually in .planning/config.json
|
||||
{
|
||||
"model_profile": "inherit"
|
||||
}
|
||||
```
|
||||
|
||||
Without `inherit`, GSD's default `balanced` profile spawns specific Anthropic models (`opus`, `sonnet`, `haiku`) for each agent type, which can result in additional API costs through your non-Anthropic provider.
|
||||
|
||||
## Resolution Logic
|
||||
|
||||
Orchestrators resolve model before spawning:
|
||||
|
||||
@@ -11,7 +11,8 @@ Configuration options for `.planning/` directory behavior.
|
||||
"git": {
|
||||
"branching_strategy": "none",
|
||||
"phase_branch_template": "gsd/phase-{phase}-{slug}",
|
||||
"milestone_branch_template": "gsd/{milestone}-{slug}"
|
||||
"milestone_branch_template": "gsd/{milestone}-{slug}",
|
||||
"quick_branch_template": null
|
||||
}
|
||||
```
|
||||
|
||||
@@ -22,6 +23,7 @@ Configuration options for `.planning/` directory behavior.
|
||||
| `git.branching_strategy` | `"none"` | Git branching approach: `"none"`, `"phase"`, or `"milestone"` |
|
||||
| `git.phase_branch_template` | `"gsd/phase-{phase}-{slug}"` | Branch template for phase strategy |
|
||||
| `git.milestone_branch_template` | `"gsd/{milestone}-{slug}"` | Branch template for milestone strategy |
|
||||
| `git.quick_branch_template` | `null` | Optional branch template for quick-task runs |
|
||||
</config_schema>
|
||||
|
||||
<commit_docs_behavior>
|
||||
|
||||
@@ -8,7 +8,7 @@ Template for `.planning/phases/XX-name/{phase_num}-UAT.md` — persistent UAT se
|
||||
|
||||
```markdown
|
||||
---
|
||||
status: testing | complete | diagnosed
|
||||
status: testing | partial | complete | diagnosed
|
||||
phase: XX-name
|
||||
source: [list of SUMMARY.md files tested]
|
||||
started: [ISO timestamp]
|
||||
@@ -45,6 +45,12 @@ expected: [observable behavior]
|
||||
result: skipped
|
||||
reason: [why skipped]
|
||||
|
||||
### 5. [Test Name]
|
||||
expected: [observable behavior]
|
||||
result: blocked
|
||||
blocked_by: server | physical-device | release-build | third-party | prior-phase
|
||||
reason: [why blocked]
|
||||
|
||||
...
|
||||
|
||||
## Summary
|
||||
@@ -54,6 +60,7 @@ passed: [N]
|
||||
issues: [N]
|
||||
pending: [N]
|
||||
skipped: [N]
|
||||
blocked: [N]
|
||||
|
||||
## Gaps
|
||||
|
||||
@@ -74,7 +81,7 @@ skipped: [N]
|
||||
<section_rules>
|
||||
|
||||
**Frontmatter:**
|
||||
- `status`: OVERWRITE - "testing" or "complete"
|
||||
- `status`: OVERWRITE - "testing", "partial", or "complete"
|
||||
- `phase`: IMMUTABLE - set on creation
|
||||
- `source`: IMMUTABLE - SUMMARY files being tested
|
||||
- `started`: IMMUTABLE - set on creation
|
||||
@@ -87,9 +94,10 @@ skipped: [N]
|
||||
|
||||
**Tests:**
|
||||
- Each test: OVERWRITE result field when user responds
|
||||
- `result` values: [pending], pass, issue, skipped
|
||||
- `result` values: [pending], pass, issue, skipped, blocked
|
||||
- If issue: add `reported` (verbatim) and `severity` (inferred)
|
||||
- If skipped: add `reason` if provided
|
||||
- If blocked: add `blocked_by` (tag) and `reason` (if provided)
|
||||
|
||||
**Summary:**
|
||||
- OVERWRITE counts after each response
|
||||
@@ -156,6 +164,16 @@ skipped: [N]
|
||||
- Commit file
|
||||
- Present summary with next steps
|
||||
|
||||
**Partial completion:**
|
||||
- status → "partial" (if pending, blocked, or unresolved skipped tests remain)
|
||||
- Current Test → "[testing paused — {N} items outstanding]"
|
||||
- Commit file
|
||||
- Present summary with outstanding items highlighted
|
||||
|
||||
**Resuming partial session:**
|
||||
- `/gsd:verify-work {phase}` picks up from first pending/blocked test
|
||||
- When all items resolved, status advances to "complete"
|
||||
|
||||
**Resume after /clear:**
|
||||
1. Read frontmatter → know phase and status
|
||||
2. Read Current Test → know where we are
|
||||
|
||||
@@ -2,8 +2,8 @@
|
||||
|
||||
Template for project-root `CLAUDE.md` — auto-generated by `gsd-tools generate-claude-md`.
|
||||
|
||||
Contains 5 marker-bounded sections. Each section is independently updatable.
|
||||
The `generate-claude-md` subcommand manages 4 sections (project, stack, conventions, architecture).
|
||||
Contains 6 marker-bounded sections. Each section is independently updatable.
|
||||
The `generate-claude-md` subcommand manages 5 sections (project, stack, conventions, architecture, workflow enforcement).
|
||||
The profile section is managed exclusively by `generate-claude-profile`.
|
||||
|
||||
---
|
||||
@@ -66,6 +66,22 @@ Conventions not yet established. Will populate as patterns emerge during develop
|
||||
Architecture not yet mapped. Follow existing patterns found in the codebase.
|
||||
```
|
||||
|
||||
### Workflow Enforcement Section
|
||||
```
|
||||
<!-- GSD:workflow-start source:GSD defaults -->
|
||||
## GSD Workflow Enforcement
|
||||
|
||||
Before using Edit, Write, or other file-changing tools, start work through a GSD command so planning artifacts and execution context stay in sync.
|
||||
|
||||
Use these entry points:
|
||||
- `/gsd:quick` for small fixes, doc updates, and ad-hoc tasks
|
||||
- `/gsd:debug` for investigation and bug fixing
|
||||
- `/gsd:execute-phase` for planned phase work
|
||||
|
||||
Do not make direct repo edits outside a GSD workflow unless the user explicitly asks to bypass it.
|
||||
<!-- GSD:workflow-end -->
|
||||
```
|
||||
|
||||
### Profile Section (Placeholder Only)
|
||||
```
|
||||
<!-- GSD:profile-start -->
|
||||
@@ -88,7 +104,8 @@ CLAUDE.md file and no profile section exists yet.
|
||||
2. **Stack** — Technology choices (what tools are used)
|
||||
3. **Conventions** — Code patterns and rules (how code is written)
|
||||
4. **Architecture** — System structure (how components fit together)
|
||||
5. **Profile** — Developer behavioral preferences (how to interact)
|
||||
5. **Workflow Enforcement** — Default GSD entry points for file-changing work
|
||||
6. **Profile** — Developer behavioral preferences (how to interact)
|
||||
|
||||
## Marker Format
|
||||
|
||||
|
||||
@@ -10,7 +10,8 @@
|
||||
},
|
||||
"planning": {
|
||||
"commit_docs": true,
|
||||
"search_gitignored": false
|
||||
"search_gitignored": false,
|
||||
"sub_repos": []
|
||||
},
|
||||
"parallelization": {
|
||||
"enabled": true,
|
||||
|
||||
63
get-shit-done/templates/discussion-log.md
Normal file
63
get-shit-done/templates/discussion-log.md
Normal file
@@ -0,0 +1,63 @@
|
||||
# Discussion Log Template
|
||||
|
||||
Template for `.planning/phases/XX-name/{phase_num}-DISCUSSION-LOG.md` — audit trail of discuss-phase Q&A sessions.
|
||||
|
||||
**Purpose:** Software audit trail for decision-making. Captures all options considered, not just the selected one. Separate from CONTEXT.md which is the implementation artifact consumed by downstream agents.
|
||||
|
||||
**NOT for LLM consumption.** This file should never be referenced in `<files_to_read>` blocks or agent prompts.
|
||||
|
||||
## Format
|
||||
|
||||
```markdown
|
||||
# Phase [X]: [Name] - Discussion Log
|
||||
|
||||
> **Audit trail only.** Do not use as input to planning, research, or execution agents.
|
||||
> Decisions are captured in CONTEXT.md — this log preserves the alternatives considered.
|
||||
|
||||
**Date:** [ISO date]
|
||||
**Phase:** [phase number]-[phase name]
|
||||
**Areas discussed:** [comma-separated list]
|
||||
|
||||
---
|
||||
|
||||
## [Area 1 Name]
|
||||
|
||||
| Option | Description | Selected |
|
||||
|--------|-------------|----------|
|
||||
| [Option 1] | [Brief description] | |
|
||||
| [Option 2] | [Brief description] | ✓ |
|
||||
| [Option 3] | [Brief description] | |
|
||||
|
||||
**User's choice:** [Selected option or verbatim free-text response]
|
||||
**Notes:** [Any clarifications or rationale provided during discussion]
|
||||
|
||||
---
|
||||
|
||||
## [Area 2 Name]
|
||||
|
||||
...
|
||||
|
||||
---
|
||||
|
||||
## Claude's Discretion
|
||||
|
||||
[Areas delegated to Claude's judgment — list what was deferred and why]
|
||||
|
||||
## Deferred Ideas
|
||||
|
||||
[Ideas mentioned but not in scope for this phase]
|
||||
|
||||
---
|
||||
|
||||
*Phase: XX-name*
|
||||
*Discussion log generated: [date]*
|
||||
```
|
||||
|
||||
## Rules
|
||||
|
||||
- Generated automatically at end of every discuss-phase session
|
||||
- Includes ALL options considered, not just the selected one
|
||||
- Includes user's freeform notes and clarifications
|
||||
- Clearly marked as audit-only, not an implementation artifact
|
||||
- Does NOT interfere with CONTEXT.md generation or downstream agent behavior
|
||||
- Committed alongside CONTEXT.md in the same git commit
|
||||
@@ -341,7 +341,7 @@ Output: User model, API endpoints, and UI components.
|
||||
<name>Task 2: Create User API endpoints</name>
|
||||
<files>src/features/user/api.ts</files>
|
||||
<action>GET /users (list), GET /users/:id (single), POST /users (create). Use User type from model.</action>
|
||||
<verify>curl tests pass for all endpoints</verify>
|
||||
<verify>fetch tests pass for all endpoints</verify>
|
||||
<done>All CRUD operations work</done>
|
||||
</task>
|
||||
</tasks>
|
||||
@@ -407,7 +407,7 @@ Output: Working dashboard component.
|
||||
<task type="auto">
|
||||
<name>Start dev server</name>
|
||||
<action>Run `npm run dev` in background, wait for ready</action>
|
||||
<verify>curl localhost:3000 returns 200</verify>
|
||||
<verify>fetch http://localhost:3000 returns 200</verify>
|
||||
</task>
|
||||
|
||||
<task type="checkpoint:human-verify" gate="blocking">
|
||||
|
||||
@@ -127,6 +127,8 @@ Common types: Tech stack, Timeline, Budget, Dependencies, Compatibility, Perform
|
||||
<evolution>
|
||||
|
||||
PROJECT.md evolves throughout the project lifecycle.
|
||||
These rules are embedded in the generated PROJECT.md (## Evolution section)
|
||||
and implemented by workflows/transition.md and workflows/complete-milestone.md.
|
||||
|
||||
**After each phase transition:**
|
||||
1. Requirements invalidated? → Move to Out of Scope with reason
|
||||
|
||||
109
get-shit-done/workflows/audit-uat.md
Normal file
109
get-shit-done/workflows/audit-uat.md
Normal file
@@ -0,0 +1,109 @@
|
||||
<purpose>
|
||||
Cross-phase audit of all UAT and verification files. Finds every outstanding item (pending, skipped, blocked, human_needed), optionally verifies against the codebase to detect stale docs, and produces a prioritized human test plan.
|
||||
</purpose>
|
||||
|
||||
<process>
|
||||
|
||||
<step name="initialize">
|
||||
Run the CLI audit:
|
||||
|
||||
```bash
|
||||
AUDIT=$(node "$HOME/.claude/get-shit-done/bin/gsd-tools.cjs" audit-uat --raw)
|
||||
```
|
||||
|
||||
Parse JSON for `results` array and `summary` object.
|
||||
|
||||
If `summary.total_items` is 0:
|
||||
```
|
||||
## All Clear
|
||||
|
||||
No outstanding UAT or verification items found across all phases.
|
||||
All tests are passing, resolved, or diagnosed with fix plans.
|
||||
```
|
||||
Stop here.
|
||||
</step>
|
||||
|
||||
<step name="categorize">
|
||||
Group items by what's actionable NOW vs. what needs prerequisites:
|
||||
|
||||
**Testable Now** (no external dependencies):
|
||||
- `pending` — tests never run
|
||||
- `human_uat` — human verification items
|
||||
- `skipped_unresolved` — skipped without clear blocking reason
|
||||
|
||||
**Needs Prerequisites:**
|
||||
- `server_blocked` — needs external server running
|
||||
- `device_needed` — needs physical device (not simulator)
|
||||
- `build_needed` — needs release/preview build
|
||||
- `third_party` — needs external service configuration
|
||||
|
||||
For each item in "Testable Now", use Grep/Read to check if the underlying feature still exists in the codebase:
|
||||
- If the test references a component/function that no longer exists → mark as `stale`
|
||||
- If the test references code that has been significantly rewritten → mark as `needs_update`
|
||||
- Otherwise → mark as `active`
|
||||
</step>
|
||||
|
||||
<step name="present">
|
||||
Present the audit report:
|
||||
|
||||
```
|
||||
## UAT Audit Report
|
||||
|
||||
**{total_items} outstanding items across {total_files} files in {phase_count} phases**
|
||||
|
||||
### Testable Now ({count})
|
||||
|
||||
| # | Phase | Test | Description | Status |
|
||||
|---|-------|------|-------------|--------|
|
||||
| 1 | {phase} | {test_name} | {expected} | {active/stale/needs_update} |
|
||||
...
|
||||
|
||||
### Needs Prerequisites ({count})
|
||||
|
||||
| # | Phase | Test | Blocked By | Description |
|
||||
|---|-------|------|------------|-------------|
|
||||
| 1 | {phase} | {test_name} | {category} | {expected} |
|
||||
...
|
||||
|
||||
### Stale (can be closed) ({count})
|
||||
|
||||
| # | Phase | Test | Why Stale |
|
||||
|---|-------|------|-----------|
|
||||
| 1 | {phase} | {test_name} | {reason} |
|
||||
...
|
||||
|
||||
---
|
||||
|
||||
## Recommended Actions
|
||||
|
||||
1. **Close stale items:** `/gsd:verify-work {phase}` — mark stale tests as resolved
|
||||
2. **Run active tests:** Human UAT test plan below
|
||||
3. **When prerequisites met:** Retest blocked items with `/gsd:verify-work {phase}`
|
||||
```
|
||||
</step>
|
||||
|
||||
<step name="test_plan">
|
||||
Generate a human UAT test plan for "Testable Now" + "active" items only:
|
||||
|
||||
Group by what can be tested together (same screen, same feature, same prerequisite):
|
||||
|
||||
```
|
||||
## Human UAT Test Plan
|
||||
|
||||
### Group 1: {category — e.g., "Billing Flow"}
|
||||
Prerequisites: {what needs to be running/configured}
|
||||
|
||||
1. **{Test name}** (Phase {N})
|
||||
- Navigate to: {where}
|
||||
- Do: {action}
|
||||
- Expected: {expected behavior}
|
||||
|
||||
2. **{Test name}** (Phase {N})
|
||||
...
|
||||
|
||||
### Group 2: {category}
|
||||
...
|
||||
```
|
||||
</step>
|
||||
|
||||
</process>
|
||||
@@ -110,6 +110,18 @@ Phase: "API documentation"
|
||||
1. Retry the question once with the same parameters
|
||||
2. If still empty, present the options as a plain-text numbered list and ask the user to type their choice number
|
||||
Never proceed with an empty answer.
|
||||
|
||||
**Text mode (`workflow.text_mode: true` in config or `--text` flag):**
|
||||
When text mode is active, **do not use AskUserQuestion at all**. Instead, present every
|
||||
question as a plain-text numbered list and ask the user to type their choice number.
|
||||
This is required for Claude Code remote sessions (`/rc` mode) where the Claude App
|
||||
cannot forward TUI menu selections back to the host.
|
||||
|
||||
Enable text mode:
|
||||
- Per-session: pass `--text` flag to any command (e.g., `/gsd:discuss-phase --text`)
|
||||
- Per-project: `gsd-tools config-set workflow.text_mode true`
|
||||
|
||||
Text mode applies to ALL workflows in the session, not just discuss-phase.
|
||||
</answer_validation>
|
||||
|
||||
<process>
|
||||
@@ -242,6 +254,47 @@ Structure the extracted information:
|
||||
**If no prior context exists:** Continue without — this is expected for early phases.
|
||||
</step>
|
||||
|
||||
<step name="cross_reference_todos">
|
||||
Check if any pending todos are relevant to this phase's scope. Surfaces backlog items that might otherwise be missed.
|
||||
|
||||
**Load and match todos:**
|
||||
```bash
|
||||
TODO_MATCHES=$(node "$HOME/.claude/get-shit-done/bin/gsd-tools.cjs" todo match-phase "${PHASE_NUMBER}")
|
||||
```
|
||||
|
||||
Parse JSON for: `todo_count`, `matches[]` (each with `file`, `title`, `area`, `score`, `reasons`).
|
||||
|
||||
**If `todo_count` is 0 or `matches` is empty:** Skip silently — no workflow slowdown.
|
||||
|
||||
**If matches found:**
|
||||
|
||||
Present matched todos to the user. Show each match with its title, area, and why it matched:
|
||||
|
||||
```
|
||||
📋 Found {N} pending todo(s) that may be relevant to Phase {X}:
|
||||
|
||||
{For each match:}
|
||||
- **{title}** (area: {area}, relevance: {score}) — matched on {reasons}
|
||||
```
|
||||
|
||||
Use AskUserQuestion (multiSelect) asking which todos to fold into this phase's scope:
|
||||
|
||||
```
|
||||
Which of these todos should be folded into Phase {X} scope?
|
||||
(Select any that apply, or none to skip)
|
||||
```
|
||||
|
||||
**For selected (folded) todos:**
|
||||
- Store internally as `<folded_todos>` for inclusion in CONTEXT.md `<decisions>` section
|
||||
- These become additional scope items that downstream agents (researcher, planner) will see
|
||||
|
||||
**For unselected (reviewed but not folded) todos:**
|
||||
- Store internally as `<reviewed_todos>` for inclusion in CONTEXT.md `<deferred>` section
|
||||
- This prevents future phases from re-surfacing the same todos as "missed"
|
||||
|
||||
**Auto mode (`--auto`):** Fold all todos with score >= 0.4 automatically. Log the selection.
|
||||
</step>
|
||||
|
||||
<step name="scout_codebase">
|
||||
Lightweight scan of existing code to inform gray area identification and discussion. Uses ~10% context — acceptable for an interactive session.
|
||||
|
||||
@@ -404,8 +457,58 @@ Continue to discuss_areas with selected areas.
|
||||
<step name="discuss_areas">
|
||||
For each selected area, conduct a focused discussion loop.
|
||||
|
||||
**Research-before-questions mode:** Check if `research_questions` is enabled in config (from init context or `.planning/config.json`). When enabled, before presenting questions for each area:
|
||||
1. Do a brief web search for best practices related to the area topic
|
||||
2. Summarize the top findings in 2-3 bullet points
|
||||
3. Present the research alongside the question so the user can make a more informed decision
|
||||
|
||||
Example with research enabled:
|
||||
```
|
||||
Let's talk about [Authentication Strategy].
|
||||
|
||||
📊 Best practices research:
|
||||
• OAuth 2.0 + PKCE is the current standard for SPAs (replaces implicit flow)
|
||||
• Session tokens with httpOnly cookies preferred over localStorage for XSS protection
|
||||
• Consider passkey/WebAuthn support — adoption is accelerating in 2025-2026
|
||||
|
||||
With that context: How should users authenticate?
|
||||
```
|
||||
|
||||
When disabled (default), skip the research and present questions directly as before.
|
||||
|
||||
**Text mode support:** Parse optional `--text` from `$ARGUMENTS`.
|
||||
- Accept `--text` flag OR read `workflow.text_mode` from config (from init context)
|
||||
- When active, replace ALL `AskUserQuestion` calls with plain-text numbered lists
|
||||
- User types a number to select, or types free text for "Other"
|
||||
- This is required for Claude Code remote sessions (`/rc` mode) where TUI menus
|
||||
don't work through the Claude App
|
||||
|
||||
**Batch mode support:** Parse optional `--batch` from `$ARGUMENTS`.
|
||||
- Accept `--batch`, `--batch=N`, or `--batch N`
|
||||
|
||||
**Analyze mode support:** Parse optional `--analyze` from `$ARGUMENTS`.
|
||||
When `--analyze` is active, before presenting each question (or question group in batch mode), provide a brief **trade-off analysis** for the decision:
|
||||
- 2-3 options with pros/cons based on codebase context and common patterns
|
||||
- A recommended approach with reasoning
|
||||
- Known pitfalls or constraints from prior phases
|
||||
|
||||
Example with `--analyze`:
|
||||
```
|
||||
**Trade-off analysis: Authentication strategy**
|
||||
|
||||
| Approach | Pros | Cons |
|
||||
|----------|------|------|
|
||||
| Session cookies | Simple, httpOnly prevents XSS | Requires CSRF protection, sticky sessions |
|
||||
| JWT (stateless) | Scalable, no server state | Token size, revocation complexity |
|
||||
| OAuth 2.0 + PKCE | Industry standard for SPAs | More setup, redirect flow UX |
|
||||
|
||||
💡 Recommended: OAuth 2.0 + PKCE — your app has social login in requirements (REQ-04) and this aligns with the existing NextAuth setup in `src/lib/auth.ts`.
|
||||
|
||||
How should users authenticate?
|
||||
```
|
||||
|
||||
This gives the user context to make informed decisions without extra prompting. When `--analyze` is absent, present questions directly as before.
|
||||
- Accept `--batch`, `--batch=N`, or `--batch N`
|
||||
- Default to 4 questions per batch when no number is provided
|
||||
- Clamp explicit sizes to 2-5 so a batch stays answerable
|
||||
- If `--batch` is absent, keep the existing one-question-at-a-time flow
|
||||
@@ -500,11 +603,23 @@ Back to [current area]: [return to current question]"
|
||||
```
|
||||
|
||||
Track deferred ideas internally.
|
||||
|
||||
**Track discussion log data internally:**
|
||||
For each question asked, accumulate:
|
||||
- Area name
|
||||
- All options presented (label + description)
|
||||
- Which option the user selected (or their free-text response)
|
||||
- Any follow-up notes or clarifications the user provided
|
||||
This data is used to generate DISCUSSION-LOG.md in the `write_context` step.
|
||||
</step>
|
||||
|
||||
<step name="write_context">
|
||||
Create CONTEXT.md capturing decisions made.
|
||||
|
||||
**Also generate DISCUSSION-LOG.md** — a full audit trail of the discuss-phase Q&A.
|
||||
This file is for human reference only (software audits, compliance reviews). It is NOT
|
||||
consumed by downstream agents (researcher, planner, executor).
|
||||
|
||||
**Find or create phase directory:**
|
||||
|
||||
Use values from init: `phase_dir`, `phase_slug`, `padded_phase`.
|
||||
@@ -544,6 +659,11 @@ mkdir -p ".planning/phases/${padded_phase}-${phase_slug}"
|
||||
### Claude's Discretion
|
||||
[Areas where user said "you decide" — note that Claude has flexibility here]
|
||||
|
||||
### Folded Todos
|
||||
[If any todos were folded into scope from the cross_reference_todos step, list them here.
|
||||
Each entry should include the todo title, original problem, and how it fits this phase's scope.
|
||||
If no todos were folded: omit this subsection entirely.]
|
||||
|
||||
</decisions>
|
||||
|
||||
<canonical_refs>
|
||||
@@ -595,6 +715,12 @@ Every entry needs a full relative path — not just a name.]
|
||||
|
||||
[Ideas that came up but belong in other phases. Don't lose them.]
|
||||
|
||||
### Reviewed Todos (not folded)
|
||||
[If any todos were reviewed in cross_reference_todos but not folded into scope,
|
||||
list them here so future phases know they were considered.
|
||||
Each entry: todo title + reason it was deferred (out of scope, belongs in Phase Y, etc.)
|
||||
If no reviewed-but-deferred todos: omit this subsection entirely.]
|
||||
|
||||
[If none: "None — discussion stayed within phase scope"]
|
||||
|
||||
</deferred>
|
||||
@@ -648,10 +774,54 @@ Created: .planning/phases/${PADDED_PHASE}-${SLUG}/${PADDED_PHASE}-CONTEXT.md
|
||||
</step>
|
||||
|
||||
<step name="git_commit">
|
||||
Commit phase context (uses `commit_docs` from init internally):
|
||||
**Write DISCUSSION-LOG.md before committing:**
|
||||
|
||||
**File location:** `${phase_dir}/${padded_phase}-DISCUSSION-LOG.md`
|
||||
|
||||
```markdown
|
||||
# Phase [X]: [Name] - Discussion Log
|
||||
|
||||
> **Audit trail only.** Do not use as input to planning, research, or execution agents.
|
||||
> Decisions are captured in CONTEXT.md — this log preserves the alternatives considered.
|
||||
|
||||
**Date:** [ISO date]
|
||||
**Phase:** [phase number]-[phase name]
|
||||
**Areas discussed:** [comma-separated list]
|
||||
|
||||
---
|
||||
|
||||
[For each gray area discussed:]
|
||||
|
||||
## [Area Name]
|
||||
|
||||
| Option | Description | Selected |
|
||||
|--------|-------------|----------|
|
||||
| [Option 1] | [Description from AskUserQuestion] | |
|
||||
| [Option 2] | [Description] | ✓ |
|
||||
| [Option 3] | [Description] | |
|
||||
|
||||
**User's choice:** [Selected option or free-text response]
|
||||
**Notes:** [Any clarifications, follow-up context, or rationale the user provided]
|
||||
|
||||
---
|
||||
|
||||
[Repeat for each area]
|
||||
|
||||
## Claude's Discretion
|
||||
|
||||
[List areas where user said "you decide" or deferred to Claude]
|
||||
|
||||
## Deferred Ideas
|
||||
|
||||
[Ideas mentioned during discussion that were noted for future phases]
|
||||
```
|
||||
|
||||
Write file.
|
||||
|
||||
Commit phase context and discussion log:
|
||||
|
||||
```bash
|
||||
node "$HOME/.claude/get-shit-done/bin/gsd-tools.cjs" commit "docs(${padded_phase}): capture phase context" --files "${phase_dir}/${padded_phase}-CONTEXT.md"
|
||||
node "$HOME/.claude/get-shit-done/bin/gsd-tools.cjs" commit "docs(${padded_phase}): capture phase context" --files "${phase_dir}/${padded_phase}-CONTEXT.md" "${phase_dir}/${padded_phase}-DISCUSSION-LOG.md"
|
||||
```
|
||||
|
||||
Confirm: "Committed: docs(${padded_phase}): capture phase context"
|
||||
|
||||
@@ -6,10 +6,45 @@ Execute all plans in a phase using wave-based parallel execution. Orchestrator s
|
||||
Orchestrator coordinates, not executes. Each subagent loads the full execute-plan context. Orchestrator: discover plans → analyze deps → group waves → spawn agents → handle checkpoints → collect results.
|
||||
</core_principle>
|
||||
|
||||
<runtime_compatibility>
|
||||
**Subagent spawning is runtime-specific:**
|
||||
- **Claude Code:** Uses `Task(subagent_type="gsd-executor", ...)` — blocks until complete, returns result
|
||||
- **Copilot:** Subagent spawning does not reliably return completion signals. **Default to
|
||||
sequential inline execution**: read and follow execute-plan.md directly for each plan
|
||||
instead of spawning parallel agents. Only attempt parallel spawning if the user
|
||||
explicitly requests it — and in that case, rely on the spot-check fallback in step 3
|
||||
to detect completion.
|
||||
- **Other runtimes (Gemini, Codex, OpenCode):** If Task/subagent API is unavailable, use sequential
|
||||
inline execution as the fallback.
|
||||
|
||||
**Fallback rule:** If a spawned agent completes its work (commits visible, SUMMARY.md exists) but
|
||||
the orchestrator never receives the completion signal, treat it as successful based on spot-checks
|
||||
and continue to the next wave/plan. Never block indefinitely waiting for a signal — always verify
|
||||
via filesystem and git state.
|
||||
</runtime_compatibility>
|
||||
|
||||
<required_reading>
|
||||
Read STATE.md before any operation to load project context.
|
||||
</required_reading>
|
||||
|
||||
<available_agent_types>
|
||||
These are the valid GSD subagent types registered in .claude/agents/ (or equivalent for your runtime).
|
||||
Always use the exact name from this list — do not fall back to 'general-purpose' or other built-in types:
|
||||
|
||||
- gsd-executor — Executes plan tasks, commits, creates SUMMARY.md
|
||||
- gsd-verifier — Verifies phase completion, checks quality gates
|
||||
- gsd-planner — Creates detailed plans from phase scope
|
||||
- gsd-phase-researcher — Researches technical approaches for a phase
|
||||
- gsd-plan-checker — Reviews plan quality before execution
|
||||
- gsd-debugger — Diagnoses and fixes issues
|
||||
- gsd-codebase-mapper — Maps project structure and dependencies
|
||||
- gsd-integration-checker — Checks cross-phase integration
|
||||
- gsd-nyquist-auditor — Validates verification coverage
|
||||
- gsd-ui-researcher — Researches UI/UX approaches
|
||||
- gsd-ui-checker — Reviews UI implementation quality
|
||||
- gsd-ui-auditor — Audits UI against design requirements
|
||||
</available_agent_types>
|
||||
|
||||
<process>
|
||||
|
||||
<step name="parse_args" priority="first">
|
||||
@@ -38,6 +73,14 @@ Parse JSON for: `executor_model`, `verifier_model`, `commit_docs`, `parallelizat
|
||||
|
||||
When `parallelization` is false, plans within a wave execute sequentially.
|
||||
|
||||
**Runtime detection for Copilot:**
|
||||
Check if the current runtime is Copilot by testing for the `@gsd-executor` agent pattern
|
||||
or absence of the `Task()` subagent API. If running under Copilot, force sequential inline
|
||||
execution regardless of the `parallelization` setting — Copilot's subagent completion
|
||||
signals are unreliable (see `<runtime_compatibility>`). Set `COPILOT_SEQUENTIAL=true`
|
||||
internally and skip the `execute_waves` step in favor of `check_interactive_mode`'s
|
||||
inline path for each plan.
|
||||
|
||||
**REQUIRED — Sync chain flag with intent.** If user invoked manually (no `--auto`), clear the ephemeral chain flag from any previous interrupted `--auto` chain. This prevents stale `_auto_chain_active: true` from causing unwanted auto-advance. This does NOT touch `workflow.auto_advance` (the user's persistent settings preference). You MUST execute this bash block before any config reads:
|
||||
```bash
|
||||
# REQUIRED: prevents stale auto-chain from previous --auto runs
|
||||
@@ -47,6 +90,54 @@ fi
|
||||
```
|
||||
</step>
|
||||
|
||||
<step name="check_interactive_mode">
|
||||
**Parse `--interactive` flag from $ARGUMENTS.**
|
||||
|
||||
**If `--interactive` flag present:** Switch to interactive execution mode.
|
||||
|
||||
Interactive mode executes plans sequentially **inline** (no subagent spawning) with user
|
||||
checkpoints between tasks. The user can review, modify, or redirect work at any point.
|
||||
|
||||
**Interactive execution flow:**
|
||||
|
||||
1. Load plan inventory as normal (discover_and_group_plans)
|
||||
2. For each plan (sequentially, ignoring wave grouping):
|
||||
|
||||
a. **Present the plan to the user:**
|
||||
```
|
||||
## Plan {plan_id}: {plan_name}
|
||||
|
||||
Objective: {from plan file}
|
||||
Tasks: {task_count}
|
||||
|
||||
Options:
|
||||
- Execute (proceed with all tasks)
|
||||
- Review first (show task breakdown before starting)
|
||||
- Skip (move to next plan)
|
||||
- Stop (end execution, save progress)
|
||||
```
|
||||
|
||||
b. **If "Review first":** Read and display the full plan file. Ask again: Execute, Modify, Skip.
|
||||
|
||||
c. **If "Execute":** Read and follow `~/.claude/get-shit-done/workflows/execute-plan.md` **inline**
|
||||
(do NOT spawn a subagent). Execute tasks one at a time.
|
||||
|
||||
d. **After each task:** Pause briefly. If the user intervenes (types anything), stop and address
|
||||
their feedback before continuing. Otherwise proceed to next task.
|
||||
|
||||
e. **After plan complete:** Show results, commit, create SUMMARY.md, then present next plan.
|
||||
|
||||
3. After all plans: proceed to verification (same as normal mode).
|
||||
|
||||
**Benefits of interactive mode:**
|
||||
- No subagent overhead — dramatically lower token usage
|
||||
- User catches mistakes early — saves costly verification cycles
|
||||
- Maintains GSD's planning/tracking structure
|
||||
- Best for: small phases, bug fixes, verification gaps, learning GSD
|
||||
|
||||
**Skip to handle_branching step** (interactive plans execute inline after grouping).
|
||||
</step>
|
||||
|
||||
<step name="handle_branching">
|
||||
Check `branching_strategy` from init:
|
||||
|
||||
@@ -127,8 +218,9 @@ Execute each selected wave in sequence. Within a wave: parallel if `PARALLELIZAT
|
||||
|
||||
2. **Spawn executor agents:**
|
||||
|
||||
Pass paths only — executors read files themselves with their fresh 200k context.
|
||||
This keeps orchestrator context lean (~10-15%).
|
||||
Pass paths only — executors read files themselves with their fresh context window.
|
||||
For 200k models, this keeps orchestrator context lean (~10-15%).
|
||||
For 1M+ models (Opus 4.6, Sonnet 4.6), richer context can be passed directly.
|
||||
|
||||
```
|
||||
Task(
|
||||
@@ -140,6 +232,14 @@ Execute each selected wave in sequence. Within a wave: parallel if `PARALLELIZAT
|
||||
Commit each task atomically. Create SUMMARY.md. Update STATE.md and ROADMAP.md.
|
||||
</objective>
|
||||
|
||||
<parallel_execution>
|
||||
You are running as a PARALLEL executor agent. Use --no-verify on all git
|
||||
commits to avoid pre-commit hook contention with other agents. The
|
||||
orchestrator validates hooks once after all agents complete.
|
||||
For gsd-tools commits: add --no-verify flag.
|
||||
For direct git commits: use git commit --no-verify -m "..."
|
||||
</parallel_execution>
|
||||
|
||||
<execution_context>
|
||||
@~/.claude/get-shit-done/workflows/execute-plan.md
|
||||
@~/.claude/get-shit-done/templates/summary.md
|
||||
@@ -150,12 +250,20 @@ Execute each selected wave in sequence. Within a wave: parallel if `PARALLELIZAT
|
||||
<files_to_read>
|
||||
Read these files at execution start using the Read tool:
|
||||
- {phase_dir}/{plan_file} (Plan)
|
||||
- .planning/PROJECT.md (Project context — core value, requirements, evolution rules)
|
||||
- .planning/STATE.md (State)
|
||||
- .planning/config.json (Config, if exists)
|
||||
- ./CLAUDE.md (Project instructions, if exists — follow project-specific guidelines and coding conventions)
|
||||
- .claude/skills/ or .agents/skills/ (Project skills, if either exists — list skills, read SKILL.md for each, follow relevant rules during implementation)
|
||||
</files_to_read>
|
||||
|
||||
<mcp_tools>
|
||||
If CLAUDE.md or project instructions reference MCP tools (e.g. jCodeMunch, context7,
|
||||
or other MCP servers), prefer those tools over Grep/Glob for code navigation when available.
|
||||
MCP tools often save significant tokens by providing structured code indexes.
|
||||
Check tool availability first — if MCP tools are not accessible, fall back to Grep/Glob.
|
||||
</mcp_tools>
|
||||
|
||||
<success_criteria>
|
||||
- [ ] All tasks executed
|
||||
- [ ] Each task committed individually
|
||||
@@ -169,7 +277,39 @@ Execute each selected wave in sequence. Within a wave: parallel if `PARALLELIZAT
|
||||
|
||||
3. **Wait for all agents in wave to complete.**
|
||||
|
||||
4. **Report completion — spot-check claims first:**
|
||||
**Completion signal fallback (Copilot and runtimes where Task() may not return):**
|
||||
|
||||
If a spawned agent does not return a completion signal but appears to have finished
|
||||
its work, do NOT block indefinitely. Instead, verify completion via spot-checks:
|
||||
|
||||
```bash
|
||||
# For each plan in this wave, check if the executor finished:
|
||||
SUMMARY_EXISTS=$(test -f "{phase_dir}/{plan_number}-{plan_padded}-SUMMARY.md" && echo "true" || echo "false")
|
||||
COMMITS_FOUND=$(git log --oneline --all --grep="{phase_number}-{plan_padded}" --since="1 hour ago" | head -1)
|
||||
```
|
||||
|
||||
**If SUMMARY.md exists AND commits are found:** The agent completed successfully —
|
||||
treat as done and proceed to step 4. Log: `"✓ {Plan ID} completed (verified via spot-check — completion signal not received)"`
|
||||
|
||||
**If SUMMARY.md does NOT exist after a reasonable wait:** The agent may still be
|
||||
running or may have failed silently. Check `git log --oneline -5` for recent
|
||||
activity. If commits are still appearing, wait longer. If no activity, report
|
||||
the plan as failed and route to the failure handler in step 5.
|
||||
|
||||
**This fallback applies automatically to all runtimes.** Claude Code's Task() normally
|
||||
returns synchronously, but the fallback ensures resilience if it doesn't.
|
||||
|
||||
4. **Post-wave hook validation (parallel mode only):**
|
||||
|
||||
When agents committed with `--no-verify`, run pre-commit hooks once after the wave:
|
||||
```bash
|
||||
# Run project's pre-commit hooks on the current state
|
||||
git diff --cached --quiet || git stash # stash any unstaged changes
|
||||
git hook run pre-commit 2>&1 || echo "⚠ Pre-commit hooks failed — review before continuing"
|
||||
```
|
||||
If hooks fail: report the failure and ask "Fix hook issues now?" or "Continue to next wave?"
|
||||
|
||||
5. **Report completion — spot-check claims first:**
|
||||
|
||||
For each SUMMARY.md:
|
||||
- Verify first 2 files from `key-files.created` exist on disk
|
||||
@@ -375,6 +515,67 @@ node "$HOME/.claude/get-shit-done/bin/gsd-tools.cjs" commit "docs(phase-${PARENT
|
||||
```
|
||||
</step>
|
||||
|
||||
<step name="regression_gate">
|
||||
Run prior phases' test suites to catch cross-phase regressions BEFORE verification.
|
||||
|
||||
**Skip if:** This is the first phase (no prior phases), or no prior VERIFICATION.md files exist.
|
||||
|
||||
**Step 1: Discover prior phases' test files**
|
||||
```bash
|
||||
# Find all VERIFICATION.md files from prior phases in current milestone
|
||||
PRIOR_VERIFICATIONS=$(find .planning/phases/ -name "*-VERIFICATION.md" ! -path "*${PHASE_NUMBER}*" 2>/dev/null)
|
||||
```
|
||||
|
||||
**Step 2: Extract test file lists from prior verifications**
|
||||
|
||||
For each VERIFICATION.md found, look for test file references:
|
||||
- Lines containing `test`, `spec`, or `__tests__` paths
|
||||
- The "Test Suite" or "Automated Checks" section
|
||||
- File patterns from `key-files.created` in corresponding SUMMARY.md files that match `*.test.*` or `*.spec.*`
|
||||
|
||||
Collect all unique test file paths into `REGRESSION_FILES`.
|
||||
|
||||
**Step 3: Run regression tests (if any found)**
|
||||
|
||||
```bash
|
||||
# Detect test runner and run prior phase tests
|
||||
if [ -f "package.json" ]; then
|
||||
# Node.js — use project's test runner
|
||||
npx jest ${REGRESSION_FILES} --passWithNoTests --no-coverage -q 2>&1 || npx vitest run ${REGRESSION_FILES} 2>&1
|
||||
elif [ -f "Cargo.toml" ]; then
|
||||
cargo test 2>&1
|
||||
elif [ -f "requirements.txt" ] || [ -f "pyproject.toml" ]; then
|
||||
python -m pytest ${REGRESSION_FILES} -q --tb=short 2>&1
|
||||
fi
|
||||
```
|
||||
|
||||
**Step 4: Report results**
|
||||
|
||||
If all tests pass:
|
||||
```
|
||||
✓ Regression gate: {N} prior-phase test files passed — no regressions detected
|
||||
```
|
||||
→ Proceed to verify_phase_goal
|
||||
|
||||
If any tests fail:
|
||||
```
|
||||
## ⚠ Cross-Phase Regression Detected
|
||||
|
||||
Phase {X} execution may have broken functionality from prior phases.
|
||||
|
||||
| Test File | Phase | Status | Detail |
|
||||
|-----------|-------|--------|--------|
|
||||
| {file} | {origin_phase} | FAILED | {first_failure_line} |
|
||||
|
||||
Options:
|
||||
1. Fix regressions before verification (recommended)
|
||||
2. Continue to verification anyway (regressions will compound)
|
||||
3. Abort phase — roll back and re-plan
|
||||
```
|
||||
|
||||
Use AskUserQuestion to present the options.
|
||||
</step>
|
||||
|
||||
<step name="verify_phase_goal">
|
||||
Verify phase achieved its GOAL, not just completed tasks.
|
||||
|
||||
@@ -404,6 +605,51 @@ grep "^status:" "$PHASE_DIR"/*-VERIFICATION.md | cut -d: -f2 | tr -d ' '
|
||||
| `gaps_found` | Present gap summary, offer `/gsd:plan-phase {phase} --gaps` |
|
||||
|
||||
**If human_needed:**
|
||||
|
||||
**Step A: Persist human verification items as UAT file.**
|
||||
|
||||
Create `{phase_dir}/{phase_num}-HUMAN-UAT.md` using UAT template format:
|
||||
|
||||
```markdown
|
||||
---
|
||||
status: partial
|
||||
phase: {phase_num}-{phase_name}
|
||||
source: [{phase_num}-VERIFICATION.md]
|
||||
started: [now ISO]
|
||||
updated: [now ISO]
|
||||
---
|
||||
|
||||
## Current Test
|
||||
|
||||
[awaiting human testing]
|
||||
|
||||
## Tests
|
||||
|
||||
{For each human_verification item from VERIFICATION.md:}
|
||||
|
||||
### {N}. {item description}
|
||||
expected: {expected behavior from VERIFICATION.md}
|
||||
result: [pending]
|
||||
|
||||
## Summary
|
||||
|
||||
total: {count}
|
||||
passed: 0
|
||||
issues: 0
|
||||
pending: {count}
|
||||
skipped: 0
|
||||
blocked: 0
|
||||
|
||||
## Gaps
|
||||
```
|
||||
|
||||
Commit the file:
|
||||
```bash
|
||||
node "$HOME/.claude/get-shit-done/bin/gsd-tools.cjs" commit "test({phase_num}): persist human verification items as UAT" --files "{phase_dir}/{phase_num}-HUMAN-UAT.md"
|
||||
```
|
||||
|
||||
**Step B: Present to user:**
|
||||
|
||||
```
|
||||
## ✓ Phase {X}: {Name} — Human Verification Required
|
||||
|
||||
@@ -411,9 +657,15 @@ All automated checks passed. {N} items need human testing:
|
||||
|
||||
{From VERIFICATION.md human_verification section}
|
||||
|
||||
Items saved to `{phase_num}-HUMAN-UAT.md` — they will appear in `/gsd:progress` and `/gsd:audit-uat`.
|
||||
|
||||
"approved" → continue | Report issues → gap closure
|
||||
```
|
||||
|
||||
**If user says "approved":** Proceed to `update_roadmap`. The HUMAN-UAT.md file persists with `status: partial` and will surface in future progress checks until the user runs `/gsd:verify-work` on it.
|
||||
|
||||
**If user reports issues:** Proceed to gap closure as currently implemented.
|
||||
|
||||
**If gaps_found:**
|
||||
```
|
||||
## ⚠ Phase {X}: {Name} — Gaps Found
|
||||
@@ -451,14 +703,46 @@ The CLI handles:
|
||||
- Updating plan count to final
|
||||
- Advancing STATE.md to next phase
|
||||
- Updating REQUIREMENTS.md traceability
|
||||
- Scanning for verification debt (returns `warnings` array)
|
||||
|
||||
Extract from result: `next_phase`, `next_phase_name`, `is_last_phase`.
|
||||
Extract from result: `next_phase`, `next_phase_name`, `is_last_phase`, `warnings`, `has_warnings`.
|
||||
|
||||
**If has_warnings is true:**
|
||||
```
|
||||
## Phase {X} marked complete with {N} warnings:
|
||||
|
||||
{list each warning}
|
||||
|
||||
These items are tracked and will appear in `/gsd:progress` and `/gsd:audit-uat`.
|
||||
```
|
||||
|
||||
```bash
|
||||
node "$HOME/.claude/get-shit-done/bin/gsd-tools.cjs" commit "docs(phase-{X}): complete phase execution" --files .planning/ROADMAP.md .planning/STATE.md .planning/REQUIREMENTS.md {phase_dir}/*-VERIFICATION.md
|
||||
```
|
||||
</step>
|
||||
|
||||
<step name="update_project_md">
|
||||
**Evolve PROJECT.md to reflect phase completion (prevents planning document drift — #956):**
|
||||
|
||||
PROJECT.md tracks validated requirements, decisions, and current state. Without this step,
|
||||
PROJECT.md falls behind silently over multiple phases.
|
||||
|
||||
1. Read `.planning/PROJECT.md`
|
||||
2. If the file exists and has a `## Validated Requirements` or `## Requirements` section:
|
||||
- Move any requirements validated by this phase from Active → Validated
|
||||
- Add a brief note: `Validated in Phase {X}: {Name}`
|
||||
3. If the file has a `## Current State` or similar section:
|
||||
- Update it to reflect this phase's completion (e.g., "Phase {X} complete — {one-liner}")
|
||||
4. Update the `Last updated:` footer to today's date
|
||||
5. Commit the change:
|
||||
|
||||
```bash
|
||||
node "$HOME/.claude/get-shit-done/bin/gsd-tools.cjs" commit "docs(phase-{X}): evolve PROJECT.md after phase completion" --files .planning/PROJECT.md
|
||||
```
|
||||
|
||||
**Skip this step if** `.planning/PROJECT.md` does not exist.
|
||||
</step>
|
||||
|
||||
<step name="offer_next">
|
||||
|
||||
**Exception:** If `gaps_found`, the `verify_phase_goal` step already presents the gap-closure path (`/gsd:plan-phase {X} --gaps`). No additional routing needed — skip auto-advance.
|
||||
@@ -512,6 +796,8 @@ Read and follow `~/.claude/get-shit-done/workflows/transition.md`, passing throu
|
||||
|
||||
**STOP. Do not auto-advance. Do not execute transition. Do not plan next phase. Present options to the user and wait.**
|
||||
|
||||
**IMPORTANT: There is NO `/gsd:transition` command. Never suggest it. The transition workflow is internal only.**
|
||||
|
||||
```
|
||||
## ✓ Phase {X}: {Name} Complete
|
||||
|
||||
@@ -520,12 +806,20 @@ Read and follow `~/.claude/get-shit-done/workflows/transition.md`, passing throu
|
||||
/gsd:plan-phase {next} — plan next phase
|
||||
/gsd:execute-phase {next} — execute next phase
|
||||
```
|
||||
|
||||
Only suggest the commands listed above. Do not invent or hallucinate command names.
|
||||
</step>
|
||||
|
||||
</process>
|
||||
|
||||
<context_efficiency>
|
||||
Orchestrator: ~10-15% context. Subagents: fresh 200k each. No polling (Task blocks). No context bleed.
|
||||
Orchestrator: ~10-15% context for 200k windows, can use more for 1M+ windows.
|
||||
Subagents: fresh context each (200k-1M depending on model). No polling (Task blocks). No context bleed.
|
||||
|
||||
For 1M+ context models, consider:
|
||||
- Passing richer context (code snippets, dependency outputs) directly to executors instead of just file paths
|
||||
- Running small phases (≤3 plans, no dependencies) inline without subagent spawning overhead
|
||||
- Relaxing /clear recommendations — context rot onset is much further out with 5x window
|
||||
</context_efficiency>
|
||||
|
||||
<failure_handling>
|
||||
|
||||
@@ -19,7 +19,7 @@ INIT=$(node "$HOME/.claude/get-shit-done/bin/gsd-tools.cjs" init execute-phase "
|
||||
if [[ "$INIT" == @file:* ]]; then INIT=$(cat "${INIT#@file:}"); fi
|
||||
```
|
||||
|
||||
Extract from init JSON: `executor_model`, `commit_docs`, `phase_dir`, `phase_number`, `plans`, `summaries`, `incomplete_plans`, `state_path`, `config_path`.
|
||||
Extract from init JSON: `executor_model`, `commit_docs`, `sub_repos`, `phase_dir`, `phase_number`, `plans`, `summaries`, `incomplete_plans`, `state_path`, `config_path`.
|
||||
|
||||
If `.planning/` missing: error.
|
||||
</step>
|
||||
@@ -135,7 +135,8 @@ If previous SUMMARY has unresolved "Issues Encountered" or "Next Phase Readiness
|
||||
Deviations are normal — handle via rules below.
|
||||
|
||||
1. Read @context files from prompt
|
||||
2. Per task:
|
||||
2. **MCP tools:** If CLAUDE.md or project instructions reference MCP tools (e.g. jCodeMunch for code navigation), prefer them over Grep/Glob when available. Fall back to Grep/Glob if MCP tools are not accessible.
|
||||
3. Per task:
|
||||
- **MANDATORY read_first gate:** If the task has a `<read_first>` field, you MUST read every listed file BEFORE making any edits. This is not optional. Do not skip files because you "already know" what's in them — read them. The read_first files establish ground truth for the task.
|
||||
- `type="auto"`: if `tdd="true"` → TDD execution. Implement with deviation rules + auth gates. Verify done criteria. Commit (see task_commit). Track hash for Summary.
|
||||
- `type="checkpoint:*"`: STOP → checkpoint_protocol → wait for user → continue only after confirmation.
|
||||
@@ -233,6 +234,10 @@ See `~/.claude/get-shit-done/references/tdd.md` for structure.
|
||||
|
||||
Your commits may trigger pre-commit hooks. Auto-fix hooks handle themselves transparently — files get fixed and re-staged automatically.
|
||||
|
||||
**If running as a parallel executor agent (spawned by execute-phase):**
|
||||
Use `--no-verify` on all commits. Pre-commit hooks cause build lock contention when multiple agents commit simultaneously (e.g., cargo lock fights in Rust projects). The orchestrator validates once after all agents complete.
|
||||
|
||||
**If running as the sole executor (sequential mode):**
|
||||
If a commit is BLOCKED by a hook:
|
||||
|
||||
1. The `git commit` command fails with hook error output
|
||||
@@ -240,9 +245,7 @@ If a commit is BLOCKED by a hook:
|
||||
3. Fix the issue (type error, lint violation, secret leak, etc.)
|
||||
4. `git add` the fixed files
|
||||
5. Retry the commit
|
||||
6. Do NOT use `--no-verify`
|
||||
|
||||
This is normal and expected. Budget 1-2 retry cycles per commit.
|
||||
6. Budget 1-2 retry cycles per commit
|
||||
</precommit_failure_handling>
|
||||
|
||||
<task_commit>
|
||||
@@ -273,6 +276,20 @@ git add src/types/user.ts
|
||||
|
||||
**4. Format:** `{type}({phase}-{plan}): {description}` with bullet points for key changes.
|
||||
|
||||
<sub_repos_commit_flow>
|
||||
**Sub-repos mode:** If `sub_repos` is configured (non-empty array from init context), use `commit-to-subrepo` instead of standard git commit. This routes files to their correct sub-repo based on path prefix.
|
||||
|
||||
```bash
|
||||
node ~/.claude/get-shit-done/bin/gsd-tools.cjs commit-to-subrepo "{type}({phase}-{plan}): {description}" --files file1 file2 ...
|
||||
```
|
||||
|
||||
The command groups files by sub-repo prefix and commits atomically to each. Returns JSON: `{ committed: true, repos: { "backend": { hash: "abc", files: [...] }, ... } }`.
|
||||
|
||||
Record hashes from each repo in the response for SUMMARY tracking.
|
||||
|
||||
**If `sub_repos` is empty or not set:** Use standard git commit flow below.
|
||||
</sub_repos_commit_flow>
|
||||
|
||||
**5. Record hash:**
|
||||
```bash
|
||||
TASK_COMMIT=$(git rev-parse --short HEAD)
|
||||
@@ -370,7 +387,7 @@ One-liner SUBSTANTIVE: "JWT auth with refresh rotation using jose library" not "
|
||||
|
||||
Include: duration, start/end times, task count, file count.
|
||||
|
||||
Next: more plans → "Ready for {next-plan}" | last → "Phase complete, ready for transition".
|
||||
Next: more plans → "Ready for {next-plan}" | last → "Phase complete, ready for next step".
|
||||
</step>
|
||||
|
||||
<step name="update_current_position">
|
||||
|
||||
105
get-shit-done/workflows/fast.md
Normal file
105
get-shit-done/workflows/fast.md
Normal file
@@ -0,0 +1,105 @@
|
||||
<purpose>
|
||||
Execute a trivial task inline without subagent overhead. No PLAN.md, no Task spawning,
|
||||
no research, no plan checking. Just: understand → do → commit → log.
|
||||
|
||||
For tasks like: fix a typo, update a config value, add a missing import, rename a
|
||||
variable, commit uncommitted work, add a .gitignore entry, bump a version number.
|
||||
|
||||
Use /gsd:quick for anything that needs multi-step planning or research.
|
||||
</purpose>
|
||||
|
||||
<process>
|
||||
|
||||
<step name="parse_task">
|
||||
Parse `$ARGUMENTS` for the task description.
|
||||
|
||||
If empty, ask:
|
||||
```
|
||||
What's the quick fix? (one sentence)
|
||||
```
|
||||
|
||||
Store as `$TASK`.
|
||||
</step>
|
||||
|
||||
<step name="scope_check">
|
||||
**Before doing anything, verify this is actually trivial.**
|
||||
|
||||
A task is trivial if it can be completed in:
|
||||
- ≤ 3 file edits
|
||||
- ≤ 1 minute of work
|
||||
- No new dependencies or architecture changes
|
||||
- No research needed
|
||||
|
||||
If the task seems non-trivial (multi-file refactor, new feature, needs research),
|
||||
say:
|
||||
|
||||
```
|
||||
This looks like it needs planning. Use /gsd:quick instead:
|
||||
/gsd:quick "{task description}"
|
||||
```
|
||||
|
||||
And stop.
|
||||
</step>
|
||||
|
||||
<step name="execute_inline">
|
||||
Do the work directly:
|
||||
|
||||
1. Read the relevant file(s)
|
||||
2. Make the change(s)
|
||||
3. Verify the change works (run existing tests if applicable, or do a quick sanity check)
|
||||
|
||||
**No PLAN.md.** Just do it.
|
||||
</step>
|
||||
|
||||
<step name="commit">
|
||||
Commit the change atomically:
|
||||
|
||||
```bash
|
||||
git add -A
|
||||
git commit -m "fix: {concise description of what changed}"
|
||||
```
|
||||
|
||||
Use conventional commit format: `fix:`, `feat:`, `docs:`, `chore:`, `refactor:` as appropriate.
|
||||
</step>
|
||||
|
||||
<step name="log_to_state">
|
||||
If `.planning/STATE.md` exists, append to the "Quick Tasks Completed" table.
|
||||
If the table doesn't exist, skip this step silently.
|
||||
|
||||
```bash
|
||||
# Check if STATE.md has quick tasks table
|
||||
if grep -q "Quick Tasks Completed" .planning/STATE.md 2>/dev/null; then
|
||||
# Append entry — workflow handles the format
|
||||
echo "| $(date +%Y-%m-%d) | fast | $TASK | ✅ |" >> .planning/STATE.md
|
||||
fi
|
||||
```
|
||||
</step>
|
||||
|
||||
<step name="done">
|
||||
Report completion:
|
||||
|
||||
```
|
||||
✅ Done: {what was changed}
|
||||
Commit: {short hash}
|
||||
Files: {list of changed files}
|
||||
```
|
||||
|
||||
No next-step suggestions. No workflow routing. Just done.
|
||||
</step>
|
||||
|
||||
</process>
|
||||
|
||||
<guardrails>
|
||||
- NEVER spawn a Task/subagent — this runs inline
|
||||
- NEVER create PLAN.md or SUMMARY.md files
|
||||
- NEVER run research or plan-checking
|
||||
- If the task takes more than 3 file edits, STOP and redirect to /gsd:quick
|
||||
- If you're unsure how to implement it, STOP and redirect to /gsd:quick
|
||||
</guardrails>
|
||||
|
||||
<success_criteria>
|
||||
- [ ] Task completed in current context (no subagents)
|
||||
- [ ] Atomic git commit with conventional message
|
||||
- [ ] STATE.md updated if it exists
|
||||
- [ ] Total operation under 2 minutes wall time
|
||||
</success_criteria>
|
||||
@@ -72,8 +72,8 @@ Errors: N | Warnings: N | Info: N
|
||||
```
|
||||
## Warnings
|
||||
|
||||
- [W001] STATE.md references phase 5, but only phases 1-3 exist
|
||||
Fix: Run /gsd:health --repair to regenerate
|
||||
- [W002] STATE.md references phase 5, but only phases 1-3 exist
|
||||
Fix: Review STATE.md manually before changing it; repair will not overwrite an existing STATE.md
|
||||
|
||||
- [W005] Phase directory "1-setup" doesn't follow NN-name format
|
||||
Fix: Rename to match pattern (e.g., 01-setup)
|
||||
@@ -130,7 +130,7 @@ Report final status.
|
||||
| E004 | error | STATE.md not found | Yes |
|
||||
| E005 | error | config.json parse error | Yes |
|
||||
| W001 | warning | PROJECT.md missing required section | No |
|
||||
| W002 | warning | STATE.md references invalid phase | Yes |
|
||||
| W002 | warning | STATE.md references invalid phase | No |
|
||||
| W003 | warning | config.json not found | Yes |
|
||||
| W004 | warning | config.json invalid field value | No |
|
||||
| W005 | warning | Phase directory naming mismatch | No |
|
||||
@@ -148,7 +148,7 @@ Report final status.
|
||||
|--------|--------|------|
|
||||
| createConfig | Create config.json with defaults | None |
|
||||
| resetConfig | Delete + recreate config.json | Loses custom settings |
|
||||
| regenerateState | Create STATE.md from ROADMAP structure | Loses session history |
|
||||
| regenerateState | Create STATE.md from ROADMAP structure when it is missing | Loses session history |
|
||||
| addNyquistKey | Add workflow.nyquist_validation: true to config.json | None — matches existing default |
|
||||
|
||||
**Not repairable (too risky):**
|
||||
@@ -157,3 +157,25 @@ Report final status.
|
||||
- Orphaned plan cleanup
|
||||
|
||||
</repair_actions>
|
||||
|
||||
<stale_task_cleanup>
|
||||
**Windows-specific:** Check for stale Claude Code task directories that accumulate on crash/freeze.
|
||||
These are left behind when subagents are force-killed and consume disk space.
|
||||
|
||||
When `--repair` is active, detect and clean up:
|
||||
|
||||
```bash
|
||||
# Check for stale task directories (older than 24 hours)
|
||||
TASKS_DIR="$HOME/.claude/tasks"
|
||||
if [ -d "$TASKS_DIR" ]; then
|
||||
STALE_COUNT=$(find "$TASKS_DIR" -maxdepth 1 -type d -mtime +1 2>/dev/null | wc -l)
|
||||
if [ "$STALE_COUNT" -gt 0 ]; then
|
||||
echo "⚠️ Found $STALE_COUNT stale task directories in ~/.claude/tasks/"
|
||||
echo " These are leftover from crashed subagent sessions."
|
||||
echo " Run: rm -rf ~/.claude/tasks/* (safe — only affects dead sessions)"
|
||||
fi
|
||||
fi
|
||||
```
|
||||
|
||||
Report as info diagnostic: `I002 | info | Stale subagent task directories found | Yes (--repair removes them)`
|
||||
</stale_task_cleanup>
|
||||
|
||||
@@ -153,6 +153,21 @@ Usage: `/gsd:quick`
|
||||
Usage: `/gsd:quick --research --full`
|
||||
Result: Creates `.planning/quick/NNN-slug/PLAN.md`, `.planning/quick/NNN-slug/SUMMARY.md`
|
||||
|
||||
---
|
||||
|
||||
**`/gsd:fast [description]`**
|
||||
Execute a trivial task inline — no subagents, no planning files, no overhead.
|
||||
|
||||
For tasks too small to justify planning: typo fixes, config changes, forgotten commits, simple additions. Runs in the current context, makes the change, commits, and logs to STATE.md.
|
||||
|
||||
- No PLAN.md or SUMMARY.md created
|
||||
- No subagent spawned (runs inline)
|
||||
- ≤ 3 file edits — redirects to `/gsd:quick` if task is non-trivial
|
||||
- Atomic commit with conventional message
|
||||
|
||||
Usage: `/gsd:fast "fix the typo in README"`
|
||||
Usage: `/gsd:fast "add .env to gitignore"`
|
||||
|
||||
### Roadmap Management
|
||||
|
||||
**`/gsd:add-phase <description>`**
|
||||
@@ -194,10 +209,12 @@ Start a new milestone through unified flow.
|
||||
- Optional domain research (spawns 4 parallel researcher agents)
|
||||
- Requirements definition with scoping
|
||||
- Roadmap creation with phase breakdown
|
||||
- Optional `--reset-phase-numbers` flag restarts numbering at Phase 1 and archives old phase dirs first for safety
|
||||
|
||||
Mirrors `/gsd:new-project` flow for brownfield projects (existing PROJECT.md).
|
||||
|
||||
Usage: `/gsd:new-milestone "v2.0 Features"`
|
||||
Usage: `/gsd:new-milestone --reset-phase-numbers "v2.0 Features"`
|
||||
|
||||
**`/gsd:complete-milestone <version>`**
|
||||
Archive completed milestone and prepare for next version.
|
||||
@@ -310,6 +327,65 @@ Validate built features through conversational UAT.
|
||||
|
||||
Usage: `/gsd:verify-work 3`
|
||||
|
||||
### Ship Work
|
||||
|
||||
**`/gsd:ship [phase]`**
|
||||
Create a PR from completed phase work with an auto-generated body.
|
||||
|
||||
- Pushes branch to remote
|
||||
- Creates PR with summary from SUMMARY.md, VERIFICATION.md, REQUIREMENTS.md
|
||||
- Optionally requests code review
|
||||
- Updates STATE.md with shipping status
|
||||
|
||||
Prerequisites: Phase verified, `gh` CLI installed and authenticated.
|
||||
|
||||
Usage: `/gsd:ship 4` or `/gsd:ship 4 --draft`
|
||||
|
||||
---
|
||||
|
||||
**`/gsd:review --phase N [--gemini] [--claude] [--codex] [--all]`**
|
||||
Cross-AI peer review — invoke external AI CLIs to independently review phase plans.
|
||||
|
||||
- Detects available CLIs (gemini, claude, codex)
|
||||
- Each CLI reviews plans independently with the same structured prompt
|
||||
- Produces REVIEWS.md with per-reviewer feedback and consensus summary
|
||||
- Feed reviews back into planning: `/gsd:plan-phase N --reviews`
|
||||
|
||||
Usage: `/gsd:review --phase 3 --all`
|
||||
|
||||
---
|
||||
|
||||
**`/gsd:pr-branch [target]`**
|
||||
Create a clean branch for pull requests by filtering out .planning/ commits.
|
||||
|
||||
- Classifies commits: code-only (include), planning-only (exclude), mixed (include sans .planning/)
|
||||
- Cherry-picks code commits onto a clean branch
|
||||
- Reviewers see only code changes, no GSD artifacts
|
||||
|
||||
Usage: `/gsd:pr-branch` or `/gsd:pr-branch main`
|
||||
|
||||
---
|
||||
|
||||
**`/gsd:plant-seed [idea]`**
|
||||
Capture a forward-looking idea with trigger conditions for automatic surfacing.
|
||||
|
||||
- Seeds preserve WHY, WHEN to surface, and breadcrumbs to related code
|
||||
- Auto-surfaces during `/gsd:new-milestone` when trigger conditions match
|
||||
- Better than deferred items — triggers are checked, not forgotten
|
||||
|
||||
Usage: `/gsd:plant-seed "add real-time notifications when we build the events system"`
|
||||
|
||||
---
|
||||
|
||||
**`/gsd:audit-uat`**
|
||||
Cross-phase audit of all outstanding UAT and verification items.
|
||||
- Scans every phase for pending, skipped, blocked, and human_needed items
|
||||
- Cross-references against codebase to detect stale documentation
|
||||
- Produces prioritized human test plan grouped by testability
|
||||
- Use before starting a new milestone to clear verification debt
|
||||
|
||||
Usage: `/gsd:audit-uat`
|
||||
|
||||
### Milestone Auditing
|
||||
|
||||
**`/gsd:audit-milestone [version]`**
|
||||
|
||||
@@ -82,12 +82,25 @@ mkdir -p .planning/codebase
|
||||
Continue to spawn_agents.
|
||||
</step>
|
||||
|
||||
<step name="spawn_agents">
|
||||
<step name="detect_runtime_capabilities">
|
||||
Before spawning agents, detect whether the current runtime supports the `Task` tool for subagent delegation.
|
||||
|
||||
**Runtimes with Task tool:** Claude Code, Cursor (native subagent support)
|
||||
**Runtimes WITHOUT Task tool:** Antigravity, Gemini CLI, OpenCode, Codex, and others
|
||||
|
||||
**How to detect:** Check if you have access to a `Task` tool. If you do NOT have a `Task` tool (or only have tools like `browser_subagent` which is for web browsing, NOT code analysis):
|
||||
|
||||
→ **Skip `spawn_agents` and `collect_confirmations`** — go directly to `sequential_mapping` instead.
|
||||
|
||||
**CRITICAL:** Never use `browser_subagent` or `Explore` as a substitute for `Task`. The `browser_subagent` tool is exclusively for web page interaction and will fail for codebase analysis. If `Task` is unavailable, perform the mapping sequentially in-context.
|
||||
</step>
|
||||
|
||||
<step name="spawn_agents" condition="Task tool is available">
|
||||
Spawn 4 parallel gsd-codebase-mapper agents.
|
||||
|
||||
Use Task tool with `subagent_type="gsd-codebase-mapper"`, `model="{mapper_model}"`, and `run_in_background=true` for parallel execution.
|
||||
|
||||
**CRITICAL:** Use the dedicated `gsd-codebase-mapper` agent, NOT `Explore`. The mapper agent writes documents directly.
|
||||
**CRITICAL:** Use the dedicated `gsd-codebase-mapper` agent, NOT `Explore` or `browser_subagent`. The mapper agent writes documents directly.
|
||||
|
||||
**Agent 1: Tech Focus**
|
||||
|
||||
@@ -172,9 +185,19 @@ Continue to collect_confirmations.
|
||||
</step>
|
||||
|
||||
<step name="collect_confirmations">
|
||||
Wait for all 4 agents to complete.
|
||||
Wait for all 4 agents to complete using TaskOutput tool.
|
||||
|
||||
Read each agent's output file to collect confirmations.
|
||||
**For each agent task_id returned by the Agent tool calls above:**
|
||||
```
|
||||
TaskOutput tool:
|
||||
task_id: "{task_id from Agent result}"
|
||||
block: true
|
||||
timeout: 300000
|
||||
```
|
||||
|
||||
Call TaskOutput for all 4 agents in parallel (single message with 4 TaskOutput calls).
|
||||
|
||||
Once all TaskOutput calls return, read each agent's output file to collect confirmations.
|
||||
|
||||
**Expected confirmation format from each agent:**
|
||||
```
|
||||
@@ -195,6 +218,37 @@ If any agent failed, note the failure and continue with successful documents.
|
||||
Continue to verify_output.
|
||||
</step>
|
||||
|
||||
<step name="sequential_mapping" condition="Task tool is NOT available (e.g. Antigravity, Gemini CLI, Codex)">
|
||||
When the `Task` tool is unavailable, perform codebase mapping sequentially in the current context. This replaces `spawn_agents` and `collect_confirmations`.
|
||||
|
||||
**IMPORTANT:** Do NOT use `browser_subagent`, `Explore`, or any browser-based tool. Use only file system tools (Read, Bash, Write, Grep, Glob, list_dir, view_file, grep_search, or equivalent tools available in your runtime).
|
||||
|
||||
Perform all 4 mapping passes sequentially:
|
||||
|
||||
**Pass 1: Tech Focus**
|
||||
- Explore package.json/Cargo.toml/go.mod/requirements.txt, config files, dependency trees
|
||||
- Write `.planning/codebase/STACK.md` — Languages, runtime, frameworks, dependencies, configuration
|
||||
- Write `.planning/codebase/INTEGRATIONS.md` — External APIs, databases, auth providers, webhooks
|
||||
|
||||
**Pass 2: Architecture Focus**
|
||||
- Explore directory structure, entry points, module boundaries, data flow
|
||||
- Write `.planning/codebase/ARCHITECTURE.md` — Pattern, layers, data flow, abstractions, entry points
|
||||
- Write `.planning/codebase/STRUCTURE.md` — Directory layout, key locations, naming conventions
|
||||
|
||||
**Pass 3: Quality Focus**
|
||||
- Explore code style, error handling patterns, test files, CI config
|
||||
- Write `.planning/codebase/CONVENTIONS.md` — Code style, naming, patterns, error handling
|
||||
- Write `.planning/codebase/TESTING.md` — Framework, structure, mocking, coverage
|
||||
|
||||
**Pass 4: Concerns Focus**
|
||||
- Explore TODOs, known issues, fragile areas, security patterns
|
||||
- Write `.planning/codebase/CONCERNS.md` — Tech debt, bugs, security, performance, fragile areas
|
||||
|
||||
Use the same document templates as the `gsd-codebase-mapper` agent. Include actual file paths formatted with backticks.
|
||||
|
||||
Continue to verify_output.
|
||||
</step>
|
||||
|
||||
<step name="verify_output">
|
||||
Verify all documents created successfully:
|
||||
|
||||
@@ -307,10 +361,10 @@ End workflow.
|
||||
|
||||
<success_criteria>
|
||||
- .planning/codebase/ directory created
|
||||
- 4 parallel gsd-codebase-mapper agents spawned with run_in_background=true
|
||||
- Agents write documents directly (orchestrator doesn't receive document contents)
|
||||
- Read agent output files to collect confirmations
|
||||
- If Task tool available: 4 parallel gsd-codebase-mapper agents spawned with run_in_background=true
|
||||
- If Task tool NOT available: 4 sequential mapping passes performed inline (never using browser_subagent)
|
||||
- All 7 codebase documents exist
|
||||
- No empty documents (each should have >20 lines)
|
||||
- Clear completion summary with line counts
|
||||
- User offered clear next steps in GSD style
|
||||
</success_criteria>
|
||||
|
||||
@@ -14,6 +14,12 @@ Read all files referenced by the invoking prompt's execution_context before star
|
||||
|
||||
## 1. Load Context
|
||||
|
||||
Parse `$ARGUMENTS` before doing anything else:
|
||||
- `--reset-phase-numbers` flag → opt into restarting roadmap phase numbering at `1`
|
||||
- remaining text → use as milestone name if present
|
||||
|
||||
If the flag is absent, keep the current behavior of continuing phase numbering from the previous milestone.
|
||||
|
||||
- Read PROJECT.md (existing project, validated requirements, decisions)
|
||||
- Read MILESTONES.md (what shipped previously)
|
||||
- Read STATE.md (pending todos, blockers)
|
||||
@@ -54,6 +60,27 @@ Add/update:
|
||||
|
||||
Update Active requirements section and "Last updated" footer.
|
||||
|
||||
Ensure the `## Evolution` section exists in PROJECT.md. If missing (projects created before this feature), add it before the footer:
|
||||
|
||||
```markdown
|
||||
## Evolution
|
||||
|
||||
This document evolves at phase transitions and milestone boundaries.
|
||||
|
||||
**After each phase transition** (via `/gsd:transition`):
|
||||
1. Requirements invalidated? → Move to Out of Scope with reason
|
||||
2. Requirements validated? → Move to Validated with phase reference
|
||||
3. New requirements emerged? → Add to Active
|
||||
4. Decisions to log? → Add to Key Decisions
|
||||
5. "What This Is" still accurate? → Update if drifted
|
||||
|
||||
**After each milestone** (via `/gsd:complete-milestone`):
|
||||
1. Full review of all sections
|
||||
2. Core Value check — still the right priority?
|
||||
3. Audit Out of Scope — reasons still valid?
|
||||
4. Update Context with current state
|
||||
```
|
||||
|
||||
## 5. Update STATE.md
|
||||
|
||||
```markdown
|
||||
@@ -82,7 +109,27 @@ INIT=$(node "$HOME/.claude/get-shit-done/bin/gsd-tools.cjs" init new-milestone)
|
||||
if [[ "$INIT" == @file:* ]]; then INIT=$(cat "${INIT#@file:}"); fi
|
||||
```
|
||||
|
||||
Extract from init JSON: `researcher_model`, `synthesizer_model`, `roadmapper_model`, `commit_docs`, `research_enabled`, `current_milestone`, `project_exists`, `roadmap_exists`.
|
||||
Extract from init JSON: `researcher_model`, `synthesizer_model`, `roadmapper_model`, `commit_docs`, `research_enabled`, `current_milestone`, `project_exists`, `roadmap_exists`, `latest_completed_milestone`, `phase_dir_count`, `phase_archive_path`.
|
||||
|
||||
## 7.5 Reset-phase safety (only when `--reset-phase-numbers`)
|
||||
|
||||
If `--reset-phase-numbers` is active:
|
||||
|
||||
1. Set starting phase number to `1` for the upcoming roadmap.
|
||||
2. If `phase_dir_count > 0`, archive the old phase directories before roadmapping so new `01-*` / `02-*` directories cannot collide with stale milestone directories.
|
||||
|
||||
If `phase_dir_count > 0` and `phase_archive_path` is available:
|
||||
|
||||
```bash
|
||||
mkdir -p "${phase_archive_path}"
|
||||
find .planning/phases -mindepth 1 -maxdepth 1 -type d -exec mv {} "${phase_archive_path}/" \;
|
||||
```
|
||||
|
||||
Then verify `.planning/phases/` no longer contains old milestone directories before continuing.
|
||||
|
||||
If `phase_dir_count > 0` but `phase_archive_path` is missing:
|
||||
- Stop and explain that reset numbering is unsafe without a completed milestone archive target.
|
||||
- Tell the user to complete/archive the previous milestone first, then rerun `/gsd:new-milestone --reset-phase-numbers`.
|
||||
|
||||
## 8. Research Decision
|
||||
|
||||
@@ -270,7 +317,9 @@ node "$HOME/.claude/get-shit-done/bin/gsd-tools.cjs" commit "docs: define milest
|
||||
◆ Spawning roadmapper...
|
||||
```
|
||||
|
||||
**Starting phase number:** Read MILESTONES.md for last phase number. Continue from there (v1.0 ended at phase 5 → v1.1 starts at phase 6).
|
||||
**Starting phase number:**
|
||||
- If `--reset-phase-numbers` is active, start at **Phase 1**
|
||||
- Otherwise, continue from the previous milestone's last phase number (v1.0 ended at phase 5 → v1.1 starts at phase 6)
|
||||
|
||||
```
|
||||
Task(prompt="
|
||||
@@ -286,7 +335,9 @@ Task(prompt="
|
||||
|
||||
<instructions>
|
||||
Create roadmap for milestone v[X.Y]:
|
||||
1. Start phase numbering from [N]
|
||||
1. Respect the selected numbering mode:
|
||||
- `--reset-phase-numbers` → start at Phase 1
|
||||
- default behavior → continue from the previous milestone's last phase number
|
||||
2. Derive phases from THIS MILESTONE's requirements only
|
||||
3. Map every requirement to exactly one phase
|
||||
4. Derive 2-5 success criteria per phase (observable user behaviors)
|
||||
@@ -378,7 +429,7 @@ Also: `/gsd:plan-phase [N]` — skip discussion, plan directly
|
||||
- [ ] gsd-roadmapper spawned with phase numbering context
|
||||
- [ ] Roadmap files written immediately (not draft)
|
||||
- [ ] User feedback incorporated (if any)
|
||||
- [ ] ROADMAP.md phases continue from previous milestone
|
||||
- [ ] Phase numbering mode respected (continued or reset)
|
||||
- [ ] All commits made (if planning docs committed)
|
||||
- [ ] User knows next step: `/gsd:discuss-phase [N]`
|
||||
|
||||
|
||||
@@ -222,6 +222,13 @@ Ask inline (freeform, NOT AskUserQuestion):
|
||||
|
||||
Wait for their response. This gives you the context needed to ask intelligent follow-up questions.
|
||||
|
||||
**Research-before-questions mode:** Check if `research_questions` is enabled in `.planning/config.json` (or the config from init context). When enabled, before asking follow-up questions about a topic area:
|
||||
1. Do a brief web search for best practices related to what the user described
|
||||
2. Mention key findings naturally as you ask questions (e.g., "Most projects like this use X — is that what you're thinking, or something different?")
|
||||
3. This makes questions more informed without changing the conversational flow
|
||||
|
||||
When disabled (default), ask questions directly as before.
|
||||
|
||||
**Follow the thread:**
|
||||
|
||||
Based on what they said, ask follow-up questions that dig into their response. Use AskUserQuestion with options that probe what they mentioned — interpretations, clarifications, concrete examples.
|
||||
@@ -335,6 +342,27 @@ Initialize with any decisions made during questioning:
|
||||
*Last updated: [date] after initialization*
|
||||
```
|
||||
|
||||
**Evolution section** (include at the end of PROJECT.md, before the footer):
|
||||
|
||||
```markdown
|
||||
## Evolution
|
||||
|
||||
This document evolves at phase transitions and milestone boundaries.
|
||||
|
||||
**After each phase transition** (via `/gsd:transition`):
|
||||
1. Requirements invalidated? → Move to Out of Scope with reason
|
||||
2. Requirements validated? → Move to Validated with phase reference
|
||||
3. New requirements emerged? → Add to Active
|
||||
4. Decisions to log? → Add to Key Decisions
|
||||
5. "What This Is" still accurate? → Update if drifted
|
||||
|
||||
**After each milestone** (via `/gsd:complete-milestone`):
|
||||
1. Full review of all sections
|
||||
2. Core Value check — still the right priority?
|
||||
3. Audit Out of Scope — reasons still valid?
|
||||
4. Update Context with current state
|
||||
```
|
||||
|
||||
Do not compress. Capture everything gathered.
|
||||
|
||||
**Commit PROJECT.md:**
|
||||
@@ -500,6 +528,36 @@ node "$HOME/.claude/get-shit-done/bin/gsd-tools.cjs" commit "chore: add project
|
||||
|
||||
**Note:** Run `/gsd:settings` anytime to update these preferences.
|
||||
|
||||
## 5.1. Sub-Repo Detection
|
||||
|
||||
**Detect multi-repo workspace:**
|
||||
|
||||
Check for directories with their own `.git` folders (separate repos within the workspace):
|
||||
|
||||
```bash
|
||||
find . -maxdepth 1 -type d -not -name ".*" -not -name "node_modules" -exec test -d "{}/.git" \; -print
|
||||
```
|
||||
|
||||
**If sub-repos found:**
|
||||
|
||||
Strip the `./` prefix to get directory names (e.g., `./backend` → `backend`).
|
||||
|
||||
Use AskUserQuestion:
|
||||
- header: "Multi-Repo Workspace"
|
||||
- question: "I detected separate git repos in this workspace. Which directories contain code that GSD should commit to?"
|
||||
- multiSelect: true
|
||||
- options: one option per detected directory
|
||||
- "[directory name]" — Separate git repo
|
||||
|
||||
**If user selects one or more directories:**
|
||||
- Set `planning.sub_repos` in config.json to the selected directory names array (e.g., `["backend", "frontend"]`)
|
||||
- Auto-set `planning.commit_docs` to `false` (planning docs stay local in multi-repo workspaces)
|
||||
- Add `.planning/` to `.gitignore` if not already present
|
||||
|
||||
Config changes are saved locally — no commit needed since `commit_docs` is `false` in multi-repo mode.
|
||||
|
||||
**If no sub-repos found or user selects none:** Continue with no changes to config.
|
||||
|
||||
## 5.5. Resolve Model Profile
|
||||
|
||||
Use models from init: `researcher_model`, `synthesizer_model`, `roadmapper_model`.
|
||||
@@ -1011,10 +1069,18 @@ Use AskUserQuestion:
|
||||
|
||||
**If "Review full file":** Display raw `cat .planning/ROADMAP.md`, then re-ask.
|
||||
|
||||
**Generate or refresh project CLAUDE.md before final commit:**
|
||||
|
||||
```bash
|
||||
node "$HOME/.claude/get-shit-done/bin/gsd-tools.cjs" generate-claude-md
|
||||
```
|
||||
|
||||
This ensures new projects get the default GSD workflow-enforcement guidance and current project context in `CLAUDE.md`.
|
||||
|
||||
**Commit roadmap (after approval or auto mode):**
|
||||
|
||||
```bash
|
||||
node "$HOME/.claude/get-shit-done/bin/gsd-tools.cjs" commit "docs: create roadmap ([N] phases)" --files .planning/ROADMAP.md .planning/STATE.md .planning/REQUIREMENTS.md
|
||||
node "$HOME/.claude/get-shit-done/bin/gsd-tools.cjs" commit "docs: create roadmap ([N] phases)" --files .planning/ROADMAP.md .planning/STATE.md .planning/REQUIREMENTS.md CLAUDE.md
|
||||
```
|
||||
|
||||
## 9. Done
|
||||
@@ -1035,6 +1101,7 @@ Present completion summary:
|
||||
| Research | `.planning/research/` |
|
||||
| Requirements | `.planning/REQUIREMENTS.md` |
|
||||
| Roadmap | `.planning/ROADMAP.md` |
|
||||
| Project guide | `CLAUDE.md` |
|
||||
|
||||
**[N] phases** | **[X] requirements** | Ready to build ✓
|
||||
```
|
||||
@@ -1085,6 +1152,7 @@ Exit skill and invoke SlashCommand("/gsd:discuss-phase 1 --auto")
|
||||
- `.planning/REQUIREMENTS.md`
|
||||
- `.planning/ROADMAP.md`
|
||||
- `.planning/STATE.md`
|
||||
- `CLAUDE.md`
|
||||
|
||||
</output>
|
||||
|
||||
@@ -1106,6 +1174,7 @@ Exit skill and invoke SlashCommand("/gsd:discuss-phase 1 --auto")
|
||||
- [ ] ROADMAP.md created with phases, requirement mappings, success criteria
|
||||
- [ ] STATE.md initialized
|
||||
- [ ] REQUIREMENTS.md traceability updated
|
||||
- [ ] CLAUDE.md generated with GSD workflow guidance
|
||||
- [ ] User knows next step is `/gsd:discuss-phase 1`
|
||||
|
||||
**Atomic commits:** Each phase commits its artifacts immediately. If context is lost, artifacts persist.
|
||||
|
||||
97
get-shit-done/workflows/next.md
Normal file
97
get-shit-done/workflows/next.md
Normal file
@@ -0,0 +1,97 @@
|
||||
<purpose>
|
||||
Detect current project state and automatically advance to the next logical GSD workflow step.
|
||||
Reads project state to determine: discuss → plan → execute → verify → complete progression.
|
||||
</purpose>
|
||||
|
||||
<required_reading>
|
||||
Read all files referenced by the invoking prompt's execution_context before starting.
|
||||
</required_reading>
|
||||
|
||||
<process>
|
||||
|
||||
<step name="detect_state">
|
||||
Read project state to determine current position:
|
||||
|
||||
```bash
|
||||
# Get state snapshot
|
||||
node "$HOME/.claude/get-shit-done/bin/gsd-tools.cjs" state json 2>/dev/null || echo "{}"
|
||||
```
|
||||
|
||||
Also read:
|
||||
- `.planning/STATE.md` — current phase, progress, plan counts
|
||||
- `.planning/ROADMAP.md` — milestone structure and phase list
|
||||
|
||||
Extract:
|
||||
- `current_phase` — which phase is active
|
||||
- `plan_of` / `plans_total` — plan execution progress
|
||||
- `progress` — overall percentage
|
||||
- `status` — active, paused, etc.
|
||||
|
||||
If no `.planning/` directory exists:
|
||||
```
|
||||
No GSD project detected. Run `/gsd:new-project` to get started.
|
||||
```
|
||||
Exit.
|
||||
</step>
|
||||
|
||||
<step name="determine_next_action">
|
||||
Apply routing rules based on state:
|
||||
|
||||
**Route 1: No phases exist yet → discuss**
|
||||
If ROADMAP has phases but no phase directories exist on disk:
|
||||
→ Next action: `/gsd:discuss-phase <first-phase>`
|
||||
|
||||
**Route 2: Phase exists but has no CONTEXT.md or RESEARCH.md → discuss**
|
||||
If the current phase directory exists but has neither CONTEXT.md nor RESEARCH.md:
|
||||
→ Next action: `/gsd:discuss-phase <current-phase>`
|
||||
|
||||
**Route 3: Phase has context but no plans → plan**
|
||||
If the current phase has CONTEXT.md (or RESEARCH.md) but no PLAN.md files:
|
||||
→ Next action: `/gsd:plan-phase <current-phase>`
|
||||
|
||||
**Route 4: Phase has plans but incomplete summaries → execute**
|
||||
If plans exist but not all have matching summaries:
|
||||
→ Next action: `/gsd:execute-phase <current-phase>`
|
||||
|
||||
**Route 5: All plans have summaries → verify and complete**
|
||||
If all plans in the current phase have summaries:
|
||||
→ Next action: `/gsd:verify-work` then `/gsd:complete-phase`
|
||||
|
||||
**Route 6: Phase complete, next phase exists → advance**
|
||||
If the current phase is complete and the next phase exists in ROADMAP:
|
||||
→ Next action: `/gsd:discuss-phase <next-phase>`
|
||||
|
||||
**Route 7: All phases complete → complete milestone**
|
||||
If all phases are complete:
|
||||
→ Next action: `/gsd:complete-milestone`
|
||||
|
||||
**Route 8: Paused → resume**
|
||||
If STATE.md shows paused_at:
|
||||
→ Next action: `/gsd:resume-work`
|
||||
</step>
|
||||
|
||||
<step name="show_and_execute">
|
||||
Display the determination:
|
||||
|
||||
```
|
||||
## GSD Next
|
||||
|
||||
**Current:** Phase [N] — [name] | [progress]%
|
||||
**Status:** [status description]
|
||||
|
||||
▶ **Next step:** `/gsd:[command] [args]`
|
||||
[One-line explanation of why this is the next step]
|
||||
```
|
||||
|
||||
Then immediately invoke the determined command via SlashCommand.
|
||||
Do not ask for confirmation — the whole point of `/gsd:next` is zero-friction advancement.
|
||||
</step>
|
||||
|
||||
</process>
|
||||
|
||||
<success_criteria>
|
||||
- [ ] Project state correctly detected
|
||||
- [ ] Next action correctly determined from routing rules
|
||||
- [ ] Command invoked immediately without user confirmation
|
||||
- [ ] Clear status shown before invoking
|
||||
</success_criteria>
|
||||
@@ -1,5 +1,5 @@
|
||||
<purpose>
|
||||
Create `.continue-here.md` handoff file to preserve complete work state across sessions. Enables seamless resumption with full context restoration.
|
||||
Create structured `.planning/HANDOFF.json` and `.continue-here.md` handoff files to preserve complete work state across sessions. The JSON provides machine-readable state for `/gsd:resume-work`; the markdown provides human-readable context.
|
||||
</purpose>
|
||||
|
||||
<required_reading>
|
||||
@@ -27,10 +27,61 @@ If no active phase detected, ask user which phase they're pausing work on.
|
||||
3. **Work remaining**: What's left in current plan/phase
|
||||
4. **Decisions made**: Key decisions and rationale
|
||||
5. **Blockers/issues**: Anything stuck
|
||||
6. **Mental context**: The approach, next steps, "vibe"
|
||||
7. **Files modified**: What's changed but not committed
|
||||
6. **Human actions pending**: Things that need manual intervention (MCP setup, API keys, approvals, manual testing)
|
||||
7. **Background processes**: Any running servers/watchers that were part of the workflow
|
||||
8. **Files modified**: What's changed but not committed
|
||||
|
||||
Ask user for clarifications if needed via conversational questions.
|
||||
|
||||
**Also inspect SUMMARY.md files for false completions:**
|
||||
```bash
|
||||
# Check for placeholder content in existing summaries
|
||||
grep -l "To be filled\|placeholder\|TBD" .planning/phases/*/*.md 2>/dev/null
|
||||
```
|
||||
Report any summaries with placeholder content as incomplete items.
|
||||
</step>
|
||||
|
||||
<step name="write_structured">
|
||||
**Write structured handoff to `.planning/HANDOFF.json`:**
|
||||
|
||||
```bash
|
||||
timestamp=$(node "$HOME/.claude/get-shit-done/bin/gsd-tools.cjs" current-timestamp full --raw)
|
||||
```
|
||||
|
||||
```json
|
||||
{
|
||||
"version": "1.0",
|
||||
"timestamp": "{timestamp}",
|
||||
"phase": "{phase_number}",
|
||||
"phase_name": "{phase_name}",
|
||||
"phase_dir": "{phase_dir}",
|
||||
"plan": {current_plan_number},
|
||||
"task": {current_task_number},
|
||||
"total_tasks": {total_task_count},
|
||||
"status": "paused",
|
||||
"completed_tasks": [
|
||||
{"id": 1, "name": "{task_name}", "status": "done", "commit": "{short_hash}"},
|
||||
{"id": 2, "name": "{task_name}", "status": "done", "commit": "{short_hash}"},
|
||||
{"id": 3, "name": "{task_name}", "status": "in_progress", "progress": "{what_done}"}
|
||||
],
|
||||
"remaining_tasks": [
|
||||
{"id": 4, "name": "{task_name}", "status": "not_started"},
|
||||
{"id": 5, "name": "{task_name}", "status": "not_started"}
|
||||
],
|
||||
"blockers": [
|
||||
{"description": "{blocker}", "type": "technical|human_action|external", "workaround": "{if any}"}
|
||||
],
|
||||
"human_actions_pending": [
|
||||
{"action": "{what needs to be done}", "context": "{why}", "blocking": true}
|
||||
],
|
||||
"decisions": [
|
||||
{"decision": "{what}", "rationale": "{why}", "phase": "{phase_number}"}
|
||||
],
|
||||
"uncommitted_files": [],
|
||||
"next_action": "{specific first action when resuming}",
|
||||
"context_notes": "{mental state, approach, what you were thinking}"
|
||||
}
|
||||
```
|
||||
</step>
|
||||
|
||||
<step name="write">
|
||||
@@ -92,19 +143,22 @@ timestamp=$(node "$HOME/.claude/get-shit-done/bin/gsd-tools.cjs" current-timesta
|
||||
|
||||
<step name="commit">
|
||||
```bash
|
||||
node "$HOME/.claude/get-shit-done/bin/gsd-tools.cjs" commit "wip: [phase-name] paused at task [X]/[Y]" --files .planning/phases/*/.continue-here.md
|
||||
node "$HOME/.claude/get-shit-done/bin/gsd-tools.cjs" commit "wip: [phase-name] paused at task [X]/[Y]" --files .planning/phases/*/.continue-here.md .planning/HANDOFF.json
|
||||
```
|
||||
</step>
|
||||
|
||||
<step name="confirm">
|
||||
```
|
||||
✓ Handoff created: .planning/phases/[XX-name]/.continue-here.md
|
||||
✓ Handoff created:
|
||||
- .planning/HANDOFF.json (structured, machine-readable)
|
||||
- .planning/phases/[XX-name]/.continue-here.md (human-readable)
|
||||
|
||||
Current state:
|
||||
|
||||
- Phase: [XX-name]
|
||||
- Task: [X] of [Y]
|
||||
- Status: [in_progress/blocked]
|
||||
- Blockers: [count] ({human_actions_pending count} need human action)
|
||||
- Committed as WIP
|
||||
|
||||
To resume: /gsd:resume-work
|
||||
|
||||
@@ -8,6 +8,13 @@ Read all files referenced by the invoking prompt's execution_context before star
|
||||
@~/.claude/get-shit-done/references/ui-brand.md
|
||||
</required_reading>
|
||||
|
||||
<available_agent_types>
|
||||
Valid GSD subagent types (use exact names — do not fall back to 'general-purpose'):
|
||||
- gsd-phase-researcher — Researches technical approaches for a phase
|
||||
- gsd-planner — Creates detailed plans from phase scope
|
||||
- gsd-plan-checker — Reviews plan quality before execution
|
||||
</available_agent_types>
|
||||
|
||||
<process>
|
||||
|
||||
## 1. Initialize
|
||||
@@ -170,7 +177,16 @@ Use AskUserQuestion:
|
||||
- "Run discuss-phase first" — Capture design decisions before planning
|
||||
|
||||
If "Continue without context": Proceed to step 5.
|
||||
If "Run discuss-phase first": Display `/gsd:discuss-phase {X}` and exit workflow.
|
||||
If "Run discuss-phase first":
|
||||
**IMPORTANT:** Do NOT invoke discuss-phase as a nested Skill/Task call — AskUserQuestion
|
||||
does not work correctly in nested subcontexts (#1009). Instead, display the command
|
||||
and exit so the user runs it as a top-level command:
|
||||
```
|
||||
Run this command first, then re-run /gsd:plan-phase {X}:
|
||||
|
||||
/gsd:discuss-phase {X}
|
||||
```
|
||||
**Exit the plan-phase workflow. Do not continue.**
|
||||
|
||||
## 5. Handle Research
|
||||
|
||||
@@ -571,11 +587,62 @@ Display: `Max iterations reached. {N} issues remain:` + issue list
|
||||
|
||||
Offer: 1) Force proceed, 2) Provide guidance and retry, 3) Abandon
|
||||
|
||||
## 13. Present Final Status
|
||||
## 13. Requirements Coverage Gate
|
||||
|
||||
After plans pass the checker (or checker is skipped), verify that all phase requirements are covered by at least one plan.
|
||||
|
||||
**Skip if:** `phase_req_ids` is null or TBD (no requirements mapped to this phase).
|
||||
|
||||
**Step 1: Extract requirement IDs claimed by plans**
|
||||
```bash
|
||||
# Collect all requirement IDs from plan frontmatter
|
||||
PLAN_REQS=$(grep -h "requirements_addressed\|requirements:" ${PHASE_DIR}/*-PLAN.md 2>/dev/null | tr -d '[]' | tr ',' '\n' | sed 's/^[[:space:]]*//' | sort -u)
|
||||
```
|
||||
|
||||
**Step 2: Compare against phase requirements from ROADMAP**
|
||||
|
||||
For each REQ-ID in `phase_req_ids`:
|
||||
- If REQ-ID appears in `PLAN_REQS` → covered ✓
|
||||
- If REQ-ID does NOT appear in any plan → uncovered ✗
|
||||
|
||||
**Step 3: Check CONTEXT.md features against plan objectives**
|
||||
|
||||
Read CONTEXT.md `<decisions>` section. Extract feature/capability names. Check each against plan `<objective>` blocks. Features not mentioned in any plan objective → potentially dropped.
|
||||
|
||||
**Step 4: Report**
|
||||
|
||||
If all requirements covered and no dropped features:
|
||||
```
|
||||
✓ Requirements coverage: {N}/{N} REQ-IDs covered by plans
|
||||
```
|
||||
→ Proceed to step 14.
|
||||
|
||||
If gaps found:
|
||||
```
|
||||
## ⚠ Requirements Coverage Gap
|
||||
|
||||
{M} of {N} phase requirements are not assigned to any plan:
|
||||
|
||||
| REQ-ID | Description | Plans |
|
||||
|--------|-------------|-------|
|
||||
| {id} | {from REQUIREMENTS.md} | None |
|
||||
|
||||
{K} CONTEXT.md features not found in plan objectives:
|
||||
- {feature_name} — described in CONTEXT.md but no plan covers it
|
||||
|
||||
Options:
|
||||
1. Re-plan to include missing requirements (recommended)
|
||||
2. Move uncovered requirements to next phase
|
||||
3. Proceed anyway — accept coverage gaps
|
||||
```
|
||||
|
||||
Use AskUserQuestion to present the options.
|
||||
|
||||
## 14. Present Final Status
|
||||
|
||||
Route to `<offer_next>` OR `auto_advance` depending on flags/config.
|
||||
|
||||
## 14. Auto-Advance Check
|
||||
## 15. Auto-Advance Check
|
||||
|
||||
Check for auto-advance trigger:
|
||||
|
||||
@@ -670,6 +737,30 @@ Verification: {Passed | Passed with override | Skipped}
|
||||
───────────────────────────────────────────────────────────────
|
||||
</offer_next>
|
||||
|
||||
<windows_troubleshooting>
|
||||
**Windows users:** If plan-phase freezes during agent spawning (common on Windows due to
|
||||
stdio deadlocks with MCP servers — see Claude Code issue anthropics/claude-code#28126):
|
||||
|
||||
1. **Force-kill:** Close the terminal (Ctrl+C may not work)
|
||||
2. **Clean up orphaned processes:**
|
||||
```powershell
|
||||
# Kill orphaned node processes from stale MCP servers
|
||||
Get-Process node -ErrorAction SilentlyContinue | Where-Object {$_.StartTime -lt (Get-Date).AddHours(-1)} | Stop-Process -Force
|
||||
```
|
||||
3. **Clean up stale task directories:**
|
||||
```powershell
|
||||
# Remove stale subagent task dirs (Claude Code never cleans these on crash)
|
||||
Remove-Item -Recurse -Force "$env:USERPROFILE\.claude\tasks\*" -ErrorAction SilentlyContinue
|
||||
```
|
||||
4. **Reduce MCP server count:** Temporarily disable non-essential MCP servers in settings.json
|
||||
5. **Retry:** Restart Claude Code and run `/gsd:plan-phase` again
|
||||
|
||||
If freezes persist, try `--skip-research` to reduce the agent chain from 3 to 2 agents:
|
||||
```
|
||||
/gsd:plan-phase N --skip-research
|
||||
```
|
||||
</windows_troubleshooting>
|
||||
|
||||
<success_criteria>
|
||||
- [ ] .planning/ directory validated
|
||||
- [ ] Phase validated against roadmap
|
||||
|
||||
169
get-shit-done/workflows/plant-seed.md
Normal file
169
get-shit-done/workflows/plant-seed.md
Normal file
@@ -0,0 +1,169 @@
|
||||
<purpose>
|
||||
Capture a forward-looking idea as a structured seed file with trigger conditions.
|
||||
Seeds auto-surface during /gsd:new-milestone when trigger conditions match the
|
||||
new milestone's scope.
|
||||
|
||||
Seeds beat deferred items because they:
|
||||
- Preserve WHY the idea matters (not just WHAT)
|
||||
- Define WHEN to surface (trigger conditions, not manual scanning)
|
||||
- Track breadcrumbs (code references, related decisions)
|
||||
- Auto-present at the right time via new-milestone scan
|
||||
</purpose>
|
||||
|
||||
<process>
|
||||
|
||||
<step name="parse_idea">
|
||||
Parse `$ARGUMENTS` for the idea summary.
|
||||
|
||||
If empty, ask:
|
||||
```
|
||||
What's the idea? (one sentence)
|
||||
```
|
||||
|
||||
Store as `$IDEA`.
|
||||
</step>
|
||||
|
||||
<step name="create_seed_dir">
|
||||
```bash
|
||||
mkdir -p .planning/seeds
|
||||
```
|
||||
</step>
|
||||
|
||||
<step name="gather_context">
|
||||
Ask focused questions to build a complete seed:
|
||||
|
||||
```
|
||||
AskUserQuestion(
|
||||
header: "Trigger",
|
||||
question: "When should this idea surface? (e.g., 'when we add user accounts', 'next major version', 'when performance becomes a priority')",
|
||||
options: [] // freeform
|
||||
)
|
||||
```
|
||||
|
||||
Store as `$TRIGGER`.
|
||||
|
||||
```
|
||||
AskUserQuestion(
|
||||
header: "Why",
|
||||
question: "Why does this matter? What problem does it solve or what opportunity does it create?",
|
||||
options: []
|
||||
)
|
||||
```
|
||||
|
||||
Store as `$WHY`.
|
||||
|
||||
```
|
||||
AskUserQuestion(
|
||||
header: "Scope",
|
||||
question: "How big is this? (rough estimate)",
|
||||
options: [
|
||||
{ label: "Small", description: "A few hours — could be a quick task" },
|
||||
{ label: "Medium", description: "A phase or two — needs planning" },
|
||||
{ label: "Large", description: "A full milestone — significant effort" }
|
||||
]
|
||||
)
|
||||
```
|
||||
|
||||
Store as `$SCOPE`.
|
||||
</step>
|
||||
|
||||
<step name="collect_breadcrumbs">
|
||||
Search the codebase for relevant references:
|
||||
|
||||
```bash
|
||||
# Find files related to the idea keywords
|
||||
grep -rl "$KEYWORD" --include="*.ts" --include="*.js" --include="*.md" . 2>/dev/null | head -10
|
||||
```
|
||||
|
||||
Also check:
|
||||
- Current STATE.md for related decisions
|
||||
- ROADMAP.md for related phases
|
||||
- todos/ for related captured ideas
|
||||
|
||||
Store relevant file paths as `$BREADCRUMBS`.
|
||||
</step>
|
||||
|
||||
<step name="generate_seed_id">
|
||||
```bash
|
||||
# Find next seed number
|
||||
EXISTING=$(ls .planning/seeds/SEED-*.md 2>/dev/null | wc -l)
|
||||
NEXT=$((EXISTING + 1))
|
||||
PADDED=$(printf "%03d" $NEXT)
|
||||
```
|
||||
|
||||
Generate slug from idea summary.
|
||||
</step>
|
||||
|
||||
<step name="write_seed">
|
||||
Write `.planning/seeds/SEED-{PADDED}-{slug}.md`:
|
||||
|
||||
```markdown
|
||||
---
|
||||
id: SEED-{PADDED}
|
||||
status: dormant
|
||||
planted: {ISO date}
|
||||
planted_during: {current milestone/phase from STATE.md}
|
||||
trigger_when: {$TRIGGER}
|
||||
scope: {$SCOPE}
|
||||
---
|
||||
|
||||
# SEED-{PADDED}: {$IDEA}
|
||||
|
||||
## Why This Matters
|
||||
|
||||
{$WHY}
|
||||
|
||||
## When to Surface
|
||||
|
||||
**Trigger:** {$TRIGGER}
|
||||
|
||||
This seed should be presented during `/gsd:new-milestone` when the milestone
|
||||
scope matches any of these conditions:
|
||||
- {trigger condition 1}
|
||||
- {trigger condition 2}
|
||||
|
||||
## Scope Estimate
|
||||
|
||||
**{$SCOPE}** — {elaboration based on scope choice}
|
||||
|
||||
## Breadcrumbs
|
||||
|
||||
Related code and decisions found in the current codebase:
|
||||
|
||||
{list of $BREADCRUMBS with file paths}
|
||||
|
||||
## Notes
|
||||
|
||||
{any additional context from the current session}
|
||||
```
|
||||
</step>
|
||||
|
||||
<step name="commit_seed">
|
||||
```bash
|
||||
node "$HOME/.claude/get-shit-done/bin/gsd-tools.cjs" commit "docs: plant seed — {$IDEA}" --files .planning/seeds/SEED-{PADDED}-{slug}.md
|
||||
```
|
||||
</step>
|
||||
|
||||
<step name="confirm">
|
||||
```
|
||||
✅ Seed planted: SEED-{PADDED}
|
||||
|
||||
"{$IDEA}"
|
||||
Trigger: {$TRIGGER}
|
||||
Scope: {$SCOPE}
|
||||
File: .planning/seeds/SEED-{PADDED}-{slug}.md
|
||||
|
||||
This seed will surface automatically when you run /gsd:new-milestone
|
||||
and the milestone scope matches the trigger condition.
|
||||
```
|
||||
</step>
|
||||
|
||||
</process>
|
||||
|
||||
<success_criteria>
|
||||
- [ ] Seed file created in .planning/seeds/
|
||||
- [ ] Frontmatter includes status, trigger, scope
|
||||
- [ ] Breadcrumbs collected from codebase
|
||||
- [ ] Committed to git
|
||||
- [ ] User shown confirmation with trigger info
|
||||
</success_criteria>
|
||||
129
get-shit-done/workflows/pr-branch.md
Normal file
129
get-shit-done/workflows/pr-branch.md
Normal file
@@ -0,0 +1,129 @@
|
||||
<purpose>
|
||||
Create a clean branch for pull requests by filtering out .planning/ commits.
|
||||
The PR branch contains only code changes — reviewers don't see GSD artifacts
|
||||
(PLAN.md, SUMMARY.md, STATE.md, CONTEXT.md, etc.).
|
||||
|
||||
Uses git cherry-pick with path filtering to rebuild a clean history.
|
||||
</purpose>
|
||||
|
||||
<process>
|
||||
|
||||
<step name="detect_state">
|
||||
Parse `$ARGUMENTS` for target branch (default: `main`).
|
||||
|
||||
```bash
|
||||
CURRENT_BRANCH=$(git branch --show-current)
|
||||
TARGET=${1:-main}
|
||||
```
|
||||
|
||||
Check preconditions:
|
||||
- Must be on a feature branch (not main/master)
|
||||
- Must have commits ahead of target
|
||||
|
||||
```bash
|
||||
AHEAD=$(git rev-list --count "$TARGET".."$CURRENT_BRANCH" 2>/dev/null)
|
||||
if [ "$AHEAD" = "0" ]; then
|
||||
echo "No commits ahead of $TARGET — nothing to filter."
|
||||
exit 0
|
||||
fi
|
||||
```
|
||||
|
||||
Display:
|
||||
```
|
||||
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
|
||||
GSD ► PR BRANCH
|
||||
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
|
||||
|
||||
Branch: {CURRENT_BRANCH}
|
||||
Target: {TARGET}
|
||||
Commits: {AHEAD} ahead
|
||||
```
|
||||
</step>
|
||||
|
||||
<step name="analyze_commits">
|
||||
Classify commits:
|
||||
|
||||
```bash
|
||||
# Get all commits ahead of target
|
||||
git log --oneline "$TARGET".."$CURRENT_BRANCH" --no-merges
|
||||
```
|
||||
|
||||
For each commit, check if it ONLY touches .planning/ files:
|
||||
|
||||
```bash
|
||||
# For each commit hash
|
||||
FILES=$(git diff-tree --no-commit-id --name-only -r $HASH)
|
||||
ALL_PLANNING=$(echo "$FILES" | grep -v "^\.planning/" | wc -l)
|
||||
```
|
||||
|
||||
Classify:
|
||||
- **Code commits**: Touch at least one non-.planning/ file → INCLUDE
|
||||
- **Planning-only commits**: Touch only .planning/ files → EXCLUDE
|
||||
- **Mixed commits**: Touch both → INCLUDE (planning changes come along)
|
||||
|
||||
Display analysis:
|
||||
```
|
||||
Commits to include: {N} (code changes)
|
||||
Commits to exclude: {N} (planning-only)
|
||||
Mixed commits: {N} (code + planning — included)
|
||||
```
|
||||
</step>
|
||||
|
||||
<step name="create_pr_branch">
|
||||
```bash
|
||||
PR_BRANCH="${CURRENT_BRANCH}-pr"
|
||||
|
||||
# Create PR branch from target
|
||||
git checkout -b "$PR_BRANCH" "$TARGET"
|
||||
```
|
||||
|
||||
Cherry-pick only code commits (in order):
|
||||
|
||||
```bash
|
||||
for HASH in $CODE_COMMITS; do
|
||||
git cherry-pick "$HASH" --no-commit
|
||||
# Remove any .planning/ files that came along in mixed commits
|
||||
git rm -r --cached .planning/ 2>/dev/null || true
|
||||
git commit -C "$HASH"
|
||||
done
|
||||
```
|
||||
|
||||
Return to original branch:
|
||||
```bash
|
||||
git checkout "$CURRENT_BRANCH"
|
||||
```
|
||||
</step>
|
||||
|
||||
<step name="verify">
|
||||
```bash
|
||||
# Verify no .planning/ files in PR branch
|
||||
PLANNING_FILES=$(git diff --name-only "$TARGET".."$PR_BRANCH" | grep "^\.planning/" | wc -l)
|
||||
TOTAL_FILES=$(git diff --name-only "$TARGET".."$PR_BRANCH" | wc -l)
|
||||
PR_COMMITS=$(git rev-list --count "$TARGET".."$PR_BRANCH")
|
||||
```
|
||||
|
||||
Display results:
|
||||
```
|
||||
✅ PR branch created: {PR_BRANCH}
|
||||
|
||||
Original: {AHEAD} commits, {ORIGINAL_FILES} files
|
||||
PR branch: {PR_COMMITS} commits, {TOTAL_FILES} files
|
||||
Planning files: {PLANNING_FILES} (should be 0)
|
||||
|
||||
Next steps:
|
||||
git push origin {PR_BRANCH}
|
||||
gh pr create --base {TARGET} --head {PR_BRANCH}
|
||||
|
||||
Or use /gsd:ship to create the PR automatically.
|
||||
```
|
||||
</step>
|
||||
|
||||
</process>
|
||||
|
||||
<success_criteria>
|
||||
- [ ] PR branch created from target
|
||||
- [ ] Planning-only commits excluded
|
||||
- [ ] No .planning/ files in PR branch diff
|
||||
- [ ] Commit messages preserved from original
|
||||
- [ ] User shown next steps
|
||||
</success_criteria>
|
||||
@@ -150,17 +150,47 @@ State: "This phase has {X} plans, {Y} summaries."
|
||||
Check for UAT.md files with status "diagnosed" (has gaps needing fixes).
|
||||
|
||||
```bash
|
||||
# Check for diagnosed UAT with gaps
|
||||
grep -l "status: diagnosed" .planning/phases/[current-phase-dir]/*-UAT.md 2>/dev/null
|
||||
# Check for diagnosed UAT with gaps or partial (incomplete) testing
|
||||
grep -l "status: diagnosed\|status: partial" .planning/phases/[current-phase-dir]/*-UAT.md 2>/dev/null
|
||||
```
|
||||
|
||||
Track:
|
||||
- `uat_with_gaps`: UAT.md files with status "diagnosed" (gaps need fixing)
|
||||
- `uat_partial`: UAT.md files with status "partial" (incomplete testing)
|
||||
|
||||
**Step 1.6: Cross-phase health check**
|
||||
|
||||
Scan ALL phases in the current milestone for outstanding verification debt using the CLI (which respects milestone boundaries via `getMilestonePhaseFilter`):
|
||||
|
||||
```bash
|
||||
DEBT=$(node "$HOME/.claude/get-shit-done/bin/gsd-tools.cjs" audit-uat --raw 2>/dev/null)
|
||||
```
|
||||
|
||||
Parse JSON for `summary.total_items` and `summary.total_files`.
|
||||
|
||||
Track: `outstanding_debt` — `summary.total_items` from the audit.
|
||||
|
||||
**If outstanding_debt > 0:** Add a warning section to the progress report output (in the `report` step), placed between "## What's Next" and the route suggestion:
|
||||
|
||||
```markdown
|
||||
## Verification Debt ({N} files across prior phases)
|
||||
|
||||
| Phase | File | Issue |
|
||||
|-------|------|-------|
|
||||
| {phase} | {filename} | {pending_count} pending, {skipped_count} skipped, {blocked_count} blocked |
|
||||
| {phase} | {filename} | human_needed — {count} items |
|
||||
|
||||
Review: `/gsd:audit-uat` — full cross-phase audit
|
||||
Resume testing: `/gsd:verify-work {phase}` — retest specific phase
|
||||
```
|
||||
|
||||
This is a WARNING, not a blocker — routing proceeds normally. The debt is visible so the user can make an informed choice.
|
||||
|
||||
**Step 2: Route based on counts**
|
||||
|
||||
| Condition | Meaning | Action |
|
||||
|-----------|---------|--------|
|
||||
| uat_partial > 0 | UAT testing incomplete | Go to **Route E.2** |
|
||||
| uat_with_gaps > 0 | UAT gaps need fix plans | Go to **Route E** |
|
||||
| summaries < plans | Unexecuted plans exist | Go to **Route A** |
|
||||
| summaries = plans AND plans > 0 | Phase complete | Go to Step 3 |
|
||||
@@ -260,6 +290,32 @@ UAT.md exists with gaps (diagnosed issues). User needs to plan fixes.
|
||||
|
||||
---
|
||||
|
||||
**Route E.2: UAT testing incomplete (partial)**
|
||||
|
||||
UAT.md exists with `status: partial` — testing session ended before all items resolved.
|
||||
|
||||
```
|
||||
---
|
||||
|
||||
## Incomplete UAT Testing
|
||||
|
||||
**{phase_num}-UAT.md** has {N} unresolved tests (pending, blocked, or skipped).
|
||||
|
||||
`/gsd:verify-work {phase}` — resume testing from where you left off
|
||||
|
||||
<sub>`/clear` first → fresh context window</sub>
|
||||
|
||||
---
|
||||
|
||||
**Also available:**
|
||||
- `/gsd:audit-uat` — full cross-phase UAT audit
|
||||
- `/gsd:execute-phase {phase}` — execute phase plans
|
||||
|
||||
---
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
**Step 3: Check milestone status (only when phase complete)**
|
||||
|
||||
Read ROADMAP.md and identify:
|
||||
|
||||
@@ -111,7 +111,7 @@ INIT=$(node "$HOME/.claude/get-shit-done/bin/gsd-tools.cjs" init quick "$DESCRIP
|
||||
if [[ "$INIT" == @file:* ]]; then INIT=$(cat "${INIT#@file:}"); fi
|
||||
```
|
||||
|
||||
Parse JSON for: `planner_model`, `executor_model`, `checker_model`, `verifier_model`, `commit_docs`, `quick_id`, `slug`, `date`, `timestamp`, `quick_dir`, `task_dir`, `roadmap_exists`, `planning_exists`.
|
||||
Parse JSON for: `planner_model`, `executor_model`, `checker_model`, `verifier_model`, `commit_docs`, `branch_name`, `quick_id`, `slug`, `date`, `timestamp`, `quick_dir`, `task_dir`, `roadmap_exists`, `planning_exists`.
|
||||
|
||||
**If `roadmap_exists` is false:** Error — Quick mode requires an active project with ROADMAP.md. Run `/gsd:new-project` first.
|
||||
|
||||
@@ -119,6 +119,20 @@ Quick tasks can run mid-phase - validation only checks ROADMAP.md exists, not ph
|
||||
|
||||
---
|
||||
|
||||
**Step 2.5: Handle quick-task branching**
|
||||
|
||||
**If `branch_name` is empty/null:** Skip and continue on the current branch.
|
||||
|
||||
**If `branch_name` is set:** Check out the quick-task branch before any planning commits:
|
||||
|
||||
```bash
|
||||
git checkout -b "$branch_name" 2>/dev/null || git checkout "$branch_name"
|
||||
```
|
||||
|
||||
All quick-task commits for this run stay on that branch. User handles merge/rebase afterward.
|
||||
|
||||
---
|
||||
|
||||
**Step 3: Create task directory**
|
||||
|
||||
```bash
|
||||
|
||||
@@ -63,6 +63,9 @@ cat .planning/PROJECT.md
|
||||
Look for incomplete work that needs attention:
|
||||
|
||||
```bash
|
||||
# Check for structured handoff (preferred — machine-readable)
|
||||
cat .planning/HANDOFF.json 2>/dev/null
|
||||
|
||||
# Check for continue-here files (mid-plan resumption)
|
||||
ls .planning/phases/*/.continue-here*.md 2>/dev/null
|
||||
|
||||
@@ -78,7 +81,18 @@ if [ "$has_interrupted_agent" = "true" ]; then
|
||||
fi
|
||||
```
|
||||
|
||||
**If .continue-here file exists:**
|
||||
**If HANDOFF.json exists:**
|
||||
|
||||
- This is the primary resumption source — structured data from `/gsd:pause-work`
|
||||
- Parse `status`, `phase`, `plan`, `task`, `total_tasks`, `next_action`
|
||||
- Check `blockers` and `human_actions_pending` — surface these immediately
|
||||
- Check `completed_tasks` for `in_progress` items — these need attention first
|
||||
- Validate `uncommitted_files` against `git status` — flag divergence
|
||||
- Use `context_notes` to restore mental model
|
||||
- Flag: "Found structured handoff — resuming from task {task}/{total_tasks}"
|
||||
- **After successful resumption, delete HANDOFF.json** (it's a one-shot artifact)
|
||||
|
||||
**If .continue-here file exists (fallback):**
|
||||
|
||||
- This is a mid-plan resumption point
|
||||
- Read the file for specific resumption context
|
||||
@@ -145,8 +159,12 @@ Based on project state, determine the most logical next action:
|
||||
→ Primary: Resume interrupted agent (Task tool with resume parameter)
|
||||
→ Option: Start fresh (abandon agent work)
|
||||
|
||||
**If HANDOFF.json exists:**
|
||||
→ Primary: Resume from structured handoff (highest priority — specific task/blocker context)
|
||||
→ Option: Discard handoff and reassess from files
|
||||
|
||||
**If .continue-here file exists:**
|
||||
→ Primary: Resume from checkpoint
|
||||
→ Fallback: Resume from checkpoint
|
||||
→ Option: Start fresh on current plan
|
||||
|
||||
**If incomplete plan (PLAN without SUMMARY):**
|
||||
@@ -154,7 +172,7 @@ Based on project state, determine the most logical next action:
|
||||
→ Option: Abandon and move on
|
||||
|
||||
**If phase in progress, all plans complete:**
|
||||
→ Primary: Transition to next phase
|
||||
→ Primary: Advance to next phase (via internal transition workflow)
|
||||
→ Option: Review completed work
|
||||
|
||||
**If phase ready to plan:**
|
||||
@@ -242,7 +260,7 @@ Based on user selection, route to appropriate workflow:
|
||||
|
||||
---
|
||||
```
|
||||
- **Transition** → ./transition.md
|
||||
- **Advance to next phase** → ./transition.md (internal workflow, invoked inline — NOT a user command)
|
||||
- **Check todos** → Read .planning/todos/pending/, present summary
|
||||
- **Review alignment** → Read PROJECT.md, compare to current state
|
||||
- **Something else** → Ask what they need
|
||||
|
||||
228
get-shit-done/workflows/review.md
Normal file
228
get-shit-done/workflows/review.md
Normal file
@@ -0,0 +1,228 @@
|
||||
<purpose>
|
||||
Cross-AI peer review — invoke external AI CLIs to independently review phase plans.
|
||||
Each CLI gets the same prompt (PROJECT.md context, phase plans, requirements) and
|
||||
produces structured feedback. Results are combined into REVIEWS.md for the planner
|
||||
to incorporate via --reviews flag.
|
||||
|
||||
This implements adversarial review: different AI models catch different blind spots.
|
||||
A plan that survives review from 2-3 independent AI systems is more robust.
|
||||
</purpose>
|
||||
|
||||
<process>
|
||||
|
||||
<step name="detect_clis">
|
||||
Check which AI CLIs are available on the system:
|
||||
|
||||
```bash
|
||||
# Check each CLI
|
||||
command -v gemini >/dev/null 2>&1 && echo "gemini:available" || echo "gemini:missing"
|
||||
command -v claude >/dev/null 2>&1 && echo "claude:available" || echo "claude:missing"
|
||||
command -v codex >/dev/null 2>&1 && echo "codex:available" || echo "codex:missing"
|
||||
```
|
||||
|
||||
Parse flags from `$ARGUMENTS`:
|
||||
- `--gemini` → include Gemini
|
||||
- `--claude` → include Claude
|
||||
- `--codex` → include Codex
|
||||
- `--all` → include all available
|
||||
- No flags → include all available
|
||||
|
||||
If no CLIs are available:
|
||||
```
|
||||
No external AI CLIs found. Install at least one:
|
||||
- gemini: https://github.com/google-gemini/gemini-cli
|
||||
- codex: https://github.com/openai/codex
|
||||
- claude: https://github.com/anthropics/claude-code
|
||||
|
||||
Then run /gsd:review again.
|
||||
```
|
||||
Exit.
|
||||
|
||||
If only one CLI is the current runtime (e.g. running inside Claude), skip it for the review
|
||||
to ensure independence. At least one DIFFERENT CLI must be available.
|
||||
</step>
|
||||
|
||||
<step name="gather_context">
|
||||
Collect phase artifacts for the review prompt:
|
||||
|
||||
```bash
|
||||
INIT=$(node "$HOME/.claude/get-shit-done/bin/gsd-tools.cjs" init phase-op "${PHASE_ARG}")
|
||||
if [[ "$INIT" == @file:* ]]; then INIT=$(cat "${INIT#@file:}"); fi
|
||||
```
|
||||
|
||||
Read from init: `phase_dir`, `phase_number`, `padded_phase`.
|
||||
|
||||
Then read:
|
||||
1. `.planning/PROJECT.md` (first 80 lines — project context)
|
||||
2. Phase section from `.planning/ROADMAP.md`
|
||||
3. All `*-PLAN.md` files in the phase directory
|
||||
4. `*-CONTEXT.md` if present (user decisions)
|
||||
5. `*-RESEARCH.md` if present (domain research)
|
||||
6. `.planning/REQUIREMENTS.md` (requirements this phase addresses)
|
||||
</step>
|
||||
|
||||
<step name="build_prompt">
|
||||
Build a structured review prompt:
|
||||
|
||||
```markdown
|
||||
# Cross-AI Plan Review Request
|
||||
|
||||
You are reviewing implementation plans for a software project phase.
|
||||
Provide structured feedback on plan quality, completeness, and risks.
|
||||
|
||||
## Project Context
|
||||
{first 80 lines of PROJECT.md}
|
||||
|
||||
## Phase {N}: {phase name}
|
||||
### Roadmap Section
|
||||
{roadmap phase section}
|
||||
|
||||
### Requirements Addressed
|
||||
{requirements for this phase}
|
||||
|
||||
### User Decisions (CONTEXT.md)
|
||||
{context if present}
|
||||
|
||||
### Research Findings
|
||||
{research if present}
|
||||
|
||||
### Plans to Review
|
||||
{all PLAN.md contents}
|
||||
|
||||
## Review Instructions
|
||||
|
||||
Analyze each plan and provide:
|
||||
|
||||
1. **Summary** — One-paragraph assessment
|
||||
2. **Strengths** — What's well-designed (bullet points)
|
||||
3. **Concerns** — Potential issues, gaps, risks (bullet points with severity: HIGH/MEDIUM/LOW)
|
||||
4. **Suggestions** — Specific improvements (bullet points)
|
||||
5. **Risk Assessment** — Overall risk level (LOW/MEDIUM/HIGH) with justification
|
||||
|
||||
Focus on:
|
||||
- Missing edge cases or error handling
|
||||
- Dependency ordering issues
|
||||
- Scope creep or over-engineering
|
||||
- Security considerations
|
||||
- Performance implications
|
||||
- Whether the plans actually achieve the phase goals
|
||||
|
||||
Output your review in markdown format.
|
||||
```
|
||||
|
||||
Write to a temp file: `/tmp/gsd-review-prompt-{phase}.md`
|
||||
</step>
|
||||
|
||||
<step name="invoke_reviewers">
|
||||
For each selected CLI, invoke in sequence (not parallel — avoid rate limits):
|
||||
|
||||
**Gemini:**
|
||||
```bash
|
||||
gemini -p "$(cat /tmp/gsd-review-prompt-{phase}.md)" 2>/dev/null > /tmp/gsd-review-gemini-{phase}.md
|
||||
```
|
||||
|
||||
**Claude (separate session):**
|
||||
```bash
|
||||
claude -p "$(cat /tmp/gsd-review-prompt-{phase}.md)" --no-input 2>/dev/null > /tmp/gsd-review-claude-{phase}.md
|
||||
```
|
||||
|
||||
**Codex:**
|
||||
```bash
|
||||
codex -p "$(cat /tmp/gsd-review-prompt-{phase}.md)" 2>/dev/null > /tmp/gsd-review-codex-{phase}.md
|
||||
```
|
||||
|
||||
If a CLI fails, log the error and continue with remaining CLIs.
|
||||
|
||||
Display progress:
|
||||
```
|
||||
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
|
||||
GSD ► CROSS-AI REVIEW — Phase {N}
|
||||
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
|
||||
|
||||
◆ Reviewing with {CLI}... done ✓
|
||||
◆ Reviewing with {CLI}... done ✓
|
||||
```
|
||||
</step>
|
||||
|
||||
<step name="write_reviews">
|
||||
Combine all review responses into `{phase_dir}/{padded_phase}-REVIEWS.md`:
|
||||
|
||||
```markdown
|
||||
---
|
||||
phase: {N}
|
||||
reviewers: [gemini, claude, codex]
|
||||
reviewed_at: {ISO timestamp}
|
||||
plans_reviewed: [{list of PLAN.md files}]
|
||||
---
|
||||
|
||||
# Cross-AI Plan Review — Phase {N}
|
||||
|
||||
## Gemini Review
|
||||
|
||||
{gemini review content}
|
||||
|
||||
---
|
||||
|
||||
## Claude Review
|
||||
|
||||
{claude review content}
|
||||
|
||||
---
|
||||
|
||||
## Codex Review
|
||||
|
||||
{codex review content}
|
||||
|
||||
---
|
||||
|
||||
## Consensus Summary
|
||||
|
||||
{synthesize common concerns across all reviewers}
|
||||
|
||||
### Agreed Strengths
|
||||
{strengths mentioned by 2+ reviewers}
|
||||
|
||||
### Agreed Concerns
|
||||
{concerns raised by 2+ reviewers — highest priority}
|
||||
|
||||
### Divergent Views
|
||||
{where reviewers disagreed — worth investigating}
|
||||
```
|
||||
|
||||
Commit:
|
||||
```bash
|
||||
node "$HOME/.claude/get-shit-done/bin/gsd-tools.cjs" commit "docs: cross-AI review for phase {N}" --files {phase_dir}/{padded_phase}-REVIEWS.md
|
||||
```
|
||||
</step>
|
||||
|
||||
<step name="present_results">
|
||||
Display summary:
|
||||
|
||||
```
|
||||
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
|
||||
GSD ► REVIEW COMPLETE
|
||||
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
|
||||
|
||||
Phase {N} reviewed by {count} AI systems.
|
||||
|
||||
Consensus concerns:
|
||||
{top 3 shared concerns}
|
||||
|
||||
Full review: {padded_phase}-REVIEWS.md
|
||||
|
||||
To incorporate feedback into planning:
|
||||
/gsd:plan-phase {N} --reviews
|
||||
```
|
||||
|
||||
Clean up temp files.
|
||||
</step>
|
||||
|
||||
</process>
|
||||
|
||||
<success_criteria>
|
||||
- [ ] At least one external CLI invoked successfully
|
||||
- [ ] REVIEWS.md written with structured feedback
|
||||
- [ ] Consensus summary synthesized from multiple reviewers
|
||||
- [ ] Temp files cleaned up
|
||||
- [ ] User knows how to use feedback (/gsd:plan-phase --reviews)
|
||||
</success_criteria>
|
||||
146
get-shit-done/workflows/session-report.md
Normal file
146
get-shit-done/workflows/session-report.md
Normal file
@@ -0,0 +1,146 @@
|
||||
<purpose>
|
||||
Generate a post-session summary document capturing work performed, outcomes achieved, and estimated resource usage. Writes SESSION_REPORT.md to .planning/reports/ for human review and stakeholder sharing.
|
||||
</purpose>
|
||||
|
||||
<required_reading>
|
||||
Read all files referenced by the invoking prompt's execution_context before starting.
|
||||
</required_reading>
|
||||
|
||||
<process>
|
||||
|
||||
<step name="gather_session_data">
|
||||
Collect session data from available sources:
|
||||
|
||||
1. **STATE.md** — current phase, milestone, progress, blockers, decisions
|
||||
2. **Git log** — commits made during this session (last 24h or since last report)
|
||||
3. **Plan/Summary files** — plans executed, summaries written
|
||||
4. **ROADMAP.md** — milestone context and phase goals
|
||||
|
||||
```bash
|
||||
# Get recent commits (last 24 hours)
|
||||
git log --oneline --since="24 hours ago" --no-merges 2>/dev/null || echo "No recent commits"
|
||||
|
||||
# Count files changed
|
||||
git diff --stat HEAD~10 HEAD 2>/dev/null | tail -1 || echo "No diff available"
|
||||
```
|
||||
|
||||
Read `.planning/STATE.md` to get:
|
||||
- Current milestone and phase
|
||||
- Progress percentage
|
||||
- Active blockers
|
||||
- Recent decisions
|
||||
|
||||
Read `.planning/ROADMAP.md` to get milestone name and goals.
|
||||
|
||||
Check for existing reports:
|
||||
```bash
|
||||
ls -la .planning/reports/SESSION_REPORT*.md 2>/dev/null || echo "No previous reports"
|
||||
```
|
||||
</step>
|
||||
|
||||
<step name="estimate_usage">
|
||||
Estimate token usage from observable signals:
|
||||
|
||||
- Count of tool calls is not directly available, so estimate from git activity and file operations
|
||||
- Note: This is an **estimate** — exact token counts require API-level instrumentation not available to hooks
|
||||
|
||||
Estimation heuristics:
|
||||
- Each commit ≈ 1 plan cycle (research + plan + execute + verify)
|
||||
- Each plan file ≈ 2,000-5,000 tokens of agent context
|
||||
- Each summary file ≈ 1,000-2,000 tokens generated
|
||||
- Subagent spawns multiply by ~1.5x per agent type used
|
||||
</step>
|
||||
|
||||
<step name="generate_report">
|
||||
Create the report directory and file:
|
||||
|
||||
```bash
|
||||
mkdir -p .planning/reports
|
||||
```
|
||||
|
||||
Write `.planning/reports/SESSION_REPORT.md` (or `.planning/reports/YYYYMMDD-session-report.md` if previous reports exist):
|
||||
|
||||
```markdown
|
||||
# GSD Session Report
|
||||
|
||||
**Generated:** [timestamp]
|
||||
**Project:** [from PROJECT.md title or directory name]
|
||||
**Milestone:** [N] — [milestone name from ROADMAP.md]
|
||||
|
||||
---
|
||||
|
||||
## Session Summary
|
||||
|
||||
**Duration:** [estimated from first to last commit timestamp, or "Single session"]
|
||||
**Phase Progress:** [from STATE.md]
|
||||
**Plans Executed:** [count of summaries written this session]
|
||||
**Commits Made:** [count from git log]
|
||||
|
||||
## Work Performed
|
||||
|
||||
### Phases Touched
|
||||
[List phases worked on with brief description of what was done]
|
||||
|
||||
### Key Outcomes
|
||||
[Bullet list of concrete deliverables: files created, features implemented, bugs fixed]
|
||||
|
||||
### Decisions Made
|
||||
[From STATE.md decisions table, if any were added this session]
|
||||
|
||||
## Files Changed
|
||||
|
||||
[Summary of files modified, created, deleted — from git diff stat]
|
||||
|
||||
## Blockers & Open Items
|
||||
|
||||
[Active blockers from STATE.md]
|
||||
[Any TODO items created during session]
|
||||
|
||||
## Estimated Resource Usage
|
||||
|
||||
| Metric | Estimate |
|
||||
|--------|----------|
|
||||
| Commits | [N] |
|
||||
| Files changed | [N] |
|
||||
| Plans executed | [N] |
|
||||
| Subagents spawned | [estimated] |
|
||||
|
||||
> **Note:** Token and cost estimates require API-level instrumentation.
|
||||
> These metrics reflect observable session activity only.
|
||||
|
||||
---
|
||||
|
||||
*Generated by `/gsd:session-report`*
|
||||
```
|
||||
</step>
|
||||
|
||||
<step name="display_result">
|
||||
Show the user:
|
||||
|
||||
```
|
||||
## Session Report Generated
|
||||
|
||||
📄 `.planning/reports/[filename].md`
|
||||
|
||||
### Highlights
|
||||
- **Commits:** [N]
|
||||
- **Files changed:** [N]
|
||||
- **Phase progress:** [X]%
|
||||
- **Plans executed:** [N]
|
||||
```
|
||||
|
||||
If this is the first report, mention:
|
||||
```
|
||||
💡 Run `/gsd:session-report` at the end of each session to build a history of project activity.
|
||||
```
|
||||
</step>
|
||||
|
||||
</process>
|
||||
|
||||
<success_criteria>
|
||||
- [ ] Session data gathered from STATE.md, git log, and plan files
|
||||
- [ ] Report written to .planning/reports/
|
||||
- [ ] Report includes work summary, outcomes, and file changes
|
||||
- [ ] Filename includes date to prevent overwrites
|
||||
- [ ] Result summary displayed to user
|
||||
</success_criteria>
|
||||
@@ -49,7 +49,7 @@ AskUserQuestion([
|
||||
{ label: "Quality", description: "Opus everywhere except verification (highest cost)" },
|
||||
{ label: "Balanced (Recommended)", description: "Opus for planning, Sonnet for research/execution/verification" },
|
||||
{ label: "Budget", description: "Sonnet for writing, Haiku for research/verification (lowest cost)" },
|
||||
{ label: "Inherit", description: "Use current session model for all agents (best for OpenCode /model)" }
|
||||
{ label: "Inherit", description: "Use current session model for all agents (best for OpenRouter, local models, or runtime model switching)" }
|
||||
]
|
||||
},
|
||||
{
|
||||
@@ -135,6 +135,15 @@ AskUserQuestion([
|
||||
{ label: "Yes (Recommended)", description: "Warn when context usage exceeds 65%. Helps avoid losing work." },
|
||||
{ label: "No", description: "Disable warnings. Allows Claude to reach auto-compact naturally. Good for long unattended runs." }
|
||||
]
|
||||
},
|
||||
{
|
||||
question: "Research best practices before asking questions? (web search during new-project and discuss-phase)",
|
||||
header: "Research Qs",
|
||||
multiSelect: false,
|
||||
options: [
|
||||
{ label: "No (Recommended)", description: "Ask questions directly. Faster, uses fewer tokens." },
|
||||
{ label: "Yes", description: "Search web for best practices before each question group. More informed questions but uses more tokens." }
|
||||
]
|
||||
}
|
||||
])
|
||||
```
|
||||
@@ -157,10 +166,16 @@ Merge new settings into existing config.json:
|
||||
"ui_safety_gate": true/false
|
||||
},
|
||||
"git": {
|
||||
"branching_strategy": "none" | "phase" | "milestone"
|
||||
"branching_strategy": "none" | "phase" | "milestone",
|
||||
"quick_branch_template": <string|null>
|
||||
},
|
||||
"hooks": {
|
||||
"context_warnings": true/false
|
||||
"context_warnings": true/false,
|
||||
"workflow_guard": true/false,
|
||||
"research_questions": true/false
|
||||
},
|
||||
"workflow": {
|
||||
"text_mode": true/false // Use plain-text questions instead of TUI menus (for /rc remote sessions)
|
||||
}
|
||||
}
|
||||
```
|
||||
@@ -200,6 +215,7 @@ Write `~/.gsd/defaults.json` with:
|
||||
"commit_docs": <current>,
|
||||
"parallelization": <current>,
|
||||
"branching_strategy": <current>,
|
||||
"quick_branch_template": <current>,
|
||||
"workflow": {
|
||||
"research": <current>,
|
||||
"plan_check": <current>,
|
||||
|
||||
228
get-shit-done/workflows/ship.md
Normal file
228
get-shit-done/workflows/ship.md
Normal file
@@ -0,0 +1,228 @@
|
||||
<purpose>
|
||||
Create a pull request from completed phase/milestone work, generate a rich PR body from planning artifacts, optionally run code review, and prepare for merge. Closes the plan → execute → verify → ship loop.
|
||||
</purpose>
|
||||
|
||||
<required_reading>
|
||||
Read all files referenced by the invoking prompt's execution_context before starting.
|
||||
</required_reading>
|
||||
|
||||
<process>
|
||||
|
||||
<step name="initialize">
|
||||
Parse arguments and load project state:
|
||||
|
||||
```bash
|
||||
INIT=$(node "$HOME/.claude/get-shit-done/bin/gsd-tools.cjs" init phase-op "${PHASE_ARG}")
|
||||
if [[ "$INIT" == @file:* ]]; then INIT=$(cat "${INIT#@file:}"); fi
|
||||
```
|
||||
|
||||
Parse from init JSON: `phase_found`, `phase_dir`, `phase_number`, `phase_name`, `padded_phase`, `commit_docs`.
|
||||
|
||||
Also load config for branching strategy:
|
||||
```bash
|
||||
CONFIG=$(node "$HOME/.claude/get-shit-done/bin/gsd-tools.cjs" state load)
|
||||
```
|
||||
|
||||
Extract: `branching_strategy`, `branch_name`.
|
||||
</step>
|
||||
|
||||
<step name="preflight_checks">
|
||||
Verify the work is ready to ship:
|
||||
|
||||
1. **Verification passed?**
|
||||
```bash
|
||||
VERIFICATION=$(cat ${PHASE_DIR}/*-VERIFICATION.md 2>/dev/null)
|
||||
```
|
||||
Check for `status: passed` or `status: human_needed` (with human approval).
|
||||
If no VERIFICATION.md or status is `gaps_found`: warn and ask user to confirm.
|
||||
|
||||
2. **Clean working tree?**
|
||||
```bash
|
||||
git status --short
|
||||
```
|
||||
If uncommitted changes exist: ask user to commit or stash first.
|
||||
|
||||
3. **On correct branch?**
|
||||
```bash
|
||||
CURRENT_BRANCH=$(git branch --show-current)
|
||||
```
|
||||
If on `main`/`master`: warn — should be on a feature branch.
|
||||
If branching_strategy is `none`: offer to create a branch now.
|
||||
|
||||
4. **Remote configured?**
|
||||
```bash
|
||||
git remote -v | head -2
|
||||
```
|
||||
Detect `origin` remote. If no remote: error — can't create PR.
|
||||
|
||||
5. **`gh` CLI available?**
|
||||
```bash
|
||||
which gh && gh auth status 2>&1
|
||||
```
|
||||
If `gh` not found or not authenticated: provide setup instructions and exit.
|
||||
</step>
|
||||
|
||||
<step name="push_branch">
|
||||
Push the current branch to remote:
|
||||
|
||||
```bash
|
||||
git push origin ${CURRENT_BRANCH} 2>&1
|
||||
```
|
||||
|
||||
If push fails (e.g., no upstream): set upstream:
|
||||
```bash
|
||||
git push --set-upstream origin ${CURRENT_BRANCH} 2>&1
|
||||
```
|
||||
|
||||
Report: "Pushed `{branch}` to origin ({commit_count} commits ahead of main)"
|
||||
</step>
|
||||
|
||||
<step name="generate_pr_body">
|
||||
Auto-generate a rich PR body from planning artifacts:
|
||||
|
||||
**1. Title:**
|
||||
```
|
||||
Phase {phase_number}: {phase_name}
|
||||
```
|
||||
Or for milestone: `Milestone {version}: {name}`
|
||||
|
||||
**2. Summary section:**
|
||||
Read ROADMAP.md for phase goal. Read VERIFICATION.md for verification status.
|
||||
|
||||
```markdown
|
||||
## Summary
|
||||
|
||||
**Phase {N}: {Name}**
|
||||
**Goal:** {goal from ROADMAP.md}
|
||||
**Status:** Verified ✓
|
||||
|
||||
{One paragraph synthesized from SUMMARY.md files — what was built}
|
||||
```
|
||||
|
||||
**3. Changes section:**
|
||||
For each SUMMARY.md in the phase directory:
|
||||
```markdown
|
||||
## Changes
|
||||
|
||||
### Plan {plan_id}: {plan_name}
|
||||
{one_liner from SUMMARY.md frontmatter}
|
||||
|
||||
**Key files:**
|
||||
{key-files.created and key-files.modified from SUMMARY.md frontmatter}
|
||||
```
|
||||
|
||||
**4. Requirements section:**
|
||||
```markdown
|
||||
## Requirements Addressed
|
||||
|
||||
{REQ-IDs from plan frontmatter, linked to REQUIREMENTS.md descriptions}
|
||||
```
|
||||
|
||||
**5. Testing section:**
|
||||
```markdown
|
||||
## Verification
|
||||
|
||||
- [x] Automated verification: {pass/fail from VERIFICATION.md}
|
||||
- {human verification items from VERIFICATION.md, if any}
|
||||
```
|
||||
|
||||
**6. Decisions section:**
|
||||
```markdown
|
||||
## Key Decisions
|
||||
|
||||
{Decisions from STATE.md accumulated context relevant to this phase}
|
||||
```
|
||||
</step>
|
||||
|
||||
<step name="create_pr">
|
||||
Create the PR using the generated body:
|
||||
|
||||
```bash
|
||||
gh pr create \
|
||||
--title "Phase ${PHASE_NUMBER}: ${PHASE_NAME}" \
|
||||
--body "${PR_BODY}" \
|
||||
--base main
|
||||
```
|
||||
|
||||
If `--draft` flag was passed: add `--draft`.
|
||||
|
||||
Report: "PR #{number} created: {url}"
|
||||
</step>
|
||||
|
||||
<step name="optional_review">
|
||||
Ask if user wants to trigger a code review:
|
||||
|
||||
```
|
||||
AskUserQuestion:
|
||||
question: "PR created. Run a code review before merge?"
|
||||
options:
|
||||
- label: "Skip review"
|
||||
description: "PR is ready — merge when CI passes"
|
||||
- label: "Self-review"
|
||||
description: "I'll review the diff in the PR myself"
|
||||
- label: "Request review"
|
||||
description: "Request review from a teammate"
|
||||
```
|
||||
|
||||
**If "Request review":**
|
||||
```bash
|
||||
gh pr edit ${PR_NUMBER} --add-reviewer "${REVIEWER}"
|
||||
```
|
||||
|
||||
**If "Self-review":**
|
||||
Report the PR URL and suggest: "Review the diff at {url}/files"
|
||||
</step>
|
||||
|
||||
<step name="track_shipping">
|
||||
Update STATE.md to reflect the shipping action:
|
||||
|
||||
```bash
|
||||
node "$HOME/.claude/get-shit-done/bin/gsd-tools.cjs" state update "Last Activity" "$(date +%Y-%m-%d)"
|
||||
node "$HOME/.claude/get-shit-done/bin/gsd-tools.cjs" state update "Status" "Phase ${PHASE_NUMBER} shipped — PR #${PR_NUMBER}"
|
||||
```
|
||||
|
||||
If `commit_docs` is true:
|
||||
```bash
|
||||
node "$HOME/.claude/get-shit-done/bin/gsd-tools.cjs" commit "docs(${padded_phase}): ship phase ${PHASE_NUMBER} — PR #${PR_NUMBER}" --files .planning/STATE.md
|
||||
```
|
||||
</step>
|
||||
|
||||
<step name="report">
|
||||
```
|
||||
───────────────────────────────────────────────────────────────
|
||||
|
||||
## ✓ Phase {X}: {Name} — Shipped
|
||||
|
||||
PR: #{number} ({url})
|
||||
Branch: {branch} → main
|
||||
Commits: {count}
|
||||
Verification: ✓ Passed
|
||||
Requirements: {N} REQ-IDs addressed
|
||||
|
||||
Next steps:
|
||||
- Review/approve PR
|
||||
- Merge when CI passes
|
||||
- /gsd:complete-milestone (if last phase in milestone)
|
||||
- /gsd:progress (to see what's next)
|
||||
|
||||
───────────────────────────────────────────────────────────────
|
||||
```
|
||||
</step>
|
||||
|
||||
</process>
|
||||
|
||||
<offer_next>
|
||||
After shipping:
|
||||
|
||||
- /gsd:complete-milestone — if all phases in milestone are done
|
||||
- /gsd:progress — see overall project state
|
||||
- /gsd:execute-phase {next} — continue to next phase
|
||||
</offer_next>
|
||||
|
||||
<success_criteria>
|
||||
- [ ] Preflight checks passed (verification, clean tree, branch, remote, gh)
|
||||
- [ ] Branch pushed to remote
|
||||
- [ ] PR created with rich auto-generated body
|
||||
- [ ] STATE.md updated with shipping status
|
||||
- [ ] User knows PR number and next steps
|
||||
</success_criteria>
|
||||
@@ -1,3 +1,19 @@
|
||||
<internal_workflow>
|
||||
|
||||
**This is an INTERNAL workflow — NOT a user-facing command.**
|
||||
|
||||
There is no `/gsd:transition` command. This workflow is invoked automatically by
|
||||
`execute-phase` during auto-advance, or inline by the orchestrator after phase
|
||||
verification. Users should never be told to run `/gsd:transition`.
|
||||
|
||||
**Valid user commands for phase progression:**
|
||||
- `/gsd:discuss-phase {N}` — discuss a phase before planning
|
||||
- `/gsd:plan-phase {N}` — plan a phase
|
||||
- `/gsd:execute-phase {N}` — execute a phase
|
||||
- `/gsd:progress` — see roadmap progress
|
||||
|
||||
</internal_workflow>
|
||||
|
||||
<required_reading>
|
||||
|
||||
**Read these files NOW:**
|
||||
@@ -58,6 +74,30 @@ cat .planning/config.json 2>/dev/null
|
||||
|
||||
</config-check>
|
||||
|
||||
**Check for verification debt in this phase:**
|
||||
|
||||
```bash
|
||||
# Count outstanding items in current phase
|
||||
OUTSTANDING=""
|
||||
for f in .planning/phases/XX-current/*-UAT.md .planning/phases/XX-current/*-VERIFICATION.md; do
|
||||
[ -f "$f" ] || continue
|
||||
grep -q "result: pending\|result: blocked\|status: partial\|status: human_needed\|status: diagnosed" "$f" && OUTSTANDING="$OUTSTANDING\n$(basename $f)"
|
||||
done
|
||||
```
|
||||
|
||||
**If OUTSTANDING is not empty:**
|
||||
|
||||
Append to the completion confirmation message (regardless of mode):
|
||||
|
||||
```
|
||||
Outstanding verification items in this phase:
|
||||
{list filenames}
|
||||
|
||||
These will carry forward as debt. Review: `/gsd:audit-uat`
|
||||
```
|
||||
|
||||
This does NOT block transition — it ensures the user sees the debt before confirming.
|
||||
|
||||
**If all plans complete:**
|
||||
|
||||
<if mode="yolo">
|
||||
|
||||
@@ -20,8 +20,11 @@ First, derive `PREFERRED_RUNTIME` from the invoking prompt's `execution_context`
|
||||
Use `PREFERRED_RUNTIME` as the first runtime checked so `/gsd:update` targets the runtime that invoked it.
|
||||
|
||||
```bash
|
||||
# Runtime candidates: "<runtime>:<config-dir>"
|
||||
RUNTIME_DIRS="claude:.claude opencode:.config/opencode opencode:.opencode gemini:.gemini codex:.codex"
|
||||
# Runtime candidates: "<runtime>:<config-dir>" stored as an array.
|
||||
# Using an array instead of a space-separated string ensures correct
|
||||
# iteration in both bash and zsh (zsh does not word-split unquoted
|
||||
# variables by default). Fixes #1173.
|
||||
RUNTIME_DIRS=( "claude:.claude" "opencode:.config/opencode" "opencode:.opencode" "gemini:.gemini" "codex:.codex" )
|
||||
|
||||
# PREFERRED_RUNTIME should be set from execution_context before running this block.
|
||||
# If not set, infer from runtime env vars; fallback to claude.
|
||||
@@ -40,23 +43,23 @@ if [ -z "$PREFERRED_RUNTIME" ]; then
|
||||
fi
|
||||
|
||||
# Reorder entries so preferred runtime is checked first.
|
||||
ORDERED_RUNTIME_DIRS=""
|
||||
for entry in $RUNTIME_DIRS; do
|
||||
ORDERED_RUNTIME_DIRS=()
|
||||
for entry in "${RUNTIME_DIRS[@]}"; do
|
||||
runtime="${entry%%:*}"
|
||||
if [ "$runtime" = "$PREFERRED_RUNTIME" ]; then
|
||||
ORDERED_RUNTIME_DIRS="$ORDERED_RUNTIME_DIRS $entry"
|
||||
ORDERED_RUNTIME_DIRS+=( "$entry" )
|
||||
fi
|
||||
done
|
||||
for entry in $RUNTIME_DIRS; do
|
||||
for entry in "${RUNTIME_DIRS[@]}"; do
|
||||
runtime="${entry%%:*}"
|
||||
if [ "$runtime" != "$PREFERRED_RUNTIME" ]; then
|
||||
ORDERED_RUNTIME_DIRS="$ORDERED_RUNTIME_DIRS $entry"
|
||||
ORDERED_RUNTIME_DIRS+=( "$entry" )
|
||||
fi
|
||||
done
|
||||
|
||||
# Check local first (takes priority only if valid and distinct from global)
|
||||
LOCAL_VERSION_FILE="" LOCAL_MARKER_FILE="" LOCAL_DIR="" LOCAL_RUNTIME=""
|
||||
for entry in $ORDERED_RUNTIME_DIRS; do
|
||||
for entry in "${ORDERED_RUNTIME_DIRS[@]}"; do
|
||||
runtime="${entry%%:*}"
|
||||
dir="${entry#*:}"
|
||||
if [ -f "./$dir/get-shit-done/VERSION" ] || [ -f "./$dir/get-shit-done/workflows/update.md" ]; then
|
||||
@@ -69,7 +72,7 @@ for entry in $ORDERED_RUNTIME_DIRS; do
|
||||
done
|
||||
|
||||
GLOBAL_VERSION_FILE="" GLOBAL_MARKER_FILE="" GLOBAL_DIR="" GLOBAL_RUNTIME=""
|
||||
for entry in $ORDERED_RUNTIME_DIRS; do
|
||||
for entry in "${ORDERED_RUNTIME_DIRS[@]}"; do
|
||||
runtime="${entry%%:*}"
|
||||
dir="${entry#*:}"
|
||||
if [ -f "$HOME/$dir/get-shit-done/VERSION" ] || [ -f "$HOME/$dir/get-shit-done/workflows/update.md" ]; then
|
||||
|
||||
@@ -231,6 +231,29 @@ result: skipped
|
||||
reason: [user's reason if provided]
|
||||
```
|
||||
|
||||
**If response indicates blocked:**
|
||||
- "blocked", "can't test - server not running", "need physical device", "need release build"
|
||||
- Or any response containing: "server", "blocked", "not running", "physical device", "release build"
|
||||
|
||||
Infer blocked_by tag from response:
|
||||
- Contains: server, not running, gateway, API → `server`
|
||||
- Contains: physical, device, hardware, real phone → `physical-device`
|
||||
- Contains: release, preview, build, EAS → `release-build`
|
||||
- Contains: stripe, twilio, third-party, configure → `third-party`
|
||||
- Contains: depends on, prior phase, prerequisite → `prior-phase`
|
||||
- Default: `other`
|
||||
|
||||
Update Tests section:
|
||||
```
|
||||
### {N}. {name}
|
||||
expected: {expected}
|
||||
result: blocked
|
||||
blocked_by: {inferred tag}
|
||||
reason: "{verbatim user response}"
|
||||
```
|
||||
|
||||
Note: Blocked tests do NOT go into the Gaps section (they aren't code issues — they're prerequisite gates).
|
||||
|
||||
**If response is anything else:**
|
||||
- Treat as issue description
|
||||
|
||||
@@ -293,8 +316,24 @@ Proceed to `present_test`.
|
||||
<step name="complete_session">
|
||||
**Complete testing and commit:**
|
||||
|
||||
**Determine final status:**
|
||||
|
||||
Count results:
|
||||
- `pending_count`: tests with `result: [pending]`
|
||||
- `blocked_count`: tests with `result: blocked`
|
||||
- `skipped_no_reason`: tests with `result: skipped` and no `reason` field
|
||||
|
||||
```
|
||||
if pending_count > 0 OR blocked_count > 0 OR skipped_no_reason > 0:
|
||||
status: partial
|
||||
# Session ended but not all tests resolved
|
||||
else:
|
||||
status: complete
|
||||
# All tests have a definitive result (pass, issue, or skipped-with-reason)
|
||||
```
|
||||
|
||||
Update frontmatter:
|
||||
- status: complete
|
||||
- status: {computed status}
|
||||
- updated: [now]
|
||||
|
||||
Clear Current Test section:
|
||||
|
||||
Reference in New Issue
Block a user