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:
Claude
2026-03-19 21:42:26 +00:00
120 changed files with 12080 additions and 791 deletions

View File

@@ -151,6 +151,20 @@ describe('SPAWN: spawn type consistency', () => {
'diagnose-issues should spawn gsd-debugger, not general-purpose'
);
});
test('execute-phase has Copilot sequential fallback in runtime_compatibility', () => {
const content = fs.readFileSync(
path.join(WORKFLOWS_DIR, 'execute-phase.md'), 'utf-8'
);
assert.ok(
content.includes('sequential inline execution'),
'execute-phase must document sequential inline execution as Copilot fallback'
);
assert.ok(
content.includes('spot-check'),
'execute-phase must have spot-check fallback for completion detection'
);
});
});
// ─── Required Frontmatter Fields ─────────────────────────────────────────────
@@ -167,3 +181,34 @@ describe('AGENT: required frontmatter fields', () => {
});
}
});
// ─── Discussion Log ──────────────────────────────────────────────────────────
describe('DISCUSS: discussion log generation', () => {
test('discuss-phase workflow references DISCUSSION-LOG.md generation', () => {
const content = fs.readFileSync(
path.join(WORKFLOWS_DIR, 'discuss-phase.md'), 'utf-8'
);
assert.ok(
content.includes('DISCUSSION-LOG.md'),
'discuss-phase must reference DISCUSSION-LOG.md generation'
);
assert.ok(
content.includes('Audit trail only'),
'discuss-phase must mark discussion log as audit-only'
);
});
test('discussion-log template exists', () => {
const templatePath = path.join(__dirname, '..', 'get-shit-done', 'templates', 'discussion-log.md');
assert.ok(
fs.existsSync(templatePath),
'discussion-log.md template must exist'
);
const content = fs.readFileSync(templatePath, 'utf-8');
assert.ok(
content.includes('Do not use as input to planning'),
'template must contain audit-only notice'
);
});
});

82
tests/claude-md.test.cjs Normal file
View File

@@ -0,0 +1,82 @@
/**
* CLAUDE.md generation and new-project workflow tests
*/
const { test, describe, beforeEach, afterEach } = require('node:test');
const assert = require('node:assert');
const fs = require('fs');
const path = require('path');
const { runGsdTools, createTempProject, cleanup } = require('./helpers.cjs');
describe('generate-claude-md', () => {
let tmpDir;
beforeEach(() => {
tmpDir = createTempProject();
});
afterEach(() => {
cleanup(tmpDir);
});
test('creates CLAUDE.md with workflow enforcement section', () => {
fs.writeFileSync(
path.join(tmpDir, '.planning', 'PROJECT.md'),
'# Test Project\n\n## What This Is\n\nA small test project.\n'
);
const result = runGsdTools('generate-claude-md', tmpDir);
assert.ok(result.success, `Command failed: ${result.error}`);
const output = JSON.parse(result.output);
assert.strictEqual(output.action, 'created');
assert.strictEqual(output.sections_total, 5);
assert.ok(output.sections_generated.includes('workflow'));
const claudePath = path.join(tmpDir, 'CLAUDE.md');
const content = fs.readFileSync(claudePath, 'utf-8');
assert.ok(content.includes('## GSD Workflow Enforcement'));
assert.ok(content.includes('/gsd:quick'));
assert.ok(content.includes('/gsd:debug'));
assert.ok(content.includes('/gsd:execute-phase'));
assert.ok(content.includes('Do not make direct repo edits outside a GSD workflow'));
});
test('adds workflow enforcement section when updating an existing CLAUDE.md', () => {
fs.writeFileSync(
path.join(tmpDir, '.planning', 'PROJECT.md'),
'# Test Project\n\n## What This Is\n\nA small test project.\n'
);
fs.writeFileSync(path.join(tmpDir, 'CLAUDE.md'), '## Local Notes\n\nKeep this intro.\n');
const result = runGsdTools('generate-claude-md', tmpDir);
assert.ok(result.success, `Command failed: ${result.error}`);
const output = JSON.parse(result.output);
assert.strictEqual(output.action, 'updated');
const content = fs.readFileSync(path.join(tmpDir, 'CLAUDE.md'), 'utf-8');
assert.ok(content.includes('## Local Notes'));
assert.ok(content.includes('## GSD Workflow Enforcement'));
});
});
describe('new-project workflow includes CLAUDE.md generation', () => {
const workflowPath = path.join(__dirname, '..', 'get-shit-done', 'workflows', 'new-project.md');
const commandsPath = path.join(__dirname, '..', 'docs', 'COMMANDS.md');
test('new-project workflow generates CLAUDE.md before final commit', () => {
const content = fs.readFileSync(workflowPath, 'utf-8');
assert.ok(content.includes('generate-claude-md'));
assert.ok(content.includes('--files .planning/ROADMAP.md .planning/STATE.md .planning/REQUIREMENTS.md CLAUDE.md'));
});
test('new-project artifacts mention CLAUDE.md', () => {
const workflowContent = fs.readFileSync(workflowPath, 'utf-8');
const commandsContent = fs.readFileSync(commandsPath, 'utf-8');
assert.ok(workflowContent.includes('| Project guide | `CLAUDE.md`'));
assert.ok(workflowContent.includes('- `CLAUDE.md`'));
assert.ok(commandsContent.includes('`CLAUDE.md`'));
});
});

View File

