feat: extract repetitive bash patterns into gsd-tools commands (#472)

* feat(gsd-tools): add history-digest, atomic state operations, and summary variants

Adds new performance-focused commands to gsd-tools and introduces specialized
summary templates to reduce context tax:

- history-digest: Compiles phase summaries into structured JSON for JIT loading
- state get/patch: Enables atomic STATE.md operations instead of full rewrites
- template select: Automatically chooses optimal summary template based on plan complexity
- Adds minimal, standard, and complex summary templates

Part of the "Hydra" architecture for GSD context optimization.

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* chore: add project config

* docs: define v1 requirements

* docs: create roadmap (6 phases)

* feat(history-digest): fix nested YAML parsing and add tests

- Fix extractFrontmatter() to handle nested YAML structures like
  dependency-graph.provides, tech-stack.added using stack-based parsing
- Add test infrastructure with Node test runner (npm test)
- Update gsd-planner to use digest fields directly instead of reading
  full SUMMARY.md files
- Add 6 schema validation tests covering nested fields, merging,
  malformed files, and backward compatibility

Closes: HIST-01, HIST-02, HIST-03, HIST-04

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* fix(planner): use digest for selection, full SUMMARY for understanding

The previous commit went too far by eliminating full SUMMARY reads.
The digest is an index for smart selection, not a replacement for
understanding what actually happened.

Two-step approach:
1. Digest to score/select relevant phases (2-4 typically)
2. Full SUMMARY read for selected phases (implementation details)
3. Digest-level context retained for unselected phases

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* feat(gsd-tools): add phases, roadmap, and phase commands

TDD implementation of three new commands to replace repetitive bash:

phases list [--type plans|summaries] [--phase N]
- Lists phase directories sorted numerically (handles decimals)
- Filter by file type or specific phase
- Replaces: ls -d .planning/phases/*/ | sort -V (22 occurrences)

roadmap get-phase <N>
- Extracts phase section from ROADMAP.md
- Returns name, goal, full section content
- Replaces: grep -A20 "Phase X:" ROADMAP.md (19 occurrences)

phase next-decimal <N>
- Calculates next decimal phase (06 → 06.1, 06.2 → 06.3)
- Handles gaps, normalizes input
- Replaces: complex bash math in insert-phase (3 occurrences)

16 new tests, all passing.

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* refactor: migrate agents/workflows to use gsd-tools commands

Replace inline bash patterns with centralized gsd-tools commands:

phases list:
- audit-milestone.md: ls -d .planning/phases/*/ | sort -V
- plan-milestone-gaps.md: ls -d ... | sort -V | tail -1

roadmap get-phase:
- plan-phase.md: grep -A5 "Phase X:" ROADMAP.md (2 occurrences)
- research-phase.md: grep patterns (2 occurrences)
- verify-phase.md: grep -A5 pattern
- gsd-verifier.md: grep -A5 pattern
- gsd-plan-checker.md: grep -A10 pattern
- commands/gsd/research-phase.md: grep patterns (2 occurrences)

phase next-decimal:
- insert-phase.md: complex bash decimal calculation
- decimal-phase-calculation.md: reference doc rewritten

phase-argument-parsing.md: updated to reference gsd-tools

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.5 <noreply@anthropic.com>
This commit is contained in:
TÂCHES
2026-02-08 00:44:49 -06:00
committed by GitHub
parent 3f5ab10713
commit 1b317dec45
29 changed files with 2938 additions and 84 deletions

View File

@@ -146,6 +146,81 @@ function normalizePhaseName(phase) {
return parts.length > 1 ? `${padded}.${parts[1]}` : padded;
}
function extractFrontmatter(content) {
const frontmatter = {};
const match = content.match(/^---\n([\s\S]+?)\n---/);
if (!match) return frontmatter;
const yaml = match[1];
const lines = yaml.split('\n');
// Stack to track nested objects: [{obj, key, indent}]
// obj = object to write to, key = current key collecting array items, indent = indentation level
let stack = [{ obj: frontmatter, key: null, indent: -1 }];
for (const line of lines) {
// Skip empty lines
if (line.trim() === '') continue;
// Calculate indentation (number of leading spaces)
const indentMatch = line.match(/^(\s*)/);
const indent = indentMatch ? indentMatch[1].length : 0;
// Pop stack back to appropriate level
while (stack.length > 1 && indent <= stack[stack.length - 1].indent) {
stack.pop();
}
const current = stack[stack.length - 1];
// Check for key: value pattern
const keyMatch = line.match(/^(\s*)([a-zA-Z0-9_-]+):\s*(.*)/);
if (keyMatch) {
const key = keyMatch[2];
const value = keyMatch[3].trim();
if (value === '' || value === '[') {
// Key with no value or opening bracket — could be nested object or array
// We'll determine based on next lines, for now create placeholder
current.obj[key] = value === '[' ? [] : {};
current.key = null;
// Push new context for potential nested content
stack.push({ obj: current.obj[key], key: null, indent });
} else if (value.startsWith('[') && value.endsWith(']')) {
// Inline array: key: [a, b, c]
current.obj[key] = value.slice(1, -1).split(',').map(s => s.trim().replace(/^["']|["']$/g, '')).filter(Boolean);
current.key = null;
} else {
// Simple key: value
current.obj[key] = value.replace(/^["']|["']$/g, '');
current.key = null;
}
} else if (line.trim().startsWith('- ')) {
// Array item
const itemValue = line.trim().slice(2).replace(/^["']|["']$/g, '');
// If current context is an empty object, convert to array
if (typeof current.obj === 'object' && !Array.isArray(current.obj) && Object.keys(current.obj).length === 0) {
// Find the key in parent that points to this object and convert it
const parent = stack.length > 1 ? stack[stack.length - 2] : null;
if (parent) {
for (const k of Object.keys(parent.obj)) {
if (parent.obj[k] === current.obj) {
parent.obj[k] = [itemValue];
current.obj = parent.obj[k];
break;
}
}
}
} else if (Array.isArray(current.obj)) {
current.obj.push(itemValue);
}
}
}
return frontmatter;
}
function output(result, raw, rawValue) {
if (raw && rawValue !== undefined) {
process.stdout.write(String(rawValue));
@@ -296,6 +371,290 @@ function cmdConfigEnsureSection(cwd, raw) {
}
}
function cmdHistoryDigest(cwd, raw) {
const phasesDir = path.join(cwd, '.planning', 'phases');
const digest = { phases: {}, decisions: [], tech_stack: new Set() };
if (!fs.existsSync(phasesDir)) {
digest.tech_stack = [];
output(digest, raw);
return;
}
try {
const phaseDirs = fs.readdirSync(phasesDir, { withFileTypes: true })
.filter(e => e.isDirectory())
.map(e => e.name)
.sort();
for (const dir of phaseDirs) {
const dirPath = path.join(phasesDir, dir);
const summaries = fs.readdirSync(dirPath).filter(f => f.endsWith('-SUMMARY.md') || f === 'SUMMARY.md');
for (const summary of summaries) {
try {
const content = fs.readFileSync(path.join(dirPath, summary), 'utf-8');
const fm = extractFrontmatter(content);
const phaseNum = fm.phase || dir.split('-')[0];
if (!digest.phases[phaseNum]) {
digest.phases[phaseNum] = {
name: fm.name || dir.split('-').slice(1).join(' ') || 'Unknown',
provides: new Set(),
affects: new Set(),
patterns: new Set(),
};
}
// Merge provides
if (fm['dependency-graph'] && fm['dependency-graph'].provides) {
fm['dependency-graph'].provides.forEach(p => digest.phases[phaseNum].provides.add(p));
} else if (fm.provides) {
fm.provides.forEach(p => digest.phases[phaseNum].provides.add(p));
}
// Merge affects
if (fm['dependency-graph'] && fm['dependency-graph'].affects) {
fm['dependency-graph'].affects.forEach(a => digest.phases[phaseNum].affects.add(a));
}
// Merge patterns
if (fm['patterns-established']) {
fm['patterns-established'].forEach(p => digest.phases[phaseNum].patterns.add(p));
}
// Merge decisions
if (fm['key-decisions']) {
fm['key-decisions'].forEach(d => {
digest.decisions.push({ phase: phaseNum, decision: d });
});
}
// Merge tech stack
if (fm['tech-stack'] && fm['tech-stack'].added) {
fm['tech-stack'].added.forEach(t => digest.tech_stack.add(typeof t === 'string' ? t : t.name));
}
} catch (e) {
// Skip malformed summaries
}
}
}
// Convert Sets to Arrays for JSON output
Object.keys(digest.phases).forEach(p => {
digest.phases[p].provides = [...digest.phases[p].provides];
digest.phases[p].affects = [...digest.phases[p].affects];
digest.phases[p].patterns = [...digest.phases[p].patterns];
});
digest.tech_stack = [...digest.tech_stack];
output(digest, raw);
} catch (e) {
error('Failed to generate history digest: ' + e.message);
}
}
function cmdPhasesList(cwd, options, raw) {
const phasesDir = path.join(cwd, '.planning', 'phases');
const { type, phase } = options;
// If no phases directory, return empty
if (!fs.existsSync(phasesDir)) {
if (type) {
output({ files: [], count: 0 }, raw, '');
} else {
output({ directories: [], count: 0 }, raw, '');
}
return;
}
try {
// Get all phase directories
const entries = fs.readdirSync(phasesDir, { withFileTypes: true });
let dirs = entries.filter(e => e.isDirectory()).map(e => e.name);
// Sort numerically (handles decimals: 01, 02, 02.1, 02.2, 03)
dirs.sort((a, b) => {
const aNum = parseFloat(a.match(/^(\d+(?:\.\d+)?)/)?.[1] || '0');
const bNum = parseFloat(b.match(/^(\d+(?:\.\d+)?)/)?.[1] || '0');
return aNum - bNum;
});
// If filtering by phase number
if (phase) {
const normalized = normalizePhaseName(phase);
const match = dirs.find(d => d.startsWith(normalized));
if (!match) {
output({ files: [], count: 0, phase_dir: null, error: 'Phase not found' }, raw, '');
return;
}
dirs = [match];
}
// If listing files of a specific type
if (type) {
const files = [];
for (const dir of dirs) {
const dirPath = path.join(phasesDir, dir);
const dirFiles = fs.readdirSync(dirPath);
let filtered;
if (type === 'plans') {
filtered = dirFiles.filter(f => f.endsWith('-PLAN.md') || f === 'PLAN.md');
} else if (type === 'summaries') {
filtered = dirFiles.filter(f => f.endsWith('-SUMMARY.md') || f === 'SUMMARY.md');
} else {
filtered = dirFiles;
}
files.push(...filtered.sort());
}
const result = {
files,
count: files.length,
phase_dir: phase ? dirs[0].replace(/^\d+(?:\.\d+)?-?/, '') : null,
};
output(result, raw, files.join('\n'));
return;
}
// Default: list directories
output({ directories: dirs, count: dirs.length }, raw, dirs.join('\n'));
} catch (e) {
error('Failed to list phases: ' + e.message);
}
}
function cmdRoadmapGetPhase(cwd, phaseNum, raw) {
const roadmapPath = path.join(cwd, '.planning', 'ROADMAP.md');
if (!fs.existsSync(roadmapPath)) {
output({ found: false, error: 'ROADMAP.md not found' }, raw, '');
return;
}
try {
const content = fs.readFileSync(roadmapPath, 'utf-8');
// Escape special regex chars in phase number, handle decimal
const escapedPhase = phaseNum.replace(/\./g, '\\.');
// Match "### Phase X:" or "### Phase X.Y:" with optional name
const phasePattern = new RegExp(
`###\\s*Phase\\s+${escapedPhase}:\\s*([^\\n]+)`,
'i'
);
const headerMatch = content.match(phasePattern);
if (!headerMatch) {
output({ found: false, phase_number: phaseNum }, raw, '');
return;
}
const phaseName = headerMatch[1].trim();
const headerIndex = headerMatch.index;
// Find the end of this section (next ### or end of file)
const restOfContent = content.slice(headerIndex);
const nextHeaderMatch = restOfContent.match(/\n###\s+Phase\s+\d/i);
const sectionEnd = nextHeaderMatch
? headerIndex + nextHeaderMatch.index
: content.length;
const section = content.slice(headerIndex, sectionEnd).trim();
// Extract goal if present
const goalMatch = section.match(/\*\*Goal:\*\*\s*([^\n]+)/i);
const goal = goalMatch ? goalMatch[1].trim() : null;
output(
{
found: true,
phase_number: phaseNum,
phase_name: phaseName,
goal,
section,
},
raw,
section
);
} catch (e) {
error('Failed to read ROADMAP.md: ' + e.message);
}
}
function cmdPhaseNextDecimal(cwd, basePhase, raw) {
const phasesDir = path.join(cwd, '.planning', 'phases');
const normalized = normalizePhaseName(basePhase);
// Check if phases directory exists
if (!fs.existsSync(phasesDir)) {
output(
{
found: false,
base_phase: normalized,
next: `${normalized}.1`,
existing: [],
},
raw,
`${normalized}.1`
);
return;
}
try {
const entries = fs.readdirSync(phasesDir, { withFileTypes: true });
const dirs = entries.filter(e => e.isDirectory()).map(e => e.name);
// Check if base phase exists
const baseExists = dirs.some(d => d.startsWith(normalized + '-') || d === normalized);
// Find existing decimal phases for this base
const decimalPattern = new RegExp(`^${normalized}\\.(\\d+)`);
const existingDecimals = [];
for (const dir of dirs) {
const match = dir.match(decimalPattern);
if (match) {
existingDecimals.push(`${normalized}.${match[1]}`);
}
}
// Sort numerically
existingDecimals.sort((a, b) => {
const aNum = parseFloat(a);
const bNum = parseFloat(b);
return aNum - bNum;
});
// Calculate next decimal
let nextDecimal;
if (existingDecimals.length === 0) {
nextDecimal = `${normalized}.1`;
} else {
const lastDecimal = existingDecimals[existingDecimals.length - 1];
const lastNum = parseInt(lastDecimal.split('.')[1], 10);
nextDecimal = `${normalized}.${lastNum + 1}`;
}
output(
{
found: baseExists,
base_phase: normalized,
next: nextDecimal,
existing: existingDecimals,
},
raw,
nextDecimal
);
} catch (e) {
error('Failed to calculate next decimal phase: ' + e.message);
}
}
function cmdStateLoad(cwd, raw) {
const config = loadConfig(cwd);
const planningDir = path.join(cwd, '.planning');
@@ -341,6 +700,69 @@ function cmdStateLoad(cwd, raw) {
output(result);
}
function cmdStateGet(cwd, section, raw) {
const statePath = path.join(cwd, '.planning', 'STATE.md');
try {
const content = fs.readFileSync(statePath, 'utf-8');
if (!section) {
output({ content }, raw, content);
return;
}
// Try to find markdown section or field
const fieldEscaped = section.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
// Check for **field:** value
const fieldPattern = new RegExp(`\\*\\*${fieldEscaped}:\\*\\*\\s*(.*)`, 'i');
const fieldMatch = content.match(fieldPattern);
if (fieldMatch) {
output({ [section]: fieldMatch[1].trim() }, raw, fieldMatch[1].trim());
return;
}
// Check for ## Section
const sectionPattern = new RegExp(`##\\s*${fieldEscaped}\\s*\n([\\s\\S]*?)(?=\\n##|$)`, 'i');
const sectionMatch = content.match(sectionPattern);
if (sectionMatch) {
output({ [section]: sectionMatch[1].trim() }, raw, sectionMatch[1].trim());
return;
}
output({ error: `Section or field "${section}" not found` }, raw, '');
} catch {
error('STATE.md not found');
}
}
function cmdStatePatch(cwd, patches, raw) {
const statePath = path.join(cwd, '.planning', 'STATE.md');
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 pattern = new RegExp(`(\\*\\*${fieldEscaped}:\\*\\*\\s*)(.*)`, 'i');
if (pattern.test(content)) {
content = content.replace(pattern, `$1${value}`);
results.updated.push(field);
} else {
results.failed.push(field);
}
}
if (results.updated.length > 0) {
fs.writeFileSync(statePath, content, 'utf-8');
}
output(results, raw, results.updated.length > 0 ? 'true' : 'false');
} catch {
error('STATE.md not found');
}
}
function cmdStateUpdate(cwd, field, value) {
if (!field || value === undefined) {
error('field and value required for state update');
@@ -570,6 +992,52 @@ function cmdVerifySummary(cwd, summaryPath, checkFileCount, raw) {
output(result, raw, passed ? 'passed' : 'failed');
}
function cmdTemplateSelect(cwd, planPath, raw) {
if (!planPath) {
error('plan-path required');
}
try {
const fullPath = path.join(cwd, planPath);
const content = fs.readFileSync(fullPath, 'utf-8');
// Simple heuristics
const taskMatch = content.match(/###\s*Task\s*\d+/g) || [];
const taskCount = taskMatch.length;
const decisionMatch = content.match(/decision/gi) || [];
const hasDecisions = decisionMatch.length > 0;
// Count file mentions
const fileMentions = new Set();
const filePattern = /`([^`]+\.[a-zA-Z]+)`/g;
let m;
while ((m = filePattern.exec(content)) !== null) {
if (m[1].includes('/') && !m[1].startsWith('http')) {
fileMentions.add(m[1]);
}
}
const fileCount = fileMentions.size;
let template = 'templates/summary-standard.md';
let type = 'standard';
if (taskCount <= 2 && fileCount <= 3 && !hasDecisions) {
template = 'templates/summary-minimal.md';
type = 'minimal';
} else if (hasDecisions || fileCount > 6 || taskCount > 5) {
template = 'templates/summary-complex.md';
type = 'complex';
}
const result = { template, type, taskCount, fileCount, hasDecisions };
output(result, raw, template);
} catch (e) {
// Fallback to standard
output({ template: 'templates/summary-standard.md', type: 'standard', error: e.message }, raw, 'templates/summary-standard.md');
}
}
// ─── Compound Commands ────────────────────────────────────────────────────────
function resolveModelInternal(cwd, agentType) {
@@ -1238,6 +1706,18 @@ function main() {
const subcommand = args[1];
if (subcommand === 'update') {
cmdStateUpdate(cwd, args[2], args[3]);
} else if (subcommand === 'get') {
cmdStateGet(cwd, args[2], raw);
} else if (subcommand === 'patch') {
const patches = {};
for (let i = 2; i < args.length; i += 2) {
const key = args[i].replace(/^--/, '');
const value = args[i + 1];
if (key && value !== undefined) {
patches[key] = value;
}
}
cmdStatePatch(cwd, patches, raw);
} else {
cmdStateLoad(cwd, raw);
}
@@ -1271,6 +1751,14 @@ function main() {
break;
}
case 'template': {
const subcommand = args[1];
if (subcommand === 'select') {
cmdTemplateSelect(cwd, args[2], raw);
}
break;
}
case 'generate-slug': {
cmdGenerateSlug(args[1], raw);
break;
@@ -1296,6 +1784,47 @@ function main() {
break;
}
case 'history-digest': {
cmdHistoryDigest(cwd, raw);
break;
}
case 'phases': {
const subcommand = args[1];
if (subcommand === 'list') {
const typeIndex = args.indexOf('--type');
const phaseIndex = args.indexOf('--phase');
const options = {
type: typeIndex !== -1 ? args[typeIndex + 1] : null,
phase: phaseIndex !== -1 ? args[phaseIndex + 1] : null,
};
cmdPhasesList(cwd, options, raw);
} else {
error('Unknown phases subcommand. Available: list');
}
break;
}
case 'roadmap': {
const subcommand = args[1];
if (subcommand === 'get-phase') {
cmdRoadmapGetPhase(cwd, args[2], raw);
} else {
error('Unknown roadmap subcommand. Available: get-phase');
}
break;
}
case 'phase': {
const subcommand = args[1];
if (subcommand === 'next-decimal') {
cmdPhaseNextDecimal(cwd, args[2], raw);
} else {
error('Unknown phase subcommand. Available: next-decimal');
}
break;
}
case 'init': {
const workflow = args[1];
switch (workflow) {

View File

@@ -0,0 +1,599 @@
/**
* GSD Tools Tests — Schema validation for history-digest command
*/
const { test, describe, beforeEach, afterEach } = require('node:test');
const assert = require('node:assert');
const fs = require('fs');
const path = require('path');
const { execSync } = require('child_process');
const TOOLS_PATH = path.join(__dirname, 'gsd-tools.js');
// Helper to run gsd-tools command
function runGsdTools(args, cwd = process.cwd()) {
try {
const result = execSync(`node "${TOOLS_PATH}" ${args}`, {
cwd,
encoding: 'utf-8',
stdio: ['pipe', 'pipe', 'pipe'],
});
return { success: true, output: result.trim() };
} catch (err) {
return {
success: false,
output: err.stdout?.toString().trim() || '',
error: err.stderr?.toString().trim() || err.message,
};
}
}
// Create temp directory structure
function createTempProject() {
const tmpDir = fs.mkdtempSync(path.join(require('os').tmpdir(), 'gsd-test-'));
fs.mkdirSync(path.join(tmpDir, '.planning', 'phases'), { recursive: true });
return tmpDir;
}
function cleanup(tmpDir) {
fs.rmSync(tmpDir, { recursive: true, force: true });
}
describe('history-digest command', () => {
let tmpDir;
beforeEach(() => {
tmpDir = createTempProject();
});
afterEach(() => {
cleanup(tmpDir);
});
test('empty phases directory returns valid schema', () => {
const result = runGsdTools('history-digest', tmpDir);
assert.ok(result.success, `Command failed: ${result.error}`);
const digest = JSON.parse(result.output);
assert.deepStrictEqual(digest.phases, {}, 'phases should be empty object');
assert.deepStrictEqual(digest.decisions, [], 'decisions should be empty array');
assert.deepStrictEqual(digest.tech_stack, [], 'tech_stack should be empty array');
});
test('nested frontmatter fields extracted correctly', () => {
// Create phase directory with SUMMARY containing nested frontmatter
const phaseDir = path.join(tmpDir, '.planning', 'phases', '01-foundation');
fs.mkdirSync(phaseDir, { recursive: true });
const summaryContent = `---
phase: "01"
name: "Foundation Setup"
dependency-graph:
provides:
- "Database schema"
- "Auth system"
affects:
- "API layer"
tech-stack:
added:
- "prisma"
- "jose"
patterns-established:
- "Repository pattern"
- "JWT auth flow"
key-decisions:
- "Use Prisma over Drizzle"
- "JWT in httpOnly cookies"
---
# Summary content here
`;
fs.writeFileSync(path.join(phaseDir, '01-01-SUMMARY.md'), summaryContent);
const result = runGsdTools('history-digest', tmpDir);
assert.ok(result.success, `Command failed: ${result.error}`);
const digest = JSON.parse(result.output);
// Check nested dependency-graph.provides
assert.ok(digest.phases['01'], 'Phase 01 should exist');
assert.deepStrictEqual(
digest.phases['01'].provides.sort(),
['Auth system', 'Database schema'],
'provides should contain nested values'
);
// Check nested dependency-graph.affects
assert.deepStrictEqual(
digest.phases['01'].affects,
['API layer'],
'affects should contain nested values'
);
// Check nested tech-stack.added
assert.deepStrictEqual(
digest.tech_stack.sort(),
['jose', 'prisma'],
'tech_stack should contain nested values'
);
// Check patterns-established (flat array)
assert.deepStrictEqual(
digest.phases['01'].patterns.sort(),
['JWT auth flow', 'Repository pattern'],
'patterns should be extracted'
);
// Check key-decisions
assert.strictEqual(digest.decisions.length, 2, 'Should have 2 decisions');
assert.ok(
digest.decisions.some(d => d.decision === 'Use Prisma over Drizzle'),
'Should contain first decision'
);
});
test('multiple phases merged into single digest', () => {
// Create phase 01
const phase01Dir = path.join(tmpDir, '.planning', 'phases', '01-foundation');
fs.mkdirSync(phase01Dir, { recursive: true });
fs.writeFileSync(
path.join(phase01Dir, '01-01-SUMMARY.md'),
`---
phase: "01"
name: "Foundation"
provides:
- "Database"
patterns-established:
- "Pattern A"
key-decisions:
- "Decision 1"
---
`
);
// Create phase 02
const phase02Dir = path.join(tmpDir, '.planning', 'phases', '02-api');
fs.mkdirSync(phase02Dir, { recursive: true });
fs.writeFileSync(
path.join(phase02Dir, '02-01-SUMMARY.md'),
`---
phase: "02"
name: "API"
provides:
- "REST endpoints"
patterns-established:
- "Pattern B"
key-decisions:
- "Decision 2"
tech-stack:
added:
- "zod"
---
`
);
const result = runGsdTools('history-digest', tmpDir);
assert.ok(result.success, `Command failed: ${result.error}`);
const digest = JSON.parse(result.output);
// Both phases present
assert.ok(digest.phases['01'], 'Phase 01 should exist');
assert.ok(digest.phases['02'], 'Phase 02 should exist');
// Decisions merged
assert.strictEqual(digest.decisions.length, 2, 'Should have 2 decisions total');
// Tech stack merged
assert.deepStrictEqual(digest.tech_stack, ['zod'], 'tech_stack should have zod');
});
test('malformed SUMMARY.md skipped gracefully', () => {
const phaseDir = path.join(tmpDir, '.planning', 'phases', '01-test');
fs.mkdirSync(phaseDir, { recursive: true });
// Valid summary
fs.writeFileSync(
path.join(phaseDir, '01-01-SUMMARY.md'),
`---
phase: "01"
provides:
- "Valid feature"
---
`
);
// Malformed summary (no frontmatter)
fs.writeFileSync(
path.join(phaseDir, '01-02-SUMMARY.md'),
`# Just a heading
No frontmatter here
`
);
// Another malformed summary (broken YAML)
fs.writeFileSync(
path.join(phaseDir, '01-03-SUMMARY.md'),
`---
broken: [unclosed
---
`
);
const result = runGsdTools('history-digest', tmpDir);
assert.ok(result.success, `Command should succeed despite malformed files: ${result.error}`);
const digest = JSON.parse(result.output);
assert.ok(digest.phases['01'], 'Phase 01 should exist');
assert.ok(
digest.phases['01'].provides.includes('Valid feature'),
'Valid feature should be extracted'
);
});
test('flat provides field still works (backward compatibility)', () => {
const phaseDir = path.join(tmpDir, '.planning', 'phases', '01-test');
fs.mkdirSync(phaseDir, { recursive: true });
fs.writeFileSync(
path.join(phaseDir, '01-01-SUMMARY.md'),
`---
phase: "01"
provides:
- "Direct provides"
---
`
);
const result = runGsdTools('history-digest', tmpDir);
assert.ok(result.success, `Command failed: ${result.error}`);
const digest = JSON.parse(result.output);
assert.deepStrictEqual(
digest.phases['01'].provides,
['Direct provides'],
'Direct provides should work'
);
});
test('inline array syntax supported', () => {
const phaseDir = path.join(tmpDir, '.planning', 'phases', '01-test');
fs.mkdirSync(phaseDir, { recursive: true });
fs.writeFileSync(
path.join(phaseDir, '01-01-SUMMARY.md'),
`---
phase: "01"
provides: [Feature A, Feature B]
patterns-established: ["Pattern X", "Pattern Y"]
---
`
);
const result = runGsdTools('history-digest', tmpDir);
assert.ok(result.success, `Command failed: ${result.error}`);
const digest = JSON.parse(result.output);
assert.deepStrictEqual(
digest.phases['01'].provides.sort(),
['Feature A', 'Feature B'],
'Inline array should work'
);
assert.deepStrictEqual(
digest.phases['01'].patterns.sort(),
['Pattern X', 'Pattern Y'],
'Inline quoted array should work'
);
});
});
// ─────────────────────────────────────────────────────────────────────────────
// phases list command
// ─────────────────────────────────────────────────────────────────────────────
describe('phases list command', () => {
let tmpDir;
beforeEach(() => {
tmpDir = createTempProject();
});
afterEach(() => {
cleanup(tmpDir);
});
test('empty phases directory returns empty array', () => {
const result = runGsdTools('phases list', tmpDir);
assert.ok(result.success, `Command failed: ${result.error}`);
const output = JSON.parse(result.output);
assert.deepStrictEqual(output.directories, [], 'directories should be empty');
assert.strictEqual(output.count, 0, 'count should be 0');
});
test('lists phase directories sorted numerically', () => {
// Create out-of-order directories
fs.mkdirSync(path.join(tmpDir, '.planning', 'phases', '10-final'), { recursive: true });
fs.mkdirSync(path.join(tmpDir, '.planning', 'phases', '02-api'), { recursive: true });
fs.mkdirSync(path.join(tmpDir, '.planning', 'phases', '01-foundation'), { recursive: true });
const result = runGsdTools('phases list', tmpDir);
assert.ok(result.success, `Command failed: ${result.error}`);
const output = JSON.parse(result.output);
assert.strictEqual(output.count, 3, 'should have 3 directories');
assert.deepStrictEqual(
output.directories,
['01-foundation', '02-api', '10-final'],
'should be sorted numerically'
);
});
test('handles decimal phases in sort order', () => {
fs.mkdirSync(path.join(tmpDir, '.planning', 'phases', '02-api'), { recursive: true });
fs.mkdirSync(path.join(tmpDir, '.planning', 'phases', '02.1-hotfix'), { recursive: true });
fs.mkdirSync(path.join(tmpDir, '.planning', 'phases', '02.2-patch'), { recursive: true });
fs.mkdirSync(path.join(tmpDir, '.planning', 'phases', '03-ui'), { recursive: true });
const result = runGsdTools('phases list', tmpDir);
assert.ok(result.success, `Command failed: ${result.error}`);
const output = JSON.parse(result.output);
assert.deepStrictEqual(
output.directories,
['02-api', '02.1-hotfix', '02.2-patch', '03-ui'],
'decimal phases should sort correctly between whole numbers'
);
});
test('--type plans lists only PLAN.md files', () => {
const phaseDir = path.join(tmpDir, '.planning', 'phases', '01-test');
fs.mkdirSync(phaseDir, { recursive: true });
fs.writeFileSync(path.join(phaseDir, '01-01-PLAN.md'), '# Plan 1');
fs.writeFileSync(path.join(phaseDir, '01-02-PLAN.md'), '# Plan 2');
fs.writeFileSync(path.join(phaseDir, '01-01-SUMMARY.md'), '# Summary');
fs.writeFileSync(path.join(phaseDir, 'RESEARCH.md'), '# Research');
const result = runGsdTools('phases list --type plans', tmpDir);
assert.ok(result.success, `Command failed: ${result.error}`);
const output = JSON.parse(result.output);
assert.deepStrictEqual(
output.files.sort(),
['01-01-PLAN.md', '01-02-PLAN.md'],
'should list only PLAN files'
);
});
test('--type summaries lists only SUMMARY.md files', () => {
const phaseDir = path.join(tmpDir, '.planning', 'phases', '01-test');
fs.mkdirSync(phaseDir, { recursive: true });
fs.writeFileSync(path.join(phaseDir, '01-01-PLAN.md'), '# Plan');
fs.writeFileSync(path.join(phaseDir, '01-01-SUMMARY.md'), '# Summary 1');
fs.writeFileSync(path.join(phaseDir, '01-02-SUMMARY.md'), '# Summary 2');
const result = runGsdTools('phases list --type summaries', tmpDir);
assert.ok(result.success, `Command failed: ${result.error}`);
const output = JSON.parse(result.output);
assert.deepStrictEqual(
output.files.sort(),
['01-01-SUMMARY.md', '01-02-SUMMARY.md'],
'should list only SUMMARY files'
);
});
test('--phase filters to specific phase directory', () => {
const phase01 = path.join(tmpDir, '.planning', 'phases', '01-foundation');
const phase02 = path.join(tmpDir, '.planning', 'phases', '02-api');
fs.mkdirSync(phase01, { recursive: true });
fs.mkdirSync(phase02, { recursive: true });
fs.writeFileSync(path.join(phase01, '01-01-PLAN.md'), '# Plan');
fs.writeFileSync(path.join(phase02, '02-01-PLAN.md'), '# Plan');
const result = runGsdTools('phases list --type plans --phase 01', tmpDir);
assert.ok(result.success, `Command failed: ${result.error}`);
const output = JSON.parse(result.output);
assert.deepStrictEqual(output.files, ['01-01-PLAN.md'], 'should only list phase 01 plans');
assert.strictEqual(output.phase_dir, 'foundation', 'should report phase name without number prefix');
});
});
// ─────────────────────────────────────────────────────────────────────────────
// roadmap get-phase command
// ─────────────────────────────────────────────────────────────────────────────
describe('roadmap get-phase command', () => {
let tmpDir;
beforeEach(() => {
tmpDir = createTempProject();
});
afterEach(() => {
cleanup(tmpDir);
});
test('extracts phase section from ROADMAP.md', () => {
fs.writeFileSync(
path.join(tmpDir, '.planning', 'ROADMAP.md'),
`# Roadmap v1.0
## Phases
### Phase 1: Foundation
**Goal:** Set up project infrastructure
**Plans:** 2 plans
Some description here.
### Phase 2: API
**Goal:** Build REST API
**Plans:** 3 plans
`
);
const result = runGsdTools('roadmap get-phase 1', tmpDir);
assert.ok(result.success, `Command failed: ${result.error}`);
const output = JSON.parse(result.output);
assert.strictEqual(output.found, true, 'phase should be found');
assert.strictEqual(output.phase_number, '1', 'phase number correct');
assert.strictEqual(output.phase_name, 'Foundation', 'phase name extracted');
assert.strictEqual(output.goal, 'Set up project infrastructure', 'goal extracted');
});
test('returns not found for missing phase', () => {
fs.writeFileSync(
path.join(tmpDir, '.planning', 'ROADMAP.md'),
`# Roadmap v1.0
### Phase 1: Foundation
**Goal:** Set up project
`
);
const result = runGsdTools('roadmap get-phase 5', tmpDir);
assert.ok(result.success, `Command failed: ${result.error}`);
const output = JSON.parse(result.output);
assert.strictEqual(output.found, false, 'phase should not be found');
});
test('handles decimal phase numbers', () => {
fs.writeFileSync(
path.join(tmpDir, '.planning', 'ROADMAP.md'),
`# Roadmap
### Phase 2: Main
**Goal:** Main work
### Phase 2.1: Hotfix
**Goal:** Emergency fix
`
);
const result = runGsdTools('roadmap get-phase 2.1', tmpDir);
assert.ok(result.success, `Command failed: ${result.error}`);
const output = JSON.parse(result.output);
assert.strictEqual(output.found, true, 'decimal phase should be found');
assert.strictEqual(output.phase_name, 'Hotfix', 'phase name correct');
assert.strictEqual(output.goal, 'Emergency fix', 'goal extracted');
});
test('extracts full section content', () => {
fs.writeFileSync(
path.join(tmpDir, '.planning', 'ROADMAP.md'),
`# Roadmap
### Phase 1: Setup
**Goal:** Initialize everything
This phase covers:
- Database setup
- Auth configuration
- CI/CD pipeline
### Phase 2: Build
**Goal:** Build features
`
);
const result = runGsdTools('roadmap get-phase 1', tmpDir);
assert.ok(result.success, `Command failed: ${result.error}`);
const output = JSON.parse(result.output);
assert.ok(output.section.includes('Database setup'), 'section includes description');
assert.ok(output.section.includes('CI/CD pipeline'), 'section includes all bullets');
assert.ok(!output.section.includes('Phase 2'), 'section does not include next phase');
});
test('handles missing ROADMAP.md gracefully', () => {
const result = runGsdTools('roadmap get-phase 1', tmpDir);
assert.ok(result.success, `Command failed: ${result.error}`);
const output = JSON.parse(result.output);
assert.strictEqual(output.found, false, 'should return not found');
assert.strictEqual(output.error, 'ROADMAP.md not found', 'should explain why');
});
});
// ─────────────────────────────────────────────────────────────────────────────
// phase next-decimal command
// ─────────────────────────────────────────────────────────────────────────────
describe('phase next-decimal command', () => {
let tmpDir;
beforeEach(() => {
tmpDir = createTempProject();
});
afterEach(() => {
cleanup(tmpDir);
});
test('returns X.1 when no decimal phases exist', () => {
fs.mkdirSync(path.join(tmpDir, '.planning', 'phases', '06-feature'), { recursive: true });
fs.mkdirSync(path.join(tmpDir, '.planning', 'phases', '07-next'), { recursive: true });
const result = runGsdTools('phase next-decimal 06', tmpDir);
assert.ok(result.success, `Command failed: ${result.error}`);
const output = JSON.parse(result.output);
assert.strictEqual(output.next, '06.1', 'should return 06.1');
assert.deepStrictEqual(output.existing, [], 'no existing decimals');
});
test('increments from existing decimal phases', () => {
fs.mkdirSync(path.join(tmpDir, '.planning', 'phases', '06-feature'), { recursive: true });
fs.mkdirSync(path.join(tmpDir, '.planning', 'phases', '06.1-hotfix'), { recursive: true });
fs.mkdirSync(path.join(tmpDir, '.planning', 'phases', '06.2-patch'), { recursive: true });
const result = runGsdTools('phase next-decimal 06', tmpDir);
assert.ok(result.success, `Command failed: ${result.error}`);
const output = JSON.parse(result.output);
assert.strictEqual(output.next, '06.3', 'should return 06.3');
assert.deepStrictEqual(output.existing, ['06.1', '06.2'], 'lists existing decimals');
});
test('handles gaps in decimal sequence', () => {
fs.mkdirSync(path.join(tmpDir, '.planning', 'phases', '06-feature'), { recursive: true });
fs.mkdirSync(path.join(tmpDir, '.planning', 'phases', '06.1-first'), { recursive: true });
fs.mkdirSync(path.join(tmpDir, '.planning', 'phases', '06.3-third'), { recursive: true });
const result = runGsdTools('phase next-decimal 06', tmpDir);
assert.ok(result.success, `Command failed: ${result.error}`);
const output = JSON.parse(result.output);
// Should take next after highest, not fill gap
assert.strictEqual(output.next, '06.4', 'should return 06.4, not fill gap at 06.2');
});
test('handles single-digit phase input', () => {
fs.mkdirSync(path.join(tmpDir, '.planning', 'phases', '06-feature'), { recursive: true });
const result = runGsdTools('phase next-decimal 6', tmpDir);
assert.ok(result.success, `Command failed: ${result.error}`);
const output = JSON.parse(result.output);
assert.strictEqual(output.next, '06.1', 'should normalize to 06.1');
assert.strictEqual(output.base_phase, '06', 'base phase should be padded');
});
test('returns error if base phase does not exist', () => {
fs.mkdirSync(path.join(tmpDir, '.planning', 'phases', '01-start'), { recursive: true });
const result = runGsdTools('phase next-decimal 06', tmpDir);
assert.ok(result.success, `Command should succeed: ${result.error}`);
const output = JSON.parse(result.output);
assert.strictEqual(output.found, false, 'base phase not found');
assert.strictEqual(output.next, '06.1', 'should still suggest 06.1');
});
});