* enhancement(#537): migrate code-review-flags to TS source of truth Collapse the hand-written get-shit-done/bin/lib/code-review-flags.cjs to a TypeScript source of truth (src/code-review-flags.cts), compiled by tsc to a gitignored .cjs build artifact at the same path, per ADR-457 (build-at-publish). Second module after the semver-compare pilot (#541). Behaviour is preserved byte-for-behaviour (characterization test added in tests/code-review-flags.test.cjs locks the parser quirks). Adds compile-time type checking: CodeReviewFlags interface + CodeReviewWorkflow literal union. The require() path is unchanged, so code-review.md and the bug-3727 test keep working. The emitted .cjs is gitignored and eslint-ignored, mirroring the pilot. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com> * enhancement(#537): migrate 9 leaf bin/lib modules to TS source of truth ADR-457 build-at-publish, batch 1 (pure leaf modules, 0 sibling-deps): 001-legacy-orphan-files, context-utilization, redaction, artifacts, command-arg-projection, clock, ui-safety-gate, review-reviewer-selection, clusters. Each moves to src/*.cts (strict TS, typed), compiled by tsc to a gitignored .cjs at the same require() path; behaviour preserved byte-for- behaviour. Adds src/node-globals.d.ts (minimal ambient shim; "types":[]). Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com> * chore(#537): add @types/node, drop hand-rolled node-globals shim ADR-457 migration infra: replace the temporary src/node-globals.d.ts ambient shim with @types/node@22 + "types":["node"] in tsconfig.build.json. Unblocks migrating the ~49 remaining bin/lib modules that use node:fs/path/os/ child_process. Build + full suite (3030 pass) + lint all green; no .cts type changes were needed (real Node types matched the shim). Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com> * enhancement(#537): migrate 9 more bin/lib modules to TS (batch 2) ADR-457 build-at-publish. Clean leaves: installer-migration-report, prompt-budget. Type-error-prone leaves (were tsconfig.lint-excluded; now strict-typed and removed from that exclude list): secrets, phase-lifecycle, workstream-name-policy, decisions, validate, schema-detect. Plus runtime-name-policy. Strict type fixes narrow unknown->concrete domain types (no any/ts-ignore); behaviour preserved. Full suite green, lint 0 errors. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com> * enhancement(#537): migrate runtime-slash to TS (cross-import proof) ADR-457. First cross-module TS->TS import: src/runtime-slash.cts imports ./runtime-name-policy.cjs and tsc resolves the sibling .cts types under strict (no declaration files; NodeNext .cjs->.cts mapping), emitting a correct require("./runtime-name-policy.cjs"). Confirms the recipe for coupled modules, which must be migrated in dependency order (leaves-up). Suite green, lint clean. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com> * enhancement(#537): migrate 10 more bin/lib modules to TS (batch 3) ADR-457 build-at-publish, Wave-1 leaves: event, workstream-inventory-builder, plan-scan, fallow-runner, project-root, installer-migration-authoring, update-context, 000-first-time-baseline, runtime-homes, model-catalog. Strict typing fixed real issues (narrowing unknown, qualified fs/path calls, removed unnecessary casts); plan-scan/project-root/workstream-inventory-builder dropped from tsconfig.lint exclude. Behaviour preserved; suite green, lint 0 errors. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com> * enhancement(#537): migrate 5 large Wave-1 leaves to TS (batch 4) ADR-457 build-at-publish: configuration, state-document, shell-command- projection (42 dependents), security, command-aliases. shell-command- projection keeps a namespace child_process import for mock-intercept testability. loadConfig/migrateOnDisk emit synchronously (every caller uses them sync; the one awaited migrateOnDisk caller tolerates a non-Promise) — full suite (3030 pass) confirms behaviour preserved. configuration/ state-document/command-aliases dropped from tsconfig.lint exclude. Also fixes the malformed batch-3 changeset frontmatter (type/pr) that failed lint:docs. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com> * enhancement(#537): migrate 6 Wave-2 modules to TS (batch 5) ADR-457 build-at-publish: config-schema, model-profiles, 002-codex-legacy-hooks-json, logger, active-workstream-store, adr-parser. First batch importing already-migrated siblings (configuration, model-catalog, shell-command-projection, redaction, security) via ./sibling.cjs specifiers. Strict type narrowing (typeof guards over String(unknown)); behaviour preserved; suite 3030 pass, lint 0 errors. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com> * enhancement(#537): migrate 5 large Wave-2 modules to TS (batch 6) ADR-457 build-at-publish: graphify, install-profiles, intel, installer-migrations, worktree-safety. installer-migrations preserves its dynamic require() loader for numbered migration modules (scoped lint suppressions). Strict typing (typeof guards over String(unknown)); behaviour preserved; suite 3030 pass, lint 0 errors. Wave 2 complete. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com> * enhancement(#537): migrate Wave-3 modules to TS (batch 7) ADR-457 build-at-publish: planning-workspace, runtime-artifact-layout, command-routing-hub, drift. Uses `import x = require()` for export= siblings; drift's lazy require of runtime-slash hoisted to a top-level import (verified non-circular). Behaviour preserved; suite 3030 pass, lint 0 errors. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com> * enhancement(#537): migrate small Wave-4 modules to TS (batch 8) ADR-457 build-at-publish: cjs-command-router-adapter, phase-command-router, surface, roadmap-upgrade. Typed the hub router handler results as the HubResult discriminated union; surface drops 4 genuinely-unused imports. Behaviour preserved; suite 3030 pass, lint 0 errors. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com> * enhancement(#537): migrate core hub (2.5k LOC, 68 dependents) to TS (batch 9) ADR-457 build-at-publish: get-shit-done/bin/lib/core.cjs -> src/core.cts, preserving all 63 exports via export=. All sibling deps already migrated (shell-command-projection, model-profiles, model-catalog, worktree-safety, planning-workspace, project-root, configuration, config-schema). Strict types, no any/ts-ignore; config-schema lazy require hoisted (non-circular). Behaviour preserved (independently verified: core's shard 3030 pass / 0 fail). Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com> * test(#537): make ESLint-coverage + test-sprawl checks migration-aware #551 test hardcoded 12 now-migrated modules as "hand-written, must be linted"; that invariant is obsoleted by the ADR-457 migration. Rewrite it to a filesystem-driven invariant that holds at every stage: a bin/lib/*.cjs must be eslint-ignored IFF it has a src/*.cts source (tsc-generated), else linted (covers package-identity, which has no TS source). Also eslint-ignore config-types.cjs (has a src counterpart) and drop the redundant tests/clock.test.cjs (clock already covered by clock-seam + bug-474 tests), which tripped the lint-test-file-count ratchet. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com> * enhancement(#537): migrate 9 Wave-5 router/inventory modules to TS (batch 10) ADR-457 build-at-publish: phases/verify/init/agent/task/validate/roadmap/state command routers + workstream-inventory. Router handler results typed against core's exported shapes; behaviour preserved (caught+fixed a --verify boolean flag regression mid-migration). Full suite green across all shards (only the 4 local gpg-env changeset-notes failures remain; CI passes them). Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com> * enhancement(#537): migrate 7 Wave-5 modules to TS (batch 11) ADR-457 build-at-publish: gap-checker, docs, check-command-router, frontmatter, learnings, gsd2-import, profile-pipeline. Behaviour preserved; full suite green across all shards (only the 4 local gpg-env failures remain). Also broadens atomic-write-coverage.test.cjs to accept the tsc-compiled namespace-import form while still asserting platformWriteSync is called (safety guard intact). Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com> * enhancement(#537): migrate config + profile-output to TS (batch 12) ADR-457 build-at-publish: config (729 LOC), profile-output (1142 LOC). All exports preserved; cmdMigrateConfig de-asynced (migrateOnDisk is sync, awaited caller tolerates it). Behaviour preserved; suite green across all shards (only the 4 local gpg-env failures). Wave 5 complete. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com> * enhancement(#537): migrate 5 Wave-6 modules to TS (batch 13) ADR-457 build-at-publish: template, uat, workstream, roadmap, audit. Behaviour preserved (dead toPosixPath import dropped from audit; inline requires hoisted). Suite green across all shards (only the 4 local gpg-env failures). Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com> * enhancement(#537): migrate commands + state hubs to TS (batch 14) ADR-457 build-at-publish: commands (1305 LOC), state (2074 LOC, 17 dependents). All exports preserved; inner requires kept non-hoisted where load-order matters (install.js, per-call security); acquireStateLock cast inlined to preserve the err.code source token a structural test inspects. Behaviour preserved; suite green across all shards (only the 4 local gpg-env failures). Wave 6 complete. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com> * enhancement(#537): migrate milestone to TS (batch 15a, hand-authored) ADR-457 build-at-publish: milestone -> src/milestone.cts. Authored directly (subagent capacity was unavailable). Also relaxes core.output()'s 3rd param to optional, matching its real always-optional call contract (unblocks remaining 2-arg output callers). Behaviour preserved; suite green across all shards (only the 4 local gpg-env failures). Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com> * enhancement(#537): migrate phase, verify, init to TS (batch 15, final modules) ADR-457 build-at-publish, Wave 7 (the last hubs): phase (1608 LOC), verify (1615), init (2113). Adds src/package-identity.d.cts so verify can import the permanently value-baked package-identity.cjs under strict TS. Fixes two regressions the migration introduced in verify: restore cmdValidateHealth's `return result` (callers/tests read result.warnings — it is NOT side-effect-only), and make the bug-3384 source-pattern test tolerant of the tsc-compiled bracket-notation form of the git_list_failed->W020 branch (behaviour intact). Full suite green across all shards (only the 4 local gpg-env failures); lint 0 errors. All 86 migratable bin/lib modules are now TypeScript sources. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com> * chore(#537): finalize ADR-457 migration — retire tsconfig.lint.json All hand-written bin/lib/*.cjs are now src/*.cts sources, so the checkJs stopgap tsconfig.lint.json (unused; not wired into eslint, scripts, or CI) is deleted per ADR-457's final step. Also gitignore the tsc-generated config-types.cjs (was still committed) for consistency with every other emitted artifact. package-identity.cjs stays value-baked (declared via src/package-identity.d.cts). Suite green; #551 ESLint-coverage test green. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com> * fix(#537): add prepare script so unpacked/git installs build bin/lib artifacts ADR-457 build-at-publish: bin/lib/*.cjs are now gitignored, built by tsc. The prepack/prepublishOnly hooks cover `npm pack`/publish, but `npm install -g <dir>` and git installs run the `prepare` lifecycle — which was missing — so the unpacked install shipped without the compiled .cjs and failed at startup with "Cannot find module './lib/core.cjs'" (caught by the smoke-unpacked CI job). Add `prepare` mirroring prepublishOnly (build:lib + build:hooks). prepare does NOT run for registry consumers (they get the pre-built tarball), only for source/local/pack installs. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com> * fix(#537): make CI build/lockfile checks work with gitignored bin/lib artifacts ADR-457 build-at-publish exposed two CI assumptions that bin/lib/*.cjs are always present on disk: - check:env's lockfile-sync ran `npm ci --dry-run`, which now triggers the `prepare` build (tsc) — but it runs before deps are installed, so tsc is absent and it misreported the lockfile as out of sync. Add --ignore-scripts (a lockfile check must not build). - the lint-tests job installs with --ignore-scripts (no prepare build), but lint:skill-deps require()s the built install-profiles.cjs. Add an explicit `npm run build:lib` step after install. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com> * fix(#537): narrow prepare to build:lib only (unbreak packed-smoke pack step) prepare running build:hooks emitted "✓ Copying ..." stdout during `npm pack`, which the install-smoke "Pack root tarball" step captures into $GITHUB_OUTPUT — breaking it with "Invalid format". build:lib (tsc) is silent on success and is all the unpacked/source install needs (the smoke-unpacked assertions exercise gsd-tools, i.e. bin/lib, and tolerate hook setup with `|| true`). Matches prepack. build:hooks still runs on prepublishOnly for real publishes. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com> * fix(#537): wire Stryker mutation gate to build-at-publish layout The gate scored 0.00 because it mutated changed bin/lib/*.cjs that (a) were generated artifacts and (b) included modules with no coverage in the command's test set. Rework: mutation.yml now derives changed COVERED modules from src/*.cts and maps them to their built bin/lib/*.cjs; Stryker mutates those built artifacts with a no-rebuild command (mutating src/*.cts + per-mutant tsc was ~3x over the 30-min CI budget). NOTE: with the gate now correctly measuring the covered modules, their actual mutation score is 42.94% (< break 50) — a pre-existing test-coverage gap (adr-parser/prompt-budget/etc.), not introduced by this behaviour-preserving migration. Reaching 50 needs more tests, a threshold/scope change, or a waiver — a maintainer decision. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com> * test(#537): raise mutation coverage of covered modules above the 50 gate Adds focused example-based unit tests that kill surviving mutants in the two lowest-scoring covered modules: - tests/prompt-budget.unit.test.cjs (112 tests): 17.9% -> 97.9% - tests/adr-parser.unit.test.cjs (205 tests): 44.7% -> 89.4% Both wired into stryker.config.mjs's command. Fresh full run over the 6 covered modules now scores 82.25% (>= break 50); every covered module is >= 68%. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com> * enhancement(#537,#609): parallelize mutation gate via dynamic per-module matrix The serial Stryker run timed out at 30 min once the migration's added tests made every mutant re-run ~300 tests. Replace it with a dynamic matrix so the gate completes well under budget — folded into this PR (was tracked as #609) because it's a prerequisite for this PR's mutation gate to pass. - scripts/mutation-matrix.cjs: single source of truth (covered-module -> test files) computing changed covered modules from git diff -> {has_work, matrix}. - mutation.yml: detect -> dynamic `matrix: fromJSON(...)` mutate job (one parallel shard per changed module, scoped via MUTATION_TEST_CMD to only that module's tests, 15-min/shard) -> summary job that KEEPS the legacy check name "Stryker mutation score (changed files only)" so branch protection is unchanged. Per-shard jobs report as "Stryker (<module>)". - stryker.config.mjs: commandRunner.command reads MUTATION_TEST_CMD (falls back to the full command locally). Closes #609. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com> * test(#537,#609): give each mutation shard ≥50% on its own tests; drop blacksmith note Per-module sharding revealed that active-workstream-store (46.5%) and frontmatter (7.4%) only cleared 50% in the old serial run via timeout-noise from the bloated 300-test command; on their own tests they were below the gate. Add focused unit tests: - tests/active-workstream-store.unit.test.cjs (115 tests): 46.5% -> 81.9% - tests/frontmatter.unit.test.cjs (165 tests): 7.4% -> 63.4% Both wired into scripts/mutation-matrix.cjs (per-module test map) and stryker.config.mjs DEFAULT_TEST_CMD. All 6 covered modules now clear break:50 with only their own tests (config-schema/context-utilization/prompt-budget/ adr-parser already did). Also removes the leftover blacksmith TODO comment — GitHub-hosted runners only; speed comes from parallel per-module shards. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com> * test(#537,#609): strengthen prompt-budget tests to clear the gate on its own tests prompt-budget scored 39.58% when mutation-tested with ONLY its own tests (the way the per-module CI shard runs it) — an earlier ~98% reading was inflated by accidentally running the full multi-module command. Add 96 targeted tests to tests/prompt-budget.unit.test.cjs (exact note-template text, plan-truncation arithmetic/percentages, drop-block strings, noteInjected/hardFailed booleans): scoped score 39.58% -> 68.75% (>= break 50). All 6 covered modules now clear the gate on their own tests. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
1411 lines
53 KiB
TypeScript
1411 lines
53 KiB
TypeScript
/**
|
|
* Commands — Standalone utility commands
|
|
*
|
|
* ADR-457 build-at-publish: the hand-written bin/lib/commands.cjs collapsed
|
|
* to a TypeScript source of truth. Behaviour is preserved byte-for-behaviour
|
|
* from the prior hand-written .cjs; only strict types are added.
|
|
*/
|
|
|
|
import fs from 'node:fs';
|
|
import path from 'node:path';
|
|
import { execGit, platformWriteSync, platformReadSync, platformEnsureDir } from './shell-command-projection.cjs';
|
|
// eslint-disable-next-line @typescript-eslint/no-require-imports
|
|
import core = require('./core.cjs');
|
|
const {
|
|
loadConfig,
|
|
isGitIgnored,
|
|
normalizePhaseName,
|
|
comparePhaseNum,
|
|
getArchivedPhaseDirs,
|
|
generateSlugInternal,
|
|
getMilestoneInfo,
|
|
getMilestonePhaseFilter,
|
|
resolveModelInternal,
|
|
resolveEffortInternal,
|
|
resolveFastModeInternal,
|
|
resolveEffortForTier,
|
|
stripShippedMilestones: _stripShippedMilestones,
|
|
extractCurrentMilestone,
|
|
toPosixPath,
|
|
output,
|
|
error,
|
|
findPhaseInternal,
|
|
extractOneLinerFromBody,
|
|
getRoadmapPhaseInternal,
|
|
extractPhaseToken,
|
|
resolveGranularityInternal,
|
|
} = core;
|
|
import { renderEffortForRuntime, RUNTIMES_WITH_FAST_MODE } from './model-catalog.cjs';
|
|
// eslint-disable-next-line @typescript-eslint/no-require-imports
|
|
import planningWorkspace = require('./planning-workspace.cjs');
|
|
const { planningDir, planningPaths } = planningWorkspace;
|
|
// eslint-disable-next-line @typescript-eslint/no-require-imports
|
|
import frontmatter = require('./frontmatter.cjs');
|
|
const { extractFrontmatter } = frontmatter;
|
|
// eslint-disable-next-line @typescript-eslint/no-require-imports
|
|
import modelProfiles = require('./model-profiles.cjs');
|
|
const { MODEL_PROFILES, VALID_PHASE_TYPES } = modelProfiles;
|
|
import { formatGsdSlash, resolveRuntime } from './runtime-slash.cjs';
|
|
|
|
// ─── Types ────────────────────────────────────────────────────────────────────
|
|
|
|
interface ArchivedPhaseDir {
|
|
name: string;
|
|
fullPath: string;
|
|
milestone: string | null;
|
|
}
|
|
|
|
interface PhaseProgress {
|
|
number: string;
|
|
name: string;
|
|
plans: number;
|
|
summaries: number;
|
|
status: string;
|
|
}
|
|
|
|
interface GroupFilesBySubrepoResult {
|
|
grouped: Record<string, string[]>;
|
|
unmatched: string[];
|
|
}
|
|
|
|
interface WebsearchOptions {
|
|
limit?: number;
|
|
freshness?: string;
|
|
}
|
|
|
|
interface ScaffoldOptions {
|
|
phase?: string;
|
|
name?: string;
|
|
}
|
|
|
|
interface CommitToSubrepoRepoResult {
|
|
committed: boolean;
|
|
hash: string | null;
|
|
files: string[];
|
|
reason?: string;
|
|
error?: string;
|
|
}
|
|
|
|
interface EffortSyncChange {
|
|
agent: string;
|
|
from: string | null;
|
|
to: string;
|
|
}
|
|
|
|
// ─── Phase Status ─────────────────────────────────────────────────────────────
|
|
|
|
/**
|
|
* 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: number, summaries: number, phaseDir: string, defaultPending: string): string {
|
|
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: string | undefined, raw: boolean): void {
|
|
if (!text) {
|
|
error('text required for slug generation');
|
|
}
|
|
|
|
const slug = (text as string)
|
|
.toLowerCase()
|
|
.replace(/[^a-z0-9]+/g, '-')
|
|
.replace(/^-+|-+$/g, '')
|
|
.substring(0, 60);
|
|
|
|
const result = { slug };
|
|
output(result, raw, slug);
|
|
}
|
|
|
|
function cmdCurrentTimestamp(format: string | undefined, raw: boolean): void {
|
|
const now = new Date();
|
|
let result: string;
|
|
|
|
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: string, area: string | undefined, raw: boolean): void {
|
|
const pendingDir = path.join(planningDir(cwd), 'todos', 'pending');
|
|
|
|
let count = 0;
|
|
const todos: Array<{ file: string; created: string; title: string; area: string; path: string }> = [];
|
|
|
|
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: string, targetPath: string | undefined, raw: boolean): void {
|
|
if (!targetPath) {
|
|
error('path required for verification');
|
|
}
|
|
|
|
// Reject null bytes and validate path does not contain traversal attempts
|
|
if ((targetPath as string).includes('\0')) {
|
|
error('path contains null bytes');
|
|
}
|
|
|
|
const fullPath = path.isAbsolute(targetPath as string) ? targetPath as string : path.join(cwd, targetPath as string);
|
|
|
|
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: string, raw: boolean): void {
|
|
const phasesDir = planningPaths(cwd).phases;
|
|
const digest: {
|
|
phases: Record<string, { name: string; provides: Set<string> | string[]; affects: Set<string> | string[]; patterns: Set<string> | string[] }>;
|
|
decisions: Array<{ phase: string; decision: string }>;
|
|
tech_stack: Set<string> | string[];
|
|
} = { phases: {}, decisions: [], tech_stack: new Set() };
|
|
|
|
// Collect all phase directories: archived + current
|
|
const allPhaseDirs: Array<{ name: string; fullPath: string; milestone: string | null }> = [];
|
|
|
|
// Add archived phases first (oldest milestones first)
|
|
const archived = getArchivedPhaseDirs(cwd) as ArchivedPhaseDir[];
|
|
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, undefined);
|
|
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) as Record<string, unknown>;
|
|
|
|
const phaseNum = (fm['phase'] as string) || dir.split('-')[0];
|
|
|
|
if (!digest.phases[phaseNum]) {
|
|
digest.phases[phaseNum] = {
|
|
name: (fm['name'] as string) || dir.split('-').slice(1).join(' ') || 'Unknown',
|
|
provides: new Set<string>(),
|
|
affects: new Set<string>(),
|
|
patterns: new Set<string>(),
|
|
};
|
|
}
|
|
|
|
// Merge provides
|
|
const depGraph = fm['dependency-graph'] as Record<string, string[]> | undefined;
|
|
if (depGraph && depGraph['provides']) {
|
|
depGraph['provides'].forEach((p: string) => (digest.phases[phaseNum].provides as Set<string>).add(p));
|
|
} else if (fm['provides']) {
|
|
(fm['provides'] as string[]).forEach((p: string) => (digest.phases[phaseNum].provides as Set<string>).add(p));
|
|
}
|
|
|
|
// Merge affects
|
|
if (depGraph && depGraph['affects']) {
|
|
depGraph['affects'].forEach((a: string) => (digest.phases[phaseNum].affects as Set<string>).add(a));
|
|
}
|
|
|
|
// Merge patterns
|
|
if (fm['patterns-established']) {
|
|
(fm['patterns-established'] as string[]).forEach((p: string) => (digest.phases[phaseNum].patterns as Set<string>).add(p));
|
|
}
|
|
|
|
// Merge decisions
|
|
if (fm['key-decisions']) {
|
|
(fm['key-decisions'] as string[]).forEach((d: string) => {
|
|
digest.decisions.push({ phase: phaseNum, decision: d });
|
|
});
|
|
}
|
|
|
|
// Merge tech stack
|
|
const techStack = fm['tech-stack'] as { added?: Array<string | { name: string }> } | undefined;
|
|
if (techStack && techStack['added']) {
|
|
techStack['added'].forEach((t: string | { name: string }) => (digest.tech_stack as Set<string>).add(typeof t === 'string' ? t : t.name));
|
|
}
|
|
|
|
} catch {
|
|
// Skip malformed summaries
|
|
}
|
|
}
|
|
}
|
|
|
|
// Convert Sets to Arrays for JSON output
|
|
Object.keys(digest.phases).forEach(p => {
|
|
digest.phases[p].provides = [...(digest.phases[p].provides as Set<string>)];
|
|
digest.phases[p].affects = [...(digest.phases[p].affects as Set<string>)];
|
|
digest.phases[p].patterns = [...(digest.phases[p].patterns as Set<string>)];
|
|
});
|
|
digest.tech_stack = [...(digest.tech_stack as Set<string>)];
|
|
|
|
output(digest, raw, undefined);
|
|
} catch (e) {
|
|
error('Failed to generate history digest: ' + (e as Error).message);
|
|
}
|
|
}
|
|
|
|
function cmdResolveModel(cwd: string, agentType: string | undefined, raw: boolean): void {
|
|
if (!agentType) {
|
|
error('agent-type required');
|
|
}
|
|
|
|
const config = loadConfig(cwd);
|
|
const profile = (config['model_profile'] as string) || 'balanced';
|
|
const model = resolveModelInternal(cwd, agentType!);
|
|
const effort = resolveEffortInternal(cwd, agentType!);
|
|
|
|
const agentModels = (MODEL_PROFILES as Record<string, unknown>)[agentType!];
|
|
const result = agentModels
|
|
? { model, profile, effort }
|
|
: { model, profile, effort, unknown_agent: true };
|
|
output(result, raw, model);
|
|
}
|
|
|
|
function cmdResolveGranularity(cwd: string, phaseType: string | undefined, raw: boolean): void {
|
|
if (!phaseType) {
|
|
error('phase-type required');
|
|
}
|
|
const granularity = resolveGranularityInternal(cwd, phaseType);
|
|
const result = (VALID_PHASE_TYPES).has(phaseType!)
|
|
? { granularity, phase_type: phaseType }
|
|
: { granularity, phase_type: phaseType, unknown_phase_type: true };
|
|
output(result, raw, granularity);
|
|
}
|
|
|
|
/**
|
|
* #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>
|
|
*/
|
|
function cmdResolveExecution(cwd: string, agentType: string | undefined, raw: boolean, opts?: { effortOverride?: string; fastModeOverride?: boolean; attempt?: number }): void {
|
|
if (!agentType) {
|
|
error('agent-type required');
|
|
}
|
|
|
|
opts = opts || {};
|
|
const config = loadConfig(cwd);
|
|
const profile = (config['model_profile'] as string) || 'balanced';
|
|
const model = resolveModelInternal(cwd, agentType!);
|
|
|
|
const effortOpts: Record<string, unknown> = {};
|
|
if (typeof opts.effortOverride === 'string') effortOpts['override'] = opts.effortOverride;
|
|
|
|
const fastModeOpts: Record<string, unknown> = {};
|
|
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'] as string) || 'claude';
|
|
const rendered = renderEffortForRuntime(runtime, effort);
|
|
|
|
const fastModeSupported = RUNTIMES_WITH_FAST_MODE.has(runtime);
|
|
|
|
const agentModels = (MODEL_PROFILES as Record<string, unknown>)[agentType!];
|
|
const result: Record<string, unknown> = {
|
|
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);
|
|
}
|
|
|
|
/**
|
|
* #488 — Replace or inject the `effort:` value in YAML frontmatter.
|
|
* Unlike injectEffortFrontmatter (install.js), this overwrites an existing value.
|
|
*/
|
|
function setEffortFrontmatter(content: string, effortValue: string): string {
|
|
const eol = /^---\r\n/.test(content) ? '\r\n' : '\n';
|
|
const fmRe = /^---\r?\n([\s\S]*?)^---\r?$/m;
|
|
const match = fmRe.exec(content);
|
|
if (!match) return content;
|
|
const fmBody = match[1];
|
|
if (/^effort:/m.test(fmBody)) {
|
|
return content.replace(/^(effort:)[ \t]*.*$/m, `$1 ${effortValue}`);
|
|
}
|
|
const openLen = 3 + eol.length;
|
|
const closingStart = match.index + openLen + fmBody.length;
|
|
return content.slice(0, closingStart) + `effort: ${effortValue}${eol}` + content.slice(closingStart);
|
|
}
|
|
|
|
/**
|
|
* #488 — Re-sync effort: frontmatter in all installed gsd-*.md agent files to
|
|
* match the current effort config, without requiring a full reinstall.
|
|
*
|
|
* Uses install-time resolution (readGsdEffectiveEffortConfig + resolveInstallTimeEffort
|
|
* from bin/install.js) rather than the runtime resolver (resolveEffortInternal), because
|
|
* the sync must mirror what install actually wrote: home defaults merged with project config.
|
|
* The runtime resolver (loadConfig) does not merge ~/.gsd/defaults.json when a project
|
|
* .planning/config.json exists, so it would silently ignore home-level effort changes.
|
|
*/
|
|
function cmdEffortSync(cwd: string, raw: boolean, opts?: { dryRun?: boolean; configDir?: string; runtime?: string }): void {
|
|
opts = opts || {};
|
|
const dryRun = opts.dryRun !== false;
|
|
|
|
const config = loadConfig(cwd);
|
|
const runtime = opts.runtime || (config['runtime'] as string) || 'claude';
|
|
|
|
if (runtime !== 'claude') {
|
|
output({ synced: 0, skipped: 0, changes: [], dry_run: dryRun, reason: `runtime '${runtime}' does not use effort: frontmatter` }, raw, '');
|
|
return;
|
|
}
|
|
|
|
// eslint-disable-next-line @typescript-eslint/no-require-imports, @typescript-eslint/unbound-method
|
|
const { getGlobalConfigDir } = require('./runtime-homes.cjs') as { getGlobalConfigDir(runtime: string): string };
|
|
// Use install-time resolvers: they merge ~/.gsd/defaults.json with project config,
|
|
// matching the exact logic used when agents were originally installed.
|
|
// eslint-disable-next-line @typescript-eslint/no-require-imports, @typescript-eslint/unbound-method
|
|
const { readGsdEffectiveEffortConfig, resolveInstallTimeEffort } = require('../../../bin/install.js') as {
|
|
readGsdEffectiveEffortConfig(cwd: string): Record<string, unknown>;
|
|
resolveInstallTimeEffort(cfg: Record<string, unknown>, agentName: string): string;
|
|
};
|
|
const effortCfg = readGsdEffectiveEffortConfig(cwd);
|
|
|
|
const agentsDir = path.join(opts.configDir || getGlobalConfigDir(runtime), 'agents');
|
|
|
|
if (!fs.existsSync(agentsDir)) {
|
|
output({ synced: 0, skipped: 0, changes: [], dry_run: dryRun, agents_dir: agentsDir, reason: 'agents directory not found' }, raw, '');
|
|
return;
|
|
}
|
|
|
|
// Skip symlinks — only write regular files to avoid clobbering symlink targets.
|
|
const files = fs.readdirSync(agentsDir).filter(f => {
|
|
if (!f.startsWith('gsd-') || !f.endsWith('.md')) return false;
|
|
try { return fs.lstatSync(path.join(agentsDir, f)).isFile(); } catch { return false; }
|
|
});
|
|
const changes: EffortSyncChange[] = [];
|
|
let synced = 0;
|
|
let skipped = 0;
|
|
|
|
for (const file of files) {
|
|
const agentName = file.replace(/\.md$/, '');
|
|
const filePath = path.join(agentsDir, file);
|
|
const content = fs.readFileSync(filePath, 'utf8');
|
|
|
|
// Resolve using install-time logic: home defaults merged with project config.
|
|
const universalEffort = resolveInstallTimeEffort(effortCfg, agentName);
|
|
const rendered = renderEffortForRuntime(runtime, universalEffort);
|
|
const newEffortValue = rendered.value;
|
|
|
|
const fmMatch = /^---\r?\n([\s\S]*?)^---\r?$/m.exec(content);
|
|
if (!fmMatch) { skipped++; continue; }
|
|
|
|
const effortMatch = /^effort:[ \t]*(.+?)[ \t]*$/m.exec(fmMatch[1]);
|
|
const currentEffort = effortMatch ? effortMatch[1] : null;
|
|
|
|
if (currentEffort === newEffortValue) { skipped++; continue; }
|
|
|
|
changes.push({ agent: agentName, from: currentEffort, to: newEffortValue });
|
|
synced++;
|
|
|
|
if (!dryRun) {
|
|
fs.writeFileSync(filePath, setEffortFrontmatter(content, newEffortValue));
|
|
}
|
|
}
|
|
|
|
output({ synced, skipped, changes, dry_run: dryRun, agents_dir: agentsDir }, raw, synced > 0 ? 'changed' : 'ok');
|
|
}
|
|
|
|
function cmdCommit(cwd: string, message: string | undefined, files: string[] | undefined, raw: boolean, amend: boolean, noVerify: boolean): void {
|
|
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
|
|
let sanitizedMessage = message;
|
|
if (sanitizedMessage) {
|
|
// eslint-disable-next-line @typescript-eslint/no-require-imports, @typescript-eslint/unbound-method
|
|
const { sanitizeForPrompt } = require('./security.cjs') as { sanitizeForPrompt(text: unknown): string };
|
|
sanitizedMessage = sanitizeForPrompt(sanitizedMessage);
|
|
}
|
|
|
|
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.
|
|
const branchingStrategy = config['branching_strategy'] as string | undefined;
|
|
if (branchingStrategy && branchingStrategy !== 'none') {
|
|
let branchName: string | null = null;
|
|
if (branchingStrategy === '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) as Record<string, unknown> | null;
|
|
if (phaseInfo) {
|
|
branchName = (config['phase_branch_template'] as string)
|
|
.replace('{phase}', phaseInfo['phase_number'] as string)
|
|
.replace('{slug}', (phaseInfo['phase_slug'] as string) || 'phase');
|
|
}
|
|
}
|
|
} else if (branchingStrategy === 'milestone') {
|
|
const milestone = getMilestoneInfo(cwd);
|
|
if (milestone && milestone.version) {
|
|
branchName = (config['milestone_branch_template'] as string)
|
|
.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', sanitizedMessage as string];
|
|
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 files - changed file paths (relative to project root)
|
|
* @param subRepos - sub-repo path prefixes from config.sub_repos
|
|
*/
|
|
function groupFilesBySubrepo(files: string[], subRepos: string[]): GroupFilesBySubrepoResult {
|
|
const reposByFirstSeg = new Map<string, string[]>();
|
|
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: Record<string, string[]> = {};
|
|
const unmatched: string[] = [];
|
|
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: string, message: string | undefined, files: string[] | undefined, raw: boolean): void {
|
|
if (!message) {
|
|
error('commit message required');
|
|
}
|
|
|
|
const config = loadConfig(cwd);
|
|
const subRepos = config['sub_repos'] as string[] | undefined;
|
|
|
|
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 as string[], subRepos as string[]);
|
|
|
|
if (unmatched.length > 0) {
|
|
process.stderr.write(`Warning: ${unmatched.length} file(s) did not match any sub-repo prefix: ${unmatched.join(', ')}\n`);
|
|
}
|
|
|
|
const repos: Record<string, CommitToSubrepoRepoResult> = {};
|
|
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 as string], { 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: string, summaryPath: string | undefined, fields: string[] | undefined, raw: boolean): void {
|
|
if (!summaryPath) {
|
|
error('summary-path required for summary-extract');
|
|
}
|
|
|
|
const fullPath = path.join(cwd, summaryPath as string);
|
|
|
|
if (!fs.existsSync(fullPath)) {
|
|
output({ error: 'File not found', path: summaryPath }, raw, undefined);
|
|
return;
|
|
}
|
|
|
|
const content = fs.readFileSync(fullPath, 'utf-8');
|
|
const fm = extractFrontmatter(content) as Record<string, unknown>;
|
|
|
|
// Parse key-decisions into structured format
|
|
const parseDecisions = (decisionsList: unknown) => {
|
|
if (!decisionsList || !Array.isArray(decisionsList)) return [];
|
|
return (decisionsList as string[]).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 };
|
|
});
|
|
};
|
|
|
|
const techStack = fm['tech-stack'] as { added?: string[] } | undefined;
|
|
|
|
// Build full result
|
|
const fullResult: Record<string, unknown> = {
|
|
path: summaryPath,
|
|
one_liner: fm['one-liner'] || extractOneLinerFromBody(content) || null,
|
|
key_files: fm['key-files'] || [],
|
|
tech_added: (techStack && techStack['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: Record<string, unknown> = { path: summaryPath };
|
|
for (const field of fields) {
|
|
if (fullResult[field] !== undefined) {
|
|
filtered[field] = fullResult[field];
|
|
}
|
|
}
|
|
output(filtered, raw, undefined);
|
|
return;
|
|
}
|
|
|
|
output(fullResult, raw, undefined);
|
|
}
|
|
|
|
function _wsSleep(ms: number): Promise<void> {
|
|
return new Promise(resolve => setTimeout(resolve, ms));
|
|
}
|
|
|
|
function _wsParseRetryAfter(header: string | null | undefined): number | null {
|
|
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: number): number {
|
|
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: string | undefined, options: WebsearchOptions, raw: boolean): Promise<void> {
|
|
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'] as string, 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: Response;
|
|
try {
|
|
response = await fetch(
|
|
// eslint-disable-next-line @typescript-eslint/restrict-template-expressions
|
|
`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() as { web?: { results?: Array<{ title: string; url: string; description: string; age?: string }> } };
|
|
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: number;
|
|
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 as Error).message, attempts: attempt }, raw, '');
|
|
return;
|
|
}
|
|
await _wsSleep(_wsRetryDelayMs(attempt - 1));
|
|
}
|
|
}
|
|
}
|
|
|
|
function cmdProgressRender(cwd: string, format: string | undefined, raw: boolean): void {
|
|
const phasesDir = planningPaths(cwd).phases;
|
|
const milestone = getMilestoneInfo(cwd);
|
|
|
|
const phases: PhaseProgress[] = [];
|
|
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 = '█'.repeat(filled) + '░'.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 = '█'.repeat(filled) + '░'.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, undefined);
|
|
}
|
|
}
|
|
|
|
/**
|
|
* 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: string, phase: string | undefined, raw: boolean): void {
|
|
if (!phase) { error('phase required for todo match-phase'); }
|
|
|
|
const pendingDir = path.join(planningDir(cwd), 'todos', 'pending');
|
|
const todos: Array<{
|
|
file: string;
|
|
title: string;
|
|
area: string;
|
|
files: string[];
|
|
body: string;
|
|
}> = [];
|
|
|
|
// 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 { /* intentionally empty */ }
|
|
|
|
if (todos.length === 0) {
|
|
output({ phase, matches: [], todo_count: 0 }, raw, undefined);
|
|
return;
|
|
}
|
|
|
|
// Load phase goal/name from ROADMAP
|
|
const phaseInfo = getRoadmapPhaseInternal(cwd, phase) as Record<string, unknown> | null;
|
|
const phaseName = phaseInfo ? ((phaseInfo['phase_name'] as string) || '') : '';
|
|
const phaseGoal = phaseInfo ? ((phaseInfo['goal'] as string) || '') : '';
|
|
const phaseSection = phaseInfo ? ((phaseInfo['section'] as string) || '') : '';
|
|
|
|
// 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) as Record<string, unknown> | null;
|
|
const phasePlans: string[] = [];
|
|
if (phaseInfoDisk && phaseInfoDisk['found']) {
|
|
try {
|
|
const phaseDir = path.join(cwd, phaseInfoDisk['directory'] as string);
|
|
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 { /* intentionally empty */ }
|
|
}
|
|
|
|
// Score each todo for relevance
|
|
const matches: Array<{
|
|
file: string;
|
|
title: string;
|
|
area: string;
|
|
score: number;
|
|
reasons: string[];
|
|
}> = [];
|
|
for (const todo of todos) {
|
|
let score = 0;
|
|
const reasons: string[] = [];
|
|
|
|
// 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, undefined);
|
|
}
|
|
|
|
function cmdTodoComplete(cwd: string, filename: string | undefined, raw: boolean): void {
|
|
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 as string);
|
|
|
|
if (!fs.existsSync(sourcePath)) {
|
|
error(`Todo not found: ${filename as string}`);
|
|
}
|
|
|
|
// 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 as string), content);
|
|
fs.unlinkSync(sourcePath);
|
|
|
|
output({ completed: true, file: filename, date: today }, raw, 'completed');
|
|
}
|
|
|
|
function cmdScaffold(cwd: string, type: string, options: ScaffoldOptions, raw: boolean): void {
|
|
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) as Record<string, unknown> | null : null;
|
|
const phaseDir = phaseInfo ? path.join(cwd, phaseInfo['directory'] as string) : null;
|
|
|
|
if (phase && !phaseDir && type !== 'phase-dir') {
|
|
error(`Phase ${phase} directory not found`);
|
|
}
|
|
|
|
let filePath: string, content: string;
|
|
|
|
switch (type) {
|
|
case 'context': {
|
|
filePath = path.join(phaseDir as string, `${padded}-CONTEXT.md`);
|
|
content = `---\nphase: "${padded}"\nname: "${name || (phaseInfo?.['phase_name'] as string | undefined) || 'Unnamed'}"\ncreated: ${today}\n---\n\n# Phase ${phase}: ${name || (phaseInfo?.['phase_name'] as string | undefined) || 'Unnamed'} — Context\n\n## Decisions\n\n_Decisions will be captured during ${String(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 as string, `${padded}-UAT.md`);
|
|
content = `---\nphase: "${padded}"\nname: "${name || (phaseInfo?.['phase_name'] as string | undefined) || 'Unnamed'}"\ncreated: ${today}\nstatus: pending\n---\n\n# Phase ${phase}: ${name || (phaseInfo?.['phase_name'] as string | undefined) || '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 as string, `${padded}-VERIFICATION.md`);
|
|
content = `---\nphase: "${padded}"\nname: "${name || (phaseInfo?.['phase_name'] as string | undefined) || 'Unnamed'}"\ncreated: ${today}\nstatus: pending\n---\n\n# Phase ${phase}: ${name || (phaseInfo?.['phase_name'] as string | undefined) || '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'] as string) || '';
|
|
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`);
|
|
// unreachable — error() calls process.exit
|
|
return;
|
|
}
|
|
|
|
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: string, format: string | undefined, raw: boolean): void {
|
|
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) as (dir: string) => boolean;
|
|
|
|
// Phase & plan stats (reuse progress pattern)
|
|
const phasesByNumber = new Map<string, {
|
|
number: string;
|
|
name: string;
|
|
plans: number;
|
|
summaries: number;
|
|
status: string;
|
|
}>();
|
|
let totalPlans = 0;
|
|
let totalSummaries = 0;
|
|
|
|
try {
|
|
const roadmapRaw = platformReadSync(roadmapPath);
|
|
if (roadmapRaw === null) throw new Error('roadmap missing');
|
|
const roadmapContent = extractCurrentMilestone(roadmapRaw, cwd);
|
|
// Matches both plain numeric (Phase 1:) and milestone-prefixed (Phase 2-01:) headings.
|
|
// Also tolerates optional [bracket-token] scope prefix on phase headings.
|
|
const headingPattern = /#{2,4}\s*(?:\[[^\]]+\]\s*)?Phase\s+([\w][\w.-]*(?:-[\w.-]+)*)\s*:\s*([^\n]+)/gi;
|
|
let match: RegExpExecArray | null;
|
|
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) {
|
|
// Use extractPhaseToken to correctly parse M-NN-style and code-prefixed dir names.
|
|
const phaseToken = extractPhaseToken(dir) as string | null;
|
|
const phaseNum = phaseToken || dir;
|
|
// phaseName is everything after the token (strip leading '-')
|
|
const afterToken = dir.slice(phaseToken ? phaseToken.length : 0).replace(/^-/, '');
|
|
const phaseName = afterToken ? afterToken.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: string | null = 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: string | null = 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 = '█'.repeat(filled) + '░'.repeat(barWidth - filled);
|
|
let out = `# ${milestone.version} ${milestone.name} — 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, undefined);
|
|
}
|
|
}
|
|
|
|
/**
|
|
* 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: string, raw: boolean): void {
|
|
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');
|
|
}
|
|
|
|
export = {
|
|
groupFilesBySubrepo,
|
|
determinePhaseStatus,
|
|
cmdGenerateSlug,
|
|
cmdCurrentTimestamp,
|
|
cmdListTodos,
|
|
cmdVerifyPathExists,
|
|
cmdHistoryDigest,
|
|
cmdResolveModel,
|
|
cmdResolveGranularity,
|
|
cmdResolveExecution,
|
|
cmdEffortSync,
|
|
cmdCommit,
|
|
cmdCommitToSubrepo,
|
|
cmdSummaryExtract,
|
|
cmdWebsearch,
|
|
cmdProgressRender,
|
|
cmdTodoComplete,
|
|
cmdTodoMatchPhase,
|
|
cmdScaffold,
|
|
cmdStats,
|
|
cmdCheckCommit,
|
|
_wsParseRetryAfter,
|
|
};
|