diff --git a/CHANGELOG.md b/CHANGELOG.md index b6e02f1c..37a3c9c4 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,7 +4,7 @@ Notable changes to house-rules. Versions follow [semantic versioning](https://se ## Unreleased -- `hr-code-review`'s panel recommendations catalog is generated: `scripts/refresh-recommendations.mjs` builds `panel-recommendations.json` from a source spec, a snapshot of the public Bug Hunt board (`--fetch` rewrites it) and the maintainer's own results (`--from-file` replaces them from a file of structured facts: a model and harness the spec lists, fixed choices and bounded numbers, with a deny file for private names; they live only in the catalog's own entries), and `--check` fails offline when the catalog is not what those inputs generate. The one-time refresh moves the Opus, Sonnet and Muse figures to the board's current rows and adds GPT-6.2 Astra and Gemini 4 Neon entries; entries gain a `kind`. +- `hr-code-review`'s panel recommendations catalog is generated: `scripts/refresh-recommendations.mjs` builds `panel-recommendations.json` from a source spec, a snapshot of the public Bug Hunt board (`--fetch` rewrites it) and the maintainer's own results (`--from-file` replaces them from a file of structured facts: a model and harness the spec lists, fixed choices and bounded numbers, with a deny file for private names; they live only in the catalog's own entries), and `--check` fails offline when the catalog is not what those inputs generate or the references folder holds a file the spec does not list or any symlink. The refresh no longer deletes inside a leftover transaction folder beyond the files it wrote, restores a file through a staged copy and keeps the before images when a restore fails, compares a stale lock's whole record before removing it, removes an interrupted run's before images, leaves the snapshot alone on an import, refuses malformed board rows and a repeated key in a fetched board, and states the board's planted total once. The one-time refresh moves the Opus, Sonnet and Muse figures to the board's current rows and adds GPT-6.2 Astra and Gemini 4 Neon entries; entries gain a `kind`. - `hr-better-colors`' focus-ring table row says it gives the blue step and that other hues are measured (Radix yellow `9` is 1.26:1 on white); the paragraph under the table is split in three. - `hr-better-colors` puts the focus ring and input boundary on Radix step `9`, not `8`: Radix blue `8` (`#5eb1ef`) measures 2.33:1 on white, `9` measures 3.26:1 (Tailwind `500` stays 3.68:1). The previous entry's wording gave step `8`. - Five review points on the vendored jakubkrehel text (from the private reviewer on the pin adoption) are fixed in wording: `hr-better-accessibility` limits `novalidate` to forms whose submit handler renders the errors (a form that renders each error from the field's `invalid` event needs none) and carries the typed-name destructive-confirmation exception into `forms.md`, `semantics-and-aria.md` and the checklist; `hr-better-colors` stops giving the focus ring to the decorative `300` border step (`--blue-300` measures 1.80:1 on white) and gives the focus ring and input boundary their own table row on the first step that measures 3:1, and its class-based theme recipe resolves the theme in one function (a saved choice wins, System reads the current query value) run at startup, on a choice change and on the system `change` event; `hr-better-typography` says `65ch` and the `max-w-md` / `max-w-lg` mapping assume a proportional font (in single-width monospace text the range is `60ch`–`75ch` and `max-w-md` holds about 46 characters; full-width glyphs take two cells, so a mixed-width line needs a rendered count), with a separate cheat-sheet row for monospace. diff --git a/skills/hr-code-review/references/panel-recommendations.md b/skills/hr-code-review/references/panel-recommendations.md index fed01fd3..9bb6106d 100644 --- a/skills/hr-code-review/references/panel-recommendations.md +++ b/skills/hr-code-review/references/panel-recommendations.md @@ -73,7 +73,13 @@ The import also needs a deny file of private names. The script refuses that file the results file when either sits inside the skill folder, because the installer copies that folder. Any published string that holds a denied name, in the spec, snapshot or catalog, fails the run. The spec's `distributed` list names every file of this folder, -and `--check` fails on any other file, so a leftover private input cannot ship. +and `--check` fails on any other file of any name, and on any symlink, so a leftover +private input cannot ship. Only the script's own lock and work files at the top of +the folder are left out. A plain run of the script regenerates the catalog and writes the snapshot in its one -canonical layout, which is what `--check` compares. +canonical layout, which is what `--check` compares; an import leaves the snapshot's +bytes alone. The spec's board task writes the planted total as `{plantedTotal}`, so the +task text always names the total the snapshot holds. A board row with a missing name or +an unreadable measurement, or a repeated key anywhere in the board, refuses the refresh +before any file changes, whether the board is fetched or saved. diff --git a/skills/hr-code-review/references/panel-recommendations.sources.json b/skills/hr-code-review/references/panel-recommendations.sources.json index af1af588..a5591e1c 100644 --- a/skills/hr-code-review/references/panel-recommendations.sources.json +++ b/skills/hr-code-review/references/panel-recommendations.sources.json @@ -2,7 +2,7 @@ "version": 1, "board": { "url": "https://bughunt.productcompass.pm/data/benchmark.json", - "task": "Find planted bugs: 105 across two repositories, count fixed", + "task": "Find planted bugs: {plantedTotal} across two repositories, count fixed", "noisePoints": 1.5, "timeDefinition": "wall clock summed over both repositories; the board says its machines were shared with other work for some rows, so times compare loosely at best", "costDefinition": "list-rate API price estimated from usage counts, summed over both repositories; not an invoice or subscription billing" diff --git a/skills/hr-code-review/scripts/refresh-files.mjs b/skills/hr-code-review/scripts/refresh-files.mjs index bd624f67..9cbf305a 100644 --- a/skills/hr-code-review/scripts/refresh-files.mjs +++ b/skills/hr-code-review/scripts/refresh-files.mjs @@ -1,18 +1,22 @@ // File handling for refresh-recommendations.mjs: a JSON reader that refuses a repeated key, the one byte layout of // the files it writes, an all-or-nothing multi-file write and the lock that serializes refreshes. +import { createHash } from "node:crypto"; import { existsSync, linkSync, + lstatSync, + mkdirSync, mkdtempSync, readdirSync, readFileSync, renameSync, + rmdirSync, rmSync, - statSync, + unlinkSync, writeFileSync, } from "node:fs"; import { tmpdir } from "node:os"; -import { dirname, join } from "node:path"; +import { dirname, join, resolve } from "node:path"; /** The one byte layout every JSON file here is written in, so --check can compare bytes. */ export const serialize = (/** @type {unknown} */ value) => `${JSON.stringify(value, null, 2)}\n`; @@ -21,41 +25,78 @@ export const serialize = (/** @type {unknown} */ value) => `${JSON.stringify(val // that is the whole of what a later run reclaims. const TRANSACTION_MARKER = ".transaction"; const TRANSACTION_TEXT = "refresh-recommendations transaction\n"; -/** @param {string} dir the references folder */ +/** + * Reclaim the transactions an interrupted run left in the references folder. Nothing is entered or removed + * recursively: a work folder is the tool's only when it is a real folder holding the marker file and plain + * `new-` files, each checked without following links; those files are unlinked one by one and the folder is + * removed with a plain rmdir, which refuses a folder that still holds anything. + * @param {string} dir the references folder + */ function reclaimAbandoned(dir) { for (const name of readdirSync(dir)) { const path = join(dir, name); - if (!/^\.refresh-[A-Za-z0-9]{6}$/.test(name) || !statSync(path).isDirectory()) { + if (!/^\.refresh-[A-Za-z0-9]{6}$/.test(name) || !lstatSync(path).isDirectory()) { continue; } - const inside = readdirSync(path); + const inside = readdirSync(path, { withFileTypes: true }); + const marker = inside.find((e) => e.name === TRANSACTION_MARKER); if ( - inside.includes(TRANSACTION_MARKER) && - readFileSync(join(path, TRANSACTION_MARKER), "utf8") === TRANSACTION_TEXT && - inside.every((n) => n === TRANSACTION_MARKER || /^new-\d+$/.test(n)) + marker?.isFile() !== true || + readFileSync(join(path, TRANSACTION_MARKER), "utf8") !== TRANSACTION_TEXT || + !inside.every( + (e) => e.isFile() && (e.name === TRANSACTION_MARKER || /^new-\d+$/.test(e.name)), + ) ) { - rmSync(path, { recursive: true, force: true }); + continue; + } + try { + for (const e of inside.filter((e) => e.name !== TRANSACTION_MARKER)) { + unlinkSync(join(path, e.name)); + } + unlinkSync(join(path, TRANSACTION_MARKER)); + rmdirSync(path); + } catch { + // Something arrived while cleaning up, or a file is held: leave what is left for the next run. } } } +/** + * Where the before images of a write to this folder go: one private directory per folder, outside the skill + * folder, so no copy of the skill carries them. The folder's lock is held by whoever writes, so a directory + * already there is what a run that was killed left behind, and the next write removes it. + * @param {string} dir the references folder + */ +export const backupDirFor = (dir) => + join( + tmpdir(), + `refresh-recommendations-${createHash("sha256").update(resolve(dir)).digest("hex").slice(0, 16)}`, + ); + /** * Write several files of one folder so that a failure leaves none of them changed. The new contents are staged * in a new directory beside the targets (same filesystem, so each rename is atomic); the before images, which - * may hold data a replacement removes, go to a private directory outside the skill folder, so no copy of the - * skill ever carries them. The renames then run back to back, and a failed rename puts the earlier files back. - * Readers consume only the catalog, which goes last: an interruption leaves the old catalog complete, and + * may hold data a replacement removes, go to a private directory outside the skill folder (`backupDirFor`). The + * renames then run back to back, and a failed rename puts the earlier files back, each by staging a copy of its + * before image beside the target and renaming that over it, so a failure while restoring never leaves a + * truncated file. When a file cannot be restored the before images are kept and their folder is named in the + * error. Readers consume only the catalog, which goes last: an interruption leaves the old catalog complete, and * --check reports the sources that are ahead of it until a plain run regenerates it. * @param {Array<[string, unknown]>} outputs + * @param {{ rename?: (from: string, to: string) => void }} [io] a test seam for the rename */ -export function writeAll(outputs) { +export function writeAll(outputs, io = {}) { + const rename = io.rename ?? renameSync; const dir = dirname(outputs[0]?.[0] ?? "."); if (outputs.some(([path]) => dirname(path) !== dir)) { throw new Error("the outputs must be in one folder"); } const stage = mkdtempSync(join(dir, ".refresh-")); writeFileSync(join(stage, TRANSACTION_MARKER), TRANSACTION_TEXT, { flag: "wx" }); - const backups = mkdtempSync(join(tmpdir(), "refresh-recommendations-")); + const backups = backupDirFor(dir); + rmSync(backups, { recursive: true, force: true }); + mkdirSync(backups, { mode: 0o700 }); + let keepBackups = /** @type {boolean} */ (false); try { const staged = outputs.map(([path, value], i) => { const file = join(stage, `new-${i}`); @@ -68,26 +109,46 @@ export function writeAll(outputs) { } return { path, file, back }; }); + /** @type {typeof staged} */ const done = []; try { for (const item of staged) { - renameSync(item.file, item.path); + rename(item.file, item.path); done.push(item); } } catch (error) { - for (const item of done) { - if (item.back === undefined) { - rmSync(item.path, { force: true }); - } else { - // The before image lives on another filesystem, so it is copied back, not renamed. - writeFileSync(item.path, readFileSync(item.back)); + /** @type {string[]} */ + const unrestored = []; + done.forEach((item, i) => { + try { + if (item.back === undefined) { + rmSync(item.path, { force: true }); + } else { + // The before image lives on another filesystem: copy it beside the target, then rename it over. + const copy = join(stage, `new-${outputs.length + i}`); + writeFileSync(copy, readFileSync(item.back), { flag: "wx" }); + rename(copy, item.path); + } + } catch (restoreError) { + unrestored.push(`${item.path} (${/** @type {Error} */ (restoreError).message})`); } + }); + if (unrestored.length > 0) { + keepBackups = true; + const kept = `${backups}-kept-${Date.now()}`; + renameSync(backups, kept); + throw new Error( + `${/** @type {Error} */ (error).message}; could not put back ${unrestored.join(", ")}; the before images are kept in ${kept}`, + { cause: error }, + ); } throw error; } } finally { rmSync(stage, { recursive: true, force: true }); - rmSync(backups, { recursive: true, force: true }); + if (!keepBackups) { + rmSync(backups, { recursive: true, force: true }); + } } } @@ -126,11 +187,16 @@ export async function withLock(dir, fn, hooks = {}) { throw error; } }; - /** @param {string} path the owner's pid, "gone" when the file vanished, "unreadable" otherwise */ + /** + * @param {string} path the owner's pid and the whole record (pid and token), "gone" when the file vanished, + * "unreadable" otherwise + * @returns {{ pid: number, record: string } | "gone" | "unreadable"} + */ const ownerOf = (path) => { try { - const owner = Number(readFileSync(path, "utf8").trim().split(/\s+/)[0]); - return Number.isInteger(owner) && owner > 0 ? owner : "unreadable"; + const record = readFileSync(path, "utf8"); + const pid = Number(record.trim().split(/\s+/)[0]); + return Number.isInteger(pid) && pid > 0 ? { pid, record } : "unreadable"; } catch (error) { if (/** @type {any} */ (error).code === "ENOENT") { return "gone"; @@ -158,21 +224,31 @@ export async function withLock(dir, fn, hooks = {}) { if (owner === "gone" || owner === "unreadable") { throw busy("its owner cannot be read"); } - let alive = true; - try { - process.kill(owner, 0); - } catch (error) { - alive = /** @type {any} */ (error).code === "EPERM"; - } - if (alive || attempt >= 5) { - throw busy(`process ${owner}`); + const isAlive = (/** @type {number} */ pid) => { + try { + process.kill(pid, 0); + return true; + } catch (error) { + return /** @type {any} */ (error).code === "EPERM"; + } + }; + if (isAlive(owner.pid) || attempt >= 5) { + throw busy(`process ${owner.pid}`); } await hooks.afterRead?.(); if (!claim(takeover)) { throw busy(`a stale lock is being recovered; remove ${takeover} if no refresh is running`); } try { - if (ownerOf(lock) === owner) { + // Under the recovery lock the lock must still be the record that was observed, whole (a pid alone can be + // reused by a later holder), and its owner still gone. + const now = ownerOf(lock); + if ( + now !== "gone" && + now !== "unreadable" && + now.record === owner.record && + !isAlive(now.pid) + ) { rmSync(lock, { force: true }); } } finally { diff --git a/skills/hr-code-review/scripts/refresh-recommendations.mjs b/skills/hr-code-review/scripts/refresh-recommendations.mjs index c5b2cc8b..6ff362ee 100644 --- a/skills/hr-code-review/scripts/refresh-recommendations.mjs +++ b/skills/hr-code-review/scripts/refresh-recommendations.mjs @@ -15,12 +15,12 @@ // // Any other argument, a conflicting pair of modes or an empty value is an error (exit 2). import { existsSync, readdirSync, readFileSync, realpathSync } from "node:fs"; -import { dirname, join, relative, resolve, sep } from "node:path"; +import { dirname, join, resolve } from "node:path"; import { fileURLToPath, pathToFileURL } from "node:url"; import { parseArgs } from "node:util"; -import { parseStrict, serialize, withLock, writeAll } from "./refresh-files.mjs"; +import { backupDirFor, parseStrict, serialize, withLock, writeAll } from "./refresh-files.mjs"; -export { parseStrict, serialize, withLock, writeAll }; +export { backupDirFor, parseStrict, serialize, withLock, writeAll }; const skill = resolve(dirname(fileURLToPath(import.meta.url)), ".."); const refs = join(skill, "references"); @@ -164,18 +164,37 @@ export function reduceBoard(board, fetched) { const rows = board.runs .filter((/** @type {any} */ r) => r.superseded === null || r.superseded === undefined) .map((/** @type {any} */ r) => { + // Every field is checked as the board states it before it becomes snapshot data: a missing identity is + // not the text "undefined", and a measurement that is present but not a number is not an absent one. + const label = `board row ${JSON.stringify([r?.model, r?.harness, r?.effort]).slice(0, 120)}`; + for (const key of ["model", "harness", "effort", "date"]) { + if (typeof r?.[key] !== "string" || r[key].trim() === "") { + throw new Error(`${label} has no readable ${key}`); + } + } if (typeof r.fixed !== "number" || typeof r.n_runs !== "number") { - throw new Error(`board row ${r.model} ${r.effort} has a figure this tool cannot read`); + throw new Error(`${label} has a figure this tool cannot read`); + } + const absent = (/** @type {unknown} */ v) => v === undefined || v === null; + if (!absent(r.wall_min) && !(typeof r.wall_min === "number" && Number.isFinite(r.wall_min))) { + throw new Error(`${label} has a wall_min this tool cannot read`); + } + if ( + r.cost_kind === "list" && + !absent(r.cost_usd) && + !(typeof r.cost_usd === "number" && Number.isFinite(r.cost_usd)) + ) { + throw new Error(`${label} has a cost_usd this tool cannot read`); } return { - model: String(r.model), - harness: String(r.harness), - effort: String(r.effort), + model: r.model, + harness: r.harness, + effort: r.effort, runs: r.n_runs, fixed: r.fixed, wallMinutes: typeof r.wall_min === "number" ? r.wall_min : null, costUsd: typeof r.cost_usd === "number" && r.cost_kind === "list" ? r.cost_usd : null, - date: String(r.date), + date: r.date, }; }); return canonicalSnapshot({ @@ -376,6 +395,19 @@ function boardRationale(rows, total, noisePoints) { return `${best.effort} fixed the most (${best.fixed} of ${total}); ${clauses.join("; ")}.`; } +/** + * The board entries' task text, with the snapshot's planted total in it: the spec states `{plantedTotal}` where + * the number goes, so the task and the metric cannot name two different totals. + * @param {any} spec + * @param {any} snapshot + */ +function boardTask(spec, snapshot) { + if (typeof spec.board?.task !== "string" || !spec.board.task.includes("{plantedTotal}")) { + throw new Error("the source spec's board task must state the planted total as {plantedTotal}"); + } + return spec.board.task.replaceAll("{plantedTotal}", String(snapshot.plantedTotal)); +} + /** * The whole catalog from its three inputs. Pure: the same inputs give the same catalog. * @param {any} spec @@ -392,7 +424,7 @@ export function buildCatalog(spec, snapshot, own) { id: entry.id, kind: "board", profiles: entry.profiles, - task: spec.board.task, + task: boardTask(spec, snapshot), model: entry.model, harness: entry.harness, route: entry.route, @@ -484,7 +516,8 @@ export async function fetchBoard(url, fetchImpl = fetch) { } chunks.push(value); } - return JSON.parse(new TextDecoder().decode(Buffer.concat(chunks))); + // The same decoder as a saved board, so a repeated key is refused whichever way the board arrives. + return parseStrict(new TextDecoder().decode(Buffer.concat(chunks)), url); } /** @param {string | undefined} file */ @@ -694,7 +727,10 @@ async function refresh(paths, values, today) { // the snapshot it read. An import writes the catalog alone. /** @type {Array<[string, unknown]>} */ const outputs = []; - if (values.fetch === true || off.some((f) => f.name === "snapshot")) { + if ( + values.fetch === true || + (values["from-file"] === undefined && off.some((f) => f.name === "snapshot")) + ) { outputs.push([paths.snapshot, snapshot]); } outputs.push([paths.catalog, catalog]); @@ -731,10 +767,56 @@ function requireCatalogShape(catalog, path) { } } +// The tool's own work files, which exist only at the top of the references folder while a run is in progress. +const WORK_FILE = /^\.refresh\.(?:lock|takeover|lock\.\d+\.[a-z0-9]+)$/; +const WORK_DIR = /^\.refresh-[A-Za-z0-9]{6}$/; +const WORK_DIR_ENTRY = /^(?:\.transaction|new-\d+)$/; + +/** + * Every file under the references folder by relative path, and every entry that is not a plain file or folder (a + * symlink, a socket, a pipe), which the installer would copy as a link to a path outside the skill. Only the + * tool's own work files at the top level are left out: its lock files and a `.refresh-` folder + * holding nothing but its marker and `new-` files. A name that merely starts with `.refresh` is a file like any other. + * @param {string} dir + * @param {string} [rel] + * @returns {{ files: string[], refused: string[] }} + */ +function inventoryOf(dir, rel = "") { + /** @type {string[]} */ + const files = []; + /** @type {string[]} */ + const refused = []; + for (const e of readdirSync(join(dir, rel), { withFileTypes: true })) { + const name = rel === "" ? e.name : `${rel}/${e.name}`; + const top = rel === ""; + if (e.isSymbolicLink()) { + refused.push(`${name} (a symlink)`); + } else if (e.isFile()) { + if (!(top && WORK_FILE.test(e.name))) { + files.push(name); + } + } else if (e.isDirectory()) { + if (top && WORK_DIR.test(e.name)) { + for (const inner of readdirSync(join(dir, name), { withFileTypes: true })) { + if (!inner.isFile() || !WORK_DIR_ENTRY.test(inner.name)) { + refused.push(`${name}/${inner.name} (not a work file of this tool)`); + } + } + } else { + const nested = inventoryOf(dir, name); + files.push(...nested.files); + refused.push(...nested.refused); + } + } else { + refused.push(`${name} (not a plain file)`); + } + } + return { files, refused }; +} + /** * The files of the references folder are the ones the source spec lists, and only those: anything else in it - * (a raw results file, a deny list, a saved board) would be copied to hosts with the skill. Work files of this - * tool (names starting `.refresh`) are not files of the folder. + * (a raw results file, a deny list, a saved board, a symlink to any of them) would be copied to hosts with the skill. * @param {string} dir * @param {unknown} distributed */ @@ -742,9 +824,12 @@ function requireInventory(dir, distributed) { if (!Array.isArray(distributed) || distributed.some((n) => typeof n !== "string")) { throw new Error("the source spec has no `distributed` list of the references folder's files"); } - const present = readdirSync(dir, { recursive: true, withFileTypes: true }) - .filter((e) => e.isFile() && !e.name.startsWith(".refresh")) - .map((e) => relative(dir, join(e.parentPath, e.name)).split(sep).join("/")); + const { files: present, refused } = inventoryOf(dir); + if (refused.length > 0) { + throw new Error( + `the references folder holds entries that are not plain files: ${refused.join(", ")}; remove them, since the installer would copy a link to a path outside the skill`, + ); + } const extra = present.filter((n) => !distributed.includes(n)); const missing = distributed.filter((n) => !present.includes(n)); if (extra.length > 0 || missing.length > 0) { diff --git a/skills/hr-code-review/test/refresh-recommendations.test.mjs b/skills/hr-code-review/test/refresh-recommendations.test.mjs index 207ea5bc..45539f8c 100644 --- a/skills/hr-code-review/test/refresh-recommendations.test.mjs +++ b/skills/hr-code-review/test/refresh-recommendations.test.mjs @@ -6,6 +6,7 @@ import { mkdtempSync, readFileSync, readdirSync, + renameSync, rmSync, symlinkSync, writeFileSync, @@ -14,6 +15,7 @@ import { tmpdir } from "node:os"; import { dirname, join, resolve } from "node:path"; import { fileURLToPath } from "node:url"; import { + backupDirFor, buildCatalog, canonicalSnapshot, fetchBoard, @@ -75,7 +77,7 @@ const spec = { distributed, board: { url: "https://example.org/b.json", - task: "t", + task: "Find {plantedTotal} bugs", timeDefinition: "td", costDefinition: "cd", }, @@ -569,7 +571,9 @@ test("a fetch goes only to https, and a board larger than the cap is cancelled a assert.ok(cancelled); assert.ok(pulls <= 25, `pulled ${pulls} chunks`); const small = async () => new Response('{"a":1}', { status: 200 }); - assert.deepEqual(await fetchBoard("https://example.org/b.json", small), { a: 1 }); + assert.deepEqual(structuredClone(await fetchBoard("https://example.org/b.json", small)), { + a: 1, + }); }); test("several outputs are written together or not at all, and nothing else in the folder is touched", async () => { @@ -1025,6 +1029,57 @@ test("member names are screened like values, and names fold the way a person rea }); }); +test("the inventory refuses symlinks and counts every name, except the tool's own work files at the top level", async () => { + await inFixture(async (dir) => { + const outside = join(dir, "..", "external"); + writeFileSync(join(outside, "own.json"), "private"); + // A symlink of any name or depth (to a file or a folder) is refused: its target path would ship with the skill. + for (const [name, target] of [ + ["own.json", join(outside, "own.json")], + ["notes", outside], + ["nested/link.json", join(outside, "own.json")], + ]) { + mkdirSync(dirname(join(dir, String(name))), { recursive: true }); + symlinkSync(String(target), join(dir, String(name))); + const out = await check(dir); + assert.equal(out.code, 1, `${name}: ${out.text}`); + assert.match(out.text, new RegExp(`${String(name).replace(".", "\\.")}[^;]*symlink`)); + rmSync(join(dir, String(name).split("/")[0] ?? ""), { recursive: true, force: true }); + } + // A name starting .refresh is not exempt unless it is one of the tool's own work files at the top level. + for (const name of [ + ".refresh-own.json", + ".refresh.lock.json", + "notes/.refresh-own.json", + "notes/.refresh.lock", + ]) { + mkdirSync(dirname(join(dir, name)), { recursive: true }); + writeFileSync(join(dir, name), "private"); + const out = await check(dir); + assert.equal(out.code, 1, name); + assert.match(out.text, new RegExp(`not listed: ${name.replace(/[.]/g, "\\.")}`)); + rmSync(join(dir, name.split("/")[0] ?? name), { recursive: true, force: true }); + } + // The tool's own work files do not count: its lock files and a work directory holding only its marker and new- files. + writeFileSync(join(dir, ".refresh.lock"), ""); + writeFileSync(join(dir, ".refresh.takeover"), ""); + writeFileSync(join(dir, ".refresh.lock.123.abc9"), ""); + mkdirSync(join(dir, ".refresh-aB3dE9")); + writeFileSync( + join(dir, ".refresh-aB3dE9", ".transaction"), + "refresh-recommendations transaction\n", + ); + writeFileSync(join(dir, ".refresh-aB3dE9", "new-0"), "x"); + assert.equal((await check(dir)).code, 0); + // A work directory holding anything else, or a symlink in place of one, is not exempt. + writeFileSync(join(dir, ".refresh-aB3dE9", "own.json"), "private"); + assert.match((await check(dir)).text, /\.refresh-aB3dE9\/own\.json/); + rmSync(join(dir, ".refresh-aB3dE9"), { recursive: true, force: true }); + symlinkSync(outside, join(dir, ".refresh-aB3dE9")); + assert.match((await check(dir)).text, /\.refresh-aB3dE9[^;]*symlink/); + }); +}); + test("the references folder holds the files the spec lists and nothing else; a saved board must be outside it", async () => { await inFixture(async (dir) => { const paths = pathsIn(dir); @@ -1054,3 +1109,157 @@ test("the references folder holds the files the spec lists and nothing else; a s assert.match(out.text, /--board-file .* inside the skill folder/); }); }); + +test("a reclaimed transaction deletes only the files the writer made: a new- folder or link is never entered", async () => { + await inFixture(async (dir) => { + const outside = join(external(dir), "precious"); + mkdirSync(outside); + writeFileSync(join(outside, "keep.txt"), "mine"); + // Marked and named like a transaction, but new-0 is a folder holding a file and new-1 a link to a folder. + const shaped = join(dir, ".refresh-abc126"); + mkdirSync(shaped); + writeFileSync(join(shaped, ".transaction"), "refresh-recommendations transaction\n"); + mkdirSync(join(shaped, "new-0")); + writeFileSync(join(shaped, "new-0", "notes.txt"), "mine"); + symlinkSync(outside, join(shaped, "new-1")); + // A genuine abandoned transaction beside it is still reclaimed. + const genuine = join(dir, ".refresh-abc127"); + mkdirSync(genuine); + writeFileSync(join(genuine, ".transaction"), "refresh-recommendations transaction\n"); + writeFileSync(join(genuine, "new-0"), "x"); + const out = await importOwn(dir, own()); + assert.equal(out.code, 0, out.text); + assert.equal(existsSync(genuine), false); + assert.equal(readFileSync(join(shaped, "new-0", "notes.txt"), "utf8"), "mine"); + assert.equal(readFileSync(join(outside, "keep.txt"), "utf8"), "mine"); + }); +}); + +test("a failed restore keeps the before image and a complete file; an interrupted run's before images are reclaimed", async () => { + await inFixture(async (dir) => { + const a = join(dir, "a.json"); + const b = join(dir, "b.json"); + writeFileSync(a, "old a\n"); + writeFileSync(b, "old b\n"); + // The second rename fails, and so does every rename that tries to put the first file back. + let calls = 0; + const failing = (/** @type {string} */ from, /** @type {string} */ to) => { + calls++; + if (calls >= 2) { + throw new Error("disk full"); + } + renameSync(from, to); + }; + assert.throws( + () => + writeAll( + [ + [a, { n: 1 }], + [b, { n: 2 }], + ], + { rename: failing }, + ), + (error) => { + const text = String(/** @type {Error} */ (error).message); + assert.match(text, /disk full/); + const kept = /before images? (?:is|are) kept in (\S+)/.exec(text)?.[1]; + assert.ok(kept, text); + assert.equal(readFileSync(join(kept, "old-0"), "utf8"), "old a\n"); + rmSync(kept, { recursive: true, force: true }); + return true; + }, + ); + // a.json is complete (the new file), never a truncated one. + assert.deepEqual(read(a), { n: 1 }); + // A run killed after it made its before images leaves them; the next run removes them. + const left = backupDirFor(dir); + mkdirSync(left, { recursive: true }); + writeFileSync(join(left, "old-0"), "stale catalog\n"); + writeAll([[a, { n: 3 }]]); + assert.equal(existsSync(left), false); + assert.deepEqual(read(a), { n: 3 }); + }); +}); + +test("a stale observer compares the whole lock record: a successor with the same pid and another token survives", async () => { + await inFixture(async (dir) => { + const lock = join(dir, ".refresh.lock"); + writeFileSync(lock, "2147483646 tokenA\n"); + const kill = process.kill.bind(process); + try { + const observer = withLock(dir, async () => "ran", { + afterRead: () => { + // The pid was reused: another holder with the same pid field and its own token, now alive. + rmSync(lock, { force: true }); + writeFileSync(lock, "2147483646 tokenB\n"); + process.kill = /** @type {any} */ ( + (/** @type {number} */ pid, /** @type {any} */ signal) => + pid === 2147483646 ? true : kill(pid, signal) + ); + }, + }); + await assert.rejects(observer, /retry/); + assert.equal(readFileSync(lock, "utf8"), "2147483646 tokenB\n"); + } finally { + process.kill = kill; + } + }); +}); + +test("an import keeps a valid snapshot that is not in canonical form, byte for byte", async () => { + await inFixture(async (dir) => { + const paths = pathsIn(dir); + const compact = JSON.stringify(read(paths.snapshot)); + writeFileSync(paths.snapshot, compact); + const out = await importOwn(dir, own()); + assert.equal(out.code, 0, out.text); + assert.equal(readFileSync(paths.snapshot, "utf8"), compact); + assert.equal(read(paths.catalog).entries.at(-1).id, "own-model-a-medium-held-out"); + }); +}); + +test("a live board is parsed like a saved one: a repeated measurement is refused", async () => { + const dup = async () => + new Response('{"meta":{"planted_total":105},"runs":[{"fixed":31,"fixed":0}]}', { status: 200 }); + await assert.rejects(() => fetchBoard("https://example.org/b.json", dup), /repeated key/); +}); + +test("a board row with a missing identity or an unreadable measurement is refused, not coerced", () => { + const reduce = (/** @type {any} */ over) => reduceBoard(board([row(), row(over)]), "2026-11-21"); + for (const over of [ + { model: undefined }, + { harness: undefined }, + { effort: 3 }, + { date: undefined }, + { wall_min: "12" }, + { wall_min: [] }, + { cost_usd: "10" }, + { cost_usd: [] }, + ]) { + assert.throws(() => reduce(over), /board row/, JSON.stringify(over)); + } + // An absent measurement, and a cost the board does not give as a list price, are still allowed. + assert.equal( + reduce({ wall_min: null, effort: "low" }).rows.find( + (/** @type {any} */ r) => r.effort === "low", + )?.wallMinutes, + null, + ); + assert.equal(reduce({ cost_kind: "unknown", cost_usd: null, effort: "low" }).rows.length, 2); +}); + +test("the task text states the snapshot's planted total, so a changed total cannot contradict it", () => { + const withTotal = (/** @type {number} */ total) => + reduceBoard( + { meta: { planted_total: total, updated: "u" }, runs: [row({ effort: "medium" }), row()] }, + "2026-11-21", + ); + const templated = { ...spec, board: { ...spec.board, task: "Find {plantedTotal} planted bugs" } }; + for (const total of [105, 106]) { + const entry = buildCatalog(templated, withTotal(total), empty).entries[0]; + assert.equal(entry.task, `Find ${total} planted bugs`); + assert.match(entry.metric, new RegExp(`out of ${total}$`)); + } + const literal = { ...spec, board: { ...spec.board, task: "Find 105 planted bugs" } }; + assert.throws(() => buildCatalog(literal, withTotal(106), empty), /\{plantedTotal\}/); +});