diff --git a/.changeset/graceful-jays-hop.md b/.changeset/graceful-jays-hop.md new file mode 100644 index 000000000..affea3bff --- /dev/null +++ b/.changeset/graceful-jays-hop.md @@ -0,0 +1,5 @@ +--- +type: Fixed +pr: 156 +--- +Fix W007/phaseVariants/W006 drift between SDK validate.ts and CJS verify.cjs via generator pattern (gen-validate.mjs + validate.generated.cjs). Per ADR-3524 generator framework introduced by PR #154 (issue #4). diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index dc4fa5c81..5a4c76425 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -219,6 +219,11 @@ jobs: shell: bash run: node sdk/scripts/check-workstream-name-policy-fresh.mjs + - name: SDK generated validate artifact drift check + if: matrix.os == 'ubuntu-latest' && matrix.node-version == 24 + shell: bash + run: node sdk/scripts/check-validate-fresh.mjs + - name: Shared Module hand-sync drift check if: matrix.os == 'ubuntu-latest' && matrix.node-version == 24 shell: bash diff --git a/docs/INVENTORY-MANIFEST.json b/docs/INVENTORY-MANIFEST.json index 201a7facf..103f7edfd 100644 --- a/docs/INVENTORY-MANIFEST.json +++ b/docs/INVENTORY-MANIFEST.json @@ -1,5 +1,5 @@ { - "generated": "2026-05-21", + "generated": "2026-05-23", "families": { "agents": [ "gsd-advisor-researcher", @@ -325,6 +325,7 @@ "template.cjs", "uat.cjs", "validate-command-router.cjs", + "validate.generated.cjs", "verify-command-router.cjs", "verify.cjs", "workstream-inventory-builder.generated.cjs", diff --git a/docs/INVENTORY.md b/docs/INVENTORY.md index e680f17bc..e92660080 100644 --- a/docs/INVENTORY.md +++ b/docs/INVENTORY.md @@ -361,7 +361,7 @@ The `gsd-planner` agent is decomposed into a core agent plus reference modules t --- -## CLI Modules (74 shipped) +## CLI Modules (75 shipped) Full listing: `get-shit-done/bin/lib/*.cjs`. @@ -433,6 +433,7 @@ Full listing: `get-shit-done/bin/lib/*.cjs`. | `template.cjs` | Template selection and filling with variable substitution | | `uat.cjs` | UAT file parsing, verification debt tracking, audit-uat support | | `validate-command-router.cjs` | Thin CJS subcommand router adapter for `gsd-tools validate` | +| `validate.generated.cjs` | GENERATED — CJS artifact emitted from `sdk/src/query/validate.ts` via `sdk/scripts/gen-validate.mjs`; pure phase variant normalization helpers (`phaseVariants`, `buildRoadmapPhaseVariants`, `buildNotStartedPhaseVariants`) used by `verify.cjs` for W006/W007 checks; no I/O, no async; do not edit directly | | `verify-command-router.cjs` | Thin CJS subcommand router adapter for `gsd-tools verify` | | `verify.cjs` | Plan structure, phase completeness, reference, commit validation | | `workstream-inventory-builder.generated.cjs` | GENERATED — pure workstream inventory projection builder; CJS artifact emitted from `sdk/src/workstream-inventory/builder.ts` via `sdk/scripts/gen-workstream-inventory-builder.mjs`; do not edit directly | diff --git a/docs/adr/3524-cjs-sdk-hard-seam.md b/docs/adr/3524-cjs-sdk-hard-seam.md index cf0761393..02b19ac75 100644 --- a/docs/adr/3524-cjs-sdk-hard-seam.md +++ b/docs/adr/3524-cjs-sdk-hard-seam.md @@ -101,3 +101,48 @@ A top-of-file banner is auto-inserted by each generator into the emitted `.gener ## Amendments _(Append-only. Use a dated header when the decision evolves.)_ + +### 2026-05-23 — validate.ts → verify.cjs generator pattern (issue #6) + +Three pure helpers from `sdk/src/query/validate.ts` Check 8 are now generated into +`get-shit-done/bin/lib/validate.generated.cjs` via `sdk/scripts/gen-validate.mjs`, +following the same I/O adapter pattern established by PR #154 (issue #4): + +**Generator:** `sdk/scripts/gen-validate.mjs` +**Artifact:** `get-shit-done/bin/lib/validate.generated.cjs` +**Freshness check:** `sdk/scripts/check-validate-fresh.mjs` +**CI:** `.github/workflows/test.yml` — "SDK generated validate artifact drift check" + +**Three drift items resolved (issue #6):** + +1. **W007 `activeDiskPhases`** — `verify.cjs` Check 8 previously iterated `diskPhases` + (which includes archived milestone phases via `forEachArchivedPhaseToken`) for the W007 + check. Archived phases absent from the current ROADMAP produced false W007 warnings. + Fix: W007 now iterates `activeDiskPhases` (from `collectDiskPhases()` only, without + `forEachArchivedPhaseToken`), matching `validate.ts` Check 8 behavior. + +2. **`phaseVariants()` normalization** — `verify.cjs` Check 8 used `parseInt(p).padStart(2,'0')` + for disk-existence and roadmap-membership checks, which drops letter suffixes (e.g. "3B" → + "03" instead of "03B"). Phase dirs with letter-suffix padding mismatches (ROADMAP "3B", + disk "03B-foo") produced false W006 and W007. Fix: both checks now use `phaseVariants(p)` + from the generated module, which returns the full normalized Set including letter-suffix forms. + +3. **W006 unchecked-phase variant skip** — `verify.cjs` Check 8 built `notStartedPhases` with + raw + `parseInt`-padded forms (drops letter suffix). `phaseVariants()` is now used instead, + so unchecked entries like "3B" correctly suppress W006 for "03B" (and vice versa). + +**`phaseVariants` extraction note:** `phaseVariants` is defined as a closure inside `validateHealth` +in the compiled output (not a module-level export). It is extracted via brace-balanced source-text +parsing from `sdk/dist/query/validate.js`, the same technique used for `escapeRegex` extraction in +`gen-phase-lifecycle-policy.mjs`. The function is deterministic and pure: no closures over external +state, no side effects. + +**Parity tests:** `tests/6-validate-cjs-drift-regression.test.cjs` — 5 tests (all GREEN after fix, +all RED on pre-fix `origin/main`). Covers each drift item with concrete fixtures: +- Drift 1: two milestone archives (v1.0 old, v1.1 active); v1.0 phase absent from ROADMAP. +- Drift 2: ROADMAP "01A", disk "1A-foo" — padding mismatch. +- Drift 3: ROADMAP "3B", disk "03B-foo" — zero-padded letter-suffix mismatch. + +**Allowlist:** `scripts/shared-module-handsync-allowlist.json` — `verify.cjs` entry updated to +reference the generator and freshness check. Classification remains `cooperating-sibling` (verify.cjs +is still a full implementation; only Check 8 helpers are generated). diff --git a/get-shit-done/bin/lib/validate.generated.cjs b/get-shit-done/bin/lib/validate.generated.cjs new file mode 100644 index 000000000..4ca0a28d3 --- /dev/null +++ b/get-shit-done/bin/lib/validate.generated.cjs @@ -0,0 +1,71 @@ +'use strict'; + +/** + * GENERATED FILE — DO NOT EDIT. + * + * Source: sdk/src/query/validate.ts + * Regenerate: cd sdk && npm run gen:validate + * + * Validate Helpers — pure computation helpers for phase variant normalization, + * roadmap phase variant set construction, and unchecked-phase skip set construction. + * No I/O. No async. No filesystem operations. + * + * These three helpers cure the three drift items from issue #6: + * 1. phaseVariants() — replaces parseInt-based padded/unpadded check in verify.cjs + * Check 8 (W006 disk-existence and W007 roadmap-membership checks). + * 2. buildRoadmapPhaseVariants() — replaces raw roadmapPhases set in W007 loop. + * 3. buildNotStartedPhaseVariants() — replaces raw+zero-padded notStartedPhases + * in W006 skip logic. + * + * I/O adapter pattern (ADR-3524 §4): pure transforms extracted from the SDK. + * + * References: + * - ADR-3524 (docs/adr/3524-cjs-sdk-hard-seam.md) + * - Issue #6 (open-gsd/get-shit-done-redux) + * - PR #154 (issue #4) — generator pattern precedent + */ + +function phaseVariants(phase) { + + const variants = new Set([phase]); + const dotIdx = phase.indexOf('.'); + const head = dotIdx === -1 ? phase : phase.slice(0, dotIdx); + const tail = dotIdx === -1 ? '' : phase.slice(dotIdx); + const headMatch = head.match(/^(\d+)([A-Z]?)$/i); + if (!headMatch) + return variants; + const numericHead = headMatch[1]; + const letterSuffix = headMatch[2] || ''; + variants.add(`${String(parseInt(numericHead, 10))}${letterSuffix}${tail}`); + variants.add(`${numericHead.padStart(2, '0')}${letterSuffix}${tail}`); + return variants; + +} + +function buildRoadmapPhaseVariants(roadmapContent) { + const roadmapPhases = new Set(); + const roadmapPhaseVariants = new Set(); + const phasePattern = /#{2,4}\s*Phase\s+(\d+[A-Z]?(?:\.\d+)*)\s*:/gi; + let m; + while ((m = phasePattern.exec(roadmapContent)) !== null) { + roadmapPhases.add(m[1]); + for (const variant of phaseVariants(m[1])) roadmapPhaseVariants.add(variant); + } + return { roadmapPhases, roadmapPhaseVariants }; +} + +function buildNotStartedPhaseVariants(roadmapContent) { + const notStartedPhases = new Set(); + const uncheckedPattern = /-\s*\[\s\]\s*\*{0,2}Phase\s+(\d+[A-Z]?(?:\.\d+)*)[:\s*]/gi; + let um; + while ((um = uncheckedPattern.exec(roadmapContent)) !== null) { + for (const variant of phaseVariants(um[1])) notStartedPhases.add(variant); + } + return notStartedPhases; +} + +module.exports = { + phaseVariants, + buildRoadmapPhaseVariants, + buildNotStartedPhaseVariants, +}; diff --git a/get-shit-done/bin/lib/verify.cjs b/get-shit-done/bin/lib/verify.cjs index e83c1b9ac..338a6d4f0 100644 --- a/get-shit-done/bin/lib/verify.cjs +++ b/get-shit-done/bin/lib/verify.cjs @@ -2,6 +2,8 @@ * Verify — Verification suite, consistency, and health validation */ +const { phaseVariants, buildRoadmapPhaseVariants, buildNotStartedPhaseVariants } = require('./validate.generated.cjs'); + const fs = require('fs'); const path = require('path'); const os = require('os'); @@ -854,48 +856,63 @@ function cmdValidateHealth(cwd, options, raw) { // archive (completed + archived). forEachArchivedPhaseToken is therefore // called below to add archived dirs to diskPhases so W006 does not fire // for them. (#3652, #3806) + // + // Fix #6 (three drift items vs sdk/src/query/validate.ts Check 8): + // 1. activeDiskPhases: separate from diskPhases; only active phasesDir phases. + // W007 uses activeDiskPhases so archived phases don't produce false W007. + // 2. phaseVariants() + buildRoadmapPhaseVariants(): W006 disk-existence check + // and W007 roadmap-membership check now use full variant sets, fixing + // false W006/W007 for letter-suffix phases with padding mismatch. + // 3. buildNotStartedPhaseVariants(): replaces raw+parseInt-padded notStartedPhases + // with phaseVariants() expansion, fixing W006 unchecked-phase skip for + // zero-padded letter-suffix forms. if (fs.existsSync(roadmapPath)) { const roadmapContentRaw = fs.readFileSync(roadmapPath, 'utf-8'); const roadmapContent = extractCurrentMilestone(roadmapContentRaw, cwd); - const roadmapPhases = new Set(); - const phasePattern = /#{2,4}\s*Phase\s+(\d+[A-Z]?(?:\.\d+)*)\s*:/gi; - let m; - while ((m = phasePattern.exec(roadmapContent)) !== null) { - roadmapPhases.add(m[1]); - } + // Build roadmapPhases (raw) and roadmapPhaseVariants (all normalized variants). + // roadmapPhases: used for W006 disk-existence check (preserve original for message). + // roadmapPhaseVariants: used for W007 roadmap-membership check. + const { roadmapPhases, roadmapPhaseVariants } = buildRoadmapPhaseVariants(roadmapContent); + + // diskPhases: active phasesDir + archived milestone dirs (for W006 — archived phases + // are valid on-disk locations for historical ROADMAP phases). const diskPhases = collectDiskPhases(planBase); // Include archived milestone phase directories as valid on-disk locations. - // Mirrors forEachArchivedPhaseToken call in sdk/src/query/validate.ts - // Check 8. (#3806) + // Mirrors forEachArchivedPhaseToken call in sdk/src/query/validate.ts Check 8. (#3806) forEachArchivedPhaseToken(planBase, (token) => diskPhases.add(token)); - // Build a set of phases explicitly marked not-yet-started in the ROADMAP - // summary list (- [ ] **Phase N:**). These phases are intentionally absent - // from disk -- W006 must not fire for them (#2009). - const notStartedPhases = new Set(); - const uncheckedPattern = /-\s*\[\s\]\s*\*{0,2}Phase\s+(\d+[A-Z]?(?:\.\d+)*)[:\s*]/gi; - let um; - while ((um = uncheckedPattern.exec(roadmapContent)) !== null) { - notStartedPhases.add(um[1]); - // Also add zero-padded variant so 1 and 01 both match - notStartedPhases.add(String(parseInt(um[1], 10)).padStart(2, '0')); - } + // activeDiskPhases: only phases from the active phasesDir (NOT archived). + // Used for W007: archived phases should not trigger W007 even if absent from + // current ROADMAP (they were shipped in a prior milestone). (#6 drift item 1) + const activeDiskPhases = collectDiskPhases(planBase); - // Phases in ROADMAP but not on disk + // Build a set of all variants of phases explicitly marked not-yet-started in + // the ROADMAP summary list (- [ ] **Phase N:**). These phases are intentionally + // absent from disk — W006 must not fire for them. (#2009, #6 drift item 3) + // buildNotStartedPhaseVariants() uses phaseVariants() so zero-padded letter-suffix + // forms like "03B" are recognized even when the unchecked entry says "3B". + const notStartedPhases = buildNotStartedPhaseVariants(roadmapContent); + + // Phases in ROADMAP but not on disk (W006) + // Uses phaseVariants() for disk-existence check so "3B" matches disk dir "03B-foo". for (const p of roadmapPhases) { - const padded = String(parseInt(p, 10)).padStart(2, '0'); - if (!diskPhases.has(p) && !diskPhases.has(padded)) { + const variants = phaseVariants(p); + const existsOnDisk = [...variants].some((v) => diskPhases.has(v)); + if (!existsOnDisk) { // Skip phases explicitly flagged as not-yet-started in the summary list - if (notStartedPhases.has(p) || notStartedPhases.has(padded)) continue; + const isNotStarted = [...variants].some((v) => notStartedPhases.has(v)); + if (isNotStarted) continue; addIssue('warning', 'W006', `Phase ${p} in ROADMAP.md but no directory on disk`, 'Create phase directory or remove from roadmap'); } } - // Phases on disk but not in ROADMAP - for (const p of diskPhases) { - const unpadded = String(parseInt(p, 10)); - if (!roadmapPhases.has(p) && !roadmapPhases.has(unpadded)) { + // Phases on disk but not in ROADMAP (W007) + // Uses activeDiskPhases (no archived) and roadmapPhaseVariants (all variants) + // so neither archived phases nor padding-mismatch phases trigger false W007. + for (const p of activeDiskPhases) { + const variants = phaseVariants(p); + if (![...variants].some((v) => roadmapPhaseVariants.has(v))) { addIssue('warning', 'W007', `Phase ${p} exists on disk but not in ROADMAP.md`, 'Add to roadmap or remove directory'); } } diff --git a/package.json b/package.json index efe2d914d..84e638813 100644 --- a/package.json +++ b/package.json @@ -74,6 +74,7 @@ "check:schema-detect-fresh": "cd sdk && npm run check:schema-detect-fresh", "check:decisions-fresh": "cd sdk && npm run check:decisions-fresh", "check:workstream-name-policy-fresh": "cd sdk && npm run check:workstream-name-policy-fresh", + "check:validate-fresh": "cd sdk && npm run check:validate-fresh", "prepublishOnly": "npm run build:hooks && npm run build:sdk", "pretest": "npm run build:sdk && npm run lint:skill-deps", "pretest:coverage": "npm run build:sdk", diff --git a/scripts/shared-module-handsync-allowlist.json b/scripts/shared-module-handsync-allowlist.json index 53dadb689..83916bf73 100644 --- a/scripts/shared-module-handsync-allowlist.json +++ b/scripts/shared-module-handsync-allowlist.json @@ -72,7 +72,7 @@ "cjs": "get-shit-done/bin/lib/verify.cjs", "ts": "sdk/src/query/verify.ts", "classification": "cooperating-sibling", - "justification": "CJS verify.cjs is the full verify implementation; SDK verify.ts provides the native handler. Phase 5.2+ candidate for further delegation." + "justification": "CJS verify.cjs is the full verify implementation; SDK verify.ts provides the native handler. Phase 5.2+ candidate for further delegation. Check 8 (W006/W007) helpers now generated from sdk/src/query/validate.ts via sdk/scripts/gen-validate.mjs (issue #6); freshness check: sdk/scripts/check-validate-fresh.mjs." }, { "cjs": "get-shit-done/bin/lib/workstream.cjs", diff --git a/sdk/package.json b/sdk/package.json index 084c51908..c8b9d6d73 100644 --- a/sdk/package.json +++ b/sdk/package.json @@ -57,6 +57,8 @@ "check:decisions-fresh": "npm run build && node scripts/check-decisions-fresh.mjs", "gen:workstream-name-policy": "npm run build && node scripts/gen-workstream-name-policy.mjs", "check:workstream-name-policy-fresh": "npm run build && node scripts/check-workstream-name-policy-fresh.mjs", + "gen:validate": "npm run build && node scripts/gen-validate.mjs", + "check:validate-fresh": "npm run build && node scripts/check-validate-fresh.mjs", "prepublishOnly": "rm -rf dist && tsc && chmod +x dist/cli.js", "test": "vitest run", "test:unit": "vitest run --project unit", diff --git a/sdk/scripts/check-validate-fresh.mjs b/sdk/scripts/check-validate-fresh.mjs new file mode 100644 index 000000000..bf4c009a3 --- /dev/null +++ b/sdk/scripts/check-validate-fresh.mjs @@ -0,0 +1,41 @@ +#!/usr/bin/env node +/** + * Freshness check for validate.generated.cjs. + * + * Regenerates the expected CJS content in-memory (without writing to disk) and + * compares it to the committed file. Exits 0 if they match, 1 if stale. + * + * Uses the same pattern as check-phase-lifecycle-policy-fresh.mjs: imports + * buildValidateCjs() from the generator directly. + * + * Run: node sdk/scripts/check-validate-fresh.mjs + * (Requires sdk/dist to be built first — `npm run build` in sdk/.) + * + * References: + * - ADR-3524 (docs/adr/3524-cjs-sdk-hard-seam.md) + * - Issue #6 (open-gsd/get-shit-done-redux) + * - PR #154 (issue #4) — generator pattern precedent + */ + +import { readFile } from 'node:fs/promises'; +import { resolve, dirname } from 'node:path'; +import { fileURLToPath } from 'node:url'; + +const here = dirname(fileURLToPath(import.meta.url)); + +// Import the generator function directly (avoids duplicating logic). +const { buildValidateCjs } = await import('./gen-validate.mjs'); + +const expected = await buildValidateCjs(); + +const committedPath = resolve(here, '..', '..', 'get-shit-done', 'bin', 'lib', 'validate.generated.cjs'); +const committed = await readFile(committedPath, 'utf-8'); + +if (expected === committed) { + console.log('validate.generated.cjs is fresh'); + process.exit(0); +} else { + console.error('validate.generated.cjs is STALE.'); + console.error('Regenerate: cd sdk && npm run gen:validate'); + process.exit(1); +} diff --git a/sdk/scripts/gen-validate.mjs b/sdk/scripts/gen-validate.mjs new file mode 100644 index 000000000..947fe0c82 --- /dev/null +++ b/sdk/scripts/gen-validate.mjs @@ -0,0 +1,170 @@ +#!/usr/bin/env node +/** + * Generator for the Validate CJS artifact. + * + * Reads the compiled ESM output from sdk/dist/query/validate.js, extracts the + * pure `phaseVariants` helper function via source-text extraction (it is a + * closure inside validateHealth, not a module-level export), then emits + * get-shit-done/bin/lib/validate.generated.cjs. + * + * The generated module exports three pure helpers that were missing from + * verify.cjs (the three drift items from issue #6): + * + * 1. phaseVariants(phase) — generates all normalized variants of a phase + * token (padded/unpadded/letter-suffix). Used for W006 disk-existence check + * and W007 roadmap-membership check in verify.cjs Check 8. + * + * 2. buildRoadmapPhaseVariants(roadmapContent) — parses ROADMAP.md and builds + * the Set of all variants of all roadmap phases. Used by the W007 + * check. verify.cjs previously used only raw phase tokens (no variants). + * + * 3. buildNotStartedPhaseVariants(roadmapContent) — parses ROADMAP.md unchecked + * phase entries and builds a Set of all variants. Used for the W006 + * unchecked-phase skip. verify.cjs previously added only raw+zero-padded + * (dropping letter suffix via parseInt). + * + * Extraction approach: since phaseVariants is defined as a closure inside + * validateHealth (not a module export), it is extracted from the compiled source + * text using a brace-balanced parser — the same approach used to extract + * escapeRegex in gen-phase-lifecycle-policy.mjs. + * + * Run: cd sdk && npm run gen:validate + * Check: node sdk/scripts/check-validate-fresh.mjs + * + * References: + * - ADR-3524 (docs/adr/3524-cjs-sdk-hard-seam.md) + * - Issue #6 (open-gsd/get-shit-done-redux) + * - PR #154 (issue #4) — generator pattern precedent + */ + +import { readFile, writeFile } from 'node:fs/promises'; +import { fileURLToPath } from 'node:url'; + +export const BANNER = `'use strict'; + +/** + * GENERATED FILE — DO NOT EDIT. + * + * Source: sdk/src/query/validate.ts + * Regenerate: cd sdk && npm run gen:validate + * + * Validate Helpers — pure computation helpers for phase variant normalization, + * roadmap phase variant set construction, and unchecked-phase skip set construction. + * No I/O. No async. No filesystem operations. + * + * These three helpers cure the three drift items from issue #6: + * 1. phaseVariants() — replaces parseInt-based padded/unpadded check in verify.cjs + * Check 8 (W006 disk-existence and W007 roadmap-membership checks). + * 2. buildRoadmapPhaseVariants() — replaces raw roadmapPhases set in W007 loop. + * 3. buildNotStartedPhaseVariants() — replaces raw+zero-padded notStartedPhases + * in W006 skip logic. + * + * I/O adapter pattern (ADR-3524 §4): pure transforms extracted from the SDK. + * + * References: + * - ADR-3524 (docs/adr/3524-cjs-sdk-hard-seam.md) + * - Issue #6 (open-gsd/get-shit-done-redux) + * - PR #154 (issue #4) — generator pattern precedent + */ + +`; + +/** + * Extract phaseVariants from compiled validate.js source text. + * + * phaseVariants is defined as a const arrow function closure inside validateHealth. + * It starts with the literal `const phaseVariants = (phase) => {` and ends at the + * matching closing brace. We re-emit it as a standalone named function declaration. + */ +function extractPhaseVariantsBody(validateSource) { + const marker = 'const phaseVariants = (phase) => {'; + const start = validateSource.indexOf(marker); + if (start === -1) throw new Error('Could not find phaseVariants in compiled validate.js'); + + // Find the opening brace of the arrow function body + const braceOpen = validateSource.indexOf('{', start + marker.length - 1); + let depth = 0; + let i = braceOpen; + for (; i < validateSource.length; i++) { + if (validateSource[i] === '{') depth++; + else if (validateSource[i] === '}') { + depth--; + if (depth === 0) break; + } + } + // Extract just the body content (between the braces) + const bodyContent = validateSource.slice(braceOpen + 1, i); + + // Emit as a standalone named function so verify.cjs can require() and call it. + return `function phaseVariants(phase) {\n${bodyContent}\n}`; +} + +export async function buildValidateCjs() { + const distUrl = new URL('../dist/query/validate.js', import.meta.url); + const validateSource = await readFile(fileURLToPath(distUrl), 'utf-8'); + + const phaseVariantsBody = extractPhaseVariantsBody(validateSource); + + // buildRoadmapPhaseVariants: parse ROADMAP.md and return {roadmapPhases, roadmapPhaseVariants} + // roadmapPhases — raw phase tokens as written in headings (used for W006 check) + // roadmapPhaseVariants — all normalized variants of each roadmap phase (used for W007 check) + const buildRoadmapPhaseVariantsBody = `function buildRoadmapPhaseVariants(roadmapContent) { + const roadmapPhases = new Set(); + const roadmapPhaseVariants = new Set(); + const phasePattern = /#{2,4}\\s*Phase\\s+(\\d+[A-Z]?(?:\\.\\d+)*)\\s*:/gi; + let m; + while ((m = phasePattern.exec(roadmapContent)) !== null) { + roadmapPhases.add(m[1]); + for (const variant of phaseVariants(m[1])) roadmapPhaseVariants.add(variant); + } + return { roadmapPhases, roadmapPhaseVariants }; +}`; + + // buildNotStartedPhaseVariants: parse ROADMAP.md unchecked entries and return + // a Set of all variants of each unchecked phase (used for W006 skip logic). + const buildNotStartedPhaseVariantsBody = `function buildNotStartedPhaseVariants(roadmapContent) { + const notStartedPhases = new Set(); + const uncheckedPattern = /-\\s*\\[\\s\\]\\s*\\*{0,2}Phase\\s+(\\d+[A-Z]?(?:\\.\\d+)*)[:\\s*]/gi; + let um; + while ((um = uncheckedPattern.exec(roadmapContent)) !== null) { + for (const variant of phaseVariants(um[1])) notStartedPhases.add(variant); + } + return notStartedPhases; +}`; + + const parts = [ + BANNER.trimEnd(), + '', + phaseVariantsBody, + '', + buildRoadmapPhaseVariantsBody, + '', + buildNotStartedPhaseVariantsBody, + '', + `module.exports = { + phaseVariants, + buildRoadmapPhaseVariants, + buildNotStartedPhaseVariants, +};`, + '', + ]; + + return parts.join('\n'); +} + +async function main() { + const content = await buildValidateCjs(); + const outPath = fileURLToPath( + new URL('../../get-shit-done/bin/lib/validate.generated.cjs', import.meta.url), + ); + await writeFile(outPath, content, 'utf-8'); + console.log(`Written: ${outPath}`); +} + +// Only run main() when this file is the entry point. +if (fileURLToPath(import.meta.url) === process.argv[1]) { + main().catch((err) => { + console.error(err); + process.exit(1); + }); +} diff --git a/tests/6-validate-cjs-drift-regression.test.cjs b/tests/6-validate-cjs-drift-regression.test.cjs new file mode 100644 index 000000000..6ef7d3e2b --- /dev/null +++ b/tests/6-validate-cjs-drift-regression.test.cjs @@ -0,0 +1,304 @@ +'use strict'; + +/** + * Regression tests for issue #6 (open-gsd/get-shit-done-redux): + * Three validation behaviors present in validate.ts are missing from verify.cjs, + * producing silent false negatives on the CJS production path. + * + * Three drift items fixed by porting phaseVariants() and activeDiskPhases to verify.cjs: + * + * 1. W007 activeDiskPhases — verify.cjs uses diskPhases (includes archived) for the + * W007 check; validate.ts uses activeDiskPhases (active phasesDir only). Archived + * phases absent from current ROADMAP trigger false W007 in verify.cjs. + * + * 2. phaseVariants() normalization — validate.ts has a phaseVariants() function + * generating padded/unpadded/letter-suffix variants for matching. verify.cjs uses + * only parseInt→padded (drops letter suffix), causing false W006/W007 for + * letter-suffix phases with padding mismatch between ROADMAP and disk. + * + * 3. W006 unchecked-phase variant skip — same phaseVariants() gap causes false W006 + * for phases with padding mismatch: ROADMAP says "3B", disk has "03B-foo", but + * verify.cjs padded("3B") = "03" (drops letter) → "03B" on disk not matched. + * + * References: + * - ADR-3524 (docs/adr/3524-cjs-sdk-hard-seam.md) + * - Issue #6 (open-gsd/get-shit-done-redux) + * - PR #154 (issue #4) — precedent for the generator pattern + */ + +const { describe, test, before, after } = require('node:test'); +const assert = require('node:assert/strict'); +const fs = require('node:fs'); +const path = require('node:path'); +const os = require('node:os'); + +const { runGsdTools } = require('./helpers.cjs'); + +// ── Fixture helpers ────────────────────────────────────────────────────────── + +function mkplanning(base) { + const planningDir = path.join(base, '.planning'); + const phasesDir = path.join(planningDir, 'phases'); + fs.mkdirSync(phasesDir, { recursive: true }); + return { planningDir, phasesDir }; +} + +function writeProjectMd(planningDir) { + fs.writeFileSync( + path.join(planningDir, 'PROJECT.md'), + '# Project\n\n## What This Is\nTest.\n\n## Core Value\nTest.\n\n## Requirements\nTest.\n', + ); +} + +function writeStateMd(planningDir, phase = '2') { + fs.writeFileSync( + path.join(planningDir, 'STATE.md'), + `# State\n\n**Current Phase:** ${phase}\n**Status:** In progress\n`, + ); +} + +function writeConfigJson(planningDir) { + fs.writeFileSync( + path.join(planningDir, 'config.json'), + JSON.stringify({ model_profile: 'balanced' }), + ); +} + +// ── Drift Item 1: W007 activeDiskPhases ──────────────────────────────────── +// +// Project has a shipped milestone archive (milestones/v1.0-phases/) with old phase +// "1" inside, and active phasesDir with phase "2". Current ROADMAP only mentions +// Phase 2 (v1.0 phases were shipped and removed from ROADMAP). +// +// validate.ts: activeDiskPhases = phases from active phasesDir only (not archived). +// "1" is only in diskPhases (via forEachArchivedPhaseToken), not activeDiskPhases. +// W007 iterates activeDiskPhases → "1" never checked → no false W007. +// +// verify.cjs pre-fix: diskPhases = collectDiskPhases() + forEachArchivedPhaseToken(). +// diskPhases includes "1" (from old archive). W007 iterates diskPhases → "1" not +// in roadmapPhases → W007 fires for "1". False positive. + +describe('Drift item 1 — W007 activeDiskPhases: no false W007 for archived phases', () => { + let tmpDir; + + before(() => { + tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'gsd-6-d1-')); + const { planningDir, phasesDir } = mkplanning(tmpDir); + writeProjectMd(planningDir); + writeStateMd(planningDir); + writeConfigJson(planningDir); + + fs.writeFileSync( + path.join(planningDir, 'ROADMAP.md'), + [ + '# Roadmap', + '', + '- [x] **Phase 2:** API', + '', + '### Phase 2: API', + '', + '## Progress', + '| Phase | Status |', + '|-------|--------|', + '| 2 | Complete |', + ].join('\n'), + ); + + // Active phasesDir: only phase 2 + fs.mkdirSync(path.join(phasesDir, '2-api'), { recursive: true }); + + // Current active milestone archive: v1.1-phases contains phase 2 (in ROADMAP) + fs.mkdirSync( + path.join(planningDir, 'milestones', 'v1.1-phases', '2-api'), + { recursive: true }, + ); + + // Old shipped milestone archive: v1.0-phases contains phase 1 (no longer in ROADMAP) + // v1.0 sorts before v1.1 so getActiveMilestoneArchiveDir returns v1.1. + // forEachArchivedPhaseToken walks BOTH v1.0 and v1.1, so diskPhases gets "1". + // collectDiskPhases (activeDiskPhases) only uses v1.1 (active archive) — "1" excluded. + fs.mkdirSync( + path.join(planningDir, 'milestones', 'v1.0-phases', '1-foundation'), + { recursive: true }, + ); + }); + + after(() => { + fs.rmSync(tmpDir, { recursive: true, force: true }); + }); + + test('no W007 for archived phase "1" absent from current ROADMAP', () => { + // validate.ts: activeDiskPhases has only "2" (from active phasesDir + v1.1 archive). + // "1" is in diskPhases (forEachArchivedPhaseToken walks v1.0) but NOT activeDiskPhases. + // W007 iterates activeDiskPhases → "1" never checked → no false W007. Correct. + // verify.cjs pre-fix: diskPhases = collectDiskPhases + forEachArchivedPhaseToken. + // diskPhases includes "1" (from v1.0 archive). W007 iterates diskPhases → "1" not + // in roadmapPhases → W007 fires for "1". False positive. + const result = runGsdTools(['validate', 'health', '--json'], tmpDir); + assert.strictEqual(result.success, true, `unexpected failure: ${result.error}`); + const data = JSON.parse(result.output); + const w007 = (data.warnings ?? []).filter((w) => w.code === 'W007'); + // Filter to W007 that mentions only phase "1" (not "1A", "01A", etc.) + const w007Phase1 = w007.filter( + (w) => /\bPhase 1\b/i.test(w.message) && !/\b1[A-Z]\b/i.test(w.message), + ); + assert.strictEqual( + w007Phase1.length, + 0, + `Expected no W007 for archived phase 1 (v1.0 archive), got: ${JSON.stringify(w007)}`, + ); + }); +}); + +// ── Drift Item 2: phaseVariants() normalization ──────────────────────────── +// +// ROADMAP has "### Phase 01A:" (zero-padded letter-suffix heading). +// Disk has directory "1A-foo" (unpadded letter-suffix form). +// These should match because phaseVariants("01A") = {"01A", "1A", "01A"}. +// +// validate.ts: diskPhases has "1A". phaseVariants("01A") includes "1A" → match → no W006. +// activeDiskPhases has "1A". phaseVariants("1A") includes "01A" → roadmapPhaseVariants +// has "01A" → match → no W007. +// +// verify.cjs pre-fix: +// W006 loop for "01A": padded = String(parseInt("01A",10)).padStart(2,'0') = "01". +// diskPhases.has("01A")? NO. diskPhases.has("01")? NO. → W006 fires. Bug. +// W007 loop for "1A": unpadded = String(parseInt("1A",10)) = "1". +// roadmapPhases.has("1A")? NO. roadmapPhases.has("1")? NO. → W007 fires. Bug. + +describe('Drift item 2 — phaseVariants() normalization: letter-suffix zero-padding mismatch', () => { + let tmpDir; + + before(() => { + tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'gsd-6-d2-')); + const { planningDir, phasesDir } = mkplanning(tmpDir); + writeProjectMd(planningDir); + writeStateMd(planningDir); + writeConfigJson(planningDir); + + // ROADMAP: Phase 01A (zero-padded + letter suffix) + fs.writeFileSync( + path.join(planningDir, 'ROADMAP.md'), + [ + '# Roadmap', + '', + '- [x] **Phase 01A:** Suffix Phase', + '', + '### Phase 01A: Suffix Phase', + '', + '## Progress', + '| Phase | Status |', + '|-------|--------|', + '| 01A | Complete |', + ].join('\n'), + ); + + // Disk: unpadded form "1A-foo" + fs.mkdirSync(path.join(phasesDir, '1A-suffix-phase'), { recursive: true }); + }); + + after(() => { + fs.rmSync(tmpDir, { recursive: true, force: true }); + }); + + test('no false W006 when ROADMAP says 01A and disk has 1A-... (phaseVariants normalizes)', () => { + const result = runGsdTools(['validate', 'health', '--json'], tmpDir); + assert.strictEqual(result.success, true, `unexpected failure: ${result.error}`); + const data = JSON.parse(result.output); + const w006 = (data.warnings ?? []).filter((w) => w.code === 'W006'); + assert.strictEqual( + w006.length, + 0, + `Expected no W006 (01A == 1A after normalization), got: ${JSON.stringify(w006)}`, + ); + }); + + test('no false W007 when disk has 1A and ROADMAP says 01A (phaseVariants normalizes)', () => { + const result = runGsdTools(['validate', 'health', '--json'], tmpDir); + assert.strictEqual(result.success, true, `unexpected failure: ${result.error}`); + const data = JSON.parse(result.output); + const w007 = (data.warnings ?? []).filter((w) => w.code === 'W007'); + assert.strictEqual( + w007.length, + 0, + `Expected no W007 (1A on disk matches 01A in ROADMAP), got: ${JSON.stringify(w007)}`, + ); + }); +}); + +// ── Drift Item 3: W006 false positive when disk uses zero-padded letter form ─ +// +// ROADMAP has "### Phase 3B:" (unpadded letter-suffix heading). +// Disk has directory "03B-feature" (zero-padded letter-suffix form). +// +// validate.ts: +// diskPhases has "03B". phaseVariants("3B") = {"3B","3B","03B"}. +// existsOnDisk = diskPhases.has("03B") = TRUE → no W006. +// activeDiskPhases has "03B". phaseVariants("03B") = {"03B","3B","03B"}. +// roadmapPhaseVariants has {"3B","3B","03B"} → "03B" found → no W007. +// +// verify.cjs pre-fix: +// W006 for "3B": padded = parseInt("3B")=3 → "03" (drops "B"). +// diskPhases.has("3B")? NO. diskPhases.has("03")? NO (dir is "03B" not "03"). → W006 fires. +// W007 for "03B": unpadded = String(parseInt("03B",10)) = "3". +// roadmapPhases.has("03B")? NO. roadmapPhases.has("3")? NO (ROADMAP has "3B" not "3"). → W007. + +describe('Drift item 3 — W006 false positive when disk has zero-padded letter form', () => { + let tmpDir; + + before(() => { + tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'gsd-6-d3-')); + const { planningDir, phasesDir } = mkplanning(tmpDir); + writeProjectMd(planningDir); + writeStateMd(planningDir, '3B'); + writeConfigJson(planningDir); + + // ROADMAP: Phase 3B (unpadded in heading) + fs.writeFileSync( + path.join(planningDir, 'ROADMAP.md'), + [ + '# Roadmap', + '', + '- [x] **Phase 3B:** Feature Extension', + '', + '### Phase 3B: Feature Extension', + '', + '## Progress', + '| Phase | Status |', + '|-------|--------|', + '| 3B | Complete |', + ].join('\n'), + ); + + // Disk: "03B-feature" (zero-padded letter-suffix form) + fs.mkdirSync(path.join(phasesDir, '03B-feature'), { recursive: true }); + }); + + after(() => { + fs.rmSync(tmpDir, { recursive: true, force: true }); + }); + + test('no false W006 when ROADMAP says 3B and disk has 03B-... (phaseVariants covers zero-padded)', () => { + const result = runGsdTools(['validate', 'health', '--json'], tmpDir); + assert.strictEqual(result.success, true, `unexpected failure: ${result.error}`); + const data = JSON.parse(result.output); + const w006 = (data.warnings ?? []).filter((w) => w.code === 'W006'); + assert.strictEqual( + w006.length, + 0, + `Expected no W006 (3B == 03B after normalization), got: ${JSON.stringify(w006)}`, + ); + }); + + test('no false W007 when disk has 03B and ROADMAP says 3B (phaseVariants covers both forms)', () => { + const result = runGsdTools(['validate', 'health', '--json'], tmpDir); + assert.strictEqual(result.success, true, `unexpected failure: ${result.error}`); + const data = JSON.parse(result.output); + const w007 = (data.warnings ?? []).filter((w) => w.code === 'W007'); + assert.strictEqual( + w007.length, + 0, + `Expected no W007 (03B on disk matches 3B in ROADMAP), got: ${JSON.stringify(w007)}`, + ); + }); +});