* test(#443): RED unified effort + fast_mode + resolve-execution All 68 tests failing as expected — no implementation yet. Covers: effort cascade (tier defaults, overrides, invalid fallthrough), fast_mode cascade (boolean-only, tier defaults), resolveEffortForTier escalation, renderEffortForRuntime clamping, resolve-execution CLI, config schema new keys, QA hostile-input matrix. Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com> * feat(#443): unified cross-provider effort + fast_mode knobs and resolve-execution query Adds config-driven effort control (universal ladder: minimal<low<medium<high<xhigh<max) and fast_mode propagation knobs, with per-runtime rendering that clamps the unique tail values (max=Anthropic-only clamps to xhigh on Codex; minimal=Codex-only clamps to low on Claude). Key changes: - config-schema.manifest.json: add effort.default, fast_mode.enabled as validKeys; add 4 dynamicKeyPatterns for effort.routing_tier_defaults, effort.agent_overrides, fast_mode.routing_tier_defaults, fast_mode.agent_overrides; fix stale _comment - config-defaults.manifest.json: add effort and fast_mode blocks with tier defaults - model-catalog.cjs: add EFFORT_RENDERING map, renderEffortForRuntime(), RUNTIMES_WITH_FAST_MODE - model-profiles.cjs: re-export new catalog exports - core.cjs: add resolveEffortInternal, resolveFastModeInternal, resolveEffortForTier, VALID_EFFORTS, EFFORT_SET, nextEffort; pass effort/fast_mode through loadConfig - commands.cjs: replace reasoning_effort in cmdResolveModel with unified effort; add cmdResolveExecution (superset command with effort_rendered, effort_param, effort_propagation, fast_mode, fast_mode_supported) - gsd-tools.cjs: add resolve-execution case with --effort/--fast-mode/--attempt flags - tests/feat-443: 69 tests covering cascade, rendering, escalation, CLI, schema, QA matrix - tests/commands.test.cjs: convert 3 reasoning_effort assertions to unified effort - docs/CONFIGURATION.md: document effort + fast_mode + resolve-execution sections - settings-advanced.md: list new effort/fast_mode keys in confirmation table Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com> * refactor(#443): remove dead catalog effort lane; unify codex effort through renderEffortForRuntime - Remove resolveReasoningEffortInternal (catalog-driven effort function) from core.cjs and its export; remove from commands.cjs destructure import - Convert tests/issue-2517-runtime-aware-profiles.test.cjs: all 11 effort assertions now use resolveEffortInternal + renderEffortForRuntime; Claude effort is first-class (output_config.effort); unknown runtimes assert param===null - Convert tests/feat-3023-model-phase-types.test.cjs: replace the entire resolveReasoningEffortInternal describe with unified effort assertions; effort derives from AGENT_DEFAULT_TIERS routing tier, not phase-type tier Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com> * docs(#443): ADR for unified cross-provider effort + fast-mode routing Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * test(#443): architecture-level QA invariants + test-strategy doc Add 48-test integration suite (feat-443-effort-fast-mode.integration.test.cjs) covering 8 architectural invariants: cross-provider validity (never emit a value the real API would 400 on), param/channel contract stability, resolve-execution JSON contract (all 8 keys + correct types), totality across the full 33-agent registry, fast-mode honesty (claude always fast_mode_supported=false), precedence first-valid-wins matrix for both effort and fast_mode cascades, dynamic-routing composition (effort escalation independent of model tier), and config-set round-trip for all new effort/* and fast_mode/* key namespaces. Append test-strategy section with invariant rationale and E2E gap documentation to docs/TESTING-SUITES.md. Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com> * test(#443): add failing install-wiring tests for effort per-runtime injection (RED) TDD RED: 10 failing tests covering: - Claude .md gets effort: injected per tier (planner=xhigh, mapper=low, executor=high) - Gemini .md does NOT get effort: (already passing — Gemini-safe) - Codex .toml gets model_reasoning_effort via unified resolver - Config-driven: effort.agent_overrides drives both Claude .md and Codex .toml - Source purity: agents/*.md have no effort: key (already passing) Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com> * feat(#443): wire effort per-runtime at install (Claude .md frontmatter + Codex .toml unified) - Import AGENT_DEFAULT_TIERS and renderEffortForRuntime from model-catalog.cjs - Add readGsdEffectiveEffortConfig(targetDir): reads merged effort config from .planning/config.json (per-project wins) + ~/.gsd/defaults.json (global fallback), same probe pattern as readGsdRuntimeProfileResolver - Add resolveInstallTimeEffort(effortCfg, agentName): pure function matching resolveEffortInternal() precedence (agent_overrides > routing_tier_defaults > default > 'high') without loadConfig side-effects (no sub-repo detection, no migration writes) - Claude agent copy loop: inject `effort: <value>` into frontmatter ONLY for runtime === 'claude'; all other .md runtimes (Gemini, Qwen, Hermes, etc.) stay effort-free (Gemini-safe source contract preserved in agents/*.md) - generateCodexAgentToml: add effortCfg param; emit model_reasoning_effort from unified resolver (replaces old catalog entry.reasoning_effort); Codex clamps max → xhigh via renderEffortForRuntime('codex', ...) - installCodexConfig: pass readGsdEffectiveEffortConfig(targetDir) to generateCodexAgentToml so per-project config wins for Codex .toml too - Update failing tests to GREEN: 12/12 pass; all 17 install tests pass; 2847/2848 unit tests pass (1 pre-existing failure: policy-shell-pinning) Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com> * refactor(#443): source install effort defaults from manifest (kill drift) + guard test Replace hardcoded _GSD_EFFORT_MANIFEST_TIER_DEFAULTS and the 'high' fallback in resolveInstallTimeEffort with values read from config-defaults.manifest.json at module init, using the same __dirname-relative path install.js already uses for all shared manifests. Add feat-443-effort-defaults-drift.test.cjs to assert equality between install.js's runtime constants and the manifest on every CI run. Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com> * fix(#443): reconcile Codex TOML tests with unified effort design The #443 unified effort resolver makes generateCodexAgentToml always emit model_reasoning_effort (driven by resolveInstallTimeEffort, not model_profile_overrides). The test 'generated TOML omits reasoning_effort when runtime has none' had an obsolete premise — model_profile_overrides.reasoning_effort:'' no longer suppresses unified effort. Convert it to assert the new invariant: Codex TOML always carries a valid model_reasoning_effort from the agent's routing tier (xhigh for gsd-planner, a heavy-tier agent), while model_profile_overrides model override is still respected. Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com> * fix(#443): make install.js effort resolution lazy (no load-time side effects breaking launcher-parity) Replace module-load-time IIFE + hard throw (config-defaults.manifest.json read) and top-level require of model-catalog.cjs with a lazy _getGsdEffortCatalog() getter that initialises on first call from resolveInstallTimeEffort / generateCodexAgentToml / Claude .md effort injection. Requiring install.js in unrelated test contexts (e.g. runtime-launcher-parity) no longer triggers manifest IO or throws, eliminating the load-time side effect that changed subprocess exit codes / stderr on the bench. Drift-guard exports (_GSD_EFFORT_MANIFEST_TIER_DEFAULTS / _GSD_EFFORT_MANIFEST_DEFAULT) preserved as lazy getter properties on module.exports so feat-443-effort-defaults-drift still validates them without forcing eager load. Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com> * fix(#443): isolate install-wiring test HOME to stop \$HOME/.claude pollution breaking launcher-parity runGlobalInstall() now redirects HOME to a per-call isolated tmpdir in addition to the existing runtime-specific env-var redirects (CLAUDE_CONFIG_DIR, GEMINI_CONFIG_DIR, CODEX_HOME). This ensures install.js code that uses os.homedir() directly — including the ~/.cache/gsd update-check deletion, ~/.gsd/defaults.json reads, and any HOME-relative npm subprocess writes — never touches the real \$HOME during the test. Without the HOME isolation the install test (which is new to this branch and is now picked up by Docker's raw \`tests/*.test.cjs\` glob) could write or delete files under the real \$HOME, causing runtime-launcher-parity test (D) to fail: (D) asserts a loud non-zero exit when \$RUNTIME_DIR/gsd-tools.cjs is absent and gsd-tools is not on PATH, but the launcher's \$HOME/.claude fallback arm succeeds if \$HOME/.claude/get-shit-done/bin/gsd-tools.cjs exists. Also sets GSD_SKIP_STALE_SDK_CHECK=1 to suppress the \`npm ls -g\` subprocess that the global installer spawns — irrelevant to effort-wiring assertions, slow, and potentially writes to ~/.npm cache. All 12 feat-443 install-wiring assertions preserved. Drift-guard 5/5. Unit suite 2848/2850 (pre-existing policy-shell-pinning.test.cjs failure on next). Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com> * chore(#443): add changeset fragment for effort + fast-mode routing Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * fix(#443): set GSD_TEST_MODE before requiring install.js in drift-guard test to prevent HOME leak Without GSD_TEST_MODE=1, require('bin/install.js') runs the module's main install block (guarded by !GSD_TEST_MODE), performing a real global Claude install into $HOME/.claude/. On CI ubuntu where node is on standard PATH, the launcher's $HOME/.claude fallback arm then finds gsd-tools.cjs, causing runtime-launcher-parity test (D) to exit zero when it must exit non-zero. Root cause: feat-443-effort-defaults-drift.test.cjs (unit suite) runs alphabetically before runtime-launcher-parity.test.cjs in the same node --test invocation. Each runs in a separate worker process but shares the same HOME. The drift test's install leaks gsd-tools.cjs into that HOME, then the launcher test's bash subprocess finds it via the $HOME/.claude arm. Fix: add process.env.GSD_TEST_MODE = '1' at the top of the drift-guard test, before the require(installPath) call. This matches the pattern used by feat-443-effort-fast-mode.test.cjs and feat-443-effort-install-wiring .install.test.cjs. Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com> * fix(#443): deterministic resolve-execution arg parsing + validate install-time effort (Codex adversarial findings) Finding 1: resolve-execution --effort low gsd-planner misrouted 'low' as the agent. Replace find(non-dash) with a proper flag-consuming loop that collects a single positional; validate missing/extra positionals and malformed --attempt values. Finding 2: resolveInstallTimeEffort returned unvalidated effort strings (e.g. "ultra") verbatim. Each precedence layer now checks GSD_EFFORT_SET (imported once from core.cjs) before accepting a value, mirroring resolveEffortInternal exactly. Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com> * fix(#443): newline-agnostic effort frontmatter injection (Windows CRLF) + CRLF-safe assertions Extracts injectEffortFrontmatter(content, effortValue) pure helper that detects EOL (LF vs CRLF) from the opening '---' line and inserts 'effort: <value>' before the closing '---' delimiter using the same EOL as the surrounding frontmatter. Regex now uses /^---\r?\n([\s\S]*?)^---\r?$/m instead of the LF-only /^(---\n[\s\S]*?)(---)(\n|$)/ that silently skipped CRLF files on Windows (git core.autocrlf=true checkout). Also adds 7 unit tests covering LF, CRLF, idempotency, no-frontmatter, and complex frontmatter cases. Exports injectEffortFrontmatter from module.exports. Fixes 6 CI failures in tests/feat-443-effort-install-wiring.install.test.cjs on windows-latest runners (lines 138, 145, 152, 261, 345, 356). Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com> --------- Co-authored-by: CI Rebase Check <ci@gsd-redux> Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com>
1189 lines
42 KiB
JavaScript
1189 lines
42 KiB
JavaScript
/**
|
|
* Commands — Standalone utility commands
|
|
*/
|
|
const fs = require('fs');
|
|
const path = require('path');
|
|
const { execGit, platformWriteSync, platformReadSync, platformEnsureDir } = require('./shell-command-projection.cjs');
|
|
const { loadConfig, isGitIgnored, normalizePhaseName, comparePhaseNum, getArchivedPhaseDirs, generateSlugInternal, getMilestoneInfo, getMilestonePhaseFilter, resolveModelInternal, resolveEffortInternal, resolveFastModeInternal, resolveEffortForTier, stripShippedMilestones, extractCurrentMilestone, toPosixPath, output, error, findPhaseInternal, extractOneLinerFromBody, getRoadmapPhaseInternal } = require('./core.cjs');
|
|
const { renderEffortForRuntime, RUNTIMES_WITH_FAST_MODE } = require('./model-catalog.cjs');
|
|
const { planningDir, planningPaths } = require('./planning-workspace.cjs');
|
|
const { extractFrontmatter } = require('./frontmatter.cjs');
|
|
const { MODEL_PROFILES } = require('./model-profiles.cjs');
|
|
const { formatGsdSlash, resolveRuntime } = require('./runtime-slash.cjs');
|
|
|
|
/**
|
|
* Determine phase status by checking plan/summary counts AND verification state.
|
|
* Introduces "Executed" for phases with all summaries but no passing verification.
|
|
*/
|
|
function determinePhaseStatus(plans, summaries, phaseDir, defaultPending) {
|
|
if (plans === 0) return defaultPending;
|
|
if (summaries < plans && summaries > 0) return 'In Progress';
|
|
if (summaries < plans) return 'Planned';
|
|
|
|
// summaries >= plans — check verification
|
|
try {
|
|
const files = fs.readdirSync(phaseDir);
|
|
const verificationFile = files.find(f => f === 'VERIFICATION.md' || f.endsWith('-VERIFICATION.md'));
|
|
if (verificationFile) {
|
|
const content = platformReadSync(path.join(phaseDir, verificationFile)) || '';
|
|
if (/status:\s*passed/i.test(content)) return 'Complete';
|
|
if (/status:\s*human_needed/i.test(content)) return 'Needs Review';
|
|
if (/status:\s*gaps_found/i.test(content)) return 'Executed';
|
|
// Verification exists but unrecognized status — treat as executed
|
|
return 'Executed';
|
|
}
|
|
} catch { /* directory read failed — fall through */ }
|
|
|
|
// No verification file — executed but not verified
|
|
return 'Executed';
|
|
}
|
|
|
|
function cmdGenerateSlug(text, raw) {
|
|
if (!text) {
|
|
error('text required for slug generation');
|
|
}
|
|
|
|
const slug = text
|
|
.toLowerCase()
|
|
.replace(/[^a-z0-9]+/g, '-')
|
|
.replace(/^-+|-+$/g, '')
|
|
.substring(0, 60);
|
|
|
|
const result = { slug };
|
|
output(result, raw, slug);
|
|
}
|
|
|
|
function cmdCurrentTimestamp(format, raw) {
|
|
const now = new Date();
|
|
let result;
|
|
|
|
switch (format) {
|
|
case 'date':
|
|
result = now.toISOString().split('T')[0];
|
|
break;
|
|
case 'filename':
|
|
result = now.toISOString().replace(/:/g, '-').replace(/\..+/, '');
|
|
break;
|
|
case 'full':
|
|
default:
|
|
result = now.toISOString();
|
|
break;
|
|
}
|
|
|
|
output({ timestamp: result }, raw, result);
|
|
}
|
|
|
|
function cmdListTodos(cwd, area, raw) {
|
|
const pendingDir = path.join(planningDir(cwd), 'todos', 'pending');
|
|
|
|
let count = 0;
|
|
const todos = [];
|
|
|
|
try {
|
|
const files = fs.readdirSync(pendingDir).filter(f => f.endsWith('.md'));
|
|
|
|
for (const file of files) {
|
|
const content = platformReadSync(path.join(pendingDir, file));
|
|
if (content === null) continue;
|
|
const createdMatch = content.match(/^created:\s*(.+)$/m);
|
|
const titleMatch = content.match(/^title:\s*(.+)$/m);
|
|
const areaMatch = content.match(/^area:\s*(.+)$/m);
|
|
|
|
const todoArea = areaMatch ? areaMatch[1].trim() : 'general';
|
|
|
|
// Apply area filter if specified
|
|
if (area && todoArea !== area) continue;
|
|
|
|
count++;
|
|
todos.push({
|
|
file,
|
|
created: createdMatch ? createdMatch[1].trim() : 'unknown',
|
|
title: titleMatch ? titleMatch[1].trim() : 'Untitled',
|
|
area: todoArea,
|
|
path: toPosixPath(path.relative(cwd, path.join(pendingDir, file))),
|
|
});
|
|
}
|
|
} catch { /* intentionally empty */ }
|
|
|
|
const result = { count, todos };
|
|
output(result, raw, count.toString());
|
|
}
|
|
|
|
function cmdVerifyPathExists(cwd, targetPath, raw) {
|
|
if (!targetPath) {
|
|
error('path required for verification');
|
|
}
|
|
|
|
// Reject null bytes and validate path does not contain traversal attempts
|
|
if (targetPath.includes('\0')) {
|
|
error('path contains null bytes');
|
|
}
|
|
|
|
const fullPath = path.isAbsolute(targetPath) ? targetPath : path.join(cwd, targetPath);
|
|
|
|
try {
|
|
const stats = fs.statSync(fullPath);
|
|
const type = stats.isDirectory() ? 'directory' : stats.isFile() ? 'file' : 'other';
|
|
const result = { exists: true, type };
|
|
output(result, raw, 'true');
|
|
} catch {
|
|
const result = { exists: false, type: null };
|
|
output(result, raw, 'false');
|
|
}
|
|
}
|
|
|
|
function cmdHistoryDigest(cwd, raw) {
|
|
const phasesDir = planningPaths(cwd).phases;
|
|
const digest = { phases: {}, decisions: [], tech_stack: new Set() };
|
|
|
|
// Collect all phase directories: archived + current
|
|
const allPhaseDirs = [];
|
|
|
|
// Add archived phases first (oldest milestones first)
|
|
const archived = getArchivedPhaseDirs(cwd);
|
|
for (const a of archived) {
|
|
allPhaseDirs.push({ name: a.name, fullPath: a.fullPath, milestone: a.milestone });
|
|
}
|
|
|
|
// Add current phases
|
|
if (fs.existsSync(phasesDir)) {
|
|
try {
|
|
const currentDirs = fs.readdirSync(phasesDir, { withFileTypes: true })
|
|
.filter(e => e.isDirectory())
|
|
.map(e => e.name)
|
|
.sort();
|
|
for (const dir of currentDirs) {
|
|
allPhaseDirs.push({ name: dir, fullPath: path.join(phasesDir, dir), milestone: null });
|
|
}
|
|
} catch { /* intentionally empty */ }
|
|
}
|
|
|
|
if (allPhaseDirs.length === 0) {
|
|
digest.tech_stack = [];
|
|
output(digest, raw);
|
|
return;
|
|
}
|
|
|
|
try {
|
|
for (const { name: dir, fullPath: dirPath } of allPhaseDirs) {
|
|
const summaries = fs.readdirSync(dirPath).filter(f => f.endsWith('-SUMMARY.md') || f === 'SUMMARY.md');
|
|
|
|
for (const summary of summaries) {
|
|
const content = platformReadSync(path.join(dirPath, summary));
|
|
if (content === null) continue;
|
|
try {
|
|
const fm = extractFrontmatter(content);
|
|
|
|
const phaseNum = fm.phase || dir.split('-')[0];
|
|
|
|
if (!digest.phases[phaseNum]) {
|
|
digest.phases[phaseNum] = {
|
|
name: fm.name || dir.split('-').slice(1).join(' ') || 'Unknown',
|
|
provides: new Set(),
|
|
affects: new Set(),
|
|
patterns: new Set(),
|
|
};
|
|
}
|
|
|
|
// Merge provides
|
|
if (fm['dependency-graph'] && fm['dependency-graph'].provides) {
|
|
fm['dependency-graph'].provides.forEach(p => digest.phases[phaseNum].provides.add(p));
|
|
} else if (fm.provides) {
|
|
fm.provides.forEach(p => digest.phases[phaseNum].provides.add(p));
|
|
}
|
|
|
|
// Merge affects
|
|
if (fm['dependency-graph'] && fm['dependency-graph'].affects) {
|
|
fm['dependency-graph'].affects.forEach(a => digest.phases[phaseNum].affects.add(a));
|
|
}
|
|
|
|
// Merge patterns
|
|
if (fm['patterns-established']) {
|
|
fm['patterns-established'].forEach(p => digest.phases[phaseNum].patterns.add(p));
|
|
}
|
|
|
|
// Merge decisions
|
|
if (fm['key-decisions']) {
|
|
fm['key-decisions'].forEach(d => {
|
|
digest.decisions.push({ phase: phaseNum, decision: d });
|
|
});
|
|
}
|
|
|
|
// Merge tech stack
|
|
if (fm['tech-stack'] && fm['tech-stack'].added) {
|
|
fm['tech-stack'].added.forEach(t => digest.tech_stack.add(typeof t === 'string' ? t : t.name));
|
|
}
|
|
|
|
} catch (e) {
|
|
// Skip malformed summaries
|
|
}
|
|
}
|
|
}
|
|
|
|
// Convert Sets to Arrays for JSON output
|
|
Object.keys(digest.phases).forEach(p => {
|
|
digest.phases[p].provides = [...digest.phases[p].provides];
|
|
digest.phases[p].affects = [...digest.phases[p].affects];
|
|
digest.phases[p].patterns = [...digest.phases[p].patterns];
|
|
});
|
|
digest.tech_stack = [...digest.tech_stack];
|
|
|
|
output(digest, raw);
|
|
} catch (e) {
|
|
error('Failed to generate history digest: ' + e.message);
|
|
}
|
|
}
|
|
|
|
function cmdResolveModel(cwd, agentType, raw) {
|
|
if (!agentType) {
|
|
error('agent-type required');
|
|
}
|
|
|
|
const config = loadConfig(cwd);
|
|
const profile = config.model_profile || 'balanced';
|
|
const model = resolveModelInternal(cwd, agentType);
|
|
const effort = resolveEffortInternal(cwd, agentType);
|
|
|
|
const agentModels = MODEL_PROFILES[agentType];
|
|
const result = agentModels
|
|
? { model, profile, effort }
|
|
: { model, profile, effort, unknown_agent: true };
|
|
output(result, raw, model);
|
|
}
|
|
|
|
/**
|
|
* #443 — Superset execution query: model + unified effort + fast_mode.
|
|
*
|
|
* Emits JSON:
|
|
* { model, profile, effort, effort_rendered, effort_param, effort_propagation,
|
|
* fast_mode, fast_mode_supported, [unknown_agent] }
|
|
*
|
|
* Flags: --effort <level>, --fast-mode <true|false>, --attempt <n>
|
|
*
|
|
* @param {string} cwd
|
|
* @param {string} agentType
|
|
* @param {boolean} raw
|
|
* @param {{ effortOverride?: string, fastModeOverride?: boolean, attempt?: number }} [opts]
|
|
*/
|
|
function cmdResolveExecution(cwd, agentType, raw, opts) {
|
|
if (!agentType) {
|
|
error('agent-type required');
|
|
}
|
|
|
|
opts = opts || {};
|
|
const config = loadConfig(cwd);
|
|
const profile = config.model_profile || 'balanced';
|
|
const model = resolveModelInternal(cwd, agentType);
|
|
|
|
const effortOpts = {};
|
|
if (typeof opts.effortOverride === 'string') effortOpts.override = opts.effortOverride;
|
|
|
|
const fastModeOpts = {};
|
|
if (typeof opts.fastModeOverride === 'boolean') fastModeOpts.override = opts.fastModeOverride;
|
|
|
|
const effort = (opts.attempt !== undefined && opts.attempt !== null)
|
|
? resolveEffortForTier(cwd, agentType, opts.attempt)
|
|
: resolveEffortInternal(cwd, agentType, effortOpts);
|
|
|
|
const fastMode = resolveFastModeInternal(cwd, agentType, fastModeOpts);
|
|
|
|
const runtime = config.runtime || 'claude';
|
|
const rendered = renderEffortForRuntime(runtime, effort);
|
|
|
|
const fastModeSupported = RUNTIMES_WITH_FAST_MODE.has(runtime);
|
|
|
|
const agentModels = MODEL_PROFILES[agentType];
|
|
const result = {
|
|
model,
|
|
profile,
|
|
effort,
|
|
effort_rendered: rendered.value,
|
|
effort_param: rendered.param,
|
|
effort_propagation: rendered.channel,
|
|
fast_mode: fastMode,
|
|
fast_mode_supported: fastModeSupported,
|
|
};
|
|
if (!agentModels) result.unknown_agent = true;
|
|
output(result, raw, effort);
|
|
}
|
|
|
|
function cmdCommit(cwd, message, files, raw, amend, noVerify) {
|
|
if (!message && !amend) {
|
|
error('commit message required');
|
|
}
|
|
|
|
// Sanitize commit message: strip invisible chars and injection markers
|
|
// that could hijack agent context when commit messages are read back
|
|
if (message) {
|
|
const { sanitizeForPrompt } = require('./security.cjs');
|
|
message = sanitizeForPrompt(message);
|
|
}
|
|
|
|
const config = loadConfig(cwd);
|
|
|
|
// Check commit_docs config
|
|
// `skipped: true` is explicit so agent prompts can match on a first-class
|
|
// success signal rather than inferring "skip" from "committed is missing"
|
|
// and improvising raw git fallbacks (#3678).
|
|
if (!config.commit_docs) {
|
|
const result = { committed: false, skipped: true, hash: null, reason: 'skipped_commit_docs_false' };
|
|
output(result, raw, 'skipped');
|
|
return;
|
|
}
|
|
|
|
// Check if .planning is gitignored
|
|
if (isGitIgnored(cwd, '.planning')) {
|
|
const result = { committed: false, skipped: true, hash: null, reason: 'skipped_gitignored' };
|
|
output(result, raw, 'skipped');
|
|
return;
|
|
}
|
|
|
|
// Ensure branching strategy branch exists before first commit (#1278).
|
|
// Pre-execution workflows (discuss, plan, research) commit artifacts but the branch
|
|
// was previously only created during execute-phase — too late.
|
|
if (config.branching_strategy && config.branching_strategy !== 'none') {
|
|
let branchName = null;
|
|
if (config.branching_strategy === 'phase') {
|
|
// Determine which phase we're committing for from the file paths
|
|
const phaseMatch = (files || []).join(' ').match(/(\d+(?:\.\d+)*)-/);
|
|
if (phaseMatch) {
|
|
const phaseNum = phaseMatch[1];
|
|
const phaseInfo = findPhaseInternal(cwd, phaseNum);
|
|
if (phaseInfo) {
|
|
branchName = config.phase_branch_template
|
|
.replace('{phase}', phaseInfo.phase_number)
|
|
.replace('{slug}', phaseInfo.phase_slug || 'phase');
|
|
}
|
|
}
|
|
} else if (config.branching_strategy === 'milestone') {
|
|
const milestone = getMilestoneInfo(cwd);
|
|
if (milestone && milestone.version) {
|
|
branchName = config.milestone_branch_template
|
|
.replace('{milestone}', milestone.version)
|
|
.replace('{slug}', generateSlugInternal(milestone.name) || 'milestone');
|
|
}
|
|
}
|
|
if (branchName) {
|
|
const currentBranch = execGit(['rev-parse', '--abbrev-ref', 'HEAD'], { cwd });
|
|
if (currentBranch.exitCode === 0 && currentBranch.stdout.trim() !== branchName) {
|
|
// Create branch if it doesn't exist, or switch to it if it does
|
|
const create = execGit(['checkout', '-b', branchName], { cwd });
|
|
if (create.exitCode !== 0) {
|
|
execGit(['checkout', branchName], { cwd });
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
// Stage files
|
|
const explicitFiles = files && files.length > 0;
|
|
const filesToStage = explicitFiles ? files : ['.planning/'];
|
|
for (const file of filesToStage) {
|
|
const fullPath = path.join(cwd, file);
|
|
if (!fs.existsSync(fullPath)) {
|
|
if (explicitFiles) {
|
|
// Caller passed an explicit --files list: missing files are skipped.
|
|
// Staging a deletion here would silently remove tracked planning files
|
|
// (e.g. STATE.md, ROADMAP.md) when they are temporarily absent (#2014).
|
|
continue;
|
|
}
|
|
// Default mode (staging all of .planning/): stage the deletion so
|
|
// removed planning files are not left dangling in the index.
|
|
execGit(['rm', '--cached', '--ignore-unmatch', file], { cwd });
|
|
} else {
|
|
execGit(['add', file], { cwd });
|
|
}
|
|
}
|
|
|
|
// Commit (--no-verify skips pre-commit hooks, used by parallel executor agents)
|
|
const commitArgs = amend ? ['commit', '--amend', '--no-edit'] : ['commit', '-m', message];
|
|
if (noVerify) commitArgs.push('--no-verify');
|
|
const commitResult = execGit(commitArgs, { cwd });
|
|
if (commitResult.exitCode !== 0) {
|
|
if (commitResult.stdout.includes('nothing to commit') || commitResult.stderr.includes('nothing to commit')) {
|
|
const result = { committed: false, hash: null, reason: 'nothing_to_commit' };
|
|
output(result, raw, 'nothing');
|
|
return;
|
|
}
|
|
const result = {
|
|
committed: false,
|
|
hash: null,
|
|
reason: 'commit_failed',
|
|
error: commitResult.stderr || commitResult.stdout,
|
|
};
|
|
output(result, raw, 'failed');
|
|
return;
|
|
}
|
|
|
|
// Get short hash
|
|
const hashResult = execGit(['rev-parse', '--short', 'HEAD'], { cwd });
|
|
const hash = hashResult.exitCode === 0 ? hashResult.stdout : null;
|
|
const result = { committed: true, hash, reason: 'committed' };
|
|
output(result, raw, hash || 'committed');
|
|
}
|
|
|
|
/**
|
|
* Route a list of changed files to their sub-repo prefixes.
|
|
*
|
|
* Bucket sub-repos by their first path segment. Any file that matches a
|
|
* sub-repo prefix must share that sub-repo's first segment, so we only scan
|
|
* the (small) bucket for the file's first segment instead of all sub-repos
|
|
* — O(F + R) expected vs the prior O(F*R) find-in-loop. Candidates stay in
|
|
* sub-repo array order, preserving the original first-match semantics
|
|
* (incl. multi-segment sub-repos like "vendor/pkg", which resolve via the
|
|
* inner startsWith). (#311)
|
|
*
|
|
* @param {string[]} files - changed file paths (relative to project root)
|
|
* @param {string[]} subRepos - sub-repo path prefixes from config.sub_repos
|
|
* @returns {{ grouped: Object<string,string[]>, unmatched: string[] }}
|
|
*/
|
|
function groupFilesBySubrepo(files, subRepos) {
|
|
const reposByFirstSeg = new Map();
|
|
for (const repo of subRepos) {
|
|
const firstSeg = String(repo).split('/')[0];
|
|
let bucket = reposByFirstSeg.get(firstSeg);
|
|
if (!bucket) { bucket = []; reposByFirstSeg.set(firstSeg, bucket); }
|
|
bucket.push(repo);
|
|
}
|
|
const grouped = {};
|
|
const unmatched = [];
|
|
for (const file of files) {
|
|
const candidates = reposByFirstSeg.get(file.split('/')[0]);
|
|
const match = candidates ? candidates.find(repo => file.startsWith(repo + '/')) : undefined;
|
|
if (match) {
|
|
(grouped[match] ||= []).push(file);
|
|
} else {
|
|
unmatched.push(file);
|
|
}
|
|
}
|
|
return { grouped, unmatched };
|
|
}
|
|
|
|
function cmdCommitToSubrepo(cwd, message, files, raw) {
|
|
if (!message) {
|
|
error('commit message required');
|
|
}
|
|
|
|
const config = loadConfig(cwd);
|
|
const subRepos = config.sub_repos;
|
|
|
|
if (!subRepos || subRepos.length === 0) {
|
|
error('no sub_repos configured in .planning/config.json');
|
|
}
|
|
|
|
if (!files || files.length === 0) {
|
|
error('--files required for commit-to-subrepo');
|
|
}
|
|
|
|
// Group files by sub-repo prefix
|
|
const { grouped, unmatched } = groupFilesBySubrepo(files, subRepos);
|
|
|
|
if (unmatched.length > 0) {
|
|
process.stderr.write(`Warning: ${unmatched.length} file(s) did not match any sub-repo prefix: ${unmatched.join(', ')}\n`);
|
|
}
|
|
|
|
const repos = {};
|
|
for (const [repo, repoFiles] of Object.entries(grouped)) {
|
|
const repoCwd = path.join(cwd, repo);
|
|
|
|
// Stage files (strip sub-repo prefix for paths relative to that repo)
|
|
for (const file of repoFiles) {
|
|
const relativePath = file.slice(repo.length + 1);
|
|
execGit(['add', relativePath], { cwd: repoCwd });
|
|
}
|
|
|
|
// Commit
|
|
const commitResult = execGit(['commit', '-m', message], { cwd: repoCwd });
|
|
if (commitResult.exitCode !== 0) {
|
|
if (commitResult.stdout.includes('nothing to commit') || commitResult.stderr.includes('nothing to commit')) {
|
|
repos[repo] = { committed: false, hash: null, files: repoFiles, reason: 'nothing_to_commit' };
|
|
continue;
|
|
}
|
|
repos[repo] = { committed: false, hash: null, files: repoFiles, reason: 'error', error: commitResult.stderr };
|
|
continue;
|
|
}
|
|
|
|
// Get hash
|
|
const hashResult = execGit(['rev-parse', '--short', 'HEAD'], { cwd: repoCwd });
|
|
const hash = hashResult.exitCode === 0 ? hashResult.stdout : null;
|
|
repos[repo] = { committed: true, hash, files: repoFiles };
|
|
}
|
|
|
|
const result = {
|
|
committed: Object.values(repos).some(r => r.committed),
|
|
repos,
|
|
unmatched: unmatched.length > 0 ? unmatched : undefined,
|
|
};
|
|
output(result, raw, Object.entries(repos).map(([r, v]) => `${r}:${v.hash || 'skip'}`).join(' '));
|
|
}
|
|
|
|
function cmdSummaryExtract(cwd, summaryPath, fields, raw) {
|
|
if (!summaryPath) {
|
|
error('summary-path required for summary-extract');
|
|
}
|
|
|
|
const fullPath = path.join(cwd, summaryPath);
|
|
|
|
if (!fs.existsSync(fullPath)) {
|
|
output({ error: 'File not found', path: summaryPath }, raw);
|
|
return;
|
|
}
|
|
|
|
const content = fs.readFileSync(fullPath, 'utf-8');
|
|
const fm = extractFrontmatter(content);
|
|
|
|
// Parse key-decisions into structured format
|
|
const parseDecisions = (decisionsList) => {
|
|
if (!decisionsList || !Array.isArray(decisionsList)) return [];
|
|
return decisionsList.map(d => {
|
|
const colonIdx = d.indexOf(':');
|
|
if (colonIdx > 0) {
|
|
return {
|
|
summary: d.substring(0, colonIdx).trim(),
|
|
rationale: d.substring(colonIdx + 1).trim(),
|
|
};
|
|
}
|
|
return { summary: d, rationale: null };
|
|
});
|
|
};
|
|
|
|
// Build full result
|
|
const fullResult = {
|
|
path: summaryPath,
|
|
one_liner: fm['one-liner'] || extractOneLinerFromBody(content) || null,
|
|
key_files: fm['key-files'] || [],
|
|
tech_added: (fm['tech-stack'] && fm['tech-stack'].added) || [],
|
|
patterns: fm['patterns-established'] || [],
|
|
decisions: parseDecisions(fm['key-decisions']),
|
|
requirements_completed: fm['requirements-completed'] || [],
|
|
};
|
|
|
|
// If fields specified, filter to only those fields
|
|
if (fields && fields.length > 0) {
|
|
const filtered = { path: summaryPath };
|
|
for (const field of fields) {
|
|
if (fullResult[field] !== undefined) {
|
|
filtered[field] = fullResult[field];
|
|
}
|
|
}
|
|
output(filtered, raw);
|
|
return;
|
|
}
|
|
|
|
output(fullResult, raw);
|
|
}
|
|
|
|
function _wsSleep(ms) {
|
|
return new Promise(resolve => setTimeout(resolve, ms));
|
|
}
|
|
|
|
function _wsParseRetryAfter(header) {
|
|
if (!header) return null;
|
|
const trimmed = header.trim();
|
|
if (/^\d+$/.test(trimmed)) {
|
|
return Math.min(Math.max(parseInt(trimmed, 10) * 1000, 0), 60000);
|
|
}
|
|
const asDate = Date.parse(trimmed);
|
|
if (!isNaN(asDate)) {
|
|
return Math.min(Math.max(asDate - Date.now(), 0), 60000);
|
|
}
|
|
return null;
|
|
}
|
|
|
|
function _wsRetryDelayMs(attempt) {
|
|
const base = 250;
|
|
const cap = 2000;
|
|
const exp = Math.min(base * Math.pow(2, attempt), cap);
|
|
return exp + Math.floor(Math.random() * 100);
|
|
}
|
|
|
|
async function cmdWebsearch(query, options, raw) {
|
|
const apiKey = process.env.BRAVE_API_KEY;
|
|
|
|
if (!apiKey) {
|
|
// No key = silent skip, agent falls back to built-in WebSearch
|
|
output({ available: false, reason: 'BRAVE_API_KEY not set' }, raw, '');
|
|
return;
|
|
}
|
|
|
|
if (!query) {
|
|
output({ available: false, error: 'Query required' }, raw, '');
|
|
return;
|
|
}
|
|
|
|
const params = new URLSearchParams({
|
|
q: query,
|
|
count: String(options.limit || 10),
|
|
country: 'us',
|
|
search_lang: 'en',
|
|
text_decorations: 'false'
|
|
});
|
|
|
|
if (options.freshness) {
|
|
params.set('freshness', options.freshness);
|
|
}
|
|
|
|
const rawTimeout = parseInt(process.env.GSD_WEBSEARCH_TIMEOUT_MS, 10);
|
|
const timeoutMs = (Number.isInteger(rawTimeout) && rawTimeout > 0) ? rawTimeout : 10000;
|
|
|
|
const MAX_RETRIES = 2;
|
|
let attempt = 0;
|
|
|
|
while (true) {
|
|
try {
|
|
const ac = new AbortController();
|
|
const timer = setTimeout(() => ac.abort(new Error('timeout')), timeoutMs);
|
|
let response;
|
|
try {
|
|
response = await fetch(
|
|
`https://api.search.brave.com/res/v1/web/search?${params}`,
|
|
{
|
|
headers: {
|
|
'Accept': 'application/json',
|
|
'X-Subscription-Token': apiKey
|
|
},
|
|
signal: ac.signal
|
|
}
|
|
);
|
|
} finally {
|
|
clearTimeout(timer);
|
|
}
|
|
|
|
if (response.ok) {
|
|
const data = await response.json();
|
|
const results = (data.web?.results || []).map(r => ({
|
|
title: r.title,
|
|
url: r.url,
|
|
description: r.description,
|
|
age: r.age || null
|
|
}));
|
|
output({
|
|
available: true,
|
|
query,
|
|
count: results.length,
|
|
results
|
|
}, raw, results.map(r => `${r.title}\n${r.url}\n${r.description}`).join('\n\n'));
|
|
return;
|
|
}
|
|
|
|
const status = response.status;
|
|
const isRetryable = status === 429 || status >= 500;
|
|
|
|
if (!isRetryable) {
|
|
// Non-retryable 4xx — fail immediately, no attempts field
|
|
output({ available: false, error: `API error: ${status}` }, raw, '');
|
|
return;
|
|
}
|
|
|
|
// Retryable HTTP error
|
|
attempt++;
|
|
if (attempt > MAX_RETRIES) {
|
|
output({ available: false, error: `API error: ${status}`, attempts: attempt }, raw, '');
|
|
return;
|
|
}
|
|
|
|
let delay;
|
|
if (status === 429) {
|
|
const retryAfter = _wsParseRetryAfter(response.headers.get('retry-after'));
|
|
delay = retryAfter !== null ? retryAfter : _wsRetryDelayMs(attempt - 1);
|
|
} else {
|
|
delay = _wsRetryDelayMs(attempt - 1);
|
|
}
|
|
await _wsSleep(delay);
|
|
|
|
} catch (err) {
|
|
attempt++;
|
|
if (attempt > MAX_RETRIES) {
|
|
output({ available: false, error: err.message, attempts: attempt }, raw, '');
|
|
return;
|
|
}
|
|
await _wsSleep(_wsRetryDelayMs(attempt - 1));
|
|
}
|
|
}
|
|
}
|
|
|
|
function cmdProgressRender(cwd, format, raw) {
|
|
const phasesDir = planningPaths(cwd).phases;
|
|
const roadmapPath = planningPaths(cwd).roadmap;
|
|
const milestone = getMilestoneInfo(cwd);
|
|
|
|
const phases = [];
|
|
let totalPlans = 0;
|
|
let totalSummaries = 0;
|
|
|
|
try {
|
|
const entries = fs.readdirSync(phasesDir, { withFileTypes: true });
|
|
const dirs = entries.filter(e => e.isDirectory()).map(e => e.name).sort((a, b) => comparePhaseNum(a, b));
|
|
|
|
for (const dir of dirs) {
|
|
const dm = dir.match(/^(\d+(?:\.\d+)*)-?(.*)/);
|
|
const phaseNum = dm ? dm[1] : dir;
|
|
const phaseName = dm && dm[2] ? dm[2].replace(/-/g, ' ') : '';
|
|
const phaseFiles = fs.readdirSync(path.join(phasesDir, dir));
|
|
const plans = phaseFiles.filter(f => f.endsWith('-PLAN.md') || f === 'PLAN.md').length;
|
|
const summaries = phaseFiles.filter(f => f.endsWith('-SUMMARY.md') || f === 'SUMMARY.md').length;
|
|
|
|
totalPlans += plans;
|
|
totalSummaries += summaries;
|
|
|
|
const status = determinePhaseStatus(plans, summaries, path.join(phasesDir, dir), 'Pending');
|
|
|
|
phases.push({ number: phaseNum, name: phaseName, plans, summaries, status });
|
|
}
|
|
} catch { /* intentionally empty */ }
|
|
|
|
const percent = totalPlans > 0 ? Math.min(100, Math.round((totalSummaries / totalPlans) * 100)) : 0;
|
|
|
|
if (format === 'table') {
|
|
// Render markdown table
|
|
const barWidth = 10;
|
|
const filled = Math.round((percent / 100) * barWidth);
|
|
const bar = '\u2588'.repeat(filled) + '\u2591'.repeat(barWidth - filled);
|
|
let out = `# ${milestone.version} ${milestone.name}\n\n`;
|
|
out += `**Progress:** [${bar}] ${totalSummaries}/${totalPlans} plans (${percent}%)\n\n`;
|
|
out += `| Phase | Name | Plans | Status |\n`;
|
|
out += `|-------|------|-------|--------|\n`;
|
|
for (const p of phases) {
|
|
out += `| ${p.number} | ${p.name} | ${p.summaries}/${p.plans} | ${p.status} |\n`;
|
|
}
|
|
output({ rendered: out }, raw, out);
|
|
} else if (format === 'bar') {
|
|
const barWidth = 20;
|
|
const filled = Math.round((percent / 100) * barWidth);
|
|
const bar = '\u2588'.repeat(filled) + '\u2591'.repeat(barWidth - filled);
|
|
const text = `[${bar}] ${totalSummaries}/${totalPlans} plans (${percent}%)`;
|
|
output({ bar: text, percent, completed: totalSummaries, total: totalPlans }, raw, text);
|
|
} else {
|
|
// JSON format
|
|
output({
|
|
milestone_version: milestone.version,
|
|
milestone_name: milestone.name,
|
|
phases,
|
|
total_plans: totalPlans,
|
|
total_summaries: totalSummaries,
|
|
percent,
|
|
}, raw);
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Match pending todos against a phase's goal/name/requirements.
|
|
* Returns todos with relevance scores based on keyword, area, and file overlap.
|
|
* Used by discuss-phase to surface relevant todos before scope-setting.
|
|
*/
|
|
function cmdTodoMatchPhase(cwd, phase, raw) {
|
|
if (!phase) { error('phase required for todo match-phase'); }
|
|
|
|
const pendingDir = path.join(planningDir(cwd), 'todos', 'pending');
|
|
const todos = [];
|
|
|
|
// Load pending todos
|
|
try {
|
|
const files = fs.readdirSync(pendingDir).filter(f => f.endsWith('.md'));
|
|
for (const file of files) {
|
|
const content = platformReadSync(path.join(pendingDir, file));
|
|
if (content === null) continue;
|
|
const titleMatch = content.match(/^title:\s*(.+)$/m);
|
|
const areaMatch = content.match(/^area:\s*(.+)$/m);
|
|
const filesMatch = content.match(/^files:\s*(.+)$/m);
|
|
const body = content.replace(/^(title|area|files|created|priority):.*$/gm, '').trim();
|
|
|
|
todos.push({
|
|
file,
|
|
title: titleMatch ? titleMatch[1].trim() : 'Untitled',
|
|
area: areaMatch ? areaMatch[1].trim() : 'general',
|
|
files: filesMatch ? filesMatch[1].trim().split(/[,\s]+/).filter(Boolean) : [],
|
|
body: body.slice(0, 200), // first 200 chars for context
|
|
});
|
|
}
|
|
} catch {}
|
|
|
|
if (todos.length === 0) {
|
|
output({ phase, matches: [], todo_count: 0 }, raw);
|
|
return;
|
|
}
|
|
|
|
// Load phase goal/name from ROADMAP
|
|
const phaseInfo = getRoadmapPhaseInternal(cwd, phase);
|
|
const phaseName = phaseInfo ? (phaseInfo.phase_name || '') : '';
|
|
const phaseGoal = phaseInfo ? (phaseInfo.goal || '') : '';
|
|
const phaseSection = phaseInfo ? (phaseInfo.section || '') : '';
|
|
|
|
// Build keyword set from phase name + goal + section text
|
|
const phaseText = `${phaseName} ${phaseGoal} ${phaseSection}`.toLowerCase();
|
|
const stopWords = new Set(['the', 'and', 'for', 'with', 'from', 'that', 'this', 'will', 'are', 'was', 'has', 'have', 'been', 'not', 'but', 'all', 'can', 'into', 'each', 'when', 'any', 'use', 'new']);
|
|
const phaseKeywords = new Set(
|
|
phaseText.split(/[\s\-_/.,;:()\[\]{}|]+/)
|
|
.map(w => w.replace(/[^a-z0-9]/g, ''))
|
|
.filter(w => w.length > 2 && !stopWords.has(w))
|
|
);
|
|
|
|
// Find phase directory to get expected file paths
|
|
const phaseInfoDisk = findPhaseInternal(cwd, phase);
|
|
const phasePlans = [];
|
|
if (phaseInfoDisk && phaseInfoDisk.found) {
|
|
try {
|
|
const phaseDir = path.join(cwd, phaseInfoDisk.directory);
|
|
const planFiles = fs.readdirSync(phaseDir).filter(f => f.endsWith('-PLAN.md'));
|
|
for (const pf of planFiles) {
|
|
const planContent = platformReadSync(path.join(phaseDir, pf));
|
|
if (planContent === null) continue;
|
|
const fmFiles = planContent.match(/files_modified:\s*\[([^\]]*)\]/);
|
|
if (fmFiles) {
|
|
phasePlans.push(...fmFiles[1].split(',').map(s => s.trim().replace(/['"]/g, '')).filter(Boolean));
|
|
}
|
|
}
|
|
} catch {}
|
|
}
|
|
|
|
// Score each todo for relevance
|
|
const matches = [];
|
|
for (const todo of todos) {
|
|
let score = 0;
|
|
const reasons = [];
|
|
|
|
// Keyword match: todo title/body terms in phase text
|
|
const todoWords = `${todo.title} ${todo.body}`.toLowerCase()
|
|
.split(/[\s\-_/.,;:()\[\]{}|]+/)
|
|
.map(w => w.replace(/[^a-z0-9]/g, ''))
|
|
.filter(w => w.length > 2 && !stopWords.has(w));
|
|
|
|
const matchedKeywords = todoWords.filter(w => phaseKeywords.has(w));
|
|
if (matchedKeywords.length > 0) {
|
|
score += Math.min(matchedKeywords.length * 0.2, 0.6);
|
|
reasons.push(`keywords: ${[...new Set(matchedKeywords)].slice(0, 5).join(', ')}`);
|
|
}
|
|
|
|
// Area match: todo area appears in phase text
|
|
if (todo.area !== 'general' && phaseText.includes(todo.area.toLowerCase())) {
|
|
score += 0.3;
|
|
reasons.push(`area: ${todo.area}`);
|
|
}
|
|
|
|
// File match: todo files overlap with phase plan files
|
|
if (todo.files.length > 0 && phasePlans.length > 0) {
|
|
const fileOverlap = todo.files.filter(f =>
|
|
phasePlans.some(pf => pf.includes(f) || f.includes(pf))
|
|
);
|
|
if (fileOverlap.length > 0) {
|
|
score += 0.4;
|
|
reasons.push(`files: ${fileOverlap.slice(0, 3).join(', ')}`);
|
|
}
|
|
}
|
|
|
|
if (score > 0) {
|
|
matches.push({
|
|
file: todo.file,
|
|
title: todo.title,
|
|
area: todo.area,
|
|
score: Math.round(score * 100) / 100,
|
|
reasons,
|
|
});
|
|
}
|
|
}
|
|
|
|
// Sort by score descending
|
|
matches.sort((a, b) => b.score - a.score);
|
|
|
|
output({ phase, matches, todo_count: todos.length }, raw);
|
|
}
|
|
|
|
function cmdTodoComplete(cwd, filename, raw) {
|
|
if (!filename) {
|
|
error('filename required for todo complete');
|
|
}
|
|
|
|
const pendingDir = path.join(planningDir(cwd), 'todos', 'pending');
|
|
const completedDir = path.join(planningDir(cwd), 'todos', 'completed');
|
|
const sourcePath = path.join(pendingDir, filename);
|
|
|
|
if (!fs.existsSync(sourcePath)) {
|
|
error(`Todo not found: ${filename}`);
|
|
}
|
|
|
|
// Ensure completed directory exists
|
|
platformEnsureDir(completedDir);
|
|
|
|
// Read, add completion timestamp, move
|
|
let content = fs.readFileSync(sourcePath, 'utf-8');
|
|
const today = new Date().toISOString().split('T')[0];
|
|
content = `completed: ${today}\n` + content;
|
|
|
|
platformWriteSync(path.join(completedDir, filename), content);
|
|
fs.unlinkSync(sourcePath);
|
|
|
|
output({ completed: true, file: filename, date: today }, raw, 'completed');
|
|
}
|
|
|
|
function cmdScaffold(cwd, type, options, raw) {
|
|
const { phase, name } = options;
|
|
const padded = phase ? normalizePhaseName(phase) : '00';
|
|
const today = new Date().toISOString().split('T')[0];
|
|
|
|
// Find phase directory
|
|
const phaseInfo = phase ? findPhaseInternal(cwd, phase) : null;
|
|
const phaseDir = phaseInfo ? path.join(cwd, phaseInfo.directory) : null;
|
|
|
|
if (phase && !phaseDir && type !== 'phase-dir') {
|
|
error(`Phase ${phase} directory not found`);
|
|
}
|
|
|
|
let filePath, content;
|
|
|
|
switch (type) {
|
|
case 'context': {
|
|
filePath = path.join(phaseDir, `${padded}-CONTEXT.md`);
|
|
content = `---\nphase: "${padded}"\nname: "${name || phaseInfo?.phase_name || 'Unnamed'}"\ncreated: ${today}\n---\n\n# Phase ${phase}: ${name || phaseInfo?.phase_name || 'Unnamed'} — Context\n\n## Decisions\n\n_Decisions will be captured during ${formatGsdSlash('discuss-phase', resolveRuntime(cwd))} ${phase}_\n\n## Discretion Areas\n\n_Areas where the executor can use judgment_\n\n## Deferred Ideas\n\n_Ideas to consider later_\n`;
|
|
break;
|
|
}
|
|
case 'uat': {
|
|
filePath = path.join(phaseDir, `${padded}-UAT.md`);
|
|
content = `---\nphase: "${padded}"\nname: "${name || phaseInfo?.phase_name || 'Unnamed'}"\ncreated: ${today}\nstatus: pending\n---\n\n# Phase ${phase}: ${name || phaseInfo?.phase_name || 'Unnamed'} — User Acceptance Testing\n\n## Test Results\n\n| # | Test | Status | Notes |\n|---|------|--------|-------|\n\n## Summary\n\n_Pending UAT_\n`;
|
|
break;
|
|
}
|
|
case 'verification': {
|
|
filePath = path.join(phaseDir, `${padded}-VERIFICATION.md`);
|
|
content = `---\nphase: "${padded}"\nname: "${name || phaseInfo?.phase_name || 'Unnamed'}"\ncreated: ${today}\nstatus: pending\n---\n\n# Phase ${phase}: ${name || phaseInfo?.phase_name || 'Unnamed'} — Verification\n\n## Goal-Backward Verification\n\n**Phase Goal:** [From ROADMAP.md]\n\n## Checks\n\n| # | Requirement | Status | Evidence |\n|---|------------|--------|----------|\n\n## Result\n\n_Pending verification_\n`;
|
|
break;
|
|
}
|
|
case 'phase-dir': {
|
|
if (!phase || !name) {
|
|
error('phase and name required for phase-dir scaffold');
|
|
}
|
|
const slug = generateSlugInternal(name);
|
|
// #3287: apply project_code prefix to stay consistent with phase.add/phase.insert
|
|
const scaffoldConfig = loadConfig(cwd);
|
|
const scaffoldProjectCode = scaffoldConfig.project_code || '';
|
|
const scaffoldPrefix = scaffoldProjectCode ? `${scaffoldProjectCode}-` : '';
|
|
const dirName = `${scaffoldPrefix}${padded}-${slug}`;
|
|
const phasesParent = planningPaths(cwd).phases;
|
|
platformEnsureDir(phasesParent);
|
|
const dirPath = path.join(phasesParent, dirName);
|
|
platformEnsureDir(dirPath);
|
|
output({ created: true, directory: toPosixPath(path.relative(cwd, dirPath)), path: dirPath }, raw, dirPath);
|
|
return;
|
|
}
|
|
default:
|
|
error(`Unknown scaffold type: ${type}. Available: context, uat, verification, phase-dir`);
|
|
}
|
|
|
|
if (fs.existsSync(filePath)) {
|
|
output({ created: false, reason: 'already_exists', path: filePath }, raw, 'exists');
|
|
return;
|
|
}
|
|
|
|
platformWriteSync(filePath, content);
|
|
const relPath = toPosixPath(path.relative(cwd, filePath));
|
|
output({ created: true, path: relPath }, raw, relPath);
|
|
}
|
|
|
|
function cmdStats(cwd, format, raw) {
|
|
const phasesDir = planningPaths(cwd).phases;
|
|
const roadmapPath = planningPaths(cwd).roadmap;
|
|
const reqPath = planningPaths(cwd).requirements;
|
|
const statePath = planningPaths(cwd).state;
|
|
const milestone = getMilestoneInfo(cwd);
|
|
const isDirInMilestone = getMilestonePhaseFilter(cwd);
|
|
|
|
// Phase & plan stats (reuse progress pattern)
|
|
const phasesByNumber = new Map();
|
|
let totalPlans = 0;
|
|
let totalSummaries = 0;
|
|
|
|
try {
|
|
const roadmapRaw = platformReadSync(roadmapPath);
|
|
if (roadmapRaw === null) throw new Error('roadmap missing');
|
|
const roadmapContent = extractCurrentMilestone(roadmapRaw, cwd);
|
|
const headingPattern = /#{2,4}\s*Phase\s+(\d+[A-Z]?(?:\.\d+)*)\s*:\s*([^\n]+)/gi;
|
|
let match;
|
|
while ((match = headingPattern.exec(roadmapContent)) !== null) {
|
|
const key = normalizePhaseName(match[1]);
|
|
phasesByNumber.set(key, {
|
|
number: key,
|
|
name: match[2].replace(/\(INSERTED\)/i, '').trim(),
|
|
plans: 0,
|
|
summaries: 0,
|
|
status: 'Not Started',
|
|
});
|
|
}
|
|
} catch { /* intentionally empty */ }
|
|
|
|
try {
|
|
const entries = fs.readdirSync(phasesDir, { withFileTypes: true });
|
|
const dirs = entries
|
|
.filter(e => e.isDirectory())
|
|
.map(e => e.name)
|
|
.filter(isDirInMilestone)
|
|
.sort((a, b) => comparePhaseNum(a, b));
|
|
|
|
for (const dir of dirs) {
|
|
const dm = dir.match(/^(\d+[A-Z]?(?:\.\d+)*)-?(.*)/i);
|
|
const phaseNum = dm ? dm[1] : dir;
|
|
const phaseName = dm && dm[2] ? dm[2].replace(/-/g, ' ') : '';
|
|
const phaseFiles = fs.readdirSync(path.join(phasesDir, dir));
|
|
const plans = phaseFiles.filter(f => f.endsWith('-PLAN.md') || f === 'PLAN.md').length;
|
|
const summaries = phaseFiles.filter(f => f.endsWith('-SUMMARY.md') || f === 'SUMMARY.md').length;
|
|
|
|
totalPlans += plans;
|
|
totalSummaries += summaries;
|
|
|
|
const status = determinePhaseStatus(plans, summaries, path.join(phasesDir, dir), 'Not Started');
|
|
|
|
const normalizedNum = normalizePhaseName(phaseNum);
|
|
const existing = phasesByNumber.get(normalizedNum);
|
|
phasesByNumber.set(normalizedNum, {
|
|
number: normalizedNum,
|
|
name: existing?.name || phaseName,
|
|
plans: (existing?.plans || 0) + plans,
|
|
summaries: (existing?.summaries || 0) + summaries,
|
|
status,
|
|
});
|
|
}
|
|
} catch { /* intentionally empty */ }
|
|
|
|
const phases = [...phasesByNumber.values()].sort((a, b) => comparePhaseNum(a.number, b.number));
|
|
const completedPhases = phases.filter(p => p.status === 'Complete').length;
|
|
const planPercent = totalPlans > 0 ? Math.min(100, Math.round((totalSummaries / totalPlans) * 100)) : 0;
|
|
const percent = phases.length > 0 ? Math.min(100, Math.round((completedPhases / phases.length) * 100)) : 0;
|
|
|
|
// Requirements stats
|
|
let requirementsTotal = 0;
|
|
let requirementsComplete = 0;
|
|
const reqContent = platformReadSync(reqPath);
|
|
if (reqContent !== null) {
|
|
const checked = reqContent.match(/^- \[x\] \*\*/gm);
|
|
const unchecked = reqContent.match(/^- \[ \] \*\*/gm);
|
|
requirementsComplete = checked ? checked.length : 0;
|
|
requirementsTotal = requirementsComplete + (unchecked ? unchecked.length : 0);
|
|
}
|
|
|
|
// Last activity from STATE.md
|
|
let lastActivity = null;
|
|
const stateContent = platformReadSync(statePath);
|
|
if (stateContent !== null) {
|
|
const activityMatch = stateContent.match(/^last_activity:\s*(.+)$/im)
|
|
|| stateContent.match(/\*\*Last Activity:\*\*\s*(.+)/i)
|
|
|| stateContent.match(/^Last Activity:\s*(.+)$/im)
|
|
|| stateContent.match(/^Last activity:\s*(.+)$/im);
|
|
if (activityMatch) lastActivity = activityMatch[1].trim();
|
|
}
|
|
|
|
// Git stats
|
|
let gitCommits = 0;
|
|
let gitFirstCommitDate = null;
|
|
const commitCount = execGit(['rev-list', '--count', 'HEAD'], { cwd });
|
|
if (commitCount.exitCode === 0) {
|
|
gitCommits = parseInt(commitCount.stdout, 10) || 0;
|
|
}
|
|
const rootHash = execGit(['rev-list', '--max-parents=0', 'HEAD'], { cwd });
|
|
if (rootHash.exitCode === 0 && rootHash.stdout) {
|
|
const firstCommit = rootHash.stdout.split('\n')[0].trim();
|
|
const firstDate = execGit(['show', '-s', '--format=%as', firstCommit], { cwd });
|
|
if (firstDate.exitCode === 0) {
|
|
gitFirstCommitDate = firstDate.stdout || null;
|
|
}
|
|
}
|
|
|
|
const result = {
|
|
milestone_version: milestone.version,
|
|
milestone_name: milestone.name,
|
|
phases,
|
|
phases_completed: completedPhases,
|
|
phases_total: phases.length,
|
|
total_plans: totalPlans,
|
|
total_summaries: totalSummaries,
|
|
percent,
|
|
plan_percent: planPercent,
|
|
requirements_total: requirementsTotal,
|
|
requirements_complete: requirementsComplete,
|
|
git_commits: gitCommits,
|
|
git_first_commit_date: gitFirstCommitDate,
|
|
last_activity: lastActivity,
|
|
};
|
|
|
|
if (format === 'table') {
|
|
const barWidth = 10;
|
|
const filled = Math.round((percent / 100) * barWidth);
|
|
const bar = '\u2588'.repeat(filled) + '\u2591'.repeat(barWidth - filled);
|
|
let out = `# ${milestone.version} ${milestone.name} \u2014 Statistics\n\n`;
|
|
out += `**Progress:** [${bar}] ${completedPhases}/${phases.length} phases (${percent}%)\n`;
|
|
if (totalPlans > 0) {
|
|
out += `**Plans:** ${totalSummaries}/${totalPlans} complete (${planPercent}%)\n`;
|
|
}
|
|
out += `**Phases:** ${completedPhases}/${phases.length} complete\n`;
|
|
if (requirementsTotal > 0) {
|
|
out += `**Requirements:** ${requirementsComplete}/${requirementsTotal} complete\n`;
|
|
}
|
|
out += '\n';
|
|
out += `| Phase | Name | Plans | Completed | Status |\n`;
|
|
out += `|-------|------|-------|-----------|--------|\n`;
|
|
for (const p of phases) {
|
|
out += `| ${p.number} | ${p.name} | ${p.plans} | ${p.summaries} | ${p.status} |\n`;
|
|
}
|
|
if (gitCommits > 0) {
|
|
out += `\n**Git:** ${gitCommits} commits`;
|
|
if (gitFirstCommitDate) out += ` (since ${gitFirstCommitDate})`;
|
|
out += '\n';
|
|
}
|
|
if (lastActivity) out += `**Last activity:** ${lastActivity}\n`;
|
|
output({ rendered: out }, raw, out);
|
|
} else {
|
|
output(result, raw);
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Check whether a commit should be allowed based on commit_docs config.
|
|
* When commit_docs is false, rejects commits that stage .planning/ files.
|
|
* Intended for use as a pre-commit hook guard.
|
|
*/
|
|
function cmdCheckCommit(cwd, raw) {
|
|
const config = loadConfig(cwd);
|
|
|
|
// If commit_docs is true (or not set), allow all commits
|
|
if (config.commit_docs !== false) {
|
|
output({ allowed: true, reason: 'commit_docs_enabled' }, raw, 'allowed');
|
|
return;
|
|
}
|
|
|
|
// commit_docs is false — check if any .planning/ files are staged
|
|
const stagedResult = execGit(['diff', '--cached', '--name-only'], { cwd });
|
|
if (stagedResult.exitCode === 0) {
|
|
const planningFiles = stagedResult.stdout.split('\n').filter(f => f.startsWith('.planning/') || f.startsWith('.planning\\'));
|
|
|
|
if (planningFiles.length > 0) {
|
|
error(
|
|
`commit_docs is false but ${planningFiles.length} .planning/ file(s) are staged:\n` +
|
|
planningFiles.map(f => ` ${f}`).join('\n') +
|
|
`\n\nTo unstage: git reset HEAD ${planningFiles.join(' ')}`
|
|
);
|
|
}
|
|
}
|
|
// exitCode !== 0 → no staged files or not a git repo — allow
|
|
|
|
output({ allowed: true, reason: 'no_planning_files_staged' }, raw, 'allowed');
|
|
}
|
|
|
|
module.exports = {
|
|
groupFilesBySubrepo,
|
|
determinePhaseStatus,
|
|
cmdGenerateSlug,
|
|
cmdCurrentTimestamp,
|
|
cmdListTodos,
|
|
cmdVerifyPathExists,
|
|
cmdHistoryDigest,
|
|
cmdResolveModel,
|
|
cmdResolveExecution,
|
|
cmdCommit,
|
|
cmdCommitToSubrepo,
|
|
cmdSummaryExtract,
|
|
cmdWebsearch,
|
|
cmdProgressRender,
|
|
cmdTodoComplete,
|
|
cmdTodoMatchPhase,
|
|
cmdScaffold,
|
|
cmdStats,
|
|
cmdCheckCommit,
|
|
_wsParseRetryAfter,
|
|
};
|