Files
msd-core/sdk/scripts/check-state-document-fresh.mjs
Tom Boucher bfd7ddbad3 feat(3530): STATE.md Document Module via generator (Phase 1 of #3524) (#3531)
* feat(3530): STATE.md Document Module via generator (Phase 1 of #3524)

Phase 1 of the CJS↔SDK hard-seam migration (parent #3524).
Converts the hand-synced state-document.cjs/state-document.ts pair
into a generator-driven seam, modeled on the existing
command-aliases.generated.* precedent.

What landed:
- sdk/src/query/state-document.ts is the source of truth.
- sdk/scripts/gen-state-document.ts emits
  get-shit-done/bin/lib/state-document.generated.cjs from the
  compiled SDK dist via Function.prototype.toString() inspection
  for the 7 public exports and 3 internal helpers.
- sdk/scripts/check-state-document-fresh.mjs is the CI freshness
  gate; pre-commit hook also runs it when relevant files change.
- get-shit-done/bin/lib/state-document.cjs is reduced to a one-line
  re-export from state-document.generated.cjs so existing callers
  (state.cjs, workstream-inventory.cjs, init.cjs) need no changes.
- New CI step in .github/workflows/test.yml after the existing alias
  drift check.
- sdk/package.json: gen:state-document, check:state-document-fresh
  scripts. tsx added as devDep.
- Root package.json: proxy script for the freshness check.
- CONTEXT.md: one-sentence amendment on STATE.md Document Module
  recording the source-of-truth file path.

Tests:
- sdk/src/query/state-document.test.ts: 34 vitest fixtures across
  the 7 public exports (TDD pinning safety net).
- tests/state-document-generator.test.cjs: 31 node:test parity
  assertions comparing SDK source vs generated CJS for every
  fixture.
- Full suite: 9177/9177 pass (baseline was 9146; +31 new tests).

One subtle behavior change worth flagging: the old hand-written
state-document.cjs used String(str) coercion inside escapeRegex,
which the SDK source does not. The generator faithfully matches
the SDK (the source of truth per ADR-3524), so the new CJS no
longer coerces non-string input to string before regex-escaping.
No current caller passes non-string input, so no observable
regression in the test suite. Flagged in the PR body for
reviewers.

Closes #3530.

* fix(3530): address state-document review findings
2026-05-14 22:17:20 -04:00

115 lines
3.9 KiB
JavaScript

#!/usr/bin/env node
/**
* Freshness check for state-document.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.
*
* Run: node sdk/scripts/check-state-document-fresh.mjs
* (Requires sdk/dist to be built first — `npm run build` in sdk/.)
*/
import { readFile } from 'node:fs/promises';
import { resolve, dirname } from 'node:path';
import { fileURLToPath } from 'node:url';
const here = dirname(fileURLToPath(import.meta.url));
const BANNER = `'use strict';
/**
* GENERATED FILE — DO NOT EDIT.
*
* Source: sdk/src/query/state-document.ts
* Regenerate: cd sdk && npm run gen:state-document
*
* STATE.md Document Module — pure transforms for STATE.md text.
* This module does not read the filesystem and does not own persistence or locking.
*/`;
/**
* Extract a top-level function declaration (non-exported) from a JS source
* string by scanning for `function <name>(` and capturing the entire body
* including balanced braces.
*/
function extractFunctionFromSource(source, name) {
const marker = `function ${name}(`;
const start = source.indexOf(marker);
if (start === -1) throw new Error(`Could not find function ${name} in compiled source`);
const braceOpen = source.indexOf('{', start);
if (braceOpen === -1) throw new Error(`Could not find opening brace for function ${name}`);
let depth = 0;
let i = braceOpen;
for (; i < source.length; i++) {
if (source[i] === '{') depth++;
else if (source[i] === '}') { depth--; if (depth === 0) break; }
}
if (depth !== 0) {
throw new Error(`Could not find closing brace for function ${name}`);
}
return source.slice(start, i + 1);
}
const distUrl = new URL('../dist/query/state-document.js', import.meta.url);
const {
stateExtractField,
stateReplaceField,
stateReplaceFieldWithFallback,
normalizeStateStatus,
computeProgressPercent,
shouldPreserveExistingProgress,
normalizeProgressNumbers,
} = await import(distUrl.href);
const compiledSource = await readFile(fileURLToPath(distUrl), 'utf-8');
const escapeRegexBody = extractFunctionFromSource(compiledSource, 'escapeRegex');
const toFiniteNumberBody = extractFunctionFromSource(compiledSource, 'toFiniteNumber');
const existingProgressExceedsDerivedBody = extractFunctionFromSource(compiledSource, 'existingProgressExceedsDerived');
const stateExtractFieldBody = stateExtractField.toString();
const stateReplaceFieldBody = stateReplaceField.toString();
const stateReplaceFieldWithFallbackBody = stateReplaceFieldWithFallback.toString();
const normalizeStateStatusBody = normalizeStateStatus.toString();
const computeProgressPercentBody = computeProgressPercent.toString();
const shouldPreserveExistingProgressBody = shouldPreserveExistingProgress.toString();
const normalizeProgressNumbersBody = normalizeProgressNumbers.toString();
const expected = [
BANNER,
'',
'// Internal helpers',
escapeRegexBody,
'',
toFiniteNumberBody,
'',
existingProgressExceedsDerivedBody,
'',
stateExtractFieldBody,
'',
stateReplaceFieldBody,
'',
stateReplaceFieldWithFallbackBody,
'',
normalizeStateStatusBody,
'',
computeProgressPercentBody,
'',
shouldPreserveExistingProgressBody,
'',
normalizeProgressNumbersBody,
'',
'module.exports = { stateExtractField, stateReplaceField, stateReplaceFieldWithFallback, normalizeStateStatus, computeProgressPercent, shouldPreserveExistingProgress, normalizeProgressNumbers };',
'',
].join('\n');
const committedPath = resolve(here, '..', '..', 'get-shit-done', 'bin', 'lib', 'state-document.generated.cjs');
const committed = await readFile(committedPath, 'utf-8');
if (expected === committed) {
console.log('state-document.generated.cjs is fresh');
process.exit(0);
} else {
console.error('state-document.generated.cjs is STALE.');
console.error('Regenerate: cd sdk && npm run gen:state-document');
process.exit(1);
}