Skip to content
10 changes: 10 additions & 0 deletions .github/workflows/pr-checks.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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

Expand Down
1 change: 1 addition & 0 deletions AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 |
Expand Down
204 changes: 204 additions & 0 deletions scripts/quality/check-regrowth.mjs
Original file line number Diff line number Diff line change
@@ -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 <ref>]
//
// 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;
}
}
Loading
Loading