* 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>
612 lines
23 KiB
TypeScript
612 lines
23 KiB
TypeScript
/**
|
|
* Roadmap Upgrade — Migration tool for converting legacy 'Phase N' phase IDs
|
|
* to milestone-prefixed 'Phase M-NN' form.
|
|
*
|
|
* ADR-457 build-at-publish: the hand-written bin/lib/roadmap-upgrade.cjs collapsed
|
|
* to a TypeScript source of truth. Behaviour is preserved byte-for-behaviour
|
|
* from the prior hand-written .cjs; only types are added.
|
|
*/
|
|
|
|
import fs from 'node:fs';
|
|
import path from 'node:path';
|
|
import { execSync } from 'node:child_process';
|
|
// eslint-disable-next-line @typescript-eslint/no-require-imports
|
|
import planningWorkspace = require('./planning-workspace.cjs');
|
|
const { planningDir } = planningWorkspace;
|
|
|
|
// ─── Regex helpers ────────────────────────────────────────────────────────────
|
|
|
|
// Matches legacy phase headings: ### Phase N: Name (also decimal: Phase 2.1:)
|
|
// Captures: (hashes)(spaces)(phase-number)(rest-of-line)
|
|
const LEGACY_PHASE_HEADING_RE = /^(#{2,4})\s*(?:\[[^\]]+\]\s*)?Phase\s+(\d+[A-Z]?(?:\.\d+)*)\s*:(.*)/i;
|
|
|
|
// Matches already-migrated phase headings: ### Phase M-NN: Name
|
|
const MIGRATED_PHASE_HEADING_RE = /^#{2,4}\s*(?:\[[^\]]+\]\s*)?Phase\s+\d+-\d{2}\s*:/i;
|
|
|
|
// Matches milestone section headings: ## v1.0, ## Roadmap v2.0, ## ✅ v1.0, ## [GSD] v1.0, etc.
|
|
// The optional bracket-token prefix (e.g., [GSD]) must be tested before the emoji group.
|
|
const MILESTONE_HEADING_RE = /^##\s+(?:\[[^\]]+\]\s+|Roadmap\s+|[✅🚧]\s*)?v(\d+)\.(\d+)(?:\s|:)/iu;
|
|
|
|
// Matches checklist phase references: - [ ] **Phase N:** or - [x] **Phase N:** (also decimal)
|
|
const CHECKLIST_PHASE_RE = /^(\s*-\s*\[[ x]\]\s*\*{0,2})Phase\s+(\d+[A-Z]?(?:\.\d+)*)\s*:/gi;
|
|
|
|
// ─── Types ────────────────────────────────────────────────────────────────────
|
|
|
|
interface ParsedPhaseEntry {
|
|
lineIndex: number;
|
|
headingLine: string;
|
|
alreadyMigrated: boolean;
|
|
milestoneInt?: number | null;
|
|
legacyPhaseNum?: string;
|
|
phaseName?: string;
|
|
hashes?: string;
|
|
}
|
|
|
|
interface AssignedMapping {
|
|
newId: string;
|
|
milestoneInt: number;
|
|
subIndex: number;
|
|
legacyPhaseNum: string;
|
|
}
|
|
|
|
interface PhaseRename {
|
|
oldId: string;
|
|
newId: string;
|
|
oldDir: string;
|
|
newDir: string;
|
|
}
|
|
|
|
interface RoadmapEdit {
|
|
lineIndex: number;
|
|
from: string;
|
|
to: string;
|
|
}
|
|
|
|
interface CrossRefEdit {
|
|
file: string;
|
|
from: string;
|
|
to: string;
|
|
}
|
|
|
|
interface MigrationPlan {
|
|
alreadyMigrated: boolean;
|
|
phases: PhaseRename[];
|
|
roadmapEdits: RoadmapEdit[];
|
|
crossRefEdits: CrossRefEdit[];
|
|
}
|
|
|
|
interface ApplyMigrationResult {
|
|
applied?: boolean;
|
|
alreadyMigrated?: boolean;
|
|
dryRun?: boolean;
|
|
renamedDirs?: string[];
|
|
editedFiles?: string[];
|
|
}
|
|
|
|
// ─── Pure computation helpers ─────────────────────────────────────────────────
|
|
|
|
/**
|
|
* Parse the ROADMAP.md content and build a list of phase entries with their
|
|
* enclosing milestone major version.
|
|
*
|
|
* Returns an array of:
|
|
* { lineIndex, headingLine, milestoneInt, legacyPhaseNum, phaseName }
|
|
*/
|
|
function parseRoadmapPhases(lines: string[]): ParsedPhaseEntry[] {
|
|
const results: ParsedPhaseEntry[] = [];
|
|
let currentMilestoneInt: number | null = null;
|
|
|
|
for (let i = 0; i < lines.length; i++) {
|
|
const line = lines[i];
|
|
|
|
const milestoneMatch = line.match(MILESTONE_HEADING_RE);
|
|
if (milestoneMatch) {
|
|
currentMilestoneInt = parseInt(milestoneMatch[1], 10);
|
|
continue;
|
|
}
|
|
|
|
if (MIGRATED_PHASE_HEADING_RE.test(line)) {
|
|
// Already-migrated heading found — caller will detect this
|
|
results.push({ lineIndex: i, headingLine: line, alreadyMigrated: true });
|
|
continue;
|
|
}
|
|
|
|
const phaseMatch = line.match(LEGACY_PHASE_HEADING_RE);
|
|
if (phaseMatch) {
|
|
results.push({
|
|
lineIndex: i,
|
|
headingLine: line,
|
|
milestoneInt: currentMilestoneInt,
|
|
legacyPhaseNum: phaseMatch[2],
|
|
phaseName: phaseMatch[3].trim(),
|
|
hashes: phaseMatch[1],
|
|
alreadyMigrated: false,
|
|
});
|
|
}
|
|
}
|
|
|
|
return results;
|
|
}
|
|
|
|
/**
|
|
* Assign sub-indices within each milestone, building a per-entry mapping.
|
|
*
|
|
* Input: array from parseRoadmapPhases (non-migrated entries only).
|
|
* Returns: Map<lineIndex, { newId, milestoneInt, subIndex }>
|
|
*
|
|
* Keyed by `lineIndex` (the unique position of the heading line in ROADMAP.md)
|
|
* so that identical legacy phase numbers in different milestones (e.g., two
|
|
* `Phase 1` headings in v1.0 and v2.0) each get their own correct M-NN ID
|
|
* instead of the later milestone's mapping overwriting the earlier one.
|
|
*
|
|
* Sub-indices are 1-based and sequential within each milestone.
|
|
*/
|
|
function assignSubIndices(phaseEntries: ParsedPhaseEntry[]): Map<number, AssignedMapping> {
|
|
const milestoneCounters = new Map<number, number>(); // milestoneInt → counter
|
|
const mapping = new Map<number, AssignedMapping>(); // lineIndex → { newId, milestoneInt, subIndex }
|
|
|
|
for (const entry of phaseEntries) {
|
|
if (entry.alreadyMigrated) continue;
|
|
const m = entry.milestoneInt;
|
|
if (m === null || m === undefined) continue;
|
|
|
|
const counter = (milestoneCounters.get(m) || 0) + 1;
|
|
milestoneCounters.set(m, counter);
|
|
|
|
const subIndex = String(counter).padStart(2, '0');
|
|
const newId = `${m}-${subIndex}`;
|
|
|
|
mapping.set(entry.lineIndex, { newId, milestoneInt: m, subIndex: counter, legacyPhaseNum: entry.legacyPhaseNum! });
|
|
}
|
|
|
|
return mapping;
|
|
}
|
|
|
|
/**
|
|
* Read a phase directory name and return its numeric token (stripping project_code prefix).
|
|
* e.g. "GSD-01-setup" → "01", "01-setup" → "01", "02-implement" → "02", "02.1-hotfix" → "02.1"
|
|
*/
|
|
function extractPhaseNumFromDir(dirName: string): string | null {
|
|
// Strip optional project_code prefix: "GSD-01-setup" → "01-setup"
|
|
const stripped = dirName.replace(/^[A-Z]{1,6}-(?=\d)/i, '');
|
|
// Matches: digits + optional letter + optional decimal suffix, followed by '-' or end.
|
|
// e.g. "02.1-hotfix" → "02.1", "01-setup" → "01"
|
|
const m = stripped.match(/^(\d+[A-Z]?(?:\.\d+)*)(?:-|$)/i);
|
|
return m ? m[1] : null;
|
|
}
|
|
|
|
|
|
/**
|
|
* Build the new directory name from old name and new phase ID.
|
|
* old: "01-setup" newId: "1-02" projectCode: "GSD" → "GSD-01-02-setup"
|
|
* old: "01-setup" newId: "1-02" projectCode: null → "01-02-setup"
|
|
* old: "GSD-01-setup" newId: "1-02" projectCode: "GSD" → "GSD-01-02-setup"
|
|
*/
|
|
function buildNewDirName(oldDirName: string, newId: string, projectCode: string | null): string {
|
|
// Strip existing project_code prefix
|
|
const stripped = oldDirName.replace(/^[A-Z]{1,6}-(?=\d)/i, '');
|
|
|
|
// Extract slug: everything after "NN-" (the old phase num, including decimal like 02.1)
|
|
const slugMatch = stripped.match(/^\d+[A-Z]?(?:\.\d+)*-(.*)/i);
|
|
const slug = slugMatch ? slugMatch[1] : stripped;
|
|
|
|
// Build M-NN prefix (zero-pad both parts)
|
|
const [milestoneStr, subStr] = newId.split('-');
|
|
const milestoneInt = parseInt(milestoneStr, 10);
|
|
const paddedMilestone = String(milestoneInt).padStart(2, '0');
|
|
const newBase = slug ? `${paddedMilestone}-${subStr}-${slug}` : `${paddedMilestone}-${subStr}`;
|
|
|
|
return projectCode ? `${projectCode}-${newBase}` : newBase;
|
|
}
|
|
|
|
/**
|
|
* Read project_code from config.json if present.
|
|
*/
|
|
function readProjectCode(configPath: string): string | null {
|
|
try {
|
|
const raw = fs.readFileSync(configPath, 'utf8');
|
|
const parsed = JSON.parse(raw) as Record<string, unknown>;
|
|
return typeof parsed['project_code'] === 'string' ? parsed['project_code'] : null;
|
|
} catch {
|
|
return null;
|
|
}
|
|
}
|
|
|
|
// ─── computeMigrationPlan ─────────────────────────────────────────────────────
|
|
|
|
/**
|
|
* Compute a migration plan without touching the filesystem.
|
|
*/
|
|
function computeMigrationPlan(cwd: string, options: Record<string, unknown> = {}): MigrationPlan {
|
|
void options;
|
|
const pDir = planningDir(cwd);
|
|
const roadmapPath = path.join(pDir, 'ROADMAP.md');
|
|
const configPath = path.join(pDir, 'config.json');
|
|
const phasesDir = path.join(pDir, 'phases');
|
|
|
|
// ── Check config for existing convention ─────────────────────────────────
|
|
let configData: Record<string, unknown> = {};
|
|
try {
|
|
configData = JSON.parse(fs.readFileSync(configPath, 'utf8')) as Record<string, unknown>;
|
|
} catch { /* config may not exist */ }
|
|
|
|
if (configData['phase_id_convention'] === 'milestone-prefixed') {
|
|
return { alreadyMigrated: true, phases: [], roadmapEdits: [], crossRefEdits: [] };
|
|
}
|
|
|
|
const projectCode = typeof configData['project_code'] === 'string' ? configData['project_code'] : null;
|
|
|
|
// ── Read ROADMAP.md ───────────────────────────────────────────────────────
|
|
let roadmapContent = '';
|
|
try {
|
|
roadmapContent = fs.readFileSync(roadmapPath, 'utf8');
|
|
} catch {
|
|
throw new Error(`ROADMAP.md not found at ${roadmapPath}`);
|
|
}
|
|
|
|
const lines = roadmapContent.split('\n');
|
|
const parsedPhases = parseRoadmapPhases(lines);
|
|
|
|
// Check for any already-migrated headings
|
|
const hasAnyMigrated = parsedPhases.some(e => e.alreadyMigrated);
|
|
if (hasAnyMigrated) {
|
|
return { alreadyMigrated: true, phases: [], roadmapEdits: [], crossRefEdits: [] };
|
|
}
|
|
|
|
const legacyPhases = parsedPhases.filter(e => !e.alreadyMigrated);
|
|
const idMapping = assignSubIndices(legacyPhases);
|
|
|
|
// Secondary lookup: (milestoneInt, normalizedLegacyNum) → newId
|
|
// Used for directory renames and checklist rewrites where line position is unknown.
|
|
// For simplicity, each milestone gets its own Map from legacy num → newId.
|
|
const milestoneIdMap = new Map<number, Map<string, string>>(); // milestoneInt → Map<normalizedLegacyNum, newId>
|
|
for (const [, entry] of idMapping) {
|
|
if (!milestoneIdMap.has(entry.milestoneInt)) {
|
|
milestoneIdMap.set(entry.milestoneInt, new Map<string, string>());
|
|
}
|
|
const mMap = milestoneIdMap.get(entry.milestoneInt)!;
|
|
const legacyNum = entry.legacyPhaseNum;
|
|
// Register integer forms (covers plain numeric and letter-suffix IDs)
|
|
const intPart = parseInt(legacyNum, 10);
|
|
const paddedLegacy = String(intPart).padStart(2, '0');
|
|
const unpaddedLegacy = String(intPart);
|
|
mMap.set(paddedLegacy, entry.newId);
|
|
mMap.set(unpaddedLegacy, entry.newId);
|
|
// Also register the original form and padded-integer+decimal form
|
|
// so decimal IDs like "2.1" / "02.1" round-trip correctly.
|
|
mMap.set(legacyNum, entry.newId);
|
|
const dotIdx = legacyNum.indexOf('.');
|
|
if (dotIdx !== -1) {
|
|
const decimalSuffix = legacyNum.slice(dotIdx); // e.g. ".1"
|
|
mMap.set(paddedLegacy + decimalSuffix, entry.newId);
|
|
mMap.set(unpaddedLegacy + decimalSuffix, entry.newId);
|
|
}
|
|
}
|
|
|
|
// ── Read existing phase directories ───────────────────────────────────────
|
|
let existingDirs: string[] = [];
|
|
try {
|
|
existingDirs = fs.readdirSync(phasesDir).filter(d => {
|
|
try {
|
|
return fs.statSync(path.join(phasesDir, d)).isDirectory();
|
|
} catch { return false; }
|
|
});
|
|
} catch { /* phases dir may not exist */ }
|
|
|
|
// ── Build phase rename pairs ───────────────────────────────────────────────
|
|
// Flat ordered list of (legacyPhaseNum, newId) in ROADMAP order, for dir matching.
|
|
const orderedMappings = [...idMapping.values()].map(e => ({
|
|
legacyPhaseNum: e.legacyPhaseNum,
|
|
newId: e.newId,
|
|
milestoneInt: e.milestoneInt,
|
|
_used: false,
|
|
}));
|
|
|
|
// Note: if the same legacy phase number appears in multiple milestones (the exact legacy
|
|
// ambiguity this tool is designed to resolve), directories are matched in ROADMAP document
|
|
// order — the first ROADMAP occurrence of a given number claims the first matching disk dir.
|
|
// This is the only unambiguous assignment strategy for flat dirs that carry no milestone
|
|
// context. The dry-run output shows the complete rename plan so users can review before
|
|
// applying with --apply.
|
|
|
|
const phases: PhaseRename[] = [];
|
|
for (const dirName of existingDirs) {
|
|
const phaseNum = extractPhaseNumFromDir(dirName);
|
|
if (!phaseNum) continue;
|
|
|
|
const intPart = parseInt(phaseNum, 10);
|
|
const paddedPhaseNum = String(intPart).padStart(2, '0');
|
|
const unpaddedPhaseNum = String(intPart);
|
|
// For decimal IDs like "02.1", also try "2.1"
|
|
const dotIdx = phaseNum.indexOf('.');
|
|
const decimalUnpadded = dotIdx !== -1 ? unpaddedPhaseNum + phaseNum.slice(dotIdx) : null;
|
|
|
|
// Find the first unused mapping whose legacy number matches (exact, padded, unpadded, or decimal)
|
|
const found = orderedMappings.find(m => !m._used && (
|
|
m.legacyPhaseNum === phaseNum ||
|
|
m.legacyPhaseNum === paddedPhaseNum ||
|
|
m.legacyPhaseNum === unpaddedPhaseNum ||
|
|
(decimalUnpadded && m.legacyPhaseNum === decimalUnpadded)
|
|
));
|
|
if (!found) continue;
|
|
found._used = true;
|
|
|
|
const newDirName = buildNewDirName(dirName, found.newId, projectCode);
|
|
if (newDirName !== dirName) {
|
|
phases.push({
|
|
oldId: phaseNum,
|
|
newId: found.newId,
|
|
oldDir: dirName,
|
|
newDir: newDirName,
|
|
});
|
|
}
|
|
}
|
|
|
|
// ── Build ROADMAP.md line edits ────────────────────────────────────────────
|
|
const roadmapEdits: RoadmapEdit[] = [];
|
|
|
|
for (const entry of legacyPhases) {
|
|
// Use lineIndex as the canonical key (not legacyPhaseNum, which may collide across milestones)
|
|
const mapping = idMapping.get(entry.lineIndex);
|
|
if (!mapping) continue;
|
|
|
|
// Rewrite heading line: "### Phase N: Name" → "### Phase M-NN: Name"
|
|
const oldLine = lines[entry.lineIndex];
|
|
const newLine = oldLine.replace(
|
|
/^(#{2,4}\s*(?:\[[^\]]+\]\s*)?Phase\s+)\d+[A-Z]?(?:\.\d+)*(\s*:)/i,
|
|
`$1${mapping.newId}$2`
|
|
);
|
|
if (newLine !== oldLine) {
|
|
roadmapEdits.push({ lineIndex: entry.lineIndex, from: oldLine, to: newLine });
|
|
}
|
|
}
|
|
|
|
// Rewrite checklist lines in ROADMAP.md — use milestone context to resolve collisions.
|
|
let currentChecklistMilestone: number | null = null;
|
|
for (let i = 0; i < lines.length; i++) {
|
|
const line = lines[i];
|
|
|
|
// Track enclosing milestone section for context-aware lookup
|
|
const milestoneHeadingMatch = line.match(MILESTONE_HEADING_RE);
|
|
if (milestoneHeadingMatch) {
|
|
currentChecklistMilestone = parseInt(milestoneHeadingMatch[1], 10);
|
|
}
|
|
|
|
// Already in roadmapEdits? skip
|
|
if (roadmapEdits.some(e => e.lineIndex === i)) continue;
|
|
|
|
// Match checklist items: "- [ ] **Phase N:**" or "- [x] Phase N:" (also decimal)
|
|
const checklistMatch = line.match(/^(\s*-\s*\[[ x]\]\s*\*{0,2}Phase\s+)(\d+[A-Z]?(?:\.\d+)*)(\s*[:\s*])/i);
|
|
if (checklistMatch) {
|
|
const legacyNum = checklistMatch[2];
|
|
const cIntPart = parseInt(legacyNum, 10);
|
|
const paddedLegacy = String(cIntPart).padStart(2, '0');
|
|
const unpaddedLegacy = String(cIntPart);
|
|
const cDotIdx = legacyNum.indexOf('.');
|
|
const paddedLegacyDecimal = cDotIdx !== -1 ? paddedLegacy + legacyNum.slice(cDotIdx) : null;
|
|
|
|
// Prefer milestone-context lookup (avoids collision across milestones)
|
|
let newId: string | undefined;
|
|
if (currentChecklistMilestone !== null && milestoneIdMap.has(currentChecklistMilestone)) {
|
|
const mMap = milestoneIdMap.get(currentChecklistMilestone)!;
|
|
newId = mMap.get(legacyNum) || mMap.get(paddedLegacy) || mMap.get(unpaddedLegacy);
|
|
if (!newId && paddedLegacyDecimal) newId = mMap.get(paddedLegacyDecimal);
|
|
}
|
|
if (!newId) {
|
|
// Fallback: use ordered flat list (no milestone collision in this roadmap)
|
|
const found = orderedMappings.find(m =>
|
|
m.legacyPhaseNum === legacyNum ||
|
|
m.legacyPhaseNum === paddedLegacy ||
|
|
m.legacyPhaseNum === unpaddedLegacy ||
|
|
(paddedLegacyDecimal && m.legacyPhaseNum === paddedLegacyDecimal)
|
|
);
|
|
if (found) newId = found.newId;
|
|
}
|
|
|
|
if (newId) {
|
|
const newLine = line.replace(
|
|
/^(\s*-\s*\[[ x]\]\s*\*{0,2}Phase\s+)\d+[A-Z]?(?:\.\d+)*(\s*[:\s*])/i,
|
|
`$1${newId}$2`
|
|
);
|
|
if (newLine !== line) {
|
|
roadmapEdits.push({ lineIndex: i, from: line, to: newLine });
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
// ── Build cross-ref edits for STATE.md and PROJECT.md ────────────────────
|
|
const crossRefEdits: CrossRefEdit[] = [];
|
|
const crossRefFiles = ['STATE.md', 'PROJECT.md'];
|
|
|
|
for (const fileName of crossRefFiles) {
|
|
const filePath = path.join(pDir, fileName);
|
|
if (!fs.existsSync(filePath)) continue;
|
|
|
|
const fileContent = fs.readFileSync(filePath, 'utf8');
|
|
|
|
// Iterate using orderedMappings (ROADMAP order) — idMapping is now keyed by lineIndex.
|
|
for (const m of orderedMappings) {
|
|
const legacyNum = m.legacyPhaseNum;
|
|
const xIntPart = parseInt(legacyNum, 10);
|
|
const paddedNum = String(xIntPart).padStart(2, '0');
|
|
const unpaddedNum = String(xIntPart);
|
|
// Decimal suffix (e.g. ".1" from "2.1") — preserve in cross-ref patterns
|
|
const xDotIdx = legacyNum.indexOf('.');
|
|
const decimalSuffix = xDotIdx !== -1 ? legacyNum.slice(xDotIdx) : '';
|
|
|
|
// Rewrite project_code-prefixed references: "GSD-01-" → "GSD-01-02-"
|
|
if (projectCode) {
|
|
const [milestoneStr, subStr] = m.newId.split('-');
|
|
const paddedMilestone = String(parseInt(milestoneStr, 10)).padStart(2, '0');
|
|
const prefixedNew = `${projectCode}-${paddedMilestone}-${subStr}-`;
|
|
// Try both padded and original forms as old prefix
|
|
for (const oldNum of new Set([paddedNum + decimalSuffix, unpaddedNum + decimalSuffix, paddedNum, unpaddedNum])) {
|
|
const prefixedOld = `${projectCode}-${oldNum}-`;
|
|
if (fileContent.includes(prefixedOld)) {
|
|
crossRefEdits.push({ file: fileName, from: prefixedOld, to: prefixedNew });
|
|
}
|
|
}
|
|
}
|
|
|
|
// Rewrite prose references: "Phase 1:" → "Phase 1-01:", "Phase 2.1:" → "Phase 1-02:"
|
|
const proseOldPatterns = new Set([
|
|
`Phase ${unpaddedNum}${decimalSuffix}:`,
|
|
`Phase ${paddedNum}${decimalSuffix}:`,
|
|
`Phase ${legacyNum}:`,
|
|
]);
|
|
for (const proseOld of proseOldPatterns) {
|
|
if (fileContent.includes(proseOld)) {
|
|
const proseNew = `Phase ${m.newId}:`;
|
|
crossRefEdits.push({ file: fileName, from: proseOld, to: proseNew });
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
return {
|
|
alreadyMigrated: false,
|
|
phases,
|
|
roadmapEdits,
|
|
crossRefEdits,
|
|
};
|
|
}
|
|
|
|
// ─── applyMigration ───────────────────────────────────────────────────────────
|
|
|
|
/**
|
|
* Apply the migration plan computed by computeMigrationPlan().
|
|
*
|
|
* @param cwd
|
|
* @param plan
|
|
* @param options
|
|
* @param options.dryRun - Print plan and exit without mutating. (default true)
|
|
*/
|
|
function applyMigration(cwd: string, plan: MigrationPlan, options: { dryRun?: boolean } = {}): ApplyMigrationResult {
|
|
const dryRun = options.dryRun !== false; // default true
|
|
|
|
if (plan.alreadyMigrated) {
|
|
return { alreadyMigrated: true };
|
|
}
|
|
|
|
if (dryRun) {
|
|
process.stdout.write(JSON.stringify(plan, null, 2) + '\n');
|
|
return { dryRun: true };
|
|
}
|
|
|
|
// ── Real run: verify clean working tree ───────────────────────────────────
|
|
let gitStatus: string;
|
|
try {
|
|
gitStatus = execSync('git status --porcelain', { cwd, encoding: 'utf8' });
|
|
} catch (err) {
|
|
throw new Error(`git status failed: ${(err as Error).message}`);
|
|
}
|
|
if (gitStatus.trim().length > 0) {
|
|
throw new Error('Working tree is dirty. Commit or stash changes before migrating.');
|
|
}
|
|
|
|
// Capture HEAD sha for rollback
|
|
let headSha: string;
|
|
try {
|
|
headSha = execSync('git rev-parse HEAD', { cwd, encoding: 'utf8' }).trim();
|
|
} catch (err) {
|
|
throw new Error(`git rev-parse HEAD failed: ${(err as Error).message}`);
|
|
}
|
|
|
|
const pDir = planningDir(cwd);
|
|
const phasesDir = path.join(pDir, 'phases');
|
|
const roadmapPath = path.join(pDir, 'ROADMAP.md');
|
|
const configPath = path.join(pDir, 'config.json');
|
|
|
|
const renamedDirs: string[] = [];
|
|
const editedFiles: string[] = [];
|
|
|
|
try {
|
|
// 1. Rename phase directories
|
|
for (const phaseEntry of plan.phases) {
|
|
const oldPath = path.join(phasesDir, phaseEntry.oldDir);
|
|
const newPath = path.join(phasesDir, phaseEntry.newDir);
|
|
if (fs.existsSync(oldPath)) {
|
|
fs.renameSync(oldPath, newPath);
|
|
renamedDirs.push(`${phaseEntry.oldDir} → ${phaseEntry.newDir}`);
|
|
}
|
|
}
|
|
|
|
// 2. Rewrite ROADMAP.md phase headings
|
|
if (plan.roadmapEdits.length > 0) {
|
|
const roadmapContent = fs.readFileSync(roadmapPath, 'utf8');
|
|
const lines = roadmapContent.split('\n');
|
|
|
|
// Sort edits by lineIndex to apply in order
|
|
const sortedEdits = [...plan.roadmapEdits].sort((a, b) => a.lineIndex - b.lineIndex);
|
|
for (const edit of sortedEdits) {
|
|
if (lines[edit.lineIndex] === edit.from) {
|
|
lines[edit.lineIndex] = edit.to;
|
|
}
|
|
}
|
|
|
|
fs.writeFileSync(roadmapPath, lines.join('\n'), 'utf8');
|
|
editedFiles.push('ROADMAP.md');
|
|
}
|
|
|
|
// 3. Rewrite cross-refs in STATE.md and PROJECT.md
|
|
const crossRefsByFile = new Map<string, CrossRefEdit[]>();
|
|
for (const edit of plan.crossRefEdits) {
|
|
if (!crossRefsByFile.has(edit.file)) {
|
|
crossRefsByFile.set(edit.file, []);
|
|
}
|
|
crossRefsByFile.get(edit.file)!.push(edit);
|
|
}
|
|
|
|
for (const [fileName, edits] of crossRefsByFile) {
|
|
const filePath = path.join(pDir, fileName);
|
|
if (!fs.existsSync(filePath)) continue;
|
|
|
|
let content = fs.readFileSync(filePath, 'utf8');
|
|
let changed = false;
|
|
|
|
for (const edit of edits) {
|
|
if (content.includes(edit.from)) {
|
|
// Replace all occurrences
|
|
content = content.split(edit.from).join(edit.to);
|
|
changed = true;
|
|
}
|
|
}
|
|
|
|
if (changed) {
|
|
fs.writeFileSync(filePath, content, 'utf8');
|
|
editedFiles.push(fileName);
|
|
}
|
|
}
|
|
|
|
// 4. Update config.json: set phase_id_convention to 'milestone-prefixed'
|
|
let configData: Record<string, unknown> = {};
|
|
try {
|
|
configData = JSON.parse(fs.readFileSync(configPath, 'utf8')) as Record<string, unknown>;
|
|
} catch { /* config may not exist yet */ }
|
|
|
|
configData['phase_id_convention'] = 'milestone-prefixed';
|
|
fs.writeFileSync(configPath, JSON.stringify(configData, null, 2) + '\n', 'utf8');
|
|
editedFiles.push('config.json');
|
|
|
|
} catch (err) {
|
|
// Rollback via git reset --hard + git clean
|
|
try {
|
|
execSync(`git reset --hard ${headSha}`, { cwd, stdio: 'pipe' });
|
|
execSync('git clean -fd .planning/phases/', { cwd, stdio: 'pipe' });
|
|
} catch {
|
|
// Swallow rollback errors — surface original error
|
|
}
|
|
throw new Error(`Migration failed (rolled back to ${headSha}): ${(err as Error).message}`);
|
|
}
|
|
|
|
return { applied: true, renamedDirs, editedFiles };
|
|
}
|
|
|
|
// ─── Exports ──────────────────────────────────────────────────────────────────
|
|
|
|
export = {
|
|
computeMigrationPlan,
|
|
applyMigration,
|
|
};
|