From 4091336ecc1a6f3307a3f640389bf20ee9612a1d Mon Sep 17 00:00:00 2001 From: bompus Date: Sat, 21 Nov 2026 12:27:40 -0700 Subject: [PATCH 1/8] hr-code-review: generate the panel recommendations catalog from a board snapshot, a source spec and sanitized own results scripts/refresh-recommendations.mjs builds panel-recommendations.json. --fetch rewrites the committed board snapshot from the public Bug Hunt board; --from-file sanitizes a maintainer's own results (fixed plain fields, no paths, links, addresses or credentials, and a required deny file for names this repository must not carry) into the own file; --check fails offline when the catalog is not what the committed files generate. Arguments are strict, conflicting or repeated options are refused, and several outputs are written together or not at all. The one-time refresh moves the Opus, Sonnet and Muse entries to the board's current rows and adds GPT-6.2 Astra and Gemini 4 Neon. Entries gain a kind (board or own-evaluation). The generated JSON files are excluded from the formatter so the generator's output is canonical. --- .gitignore | 1 + .oxfmtrc.json | 8 +- CHANGELOG.md | 1 + .../references/panel-board-snapshot.json | 1598 +++++++++++++++++ .../references/panel-recommendations.json | 121 +- .../references/panel-recommendations.md | 19 +- .../references/panel-recommendations.own.json | 4 + .../panel-recommendations.sources.json | 84 + .../scripts/refresh-recommendations.mjs | 530 ++++++ .../hr-code-review/test/panel-setup.test.mjs | 22 +- .../test/refresh-recommendations.test.mjs | 371 ++++ 11 files changed, 2734 insertions(+), 25 deletions(-) create mode 100644 skills/hr-code-review/references/panel-board-snapshot.json create mode 100644 skills/hr-code-review/references/panel-recommendations.own.json create mode 100644 skills/hr-code-review/references/panel-recommendations.sources.json create mode 100644 skills/hr-code-review/scripts/refresh-recommendations.mjs create mode 100644 skills/hr-code-review/test/refresh-recommendations.test.mjs diff --git a/.gitignore b/.gitignore index 81692651..d9c87cdb 100644 --- a/.gitignore +++ b/.gitignore @@ -5,3 +5,4 @@ __pycache__/ .codegraph/ *.py[cod] +skills/hr-code-review/references/*.new diff --git a/.oxfmtrc.json b/.oxfmtrc.json index e89e5850..cc383447 100644 --- a/.oxfmtrc.json +++ b/.oxfmtrc.json @@ -1,6 +1,12 @@ { "$schema": "./node_modules/oxfmt/configuration_schema.json", "printWidth": 100, - "ignorePatterns": ["bun.lock", "skills/*/test/fixtures/**"], + "ignorePatterns": [ + "bun.lock", + "skills/*/test/fixtures/**", + "skills/hr-code-review/references/panel-board-snapshot.json", + "skills/hr-code-review/references/panel-recommendations.json", + "skills/hr-code-review/references/panel-recommendations.own.json" + ], "sortPackageJson": true } diff --git a/CHANGELOG.md b/CHANGELOG.md index 59035eae..a8699f30 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +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 an optional file of the maintainer's own results (`--from-file`, sanitized to a fixed set of plain fields, with a deny file for extra names), and `--check` fails offline when the catalog is not what those files 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-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-board-snapshot.json b/skills/hr-code-review/references/panel-board-snapshot.json new file mode 100644 index 00000000..9a92ca3a --- /dev/null +++ b/skills/hr-code-review/references/panel-board-snapshot.json @@ -0,0 +1,1598 @@ +{ + "version": 1, + "fetched": "2026-11-21", + "boardUpdated": "2026-11-19", + "plantedTotal": 105, + "rows": [ + { + "model": "DeepSeek V4-Flash", + "harness": "Claude Code / OpenRouter", + "effort": "default", + "runs": 1, + "fixed": 14, + "wallMinutes": 48.5, + "costUsd": null, + "date": "2026-08-01" + }, + { + "model": "DeepSeek V4-Pro", + "harness": "Claude Code / DeepSeek API", + "effort": "high", + "runs": 1, + "fixed": 13, + "wallMinutes": 26.6, + "costUsd": null, + "date": "2026-09-10" + }, + { + "model": "DeepSeek V4-Pro", + "harness": "Claude Code / DeepSeek API", + "effort": "max", + "runs": 1, + "fixed": 16, + "wallMinutes": 37.2, + "costUsd": null, + "date": "2026-09-10" + }, + { + "model": "DeepSeek V4.1 Flash", + "harness": "Claude Code / DeepSeek API", + "effort": "high", + "runs": 1, + "fixed": 19, + "wallMinutes": 26.1, + "costUsd": null, + "date": "2026-09-10" + }, + { + "model": "DeepSeek V4.1 Flash", + "harness": "Claude Code / DeepSeek API", + "effort": "max", + "runs": 3, + "fixed": 21.7, + "wallMinutes": 55.9, + "costUsd": null, + "date": "2026-09-15" + }, + { + "model": "DeepSeek V4.1 Flash 1017", + "harness": "Claude Code / DeepSeek API", + "effort": "high", + "runs": 5, + "fixed": 36.4, + "wallMinutes": 54.5, + "costUsd": null, + "date": "2026-10-17" + }, + { + "model": "DeepSeek V4.1 Flash 1017", + "harness": "Claude Code / DeepSeek API", + "effort": "low", + "runs": 5, + "fixed": 34.4, + "wallMinutes": 44.5, + "costUsd": null, + "date": "2026-10-17" + }, + { + "model": "DeepSeek V4.1 Flash 1017", + "harness": "Claude Code / DeepSeek API", + "effort": "max", + "runs": 7, + "fixed": 39.1, + "wallMinutes": 57.7, + "costUsd": null, + "date": "2026-10-18" + }, + { + "model": "DeepSeek V4.1 Flash 1017", + "harness": "DeepSeek Harness / DeepSeek API", + "effort": "high", + "runs": 5, + "fixed": 39.2, + "wallMinutes": 53, + "costUsd": null, + "date": "2026-10-18" + }, + { + "model": "DeepSeek V4.1 Flash 1017", + "harness": "DeepSeek Harness / DeepSeek API", + "effort": "low", + "runs": 5, + "fixed": 34.8, + "wallMinutes": 33.8, + "costUsd": null, + "date": "2026-10-18" + }, + { + "model": "DeepSeek V4.1 Flash 1017", + "harness": "DeepSeek Harness / DeepSeek API", + "effort": "max", + "runs": 7, + "fixed": 42.7, + "wallMinutes": 62.1, + "costUsd": null, + "date": "2026-10-18" + }, + { + "model": "DeepSeek V4.1 Flash 1017", + "harness": "OpenCode / DeepSeek API", + "effort": "high", + "runs": 5, + "fixed": 36.6, + "wallMinutes": 41.6, + "costUsd": null, + "date": "2026-10-19" + }, + { + "model": "DeepSeek V4.1 Flash 1017", + "harness": "OpenCode / DeepSeek API", + "effort": "low", + "runs": 5, + "fixed": 32.8, + "wallMinutes": 41.2, + "costUsd": null, + "date": "2026-10-19" + }, + { + "model": "DeepSeek V4.1 Flash 1017", + "harness": "OpenCode / DeepSeek API", + "effort": "max", + "runs": 5, + "fixed": 37.6, + "wallMinutes": 55.7, + "costUsd": null, + "date": "2026-10-18" + }, + { + "model": "DeepSeek V4.1 Flash 1017", + "harness": "Pi / DeepSeek API", + "effort": "high", + "runs": 5, + "fixed": 40.4, + "wallMinutes": 48.3, + "costUsd": null, + "date": "2026-10-18" + }, + { + "model": "DeepSeek V4.1 Flash 1017", + "harness": "Pi / DeepSeek API", + "effort": "low", + "runs": 5, + "fixed": 33.8, + "wallMinutes": 33.2, + "costUsd": null, + "date": "2026-10-18" + }, + { + "model": "DeepSeek V4.1 Flash 1017", + "harness": "Pi / DeepSeek API", + "effort": "max", + "runs": 5, + "fixed": 42.2, + "wallMinutes": 54.1, + "costUsd": null, + "date": "2026-10-18" + }, + { + "model": "Fable 5", + "harness": "Claude Code", + "effort": "high", + "runs": 1, + "fixed": 24, + "wallMinutes": 31.4, + "costUsd": 74.52, + "date": "2026-07-26" + }, + { + "model": "Fable 5", + "harness": "Claude Code", + "effort": "max", + "runs": 1, + "fixed": 29, + "wallMinutes": 57.3, + "costUsd": 112.4, + "date": "2026-08-01" + }, + { + "model": "Fable 5.1", + "harness": "Claude Code", + "effort": "high", + "runs": 1, + "fixed": 33, + "wallMinutes": 36.3, + "costUsd": 48.58, + "date": "2026-09-01" + }, + { + "model": "Fable 5.1", + "harness": "Claude Code", + "effort": "low", + "runs": 1, + "fixed": 29, + "wallMinutes": 33.2, + "costUsd": 33, + "date": "2026-09-02" + }, + { + "model": "Fable 5.1", + "harness": "Claude Code", + "effort": "max", + "runs": 1, + "fixed": 43, + "wallMinutes": 73.1, + "costUsd": 87.18, + "date": "2026-09-01" + }, + { + "model": "Fable 5.1", + "harness": "Claude Code", + "effort": "medium", + "runs": 1, + "fixed": 21, + "wallMinutes": 23, + "costUsd": 23.73, + "date": "2026-09-10" + }, + { + "model": "Fable 5.1", + "harness": "Claude Code", + "effort": "xhigh", + "runs": 1, + "fixed": 29, + "wallMinutes": 59.5, + "costUsd": 53.61, + "date": "2026-09-10" + }, + { + "model": "Fable 5.2", + "harness": "Claude Code", + "effort": "high", + "runs": 2, + "fixed": 43, + "wallMinutes": 39.5, + "costUsd": 46.67, + "date": "2026-11-10" + }, + { + "model": "Fable 5.2", + "harness": "Claude Code", + "effort": "low", + "runs": 2, + "fixed": 41, + "wallMinutes": 18.7, + "costUsd": 24.32, + "date": "2026-11-10" + }, + { + "model": "Fable 5.2", + "harness": "Claude Code", + "effort": "max", + "runs": 3, + "fixed": 58, + "wallMinutes": 142.8, + "costUsd": 139.65, + "date": "2026-11-09" + }, + { + "model": "Fable 5.2", + "harness": "Claude Code", + "effort": "medium", + "runs": 2, + "fixed": 41.5, + "wallMinutes": 19.8, + "costUsd": 26.55, + "date": "2026-11-10" + }, + { + "model": "Fable 5.2", + "harness": "Claude Code", + "effort": "xhigh", + "runs": 3, + "fixed": 49, + "wallMinutes": 57, + "costUsd": 61.01, + "date": "2026-11-10" + }, + { + "model": "Gemini 3.7 Flash", + "harness": "Antigravity CLI", + "effort": "high", + "runs": 1, + "fixed": 16, + "wallMinutes": 22.7, + "costUsd": 6.36, + "date": "2026-08-28" + }, + { + "model": "Gemini 3.7 Flash", + "harness": "Gemini CLI (retired) + model-pinning gateway", + "effort": "high", + "runs": 1, + "fixed": 22, + "wallMinutes": 96.8, + "costUsd": 8.43, + "date": "2026-08-24" + }, + { + "model": "Gemini 3.8 Flash", + "harness": "Antigravity CLI", + "effort": "high", + "runs": 3, + "fixed": 18, + "wallMinutes": 38.7, + "costUsd": 11.03, + "date": "2026-09-15" + }, + { + "model": "Gemini 4 Argon", + "harness": "Antigravity CLI", + "effort": "high", + "runs": 3, + "fixed": 40.7, + "wallMinutes": 56.5, + "costUsd": 7.16, + "date": "2026-10-14" + }, + { + "model": "Gemini 4 Argon", + "harness": "Antigravity CLI", + "effort": "low", + "runs": 3, + "fixed": 35.3, + "wallMinutes": 59.6, + "costUsd": 6.47, + "date": "2026-10-14" + }, + { + "model": "Gemini 4 Argon", + "harness": "Antigravity CLI", + "effort": "medium", + "runs": 3, + "fixed": 39.3, + "wallMinutes": 59.9, + "costUsd": 7.5, + "date": "2026-10-14" + }, + { + "model": "Gemini 4 Carbon", + "harness": "Antigravity CLI", + "effort": "high", + "runs": 3, + "fixed": 57.3, + "wallMinutes": 114, + "costUsd": 31.32, + "date": "2026-11-10" + }, + { + "model": "Gemini 4 Carbon", + "harness": "Antigravity CLI", + "effort": "low", + "runs": 3, + "fixed": 46, + "wallMinutes": 60.4, + "costUsd": 7.67, + "date": "2026-11-13" + }, + { + "model": "Gemini 4 Carbon", + "harness": "Antigravity CLI", + "effort": "medium", + "runs": 3, + "fixed": 56, + "wallMinutes": 81.1, + "costUsd": 24.95, + "date": "2026-11-10" + }, + { + "model": "Gemini 4 Hydrogen", + "harness": "Antigravity CLI", + "effort": "high", + "runs": 3, + "fixed": 28.3, + "wallMinutes": 22.4, + "costUsd": 4.42, + "date": "2026-11-13" + }, + { + "model": "Gemini 4 Hydrogen", + "harness": "Antigravity CLI", + "effort": "low", + "runs": 3, + "fixed": 10.3, + "wallMinutes": 7.2, + "costUsd": 0.43, + "date": "2026-11-13" + }, + { + "model": "Gemini 4 Hydrogen", + "harness": "Antigravity CLI", + "effort": "medium", + "runs": 3, + "fixed": 24.7, + "wallMinutes": 19.9, + "costUsd": 2.1, + "date": "2026-11-13" + }, + { + "model": "Gemini 4 Hydrogen", + "harness": "Antigravity CLI", + "effort": "xhigh", + "runs": 3, + "fixed": 32.7, + "wallMinutes": 35.8, + "costUsd": 7.07, + "date": "2026-11-13" + }, + { + "model": "Gemini 4 Neon", + "harness": "Antigravity CLI", + "effort": "high", + "runs": 3, + "fixed": 57, + "wallMinutes": 45.4, + "costUsd": 29.11, + "date": "2026-11-19" + }, + { + "model": "Gemini 4 Neon", + "harness": "Antigravity CLI", + "effort": "low", + "runs": 3, + "fixed": 29.7, + "wallMinutes": 10.8, + "costUsd": 5.29, + "date": "2026-11-19" + }, + { + "model": "Gemini 4 Neon", + "harness": "Antigravity CLI", + "effort": "medium", + "runs": 3, + "fixed": 47.7, + "wallMinutes": 24.5, + "costUsd": 12.84, + "date": "2026-11-19" + }, + { + "model": "Gemini 4 Neon", + "harness": "Antigravity CLI", + "effort": "xhigh", + "runs": 3, + "fixed": 63, + "wallMinutes": 75.9, + "costUsd": 46.34, + "date": "2026-11-19" + }, + { + "model": "Gemma 4 31B", + "harness": "Claude Code / OpenRouter", + "effort": "default", + "runs": 1, + "fixed": 4, + "wallMinutes": 221.8, + "costUsd": null, + "date": "2026-09-16" + }, + { + "model": "Gemma 4 31B 4-bit", + "harness": "Claude Code / OpenRouter", + "effort": "default", + "runs": 1, + "fixed": 3, + "wallMinutes": 24.9, + "costUsd": null, + "date": "2026-09-16" + }, + { + "model": "GLM-5.3", + "harness": "Claude Code / Z.ai API", + "effort": "max", + "runs": 1, + "fixed": 19, + "wallMinutes": 40.4, + "costUsd": 15.93, + "date": "2026-09-10" + }, + { + "model": "GLM-5.3 Flash", + "harness": "Claude Code / OpenRouter", + "effort": "default", + "runs": 1, + "fixed": 13, + "wallMinutes": 57.1, + "costUsd": null, + "date": "2026-08-27" + }, + { + "model": "GLM-5.3 Flash", + "harness": "Claude Code / Z.ai API", + "effort": "high", + "runs": 1, + "fixed": 16, + "wallMinutes": 62.3, + "costUsd": 0.94, + "date": "2026-09-13" + }, + { + "model": "GLM-5.3 Flash", + "harness": "Claude Code / Z.ai API", + "effort": "low", + "runs": 1, + "fixed": 9, + "wallMinutes": 29, + "costUsd": 0.42, + "date": "2026-09-13" + }, + { + "model": "GLM-5.3 Flash", + "harness": "Claude Code / Z.ai API", + "effort": "max", + "runs": 3, + "fixed": 17.7, + "wallMinutes": 63.2, + "costUsd": 1.03, + "date": "2026-09-15" + }, + { + "model": "GPT-5.6 Luna", + "harness": "Codex CLI", + "effort": "high", + "runs": 1, + "fixed": 13, + "wallMinutes": 64.1, + "costUsd": 0.57, + "date": "2026-07-31" + }, + { + "model": "GPT-5.6 Luna", + "harness": "Codex CLI", + "effort": "low", + "runs": 1, + "fixed": 4, + "wallMinutes": 5.8, + "costUsd": 0.1, + "date": "2026-08-27" + }, + { + "model": "GPT-5.6 Luna", + "harness": "Codex CLI", + "effort": "max", + "runs": 3, + "fixed": 31.3, + "wallMinutes": 187.1, + "costUsd": 3.15, + "date": "2026-09-22" + }, + { + "model": "GPT-5.6 Luna", + "harness": "Codex CLI", + "effort": "medium", + "runs": 1, + "fixed": 9, + "wallMinutes": 15.4, + "costUsd": 0.33, + "date": "2026-08-27" + }, + { + "model": "GPT-5.6 Luna", + "harness": "Codex CLI", + "effort": "xhigh", + "runs": 1, + "fixed": 23, + "wallMinutes": 135.6, + "costUsd": 2.5, + "date": "2026-08-28" + }, + { + "model": "GPT-5.6 Sol", + "harness": "Codex CLI", + "effort": "high", + "runs": 1, + "fixed": 34, + "wallMinutes": 66.7, + "costUsd": 33.92, + "date": "2026-07-31" + }, + { + "model": "GPT-5.6 Sol", + "harness": "Codex CLI", + "effort": "max", + "runs": 2, + "fixed": 43.5, + "wallMinutes": 253.1, + "costUsd": 95.35, + "date": "2026-09-16" + }, + { + "model": "GPT-5.6 Sol", + "harness": "Codex CLI", + "effort": "medium", + "runs": 1, + "fixed": 29, + "wallMinutes": 47.6, + "costUsd": 15.77, + "date": "2026-09-06" + }, + { + "model": "GPT-5.6 Sol", + "harness": "Codex CLI", + "effort": "xhigh", + "runs": 1, + "fixed": 39, + "wallMinutes": 126.2, + "costUsd": 52.75, + "date": "2026-08-28" + }, + { + "model": "GPT-5.6 Terra", + "harness": "Codex CLI", + "effort": "high", + "runs": 1, + "fixed": 18, + "wallMinutes": 28.1, + "costUsd": 5.89, + "date": "2026-08-27" + }, + { + "model": "GPT-5.6 Terra", + "harness": "Codex CLI", + "effort": "max", + "runs": 1, + "fixed": 32, + "wallMinutes": 159.7, + "costUsd": 27.98, + "date": "2026-08-27" + }, + { + "model": "GPT-5.6 Terra", + "harness": "Codex CLI", + "effort": "medium", + "runs": 1, + "fixed": 15, + "wallMinutes": 20.2, + "costUsd": 3.87, + "date": "2026-08-27" + }, + { + "model": "GPT-5.6 Terra", + "harness": "Codex CLI", + "effort": "xhigh", + "runs": 1, + "fixed": 20, + "wallMinutes": 56.6, + "costUsd": 8.98, + "date": "2026-08-28" + }, + { + "model": "GPT-6 Astra", + "harness": "Codex CLI", + "effort": "high", + "runs": 1, + "fixed": 35, + "wallMinutes": 40.5, + "costUsd": 20.6, + "date": "2026-09-04" + }, + { + "model": "GPT-6 Astra", + "harness": "Codex CLI", + "effort": "low", + "runs": 1, + "fixed": 27, + "wallMinutes": 32.1, + "costUsd": 11.69, + "date": "2026-09-05" + }, + { + "model": "GPT-6 Astra", + "harness": "Codex CLI", + "effort": "max", + "runs": 3, + "fixed": 45, + "wallMinutes": 89.8, + "costUsd": 33.03, + "date": "2026-09-14" + }, + { + "model": "GPT-6 Astra", + "harness": "Codex CLI", + "effort": "medium", + "runs": 1, + "fixed": 34, + "wallMinutes": 28, + "costUsd": 15.78, + "date": "2026-09-05" + }, + { + "model": "GPT-6 Astra", + "harness": "Codex CLI", + "effort": "xhigh", + "runs": 1, + "fixed": 43, + "wallMinutes": 58.8, + "costUsd": 24.22, + "date": "2026-09-04" + }, + { + "model": "GPT-6 Luna", + "harness": "Codex CLI", + "effort": "high", + "runs": 1, + "fixed": 9, + "wallMinutes": 24.4, + "costUsd": 0.13, + "date": "2026-09-23" + }, + { + "model": "GPT-6 Luna", + "harness": "Codex CLI", + "effort": "low", + "runs": 1, + "fixed": 4, + "wallMinutes": 19.3, + "costUsd": 0.2, + "date": "2026-09-23" + }, + { + "model": "GPT-6 Luna", + "harness": "Codex CLI", + "effort": "max", + "runs": 3, + "fixed": 18.3, + "wallMinutes": 99.2, + "costUsd": 0.52, + "date": "2026-09-23" + }, + { + "model": "GPT-6 Luna", + "harness": "Codex CLI", + "effort": "medium", + "runs": 1, + "fixed": 4, + "wallMinutes": 8.6, + "costUsd": 0.06, + "date": "2026-09-23" + }, + { + "model": "GPT-6 Luna", + "harness": "Codex CLI", + "effort": "xhigh", + "runs": 1, + "fixed": 14, + "wallMinutes": 57, + "costUsd": 0.39, + "date": "2026-09-23" + }, + { + "model": "GPT-6 Sol", + "harness": "Codex CLI", + "effort": "high", + "runs": 1, + "fixed": 20, + "wallMinutes": 33.9, + "costUsd": 4.16, + "date": "2026-09-23" + }, + { + "model": "GPT-6 Sol", + "harness": "Codex CLI", + "effort": "low", + "runs": 1, + "fixed": 6, + "wallMinutes": 11.1, + "costUsd": 1.08, + "date": "2026-09-23" + }, + { + "model": "GPT-6 Sol", + "harness": "Codex CLI", + "effort": "max", + "runs": 3, + "fixed": 29.3, + "wallMinutes": 63.4, + "costUsd": 9.33, + "date": "2026-09-23" + }, + { + "model": "GPT-6 Sol", + "harness": "Codex CLI", + "effort": "medium", + "runs": 1, + "fixed": 14, + "wallMinutes": 24.5, + "costUsd": 2.39, + "date": "2026-09-23" + }, + { + "model": "GPT-6 Sol", + "harness": "Codex CLI", + "effort": "xhigh", + "runs": 1, + "fixed": 25, + "wallMinutes": 51.4, + "costUsd": 7.67, + "date": "2026-09-23" + }, + { + "model": "GPT-6.1 Sol", + "harness": "Codex CLI", + "effort": "high", + "runs": 2, + "fixed": 36.5, + "wallMinutes": 70.3, + "costUsd": 3.26, + "date": "2026-09-30" + }, + { + "model": "GPT-6.1 Sol", + "harness": "Codex CLI", + "effort": "low", + "runs": 2, + "fixed": 22.5, + "wallMinutes": 25.4, + "costUsd": 1.34, + "date": "2026-10-01" + }, + { + "model": "GPT-6.1 Sol", + "harness": "Codex CLI", + "effort": "max", + "runs": 3, + "fixed": 44.3, + "wallMinutes": 139.3, + "costUsd": 5.88, + "date": "2026-09-30" + }, + { + "model": "GPT-6.1 Sol", + "harness": "Codex CLI", + "effort": "medium", + "runs": 2, + "fixed": 29, + "wallMinutes": 29.8, + "costUsd": 1.76, + "date": "2026-09-30" + }, + { + "model": "GPT-6.1 Sol", + "harness": "Codex CLI", + "effort": "xhigh", + "runs": 3, + "fixed": 42.7, + "wallMinutes": 98.7, + "costUsd": 4.35, + "date": "2026-09-30" + }, + { + "model": "GPT-6.1 Terra", + "harness": "Codex CLI", + "effort": "high", + "runs": 3, + "fixed": 9.7, + "wallMinutes": 12.6, + "costUsd": 0.56, + "date": "2026-10-26" + }, + { + "model": "GPT-6.1 Terra", + "harness": "Codex CLI", + "effort": "low", + "runs": 3, + "fixed": 6, + "wallMinutes": 10.1, + "costUsd": 0.3, + "date": "2026-10-27" + }, + { + "model": "GPT-6.1 Terra", + "harness": "Codex CLI", + "effort": "max", + "runs": 3, + "fixed": 40.7, + "wallMinutes": 37.3, + "costUsd": 3.88, + "date": "2026-10-26" + }, + { + "model": "GPT-6.1 Terra", + "harness": "Codex CLI", + "effort": "medium", + "runs": 3, + "fixed": 7.3, + "wallMinutes": 9.6, + "costUsd": 0.31, + "date": "2026-10-27" + }, + { + "model": "GPT-6.1 Terra", + "harness": "Codex CLI", + "effort": "xhigh", + "runs": 3, + "fixed": 11.3, + "wallMinutes": 15.9, + "costUsd": 0.75, + "date": "2026-10-26" + }, + { + "model": "GPT-6.2 Astra", + "harness": "Codex CLI", + "effort": "high", + "runs": 5, + "fixed": 59.6, + "wallMinutes": 48.5, + "costUsd": 19.84, + "date": "2026-11-18" + }, + { + "model": "GPT-6.2 Astra", + "harness": "Codex CLI", + "effort": "low", + "runs": 3, + "fixed": 46.3, + "wallMinutes": 17.7, + "costUsd": 7.28, + "date": "2026-11-18" + }, + { + "model": "GPT-6.2 Astra", + "harness": "Codex CLI", + "effort": "max", + "runs": 3, + "fixed": 62.7, + "wallMinutes": 121.8, + "costUsd": 28.35, + "date": "2026-11-18" + }, + { + "model": "GPT-6.2 Astra", + "harness": "Codex CLI", + "effort": "medium", + "runs": 3, + "fixed": 50.3, + "wallMinutes": 30.2, + "costUsd": 12.34, + "date": "2026-11-18" + }, + { + "model": "GPT-6.2 Astra", + "harness": "Codex CLI", + "effort": "xhigh", + "runs": 5, + "fixed": 60.2, + "wallMinutes": 84, + "costUsd": 22.82, + "date": "2026-11-18" + }, + { + "model": "GPT-6.2 Sol", + "harness": "Codex CLI", + "effort": "high", + "runs": 3, + "fixed": 49.7, + "wallMinutes": 42.4, + "costUsd": 4.14, + "date": "2026-11-18" + }, + { + "model": "GPT-6.2 Sol", + "harness": "Codex CLI", + "effort": "low", + "runs": 3, + "fixed": 36, + "wallMinutes": 18.9, + "costUsd": 1.96, + "date": "2026-11-18" + }, + { + "model": "GPT-6.2 Sol", + "harness": "Codex CLI", + "effort": "max", + "runs": 3, + "fixed": 54.7, + "wallMinutes": 68.2, + "costUsd": 7, + "date": "2026-11-18" + }, + { + "model": "GPT-6.2 Sol", + "harness": "Codex CLI", + "effort": "medium", + "runs": 3, + "fixed": 45.7, + "wallMinutes": 31.7, + "costUsd": 3.22, + "date": "2026-11-18" + }, + { + "model": "GPT-6.2 Sol", + "harness": "Codex CLI", + "effort": "xhigh", + "runs": 3, + "fixed": 49, + "wallMinutes": 41.4, + "costUsd": 3.89, + "date": "2026-11-18" + }, + { + "model": "gpt-oss-120b", + "harness": "Claude Code / OpenRouter", + "effort": "default", + "runs": 3, + "fixed": 0, + "wallMinutes": 3.7, + "costUsd": null, + "date": "2026-09-15" + }, + { + "model": "gpt-oss-20b", + "harness": "Claude Code / OpenRouter", + "effort": "default", + "runs": 3, + "fixed": 0, + "wallMinutes": 7.4, + "costUsd": null, + "date": "2026-09-15" + }, + { + "model": "Grok 4.5", + "harness": "Grok Build CLI (ACP)", + "effort": "high", + "runs": 1, + "fixed": 17, + "wallMinutes": 27.9, + "costUsd": null, + "date": "2026-08-06" + }, + { + "model": "Grok 4.6", + "harness": "Grok Build CLI (ACP)", + "effort": "high", + "runs": 1, + "fixed": 23, + "wallMinutes": 33, + "costUsd": null, + "date": "2026-08-28" + }, + { + "model": "Grok 4.6", + "harness": "Grok Build CLI (ACP)", + "effort": "low", + "runs": 1, + "fixed": 15, + "wallMinutes": 18, + "costUsd": null, + "date": "2026-08-27" + }, + { + "model": "Grok 4.6", + "harness": "Grok Build CLI (ACP)", + "effort": "medium", + "runs": 1, + "fixed": 22, + "wallMinutes": 26.5, + "costUsd": null, + "date": "2026-08-28" + }, + { + "model": "Grok 4.6", + "harness": "Grok Build CLI (ACP)", + "effort": "xhigh", + "runs": 3, + "fixed": 28.7, + "wallMinutes": 43.1, + "costUsd": null, + "date": "2026-09-14" + }, + { + "model": "Grok 4.7", + "harness": "Grok Build CLI (ACP)", + "effort": "high", + "runs": 3, + "fixed": 19.3, + "wallMinutes": 37.9, + "costUsd": null, + "date": "2026-09-21" + }, + { + "model": "Grok 4.7", + "harness": "Grok Build CLI (ACP)", + "effort": "low", + "runs": 3, + "fixed": 15.7, + "wallMinutes": 22.2, + "costUsd": null, + "date": "2026-09-21" + }, + { + "model": "Grok 4.7", + "harness": "Grok Build CLI (ACP)", + "effort": "medium", + "runs": 3, + "fixed": 26.7, + "wallMinutes": 30.7, + "costUsd": null, + "date": "2026-09-21" + }, + { + "model": "Grok 4.7", + "harness": "Grok Build CLI (ACP)", + "effort": "xhigh", + "runs": 5, + "fixed": 29, + "wallMinutes": 44.7, + "costUsd": null, + "date": "2026-10-08" + }, + { + "model": "Haiku 4.5", + "harness": "Claude Code", + "effort": "default", + "runs": 2, + "fixed": 1.5, + "wallMinutes": 16.9, + "costUsd": 2.22, + "date": "2026-10-08" + }, + { + "model": "Haiku 5.5", + "harness": "Claude Code", + "effort": "high", + "runs": 2, + "fixed": 16, + "wallMinutes": 19.3, + "costUsd": 3.56, + "date": "2026-10-07" + }, + { + "model": "Haiku 5.5", + "harness": "Claude Code", + "effort": "low", + "runs": 1, + "fixed": 11, + "wallMinutes": 8.7, + "costUsd": 1.61, + "date": "2026-10-08" + }, + { + "model": "Haiku 5.5", + "harness": "Claude Code", + "effort": "max", + "runs": 2, + "fixed": 21.5, + "wallMinutes": 32.5, + "costUsd": 5.83, + "date": "2026-10-07" + }, + { + "model": "Haiku 5.5", + "harness": "Claude Code", + "effort": "medium", + "runs": 1, + "fixed": 12, + "wallMinutes": 15.5, + "costUsd": 2.66, + "date": "2026-10-08" + }, + { + "model": "Haiku 5.5", + "harness": "Claude Code", + "effort": "xhigh", + "runs": 3, + "fixed": 18.3, + "wallMinutes": 24.1, + "costUsd": 4.8, + "date": "2026-10-07" + }, + { + "model": "Hy4 Preview", + "harness": "Claude Code / OpenRouter", + "effort": "default", + "runs": 1, + "fixed": 18, + "wallMinutes": 67.5, + "costUsd": null, + "date": "2026-08-28" + }, + { + "model": "Kimi K3", + "harness": "Claude Code / OpenRouter", + "effort": "default", + "runs": 1, + "fixed": 21, + "wallMinutes": 107.8, + "costUsd": 25.27, + "date": "2026-07-26" + }, + { + "model": "Kimi K3.1 Pro", + "harness": "Claude Code / Moonshot API", + "effort": "max", + "runs": 3, + "fixed": 36, + "wallMinutes": 64.8, + "costUsd": null, + "date": "2026-10-23" + }, + { + "model": "MiMo-V2.6-Flash", + "harness": "Claude Code / OpenRouter", + "effort": "default", + "runs": 3, + "fixed": 23.3, + "wallMinutes": 70.7, + "costUsd": null, + "date": "2026-09-22" + }, + { + "model": "MiMo-V2.6-Pro", + "harness": "Claude Code / OpenRouter", + "effort": "default", + "runs": 3, + "fixed": 22.7, + "wallMinutes": 90.9, + "costUsd": null, + "date": "2026-09-22" + }, + { + "model": "MiMo-V2.6-Pro", + "harness": "Claude Code / Xiaomi first-party", + "effort": "enabled", + "runs": 1, + "fixed": 18, + "wallMinutes": 74.9, + "costUsd": 0.59, + "date": "2026-09-22" + }, + { + "model": "Mistral Large 4", + "harness": "Claude Code / OpenRouter", + "effort": "high", + "runs": 3, + "fixed": 15, + "wallMinutes": 111.1, + "costUsd": null, + "date": "2026-10-07" + }, + { + "model": "Muse Spark 1.2", + "harness": "Claude Code / Meta API", + "effort": "xhigh", + "runs": 1, + "fixed": 17, + "wallMinutes": 35.7, + "costUsd": 13.99, + "date": "2026-08-06" + }, + { + "model": "Muse Spark 1.3", + "harness": "Muse Code / Meta API", + "effort": "high", + "runs": 3, + "fixed": 18.7, + "wallMinutes": 75.6, + "costUsd": 12.94, + "date": "2026-09-14" + }, + { + "model": "Muse Spark 1.3", + "harness": "Muse Code / Meta API", + "effort": "low", + "runs": 3, + "fixed": 9.7, + "wallMinutes": 36.4, + "costUsd": 5.61, + "date": "2026-09-14" + }, + { + "model": "Muse Spark 1.3", + "harness": "Muse Code / Meta API", + "effort": "max", + "runs": 5, + "fixed": 32.2, + "wallMinutes": 85.6, + "costUsd": 18.11, + "date": "2026-09-17" + }, + { + "model": "Muse Spark 1.3", + "harness": "Muse Code / Meta API", + "effort": "medium", + "runs": 3, + "fixed": 13, + "wallMinutes": 58.3, + "costUsd": 9.24, + "date": "2026-09-14" + }, + { + "model": "Muse Spark 1.3", + "harness": "Muse Code / Meta API", + "effort": "xhigh", + "runs": 3, + "fixed": 20.3, + "wallMinutes": 63.8, + "costUsd": 13.71, + "date": "2026-09-14" + }, + { + "model": "Muse Wonder 1.0", + "harness": "Muse Code / Meta API", + "effort": "max", + "runs": 3, + "fixed": 31.7, + "wallMinutes": 96.2, + "costUsd": 27.87, + "date": "2026-10-13" + }, + { + "model": "Muse Wonder Full 1.0", + "harness": "Muse Code / Meta API", + "effort": "max", + "runs": 2, + "fixed": 42, + "wallMinutes": 145.3, + "costUsd": null, + "date": "2026-10-14" + }, + { + "model": "Muse Wonder Full 1.0", + "harness": "Muse Code / Meta API", + "effort": "xhigh", + "runs": 2, + "fixed": 41.5, + "wallMinutes": 90.5, + "costUsd": null, + "date": "2026-10-14" + }, + { + "model": "Opus 4.8", + "harness": "Claude Code", + "effort": "high", + "runs": 1, + "fixed": 9, + "wallMinutes": 34.8, + "costUsd": 21.3, + "date": "2026-07-26" + }, + { + "model": "Opus 4.8", + "harness": "Claude Code", + "effort": "max", + "runs": 1, + "fixed": 15, + "wallMinutes": 108.8, + "costUsd": 58.11, + "date": "2026-09-10" + }, + { + "model": "Opus 5", + "harness": "Claude Code", + "effort": "high", + "runs": 1, + "fixed": 21, + "wallMinutes": 37.4, + "costUsd": 41.51, + "date": "2026-07-26" + }, + { + "model": "Opus 5", + "harness": "Claude Code", + "effort": "max", + "runs": 1, + "fixed": 27, + "wallMinutes": 60, + "costUsd": 54.94, + "date": "2026-08-01" + }, + { + "model": "Opus 5", + "harness": "Claude Code", + "effort": "medium", + "runs": 1, + "fixed": 24, + "wallMinutes": 30.5, + "costUsd": 37.4, + "date": "2026-08-27" + }, + { + "model": "Opus 5", + "harness": "Claude Code", + "effort": "xhigh", + "runs": 1, + "fixed": 26, + "wallMinutes": 49.9, + "costUsd": 63.25, + "date": "2026-08-28" + }, + { + "model": "Opus 5.5", + "harness": "Claude Code", + "effort": "high", + "runs": 3, + "fixed": 31.7, + "wallMinutes": 23.9, + "costUsd": 22.25, + "date": "2026-09-23" + }, + { + "model": "Opus 5.5", + "harness": "Claude Code", + "effort": "low", + "runs": 3, + "fixed": 22.3, + "wallMinutes": 11.5, + "costUsd": 8.34, + "date": "2026-09-23" + }, + { + "model": "Opus 5.5", + "harness": "Claude Code", + "effort": "max", + "runs": 3, + "fixed": 41.7, + "wallMinutes": 66.9, + "costUsd": 58.53, + "date": "2026-09-23" + }, + { + "model": "Opus 5.5", + "harness": "Claude Code", + "effort": "medium", + "runs": 3, + "fixed": 30.3, + "wallMinutes": 17, + "costUsd": 15.68, + "date": "2026-09-23" + }, + { + "model": "Opus 5.5", + "harness": "Claude Code", + "effort": "xhigh", + "runs": 3, + "fixed": 36, + "wallMinutes": 42.5, + "costUsd": 34.98, + "date": "2026-09-23" + }, + { + "model": "Ox Alpha (stealth)", + "harness": "Claude Code / OpenRouter", + "effort": "default", + "runs": 1, + "fixed": 16, + "wallMinutes": 59.4, + "costUsd": null, + "date": "2026-08-25" + }, + { + "model": "Pareto (ex-Union Alpha)", + "harness": "Claude Code / OpenRouter", + "effort": "default", + "runs": 3, + "fixed": 30.7, + "wallMinutes": 38.2, + "costUsd": 4.81, + "date": "2026-09-17" + }, + { + "model": "Qwen3.8-27B", + "harness": "Claude Code / Alibaba API", + "effort": "xhigh", + "runs": 3, + "fixed": 15, + "wallMinutes": 56.8, + "costUsd": 5.55, + "date": "2026-09-15" + }, + { + "model": "Qwen3.8-27B 8-bit", + "harness": "Claude Code / OpenRouter", + "effort": "default", + "runs": 3, + "fixed": 10.7, + "wallMinutes": 56.6, + "costUsd": null, + "date": "2026-09-16" + }, + { + "model": "Qwen3.8-Flash", + "harness": "Claude Code / Alibaba API", + "effort": "low", + "runs": 1, + "fixed": 23, + "wallMinutes": 98.1, + "costUsd": 1.37, + "date": "2026-09-11" + }, + { + "model": "Qwen3.8-Flash", + "harness": "Claude Code / Alibaba API", + "effort": "max", + "runs": 1, + "fixed": 26, + "wallMinutes": 97.3, + "costUsd": 1.81, + "date": "2026-09-11" + }, + { + "model": "Qwen3.8-Max", + "harness": "Claude Code / Alibaba API", + "effort": "max", + "runs": 3, + "fixed": 25.7, + "wallMinutes": 117.1, + "costUsd": 26.76, + "date": "2026-09-15" + }, + { + "model": "Sonnet 5", + "harness": "Claude Code", + "effort": "high", + "runs": 1, + "fixed": 9, + "wallMinutes": 32.8, + "costUsd": 11.38, + "date": "2026-07-26" + }, + { + "model": "Sonnet 5", + "harness": "Claude Code", + "effort": "max", + "runs": 1, + "fixed": 9, + "wallMinutes": 61.3, + "costUsd": 17.96, + "date": "2026-09-10" + }, + { + "model": "Sonnet 5.5", + "harness": "Claude Code", + "effort": "high", + "runs": 3, + "fixed": 34.3, + "wallMinutes": 27.9, + "costUsd": 19.85, + "date": "2026-09-29" + }, + { + "model": "Sonnet 5.5", + "harness": "Claude Code", + "effort": "low", + "runs": 3, + "fixed": 19, + "wallMinutes": 8.5, + "costUsd": 5.73, + "date": "2026-09-30" + }, + { + "model": "Sonnet 5.5", + "harness": "Claude Code", + "effort": "max", + "runs": 3, + "fixed": 51.3, + "wallMinutes": 287.1, + "costUsd": 154.03, + "date": "2026-09-29" + }, + { + "model": "Sonnet 5.5", + "harness": "Claude Code", + "effort": "medium", + "runs": 3, + "fixed": 23.3, + "wallMinutes": 17.4, + "costUsd": 11.11, + "date": "2026-09-30" + }, + { + "model": "Sonnet 5.5", + "harness": "Claude Code", + "effort": "xhigh", + "runs": 3, + "fixed": 36, + "wallMinutes": 72.7, + "costUsd": 42.86, + "date": "2026-09-29" + } + ] +} diff --git a/skills/hr-code-review/references/panel-recommendations.json b/skills/hr-code-review/references/panel-recommendations.json index f71bb2c0..6d77cec7 100644 --- a/skills/hr-code-review/references/panel-recommendations.json +++ b/skills/hr-code-review/references/panel-recommendations.json @@ -1,10 +1,13 @@ { "version": 1, - "reviewed": "2026-10-14", + "reviewed": "2026-11-21", "entries": [ { "id": "opus-5-5-bug-hunt", - "profiles": ["balanced"], + "kind": "board", + "profiles": [ + "balanced" + ], "task": "Find planted bugs: 105 across two repositories, count fixed", "model": "claude-opus-5-5", "harness": "Claude Code", @@ -14,7 +17,7 @@ "effort": "medium", "fixed": 30.3, "listCostUsd": 15.68, - "wallMinutes": 17.0 + "wallMinutes": 17 }, { "effort": "high", @@ -24,24 +27,27 @@ }, { "effort": "xhigh", - "fixed": 36.0, + "fixed": 36, "listCostUsd": 34.98, "wallMinutes": 42.5 } ], "sourceUrl": "https://bughunt.productcompass.pm/data/benchmark.json", - "checked": "2026-10-14", - "samples": "3 runs per effort, non-superseded rows; each run covers both repositories", + "checked": "2026-11-21", + "samples": "3 runs per effort, current rows; each run covers both repositories", "metric": "planted bugs fixed, mean of 3, out of 105", - "timeDefinition": "wall clock summed over both repositories; the board says these runs shared the machine with other work", + "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", "limitations": "Counts planted bugs, not review quality on real changes; repeated attempts are not independent replications; runs used a 1M context window, and the board says its older Opus 5 rows are not comparable to these; the board also lists low and max rungs that this entry leaves out", - "rationale": "Medium used about 30% less cost and 29% less time than high for 1.4 fewer bugs; xhigh found more bugs at much higher cost and time. Medium supports a balanced starting point, not equivalence", + "rationale": "xhigh fixed the most (36 of 105); medium fixed 5.7 fewer for 55% less cost and 60% less time. A lower effort supports a balanced starting point, not equivalence", "status": "current" }, { "id": "sonnet-5-5-bug-hunt", - "profiles": ["balanced"], + "kind": "board", + "profiles": [ + "balanced" + ], "task": "Find planted bugs: 105 across two repositories, count fixed", "model": "claude-sonnet-5-5", "harness": "Claude Code", @@ -55,24 +61,27 @@ }, { "effort": "xhigh", - "fixed": 36.0, + "fixed": 36, "listCostUsd": 42.86, "wallMinutes": 72.7 } ], "sourceUrl": "https://bughunt.productcompass.pm/data/benchmark.json", - "checked": "2026-10-14", - "samples": "3 runs per effort, non-superseded rows; each run covers both repositories", + "checked": "2026-11-21", + "samples": "3 runs per effort, current rows; each run covers both repositories", "metric": "planted bugs fixed, mean of 3, out of 105", "timeDefinition": "wall clock summed over both repositories; the board says the machine was idle for these runs, so the times do not compare with the Opus entry's", "costDefinition": "list-rate API price estimated from usage counts, summed over both repositories; the board notes its harness priced this model on another model's table, so the dollar figure is less certain than the usage counts", "limitations": "Same board limits as the Opus entry; its older Sonnet 5 rows are not comparable to these; the board also lists low, medium and max rungs that this entry leaves out", - "rationale": "At high and xhigh it found 34.3 and 36.0 planted bugs against Opus's 31.7 and 36.0, at similar cost ($19.85 and $42.86 against $22.25 and $34.98); the times are not comparable. Suggest it only where the user allows that model and effort", + "rationale": "xhigh fixed the most (36 of 105); high fixed 1.7 fewer for 54% less cost and 62% less time. Suggest it only where the user allows that model and effort", "status": "current" }, { "id": "muse-wonder-full-bug-hunt", - "profiles": ["balanced"], + "kind": "board", + "profiles": [ + "balanced" + ], "task": "Find planted bugs: 105 across two repositories, count fixed", "model": "muse-wonder-full-1.0", "harness": "Muse Code (Meta's agent CLI)", @@ -92,13 +101,87 @@ } ], "sourceUrl": "https://bughunt.productcompass.pm/data/benchmark.json", - "checked": "2026-10-14", - "samples": "2 runs per effort (xhigh 44 and 39, max 44 and 40); each run covers both repositories", + "checked": "2026-11-21", + "samples": "2 runs per effort, current rows; each run covers both repositories", "metric": "planted bugs fixed, mean of 2, out of 105", - "timeDefinition": "active wall clock summed over both repositories; the board says its machine was shared with other work, and the second run of each effort was resumed in segments across two Muse Code versions, so only its active time is counted", + "timeDefinition": "active wall clock summed over both repositories; the board says its machine was shared with other work, and some runs were resumed in segments, so only active time is counted", "costDefinition": "unknown: Meta publishes no price for this model, so no dollar figure is recorded", - "limitations": "Two runs per effort, and the board measures a median 1.7-point run-to-run move on three-run configurations, so the 0.5-point gap between xhigh and max is not a difference; the board lists no high or lower rung; the board's own note says max led on one repository and xhigh on the other; reachable only through a Muse Code subscription plan, so it fits a user who already has one; its usage draws on that plan's rolling windows, which the board does not measure", - "rationale": "xhigh fixed 41.5 planted bugs against Opus 5.5 xhigh's 36.0 and Sonnet 5.5 xhigh's 36.0, in a time the board says is loosely comparable at best, and max added nothing clear for 55 more minutes. Suggest it as an additional seat from a different model family where the user has a Muse Code plan and allows the effort; start at xhigh, and use max only on request", + "limitations": "Few runs per effort, and the board measures a median run-to-run move of about a point and a half on three-run configurations, so a gap of that size between efforts is not a difference; the board lists no high or lower rung; reachable only through a Muse Code subscription plan, so it fits a user who already has one; its usage draws on that plan's rolling windows, which the board does not measure", + "rationale": "max fixed 42 and xhigh 41.5 of 105, a gap within the board's run-to-run spread, so the efforts are not distinguishable on fixed bugs. Suggest it as an additional seat from a different model family where the user has a Muse Code plan and allows the effort; start at xhigh, and use max only on request", + "status": "current" + }, + { + "id": "gpt-6-2-astra-bug-hunt", + "kind": "board", + "profiles": [ + "balanced" + ], + "task": "Find planted bugs: 105 across two repositories, count fixed", + "model": "gpt-6.2-astra", + "harness": "Codex CLI", + "route": "OpenAI Codex CLI on a ChatGPT account; no per-use price", + "efforts": [ + { + "effort": "medium", + "fixed": 50.3, + "listCostUsd": 12.34, + "wallMinutes": 30.2 + }, + { + "effort": "high", + "fixed": 59.6, + "listCostUsd": 19.84, + "wallMinutes": 48.5 + }, + { + "effort": "xhigh", + "fixed": 60.2, + "listCostUsd": 22.82, + "wallMinutes": 84 + } + ], + "sourceUrl": "https://bughunt.productcompass.pm/data/benchmark.json", + "checked": "2026-11-21", + "samples": "3 to 5 runs per effort, current rows; each run covers both repositories", + "metric": "planted bugs fixed, mean of 3 to 5, out of 105", + "timeDefinition": "wall clock summed over both repositories on cloud machines, not the laptop most other rows ran on, so it does not compare with them", + "costDefinition": "list-rate API price estimated from usage counts, summed over both repositories; not an invoice or subscription billing", + "limitations": "Counts planted bugs, not review quality on real changes; the board ran every GPT-6.2 row with file timestamps flattened and a newer Codex than earlier OpenAI rows, so a gap against them is model plus client plus machine; the board also lists low and max rungs that this entry leaves out; list cost is an estimate, not what a ChatGPT plan charges", + "rationale": "xhigh fixed the most (60.2 of 105); medium fixed 9.9 fewer for 46% less cost and 64% less time. A lower effort supports a balanced starting point, not equivalence; suggest it where the user has a Codex plan and allows the model and effort", + "status": "current" + }, + { + "id": "gemini-4-neon-bug-hunt", + "kind": "board", + "profiles": [ + "balanced" + ], + "task": "Find planted bugs: 105 across two repositories, count fixed", + "model": "gemini-4-neon", + "harness": "Antigravity CLI", + "route": "Google AI Ultra subscription through the Antigravity CLI", + "efforts": [ + { + "effort": "high", + "fixed": 57, + "listCostUsd": 29.11, + "wallMinutes": 45.4 + }, + { + "effort": "xhigh", + "fixed": 63, + "listCostUsd": 46.34, + "wallMinutes": 75.9 + } + ], + "sourceUrl": "https://bughunt.productcompass.pm/data/benchmark.json", + "checked": "2026-11-21", + "samples": "3 runs per effort, current rows; each run covers both repositories", + "metric": "planted bugs fixed, mean of 3, out of 105", + "timeDefinition": "wall clock summed over both repositories on a laptop, excluding the waits for the subscription's usage windows to reopen", + "costDefinition": "list-rate API price estimated from usage counts, summed over both repositories; not an invoice or subscription billing", + "limitations": "Counts planted bugs, not review quality on real changes; runs were resumed after the subscription's five-hour usage window ran out, so a user on a smaller plan may hit that limit sooner; the board also lists low and medium rungs that this entry leaves out; list cost is an estimate from the CLI's own usage counts, sub-agents included", + "rationale": "xhigh fixed the most (63 of 105); high fixed 6 fewer for 37% less cost and 40% less time. Suggest it as an additional seat from a different model family where the user has a Google AI Ultra plan and allows the effort", "status": "current" } ] diff --git a/skills/hr-code-review/references/panel-recommendations.md b/skills/hr-code-review/references/panel-recommendations.md index aebae06e..9a6c6e56 100644 --- a/skills/hr-code-review/references/panel-recommendations.md +++ b/skills/hr-code-review/references/panel-recommendations.md @@ -26,7 +26,7 @@ and say that no recorded evidence backs a seat choice. ## Reading an entry -Each entry names the task the evidence measures, the exact model and effort, the +Each entry (`kind: "board"` unless it says otherwise) names the task the evidence measures, the exact model and effort, the harness and route, the source URL, the date it was checked, the number of runs, the quality metric and its definitions of time and cost, the limits of the evidence and why it is suggested. A value that was not recorded is the string `unknown`. @@ -39,8 +39,25 @@ why it is suggested. A value that was not recorded is the string `unknown`. ## Updating +The catalog is generated, so do not edit [`panel-recommendations.json`](panel-recommendations.json) +by hand. `scripts/refresh-recommendations.mjs` builds it from three files in this +folder: the source spec (`panel-recommendations.sources.json`: which board rows each +entry uses, plus the route, limits and advice that no board states), the board +snapshot (`panel-board-snapshot.json`: the board's current rows, fetched by +`--fetch`) and the own results (`panel-recommendations.own.json`). `--check` runs +offline, with no clock and no network, and fails when the catalog is not what those +files generate. + Check an entry again when a model, route, price or benchmark correction changes the choice, and when preparing a release. Only changed entries need new evidence. An update shows the old and suggested choices, the evidence date, the expected tradeoff and the uncertainty; the user confirms before any saved preference changes, and installing a newer catalog leaves saved profiles and bindings alone. + +An entry with `kind: "own-evaluation"` is a maintainer's own result: model, effort, +defects found of the total, false share, minutes a review and a one-line cohort +description, with `provenance: "own-evaluation"` and no public source. It comes from +a case set this repository does not publish, so it cannot be reproduced here and does +not compare with the board entries. The generator accepts only a fixed set of plain +fields for it (no paths, links, addresses, credentials or free text beyond the cohort +line) and refuses any extra name the maintainer lists in a deny file. diff --git a/skills/hr-code-review/references/panel-recommendations.own.json b/skills/hr-code-review/references/panel-recommendations.own.json new file mode 100644 index 00000000..d8557c7e --- /dev/null +++ b/skills/hr-code-review/references/panel-recommendations.own.json @@ -0,0 +1,4 @@ +{ + "version": 1, + "results": [] +} diff --git a/skills/hr-code-review/references/panel-recommendations.sources.json b/skills/hr-code-review/references/panel-recommendations.sources.json new file mode 100644 index 00000000..f3b7aae7 --- /dev/null +++ b/skills/hr-code-review/references/panel-recommendations.sources.json @@ -0,0 +1,84 @@ +{ + "version": 1, + "board": { + "url": "https://bughunt.productcompass.pm/data/benchmark.json", + "task": "Find planted bugs: 105 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" + }, + "own": { + "task": "Find known defects in code changes under review", + "timeDefinition": "wall-clock minutes per review as recorded by the evaluator; reviews may have shared the machine with other work", + "limitations": "Measured by the repository owner on a private set of code-review cases that this repository does not publish, so it cannot be reproduced here; some of the cases also chose between seats, so treat the figure as the owner's result on the owner's cases, not a ranking; it does not compare with the board entries, which use a different task", + "rationaleTail": "A result on the owner's cases that a user can weigh beside the board entries, not a measured guarantee" + }, + "entries": [ + { + "id": "opus-5-5-bug-hunt", + "profiles": ["balanced"], + "model": "claude-opus-5-5", + "boardModel": "Opus 5.5", + "harness": "Claude Code", + "boardHarness": "Claude Code", + "route": "Anthropic first-party API", + "efforts": ["medium", "high", "xhigh"], + "limitations": "Counts planted bugs, not review quality on real changes; repeated attempts are not independent replications; runs used a 1M context window, and the board says its older Opus 5 rows are not comparable to these; the board also lists low and max rungs that this entry leaves out", + "rationaleTail": "A lower effort supports a balanced starting point, not equivalence" + }, + { + "id": "sonnet-5-5-bug-hunt", + "profiles": ["balanced"], + "model": "claude-sonnet-5-5", + "boardModel": "Sonnet 5.5", + "harness": "Claude Code", + "boardHarness": "Claude Code", + "route": "Anthropic first-party API", + "efforts": ["high", "xhigh"], + "timeDefinition": "wall clock summed over both repositories; the board says the machine was idle for these runs, so the times do not compare with the Opus entry's", + "costDefinition": "list-rate API price estimated from usage counts, summed over both repositories; the board notes its harness priced this model on another model's table, so the dollar figure is less certain than the usage counts", + "limitations": "Same board limits as the Opus entry; its older Sonnet 5 rows are not comparable to these; the board also lists low, medium and max rungs that this entry leaves out", + "rationaleTail": "Suggest it only where the user allows that model and effort" + }, + { + "id": "muse-wonder-full-bug-hunt", + "profiles": ["balanced"], + "model": "muse-wonder-full-1.0", + "boardModel": "Muse Wonder Full 1.0", + "harness": "Muse Code (Meta's agent CLI)", + "boardHarness": "Muse Code / Meta API", + "route": "Meta API through a Muse Code subscription plan; no per-use price", + "efforts": ["xhigh", "max"], + "timeDefinition": "active wall clock summed over both repositories; the board says its machine was shared with other work, and some runs were resumed in segments, so only active time is counted", + "costDefinition": "unknown: Meta publishes no price for this model, so no dollar figure is recorded", + "limitations": "Few runs per effort, and the board measures a median run-to-run move of about a point and a half on three-run configurations, so a gap of that size between efforts is not a difference; the board lists no high or lower rung; reachable only through a Muse Code subscription plan, so it fits a user who already has one; its usage draws on that plan's rolling windows, which the board does not measure", + "rationaleTail": "Suggest it as an additional seat from a different model family where the user has a Muse Code plan and allows the effort; start at xhigh, and use max only on request" + }, + { + "id": "gpt-6-2-astra-bug-hunt", + "profiles": ["balanced"], + "model": "gpt-6.2-astra", + "boardModel": "GPT-6.2 Astra", + "harness": "Codex CLI", + "boardHarness": "Codex CLI", + "route": "OpenAI Codex CLI on a ChatGPT account; no per-use price", + "efforts": ["medium", "high", "xhigh"], + "timeDefinition": "wall clock summed over both repositories on cloud machines, not the laptop most other rows ran on, so it does not compare with them", + "limitations": "Counts planted bugs, not review quality on real changes; the board ran every GPT-6.2 row with file timestamps flattened and a newer Codex than earlier OpenAI rows, so a gap against them is model plus client plus machine; the board also lists low and max rungs that this entry leaves out; list cost is an estimate, not what a ChatGPT plan charges", + "rationaleTail": "A lower effort supports a balanced starting point, not equivalence; suggest it where the user has a Codex plan and allows the model and effort" + }, + { + "id": "gemini-4-neon-bug-hunt", + "profiles": ["balanced"], + "model": "gemini-4-neon", + "boardModel": "Gemini 4 Neon", + "harness": "Antigravity CLI", + "boardHarness": "Antigravity CLI", + "route": "Google AI Ultra subscription through the Antigravity CLI", + "efforts": ["high", "xhigh"], + "timeDefinition": "wall clock summed over both repositories on a laptop, excluding the waits for the subscription's usage windows to reopen", + "limitations": "Counts planted bugs, not review quality on real changes; runs were resumed after the subscription's five-hour usage window ran out, so a user on a smaller plan may hit that limit sooner; the board also lists low and medium rungs that this entry leaves out; list cost is an estimate from the CLI's own usage counts, sub-agents included", + "rationaleTail": "Suggest it as an additional seat from a different model family where the user has a Google AI Ultra plan and allows the effort" + } + ] +} diff --git a/skills/hr-code-review/scripts/refresh-recommendations.mjs b/skills/hr-code-review/scripts/refresh-recommendations.mjs new file mode 100644 index 00000000..dd7af52f --- /dev/null +++ b/skills/hr-code-review/scripts/refresh-recommendations.mjs @@ -0,0 +1,530 @@ +// Regenerates references/panel-recommendations.json from the Bug Hunt board snapshot, the source +// spec and the sanitized own-results file, so the catalog follows its evidence and is not +// edited by hand. +// +// bun scripts/refresh-recommendations.mjs regenerate the catalog from the committed files +// bun scripts/refresh-recommendations.mjs --fetch read the public board, rewrite the snapshot, regenerate +// bun scripts/refresh-recommendations.mjs --fetch --board-file board.json the same from a saved board file +// bun scripts/refresh-recommendations.mjs --from-file own.json [--deny-file words.txt] +// sanitize own results, rewrite the own file, regenerate +// bun scripts/refresh-recommendations.mjs --check [--deny-file words.txt] +// offline: fail when the catalog is not what the +// committed files generate; no clock, no network +// +// Any other argument, a conflicting pair of modes or an empty value is an error (exit 2). +import { + copyFileSync, + existsSync, + mkdtempSync, + readFileSync, + renameSync, + rmSync, + writeFileSync, +} from "node:fs"; +import { tmpdir } from "node:os"; +import { dirname, join, resolve } from "node:path"; +import { fileURLToPath, pathToFileURL } from "node:url"; +import { parseArgs } from "node:util"; + +const skill = resolve(dirname(fileURLToPath(import.meta.url)), ".."); +const refs = join(skill, "references"); +/** @param {string} dir the references folder */ +export const pathsIn = (dir) => ({ + spec: join(dir, "panel-recommendations.sources.json"), + snapshot: join(dir, "panel-board-snapshot.json"), + own: join(dir, "panel-recommendations.own.json"), + catalog: join(dir, "panel-recommendations.json"), +}); + +const DATE = /^\d{4}-\d{2}-\d{2}$/; +/** @param {unknown} value a YYYY-MM-DD string that is a real calendar date */ +const isDate = (value) => { + if (typeof value !== "string" || !DATE.test(value)) { + return false; + } + const parsed = new Date(`${value}T00:00:00Z`); + return !Number.isNaN(parsed.getTime()) && parsed.toISOString().slice(0, 10) === value; +}; +/** Locale-free order, so a snapshot sorts the same on every machine. */ +const order = (/** @type {string} */ a, /** @type {string} */ b) => (a < b ? -1 : a > b ? 1 : 0); +const EFFORTS = ["none", "minimal", "low", "medium", "high", "xhigh", "max", "ultra", "default"]; +const MAX_BOARD_BYTES = 20 * 1024 * 1024; + +/** @param {string} path */ +const readJson = (path) => JSON.parse(readFileSync(path, "utf8")); + +/** + * Write several files so that a failure leaves none of them changed: every output is staged first, then the + * renames run back to back, and a failed rename puts the earlier files back. + * @param {Array<[string, unknown]>} outputs + */ +export function writeAll(outputs) { + const stage = mkdtempSync(join(tmpdir(), "refresh-recommendations-")); + try { + const staged = outputs.map(([path, value], i) => { + const file = join(stage, String(i)); + writeFileSync(file, `${JSON.stringify(value, null, 2)}\n`, { flag: "wx" }); + return { path, file, before: existsSync(path) ? readFileSync(path, "utf8") : undefined }; + }); + const done = []; + try { + for (const item of staged) { + copyFileSync(item.file, `${item.path}.new`); + renameSync(`${item.path}.new`, item.path); + done.push(item); + } + } catch (error) { + for (const item of done) { + if (item.before === undefined) { + rmSync(item.path, { force: true }); + } else { + writeFileSync(item.path, item.before); + } + } + for (const item of staged) { + rmSync(`${item.path}.new`, { force: true }); + } + throw error; + } + } finally { + rmSync(stage, { recursive: true, force: true }); + } +} + +/** + * The rows the catalog can use, from a full board: current rows only (a superseded row is the receipt of an + * earlier figure), with the fields this tool reads. + * @param {any} board + * @param {string} fetched + */ +export function reduceBoard(board, fetched) { + if (!DATE.test(fetched)) { + throw new Error(`fetched date ${fetched} is not YYYY-MM-DD`); + } + if (!Array.isArray(board?.runs) || typeof board?.meta?.planted_total !== "number") { + throw new Error("the board file has no runs list or planted total: its layout changed"); + } + const rows = board.runs + .filter((/** @type {any} */ r) => r.superseded === null || r.superseded === undefined) + .map((/** @type {any} */ r) => { + 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`); + } + return r; + }) + .map((/** @type {any} */ r) => ({ + model: String(r.model), + harness: String(r.harness), + effort: String(r.effort), + runs: Number(r.n_runs), + fixed: Number(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), + })); + for (const row of rows) { + if (!Number.isFinite(row.runs) || !Number.isFinite(row.fixed) || !isDate(row.date)) { + throw new Error(`board row ${row.model} ${row.effort} has a figure this tool cannot read`); + } + } + return { + version: 1, + fetched, + boardUpdated: String(board.meta.updated ?? "unknown"), + plantedTotal: board.meta.planted_total, + rows: rows.toSorted( + (/** @type {any} */ a, /** @type {any} */ b) => + order(a.model, b.model) || order(a.harness, b.harness) || order(a.effort, b.effort), + ), + }; +} + +/** + * The strings an own result may carry: a fixed set of keys, numbers, effort names and one short plain-text + * cohort line. Anything that could name a private repository, path, case or account is refused; extra words to + * refuse (private names this repository must not know) come from `deny`. + * @param {any} input + * @param {string[]} [deny] + */ +export function sanitizeOwn(input, deny = []) { + /** @type {string[]} */ + const problems = []; + if (input?.version !== 1 || !Array.isArray(input.results)) { + throw new Error("own results: expected { version: 1, results: [...] }"); + } + const keys = new Set([ + "id", + "model", + "harness", + "effort", + "found", + "of", + "falseSharePercent", + "wallMinutesPerReview", + "cohort", + "checked", + ]); + const ID = /^[a-z0-9][a-z0-9-]{1,60}$/; + const MODEL = /^[a-z0-9][a-z0-9.-]{1,60}$/; + const PLAIN = /^[A-Za-z0-9][A-Za-z0-9 ,.%()+:;'-]{0,139}$/; + const NAME = /^[A-Za-z0-9][A-Za-z0-9 .+-]{0,39}$/; + // Compared with case, spacing and punctuation removed, so "Internal Tool" and "internal_tool" match "internal-tool". + const squash = (/** @type {string} */ s) => s.toLowerCase().replace(/[^a-z0-9]/g, ""); + const lowered = deny.map(squash).filter((w) => w !== ""); + const seen = new Set(); + const results = input.results.map((/** @type {any} */ r, /** @type {number} */ i) => { + const at = `results[${i}]`; + for (const key of Object.keys(r ?? {})) { + if (!keys.has(key)) { + problems.push(`${at}: field ${key} is not allowed`); + } + } + const text = (/** @type {string} */ key, /** @type {RegExp} */ pattern) => { + const value = r?.[key]; + if (typeof value !== "string" || !pattern.test(value)) { + problems.push(`${at}.${key}: not a plain value of the allowed shape`); + return ""; + } + if (/api[_-]?key|token|secret|password|passwd|bearer|credential/i.test(value)) { + problems.push(`${at}.${key}: names a credential`); + } + for (const word of lowered) { + if (squash(value).includes(word)) { + problems.push(`${at}.${key}: contains a name this repository must not carry`); + } + } + return value; + }; + const number = ( + /** @type {string} */ key, + /** @type {number} */ min, + /** @type {number} */ max, + ) => { + const value = r?.[key]; + if (typeof value !== "number" || !Number.isFinite(value) || value < min || value > max) { + problems.push(`${at}.${key}: expected a number from ${min} to ${max}`); + return 0; + } + return value; + }; + const checked = text("checked", DATE); + if (checked !== "" && !isDate(checked)) { + problems.push(`${at}.checked: not a real date`); + } + const id = text("id", ID); + if (seen.has(id)) { + problems.push(`${at}.id: duplicate ${id}`); + } + seen.add(id); + const effort = r?.effort; + if (!EFFORTS.includes(effort)) { + problems.push(`${at}.effort: not one of ${EFFORTS.join(", ")}`); + } + const of = number("of", 1, 100000); + const found = number("found", 0, of); + return { + id, + model: text("model", MODEL), + harness: text("harness", NAME), + effort, + found, + of, + falseSharePercent: number("falseSharePercent", 0, 100), + wallMinutesPerReview: number("wallMinutesPerReview", 0, 100000), + cohort: text("cohort", PLAIN), + checked, + }; + }); + if (problems.length > 0) { + throw new Error(`own results refused:\n${problems.join("\n")}`); + } + return { version: 1, results }; +} + +/** @param {number} n */ +const round = (n) => Math.round(n * 10) / 10; + +/** + * The newest current row for each wanted effort; a wanted effort with no row is an error naming it. + * @param {any} snapshot + * @param {any} entry + */ +function boardRows(snapshot, entry) { + return entry.efforts.map((/** @type {string} */ effort) => { + const candidates = snapshot.rows + .filter( + (/** @type {any} */ r) => + r.model === entry.boardModel && r.harness === entry.boardHarness && r.effort === effort, + ) + .toSorted( + (/** @type {any} */ a, /** @type {any} */ b) => order(b.date, a.date) || b.runs - a.runs, + ); + if (candidates.length === 0) { + throw new Error( + `${entry.id}: the board has no current ${entry.boardModel} ${effort} row for ${entry.boardHarness}`, + ); + } + return candidates[0]; + }); +} + +/** + * @param {any} rows board rows of one entry, in effort order + * @param {number} total + * @param {number} noisePoints a gap in fixed bugs below this is run-to-run spread + */ +function boardRationale(rows, total, noisePoints) { + const best = rows.reduce((/** @type {any} */ a, /** @type {any} */ b) => + b.fixed > a.fixed ? b : a, + ); + const fewest = rows.reduce((/** @type {any} */ a, /** @type {any} */ b) => + b.fixed < a.fixed ? b : a, + ); + if (rows.length < 2 || best === fewest) { + return `${best.effort} fixed ${best.fixed} of ${total} planted bugs.`; + } + const gap = round(best.fixed - fewest.fixed); + if (gap < noisePoints) { + return `${best.effort} fixed ${best.fixed} and ${fewest.effort} ${fewest.fixed} of ${total}, a gap within the board's run-to-run spread, so the efforts are not distinguishable on fixed bugs.`; + } + // A saving is stated only when it is one: a lower-fixing rung that costs more or runs longer says nothing. + const saved = (/** @type {string} */ key) => { + const pct = + best[key] > 0 && fewest[key] !== null && best[key] !== null + ? Math.round((1 - fewest[key] / best[key]) * 100) + : 0; + return pct > 0 ? pct : undefined; + }; + const cost = saved("costUsd"); + const time = saved("wallMinutes"); + const parts = [ + ...(cost === undefined ? [] : [`${cost}% less cost`]), + ...(time === undefined ? [] : [`${time}% less time`]), + ]; + return ( + `${best.effort} fixed the most (${best.fixed} of ${total}); ${fewest.effort} fixed ${gap} fewer` + + (parts.length > 0 ? ` for ${parts.join(" and ")}` : "") + + "." + ); +} + +/** + * The whole catalog from its three inputs. Pure: the same inputs give the same catalog. + * @param {any} spec + * @param {any} snapshot + * @param {any} own + */ +export function buildCatalog(spec, snapshot, own) { + const entries = spec.entries.map((/** @type {any} */ entry) => { + const rows = boardRows(snapshot, entry); + const runs = rows.map((/** @type {any} */ r) => r.runs); + const low = Math.min(...runs); + const high = Math.max(...runs); + return { + id: entry.id, + kind: "board", + profiles: entry.profiles, + task: spec.board.task, + model: entry.model, + harness: entry.harness, + route: entry.route, + efforts: rows.map((/** @type {any} */ r) => ({ + effort: r.effort, + fixed: r.fixed, + listCostUsd: r.costUsd ?? "unknown", + wallMinutes: r.wallMinutes ?? "unknown", + })), + sourceUrl: spec.board.url, + checked: snapshot.fetched, + samples: `${low === high ? `${low} runs` : `${low} to ${high} runs`} per effort, current rows; each run covers both repositories`, + metric: `planted bugs fixed, mean of ${low === high ? low : `${low} to ${high}`}, out of ${snapshot.plantedTotal}`, + timeDefinition: entry.timeDefinition ?? spec.board.timeDefinition, + costDefinition: entry.costDefinition ?? spec.board.costDefinition, + limitations: entry.limitations, + rationale: `${boardRationale(rows, snapshot.plantedTotal, spec.board.noisePoints)} ${entry.rationaleTail}`, + status: entry.status ?? "current", + }; + }); + const ownEntries = own.results.map((/** @type {any} */ r) => ({ + id: `own-${r.id}`, + kind: "own-evaluation", + provenance: "own-evaluation", + profiles: ["balanced"], + task: spec.own.task, + model: r.model, + harness: r.harness, + efforts: [ + { + effort: r.effort, + found: r.found, + of: r.of, + falseSharePercent: r.falseSharePercent, + wallMinutes: r.wallMinutesPerReview, + }, + ], + checked: r.checked, + samples: `${r.of} known defects across ${r.cohort}`, + metric: `known defects found, out of ${r.of}; false findings as a share of posted comments`, + timeDefinition: spec.own.timeDefinition, + costDefinition: "unknown", + limitations: spec.own.limitations, + rationale: `Found ${r.found} of ${r.of} (${Math.round((r.found / r.of) * 100)}%) with ${r.falseSharePercent}% false findings in ${r.wallMinutesPerReview} minutes a review. ${spec.own.rationaleTail}`, + status: "current", + })); + const dates = [snapshot.fetched, ...own.results.map((/** @type {any} */ r) => r.checked)]; + return { + version: 1, + reviewed: dates.toSorted().at(-1), + entries: [...entries, ...ownEntries], + }; +} + +/** + * @param {string} url + */ +export async function fetchBoard(url) { + const target = new URL(url); + if (target.protocol !== "https:") { + throw new Error(`refusing to fetch ${url}: only https`); + } + // A redirect would leave the host the spec names, so it is an error, not a hop. + const response = await fetch(target, { signal: AbortSignal.timeout(30000), redirect: "error" }); + if (!response.ok) { + throw new Error(`${url} answered ${response.status}`); + } + const bytes = new Uint8Array(await response.arrayBuffer()); + if (bytes.length > MAX_BOARD_BYTES) { + throw new Error(`${url} is larger than ${MAX_BOARD_BYTES} bytes`); + } + return JSON.parse(new TextDecoder().decode(bytes)); +} + +/** @param {string | undefined} file */ +const readDeny = (file) => + file === undefined + ? [] + : readFileSync(file, "utf8") + .split("\n") + .map((l) => l.trim()) + .filter(Boolean); + +const OPTIONS = /** @type {const} */ ({ + fetch: { type: "boolean" }, + check: { type: "boolean" }, + "from-file": { type: "string" }, + "deny-file": { type: "string" }, + "board-file": { type: "string" }, + today: { type: "string" }, +}); + +/** + * @param {string[]} argv + * @param {string} [today] + * @param {string} [dir] the references folder to read and write + */ +export async function run(argv, today = new Date().toISOString().slice(0, 10), dir = refs) { + const paths = pathsIn(dir); + let values; + try { + values = parseArgs({ + args: argv, + options: OPTIONS, + strict: true, + allowPositionals: false, + }).values; + for (const key of Object.keys(OPTIONS)) { + const given = argv.filter((a) => a === `--${key}` || a.startsWith(`--${key}=`)).length; + if (given > 1) { + throw new Error(`--${key} is given more than once`); + } + } + for (const key of /** @type {const} */ (["from-file", "deny-file", "board-file", "today"])) { + if (values[key] === "") { + throw new Error(`--${key} needs a value`); + } + } + if (values["from-file"] !== undefined && values["deny-file"] === undefined) { + // Fail closed: own results are published, and only the maintainer knows which names are private. + throw new Error("--from-file needs --deny-file (the names this repository must not carry)"); + } + const modes = [values.fetch === true, values.check === true, values["from-file"] !== undefined]; + if (modes.filter(Boolean).length > 1) { + throw new Error("--fetch, --check and --from-file are separate modes"); + } + if ( + values.check === true && + (values["board-file"] !== undefined || values.today !== undefined) + ) { + throw new Error("--check reads only the committed files"); + } + if ( + values.fetch !== true && + (values["board-file"] !== undefined || values.today !== undefined) + ) { + throw new Error("--board-file and --today go with --fetch"); + } + if (values.today !== undefined && !DATE.test(values.today)) { + throw new Error("--today is YYYY-MM-DD"); + } + } catch (error) { + console.error(`refresh-recommendations: ${/** @type {Error} */ (error).message}`); + return 2; + } + try { + const spec = readJson(paths.spec); + const deny = readDeny(values["deny-file"]); + let snapshot = readJson(paths.snapshot); + let own = sanitizeOwn(readJson(paths.own), deny); + if (values.fetch === true) { + const board = + values["board-file"] !== undefined + ? readJson(resolve(values["board-file"])) + : await fetchBoard(spec.board.url); + snapshot = reduceBoard(board, values.today ?? today); + } + if (values["from-file"] !== undefined) { + own = sanitizeOwn(readJson(resolve(values["from-file"])), deny); + } + const catalog = buildCatalog(spec, snapshot, own); + if (values.check === true) { + const committed = existsSync(paths.catalog) ? readJson(paths.catalog) : undefined; + if (JSON.stringify(committed) !== JSON.stringify(catalog)) { + const ids = new Set(catalog.entries.map((/** @type {any} */ e) => e.id)); + const behind = catalog.entries + .filter( + (/** @type {any} */ e) => + JSON.stringify(e) !== + JSON.stringify(committed?.entries?.find((/** @type {any} */ c) => c.id === e.id)), + ) + .map((/** @type {any} */ e) => e.id); + const extra = (committed?.entries ?? []) + .filter((/** @type {any} */ c) => !ids.has(c.id)) + .map((/** @type {any} */ c) => c.id); + console.error( + `refresh-recommendations: the catalog is not what the snapshot, spec and own results generate (differs: ${[...behind, ...extra].join(", ") || "header"}); run scripts/refresh-recommendations.mjs`, + ); + return 1; + } + console.log(`refresh-recommendations: catalog matches (${catalog.entries.length} entries)`); + return 0; + } + /** @type {Array<[string, unknown]>} */ + const outputs = [[paths.catalog, catalog]]; + if (values.fetch === true) { + outputs.unshift([paths.snapshot, snapshot]); + } + if (values["from-file"] !== undefined) { + outputs.unshift([paths.own, own]); + } + writeAll(outputs); + console.log(`refresh-recommendations: wrote the catalog (${catalog.entries.length} entries)`); + return 0; + } catch (error) { + console.error(`refresh-recommendations: ${/** @type {Error} */ (error).message}`); + return 1; + } +} + +if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) { + process.exitCode = await run(process.argv.slice(2)); +} diff --git a/skills/hr-code-review/test/panel-setup.test.mjs b/skills/hr-code-review/test/panel-setup.test.mjs index f1a9054d..97b965dd 100644 --- a/skills/hr-code-review/test/panel-setup.test.mjs +++ b/skills/hr-code-review/test/panel-setup.test.mjs @@ -12,13 +12,12 @@ const catalog = JSON.parse(read("references/panel-recommendations.json")); const fields = [ "id", + "kind", "profiles", "task", "model", "harness", - "route", "efforts", - "sourceUrl", "checked", "samples", "metric", @@ -28,6 +27,8 @@ const fields = [ "rationale", "status", ]; +// A board entry also names its route and its public source; an own-evaluation entry names its provenance. +const boardFields = ["route", "sourceUrl"]; test("every catalog entry records the evidence the setup procedure promises", () => { assert.equal(catalog.version, 1); @@ -41,7 +42,16 @@ test("every catalog entry records the evidence the setup procedure promises", () assert(!ids.has(entry.id), `duplicate ${entry.id}`); ids.add(entry.id); assert.match(entry.checked, /^\d{4}-\d{2}-\d{2}$/); - assert.match(entry.sourceUrl, /^https:\/\//); + assert(["board", "own-evaluation"].includes(entry.kind), `${entry.id}: kind`); + if (entry.kind === "board") { + for (const field of boardFields) { + assert.notEqual(entry[field], undefined, `${entry.id}: ${field}`); + } + assert.match(entry.sourceUrl, /^https:\/\//); + } else { + assert.equal(entry.provenance, "own-evaluation", entry.id); + assert.equal(entry.sourceUrl, undefined, `${entry.id}: an own result has no public source`); + } assert(["current", "superseded", "withdrawn", "unverified"].includes(entry.status)); for (const profile of entry.profiles) { assert(["quick", "balanced", "deep"].includes(profile)); @@ -49,7 +59,11 @@ test("every catalog entry records the evidence the setup procedure promises", () assert(entry.efforts.length > 0); for (const row of entry.efforts) { assert.equal(typeof row.effort, "string"); - for (const value of [row.fixed, row.listCostUsd, row.wallMinutes]) { + const figures = + entry.kind === "board" + ? [row.fixed, row.listCostUsd, row.wallMinutes] + : [row.found, row.of, row.falseSharePercent, row.wallMinutes]; + for (const value of figures) { assert(value === "unknown" || Number.isFinite(value), `${entry.id}: ${row.effort}`); } } diff --git a/skills/hr-code-review/test/refresh-recommendations.test.mjs b/skills/hr-code-review/test/refresh-recommendations.test.mjs new file mode 100644 index 00000000..f6960b99 --- /dev/null +++ b/skills/hr-code-review/test/refresh-recommendations.test.mjs @@ -0,0 +1,371 @@ +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { cpSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { dirname, join, resolve } from "node:path"; +import { fileURLToPath } from "node:url"; +import { + buildCatalog, + fetchBoard, + pathsIn, + reduceBoard, + run, + sanitizeOwn, + writeAll, +} from "../scripts/refresh-recommendations.mjs"; + +const refs = resolve(dirname(fileURLToPath(import.meta.url)), "..", "references"); +const real = pathsIn(refs); +/** @param {string} path */ +const read = (path) => JSON.parse(readFileSync(path, "utf8")); + +/** A references folder copy that a test may write to; removed after the test. */ +async function inCopy(/** @type {(dir: string) => Promise | void} */ fn) { + const dir = mkdtempSync(join(tmpdir(), "refresh-rec-")); + try { + for (const path of Object.values(real)) { + cpSync(path, join(dir, path.slice(refs.length + 1))); + } + await fn(dir); + } finally { + rmSync(dir, { recursive: true, force: true }); + } +} + +const silent = async (/** @type {() => Promise} */ fn) => { + const err = console.error; + const log = console.log; + /** @type {string[]} */ + const lines = []; + console.error = (...a) => void lines.push(a.join(" ")); + console.log = (...a) => void lines.push(a.join(" ")); + try { + return { code: await fn(), text: lines.join("\n") }; + } finally { + console.error = err; + console.log = log; + } +}; + +const row = (/** @type {any} */ over = {}) => ({ + model: "Model A", + vendor: "V", + harness: "CLI A", + effort: "high", + n_runs: 3, + fixed: 30, + wall_min: 20, + cost_usd: 10, + cost_kind: "list", + date: "2026-11-01", + superseded: null, + ...over, +}); +const board = (/** @type {any[]} */ runs) => ({ + meta: { planted_total: 105, updated: "2026-11-02" }, + runs, +}); +const spec = { + board: { + url: "https://example.org/b.json", + task: "t", + timeDefinition: "td", + costDefinition: "cd", + }, + own: { task: "ot", timeDefinition: "otd", limitations: "ol", rationaleTail: "ort" }, + entries: [ + { + id: "a", + profiles: ["balanced"], + model: "model-a", + boardModel: "Model A", + harness: "CLI A", + boardHarness: "CLI A", + route: "r", + efforts: ["medium", "high"], + limitations: "l", + rationaleTail: "tail", + }, + ], +}; + +test("the committed catalog is what the snapshot, the spec and the own results generate", async () => { + const { code, text } = await silent(() => run(["--check"])); + assert.equal(code, 0, text); +}); + +test("a superseded row is dropped and the newest current row per effort is used", () => { + const snap = reduceBoard( + board([ + row({ effort: "medium", fixed: 20 }), + row({ effort: "high", fixed: 25, superseded: "Superseded by a later mean" }), + row({ effort: "high", fixed: 31, date: "2026-11-02" }), + ]), + "2026-11-03", + ); + assert.equal(snap.rows.length, 2); + const catalog = buildCatalog(spec, snap, { version: 1, results: [] }); + assert.deepEqual( + catalog.entries[0].efforts.map((/** @type {any} */ e) => [e.effort, e.fixed]), + [ + ["medium", 20], + ["high", 31], + ], + ); + assert.equal(catalog.entries[0].checked, "2026-11-03"); + assert.equal(catalog.reviewed, "2026-11-03"); + assert.match( + catalog.entries[0].rationale, + /high fixed the most \(31 of 105\); medium fixed 11 fewer\./, + ); +}); + +test("a wanted effort the board no longer lists is an error that names it", () => { + const snap = reduceBoard(board([row({ effort: "high" })]), "2026-11-03"); + assert.throws(() => buildCatalog(spec, snap, { version: 1, results: [] }), /Model A medium/); +}); + +test("a board whose layout changed is refused, not guessed at", () => { + assert.throws(() => reduceBoard({ runs: [] }, "2026-11-03"), /layout changed/); + assert.throws(() => reduceBoard(board([row({ fixed: "many" })]), "2026-11-03"), /cannot read/); + assert.throws(() => reduceBoard(board([]), "yesterday"), /YYYY-MM-DD/); +}); + +const good = { + id: "astra-62-medium-heldout", + model: "gpt-6.2-astra", + harness: "Codex CLI", + effort: "medium", + found: 80, + of: 141, + falseSharePercent: 0.2, + wallMinutesPerReview: 2.7, + cohort: "46 held-out code changes, judged blind by a second model", + checked: "2026-11-21", +}; +const own = (/** @type {any} */ over) => ({ version: 1, results: [{ ...good, ...over }] }); + +test("a sanitized own result becomes a catalog entry that says whose figure it is", () => { + const catalog = buildCatalog( + spec, + reduceBoard(board([row({ effort: "medium" }), row()]), "2026-11-03"), + sanitizeOwn(own({})), + ); + const entry = catalog.entries.at(-1); + assert.equal(entry.id, "own-astra-62-medium-heldout"); + assert.equal(entry.kind, "own-evaluation"); + assert.equal(entry.provenance, "own-evaluation"); + assert.equal(entry.sourceUrl, undefined); + assert.equal(entry.efforts[0].found, 80); + assert.equal(entry.limitations, "ol"); + assert.equal(catalog.reviewed, "2026-11-21"); +}); + +test("own results that could carry a private name, path, address or link are refused", () => { + const bad = [ + { id: "x/y" }, + { cohort: "cases from acme/widgets" }, + { cohort: "files under /home/someone/cases" }, + { cohort: "reported by someone@example.com" }, + { cohort: "see https://private.example/cases" }, + { cohort: "C:\\cases\\private" }, + { harness: "codex --api-key abc" }, + { model: "Model With Spaces" }, + { effort: "extreme" }, + { found: 200 }, + { falseSharePercent: -1 }, + { wallMinutesPerReview: "2" }, + { extra: "field" }, + ]; + for (const over of bad) { + assert.throws(() => sanitizeOwn(own(over)), /own results refused/, JSON.stringify(over)); + } + assert.throws(() => sanitizeOwn({ version: 1, results: [good, good] }), /duplicate/); + assert.throws(() => sanitizeOwn({ results: [] }), /expected/); +}); + +test("a name on the deny list is refused wherever it appears, whatever its case", () => { + assert.throws( + () => sanitizeOwn(own({ cohort: "46 Held-Out cases of Widget Co changes" }), ["widget co"]), + /must not carry/, + ); + assert.doesNotThrow(() => sanitizeOwn(own({}), ["widget co", ""])); +}); + +test("the committed own results and catalog name no private repository, path, address or credential", () => { + const text = JSON.stringify([read(real.own), read(real.catalog)]); + assert.doesNotMatch(text, /\/home\/|\/Users\/|api[_-]?key|token|@/i); + sanitizeOwn(read(real.own)); +}); + +test("--from-file sanitizes, rewrites the own file and the catalog, and --check then agrees", async () => { + await inCopy(async (dir) => { + const file = join(dir, "incoming.json"); + writeFileSync(file, JSON.stringify(own({}))); + const deny = join(dir, "deny.txt"); + writeFileSync(deny, "widget co\n"); + const done = await silent(() => + run(["--from-file", file, "--deny-file", deny], "2026-11-21", dir), + ); + assert.equal(done.code, 0, done.text); + assert.equal(read(join(dir, "panel-recommendations.own.json")).results.length, 1); + assert.equal( + read(join(dir, "panel-recommendations.json")).entries.at(-1).id, + "own-astra-62-medium-heldout", + ); + assert.equal((await silent(() => run(["--check"], "2026-11-21", dir))).code, 0); + // A hand edit of the catalog is what --check exists to catch. + const catalog = read(join(dir, "panel-recommendations.json")); + catalog.entries[0].efforts[0].fixed += 1; + writeFileSync(join(dir, "panel-recommendations.json"), JSON.stringify(catalog)); + const drift = await silent(() => run(["--check"], "2026-11-21", dir)); + assert.equal(drift.code, 1); + assert.match(drift.text, /differs: opus-5-5-bug-hunt/); + }); +}); + +test("a refused own file changes nothing", async () => { + await inCopy(async (dir) => { + const before = readFileSync(join(dir, "panel-recommendations.json"), "utf8"); + const file = join(dir, "incoming.json"); + writeFileSync(file, JSON.stringify(own({ cohort: "from /home/x" }))); + const deny = join(dir, "deny.txt"); + writeFileSync(deny, "held-out\n"); + const out = await silent(() => + run(["--from-file", file, "--deny-file", deny], "2026-11-21", dir), + ); + assert.equal(out.code, 1); + assert.equal(readFileSync(join(dir, "panel-recommendations.json"), "utf8"), before); + writeFileSync(file, JSON.stringify(own({}))); + assert.equal( + (await silent(() => run(["--from-file", file, "--deny-file", deny], "2026-11-21", dir))).code, + 1, + ); + }); +}); + +test("--fetch with a saved board rewrites the snapshot and regenerates", async () => { + await inCopy(async (dir) => { + const saved = join(dir, "board.json"); + writeFileSync(saved, JSON.stringify(board([row({ effort: "medium" }), row()]))); + writeFileSync(join(dir, "panel-recommendations.sources.json"), JSON.stringify(spec)); + const out = await silent(() => + run(["--fetch", "--board-file", saved, "--today", "2026-11-05"], "2026-11-21", dir), + ); + assert.equal(out.code, 0, out.text); + assert.equal(read(join(dir, "panel-board-snapshot.json")).fetched, "2026-11-05"); + assert.equal(read(join(dir, "panel-recommendations.json")).entries.length, 1); + }); +}); + +test("an unknown, positional, empty or conflicting argument is an error and writes nothing", async () => { + await inCopy(async (dir) => { + const before = readFileSync(join(dir, "panel-recommendations.json"), "utf8"); + for (const argv of [ + ["--unknown"], + ["stray"], + ["--from-file"], + ["--from-file="], + ["--from-file", "x.json"], + ["--from-file", "a.json", "--from-file", "b.json", "--deny-file", "d.txt"], + ["--check", "--check"], + ["--check", "--fetch"], + ["--check", "--from-file", "x.json"], + ["--fetch", "--from-file", "x.json"], + ["--check", "--today", "2026-11-05"], + ["--board-file", "x.json"], + ["--fetch", "--today", "yesterday"], + ]) { + const out = await silent(() => run(argv, "2026-11-21", dir)); + assert.equal(out.code, 2, `${argv.join(" ")}: ${out.text}`); + } + assert.equal(readFileSync(join(dir, "panel-recommendations.json"), "utf8"), before); + }); +}); + +test("a fetch goes only to https", async () => { + await assert.rejects(() => fetchBoard("http://example.org/b.json"), /only https/); +}); + +test("an own file is refused without a deny file, and a deny entry matches however it is spelled", async () => { + await inCopy(async (dir) => { + const file = join(dir, "incoming.json"); + writeFileSync(file, JSON.stringify(own({}))); + const out = await silent(() => run(["--from-file", file], "2026-11-21", dir)); + assert.equal(out.code, 2); + assert.match(out.text, /needs --deny-file/); + }); + // A name made of letters and hyphens passes the shape checks, so only a deny entry can stop it. + assert.doesNotThrow(() => sanitizeOwn(own({ cohort: "46 cases from internal-tool" }))); + for (const spelled of ["internal tool", "INTERNAL-TOOL", "Internal.Tool", "internaltool"]) { + assert.throws( + () => sanitizeOwn(own({ cohort: `46 cases from ${spelled}` }), ["internal-tool"]), + /must not carry/, + spelled, + ); + } +}); + +test("harness is a short name, not a second free-text field", () => { + assert.throws( + () => sanitizeOwn(own({ harness: "Codex CLI with a long description of the setup used" })), + /own results refused/, + ); + assert.throws(() => sanitizeOwn(own({ checked: "2026-13-45" })), /not a real date/); +}); + +test("the newest current row wins, then the one with more runs; a saving is stated only when it is one", () => { + const snap = reduceBoard( + board([ + row({ effort: "medium", fixed: 10, date: "2026-11-02", cost_usd: 30, wall_min: 50 }), + row({ effort: "medium", fixed: 20, date: "2026-11-01", cost_usd: 5, wall_min: 5 }), + row({ effort: "high", fixed: 40, date: "2026-11-02", n_runs: 2, cost_usd: 10, wall_min: 10 }), + row({ effort: "high", fixed: 41, date: "2026-11-02", n_runs: 5, cost_usd: 10, wall_min: 10 }), + ]), + "2026-11-03", + ); + const [entry] = buildCatalog(spec, snap, { version: 1, results: [] }).entries; + assert.deepEqual( + entry.efforts.map((/** @type {any} */ e) => [e.effort, e.fixed]), + [ + ["medium", 10], + ["high", 41], + ], + ); + // The lower-fixing rung costs more and takes longer, so no "less cost" or "less time" is claimed. + assert.match(entry.rationale, /^high fixed the most \(41 of 105\); medium fixed 31 fewer\.( |$)/); +}); + +test("a gap inside the board's run-to-run spread is not ranked", () => { + const snap = reduceBoard( + board([row({ effort: "medium", fixed: 40 }), row({ effort: "high", fixed: 40.5 })]), + "2026-11-03", + ); + const [entry] = buildCatalog({ ...spec, board: { ...spec.board, noisePoints: 1.5 } }, snap, { + version: 1, + results: [], + }).entries; + assert.match(entry.rationale, /not distinguishable/); +}); + +test("a board figure that is null or boolean is refused, not read as a number", () => { + assert.throws(() => reduceBoard(board([row({ fixed: null })]), "2026-11-03"), /cannot read/); + assert.throws(() => reduceBoard(board([row({ n_runs: true })]), "2026-11-03"), /cannot read/); +}); + +test("several outputs are written together or not at all", async () => { + await inCopy(async (dir) => { + const a = join(dir, "a.json"); + writeFileSync(a, "old a\n"); + // The second target's directory does not exist, so its rename fails and the first file is restored. + assert.throws(() => + writeAll([ + [a, { n: 1 }], + [join(dir, "missing-dir", "b.json"), { n: 2 }], + ]), + ); + assert.equal(readFileSync(a, "utf8"), "old a\n"); + writeAll([[a, { n: 3 }]]); + assert.deepEqual(read(a), { n: 3 }); + }); +}); From 5172ece1b4a0bb7af93c148c245aa94074b24816 Mon Sep 17 00:00:00 2001 From: bompus Date: Sat, 21 Nov 2026 12:44:20 -0700 Subject: [PATCH 2/8] Panel recommendations generator: credential and host screening, invocation-owned staging, byte-level check, refresh lock, input selection by mode, streamed fetch cap, spread-aware rationale --- .gitignore | 3 +- .../references/panel-recommendations.json | 4 +- .../scripts/refresh-recommendations.mjs | 376 +++++++++++++----- .../test/refresh-recommendations.test.mjs | 222 ++++++++++- 4 files changed, 490 insertions(+), 115 deletions(-) diff --git a/.gitignore b/.gitignore index d9c87cdb..642a9e7c 100644 --- a/.gitignore +++ b/.gitignore @@ -5,4 +5,5 @@ __pycache__/ .codegraph/ *.py[cod] -skills/hr-code-review/references/*.new +skills/hr-code-review/references/.refresh-* +skills/hr-code-review/references/.refresh.lock diff --git a/skills/hr-code-review/references/panel-recommendations.json b/skills/hr-code-review/references/panel-recommendations.json index 6d77cec7..e6c990fd 100644 --- a/skills/hr-code-review/references/panel-recommendations.json +++ b/skills/hr-code-review/references/panel-recommendations.json @@ -39,7 +39,7 @@ "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", "limitations": "Counts planted bugs, not review quality on real changes; repeated attempts are not independent replications; runs used a 1M context window, and the board says its older Opus 5 rows are not comparable to these; the board also lists low and max rungs that this entry leaves out", - "rationale": "xhigh fixed the most (36 of 105); medium fixed 5.7 fewer for 55% less cost and 60% less time. A lower effort supports a balanced starting point, not equivalence", + "rationale": "xhigh fixed the most (36 of 105); high fixed 4.3 fewer for 36% less cost and 44% less time; medium fixed 5.7 fewer for 55% less cost and 60% less time. A lower effort supports a balanced starting point, not equivalence", "status": "current" }, { @@ -147,7 +147,7 @@ "timeDefinition": "wall clock summed over both repositories on cloud machines, not the laptop most other rows ran on, so it does not compare with them", "costDefinition": "list-rate API price estimated from usage counts, summed over both repositories; not an invoice or subscription billing", "limitations": "Counts planted bugs, not review quality on real changes; the board ran every GPT-6.2 row with file timestamps flattened and a newer Codex than earlier OpenAI rows, so a gap against them is model plus client plus machine; the board also lists low and max rungs that this entry leaves out; list cost is an estimate, not what a ChatGPT plan charges", - "rationale": "xhigh fixed the most (60.2 of 105); medium fixed 9.9 fewer for 46% less cost and 64% less time. A lower effort supports a balanced starting point, not equivalence; suggest it where the user has a Codex plan and allows the model and effort", + "rationale": "xhigh fixed the most (60.2 of 105); high (59.6) is within the board's run-to-run spread of it for 13% less cost and 42% less time; medium fixed 9.9 fewer for 46% less cost and 64% less time. A lower effort supports a balanced starting point, not equivalence; suggest it where the user has a Codex plan and allows the model and effort", "status": "current" }, { diff --git a/skills/hr-code-review/scripts/refresh-recommendations.mjs b/skills/hr-code-review/scripts/refresh-recommendations.mjs index dd7af52f..efa39f47 100644 --- a/skills/hr-code-review/scripts/refresh-recommendations.mjs +++ b/skills/hr-code-review/scripts/refresh-recommendations.mjs @@ -13,15 +13,15 @@ // // Any other argument, a conflicting pair of modes or an empty value is an error (exit 2). import { - copyFileSync, + closeSync, existsSync, mkdtempSync, + openSync, readFileSync, renameSync, rmSync, writeFileSync, } from "node:fs"; -import { tmpdir } from "node:os"; import { dirname, join, resolve } from "node:path"; import { fileURLToPath, pathToFileURL } from "node:url"; import { parseArgs } from "node:util"; @@ -53,37 +53,50 @@ const MAX_BOARD_BYTES = 20 * 1024 * 1024; /** @param {string} path */ const readJson = (path) => JSON.parse(readFileSync(path, "utf8")); +/** 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`; + /** - * Write several files so that a failure leaves none of them changed: every output is staged first, then the - * renames run back to back, and a failed rename puts the earlier files back. + * Write several files of one folder so that a failure leaves none of them changed. Every output and every + * before image is staged in a new directory this call creates beside the targets (same filesystem); the + * renames then run back to back, and a failed rename puts the earlier files back. Nothing outside that + * directory is created, so an existing file of any name survives, and only that directory is removed. + * 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 */ export function writeAll(outputs) { - const stage = mkdtempSync(join(tmpdir(), "refresh-recommendations-")); + 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-")); try { const staged = outputs.map(([path, value], i) => { - const file = join(stage, String(i)); - writeFileSync(file, `${JSON.stringify(value, null, 2)}\n`, { flag: "wx" }); - return { path, file, before: existsSync(path) ? readFileSync(path, "utf8") : undefined }; + const file = join(stage, `new-${i}`); + writeFileSync(file, serialize(value), { flag: "wx" }); + /** @type {string | undefined} */ + let back; + if (existsSync(path)) { + back = join(stage, `old-${i}`); + writeFileSync(back, readFileSync(path), { flag: "wx" }); + } + return { path, file, back }; }); const done = []; try { for (const item of staged) { - copyFileSync(item.file, `${item.path}.new`); - renameSync(`${item.path}.new`, item.path); + renameSync(item.file, item.path); done.push(item); } } catch (error) { for (const item of done) { - if (item.before === undefined) { + if (item.back === undefined) { rmSync(item.path, { force: true }); } else { - writeFileSync(item.path, item.before); + renameSync(item.back, item.path); } } - for (const item of staged) { - rmSync(`${item.path}.new`, { force: true }); - } throw error; } } finally { @@ -91,6 +104,49 @@ export function writeAll(outputs) { } } +/** + * Run `fn` holding the folder's refresh lock, so two refreshes cannot interleave their read-build-write. + * A second refresh fails with a message that says to retry; a lock left by a dead process is taken over. + * @template T + * @param {string} dir + * @param {() => Promise} fn + */ +async function withLock(dir, fn) { + const lock = join(dir, ".refresh.lock"); + /** @type {number | undefined} */ + let fd; + for (let attempt = 0; fd === undefined; attempt++) { + try { + fd = openSync(lock, "wx"); + writeFileSync(fd, `${process.pid}\n`); + } catch (error) { + if (/** @type {any} */ (error).code !== "EEXIST") { + throw error; + } + const owner = Number.parseInt(readFileSync(lock, "utf8"), 10); + let alive = true; + try { + process.kill(owner, 0); + } catch (e) { + alive = /** @type {any} */ (e).code === "EPERM"; + } + if (alive || attempt > 0) { + throw new Error( + `another refresh holds ${lock} (process ${owner}); retry when it has finished`, + { cause: error }, + ); + } + rmSync(lock, { force: true }); + } + } + try { + return await fn(); + } finally { + closeSync(fd); + rmSync(lock, { force: true }); + } +} + /** * The rows the catalog can use, from a full board: current rows only (a superseded row is the receipt of an * earlier figure), with the fields this tool reads. @@ -98,8 +154,8 @@ export function writeAll(outputs) { * @param {string} fetched */ export function reduceBoard(board, fetched) { - if (!DATE.test(fetched)) { - throw new Error(`fetched date ${fetched} is not YYYY-MM-DD`); + if (!isDate(fetched)) { + throw new Error(`fetched date ${fetched} is not a real YYYY-MM-DD date`); } if (!Array.isArray(board?.runs) || typeof board?.meta?.planted_total !== "number") { throw new Error("the board file has no runs list or planted total: its layout changed"); @@ -139,6 +195,34 @@ export function reduceBoard(board, fetched) { }; } +/** + * Whether a published text looks like a credential, an address or a host: an assignment-style word, a + * provider key prefix, a long hex run, an IPv4 or IPv6 address, or (for free text) a host name or a very long + * token with digits. + * @param {string} value + * @param {boolean} [freeText] a cohort or harness line, where a host name or long token can hide + */ +export function looksSecret(value, freeText = false) { + if (/api[_-]?key|token|secret|password|passwd|bearer|credential/i.test(value)) { + return true; + } + if ( + /(?:^|[^A-Za-z0-9])(?:sk|pk|rk|ghp|gho|ghu|ghs|github_pat|xox[a-z]|AKIA|ASIA|AIza|eyJ)[-_A-Za-z0-9]{6,}/.test( + value, + ) || + /\b[0-9a-f]{16,}\b/i.test(value) || + /\b\d{1,3}(?:\.\d{1,3}){3}\b/.test(value) || + (value.match(/:/g) ?? []).length >= 2 + ) { + return true; + } + return ( + freeText && + (/[A-Za-z0-9-]+(?:\.[A-Za-z0-9-]+)*\.[A-Za-z]{2,}\b/.test(value) || + value.split(/\s+/).some((token) => token.length >= 24 && /\d/.test(token))) + ); +} + /** * The strings an own result may carry: a fixed set of keys, numbers, effort names and one short plain-text * cohort line. Anything that could name a private repository, path, case or account is refused; extra words to @@ -149,8 +233,12 @@ export function reduceBoard(board, fetched) { export function sanitizeOwn(input, deny = []) { /** @type {string[]} */ const problems = []; - if (input?.version !== 1 || !Array.isArray(input.results)) { - throw new Error("own results: expected { version: 1, results: [...] }"); + if ( + input?.version !== 1 || + !Array.isArray(input.results) || + Object.keys(input).some((key) => key !== "version" && key !== "results") + ) { + throw new Error("own results: expected exactly { version: 1, results: [...] }"); } const keys = new Set([ "id", @@ -179,14 +267,14 @@ export function sanitizeOwn(input, deny = []) { problems.push(`${at}: field ${key} is not allowed`); } } - const text = (/** @type {string} */ key, /** @type {RegExp} */ pattern) => { + const text = (/** @type {string} */ key, /** @type {RegExp} */ pattern, freeText = false) => { const value = r?.[key]; if (typeof value !== "string" || !pattern.test(value)) { problems.push(`${at}.${key}: not a plain value of the allowed shape`); return ""; } - if (/api[_-]?key|token|secret|password|passwd|bearer|credential/i.test(value)) { - problems.push(`${at}.${key}: names a credential`); + if (looksSecret(value, freeText)) { + problems.push(`${at}.${key}: looks like a credential, address or host`); } for (const word of lowered) { if (squash(value).includes(word)) { @@ -220,18 +308,26 @@ export function sanitizeOwn(input, deny = []) { if (!EFFORTS.includes(effort)) { problems.push(`${at}.effort: not one of ${EFFORTS.join(", ")}`); } + // The published id and every string built from the fields are screened as published, not as entered. + for (const word of lowered) { + if (squash(`own-${id}`).includes(word) || squash(String(effort)).includes(word)) { + problems.push( + `${at}: the published id or effort contains a name this repository must not carry`, + ); + } + } const of = number("of", 1, 100000); const found = number("found", 0, of); return { id, model: text("model", MODEL), - harness: text("harness", NAME), + harness: text("harness", NAME, true), effort, found, of, falseSharePercent: number("falseSharePercent", 0, 100), wallMinutesPerReview: number("wallMinutesPerReview", 0, 100000), - cohort: text("cohort", PLAIN), + cohort: text("cohort", PLAIN, true), checked, }; }); @@ -274,38 +370,45 @@ function boardRows(snapshot, entry) { * @param {number} noisePoints a gap in fixed bugs below this is run-to-run spread */ function boardRationale(rows, total, noisePoints) { - const best = rows.reduce((/** @type {any} */ a, /** @type {any} */ b) => - b.fixed > a.fixed ? b : a, - ); - const fewest = rows.reduce((/** @type {any} */ a, /** @type {any} */ b) => - b.fixed < a.fixed ? b : a, - ); - if (rows.length < 2 || best === fewest) { + const sorted = rows.toSorted((/** @type {any} */ a, /** @type {any} */ b) => b.fixed - a.fixed); + const best = sorted[0]; + if (sorted.length < 2) { return `${best.effort} fixed ${best.fixed} of ${total} planted bugs.`; } - const gap = round(best.fixed - fewest.fixed); - if (gap < noisePoints) { - return `${best.effort} fixed ${best.fixed} and ${fewest.effort} ${fewest.fixed} of ${total}, a gap within the board's run-to-run spread, so the efforts are not distinguishable on fixed bugs.`; + // An effort is indistinguishable from the leader when its gap is zero or inside the board's spread. + const within = (/** @type {any} */ r) => { + const gap = round(best.fixed - r.fixed); + return gap === 0 || gap < noisePoints; + }; + if (sorted.every(within)) { + const list = sorted.map((/** @type {any} */ r, /** @type {number} */ i) => + i === 0 ? `${r.effort} fixed ${r.fixed}` : `${r.effort} ${r.fixed}`, + ); + const joined = + list.length === 2 ? list.join(" and ") : `${list.slice(0, -1).join(", ")} and ${list.at(-1)}`; + return `${joined} of ${total}, a gap within the board's run-to-run spread, so the efforts are not distinguishable on fixed bugs.`; } - // A saving is stated only when it is one: a lower-fixing rung that costs more or runs longer says nothing. - const saved = (/** @type {string} */ key) => { + // A saving is stated only when it is one: a rung that costs more or runs longer says nothing. + const saved = (/** @type {any} */ r, /** @type {string} */ key) => { const pct = - best[key] > 0 && fewest[key] !== null && best[key] !== null - ? Math.round((1 - fewest[key] / best[key]) * 100) + best[key] > 0 && r[key] !== null && best[key] !== null + ? Math.round((1 - r[key] / best[key]) * 100) : 0; return pct > 0 ? pct : undefined; }; - const cost = saved("costUsd"); - const time = saved("wallMinutes"); - const parts = [ - ...(cost === undefined ? [] : [`${cost}% less cost`]), - ...(time === undefined ? [] : [`${time}% less time`]), - ]; - return ( - `${best.effort} fixed the most (${best.fixed} of ${total}); ${fewest.effort} fixed ${gap} fewer` + - (parts.length > 0 ? ` for ${parts.join(" and ")}` : "") + - "." - ); + const clauses = sorted.slice(1).map((/** @type {any} */ r) => { + const cost = saved(r, "costUsd"); + const time = saved(r, "wallMinutes"); + const parts = [ + ...(cost === undefined ? [] : [`${cost}% less cost`]), + ...(time === undefined ? [] : [`${time}% less time`]), + ]; + const head = within(r) + ? `${r.effort} (${r.fixed}) is within the board's run-to-run spread of it` + : `${r.effort} fixed ${round(best.fixed - r.fixed)} fewer`; + return head + (parts.length > 0 ? ` for ${parts.join(" and ")}` : ""); + }); + return `${best.effort} fixed the most (${best.fixed} of ${total}); ${clauses.join("; ")}.`; } /** @@ -381,22 +484,41 @@ export function buildCatalog(spec, snapshot, own) { /** * @param {string} url + * @param {(url: URL, init: RequestInit) => Promise} [fetchImpl] replaced by a test */ -export async function fetchBoard(url) { +export async function fetchBoard(url, fetchImpl = fetch) { const target = new URL(url); if (target.protocol !== "https:") { throw new Error(`refusing to fetch ${url}: only https`); } // A redirect would leave the host the spec names, so it is an error, not a hop. - const response = await fetch(target, { signal: AbortSignal.timeout(30000), redirect: "error" }); - if (!response.ok) { - throw new Error(`${url} answered ${response.status}`); + const response = await fetchImpl(target, { + signal: AbortSignal.timeout(30000), + redirect: "error", + }); + if (!response.ok || response.body === null) { + throw new Error( + `${url} answered ${response.status}${response.body === null ? " with no body" : ""}`, + ); } - const bytes = new Uint8Array(await response.arrayBuffer()); - if (bytes.length > MAX_BOARD_BYTES) { - throw new Error(`${url} is larger than ${MAX_BOARD_BYTES} bytes`); + // Counted as it arrives, and the stream is cancelled at the cap: the rest is never read into memory. + const reader = response.body.getReader(); + /** @type {Uint8Array[]} */ + const chunks = []; + let size = 0; + for (;;) { + const { done, value } = await reader.read(); + if (done) { + break; + } + size += value.length; + if (size > MAX_BOARD_BYTES) { + await reader.cancel(); + throw new Error(`${url} is larger than ${MAX_BOARD_BYTES} bytes`); + } + chunks.push(value); } - return JSON.parse(new TextDecoder().decode(bytes)); + return JSON.parse(new TextDecoder().decode(Buffer.concat(chunks))); } /** @param {string | undefined} file */ @@ -463,66 +585,108 @@ export async function run(argv, today = new Date().toISOString().slice(0, 10), d ) { throw new Error("--board-file and --today go with --fetch"); } - if (values.today !== undefined && !DATE.test(values.today)) { - throw new Error("--today is YYYY-MM-DD"); + if (values.today !== undefined && !isDate(values.today)) { + throw new Error("--today is a real date, YYYY-MM-DD"); } } catch (error) { console.error(`refresh-recommendations: ${/** @type {Error} */ (error).message}`); return 2; } try { - const spec = readJson(paths.spec); - const deny = readDeny(values["deny-file"]); - let snapshot = readJson(paths.snapshot); - let own = sanitizeOwn(readJson(paths.own), deny); - if (values.fetch === true) { - const board = - values["board-file"] !== undefined - ? readJson(resolve(values["board-file"])) - : await fetchBoard(spec.board.url); - snapshot = reduceBoard(board, values.today ?? today); - } - if (values["from-file"] !== undefined) { - own = sanitizeOwn(readJson(resolve(values["from-file"])), deny); - } - const catalog = buildCatalog(spec, snapshot, own); - if (values.check === true) { - const committed = existsSync(paths.catalog) ? readJson(paths.catalog) : undefined; - if (JSON.stringify(committed) !== JSON.stringify(catalog)) { - const ids = new Set(catalog.entries.map((/** @type {any} */ e) => e.id)); - const behind = catalog.entries - .filter( - (/** @type {any} */ e) => - JSON.stringify(e) !== - JSON.stringify(committed?.entries?.find((/** @type {any} */ c) => c.id === e.id)), - ) - .map((/** @type {any} */ e) => e.id); - const extra = (committed?.entries ?? []) - .filter((/** @type {any} */ c) => !ids.has(c.id)) - .map((/** @type {any} */ c) => c.id); - console.error( - `refresh-recommendations: the catalog is not what the snapshot, spec and own results generate (differs: ${[...behind, ...extra].join(", ") || "header"}); run scripts/refresh-recommendations.mjs`, - ); - return 1; + const check = values.check === true; + return check + ? await refresh(paths, values, today) + : await withLock(dir, () => refresh(paths, values, today)); + } catch (error) { + console.error(`refresh-recommendations: ${/** @type {Error} */ (error).message}`); + return 1; + } +} + +/** + * Read the inputs this mode consumes (a mode that replaces an input does not read the old one), build the + * catalog and either check it against the committed bytes or write it. + * @param {ReturnType} paths + * @param {Record} values + * @param {string} today + */ +async function refresh(paths, values, today) { + const spec = readJson(paths.spec); + const deny = readDeny(values["deny-file"]); + const rawSnapshot = values.fetch === true ? undefined : readFileSync(paths.snapshot, "utf8"); + let snapshot = rawSnapshot === undefined ? undefined : JSON.parse(rawSnapshot); + if (values.fetch === true) { + const board = + values["board-file"] !== undefined + ? readJson(resolve(values["board-file"])) + : await fetchBoard(spec.board.url); + snapshot = reduceBoard(board, values.today ?? today); + } + const rawOwn = + values["from-file"] === undefined && existsSync(paths.own) + ? readFileSync(paths.own, "utf8") + : undefined; + const own = + values["from-file"] !== undefined + ? sanitizeOwn(readJson(resolve(values["from-file"])), deny) + : rawOwn === undefined + ? { version: 1, results: [] } + : sanitizeOwn(JSON.parse(rawOwn), deny); + const catalog = buildCatalog(spec, snapshot, own); + // Every string published for an own result is screened as published, assembled text included. + for (const entry of catalog.entries.filter( + (/** @type {any} */ e) => e.kind === "own-evaluation", + )) { + const flat = JSON.stringify(entry) + .toLowerCase() + .replace(/[^a-z0-9]/g, ""); + for (const word of deny.map((w) => w.toLowerCase().replace(/[^a-z0-9]/g, "")).filter(Boolean)) { + if (flat.includes(word)) { + throw new Error(`catalog entry ${entry.id} contains a name this repository must not carry`); } - console.log(`refresh-recommendations: catalog matches (${catalog.entries.length} entries)`); - return 0; - } - /** @type {Array<[string, unknown]>} */ - const outputs = [[paths.catalog, catalog]]; - if (values.fetch === true) { - outputs.unshift([paths.snapshot, snapshot]); } - if (values["from-file"] !== undefined) { - outputs.unshift([paths.own, own]); + } + if (values.check === true) { + // The committed bytes, not their parse: an extra field or a shadowed duplicate key is a difference. + const committed = existsSync(paths.catalog) ? readFileSync(paths.catalog, "utf8") : undefined; + const files = [ + ["catalog", committed, serialize(catalog)], + ["snapshot", rawSnapshot, serialize(snapshot)], + ...(rawOwn === undefined ? [] : [["own results", rawOwn, serialize(own)]]), + ]; + const off = files.filter(([, have, want]) => have !== want); + if (off.length > 0) { + const parsed = committed === undefined ? undefined : JSON.parse(committed); + const ids = new Set(catalog.entries.map((/** @type {any} */ e) => e.id)); + const behind = catalog.entries + .filter( + (/** @type {any} */ e) => + JSON.stringify(e) !== + JSON.stringify(parsed?.entries?.find((/** @type {any} */ c) => c.id === e.id)), + ) + .map((/** @type {any} */ e) => e.id); + const extra = (parsed?.entries ?? []) + .filter((/** @type {any} */ c) => !ids.has(c.id)) + .map((/** @type {any} */ c) => c.id); + console.error( + `refresh-recommendations: not what the committed inputs generate: ${off.map(([name]) => name).join(", ")} (entries: ${[...behind, ...extra].join(", ") || "none; bytes, extra fields or duplicate keys"}); run scripts/refresh-recommendations.mjs`, + ); + return 1; } - writeAll(outputs); - console.log(`refresh-recommendations: wrote the catalog (${catalog.entries.length} entries)`); + console.log(`refresh-recommendations: catalog matches (${catalog.entries.length} entries)`); return 0; - } catch (error) { - console.error(`refresh-recommendations: ${/** @type {Error} */ (error).message}`); - return 1; } + /** @type {Array<[string, unknown]>} */ + const outputs = [[paths.catalog, catalog]]; + if (values.fetch === true) { + outputs.unshift([paths.snapshot, snapshot]); + } + if (values["from-file"] !== undefined) { + outputs.unshift([paths.own, own]); + } + writeAll(outputs); + console.log(`refresh-recommendations: wrote the catalog (${catalog.entries.length} entries)`); + return 0; } if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) { diff --git a/skills/hr-code-review/test/refresh-recommendations.test.mjs b/skills/hr-code-review/test/refresh-recommendations.test.mjs index f6960b99..9431db28 100644 --- a/skills/hr-code-review/test/refresh-recommendations.test.mjs +++ b/skills/hr-code-review/test/refresh-recommendations.test.mjs @@ -1,16 +1,28 @@ import { test } from "node:test"; import assert from "node:assert/strict"; -import { cpSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs"; +import { + cpSync, + existsSync, + mkdirSync, + mkdtempSync, + readFileSync, + readdirSync, + rmSync, + symlinkSync, + writeFileSync, +} from "node:fs"; import { tmpdir } from "node:os"; import { dirname, join, resolve } from "node:path"; import { fileURLToPath } from "node:url"; import { buildCatalog, fetchBoard, + looksSecret, pathsIn, reduceBoard, run, sanitizeOwn, + serialize, writeAll, } from "../scripts/refresh-recommendations.mjs"; @@ -170,6 +182,14 @@ test("own results that could carry a private name, path, address or link are ref { cohort: "see https://private.example/cases" }, { cohort: "C:\\cases\\private" }, { harness: "codex --api-key abc" }, + { cohort: "46 cases, key sk-proj1234567890abcdef" }, + { cohort: "46 cases, id 0123456789abcdef0123" }, + { cohort: "see 192.0.2.1" }, + { cohort: "see host.internal.example" }, + { cohort: "46 cases, addr 2001:db8::1" }, + { cohort: "46 cases, blob Zm9vYmFyMTIzNDU2Nzg5MDEyMzQ1" }, + { harness: "build.internal.example" }, + { id: "sk-proj1234567890abcdef" }, { model: "Model With Spaces" }, { effort: "extreme" }, { found: 200 }, @@ -182,6 +202,12 @@ test("own results that could carry a private name, path, address or link are ref } assert.throws(() => sanitizeOwn({ version: 1, results: [good, good] }), /duplicate/); assert.throws(() => sanitizeOwn({ results: [] }), /expected/); + assert.throws(() => sanitizeOwn({ version: 1, results: [], project: "x" }), /expected exactly/); + assert.doesNotThrow(() => sanitizeOwn(own({}))); + assert.equal( + looksSecret("46 held-out code changes, judged blind by a second model", true), + false, + ); }); test("a name on the deny list is refused wherever it appears, whatever its case", () => { @@ -194,7 +220,12 @@ test("a name on the deny list is refused wherever it appears, whatever its case" test("the committed own results and catalog name no private repository, path, address or credential", () => { const text = JSON.stringify([read(real.own), read(real.catalog)]); - assert.doesNotMatch(text, /\/home\/|\/Users\/|api[_-]?key|token|@/i); + assert.doesNotMatch(text, /\/home\/|\/Users\/|@/i); + // The same detector the importer uses runs over every string the committed files hold. + const strings = text.match(/"((?:[^"\\]|\\.)*)"/g) ?? []; + for (const quoted of strings) { + assert.equal(looksSecret(quoted.slice(1, -1)), false, quoted); + } sanitizeOwn(read(real.own)); }); @@ -220,7 +251,7 @@ test("--from-file sanitizes, rewrites the own file and the catalog, and --check writeFileSync(join(dir, "panel-recommendations.json"), JSON.stringify(catalog)); const drift = await silent(() => run(["--check"], "2026-11-21", dir)); assert.equal(drift.code, 1); - assert.match(drift.text, /differs: opus-5-5-bug-hunt/); + assert.match(drift.text, /entries: opus-5-5-bug-hunt/); }); }); @@ -287,6 +318,26 @@ test("a fetch goes only to https", async () => { await assert.rejects(() => fetchBoard("http://example.org/b.json"), /only https/); }); +test("a board larger than the cap is cancelled at the cap, not read to the end", async () => { + let pulls = 0; + let cancelled = false; + const stream = new ReadableStream({ + pull(controller) { + pulls++; + controller.enqueue(new Uint8Array(1 << 20)); + }, + cancel() { + cancelled = true; + }, + }); + const fake = async () => new Response(stream, { status: 200 }); + await assert.rejects(() => fetchBoard("https://example.org/b.json", fake), /larger than/); + 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 }); +}); + test("an own file is refused without a deny file, and a deny entry matches however it is spelled", async () => { await inCopy(async (dir) => { const file = join(dir, "incoming.json"); @@ -353,19 +404,178 @@ test("a board figure that is null or boolean is refused, not read as a number", assert.throws(() => reduceBoard(board([row({ n_runs: true })]), "2026-11-03"), /cannot read/); }); -test("several outputs are written together or not at all", async () => { +test("several outputs are written together or not at all, and nothing else in the folder is touched", async () => { await inCopy(async (dir) => { const a = join(dir, "a.json"); writeFileSync(a, "old a\n"); - // The second target's directory does not exist, so its rename fails and the first file is restored. + // A pre-existing file of the old temporary name, and a symlink at that name, must survive untouched. + writeFileSync(`${a}.new`, "keep me\n"); + const other = join(dir, "other.txt"); + writeFileSync(other, "other\n"); + symlinkSync(other, join(dir, "b.json.new")); + // The second target is a directory with content, so its rename fails and the first file is restored. + const b = join(dir, "b.json"); + mkdirSync(b); + writeFileSync(join(b, "x"), "x"); assert.throws(() => writeAll([ [a, { n: 1 }], - [join(dir, "missing-dir", "b.json"), { n: 2 }], + [b, { n: 2 }], ]), ); assert.equal(readFileSync(a, "utf8"), "old a\n"); + assert.equal(readFileSync(`${a}.new`, "utf8"), "keep me\n"); + assert.equal(readFileSync(other, "utf8"), "other\n"); + assert.deepEqual( + readdirSync(dir).filter((name) => name.startsWith(".refresh")), + [], + ); writeAll([[a, { n: 3 }]]); assert.deepEqual(read(a), { n: 3 }); + assert.equal(readFileSync(`${a}.new`, "utf8"), "keep me\n"); + assert.throws( + () => + writeAll([ + [a, 1], + [join(dir, "sub", "c.json"), 2], + ]), + /one folder/, + ); + }); +}); + +test("--check compares the committed bytes: a private extra field or a shadowed duplicate key fails", async () => { + await inCopy(async (dir) => { + const ownFile = join(dir, "panel-recommendations.own.json"); + const good = readFileSync(ownFile, "utf8"); + writeFileSync(ownFile, good.replace('"version": 1,', '"version": 1,\n "project": "acme",')); + const extra = await silent(() => run(["--check"], "2026-11-21", dir)); + assert.equal(extra.code, 1); + assert.match(extra.text, /expected exactly/); + writeFileSync(ownFile, good); + const catalogFile = join(dir, "panel-recommendations.json"); + const catalog = readFileSync(catalogFile, "utf8"); + // A shadowed first value: same parse as the generated catalog, different bytes. + writeFileSync(catalogFile, catalog.replace('"version": 1,', '"version": 1,\n "version": 1,')); + const dup = await silent(() => run(["--check"], "2026-11-21", dir)); + assert.equal(dup.code, 1); + assert.match(dup.text, /duplicate keys/); + writeFileSync(catalogFile, catalog); + assert.equal((await silent(() => run(["--check"], "2026-11-21", dir))).code, 0); + }); +}); + +test("an interruption between publishing sources and the catalog leaves a complete old catalog that --check flags and a plain run repairs", async () => { + await inCopy(async (dir) => { + const before = readFileSync(join(dir, "panel-recommendations.json"), "utf8"); + // The own file is already new, the catalog still old: what an interruption after the first rename leaves. + writeFileSync(join(dir, "panel-recommendations.own.json"), serialize(own({ found: 81 }))); + assert.equal(readFileSync(join(dir, "panel-recommendations.json"), "utf8"), before); + assert.equal(JSON.parse(before).entries.length, 5); + const flagged = await silent(() => run(["--check"], "2026-11-21", dir)); + assert.equal(flagged.code, 1); + assert.equal((await silent(() => run([], "2026-11-21", dir))).code, 0); + assert.equal((await silent(() => run(["--check"], "2026-11-21", dir))).code, 0); + }); +}); + +test("a second refresh while one holds the lock fails with a retry message; a dead owner's lock is taken over", async () => { + await inCopy(async (dir) => { + const lock = join(dir, ".refresh.lock"); + writeFileSync(lock, `${process.pid}\n`); + const busy = await silent(() => run([], "2026-11-21", dir)); + assert.equal(busy.code, 1); + assert.match(busy.text, /retry/); + writeFileSync(lock, "2147483646\n"); + assert.equal((await silent(() => run([], "2026-11-21", dir))).code, 0); + assert.equal(existsSync(lock), false); + }); +}); + +test("the mode picks the inputs: fetch rebuilds a missing snapshot, an import replaces a denied old file, no own file is empty", async () => { + await inCopy(async (dir) => { + const saved = join(dir, "board.json"); + writeFileSync(saved, JSON.stringify(board([row({ effort: "medium" }), row()]))); + writeFileSync(join(dir, "panel-recommendations.sources.json"), JSON.stringify(spec)); + rmSync(join(dir, "panel-board-snapshot.json")); + rmSync(join(dir, "panel-recommendations.own.json")); + const fetched = await silent(() => + run(["--fetch", "--board-file", saved, "--today", "2026-11-05"], "2026-11-21", dir), + ); + assert.equal(fetched.code, 0, fetched.text); + assert.equal(read(join(dir, "panel-recommendations.json")).entries.length, 1); + // An own file holding a name that is denied now is replaced by a clean import, not an abort. + writeFileSync( + join(dir, "panel-recommendations.own.json"), + serialize(own({ cohort: "46 cases of widgetco" })), + ); + const incoming = join(dir, "incoming.json"); + writeFileSync(incoming, JSON.stringify(own({}))); + const deny = join(dir, "deny.txt"); + writeFileSync(deny, "widgetco\n"); + const replaced = await silent(() => + run(["--from-file", incoming, "--deny-file", deny], "2026-11-21", dir), + ); + assert.equal(replaced.code, 0, replaced.text); + assert.equal(read(join(dir, "panel-recommendations.own.json")).results[0].cohort, good.cohort); + }); +}); + +test("a deny entry covers the published id, the effort and the assembled text", async () => { + assert.throws(() => sanitizeOwn(own({}), ["own-astra-62-medium-heldout"]), /published id/); + assert.throws(() => sanitizeOwn(own({}), ["medium"]), /published id or effort/); + await inCopy(async (dir) => { + const incoming = join(dir, "incoming.json"); + writeFileSync(incoming, JSON.stringify(own({}))); + const deny = join(dir, "deny.txt"); + // Spans the cohort wording and a generated phrase: only the assembled entry holds it whole. + writeFileSync(deny, "known defects across 46\n"); + const out = await silent(() => + run(["--from-file", incoming, "--deny-file", deny], "2026-11-21", dir), + ); + assert.equal(out.code, 1); + assert.match(out.text, /must not carry/); + }); +}); + +test("every effort inside the spread of the leader is named, and an exact tie names both", () => { + const rows = [ + row({ effort: "medium", fixed: 50.3, cost_usd: 5, wall_min: 10 }), + row({ effort: "high", fixed: 59.6, cost_usd: 8, wall_min: 48.5 }), + row({ effort: "xhigh", fixed: 60.2, cost_usd: 10, wall_min: 84 }), + ]; + const withSpread = { ...spec, board: { ...spec.board, noisePoints: 1.5 } }; + const three = { + ...spec, + entries: [{ ...spec.entries[0], efforts: ["medium", "high", "xhigh"] }], + }; + const [entry] = buildCatalog( + { ...three, board: withSpread.board }, + reduceBoard(board(rows), "2026-11-03"), + { + version: 1, + results: [], + }, + ).entries; + assert.match( + entry.rationale, + /^xhigh fixed the most \(60\.2 of 105\); high \(59\.6\) is within the board's run-to-run spread of it for 20% less cost and 42% less time; medium fixed 9\.9 fewer for 50% less cost and 88% less time\./, + ); + const tie = reduceBoard( + board([row({ effort: "medium", fixed: 40 }), row({ effort: "high", fixed: 40 })]), + "2026-11-03", + ); + const [tied] = buildCatalog(spec, tie, { version: 1, results: [] }).entries; + assert.match(tied.rationale, /medium fixed 40 and high 40 of 105/); +}); + +test("an impossible calendar date is refused wherever a fetch date enters", async () => { + assert.throws(() => reduceBoard(board([row()]), "2026-02-31"), /real YYYY-MM-DD/); + assert.doesNotThrow(() => reduceBoard(board([row()]), "2028-02-29")); + await inCopy(async (dir) => { + const before = readFileSync(join(dir, "panel-recommendations.json"), "utf8"); + const out = await silent(() => run(["--fetch", "--today", "2026-02-31"], "2026-11-21", dir)); + assert.equal(out.code, 2); + assert.equal(readFileSync(join(dir, "panel-recommendations.json"), "utf8"), before); }); }); From d79140886be8adc639c39d729fa099ea8f0de502 Mon Sep 17 00:00:00 2001 From: bompus Date: Sat, 21 Nov 2026 13:00:27 -0700 Subject: [PATCH 3/8] Panel recommendations generator round 2: plain-word cohort grammar and public model/harness vocabulary, one strict snapshot schema and canonical layout, measurement domains, per-string deny matching, race-safe refresh lock, backups outside the skill folder, canonicalizing plain run, controlled test fixtures --- .gitignore | 2 +- .../references/panel-board-snapshot.json | 400 +++++++++--------- .../references/panel-recommendations.md | 6 +- .../scripts/refresh-recommendations.mjs | 399 ++++++++++++----- .../test/refresh-recommendations.test.mjs | 198 ++++++++- 5 files changed, 701 insertions(+), 304 deletions(-) diff --git a/.gitignore b/.gitignore index 642a9e7c..f750c0b1 100644 --- a/.gitignore +++ b/.gitignore @@ -6,4 +6,4 @@ __pycache__/ *.py[cod] skills/hr-code-review/references/.refresh-* -skills/hr-code-review/references/.refresh.lock +skills/hr-code-review/references/.refresh.lock* diff --git a/skills/hr-code-review/references/panel-board-snapshot.json b/skills/hr-code-review/references/panel-board-snapshot.json index 9a92ca3a..422d3b04 100644 --- a/skills/hr-code-review/references/panel-board-snapshot.json +++ b/skills/hr-code-review/references/panel-board-snapshot.json @@ -294,196 +294,6 @@ "costUsd": 61.01, "date": "2026-11-10" }, - { - "model": "Gemini 3.7 Flash", - "harness": "Antigravity CLI", - "effort": "high", - "runs": 1, - "fixed": 16, - "wallMinutes": 22.7, - "costUsd": 6.36, - "date": "2026-08-28" - }, - { - "model": "Gemini 3.7 Flash", - "harness": "Gemini CLI (retired) + model-pinning gateway", - "effort": "high", - "runs": 1, - "fixed": 22, - "wallMinutes": 96.8, - "costUsd": 8.43, - "date": "2026-08-24" - }, - { - "model": "Gemini 3.8 Flash", - "harness": "Antigravity CLI", - "effort": "high", - "runs": 3, - "fixed": 18, - "wallMinutes": 38.7, - "costUsd": 11.03, - "date": "2026-09-15" - }, - { - "model": "Gemini 4 Argon", - "harness": "Antigravity CLI", - "effort": "high", - "runs": 3, - "fixed": 40.7, - "wallMinutes": 56.5, - "costUsd": 7.16, - "date": "2026-10-14" - }, - { - "model": "Gemini 4 Argon", - "harness": "Antigravity CLI", - "effort": "low", - "runs": 3, - "fixed": 35.3, - "wallMinutes": 59.6, - "costUsd": 6.47, - "date": "2026-10-14" - }, - { - "model": "Gemini 4 Argon", - "harness": "Antigravity CLI", - "effort": "medium", - "runs": 3, - "fixed": 39.3, - "wallMinutes": 59.9, - "costUsd": 7.5, - "date": "2026-10-14" - }, - { - "model": "Gemini 4 Carbon", - "harness": "Antigravity CLI", - "effort": "high", - "runs": 3, - "fixed": 57.3, - "wallMinutes": 114, - "costUsd": 31.32, - "date": "2026-11-10" - }, - { - "model": "Gemini 4 Carbon", - "harness": "Antigravity CLI", - "effort": "low", - "runs": 3, - "fixed": 46, - "wallMinutes": 60.4, - "costUsd": 7.67, - "date": "2026-11-13" - }, - { - "model": "Gemini 4 Carbon", - "harness": "Antigravity CLI", - "effort": "medium", - "runs": 3, - "fixed": 56, - "wallMinutes": 81.1, - "costUsd": 24.95, - "date": "2026-11-10" - }, - { - "model": "Gemini 4 Hydrogen", - "harness": "Antigravity CLI", - "effort": "high", - "runs": 3, - "fixed": 28.3, - "wallMinutes": 22.4, - "costUsd": 4.42, - "date": "2026-11-13" - }, - { - "model": "Gemini 4 Hydrogen", - "harness": "Antigravity CLI", - "effort": "low", - "runs": 3, - "fixed": 10.3, - "wallMinutes": 7.2, - "costUsd": 0.43, - "date": "2026-11-13" - }, - { - "model": "Gemini 4 Hydrogen", - "harness": "Antigravity CLI", - "effort": "medium", - "runs": 3, - "fixed": 24.7, - "wallMinutes": 19.9, - "costUsd": 2.1, - "date": "2026-11-13" - }, - { - "model": "Gemini 4 Hydrogen", - "harness": "Antigravity CLI", - "effort": "xhigh", - "runs": 3, - "fixed": 32.7, - "wallMinutes": 35.8, - "costUsd": 7.07, - "date": "2026-11-13" - }, - { - "model": "Gemini 4 Neon", - "harness": "Antigravity CLI", - "effort": "high", - "runs": 3, - "fixed": 57, - "wallMinutes": 45.4, - "costUsd": 29.11, - "date": "2026-11-19" - }, - { - "model": "Gemini 4 Neon", - "harness": "Antigravity CLI", - "effort": "low", - "runs": 3, - "fixed": 29.7, - "wallMinutes": 10.8, - "costUsd": 5.29, - "date": "2026-11-19" - }, - { - "model": "Gemini 4 Neon", - "harness": "Antigravity CLI", - "effort": "medium", - "runs": 3, - "fixed": 47.7, - "wallMinutes": 24.5, - "costUsd": 12.84, - "date": "2026-11-19" - }, - { - "model": "Gemini 4 Neon", - "harness": "Antigravity CLI", - "effort": "xhigh", - "runs": 3, - "fixed": 63, - "wallMinutes": 75.9, - "costUsd": 46.34, - "date": "2026-11-19" - }, - { - "model": "Gemma 4 31B", - "harness": "Claude Code / OpenRouter", - "effort": "default", - "runs": 1, - "fixed": 4, - "wallMinutes": 221.8, - "costUsd": null, - "date": "2026-09-16" - }, - { - "model": "Gemma 4 31B 4-bit", - "harness": "Claude Code / OpenRouter", - "effort": "default", - "runs": 1, - "fixed": 3, - "wallMinutes": 24.9, - "costUsd": null, - "date": "2026-09-16" - }, { "model": "GLM-5.3", "harness": "Claude Code / Z.ai API", @@ -1015,24 +825,194 @@ "date": "2026-11-18" }, { - "model": "gpt-oss-120b", + "model": "Gemini 3.7 Flash", + "harness": "Antigravity CLI", + "effort": "high", + "runs": 1, + "fixed": 16, + "wallMinutes": 22.7, + "costUsd": 6.36, + "date": "2026-08-28" + }, + { + "model": "Gemini 3.7 Flash", + "harness": "Gemini CLI (retired) + model-pinning gateway", + "effort": "high", + "runs": 1, + "fixed": 22, + "wallMinutes": 96.8, + "costUsd": 8.43, + "date": "2026-08-24" + }, + { + "model": "Gemini 3.8 Flash", + "harness": "Antigravity CLI", + "effort": "high", + "runs": 3, + "fixed": 18, + "wallMinutes": 38.7, + "costUsd": 11.03, + "date": "2026-09-15" + }, + { + "model": "Gemini 4 Argon", + "harness": "Antigravity CLI", + "effort": "high", + "runs": 3, + "fixed": 40.7, + "wallMinutes": 56.5, + "costUsd": 7.16, + "date": "2026-10-14" + }, + { + "model": "Gemini 4 Argon", + "harness": "Antigravity CLI", + "effort": "low", + "runs": 3, + "fixed": 35.3, + "wallMinutes": 59.6, + "costUsd": 6.47, + "date": "2026-10-14" + }, + { + "model": "Gemini 4 Argon", + "harness": "Antigravity CLI", + "effort": "medium", + "runs": 3, + "fixed": 39.3, + "wallMinutes": 59.9, + "costUsd": 7.5, + "date": "2026-10-14" + }, + { + "model": "Gemini 4 Carbon", + "harness": "Antigravity CLI", + "effort": "high", + "runs": 3, + "fixed": 57.3, + "wallMinutes": 114, + "costUsd": 31.32, + "date": "2026-11-10" + }, + { + "model": "Gemini 4 Carbon", + "harness": "Antigravity CLI", + "effort": "low", + "runs": 3, + "fixed": 46, + "wallMinutes": 60.4, + "costUsd": 7.67, + "date": "2026-11-13" + }, + { + "model": "Gemini 4 Carbon", + "harness": "Antigravity CLI", + "effort": "medium", + "runs": 3, + "fixed": 56, + "wallMinutes": 81.1, + "costUsd": 24.95, + "date": "2026-11-10" + }, + { + "model": "Gemini 4 Hydrogen", + "harness": "Antigravity CLI", + "effort": "high", + "runs": 3, + "fixed": 28.3, + "wallMinutes": 22.4, + "costUsd": 4.42, + "date": "2026-11-13" + }, + { + "model": "Gemini 4 Hydrogen", + "harness": "Antigravity CLI", + "effort": "low", + "runs": 3, + "fixed": 10.3, + "wallMinutes": 7.2, + "costUsd": 0.43, + "date": "2026-11-13" + }, + { + "model": "Gemini 4 Hydrogen", + "harness": "Antigravity CLI", + "effort": "medium", + "runs": 3, + "fixed": 24.7, + "wallMinutes": 19.9, + "costUsd": 2.1, + "date": "2026-11-13" + }, + { + "model": "Gemini 4 Hydrogen", + "harness": "Antigravity CLI", + "effort": "xhigh", + "runs": 3, + "fixed": 32.7, + "wallMinutes": 35.8, + "costUsd": 7.07, + "date": "2026-11-13" + }, + { + "model": "Gemini 4 Neon", + "harness": "Antigravity CLI", + "effort": "high", + "runs": 3, + "fixed": 57, + "wallMinutes": 45.4, + "costUsd": 29.11, + "date": "2026-11-19" + }, + { + "model": "Gemini 4 Neon", + "harness": "Antigravity CLI", + "effort": "low", + "runs": 3, + "fixed": 29.7, + "wallMinutes": 10.8, + "costUsd": 5.29, + "date": "2026-11-19" + }, + { + "model": "Gemini 4 Neon", + "harness": "Antigravity CLI", + "effort": "medium", + "runs": 3, + "fixed": 47.7, + "wallMinutes": 24.5, + "costUsd": 12.84, + "date": "2026-11-19" + }, + { + "model": "Gemini 4 Neon", + "harness": "Antigravity CLI", + "effort": "xhigh", + "runs": 3, + "fixed": 63, + "wallMinutes": 75.9, + "costUsd": 46.34, + "date": "2026-11-19" + }, + { + "model": "Gemma 4 31B", "harness": "Claude Code / OpenRouter", "effort": "default", - "runs": 3, - "fixed": 0, - "wallMinutes": 3.7, + "runs": 1, + "fixed": 4, + "wallMinutes": 221.8, "costUsd": null, - "date": "2026-09-15" + "date": "2026-09-16" }, { - "model": "gpt-oss-20b", + "model": "Gemma 4 31B 4-bit", "harness": "Claude Code / OpenRouter", "effort": "default", - "runs": 3, - "fixed": 0, - "wallMinutes": 7.4, + "runs": 1, + "fixed": 3, + "wallMinutes": 24.9, "costUsd": null, - "date": "2026-09-15" + "date": "2026-09-16" }, { "model": "Grok 4.5", @@ -1593,6 +1573,26 @@ "wallMinutes": 72.7, "costUsd": 42.86, "date": "2026-09-29" + }, + { + "model": "gpt-oss-120b", + "harness": "Claude Code / OpenRouter", + "effort": "default", + "runs": 3, + "fixed": 0, + "wallMinutes": 3.7, + "costUsd": null, + "date": "2026-09-15" + }, + { + "model": "gpt-oss-20b", + "harness": "Claude Code / OpenRouter", + "effort": "default", + "runs": 3, + "fixed": 0, + "wallMinutes": 7.4, + "costUsd": null, + "date": "2026-09-15" } ] } diff --git a/skills/hr-code-review/references/panel-recommendations.md b/skills/hr-code-review/references/panel-recommendations.md index 9a6c6e56..82fbf030 100644 --- a/skills/hr-code-review/references/panel-recommendations.md +++ b/skills/hr-code-review/references/panel-recommendations.md @@ -60,4 +60,8 @@ description, with `provenance: "own-evaluation"` and no public source. It comes a case set this repository does not publish, so it cannot be reproduced here and does not compare with the board entries. The generator accepts only a fixed set of plain fields for it (no paths, links, addresses, credentials or free text beyond the cohort -line) and refuses any extra name the maintainer lists in a deny file. +line) and refuses any extra name the maintainer lists in a deny file. The model and +harness must be names the source spec already lists, and the cohort line may hold only +plain words and numbers (no token that mixes letters and digits, no dotted host or +address). A plain run of the script also rewrites the snapshot and the own results in +their one canonical layout, which is what `--check` compares. diff --git a/skills/hr-code-review/scripts/refresh-recommendations.mjs b/skills/hr-code-review/scripts/refresh-recommendations.mjs index efa39f47..fafca71c 100644 --- a/skills/hr-code-review/scripts/refresh-recommendations.mjs +++ b/skills/hr-code-review/scripts/refresh-recommendations.mjs @@ -13,15 +13,17 @@ // // Any other argument, a conflicting pair of modes or an empty value is an error (exit 2). import { - closeSync, existsSync, + linkSync, mkdtempSync, - openSync, + readdirSync, readFileSync, renameSync, rmSync, + statSync, writeFileSync, } from "node:fs"; +import { tmpdir } from "node:os"; import { dirname, join, resolve } from "node:path"; import { fileURLToPath, pathToFileURL } from "node:url"; import { parseArgs } from "node:util"; @@ -57,10 +59,10 @@ const readJson = (path) => JSON.parse(readFileSync(path, "utf8")); export const serialize = (/** @type {unknown} */ value) => `${JSON.stringify(value, null, 2)}\n`; /** - * Write several files of one folder so that a failure leaves none of them changed. Every output and every - * before image is staged in a new directory this call creates beside the targets (same filesystem); the - * renames then run back to back, and a failed rename puts the earlier files back. Nothing outside that - * directory is created, so an existing file of any name survives, and only that directory is removed. + * 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 * --check reports the sources that are ahead of it until a plain run regenerates it. * @param {Array<[string, unknown]>} outputs @@ -71,6 +73,7 @@ export function writeAll(outputs) { throw new Error("the outputs must be in one folder"); } const stage = mkdtempSync(join(dir, ".refresh-")); + const backups = mkdtempSync(join(tmpdir(), "refresh-recommendations-")); try { const staged = outputs.map(([path, value], i) => { const file = join(stage, `new-${i}`); @@ -78,7 +81,7 @@ export function writeAll(outputs) { /** @type {string | undefined} */ let back; if (existsSync(path)) { - back = join(stage, `old-${i}`); + back = join(backups, `old-${i}`); writeFileSync(back, readFileSync(path), { flag: "wx" }); } return { path, file, back }; @@ -94,62 +97,203 @@ export function writeAll(outputs) { if (item.back === undefined) { rmSync(item.path, { force: true }); } else { - renameSync(item.back, item.path); + // The before image lives on another filesystem, so it is copied back, not renamed. + writeFileSync(item.path, readFileSync(item.back)); } } throw error; } } finally { rmSync(stage, { recursive: true, force: true }); + rmSync(backups, { recursive: true, force: true }); } } /** * Run `fn` holding the folder's refresh lock, so two refreshes cannot interleave their read-build-write. - * A second refresh fails with a message that says to retry; a lock left by a dead process is taken over. + * The lock is a hard link to a file that already holds the owner's pid, so it is never seen empty. A refresh + * that finds a live (or unreadable) owner fails with a retry message and removes nothing; a lock whose owner + * is dead is renamed away (one rename wins) and re-acquired; a lock is removed only by the process whose file it + * still is. Work files of an earlier interrupted refresh are reclaimed under the lock. * @template T * @param {string} dir * @param {() => Promise} fn + * @param {{ afterContended?: () => void }} [hooks] a test seam between finding the lock and reading it */ -async function withLock(dir, fn) { +export async function withLock(dir, fn, hooks = {}) { const lock = join(dir, ".refresh.lock"); - /** @type {number | undefined} */ - let fd; - for (let attempt = 0; fd === undefined; attempt++) { - try { - fd = openSync(lock, "wx"); - writeFileSync(fd, `${process.pid}\n`); - } catch (error) { - if (/** @type {any} */ (error).code !== "EEXIST") { + const mine = join(dir, `.refresh.lock.${process.pid}.${Math.random().toString(36).slice(2)}`); + writeFileSync(mine, `${process.pid}\n`, { flag: "wx" }); + const busy = (/** @type {string} */ why) => + new Error(`another refresh holds ${lock} (${why}); retry when it has finished`); + try { + for (let attempt = 0; ; attempt++) { + try { + linkSync(mine, lock); + break; + } catch (error) { + if (/** @type {any} */ (error).code !== "EEXIST") { + throw error; + } + } + hooks.afterContended?.(); + let text; + try { + text = readFileSync(lock, "utf8"); + } catch (error) { + if (/** @type {any} */ (error).code === "ENOENT" && attempt < 5) { + continue; // the holder finished between the failed link and the read + } throw error; } - const owner = Number.parseInt(readFileSync(lock, "utf8"), 10); + const owner = Number(text.trim()); + if (!Number.isInteger(owner) || owner <= 0) { + throw busy("its owner cannot be read"); + } let alive = true; try { process.kill(owner, 0); - } catch (e) { - alive = /** @type {any} */ (e).code === "EPERM"; + } catch (error) { + alive = /** @type {any} */ (error).code === "EPERM"; } - if (alive || attempt > 0) { - throw new Error( - `another refresh holds ${lock} (process ${owner}); retry when it has finished`, - { cause: error }, - ); + if (alive || attempt >= 5) { + throw busy(`process ${owner}`); + } + // Take the dead owner's lock away by rename: of two waiters only one rename succeeds. If what was + // renamed is not the lock that was read (a live process took it in between), it is put back. + const stale = `${lock}.stale.${process.pid}.${attempt}`; + try { + renameSync(lock, stale); + } catch (error) { + if (/** @type {any} */ (error).code === "ENOENT") { + continue; + } + throw error; + } + const taken = Number(readFileSync(stale, "utf8").trim()); + if (taken === owner) { + rmSync(stale, { force: true }); + } else { + try { + linkSync(stale, lock); + } finally { + rmSync(stale, { force: true }); + } + throw busy(`process ${taken}`); + } + } + for (const name of readdirSync(dir)) { + if (name.startsWith(".refresh-")) { + rmSync(join(dir, name), { recursive: true, force: true }); } - rmSync(lock, { force: true }); } - } - try { return await fn(); } finally { - closeSync(fd); - rmSync(lock, { force: true }); + // Remove the lock only when it is still the file this call linked. + try { + if (statSync(lock).ino === statSync(mine).ino) { + rmSync(lock, { force: true }); + } + } catch { + // no lock, or not readable: nothing of this call's to remove + } + rmSync(mine, { force: true }); } } +// Compared with case, spacing and punctuation removed, so "Internal Tool" and "internal_tool" match "internal-tool". +const squash = (/** @type {string} */ s) => s.toLowerCase().replace(/[^a-z0-9]/g, ""); +/** @param {unknown} v a finite number that is not negative */ +const nonNegative = (v) => typeof v === "number" && Number.isFinite(v) && v >= 0; +const SNAPSHOT_KEYS = ["version", "fetched", "boardUpdated", "plantedTotal", "rows"]; +const ROW_KEYS = ["model", "harness", "effort", "runs", "fixed", "wallMinutes", "costUsd", "date"]; +/** @param {any} a @param {any} b a total order, so a snapshot has one byte layout */ +const rowOrder = (a, b) => + order(a.model, b.model) || + order(a.harness, b.harness) || + order(a.effort, b.effort) || + order(b.date, a.date) || + b.runs - a.runs || + b.fixed - a.fixed || + (a.wallMinutes ?? -1) - (b.wallMinutes ?? -1) || + (a.costUsd ?? -1) - (b.costUsd ?? -1); + +/** + * The one snapshot shape: exactly these fields, real dates, integer run counts of at least one, fixed bug means + * between zero and the planted total, nonnegative times and prices, and rows in one canonical order. A snapshot + * read from disk and a freshly reduced board both pass through here, so neither can hold a value the other + * could not. + * @param {any} snap + */ +export function canonicalSnapshot(snap) { + const fail = (/** @type {string} */ why) => { + throw new Error(`the board snapshot ${why}`); + }; + if (snap === null || typeof snap !== "object" || Array.isArray(snap)) { + fail("is not an object"); + } + const extra = Object.keys(snap).filter((k) => !SNAPSHOT_KEYS.includes(k)); + if (extra.length > 0 || SNAPSHOT_KEYS.some((k) => !(k in snap))) { + fail(`must have exactly the fields ${SNAPSHOT_KEYS.join(", ")}`); + } + if (snap.version !== 1) { + fail("has an unknown version"); + } + if (!isDate(snap.fetched)) { + fail(`has a fetched date ${snap.fetched} that is not a real YYYY-MM-DD date`); + } + if (typeof snap.boardUpdated !== "string") { + fail("has no boardUpdated text"); + } + if (!Number.isInteger(snap.plantedTotal) || snap.plantedTotal < 1) { + fail("has a planted total that is not a positive integer"); + } + if (!Array.isArray(snap.rows)) { + fail("has no rows list"); + } + const rows = snap.rows.map((/** @type {any} */ r) => { + const at = `row ${r?.model} ${r?.effort}`; + if ( + r === null || + typeof r !== "object" || + Object.keys(r).length !== ROW_KEYS.length || + ROW_KEYS.some((k) => !(k in r)) + ) { + fail(`${at} must have exactly the fields ${ROW_KEYS.join(", ")}`); + } + for (const key of ["model", "harness", "effort"]) { + if (typeof r[key] !== "string" || r[key] === "") { + fail(`${at} has no ${key}`); + } + } + if (!Number.isInteger(r.runs) || r.runs < 1) { + fail(`${at} has a run count that is not a positive integer`); + } + if (!nonNegative(r.fixed) || r.fixed > snap.plantedTotal) { + fail(`${at} has a fixed mean outside 0 to ${snap.plantedTotal}`); + } + for (const key of ["wallMinutes", "costUsd"]) { + if (r[key] !== null && !nonNegative(r[key])) { + fail(`${at} has a ${key} that is neither null nor a nonnegative number`); + } + } + if (!isDate(r.date)) { + fail(`${at} has a date that is not a real YYYY-MM-DD date`); + } + return Object.fromEntries(ROW_KEYS.map((k) => [k, r[k]])); + }); + return { + version: 1, + fetched: snap.fetched, + boardUpdated: snap.boardUpdated, + plantedTotal: snap.plantedTotal, + rows: rows.toSorted(rowOrder), + }; +} + /** * The rows the catalog can use, from a full board: current rows only (a superseded row is the receipt of an - * earlier figure), with the fields this tool reads. + * earlier figure), with the fields this tool reads, validated by the snapshot schema. * @param {any} board * @param {string} fetched */ @@ -166,48 +310,38 @@ export function reduceBoard(board, fetched) { 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`); } - return r; - }) - .map((/** @type {any} */ r) => ({ - model: String(r.model), - harness: String(r.harness), - effort: String(r.effort), - runs: Number(r.n_runs), - fixed: Number(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), - })); - for (const row of rows) { - if (!Number.isFinite(row.runs) || !Number.isFinite(row.fixed) || !isDate(row.date)) { - throw new Error(`board row ${row.model} ${row.effort} has a figure this tool cannot read`); - } - } - return { + return { + model: String(r.model), + harness: String(r.harness), + effort: String(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), + }; + }); + return canonicalSnapshot({ version: 1, fetched, boardUpdated: String(board.meta.updated ?? "unknown"), plantedTotal: board.meta.planted_total, - rows: rows.toSorted( - (/** @type {any} */ a, /** @type {any} */ b) => - order(a.model, b.model) || order(a.harness, b.harness) || order(a.effort, b.effort), - ), - }; + rows, + }); } /** - * Whether a published text looks like a credential, an address or a host: an assignment-style word, a - * provider key prefix, a long hex run, an IPv4 or IPv6 address, or (for free text) a host name or a very long - * token with digits. + * Whether a published text looks like a credential, an address or a host: an assignment-style word, a provider + * key with its separator, a long hex run, an IPv4 or IPv6 address, or (for free text) a host name. * @param {string} value - * @param {boolean} [freeText] a cohort or harness line, where a host name or long token can hide + * @param {boolean} [freeText] a cohort, harness or model line, where a host name can hide */ export function looksSecret(value, freeText = false) { if (/api[_-]?key|token|secret|password|passwd|bearer|credential/i.test(value)) { return true; } if ( - /(?:^|[^A-Za-z0-9])(?:sk|pk|rk|ghp|gho|ghu|ghs|github_pat|xox[a-z]|AKIA|ASIA|AIza|eyJ)[-_A-Za-z0-9]{6,}/.test( + /(?:^|[^A-Za-z0-9])(?:(?:sk|pk|rk)-[A-Za-z0-9_-]{6,}|gh[pousr]_[A-Za-z0-9]{6,}|github_pat_[A-Za-z0-9_]{6,}|xox[a-z]-[A-Za-z0-9-]{6,}|(?:AKIA|ASIA)[A-Z0-9]{12,}|AIza[A-Za-z0-9_-]{20,}|eyJ[A-Za-z0-9_-]{8,})/.test( value, ) || /\b[0-9a-f]{16,}\b/i.test(value) || @@ -216,11 +350,27 @@ export function looksSecret(value, freeText = false) { ) { return true; } - return ( - freeText && - (/[A-Za-z0-9-]+(?:\.[A-Za-z0-9-]+)*\.[A-Za-z]{2,}\b/.test(value) || - value.split(/\s+/).some((token) => token.length >= 24 && /\d/.test(token))) - ); + return freeText && /[A-Za-z0-9-]+(?:\.[A-Za-z0-9-]+)*\.[A-Za-z]{2,}\b/.test(value); +} + +/** + * A description made only of plain words and numbers: words are letters (hyphenated words allowed, each part at + * most 15 letters, an all-capitals part at most 5), numbers are integers or decimals with an optional percent + * sign, and the punctuation is , ; : ( ) + and an apostrophe. A token that mixes letters and digits, carries a + * dot inside it or runs long (a key, a seed, a host) is not a word, so it is refused whatever it encodes. + * @param {string} value + */ +export function plainWords(value) { + const word = /^[A-Za-z]{1,15}(?:-[A-Za-z]{1,15})*$/; + return value + .split(/[\s,;:()+']+/) + .filter(Boolean) + .map((t) => t.replace(/\.$/, "")) + .every( + (token) => + /^\d+(?:\.\d+)?%?$/.test(token) || + (word.test(token) && token.split("-").every((part) => !/^[A-Z]{6,}$/.test(part))), + ); } /** @@ -229,8 +379,10 @@ export function looksSecret(value, freeText = false) { * refuse (private names this repository must not know) come from `deny`. * @param {any} input * @param {string[]} [deny] + * @param {{ models: string[], harnesses: string[] }} [vocabulary] the public names a result may use (the source + * spec's entries); a model or harness outside it is refused */ -export function sanitizeOwn(input, deny = []) { +export function sanitizeOwn(input, deny = [], vocabulary = undefined) { /** @type {string[]} */ const problems = []; if ( @@ -256,8 +408,6 @@ export function sanitizeOwn(input, deny = []) { const MODEL = /^[a-z0-9][a-z0-9.-]{1,60}$/; const PLAIN = /^[A-Za-z0-9][A-Za-z0-9 ,.%()+:;'-]{0,139}$/; const NAME = /^[A-Za-z0-9][A-Za-z0-9 .+-]{0,39}$/; - // Compared with case, spacing and punctuation removed, so "Internal Tool" and "internal_tool" match "internal-tool". - const squash = (/** @type {string} */ s) => s.toLowerCase().replace(/[^a-z0-9]/g, ""); const lowered = deny.map(squash).filter((w) => w !== ""); const seen = new Set(); const results = input.results.map((/** @type {any} */ r, /** @type {number} */ i) => { @@ -273,7 +423,7 @@ export function sanitizeOwn(input, deny = []) { problems.push(`${at}.${key}: not a plain value of the allowed shape`); return ""; } - if (looksSecret(value, freeText)) { + if (looksSecret(value, freeText) || (freeText && key === "cohort" && !plainWords(value))) { problems.push(`${at}.${key}: looks like a credential, address or host`); } for (const word of lowered) { @@ -287,15 +437,28 @@ export function sanitizeOwn(input, deny = []) { /** @type {string} */ key, /** @type {number} */ min, /** @type {number} */ max, + integer = false, ) => { const value = r?.[key]; - if (typeof value !== "number" || !Number.isFinite(value) || value < min || value > max) { - problems.push(`${at}.${key}: expected a number from ${min} to ${max}`); + if ( + typeof value !== "number" || + !Number.isFinite(value) || + value < min || + value > max || + (integer && !Number.isInteger(value)) + ) { + problems.push( + `${at}.${key}: expected ${integer ? "an integer" : "a number"} from ${min} to ${max}`, + ); return 0; } return value; }; const checked = text("checked", DATE); + // The id is words and numbers like a cohort line, not a place to carry anything else. + if (typeof r?.id === "string" && !plainWords(r.id.replaceAll("-", " "))) { + problems.push(`${at}.id: not made of plain words and numbers`); + } if (checked !== "" && !isDate(checked)) { problems.push(`${at}.checked: not a real date`); } @@ -316,12 +479,22 @@ export function sanitizeOwn(input, deny = []) { ); } } - const of = number("of", 1, 100000); - const found = number("found", 0, of); + const of = number("of", 1, 100000, true); + const found = number("found", 0, of, true); + const model = text("model", MODEL, true); + const harness = text("harness", vocabulary === undefined ? NAME : /^.{1,60}$/, true); + if (vocabulary !== undefined) { + if (!vocabulary.models.includes(model)) { + problems.push(`${at}.model: not a model the source spec names`); + } + if (!vocabulary.harnesses.includes(harness)) { + problems.push(`${at}.harness: not a harness the source spec names`); + } + } return { id, - model: text("model", MODEL), - harness: text("harness", NAME, true), + model, + harness, effort, found, of, @@ -613,14 +786,20 @@ export async function run(argv, today = new Date().toISOString().slice(0, 10), d async function refresh(paths, values, today) { const spec = readJson(paths.spec); const deny = readDeny(values["deny-file"]); + const vocabulary = { + models: spec.entries.map((/** @type {any} */ e) => e.model), + harnesses: spec.entries.map((/** @type {any} */ e) => e.harness), + }; const rawSnapshot = values.fetch === true ? undefined : readFileSync(paths.snapshot, "utf8"); - let snapshot = rawSnapshot === undefined ? undefined : JSON.parse(rawSnapshot); + let snapshot; if (values.fetch === true) { const board = values["board-file"] !== undefined ? readJson(resolve(values["board-file"])) : await fetchBoard(spec.board.url); snapshot = reduceBoard(board, values.today ?? today); + } else { + snapshot = canonicalSnapshot(JSON.parse(/** @type {string} */ (rawSnapshot))); } const rawOwn = values["from-file"] === undefined && existsSync(paths.own) @@ -628,34 +807,40 @@ async function refresh(paths, values, today) { : undefined; const own = values["from-file"] !== undefined - ? sanitizeOwn(readJson(resolve(values["from-file"])), deny) + ? sanitizeOwn(readJson(resolve(values["from-file"])), deny, vocabulary) : rawOwn === undefined ? { version: 1, results: [] } - : sanitizeOwn(JSON.parse(rawOwn), deny); + : sanitizeOwn(JSON.parse(rawOwn), deny, vocabulary); const catalog = buildCatalog(spec, snapshot, own); - // Every string published for an own result is screened as published, assembled text included. + // Every string published for an own result is screened as published: each value on its own (a generated id, + // a sample line, the rationale), never joined with its neighbours. + const denied = deny.map(squash).filter(Boolean); for (const entry of catalog.entries.filter( (/** @type {any} */ e) => e.kind === "own-evaluation", )) { - const flat = JSON.stringify(entry) - .toLowerCase() - .replace(/[^a-z0-9]/g, ""); - for (const word of deny.map((w) => w.toLowerCase().replace(/[^a-z0-9]/g, "")).filter(Boolean)) { - if (flat.includes(word)) { + for (const text of stringValues(entry)) { + if (denied.some((word) => squash(text).includes(word))) { throw new Error(`catalog entry ${entry.id} contains a name this repository must not carry`); } } } + // What each input should hold on disk, so --check and a plain run agree on one repair. + const files = [ + { + name: "catalog", + path: paths.catalog, + have: existsSync(paths.catalog) ? readFileSync(paths.catalog, "utf8") : undefined, + want: catalog, + }, + { name: "snapshot", path: paths.snapshot, have: rawSnapshot, want: snapshot }, + ...(rawOwn === undefined + ? [] + : [{ name: "own results", path: paths.own, have: rawOwn, want: own }]), + ]; + const off = files.filter((f) => f.have !== serialize(f.want)); if (values.check === true) { - // The committed bytes, not their parse: an extra field or a shadowed duplicate key is a difference. - const committed = existsSync(paths.catalog) ? readFileSync(paths.catalog, "utf8") : undefined; - const files = [ - ["catalog", committed, serialize(catalog)], - ["snapshot", rawSnapshot, serialize(snapshot)], - ...(rawOwn === undefined ? [] : [["own results", rawOwn, serialize(own)]]), - ]; - const off = files.filter(([, have, want]) => have !== want); if (off.length > 0) { + const committed = files.find((f) => f.name === "catalog")?.have; const parsed = committed === undefined ? undefined : JSON.parse(committed); const ids = new Set(catalog.entries.map((/** @type {any} */ e) => e.id)); const behind = catalog.entries @@ -669,26 +854,46 @@ async function refresh(paths, values, today) { .filter((/** @type {any} */ c) => !ids.has(c.id)) .map((/** @type {any} */ c) => c.id); console.error( - `refresh-recommendations: not what the committed inputs generate: ${off.map(([name]) => name).join(", ")} (entries: ${[...behind, ...extra].join(", ") || "none; bytes, extra fields or duplicate keys"}); run scripts/refresh-recommendations.mjs`, + `refresh-recommendations: not what the committed inputs generate: ${off.map((f) => f.name).join(", ")} (entries: ${[...behind, ...extra].join(", ") || "none; bytes, extra fields, duplicate keys or row order"}); run scripts/refresh-recommendations.mjs, which rewrites each of those files in its canonical form`, ); return 1; } console.log(`refresh-recommendations: catalog matches (${catalog.entries.length} entries)`); return 0; } + // A plain run writes the catalog and the canonical form of every input that differs from it; a fetch or an + // import also writes the input it replaces. /** @type {Array<[string, unknown]>} */ - const outputs = [[paths.catalog, catalog]]; - if (values.fetch === true) { - outputs.unshift([paths.snapshot, snapshot]); + const outputs = off.filter((f) => f.name !== "catalog").map((f) => [f.path, f.want]); + if (values.fetch === true && !outputs.some(([path]) => path === paths.snapshot)) { + outputs.push([paths.snapshot, snapshot]); } if (values["from-file"] !== undefined) { - outputs.unshift([paths.own, own]); + outputs.push([paths.own, own]); } + outputs.push([paths.catalog, catalog]); writeAll(outputs); console.log(`refresh-recommendations: wrote the catalog (${catalog.entries.length} entries)`); return 0; } +/** + * @param {unknown} value every string value in a JSON value, not its keys + * @returns {string[]} + */ +function stringValues(value) { + if (typeof value === "string") { + return [value]; + } + if (Array.isArray(value)) { + return value.flatMap(stringValues); + } + if (value !== null && typeof value === "object") { + return Object.values(value).flatMap(stringValues); + } + return []; +} + if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) { process.exitCode = await run(process.argv.slice(2)); } diff --git a/skills/hr-code-review/test/refresh-recommendations.test.mjs b/skills/hr-code-review/test/refresh-recommendations.test.mjs index 9431db28..d0a12711 100644 --- a/skills/hr-code-review/test/refresh-recommendations.test.mjs +++ b/skills/hr-code-review/test/refresh-recommendations.test.mjs @@ -16,13 +16,16 @@ import { dirname, join, resolve } from "node:path"; import { fileURLToPath } from "node:url"; import { buildCatalog, + canonicalSnapshot, fetchBoard, looksSecret, + plainWords, pathsIn, reduceBoard, run, sanitizeOwn, serialize, + withLock, writeAll, } from "../scripts/refresh-recommendations.mjs"; @@ -35,8 +38,11 @@ const read = (path) => JSON.parse(readFileSync(path, "utf8")); async function inCopy(/** @type {(dir: string) => Promise | void} */ fn) { const dir = mkdtempSync(join(tmpdir(), "refresh-rec-")); try { + // The own file is optional: a checkout without one is a supported state, so the copy does not require it. for (const path of Object.values(real)) { - cpSync(path, join(dir, path.slice(refs.length + 1))); + if (existsSync(path)) { + cpSync(path, join(dir, path.slice(refs.length + 1))); + } } await fn(dir); } finally { @@ -219,14 +225,14 @@ test("a name on the deny list is refused wherever it appears, whatever its case" }); test("the committed own results and catalog name no private repository, path, address or credential", () => { - const text = JSON.stringify([read(real.own), read(real.catalog)]); + const text = JSON.stringify([existsSync(real.own) ? read(real.own) : null, read(real.catalog)]); assert.doesNotMatch(text, /\/home\/|\/Users\/|@/i); // The same detector the importer uses runs over every string the committed files hold. const strings = text.match(/"((?:[^"\\]|\\.)*)"/g) ?? []; for (const quoted of strings) { assert.equal(looksSecret(quoted.slice(1, -1)), false, quoted); } - sanitizeOwn(read(real.own)); + sanitizeOwn(existsSync(real.own) ? read(real.own) : { version: 1, results: [] }); }); test("--from-file sanitizes, rewrites the own file and the catalog, and --check then agrees", async () => { @@ -468,14 +474,17 @@ test("--check compares the committed bytes: a private extra field or a shadowed test("an interruption between publishing sources and the catalog leaves a complete old catalog that --check flags and a plain run repairs", async () => { await inCopy(async (dir) => { const before = readFileSync(join(dir, "panel-recommendations.json"), "utf8"); + const baseline = JSON.parse(before).entries.length; // The own file is already new, the catalog still old: what an interruption after the first rename leaves. writeFileSync(join(dir, "panel-recommendations.own.json"), serialize(own({ found: 81 }))); assert.equal(readFileSync(join(dir, "panel-recommendations.json"), "utf8"), before); - assert.equal(JSON.parse(before).entries.length, 5); + assert.ok(baseline > 0); const flagged = await silent(() => run(["--check"], "2026-11-21", dir)); assert.equal(flagged.code, 1); assert.equal((await silent(() => run([], "2026-11-21", dir))).code, 0); assert.equal((await silent(() => run(["--check"], "2026-11-21", dir))).code, 0); + // The repaired catalog is the old entries plus one for the new result, whatever the baseline was. + assert.equal(read(join(dir, "panel-recommendations.json")).entries.length, baseline + 1); }); }); @@ -510,7 +519,7 @@ test("the mode picks the inputs: fetch rebuilds a missing snapshot, an import re serialize(own({ cohort: "46 cases of widgetco" })), ); const incoming = join(dir, "incoming.json"); - writeFileSync(incoming, JSON.stringify(own({}))); + writeFileSync(incoming, JSON.stringify(own({ model: "model-a", harness: "CLI A" }))); const deny = join(dir, "deny.txt"); writeFileSync(deny, "widgetco\n"); const replaced = await silent(() => @@ -518,6 +527,10 @@ test("the mode picks the inputs: fetch rebuilds a missing snapshot, an import re ); assert.equal(replaced.code, 0, replaced.text); assert.equal(read(join(dir, "panel-recommendations.own.json")).results[0].cohort, good.cohort); + // A checkout without the optional own file passes the offline check too. + rmSync(join(dir, "panel-recommendations.own.json")); + assert.equal((await silent(() => run([], "2026-11-21", dir))).code, 0); + assert.equal((await silent(() => run(["--check"], "2026-11-21", dir))).code, 0); }); }); @@ -579,3 +592,178 @@ test("an impossible calendar date is refused wherever a fetch date enters", asyn assert.equal(readFileSync(join(dir, "panel-recommendations.json"), "utf8"), before); }); }); + +test("a seed, a host or a key in any identifier or description is refused; ordinary words are not", () => { + const bad = [ + { cohort: "46 cases, seed JBSWY3DPEHPK3PXP" }, + { cohort: "46 cases, seed JBSWYDPEHPKPXPAB" }, + { cohort: "46 cases, seed jbswy3dpehpk3pxp" }, + { cohort: "46 cases from bench.internal.example" }, + { model: "bench.internal.example" }, + { harness: "bench.internal.example" }, + { id: "jbswy3dpehpk3pxp" }, + { id: "key-0123456789abcdef0123" }, + ]; + for (const over of bad) { + assert.throws(() => sanitizeOwn(own(over)), /own results refused/, JSON.stringify(over)); + } + // "skipping" is a word, not a key; a decimal and a percent are numbers. + assert.doesNotThrow(() => + sanitizeOwn(own({ cohort: "46 cases, skipping 2.5% of files (blind)" })), + ); + assert.equal(plainWords("skipping the sk-proj1234567890abcdef"), false); + assert.equal(looksSecret("skipping ahead"), false); + // A model or harness the source spec does not name is refused even when it is plain. + const vocabulary = { models: ["gpt-6.2-astra"], harnesses: ["Codex CLI"] }; + assert.doesNotThrow(() => sanitizeOwn(own({}), [], vocabulary)); + assert.throws(() => sanitizeOwn(own({ model: "internal-model" }), [], vocabulary), /spec names/); + assert.throws(() => sanitizeOwn(own({ harness: "Internal Tool" }), [], vocabulary), /spec names/); +}); + +test("measurements outside their domain are refused, fractional means and durations are not", () => { + const bad = (/** @type {any} */ over) => + assert.throws( + () => reduceBoard(board([row(over)]), "2026-11-03"), + /snapshot|cannot read/, + JSON.stringify(over), + ); + bad({ cost_usd: -5 }); + bad({ wall_min: -1 }); + bad({ n_runs: 0 }); + bad({ n_runs: 2.5 }); + bad({ fixed: 106 }); + bad({ fixed: -1 }); + assert.doesNotThrow(() => + reduceBoard(board([row({ fixed: 40.25, wall_min: 12.5, n_runs: 3 })]), "2026-11-03"), + ); + for (const over of [ + { found: 0.5, of: 2 }, + { of: 2.5, found: 1 }, + ]) { + assert.throws(() => sanitizeOwn(own(over)), /an integer/); + } +}); + +test("the snapshot has one schema and one byte layout: an unknown field, a bad date or a changed row order fails offline", async () => { + const committed = readFileSync(real.snapshot, "utf8"); + // Reducing the committed measurements again gives the same bytes. + assert.equal(serialize(canonicalSnapshot(JSON.parse(committed))), committed); + await inCopy(async (dir) => { + const file = join(dir, "panel-board-snapshot.json"); + const snap = JSON.parse(committed); + /** @type {Array<[string, (s: any) => void]>} */ + const edits = [ + ["an extra field", (x) => void (x.project = "acme")], + ["an impossible date", (x) => void (x.fetched = "2026-02-31")], + ["a row reordered", (x) => void x.rows.reverse()], + ["a row with an extra field", (x) => void (x.rows[0].note = "x")], + ]; + for (const [name, edit] of edits) { + const edited = structuredClone(snap); + edit(edited); + writeFileSync(file, serialize(edited)); + const out = await silent(() => run(["--check"], "2026-11-21", dir)); + assert.equal(out.code, 1, `${name}: ${out.text}`); + } + writeFileSync(file, committed); + assert.equal((await silent(() => run(["--check"], "2026-11-21", dir))).code, 0); + }); +}); + +test("the repair --check prints fixes reformatted inputs: a plain run rewrites each input in its canonical form", async () => { + await inCopy(async (dir) => { + const snapshot = join(dir, "panel-board-snapshot.json"); + const ownFile = join(dir, "panel-recommendations.own.json"); + const canonicalSnap = readFileSync(snapshot, "utf8"); + writeFileSync(snapshot, JSON.stringify(JSON.parse(canonicalSnap))); + writeFileSync(ownFile, JSON.stringify({ version: 1, results: [] })); + const flagged = await silent(() => run(["--check"], "2026-11-21", dir)); + assert.equal(flagged.code, 1); + assert.match(flagged.text, /snapshot, own results/); + assert.equal((await silent(() => run([], "2026-11-21", dir))).code, 0); + assert.equal((await silent(() => run(["--check"], "2026-11-21", dir))).code, 0); + assert.equal(readFileSync(snapshot, "utf8"), canonicalSnap); + }); +}); + +test("a deny entry matches only inside one published string, never across neighbouring fields", async () => { + await inCopy(async (dir) => { + const incoming = join(dir, "incoming.json"); + writeFileSync(incoming, JSON.stringify(own({ id: "widget" }))); + const deny = join(dir, "deny.txt"); + // "widget-kind" spans the id's end and the next key in the serialized entry, but no value holds it. + writeFileSync(deny, "widget-kind\n"); + const ok = await silent(() => + run(["--from-file", incoming, "--deny-file", deny], "2026-11-21", dir), + ); + assert.equal(ok.code, 0, ok.text); + writeFileSync(deny, "known defects across 46\n"); + const refused = await silent(() => + run(["--from-file", incoming, "--deny-file", deny], "2026-11-21", dir), + ); + assert.equal(refused.code, 1); + }); +}); + +test("the refresh lock: an unreadable owner is busy, not stolen; a vanished lock is retried; a stale lock goes to exactly one racer", async () => { + await inCopy(async (dir) => { + const lock = join(dir, ".refresh.lock"); + writeFileSync(lock, ""); + await assert.rejects(() => withLock(dir, async () => 1), /retry/); + assert.equal(readFileSync(lock, "utf8"), ""); + writeFileSync(lock, "not a pid\n"); + await assert.rejects(() => withLock(dir, async () => 1), /cannot be read/); + // The holder finishes between the failed link and the read: the waiter acquires on retry. + writeFileSync(lock, `${process.pid}\n`); + assert.equal( + await withLock(dir, async () => "ran", { + afterContended: () => rmSync(lock, { force: true }), + }), + "ran", + ); + assert.equal(existsSync(lock), false); + // Two refreshes race on a dead owner's lock: one runs, the other is told to retry; nothing is left behind. + writeFileSync(lock, "2147483646\n"); + const results = await Promise.allSettled([ + withLock(dir, async () => "a"), + withLock(dir, async () => "b"), + ]); + assert.deepEqual(results.map((r) => r.status).toSorted(), ["fulfilled", "rejected"]); + assert.equal(existsSync(lock), false); + assert.deepEqual( + readdirSync(dir).filter((n) => n.startsWith(".refresh")), + [], + ); + // A lock is removed only by the process whose file it still is. + await withLock(dir, async () => { + rmSync(lock, { force: true }); + writeFileSync(lock, "99999\n"); + }); + assert.equal(readFileSync(lock, "utf8"), "99999\n"); + }); +}); + +test("work files of an interrupted refresh are reclaimed, and no before image is staged in the skill folder", async () => { + await inCopy(async (dir) => { + const abandoned = join(dir, ".refresh-abandoned"); + mkdirSync(abandoned); + writeFileSync(join(abandoned, "old-0"), "a private name that a replacement removed\n"); + assert.equal((await silent(() => run([], "2026-11-21", dir))).code, 0); + assert.equal(existsSync(abandoned), false); + // The before image of a replaced file is kept outside the folder while the renames run. + const seen = /** @type {string[]} */ ([]); + const a = join(dir, "a.json"); + writeFileSync(a, "old a\n"); + const b = join(dir, "b.json"); + mkdirSync(b); + writeFileSync(join(b, "x"), "x"); + assert.throws(() => + writeAll([ + [a, { n: 1 }], + [b, { n: 2 }], + ]), + ); + seen.push(...readdirSync(dir).filter((n) => n.startsWith(".refresh"))); + assert.deepEqual(seen, []); + }); +}); From 5e8d41e49c96bfa6bd3e8b4422f3c34feeb2db4a Mon Sep 17 00:00:00 2001 From: bompus Date: Sat, 21 Nov 2026 13:14:00 -0700 Subject: [PATCH 4/8] Panel recommendations generator round 3: own results are structured facts kept only in the catalog (one-file import), tool-owned transaction reclaim, serialized stale-lock recovery, controlled test fixtures, doc paragraph under the ceiling --- .oxfmtrc.json | 3 +- CHANGELOG.md | 2 +- .../references/panel-recommendations.md | 28 +- .../references/panel-recommendations.own.json | 4 - .../scripts/refresh-recommendations.mjs | 387 ++++--- .../test/refresh-recommendations.test.mjs | 943 +++++++++--------- 6 files changed, 634 insertions(+), 733 deletions(-) delete mode 100644 skills/hr-code-review/references/panel-recommendations.own.json diff --git a/.oxfmtrc.json b/.oxfmtrc.json index cc383447..08380398 100644 --- a/.oxfmtrc.json +++ b/.oxfmtrc.json @@ -5,8 +5,7 @@ "bun.lock", "skills/*/test/fixtures/**", "skills/hr-code-review/references/panel-board-snapshot.json", - "skills/hr-code-review/references/panel-recommendations.json", - "skills/hr-code-review/references/panel-recommendations.own.json" + "skills/hr-code-review/references/panel-recommendations.json" ], "sortPackageJson": true } diff --git a/CHANGELOG.md b/CHANGELOG.md index a8699f30..b6e02f1c 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 an optional file of the maintainer's own results (`--from-file`, sanitized to a fixed set of plain fields, with a deny file for extra names), and `--check` fails offline when the catalog is not what those files 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. 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 82fbf030..a758fb85 100644 --- a/skills/hr-code-review/references/panel-recommendations.md +++ b/skills/hr-code-review/references/panel-recommendations.md @@ -55,13 +55,21 @@ tradeoff and the uncertainty; the user confirms before any saved preference changes, and installing a newer catalog leaves saved profiles and bindings alone. An entry with `kind: "own-evaluation"` is a maintainer's own result: model, effort, -defects found of the total, false share, minutes a review and a one-line cohort -description, with `provenance: "own-evaluation"` and no public source. It comes from -a case set this repository does not publish, so it cannot be reproduced here and does -not compare with the board entries. The generator accepts only a fixed set of plain -fields for it (no paths, links, addresses, credentials or free text beyond the cohort -line) and refuses any extra name the maintainer lists in a deny file. The model and -harness must be names the source spec already lists, and the cohort line may hold only -plain words and numbers (no token that mixes letters and digits, no dotted host or -address). A plain run of the script also rewrites the snapshot and the own results in -their one canonical layout, which is what `--check` compares. +defects found of the total, false share and minutes a review, with +`provenance: "own-evaluation"` and no public source. It comes from a case set this +repository does not publish, so it cannot be reproduced here and does not compare with +the board entries. + +The entry carries the structured facts it is generated from (`facts`), so the catalog +is the only place the own results live. `--from-file` replaces all of them from a +file of `{ version: 1, results: [...] }` and writes the catalog alone. Each result has +exactly these fields: a `model` and `harness` the source spec already lists, an +`effort`, `found`, `of`, `falseSharePercent`, `wallMinutesPerReview`, `cases`, a +`caseSet` (`held-out`, `development` or `mixed`), `judging` (`blind-second-model`, +`one-model`, `two-models` or `person`) and a `checked` date. The cohort wording and the +entry id are built from those facts, so no typed text reaches a public file. The +import also needs a deny file of private names and refuses any published string that +holds one. + +A plain run of the script regenerates the catalog and writes the snapshot in its one +canonical layout, which is what `--check` compares. diff --git a/skills/hr-code-review/references/panel-recommendations.own.json b/skills/hr-code-review/references/panel-recommendations.own.json deleted file mode 100644 index d8557c7e..00000000 --- a/skills/hr-code-review/references/panel-recommendations.own.json +++ /dev/null @@ -1,4 +0,0 @@ -{ - "version": 1, - "results": [] -} diff --git a/skills/hr-code-review/scripts/refresh-recommendations.mjs b/skills/hr-code-review/scripts/refresh-recommendations.mjs index fafca71c..62189d5b 100644 --- a/skills/hr-code-review/scripts/refresh-recommendations.mjs +++ b/skills/hr-code-review/scripts/refresh-recommendations.mjs @@ -1,12 +1,14 @@ -// Regenerates references/panel-recommendations.json from the Bug Hunt board snapshot, the source -// spec and the sanitized own-results file, so the catalog follows its evidence and is not -// edited by hand. +// Regenerates references/panel-recommendations.json from the Bug Hunt board snapshot, the source spec and the +// maintainer's own results, so the catalog follows its evidence and is not edited by hand. The own results live +// only inside the catalog (each own entry carries the structured facts it is generated from), so importing them +// rewrites one file. // // bun scripts/refresh-recommendations.mjs regenerate the catalog from the committed files // bun scripts/refresh-recommendations.mjs --fetch read the public board, rewrite the snapshot, regenerate // bun scripts/refresh-recommendations.mjs --fetch --board-file board.json the same from a saved board file -// bun scripts/refresh-recommendations.mjs --from-file own.json [--deny-file words.txt] -// sanitize own results, rewrite the own file, regenerate +// bun scripts/refresh-recommendations.mjs --from-file own.json --deny-file words.txt +// replace the own results with the file's (validated, +// structured), regenerate // bun scripts/refresh-recommendations.mjs --check [--deny-file words.txt] // offline: fail when the catalog is not what the // committed files generate; no clock, no network @@ -34,7 +36,6 @@ const refs = join(skill, "references"); export const pathsIn = (dir) => ({ spec: join(dir, "panel-recommendations.sources.json"), snapshot: join(dir, "panel-board-snapshot.json"), - own: join(dir, "panel-recommendations.own.json"), catalog: join(dir, "panel-recommendations.json"), }); @@ -58,6 +59,28 @@ const readJson = (path) => JSON.parse(readFileSync(path, "utf8")); /** 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`; +// A work directory of this tool is `.refresh-` holding this marker file and `new-` files only; +// 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 */ +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()) { + continue; + } + const inside = readdirSync(path); + if ( + inside.includes(TRANSACTION_MARKER) && + readFileSync(join(path, TRANSACTION_MARKER), "utf8") === TRANSACTION_TEXT && + inside.every((n) => n === TRANSACTION_MARKER || /^new-\d+$/.test(n)) + ) { + rmSync(path, { recursive: true, force: true }); + } + } +} + /** * 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 @@ -73,6 +96,7 @@ export function writeAll(outputs) { 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-")); try { const staged = outputs.map(([path, value], i) => { @@ -111,43 +135,66 @@ export function writeAll(outputs) { /** * Run `fn` holding the folder's refresh lock, so two refreshes cannot interleave their read-build-write. - * The lock is a hard link to a file that already holds the owner's pid, so it is never seen empty. A refresh - * that finds a live (or unreadable) owner fails with a retry message and removes nothing; a lock whose owner - * is dead is renamed away (one rename wins) and re-acquired; a lock is removed only by the process whose file it - * still is. Work files of an earlier interrupted refresh are reclaimed under the lock. + * A lock is a hard link to a file that already holds the owner's pid, so it is never seen empty. A refresh that + * finds a live or unreadable owner fails with a retry message and removes nothing. A dead owner's lock is removed + * only by the one process that holds the recovery lock (`.refresh.takeover`, claimed the same way), which reads + * the owner again under it: the lock it removes is the dead owner's, because nobody else removes locks and nobody + * can link a new one while it exists. A lock is released only by the process whose file it still is. * @template T * @param {string} dir * @param {() => Promise} fn - * @param {{ afterContended?: () => void }} [hooks] a test seam between finding the lock and reading it + * @param {{ afterContended?: () => void | Promise, afterRead?: () => void | Promise }} [hooks] + * test seams: after a failed claim, and after the stale owner was read */ export async function withLock(dir, fn, hooks = {}) { const lock = join(dir, ".refresh.lock"); + const takeover = join(dir, ".refresh.takeover"); const mine = join(dir, `.refresh.lock.${process.pid}.${Math.random().toString(36).slice(2)}`); writeFileSync(mine, `${process.pid}\n`, { flag: "wx" }); const busy = (/** @type {string} */ why) => new Error(`another refresh holds ${lock} (${why}); retry when it has finished`); - try { - for (let attempt = 0; ; attempt++) { - try { - linkSync(mine, lock); - break; - } catch (error) { - if (/** @type {any} */ (error).code !== "EEXIST") { - throw error; - } + /** @param {string} path */ + const claim = (path) => { + try { + linkSync(mine, path); + return true; + } catch (error) { + if (/** @type {any} */ (error).code === "EEXIST") { + return false; } - hooks.afterContended?.(); - let text; - try { - text = readFileSync(lock, "utf8"); - } catch (error) { - if (/** @type {any} */ (error).code === "ENOENT" && attempt < 5) { - continue; // the holder finished between the failed link and the read - } - throw error; + throw error; + } + }; + /** @param {string} path the owner's pid, "gone" when the file vanished, "unreadable" otherwise */ + const ownerOf = (path) => { + try { + const owner = Number(readFileSync(path, "utf8").trim()); + return Number.isInteger(owner) && owner > 0 ? owner : "unreadable"; + } catch (error) { + if (/** @type {any} */ (error).code === "ENOENT") { + return "gone"; + } + throw error; + } + }; + /** @param {string} path remove a claim only when it is still this call's file */ + const release = (path) => { + try { + if (statSync(path).ino === statSync(mine).ino) { + rmSync(path, { force: true }); } - const owner = Number(text.trim()); - if (!Number.isInteger(owner) || owner <= 0) { + } catch { + // no claim, or not readable: nothing of this call's to remove + } + }; + try { + for (let attempt = 0; !claim(lock); attempt++) { + await hooks.afterContended?.(); + const owner = ownerOf(lock); + if (owner === "gone" && attempt < 5) { + continue; // the holder finished between the failed claim and the read + } + if (owner === "gone" || owner === "unreadable") { throw busy("its owner cannot be read"); } let alive = true; @@ -159,44 +206,22 @@ export async function withLock(dir, fn, hooks = {}) { if (alive || attempt >= 5) { throw busy(`process ${owner}`); } - // Take the dead owner's lock away by rename: of two waiters only one rename succeeds. If what was - // renamed is not the lock that was read (a live process took it in between), it is put back. - const stale = `${lock}.stale.${process.pid}.${attempt}`; - try { - renameSync(lock, stale); - } catch (error) { - if (/** @type {any} */ (error).code === "ENOENT") { - continue; - } - throw error; + await hooks.afterRead?.(); + if (!claim(takeover)) { + throw busy(`a stale lock is being recovered; remove ${takeover} if no refresh is running`); } - const taken = Number(readFileSync(stale, "utf8").trim()); - if (taken === owner) { - rmSync(stale, { force: true }); - } else { - try { - linkSync(stale, lock); - } finally { - rmSync(stale, { force: true }); + try { + if (ownerOf(lock) === owner) { + rmSync(lock, { force: true }); } - throw busy(`process ${taken}`); - } - } - for (const name of readdirSync(dir)) { - if (name.startsWith(".refresh-")) { - rmSync(join(dir, name), { recursive: true, force: true }); + } finally { + release(takeover); } } + reclaimAbandoned(dir); return await fn(); } finally { - // Remove the lock only when it is still the file this call linked. - try { - if (statSync(lock).ino === statSync(mine).ino) { - rmSync(lock, { force: true }); - } - } catch { - // no lock, or not readable: nothing of this call's to remove - } + release(lock); rmSync(mine, { force: true }); } } @@ -330,59 +355,40 @@ export function reduceBoard(board, fetched) { }); } -/** - * Whether a published text looks like a credential, an address or a host: an assignment-style word, a provider - * key with its separator, a long hex run, an IPv4 or IPv6 address, or (for free text) a host name. - * @param {string} value - * @param {boolean} [freeText] a cohort, harness or model line, where a host name can hide - */ -export function looksSecret(value, freeText = false) { - if (/api[_-]?key|token|secret|password|passwd|bearer|credential/i.test(value)) { - return true; - } - if ( - /(?:^|[^A-Za-z0-9])(?:(?:sk|pk|rk)-[A-Za-z0-9_-]{6,}|gh[pousr]_[A-Za-z0-9]{6,}|github_pat_[A-Za-z0-9_]{6,}|xox[a-z]-[A-Za-z0-9-]{6,}|(?:AKIA|ASIA)[A-Z0-9]{12,}|AIza[A-Za-z0-9_-]{20,}|eyJ[A-Za-z0-9_-]{8,})/.test( - value, - ) || - /\b[0-9a-f]{16,}\b/i.test(value) || - /\b\d{1,3}(?:\.\d{1,3}){3}\b/.test(value) || - (value.match(/:/g) ?? []).length >= 2 - ) { - return true; - } - return freeText && /[A-Za-z0-9-]+(?:\.[A-Za-z0-9-]+)*\.[A-Za-z]{2,}\b/.test(value); -} - -/** - * A description made only of plain words and numbers: words are letters (hyphenated words allowed, each part at - * most 15 letters, an all-capitals part at most 5), numbers are integers or decimals with an optional percent - * sign, and the punctuation is , ; : ( ) + and an apostrophe. A token that mixes letters and digits, carries a - * dot inside it or runs long (a key, a seed, a host) is not a word, so it is refused whatever it encodes. - * @param {string} value - */ -export function plainWords(value) { - const word = /^[A-Za-z]{1,15}(?:-[A-Za-z]{1,15})*$/; - return value - .split(/[\s,;:()+']+/) - .filter(Boolean) - .map((t) => t.replace(/\.$/, "")) - .every( - (token) => - /^\d+(?:\.\d+)?%?$/.test(token) || - (word.test(token) && token.split("-").every((part) => !/^[A-Z]{6,}$/.test(part))), - ); -} +const CASE_SETS = /** @type {Record} */ ({ + "held-out": "held-out", + development: "development", + mixed: "development and held-out", +}); +const JUDGING = /** @type {Record} */ ({ + "blind-second-model": "judged blind by a second model", + "one-model": "judged by one model", + "two-models": "judged by two models", + person: "judged by a person", +}); +const OWN_KEYS = [ + "model", + "harness", + "effort", + "found", + "of", + "falseSharePercent", + "wallMinutesPerReview", + "cases", + "caseSet", + "judging", + "checked", +]; /** - * The strings an own result may carry: a fixed set of keys, numbers, effort names and one short plain-text - * cohort line. Anything that could name a private repository, path, case or account is refused; extra words to - * refuse (private names this repository must not know) come from `deny`. - * @param {any} input - * @param {string[]} [deny] - * @param {{ models: string[], harnesses: string[] }} [vocabulary] the public names a result may use (the source - * spec's entries); a model or harness outside it is refused + * The facts an own result may state, and nothing else: no free text reaches the public catalog. The model and the + * harness must be names the source spec lists; the effort, the case set and the judging are fixed choices; the + * rest are bounded numbers and a date. The cohort wording and the result's id are built from those facts, so + * nothing a maintainer types can carry a name, a host or a credential into a public file. + * @param {any} input { version: 1, results: [...] } + * @param {{ models: string[], harnesses: string[] }} vocabulary */ -export function sanitizeOwn(input, deny = [], vocabulary = undefined) { +export function sanitizeOwn(input, vocabulary) { /** @type {string[]} */ const problems = []; if ( @@ -392,46 +398,22 @@ export function sanitizeOwn(input, deny = [], vocabulary = undefined) { ) { throw new Error("own results: expected exactly { version: 1, results: [...] }"); } - const keys = new Set([ - "id", - "model", - "harness", - "effort", - "found", - "of", - "falseSharePercent", - "wallMinutesPerReview", - "cohort", - "checked", - ]); - const ID = /^[a-z0-9][a-z0-9-]{1,60}$/; - const MODEL = /^[a-z0-9][a-z0-9.-]{1,60}$/; - const PLAIN = /^[A-Za-z0-9][A-Za-z0-9 ,.%()+:;'-]{0,139}$/; - const NAME = /^[A-Za-z0-9][A-Za-z0-9 .+-]{0,39}$/; - const lowered = deny.map(squash).filter((w) => w !== ""); const seen = new Set(); const results = input.results.map((/** @type {any} */ r, /** @type {number} */ i) => { const at = `results[${i}]`; - for (const key of Object.keys(r ?? {})) { - if (!keys.has(key)) { - problems.push(`${at}: field ${key} is not allowed`); - } + const keys = Object.keys(r ?? {}); + for (const key of keys.filter((k) => !OWN_KEYS.includes(k))) { + problems.push(`${at}: field ${key} is not allowed`); } - const text = (/** @type {string} */ key, /** @type {RegExp} */ pattern, freeText = false) => { - const value = r?.[key]; - if (typeof value !== "string" || !pattern.test(value)) { - problems.push(`${at}.${key}: not a plain value of the allowed shape`); + for (const key of OWN_KEYS.filter((k) => !keys.includes(k))) { + problems.push(`${at}: field ${key} is missing`); + } + const choice = (/** @type {string} */ key, /** @type {string[]} */ allowed) => { + if (typeof r?.[key] !== "string" || !allowed.includes(r[key])) { + problems.push(`${at}.${key}: not one of ${allowed.join(", ")}`); return ""; } - if (looksSecret(value, freeText) || (freeText && key === "cohort" && !plainWords(value))) { - problems.push(`${at}.${key}: looks like a credential, address or host`); - } - for (const word of lowered) { - if (squash(value).includes(word)) { - problems.push(`${at}.${key}: contains a name this repository must not carry`); - } - } - return value; + return r[key]; }; const number = ( /** @type {string} */ key, @@ -454,53 +436,31 @@ export function sanitizeOwn(input, deny = [], vocabulary = undefined) { } return value; }; - const checked = text("checked", DATE); - // The id is words and numbers like a cohort line, not a place to carry anything else. - if (typeof r?.id === "string" && !plainWords(r.id.replaceAll("-", " "))) { - problems.push(`${at}.id: not made of plain words and numbers`); - } - if (checked !== "" && !isDate(checked)) { - problems.push(`${at}.checked: not a real date`); + const model = choice("model", vocabulary.models); + const harness = choice("harness", vocabulary.harnesses); + const effort = choice("effort", EFFORTS); + const caseSet = choice("caseSet", Object.keys(CASE_SETS)); + const of = number("of", 1, 100000, true); + const checked = typeof r?.checked === "string" && isDate(r.checked) ? r.checked : ""; + if (checked === "") { + problems.push(`${at}.checked: not a real YYYY-MM-DD date`); } - const id = text("id", ID); + const id = `${model}-${effort}-${caseSet}`; if (seen.has(id)) { - problems.push(`${at}.id: duplicate ${id}`); + problems.push(`${at}: a second ${model} ${effort} ${caseSet} result`); } seen.add(id); - const effort = r?.effort; - if (!EFFORTS.includes(effort)) { - problems.push(`${at}.effort: not one of ${EFFORTS.join(", ")}`); - } - // The published id and every string built from the fields are screened as published, not as entered. - for (const word of lowered) { - if (squash(`own-${id}`).includes(word) || squash(String(effort)).includes(word)) { - problems.push( - `${at}: the published id or effort contains a name this repository must not carry`, - ); - } - } - const of = number("of", 1, 100000, true); - const found = number("found", 0, of, true); - const model = text("model", MODEL, true); - const harness = text("harness", vocabulary === undefined ? NAME : /^.{1,60}$/, true); - if (vocabulary !== undefined) { - if (!vocabulary.models.includes(model)) { - problems.push(`${at}.model: not a model the source spec names`); - } - if (!vocabulary.harnesses.includes(harness)) { - problems.push(`${at}.harness: not a harness the source spec names`); - } - } return { - id, model, harness, effort, - found, + found: number("found", 0, of, true), of, falseSharePercent: number("falseSharePercent", 0, 100), wallMinutesPerReview: number("wallMinutesPerReview", 0, 100000), - cohort: text("cohort", PLAIN, true), + cases: number("cases", 1, 100000, true), + caseSet, + judging: choice("judging", Object.keys(JUDGING)), checked, }; }); @@ -622,7 +582,7 @@ export function buildCatalog(spec, snapshot, own) { }; }); const ownEntries = own.results.map((/** @type {any} */ r) => ({ - id: `own-${r.id}`, + id: `own-${r.model}-${r.effort}-${r.caseSet}`, kind: "own-evaluation", provenance: "own-evaluation", profiles: ["balanced"], @@ -639,13 +599,14 @@ export function buildCatalog(spec, snapshot, own) { }, ], checked: r.checked, - samples: `${r.of} known defects across ${r.cohort}`, + samples: `${r.of} known defects across ${r.cases} ${CASE_SETS[r.caseSet]} code changes, ${JUDGING[r.judging]}`, metric: `known defects found, out of ${r.of}; false findings as a share of posted comments`, timeDefinition: spec.own.timeDefinition, costDefinition: "unknown", limitations: spec.own.limitations, rationale: `Found ${r.found} of ${r.of} (${Math.round((r.found / r.of) * 100)}%) with ${r.falseSharePercent}% false findings in ${r.wallMinutesPerReview} minutes a review. ${spec.own.rationaleTail}`, status: "current", + facts: r, })); const dates = [snapshot.fetched, ...own.results.map((/** @type {any} */ r) => r.checked)]; return { @@ -790,6 +751,7 @@ async function refresh(paths, values, today) { models: spec.entries.map((/** @type {any} */ e) => e.model), harnesses: spec.entries.map((/** @type {any} */ e) => e.harness), }; + const rawCatalog = existsSync(paths.catalog) ? readFileSync(paths.catalog, "utf8") : undefined; const rawSnapshot = values.fetch === true ? undefined : readFileSync(paths.snapshot, "utf8"); let snapshot; if (values.fetch === true) { @@ -801,19 +763,23 @@ async function refresh(paths, values, today) { } else { snapshot = canonicalSnapshot(JSON.parse(/** @type {string} */ (rawSnapshot))); } - const rawOwn = - values["from-file"] === undefined && existsSync(paths.own) - ? readFileSync(paths.own, "utf8") - : undefined; - const own = + // The own results are the facts the catalog's own entries carry; an import replaces all of them, so the + // old ones are not read (a newly denied name in them cannot block their replacement). + const committed = rawCatalog === undefined ? undefined : JSON.parse(rawCatalog); + const own = sanitizeOwn( values["from-file"] !== undefined - ? sanitizeOwn(readJson(resolve(values["from-file"])), deny, vocabulary) - : rawOwn === undefined - ? { version: 1, results: [] } - : sanitizeOwn(JSON.parse(rawOwn), deny, vocabulary); + ? readJson(resolve(values["from-file"])) + : { + version: 1, + results: (committed?.entries ?? []) + .filter((/** @type {any} */ e) => e.kind === "own-evaluation") + .map((/** @type {any} */ e) => e.facts), + }, + vocabulary, + ); const catalog = buildCatalog(spec, snapshot, own); - // Every string published for an own result is screened as published: each value on its own (a generated id, - // a sample line, the rationale), never joined with its neighbours. + // Every string published for an own result is screened as published: each value on its own, never joined + // with its neighbours. const denied = deny.map(squash).filter(Boolean); for (const entry of catalog.entries.filter( (/** @type {any} */ e) => e.kind === "own-evaluation", @@ -824,33 +790,23 @@ async function refresh(paths, values, today) { } } } - // What each input should hold on disk, so --check and a plain run agree on one repair. + // What each file should hold on disk, so --check and a plain run agree on one repair. const files = [ - { - name: "catalog", - path: paths.catalog, - have: existsSync(paths.catalog) ? readFileSync(paths.catalog, "utf8") : undefined, - want: catalog, - }, + { name: "catalog", path: paths.catalog, have: rawCatalog, want: catalog }, { name: "snapshot", path: paths.snapshot, have: rawSnapshot, want: snapshot }, - ...(rawOwn === undefined - ? [] - : [{ name: "own results", path: paths.own, have: rawOwn, want: own }]), ]; const off = files.filter((f) => f.have !== serialize(f.want)); if (values.check === true) { if (off.length > 0) { - const committed = files.find((f) => f.name === "catalog")?.have; - const parsed = committed === undefined ? undefined : JSON.parse(committed); const ids = new Set(catalog.entries.map((/** @type {any} */ e) => e.id)); const behind = catalog.entries .filter( (/** @type {any} */ e) => JSON.stringify(e) !== - JSON.stringify(parsed?.entries?.find((/** @type {any} */ c) => c.id === e.id)), + JSON.stringify(committed?.entries?.find((/** @type {any} */ c) => c.id === e.id)), ) .map((/** @type {any} */ e) => e.id); - const extra = (parsed?.entries ?? []) + const extra = (committed?.entries ?? []) .filter((/** @type {any} */ c) => !ids.has(c.id)) .map((/** @type {any} */ c) => c.id); console.error( @@ -861,16 +817,13 @@ async function refresh(paths, values, today) { console.log(`refresh-recommendations: catalog matches (${catalog.entries.length} entries)`); return 0; } - // A plain run writes the catalog and the canonical form of every input that differs from it; a fetch or an - // import also writes the input it replaces. + // A plain run writes the catalog and the canonical form of the snapshot when it differs; a fetch also writes + // the snapshot it read. An import writes the catalog alone. /** @type {Array<[string, unknown]>} */ - const outputs = off.filter((f) => f.name !== "catalog").map((f) => [f.path, f.want]); - if (values.fetch === true && !outputs.some(([path]) => path === paths.snapshot)) { + const outputs = []; + if (values.fetch === true || off.some((f) => f.name === "snapshot")) { outputs.push([paths.snapshot, snapshot]); } - if (values["from-file"] !== undefined) { - outputs.push([paths.own, own]); - } outputs.push([paths.catalog, catalog]); writeAll(outputs); console.log(`refresh-recommendations: wrote the catalog (${catalog.entries.length} entries)`); diff --git a/skills/hr-code-review/test/refresh-recommendations.test.mjs b/skills/hr-code-review/test/refresh-recommendations.test.mjs index d0a12711..9a025c4d 100644 --- a/skills/hr-code-review/test/refresh-recommendations.test.mjs +++ b/skills/hr-code-review/test/refresh-recommendations.test.mjs @@ -1,14 +1,12 @@ import { test } from "node:test"; import assert from "node:assert/strict"; import { - cpSync, existsSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, rmSync, - symlinkSync, writeFileSync, } from "node:fs"; import { tmpdir } from "node:os"; @@ -18,8 +16,6 @@ import { buildCatalog, canonicalSnapshot, fetchBoard, - looksSecret, - plainWords, pathsIn, reduceBoard, run, @@ -34,22 +30,6 @@ const real = pathsIn(refs); /** @param {string} path */ const read = (path) => JSON.parse(readFileSync(path, "utf8")); -/** A references folder copy that a test may write to; removed after the test. */ -async function inCopy(/** @type {(dir: string) => Promise | void} */ fn) { - const dir = mkdtempSync(join(tmpdir(), "refresh-rec-")); - try { - // The own file is optional: a checkout without one is a supported state, so the copy does not require it. - for (const path of Object.values(real)) { - if (existsSync(path)) { - cpSync(path, join(dir, path.slice(refs.length + 1))); - } - } - await fn(dir); - } finally { - rmSync(dir, { recursive: true, force: true }); - } -} - const silent = async (/** @type {() => Promise} */ fn) => { const err = console.error; const log = console.log; @@ -106,11 +86,82 @@ const spec = { }, ], }; +const vocabulary = { models: ["model-a", "model-b"], harnesses: ["CLI A", "CLI B"] }; +const empty = { version: 1, results: [] }; + +const good = { + model: "model-a", + harness: "CLI A", + effort: "medium", + found: 80, + of: 141, + falseSharePercent: 0.2, + wallMinutesPerReview: 2.7, + cases: 46, + caseSet: "held-out", + judging: "blind-second-model", + checked: "2026-11-21", +}; +const own = (/** @type {any} */ over = {}) => ({ version: 1, results: [{ ...good, ...over }] }); + +/** + * A complete controlled references folder: a test spec, a snapshot reduced from a small board and the catalog + * they generate. Mutation tests run here; the committed files are read only by the committed-artifact checks. + * @param {(dir: string) => Promise | void} fn + */ +async function inFixture(fn) { + const dir = mkdtempSync(join(tmpdir(), "refresh-rec-")); + try { + const paths = pathsIn(dir); + const snapshot = reduceBoard( + board([row({ effort: "medium", fixed: 20 }), row()]), + "2026-11-03", + ); + writeFileSync(paths.spec, serialize(spec)); + writeFileSync(paths.snapshot, serialize(snapshot)); + writeFileSync(paths.catalog, serialize(buildCatalog(spec, snapshot, empty))); + await fn(dir); + } finally { + rmSync(dir, { recursive: true, force: true }); + } +} +/** Import a result file with a deny file, as a maintainer does. */ +async function importOwn( + /** @type {string} */ dir, + /** @type {any} */ file, + deny = "unrelated-name\n", +) { + writeFileSync(join(dir, "incoming.json"), JSON.stringify(file)); + writeFileSync(join(dir, "deny.txt"), deny); + return silent(() => + run( + ["--from-file", join(dir, "incoming.json"), "--deny-file", join(dir, "deny.txt")], + "2026-11-21", + dir, + ), + ); +} +const check = (/** @type {string} */ dir) => silent(() => run(["--check"], "2026-11-21", dir)); -test("the committed catalog is what the snapshot, the spec and the own results generate", async () => { +test("the committed catalog is what the snapshot, the spec and the own facts it carries generate", async () => { const { code, text } = await silent(() => run(["--check"])); assert.equal(code, 0, text); -}); + const catalog = read(real.catalog); + assert.doesNotMatch(JSON.stringify(catalog), /\/home\/|\/Users\/|@/i); + // The committed own entries are valid facts, so a plain regeneration would keep them. + const facts = catalog.entries + .filter((/** @type {any} */ e) => e.kind === "own-evaluation") + .map((/** @type {any} */ e) => e.facts); + assert.doesNotThrow(() => sanitizeOwn({ version: 1, results: facts }, committedVocabulary())); +}); +/** The committed spec's own names, for the committed-artifact check. */ +function committedVocabulary() { + const committed = read(real.spec); + return { + models: committed.entries.map((/** @type {any} */ e) => e.model), + harnesses: committed.entries.map((/** @type {any} */ e) => e.harness), + }; +} test("a superseded row is dropped and the newest current row per effort is used", () => { const snap = reduceBoard( @@ -122,7 +173,7 @@ test("a superseded row is dropped and the newest current row per effort is used" "2026-11-03", ); assert.equal(snap.rows.length, 2); - const catalog = buildCatalog(spec, snap, { version: 1, results: [] }); + const catalog = buildCatalog(spec, snap, empty); assert.deepEqual( catalog.entries[0].efforts.map((/** @type {any} */ e) => [e.effort, e.fixed]), [ @@ -140,164 +191,319 @@ test("a superseded row is dropped and the newest current row per effort is used" test("a wanted effort the board no longer lists is an error that names it", () => { const snap = reduceBoard(board([row({ effort: "high" })]), "2026-11-03"); - assert.throws(() => buildCatalog(spec, snap, { version: 1, results: [] }), /Model A medium/); + assert.throws(() => buildCatalog(spec, snap, empty), /Model A medium/); }); -test("a board whose layout changed is refused, not guessed at", () => { +test("a board whose layout changed, or a measurement outside its domain, is refused", () => { assert.throws(() => reduceBoard({ runs: [] }, "2026-11-03"), /layout changed/); assert.throws(() => reduceBoard(board([row({ fixed: "many" })]), "2026-11-03"), /cannot read/); + assert.throws(() => reduceBoard(board([row({ fixed: null })]), "2026-11-03"), /cannot read/); + assert.throws(() => reduceBoard(board([row({ n_runs: true })]), "2026-11-03"), /cannot read/); assert.throws(() => reduceBoard(board([]), "yesterday"), /YYYY-MM-DD/); + assert.throws(() => reduceBoard(board([row()]), "2026-02-31"), /real YYYY-MM-DD/); + assert.doesNotThrow(() => reduceBoard(board([row()]), "2028-02-29")); + for (const over of [ + { cost_usd: -5 }, + { wall_min: -1 }, + { n_runs: 0 }, + { n_runs: 2.5 }, + { fixed: 106 }, + { fixed: -1 }, + ]) { + assert.throws( + () => reduceBoard(board([row(over)]), "2026-11-03"), + /snapshot/, + JSON.stringify(over), + ); + } + assert.doesNotThrow(() => + reduceBoard(board([row({ fixed: 40.25, wall_min: 12.5, n_runs: 3 })]), "2026-11-03"), + ); }); -const good = { - id: "astra-62-medium-heldout", - model: "gpt-6.2-astra", - harness: "Codex CLI", - effort: "medium", - found: 80, - of: 141, - falseSharePercent: 0.2, - wallMinutesPerReview: 2.7, - cohort: "46 held-out code changes, judged blind by a second model", - checked: "2026-11-21", -}; -const own = (/** @type {any} */ over) => ({ version: 1, results: [{ ...good, ...over }] }); +test("the newest current row wins, then the one with more runs; a saving is stated only when it is one", () => { + const snap = reduceBoard( + board([ + row({ effort: "medium", fixed: 10, date: "2026-11-02", cost_usd: 30, wall_min: 50 }), + row({ effort: "medium", fixed: 20, date: "2026-11-01", cost_usd: 5, wall_min: 5 }), + row({ effort: "high", fixed: 40, date: "2026-11-02", n_runs: 2, cost_usd: 10, wall_min: 10 }), + row({ effort: "high", fixed: 41, date: "2026-11-02", n_runs: 5, cost_usd: 10, wall_min: 10 }), + ]), + "2026-11-03", + ); + const [entry] = buildCatalog(spec, snap, empty).entries; + assert.deepEqual( + entry.efforts.map((/** @type {any} */ e) => [e.effort, e.fixed]), + [ + ["medium", 10], + ["high", 41], + ], + ); + assert.match(entry.rationale, /^high fixed the most \(41 of 105\); medium fixed 31 fewer\.( |$)/); +}); -test("a sanitized own result becomes a catalog entry that says whose figure it is", () => { - const catalog = buildCatalog( - spec, - reduceBoard(board([row({ effort: "medium" }), row()]), "2026-11-03"), - sanitizeOwn(own({})), +test("a gap inside the board's run-to-run spread is not ranked; every effort inside it is named", () => { + const withSpread = { ...spec, board: { ...spec.board, noisePoints: 1.5 } }; + const snap = reduceBoard( + board([row({ effort: "medium", fixed: 40 }), row({ effort: "high", fixed: 40.5 })]), + "2026-11-03", + ); + assert.match(buildCatalog(withSpread, snap, empty).entries[0].rationale, /not distinguishable/); + const three = { + ...withSpread, + entries: [{ ...spec.entries[0], efforts: ["medium", "high", "xhigh"] }], + }; + const [entry] = buildCatalog( + three, + reduceBoard( + board([ + row({ effort: "medium", fixed: 50.3, cost_usd: 5, wall_min: 10 }), + row({ effort: "high", fixed: 59.6, cost_usd: 8, wall_min: 48.5 }), + row({ effort: "xhigh", fixed: 60.2, cost_usd: 10, wall_min: 84 }), + ]), + "2026-11-03", + ), + empty, + ).entries; + assert.match( + entry.rationale, + /^xhigh fixed the most \(60\.2 of 105\); high \(59\.6\) is within the board's run-to-run spread of it for 20% less cost and 42% less time; medium fixed 9\.9 fewer for 50% less cost and 88% less time\./, ); - const entry = catalog.entries.at(-1); - assert.equal(entry.id, "own-astra-62-medium-heldout"); + const tie = reduceBoard( + board([row({ effort: "medium", fixed: 40 }), row({ effort: "high", fixed: 40 })]), + "2026-11-03", + ); + assert.match( + buildCatalog(spec, tie, empty).entries[0].rationale, + /medium fixed 40 and high 40 of 105/, + ); +}); + +test("the snapshot has one schema and one byte layout", async () => { + const committed = readFileSync(real.snapshot, "utf8"); + assert.equal(serialize(canonicalSnapshot(JSON.parse(committed))), committed); + await inFixture(async (dir) => { + const file = pathsIn(dir).snapshot; + const canonical = readFileSync(file, "utf8"); + const snap = JSON.parse(canonical); + /** @type {Array<[string, (s: any) => void]>} */ + const edits = [ + ["an extra field", (x) => void (x.project = "acme")], + ["an impossible date", (x) => void (x.fetched = "2026-02-31")], + ["a row reordered", (x) => void x.rows.reverse()], + ["a row with an extra field", (x) => void (x.rows[0].note = "x")], + ]; + for (const [name, edit] of edits) { + const edited = structuredClone(snap); + edit(edited); + writeFileSync(file, serialize(edited)); + const out = await check(dir); + assert.equal(out.code, 1, `${name}: ${out.text}`); + } + // Reformatted bytes: the printed repair, a plain run, makes the next check pass. + writeFileSync(file, JSON.stringify(snap)); + assert.equal((await check(dir)).code, 1); + assert.equal((await silent(() => run([], "2026-11-21", dir))).code, 0); + assert.equal((await check(dir)).code, 0); + assert.equal(readFileSync(file, "utf8"), canonical); + }); +}); + +test("an own result is structured facts: nothing a maintainer types becomes public text", () => { + const entry = buildCatalog( + spec, + canonicalSnapshot( + JSON.parse(serialize(reduceBoard(board([row({ effort: "medium" }), row()]), "2026-11-03"))), + ), + sanitizeOwn(own(), vocabulary), + ).entries.at(-1); + assert.equal(entry.id, "own-model-a-medium-held-out"); assert.equal(entry.kind, "own-evaluation"); assert.equal(entry.provenance, "own-evaluation"); assert.equal(entry.sourceUrl, undefined); assert.equal(entry.efforts[0].found, 80); - assert.equal(entry.limitations, "ol"); - assert.equal(catalog.reviewed, "2026-11-21"); -}); - -test("own results that could carry a private name, path, address or link are refused", () => { + assert.equal( + entry.samples, + "141 known defects across 46 held-out code changes, judged blind by a second model", + ); + assert.deepEqual(entry.facts, good); const bad = [ - { id: "x/y" }, - { cohort: "cases from acme/widgets" }, - { cohort: "files under /home/someone/cases" }, - { cohort: "reported by someone@example.com" }, - { cohort: "see https://private.example/cases" }, - { cohort: "C:\\cases\\private" }, - { harness: "codex --api-key abc" }, - { cohort: "46 cases, key sk-proj1234567890abcdef" }, - { cohort: "46 cases, id 0123456789abcdef0123" }, - { cohort: "see 192.0.2.1" }, - { cohort: "see host.internal.example" }, - { cohort: "46 cases, addr 2001:db8::1" }, - { cohort: "46 cases, blob Zm9vYmFyMTIzNDU2Nzg5MDEyMzQ1" }, - { harness: "build.internal.example" }, - { id: "sk-proj1234567890abcdef" }, - { model: "Model With Spaces" }, + { cohort: "46 cases of acme" }, + { id: "x" }, + { model: "internal-model" }, + { model: "bench.internal.example" }, + { harness: "Internal Tool" }, { effort: "extreme" }, + { caseSet: "private" }, + { judging: "see https://private.example" }, { found: 200 }, + { found: 0.5 }, + { of: 2.5 }, + { cases: 0 }, { falseSharePercent: -1 }, { wallMinutesPerReview: "2" }, - { extra: "field" }, + { checked: "2026-13-45" }, ]; for (const over of bad) { - assert.throws(() => sanitizeOwn(own(over)), /own results refused/, JSON.stringify(over)); + assert.throws( + () => sanitizeOwn(own(over), vocabulary), + /own results refused/, + JSON.stringify(over), + ); } - assert.throws(() => sanitizeOwn({ version: 1, results: [good, good] }), /duplicate/); - assert.throws(() => sanitizeOwn({ results: [] }), /expected/); - assert.throws(() => sanitizeOwn({ version: 1, results: [], project: "x" }), /expected exactly/); - assert.doesNotThrow(() => sanitizeOwn(own({}))); - assert.equal( - looksSecret("46 held-out code changes, judged blind by a second model", true), - false, + const missing = { ...good }; + delete /** @type {any} */ (missing).judging; + assert.throws( + () => sanitizeOwn({ version: 1, results: [missing] }, vocabulary), + /judging is missing/, ); -}); - -test("a name on the deny list is refused wherever it appears, whatever its case", () => { assert.throws( - () => sanitizeOwn(own({ cohort: "46 Held-Out cases of Widget Co changes" }), ["widget co"]), - /must not carry/, + () => sanitizeOwn({ version: 1, results: [good, good] }, vocabulary), + /second model-a/, + ); + assert.throws( + () => sanitizeOwn({ version: 1, results: [], project: "x" }, vocabulary), + /exactly/, + ); + assert.throws(() => sanitizeOwn({ results: [] }, vocabulary), /exactly/); + // Two results for one model differ by effort or case set. + assert.doesNotThrow(() => + sanitizeOwn( + { version: 1, results: [good, { ...good, effort: "high" }, { ...good, caseSet: "mixed" }] }, + vocabulary, + ), ); - assert.doesNotThrow(() => sanitizeOwn(own({}), ["widget co", ""])); -}); - -test("the committed own results and catalog name no private repository, path, address or credential", () => { - const text = JSON.stringify([existsSync(real.own) ? read(real.own) : null, read(real.catalog)]); - assert.doesNotMatch(text, /\/home\/|\/Users\/|@/i); - // The same detector the importer uses runs over every string the committed files hold. - const strings = text.match(/"((?:[^"\\]|\\.)*)"/g) ?? []; - for (const quoted of strings) { - assert.equal(looksSecret(quoted.slice(1, -1)), false, quoted); - } - sanitizeOwn(existsSync(real.own) ? read(real.own) : { version: 1, results: [] }); }); -test("--from-file sanitizes, rewrites the own file and the catalog, and --check then agrees", async () => { - await inCopy(async (dir) => { - const file = join(dir, "incoming.json"); - writeFileSync(file, JSON.stringify(own({}))); - const deny = join(dir, "deny.txt"); - writeFileSync(deny, "widget co\n"); - const done = await silent(() => - run(["--from-file", file, "--deny-file", deny], "2026-11-21", dir), - ); +test("an import rewrites the catalog alone, keeps the snapshot's bytes, and --check then agrees", async () => { + await inFixture(async (dir) => { + const paths = pathsIn(dir); + const snapshotBefore = readFileSync(paths.snapshot, "utf8"); + const done = await importOwn(dir, own()); assert.equal(done.code, 0, done.text); - assert.equal(read(join(dir, "panel-recommendations.own.json")).results.length, 1); - assert.equal( - read(join(dir, "panel-recommendations.json")).entries.at(-1).id, - "own-astra-62-medium-heldout", + assert.equal(readFileSync(paths.snapshot, "utf8"), snapshotBefore); + assert.deepEqual( + readdirSync(dir).filter((n) => n.includes("own")), + [], + ); + const catalog = read(paths.catalog); + assert.equal(catalog.entries.at(-1).id, "own-model-a-medium-held-out"); + assert.equal(catalog.reviewed, "2026-11-21"); + assert.equal((await check(dir)).code, 0); + // A plain run keeps the own entries it finds in the catalog. + assert.equal((await silent(() => run([], "2026-11-21", dir))).code, 0); + assert.equal(read(paths.catalog).entries.length, 2); + // A later import replaces all of them: removing a result is an import without it. + assert.equal((await importOwn(dir, own({ effort: "high" }))).code, 0); + assert.deepEqual( + read(paths.catalog).entries.map((/** @type {any} */ e) => e.id), + ["a", "own-model-a-high-held-out"], + ); + assert.equal((await importOwn(dir, empty)).code, 0); + assert.deepEqual( + read(paths.catalog).entries.map((/** @type {any} */ e) => e.id), + ["a"], ); - assert.equal((await silent(() => run(["--check"], "2026-11-21", dir))).code, 0); - // A hand edit of the catalog is what --check exists to catch. - const catalog = read(join(dir, "panel-recommendations.json")); - catalog.entries[0].efforts[0].fixed += 1; - writeFileSync(join(dir, "panel-recommendations.json"), JSON.stringify(catalog)); - const drift = await silent(() => run(["--check"], "2026-11-21", dir)); - assert.equal(drift.code, 1); - assert.match(drift.text, /entries: opus-5-5-bug-hunt/); }); }); -test("a refused own file changes nothing", async () => { - await inCopy(async (dir) => { - const before = readFileSync(join(dir, "panel-recommendations.json"), "utf8"); - const file = join(dir, "incoming.json"); - writeFileSync(file, JSON.stringify(own({ cohort: "from /home/x" }))); - const deny = join(dir, "deny.txt"); - writeFileSync(deny, "held-out\n"); +test("a refused import changes nothing, and an import needs a deny file", async () => { + await inFixture(async (dir) => { + const before = readFileSync(pathsIn(dir).catalog, "utf8"); + const refused = await importOwn(dir, own({ model: "internal-model" })); + assert.equal(refused.code, 1); + assert.equal(readFileSync(pathsIn(dir).catalog, "utf8"), before); + // A deny entry that matches a published string refuses the import. + const denied = await importOwn(dir, own(), "model-a\n"); + assert.equal(denied.code, 1); + assert.match(denied.text, /must not carry/); + assert.equal(readFileSync(pathsIn(dir).catalog, "utf8"), before); + writeFileSync(join(dir, "incoming.json"), JSON.stringify(own())); const out = await silent(() => - run(["--from-file", file, "--deny-file", deny], "2026-11-21", dir), + run(["--from-file", join(dir, "incoming.json")], "2026-11-21", dir), ); - assert.equal(out.code, 1); - assert.equal(readFileSync(join(dir, "panel-recommendations.json"), "utf8"), before); - writeFileSync(file, JSON.stringify(own({}))); - assert.equal( - (await silent(() => run(["--from-file", file, "--deny-file", deny], "2026-11-21", dir))).code, - 1, + assert.equal(out.code, 2); + assert.match(out.text, /needs --deny-file/); + }); +}); + +test("a deny entry matches inside one published string, never across neighbouring fields", async () => { + await inFixture(async (dir) => { + // "ownmodel" would span the id prefix and the next JSON key if the entry were joined; no value holds it. + const ok = await importOwn(dir, own(), "id-kind\n"); + assert.equal(ok.code, 0, ok.text); + // A phrase inside one generated sample line refuses. + const refused = await importOwn(dir, own(), "known defects across 46\n"); + assert.equal(refused.code, 1); + // A deny entry covers the generated id and the effort as published. + assert.equal((await importOwn(dir, own(), "own-model-a-medium-held-out\n")).code, 1); + assert.equal((await importOwn(dir, own({ effort: "high" }), "high\n")).code, 1); + }); +}); + +test("the catalog is checked byte for byte: a hand edit, extra field, tampered own text or duplicate key fails", async () => { + await inFixture(async (dir) => { + const file = pathsIn(dir).catalog; + await importOwn(dir, own()); + const canonical = readFileSync(file, "utf8"); + const edit = async (/** @type {string} */ name, /** @type {(c: any) => void} */ fn) => { + const catalog = JSON.parse(canonical); + fn(catalog); + writeFileSync(file, serialize(catalog)); + const out = await check(dir); + assert.equal(out.code, 1, name); + return out.text; + }; + assert.match( + await edit("board figure", (c) => void (c.entries[0].efforts[0].fixed += 1)), + /entries: a/, + ); + assert.match( + await edit("own text", (c) => void (c.entries[1].samples = "x")), + /own-model-a-medium-held-out/, + ); + await edit("extra field", (c) => void (c.entries[1].project = "acme")); + await edit("extra top-level field", (c) => void (c.project = "acme")); + writeFileSync(file, canonical.replace('"version": 1,', '"version": 1,\n "version": 1,')); + assert.match((await check(dir)).text, /duplicate keys/); + // A plain run regenerates the catalog from the facts and the board, which repairs the own text. + writeFileSync( + file, + serialize({ + ...JSON.parse(canonical), + entries: JSON.parse(canonical).entries.map( + (/** @type {any} */ e, /** @type {number} */ i) => (i === 1 ? { ...e, samples: "x" } : e), + ), + }), ); + assert.equal((await silent(() => run([], "2026-11-21", dir))).code, 0); + assert.equal(readFileSync(file, "utf8"), canonical); }); }); -test("--fetch with a saved board rewrites the snapshot and regenerates", async () => { - await inCopy(async (dir) => { +test("--fetch with a saved board rewrites the snapshot and regenerates; a missing snapshot is rebuilt", async () => { + await inFixture(async (dir) => { + const paths = pathsIn(dir); const saved = join(dir, "board.json"); - writeFileSync(saved, JSON.stringify(board([row({ effort: "medium" }), row()]))); - writeFileSync(join(dir, "panel-recommendations.sources.json"), JSON.stringify(spec)); + writeFileSync(saved, JSON.stringify(board([row({ effort: "medium", fixed: 22 }), row()]))); + rmSync(paths.snapshot); const out = await silent(() => run(["--fetch", "--board-file", saved, "--today", "2026-11-05"], "2026-11-21", dir), ); assert.equal(out.code, 0, out.text); - assert.equal(read(join(dir, "panel-board-snapshot.json")).fetched, "2026-11-05"); - assert.equal(read(join(dir, "panel-recommendations.json")).entries.length, 1); + assert.equal(read(paths.snapshot).fetched, "2026-11-05"); + assert.equal(read(paths.catalog).entries[0].efforts[0].fixed, 22); + assert.equal((await check(dir)).code, 0); + const before = readFileSync(paths.catalog, "utf8"); + const bad = await silent(() => run(["--fetch", "--today", "2026-02-31"], "2026-11-21", dir)); + assert.equal(bad.code, 2); + assert.equal(readFileSync(paths.catalog, "utf8"), before); }); }); test("an unknown, positional, empty or conflicting argument is an error and writes nothing", async () => { - await inCopy(async (dir) => { - const before = readFileSync(join(dir, "panel-recommendations.json"), "utf8"); + await inFixture(async (dir) => { + const before = readFileSync(pathsIn(dir).catalog, "utf8"); for (const argv of [ ["--unknown"], ["stray"], @@ -316,15 +522,12 @@ test("an unknown, positional, empty or conflicting argument is an error and writ const out = await silent(() => run(argv, "2026-11-21", dir)); assert.equal(out.code, 2, `${argv.join(" ")}: ${out.text}`); } - assert.equal(readFileSync(join(dir, "panel-recommendations.json"), "utf8"), before); + assert.equal(readFileSync(pathsIn(dir).catalog, "utf8"), before); }); }); -test("a fetch goes only to https", async () => { +test("a fetch goes only to https, and a board larger than the cap is cancelled at the cap", async () => { await assert.rejects(() => fetchBoard("http://example.org/b.json"), /only https/); -}); - -test("a board larger than the cap is cancelled at the cap, not read to the end", async () => { let pulls = 0; let cancelled = false; const stream = new ReadableStream({ @@ -344,81 +547,12 @@ test("a board larger than the cap is cancelled at the cap, not read to the end", assert.deepEqual(await fetchBoard("https://example.org/b.json", small), { a: 1 }); }); -test("an own file is refused without a deny file, and a deny entry matches however it is spelled", async () => { - await inCopy(async (dir) => { - const file = join(dir, "incoming.json"); - writeFileSync(file, JSON.stringify(own({}))); - const out = await silent(() => run(["--from-file", file], "2026-11-21", dir)); - assert.equal(out.code, 2); - assert.match(out.text, /needs --deny-file/); - }); - // A name made of letters and hyphens passes the shape checks, so only a deny entry can stop it. - assert.doesNotThrow(() => sanitizeOwn(own({ cohort: "46 cases from internal-tool" }))); - for (const spelled of ["internal tool", "INTERNAL-TOOL", "Internal.Tool", "internaltool"]) { - assert.throws( - () => sanitizeOwn(own({ cohort: `46 cases from ${spelled}` }), ["internal-tool"]), - /must not carry/, - spelled, - ); - } -}); - -test("harness is a short name, not a second free-text field", () => { - assert.throws( - () => sanitizeOwn(own({ harness: "Codex CLI with a long description of the setup used" })), - /own results refused/, - ); - assert.throws(() => sanitizeOwn(own({ checked: "2026-13-45" })), /not a real date/); -}); - -test("the newest current row wins, then the one with more runs; a saving is stated only when it is one", () => { - const snap = reduceBoard( - board([ - row({ effort: "medium", fixed: 10, date: "2026-11-02", cost_usd: 30, wall_min: 50 }), - row({ effort: "medium", fixed: 20, date: "2026-11-01", cost_usd: 5, wall_min: 5 }), - row({ effort: "high", fixed: 40, date: "2026-11-02", n_runs: 2, cost_usd: 10, wall_min: 10 }), - row({ effort: "high", fixed: 41, date: "2026-11-02", n_runs: 5, cost_usd: 10, wall_min: 10 }), - ]), - "2026-11-03", - ); - const [entry] = buildCatalog(spec, snap, { version: 1, results: [] }).entries; - assert.deepEqual( - entry.efforts.map((/** @type {any} */ e) => [e.effort, e.fixed]), - [ - ["medium", 10], - ["high", 41], - ], - ); - // The lower-fixing rung costs more and takes longer, so no "less cost" or "less time" is claimed. - assert.match(entry.rationale, /^high fixed the most \(41 of 105\); medium fixed 31 fewer\.( |$)/); -}); - -test("a gap inside the board's run-to-run spread is not ranked", () => { - const snap = reduceBoard( - board([row({ effort: "medium", fixed: 40 }), row({ effort: "high", fixed: 40.5 })]), - "2026-11-03", - ); - const [entry] = buildCatalog({ ...spec, board: { ...spec.board, noisePoints: 1.5 } }, snap, { - version: 1, - results: [], - }).entries; - assert.match(entry.rationale, /not distinguishable/); -}); - -test("a board figure that is null or boolean is refused, not read as a number", () => { - assert.throws(() => reduceBoard(board([row({ fixed: null })]), "2026-11-03"), /cannot read/); - assert.throws(() => reduceBoard(board([row({ n_runs: true })]), "2026-11-03"), /cannot read/); -}); - test("several outputs are written together or not at all, and nothing else in the folder is touched", async () => { - await inCopy(async (dir) => { + await inFixture(async (dir) => { const a = join(dir, "a.json"); writeFileSync(a, "old a\n"); - // A pre-existing file of the old temporary name, and a symlink at that name, must survive untouched. + // A pre-existing file named like the old temporary name must survive untouched. writeFileSync(`${a}.new`, "keep me\n"); - const other = join(dir, "other.txt"); - writeFileSync(other, "other\n"); - symlinkSync(other, join(dir, "b.json.new")); // The second target is a directory with content, so its rename fails and the first file is restored. const b = join(dir, "b.json"); mkdirSync(b); @@ -431,14 +565,12 @@ test("several outputs are written together or not at all, and nothing else in th ); assert.equal(readFileSync(a, "utf8"), "old a\n"); assert.equal(readFileSync(`${a}.new`, "utf8"), "keep me\n"); - assert.equal(readFileSync(other, "utf8"), "other\n"); assert.deepEqual( - readdirSync(dir).filter((name) => name.startsWith(".refresh")), + readdirSync(dir).filter((n) => n.startsWith(".refresh")), [], ); writeAll([[a, { n: 3 }]]); assert.deepEqual(read(a), { n: 3 }); - assert.equal(readFileSync(`${a}.new`, "utf8"), "keep me\n"); assert.throws( () => writeAll([ @@ -450,271 +582,62 @@ test("several outputs are written together or not at all, and nothing else in th }); }); -test("--check compares the committed bytes: a private extra field or a shadowed duplicate key fails", async () => { - await inCopy(async (dir) => { - const ownFile = join(dir, "panel-recommendations.own.json"); - const good = readFileSync(ownFile, "utf8"); - writeFileSync(ownFile, good.replace('"version": 1,', '"version": 1,\n "project": "acme",')); - const extra = await silent(() => run(["--check"], "2026-11-21", dir)); - assert.equal(extra.code, 1); - assert.match(extra.text, /expected exactly/); - writeFileSync(ownFile, good); - const catalogFile = join(dir, "panel-recommendations.json"); - const catalog = readFileSync(catalogFile, "utf8"); - // A shadowed first value: same parse as the generated catalog, different bytes. - writeFileSync(catalogFile, catalog.replace('"version": 1,', '"version": 1,\n "version": 1,')); - const dup = await silent(() => run(["--check"], "2026-11-21", dir)); - assert.equal(dup.code, 1); - assert.match(dup.text, /duplicate keys/); - writeFileSync(catalogFile, catalog); - assert.equal((await silent(() => run(["--check"], "2026-11-21", dir))).code, 0); - }); -}); - -test("an interruption between publishing sources and the catalog leaves a complete old catalog that --check flags and a plain run repairs", async () => { - await inCopy(async (dir) => { - const before = readFileSync(join(dir, "panel-recommendations.json"), "utf8"); - const baseline = JSON.parse(before).entries.length; - // The own file is already new, the catalog still old: what an interruption after the first rename leaves. - writeFileSync(join(dir, "panel-recommendations.own.json"), serialize(own({ found: 81 }))); - assert.equal(readFileSync(join(dir, "panel-recommendations.json"), "utf8"), before); - assert.ok(baseline > 0); - const flagged = await silent(() => run(["--check"], "2026-11-21", dir)); - assert.equal(flagged.code, 1); - assert.equal((await silent(() => run([], "2026-11-21", dir))).code, 0); - assert.equal((await silent(() => run(["--check"], "2026-11-21", dir))).code, 0); - // The repaired catalog is the old entries plus one for the new result, whatever the baseline was. - assert.equal(read(join(dir, "panel-recommendations.json")).entries.length, baseline + 1); - }); -}); - -test("a second refresh while one holds the lock fails with a retry message; a dead owner's lock is taken over", async () => { - await inCopy(async (dir) => { - const lock = join(dir, ".refresh.lock"); - writeFileSync(lock, `${process.pid}\n`); - const busy = await silent(() => run([], "2026-11-21", dir)); - assert.equal(busy.code, 1); - assert.match(busy.text, /retry/); - writeFileSync(lock, "2147483646\n"); - assert.equal((await silent(() => run([], "2026-11-21", dir))).code, 0); - assert.equal(existsSync(lock), false); - }); -}); - -test("the mode picks the inputs: fetch rebuilds a missing snapshot, an import replaces a denied old file, no own file is empty", async () => { - await inCopy(async (dir) => { - const saved = join(dir, "board.json"); - writeFileSync(saved, JSON.stringify(board([row({ effort: "medium" }), row()]))); - writeFileSync(join(dir, "panel-recommendations.sources.json"), JSON.stringify(spec)); - rmSync(join(dir, "panel-board-snapshot.json")); - rmSync(join(dir, "panel-recommendations.own.json")); - const fetched = await silent(() => - run(["--fetch", "--board-file", saved, "--today", "2026-11-05"], "2026-11-21", dir), - ); - assert.equal(fetched.code, 0, fetched.text); - assert.equal(read(join(dir, "panel-recommendations.json")).entries.length, 1); - // An own file holding a name that is denied now is replaced by a clean import, not an abort. - writeFileSync( - join(dir, "panel-recommendations.own.json"), - serialize(own({ cohort: "46 cases of widgetco" })), - ); - const incoming = join(dir, "incoming.json"); - writeFileSync(incoming, JSON.stringify(own({ model: "model-a", harness: "CLI A" }))); - const deny = join(dir, "deny.txt"); - writeFileSync(deny, "widgetco\n"); - const replaced = await silent(() => - run(["--from-file", incoming, "--deny-file", deny], "2026-11-21", dir), - ); - assert.equal(replaced.code, 0, replaced.text); - assert.equal(read(join(dir, "panel-recommendations.own.json")).results[0].cohort, good.cohort); - // A checkout without the optional own file passes the offline check too. - rmSync(join(dir, "panel-recommendations.own.json")); - assert.equal((await silent(() => run([], "2026-11-21", dir))).code, 0); - assert.equal((await silent(() => run(["--check"], "2026-11-21", dir))).code, 0); - }); -}); - -test("a deny entry covers the published id, the effort and the assembled text", async () => { - assert.throws(() => sanitizeOwn(own({}), ["own-astra-62-medium-heldout"]), /published id/); - assert.throws(() => sanitizeOwn(own({}), ["medium"]), /published id or effort/); - await inCopy(async (dir) => { - const incoming = join(dir, "incoming.json"); - writeFileSync(incoming, JSON.stringify(own({}))); - const deny = join(dir, "deny.txt"); - // Spans the cohort wording and a generated phrase: only the assembled entry holds it whole. - writeFileSync(deny, "known defects across 46\n"); +test("a refresh reclaims only its own abandoned transactions", async () => { + await inFixture(async (dir) => { + // An abandoned transaction: the tool's name, its marker, and its new- files only. + const abandoned = join(dir, ".refresh-abc123"); + mkdirSync(abandoned); + writeFileSync(join(abandoned, ".transaction"), "refresh-recommendations transaction\n"); + writeFileSync(join(abandoned, "new-0"), "x"); + // Look-alikes: a directory with the tool's name shape but no marker, one with extra content, a plain + // directory and a file with the prefix. None is the tool's, so every mode leaves them. + const unmarked = join(dir, ".refresh-abc124"); + mkdirSync(unmarked); + writeFileSync(join(unmarked, "keep"), "mine"); + const extra = join(dir, ".refresh-abc125"); + mkdirSync(extra); + writeFileSync(join(extra, ".transaction"), "refresh-recommendations transaction\n"); + writeFileSync(join(extra, "notes.txt"), "mine"); + const notes = join(dir, ".refresh-notes"); + mkdirSync(notes); + writeFileSync(join(notes, "a"), "mine"); + // An import file named like the prefix is read, and survives. + const input = join(dir, ".refresh-input.json"); + writeFileSync(input, JSON.stringify(own())); + writeFileSync(join(dir, "deny.txt"), "unrelated-name\n"); const out = await silent(() => - run(["--from-file", incoming, "--deny-file", deny], "2026-11-21", dir), + run(["--from-file", input, "--deny-file", join(dir, "deny.txt")], "2026-11-21", dir), ); - assert.equal(out.code, 1); - assert.match(out.text, /must not carry/); - }); -}); - -test("every effort inside the spread of the leader is named, and an exact tie names both", () => { - const rows = [ - row({ effort: "medium", fixed: 50.3, cost_usd: 5, wall_min: 10 }), - row({ effort: "high", fixed: 59.6, cost_usd: 8, wall_min: 48.5 }), - row({ effort: "xhigh", fixed: 60.2, cost_usd: 10, wall_min: 84 }), - ]; - const withSpread = { ...spec, board: { ...spec.board, noisePoints: 1.5 } }; - const three = { - ...spec, - entries: [{ ...spec.entries[0], efforts: ["medium", "high", "xhigh"] }], - }; - const [entry] = buildCatalog( - { ...three, board: withSpread.board }, - reduceBoard(board(rows), "2026-11-03"), - { - version: 1, - results: [], - }, - ).entries; - assert.match( - entry.rationale, - /^xhigh fixed the most \(60\.2 of 105\); high \(59\.6\) is within the board's run-to-run spread of it for 20% less cost and 42% less time; medium fixed 9\.9 fewer for 50% less cost and 88% less time\./, - ); - const tie = reduceBoard( - board([row({ effort: "medium", fixed: 40 }), row({ effort: "high", fixed: 40 })]), - "2026-11-03", - ); - const [tied] = buildCatalog(spec, tie, { version: 1, results: [] }).entries; - assert.match(tied.rationale, /medium fixed 40 and high 40 of 105/); -}); - -test("an impossible calendar date is refused wherever a fetch date enters", async () => { - assert.throws(() => reduceBoard(board([row()]), "2026-02-31"), /real YYYY-MM-DD/); - assert.doesNotThrow(() => reduceBoard(board([row()]), "2028-02-29")); - await inCopy(async (dir) => { - const before = readFileSync(join(dir, "panel-recommendations.json"), "utf8"); - const out = await silent(() => run(["--fetch", "--today", "2026-02-31"], "2026-11-21", dir)); - assert.equal(out.code, 2); - assert.equal(readFileSync(join(dir, "panel-recommendations.json"), "utf8"), before); - }); -}); - -test("a seed, a host or a key in any identifier or description is refused; ordinary words are not", () => { - const bad = [ - { cohort: "46 cases, seed JBSWY3DPEHPK3PXP" }, - { cohort: "46 cases, seed JBSWYDPEHPKPXPAB" }, - { cohort: "46 cases, seed jbswy3dpehpk3pxp" }, - { cohort: "46 cases from bench.internal.example" }, - { model: "bench.internal.example" }, - { harness: "bench.internal.example" }, - { id: "jbswy3dpehpk3pxp" }, - { id: "key-0123456789abcdef0123" }, - ]; - for (const over of bad) { - assert.throws(() => sanitizeOwn(own(over)), /own results refused/, JSON.stringify(over)); - } - // "skipping" is a word, not a key; a decimal and a percent are numbers. - assert.doesNotThrow(() => - sanitizeOwn(own({ cohort: "46 cases, skipping 2.5% of files (blind)" })), - ); - assert.equal(plainWords("skipping the sk-proj1234567890abcdef"), false); - assert.equal(looksSecret("skipping ahead"), false); - // A model or harness the source spec does not name is refused even when it is plain. - const vocabulary = { models: ["gpt-6.2-astra"], harnesses: ["Codex CLI"] }; - assert.doesNotThrow(() => sanitizeOwn(own({}), [], vocabulary)); - assert.throws(() => sanitizeOwn(own({ model: "internal-model" }), [], vocabulary), /spec names/); - assert.throws(() => sanitizeOwn(own({ harness: "Internal Tool" }), [], vocabulary), /spec names/); -}); - -test("measurements outside their domain are refused, fractional means and durations are not", () => { - const bad = (/** @type {any} */ over) => - assert.throws( - () => reduceBoard(board([row(over)]), "2026-11-03"), - /snapshot|cannot read/, - JSON.stringify(over), - ); - bad({ cost_usd: -5 }); - bad({ wall_min: -1 }); - bad({ n_runs: 0 }); - bad({ n_runs: 2.5 }); - bad({ fixed: 106 }); - bad({ fixed: -1 }); - assert.doesNotThrow(() => - reduceBoard(board([row({ fixed: 40.25, wall_min: 12.5, n_runs: 3 })]), "2026-11-03"), - ); - for (const over of [ - { found: 0.5, of: 2 }, - { of: 2.5, found: 1 }, - ]) { - assert.throws(() => sanitizeOwn(own(over)), /an integer/); - } -}); - -test("the snapshot has one schema and one byte layout: an unknown field, a bad date or a changed row order fails offline", async () => { - const committed = readFileSync(real.snapshot, "utf8"); - // Reducing the committed measurements again gives the same bytes. - assert.equal(serialize(canonicalSnapshot(JSON.parse(committed))), committed); - await inCopy(async (dir) => { - const file = join(dir, "panel-board-snapshot.json"); - const snap = JSON.parse(committed); - /** @type {Array<[string, (s: any) => void]>} */ - const edits = [ - ["an extra field", (x) => void (x.project = "acme")], - ["an impossible date", (x) => void (x.fetched = "2026-02-31")], - ["a row reordered", (x) => void x.rows.reverse()], - ["a row with an extra field", (x) => void (x.rows[0].note = "x")], - ]; - for (const [name, edit] of edits) { - const edited = structuredClone(snap); - edit(edited); - writeFileSync(file, serialize(edited)); - const out = await silent(() => run(["--check"], "2026-11-21", dir)); - assert.equal(out.code, 1, `${name}: ${out.text}`); + assert.equal(out.code, 0, out.text); + assert.equal(existsSync(abandoned), false); + for (const kept of [ + join(unmarked, "keep"), + join(extra, "notes.txt"), + join(notes, "a"), + input, + ]) { + assert.equal(existsSync(kept), true, kept); + } + for (const argv of [[], ["--check"]]) { + await silent(() => run(argv, "2026-11-21", dir)); + assert.equal(existsSync(join(notes, "a")), true); } - writeFileSync(file, committed); - assert.equal((await silent(() => run(["--check"], "2026-11-21", dir))).code, 0); - }); -}); - -test("the repair --check prints fixes reformatted inputs: a plain run rewrites each input in its canonical form", async () => { - await inCopy(async (dir) => { - const snapshot = join(dir, "panel-board-snapshot.json"); - const ownFile = join(dir, "panel-recommendations.own.json"); - const canonicalSnap = readFileSync(snapshot, "utf8"); - writeFileSync(snapshot, JSON.stringify(JSON.parse(canonicalSnap))); - writeFileSync(ownFile, JSON.stringify({ version: 1, results: [] })); - const flagged = await silent(() => run(["--check"], "2026-11-21", dir)); - assert.equal(flagged.code, 1); - assert.match(flagged.text, /snapshot, own results/); - assert.equal((await silent(() => run([], "2026-11-21", dir))).code, 0); - assert.equal((await silent(() => run(["--check"], "2026-11-21", dir))).code, 0); - assert.equal(readFileSync(snapshot, "utf8"), canonicalSnap); - }); -}); - -test("a deny entry matches only inside one published string, never across neighbouring fields", async () => { - await inCopy(async (dir) => { - const incoming = join(dir, "incoming.json"); - writeFileSync(incoming, JSON.stringify(own({ id: "widget" }))); - const deny = join(dir, "deny.txt"); - // "widget-kind" spans the id's end and the next key in the serialized entry, but no value holds it. - writeFileSync(deny, "widget-kind\n"); - const ok = await silent(() => - run(["--from-file", incoming, "--deny-file", deny], "2026-11-21", dir), - ); - assert.equal(ok.code, 0, ok.text); - writeFileSync(deny, "known defects across 46\n"); - const refused = await silent(() => - run(["--from-file", incoming, "--deny-file", deny], "2026-11-21", dir), - ); - assert.equal(refused.code, 1); }); }); -test("the refresh lock: an unreadable owner is busy, not stolen; a vanished lock is retried; a stale lock goes to exactly one racer", async () => { - await inCopy(async (dir) => { +test("the refresh lock never removes a lock it does not own", async () => { + await inFixture(async (dir) => { const lock = join(dir, ".refresh.lock"); writeFileSync(lock, ""); await assert.rejects(() => withLock(dir, async () => 1), /retry/); assert.equal(readFileSync(lock, "utf8"), ""); writeFileSync(lock, "not a pid\n"); await assert.rejects(() => withLock(dir, async () => 1), /cannot be read/); - // The holder finishes between the failed link and the read: the waiter acquires on retry. + // A live owner is busy. writeFileSync(lock, `${process.pid}\n`); + await assert.rejects(() => withLock(dir, async () => 1), /retry/); + assert.equal(readFileSync(lock, "utf8"), `${process.pid}\n`); + // The holder finishes between the failed claim and the read: the waiter acquires on retry. assert.equal( await withLock(dir, async () => "ran", { afterContended: () => rmSync(lock, { force: true }), @@ -722,48 +645,70 @@ test("the refresh lock: an unreadable owner is busy, not stolen; a vanished lock "ran", ); assert.equal(existsSync(lock), false); - // Two refreshes race on a dead owner's lock: one runs, the other is told to retry; nothing is left behind. + // A lock is released only when it is still the file this call linked. + await withLock(dir, async () => { + rmSync(lock, { force: true }); + writeFileSync(lock, "99999\n"); + }); + assert.equal(readFileSync(lock, "utf8"), "99999\n"); + }); +}); + +test("a stale observer paused after its read cannot remove a successor's lock: at most one holder at a time", async () => { + await inFixture(async (dir) => { + const lock = join(dir, ".refresh.lock"); writeFileSync(lock, "2147483646\n"); - const results = await Promise.allSettled([ - withLock(dir, async () => "a"), - withLock(dir, async () => "b"), - ]); - assert.deepEqual(results.map((r) => r.status).toSorted(), ["fulfilled", "rejected"]); + let holders = 0; + let most = 0; + /** @type {() => void} */ + let releaseObserver = () => {}; + const observerGate = new Promise((resolveGate) => { + releaseObserver = /** @type {() => void} */ (resolveGate); + }); + /** @type {() => void} */ + let releaseHolder = () => {}; + const holderGate = new Promise((resolveGate) => { + releaseHolder = /** @type {() => void} */ (resolveGate); + }); + const hold = async () => { + holders++; + most = Math.max(most, holders); + await holderGate; + holders--; + return "ran"; + }; + // The observer reads the dead owner, then pauses. + const observer = withLock(dir, hold, { afterRead: () => observerGate }); + await new Promise((r) => setTimeout(r, 20)); + // A successor takes the stale lock over and holds it; a third contender finds a live lock. + const successor = withLock(dir, hold); + await new Promise((r) => setTimeout(r, 20)); + const third = withLock(dir, hold); + await assert.rejects(third, /retry/); + // The observer resumes: it must find the successor's live lock and leave it alone. + releaseObserver(); + await assert.rejects(observer, /retry/); + assert.equal(existsSync(lock), true); + releaseHolder(); + assert.equal(await successor, "ran"); + assert.equal(most, 1); assert.equal(existsSync(lock), false); assert.deepEqual( readdirSync(dir).filter((n) => n.startsWith(".refresh")), [], ); - // A lock is removed only by the process whose file it still is. - await withLock(dir, async () => { - rmSync(lock, { force: true }); - writeFileSync(lock, "99999\n"); - }); - assert.equal(readFileSync(lock, "utf8"), "99999\n"); }); }); -test("work files of an interrupted refresh are reclaimed, and no before image is staged in the skill folder", async () => { - await inCopy(async (dir) => { - const abandoned = join(dir, ".refresh-abandoned"); - mkdirSync(abandoned); - writeFileSync(join(abandoned, "old-0"), "a private name that a replacement removed\n"); +test("a second refresh while one holds the lock fails with a retry message", async () => { + await inFixture(async (dir) => { + const lock = join(dir, ".refresh.lock"); + writeFileSync(lock, `${process.pid}\n`); + const busy = await silent(() => run([], "2026-11-21", dir)); + assert.equal(busy.code, 1); + assert.match(busy.text, /retry/); + writeFileSync(lock, "2147483646\n"); assert.equal((await silent(() => run([], "2026-11-21", dir))).code, 0); - assert.equal(existsSync(abandoned), false); - // The before image of a replaced file is kept outside the folder while the renames run. - const seen = /** @type {string[]} */ ([]); - const a = join(dir, "a.json"); - writeFileSync(a, "old a\n"); - const b = join(dir, "b.json"); - mkdirSync(b); - writeFileSync(join(b, "x"), "x"); - assert.throws(() => - writeAll([ - [a, { n: 1 }], - [b, { n: 2 }], - ]), - ); - seen.push(...readdirSync(dir).filter((n) => n.startsWith(".refresh"))); - assert.deepEqual(seen, []); + assert.equal(existsSync(lock), false); }); }); From 575215fbeb8961484024a41d72045e4bbc61ba3f Mon Sep 17 00:00:00 2001 From: bompus Date: Sat, 21 Nov 2026 13:28:40 -0700 Subject: [PATCH 5/8] Panel recommendations generator round 4: deny file screens the snapshot and whole catalog, obsolete own file refused, own facts recovered by any marker, lock ownership read from content (Windows inode numbers are not reliable) --- .../references/panel-recommendations.md | 14 +-- .../scripts/refresh-recommendations.mjs | 69 +++++++++++---- .../test/refresh-recommendations.test.mjs | 86 +++++++++++++++++++ 3 files changed, 145 insertions(+), 24 deletions(-) diff --git a/skills/hr-code-review/references/panel-recommendations.md b/skills/hr-code-review/references/panel-recommendations.md index a758fb85..57f4f91f 100644 --- a/skills/hr-code-review/references/panel-recommendations.md +++ b/skills/hr-code-review/references/panel-recommendations.md @@ -40,13 +40,13 @@ why it is suggested. A value that was not recorded is the string `unknown`. ## Updating The catalog is generated, so do not edit [`panel-recommendations.json`](panel-recommendations.json) -by hand. `scripts/refresh-recommendations.mjs` builds it from three files in this -folder: the source spec (`panel-recommendations.sources.json`: which board rows each -entry uses, plus the route, limits and advice that no board states), the board -snapshot (`panel-board-snapshot.json`: the board's current rows, fetched by -`--fetch`) and the own results (`panel-recommendations.own.json`). `--check` runs -offline, with no clock and no network, and fails when the catalog is not what those -files generate. +by hand. `scripts/refresh-recommendations.mjs` builds it from the source spec +(`panel-recommendations.sources.json`: which board rows each entry uses, plus the route, +limits and advice that no board states), the board snapshot (`panel-board-snapshot.json`: +the board's current rows, fetched by `--fetch`) and the own results, which live only in +the catalog's own entries. `--check` runs offline, with no clock and no network, and +fails when the catalog is not what those inputs generate. A raw results file is never +kept in this folder: the script refuses a leftover `panel-recommendations.own.json`. Check an entry again when a model, route, price or benchmark correction changes the choice, and when preparing a release. Only changed entries need new evidence. An diff --git a/skills/hr-code-review/scripts/refresh-recommendations.mjs b/skills/hr-code-review/scripts/refresh-recommendations.mjs index 62189d5b..6faba75c 100644 --- a/skills/hr-code-review/scripts/refresh-recommendations.mjs +++ b/skills/hr-code-review/scripts/refresh-recommendations.mjs @@ -34,6 +34,8 @@ const skill = resolve(dirname(fileURLToPath(import.meta.url)), ".."); const refs = join(skill, "references"); /** @param {string} dir the references folder */ export const pathsIn = (dir) => ({ + // Raw own results are never kept in the skill folder; a file here is a leftover of an earlier layout. + obsoleteOwn: join(dir, "panel-recommendations.own.json"), spec: join(dir, "panel-recommendations.sources.json"), snapshot: join(dir, "panel-board-snapshot.json"), catalog: join(dir, "panel-recommendations.json"), @@ -150,7 +152,10 @@ export async function withLock(dir, fn, hooks = {}) { const lock = join(dir, ".refresh.lock"); const takeover = join(dir, ".refresh.takeover"); const mine = join(dir, `.refresh.lock.${process.pid}.${Math.random().toString(36).slice(2)}`); - writeFileSync(mine, `${process.pid}\n`, { flag: "wx" }); + // The file's content is the owner's pid and a token only this call knows, so ownership is read from content + // (an inode number is not reliable on every filesystem). + const content = `${process.pid} ${Math.random().toString(36).slice(2)}\n`; + writeFileSync(mine, content, { flag: "wx" }); const busy = (/** @type {string} */ why) => new Error(`another refresh holds ${lock} (${why}); retry when it has finished`); /** @param {string} path */ @@ -168,7 +173,7 @@ export async function withLock(dir, fn, hooks = {}) { /** @param {string} path the owner's pid, "gone" when the file vanished, "unreadable" otherwise */ const ownerOf = (path) => { try { - const owner = Number(readFileSync(path, "utf8").trim()); + const owner = Number(readFileSync(path, "utf8").trim().split(/\s+/)[0]); return Number.isInteger(owner) && owner > 0 ? owner : "unreadable"; } catch (error) { if (/** @type {any} */ (error).code === "ENOENT") { @@ -177,10 +182,10 @@ export async function withLock(dir, fn, hooks = {}) { throw error; } }; - /** @param {string} path remove a claim only when it is still this call's file */ + /** @param {string} path remove a claim only when it still holds this call's content */ const release = (path) => { try { - if (statSync(path).ino === statSync(mine).ino) { + if (readFileSync(path, "utf8") === content) { rmSync(path, { force: true }); } } catch { @@ -745,6 +750,11 @@ export async function run(argv, today = new Date().toISOString().slice(0, 10), d * @param {string} today */ async function refresh(paths, values, today) { + if (existsSync(paths.obsoleteOwn)) { + throw new Error( + `${paths.obsoleteOwn} is an obsolete source: own results live only in the catalog; delete the file (keep the raw results outside the skill folder)`, + ); + } const spec = readJson(paths.spec); const deny = readDeny(values["deny-file"]); const vocabulary = { @@ -769,24 +779,20 @@ async function refresh(paths, values, today) { const own = sanitizeOwn( values["from-file"] !== undefined ? readJson(resolve(values["from-file"])) - : { - version: 1, - results: (committed?.entries ?? []) - .filter((/** @type {any} */ e) => e.kind === "own-evaluation") - .map((/** @type {any} */ e) => e.facts), - }, + : { version: 1, results: ownFactsOf(committed) }, vocabulary, ); const catalog = buildCatalog(spec, snapshot, own); - // Every string published for an own result is screened as published: each value on its own, never joined - // with its neighbours. + // Every string of every file this tool publishes, the board snapshot and the whole catalog included, is + // screened as published: each value on its own, never joined with its neighbours. const denied = deny.map(squash).filter(Boolean); - for (const entry of catalog.entries.filter( - (/** @type {any} */ e) => e.kind === "own-evaluation", - )) { - for (const text of stringValues(entry)) { + for (const [name, published] of [ + ["snapshot", snapshot], + ["catalog", catalog], + ]) { + for (const text of stringValues(published)) { if (denied.some((word) => squash(text).includes(word))) { - throw new Error(`catalog entry ${entry.id} contains a name this repository must not carry`); + throw new Error(`the ${name} would publish a name this repository must not carry`); } } } @@ -830,6 +836,35 @@ async function refresh(paths, values, today) { return 0; } +/** + * The own facts a committed catalog carries. An entry counts as an own entry by any of its markers (its kind, an + * `own-` id, or its facts), so damage to one derived field cannot make a plain run drop the measurements: an + * entry with facts keeps them whatever its kind says, and one that looks like an own entry but has no facts + * stops the run without changing anything. + * @param {any} committed + * @returns {any[]} + */ +function ownFactsOf(committed) { + /** @type {any[]} */ + const facts = []; + for (const entry of committed?.entries ?? []) { + const looksOwn = + entry?.facts !== undefined || + entry?.kind === "own-evaluation" || + String(entry?.id).startsWith("own-"); + if (!looksOwn) { + continue; + } + if (entry.facts === null || typeof entry.facts !== "object") { + throw new Error( + `catalog entry ${entry?.id} looks like an own result but carries no facts: restore it from version control or import the results again`, + ); + } + facts.push(entry.facts); + } + return facts; +} + /** * @param {unknown} value every string value in a JSON value, not its keys * @returns {string[]} diff --git a/skills/hr-code-review/test/refresh-recommendations.test.mjs b/skills/hr-code-review/test/refresh-recommendations.test.mjs index 9a025c4d..585b32e0 100644 --- a/skills/hr-code-review/test/refresh-recommendations.test.mjs +++ b/skills/hr-code-review/test/refresh-recommendations.test.mjs @@ -712,3 +712,89 @@ test("a second refresh while one holds the lock fails with a retry message", asy assert.equal(existsSync(lock), false); }); }); + +test("a deny file screens every published string, the snapshot's unused rows included", async () => { + await inFixture(async (dir) => { + const paths = pathsIn(dir); + const deny = join(dir, "deny.txt"); + writeFileSync(deny, "internal-harness\n"); + const saved = join(dir, "board.json"); + // A row no recommendation uses still lands in the published snapshot. + writeFileSync( + saved, + JSON.stringify( + board([ + row({ effort: "medium", fixed: 22 }), + row(), + row({ model: "Other", harness: "Internal Harness" }), + ]), + ), + ); + const snapshotBefore = readFileSync(paths.snapshot, "utf8"); + const catalogBefore = readFileSync(paths.catalog, "utf8"); + const refused = await silent(() => + run( + ["--fetch", "--board-file", saved, "--deny-file", deny, "--today", "2026-11-05"], + "2026-11-21", + dir, + ), + ); + assert.equal(refused.code, 1); + assert.match(refused.text, /snapshot would publish a name/); + assert.equal(readFileSync(paths.snapshot, "utf8"), snapshotBefore); + assert.equal(readFileSync(paths.catalog, "utf8"), catalogBefore); + // Without the deny file the same board is accepted; the offline check with it then fails. + const accepted = await silent(() => + run(["--fetch", "--board-file", saved, "--today", "2026-11-05"], "2026-11-21", dir), + ); + assert.equal(accepted.code, 0, accepted.text); + const checked = await silent(() => run(["--check", "--deny-file", deny], "2026-11-21", dir)); + assert.equal(checked.code, 1); + assert.match(checked.text, /must not carry/); + }); +}); + +test("a raw own-results file in the skill folder is an obsolete source: every mode refuses it", async () => { + await inFixture(async (dir) => { + writeFileSync( + join(dir, "panel-recommendations.own.json"), + serialize({ version: 1, results: [], project: "acme" }), + ); + for (const argv of [[], ["--check"]]) { + const out = await silent(() => run(argv, "2026-11-21", dir)); + assert.equal(out.code, 1); + assert.match(out.text, /obsolete source/); + } + rmSync(join(dir, "panel-recommendations.own.json")); + assert.equal((await check(dir)).code, 0); + }); +}); + +test("damage to an own entry's derived fields never drops its facts", async () => { + await inFixture(async (dir) => { + const file = pathsIn(dir).catalog; + await importOwn(dir, own()); + const canonical = readFileSync(file, "utf8"); + // The discriminator is changed or removed: the facts are intact, so a plain run restores the entry. + for (const edit of [ + (/** @type {any} */ e) => void (e.kind = "board"), + (/** @type {any} */ e) => void delete e.kind, + ]) { + const catalog = JSON.parse(canonical); + edit(catalog.entries[1]); + writeFileSync(file, serialize(catalog)); + assert.equal((await check(dir)).code, 1); + assert.equal((await silent(() => run([], "2026-11-21", dir))).code, 0); + assert.equal(readFileSync(file, "utf8"), canonical); + } + // Facts removed: nothing to recover from, so the run stops and the catalog is left as it was. + const catalog = JSON.parse(canonical); + delete catalog.entries[1].facts; + writeFileSync(file, serialize(catalog)); + const damaged = readFileSync(file, "utf8"); + const out = await silent(() => run([], "2026-11-21", dir)); + assert.equal(out.code, 1); + assert.match(out.text, /carries no facts/); + assert.equal(readFileSync(file, "utf8"), damaged); + }); +}); From 717e53298b7abd6c913f784cbfec69956545ac26 Mon Sep 17 00:00:00 2001 From: bompus Date: Sat, 21 Nov 2026 13:48:29 -0700 Subject: [PATCH 6/8] Panel recommendations generator round 5: private inputs refused inside the skill folder (symlinks included), repeated JSON keys refused before any own fact is read, deny check covers the spec and Unicode names, script split under the line limit --- .../references/panel-recommendations.md | 6 +- .../hr-code-review/scripts/refresh-files.mjs | 300 ++++++++++++++++++ .../scripts/refresh-recommendations.mjs | 249 ++++----------- .../test/refresh-recommendations.test.mjs | 188 ++++++++++- 4 files changed, 530 insertions(+), 213 deletions(-) create mode 100644 skills/hr-code-review/scripts/refresh-files.mjs diff --git a/skills/hr-code-review/references/panel-recommendations.md b/skills/hr-code-review/references/panel-recommendations.md index 57f4f91f..115435b2 100644 --- a/skills/hr-code-review/references/panel-recommendations.md +++ b/skills/hr-code-review/references/panel-recommendations.md @@ -68,8 +68,10 @@ exactly these fields: a `model` and `harness` the source spec already lists, an `caseSet` (`held-out`, `development` or `mixed`), `judging` (`blind-second-model`, `one-model`, `two-models` or `person`) and a `checked` date. The cohort wording and the entry id are built from those facts, so no typed text reaches a public file. The -import also needs a deny file of private names and refuses any published string that -holds one. +import also needs a deny file of private names, and the script refuses it and the results +file when either sits inside the skill folder (the installer copies that folder). +Any published string that holds a denied name, in the spec, snapshot or catalog, fails +the run. A plain run of the script regenerates the catalog and writes the snapshot in its one canonical layout, which is what `--check` compares. diff --git a/skills/hr-code-review/scripts/refresh-files.mjs b/skills/hr-code-review/scripts/refresh-files.mjs new file mode 100644 index 00000000..bd624f67 --- /dev/null +++ b/skills/hr-code-review/scripts/refresh-files.mjs @@ -0,0 +1,300 @@ +// 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 { + existsSync, + linkSync, + mkdtempSync, + readdirSync, + readFileSync, + renameSync, + rmSync, + statSync, + writeFileSync, +} from "node:fs"; +import { tmpdir } from "node:os"; +import { dirname, join } 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`; + +// A work directory of this tool is `.refresh-` holding this marker file and `new-` files only; +// 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 */ +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()) { + continue; + } + const inside = readdirSync(path); + if ( + inside.includes(TRANSACTION_MARKER) && + readFileSync(join(path, TRANSACTION_MARKER), "utf8") === TRANSACTION_TEXT && + inside.every((n) => n === TRANSACTION_MARKER || /^new-\d+$/.test(n)) + ) { + rmSync(path, { recursive: true, force: true }); + } + } +} + +/** + * 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 + * --check reports the sources that are ahead of it until a plain run regenerates it. + * @param {Array<[string, unknown]>} outputs + */ +export function writeAll(outputs) { + 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-")); + try { + const staged = outputs.map(([path, value], i) => { + const file = join(stage, `new-${i}`); + writeFileSync(file, serialize(value), { flag: "wx" }); + /** @type {string | undefined} */ + let back; + if (existsSync(path)) { + back = join(backups, `old-${i}`); + writeFileSync(back, readFileSync(path), { flag: "wx" }); + } + return { path, file, back }; + }); + const done = []; + try { + for (const item of staged) { + renameSync(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)); + } + } + throw error; + } + } finally { + rmSync(stage, { recursive: true, force: true }); + rmSync(backups, { recursive: true, force: true }); + } +} + +/** + * Run `fn` holding the folder's refresh lock, so two refreshes cannot interleave their read-build-write. + * A lock is a hard link to a file that already holds the owner's pid, so it is never seen empty. A refresh that + * finds a live or unreadable owner fails with a retry message and removes nothing. A dead owner's lock is removed + * only by the one process that holds the recovery lock (`.refresh.takeover`, claimed the same way), which reads + * the owner again under it: the lock it removes is the dead owner's, because nobody else removes locks and nobody + * can link a new one while it exists. A lock is released only by the process whose file it still is. + * @template T + * @param {string} dir + * @param {() => Promise} fn + * @param {{ afterContended?: () => void | Promise, afterRead?: () => void | Promise }} [hooks] + * test seams: after a failed claim, and after the stale owner was read + */ +export async function withLock(dir, fn, hooks = {}) { + const lock = join(dir, ".refresh.lock"); + const takeover = join(dir, ".refresh.takeover"); + const mine = join(dir, `.refresh.lock.${process.pid}.${Math.random().toString(36).slice(2)}`); + // The file's content is the owner's pid and a token only this call knows, so ownership is read from content + // (an inode number is not reliable on every filesystem). + const content = `${process.pid} ${Math.random().toString(36).slice(2)}\n`; + writeFileSync(mine, content, { flag: "wx" }); + const busy = (/** @type {string} */ why) => + new Error(`another refresh holds ${lock} (${why}); retry when it has finished`); + /** @param {string} path */ + const claim = (path) => { + try { + linkSync(mine, path); + return true; + } catch (error) { + if (/** @type {any} */ (error).code === "EEXIST") { + return false; + } + throw error; + } + }; + /** @param {string} path the owner's pid, "gone" when the file vanished, "unreadable" otherwise */ + const ownerOf = (path) => { + try { + const owner = Number(readFileSync(path, "utf8").trim().split(/\s+/)[0]); + return Number.isInteger(owner) && owner > 0 ? owner : "unreadable"; + } catch (error) { + if (/** @type {any} */ (error).code === "ENOENT") { + return "gone"; + } + throw error; + } + }; + /** @param {string} path remove a claim only when it still holds this call's content */ + const release = (path) => { + try { + if (readFileSync(path, "utf8") === content) { + rmSync(path, { force: true }); + } + } catch { + // no claim, or not readable: nothing of this call's to remove + } + }; + try { + for (let attempt = 0; !claim(lock); attempt++) { + await hooks.afterContended?.(); + const owner = ownerOf(lock); + if (owner === "gone" && attempt < 5) { + continue; // the holder finished between the failed claim and the read + } + 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}`); + } + 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) { + rmSync(lock, { force: true }); + } + } finally { + release(takeover); + } + } + reclaimAbandoned(dir); + return await fn(); + } finally { + release(lock); + rmSync(mine, { force: true }); + } +} + +/** + * JSON.parse that refuses a repeated key in any object. The built-in parser keeps the last value of a repeated + * key and drops the rest, so a merge that leaves two `entries` or two `results` would lose data without a trace + * before anything is checked. + * @param {string} text + * @param {string} [what] named in the error + * @returns {any} + */ +export function parseStrict(text, what = "JSON") { + let i = 0; + /** @param {string} why @returns {never} */ + const fail = (why) => { + throw new Error(`${what}: ${why} at offset ${i}`); + }; + const space = () => { + while (i < text.length && " \t\n\r".includes(text.charAt(i))) { + i++; + } + }; + const string = () => { + const start = i; + i++; + while (i < text.length && text.charAt(i) !== '"') { + i += text.charAt(i) === "\\" ? 2 : 1; + } + if (i >= text.length) { + fail("unterminated string"); + } + i++; + return JSON.parse(text.slice(start, i)); + }; + /** @returns {any} */ + const value = () => { + space(); + const c = text.charAt(i); + if (c === "{") { + i++; + /** @type {Record} */ + const object = Object.create(null); + space(); + if (text.charAt(i) === "}") { + i++; + return object; + } + for (;;) { + space(); + if (text.charAt(i) !== '"') { + fail("expected a key"); + } + const key = string(); + if (key in object) { + fail(`repeated key ${JSON.stringify(key)}`); + } + space(); + if (text.charAt(i) !== ":") { + fail("expected :"); + } + i++; + object[key] = value(); + space(); + if (text.charAt(i) === ",") { + i++; + } else if (text.charAt(i) === "}") { + i++; + return object; + } else { + fail("expected , or }"); + } + } + } + if (c === "[") { + i++; + /** @type {any[]} */ + const list = []; + space(); + if (text.charAt(i) === "]") { + i++; + return list; + } + for (;;) { + list.push(value()); + space(); + if (text.charAt(i) === ",") { + i++; + } else if (text.charAt(i) === "]") { + i++; + return list; + } else { + fail("expected , or ]"); + } + } + } + if (c === '"') { + return string(); + } + const literal = /true|false|null|-?\d+(?:\.\d+)?(?:[eE][+-]?\d+)?/y; + literal.lastIndex = i; + const match = literal.exec(text); + if (match === null) { + throw new Error(`${what}: unexpected character at offset ${i}`); + } + i += match[0].length; + return JSON.parse(match[0]); + }; + const result = value(); + space(); + if (i !== text.length) { + fail("trailing text"); + } + return result; +} diff --git a/skills/hr-code-review/scripts/refresh-recommendations.mjs b/skills/hr-code-review/scripts/refresh-recommendations.mjs index 6faba75c..a474692f 100644 --- a/skills/hr-code-review/scripts/refresh-recommendations.mjs +++ b/skills/hr-code-review/scripts/refresh-recommendations.mjs @@ -14,21 +14,13 @@ // committed files generate; no clock, no network // // Any other argument, a conflicting pair of modes or an empty value is an error (exit 2). -import { - existsSync, - linkSync, - mkdtempSync, - readdirSync, - readFileSync, - renameSync, - rmSync, - statSync, - writeFileSync, -} from "node:fs"; -import { tmpdir } from "node:os"; +import { existsSync, readFileSync, realpathSync } from "node:fs"; 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"; + +export { parseStrict, serialize, withLock, writeAll }; const skill = resolve(dirname(fileURLToPath(import.meta.url)), ".."); const refs = join(skill, "references"); @@ -56,183 +48,14 @@ const EFFORTS = ["none", "minimal", "low", "medium", "high", "xhigh", "max", "ul const MAX_BOARD_BYTES = 20 * 1024 * 1024; /** @param {string} path */ -const readJson = (path) => JSON.parse(readFileSync(path, "utf8")); - -/** 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`; - -// A work directory of this tool is `.refresh-` holding this marker file and `new-` files only; -// 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 */ -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()) { - continue; - } - const inside = readdirSync(path); - if ( - inside.includes(TRANSACTION_MARKER) && - readFileSync(join(path, TRANSACTION_MARKER), "utf8") === TRANSACTION_TEXT && - inside.every((n) => n === TRANSACTION_MARKER || /^new-\d+$/.test(n)) - ) { - rmSync(path, { recursive: true, force: true }); - } - } -} - -/** - * 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 - * --check reports the sources that are ahead of it until a plain run regenerates it. - * @param {Array<[string, unknown]>} outputs - */ -export function writeAll(outputs) { - 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-")); - try { - const staged = outputs.map(([path, value], i) => { - const file = join(stage, `new-${i}`); - writeFileSync(file, serialize(value), { flag: "wx" }); - /** @type {string | undefined} */ - let back; - if (existsSync(path)) { - back = join(backups, `old-${i}`); - writeFileSync(back, readFileSync(path), { flag: "wx" }); - } - return { path, file, back }; - }); - const done = []; - try { - for (const item of staged) { - renameSync(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)); - } - } - throw error; - } - } finally { - rmSync(stage, { recursive: true, force: true }); - rmSync(backups, { recursive: true, force: true }); - } -} - -/** - * Run `fn` holding the folder's refresh lock, so two refreshes cannot interleave their read-build-write. - * A lock is a hard link to a file that already holds the owner's pid, so it is never seen empty. A refresh that - * finds a live or unreadable owner fails with a retry message and removes nothing. A dead owner's lock is removed - * only by the one process that holds the recovery lock (`.refresh.takeover`, claimed the same way), which reads - * the owner again under it: the lock it removes is the dead owner's, because nobody else removes locks and nobody - * can link a new one while it exists. A lock is released only by the process whose file it still is. - * @template T - * @param {string} dir - * @param {() => Promise} fn - * @param {{ afterContended?: () => void | Promise, afterRead?: () => void | Promise }} [hooks] - * test seams: after a failed claim, and after the stale owner was read - */ -export async function withLock(dir, fn, hooks = {}) { - const lock = join(dir, ".refresh.lock"); - const takeover = join(dir, ".refresh.takeover"); - const mine = join(dir, `.refresh.lock.${process.pid}.${Math.random().toString(36).slice(2)}`); - // The file's content is the owner's pid and a token only this call knows, so ownership is read from content - // (an inode number is not reliable on every filesystem). - const content = `${process.pid} ${Math.random().toString(36).slice(2)}\n`; - writeFileSync(mine, content, { flag: "wx" }); - const busy = (/** @type {string} */ why) => - new Error(`another refresh holds ${lock} (${why}); retry when it has finished`); - /** @param {string} path */ - const claim = (path) => { - try { - linkSync(mine, path); - return true; - } catch (error) { - if (/** @type {any} */ (error).code === "EEXIST") { - return false; - } - throw error; - } - }; - /** @param {string} path the owner's pid, "gone" when the file vanished, "unreadable" otherwise */ - const ownerOf = (path) => { - try { - const owner = Number(readFileSync(path, "utf8").trim().split(/\s+/)[0]); - return Number.isInteger(owner) && owner > 0 ? owner : "unreadable"; - } catch (error) { - if (/** @type {any} */ (error).code === "ENOENT") { - return "gone"; - } - throw error; - } - }; - /** @param {string} path remove a claim only when it still holds this call's content */ - const release = (path) => { - try { - if (readFileSync(path, "utf8") === content) { - rmSync(path, { force: true }); - } - } catch { - // no claim, or not readable: nothing of this call's to remove - } - }; - try { - for (let attempt = 0; !claim(lock); attempt++) { - await hooks.afterContended?.(); - const owner = ownerOf(lock); - if (owner === "gone" && attempt < 5) { - continue; // the holder finished between the failed claim and the read - } - 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}`); - } - 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) { - rmSync(lock, { force: true }); - } - } finally { - release(takeover); - } - } - reclaimAbandoned(dir); - return await fn(); - } finally { - release(lock); - rmSync(mine, { force: true }); - } -} +const readJson = (path) => parseStrict(readFileSync(path, "utf8"), path); // Compared with case, spacing and punctuation removed, so "Internal Tool" and "internal_tool" match "internal-tool". -const squash = (/** @type {string} */ s) => s.toLowerCase().replace(/[^a-z0-9]/g, ""); +const squash = (/** @type {string} */ s) => + s + .normalize("NFKC") + .toLowerCase() + .replace(/[^\p{L}\p{N}]/gu, ""); /** @param {unknown} v a finite number that is not negative */ const nonNegative = (v) => typeof v === "number" && Number.isFinite(v) && v >= 0; const SNAPSHOT_KEYS = ["version", "fetched", "boardUpdated", "plantedTotal", "rows"]; @@ -661,13 +484,41 @@ export async function fetchBoard(url, fetchImpl = fetch) { } /** @param {string | undefined} file */ -const readDeny = (file) => - file === undefined - ? [] - : readFileSync(file, "utf8") - .split("\n") - .map((l) => l.trim()) - .filter(Boolean); +const readDeny = (file) => { + const words = + file === undefined + ? [] + : readFileSync(file, "utf8") + .split("\n") + .map((l) => l.trim()) + .filter(Boolean); + // A name with no letter or digit would match nothing, so the list would silently not cover it. + const empty = words.find((w) => squash(w) === ""); + if (empty !== undefined) { + throw new Error( + `deny entry ${JSON.stringify(empty)} has no letter or digit, so it cannot match`, + ); + } + return words; +}; + +/** + * Private inputs (raw results, deny lists) must not sit where the installer copies: the references folder or + * anywhere in the skill, reached through a symlink or not. + * @param {string} file + * @param {string} dir the references folder + * @param {string} flag + */ +function requireOutsideSkill(file, dir, flag) { + const real = realpathSync(resolve(file)); + for (const root of [realpathSync(dir), realpathSync(skill)]) { + if (real === root || real.startsWith(`${root}/`) || real.startsWith(`${root}\\`)) { + throw new Error( + `${flag} ${file} is inside the skill folder, which is copied to hosts; keep private inputs outside it`, + ); + } + } +} const OPTIONS = /** @type {const} */ ({ fetch: { type: "boolean" }, @@ -755,6 +606,11 @@ async function refresh(paths, values, today) { `${paths.obsoleteOwn} is an obsolete source: own results live only in the catalog; delete the file (keep the raw results outside the skill folder)`, ); } + for (const flag of ["from-file", "deny-file"]) { + if (values[flag] !== undefined) { + requireOutsideSkill(values[flag], dirname(paths.catalog), `--${flag}`); + } + } const spec = readJson(paths.spec); const deny = readDeny(values["deny-file"]); const vocabulary = { @@ -771,11 +627,11 @@ async function refresh(paths, values, today) { : await fetchBoard(spec.board.url); snapshot = reduceBoard(board, values.today ?? today); } else { - snapshot = canonicalSnapshot(JSON.parse(/** @type {string} */ (rawSnapshot))); + snapshot = canonicalSnapshot(parseStrict(/** @type {string} */ (rawSnapshot), paths.snapshot)); } // The own results are the facts the catalog's own entries carry; an import replaces all of them, so the // old ones are not read (a newly denied name in them cannot block their replacement). - const committed = rawCatalog === undefined ? undefined : JSON.parse(rawCatalog); + const committed = rawCatalog === undefined ? undefined : parseStrict(rawCatalog, paths.catalog); const own = sanitizeOwn( values["from-file"] !== undefined ? readJson(resolve(values["from-file"])) @@ -787,6 +643,7 @@ async function refresh(paths, values, today) { // screened as published: each value on its own, never joined with its neighbours. const denied = deny.map(squash).filter(Boolean); for (const [name, published] of [ + ["source spec", spec], ["snapshot", snapshot], ["catalog", catalog], ]) { diff --git a/skills/hr-code-review/test/refresh-recommendations.test.mjs b/skills/hr-code-review/test/refresh-recommendations.test.mjs index 585b32e0..a9a072a3 100644 --- a/skills/hr-code-review/test/refresh-recommendations.test.mjs +++ b/skills/hr-code-review/test/refresh-recommendations.test.mjs @@ -7,6 +7,7 @@ import { readFileSync, readdirSync, rmSync, + symlinkSync, writeFileSync, } from "node:fs"; import { tmpdir } from "node:os"; @@ -16,6 +17,7 @@ import { buildCatalog, canonicalSnapshot, fetchBoard, + parseStrict, pathsIn, reduceBoard, run, @@ -110,7 +112,12 @@ const own = (/** @type {any} */ over = {}) => ({ version: 1, results: [{ ...good * @param {(dir: string) => Promise | void} fn */ async function inFixture(fn) { - const dir = mkdtempSync(join(tmpdir(), "refresh-rec-")); + // The references folder and, beside it, the maintainer's private inputs (raw results, deny list), which + // must live outside anything the installer copies. + const root = mkdtempSync(join(tmpdir(), "refresh-rec-")); + const dir = join(root, "references"); + mkdirSync(dir); + mkdirSync(join(root, "external")); try { const paths = pathsIn(dir); const snapshot = reduceBoard( @@ -122,20 +129,27 @@ async function inFixture(fn) { writeFileSync(paths.catalog, serialize(buildCatalog(spec, snapshot, empty))); await fn(dir); } finally { - rmSync(dir, { recursive: true, force: true }); + rmSync(root, { recursive: true, force: true }); } } +/** @param {string} dir the references folder of a fixture */ +const external = (dir) => join(dirname(dir), "external"); /** Import a result file with a deny file, as a maintainer does. */ async function importOwn( /** @type {string} */ dir, /** @type {any} */ file, deny = "unrelated-name\n", ) { - writeFileSync(join(dir, "incoming.json"), JSON.stringify(file)); - writeFileSync(join(dir, "deny.txt"), deny); + writeFileSync(join(external(dir), "incoming.json"), JSON.stringify(file)); + writeFileSync(join(external(dir), "deny.txt"), deny); return silent(() => run( - ["--from-file", join(dir, "incoming.json"), "--deny-file", join(dir, "deny.txt")], + [ + "--from-file", + join(external(dir), "incoming.json"), + "--deny-file", + join(external(dir), "deny.txt"), + ], "2026-11-21", dir, ), @@ -418,9 +432,9 @@ test("a refused import changes nothing, and an import needs a deny file", async assert.equal(denied.code, 1); assert.match(denied.text, /must not carry/); assert.equal(readFileSync(pathsIn(dir).catalog, "utf8"), before); - writeFileSync(join(dir, "incoming.json"), JSON.stringify(own())); + writeFileSync(join(external(dir), "incoming.json"), JSON.stringify(own())); const out = await silent(() => - run(["--from-file", join(dir, "incoming.json")], "2026-11-21", dir), + run(["--from-file", join(external(dir), "incoming.json")], "2026-11-21", dir), ); assert.equal(out.code, 2); assert.match(out.text, /needs --deny-file/); @@ -464,8 +478,12 @@ test("the catalog is checked byte for byte: a hand edit, extra field, tampered o ); await edit("extra field", (c) => void (c.entries[1].project = "acme")); await edit("extra top-level field", (c) => void (c.project = "acme")); + // A repeated key is refused before anything is read, and nothing is rewritten: the original stays as it was. writeFileSync(file, canonical.replace('"version": 1,', '"version": 1,\n "version": 1,')); - assert.match((await check(dir)).text, /duplicate keys/); + const repeated = readFileSync(file, "utf8"); + assert.match((await check(dir)).text, /repeated key "version"/); + assert.equal((await silent(() => run([], "2026-11-21", dir))).code, 1); + assert.equal(readFileSync(file, "utf8"), repeated); // A plain run regenerates the catalog from the facts and the board, which repairs the own text. writeFileSync( file, @@ -601,13 +619,10 @@ test("a refresh reclaims only its own abandoned transactions", async () => { const notes = join(dir, ".refresh-notes"); mkdirSync(notes); writeFileSync(join(notes, "a"), "mine"); - // An import file named like the prefix is read, and survives. + // A file with the prefix is not a directory of the tool's, so it survives. const input = join(dir, ".refresh-input.json"); - writeFileSync(input, JSON.stringify(own())); - writeFileSync(join(dir, "deny.txt"), "unrelated-name\n"); - const out = await silent(() => - run(["--from-file", input, "--deny-file", join(dir, "deny.txt")], "2026-11-21", dir), - ); + writeFileSync(input, "mine"); + const out = await importOwn(dir, own()); assert.equal(out.code, 0, out.text); assert.equal(existsSync(abandoned), false); for (const kept of [ @@ -716,7 +731,7 @@ test("a second refresh while one holds the lock fails with a retry message", asy test("a deny file screens every published string, the snapshot's unused rows included", async () => { await inFixture(async (dir) => { const paths = pathsIn(dir); - const deny = join(dir, "deny.txt"); + const deny = join(external(dir), "deny.txt"); writeFileSync(deny, "internal-harness\n"); const saved = join(dir, "board.json"); // A row no recommendation uses still lands in the published snapshot. @@ -798,3 +813,146 @@ test("damage to an own entry's derived fields never drops its facts", async () = assert.equal(readFileSync(file, "utf8"), damaged); }); }); + +test("private inputs inside the skill folder are refused, symlinks included, and external paths work", async () => { + await inFixture(async (dir) => { + const before = readFileSync(pathsIn(dir).catalog, "utf8"); + // Inside the references folder: the installer would copy it. + writeFileSync(join(dir, "incoming.json"), JSON.stringify(own())); + writeFileSync(join(dir, "deny.txt"), "unrelated-name\n"); + const inside = await silent(() => + run( + ["--from-file", join(dir, "incoming.json"), "--deny-file", join(external(dir), "x")], + "2026-11-21", + dir, + ), + ); + assert.equal(inside.code, 1); + assert.match(inside.text, /inside the skill folder/); + const deny = await silent(() => + run(["--check", "--deny-file", join(dir, "deny.txt")], "2026-11-21", dir), + ); + assert.equal(deny.code, 1); + assert.match(deny.text, /inside the skill folder/); + // A symlink outside that points inside is refused by its real path. + symlinkSync(join(dir, "deny.txt"), join(external(dir), "link.txt")); + const linked = await silent(() => + run(["--check", "--deny-file", join(external(dir), "link.txt")], "2026-11-21", dir), + ); + assert.equal(linked.code, 1); + assert.equal(readFileSync(pathsIn(dir).catalog, "utf8"), before); + // An import from external paths still works. + assert.equal((await importOwn(dir, own())).code, 0); + // The real skill folder is refused too, not only the folder being refreshed. + const realDeny = await silent(() => + run(["--check", "--deny-file", join(refs, "panel-recommendations.md")], "2026-11-21", dir), + ); + assert.equal(realDeny.code, 1); + assert.match(realDeny.text, /inside the skill folder/); + }); +}); + +test("a repeated key in any JSON that carries own facts stops the run with the original intact", async () => { + await inFixture(async (dir) => { + await importOwn(dir, own()); + const file = pathsIn(dir).catalog; + const canonical = readFileSync(file, "utf8"); + const catalog = JSON.parse(canonical); + const textOf = (/** @type {any} */ c) => serialize(c); + /** @type {Array<[string, string]>} */ + const damaged = [ + // Two entries keys: the first holds the own entry, the second the board entry alone. + [ + "entries", + textOf(catalog).replace( + '"entries": [', + `"entries": ${JSON.stringify(catalog.entries.slice(1))},\n "entries": [`, + ), + ], + // A repeated key inside the facts. + ["found", canonical.replace('"found": 80,', '"found": 80,\n "found": 0,')], + ]; + for (const [key, text] of damaged) { + writeFileSync(file, text); + for (const argv of [[], ["--check"]]) { + const out = await silent(() => run(argv, "2026-11-21", dir)); + assert.equal(out.code, 1, `${key}: ${out.text}`); + assert.match(out.text, /repeated key/); + } + assert.equal(readFileSync(file, "utf8"), text); + } + // A replacement file with a repeated results key never clears the catalog's measurements. + writeFileSync(file, canonical); + writeFileSync( + join(external(dir), "incoming.json"), + '{"version":1,"results":[' + JSON.stringify(good) + '],"results":[]}', + ); + writeFileSync(join(external(dir), "deny.txt"), "unrelated-name\n"); + const out = await silent(() => + run( + [ + "--from-file", + join(external(dir), "incoming.json"), + "--deny-file", + join(external(dir), "deny.txt"), + ], + "2026-11-21", + dir, + ), + ); + assert.equal(out.code, 1); + assert.match(out.text, /repeated key "results"/); + assert.equal(readFileSync(file, "utf8"), canonical); + }); +}); + +test("the deny check covers the source spec and names in any script", async () => { + await inFixture(async (dir) => { + const paths = pathsIn(dir); + const deny = join(external(dir), "deny.txt"); + // A denied name that only the spec's own-evaluation text holds, with no own result in the catalog. + writeFileSync(deny, "private case set\n"); + writeFileSync( + paths.spec, + serialize({ ...spec, own: { ...spec.own, task: "Find defects in the private case set" } }), + ); + for (const argv of [ + ["--check", "--deny-file", deny], + ["--deny-file", deny], + ]) { + const refused = await silent(() => run(argv, "2026-11-21", dir)); + assert.equal(refused.code, 1, refused.text); + } + const out = await silent(() => run(["--check", "--deny-file", deny], "2026-11-21", dir)); + assert.match(out.text, /source spec would publish a name/); + // A name written only in non-Latin letters still matches, with or without punctuation. + writeFileSync(paths.spec, serialize(spec)); + const snapshot = JSON.parse(readFileSync(paths.snapshot, "utf8")); + // An unused row: a model the spec does not read. + snapshot.rows.push({ ...snapshot.rows[0], model: "Unused", harness: "内部工具" }); + snapshot.rows = canonicalSnapshot(snapshot).rows; + writeFileSync(paths.snapshot, serialize(snapshot)); + for (const name of ["内部工具", "内部-工具", "内部 工具"]) { + writeFileSync(deny, `${name}\n`); + const found = await silent(() => run(["--check", "--deny-file", deny], "2026-11-21", dir)); + assert.equal(found.code, 1, name); + assert.match(found.text, /would publish a name/); + } + // An entry with no letter or digit would match nothing, so it is refused, not dropped. + writeFileSync(deny, "---\n"); + const empty = await silent(() => run(["--check", "--deny-file", deny], "2026-11-21", dir)); + assert.equal(empty.code, 1); + assert.match(empty.text, /no letter or digit/); + }); +}); + +test("the strict parser reads what JSON.parse reads and refuses a repeated key at any depth", () => { + const text = '{"a":[1,2.5,-3e2,true,false,null,"x\\"y"],"b":{"c":"d"},"e":""}'; + assert.deepEqual(structuredClone(parseStrict(text)), JSON.parse(text)); + assert.throws(() => parseStrict('{"a":{"b":1,"b":2}}'), /repeated key "b"/); + assert.throws(() => parseStrict('{"a":[{"k":1,"k":1}]}'), /repeated key "k"/); + assert.throws(() => parseStrict('{"a":1} x'), /trailing text/); + assert.throws(() => parseStrict('{"a":'), /unexpected character/); + assert.doesNotThrow(() => parseStrict("[]")); + assert.doesNotThrow(() => parseStrict(' {"__proto__": 1} ')); +}); From 4a09a37352586b7c07bfc3a88053908bdb9a2fdd Mon Sep 17 00:00:00 2001 From: bompus Date: Sat, 21 Nov 2026 13:48:45 -0700 Subject: [PATCH 7/8] panel-recommendations.md: split the update paragraph under the prose ceiling --- .../references/panel-recommendations.md | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-) diff --git a/skills/hr-code-review/references/panel-recommendations.md b/skills/hr-code-review/references/panel-recommendations.md index 115435b2..f9923efc 100644 --- a/skills/hr-code-review/references/panel-recommendations.md +++ b/skills/hr-code-review/references/panel-recommendations.md @@ -67,11 +67,12 @@ exactly these fields: a `model` and `harness` the source spec already lists, an `effort`, `found`, `of`, `falseSharePercent`, `wallMinutesPerReview`, `cases`, a `caseSet` (`held-out`, `development` or `mixed`), `judging` (`blind-second-model`, `one-model`, `two-models` or `person`) and a `checked` date. The cohort wording and the -entry id are built from those facts, so no typed text reaches a public file. The -import also needs a deny file of private names, and the script refuses it and the results -file when either sits inside the skill folder (the installer copies that folder). -Any published string that holds a denied name, in the spec, snapshot or catalog, fails -the run. +entry id are built from those facts, so no typed text reaches a public file. + +The import also needs a deny file of private names. The script refuses that file and +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. A plain run of the script regenerates the catalog and writes the snapshot in its one canonical layout, which is what `--check` compares. From 5c06cb8801bbc15300dd689028f35d60c1e74099 Mon Sep 17 00:00:00 2001 From: bompus Date: Sat, 21 Nov 2026 14:14:57 -0700 Subject: [PATCH 8/8] Panel recommendations generator round 6 (owner 428a): catalog container validated before use, member names screened, full case folding, saved board location-checked, references folder inventory in the spec enforced by --check --- .../references/panel-recommendations.md | 3 +- .../panel-recommendations.sources.json | 13 +++ .../scripts/refresh-recommendations.mjs | 72 ++++++++++++- .../test/refresh-recommendations.test.mjs | 102 +++++++++++++++++- 4 files changed, 182 insertions(+), 8 deletions(-) diff --git a/skills/hr-code-review/references/panel-recommendations.md b/skills/hr-code-review/references/panel-recommendations.md index f9923efc..fed01fd3 100644 --- a/skills/hr-code-review/references/panel-recommendations.md +++ b/skills/hr-code-review/references/panel-recommendations.md @@ -72,7 +72,8 @@ entry id are built from those facts, so no typed text reaches a public file. The import also needs a deny file of private names. The script refuses that file and 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. +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. A plain run of the script regenerates the catalog and writes the snapshot in its one canonical layout, which is what `--check` compares. diff --git a/skills/hr-code-review/references/panel-recommendations.sources.json b/skills/hr-code-review/references/panel-recommendations.sources.json index f3b7aae7..af1af588 100644 --- a/skills/hr-code-review/references/panel-recommendations.sources.json +++ b/skills/hr-code-review/references/panel-recommendations.sources.json @@ -80,5 +80,18 @@ "limitations": "Counts planted bugs, not review quality on real changes; runs were resumed after the subscription's five-hour usage window ran out, so a user on a smaller plan may hit that limit sooner; the board also lists low and medium rungs that this entry leaves out; list cost is an estimate from the CLI's own usage counts, sub-agents included", "rationaleTail": "Suggest it as an additional seat from a different model family where the user has a Google AI Ultra plan and allows the effort" } + ], + "distributed": [ + "acp-client.md", + "evidence.md", + "impact.md", + "panel-adjudication.md", + "panel-board-snapshot.json", + "panel-plan.md", + "panel-recommendations.json", + "panel-recommendations.md", + "panel-recommendations.sources.json", + "panel-setup.md", + "reviewer-role.md" ] } diff --git a/skills/hr-code-review/scripts/refresh-recommendations.mjs b/skills/hr-code-review/scripts/refresh-recommendations.mjs index a474692f..c5b2cc8b 100644 --- a/skills/hr-code-review/scripts/refresh-recommendations.mjs +++ b/skills/hr-code-review/scripts/refresh-recommendations.mjs @@ -14,8 +14,8 @@ // committed files generate; no clock, no network // // Any other argument, a conflicting pair of modes or an empty value is an error (exit 2). -import { existsSync, readFileSync, realpathSync } from "node:fs"; -import { dirname, join, resolve } from "node:path"; +import { existsSync, readdirSync, readFileSync, realpathSync } from "node:fs"; +import { dirname, join, relative, resolve, sep } from "node:path"; import { fileURLToPath, pathToFileURL } from "node:url"; import { parseArgs } from "node:util"; import { parseStrict, serialize, withLock, writeAll } from "./refresh-files.mjs"; @@ -51,10 +51,14 @@ const MAX_BOARD_BYTES = 20 * 1024 * 1024; const readJson = (path) => parseStrict(readFileSync(path, "utf8"), path); // Compared with case, spacing and punctuation removed, so "Internal Tool" and "internal_tool" match "internal-tool". +// Compatibility-normalized, upper then lower case (a sharp s matches SS, a final sigma its capital), normalized +// again, then only letters and digits kept. const squash = (/** @type {string} */ s) => s .normalize("NFKC") + .toUpperCase() .toLowerCase() + .normalize("NFKC") .replace(/[^\p{L}\p{N}]/gu, ""); /** @param {unknown} v a finite number that is not negative */ const nonNegative = (v) => typeof v === "number" && Number.isFinite(v) && v >= 0; @@ -606,7 +610,7 @@ async function refresh(paths, values, today) { `${paths.obsoleteOwn} is an obsolete source: own results live only in the catalog; delete the file (keep the raw results outside the skill folder)`, ); } - for (const flag of ["from-file", "deny-file"]) { + for (const flag of ["from-file", "deny-file", "board-file"]) { if (values[flag] !== undefined) { requireOutsideSkill(values[flag], dirname(paths.catalog), `--${flag}`); } @@ -632,6 +636,12 @@ async function refresh(paths, values, today) { // The own results are the facts the catalog's own entries carry; an import replaces all of them, so the // old ones are not read (a newly denied name in them cannot block their replacement). const committed = rawCatalog === undefined ? undefined : parseStrict(rawCatalog, paths.catalog); + if (committed !== undefined) { + requireCatalogShape(committed, paths.catalog); + } + if (values.check === true) { + requireInventory(dirname(paths.catalog), spec.distributed); + } const own = sanitizeOwn( values["from-file"] !== undefined ? readJson(resolve(values["from-file"])) @@ -693,6 +703,57 @@ async function refresh(paths, values, today) { return 0; } +/** + * The catalog is the only copy of the own facts, so before it is used as their source its container must be + * what the tool writes: exactly these top-level fields, a list of entries, each an object with a string id. A + * renamed or nested list would otherwise read as "no own results" and the next write would erase them. + * @param {any} catalog + * @param {string} path + */ +function requireCatalogShape(catalog, path) { + const keys = ["version", "reviewed", "entries"]; + const damaged = + catalog === null || + typeof catalog !== "object" || + Array.isArray(catalog) || + Object.keys(catalog).length !== keys.length || + keys.some((k) => !(k in catalog)) || + catalog.version !== 1 || + !Array.isArray(catalog.entries) || + catalog.entries.some( + (/** @type {any} */ e) => + e === null || typeof e !== "object" || Array.isArray(e) || typeof e.id !== "string", + ); + if (damaged) { + throw new Error( + `${path} is not a catalog this tool wrote (version, reviewed and a list of entries with ids); nothing was changed: restore the file from version control before refreshing`, + ); + } +} + +/** + * 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. + * @param {string} dir + * @param {unknown} distributed + */ +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 extra = present.filter((n) => !distributed.includes(n)); + const missing = distributed.filter((n) => !present.includes(n)); + if (extra.length > 0 || missing.length > 0) { + throw new Error( + `the references folder differs from the spec's distributed list (not listed: ${extra.join(", ") || "none"}; missing: ${missing.join(", ") || "none"}); a file that is not public must be removed, one that is must be listed`, + ); + } +} + /** * The own facts a committed catalog carries. An entry counts as an own entry by any of its markers (its kind, an * `own-` id, or its facts), so damage to one derived field cannot make a plain run drop the measurements: an @@ -723,7 +784,7 @@ function ownFactsOf(committed) { } /** - * @param {unknown} value every string value in a JSON value, not its keys + * @param {unknown} value every string value and member name in a JSON value * @returns {string[]} */ function stringValues(value) { @@ -734,7 +795,8 @@ function stringValues(value) { return value.flatMap(stringValues); } if (value !== null && typeof value === "object") { - return Object.values(value).flatMap(stringValues); + // Member names are published text as much as values are. + return [...Object.keys(value), ...Object.values(value).flatMap(stringValues)]; } return []; } diff --git a/skills/hr-code-review/test/refresh-recommendations.test.mjs b/skills/hr-code-review/test/refresh-recommendations.test.mjs index a9a072a3..207ea5bc 100644 --- a/skills/hr-code-review/test/refresh-recommendations.test.mjs +++ b/skills/hr-code-review/test/refresh-recommendations.test.mjs @@ -65,7 +65,14 @@ const board = (/** @type {any[]} */ runs) => ({ meta: { planted_total: 105, updated: "2026-11-02" }, runs, }); +// The fixture folder holds the spec, the snapshot and the catalog, and the spec says so. +const distributed = [ + "panel-board-snapshot.json", + "panel-recommendations.json", + "panel-recommendations.sources.json", +]; const spec = { + distributed, board: { url: "https://example.org/b.json", task: "t", @@ -502,7 +509,7 @@ test("the catalog is checked byte for byte: a hand edit, extra field, tampered o test("--fetch with a saved board rewrites the snapshot and regenerates; a missing snapshot is rebuilt", async () => { await inFixture(async (dir) => { const paths = pathsIn(dir); - const saved = join(dir, "board.json"); + const saved = join(external(dir), "board.json"); writeFileSync(saved, JSON.stringify(board([row({ effort: "medium", fixed: 22 }), row()]))); rmSync(paths.snapshot); const out = await silent(() => @@ -733,7 +740,7 @@ test("a deny file screens every published string, the snapshot's unused rows inc const paths = pathsIn(dir); const deny = join(external(dir), "deny.txt"); writeFileSync(deny, "internal-harness\n"); - const saved = join(dir, "board.json"); + const saved = join(external(dir), "board.json"); // A row no recommendation uses still lands in the published snapshot. writeFileSync( saved, @@ -956,3 +963,94 @@ test("the strict parser reads what JSON.parse reads and refuses a repeated key a assert.doesNotThrow(() => parseStrict("[]")); assert.doesNotThrow(() => parseStrict(' {"__proto__": 1} ')); }); + +test("the catalog container is validated before it is the source of own facts", async () => { + await inFixture(async (dir) => { + await importOwn(dir, own()); + const file = pathsIn(dir).catalog; + const canonical = readFileSync(file, "utf8"); + const catalog = JSON.parse(canonical); + /** @type {Array<[string, any]>} */ + const damaged = [ + ["renamed entries", { version: 1, reviewed: catalog.reviewed, entryList: catalog.entries }], + ["nested entries", { ...catalog, entries: [catalog.entries] }], + ["extra field", { ...catalog, project: "acme" }], + ["wrong version", { ...catalog, version: 2 }], + ["not an object", [catalog]], + ["entry without an id", { ...catalog, entries: [{ kind: "board" }] }], + ]; + const saved = join(external(dir), "board.json"); + writeFileSync(saved, JSON.stringify(board([row({ effort: "medium", fixed: 22 }), row()]))); + for (const [name, value] of damaged) { + writeFileSync(file, serialize(value)); + const bytes = readFileSync(file, "utf8"); + for (const argv of [ + [], + ["--check"], + ["--fetch", "--board-file", saved, "--today", "2026-11-05"], + ]) { + const out = await silent(() => run(argv, "2026-11-21", dir)); + assert.equal(out.code, 1, `${name} ${argv.join(" ")}: ${out.text}`); + assert.match(out.text, /not a catalog this tool wrote/); + assert.equal(readFileSync(file, "utf8"), bytes, name); + } + } + writeFileSync(file, canonical); + assert.equal((await check(dir)).code, 0); + }); +}); + +test("member names are screened like values, and names fold the way a person reads them", async () => { + await inFixture(async (dir) => { + const paths = pathsIn(dir); + const deny = join(external(dir), "deny.txt"); + // A denied name used only as a nested key of the source spec. + writeFileSync(deny, "private project\n"); + writeFileSync(paths.spec, serialize({ ...spec, notes: { "Private Project": true } })); + const keyed = await silent(() => run(["--check", "--deny-file", deny], "2026-11-21", dir)); + assert.equal(keyed.code, 1); + assert.match(keyed.text, /source spec would publish a name/); + // Case folding goes both ways: a sharp s and SS, a final sigma and a capital sigma. + for (const [listed, published] of [ + ["STRASSE", "Straße"], + ["Straße", "STRASSE"], + ["ΟΔΥΣΣΕΥΣ", "Οδυσσευς"], + ["Οδυσσεύς", "ΟΔΥΣΣΕΎΣ"], + ]) { + writeFileSync(paths.spec, serialize({ ...spec, own: { ...spec.own, task: published } })); + writeFileSync(deny, `${listed}\n`); + const out = await silent(() => run(["--check", "--deny-file", deny], "2026-11-21", dir)); + assert.equal(out.code, 1, `${listed} / ${published}: ${out.text}`); + } + }); +}); + +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); + assert.equal((await check(dir)).code, 0); + // A leftover private input of any name, at any depth, fails the offline check. + for (const name of ["deny.txt", "incoming.json", "board.json", "notes/raw.csv"]) { + const file = join(dir, name); + mkdirSync(dirname(file), { recursive: true }); + writeFileSync(file, "private"); + const out = await check(dir); + assert.equal(out.code, 1, name); + assert.match(out.text, new RegExp(`not listed: ${name.replace(".", "\\.")}`)); + rmSync(join(dir, name.split("/")[0] ?? name), { recursive: true, force: true }); + } + // A listed file that is missing fails too, and a spec without the list is refused. + writeFileSync(paths.spec, serialize({ ...spec, distributed: [...distributed, "ghost.md"] })); + assert.match((await check(dir)).text, /missing: ghost\.md/); + const { distributed: _list, ...bare } = spec; + writeFileSync(paths.spec, serialize(bare)); + assert.match((await check(dir)).text, /no `distributed` list/); + writeFileSync(paths.spec, serialize(spec)); + // A saved board inside the folder is refused as an input. + const inside = join(dir, "board.json"); + writeFileSync(inside, JSON.stringify(board([row()]))); + const out = await silent(() => run(["--fetch", "--board-file", inside], "2026-11-21", dir)); + assert.equal(out.code, 1); + assert.match(out.text, /--board-file .* inside the skill folder/); + }); +});