* 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:
158
sdk/src/query/phase-ready.ts
Normal file
158
sdk/src/query/phase-ready.ts
Normal file
@@ -0,0 +1,158 @@
|
||||
/**
|
||||
* Phase readiness snapshot (`check.phase-ready`).
|
||||
*
|
||||
* Deterministic file + plan/summary counts and a suggested `next_step` for orchestration.
|
||||
* See `.planning/research/decision-routing-audit.md` §3.4.
|
||||
*/
|
||||
|
||||
import { readFile } from 'node:fs/promises';
|
||||
import { join } from 'node:path';
|
||||
import { existsSync, readdirSync } from 'node:fs';
|
||||
import { GSDError, ErrorClassification } from '../errors.js';
|
||||
import { comparePhaseNum, escapeRegex, normalizePhaseName, planningPaths } from './helpers.js';
|
||||
import { findPhase } from './phase.js';
|
||||
import { roadmapAnalyze } from './roadmap.js';
|
||||
import type { QueryHandler } from './utils.js';
|
||||
|
||||
const UI_INDICATOR_RE = /UI|interface|frontend|component|layout|page|screen|view|form|dashboard|widget/i;
|
||||
|
||||
/**
|
||||
* True if ROADMAP phase heading line for this phase matches UI_INDICATOR_RE.
|
||||
*/
|
||||
async function roadmapPhaseLineHasUiIndicators(
|
||||
projectDir: string,
|
||||
phaseNum: string,
|
||||
): Promise<boolean> {
|
||||
const roadmapPath = planningPaths(projectDir).roadmap;
|
||||
let content: string;
|
||||
try {
|
||||
content = await readFile(roadmapPath, 'utf-8');
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
const re = new RegExp(
|
||||
`#{2,4}\\s*Phase\\s+${escapeRegex(phaseNum)}\\s*:[^\\n]*`,
|
||||
'i',
|
||||
);
|
||||
const m = content.match(re);
|
||||
if (!m) return false;
|
||||
return UI_INDICATOR_RE.test(m[0]);
|
||||
}
|
||||
|
||||
function hasUiSpecFile(phaseDirFull: string): boolean {
|
||||
if (!existsSync(phaseDirFull)) return false;
|
||||
try {
|
||||
const files = readdirSync(phaseDirFull);
|
||||
return files.some(f => f === 'UI-SPEC.md' || f.endsWith('-UI-SPEC.md'));
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether all roadmap phases strictly before `phaseNum` are complete on disk / roadmap.
|
||||
*/
|
||||
function dependenciesMet(
|
||||
phases: Array<Record<string, unknown>>,
|
||||
phaseNum: string,
|
||||
): boolean {
|
||||
const sorted = [...phases].sort((a, b) =>
|
||||
comparePhaseNum(String(a.number), String(b.number)),
|
||||
);
|
||||
const idx = sorted.findIndex(p => normalizePhaseName(String(p.number)) === normalizePhaseName(phaseNum));
|
||||
if (idx <= 0) return true;
|
||||
for (let i = 0; i < idx; i++) {
|
||||
const p = sorted[i];
|
||||
const complete =
|
||||
p.roadmap_complete === true ||
|
||||
p.disk_status === 'complete';
|
||||
if (!complete) return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
type NextStep = 'discuss' | 'plan' | 'execute' | 'verify' | 'complete';
|
||||
|
||||
function inferNextStep(params: {
|
||||
found: boolean;
|
||||
has_context: boolean;
|
||||
has_research: boolean;
|
||||
plan_count: number;
|
||||
incomplete_plans: string[];
|
||||
has_verification: boolean;
|
||||
}): NextStep {
|
||||
if (!params.found) return 'discuss';
|
||||
if (!params.has_context && !params.has_research) return 'discuss';
|
||||
if (params.plan_count === 0) return 'plan';
|
||||
if (params.incomplete_plans.length > 0) return 'execute';
|
||||
if (!params.has_verification) return 'verify';
|
||||
return 'complete';
|
||||
}
|
||||
|
||||
export const checkPhaseReady: QueryHandler = async (args, projectDir) => {
|
||||
const raw = args[0];
|
||||
if (!raw) {
|
||||
throw new GSDError('phase number required for check phase-ready', ErrorClassification.Validation);
|
||||
}
|
||||
const phaseArg = normalizePhaseName(raw);
|
||||
|
||||
const phaseRes = await findPhase([raw], projectDir);
|
||||
const pdata = phaseRes.data as Record<string, unknown>;
|
||||
const found = Boolean(pdata.found);
|
||||
|
||||
const planCount = (pdata.plans as string[] | undefined)?.length ?? 0;
|
||||
const incomplete = (pdata.incomplete_plans as string[] | undefined) ?? [];
|
||||
const has_context = Boolean(pdata.has_context);
|
||||
const has_research = Boolean(pdata.has_research);
|
||||
const has_verification = Boolean(pdata.has_verification);
|
||||
|
||||
let has_ui_spec = false;
|
||||
let phaseDirFull: string | null = null;
|
||||
if (found && pdata.directory) {
|
||||
phaseDirFull = join(projectDir, pdata.directory as string);
|
||||
has_ui_spec = hasUiSpecFile(phaseDirFull);
|
||||
}
|
||||
|
||||
const phaseNumForRoadmap = (pdata.phase_number as string) || phaseArg;
|
||||
const has_ui_indicators =
|
||||
(await roadmapPhaseLineHasUiIndicators(projectDir, phaseNumForRoadmap)) ||
|
||||
(phaseNumForRoadmap !== phaseArg ? await roadmapPhaseLineHasUiIndicators(projectDir, phaseArg) : false);
|
||||
|
||||
const analysis = await roadmapAnalyze([], projectDir);
|
||||
const adata = analysis.data as { phases?: Array<Record<string, unknown>> };
|
||||
const phases = adata.phases ?? [];
|
||||
const deps = dependenciesMet(phases, phaseArg);
|
||||
|
||||
const next_step = inferNextStep({
|
||||
found,
|
||||
has_context,
|
||||
has_research,
|
||||
plan_count: planCount,
|
||||
incomplete_plans: incomplete,
|
||||
has_verification,
|
||||
});
|
||||
|
||||
/** Phase exists on disk and prior roadmap phases are complete — safe to focus on `next_step`. */
|
||||
const ready = found && deps;
|
||||
|
||||
return {
|
||||
data: {
|
||||
found,
|
||||
ready,
|
||||
phase: phaseArg,
|
||||
phase_name: (pdata.phase_name as string) ?? null,
|
||||
phase_dir: (pdata.directory as string) ?? null,
|
||||
has_context,
|
||||
has_research,
|
||||
has_plans: planCount > 0,
|
||||
plan_count: planCount,
|
||||
incomplete_plans: incomplete.length,
|
||||
has_verification,
|
||||
has_ui_spec,
|
||||
has_ui_indicators,
|
||||
dependencies_met: deps,
|
||||
blockers: [] as string[],
|
||||
next_step,
|
||||
},
|
||||
};
|
||||
};
|
||||
Reference in New Issue
Block a user