Files
msd-core/src/gsd2-import.cts
Tom Boucher b9f51836e6 refactor(#3180): ADR-3180 behavior contract + cross-surface drift guardrails (#3223)
* refactor(#3180): one owner for completion ratio, a prompt-layer drift guard, and a written behavior contract

The 2026-08-08 coverage audit on #3180 found the epic's copy counts were a
lower bound for the third consecutive time, and that two derivation families
had never been named at all.

ADR-3180 gains Decision 7 — a normative behavior contract that says what the
right answer IS for each derivation, not merely who owns it. A reviewer with
no written rule can only ask "does this look like the others", which is how a
fifth copy passes review. Decision 4 gains (d) scan surface is every authored
surface and an owner FILE is never exempt, only its named functions; and (e)
a surface that cannot be consolidated today ships ratcheted, never unguarded.

Completion ratio: `clampPercent` sat exported and unused beside six hand-inlined
copies of its own body across five modules. All six now route through it;
`clampPercentFromFraction` is added for the one caller that already held a
fraction. Every migration is behaviour-identical — clampPercent's first line IS
the `total > 0 ? … : 0` ternary each copy carried. Guarded by
lint-completion-ratio-drift.cjs, which reports zero re-derivations with no
file-level exemption.

Prompt layer: workflow markdown re-derives live-plan counting in raw shell
(#1762), invisible to every `src/`-scoped guard. lint-planning-prompt-drift.cjs
scans it with a shrink-only baseline of the 7 sites that exist today — new
sites fail, and a baseline entry that stops firing fails too, so an
acknowledgment can never outlive the thing it describes.

lint-milestone-window-drift.cjs stops exempting its owner file wholesale; only
the four named canonical functions are exempt now. The blanket exemption was
pointed at the one file most likely to grow the next copy, and it had.

Refs #3180

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

* docs(#3180): link Phases 6-8 sub-issues (#3216, #3217, #3218) from ADR-3180

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

* fix(#3180): address orthogonal review — consumer-output identity tests, count-keyed ratchet, property coverage

Five findings from the two orthogonal review passes, all fixed.

Decision 4(c) breach: the completion-ratio identity test asserted at the
OWNER, which is exactly the bypass that decision exists to close — a consumer
can call clampPercent and then post-process locally, leaving both the lint and
an owner-level test green. It now drives `roadmap analyze`, `query progress`
and `stats` and asserts on their own output, over a fixture containing a
`status: superseded` plan so a consumer that re-counted raw files would report
60 where the owner reports 75.

Decision 4(e) breach: ratchet entries named the epic (#3180) rather than the
issue that removes them. They name Phase 8 (#3218) now.

The ratchet keyed on (file, text) alone, so plan-phase.md's two byte-identical
sites were one indistinguishable key and migrating either would have left the
guard green with the other alive. Entries carry an occurrence count; fewer than
acknowledged fails as a partial migration, more fails as a new copy.

Adds the missing MAX_REGEX_LITERAL_LEN boundary coverage the sibling guard's
test already had, and the fast-check property tests CONTRIBUTING requires for
clamp/budget-limit functions.

Refs #3180

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

* test: stop wrapping a nested double-spawn in a 15s wall-clock budget (bug #641 probes)

`tests/ci-test-scope.test.cjs`'s `bug #641` block spawned `run-tests.cjs`
under PROBE_TIMEOUT_MS=15000; that child then spawned a nested `node --test`.
A fixed wall-clock budget around a double spawn, running inside a container
that is concurrently executing the full ~31k-test suite, fails by construction
under load.

Confirmed against three full matrix runs. Every failure was shaped
`null !== 0` — the child was KILLED, never an assertion about the thing under
test. One captured probe had already printed the correct resolution
(`suite="all" files=2: a.test.cjs b.test.cjs`) and was killed anyway. It
reproduces on `next` alone: 5 failures on linux-node22, 0 on linux-node24. The
victim subset varies by run and by lane.

What these tests are actually about is suite-token RESOLUTION — `unit` as a
bare token in --files/--files-from. Executing the seeded trivial files is
incidental and is the entire timeout surface, so the assertions move
in-process against the same functions `main()` calls, in the same order.
`parseArgs`, `selectExplicitFiles`, `selectFiles` and `walkTestFiles` are
exported for that; no behavior, signature or logic changed.

No coverage lost: `tests/run-tests-harness.test.cjs` already spawns the
harness for real and asserts exit codes end to end, on a 120s budget.

Pre-existing on `next`, fixed here rather than deferred.

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

* test: delete the three elapsed-time assertions

CLAUDE.md forbids asserting on wall-clock time. Three assertions did, and all
three are load-sensitive: on a saturated bench each can fail while the code
under test is correct. In every case the load-bearing assertion sits on the
line above and the timing line adds no discrimination.

run-with-timeout: the stated worry — "was this 124 the cap firing or the 30s
harness backstop?" — is already answered by the assertion above it. A backstop
kills by signal, which surfaces as status null, never 124. Observed directly
this session: three matrix runs produced exactly that null shape from killed
children.

normalize-test-command and context-predicates: both bounded a ReDoS check.
A threshold only ever separates "fast" from "slightly slow", which is bench
load, not correctness — catastrophic backtracking on 800 KB of input does not
take 251ms, it does not finish at all. A real regression therefore shows up as
the suite being killed on that test, which is louder and more reliable than a
number. The structural assertions (returned unchanged; cleanly rejected) are
what actually carry those tests, and they stay.

The sweep now reports zero elapsed-time assertions in tests/. The remaining
Date.now() uses are unique-path suffixes, barrier deadlines, fixture
timestamps and fake mtimes — none of them assertions.

Pre-existing on `next`, fixed here rather than deferred.

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

* chore(#3180): backfill changeset PR number (#3223)

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

* fix(#3180): key the prompt-drift ratchet on POSIX paths so it works on Windows

The baseline keys on (file, trimmed text). `file` came from scanTree's
`path.relative()`, which uses NATIVE separators, while the committed baseline
stores POSIX. On Windows every violation was therefore unmatched — reported as
FRESH — and every baseline entry matched nothing — reported as STALE. The guard
failed 100% of the time there, on both CI shards:

  ✖ scanRepo(repoRoot) matches the baseline exactly: zero fresh AND zero stale
    + { file: 'gsd-core\\workflows\\execute-plan.md', ... }

The remote runner this repo gates on is Linux-only and cannot see this class at
all; the GitHub Actions Windows lane is what caught it.

Normalization is unconditional — never gated on process.platform. A
platform-conditional normalizer makes the POSIX path the special case and
leaves the Windows branch unexercised on every other OS, which is the same
blind spot in a different place. It is applied at one seam inside
findPromptDrift, which builds `file` on every returned violation, so the
baseline key, the --update writer, the stderr report and the tests all consume
one normalized value.

The regression tests drive a Windows-shaped relPath directly and run on every
OS rather than skipping off-Windows — a test that only runs on the platform
where the bug lives is why this escaped. They include a sanity check that
un-normalized input does NOT match, so the assertion cannot pass vacuously.

Audited the three sibling guards: none keys against a committed cross-platform
baseline, and their exemption keys are path.join-built, so producer and
consumer share the native convention. Left correct code alone rather than
making them look alike. scripts/lib/drift-scan.cjs is untouched — normalizing
there would break those three on Windows.

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

---------

Co-authored-by: sim <sim@local>
Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
2026-08-08 16:05:17 -04:00

603 lines
20 KiB
TypeScript

/**
* gsd2-import — Reverse migration from GSD-2 (.gsd/) to GSD v1 (.planning/)
*
* Reads a GSD-2 project directory structure and produces a complete
* .planning/ artifact tree in GSD v1 format.
*
* GSD-2 hierarchy: Milestone → Slice → Task
* GSD v1 hierarchy: Milestone (in ROADMAP.md) → Phase → Plan
*
* Mapping rules:
* - Slices are numbered sequentially across all milestones (01, 02, …)
* - Tasks within a slice become plans (01-01, 01-02, …)
* - Completed slices ([x] in ROADMAP) → [x] phases in ROADMAP.md
* - Tasks with a SUMMARY file → SUMMARY.md written
* - Slice RESEARCH.md → phase XX-RESEARCH.md
*
* ADR-457 build-at-publish: the hand-written bin/lib/gsd2-import.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 { platformWriteSync } from './shell-command-projection.cjs';
import { formatGsdSlash, resolveRuntime } from './runtime-slash.cjs';
import { realClock } from './clock.cjs';
import { clampPercent } from './phase-lifecycle.cjs';
// eslint-disable-next-line @typescript-eslint/no-require-imports -- core-utils.cjs is an export= CommonJS module
import coreUtilsMod = require('./core-utils.cjs');
// eslint-disable-next-line @typescript-eslint/no-require-imports
import ioMod = require('./io.cjs');
// eslint-disable-next-line @typescript-eslint/no-require-imports -- frontmatter.cjs is an export= CommonJS module
import frontmatterMod = require('./frontmatter.cjs');
const { output } = ioMod;
const { transliterateForSlug } = coreUtilsMod;
const { stripFrontmatter } = frontmatterMod;
// ─── Types ───────────────────────────────────────────────────────────────────
interface SliceInfo {
done: boolean;
id: string;
title: string;
}
interface TaskInfo {
id: string;
title: string;
description: string;
mustHaves: string[];
plan: string | null;
summary: string | null;
done: boolean;
}
interface Slice {
id: string;
title: string;
done: boolean;
plan: string | null;
summary: string | null;
research: string | null;
context: string | null;
tasks: TaskInfo[];
}
interface Milestone {
id: string;
title: string;
research: string | null;
slices: Slice[];
}
interface Gsd2Data {
projectContent: string | null;
requirements: string | null;
milestones: Milestone[];
}
interface PhaseMapEntry {
milestoneId: string;
milestoneTitle: string;
slice: Slice;
phaseNum: number;
}
// ─── Utilities ──────────────────────────────────────────────────────────────
function readOptional(filePath: string): string | null {
try { return fs.readFileSync(filePath, 'utf8'); } catch { return null; }
}
function zeroPad(n: number, width = 2): string {
return String(n).padStart(width, '0');
}
function slugify(title: string): string {
// #2848: transliterate Cyrillic to ASCII before the filter so a non-Latin
// title does not collapse to an empty slug. The shared primitive keeps this
// in sync with generateSlugInternal. slugify's DISTINCT contract is preserved:
// single leading/trailing hyphen strip (/^-|-$/), and NO 60-char truncation.
return transliterateForSlug(title).replace(/[^a-z0-9]+/g, '-').replace(/^-|-$/g, '');
}
// ─── GSD-2 Parser ───────────────────────────────────────────────────────────
/**
* Find the .gsd/ directory starting from a project root.
* Returns the absolute path or null if not found.
*/
function findGsd2Root(startPath: string): string | null {
if (path.basename(startPath) === '.gsd' && fs.existsSync(startPath)) {
return startPath;
}
const candidate = path.join(startPath, '.gsd');
if (fs.existsSync(candidate) && fs.statSync(candidate).isDirectory()) {
return candidate;
}
return null;
}
/**
* Parse the ## Slices section from a GSD-2 milestone ROADMAP.md.
* Each slice entry looks like:
* - [x] **S01: Title** `risk:medium` `depends:[S00]`
*/
function parseSlicesFromRoadmap(content: string): SliceInfo[] {
const slices: SliceInfo[] = [];
const sectionMatch = content.match(/## Slices\n([\s\S]*?)(?:\n## |\n# |$)/);
if (!sectionMatch) return slices;
for (const line of sectionMatch[1].split('\n')) {
const m = line.match(/^- \[([x ])\]\s+\*\*(\w+):\s*([^*]+)\*\*/);
if (!m) continue;
slices.push({ done: m[1] === 'x', id: m[2].trim(), title: m[3].trim() });
}
return slices;
}
/**
* Parse the milestone title from the first heading in a GSD-2 ROADMAP.md.
* Format: # M001: Title
*/
function parseMilestoneTitle(content: string): string | null {
const m = content.match(/^# \w+:\s*(.+)/m);
return m ? m[1].trim() : null;
}
/**
* Parse a task title from a GSD-2 T##-PLAN.md.
* Format: # T01: Title
*/
function parseTaskTitle(content: string, fallback: string): string {
const m = content.match(/^# \w+:\s*(.+)/m);
return m ? m[1].trim() : fallback;
}
/**
* Parse the ## Description body from a GSD-2 task plan.
*/
function parseTaskDescription(content: string): string {
const m = content.match(/## Description\n+([\s\S]+?)(?:\n## |\n# |$)/);
return m ? m[1].trim() : '';
}
/**
* Parse ## Must-Haves items from a GSD-2 task plan.
*/
function parseTaskMustHaves(content: string): string[] {
const m = content.match(/## Must-Haves\n+([\s\S]+?)(?:\n## |\n# |$)/);
if (!m) return [];
return m[1].split('\n')
.map(l => l.match(/^- \[[ x]\]\s*(.+)/))
.filter((match): match is RegExpMatchArray => match !== null)
.map(match => match[1].trim());
}
/**
* Read all task plan files from a GSD-2 tasks/ directory.
*/
// #3183 (ADR-3180 Decision 4(a) — bucket B, out of scope for the
// scanPhasePlans migration): this reads a FOREIGN GSD-2 legacy project's own
// `tasks/` directory convention (`T##-PLAN.md`) during a one-time import —
// it is not this project's `.planning/phases/<phase>/` layout at all, has no
// nested-plans/superseded-status concept, and scanPhasePlans's grammar
// (which is scoped to GSD's OWN phase directories) does not apply here.
function readTasksDir(tasksDir: string): TaskInfo[] {
if (!fs.existsSync(tasksDir)) return [];
return fs.readdirSync(tasksDir)
.filter(f => f.endsWith('-PLAN.md'))
.sort()
.map(tf => {
const tid = tf.replace('-PLAN.md', '');
const plan = readOptional(path.join(tasksDir, tf));
const summary = readOptional(path.join(tasksDir, `${tid}-SUMMARY.md`));
return {
id: tid,
title: plan ? parseTaskTitle(plan, tid) : tid,
description: plan ? parseTaskDescription(plan) : '',
mustHaves: plan ? parseTaskMustHaves(plan) : [],
plan,
summary,
done: !!summary,
};
});
}
/**
* Parse a complete GSD-2 .gsd/ directory into a structured representation.
*/
function parseGsd2(gsdDir: string): Gsd2Data {
const data: Gsd2Data = {
projectContent: readOptional(path.join(gsdDir, 'PROJECT.md')),
requirements: readOptional(path.join(gsdDir, 'REQUIREMENTS.md')),
milestones: [],
};
const milestonesBase = path.join(gsdDir, 'milestones');
if (!fs.existsSync(milestonesBase)) return data;
const milestoneIds = fs.readdirSync(milestonesBase)
.filter(d => fs.statSync(path.join(milestonesBase, d)).isDirectory())
.sort();
for (const mid of milestoneIds) {
const mDir = path.join(milestonesBase, mid);
const roadmapContent = readOptional(path.join(mDir, `${mid}-ROADMAP.md`));
const slicesDir = path.join(mDir, 'slices');
const sliceInfos = roadmapContent ? parseSlicesFromRoadmap(roadmapContent) : [];
const slices: Slice[] = sliceInfos.map(info => {
const sDir = path.join(slicesDir, info.id);
const hasSDir = fs.existsSync(sDir);
return {
id: info.id,
title: info.title,
done: info.done,
plan: hasSDir ? readOptional(path.join(sDir, `${info.id}-PLAN.md`)) : null,
summary: hasSDir ? readOptional(path.join(sDir, `${info.id}-SUMMARY.md`)) : null,
research: hasSDir ? readOptional(path.join(sDir, `${info.id}-RESEARCH.md`)) : null,
context: hasSDir ? readOptional(path.join(sDir, `${info.id}-CONTEXT.md`)) : null,
tasks: hasSDir ? readTasksDir(path.join(sDir, 'tasks')) : [],
};
});
data.milestones.push({
id: mid,
title: roadmapContent ? (parseMilestoneTitle(roadmapContent) ?? mid) : mid,
research: readOptional(path.join(mDir, `${mid}-RESEARCH.md`)),
slices,
});
}
return data;
}
// ─── Artifact Builders ──────────────────────────────────────────────────────
/**
* Build a GSD v1 PLAN.md from a GSD-2 task.
*/
function buildPlanMd(task: TaskInfo, phasePrefix: string, planPrefix: string, phaseSlug: string, milestoneTitle: string): string {
const lines = [
'---',
`phase: "${phasePrefix}"`,
`plan: "${planPrefix}"`,
'type: "implementation"',
'---',
'',
'<objective>',
task.title,
'</objective>',
'',
'<context>',
`Phase: ${phasePrefix} (${phaseSlug}) — Milestone: ${milestoneTitle}`,
];
if (task.description) {
lines.push('', task.description);
}
lines.push('</context>');
if (task.mustHaves.length > 0) {
lines.push('', '<must_haves>');
for (const mh of task.mustHaves) {
lines.push(`- ${mh}`);
}
lines.push('</must_haves>');
}
return lines.join('\n') + '\n';
}
/**
* Build a GSD v1 SUMMARY.md from a GSD-2 task summary.
* Strips the GSD-2 frontmatter and preserves the body.
*/
function buildSummaryMd(task: TaskInfo, phasePrefix: string, planPrefix: string): string {
const raw = task.summary || '';
// Strip the GSD-2 frontmatter block via the canonical primitive (#2703). The
// previous local regex required a bare `\n` after the closing `---`, so a
// CRLF-authored summary never matched, fell through to the untouched-raw
// branch, and had its frontmatter emitted a second time inside the body of
// the document this function then wrapped in a fresh v1 block.
//
// `extractFrontmatter` — which the issue names — returns only the parsed
// object and never the body, so it cannot serve this call site;
// `stripFrontmatter` is the same module's canonical body primitive.
//
// `once` is load-bearing. A GSD-2 summary is an arbitrary user-authored
// document, not a GSD artefact with a known frontmatter-doubling failure
// mode, so a body opening with a thematic-break-delimited section
// (`---` / heading / `---`) is far likelier than a corrupt second header —
// and the default greedy loop would delete it without a trace.
const body = stripFrontmatter(raw, { once: true }).trim();
return [
'---',
`phase: "${phasePrefix}"`,
`plan: "${planPrefix}"`,
'---',
'',
body || 'Task completed (migrated from GSD-2).',
'',
].join('\n');
}
/**
* Build a GSD v1 XX-CONTEXT.md from a GSD-2 slice.
*/
function buildContextMd(slice: Slice, phasePrefix: string): string {
const lines = [
`# Phase ${phasePrefix} Context`,
'',
`Migrated from GSD-2 slice ${slice.id}: ${slice.title}`,
];
const extra = slice.context || '';
if (extra.trim()) {
lines.push('', extra.trim());
}
return lines.join('\n') + '\n';
}
/**
* Build the GSD v1 ROADMAP.md with milestone-sectioned format.
*/
function buildRoadmapMd(milestones: Milestone[], phaseMap: PhaseMapEntry[]): string {
const lines = ['# Roadmap', ''];
for (const milestone of milestones) {
lines.push(`## ${milestone.id}: ${milestone.title}`, '');
const mPhases = phaseMap.filter(p => p.milestoneId === milestone.id);
for (const { slice, phaseNum } of mPhases) {
const prefix = zeroPad(phaseNum);
const slug = slugify(slice.title);
const check = slice.done ? 'x' : ' ';
lines.push(`- [${check}] **Phase ${prefix}: ${slug}** — ${slice.title}`);
}
lines.push('');
}
return lines.join('\n');
}
/**
* Build the GSD v1 STATE.md reflecting the current position in the project.
*/
function buildStateMd(phaseMap: PhaseMapEntry[]): string {
const currentEntry = phaseMap.find(p => !p.slice.done);
const totalPhases = phaseMap.length;
const donePhases = phaseMap.filter(p => p.slice.done).length;
// ADR-3180 D7: one owner for completion percent. clampPercent's 100 ceiling is
// unreachable here (donePhases is a subset of totalPhases) — the value is unchanged.
const pct = clampPercent(donePhases, totalPhases);
const currentPhaseNum = currentEntry ? zeroPad(currentEntry.phaseNum) : zeroPad(totalPhases);
const currentSlug = currentEntry ? slugify(currentEntry.slice.title) : 'complete';
const status = currentEntry ? 'Ready to plan' : 'All phases complete';
const filled = Math.round(pct / 10);
const bar = `[${'█'.repeat(filled)}${'░'.repeat(10 - filled)}]`;
const today = realClock.localToday();
return [
'# Project State',
'',
'## Project Reference',
'',
'See: .planning/PROJECT.md',
'',
`**Current focus:** Phase ${currentPhaseNum} (${currentSlug})`,
'',
'## Current Position',
'',
`Phase: ${currentPhaseNum} of ${zeroPad(totalPhases)} (${currentSlug})`,
`Status: ${status}`,
`Last activity: ${today} — Migrated from GSD-2`,
'',
`Progress: ${bar} ${pct}%`,
'',
'## Accumulated Context',
'',
'### Decisions',
'',
'Migrated from GSD-2. Review PROJECT.md for key decisions.',
'',
'### Blockers/Concerns',
'',
'None.',
'',
'## Session Continuity',
'',
`Last session: ${today}`,
'Stopped at: Migration from GSD-2 completed',
'Resume file: None',
'',
].join('\n');
}
// ─── Transformer ─────────────────────────────────────────────────────────────
/**
* Convert parsed GSD-2 data into a map of relative path → file content.
* All paths are relative to the .planning/ root.
*/
function buildPlanningArtifacts(gsd2Data: Gsd2Data): Map<string, string> {
const artifacts = new Map<string, string>();
// Passthrough files
artifacts.set('PROJECT.md', gsd2Data.projectContent || '# Project\n\n(Migrated from GSD-2)\n');
if (gsd2Data.requirements) {
artifacts.set('REQUIREMENTS.md', gsd2Data.requirements);
}
// Minimal valid v1 config
artifacts.set('config.json', JSON.stringify({ version: 1 }, null, 2) + '\n');
// Build sequential phase map: flatten Milestones → Slices into numbered phases
const phaseMap: PhaseMapEntry[] = [];
let phaseNum = 1;
for (const milestone of gsd2Data.milestones) {
for (const slice of milestone.slices) {
phaseMap.push({ milestoneId: milestone.id, milestoneTitle: milestone.title, slice, phaseNum });
phaseNum++;
}
}
artifacts.set('ROADMAP.md', buildRoadmapMd(gsd2Data.milestones, phaseMap));
artifacts.set('STATE.md', buildStateMd(phaseMap));
for (const { slice, phaseNum: pNum, milestoneTitle } of phaseMap) {
const prefix = zeroPad(pNum);
const slug = slugify(slice.title);
const dir = `phases/${prefix}-${slug}`;
artifacts.set(`${dir}/${prefix}-CONTEXT.md`, buildContextMd(slice, prefix));
if (slice.research) {
artifacts.set(`${dir}/${prefix}-RESEARCH.md`, slice.research);
}
for (let i = 0; i < slice.tasks.length; i++) {
const task = slice.tasks[i];
const planPrefix = zeroPad(i + 1);
artifacts.set(
`${dir}/${prefix}-${planPrefix}-PLAN.md`,
buildPlanMd(task, prefix, planPrefix, slug, milestoneTitle)
);
if (task.done && task.summary) {
artifacts.set(
`${dir}/${prefix}-${planPrefix}-SUMMARY.md`,
buildSummaryMd(task, prefix, planPrefix)
);
}
}
}
return artifacts;
}
// ─── Preview ─────────────────────────────────────────────────────────────────
/**
* Format a dry-run preview string for display before writing.
*/
function buildPreview(gsd2Data: Gsd2Data, artifacts: Map<string, string>, projectDir: string): string {
const lines = ['Preview — files that will be created in .planning/:'];
for (const rel of artifacts.keys()) {
lines.push(` ${rel}`);
}
const totalSlices = gsd2Data.milestones.reduce((s, m) => s + m.slices.length, 0);
const doneSlices = gsd2Data.milestones.reduce((s, m) => s + m.slices.filter(sl => sl.done).length, 0);
const allTasks = gsd2Data.milestones.flatMap(m => m.slices.flatMap(sl => sl.tasks));
const doneTasks = allTasks.filter(t => t.done).length;
lines.push('');
lines.push(`Milestones: ${gsd2Data.milestones.length}`);
lines.push(`Phases (slices): ${totalSlices} (${doneSlices} completed)`);
lines.push(`Plans (tasks): ${allTasks.length} (${doneTasks} completed)`);
lines.push('');
lines.push('Cannot migrate automatically:');
lines.push(' - GSD-2 cost/token ledger (no v1 equivalent)');
lines.push(` - GSD-2 database state (rebuilt from files on first ${formatGsdSlash('health', resolveRuntime(projectDir)) as string})`);
lines.push(' - VS Code extension state');
return lines.join('\n');
}
// ─── Writer ───────────────────────────────────────────────────────────────────
/**
* Write all artifacts to the .planning/ directory.
*/
function writePlanningDir(artifacts: Map<string, string>, planningRoot: string): void {
for (const [rel, content] of artifacts) {
const absPath = path.join(planningRoot, rel);
platformWriteSync(absPath, content);
}
}
// ─── Command Handler ──────────────────────────────────────────────────────────
/**
* Entry point called from gsd-tools.cjs.
* Supports: --force, --dry-run, --path <dir>
*/
function cmdFromGsd2(args: string[], cwd: string, raw: boolean): void {
const force = args.includes('--force');
const dryRun = args.includes('--dry-run');
const pathIdx = args.indexOf('--path');
const projectDir = pathIdx >= 0 && args[pathIdx + 1]
? path.resolve(cwd, args[pathIdx + 1])
: cwd;
const gsdDir = findGsd2Root(projectDir);
if (!gsdDir) {
output({ success: false, error: `No .gsd/ directory found in ${projectDir}` }, raw, undefined);
return;
}
const planningRoot = path.join(path.dirname(gsdDir), '.planning');
if (fs.existsSync(planningRoot) && !force) {
output({
success: false,
error: `.planning/ already exists at ${planningRoot}. Pass --force to overwrite.`,
}, raw, undefined);
return;
}
const gsd2Data = parseGsd2(gsdDir);
const artifacts = buildPlanningArtifacts(gsd2Data);
// Use projectDir (resolved from --path) — not the process cwd — so the
// preview command targets the project actually being imported (#3584).
const preview = buildPreview(gsd2Data, artifacts, projectDir);
if (dryRun) {
output({ success: true, dryRun: true, preview }, raw, undefined);
return;
}
writePlanningDir(artifacts, planningRoot);
output({
success: true,
planningDir: planningRoot,
filesWritten: artifacts.size,
milestones: gsd2Data.milestones.length,
preview,
}, raw, undefined);
}
export = {
findGsd2Root,
parseGsd2,
buildPlanningArtifacts,
buildPreview,
writePlanningDir,
cmdFromGsd2,
// Exported for unit tests
parseSlicesFromRoadmap,
parseMilestoneTitle,
parseTaskTitle,
parseTaskDescription,
parseTaskMustHaves,
buildPlanMd,
buildSummaryMd,
buildContextMd,
buildRoadmapMd,
buildStateMd,
slugify,
zeroPad,
};