@@ -160,6 +160,19 @@ tools: Read, Grep, Glob
assert.ok(result.includes("'''"), 'has closing literal triple quotes');
});
test('includes required name and description fields', () => {
const result = generateCodexAgentToml('gsd-executor', sampleAgent);
assert.ok(result.includes('name = "gsd-executor"'), 'has name');
assert.ok(result.includes('description = "Executes plans"'), 'has description');
});
test('falls back to generated description when frontmatter is missing fields', () => {
const minimalAgent = `<role>You are an unknown agent.</role>`;
const result = generateCodexAgentToml('gsd-unknown', minimalAgent);
assert.ok(result.includes('name = "gsd-unknown"'), 'falls back to agent name');
assert.ok(result.includes('description = "GSD agent gsd-unknown"'), 'falls back to synthetic description');
});
test('defaults unknown agents to read-only', () => {
const result = generateCodexAgentToml('gsd-unknown', sampleAgent);
assert.ok(result.includes('sandbox_mode = "read-only"'), 'defaults to read-only');
@@ -354,6 +367,36 @@ describe('mergeCodexConfig', () => {
assert.ok(content.includes('[agents.gsd-executor]'), 'has agent');
});
test('case 3 strips existing [agents.gsd-*] sections before appending fresh block', () => {
const configPath = path.join(tmpDir, 'config.toml');
const existing = [
'[model]',
'name = "o3"',
'',
'[agents.custom-agent]',
'description = "user agent"',
'',
'',
'[agents.gsd-executor]',
'description = "old"',
'config_file = "agents/gsd-executor.toml"',
'',
].join('\n');
fs.writeFileSync(configPath, existing);
mergeCodexConfig(configPath, sampleBlock);
const content = fs.readFileSync(configPath, 'utf8');
const gsdAgentCount = (content.match(/^\[agents\.gsd-executor\]\s*$/gm) || []).length;
const markerCount = (content.match(new RegExp(GSD_CODEX_MARKER.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'), 'g')) || []).length;
assert.ok(content.includes('[model]'), 'preserves user content');
assert.ok(content.includes('[agents.custom-agent]'), 'preserves non-GSD agent section');
assert.strictEqual(gsdAgentCount, 1, 'keeps exactly one GSD agent section');
assert.strictEqual(markerCount, 1, 'adds exactly one marker block');
assert.ok(!/\n{3,}# GSD Agent Configuration/.test(content), 'does not leave extra blank lines before marker block');
});
test('idempotent: re-merge produces same result', () => {
const configPath = path.join(tmpDir, 'config.toml');
mergeCodexConfig(configPath, sampleBlock);
@@ -485,10 +528,47 @@ describe('installCodexConfig (integration)', () => {
assert.ok(fs.existsSync(path.join(agentsDir, 'gsd-plan-checker.toml')), 'plan-checker .toml exists');
const executorToml = fs.readFileSync(path.join(agentsDir, 'gsd-executor.toml'), 'utf8');
assert.ok(executorToml.includes('name = "gsd-executor"'), 'executor has name');
assert.ok(executorToml.includes('description = "Executes GSD plans with atomic commits, deviation handling, checkpoint protocols, and state management. Spawned by execute-phase orchestrator or execute-plan command."'), 'executor has description');
assert.ok(executorToml.includes('sandbox_mode = "workspace-write"'), 'executor is workspace-write');
assert.ok(executorToml.includes('developer_instructions'), 'has developer_instructions');
const checkerToml = fs.readFileSync(path.join(agentsDir, 'gsd-plan-checker.toml'), 'utf8');
assert.ok(checkerToml.includes('name = "gsd-plan-checker"'), 'plan-checker has name');
assert.ok(checkerToml.includes('sandbox_mode = "read-only"'), 'plan-checker is read-only');
});
});
// ─── Codex config.toml [features] safety (#1202) ─────────────────────────────
describe('codex features section safety', () => {
test('non-boolean keys under [features] are moved to top level', () => {
// Simulate the bug from #1202: model = "gpt-5.4" under [features]
// causes "invalid type: string, expected a boolean in features"
const configContent = `[features]\ncodex_hooks = true\n\nmodel = "gpt-5.4"\nmodel_reasoning_effort = "medium"\n\n[agents.gsd-executor]\ndescription = "test"\n`;
const featuresMatch = configContent.match(/\[features\]\n([\s\S]*?)(?=\n\[|$)/);
assert.ok(featuresMatch, 'features section found');
const featuresBody = featuresMatch[1];
const nonBooleanKeys = featuresBody.split('\n')
.filter(line => line.match(/^\s*\w+\s*=/) && !line.match(/=\s*(true|false)\s*(#.*)?$/))
.map(line => line.trim());
assert.strictEqual(nonBooleanKeys.length, 2, 'should detect 2 non-boolean keys');
assert.ok(nonBooleanKeys.includes('model = "gpt-5.4"'), 'detects model key');
assert.ok(nonBooleanKeys.includes('model_reasoning_effort = "medium"'), 'detects model_reasoning_effort key');
});
test('boolean keys under [features] are NOT flagged', () => {
const configContent = `[features]\ncodex_hooks = true\nmulti_agent = false\n`;
const featuresMatch = configContent.match(/\[features\]\n([\s\S]*?)(?=\n\[|$)/);
const featuresBody = featuresMatch[1];
const nonBooleanKeys = featuresBody.split('\n')
.filter(line => line.match(/^\s*\w+\s*=/) && !line.match(/=\s*(true|false)\s*(#.*)?$/))
.map(line => line.trim());
assert.strictEqual(nonBooleanKeys.length, 0, 'no non-boolean keys in a clean config');
});
});

View File

@@ -363,6 +363,37 @@ requirements-completed:
assert.strictEqual(output.decisions, undefined, 'decisions excluded');
});
test('extracts one-liner from body when not in frontmatter', () => {
const phaseDir = path.join(tmpDir, '.planning', 'phases', '01-foundation');
fs.mkdirSync(phaseDir, { recursive: true });
fs.writeFileSync(
path.join(phaseDir, '01-01-SUMMARY.md'),
`---
phase: "01"
key-files:
- src/lib/db.ts
---
# Phase 1: Foundation Summary
**JWT auth with refresh rotation using jose library**
## Performance
- **Duration:** 28 min
- **Tasks:** 5
`
);
const result = runGsdTools('summary-extract .planning/phases/01-foundation/01-01-SUMMARY.md', tmpDir);
assert.ok(result.success, `Command failed: ${result.error}`);
const output = JSON.parse(result.output);
assert.strictEqual(output.one_liner, 'JWT auth with refresh rotation using jose library',
'one-liner should be extracted from body **bold** line');
});
test('handles missing frontmatter fields gracefully', () => {
const phaseDir = path.join(tmpDir, '.planning', 'phases', '01-foundation');
fs.mkdirSync(phaseDir, { recursive: true });
@@ -567,6 +598,98 @@ describe('todo complete command', () => {
});
});
// ─────────────────────────────────────────────────────────────────────────────
// todo match-phase command
// ─────────────────────────────────────────────────────────────────────────────
describe('todo match-phase command', () => {
let tmpDir;
beforeEach(() => {
tmpDir = createTempProject();
});
afterEach(() => cleanup(tmpDir));
test('returns empty matches when no todos exist', () => {
const result = runGsdTools('todo match-phase 01', tmpDir);
assert.ok(result.success, 'should succeed');
const output = JSON.parse(result.output);
assert.strictEqual(output.todo_count, 0);
assert.deepStrictEqual(output.matches, []);
});
test('matches todo by keyword overlap with phase name', () => {
const pendingDir = path.join(tmpDir, '.planning', 'todos', 'pending');
fs.mkdirSync(pendingDir, { recursive: true });
fs.writeFileSync(path.join(pendingDir, 'auth-todo.md'),
'title: Add OAuth token refresh\narea: auth\ncreated: 2026-03-01\n\nNeed to handle token expiry for OAuth flows.');
fs.writeFileSync(path.join(tmpDir, '.planning', 'ROADMAP.md'),
'# Roadmap\n\n### Phase 01: Authentication and Session Management\n\n**Goal:** Implement OAuth login and session handling\n');
const result = runGsdTools('todo match-phase 01', tmpDir);
assert.ok(result.success, 'should succeed');
const output = JSON.parse(result.output);
assert.strictEqual(output.todo_count, 1, 'should find 1 todo');
assert.ok(output.matches.length > 0, 'should have matches');
assert.strictEqual(output.matches[0].title, 'Add OAuth token refresh');
assert.ok(output.matches[0].score > 0, 'score should be positive');
assert.ok(output.matches[0].reasons.length > 0, 'should have reasons');
});
test('does not match unrelated todo', () => {
const pendingDir = path.join(tmpDir, '.planning', 'todos', 'pending');
fs.mkdirSync(pendingDir, { recursive: true });
fs.writeFileSync(path.join(pendingDir, 'auth-todo.md'),
'title: Add OAuth token refresh\narea: auth\ncreated: 2026-03-01\n\nOAuth token expiry.');
fs.writeFileSync(path.join(pendingDir, 'unrelated-todo.md'),
'title: Fix CSS grid layout in dashboard\narea: ui\ncreated: 2026-03-01\n\nGrid columns break on mobile.');
fs.writeFileSync(path.join(tmpDir, '.planning', 'ROADMAP.md'),
'# Roadmap\n\n### Phase 01: Authentication and Session Management\n\n**Goal:** Implement OAuth login and session handling\n');
const result = runGsdTools('todo match-phase 01', tmpDir);
assert.ok(result.success, 'should succeed');
const output = JSON.parse(result.output);
const matchTitles = output.matches.map(m => m.title);
assert.ok(matchTitles.includes('Add OAuth token refresh'), 'auth todo should match');
assert.ok(!matchTitles.includes('Fix CSS grid layout in dashboard'), 'unrelated todo should not match');
});
test('matches todo by area overlap', () => {
const pendingDir = path.join(tmpDir, '.planning', 'todos', 'pending');
fs.mkdirSync(pendingDir, { recursive: true });
fs.writeFileSync(path.join(pendingDir, 'auth-todo.md'),
'title: Add OAuth token refresh\narea: auth\ncreated: 2026-03-01\n\nOAuth token handling.');
fs.writeFileSync(path.join(tmpDir, '.planning', 'ROADMAP.md'),
'# Roadmap\n\n### Phase 01: Auth System\n\n**Goal:** Build auth module\n');
const result = runGsdTools('todo match-phase 01', tmpDir);
const output = JSON.parse(result.output);
const authMatch = output.matches.find(m => m.title === 'Add OAuth token refresh');
assert.ok(authMatch, 'should find auth todo');
const hasAreaReason = authMatch.reasons.some(r => r.startsWith('area:'));
assert.ok(hasAreaReason, 'should match on area');
});
test('sorts matches by score descending', () => {
const pendingDir = path.join(tmpDir, '.planning', 'todos', 'pending');
fs.mkdirSync(pendingDir, { recursive: true });
fs.writeFileSync(path.join(pendingDir, 'weak-match.md'),
'title: Check token format\narea: general\ncreated: 2026-03-01\n\nToken format validation.');
fs.writeFileSync(path.join(pendingDir, 'strong-match.md'),
'title: Session management authentication OAuth token handling\narea: auth\ncreated: 2026-03-01\n\nSession auth OAuth tokens.');
fs.writeFileSync(path.join(tmpDir, '.planning', 'ROADMAP.md'),
'# Roadmap\n\n### Phase 01: Authentication and Session Management\n\n**Goal:** Implement OAuth login, session handling, and token management\n');
const result = runGsdTools('todo match-phase 01', tmpDir);
const output = JSON.parse(result.output);
assert.ok(output.matches.length >= 2, 'should have multiple matches');
for (let i = 1; i < output.matches.length; i++) {
assert.ok(output.matches[i - 1].score >= output.matches[i].score,
`match ${i-1} score (${output.matches[i-1].score}) should be >= match ${i} score (${output.matches[i].score})`);
}
});
});
// ─────────────────────────────────────────────────────────────────────────────
// scaffold command
// ─────────────────────────────────────────────────────────────────────────────

View File

@@ -287,6 +287,16 @@ describe('config-set command', () => {
);
});
test('sets workflow.text_mode for remote session support', () => {
writeConfig(tmpDir, {});
const result = runGsdTools('config-set workflow.text_mode true', tmpDir);
assert.ok(result.success, `Command failed: ${result.error}`);
const config = readConfig(tmpDir);
assert.strictEqual(config.workflow.text_mode, true);
});
test('errors when no key path provided', () => {
const result = runGsdTools('config-set', tmpDir);
assert.strictEqual(result.success, false);

View File

@@ -625,7 +625,7 @@ describe('copyCommandsAsCopilotSkills', () => {
// Count gsd-* directories — should be 31
const dirs = fs.readdirSync(tempDir, { withFileTypes: true })
.filter(e => e.isDirectory() && e.name.startsWith('gsd-'));
assert.strictEqual(dirs.length, 39, `expected 39 skill folders, got ${dirs.length}`);
assert.strictEqual(dirs.length, 50, `expected 50 skill folders, got ${dirs.length}`);
} finally {
fs.rmSync(tempDir, { recursive: true });
}
@@ -1119,7 +1119,7 @@ const { execFileSync } = require('child_process');
const crypto = require('crypto');
const INSTALL_PATH = path.join(__dirname, '..', 'bin', 'install.js');
const EXPECTED_SKILLS = 39;
const EXPECTED_SKILLS = 50;
const EXPECTED_AGENTS = 16;
function runCopilotInstall(cwd) {

View File

@@ -10,6 +10,7 @@ const assert = require('node:assert');
const fs = require('fs');
const path = require('path');
const os = require('os');
const { createTempProject, cleanup } = require('./helpers.cjs');
const {
loadConfig,
@@ -26,6 +27,8 @@ const {
getRoadmapPhaseInternal,
searchPhaseInDir,
findPhaseInternal,
findProjectRoot,
detectSubRepos,
} = require('../get-shit-done/bin/lib/core.cjs');
// ─── loadConfig ────────────────────────────────────────────────────────────────
@@ -35,14 +38,13 @@ describe('loadConfig', () => {
let originalCwd;
beforeEach(() => {
tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'gsd-core-test-'));
fs.mkdirSync(path.join(tmpDir, '.planning'), { recursive: true });
tmpDir = createTempProject();
originalCwd = process.cwd();
});
afterEach(() => {
process.chdir(originalCwd);
fs.rmSync(tmpDir, { recursive: true, force: true });
cleanup(tmpDir);
});
function writeConfig(obj) {
@@ -61,6 +63,7 @@ describe('loadConfig', () => {
assert.strictEqual(config.brave_search, false);
assert.strictEqual(config.parallelization, true);
assert.strictEqual(config.nyquist_validation, true);
assert.strictEqual(config.text_mode, false);
});
test('reads model_profile from config.json', () => {
@@ -129,12 +132,11 @@ describe('resolveModelInternal', () => {
let tmpDir;
beforeEach(() => {
tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'gsd-core-test-'));
fs.mkdirSync(path.join(tmpDir, '.planning'), { recursive: true });
tmpDir = createTempProject();
});
afterEach(() => {
fs.rmSync(tmpDir, { recursive: true, force: true });
cleanup(tmpDir);
});
function writeConfig(obj) {
@@ -276,62 +278,11 @@ describe('generateSlugInternal', () => {
});
});
// ─── normalizePhaseName ────────────────────────────────────────────────────────
describe('normalizePhaseName', () => {
test('pads single digit', () => {
assert.strictEqual(normalizePhaseName('1'), '01');
});
test('preserves double digit', () => {
assert.strictEqual(normalizePhaseName('12'), '12');
});
test('handles letter suffix', () => {
assert.strictEqual(normalizePhaseName('1A'), '01A');
});
test('handles decimal phases', () => {
assert.strictEqual(normalizePhaseName('2.1'), '02.1');
});
test('handles multi-level decimals', () => {
assert.strictEqual(normalizePhaseName('1.2.3'), '01.2.3');
});
test('returns non-matching input unchanged', () => {
assert.strictEqual(normalizePhaseName('abc'), 'abc');
});
});
// ─── comparePhaseNum ───────────────────────────────────────────────────────────
describe('comparePhaseNum', () => {
test('sorts integer phases numerically', () => {
assert.ok(comparePhaseNum('1', '2') < 0);
assert.ok(comparePhaseNum('10', '2') > 0);
});
test('sorts letter suffixes', () => {
assert.ok(comparePhaseNum('12', '12A') < 0);
assert.ok(comparePhaseNum('12A', '12B') < 0);
});
test('sorts decimal phases', () => {
assert.ok(comparePhaseNum('2', '2.1') < 0);
assert.ok(comparePhaseNum('2.1', '2.2') < 0);
});
test('handles multi-level decimals', () => {
assert.ok(comparePhaseNum('1.1', '1.1.2') < 0);
assert.ok(comparePhaseNum('1.1.2', '1.2') < 0);
});
test('returns 0 for equal phases', () => {
assert.strictEqual(comparePhaseNum('1', '1'), 0);
assert.strictEqual(comparePhaseNum('2.1', '2.1'), 0);
});
});
// ─── normalizePhaseName / comparePhaseNum ──────────────────────────────────────
// NOTE: Comprehensive tests for normalizePhaseName and comparePhaseNum are in
// phase.test.cjs (which covers all edge cases: hybrid, letter-suffix,
// multi-level decimal, case-insensitive, directory-slug, and full sort order).
// Removed duplicates here to keep a single authoritative test location.
// ─── safeReadFile ──────────────────────────────────────────────────────────────
@@ -343,7 +294,7 @@ describe('safeReadFile', () => {
});
afterEach(() => {
fs.rmSync(tmpDir, { recursive: true, force: true });
cleanup(tmpDir);
});
test('reads existing file', () => {
@@ -363,12 +314,11 @@ describe('pathExistsInternal', () => {
let tmpDir;
beforeEach(() => {
tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'gsd-core-test-'));
fs.mkdirSync(path.join(tmpDir, '.planning'), { recursive: true });
tmpDir = createTempProject();
});
afterEach(() => {
fs.rmSync(tmpDir, { recursive: true, force: true });
cleanup(tmpDir);
});
test('returns true for existing path', () => {
@@ -390,12 +340,11 @@ describe('getMilestoneInfo', () => {
let tmpDir;
beforeEach(() => {
tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'gsd-core-test-'));
fs.mkdirSync(path.join(tmpDir, '.planning'), { recursive: true });
tmpDir = createTempProject();
});
afterEach(() => {
fs.rmSync(tmpDir, { recursive: true, force: true });
cleanup(tmpDir);
});
test('extracts version and name from roadmap', () => {
@@ -502,7 +451,7 @@ describe('searchPhaseInDir', () => {
});
afterEach(() => {
fs.rmSync(tmpDir, { recursive: true, force: true });
cleanup(tmpDir);
});
test('finds phase directory by normalized prefix', () => {
@@ -564,12 +513,11 @@ describe('findPhaseInternal', () => {
let tmpDir;
beforeEach(() => {
tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'gsd-core-test-'));
fs.mkdirSync(path.join(tmpDir, '.planning', 'phases'), { recursive: true });
tmpDir = createTempProject();
});
afterEach(() => {
fs.rmSync(tmpDir, { recursive: true, force: true });
cleanup(tmpDir);
});
test('finds phase in current phases directory', () => {
@@ -605,12 +553,11 @@ describe('getRoadmapPhaseInternal', () => {
let tmpDir;
beforeEach(() => {
tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'gsd-core-test-'));
fs.mkdirSync(path.join(tmpDir, '.planning'), { recursive: true });
tmpDir = createTempProject();
});
afterEach(() => {
fs.rmSync(tmpDir, { recursive: true, force: true });
cleanup(tmpDir);
});
// Bug: getRoadmapPhaseInternal was missing from module.exports
@@ -687,12 +634,11 @@ describe('getMilestonePhaseFilter', () => {
let tmpDir;
beforeEach(() => {
tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'gsd-core-test-'));
fs.mkdirSync(path.join(tmpDir, '.planning', 'phases'), { recursive: true });
tmpDir = createTempProject();
});
afterEach(() => {
fs.rmSync(tmpDir, { recursive: true, force: true });
cleanup(tmpDir);
});
test('filters directories to only current milestone phases', () => {
@@ -924,3 +870,382 @@ describe('normalizeMd', () => {
assert.ok(result.includes('\n\n- Decision 1'), 'list needs blank line before');
});
});
// ─── Stale hook filter regression (#1200) ─────────────────────────────────────
describe('stale hook filter', () => {
test('filter should only match gsd-prefixed .js files', () => {
const files = [
'gsd-check-update.js',
'gsd-context-monitor.js',
'gsd-statusline.js',
'gsd-workflow-guard.js',
'guard-edits-outside-project.js', // user hook
'my-custom-hook.js', // user hook
'gsd-check-update.js.bak', // backup file
'README.md', // non-js file
];
const gsdFilter = f => f.startsWith('gsd-') && f.endsWith('.js');
const filtered = files.filter(gsdFilter);
assert.deepStrictEqual(filtered, [
'gsd-check-update.js',
'gsd-context-monitor.js',
'gsd-statusline.js',
'gsd-workflow-guard.js',
], 'should only include gsd-prefixed .js files');
assert.ok(!filtered.includes('guard-edits-outside-project.js'), 'must not include user hooks');
assert.ok(!filtered.includes('my-custom-hook.js'), 'must not include non-gsd hooks');
});
});
// ─── resolveWorktreeRoot ─────────────────────────────────────────────────────
describe('resolveWorktreeRoot', () => {
const { resolveWorktreeRoot } = require('../get-shit-done/bin/lib/core.cjs');
test('returns cwd when not in a git repo', () => {
const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'gsd-wt-test-'));
try {
assert.strictEqual(resolveWorktreeRoot(tmpDir), tmpDir);
} finally {
fs.rmSync(tmpDir, { recursive: true, force: true });
}
});
test('returns cwd in a normal git repo (not a worktree)', () => {
const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'gsd-wt-test-'));
try {
const { execSync } = require('child_process');
execSync('git init', { cwd: tmpDir, stdio: 'pipe' });
assert.strictEqual(resolveWorktreeRoot(tmpDir), tmpDir);
} finally {
fs.rmSync(tmpDir, { recursive: true, force: true });
}
});
});
// ─── withPlanningLock ────────────────────────────────────────────────────────
describe('withPlanningLock', () => {
const { withPlanningLock, planningDir } = require('../get-shit-done/bin/lib/core.cjs');
test('executes function and returns result', () => {
const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'gsd-lock-test-'));
fs.mkdirSync(path.join(tmpDir, '.planning'), { recursive: true });
try {
const result = withPlanningLock(tmpDir, () => 42);
assert.strictEqual(result, 42);
// Lock file should be cleaned up
assert.ok(!fs.existsSync(path.join(planningDir(tmpDir), '.lock')));
} finally {
fs.rmSync(tmpDir, { recursive: true, force: true });
}
});
test('cleans up lock file even on error', () => {
const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'gsd-lock-test-'));
fs.mkdirSync(path.join(tmpDir, '.planning'), { recursive: true });
try {
assert.throws(() => {
withPlanningLock(tmpDir, () => { throw new Error('test'); });
}, /test/);
assert.ok(!fs.existsSync(path.join(planningDir(tmpDir), '.lock')));
} finally {
fs.rmSync(tmpDir, { recursive: true, force: true });
}
});
test('recovers from stale lock (>30s old)', () => {
const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'gsd-lock-test-'));
const planDir = path.join(tmpDir, '.planning');
fs.mkdirSync(planDir, { recursive: true });
const lockPath = path.join(planDir, '.lock');
try {
// Create a stale lock
fs.writeFileSync(lockPath, '{"pid":99999}');
// Backdate the lock file by 31 seconds
const staleTime = new Date(Date.now() - 31000);
fs.utimesSync(lockPath, staleTime, staleTime);
const result = withPlanningLock(tmpDir, () => 'recovered');
assert.strictEqual(result, 'recovered');
} finally {
fs.rmSync(tmpDir, { recursive: true, force: true });
}
});
});
// ─── detectSubRepos ──────────────────────────────────────────────────────────
describe('detectSubRepos', () => {
let projectRoot;
beforeEach(() => {
projectRoot = fs.mkdtempSync(path.join(os.tmpdir(), 'gsd-detect-test-'));
});
afterEach(() => {
fs.rmSync(projectRoot, { recursive: true, force: true });
});
test('returns empty array when no child directories have .git', () => {
fs.mkdirSync(path.join(projectRoot, 'src'));
fs.mkdirSync(path.join(projectRoot, 'lib'));
assert.deepStrictEqual(detectSubRepos(projectRoot), []);
});
test('detects directories with .git', () => {
fs.mkdirSync(path.join(projectRoot, 'backend', '.git'), { recursive: true });
fs.mkdirSync(path.join(projectRoot, 'frontend', '.git'), { recursive: true });
fs.mkdirSync(path.join(projectRoot, 'scripts')); // no .git
assert.deepStrictEqual(detectSubRepos(projectRoot), ['backend', 'frontend']);
});
test('returns sorted results', () => {
fs.mkdirSync(path.join(projectRoot, 'zeta', '.git'), { recursive: true });
fs.mkdirSync(path.join(projectRoot, 'alpha', '.git'), { recursive: true });
fs.mkdirSync(path.join(projectRoot, 'mid', '.git'), { recursive: true });
assert.deepStrictEqual(detectSubRepos(projectRoot), ['alpha', 'mid', 'zeta']);
});
test('skips hidden directories', () => {
fs.mkdirSync(path.join(projectRoot, '.hidden', '.git'), { recursive: true });
fs.mkdirSync(path.join(projectRoot, 'visible', '.git'), { recursive: true });
assert.deepStrictEqual(detectSubRepos(projectRoot), ['visible']);
});
test('skips node_modules', () => {
fs.mkdirSync(path.join(projectRoot, 'node_modules', '.git'), { recursive: true });
fs.mkdirSync(path.join(projectRoot, 'app', '.git'), { recursive: true });
assert.deepStrictEqual(detectSubRepos(projectRoot), ['app']);
});
});
// ─── loadConfig sub_repos auto-sync ──────────────────────────────────────────
describe('loadConfig sub_repos auto-sync', () => {
let projectRoot;
beforeEach(() => {
projectRoot = fs.mkdtempSync(path.join(os.tmpdir(), 'gsd-sync-test-'));
fs.mkdirSync(path.join(projectRoot, '.planning'), { recursive: true });
});
afterEach(() => {
fs.rmSync(projectRoot, { recursive: true, force: true });
});
test('migrates multiRepo: true to sub_repos array', () => {
// Create config with legacy multiRepo flag
fs.writeFileSync(
path.join(projectRoot, '.planning', 'config.json'),
JSON.stringify({ multiRepo: true, model_profile: 'quality' })
);
// Create sub-repos
fs.mkdirSync(path.join(projectRoot, 'backend', '.git'), { recursive: true });
fs.mkdirSync(path.join(projectRoot, 'frontend', '.git'), { recursive: true });
const config = loadConfig(projectRoot);
assert.deepStrictEqual(config.sub_repos, ['backend', 'frontend']);
assert.strictEqual(config.commit_docs, false);
// Verify config was persisted
const saved = JSON.parse(fs.readFileSync(path.join(projectRoot, '.planning', 'config.json'), 'utf-8'));
assert.deepStrictEqual(saved.sub_repos, ['backend', 'frontend']);
assert.strictEqual(saved.multiRepo, undefined, 'multiRepo should be removed');
});
test('adds newly detected repos to sub_repos', () => {
fs.mkdirSync(path.join(projectRoot, 'backend', '.git'), { recursive: true });
fs.writeFileSync(
path.join(projectRoot, '.planning', 'config.json'),
JSON.stringify({ sub_repos: ['backend'] })
);
// Add a new repo
fs.mkdirSync(path.join(projectRoot, 'frontend', '.git'), { recursive: true });
const config = loadConfig(projectRoot);
assert.deepStrictEqual(config.sub_repos, ['backend', 'frontend']);
});
test('removes repos that no longer have .git', () => {
fs.mkdirSync(path.join(projectRoot, 'backend', '.git'), { recursive: true });
fs.writeFileSync(
path.join(projectRoot, '.planning', 'config.json'),
JSON.stringify({ sub_repos: ['backend', 'old-repo'] })
);
const config = loadConfig(projectRoot);
assert.deepStrictEqual(config.sub_repos, ['backend']);
});
test('does not sync when sub_repos is empty and no repos detected', () => {
fs.writeFileSync(
path.join(projectRoot, '.planning', 'config.json'),
JSON.stringify({ sub_repos: [] })
);
const config = loadConfig(projectRoot);
assert.deepStrictEqual(config.sub_repos, []);
});
});
// ─── findProjectRoot ─────────────────────────────────────────────────────────
describe('findProjectRoot', () => {
let projectRoot;
beforeEach(() => {
projectRoot = fs.mkdtempSync(path.join(os.tmpdir(), 'gsd-root-test-'));
});
afterEach(() => {
fs.rmSync(projectRoot, { recursive: true, force: true });
});
test('returns startDir when no .planning/ exists anywhere', () => {
const subDir = path.join(projectRoot, 'backend');
fs.mkdirSync(subDir);
assert.strictEqual(findProjectRoot(subDir), subDir);
});
test('returns startDir when .planning/ is in startDir itself', () => {
fs.mkdirSync(path.join(projectRoot, '.planning'), { recursive: true });
assert.strictEqual(findProjectRoot(projectRoot), projectRoot);
});
test('walks up to parent with .planning/ and sub_repos config listing this dir', () => {
fs.mkdirSync(path.join(projectRoot, '.planning'), { recursive: true });
fs.writeFileSync(
path.join(projectRoot, '.planning', 'config.json'),
JSON.stringify({ sub_repos: ['backend', 'frontend'] })
);
const backendDir = path.join(projectRoot, 'backend');
fs.mkdirSync(backendDir);
assert.strictEqual(findProjectRoot(backendDir), projectRoot);
});
test('walks up from nested sub-repo subdirectory', () => {
fs.mkdirSync(path.join(projectRoot, '.planning'), { recursive: true });
fs.writeFileSync(
path.join(projectRoot, '.planning', 'config.json'),
JSON.stringify({ sub_repos: ['backend', 'frontend'] })
);
const deepDir = path.join(projectRoot, 'backend', 'src', 'services');
fs.mkdirSync(deepDir, { recursive: true });
assert.strictEqual(findProjectRoot(deepDir), projectRoot);
});
test('walks up via legacy multiRepo flag', () => {
fs.mkdirSync(path.join(projectRoot, '.planning'), { recursive: true });
fs.writeFileSync(
path.join(projectRoot, '.planning', 'config.json'),
JSON.stringify({ multiRepo: true })
);
const backendDir = path.join(projectRoot, 'backend');
fs.mkdirSync(path.join(backendDir, '.git'), { recursive: true });
assert.strictEqual(findProjectRoot(backendDir), projectRoot);
});
test('walks up via .git heuristic when no config exists', () => {
fs.mkdirSync(path.join(projectRoot, '.planning'), { recursive: true });
// No config.json at all
const backendDir = path.join(projectRoot, 'backend');
fs.mkdirSync(path.join(backendDir, '.git'), { recursive: true });
assert.strictEqual(findProjectRoot(backendDir), projectRoot);
});
test('walks up from nested path inside sub-repo via .git heuristic', () => {
fs.mkdirSync(path.join(projectRoot, '.planning'), { recursive: true });
// Sub-repo with .git at its root
const backendDir = path.join(projectRoot, 'backend');
fs.mkdirSync(path.join(backendDir, '.git'), { recursive: true });
// Nested path deep inside the sub-repo
const nestedDir = path.join(backendDir, 'src', 'modules', 'auth');
fs.mkdirSync(nestedDir, { recursive: true });
// isInsideGitRepo walks up and finds backend/.git
assert.strictEqual(findProjectRoot(nestedDir), projectRoot);
});
test('walks up from nested path inside sub-repo via sub_repos config', () => {
fs.mkdirSync(path.join(projectRoot, '.planning'), { recursive: true });
fs.writeFileSync(
path.join(projectRoot, '.planning', 'config.json'),
JSON.stringify({ sub_repos: ['backend'] })
);
// Nested path deep inside the sub-repo
const nestedDir = path.join(projectRoot, 'backend', 'src', 'modules');
fs.mkdirSync(nestedDir, { recursive: true });
// With sub_repos config, it checks topSegment of relative path
assert.strictEqual(findProjectRoot(nestedDir), projectRoot);
});
test('walks up from nested path via legacy multiRepo flag', () => {
fs.mkdirSync(path.join(projectRoot, '.planning'), { recursive: true });
fs.writeFileSync(
path.join(projectRoot, '.planning', 'config.json'),
JSON.stringify({ multiRepo: true })
);
const backendDir = path.join(projectRoot, 'backend');
fs.mkdirSync(path.join(backendDir, '.git'), { recursive: true });
// Nested inside sub-repo — isInsideGitRepo walks up and finds backend/.git
const nestedDir = path.join(backendDir, 'src');
fs.mkdirSync(nestedDir, { recursive: true });
assert.strictEqual(findProjectRoot(nestedDir), projectRoot);
});
test('does not walk up for dirs without .git when no sub_repos config', () => {
fs.mkdirSync(path.join(projectRoot, '.planning'), { recursive: true });
const scriptsDir = path.join(projectRoot, 'scripts');
fs.mkdirSync(scriptsDir);
assert.strictEqual(findProjectRoot(scriptsDir), scriptsDir);
});
test('handles planning.sub_repos nested config format', () => {
fs.mkdirSync(path.join(projectRoot, '.planning'), { recursive: true });
fs.writeFileSync(
path.join(projectRoot, '.planning', 'config.json'),
JSON.stringify({ planning: { sub_repos: ['backend'] } })
);
const backendDir = path.join(projectRoot, 'backend');
fs.mkdirSync(backendDir);
assert.strictEqual(findProjectRoot(backendDir), projectRoot);
});
test('returns startDir when sub_repos is empty and no .git', () => {
fs.mkdirSync(path.join(projectRoot, '.planning'), { recursive: true });
fs.writeFileSync(
path.join(projectRoot, '.planning', 'config.json'),
JSON.stringify({ sub_repos: [] })
);
const backendDir = path.join(projectRoot, 'backend');
fs.mkdirSync(backendDir);
assert.strictEqual(findProjectRoot(backendDir), backendDir);
});
});

View File

@@ -0,0 +1,81 @@
/**
* Cursor conversion regression tests.
*
* Ensures Cursor frontmatter names are emitted as plain identifiers
* (without surrounding quotes), so Cursor does not treat quotes as
* literal parts of skill/subagent names.
*/
process.env.GSD_TEST_MODE = '1';
const { describe, test } = require('node:test');
const assert = require('node:assert');
const {
convertClaudeCommandToCursorSkill,
convertClaudeAgentToCursorAgent,
} = require('../bin/install.js');
describe('convertClaudeCommandToCursorSkill', () => {
test('writes unquoted Cursor skill name in frontmatter', () => {
const input = `---
name: quick
description: Execute a quick task
---
<objective>
Test body
</objective>
`;
const result = convertClaudeCommandToCursorSkill(input, 'gsd-quick');
const nameMatch = result.match(/^name:\s*(.+)$/m);
assert.ok(nameMatch, 'frontmatter contains name field');
assert.strictEqual(nameMatch[1], 'gsd-quick', 'skill name is plain scalar');
assert.ok(!result.includes('name: "gsd-quick"'), 'quoted skill name is not emitted');
});
test('preserves slash for slash commands in markdown body', () => {
const input = `---
name: gsd:plan-phase
description: Plan a phase
---
Next:
/gsd:execute-phase 17
/gsd-help
gsd:progress
`;
const result = convertClaudeCommandToCursorSkill(input, 'gsd-plan-phase');
assert.ok(result.includes('/gsd-execute-phase 17'), 'slash command remains slash-prefixed');
assert.ok(result.includes('/gsd-help'), 'existing slash command is preserved');
assert.ok(result.includes('gsd-progress'), 'non-slash gsd: references still normalize');
assert.ok(!result.includes('/gsd:execute-phase'), 'legacy colon command form is removed');
});
});
describe('convertClaudeAgentToCursorAgent', () => {
test('writes unquoted Cursor agent name in frontmatter', () => {
const input = `---
name: gsd-planner
description: Planner agent
tools: Read, Write
color: green
---
<role>
Planner body
</role>
`;
const result = convertClaudeAgentToCursorAgent(input);
const nameMatch = result.match(/^name:\s*(.+)$/m);
assert.ok(nameMatch, 'frontmatter contains name field');
assert.strictEqual(nameMatch[1], 'gsd-planner', 'agent name is plain scalar');
assert.ok(!result.includes('name: "gsd-planner"'), 'quoted agent name is not emitted');
});
});

View File

@@ -1,47 +0,0 @@
/**
* GSD Tools Tests - Gemini agent conversion
*
* Verifies Gemini-specific agent frontmatter conversion removes
* unsupported fields while preserving converted tools and body text.
*/
process.env.GSD_TEST_MODE = '1';
const { test, describe } = require('node:test');
const assert = require('node:assert');
const { convertClaudeToGeminiAgent } = require('../bin/install.js');
describe('convertClaudeToGeminiAgent', () => {
test('drops unsupported skills frontmatter while keeping converted tools', () => {
const input = `---
name: gsd-codebase-mapper
description: Explores codebase and writes structured analysis documents.
tools: Read, Bash, Grep, Glob, Write
color: cyan
skills:
- gsd-mapper-workflow
---
<role>
Use \${PHASE} in shell examples.
</role>`;
const result = convertClaudeToGeminiAgent(input);
const frontmatter = result.split('---')[1] || '';
assert.ok(frontmatter.includes('name: gsd-codebase-mapper'), 'keeps name');
assert.ok(frontmatter.includes('description: Explores codebase and writes structured analysis documents.'), 'keeps description');
assert.ok(frontmatter.includes('tools:'), 'adds Gemini tools array');
assert.ok(frontmatter.includes(' - read_file'), 'maps Read -> read_file');
assert.ok(frontmatter.includes(' - run_shell_command'), 'maps Bash -> run_shell_command');
assert.ok(frontmatter.includes(' - search_file_content'), 'maps Grep -> search_file_content');
assert.ok(frontmatter.includes(' - glob'), 'maps Glob -> glob');
assert.ok(frontmatter.includes(' - write_file'), 'maps Write -> write_file');
assert.ok(!frontmatter.includes('color:'), 'drops unsupported color field');
assert.ok(!frontmatter.includes('skills:'), 'drops unsupported skills field');
assert.ok(!frontmatter.includes('gsd-mapper-workflow'), 'drops skills list items');
assert.ok(result.includes('$PHASE'), 'escapes ${PHASE} shell variable for Gemini');
assert.ok(!result.includes('${PHASE}'), 'removes Gemini template-string pattern');
});
});

View File

@@ -679,6 +679,7 @@ describe('cmdInitQuick', () => {
assert.ok(result.success, `Command failed: ${result.error}`);
const output = JSON.parse(result.output);
assert.strictEqual(output.branch_name, null);
assert.strictEqual(output.slug, 'fix-login-bug');
assert.strictEqual(output.description, 'Fix login bug');
@@ -736,6 +737,44 @@ describe('cmdInitQuick', () => {
const output = JSON.parse(result.output);
assert.ok(output.slug.length <= 40, `Slug should be <= 40 chars, got ${output.slug.length}: "${output.slug}"`);
});
test('returns quick branch name when quick_branch_template is configured', () => {
fs.writeFileSync(
path.join(tmpDir, '.planning', 'config.json'),
JSON.stringify({
git: {
quick_branch_template: 'gsd/quick-{num}-{slug}',
},
}, null, 2)
);
const result = runGsdTools('init quick "Fix login bug"', tmpDir);
assert.ok(result.success, `Command failed: ${result.error}`);
const output = JSON.parse(result.output);
assert.ok(output.branch_name, 'branch_name should be set');
assert.ok(output.branch_name.startsWith('gsd/quick-'));
assert.ok(output.branch_name.endsWith('-fix-login-bug'));
assert.ok(output.branch_name.includes(output.quick_id), 'branch_name should include quick_id');
});
test('uses fallback slug in quick branch name when description is omitted', () => {
fs.writeFileSync(
path.join(tmpDir, '.planning', 'config.json'),
JSON.stringify({
git: {
quick_branch_template: 'gsd/quick-{quick}-{slug}',
},
}, null, 2)
);
const result = runGsdTools('init quick', tmpDir);
assert.ok(result.success, `Command failed: ${result.error}`);
const output = JSON.parse(result.output);
assert.ok(output.branch_name, 'branch_name should be set');
assert.ok(output.branch_name.endsWith('-quick'), `Expected fallback slug in branch name, got "${output.branch_name}"`);
});
});
// ─────────────────────────────────────────────────────────────────────────────
@@ -907,6 +946,99 @@ describe('cmdInitNewMilestone', () => {
assert.strictEqual(output2.roadmap_exists, true);
assert.strictEqual(output2.project_exists, true);
});
test('reports latest completed milestone and archive target for reset flow', () => {
fs.writeFileSync(
path.join(tmpDir, '.planning', 'MILESTONES.md'),
'# Milestones\n\n## v1.2 Search Refresh (Shipped: 2026-02-18)\n\n---\n'
);
fs.mkdirSync(path.join(tmpDir, '.planning', 'phases', '06-refine-search'), { recursive: true });
fs.mkdirSync(path.join(tmpDir, '.planning', 'phases', '07-polish'), { recursive: true });
const result = runGsdTools('init new-milestone', tmpDir);
assert.ok(result.success, `Command failed: ${result.error}`);
const output = JSON.parse(result.output);
assert.strictEqual(output.latest_completed_milestone, 'v1.2');
assert.strictEqual(output.latest_completed_milestone_name, 'Search Refresh');
assert.strictEqual(output.phase_dir_count, 2);
assert.strictEqual(output.phase_archive_path, '.planning/milestones/v1.2-phases');
});
test('reset flow metadata is null-safe when no milestones file exists', () => {
const result = runGsdTools('init new-milestone', tmpDir);
assert.ok(result.success, `Command failed: ${result.error}`);
const output = JSON.parse(result.output);
assert.strictEqual(output.latest_completed_milestone, null);
assert.strictEqual(output.latest_completed_milestone_name, null);
assert.strictEqual(output.phase_dir_count, 0);
assert.strictEqual(output.phase_archive_path, null);
});
});
// ─────────────────────────────────────────────────────────────────────────────
// findProjectRoot integration — gsd-tools resolves project root from sub-repo
// ─────────────────────────────────────────────────────────────────────────────
describe('findProjectRoot integration via --cwd', () => {
let projectRoot;
beforeEach(() => {
projectRoot = createTempProject();
// Add ROADMAP.md so init quick doesn't error
fs.writeFileSync(
path.join(projectRoot, '.planning', 'ROADMAP.md'),
'# Roadmap\n\n## Phase 1: Foundation\n**Goal:** Setup\n'
);
// Write sub_repos config
fs.writeFileSync(
path.join(projectRoot, '.planning', 'config.json'),
JSON.stringify({ sub_repos: ['backend', 'frontend'] })
);
// Create sub-repo directory
fs.mkdirSync(path.join(projectRoot, 'backend'));
});
afterEach(() => {
cleanup(projectRoot);
});
test('init quick from sub-repo CWD returns project_root pointing to parent', () => {
const backendDir = path.join(projectRoot, 'backend');
const result = runGsdTools(['init', 'quick', 'test task', '--cwd', backendDir]);
assert.ok(result.success, `Command failed: ${result.error}`);
const output = JSON.parse(result.output);
assert.ok('project_root' in output, 'Should have project_root');
assert.strictEqual(output.project_root, projectRoot, 'project_root should be the parent, not the sub-repo');
assert.ok(output.roadmap_exists, 'Should find ROADMAP.md at project root');
});
test('init quick from project root returns project_root as-is', () => {
const result = runGsdTools(['init', 'quick', 'test task', '--cwd', projectRoot]);
assert.ok(result.success, `Command failed: ${result.error}`);
const output = JSON.parse(result.output);
assert.strictEqual(output.project_root, projectRoot);
});
test('state load from sub-repo CWD reads project root config', () => {
// Write STATE.md at project root
fs.writeFileSync(
path.join(projectRoot, '.planning', 'STATE.md'),
'---\ncurrent_phase: 1\nphase_name: Foundation\n---\n# State\n'
);
const backendDir = path.join(projectRoot, 'backend');
const result = runGsdTools(['state', '--cwd', backendDir]);
assert.ok(result.success, `Command failed: ${result.error}`);
const output = JSON.parse(result.output);
// Should find config from project root, not from backend/
assert.deepStrictEqual(output.config.sub_repos, ['backend', 'frontend'],
'Should read sub_repos from project root config');
});
});
// ─────────────────────────────────────────────────────────────────────────────

View File

@@ -424,6 +424,75 @@ describe('milestone complete command', () => {
assert.strictEqual(output.phases, 2, 'should count only phases 456 and 457');
});
test('counts tasks from **Tasks:** N in summary body', () => {
fs.writeFileSync(
path.join(tmpDir, '.planning', 'ROADMAP.md'),
`# Roadmap v1.0\n\n### Phase 1: Foundation\n**Goal:** Setup\n`
);
fs.writeFileSync(
path.join(tmpDir, '.planning', 'STATE.md'),
`# State\n\n**Status:** In progress\n**Last Activity:** 2025-01-01\n**Last Activity Description:** Working\n`
);
const p1 = path.join(tmpDir, '.planning', 'phases', '01-foundation');
fs.mkdirSync(p1, { recursive: true });
fs.writeFileSync(
path.join(p1, '01-01-SUMMARY.md'),
`---\none-liner: Built the foundation\n---\n\n# Phase 1: Foundation Summary\n\n**Built the foundation**\n\n## Performance\n\n- **Duration:** 28 min\n- **Tasks:** 7\n- **Files modified:** 12\n`
);
const result = runGsdTools('milestone complete v1.0 --name MVP', tmpDir);
assert.ok(result.success, `Command failed: ${result.error}`);
const output = JSON.parse(result.output);
assert.strictEqual(output.tasks, 7, 'should count tasks from **Tasks:** N field');
});
test('extracts one-liner from body when not in frontmatter', () => {
fs.writeFileSync(
path.join(tmpDir, '.planning', 'ROADMAP.md'),
`# Roadmap v1.0\n\n### Phase 1: Foundation\n**Goal:** Setup\n`
);
fs.writeFileSync(
path.join(tmpDir, '.planning', 'STATE.md'),
`# State\n\n**Status:** In progress\n**Last Activity:** 2025-01-01\n**Last Activity Description:** Working\n`
);
const p1 = path.join(tmpDir, '.planning', 'phases', '01-foundation');
fs.mkdirSync(p1, { recursive: true });
// No one-liner in frontmatter, but present in body as bold line
fs.writeFileSync(
path.join(p1, '01-01-SUMMARY.md'),
`---\nphase: "01"\n---\n\n# Phase 1: Foundation Summary\n\n**JWT auth with refresh rotation using jose library**\n\n## Performance\n`
);
const result = runGsdTools('milestone complete v1.0 --name MVP', tmpDir);
assert.ok(result.success, `Command failed: ${result.error}`);
const output = JSON.parse(result.output);
assert.ok(
output.accomplishments.includes('JWT auth with refresh rotation using jose library'),
'should extract one-liner from body bold line'
);
});
test('updates STATE.md with plain format fields', () => {
fs.writeFileSync(
path.join(tmpDir, '.planning', 'ROADMAP.md'),
`# Roadmap v1.0\n`
);
fs.writeFileSync(
path.join(tmpDir, '.planning', 'STATE.md'),
`# State\n\nStatus: In progress\nLast Activity: 2025-01-01\nLast Activity Description: Working\n`
);
const result = runGsdTools('milestone complete v1.0 --name Test', tmpDir);
assert.ok(result.success, `Command failed: ${result.error}`);
const state = fs.readFileSync(path.join(tmpDir, '.planning', 'STATE.md'), 'utf-8');
assert.ok(state.includes('v1.0 milestone complete'), 'plain Status field should be updated');
});
test('handles empty phases directory', () => {
fs.writeFileSync(
path.join(tmpDir, '.planning', 'ROADMAP.md'),

View File

@@ -0,0 +1,134 @@
/**
* Model Profiles Tests
*
* Tests for MODEL_PROFILES data structure, VALID_PROFILES list,
* formatAgentToModelMapAsTable, and getAgentToModelMapForProfile.
*/
const { test, describe } = require('node:test');
const assert = require('node:assert');
const {
MODEL_PROFILES,
VALID_PROFILES,
formatAgentToModelMapAsTable,
getAgentToModelMapForProfile,
} = require('../get-shit-done/bin/lib/model-profiles.cjs');
// ─── MODEL_PROFILES data integrity ────────────────────────────────────────────
describe('MODEL_PROFILES', () => {
test('contains all expected GSD agents', () => {
const expectedAgents = [
'gsd-planner', 'gsd-roadmapper', 'gsd-executor',
'gsd-phase-researcher', 'gsd-project-researcher', 'gsd-research-synthesizer',
'gsd-debugger', 'gsd-codebase-mapper', 'gsd-verifier',
'gsd-plan-checker', 'gsd-integration-checker', 'gsd-nyquist-auditor',
'gsd-ui-researcher', 'gsd-ui-checker', 'gsd-ui-auditor',
];
for (const agent of expectedAgents) {
assert.ok(MODEL_PROFILES[agent], `Missing agent: ${agent}`);
}
});
test('every agent has quality, balanced, and budget profiles', () => {
for (const [agent, profiles] of Object.entries(MODEL_PROFILES)) {
assert.ok(profiles.quality, `${agent} missing quality profile`);
assert.ok(profiles.balanced, `${agent} missing balanced profile`);
assert.ok(profiles.budget, `${agent} missing budget profile`);
}
});
test('all profile values are valid model aliases', () => {
const validModels = ['opus', 'sonnet', 'haiku'];
for (const [agent, profiles] of Object.entries(MODEL_PROFILES)) {
for (const [profile, model] of Object.entries(profiles)) {
assert.ok(
validModels.includes(model),
`${agent}.${profile} has invalid model "${model}" — expected one of ${validModels.join(', ')}`
);
}
}
});
test('quality profile never uses haiku', () => {
for (const [agent, profiles] of Object.entries(MODEL_PROFILES)) {
assert.notStrictEqual(
profiles.quality, 'haiku',
`${agent} quality profile should not use haiku`
);
}
});
});
// ─── VALID_PROFILES ───────────────────────────────────────────────────────────
describe('VALID_PROFILES', () => {
test('contains quality, balanced, and budget', () => {
assert.deepStrictEqual(VALID_PROFILES.sort(), ['balanced', 'budget', 'quality']);
});
test('is derived from MODEL_PROFILES keys', () => {
const fromData = Object.keys(MODEL_PROFILES['gsd-planner']);
assert.deepStrictEqual(VALID_PROFILES.sort(), fromData.sort());
});
});
// ─── getAgentToModelMapForProfile ─────────────────────────────────────────────
describe('getAgentToModelMapForProfile', () => {
test('returns correct models for balanced profile', () => {
const map = getAgentToModelMapForProfile('balanced');
assert.strictEqual(map['gsd-planner'], 'opus');
assert.strictEqual(map['gsd-codebase-mapper'], 'haiku');
assert.strictEqual(map['gsd-verifier'], 'sonnet');
});
test('returns correct models for budget profile', () => {
const map = getAgentToModelMapForProfile('budget');
assert.strictEqual(map['gsd-planner'], 'sonnet');
assert.strictEqual(map['gsd-phase-researcher'], 'haiku');
});
test('returns correct models for quality profile', () => {
const map = getAgentToModelMapForProfile('quality');
assert.strictEqual(map['gsd-planner'], 'opus');
assert.strictEqual(map['gsd-executor'], 'opus');
});
test('returns all agents in the map', () => {
const map = getAgentToModelMapForProfile('balanced');
const agentCount = Object.keys(MODEL_PROFILES).length;
assert.strictEqual(Object.keys(map).length, agentCount);
});
});
// ─── formatAgentToModelMapAsTable ─────────────────────────────────────────────
describe('formatAgentToModelMapAsTable', () => {
test('produces a table with header and separator', () => {
const map = { 'gsd-planner': 'opus', 'gsd-executor': 'sonnet' };
const table = formatAgentToModelMapAsTable(map);
assert.ok(table.includes('Agent'), 'should have Agent header');
assert.ok(table.includes('Model'), 'should have Model header');
assert.ok(table.includes('─'), 'should have separator line');
assert.ok(table.includes('gsd-planner'), 'should list agent');
assert.ok(table.includes('opus'), 'should list model');
});
test('pads columns correctly', () => {
const map = { 'a': 'opus', 'very-long-agent-name': 'haiku' };
const table = formatAgentToModelMapAsTable(map);
const lines = table.split('\n').filter(l => l.trim());
// Separator line uses ┼, data/header lines use │
const dataLines = lines.filter(l => l.includes('│'));
const pipePositions = dataLines.map(l => l.indexOf('│'));
const unique = [...new Set(pipePositions)];
assert.strictEqual(unique.length, 1, 'all data lines should align on │');
});
test('handles empty map', () => {
const table = formatAgentToModelMapAsTable({});
assert.ok(table.includes('Agent'), 'should still have header');
});
});

View File

@@ -1,143 +0,0 @@
/**
* OpenCode Agent Frontmatter Conversion Tests
*
* Validates that convertClaudeToOpencodeFrontmatter correctly converts
* agent frontmatter for OpenCode compatibility when isAgent: true.
*
* Bug: Without isAgent flag, the function strips name: (agents need it),
* keeps color:/skills:/tools: record (should strip), and doesn't add
* model: inherit / mode: subagent (required by OpenCode agents).
*/
const { test, describe } = require('node:test');
const assert = require('node:assert');
process.env.GSD_TEST_MODE = '1';
const { convertClaudeToOpencodeFrontmatter } = require('../bin/install.js');
// Sample Claude agent frontmatter (matches actual GSD agent format)
const SAMPLE_AGENT = `---
name: gsd-executor
description: Executes GSD plans with atomic commits
tools: Read, Write, Edit, Bash, Grep, Glob
color: yellow
skills:
- gsd-executor-workflow
# hooks:
# PostToolUse:
# - matcher: "Write|Edit"
# hooks:
# - type: command
# command: "npx eslint --fix $FILE 2>/dev/null || true"
---
<role>
You are a GSD plan executor.
</role>`;
// Sample Claude command frontmatter (for comparison — commands work differently)
const SAMPLE_COMMAND = `---
name: gsd-execute-phase
description: Execute all plans in a phase
allowed-tools:
- Read
- Write
- Bash
---
Execute the phase plan.`;
describe('OpenCode agent conversion (isAgent: true)', () => {
test('keeps name: field for agents', () => {
const result = convertClaudeToOpencodeFrontmatter(SAMPLE_AGENT, { isAgent: true });
const frontmatter = result.split('---')[1];
assert.ok(frontmatter.includes('name: gsd-executor'), 'name: should be preserved for agents');
});
test('adds model: inherit', () => {
const result = convertClaudeToOpencodeFrontmatter(SAMPLE_AGENT, { isAgent: true });
const frontmatter = result.split('---')[1];
assert.ok(frontmatter.includes('model: inherit'), 'model: inherit should be added');
});
test('adds mode: subagent', () => {
const result = convertClaudeToOpencodeFrontmatter(SAMPLE_AGENT, { isAgent: true });
const frontmatter = result.split('---')[1];
assert.ok(frontmatter.includes('mode: subagent'), 'mode: subagent should be added');
});
test('strips tools: field', () => {
const result = convertClaudeToOpencodeFrontmatter(SAMPLE_AGENT, { isAgent: true });
const frontmatter = result.split('---')[1];
assert.ok(!frontmatter.includes('tools:'), 'tools: should be stripped for agents');
assert.ok(!frontmatter.includes('read: true'), 'tools object should not be generated');
});
test('strips skills: array', () => {
const result = convertClaudeToOpencodeFrontmatter(SAMPLE_AGENT, { isAgent: true });
const frontmatter = result.split('---')[1];
assert.ok(!frontmatter.includes('skills:'), 'skills: should be stripped');
assert.ok(!frontmatter.includes('gsd-executor-workflow'), 'skill entries should be stripped');
});
test('strips color: field', () => {
const result = convertClaudeToOpencodeFrontmatter(SAMPLE_AGENT, { isAgent: true });
const frontmatter = result.split('---')[1];
assert.ok(!frontmatter.includes('color:'), 'color: should be stripped for agents');
});
test('strips commented hooks block', () => {
const result = convertClaudeToOpencodeFrontmatter(SAMPLE_AGENT, { isAgent: true });
const frontmatter = result.split('---')[1];
assert.ok(!frontmatter.includes('# hooks:'), 'commented hooks should be stripped');
assert.ok(!frontmatter.includes('PostToolUse'), 'hook content should be stripped');
});
test('keeps description: field', () => {
const result = convertClaudeToOpencodeFrontmatter(SAMPLE_AGENT, { isAgent: true });
const frontmatter = result.split('---')[1];
assert.ok(frontmatter.includes('description: Executes GSD plans'), 'description should be kept');
});
test('preserves body content', () => {
const result = convertClaudeToOpencodeFrontmatter(SAMPLE_AGENT, { isAgent: true });
assert.ok(result.includes('<role>'), 'body should be preserved');
assert.ok(result.includes('You are a GSD plan executor.'), 'body content should be intact');
});
test('applies body text replacements', () => {
const agentWithClaudePaths = `---
name: test-agent
description: Test
tools: Read
---
Read ~/.claude/agent-memory/ for context.
Use $HOME/.claude/skills/ for reference.`;
const result = convertClaudeToOpencodeFrontmatter(agentWithClaudePaths, { isAgent: true });
assert.ok(result.includes('~/.config/opencode/agent-memory/'), '~/.claude should be replaced');
assert.ok(result.includes('$HOME/.config/opencode/skills/'), '$HOME/.claude should be replaced');
});
});
describe('OpenCode command conversion (isAgent: false, default)', () => {
test('strips name: field for commands', () => {
const result = convertClaudeToOpencodeFrontmatter(SAMPLE_COMMAND);
const frontmatter = result.split('---')[1];
assert.ok(!frontmatter.includes('name:'), 'name: should be stripped for commands');
});
test('does not add model: or mode: for commands', () => {
const result = convertClaudeToOpencodeFrontmatter(SAMPLE_COMMAND);
const frontmatter = result.split('---')[1];
assert.ok(!frontmatter.includes('model:'), 'model: should not be added for commands');
assert.ok(!frontmatter.includes('mode:'), 'mode: should not be added for commands');
});
test('keeps description: for commands', () => {
const result = convertClaudeToOpencodeFrontmatter(SAMPLE_COMMAND);
const frontmatter = result.split('---')[1];
assert.ok(frontmatter.includes('description:'), 'description should be kept');
});
});

View File

@@ -0,0 +1,100 @@
/**
* GSD Tests - path replacement in install.js
*
* Verifies that global installs produce ~/ paths in .md files,
* never resolved absolute paths containing os.homedir().
* Reproduces the bug where Windows installs write C:/Users/...
* paths that break in Docker containers.
*/
const { test, describe } = require('node:test');
const assert = require('node:assert');
const fs = require('fs');
const path = require('path');
const os = require('os');
const repoRoot = path.join(__dirname, '..');
// Simulate the pathPrefix computation from install.js (global install)
function computePathPrefix(homedir, targetDir) {
return path.resolve(targetDir).replace(homedir, '~').replace(/\\/g, '/') + '/';
}
describe('pathPrefix computation', () => {
test('default Claude global install uses ~/', () => {
const homedir = os.homedir();
const targetDir = path.join(homedir, '.claude');
const prefix = computePathPrefix(homedir, targetDir);
assert.strictEqual(prefix, '~/.claude/');
});
test('default Gemini global install uses ~/', () => {
const homedir = os.homedir();
const targetDir = path.join(homedir, '.gemini');
const prefix = computePathPrefix(homedir, targetDir);
assert.strictEqual(prefix, '~/.gemini/');
});
test('custom config dir under home uses ~/', () => {
const homedir = os.homedir();
const targetDir = path.join(homedir, '.config', 'claude');
const prefix = computePathPrefix(homedir, targetDir);
assert.ok(prefix.startsWith('~/'), `Expected ~/ prefix, got: ${prefix}`);
assert.ok(!prefix.includes(homedir), `Should not contain homedir: ${homedir}`);
});
test('Windows-style paths produce ~/ not C:/', () => {
// On Windows, path.resolve returns the input unchanged when it's already absolute.
// Simulate the string operation directly (can't use path.resolve for Windows paths on Linux).
const winHomedir = 'C:\\Users\\matte';
const winTargetDir = 'C:\\Users\\matte\\.claude';
// This is what the fix does: targetDir.replace(homedir, '~').replace(/\\/g, '/') + '/'
const prefix = winTargetDir.replace(winHomedir, '~').replace(/\\/g, '/') + '/';
assert.strictEqual(prefix, '~/.claude/');
assert.ok(!prefix.includes('C:'), `Should not contain drive letter, got: ${prefix}`);
});
});
describe('installed .md files contain no resolved absolute paths', () => {
const homedir = os.homedir();
const targetDir = path.join(homedir, '.claude');
const pathPrefix = computePathPrefix(homedir, targetDir);
const claudeDirRegex = /~\/\.claude\//g;
const claudeHomeRegex = /\$HOME\/\.claude\//g;
const normalizedHomedir = homedir.replace(/\\/g, '/');
// Collect all .md files from source directories
function collectMdFiles(dir) {
const results = [];
if (!fs.existsSync(dir)) return results;
for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
const fullPath = path.join(dir, entry.name);
if (entry.isDirectory()) {
results.push(...collectMdFiles(fullPath));
} else if (entry.name.endsWith('.md')) {
results.push(fullPath);
}
}
return results;
}
const dirsToCheck = ['commands', 'get-shit-done', 'agents'].map(d => path.join(repoRoot, d));
const mdFiles = dirsToCheck.flatMap(collectMdFiles);
test('source .md files exist', () => {
assert.ok(mdFiles.length > 0, `Expected .md files, found ${mdFiles.length}`);
});
test('after replacement, no .md file contains os.homedir()', () => {
const failures = [];
for (const file of mdFiles) {
let content = fs.readFileSync(file, 'utf8');
content = content.replace(claudeDirRegex, pathPrefix);
content = content.replace(claudeHomeRegex, pathPrefix);
if (content.includes(normalizedHomedir) && normalizedHomedir !== '~') {
failures.push(path.relative(repoRoot, file));
}
}
assert.deepStrictEqual(failures, [], `Files with resolved absolute paths: ${failures.join(', ')}`);
});
});

View File

@@ -1468,6 +1468,71 @@ describe('phase complete command', () => {
const req = fs.readFileSync(path.join(tmpDir, '.planning', 'REQUIREMENTS.md'), 'utf-8');
assert.ok(req.includes('- [ ] **AMT-01**'), 'AMT-01 should remain unchanged');
});
test('preserves Milestone column in 5-column progress table', () => {
fs.writeFileSync(
path.join(tmpDir, '.planning', 'ROADMAP.md'),
`# Roadmap
- [ ] Phase 1: Foundation
### Phase 1: Foundation
**Goal:** Setup
**Plans:** 1 plans
## Progress
| Phase | Milestone | Plans Complete | Status | Completed |
|-------|-----------|----------------|--------|-----------|
| 1. Foundation | v1.0 | 0/1 | Planned | |
`
);
fs.writeFileSync(
path.join(tmpDir, '.planning', 'STATE.md'),
`# State\n\n**Current Phase:** 01\n**Status:** In progress\n**Current Plan:** 01-01\n**Last Activity:** 2025-01-01\n**Last Activity Description:** Working\n`
);
const p1 = path.join(tmpDir, '.planning', 'phases', '01-foundation');
fs.mkdirSync(p1, { recursive: true });
fs.writeFileSync(path.join(p1, '01-01-PLAN.md'), '# Plan');
fs.writeFileSync(path.join(p1, '01-01-SUMMARY.md'), '# Summary');
const result = runGsdTools('phase complete 1', tmpDir);
assert.ok(result.success, `Command failed: ${result.error}`);
const roadmap = fs.readFileSync(path.join(tmpDir, '.planning', 'ROADMAP.md'), 'utf-8');
const rowMatch = roadmap.match(/^\|[^\n]*1\. Foundation[^\n]*$/m);
assert.ok(rowMatch, 'table row should exist');
const cells = rowMatch[0].split('|').slice(1, -1).map(c => c.trim());
assert.strictEqual(cells.length, 5, 'should have 5 columns');
assert.strictEqual(cells[1], 'v1.0', 'Milestone column should be preserved');
assert.ok(cells[3].includes('Complete'), 'Status column should be Complete');
});
test('updates STATE.md with plain format fields (no bold)', () => {
fs.writeFileSync(
path.join(tmpDir, '.planning', 'ROADMAP.md'),
`# Roadmap\n\n### Phase 1: Only\n**Goal:** Test\n`
);
fs.writeFileSync(
path.join(tmpDir, '.planning', 'STATE.md'),
`# State\n\nPhase: 1 of 1 (Only)\nStatus: In progress\nPlan: 01-01\nLast Activity: 2025-01-01\nLast Activity Description: Working\n`
);
const p1 = path.join(tmpDir, '.planning', 'phases', '01-only');
fs.mkdirSync(p1, { recursive: true });
fs.writeFileSync(path.join(p1, '01-01-PLAN.md'), '# Plan');
fs.writeFileSync(path.join(p1, '01-01-SUMMARY.md'), '# Summary');
const result = runGsdTools('phase complete 1', tmpDir);
assert.ok(result.success, `Command failed: ${result.error}`);
const state = fs.readFileSync(path.join(tmpDir, '.planning', 'STATE.md'), 'utf-8');
assert.ok(state.includes('Milestone complete'), 'plain Status field should be updated');
assert.ok(state.includes('Not started'), 'plain Plan field should be updated');
// Verify compound format preserved
assert.ok(state.match(/Phase:.*of\s+1/), 'should preserve "of N" in compound Phase format');
});
});
// ─────────────────────────────────────────────────────────────────────────────

View File

@@ -0,0 +1,197 @@
/**
* Profile Output Tests
*
* Tests for profile rendering commands and PROFILING_QUESTIONS data.
*/
const { test, describe, beforeEach, afterEach } = require('node:test');
const assert = require('node:assert');
const fs = require('fs');
const path = require('path');
const { runGsdTools, createTempProject, createTempGitProject, cleanup } = require('./helpers.cjs');
const {
PROFILING_QUESTIONS,
CLAUDE_INSTRUCTIONS,
} = require('../get-shit-done/bin/lib/profile-output.cjs');
// ─── PROFILING_QUESTIONS data ─────────────────────────────────────────────────
describe('PROFILING_QUESTIONS', () => {
test('is a non-empty array', () => {
assert.ok(Array.isArray(PROFILING_QUESTIONS));
assert.ok(PROFILING_QUESTIONS.length > 0);
});
test('each question has required fields', () => {
for (const q of PROFILING_QUESTIONS) {
assert.ok(q.dimension, `question missing dimension`);
assert.ok(q.header, `${q.dimension} missing header`);
assert.ok(q.question, `${q.dimension} missing question`);
assert.ok(Array.isArray(q.options), `${q.dimension} options should be array`);
assert.ok(q.options.length >= 2, `${q.dimension} should have at least 2 options`);
}
});
test('each option has label, value, and rating', () => {
for (const q of PROFILING_QUESTIONS) {
for (const opt of q.options) {
assert.ok(opt.label, `${q.dimension} option missing label`);
assert.ok(opt.value, `${q.dimension} option missing value`);
assert.ok(opt.rating, `${q.dimension} option missing rating`);
}
}
});
test('all dimension keys are unique', () => {
const dims = PROFILING_QUESTIONS.map(q => q.dimension);
const unique = [...new Set(dims)];
assert.strictEqual(dims.length, unique.length);
});
});
// ─── CLAUDE_INSTRUCTIONS ──────────────────────────────────────────────────────
describe('CLAUDE_INSTRUCTIONS', () => {
test('is a non-empty object', () => {
assert.ok(typeof CLAUDE_INSTRUCTIONS === 'object');
assert.ok(Object.keys(CLAUDE_INSTRUCTIONS).length > 0);
});
test('each dimension has at least one instruction', () => {
for (const [dim, instructions] of Object.entries(CLAUDE_INSTRUCTIONS)) {
assert.ok(typeof instructions === 'object', `${dim} should be an object`);
assert.ok(Object.keys(instructions).length > 0, `${dim} should have instructions`);
}
});
test('every PROFILING_QUESTIONS dimension has CLAUDE_INSTRUCTIONS', () => {
for (const q of PROFILING_QUESTIONS) {
assert.ok(
CLAUDE_INSTRUCTIONS[q.dimension],
`${q.dimension} has questions but no CLAUDE_INSTRUCTIONS`
);
}
});
});
// ─── write-profile command ────────────────────────────────────────────────────
describe('write-profile command', () => {
let tmpDir;
beforeEach(() => {
tmpDir = createTempProject();
});
afterEach(() => {
cleanup(tmpDir);
});
test('writes USER-PROFILE.md from analysis JSON', () => {
const analysis = {
profile_version: '1.0',
dimensions: {
communication_style: { rating: 'terse-direct', confidence: 'HIGH' },
decision_speed: { rating: 'fast-intuitive', confidence: 'MEDIUM' },
explanation_depth: { rating: 'concise', confidence: 'HIGH' },
debugging_approach: { rating: 'fix-first', confidence: 'LOW' },
ux_philosophy: { rating: 'function-first', confidence: 'MEDIUM' },
vendor_philosophy: { rating: 'pragmatic', confidence: 'HIGH' },
frustration_triggers: { rating: 'over-explanation', confidence: 'LOW' },
learning_style: { rating: 'hands-on', confidence: 'MEDIUM' },
},
};
const analysisPath = path.join(tmpDir, 'analysis.json');
fs.writeFileSync(analysisPath, JSON.stringify(analysis));
const result = runGsdTools(['write-profile', '--input', analysisPath, '--raw'], tmpDir);
assert.ok(result.success, `Failed: ${result.error}`);
const out = JSON.parse(result.output);
assert.ok(out.profile_path, 'should return profile_path');
assert.ok(out.dimensions_scored > 0, 'should have scored dimensions');
});
test('errors when --input is missing', () => {
const result = runGsdTools('write-profile --raw', tmpDir);
assert.ok(!result.success, 'should fail without --input');
assert.ok(result.error.includes('--input'), 'should mention --input');
});
});
// ─── generate-claude-md command ───────────────────────────────────────────────
describe('generate-claude-md command', () => {
let tmpDir;
beforeEach(() => {
tmpDir = createTempGitProject();
fs.writeFileSync(
path.join(tmpDir, '.planning', 'PROJECT.md'),
'# My Project\n\nA test project.\n\n## Tech Stack\n\n- Node.js\n- TypeScript\n'
);
});
afterEach(() => {
cleanup(tmpDir);
});
test('generates CLAUDE.md with --auto flag', () => {
const outputPath = path.join(tmpDir, 'CLAUDE.md');
const result = runGsdTools(['generate-claude-md', '--output', outputPath, '--auto', '--raw'], tmpDir);
assert.ok(result.success, `Failed: ${result.error}`);
if (fs.existsSync(outputPath)) {
const content = fs.readFileSync(outputPath, 'utf-8');
assert.ok(content.length > 0, 'should have content');
}
});
test('does not overwrite existing CLAUDE.md without --force', () => {
const outputPath = path.join(tmpDir, 'CLAUDE.md');
fs.writeFileSync(outputPath, '# Custom CLAUDE.md\n\nUser content.\n');
const result = runGsdTools(['generate-claude-md', '--output', outputPath, '--auto', '--raw'], tmpDir);
// Should merge, not overwrite
const content = fs.readFileSync(outputPath, 'utf-8');
assert.ok(content.length > 0, 'should still have content');
});
});
// ─── generate-dev-preferences ─────────────────────────────────────────────────
describe('generate-dev-preferences command', () => {
let tmpDir;
beforeEach(() => {
tmpDir = createTempProject();
});
afterEach(() => {
cleanup(tmpDir);
});
test('errors when --analysis is missing', () => {
const result = runGsdTools('generate-dev-preferences --raw', tmpDir);
assert.ok(!result.success, 'should fail without --analysis');
assert.ok(result.error.includes('--analysis'), 'should mention --analysis');
});
test('generates preferences from analysis file', () => {
const analysis = {
profile_version: '1.0',
dimensions: {
communication_style: { rating: 'terse-direct', confidence: 'HIGH' },
decision_speed: { rating: 'fast-intuitive', confidence: 'MEDIUM' },
},
};
const analysisPath = path.join(tmpDir, 'analysis.json');
fs.writeFileSync(analysisPath, JSON.stringify(analysis));
const result = runGsdTools(['generate-dev-preferences', '--analysis', analysisPath, '--raw'], tmpDir);
assert.ok(result.success, `Failed: ${result.error}`);
const out = JSON.parse(result.output);
assert.ok(out.command_path || out.command_name, 'should return command output');
});
});

View File

@@ -0,0 +1,160 @@
/**
* Profile Pipeline Tests
*
* Tests for session scanning, message extraction, and profile sampling.
* Uses synthetic session data in temp directories via --path override.
*/
const { test, describe, beforeEach, afterEach } = require('node:test');
const assert = require('node:assert');
const fs = require('fs');
const path = require('path');
const os = require('os');
const { runGsdTools, createTempProject, cleanup } = require('./helpers.cjs');
// ─── scan-sessions ────────────────────────────────────────────────────────────
describe('scan-sessions command', () => {
let tmpDir;
beforeEach(() => {
tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'gsd-profile-test-'));
});
afterEach(() => {
cleanup(tmpDir);
});
test('returns empty array for empty sessions directory', () => {
const sessionsDir = path.join(tmpDir, 'projects');
fs.mkdirSync(sessionsDir, { recursive: true });
const result = runGsdTools(`scan-sessions --path ${sessionsDir} --raw`, tmpDir);
assert.ok(result.success, `Failed: ${result.error}`);
const out = JSON.parse(result.output);
assert.ok(Array.isArray(out), 'should return an array');
assert.strictEqual(out.length, 0, 'should be empty');
});
test('scans synthetic project directory', () => {
const sessionsDir = path.join(tmpDir, 'projects');
const projectDir = path.join(sessionsDir, 'test-project-abc123');
fs.mkdirSync(projectDir, { recursive: true });
// Create a synthetic session file
const sessionData = [
JSON.stringify({ type: 'user', userType: 'external', message: { content: 'hello' }, timestamp: Date.now() }),
JSON.stringify({ type: 'assistant', message: { content: 'hi' }, timestamp: Date.now() }),
].join('\n');
fs.writeFileSync(path.join(projectDir, 'session-001.jsonl'), sessionData);
const result = runGsdTools(`scan-sessions --path ${sessionsDir} --raw`, tmpDir);
assert.ok(result.success, `Failed: ${result.error}`);
const out = JSON.parse(result.output);
assert.ok(Array.isArray(out), 'should return array');
assert.strictEqual(out.length, 1, 'should find 1 project');
assert.strictEqual(out[0].sessionCount, 1, 'should have 1 session');
});
test('reports multiple sessions and sizes', () => {
const sessionsDir = path.join(tmpDir, 'projects');
const projectDir = path.join(sessionsDir, 'multi-session-project');
fs.mkdirSync(projectDir, { recursive: true });
for (let i = 1; i <= 3; i++) {
const data = JSON.stringify({ type: 'user', userType: 'external', message: { content: `msg ${i}` }, timestamp: Date.now() });
fs.writeFileSync(path.join(projectDir, `session-${i}.jsonl`), data + '\n');
}
const result = runGsdTools(`scan-sessions --path ${sessionsDir} --raw`, tmpDir);
assert.ok(result.success, `Failed: ${result.error}`);
const out = JSON.parse(result.output);
assert.strictEqual(out[0].sessionCount, 3);
assert.ok(out[0].totalSize > 0, 'should have non-zero size');
});
});
// ─── extract-messages ─────────────────────────────────────────────────────────
describe('extract-messages command', () => {
let tmpDir;
beforeEach(() => {
tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'gsd-profile-test-'));
});
afterEach(() => {
cleanup(tmpDir);
});
test('extracts user messages from synthetic session', () => {
const sessionsDir = path.join(tmpDir, 'projects');
const projectDir = path.join(sessionsDir, 'my-project');
fs.mkdirSync(projectDir, { recursive: true });
const messages = [
{ type: 'user', userType: 'external', message: { content: 'fix the login bug' }, timestamp: Date.now() },
{ type: 'assistant', message: { content: 'I will fix it.' }, timestamp: Date.now() },
{ type: 'user', userType: 'external', message: { content: 'add dark mode' }, timestamp: Date.now() },
{ type: 'user', userType: 'internal', isMeta: true, message: { content: '<local-command' }, timestamp: Date.now() },
];
fs.writeFileSync(
path.join(projectDir, 'session-001.jsonl'),
messages.map(m => JSON.stringify(m)).join('\n')
);
const result = runGsdTools(`extract-messages my-project --path ${sessionsDir} --raw`, tmpDir);
assert.ok(result.success, `Failed: ${result.error}`);
const out = JSON.parse(result.output);
assert.strictEqual(out.messages_extracted, 2, 'should extract 2 genuine user messages');
assert.strictEqual(out.project, 'my-project');
assert.ok(out.output_file, 'should have output file path');
});
test('filters out meta and internal messages', () => {
const sessionsDir = path.join(tmpDir, 'projects');
const projectDir = path.join(sessionsDir, 'filter-test');
fs.mkdirSync(projectDir, { recursive: true });
const messages = [
{ type: 'user', userType: 'external', message: { content: 'real message' }, timestamp: Date.now() },
{ type: 'user', userType: 'internal', message: { content: 'internal msg' }, timestamp: Date.now() },
{ type: 'user', userType: 'external', isMeta: true, message: { content: 'meta msg' }, timestamp: Date.now() },
{ type: 'user', userType: 'external', message: { content: '<local-command test' }, timestamp: Date.now() },
{ type: 'user', userType: 'external', message: { content: '' }, timestamp: Date.now() },
{ type: 'user', userType: 'external', message: { content: 'second real' }, timestamp: Date.now() },
];
fs.writeFileSync(
path.join(projectDir, 'session-001.jsonl'),
messages.map(m => JSON.stringify(m)).join('\n')
);
const result = runGsdTools(`extract-messages filter-test --path ${sessionsDir} --raw`, tmpDir);
assert.ok(result.success, `Failed: ${result.error}`);
const out = JSON.parse(result.output);
assert.strictEqual(out.messages_extracted, 2, 'should only extract 2 genuine external messages');
});
});
// ─── profile-questionnaire ────────────────────────────────────────────────────
describe('profile-questionnaire command', () => {
let tmpDir;
beforeEach(() => {
tmpDir = createTempProject();
});
afterEach(() => {
cleanup(tmpDir);
});
test('returns questionnaire structure', () => {
const result = runGsdTools('profile-questionnaire --raw', tmpDir);
assert.ok(result.success, `Failed: ${result.error}`);
const out = JSON.parse(result.output);
assert.ok(out.questions, 'should have questions array');
assert.ok(out.questions.length > 0, 'should have at least one question');
assert.ok(out.questions[0].dimension, 'each question should have a dimension');
assert.ok(out.questions[0].options, 'each question should have options');
});
});

View File

@@ -0,0 +1,39 @@
/**
* Quick task branching tests
*
* Validates that /gsd:quick exposes branch_name from init and that the
* workflow checks out a dedicated quick-task branch when configured.
*/
const { test, describe } = require('node:test');
const assert = require('node:assert');
const fs = require('fs');
const path = require('path');
describe('quick workflow: branching support', () => {
const workflowPath = path.join(__dirname, '..', 'get-shit-done', 'workflows', 'quick.md');
let content;
test('workflow file exists', () => {
assert.ok(fs.existsSync(workflowPath), 'workflows/quick.md should exist');
});
test('init parse list includes branch_name', () => {
content = fs.readFileSync(workflowPath, 'utf-8');
assert.ok(content.includes('branch_name'), 'quick workflow should parse branch_name from init JSON');
});
test('workflow includes quick-task branching step', () => {
content = fs.readFileSync(workflowPath, 'utf-8');
assert.ok(content.includes('Step 2.5: Handle quick-task branching'));
assert.ok(content.includes('git checkout -b "$branch_name" 2>/dev/null || git checkout "$branch_name"'));
});
test('branching step runs before task directory creation', () => {
content = fs.readFileSync(workflowPath, 'utf-8');
const branchingIndex = content.indexOf('Step 2.5: Handle quick-task branching');
const createDirIndex = content.indexOf('Step 3: Create task directory');
assert.ok(branchingIndex !== -1 && createDirIndex !== -1, 'workflow should contain both branching and directory steps');
assert.ok(branchingIndex < createDirIndex, 'branching should happen before quick task directories and commits');
});
});

View File

@@ -756,6 +756,74 @@ describe('roadmap update-plan-progress command', () => {
assert.strictEqual(output.updated, false, 'should not update');
assert.ok(output.reason.includes('ROADMAP.md not found'), 'reason should mention missing ROADMAP.md');
});
test('marks completed plan checkboxes', () => {
const roadmapContent = `# Roadmap
- [ ] Phase 50: Build
- [ ] 50-01-PLAN.md
- [ ] 50-02-PLAN.md
### Phase 50: Build
**Goal:** Build stuff
**Plans:** 2 plans
## Progress
| Phase | Plans Complete | Status | Completed |
|-------|---------------|--------|-----------|
| 50. Build | 0/2 | Planned | |
`;
fs.writeFileSync(path.join(tmpDir, '.planning', 'ROADMAP.md'), roadmapContent);
const p50 = path.join(tmpDir, '.planning', 'phases', '50-build');
fs.mkdirSync(p50, { recursive: true });
fs.writeFileSync(path.join(p50, '50-01-PLAN.md'), '# Plan 1');
fs.writeFileSync(path.join(p50, '50-02-PLAN.md'), '# Plan 2');
// Only plan 1 has a summary (completed)
fs.writeFileSync(path.join(p50, '50-01-SUMMARY.md'), '# Summary 1');
const result = runGsdTools('roadmap update-plan-progress 50', tmpDir);
assert.ok(result.success, `Command failed: ${result.error}`);
const roadmap = fs.readFileSync(path.join(tmpDir, '.planning', 'ROADMAP.md'), 'utf-8');
assert.ok(roadmap.includes('[x] 50-01-PLAN.md') || roadmap.includes('[x] 50-01'),
'completed plan checkbox should be marked');
assert.ok(roadmap.includes('[ ] 50-02-PLAN.md') || roadmap.includes('[ ] 50-02'),
'incomplete plan checkbox should remain unchecked');
});
test('preserves Milestone column in 5-column progress table', () => {
const roadmapContent = `# Roadmap
### Phase 50: Build
**Goal:** Build stuff
**Plans:** 1 plans
## Progress
| Phase | Milestone | Plans Complete | Status | Completed |
|-------|-----------|----------------|--------|-----------|
| 50. Build | v2.0 | 0/1 | Planned | |
`;
fs.writeFileSync(path.join(tmpDir, '.planning', 'ROADMAP.md'), roadmapContent);
const p50 = path.join(tmpDir, '.planning', 'phases', '50-build');
fs.mkdirSync(p50, { recursive: true });
fs.writeFileSync(path.join(p50, '50-01-PLAN.md'), '# Plan');
fs.writeFileSync(path.join(p50, '50-01-SUMMARY.md'), '# Summary');
const result = runGsdTools('roadmap update-plan-progress 50', tmpDir);
assert.ok(result.success, `Command failed: ${result.error}`);
const roadmap = fs.readFileSync(path.join(tmpDir, '.planning', 'ROADMAP.md'), 'utf-8');
const rowMatch = roadmap.match(/^\|[^\n]*50\. Build[^\n]*$/m);
assert.ok(rowMatch, 'table row should exist');
const cells = rowMatch[0].split('|').slice(1, -1).map(c => c.trim());
assert.strictEqual(cells.length, 5, 'should have 5 columns');
assert.strictEqual(cells[1], 'v2.0', 'Milestone column should be preserved');
assert.ok(cells[3].includes('Complete'), 'Status column should show Complete');
});
});
// ─────────────────────────────────────────────────────────────────────────────

View File

@@ -0,0 +1,239 @@
/**
* Runtime Converter Tests — OpenCode + Gemini
*
* Tests for small runtime-specific conversion functions from install.js.
* Larger runtime test suites (Copilot, Codex, Antigravity) have their own files.
*
* OpenCode: convertClaudeToOpencodeFrontmatter (agent + command modes)
* model: inherit is NOT added (OpenCode doesn't support it — see #1156)
* but mode: subagent IS added (required by OpenCode agents).
* Gemini: convertClaudeToGeminiAgent (frontmatter + tool mapping + body escaping)
*/
const { test, describe } = require('node:test');
const assert = require('node:assert');
process.env.GSD_TEST_MODE = '1';
const {
convertClaudeToOpencodeFrontmatter,
convertClaudeToGeminiAgent,
neutralizeAgentReferences,
} = require('../bin/install.js');
// Sample Claude agent frontmatter (matches actual GSD agent format)
const SAMPLE_AGENT = `---
name: gsd-executor
description: Executes GSD plans with atomic commits
tools: Read, Write, Edit, Bash, Grep, Glob
color: yellow
skills:
- gsd-executor-workflow
# hooks:
# PostToolUse:
# - matcher: "Write|Edit"
# hooks:
# - type: command
# command: "npx eslint --fix $FILE 2>/dev/null || true"
---
<role>
You are a GSD plan executor.
</role>`;
// Sample Claude command frontmatter (for comparison — commands work differently)
const SAMPLE_COMMAND = `---
name: gsd-execute-phase
description: Execute all plans in a phase
allowed-tools:
- Read
- Write
- Bash
---
Execute the phase plan.`;
describe('OpenCode agent conversion (isAgent: true)', () => {
test('keeps name: field for agents', () => {
const result = convertClaudeToOpencodeFrontmatter(SAMPLE_AGENT, { isAgent: true });
const frontmatter = result.split('---')[1];
assert.ok(frontmatter.includes('name: gsd-executor'), 'name: should be preserved for agents');
});
test('does not add model: inherit (OpenCode does not support it)', () => {
const result = convertClaudeToOpencodeFrontmatter(SAMPLE_AGENT, { isAgent: true });
const frontmatter = result.split('---')[1];
assert.ok(!frontmatter.includes('model: inherit'), 'model: inherit should NOT be added — OpenCode throws ProviderModelNotFoundError');
});
test('adds mode: subagent', () => {
const result = convertClaudeToOpencodeFrontmatter(SAMPLE_AGENT, { isAgent: true });
const frontmatter = result.split('---')[1];
assert.ok(frontmatter.includes('mode: subagent'), 'mode: subagent should be added');
});
test('strips tools: field', () => {
const result = convertClaudeToOpencodeFrontmatter(SAMPLE_AGENT, { isAgent: true });
const frontmatter = result.split('---')[1];
assert.ok(!frontmatter.includes('tools:'), 'tools: should be stripped for agents');
assert.ok(!frontmatter.includes('read: true'), 'tools object should not be generated');
});
test('strips skills: array', () => {
const result = convertClaudeToOpencodeFrontmatter(SAMPLE_AGENT, { isAgent: true });
const frontmatter = result.split('---')[1];
assert.ok(!frontmatter.includes('skills:'), 'skills: should be stripped');
assert.ok(!frontmatter.includes('gsd-executor-workflow'), 'skill entries should be stripped');
});
test('strips color: field', () => {
const result = convertClaudeToOpencodeFrontmatter(SAMPLE_AGENT, { isAgent: true });
const frontmatter = result.split('---')[1];
assert.ok(!frontmatter.includes('color:'), 'color: should be stripped for agents');
});
test('strips commented hooks block', () => {
const result = convertClaudeToOpencodeFrontmatter(SAMPLE_AGENT, { isAgent: true });
const frontmatter = result.split('---')[1];
assert.ok(!frontmatter.includes('# hooks:'), 'commented hooks should be stripped');
assert.ok(!frontmatter.includes('PostToolUse'), 'hook content should be stripped');
});
test('keeps description: field', () => {
const result = convertClaudeToOpencodeFrontmatter(SAMPLE_AGENT, { isAgent: true });
const frontmatter = result.split('---')[1];
assert.ok(frontmatter.includes('description: Executes GSD plans'), 'description should be kept');
});
test('preserves body content', () => {
const result = convertClaudeToOpencodeFrontmatter(SAMPLE_AGENT, { isAgent: true });
assert.ok(result.includes('<role>'), 'body should be preserved');
assert.ok(result.includes('You are a GSD plan executor.'), 'body content should be intact');
});
test('applies body text replacements', () => {
const agentWithClaudePaths = `---
name: test-agent
description: Test
tools: Read
---
Read ~/.claude/agent-memory/ for context.
Use $HOME/.claude/skills/ for reference.`;
const result = convertClaudeToOpencodeFrontmatter(agentWithClaudePaths, { isAgent: true });
assert.ok(result.includes('~/.config/opencode/agent-memory/'), '~/.claude should be replaced');
assert.ok(result.includes('$HOME/.config/opencode/skills/'), '$HOME/.claude should be replaced');
});
});
describe('OpenCode command conversion (isAgent: false, default)', () => {
test('strips name: field for commands', () => {
const result = convertClaudeToOpencodeFrontmatter(SAMPLE_COMMAND);
const frontmatter = result.split('---')[1];
assert.ok(!frontmatter.includes('name:'), 'name: should be stripped for commands');
});
test('does not add model: or mode: for commands', () => {
const result = convertClaudeToOpencodeFrontmatter(SAMPLE_COMMAND);
const frontmatter = result.split('---')[1];
assert.ok(!frontmatter.includes('model:'), 'model: should not be added for commands');
assert.ok(!frontmatter.includes('mode:'), 'mode: should not be added for commands');
});
test('keeps description: for commands', () => {
const result = convertClaudeToOpencodeFrontmatter(SAMPLE_COMMAND);
const frontmatter = result.split('---')[1];
assert.ok(frontmatter.includes('description:'), 'description should be kept');
});
});
// ─────────────────────────────────────────────────────────────────────────────
// Gemini CLI agent conversion (merged from gemini-config.test.cjs)
// ─────────────────────────────────────────────────────────────────────────────
describe('convertClaudeToGeminiAgent', () => {
test('drops unsupported skills frontmatter while keeping converted tools', () => {
const input = `---
name: gsd-codebase-mapper
description: Explores codebase and writes structured analysis documents.
tools: Read, Bash, Grep, Glob, Write
color: cyan
skills:
- gsd-mapper-workflow
---
<role>
Use \${PHASE} in shell examples.
</role>`;
const result = convertClaudeToGeminiAgent(input);
const frontmatter = result.split('---')[1] || '';
assert.ok(frontmatter.includes('name: gsd-codebase-mapper'), 'keeps name');
assert.ok(frontmatter.includes('description: Explores codebase and writes structured analysis documents.'), 'keeps description');
assert.ok(frontmatter.includes('tools:'), 'adds Gemini tools array');
assert.ok(frontmatter.includes(' - read_file'), 'maps Read -> read_file');
assert.ok(frontmatter.includes(' - run_shell_command'), 'maps Bash -> run_shell_command');
assert.ok(frontmatter.includes(' - search_file_content'), 'maps Grep -> search_file_content');
assert.ok(frontmatter.includes(' - glob'), 'maps Glob -> glob');
assert.ok(frontmatter.includes(' - write_file'), 'maps Write -> write_file');
assert.ok(!frontmatter.includes('color:'), 'drops unsupported color field');
assert.ok(!frontmatter.includes('skills:'), 'drops unsupported skills field');
assert.ok(!frontmatter.includes('gsd-mapper-workflow'), 'drops skills list items');
assert.ok(result.includes('$PHASE'), 'escapes ${PHASE} shell variable for Gemini');
assert.ok(!result.includes('${PHASE}'), 'removes Gemini template-string pattern');
});
});
// ─── neutralizeAgentReferences (#766) ─────────────────────────────────────────
describe('neutralizeAgentReferences', () => {
test('replaces standalone Claude with "the agent"', () => {
const input = 'Claude handles these decisions. Claude should read the file.';
const result = neutralizeAgentReferences(input, 'AGENTS.md');
assert.ok(!result.includes('Claude handles'), 'standalone Claude replaced');
assert.ok(result.includes('the agent handles'), 'replaced with "the agent"');
});
test('preserves Claude Code (product name)', () => {
const input = 'This is a Claude Code bug. Use Claude Code settings.';
const result = neutralizeAgentReferences(input, 'AGENTS.md');
assert.ok(result.includes('Claude Code bug'), 'Claude Code preserved');
assert.ok(result.includes('Claude Code settings'), 'Claude Code preserved');
});
test('preserves Claude model names', () => {
const input = 'Use Claude Opus for planning. Claude Sonnet for execution. Claude Haiku for research.';
const result = neutralizeAgentReferences(input, 'AGENTS.md');
assert.ok(result.includes('Claude Opus'), 'Opus preserved');
assert.ok(result.includes('Claude Sonnet'), 'Sonnet preserved');
assert.ok(result.includes('Claude Haiku'), 'Haiku preserved');
});
test('replaces CLAUDE.md with runtime instruction file', () => {
const input = 'Read CLAUDE.md for project instructions. Check ./CLAUDE.md if exists.';
const result = neutralizeAgentReferences(input, 'AGENTS.md');
assert.ok(result.includes('AGENTS.md'), 'CLAUDE.md -> AGENTS.md');
assert.ok(!result.includes('CLAUDE.md'), 'no CLAUDE.md remains');
});
test('uses different instruction file per runtime', () => {
const input = 'Read CLAUDE.md for instructions.';
assert.ok(neutralizeAgentReferences(input, 'GEMINI.md').includes('GEMINI.md'));
assert.ok(neutralizeAgentReferences(input, 'copilot-instructions.md').includes('copilot-instructions.md'));
assert.ok(neutralizeAgentReferences(input, 'AGENTS.md').includes('AGENTS.md'));
});
test('removes AGENTS.md load-blocking instruction', () => {
const input = 'Do NOT load full `AGENTS.md` files — they contain agent definitions.';
const result = neutralizeAgentReferences(input, 'AGENTS.md');
assert.ok(!result.includes('Do NOT load full'), 'blocking instruction removed');
});
test('preserves claude- prefixes (CSS classes, package names)', () => {
const input = 'The claude-ctx session and claude-code package.';
const result = neutralizeAgentReferences(input, 'AGENTS.md');
assert.ok(result.includes('claude-ctx'), 'claude- prefix preserved');
assert.ok(result.includes('claude-code'), 'claude-code preserved');
});
});

View File

@@ -506,7 +506,7 @@ describe('STATE.md frontmatter sync', () => {
// stateExtractField and stateReplaceField helpers
// ─────────────────────────────────────────────────────────────────────────────
const { stateExtractField, stateReplaceField } = require('../get-shit-done/bin/lib/state.cjs');
const { stateExtractField, stateReplaceField, stateReplaceFieldWithFallback } = require('../get-shit-done/bin/lib/state.cjs');
describe('stateExtractField and stateReplaceField helpers', () => {
// stateExtractField tests
@@ -585,6 +585,45 @@ describe('stateExtractField and stateReplaceField helpers', () => {
});
});
// ─────────────────────────────────────────────────────────────────────────────
// stateReplaceFieldWithFallback — consolidated fallback helper
// ─────────────────────────────────────────────────────────────────────────────
describe('stateReplaceFieldWithFallback', () => {
test('replaces primary field when present', () => {
const content = '# State\n\n**Status:** Old\n';
const result = stateReplaceFieldWithFallback(content, 'Status', null, 'New');
assert.ok(result.includes('**Status:** New'));
});
test('falls back to secondary field when primary not found', () => {
const content = '# State\n\nLast activity: 2024-01-01\n';
const result = stateReplaceFieldWithFallback(content, 'Last Activity', 'Last activity', '2025-03-19');
assert.ok(result.includes('Last activity: 2025-03-19'), 'should update fallback field');
});
test('returns content unchanged when neither field matches', () => {
const content = '# State\n\n**Phase:** 3\n';
const result = stateReplaceFieldWithFallback(content, 'Status', 'state', 'New');
assert.strictEqual(result, content, 'content should be unchanged');
});
test('prefers primary over fallback when both exist', () => {
const content = '# State\n\n**Status:** Old\nStatus: Also old\n';
const result = stateReplaceFieldWithFallback(content, 'Status', 'Status', 'New');
// Bold format is tried first by stateReplaceField
assert.ok(result.includes('**Status:** New'), 'should replace bold (primary) format');
});
test('works with plain format fields', () => {
const content = '# State\n\nPhase: 1 of 3 (Foundation)\nStatus: In progress\nPlan: 01-01\n';
let updated = stateReplaceFieldWithFallback(content, 'Status', null, 'Complete');
assert.ok(updated.includes('Status: Complete'), 'should update plain Status');
updated = stateReplaceFieldWithFallback(updated, 'Current Plan', 'Plan', 'Not started');
assert.ok(updated.includes('Plan: Not started'), 'should fall back to Plan field');
});
});
// ─────────────────────────────────────────────────────────────────────────────
// cmdStateLoad, cmdStateGet, cmdStatePatch, cmdStateUpdate CLI tests
// ─────────────────────────────────────────────────────────────────────────────
@@ -892,6 +931,45 @@ describe('cmdStateAdvancePlan (state advance-plan)', () => {
assert.ok(output.error !== undefined, 'output should have error field');
assert.ok(output.error.toLowerCase().includes('cannot parse'), 'error should mention Cannot parse');
});
test('advances plan in compound "Plan: X of Y" format', () => {
fs.writeFileSync(
path.join(tmpDir, '.planning', 'STATE.md'),
`# Project State\n\nPlan: 2 of 5 in current phase\nStatus: In progress\nLast activity: 2025-01-01\n`
);
const result = runGsdTools('state advance-plan', tmpDir);
assert.ok(result.success, `Command failed: ${result.error}`);
const output = JSON.parse(result.output);
assert.strictEqual(output.advanced, true, 'advanced should be true');
assert.strictEqual(output.previous_plan, 2);
assert.strictEqual(output.current_plan, 3);
assert.strictEqual(output.total_plans, 5);
const updated = fs.readFileSync(path.join(tmpDir, '.planning', 'STATE.md'), 'utf-8');
assert.ok(updated.includes('Plan: 3 of 5 in current phase'),
'should preserve compound format with updated plan number');
assert.ok(updated.includes('Status: Ready to execute'),
'Status should be updated');
});
test('marks phase complete on last plan in compound format', () => {
fs.writeFileSync(
path.join(tmpDir, '.planning', 'STATE.md'),
`# Project State\n\nPlan: 3 of 3 in current phase\nStatus: In progress\nLast activity: 2025-01-01\n`
);
const result = runGsdTools('state advance-plan', tmpDir);
assert.ok(result.success, `Command failed: ${result.error}`);
const output = JSON.parse(result.output);
assert.strictEqual(output.advanced, false);
assert.strictEqual(output.reason, 'last_plan');
const updated = fs.readFileSync(path.join(tmpDir, '.planning', 'STATE.md'), 'utf-8');
assert.ok(updated.includes('Phase complete'), 'Status should contain Phase complete');
});
});
describe('cmdStateRecordMetric (state record-metric)', () => {

186
tests/template.test.cjs Normal file
View File

@@ -0,0 +1,186 @@
/**
* Template Tests
*
* Tests for cmdTemplateSelect (heuristic template selection) and
* cmdTemplateFill (summary, plan, verification template generation).
*/
const { test, describe, beforeEach, afterEach } = require('node:test');
const assert = require('node:assert');
const fs = require('fs');
const path = require('path');
const { runGsdTools, createTempProject, cleanup } = require('./helpers.cjs');
// ─── template select ──────────────────────────────────────────────────────────
describe('template select command', () => {
let tmpDir;
beforeEach(() => {
tmpDir = createTempProject();
// Create a phase directory with a plan
const phaseDir = path.join(tmpDir, '.planning', 'phases', '01-setup');
fs.mkdirSync(phaseDir, { recursive: true });
});
afterEach(() => {
cleanup(tmpDir);
});
test('selects minimal template for simple plan', () => {
const planPath = path.join(tmpDir, '.planning', 'phases', '01-setup', '01-01-PLAN.md');
fs.writeFileSync(planPath, [
'# Plan',
'',
'### Task 1',
'Do the thing.',
'',
'File: `src/index.ts`',
].join('\n'));
const result = runGsdTools(`template select .planning/phases/01-setup/01-01-PLAN.md`, tmpDir);
assert.ok(result.success, `Failed: ${result.error}`);
const out = JSON.parse(result.output);
assert.strictEqual(out.type, 'minimal');
assert.ok(out.template.includes('summary-minimal'));
});
test('selects standard template for moderate plan', () => {
const planPath = path.join(tmpDir, '.planning', 'phases', '01-setup', '01-01-PLAN.md');
fs.writeFileSync(planPath, [
'# Plan',
'',
'### Task 1',
'Create `src/auth/login.ts`',
'',
'### Task 2',
'Create `src/auth/register.ts`',
'',
'### Task 3',
'Update `src/routes/index.ts`',
'',
'Files: `src/auth/login.ts`, `src/auth/register.ts`, `src/routes/index.ts`, `src/middleware/auth.ts`',
].join('\n'));
const result = runGsdTools(`template select .planning/phases/01-setup/01-01-PLAN.md`, tmpDir);
assert.ok(result.success, `Failed: ${result.error}`);
const out = JSON.parse(result.output);
assert.strictEqual(out.type, 'standard');
});
test('selects complex template for plan with decisions and many files', () => {
const planPath = path.join(tmpDir, '.planning', 'phases', '01-setup', '01-01-PLAN.md');
const lines = ['# Plan', ''];
for (let i = 1; i <= 6; i++) {
lines.push(`### Task ${i}`, `Do task ${i}.`, '');
}
lines.push('Made a decision about architecture.', 'Another decision here.');
for (let i = 1; i <= 8; i++) {
lines.push(`File: \`src/module${i}/index.ts\``);
}
fs.writeFileSync(planPath, lines.join('\n'));
const result = runGsdTools(`template select .planning/phases/01-setup/01-01-PLAN.md`, tmpDir);
assert.ok(result.success, `Failed: ${result.error}`);
const out = JSON.parse(result.output);
assert.strictEqual(out.type, 'complex');
});
test('returns standard as fallback for nonexistent file', () => {
const result = runGsdTools(`template select .planning/phases/01-setup/nonexistent.md`, tmpDir);
assert.ok(result.success, `Failed: ${result.error}`);
const out = JSON.parse(result.output);
assert.strictEqual(out.type, 'standard');
assert.ok(out.error, 'should include error message');
});
});
// ─── template fill ────────────────────────────────────────────────────────────
describe('template fill command', () => {
let tmpDir;
beforeEach(() => {
tmpDir = createTempProject();
const phaseDir = path.join(tmpDir, '.planning', 'phases', '01-setup');
fs.mkdirSync(phaseDir, { recursive: true });
fs.writeFileSync(
path.join(tmpDir, '.planning', 'ROADMAP.md'),
'## Roadmap\n\n### Phase 1: Setup\n**Goal:** Initial setup\n'
);
});
afterEach(() => {
cleanup(tmpDir);
});
test('fills summary template', () => {
const result = runGsdTools('template fill summary --phase 1', tmpDir);
assert.ok(result.success, `Failed: ${result.error}`);
const out = JSON.parse(result.output);
assert.strictEqual(out.created, true);
assert.ok(out.path.includes('01-01-SUMMARY.md'));
const content = fs.readFileSync(path.join(tmpDir, out.path), 'utf-8');
assert.ok(content.includes('---'), 'should have frontmatter');
assert.ok(content.includes('Phase 1'), 'should reference phase');
assert.ok(content.includes('Accomplishments'), 'should have accomplishments section');
});
test('fills plan template', () => {
const result = runGsdTools('template fill plan --phase 1', tmpDir);
assert.ok(result.success, `Failed: ${result.error}`);
const out = JSON.parse(result.output);
assert.strictEqual(out.created, true);
assert.ok(out.path.includes('01-01-PLAN.md'));
const content = fs.readFileSync(path.join(tmpDir, out.path), 'utf-8');
assert.ok(content.includes('---'), 'should have frontmatter');
assert.ok(content.includes('Objective'), 'should have objective section');
assert.ok(content.includes('<task type="code">'), 'should have task XML');
});
test('fills verification template', () => {
const result = runGsdTools('template fill verification --phase 1', tmpDir);
assert.ok(result.success, `Failed: ${result.error}`);
const out = JSON.parse(result.output);
assert.strictEqual(out.created, true);
assert.ok(out.path.includes('01-VERIFICATION.md'));
const content = fs.readFileSync(path.join(tmpDir, out.path), 'utf-8');
assert.ok(content.includes('Observable Truths'), 'should have truths section');
assert.ok(content.includes('Required Artifacts'), 'should have artifacts section');
});
test('rejects existing file', () => {
// Create the file first
const phaseDir = path.join(tmpDir, '.planning', 'phases', '01-setup');
fs.writeFileSync(path.join(phaseDir, '01-01-SUMMARY.md'), '# Existing');
const result = runGsdTools('template fill summary --phase 1', tmpDir);
assert.ok(result.success); // outputs JSON, doesn't crash
const out = JSON.parse(result.output);
assert.ok(out.error, 'should report error for existing file');
assert.ok(out.error.includes('already exists'));
});
test('errors on unknown template type', () => {
const result = runGsdTools('template fill bogus --phase 1', tmpDir);
assert.ok(!result.success, 'should fail for unknown type');
assert.ok(result.error.includes('Unknown template type'));
});
test('errors when phase not found', () => {
const result = runGsdTools('template fill summary --phase 99', tmpDir);
assert.ok(result.success);
const out = JSON.parse(result.output);
assert.ok(out.error, 'should report phase not found');
});
test('respects --plan option for plan number', () => {
const result = runGsdTools('template fill plan --phase 1 --plan 03', tmpDir);
assert.ok(result.success, `Failed: ${result.error}`);
const out = JSON.parse(result.output);
assert.ok(out.path.includes('01-03-PLAN.md'), `Expected plan 03 in path, got ${out.path}`);
});
});

326
tests/uat.test.cjs Normal file
View File

@@ -0,0 +1,326 @@
/**
* GSD Tools Tests - UAT Audit
*/
const { test, describe, beforeEach, afterEach } = require('node:test');
const assert = require('node:assert');
const fs = require('fs');
const path = require('path');
const { runGsdTools, createTempProject, cleanup } = require('./helpers.cjs');
describe('audit-uat command', () => {
let tmpDir;
beforeEach(() => {
tmpDir = createTempProject();
});
afterEach(() => {
cleanup(tmpDir);
});
test('returns empty results when no UAT files exist', () => {
// Create a phase directory with no UAT files
fs.mkdirSync(path.join(tmpDir, '.planning', 'phases', '01-foundation'), { recursive: true });
fs.writeFileSync(path.join(tmpDir, '.planning', 'phases', '01-foundation', '.gitkeep'), '');
const result = runGsdTools('audit-uat --raw', tmpDir);
assert.ok(result.success, `Command failed: ${result.error}`);
const output = JSON.parse(result.output);
assert.deepStrictEqual(output.results, []);
assert.strictEqual(output.summary.total_items, 0);
assert.strictEqual(output.summary.total_files, 0);
});
test('detects UAT with pending items', () => {
const phaseDir = path.join(tmpDir, '.planning', 'phases', '01-foundation');
fs.mkdirSync(phaseDir, { recursive: true });
fs.writeFileSync(path.join(phaseDir, '01-UAT.md'), `---
status: testing
phase: 01-foundation
started: 2025-01-01T00:00:00Z
updated: 2025-01-01T00:00:00Z
---
## Tests
### 1. Login Form
expected: Form displays with email and password fields
result: pass
### 2. Submit Button
expected: Submitting shows loading state
result: pending
`);
const result = runGsdTools('audit-uat --raw', tmpDir);
assert.ok(result.success, `Command failed: ${result.error}`);
const output = JSON.parse(result.output);
assert.strictEqual(output.summary.total_items, 1);
assert.strictEqual(output.results[0].phase, '01');
assert.strictEqual(output.results[0].items[0].result, 'pending');
assert.strictEqual(output.results[0].items[0].category, 'pending');
assert.strictEqual(output.results[0].items[0].name, 'Submit Button');
});
test('detects UAT with blocked items and categorizes blocked_by', () => {
const phaseDir = path.join(tmpDir, '.planning', 'phases', '02-api');
fs.mkdirSync(phaseDir, { recursive: true });
fs.writeFileSync(path.join(phaseDir, '02-UAT.md'), `---
status: partial
phase: 02-api
started: 2025-01-01T00:00:00Z
updated: 2025-01-01T00:00:00Z
---
## Tests
### 1. API Health Check
expected: Returns 200 OK
result: blocked
blocked_by: server
reason: Server not running locally
`);
const result = runGsdTools('audit-uat --raw', tmpDir);
assert.ok(result.success, `Command failed: ${result.error}`);
const output = JSON.parse(result.output);
assert.strictEqual(output.summary.total_items, 1);
assert.strictEqual(output.results[0].items[0].result, 'blocked');
assert.strictEqual(output.results[0].items[0].category, 'server_blocked');
assert.strictEqual(output.results[0].items[0].blocked_by, 'server');
});
test('detects false completion (complete status with pending items)', () => {
const phaseDir = path.join(tmpDir, '.planning', 'phases', '03-ui');
fs.mkdirSync(phaseDir, { recursive: true });
fs.writeFileSync(path.join(phaseDir, '03-UAT.md'), `---
status: complete
phase: 03-ui
started: 2025-01-01T00:00:00Z
updated: 2025-01-01T00:00:00Z
---
## Tests
### 1. Dashboard Layout
expected: Cards render in grid
result: pass
### 2. Mobile Responsive
expected: Grid collapses to single column on mobile
result: pending
`);
const result = runGsdTools('audit-uat --raw', tmpDir);
assert.ok(result.success, `Command failed: ${result.error}`);
const output = JSON.parse(result.output);
assert.strictEqual(output.summary.total_items, 1);
assert.strictEqual(output.results[0].status, 'complete');
assert.strictEqual(output.results[0].items[0].result, 'pending');
});
test('extracts human_needed items from VERIFICATION files', () => {
const phaseDir = path.join(tmpDir, '.planning', 'phases', '04-auth');
fs.mkdirSync(phaseDir, { recursive: true });
fs.writeFileSync(path.join(phaseDir, '04-VERIFICATION.md'), `---
status: human_needed
phase: 04-auth
---
## Automated Checks
All passed.
## Human Verification
1. Test SSO login with Google account
2. Test password reset flow end-to-end
3. Verify MFA enrollment on new device
`);
const result = runGsdTools('audit-uat --raw', tmpDir);
assert.ok(result.success, `Command failed: ${result.error}`);
const output = JSON.parse(result.output);
assert.strictEqual(output.summary.total_items, 3);
assert.strictEqual(output.results[0].type, 'verification');
assert.strictEqual(output.results[0].status, 'human_needed');
assert.strictEqual(output.results[0].items[0].category, 'human_uat');
assert.strictEqual(output.results[0].items[0].name, 'Test SSO login with Google account');
});
test('scans and aggregates across multiple phases', () => {
// Phase 1 with pending
const phase1 = path.join(tmpDir, '.planning', 'phases', '01-foundation');
fs.mkdirSync(phase1, { recursive: true });
fs.writeFileSync(path.join(phase1, '01-UAT.md'), `---
status: partial
phase: 01-foundation
started: 2025-01-01T00:00:00Z
updated: 2025-01-01T00:00:00Z
---
## Tests
### 1. Test A
expected: Works
result: pending
`);
// Phase 2 with blocked
const phase2 = path.join(tmpDir, '.planning', 'phases', '02-api');
fs.mkdirSync(phase2, { recursive: true });
fs.writeFileSync(path.join(phase2, '02-UAT.md'), `---
status: partial
phase: 02-api
started: 2025-01-01T00:00:00Z
updated: 2025-01-01T00:00:00Z
---
## Tests
### 1. Test B
expected: Responds
result: blocked
blocked_by: server
### 2. Test C
expected: Returns data
result: skipped
reason: device not available
`);
const result = runGsdTools('audit-uat --raw', tmpDir);
assert.ok(result.success, `Command failed: ${result.error}`);
const output = JSON.parse(result.output);
assert.strictEqual(output.summary.total_files, 2);
assert.strictEqual(output.summary.total_items, 3);
assert.strictEqual(output.summary.by_phase['01'], 1);
assert.strictEqual(output.summary.by_phase['02'], 2);
});
test('milestone scoping filters phases to current milestone', () => {
// Create a ROADMAP.md that only references Phase 2
fs.writeFileSync(path.join(tmpDir, '.planning', 'ROADMAP.md'), `# Roadmap
### Phase 2: API Layer
**Goal:** Build API
`);
// Phase 1 (not in current milestone) with pending
const phase1 = path.join(tmpDir, '.planning', 'phases', '01-foundation');
fs.mkdirSync(phase1, { recursive: true });
fs.writeFileSync(path.join(phase1, '01-UAT.md'), `---
status: partial
phase: 01-foundation
started: 2025-01-01T00:00:00Z
updated: 2025-01-01T00:00:00Z
---
## Tests
### 1. Old Test
expected: Old behavior
result: pending
`);
// Phase 2 (in current milestone) with pending
const phase2 = path.join(tmpDir, '.planning', 'phases', '02-api');
fs.mkdirSync(phase2, { recursive: true });
fs.writeFileSync(path.join(phase2, '02-UAT.md'), `---
status: partial
phase: 02-api
started: 2025-01-01T00:00:00Z
updated: 2025-01-01T00:00:00Z
---
## Tests
### 1. New Test
expected: New behavior
result: pending
`);
const result = runGsdTools('audit-uat --raw', tmpDir);
assert.ok(result.success, `Command failed: ${result.error}`);
const output = JSON.parse(result.output);
// Only Phase 2 should be included (Phase 1 not in ROADMAP)
assert.strictEqual(output.summary.total_files, 1);
assert.strictEqual(output.results[0].phase, '02');
});
test('summary by_category counts are correct', () => {
const phaseDir = path.join(tmpDir, '.planning', 'phases', '05-billing');
fs.mkdirSync(phaseDir, { recursive: true });
fs.writeFileSync(path.join(phaseDir, '05-UAT.md'), `---
status: partial
phase: 05-billing
started: 2025-01-01T00:00:00Z
updated: 2025-01-01T00:00:00Z
---
## Tests
### 1. Payment Form
expected: Stripe elements load
result: pending
### 2. Webhook Handler
expected: Processes payment events
result: blocked
blocked_by: third-party Stripe
### 3. Invoice PDF
expected: Generates downloadable PDF
result: skipped
reason: needs release build
### 4. Refund Flow
expected: Processes refund
result: pending
`);
const result = runGsdTools('audit-uat --raw', tmpDir);
assert.ok(result.success, `Command failed: ${result.error}`);
const output = JSON.parse(result.output);
assert.strictEqual(output.summary.total_items, 4);
assert.strictEqual(output.summary.by_category.pending, 2);
assert.strictEqual(output.summary.by_category.third_party, 1);
assert.strictEqual(output.summary.by_category.build_needed, 1);
});
test('ignores VERIFICATION files without human_needed or gaps_found status', () => {
const phaseDir = path.join(tmpDir, '.planning', 'phases', '01-foundation');
fs.mkdirSync(phaseDir, { recursive: true });
fs.writeFileSync(path.join(phaseDir, '01-VERIFICATION.md'), `---
status: passed
phase: 01-foundation
---
## Results
All checks passed.
`);
const result = runGsdTools('audit-uat --raw', tmpDir);
assert.ok(result.success, `Command failed: ${result.error}`);
const output = JSON.parse(result.output);
assert.strictEqual(output.summary.total_items, 0);
assert.strictEqual(output.summary.total_files, 0);
});
});

View File

@@ -191,10 +191,9 @@ describe('validate health command', () => {
assert.ok(result.success, `Command failed: ${result.error}`);
const output = JSON.parse(result.output);
assert.ok(
output.warnings.some(w => w.code === 'W002'),
`Expected W002 in warnings: ${JSON.stringify(output.warnings)}`
);
const w002 = output.warnings.find(w => w.code === 'W002');
assert.ok(w002, `Expected W002 in warnings: ${JSON.stringify(output.warnings)}`);
assert.strictEqual(w002.repairable, false, 'W002 should not be auto-repairable');
});
// ─── Check 5: config.json valid JSON + valid schema ───────────────────────
@@ -613,16 +612,13 @@ describe('validate health --repair command', () => {
assert.ok(stateContent.includes('# Session State'), 'regenerated STATE.md should contain "# Session State"');
});
test('backs up existing STATE.md before regenerating', () => {
test('does not rewrite existing STATE.md for invalid phase references', () => {
writeValidConfigJson(tmpDir);
const statePath = path.join(tmpDir, '.planning', 'STATE.md');
const originalContent = '# Session State\n\nOriginal content here.\n';
fs.writeFileSync(statePath, originalContent);
// Make STATE.md reference a nonexistent phase so repair is triggered
const originalContent = '# Session State\n\nPhase 99 is current.\n';
fs.writeFileSync(
statePath,
'# Session State\n\nPhase 99 is current.\n'
originalContent
);
const result = runGsdTools('validate health --repair', tmpDir);
@@ -630,19 +626,17 @@ describe('validate health --repair command', () => {
const output = JSON.parse(result.output);
assert.ok(
Array.isArray(output.repairs_performed),
`Expected repairs_performed: ${JSON.stringify(output)}`
!Array.isArray(output.repairs_performed) || !output.repairs_performed.some(r => r.action === 'regenerateState'),
`Did not expect regenerateState for W002: ${JSON.stringify(output)}`
);
// Verify a .bak- file exists alongside STATE.md
const stateContent = fs.readFileSync(statePath, 'utf-8');
assert.strictEqual(stateContent, originalContent, 'existing STATE.md should be preserved');
const planningDir = path.join(tmpDir, '.planning');
const planningFiles = fs.readdirSync(planningDir);
const backupFile = planningFiles.find(f => f.startsWith('STATE.md.bak-'));
assert.ok(backupFile, `Expected a STATE.md.bak- file. Found files: ${planningFiles.join(', ')}`);
// Verify backup contains the original content
const backupContent = fs.readFileSync(path.join(planningDir, backupFile), 'utf-8');
assert.ok(backupContent.includes('Phase 99'), 'backup should contain the original STATE.md content');
assert.strictEqual(backupFile, undefined, `Did not expect backup file for non-destructive repair. Found: ${planningFiles.join(', ')}`);
});
test('adds nyquist_validation key to config.json via addNyquistKey repair', () => {
@@ -688,4 +682,18 @@ describe('validate health --repair command', () => {
`Expected repairable_count >= 2, got ${output.repairable_count}. Full output: ${JSON.stringify(output)}`
);
});
test('phase mismatch warnings do not count as repairable issues', () => {
writeValidConfigJson(tmpDir);
fs.writeFileSync(
path.join(tmpDir, '.planning', 'STATE.md'),
'# Session State\n\nPhase 99 is the current phase.\n'
);
const result = runGsdTools('validate health', tmpDir);
assert.ok(result.success, `Command failed: ${result.error}`);
const output = JSON.parse(result.output);
assert.strictEqual(output.repairable_count, 0, `Expected no repairable issues for W002: ${JSON.stringify(output)}`);
});
});