Autonomous development for real products. Governed agents build from specs you approve, follow the rules you set, and nothing merges until another agent proves it. Your decisions, judgement and taste are the bar that work must clear. Declare your vision and let agents build it.
JavaScript agentic-codingai-agentsai-governanceautonomous-agentsclaude-codeclicode-reviewcodexcoding-agentsdeveloper-toolsgit-hooksllmlocal-firstmulti-agentsoftware-factoryspec-driven-developmentverificationvibe-coding
feat(checks): four Rigor checks with a 1500-line cap [D1,C7]
Corey Olsonb6f726be088d
diff --git a/bin/checks/empty-catch.js b/bin/checks/empty-catch.jsnew file mode 100644index 00000000..6c4c8561--- /dev/null+++ b/bin/checks/empty-catch.js@@ -0,0 +1,38 @@+#!/usr/bin/env node+/**+ * Rigor check: no bare empty catch [D1,C7].+ *+ * A bare empty catch is a `catch` clause, with or without a binding, whose block holds nothing but+ * white space and no comment, and with no comment after its closing brace on the same line. A+ * comment in either place says why the error is ignored; a block with any statement handles it.+ * Only code counts: a catch inside a string, a template's text or a comment is not one, and a+ * promise's `.catch(...)` method is not a catch clause. Every .js, .mjs and .cjs file under the+ * root is read (see scan.js for the walk). One problem per bare empty catch, at its `catch`.+ */+import { lex, lineAt, readText, runCheck, walk } from './scan.js';++const CLAUSE = /(?<![\w$.])catch\s*(?:\([^()]*\)\s*)?\{(\s*)\}/gu;++/**+ * One problem per bare empty catch in every JavaScript file.+ *+ * @param {string} root+ * @returns {{ path: string, line: number, text: string }[]}+ */+export function emptyCatchProblems(root) {+ const problems = [];+ for (const path of walk(root, /\.[cm]?js$/u)) {+ const source = readText(root, path);+ const { code, comments } = lex(source);+ for (const clause of code.matchAll(CLAUSE)) {+ const open = clause.index + clause[0].length - clause[1].length - 2;+ const close = clause.index + clause[0].length - 1;+ const lineEnd = code.indexOf('\n', close) === -1 ? code.length : code.indexOf('\n', close);+ const explained = comments.some((comment) => (comment.start > open && comment.start < close) || (comment.start > close && comment.start < lineEnd));+ if (!explained) problems.push({ path, line: lineAt(source, clause.index), text: 'empty catch names no reason: handle the error or say in a comment why it is ignored' });+ }+ }+ return problems;+}++runCheck(import.meta, emptyCatchProblems);diff --git a/bin/checks/file-size.js b/bin/checks/file-size.jsnew file mode 100644index 00000000..d64c1799--- /dev/null+++ b/bin/checks/file-size.js@@ -0,0 +1,49 @@+#!/usr/bin/env node+/**+ * Rigor check: no source or test file over 1500 lines [D1,C7].+ *+ * A source or test file is any file ending .js, .mjs, .cjs or .css under the root (see scan.js for+ * the walk and what it skips). Its length is its count of lines as an editor numbers them: one per+ * newline, plus one for a last line without a newline.+ *+ * A file over the cap prints one problem per started 100 lines over it: a file of 1501 to 1600+ * lines prints one, 1601 to 1700 two, and so on. Each problem names its block of lines, as+ * `src/cli.js:1601: lines 1601-1700 are over the 1500-line cap`. Why per block: a doctrine count+ * only falls, and one line per file would let an over-cap file grow forever without the count+ * moving. With one per block, adding 100 lines to an over-cap file raises the count by one.+ */+import { readText, runCheck, walk } from './scan.js';++const CAP = 1500;+const BLOCK = 100;++/**+ * The number of lines in a text, as an editor numbers them.+ *+ * @param {string} text+ * @returns {number}+ */+export function lineCount(text) {+ if (!text) return 0;+ const newlines = text.split('\n').length - 1;+ return text.endsWith('\n') ? newlines : newlines + 1;+}++/**+ * One problem per started block of lines over the cap, for every source or test file.+ *+ * @param {string} root+ * @returns {{ path: string, line: number, text: string }[]}+ */+export function fileSizeProblems(root) {+ const problems = [];+ for (const path of walk(root, /\.(?:[cm]?js|css)$/u)) {+ const lines = lineCount(readText(root, path));+ for (let first = CAP + 1; first <= lines; first += BLOCK) {+ problems.push({ path, line: first, text: `lines ${first}-${first + BLOCK - 1} are over the ${CAP}-line cap` });+ }+ }+ return problems;+}++runCheck(import.meta, fileSizeProblems);diff --git a/bin/checks/scan.js b/bin/checks/scan.jsnew file mode 100644index 00000000..c0659683--- /dev/null+++ b/bin/checks/scan.js@@ -0,0 +1,235 @@+/**+ * Shared parts of Pullboard's Rigor checks [D1,C7]: the file walk, a small JavaScript lexer and the+ * report. Each check prints one line per problem as `path:line: text`, sorted by path and line, and+ * exits 0 with no problems or 1 with some, so a doctrine row's `gate: check` can count it and blame+ * a changed file by the repo path at the start of each line.+ *+ * The walk starts at the directory given as the first argument, or the working directory, and skips+ * node_modules, work and every directory whose name starts with a dot (.git among them). Paths are+ * repo-relative with forward slashes, and nothing depends on the order the file system lists them.+ */+import { readdirSync, readFileSync, realpathSync } from 'node:fs';+import { join, relative, resolve, sep } from 'node:path';+import { fileURLToPath } from 'node:url';++const SKIPPED = new Set(['node_modules', 'work']);++/**+ * Every file under the root whose repo-relative path matches `pattern`, sorted.+ *+ * @param {string} root+ * @param {RegExp} pattern+ * @returns {string[]}+ */+export function walk(root, pattern) {+ const found = [];+ const pending = [resolve(root)];+ while (pending.length) {+ const directory = pending.pop();+ for (const entry of readdirSync(directory, { withFileTypes: true })) {+ const path = join(directory, entry.name);+ if (entry.isDirectory()) {+ if (!SKIPPED.has(entry.name) && !entry.name.startsWith('.')) pending.push(path);+ continue;+ }+ if (!entry.isFile()) continue;+ const name = relative(root, path).split(sep).join('/');+ if (pattern.test(name)) found.push(name);+ }+ }+ return found.sort(byText);+}++/** Compare by UTF-16 code units, so the order never depends on the machine's locale. */+function byText(left, right) {+ return left < right ? -1 : left > right ? 1 : 0;+}++/**+ * Read one walked file as text.+ *+ * @param {string} root+ * @param {string} path - repo-relative+ * @returns {string}+ */+export function readText(root, path) {+ return readFileSync(join(root, path), 'utf8');+}++/** The root a check scans: its first argument, else the working directory. */+export function rootOf(argv = process.argv) {+ return resolve(argv[2] ?? process.cwd());+}++/**+ * Run a check and report when its file is the program Node started; importing it runs nothing.+ * Why: the test imports each check, so the affected-test selection sees an import edge to it.+ *+ * @param {ImportMeta} meta - the check's `import.meta`+ * @param {(root: string) => { path: string, line: number, text: string }[]} find+ */+export function runCheck(meta, find) {+ // Node resolves symlinks in a module's URL but not in argv, so compare real paths.+ if (process.argv[1] && realpathSync(process.argv[1]) === realpathSync(fileURLToPath(meta.url))) report(find(rootOf()));+}++/**+ * Print problems sorted by path, then line number, then text, and set the exit status: 0 with no+ * problems, 1 with some. One line each, as `path:line: text`.+ *+ * @param {{ path: string, line: number, text: string }[]} problems+ */+export function report(problems) {+ const sorted = [...problems].sort((a, b) => byText(a.path, b.path) || a.line - b.line || byText(a.text, b.text));+ if (sorted.length) process.stdout.write(sorted.map((problem) => `${problem.path}:${problem.line}: ${problem.text}\n`).join(''));+ process.exitCode = sorted.length ? 1 : 0;+}++/** A word before `/` that means a regular expression follows, not a division. */+const KEYWORDS = new Set(['return', 'typeof', 'instanceof', 'in', 'of', 'new', 'delete', 'void', 'throw', 'case', 'do', 'else', 'yield', 'await']);++/**+ * Split JavaScript into code, strings and comments, without running it. `code` is the source with+ * the inside of every string, template text, regular expression and comment blanked to spaces+ * (newlines kept), so a pattern run over it only ever sees real code at its real offsets. A+ * template's `${...}` expressions stay code. Each string and template is listed whole, with its+ * text between the quotes; each comment with its span.+ *+ * Why a lexer: test files write fixture tests and catches inside strings, and a plain text search+ * would count those as the test file's own.+ *+ * @param {string} source+ * @returns {{ code: string, strings: { start: number, end: number, text: string }[], comments: { start: number, end: number }[] }}+ */+export function lex(source) {+ const code = source.split('');+ const strings = [];+ const comments = [];+ // Each open template, with the brace depth of its innermost `${` expression.+ const templates = [];+ let previous = '';+ const blank = (from, to) => { for (let at = from; at < to; at += 1) if (code[at] !== '\n') code[at] = ' '; };+ let at = 0;+ /** Scan template text from `at` to its end or its next `${`; returns true when the template closed. */+ const templateText = () => {+ const open = templates[templates.length - 1];+ while (at < source.length) {+ const char = source[at];+ if (char === '\\') { at += 2; continue; }+ if (char === '`') {+ blank(open.textFrom, at);+ strings.push({ start: open.start, end: at + 1, text: source.slice(open.start + 1, at) });+ templates.pop();+ at += 1;+ previous = '`';+ return;+ }+ if (char === '$' && source[at + 1] === '{') {+ blank(open.textFrom, at);+ open.depth = 0;+ at += 2;+ previous = '{';+ return;+ }+ at += 1;+ }+ blank(open.textFrom, source.length);+ templates.pop();+ };+ while (at < source.length) {+ const char = source[at];+ const next = source[at + 1];+ if (char === '/' && next === '/') {+ const end = source.indexOf('\n', at) === -1 ? source.length : source.indexOf('\n', at);+ comments.push({ start: at, end });+ blank(at, end);+ at = end;+ continue;+ }+ if (char === '/' && next === '*') {+ const close = source.indexOf('*/', at + 2);+ const end = close === -1 ? source.length : close + 2;+ comments.push({ start: at, end });+ blank(at, end);+ at = end;+ continue;+ }+ if (char === '\'' || char === '"') {+ let end = at + 1;+ while (end < source.length && source[end] !== char && source[end] !== '\n') end += source[end] === '\\' ? 2 : 1;+ strings.push({ start: at, end: end + 1, text: source.slice(at + 1, end) });+ blank(at + 1, end);+ at = end + 1;+ previous = char;+ continue;+ }+ if (char === '`') {+ templates.push({ start: at, textFrom: at + 1, depth: -1 });+ at += 1;+ templateText();+ continue;+ }+ if (char === '/' && regexAllowed(previous)) {+ let end = at + 1;+ let inClass = false;+ while (end < source.length && source[end] !== '\n') {+ if (source[end] === '\\') { end += 2; continue; }+ if (source[end] === '[') inClass = true;+ else if (source[end] === ']') inClass = false;+ else if (source[end] === '/' && !inClass) break;+ end += 1;+ }+ blank(at + 1, end);+ at = end + 1;+ previous = '/';+ continue;+ }+ const open = templates[templates.length - 1];+ if (open && open.depth >= 0) {+ if (char === '{') open.depth += 1;+ else if (char === '}') {+ if (open.depth === 0) {+ open.depth = -1;+ open.textFrom = at + 1;+ at += 1;+ templateText();+ continue;+ }+ open.depth -= 1;+ }+ }+ if (/[\w$]/u.test(char)) {+ let end = at;+ while (end < source.length && /[\w$]/u.test(source[end])) end += 1;+ previous = source.slice(at, end);+ at = end;+ continue;+ }+ if (!/\s/u.test(char)) previous = char;+ at += 1;+ }+ return { code: code.join(''), strings, comments };+}++/** True when a `/` after this token starts a regular expression rather than dividing. */+function regexAllowed(previous) {+ if (!previous) return true;+ if (/^[\w$]+$/u.test(previous)) return KEYWORDS.has(previous);+ return !/^[)\]'"`]$/u.test(previous) && previous !== '/';+}++/**+ * The 1-based line of an offset.+ *+ * @param {string} source+ * @param {number} offset+ * @returns {number}+ */+export function lineAt(source, offset) {+ let line = 1;+ for (let at = source.indexOf('\n'); at !== -1 && at < offset; at = source.indexOf('\n', at + 1)) line += 1;+ return line;+}++/** A test file, as the affected-test selection names one: `*.test.js` or `*.spec.js`, also .mjs and .cjs. */+export const TEST_FILE = /\.(?:test|spec)\.[cm]?js$/u;diff --git a/bin/checks/test-inputs.js b/bin/checks/test-inputs.jsnew file mode 100644index 00000000..95be16ca--- /dev/null+++ b/bin/checks/test-inputs.js@@ -0,0 +1,63 @@+#!/usr/bin/env node+/**+ * Rigor check: a test that reads source files declares it [D1,C7,V4].+ *+ * Submit selects the tests a change affects through import edges (src/affected-tests.js). A test+ * that reads source as data, rather than importing it, is invisible to that graph unless its file+ * opens with the header line the selection reads: `/** @pullboard-test-input source-tree *\/`,+ * among the declaration lines at the very top of the file.+ *+ * A test reads source files when one line of its code (outside strings and comments) calls a+ * node:fs read (readFileSync, readFile, readdirSync, readdir, opendirSync, opendir or+ * createReadStream), anchors a path at this checkout through `import.meta` or a `ROOT` constant,+ * and holds a string or template literal naming the source tree: `src` as a whole path segment,+ * as in '../src/seal.js' or join(ROOT, 'src'). The anchor keeps out fixtures, which copy src into+ * a temporary repo and read that copy. A test file is `*.test.js` or `*.spec.js`, also .mjs and+ * .cjs. One problem per undeclared test file, at its first such line.+ */+import { lex, readText, runCheck, TEST_FILE, walk } from './scan.js';++const SOURCE_TREE_INPUT = '/** @pullboard-test-input source-tree */';+const DECLARATIONS = new Set([SOURCE_TREE_INPUT, '/** @pullboard-test-input test-tree */', '/** @pullboard-test-input docs-tree */']);+const READ = /\b(?:readFileSync|readFile|readdirSync|readdir|opendirSync|opendir|createReadStream)\s*\(/u;+const ANCHOR = /\bimport\s*\.\s*meta\b|(?<![\w$.])ROOT\b/u;+const SOURCE_PATH = /(?:^|\/)src(?:\/|$)/u;++/**+ * True when the file's leading declaration lines include the source-tree input, read as the+ * affected-test selection reads them.+ *+ * @param {string} source+ * @returns {boolean}+ */+export function declaresSource(source) {+ for (const line of source.split(/\r?\n/u)) {+ if (line === SOURCE_TREE_INPUT) return true;+ if (!DECLARATIONS.has(line)) return false;+ }+ return false;+}++/**+ * One problem per test file that reads source files without the declaration.+ *+ * @param {string} root+ * @returns {{ path: string, line: number, text: string }[]}+ */+export function testInputProblems(root) {+ const problems = [];+ for (const path of walk(root, TEST_FILE)) {+ const source = readText(root, path);+ if (declaresSource(source)) continue;+ const { code, strings } = lex(source);+ const codeLines = code.split('\n');+ const lineStarts = [0];+ for (const line of codeLines) lineStarts.push(lineStarts[lineStarts.length - 1] + line.length + 1);+ const index = codeLines.findIndex((line, at) => READ.test(line) && ANCHOR.test(line)+ && strings.some((literal) => literal.start >= lineStarts[at] && literal.start < lineStarts[at + 1] && SOURCE_PATH.test(literal.text)));+ if (index !== -1) problems.push({ path, line: index + 1, text: `reads source files without ${SOURCE_TREE_INPUT} at the top` });+ }+ return problems;+}++runCheck(import.meta, testInputProblems);diff --git a/bin/checks/test-names.js b/bin/checks/test-names.jsnew file mode 100644index 00000000..e11bd435--- /dev/null+++ b/bin/checks/test-names.js@@ -0,0 +1,42 @@+#!/usr/bin/env node+/**+ * Rigor check: every test name carries a spec row id [D1,C7,W3].+ *+ * A test name is the string or template literal given as the first argument of a call to `test`,+ * `it`, `describe` or `suite` (optionally `.only`, `.skip` or `.todo`) in the code of a test file+ * (`*.test.js` or `*.spec.js`, also .mjs and .cjs). Calls reached through another object, such as+ * a subtest's `t.test(...)`, are not test names here: they nest under a named parent. Calls inside+ * strings and comments are not code, so fixture tests that a test writes out are not its own. A+ * call whose first argument is not a literal has no name to read and is not counted.+ *+ * A name carries a spec row id when it holds square brackets with at least one id in them, an+ * upper-case prefix and a number, as in `[G1.2]` or `[V4, C7]`. One problem per name without one.+ */+import { lex, lineAt, readText, runCheck, TEST_FILE, walk } from './scan.js';++const CALL = /(?<![\w$.])(?:test|it|describe|suite)(?:\s*\.\s*(?:only|skip|todo))?\s*\(\s*/gu;+const ROW_ID = /\[[^\]]*\b[A-Z]+\d+(?:\.\d+)*\b[^\]]*\]/u;++/**+ * One problem per literal test name without a spec row id, in every test file.+ *+ * @param {string} root+ * @returns {{ path: string, line: number, text: string }[]}+ */+export function testNameProblems(root) {+ const problems = [];+ for (const path of walk(root, TEST_FILE)) {+ const source = readText(root, path);+ const { code, strings } = lex(source);+ const starts = new Map(strings.map((literal) => [literal.start, literal]));+ for (const call of code.matchAll(CALL)) {+ const name = starts.get(call.index + call[0].length);+ if (!name || ROW_ID.test(name.text)) continue;+ const shown = name.text.replace(/\\(['"`\\])/gu, '$1').replace(/\s+/gu, ' ');+ problems.push({ path, line: lineAt(source, name.start), text: `test name has no spec row id: ${shown.length > 80 ? `${shown.slice(0, 77)}...` : shown}` });+ }+ }+ return problems;+}++runCheck(import.meta, testNameProblems);diff --git a/test/rigor-checks.test.js b/test/rigor-checks.test.jsnew file mode 100644index 00000000..2c90dc74--- /dev/null+++ b/test/rigor-checks.test.js@@ -0,0 +1,265 @@+/** @pullboard-test-input test-tree */+/** @pullboard-test-input source-tree */+/**+ * Pullboard's first Rigor checks (D1, C7): bin/checks/ holds four scripts a doctrine row's+ * `gate: check` can count. Each prints one `path:line: text` line per problem, sorted, and exits 0+ * with none or 1 with some. The census is pinned to the main commit this item merged, so it never+ * goes stale as main moves; the live checkout is held to the format, the timing and, for file size,+ * an independent recount. Fixtures prove each check adds exactly one line for one new problem.+ */+import assert from 'node:assert/strict';+import { spawnSync } from 'node:child_process';+import { mkdirSync, mkdtempSync, readFileSync, realpathSync, rmSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { dirname, join, resolve } from 'node:path';+import { after, test } from 'node:test';+// Imported so the affected-test selection sees an edge to every check; importing runs nothing.+import { fileSizeProblems } from '../bin/checks/file-size.js';+import { testNameProblems } from '../bin/checks/test-names.js';+import { emptyCatchProblems } from '../bin/checks/empty-catch.js';+import { testInputProblems } from '../bin/checks/test-inputs.js';++const ROOT = resolve(import.meta.dirname, '..');+const CHECKS = ['file-size', 'test-names', 'empty-catch', 'test-inputs'];+const dir = realpathSync(mkdtempSync(join(tmpdir(), 'pullboard-rigor-')));+after(() => rmSync(dir, { recursive: true, force: true }));++/** The main commit whose census this item counted; moved forward when the item merges main. */+const PINNED = '59a6e2b286ee852add0d68a659f1a1e6b3257c44';++/** Today's over-cap files on the pinned main, with their line counts. */+const PINNED_SIZES = { 'src/board.js': 2796, 'src/cli.js': 3794, 'src/cockpit.js': 3332, 'test/api-http.test.js': 1991,+ 'test/api.test.js': 1958, 'test/cockpit/demo.test.js': 1719, 'test/run-tests.test.js': 1672 };++const NO_ID = 'test name has no spec row id: ';+const BARE = 'empty catch names no reason: handle the error or say in a comment why it is ignored';+const UNDECLARED = 'reads source files without /** @pullboard-test-input source-tree */ at the top';++/** Today's problems on the pinned main for the three checks that are not about size. */+const PINNED_PROBLEMS = {+ 'test-names': [+ ['test/board.test.js', 139, 'agents are numbered per lane; one coordinator; a worktree joins once'],+ ['test/board.test.js', 168, 'the coordinator follows the main checkout when the repo moves'],+ ['test/board.test.js', 286, 'submit needs your claim and finished children'],+ ['test/board.test.js', 353, 'under verify: coordinator, lane work is the coordinator\'s to verify'],+ ['test/board.test.js', 535, 'merged and withdraw are the coordinator\'s, and only for the right states'],+ ['test/hooks.test.js', 116, 'comments are dropped; merges, reverts and fixups are exempt'],+ ['test/hooks.test.js', 122, 'opt-in rules: filler words, emoji, co-author trailers'],+ ['test/hooks.test.js', 129, 'blocked paths: env files by name, examples allowed, patterns with a slash mat...'],+ ['test/hooks.test.js', 139, 'secrets are named by kind and place, never echoed'],+ ['test/lanes.test.js', 29, 'a lane may change its own paths and shared ones; the coordinator may change a...'],+ ['test/lanes.test.js', 55, 'config merges nested groups over the defaults, and leases read as durations'],+ ['test/spec.test.js', 226, 'rows inside code fences are examples, not rows'],+ ['test/spec.test.js', 251, 'bad status, bad tier and unknown fields are errors; long rows warn'],+ ['test/spec.test.js', 262, 'cited ids must exist and must not be retired'],+ ['test/view.test.js', 200, 'row text is escaped, so a row cannot inject markup'],+ ].map(([path, line, name]) => `${path}:${line}: ${NO_ID}${name}`),+ 'empty-catch': [+ ['src/api.js', 214], ['src/api.js', 222], ['src/board.js', 166], ['src/board.js', 224], ['src/runner-worker.js', 1190],+ ['test/cockpit/items.test.js', 1159], ['test/land.test.js', 170], ['test/land.test.js', 172], ['test/land.test.js', 673],+ ['test/land.test.js', 760], ['test/land.test.js', 762], ['test/land.test.js', 906], ['test/runners.test.js', 1250],+ ].map(([path, line]) => `${path}:${line}: ${BARE}`),+ 'test-inputs': [+ ['test/blueprint.test.js', 13], ['test/cockpit/layout.test.js', 146], ['test/cockpit/relay.test.js', 131],+ ['test/doctrine.test.js', 28], ['test/seal.test.js', 90],+ ].map(([path, line]) => `${path}:${line}: ${UNDECLARED}`),+};++/** Git for the test, without any GIT_* the suite inherited. */+function git(args, options = {}) {+ const env = Object.fromEntries(Object.entries(process.env).filter(([name]) => !name.startsWith('GIT_')));+ const result = spawnSync('git', ['-C', ROOT, ...args], { env, maxBuffer: 512 * 1024 * 1024, ...options });+ assert.equal(result.status, 0, `git ${args.join(' ')}: ${result.stderr}`);+ return result.stdout;+}++/**+ * Run one check as a doctrine row runs it, from `cwd` (or on `root` when given), timed.+ *+ * @returns {{ status: number|null, lines: string[], stderr: string, ms: number }}+ */+function runCheck(name, { cwd = ROOT, root } = {}) {+ const started = performance.now();+ const result = spawnSync(process.execPath, [join(ROOT, 'bin/checks', `${name}.js`), ...(root ? [root] : [])], { cwd, encoding: 'utf8' });+ const ms = performance.now() - started;+ return { status: result.status, lines: result.stdout.split('\n').filter(Boolean), stderr: result.stderr, ms };+}++/** The problem lines the size rule expects for files of these lengths. */+function sizeLines(sizes) {+ const lines = [];+ for (const [path, count] of Object.entries(sizes).sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0))) {+ for (let first = 1501; first <= count; first += 100) lines.push(`${path}:${first}: lines ${first}-${first + 99} are over the 1500-line cap`);+ }+ return lines;+}++/** Sort problem lines as the checks promise: path, then line number, then text. */+function sortedProblems(lines) {+ const parts = (line) => /^(.*?):(\d+): (.*)$/su.exec(line);+ return [...lines].sort((a, b) => {+ const [, pathA, lineA, textA] = parts(a);+ const [, pathB, lineB, textB] = parts(b);+ return (pathA < pathB ? -1 : pathA > pathB ? 1 : 0) || Number(lineA) - Number(lineB) || (textA < textB ? -1 : textA > textB ? 1 : 0);+ });+}++/** Write a fixture file under a fixture root, making its folders. */+function put(root, path, text) {+ mkdirSync(dirname(join(root, path)), { recursive: true });+ writeFileSync(join(root, path), text);+}++/** A fixture tree with no problems for any check yet. */+function fixture(name) {+ const root = join(dir, name);+ mkdirSync(root, { recursive: true });+ return root;+}++test('Pullboard\'s four checks count what main has [D1, C7]', async (t) => {+ assert.equal(typeof fileSizeProblems, 'function', 'the size check imports without running');+ assert.equal([testNameProblems, emptyCatchProblems, testInputProblems].every((find) => typeof find === 'function'), true);++ await t.test('on the pinned main each check prints exactly its census and exits 1, in under 10s [D1, C7]', () => {+ const pinned = join(dir, 'pinned');+ mkdirSync(pinned);+ const archive = git(['archive', '--format=tar', PINNED]);+ const unpacked = spawnSync('tar', ['-x', '-C', pinned], { input: archive });+ assert.equal(unpacked.status, 0, `tar: ${unpacked.stderr}`);+ const expected = { 'file-size': sizeLines(PINNED_SIZES), ...PINNED_PROBLEMS };+ assert.equal(Object.keys(PINNED_SIZES).length, 7, 'seven files are over the cap');+ assert.equal(Math.max(...Object.values(PINNED_SIZES)), PINNED_SIZES['src/cli.js'], 'the largest is src/cli.js');+ for (const name of CHECKS) {+ const run = runCheck(name, { cwd: pinned });+ assert.deepEqual(run.lines, expected[name], `${name} counts the pinned main's problems exactly`);+ assert.equal(run.status, 1, `${name} exits 1 with problems`);+ assert.equal(run.stderr, '', `${name} writes nothing else`);+ assert.ok(run.ms < 10_000, `${name} took ${Math.round(run.ms)}ms on the pinned main`);+ assert.deepEqual(runCheck(name, { cwd: dir, root: pinned }).lines, expected[name], `${name} scans its argument the same`);+ }+ assert.deepEqual(Object.fromEntries(CHECKS.map((name) => [name, expected[name].length])),+ { 'file-size': 70, 'test-names': 15, 'empty-catch': 13, 'test-inputs': 5 }, 'today\'s counts');+ });++ await t.test('on this checkout each check prints sorted path:line: text lines, exits 0 or 1, in under 10s [D1, C7]', () => {+ const tracked = git(['ls-files', '-z'], { encoding: 'utf8' }).split('\0').filter(Boolean);+ const sizes = {};+ for (const path of tracked.filter((name) => /\.(?:[cm]?js|css)$/u.test(name))) {+ const bytes = readFileSync(join(ROOT, path));+ let count = bytes.filter((byte) => byte === 10).length;+ if (bytes.length && bytes[bytes.length - 1] !== 10) count += 1;+ if (count > 1500) sizes[path] = count;+ }+ const trackedSet = new Set(tracked);+ for (const name of CHECKS) {+ const run = runCheck(name);+ assert.ok(run.status === 0 || run.status === 1, `${name} exits 0 or 1, not ${run.status}`);+ assert.equal(run.status, run.lines.length ? 1 : 0, `${name} exits 1 exactly when it prints problems`);+ assert.equal(run.stderr, '', `${name} writes nothing else`);+ assert.ok(run.ms < 10_000, `${name} took ${Math.round(run.ms)}ms`);+ for (const line of run.lines) assert.match(line, /^[^\s:/][^:]*:[1-9]\d*: \S/u, `${name} prints path:line: text`);+ assert.deepEqual(run.lines, sortedProblems(run.lines), `${name} sorts its output`);+ assert.equal(new Set(run.lines).size, run.lines.length, `${name} prints each problem once`);+ assert.equal(run.lines.some((line) => line.startsWith('test/rigor-checks.test.js:') || line.startsWith('bin/checks/')), false,+ `${name} finds nothing in this item's own files`);+ if (name === 'file-size') {+ const ours = run.lines.filter((line) => trackedSet.has(line.slice(0, line.indexOf(':'))));+ assert.deepEqual(ours, sizeLines(sizes), 'the size check agrees with an independent recount of every tracked file');+ }+ }+ });++ await t.test('adding 100 lines to an over-cap file adds exactly one line [D1, C7]', () => {+ const root = fixture('size');+ const lines = (count) => Array.from({ length: count }, (_, index) => `export const value${index} = ${index};\n`).join('');+ put(root, 'src/at-cap.js', lines(1500));+ put(root, 'src/view.css', 'a { color: red; }\n'.repeat(1500));+ put(root, 'work/scratch.js', lines(4000));+ put(root, 'node_modules/dep/index.js', lines(4000));+ put(root, '.git/hooks/huge.js', lines(4000));+ put(root, 'docs/page.html', '<p>\n'.repeat(4000));+ const clean = runCheck('file-size', { root });+ assert.deepEqual([clean.status, clean.lines], [0, []], 'a file at the cap, and skipped folders, print nothing and exit 0');+ put(root, 'src/big.js', lines(1650));+ const before = runCheck('file-size', { root });+ assert.deepEqual(before.lines, ['src/big.js:1501: lines 1501-1600 are over the 1500-line cap', 'src/big.js:1601: lines 1601-1700 are over the 1500-line cap']);+ assert.equal(before.status, 1);+ put(root, 'src/big.js', lines(1750));+ const grown = runCheck('file-size', { root });+ assert.equal(grown.lines.length, before.lines.length + 1, 'one more line for 100 more lines');+ assert.deepEqual(grown.lines.filter((line) => !before.lines.includes(line)), ['src/big.js:1701: lines 1701-1800 are over the 1500-line cap']);+ put(root, 'src/one-over.js', `${lines(1500)}last line without a newline`);+ assert.deepEqual(runCheck('file-size', { root }).lines.filter((line) => line.startsWith('src/one-over.js')),+ ['src/one-over.js:1501: lines 1501-1600 are over the 1500-line cap'], 'one line over the cap is one problem');+ });++ await t.test('adding a bare empty catch adds exactly one line [D1, C7]', () => {+ const root = fixture('catch');+ const reasoned = [+ 'export function close(db) {',+ ' try { db.close(); } catch { /* already closed: closing twice is harmless */ }',+ ' try { db.close(); } catch (error) {} // a second close is harmless',+ ' try { db.close(); } catch (error) { console.error(error); }',+ ' db.ready.catch(() => {});',+ " const text = 'try { x(); } catch {}';",+ ' const template = `${text} catch (error) {}`;',+ ' // try { x(); } catch {}',+ ' return /catch {}/u.test(template);',+ '}',+ '',+ ].join('\n');+ put(root, 'src/close.js', reasoned);+ put(root, 'work/scratch.js', 'try { x(); } catch {}\n');+ const clean = runCheck('empty-catch', { root });+ assert.deepEqual([clean.status, clean.lines], [0, []], 'catches that say why, handle the error or are not code print nothing');+ put(root, 'src/close.js', `${reasoned}export function quiet(db) {\n try { db.close(); } catch (error) {\n }\n}\n`);+ const bare = runCheck('empty-catch', { root });+ assert.deepEqual(bare.lines, [`src/close.js:12: ${BARE}`], 'one bare empty catch is one line, at its catch');+ assert.equal(bare.status, 1);+ });++ await t.test('adding a test name without a spec row id adds exactly one line [D1, C7]', () => {+ const root = fixture('names');+ const named = [+ "import { test } from 'node:test';",+ "test('a name with an id [G1.2]', async (t) => {",+ " await t.test('a subtest nests under its parent', () => {});",+ " const fixture = \"test('a fixture test written out', () => {});\";",+ '});',+ "describe.skip('a suite with ids [V4, C7]', () => it(`a template name [A1]`, () => {}));",+ 'test(nameFromSomewhere, () => {});',+ '',+ ].join('\n');+ put(root, 'test/named.test.js', named);+ put(root, 'src/helper.js', "test('not a test file', () => {});\n");+ const clean = runCheck('test-names', { root });+ assert.deepEqual([clean.status, clean.lines], [0, []], 'named tests, subtests, fixtures and non-test files print nothing');+ put(root, 'test/named.test.js', `${named}test('a [note] without an id', () => {});\n`);+ const unnamed = runCheck('test-names', { root });+ assert.deepEqual(unnamed.lines, [`test/named.test.js:8: ${NO_ID}a [note] without an id`], 'one name without an id is one line');+ assert.equal(unnamed.status, 1);+ });++ await t.test('adding an undeclared source reader adds exactly one line [D1, C7]', () => {+ const root = fixture('inputs');+ const reader = [+ "import { readFileSync } from 'node:fs';",+ "import { test } from 'node:test';",+ "test('reads the seal source [S1]', () => readFileSync(new URL('../src/seal.js', import.meta.url), 'utf8'));",+ '',+ ].join('\n');+ put(root, 'test/declared.test.js', `/** @pullboard-test-input test-tree */\n/** @pullboard-test-input source-tree */\n${reader}`);+ put(root, 'test/fixture-copy.test.js', "import { readFileSync } from 'node:fs';\nconst copy = (lane) => readFileSync(join(lane, 'src/board.js'), 'utf8');\n");+ put(root, 'test/imports.test.js', "import { seal } from '../src/seal.js';\nconst note = \"readFileSync(new URL('../src/a.js', import.meta.url))\";\n");+ const clean = runCheck('test-inputs', { root });+ assert.deepEqual([clean.status, clean.lines], [0, []], 'a declared reader, a fixture copy and an import print nothing');+ put(root, 'test/undeclared.test.js', reader);+ const undeclared = runCheck('test-inputs', { root });+ assert.deepEqual(undeclared.lines, [`test/undeclared.test.js:3: ${UNDECLARED}`], 'one undeclared reader is one line');+ assert.equal(undeclared.status, 1);+ put(root, 'test/late.test.js', `import { readFileSync } from 'node:fs';\n/** @pullboard-test-input source-tree */\n${reader.split('\n').slice(1).join('\n')}`);+ assert.deepEqual(runCheck('test-inputs', { root }).lines.map((line) => line.slice(0, line.indexOf(':'))),+ ['test/late.test.js', 'test/undeclared.test.js'], 'a declaration below the first code line is not read, as the selection reads it');+ });+});