diff --git a/.github/workflows/pr-checks.yml b/.github/workflows/pr-checks.yml index 3041409..4635928 100644 --- a/.github/workflows/pr-checks.yml +++ b/.github/workflows/pr-checks.yml @@ -34,6 +34,8 @@ jobs: uses: actions/checkout@v6 with: persist-credentials: false + # The regrowth check compares the change with its merge base. + fetch-depth: 0 - name: Setup Bun uses: oven-sh/setup-bun@v2 @@ -60,6 +62,14 @@ jobs: - name: Lint (shrink-only baseline) run: bun run lint + # Judges only what this pull request adds: no comment the codemod's + # narrow pass would remove, and no report-style markdown outside .plans/ + # and docs/. + - name: No regrowth of purged comments or report markdown + env: + REGROWTH_BASE_REF: origin/${{ github.base_ref }} + run: bun scripts/quality/check-regrowth.mjs + - name: Build website run: bun run build:website diff --git a/AGENTS.md b/AGENTS.md index 6c8a331..f99521d 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -67,6 +67,7 @@ Each rule names what enforces it. "Review only" means nothing fails automaticall | Changes to critical and sensitive paths follow the merge tiers; agent-image changes wait for afo's go | review only (no merge gate check) | `.agents/merge-policy.json` | | Website CSS uses `--gp-*` tokens and the Modern CSS Standard; the source baseline only shrinks | `ui:check` in CI `PR checks`; `--write-source-baseline` refuses new entries | `scripts/ui-verify.ts`, `scripts/ui-source-baseline.test.ts` | | No new lint finding: oxlint, wrap-once, Biome formatting | CI `PR checks` (`bun run lint`) against a shrink-only baseline | `scripts/lint/run.mjs`, `.agents/lint-baseline.json` | +| No new banner, label, commented-out code or name-restating comment in package source or `scripts/`; no report-style markdown outside `.plans/` and `docs/`, and no other new markdown outside those, the guidance folders and conventional names such as README.md | CI `PR checks` (judges only added lines and files) | `scripts/quality/check-regrowth.mjs`, `scripts/quality/comment-policy.mjs` | | Every migration applies to a fresh Postgres, reruns skip, and the database proofs pass; no two new migrations share a prefix | CI `Database proofs` | `.github/workflows/database-proofs.yml`, `scripts/migration-prefixes.test.ts` | | Greenpill-owned migrations live only in `packages/agent/migrations`; Directus is never the public API; the website stays static | review only | this file | | Install or upgrade no dependency without approval in the current task | review only | this file | diff --git a/scripts/quality/check-regrowth.mjs b/scripts/quality/check-regrowth.mjs new file mode 100644 index 0000000..e9b5f64 --- /dev/null +++ b/scripts/quality/check-regrowth.mjs @@ -0,0 +1,204 @@ +#!/usr/bin/env node +// Stops two kinds of text the purge removed from growing back, judged only on what a change adds: +// +// - Comments the comment codemod's narrow pass removes (banners, commented-out code, labels and +// notes that restate a name) on added lines of package source (`packages/*/src`) and +// `scripts/`. Test, spec, story and mock files are not judged; database proofs and browser +// smoke scripts are, like any other script. +// The codemod decides, so a comment whose place carries its meaning stays allowed. +// - New markdown that reads as a report (an audit, findings, a summary, a dated note) anywhere +// outside `.plans/` and `docs/`, and any other new markdown outside those folders, the guidance +// folders and the conventional names (README.md, AGENTS.md and the like). +// +// Existing text is not judged: a file is compared with the merge base, so only its added lines +// and added files count. +// +// node scripts/quality/check-regrowth.mjs [--base ] +// +// CI names its base in REGROWTH_BASE_REF; when that does not resolve the check fails rather than +// judge nothing. +import { existsSync, readFileSync } from 'node:fs'; +import path from 'node:path'; +import { fileURLToPath } from 'node:url'; +import { parseBaseArgs, resolveGitBase, runGit } from '../lib/git-guardrails.mjs'; +import { purgeSource } from './comment-policy.mjs'; + +const repoRoot = path.resolve(fileURLToPath(new URL('../..', import.meta.url))); + +// Package source and the repository's scripts, Astro components included. +const PACKAGE_SOURCE = /^(packages\/[^/]+\/src\/.+|scripts\/.+)\.(ts|tsx|js|jsx|mjs|cjs|mts|cts|sol|astro)$/; +const TEST_PATH = /(^|\/)(__tests__|__mocks__|test|tests)\/|\.(test|spec|stories)\.([cm]?[jt]sx?|astro)$/; +const GENERATED = /\.d\.[cm]?ts$|(^|\/)(generated|vendor|dist)\/|\.generated\./; + +const MARKDOWN = /\.(md|mdx)$/i; +const MARKDOWN_HOMES = ['.plans/', 'docs/']; +const GUIDANCE_FOLDERS = ['.claude/', '.agents/', '.codex/', '.github/']; +// A skill's references are its templates, a report template included. +const SKILL_FOLDERS = ['.claude/skills/', '.agents/skills/']; +const CONVENTIONAL_NAMES = + /^(README|AGENTS|CLAUDE|DESIGN[\w.-]*|SKILL|ARCHITECTURE|CHANGELOG|MODULES|CONTRIBUTING|SECURITY|CODE_OF_CONDUCT|LICENSES?)\.mdx?$/i; +const REPORT_NAME = + /(^|[-_.\s])(report|reports|audit|audits|findings|summary|analysis|handoff|handover|retro|retrospective|postmortem|investigation|status|notes)([-_.\s]|$)|\d{4}-\d{2}-\d{2}/i; + +export function isPackageSource(file) { + return PACKAGE_SOURCE.test(file) && !TEST_PATH.test(file) && !GENERATED.test(file); +} + +/** Why a new markdown file may not be added where it is, or null when it may. */ +export function markdownProblem(file) { + if (!MARKDOWN.test(file)) return null; + if ([...MARKDOWN_HOMES, ...SKILL_FOLDERS].some((home) => file.startsWith(home))) return null; + const name = path.posix.basename(file); + if (REPORT_NAME.test(name.replace(MARKDOWN, ''))) { + return "reads as a report; reports belong in the plan's hub under .plans/, or in Linear"; + } + if (GUIDANCE_FOLDERS.some((folder) => file.startsWith(folder))) return null; + if (CONVENTIONAL_NAMES.test(name)) return null; + return 'is new markdown outside .plans/ and docs/; put documentation in docs/ and plan notes in their hub'; +} + +/** Line numbers (1-based, in the new file) that a unified diff with no context adds. */ +export function addedLines(diff) { + const lines = new Set(); + for (const match of diff.matchAll(/^@@ -\d+(?:,\d+)? \+(\d+)(?:,(\d+))? @@/gm)) { + const start = Number(match[1]); + const count = match[2] === undefined ? 1 : Number(match[2]); + for (let line = start; line < start + count; line += 1) lines.add(line); + } + return lines; +} + +// Counted as git counts lines, so a line number matches the diff's. +function lineOf(code, index) { + return code.slice(0, index).split('\n').length; +} + +/** + * The comments the narrow purge would remove that hold a line the change added, so a line added + * inside or below an existing comment counts even when the comment starts on an old line. + */ +export function regrownComments(code, file, added) { + const holdsAddedLine = (comment) => { + if (added === 'all') return true; + const last = lineOf(code, Math.max(comment.start, comment.end - 1)); + for (let line = lineOf(code, comment.start); line <= last; line += 1) if (added.has(line)) return true; + return false; + }; + return purgeSource(code, file) + .removed.filter(holdsAddedLine) + .map((comment) => ({ + line: lineOf(code, comment.start), + kind: comment.kind, + text: code.slice(comment.start, comment.end), + })); +} + +/** + * Paths the change adds or modifies, committed and uncommitted work and untracked files too, as + * `{ how, from }`: a rename or copy is judged against the file it came from, so a move adds nothing. + */ +export function changedPaths(root, ref) { + const entries = new Map(); + const status = runGit(root, ['diff', '--name-status', '-M', '-z', ref]).stdout.split('\0').filter(Boolean); + for (let index = 0; index < status.length; ) { + const how = status[index][0]; + if (how === 'R' || how === 'C') { + entries.set(status[index + 2], { how, from: status[index + 1] }); + index += 3; + } else { + entries.set(status[index + 1], { how, from: null }); + index += 2; + } + } + const untracked = runGit(root, ['ls-files', '--others', '--exclude-standard', '-z']) + .stdout.split('\0') + .filter(Boolean); + for (const file of untracked) entries.set(file, { how: 'A', from: null }); + return entries; +} + +export function judge(root, ref) { + const problems = []; + let sourceFiles = 0; + for (const [file, { how, from }] of changedPaths(root, ref)) { + if (how === 'D') continue; + // A move lands markdown somewhere new, unless the file was already where it may not be. + if (how === 'A' || (from && !markdownProblem(from))) { + const problem = markdownProblem(file); + if (problem) problems.push(`${file}: ${problem}.`); + } + if (!isPackageSource(file)) continue; + const absolute = path.join(root, file); + if (!existsSync(absolute)) continue; + sourceFiles += 1; + const code = readFileSync(absolute, 'utf8'); + // Whitespace is ignored, so re-indenting old comments (wrapping code in a block) adds none. + // `--text` and no diff drivers keep `.gitattributes` from hiding hunks, and literal pathspecs + // keep a route like `[slug].astro` from matching other files. + // A file that arrives from outside the judged scope brings all its comments with it. + const paths = from ? [from, file] : [file]; + const added = + how === 'A' || (from && !isPackageSource(from)) + ? 'all' + : addedLines( + runGit(root, [ + '--literal-pathspecs', + 'diff', + '-U0', + '-w', + '-M', + '--text', + '--no-ext-diff', + '--no-textconv', + '--no-color', + ref, + '--', + ...paths, + ]).stdout, + ); + let comments; + try { + comments = regrownComments(code, file, added); + } catch (error) { + problems.push(`${file}: could not be parsed for comments (${error.message}).`); + continue; + } + for (const comment of comments) { + const shown = comment.text.split(/\r?\n/)[0].slice(0, 100); + problems.push(`${file}:${comment.line}: new ${comment.kind} comment, which the purge removed: ${shown}`); + } + } + return { problems, sourceFiles }; +} + +function main(argv = process.argv.slice(2)) { + const explicitBase = parseBaseArgs(argv).base; + const base = resolveGitBase({ repoRoot, explicitBase, environmentVariables: ['REGROWTH_BASE_REF'] }); + const required = explicitBase ?? process.env.REGROWTH_BASE_REF; + if (!base || (required && base !== required)) { + console.error( + `regrowth: the base ${required ?? 'origin/main'} is not available, so nothing can be compared with it`, + ); + return 2; + } + const ref = runGit(repoRoot, ['merge-base', 'HEAD', base], { allowFailure: true }).stdout.trim() || base; + const { problems, sourceFiles } = judge(repoRoot, ref); + for (const problem of problems) console.error(`regrowth: ${problem}`); + if (problems.length) { + console.error( + 'regrowth: delete the comment (the code or a name should carry it), and move a report into its plan hub or Linear.', + ); + return 1; + } + console.log(`regrowth: nothing regrown since ${base} (${sourceFiles} package source file(s) read).`); + return 0; +} + +if (process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.meta.url)) { + try { + process.exitCode = main(); + } catch (error) { + console.error(`regrowth check could not run: ${error.message}`); + process.exitCode = 2; + } +} diff --git a/scripts/quality/check-regrowth.test.mjs b/scripts/quality/check-regrowth.test.mjs new file mode 100644 index 0000000..0eb7028 --- /dev/null +++ b/scripts/quality/check-regrowth.test.mjs @@ -0,0 +1,214 @@ +import assert from 'node:assert/strict'; +import { execFileSync } from 'node:child_process'; +import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import path from 'node:path'; +import test from 'node:test'; + +import { fixtureGitEnvironment } from '../lib/git-guardrails.mjs'; +import { addedLines, isPackageSource, judge, markdownProblem, regrownComments } from './check-regrowth.mjs'; + +test('new markdown is allowed in its homes, guidance folders and conventional names only', () => { + for (const file of [ + '.plans/active/hub/findings-2026-11-21.md', + 'docs/docs/builders/quality/index.mdx', + 'packages/agent/README.md', + 'packages/client/DESIGN.md', + '.claude/skills/review/SKILL.md', + '.claude/context/testing.md', + '.claude/skills/qa-triage/references/unattended-report.md', + 'scripts/quality/check-regrowth.test.mjs', + ]) { + assert.equal(markdownProblem(file), null, file); + } + for (const file of [ + 'packages/shared/AUDIT_REPORT.md', + 'packages/contracts/docs/conviction-sync-launch.md', + 'packages/indexer/notes.md', + '.claude/context/audit-2026-11-21.md', + 'scripts/handoff.md', + 'SUMMARY.md', + ]) { + assert.ok(markdownProblem(file), file); + } +}); + +test('package source excludes tests, stories, mocks, declarations and generated files', () => { + assert.ok(isPackageSource('packages/shared/src/modules/work/submit.ts')); + assert.ok(isPackageSource('packages/contracts/src/Garden.sol')); + assert.ok(isPackageSource('packages/website/src/components/ui/Card.astro')); + assert.ok(isPackageSource('scripts/operational-content.ts')); + assert.ok(!isPackageSource('scripts/agent-contract.test.ts')); + // Unlike Green Goods, the repository's own scripts are in scope here. + assert.ok(isPackageSource('scripts/quality/check.mjs')); + for (const file of [ + 'packages/shared/src/__tests__/a.test.ts', + 'packages/shared/src/components/Button.stories.tsx', + 'packages/shared/src/__mocks__/wagmi.ts', + 'packages/shared/src/types/indexer.d.ts', + 'packages/contracts/script/deploy.ts', + 'scripts/quality/check-regrowth.test.mjs', + 'packages/website/src/components/ui/Card.test.astro', + 'packages/website/src/components/ui/Card.stories.astro', + ]) { + assert.ok(!isPackageSource(file), file); + } +}); + +test("added lines come from each hunk's new-file range", () => { + const diff = '@@ -3,0 +4,2 @@\n+a\n+b\n@@ -10 +12 @@\n-x\n+y\n@@ -20,3 +23,0 @@\n-p\n'; + assert.deepEqual([...addedLines(diff)], [4, 5, 12]); +}); + +test('only purge-shaped comments on added lines count, and a comment whose place carries meaning stays', () => { + const code = [ + '// ===== Setup =====', + 'const a = 1;', + '// Submit batch transaction', + 'const b = 2; // explains b', + '// Safari drops the event when the tab is hidden, so poll instead.', + 'const c = gql(/* GraphQL */ `query Q { a }`);', + ].join('\n'); + const all = regrownComments(code, 'packages/shared/src/x.ts', 'all').map((comment) => comment.line); + assert.deepEqual(all, [1, 3]); + assert.deepEqual( + regrownComments(code, 'packages/shared/src/x.ts', new Set([3, 4, 5, 6])).map((comment) => comment.line), + [3], + ); +}); + +test('the check judges a change against its merge base, uncommitted and untracked work included', (t) => { + const root = mkdtempSync(path.join(tmpdir(), 'regrowth-')); + t.after(() => rmSync(root, { recursive: true, force: true })); + const env = fixtureGitEnvironment(); + const git = (...args) => execFileSync('git', ['-C', root, ...args], { env, encoding: 'utf8' }); + const write = (file, text) => { + mkdirSync(path.dirname(path.join(root, file)), { recursive: true }); + writeFileSync(path.join(root, file), text); + }; + git('init', '-q', '-b', 'develop'); + write('packages/shared/src/old.ts', '// ===== Old banner =====\nexport const a = 1;\n'); + write('packages/indexer/legacy-notes.md', 'old\n'); + git('add', '.'); + git('commit', '-q', '-m', 'base'); + const base = git('rev-parse', 'HEAD').trim(); + + assert.deepEqual(judge(root, base).problems, []); + + write( + 'packages/shared/src/old.ts', + '// ===== Old banner =====\nexport const a = 1;\n// Submit batch transaction\nconst b = 2;\nexport { b };\n', + ); + write('packages/shared/src/new.ts', '// ----- Section -----\nexport const c = 3;\n'); + write('packages/shared/REVIEW_FINDINGS.md', 'findings\n'); + write('packages/indexer/legacy-notes.md', 'edited, not added\n'); + const { problems } = judge(root, base); + assert.equal(problems.length, 3, problems.join('\n')); + + // A move and a re-indent add no comment: the moved file is judged against its source, and + // whitespace is ignored. + git('add', '.'); + git('commit', '-q', '-m', 'change'); + const changed = git('rev-parse', 'HEAD').trim(); + git('mv', 'packages/shared/src/old.ts', 'packages/shared/src/moved.ts'); + write( + 'packages/shared/src/moved.ts', + 'if (true) {\n // ===== Old banner =====\n}\nexport const a = 1;\n// Submit batch transaction\nconst b = 2;\nexport { b };\n', + ); + assert.deepEqual(judge(root, changed).problems, []); + + // Moving markdown into a place it may not be is an addition there; moving it within one is not. + git('mv', 'packages/indexer/legacy-notes.md', 'packages/indexer/kept-notes.md'); + assert.deepEqual(judge(root, changed).problems, []); + mkdirSync(path.join(root, '.plans/active/hub'), { recursive: true }); + write('.plans/active/hub/findings.md', 'plan\n'); + git('add', '.'); + git('commit', '-q', '-m', 'plan note'); + const planned = git('rev-parse', 'HEAD').trim(); + git('mv', '.plans/active/hub/findings.md', 'packages/shared/findings.md'); + assert.equal(judge(root, planned).problems.length, 1); + assert.ok(problems.some((problem) => problem.startsWith('packages/shared/src/old.ts:3: new label comment'))); + assert.ok(problems.some((problem) => problem.startsWith('packages/shared/src/new.ts:1: new banner comment'))); + assert.ok(problems.some((problem) => problem.startsWith('packages/shared/REVIEW_FINDINGS.md: reads as a report'))); +}); + +test('re-indenting old comments, as wrapping code in a function does, adds none', (t) => { + const root = mkdtempSync(path.join(tmpdir(), 'regrowth-indent-')); + t.after(() => rmSync(root, { recursive: true, force: true })); + const env = fixtureGitEnvironment(); + const git = (...args) => execFileSync('git', ['-C', root, ...args], { env, encoding: 'utf8' }); + const file = path.join(root, 'packages/shared/src/flow.ts'); + mkdirSync(path.dirname(file), { recursive: true }); + writeFileSync(file, 'const a = 1;\n// Submit batch transaction\nconst b = a + 1;\nconsole.log(b);\n'); + git('init', '-q', '-b', 'develop'); + git('add', '.'); + git('commit', '-q', '-m', 'base'); + const base = git('rev-parse', 'HEAD').trim(); + writeFileSync( + file, + 'function run() {\n const a = 1;\n // Submit batch transaction\n const b = a + 1;\n return b;\n}\nrun();\n', + ); + assert.deepEqual(judge(root, base).problems, []); + writeFileSync( + file, + 'function run() {\n const a = 1;\n // Submit batch transaction\n const b = a + 1;\n // Return the result\n return b;\n}\nrun();\n', + ); + assert.equal(judge(root, base).problems.length, 1); +}); + +test('gitattributes, bracketed route names and odd line breaks cannot hide or invent an added comment', (t) => { + const root = mkdtempSync(path.join(tmpdir(), 'regrowth-edges-')); + t.after(() => rmSync(root, { recursive: true, force: true })); + const env = fixtureGitEnvironment(); + const git = (...args) => execFileSync('git', ['-C', root, ...args], { env, encoding: 'utf8' }); + const write = (file, text) => { + mkdirSync(path.dirname(path.join(root, file)), { recursive: true }); + writeFileSync(path.join(root, file), text); + }; + git('init', '-q', '-b', 'develop'); + write('.gitattributes', '*.ts -diff\n'); + write('packages/shared/src/hidden.ts', 'export const a = 1;\nexport const b = 2;\n'); + write('packages/shared/src/[id].ts', '// ===== Old banner =====\nexport const a = 1;\n'); + write('packages/shared/src/i.ts', 'export const a = 1;\n'); + write('packages/shared/src/breaks.ts', 'const s = "a
b";\nexport const a = s;\nexport const b = 2;\n'); + git('add', '.'); + git('commit', '-q', '-m', 'base'); + const base = git('rev-parse', 'HEAD').trim(); + + write('packages/shared/src/hidden.ts', 'export const a = 1;\n// ===== Hidden banner =====\nexport const b = 2;\n'); + write('packages/shared/src/i.ts', 'export const z = 0;\nexport const a = 1;\n'); + write('packages/shared/src/[id].ts', '// ===== Old banner =====\nexport const a = 1;\nexport const c = 3;\n'); + write( + 'packages/shared/src/breaks.ts', + 'const s = "a
b";\nexport const a = s;\n// ===== Late banner =====\nexport const b = 2;\n', + ); + const { problems } = judge(root, base); + assert.equal(problems.length, 2, problems.join('\n')); + assert.ok(problems.some((problem) => problem.startsWith('packages/shared/src/hidden.ts:2: new banner comment'))); + assert.ok(problems.some((problem) => problem.startsWith('packages/shared/src/breaks.ts:3: new banner comment'))); +}); + +test('a line added inside an old comment, or a file moved in from outside the scope, is judged', (t) => { + const root = mkdtempSync(path.join(tmpdir(), 'regrowth-span-')); + t.after(() => rmSync(root, { recursive: true, force: true })); + const env = fixtureGitEnvironment(); + const git = (...args) => execFileSync('git', ['-C', root, ...args], { env, encoding: 'utf8' }); + const write = (file, text) => { + mkdirSync(path.dirname(path.join(root, file)), { recursive: true }); + writeFileSync(path.join(root, file), text); + }; + git('init', '-q', '-b', 'develop'); + write('packages/shared/src/kept.ts', '// const oldValue = 1;\nexport const a = 1;\n'); + write('packages/shared/legacy.ts', '// ===== Legacy banner =====\nexport const l = 1;\n'); + git('add', '.'); + git('commit', '-q', '-m', 'base'); + const base = git('rev-parse', 'HEAD').trim(); + assert.deepEqual(judge(root, base).problems, []); + + write('packages/shared/src/kept.ts', '// const oldValue = 1;\n// const newValue = 2;\nexport const a = 1;\n'); + git('mv', 'packages/shared/legacy.ts', 'packages/shared/src/legacy.ts'); + const { problems } = judge(root, base); + assert.equal(problems.length, 2, problems.join('\n')); + assert.ok(problems.some((problem) => problem.startsWith('packages/shared/src/kept.ts:1: new'))); + assert.ok(problems.some((problem) => problem.startsWith('packages/shared/src/legacy.ts:1: new banner comment'))); +});