* fix(#2969): deterministic Step 5 verification gate for /gsd-reapply-patches The prior Step 5 "Hunk Verification Gate" was prescribed correctly in the workflow text — but executed laxly by the LLM, which filled in `verified: yes` without actually checking content presence. The reporter observed three distinct files (skills/gsd-discuss-phase/SKILL.md, skills/gsd-autonomous/ SKILL.md, get-shit-done/workflows/new-project.md) where archives contained substantive user-added blocks that did not survive into the merged result, yet the gate reported clean. Move verification from LLM-driven prose into a deterministic Node script the workflow calls. The script can't be shortcut. Changes: - scripts/verify-reapply-patches.cjs (new): pure Node, no external deps. For each file in the patches dir, computes user-added significant lines as the line-set diff between backup and pristine baseline (when available; falls back to "every significant backup line" when no pristine — over-broad but the safe direction for this bug class). Asserts each line appears literally in the merged installed file via String.prototype.includes. Filters trivial lines (length < 12 chars, pure punctuation, decorative comments) so harmless drift doesn't trigger false failures. Exits 0 on pass, 1 on any miss with per-file diagnostic, 2 on usage error. Supports --json for workflow consumption. - get-shit-done/workflows/reapply-patches.md: rewrite Step 5 to call the script and parse its JSON output. The Step 4 Hunk Verification Table remains as advisory Claude-readable summary, but the gate is now the script's exit code. - tests/bug-2969-verify-reapply-patches.test.cjs (new): 6 tests covering (a) pass when every line survives, (b) fail when a line is missing, (c) fail when the merged file is deleted entirely, (d) --json structured report shape, (e) backup-meta.json is correctly skipped as metadata, (f) no-pristine-dir fallback exercises the safe over-broad path. All pass. Out of scope: the manifest-baseline tightening described in #2969 Failure 1 (saveLocalPatches comparing against the wrong baseline so prior silent wipes poison subsequent updates). That's a separate, bigger architectural change involving pristine-content infrastructure; this PR addresses the gate fidelity half so users at least see the diagnostic when content goes missing. Closes #2969 (partial — Failure 2 only) * fix(#2969): preserve #1999 Hunk Verification Table assertions alongside new script gate CI failure on PR #2972 surfaced that tests/reapply-patches.test.cjs (the #1999 contract) asserts Step 5 references: - "Hunk Verification Table" - `verified: no` failure condition - explicit STOP/halt/abort directive - "table absent / missing" halt path My initial Step 5 rewrite for #2969 substituted the deterministic script for the table-based gate entirely, stripping those references. The script is the strictly stronger gate, but the existing #1999 test enforces the table-based safety net as a defense-in-depth contract. Restore both gates as a layered Step 5: - 5a (binding): deterministic verifier script — script gate, exits non-zero on any miss, cannot be shortcut by the LLM - 5b (advisory): Hunk Verification Table review — preserved as redundant safety net for the case where the script has a bug or the pristine baseline is unavailable Both gates must pass. Verified: tests/reapply-patches.test.cjs (5 tests in the #1999 suite) and tests/bug-2969-verify-reapply-patches.test.cjs (6 tests in the #2969 suite) all pass — 21/21 total in this fixture. * fix(#2969): address CodeRabbit findings on workflow + script Five CR findings on PR #2972, all valid; addressed in this commit: 1. (Major) Stderr was merged into VERIFY_OUTPUT via `2>&1`, so any Node warning, deprecation notice, or stack trace would corrupt the JSON parse downstream. Capture stdout only; stderr remains on the controlling terminal for operator visibility. 2. (Major) verifyFile() crashed with EISDIR/EACCES instead of producing a structured diagnostic when the installed path was a directory or unreadable. Wrap statSync/readFileSync in try/catch and emit a per-file fail row; the whole-run gate continues with structured output. Added test case asserting the directory-at-installed-path case fails with `not a regular file` diagnostic instead of crashing. 3. (Minor) PRISTINE_FLAG built as a single string + unquoted expansion would split paths with spaces. Switched to a bash array (VERIFY_ARGS) that preserves whitespace through expansion. 4. (Minor) Fenced code block missing language tag (markdownlint MD040). Added `text` tag to the error message block. 5. (Minor) Usage comment said pristine fallback was "backup-meta lookup" but the actual code path falls back to significant-line checks from backup content. Corrected the comment to match implementation. Verified all 21 tests in tests/reapply-patches.test.cjs (#1999 contract) + tests/bug-2969-verify-reapply-patches.test.cjs (now 7 tests with the new directory case) pass. * test(#2969): structured JSON assertions, no substring matching on script output Replace every assert.match(r.stdout, /pattern/) call with structured assertions on the parsed JSON report from the script's own --json mode. The script's --json contract IS the structured shape we test against — the test author should never depend on the human-readable formatter output, just as no test should depend on substring presence in source. Changes: - All 7 tests now run the verifier with --json (via a runVerifier() helper) and parse the resulting JSON document into { status, report, stderr }. Diagnostic stderr is preserved as a separate channel for debug output but is not used for assertions. - Each previously substring-matched diagnostic ("Failures: 1", "not a regular file", "installed file missing after merge", file path, dropped line) is now a deepEqual / equal / Array.includes against typed report fields: report.failures, report.results[i].status, report.results[i].reason, report.results[i].file, report.results[i].missing[]. - Added an explicit "documented shape" test asserting the JSON output has exactly the keys { file, missing, reason, status } per result — locks the public contract of the --json mode. - DRY'd up fixture reset into a resetFixture() helper since every test starts with a fresh patches/installed/pristine triple. Linter: scripts/lint-no-source-grep.cjs reports 0 violations across 348 test files. Combined run of bug-2969-...test.cjs (7 tests) + reapply-patches.test.cjs (5 tests in the #1999 suite) all pass — 22/22 in the relevant fixture. * fix(#2969): typed REASON enum + raw-text-matching rule shipped repo-wide This commit closes the loop on the no-source-grep discipline: 1. scripts/verify-reapply-patches.cjs: - Frozen REASON enum exposes the diagnostic surface as stable codes: OK_NO_USER_LINES_VS_PRISTINE, OK_NO_SIGNIFICANT_BACKUP_LINES, FAIL_INSTALLED_MISSING, FAIL_INSTALLED_NOT_REGULAR_FILE, FAIL_READ_ERROR, FAIL_USER_LINES_MISSING. - Each result.reason is now a code from this enum, not free text. Tests assert via REASON.X equality, not regex on prose. - REASON exported from module.exports. 2. tests/bug-2969-verify-reapply-patches.test.cjs: - Full rewrite. Every assertion on typed structured fields: report.results[0].status === 'fail', report.results[0].reason === REASON.FAIL_INSTALLED_NOT_REGULAR_FILE, report.results[0].missing.includes(droppedLine) (Array set membership, not String substring). - Locks the REASON enum surface via Object.keys(REASON).sort() deepEqual. - Locks the JSON report shape via Object.keys(report).sort() deepEqual. - Zero regex, zero String#includes, zero startsWith/endsWith on text. 3. CONTRIBUTING.md: - New section "Prohibited: Raw Text Matching on Test Outputs" with concrete BAD/GOOD examples (substring on file content; assert.match on stdout; "structured parser" hiding string ops; regex on free-form reason fields). - The rule statement: "Tests assert on typed structured values. If the code under test produces text, the code under test must also expose a structured intermediate representation, and the test must assert on that IR — never on the rendered text." - Required structured-surface table: file IR, --json mode, frozen enum, fs facts. - "Hiding grep behind a function is still grep" callout — the parser-wrapper anti-pattern. - New `pre-existing-text-matching` exemption category for the 8 grandfathered files. Marked Transitional; new tests cannot use it. 4. scripts/lint-no-source-grep.cjs: - Three new patterns enforced (in addition to the existing .cjs-source readFileSync rule): - assert.match/doesNotMatch on .stdout/.stderr - .stdout/.stderr.<includes|startsWith|endsWith>( - readFileSync(...).<includes|startsWith|endsWith>( - Aggregated violations per file (multiple findings now report together). - Updated diagnostic message references both CONTRIBUTING.md sections. 5. 8 pre-existing tests annotated with `// allow-test-rule: pre-existing-text-matching` so the lint passes on this commit; each carries the prose "Tracked for migration to typed-IR assertions; do not copy this pattern." Files: bug-2649, bug-2687, bug-2796, bug-2838, bug-2943, graphify, hooks-opt-in, security-scan. Verification: lint 0 violations across 348 test files; full suite passes. * fix(#2969): rename exemption category to pending-migration-to-typed-ir + cite tracking issue Per maintainer feedback: 1. "Grandfathered" / "legacy" framing is wrong — both terms imply permanent or condoned exemption. The 8 files are tracked for correction, not exempted. 2. Each annotated file must cite the tracking issue so the migration work is auditable. Changes: - CONTRIBUTING.md: rename exemption category from `pre-existing-text-matching` to `pending-migration-to-typed-ir`. Update prose to "Tracked for correction, not exempted" and require each annotation to cite the open migration issue (e.g. `// allow-test-rule: pending-migration-to-typed-ir [#NNNN]`). - 8 test files: update annotation to cite #2974 (the tracking issue opened for migrating these files to typed-IR assertions).
153 lines
6.0 KiB
JavaScript
153 lines
6.0 KiB
JavaScript
#!/usr/bin/env node
|
|
/**
|
|
* lint-no-source-grep.cjs
|
|
*
|
|
* Enforces the "no source-grep tests" rule:
|
|
* Tests must NOT read source-code .cjs files with readFileSync to assert string
|
|
* presence. That pattern (source-grep theater) proves a literal exists in source,
|
|
* not that the runtime behavior is correct.
|
|
*
|
|
* ALLOWED:
|
|
* - require('../get-shit-done/bin/lib/foo.cjs') -- runs the module, not text inspection
|
|
* - readFileSync on .md / .json / .txt files -- product-content or config output
|
|
* - Files annotated: // allow-test-rule: <reason>
|
|
*
|
|
* DISALLOWED (without allow-test-rule):
|
|
* - readFileSync where the path argument ends in a .cjs filename literal
|
|
* - A path constant (e.g. CONFIG_PATH) assigned to a .cjs lib file, used in readFileSync
|
|
*
|
|
* Exit 0 = clean. Exit 1 = violations found (with diagnostics).
|
|
*/
|
|
|
|
'use strict';
|
|
|
|
const fs = require('fs');
|
|
const path = require('path');
|
|
|
|
const TESTS_DIR = path.join(__dirname, '..', 'tests');
|
|
const ALLOW_ANNOTATION = /\/\/\s*allow-test-rule:\s*\S/;
|
|
|
|
// Matches constant definitions that hold a .cjs path in a SOURCE directory.
|
|
// Requires a source-dir indicator ('bin', 'lib', 'get-shit-done') to avoid
|
|
// flagging temp files like path.join(tmpDir, 'example.cjs').
|
|
// const CONFIG_PATH = path.join(__dirname, '..', 'get-shit-done', 'bin', 'lib', 'config-schema.cjs');
|
|
const CJS_PATH_CONST_RE = /(?:const|let|var)\s+(\w+)\s*=\s*path\.join\s*\([^)]*(?:'bin'|"bin"|'lib'|"lib"|'get-shit-done'|"get-shit-done")[^)]*['"][^'"]*\.cjs['"]/gm;
|
|
|
|
// Matches readFileSync with a named variable as first arg
|
|
const READ_WITH_CONST_RE = /readFileSync\s*\(\s*([A-Za-z_][A-Za-z0-9_]*)\s*,/gm;
|
|
|
|
// Matches readFileSync with an inline path.join(.cjs) as first arg
|
|
const READ_WITH_INLINE_CJS_RE = /readFileSync\s*\([^,)]*path\.join\s*\([^)]*(?:'bin'|"bin"|'lib'|"lib"|'get-shit-done'|"get-shit-done")[^)]*['"][^'"]*\.cjs['"]/;
|
|
|
|
/**
|
|
* #2962-class violations: raw text matching against process output or file
|
|
* content. The rule from CONTRIBUTING.md "Prohibited: Raw Text Matching on
|
|
* Test Outputs": tests assert on typed structured fields, never on rendered
|
|
* text. Patterns below are the obvious anti-patterns; subtler hidden forms
|
|
* (e.g. wrapping the same logic in a parser function) are still forbidden
|
|
* by the prose rule but cannot be detected lexically without an AST.
|
|
*/
|
|
const RAW_MATCH_PATTERNS = [
|
|
{
|
|
re: /assert\.(?:match|doesNotMatch)\s*\(\s*[A-Za-z_$][A-Za-z0-9_$]*\.(?:stdout|stderr)\b/,
|
|
label: 'assert.match/doesNotMatch on .stdout/.stderr (emit --json from the SUT and assert on typed fields)',
|
|
},
|
|
{
|
|
re: /\.(?:stdout|stderr)\.(?:includes|startsWith|endsWith)\s*\(/,
|
|
label: '.stdout/.stderr substring match (emit --json and assert on typed fields)',
|
|
},
|
|
{
|
|
re: /readFileSync\s*\([^)]*\)\s*\.(?:includes|startsWith|endsWith)\s*\(/,
|
|
label: 'readFileSync(...).<includes|startsWith|endsWith> (expose an IR from production code; assert on its fields)',
|
|
},
|
|
];
|
|
|
|
function setFromMatches(content, re) {
|
|
const found = new Set();
|
|
let m;
|
|
const cloned = new RegExp(re.source, re.flags);
|
|
while ((m = cloned.exec(content)) !== null) found.add(m[1]);
|
|
return found;
|
|
}
|
|
|
|
function check(filepath) {
|
|
const content = fs.readFileSync(filepath, 'utf-8');
|
|
const rel = path.relative(path.join(__dirname, '..'), filepath);
|
|
|
|
if (ALLOW_ANNOTATION.test(content)) return null;
|
|
|
|
const violations = [];
|
|
|
|
// Pattern A: readFileSync(path.join(..., 'foo.cjs'), ...)
|
|
if (READ_WITH_INLINE_CJS_RE.test(content)) {
|
|
violations.push({
|
|
reason: 'readFileSync with inline .cjs path literal',
|
|
fix: 'Replace with runGsdTools() behavioral test, or add // allow-test-rule: <reason>',
|
|
});
|
|
}
|
|
|
|
// Pattern B: const FOO_PATH = path.join(..., 'foo.cjs') + readFileSync(FOO_PATH, ...)
|
|
const cjsConsts = setFromMatches(content, CJS_PATH_CONST_RE);
|
|
if (cjsConsts.size > 0) {
|
|
const readConsts = setFromMatches(content, READ_WITH_CONST_RE);
|
|
const overlap = [...cjsConsts].filter(c => readConsts.has(c));
|
|
if (overlap.length > 0) {
|
|
violations.push({
|
|
reason: `source .cjs path constant(s) used in readFileSync: ${overlap.join(', ')}`,
|
|
fix: 'Replace with runGsdTools() behavioral test, or add // allow-test-rule: <reason>',
|
|
});
|
|
}
|
|
}
|
|
|
|
// Patterns C..E: raw text matching against process output or file content.
|
|
// See CONTRIBUTING.md "Prohibited: Raw Text Matching on Test Outputs".
|
|
for (const { re, label } of RAW_MATCH_PATTERNS) {
|
|
if (re.test(content)) {
|
|
violations.push({
|
|
reason: label,
|
|
fix: 'Expose typed IR from production code; assert on structured fields. Or add // allow-test-rule: <reason>',
|
|
});
|
|
}
|
|
}
|
|
|
|
if (violations.length === 0) return null;
|
|
return { file: rel, violations };
|
|
}
|
|
|
|
function findTestFiles(dir) {
|
|
const results = [];
|
|
for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
|
|
const full = path.join(dir, entry.name);
|
|
if (entry.isDirectory()) {
|
|
results.push(...findTestFiles(full));
|
|
} else if (entry.name.endsWith('.test.cjs')) {
|
|
results.push(full);
|
|
}
|
|
}
|
|
return results;
|
|
}
|
|
|
|
const testFiles = findTestFiles(TESTS_DIR);
|
|
|
|
const violations = testFiles.map(check).filter(Boolean);
|
|
|
|
if (violations.length === 0) {
|
|
console.log(`ok lint-no-source-grep: ${testFiles.length} test files checked, 0 violations`);
|
|
process.exit(0);
|
|
}
|
|
|
|
const totalIssues = violations.reduce((n, v) => n + v.violations.length, 0);
|
|
process.stderr.write(`\nERROR lint-no-source-grep: ${totalIssues} violation(s) across ${violations.length} file(s)\n\n`);
|
|
for (const f of violations) {
|
|
process.stderr.write(` ${f.file}\n`);
|
|
for (const v of f.violations) {
|
|
process.stderr.write(` Problem : ${v.reason}\n`);
|
|
process.stderr.write(` Fix : ${v.fix}\n`);
|
|
}
|
|
process.stderr.write('\n');
|
|
}
|
|
process.stderr.write('See CONTRIBUTING.md "Prohibited: Source-Grep Tests" and\n');
|
|
process.stderr.write('"Prohibited: Raw Text Matching on Test Outputs" for guidance.\n');
|
|
process.stderr.write('Structural tests that legitimately read source files: add // allow-test-rule: <reason>\n\n');
|
|
process.exit(1);
|