feat(sdk): golden parity harness and query handler CJS alignment (#2302 Track A) (#2341)

* feat(sdk): golden parity harness and query handler CJS alignment (#2302 Track A)

Golden/read-only parity tests and registry alignment, query handler fixes
(check-completion, state-mutation, commit, validate, summary, etc.), and
WAITING.json dual-write for .gsd/.planning readers.

Refs gsd-build/get-shit-done#2341

* fix(sdk): getMilestoneInfo matches GSD ROADMAP (🟡, last bold, STATE fallback)

- Recognize in-flight 🟡 milestone bullets like 🚧.
- Derive from last **vX.Y Title** before ## Phases when emoji absent.
- Fall back to STATE.md milestone when ROADMAP is missing; use last bare vX.Y
  in cleaned text instead of first (avoids v1.0 from shipped list).
- Fixes init.execute-phase milestone_version and buildStateFrontmatter after
  state.begin-phase (syncStateFrontmatter).

* feat(sdk): phase list, plan task structure, requirements extract handlers

- Register phase.list-plans, phase.list-artifacts, plan.task-structure,
  requirements.extract-from-plans (SDK-only; golden-policy exceptions).
- Add unit tests; document in QUERY-HANDLERS.md.
- writeProfile: honor --output, render dimensions, return profile_path and dimensions_scored.

* feat(sdk): centralize getGsdAgentsDir in query helpers

Extract agent directory resolution to helpers (GSD_AGENTS_DIR, primary
~/.claude/agents, legacy path). Use from init and docs-init init bundles.

docs(15): add 15-CONTEXT for autonomous phase-15 run.

* feat(sdk): query CLI CJS fallback and session correlation

- createRegistry(eventStream, sessionId) threads correlation into mutation events
- gsd-sdk query falls back to gsd-tools.cjs when no native handler matches
  (disable with GSD_QUERY_FALLBACK=off); stderr bridge warnings
- Export createRegistry from @gsd-build/sdk; add sdk/README.md
- Update QUERY-HANDLERS.md and registry module docs for fallback + sessionId
- Agents: prefer node dist/cli.js query over cat/grep for STATE and plans

* fix(sdk): init phase_found parity, docs-init agents path, state field extract

- Normalize findPhase not-found to null before roadmap fallback (matches findPhaseInternal)

- docs-init: use detectRuntime + resolveAgentsDir for checkAgentsInstalled

- state.cjs stateExtractField: horizontal whitespace only after colon (YAML progress guard)

- Tests: commit_docs default true; config-get golden uses temp config; golden integration green

Refs: #2302

* refactor(sdk): share SessionJsonlRecord in profile-extract-messages

CodeRabbit nit: dedupe JSONL record shape for isGenuineUserMessage and streamExtractMessages.

* fix(sdk): address CodeRabbit major threads (paths, gates, audit, verify)

- Resolve @file: and CLI JSON indirection relative to projectDir; guard empty normalized query command

- plan.task-structure + intel extract/patch-meta: resolvePathUnderProject containment

- check.config-gates: safe string booleans; plan_checker alias precedence over plan_check default

- state.validate/sync: phaseTokenMatches + comparePhaseNum ordering

- verify.schema-drift: token match phase dirs; files_modified from parsed frontmatter

- audit-open: has_scan_errors, unreadable rows, human report when scans fail

- requirements PLANNED key PLAN for root PLAN.md; gsd-tools timeout note

- ingest-docs: repo-root path containment; classifier output slug-hash

Golden parity test strips has_scan_errors until CJS adds field.

* fix: Resolve CodeRabbit security and quality findings
- Secure intel.ts and cli.ts against path traversal
- Catch and validate git add status in commit.ts
- Expand roadmap milestone marker extraction
- Fix parsing array-of-objects in frontmatter YAML
- Fix unhandled config evaluations
- Improve coverage test parity mapping

* test: raise planner character extraction limit to 48K

* fix(sdk): resolve TS build error in docs-init passing config
This commit is contained in:
Rezolv
2026-04-20 18:09:02 -04:00
committed by GitHub
parent c8807e38d7
commit c5b1445529
109 changed files with 11588 additions and 1030 deletions

View File

@@ -2,8 +2,8 @@
* Phase lifecycle handlers — add, insert, scaffold operations.
*
* Ported from get-shit-done/bin/lib/phase.cjs and commands.cjs.
* Provides phaseAdd (append phase), phaseInsert (decimal phase insertion),
* and phaseScaffold (template file/directory creation).
* Provides phaseAdd (append phase), phaseAddBatch (append multiple phases),
* phaseInsert (decimal phase insertion), and phaseScaffold (template file/directory creation).
*
* Shared helpers replaceInCurrentMilestone and readModifyWriteRoadmapMd
* are exported for use by downstream handlers (phaseComplete in Plan 03).
@@ -24,6 +24,7 @@ import { join, relative } from 'node:path';
import { GSDError, ErrorClassification } from '../errors.js';
import {
escapeRegex,
normalizeMd,
normalizePhaseName,
comparePhaseNum,
phaseTokenMatches,
@@ -31,9 +32,15 @@ import {
planningPaths,
stateExtractField,
} from './helpers.js';
import { extractFrontmatter } from './frontmatter.js';
import { extractCurrentMilestone } from './roadmap.js';
import { getMilestonePhaseFilter } from './state.js';
import { acquireStateLock, releaseStateLock, stateReplaceField } from './state-mutation.js';
import {
acquireStateLock,
readModifyWriteStateMdFull,
releaseStateLock,
stateReplaceField,
} from './state-mutation.js';
import type { QueryHandler } from './utils.js';
// ─── Null byte validation ────────────────────────────────────────────────
@@ -238,6 +245,145 @@ export const phaseAdd: QueryHandler = async (args, projectDir) => {
return { data: result };
};
// ─── phaseAddBatch handler ────────────────────────────────────────────────
/**
* Query handler for phase.add-batch.
*
* Port of cmdPhaseAddBatch from phase.cjs lines 411-478.
* Appends multiple phases in one locked ROADMAP pass (sequential or custom naming).
*
* @param args - Either `--descriptions` followed by a JSON array string, or one description per arg (`--raw` ignored)
*/
export const phaseAddBatch: QueryHandler = async (args, projectDir) => {
let descriptions: string[];
const descIdx = args.indexOf('--descriptions');
if (descIdx !== -1 && args[descIdx + 1] !== undefined) {
try {
const parsed = JSON.parse(args[descIdx + 1]) as unknown;
if (!Array.isArray(parsed)) {
throw new GSDError('--descriptions must be a JSON array', ErrorClassification.Validation);
}
descriptions = parsed.map((x) => String(x));
} catch (e) {
if (e instanceof GSDError) throw e;
throw new GSDError('--descriptions must be a valid JSON array', ErrorClassification.Validation);
}
} else {
descriptions = args.filter((a) => a !== '--raw');
}
if (descriptions.length === 0) {
throw new GSDError('descriptions array required for phase add-batch', ErrorClassification.Validation);
}
for (const d of descriptions) {
assertNoNullBytes(d, 'description');
if (!d.trim()) {
throw new GSDError('description must be non-empty', ErrorClassification.Validation);
}
}
const roadmapPath = planningPaths(projectDir).roadmap;
if (!existsSync(roadmapPath)) {
throw new GSDError('ROADMAP.md not found', ErrorClassification.Validation);
}
let config: Record<string, unknown> = {};
try {
config = JSON.parse(await readFile(planningPaths(projectDir).config, 'utf-8'));
} catch { /* use defaults */ }
const projectCode = (config.project_code as string) || '';
assertSafeProjectCode(projectCode);
const prefix = projectCode ? `${projectCode}-` : '';
const added: Array<{
phase_number: string | number;
padded: string;
name: string;
slug: string;
directory: string;
naming_mode: unknown;
}> = [];
await readModifyWriteRoadmapMd(projectDir, async (initialContent) => {
let rawContent = initialContent;
const content = await extractCurrentMilestone(rawContent, projectDir);
let maxPhase = 0;
if (config.phase_naming !== 'custom') {
const phasePattern = /#{2,4}\s*Phase\s+(\d+)[A-Z]?(?:\.\d+)*:/gi;
let m: RegExpExecArray | null;
while ((m = phasePattern.exec(content)) !== null) {
const num = parseInt(m[1], 10);
if (num >= 999) continue;
if (num > maxPhase) maxPhase = num;
}
const phasesOnDisk = planningPaths(projectDir).phases;
if (existsSync(phasesOnDisk)) {
const entries = await readdir(phasesOnDisk, { withFileTypes: true });
const dirNumPattern = /^(?:[A-Z][A-Z0-9]*-)?(\d+)-/;
for (const entry of entries) {
if (!entry.isDirectory()) continue;
const match = entry.name.match(dirNumPattern);
if (!match) continue;
const num = parseInt(match[1], 10);
if (num >= 999) continue;
if (num > maxPhase) maxPhase = num;
}
}
}
for (const description of descriptions) {
const slug = generateSlugInternal(description);
let newPhaseId: number | string;
let dirName: string;
if (config.phase_naming === 'custom') {
// Match CJS cmdPhaseAddBatch: slug.toUpperCase().replace(/-/g, '-') (identity on hyphens)
newPhaseId = slug.toUpperCase();
dirName = `${prefix}${newPhaseId}-${slug}`;
} else {
maxPhase += 1;
newPhaseId = maxPhase;
dirName = `${prefix}${String(newPhaseId).padStart(2, '0')}-${slug}`;
}
assertSafePhaseDirName(dirName);
const dirPath = join(planningPaths(projectDir).phases, dirName);
await mkdir(dirPath, { recursive: true });
await writeFile(join(dirPath, '.gitkeep'), '', 'utf-8');
const dependsOn =
config.phase_naming === 'custom'
? ''
: `\n**Depends on:** Phase ${typeof newPhaseId === 'number' ? newPhaseId - 1 : 'TBD'}`;
const phaseEntry = `\n### Phase ${newPhaseId}: ${description}\n\n**Goal:** [To be planned]\n**Requirements**: TBD${dependsOn}\n**Plans:** 0 plans\n\nPlans:\n- [ ] TBD (run /gsd-plan-phase ${newPhaseId} to break down)\n`;
const lastSeparator = rawContent.lastIndexOf('\n---');
rawContent =
lastSeparator > 0
? rawContent.slice(0, lastSeparator) + phaseEntry + rawContent.slice(lastSeparator)
: rawContent + phaseEntry;
added.push({
phase_number: typeof newPhaseId === 'number' ? newPhaseId : String(newPhaseId),
padded: typeof newPhaseId === 'number' ? String(newPhaseId).padStart(2, '0') : String(newPhaseId),
name: description,
slug,
directory: toPosixPath(relative(projectDir, join(planningPaths(projectDir).phases, dirName))),
naming_mode: config.phase_naming || 'sequential',
});
}
return rawContent;
});
return { data: { phases: added, count: added.length } };
};
// ─── phaseInsert handler ────────────────────────────────────────────────
/**
@@ -402,14 +548,36 @@ async function findPhaseDir(
* Port of cmdScaffold from commands.cjs lines 750-806.
* Creates template files (context, uat, verification) or phase directories.
*
* @param args - args[0]: type (required), args[1]: phase (required), args[2]: name (optional)
* @param args - Positional `[type, phase, name?]` **or** gsd-tools style
* `[type, '--phase', N, '--name', title]` (name may be multiple words).
* @param projectDir - Project root directory
* @returns QueryResult with { created, path } or { created: false, reason: 'already_exists' }
*/
export const phaseScaffold: QueryHandler = async (args, projectDir) => {
function normalizeScaffoldArgs(args: string[]): string[] {
const type = args[0];
const phase = args[1];
const name = args[2] || undefined;
if (!type || !args.includes('--phase')) {
return args;
}
const phaseIdx = args.indexOf('--phase');
const phase = phaseIdx !== -1 && args[phaseIdx + 1] && !args[phaseIdx + 1].startsWith('--')
? args[phaseIdx + 1]
: '';
const nameIdx = args.indexOf('--name');
let name: string | undefined;
if (nameIdx !== -1) {
const tail = args.slice(nameIdx + 1);
const stop = tail.findIndex(a => a.startsWith('--'));
const parts = stop === -1 ? tail : tail.slice(0, stop);
name = parts.join(' ').trim() || undefined;
}
return [type, phase, ...(name !== undefined && name !== '' ? [name] : [])];
}
export const phaseScaffold: QueryHandler = async (args, projectDir) => {
const normalized = normalizeScaffoldArgs(args);
const type = normalized[0];
const phase = normalized[1];
const name = normalized[2] || undefined;
if (!type) {
throw new GSDError('type required for scaffold', ErrorClassification.Validation);
@@ -1436,18 +1604,196 @@ export const phasesArchive: QueryHandler = async (args, projectDir) => {
// ─── milestoneComplete ────────────────────────────────────────────────────
export const milestoneComplete: QueryHandler = async (args, projectDir) => {
const version = args[0] || 'current';
try {
const archiveResult = await phasesArchive([], projectDir);
return {
data: {
completed: true,
version,
archive: archiveResult.data,
},
};
} catch (err) {
return { data: { completed: false, reason: String(err) } };
/** Port of `parseMultiwordArg` in `gsd-tools.cjs`. */
function parseMultiwordArg(args: string[], flag: string): string | null {
const idx = args.indexOf(`--${flag}`);
if (idx === -1) return null;
const tokens: string[] = [];
for (let i = idx + 1; i < args.length; i++) {
if (args[i]!.startsWith('--')) break;
tokens.push(args[i]!);
}
return tokens.length > 0 ? tokens.join(' ') : null;
}
/** Port of `extractOneLinerFromBody` from `core.cjs` / `summary.ts`. */
function extractOneLinerFromBody(content: string): string | null {
if (!content) return null;
const body = content.replace(/^---\r?\n[\s\S]*?\r?\n---\r?\n*/, '');
const match = body.match(/^#[^\n]*\n+\*\*([^*]+)\*\*/m);
return match ? match[1]!.trim() : null;
}
/**
* Query handler for `milestone.complete` — port of `cmdMilestoneComplete` from `milestone.cjs`.
*/
export const milestoneComplete: QueryHandler = async (args, projectDir) => {
const version = args[0];
if (!version) {
throw new GSDError('version required for milestone complete (e.g., v1.0)', ErrorClassification.Validation);
}
assertNoNullBytes(version, 'version');
const nameOpt = parseMultiwordArg(args, 'name');
const archivePhases = args.includes('--archive-phases');
const paths = planningPaths(projectDir);
const roadmapPath = paths.roadmap;
const reqPath = paths.requirements;
const statePath = paths.state;
const milestonesPath = join(paths.planning, 'MILESTONES.md');
const archiveDir = join(paths.planning, 'milestones');
const phasesDir = paths.phases;
const today = new Date().toISOString().split('T')[0]!;
const milestoneName = nameOpt || version;
await mkdir(archiveDir, { recursive: true });
const isDirInMilestone = await getMilestonePhaseFilter(projectDir);
let phaseCount = 0;
let totalPlans = 0;
let totalTasks = 0;
const accomplishments: string[] = [];
try {
const entries = await readdir(phasesDir, { withFileTypes: true });
const dirs = entries.filter((e) => e.isDirectory()).map((e) => e.name).sort();
for (const dir of dirs) {
if (!isDirInMilestone(dir)) continue;
phaseCount++;
const phaseFiles = await readdir(join(phasesDir, dir));
const plans = phaseFiles.filter((f) => f.endsWith('-PLAN.md') || f === 'PLAN.md');
const summaries = phaseFiles.filter((f) => f.endsWith('-SUMMARY.md') || f === 'SUMMARY.md');
totalPlans += plans.length;
for (const s of summaries) {
try {
const content = await readFile(join(phasesDir, dir, s), 'utf-8');
const fm = extractFrontmatter(content);
const oneLiner =
(fm['one-liner'] as string | undefined) || extractOneLinerFromBody(content);
if (oneLiner) {
accomplishments.push(oneLiner);
}
const tasksFieldMatch = content.match(/\*\*Tasks:\*\*\s*(\d+)/);
if (tasksFieldMatch) {
totalTasks += parseInt(tasksFieldMatch[1]!, 10);
} else {
const xmlTaskMatches = content.match(/<task[\s>]/gi) || [];
const mdTaskMatches = content.match(/##\s*Task\s*\d+/gi) || [];
totalTasks += xmlTaskMatches.length || mdTaskMatches.length;
}
} catch {
/* intentionally empty */
}
}
}
} catch {
/* intentionally empty */
}
if (existsSync(roadmapPath)) {
const roadmapContent = await readFile(roadmapPath, 'utf-8');
await writeFile(join(archiveDir, `${version}-ROADMAP.md`), roadmapContent, 'utf-8');
}
if (existsSync(reqPath)) {
const reqContent = await readFile(reqPath, 'utf-8');
const archiveHeader =
`# Requirements Archive: ${version} ${milestoneName}\n\n` +
`**Archived:** ${today}\n**Status:** SHIPPED\n\n` +
`For current requirements, see \`.planning/REQUIREMENTS.md\`.\n\n---\n\n`;
await writeFile(join(archiveDir, `${version}-REQUIREMENTS.md`), archiveHeader + reqContent, 'utf-8');
}
const auditFile = join(projectDir, '.planning', `${version}-MILESTONE-AUDIT.md`);
if (existsSync(auditFile)) {
await rename(auditFile, join(archiveDir, `${version}-MILESTONE-AUDIT.md`));
}
const accomplishmentsList = accomplishments.map((a) => `- ${a}`).join('\n');
const milestoneEntry =
`## ${version} ${milestoneName} (Shipped: ${today})\n\n` +
`**Phases completed:** ${phaseCount} phases, ${totalPlans} plans, ${totalTasks} tasks\n\n` +
`**Key accomplishments:**\n${accomplishmentsList || '- (none recorded)'}\n\n---\n\n`;
if (existsSync(milestonesPath)) {
const existing = await readFile(milestonesPath, 'utf-8');
if (!existing.trim()) {
await writeFile(milestonesPath, normalizeMd(`# Milestones\n\n${milestoneEntry}`), 'utf-8');
} else {
const headerMatch = existing.match(/^(#{1,3}\s+[^\n]*\n\n?)/);
if (headerMatch) {
const header = headerMatch[1]!;
const rest = existing.slice(header.length);
await writeFile(milestonesPath, normalizeMd(header + milestoneEntry + rest), 'utf-8');
} else {
await writeFile(milestonesPath, normalizeMd(milestoneEntry + existing), 'utf-8');
}
}
} else {
await writeFile(milestonesPath, normalizeMd(`# Milestones\n\n${milestoneEntry}`), 'utf-8');
}
if (existsSync(statePath)) {
await readModifyWriteStateMdFull(projectDir, (stateContent) => {
let next = stateReplaceFieldWithFallback(
stateContent,
'Status',
null,
`${version} milestone complete`,
);
next = stateReplaceFieldWithFallback(next, 'Last Activity', 'Last activity', today);
next = stateReplaceFieldWithFallback(
next,
'Last Activity Description',
null,
`${version} milestone completed and archived`,
);
return next;
});
}
let phasesArchived = false;
if (archivePhases) {
try {
const phaseArchiveDir = join(archiveDir, `${version}-phases`);
await mkdir(phaseArchiveDir, { recursive: true });
const phaseEntries = await readdir(phasesDir, { withFileTypes: true });
const phaseDirNames = phaseEntries.filter((e) => e.isDirectory()).map((e) => e.name);
let archivedCount = 0;
for (const dir of phaseDirNames) {
if (!isDirInMilestone(dir)) continue;
await rename(join(phasesDir, dir), join(phaseArchiveDir, dir));
archivedCount++;
}
phasesArchived = archivedCount > 0;
} catch {
/* intentionally empty */
}
}
return {
data: {
version,
name: milestoneName,
date: today,
phases: phaseCount,
plans: totalPlans,
tasks: totalTasks,
accomplishments,
archived: {
roadmap: existsSync(join(archiveDir, `${version}-ROADMAP.md`)),
requirements: existsSync(join(archiveDir, `${version}-REQUIREMENTS.md`)),
audit: existsSync(join(archiveDir, `${version}-MILESTONE-AUDIT.md`)),
phases: phasesArchived,
},
milestones_updated: true,
state_updated: existsSync(statePath),
},
};
};