@heyramzi/lint 2.4.4 → 2.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,88 @@
1
+ /**
2
+ * An import of a file the commit won't carry. @heyramzi/ui 2.15.0 shipped
3
+ * kanban-board-state importing `#src/lib/motion.js` while lib/motion.ts sat untracked on
4
+ * the author's disk: typecheck passed there and failed in every app that installed it.
5
+ */
6
+
7
+ import { dirOf } from "#lint/repo-rules/tree.js";
8
+
9
+ const CODE = /\.(m?[jt]s|svelte)$/;
10
+ const SPECIFIER = /(?:\bfrom|\bimport)\s*\(?\s*["']([.#][^"']*)["']/g;
11
+
12
+ /** Folds `.` and `..` out of a repo-relative path. */
13
+ function normalize(file) {
14
+ const parts = [];
15
+ for (const part of file.split("/")) {
16
+ if (part === "" || part === ".") continue;
17
+ if (part === "..") parts.pop();
18
+ else parts.push(part);
19
+ }
20
+ return parts.join("/");
21
+ }
22
+
23
+ /** The nearest tracked package.json above a file, with its directory. */
24
+ function manifestFor(file, tree) {
25
+ let dir = dirOf(file);
26
+ for (;;) {
27
+ const manifest = `${dir}package.json`;
28
+ if (tree.isTracked(manifest)) return { dir, json: tree.json(manifest) };
29
+ if (dir === "") return null;
30
+ dir = dirOf(dir.slice(0, -1));
31
+ }
32
+ }
33
+
34
+ /** A `#alias/x` specifier through the package's `imports` map, the way Node matches one `*`. */
35
+ function viaImportMap(specifier, file, tree) {
36
+ const manifest = manifestFor(file, tree);
37
+ for (const [key, target] of Object.entries(manifest?.json?.imports ?? {})) {
38
+ const value = typeof target === "string" ? target : (target?.types ?? target?.default);
39
+ if (typeof value !== "string") continue;
40
+ const star = key.indexOf("*");
41
+ let resolved = null;
42
+ if (star === -1 && key === specifier) resolved = value;
43
+ else if (star !== -1) {
44
+ const [prefix, suffix] = [key.slice(0, star), key.slice(star + 1)];
45
+ if (specifier.startsWith(prefix) && specifier.endsWith(suffix)) {
46
+ resolved = value.replace(
47
+ "*",
48
+ specifier.slice(prefix.length, specifier.length - suffix.length),
49
+ );
50
+ }
51
+ }
52
+ if (resolved !== null) return normalize(`${manifest.dir}${resolved}`);
53
+ }
54
+ return null;
55
+ }
56
+
57
+ /** Every file a resolver might land on: the path, its .ts twin, or an extension or index added. */
58
+ function candidates(target) {
59
+ const twin = target.replace(/\.(m?)js$/, ".$1ts");
60
+ return [
61
+ target,
62
+ twin,
63
+ ...[".ts", ".js", ".svelte", "/index.ts", "/index.js"].map((ending) => `${target}${ending}`),
64
+ ];
65
+ }
66
+
67
+ export function untrackedImports(tree) {
68
+ if (tree.untracked.length === 0) return [];
69
+ const found = [];
70
+ for (const file of tree.touchedMatching(CODE)) {
71
+ for (const [, specifier] of tree.text(file).matchAll(SPECIFIER)) {
72
+ const target = specifier.startsWith("#")
73
+ ? viaImportMap(specifier, file, tree)
74
+ : normalize(`${dirOf(file)}${specifier}`);
75
+ if (target === null) continue;
76
+ const options = candidates(target);
77
+ if (options.some((option) => tree.isTracked(option))) continue;
78
+ const missing = options.find((option) => tree.isUntracked(option));
79
+ if (!missing) continue;
80
+ found.push({
81
+ file,
82
+ rule: "untracked-import",
83
+ message: `imports ${specifier}, but ${missing} isn't in the commit. It exists only on this disk, so typecheck passes here and fails for everyone who pulls. Add it to the commit (\`git add -- ${missing}\`) or drop the import.`,
84
+ });
85
+ }
86
+ }
87
+ return found;
88
+ }
@@ -33,23 +33,37 @@ function heyramziSpecs(manifest) {
33
33
  const LINK_MESSAGE = (name, spec) =>
34
34
  `${name} is "${spec}". A @heyramzi/* dependency is always a published semver range like ^0.4.0, never link:, file: or a path. A link breaks every build container with no sibling vibe-kit checkout. If the export isn't published yet, bump the version in vibe-kit/packages/<pkg>/package.json, publish, then move this range. Don't swap the protocol to fix a version mismatch.`;
35
35
 
36
+ const WORKSPACE_LINK = /^\s*['"]?(@heyramzi\/[^'":\s]+)['"]?\s*:\s*['"]?((link|file|portal):\S*)/;
37
+
38
+ /**
39
+ * Only a link the commit adds fails. One the last commit already held is judged when it went in,
40
+ * and blocking every later edit to that manifest only keeps its scripts and tests from moving.
41
+ */
36
42
  export function heyramziLinks(tree) {
37
43
  const found = [];
38
44
  for (const file of tree.touchedMatching(MANIFEST)) {
39
45
  const manifest = tree.json(file);
40
46
  if (!manifest) continue;
47
+ const before = tree.jsonBefore(file);
48
+ const held = new Set(before ? heyramziSpecs(before).map((pair) => pair.join(" ")) : []);
41
49
  for (const [name, spec] of heyramziSpecs(manifest)) {
42
- if (LOCAL_SPEC.test(spec)) {
50
+ if (LOCAL_SPEC.test(spec) && !held.has(`${name} ${spec}`)) {
43
51
  found.push({ file, rule: "heyramzi-link", message: LINK_MESSAGE(name, spec) });
44
52
  }
45
53
  }
46
54
  }
47
55
  for (const file of tree.touchedMatching(/(^|\/)pnpm-workspace\.yaml$/)) {
56
+ const held = new Set(
57
+ tree
58
+ .textBefore(file)
59
+ .split("\n")
60
+ .map((line) => WORKSPACE_LINK.exec(line))
61
+ .filter(Boolean)
62
+ .map((match) => `${match[1]} ${match[2]}`),
63
+ );
48
64
  for (const line of tree.text(file).split("\n")) {
49
- const match = /^\s*['"]?(@heyramzi\/[^'":\s]+)['"]?\s*:\s*['"]?((link|file|portal):\S*)/.exec(
50
- line,
51
- );
52
- if (match) {
65
+ const match = WORKSPACE_LINK.exec(line);
66
+ if (match && !held.has(`${match[1]} ${match[2]}`)) {
53
67
  found.push({ file, rule: "heyramzi-link", message: LINK_MESSAGE(match[1], match[2]) });
54
68
  }
55
69
  }
@@ -1,7 +1,9 @@
1
1
  /**
2
2
  * What a repo rule reads. `touched` is the files a gate judges (staged, or every
3
- * tracked file under `--all`), `tracked` is the whole index, `added` is new paths.
4
- * Pure here: the caller supplies `read`.
3
+ * tracked file under `--all`), `tracked` is the whole index, `added` is new paths,
4
+ * `untracked` is files on disk that git doesn't know and doesn't ignore. `readBefore` gives a file as the last commit had it, so a rule can judge only what
5
+ * the commit adds; it's absent under `--all`, where everything counts as new.
6
+ * Pure here: the caller supplies `read` and `readBefore`.
5
7
  */
6
8
 
7
9
  /** Drops comments and trailing commas from JSONC, leaving strings alone. */
@@ -20,8 +22,17 @@ export function parseJsonc(text) {
20
22
  }
21
23
  }
22
24
 
23
- export function createTree({ touched, added = [], tracked, read }) {
25
+ export function createTree({
26
+ touched,
27
+ added = [],
28
+ tracked,
29
+ untracked = [],
30
+ read,
31
+ readBefore = () => null,
32
+ }) {
24
33
  const cache = new Map();
34
+ const trackedSet = new Set(tracked);
35
+ const untrackedSet = new Set(untracked);
25
36
  const text = (file) => {
26
37
  if (!cache.has(file)) cache.set(file, read(file) ?? "");
27
38
  return cache.get(file);
@@ -30,11 +41,19 @@ export function createTree({ touched, added = [], tracked, read }) {
30
41
  touched,
31
42
  added,
32
43
  tracked,
44
+ untracked,
33
45
  text,
34
46
  json(file) {
35
47
  return parseJsonc(text(file));
36
48
  },
37
- isTracked: (file) => tracked.includes(file),
49
+ /** The file as the last commit had it, or null when it's new or there's no history to ask. */
50
+ jsonBefore(file) {
51
+ const before = readBefore(file);
52
+ return before === null ? null : parseJsonc(before);
53
+ },
54
+ textBefore: (file) => readBefore(file) ?? "",
55
+ isTracked: (file) => trackedSet.has(file),
56
+ isUntracked: (file) => untrackedSet.has(file),
38
57
  touchedMatching: (pattern) => touched.filter((file) => pattern.test(file)),
39
58
  trackedMatching: (pattern) => tracked.filter((file) => pattern.test(file)),
40
59
  };
@@ -113,6 +113,15 @@ function hostedJob(lines, index) {
113
113
  return false;
114
114
  }
115
115
 
116
+ /** pnpm/action-setup learned pnpm 12 in v6.1.0; a commit sha is trusted as pinned. */
117
+ function pnpmSetupSupports12(ref) {
118
+ if (/^[0-9a-f]{40}$/.test(ref)) return true;
119
+ const version = /^v(\d+)\.(\d+)\.(\d+)$/.exec(ref);
120
+ if (!version) return false;
121
+ const [major, minor] = version.slice(1).map(Number);
122
+ return major > 6 || (major === 6 && minor >= 1);
123
+ }
124
+
116
125
  export function workflows(tree) {
117
126
  const found = [];
118
127
  for (const file of tree.touchedMatching(WORKFLOW)) {
@@ -138,7 +147,18 @@ export function workflows(tree) {
138
147
  add(
139
148
  "workflow-runs-on",
140
149
  index,
141
- `runs-on ${value} is a hosted runner, and private repos burn the billed Actions allowance on them. Every job runs on our own hardware with no hosted fallback: runs-on: [self-hosted, Linux, X64, studio-linux], or [self-hosted, macOS, ARM64, studio-mac] for Xcode work only. Public forks keep hosted runners. The one exception is a job whose NODE_OPTIONS --max-old-space-size is over ${RUNNER_MEMORY_MB}, a VPS runner's memory cap.`,
150
+ `runs-on ${value} is a hosted runner, and private repos burn the billed Actions allowance on them. Every job runs on our own hardware with no hosted fallback: runs-on: [self-hosted, Linux, X64, studio-linux] (studio-linux-heavy in its place for a job that needs both VPS slots), or [self-hosted, macOS, ARM64, studio-mac] for Xcode work only. Public forks keep hosted runners. The one exception is a job whose NODE_OPTIONS --max-old-space-size is over ${RUNNER_MEMORY_MB}, a VPS runner's memory cap.`,
151
+ );
152
+ }
153
+ if (
154
+ /\bstudio-linux\b(?!-)/.test(value) &&
155
+ value.includes("studio-linux-heavy") &&
156
+ !value.includes("${{")
157
+ ) {
158
+ add(
159
+ "workflow-runner-labels",
160
+ index,
161
+ "runs-on names both studio-linux and studio-linux-heavy, and no VPS runner carries both, so the job never starts. A heavy job names studio-linux-heavy in place of studio-linux (upsys services/ci-runners README, Slots).",
142
162
  );
143
163
  }
144
164
  }
@@ -146,7 +166,22 @@ export function workflows(tree) {
146
166
  add(
147
167
  "workflow-npmrc-write",
148
168
  index,
149
- "a workflow step writes a token to ~/.npmrc. On a self-hosted runner that file outlives the job, so each run stacks another line and the last one wins, which buried the good key under a dead one. The packages key is installed on the runner by infrastructure/scripts/runner-key.sh. Delete the step.",
169
+ "a workflow step writes a token to ~/.npmrc. Every self-hosted runner already holds the packages key: the VPS dispatcher writes it into each runner container (upsys services/ci-runners), and infrastructure/scripts/runner-key.sh installs it on the Mac. Delete the step.",
170
+ );
171
+ }
172
+ const pnpmSetup = /^\s*(?:-\s*)?uses\s*:\s*["']?pnpm\/action-setup@([\w.]+)/.exec(line);
173
+ if (pnpmSetup && !pnpmSetupSupports12(pnpmSetup[1])) {
174
+ add(
175
+ "workflow-pnpm-setup",
176
+ index,
177
+ `pnpm/action-setup@${pnpmSetup[1]} predates pnpm 12 (the floating @v6 tag is still v6.0.10). It switches to pnpm 12 without the native build, and on the VPS runners' shared store that broken pnpm then fails every repo's setup (29 Oct 2026). Pin pnpm/action-setup@v6.1.0.`,
178
+ );
179
+ }
180
+ if (/^\s*cache\s*:\s*["']?(pnpm|npm|yarn)\b/.test(line) && !hostedJob(lines, index)) {
181
+ add(
182
+ "workflow-self-hosted-cache",
183
+ index,
184
+ "setup-node's cache input on a self-hosted job. The runners share one pnpm store that persists between jobs, so this only tars the whole store into GitHub's cache after every job (4 minutes for 3 GB on 29 Oct 2026) and extracts it back over the store. Delete the cache line; hosted jobs keep theirs.",
150
185
  );
151
186
  }
152
187
  });
package/repo-rules.js CHANGED
@@ -3,6 +3,7 @@
3
3
  * to live in Markdown. Pure here, git and process in `bin/heyramzi-repo-rules.js`.
4
4
  */
5
5
 
6
+ import { untrackedImports } from "#lint/repo-rules/imports.js";
6
7
  import { composeImages, fossilNames } from "#lint/repo-rules/paths.js";
7
8
  import {
8
9
  heyramziLinks,
@@ -36,6 +37,7 @@ export const RULES = [
36
37
  viteLintBlock,
37
38
  composeImages,
38
39
  fossilNames,
40
+ untrackedImports,
39
41
  ];
40
42
 
41
43
  /** Every violation in the files the tree says were touched. */
@@ -4,7 +4,8 @@
4
4
  // Needs JEV_BASE_URL and JEV_API_KEY, from the env or Proton Pass (Dev vault, item AI endpoints).
5
5
 
6
6
  import { PARAGRAPHS, SENTENCES } from "#lint/data/jev-bench.js";
7
- import { PARAGRAPH_SHAPES, SHAPES, auditShapes, jevKey } from "#lint/jev.js";
7
+ import { PARAGRAPH_SHAPES, SHAPES } from "#lint/jev-core.js";
8
+ import { auditShapes, jevKey } from "#lint/jev.js";
8
9
 
9
10
  // Measuring the model, so no cached score stands in for a fresh answer.
10
11
  process.env.HEYRAMZI_SLOP_CACHE = "off";
@@ -0,0 +1,294 @@
1
+ #!/usr/bin/env bun
2
+ /**
3
+ * Pulls u/heyramzi's comments that went badly, plus the top human replies in the same threads,
4
+ * into data/reddit-bench.json, then reruns scripts/reddit-bench.mjs and exits with its code.
5
+ * A row once bad stays bad, so the bench only grows. Needs the logged-in Orca tab on old.reddit.com:
6
+ *
7
+ * cd ~/Studio/vibe-kit && bun ./CLIs/scripts/secrets.mjs run --mode development \
8
+ * --file 'CLIs/.env' --shell "bun packages/lint/scripts/reddit-bench-harvest.mjs"
9
+ *
10
+ * `--no-bench` stops after the harvest.
11
+ */
12
+
13
+ import { execFileSync, spawnSync } from "node:child_process";
14
+ import { readFileSync, writeFileSync } from "node:fs";
15
+ import { homedir } from "node:os";
16
+ import { join } from "node:path";
17
+
18
+ // =========================
19
+ // CONSTANTS
20
+ // =========================
21
+ const BENCH = join(import.meta.dirname, "../data/reddit-bench.json");
22
+ const ACCOUNT = "heyramzi";
23
+ const UPSYS = process.env.UPSYS_DIR || join(homedir(), "Studio/upsys");
24
+ /** A listing page holds 100; 10 pages is past every comment the account has written. */
25
+ const PAGES = 10;
26
+ /** Human replies kept per thread: the most upvoted, long enough to have a shape. */
27
+ const HUMANS_PER_THREAD = 5;
28
+ const MIN_WORDS = 25;
29
+ const MAX_WORDS = 300;
30
+ const MIN_SCORE = 1;
31
+ /** Reddit's rate window: 100 reads per 10 minutes, per account. */
32
+ const WINDOW_MS = 600_000;
33
+ /** Notices that mean a person or a bot acted on one of our comments. */
34
+ const NOTICE = /-ModTeam$|^BotBouncer$|^AutoModerator$/;
35
+ const BOT_NAME = /bot$|^bot|_bot|-bot|^AutoModerator$/i;
36
+
37
+ const { createTransport } = await import(
38
+ join(import.meta.dirname, "../../../CLIs/reddit/transport.ts")
39
+ );
40
+ const transport = createTransport();
41
+
42
+ // =========================
43
+ // FUNCTIONS
44
+ // =========================
45
+ const words = (text) => text.split(/\s+/).filter(Boolean).length;
46
+ const day = (utc) => new Date(utc * 1000).toISOString().slice(0, 10);
47
+
48
+ const pause = (ms) => new Promise((done) => setTimeout(done, ms));
49
+
50
+ /**
51
+ * One read every 6 seconds, which keeps under Reddit's 100 reads per 10 minutes. The budget is the
52
+ * account's, shared with every other reader of u/heyramzi: on 2 Nov 2026 it sat at 0 between our
53
+ * own runs. A 429 reaches us as an empty body, so a failed read waits out a whole window.
54
+ */
55
+ async function get(path, params = {}) {
56
+ for (let attempt = 0; ; attempt += 1) {
57
+ await pause(6000);
58
+ try {
59
+ // A 429 sticks to its exact query string: the same read reordered answered 200 with 98 left
60
+ // (2 Nov 2026). A fresh value per attempt never meets a stuck one.
61
+ return await transport.get(path, { ...params, _q: `${Date.now()}` });
62
+ } catch (err) {
63
+ if (attempt === 3) throw err;
64
+ console.warn(`${path} unread (${err.message.slice(0, 80)}), waiting out the rate window`);
65
+ await pause(WINDOW_MS);
66
+ }
67
+ }
68
+ }
69
+
70
+ async function listing(path, params = {}, pages = PAGES) {
71
+ const out = [];
72
+ let after;
73
+ for (let page = 0; page < pages; page += 1) {
74
+ const { data } = await get(path, { limit: 100, ...params, after });
75
+ out.push(...data.children.map((child) => child.data));
76
+ after = data.after;
77
+ if (!after) break;
78
+ }
79
+ return out;
80
+ }
81
+
82
+ /** Subs the app has closed after a removal. Null when the app can't answer, so the last list stands. */
83
+ function coldSubs() {
84
+ try {
85
+ const raw = execFileSync("pnpm", ["-s", "cli", "reddit", "rooms", "--json"], {
86
+ cwd: UPSYS,
87
+ encoding: "utf8",
88
+ stdio: ["ignore", "pipe", "ignore"],
89
+ timeout: 120_000,
90
+ maxBuffer: 64 * 1024 * 1024,
91
+ });
92
+ const { campaigns } = JSON.parse(raw.slice(raw.indexOf("{")));
93
+ const now = Date.now();
94
+ return [
95
+ ...new Set(
96
+ campaigns
97
+ .flatMap((campaign) => campaign.subs ?? [])
98
+ .filter((sub) => sub.coldUntil && Date.parse(sub.coldUntil) > now)
99
+ .map((sub) => sub.name.toLowerCase()),
100
+ ),
101
+ ];
102
+ } catch (err) {
103
+ console.warn(`app rooms unreadable, keeping the last cold list: ${err.message.split("\n")[0]}`);
104
+ return null;
105
+ }
106
+ }
107
+
108
+ /** Comment ids the app recorded as removed. Empty when the app can't answer. */
109
+ function appRemovals() {
110
+ try {
111
+ const raw = execFileSync(
112
+ "pnpm",
113
+ ["-s", "cli", "reddit", "queue", "--status", "all", "--limit", "500", "--json"],
114
+ {
115
+ cwd: UPSYS,
116
+ encoding: "utf8",
117
+ stdio: ["ignore", "pipe", "ignore"],
118
+ timeout: 120_000,
119
+ maxBuffer: 64 * 1024 * 1024,
120
+ },
121
+ );
122
+ const { threads } = JSON.parse(raw.slice(raw.indexOf("{")));
123
+ return threads
124
+ .map((thread) => thread.reply)
125
+ .filter((reply) => reply?.removedAt && reply.providerRef)
126
+ .map((reply) => String(reply.providerRef).replace(/^t1_/, ""));
127
+ } catch (err) {
128
+ console.warn(
129
+ `app queue unreadable, removals come from notices only: ${err.message.split("\n")[0]}`,
130
+ );
131
+ return [];
132
+ }
133
+ }
134
+
135
+ /** Our comment ids a mod team, AutoModerator or BotBouncer answered or named. */
136
+ async function noticed(ours) {
137
+ const ids = new Set(ours.map((c) => c.id));
138
+ // Two pages of each: a notice about a comment lands within days of it.
139
+ const mail = [
140
+ ...(await listing("/message/inbox", {}, 2)),
141
+ ...(await listing("/message/messages", {}, 2)),
142
+ ];
143
+ const hit = new Map();
144
+ for (const m of mail.filter((m) => NOTICE.test(m.author ?? ""))) {
145
+ const named = [
146
+ m.parent_id?.startsWith("t1_") ? m.parent_id.slice(3) : null,
147
+ ...[...(m.body ?? "").matchAll(/comments\/\w+\/[^/\s)]*\/(\w+)/g)].map((x) => x[1]),
148
+ ].filter((id) => id && ids.has(id));
149
+ for (const id of named) hit.set(id, `${m.author}: ${(m.body ?? "").slice(0, 80)}`);
150
+ }
151
+ return hit;
152
+ }
153
+
154
+ /** Subs that banned the account, read off each sub's own about page. */
155
+ async function bannedSubs(subs) {
156
+ const banned = [];
157
+ for (const sub of subs) {
158
+ const { data } = await get(`/r/${sub}/about`);
159
+ if (data?.user_is_banned) banned.push(sub.toLowerCase());
160
+ }
161
+ return banned;
162
+ }
163
+
164
+ /** Every comment in a thread, flattened. */
165
+ function flatten(children, out = []) {
166
+ for (const child of children ?? []) {
167
+ if (child.kind !== "t1") continue;
168
+ out.push(child.data);
169
+ flatten(child.data.replies?.data?.children, out);
170
+ }
171
+ return out;
172
+ }
173
+
174
+ function isHuman(c) {
175
+ return (
176
+ c.author !== ACCOUNT &&
177
+ !BOT_NAME.test(c.author ?? "") &&
178
+ c.author !== "[deleted]" &&
179
+ !c.distinguished &&
180
+ !c.stickied &&
181
+ !/^\[(removed|deleted)\]$/.test(c.body) &&
182
+ !/\bI am a bot\b/i.test(c.body) &&
183
+ c.score >= MIN_SCORE &&
184
+ words(c.body) >= MIN_WORDS &&
185
+ words(c.body) <= MAX_WORDS
186
+ );
187
+ }
188
+
189
+ // =========================
190
+ // MAIN
191
+ // =========================
192
+ const bench = JSON.parse(readFileSync(BENCH, "utf8"));
193
+ const rows = new Map(bench.rows.map((row) => [row.id, row]));
194
+
195
+ const ours = await listing(`/user/${ACCOUNT}/comments`);
196
+ const subs = [...new Set(ours.map((c) => c.subreddit))];
197
+ const banned = await bannedSubs(subs);
198
+ const cold = coldSubs() ?? bench.coldSubs;
199
+ const removed = new Set(appRemovals());
200
+ const notices = await noticed(ours);
201
+ const badDays = new Set(bench.badDays);
202
+ const reported = new Set(bench.reported);
203
+
204
+ let added = 0;
205
+ for (const c of ours) {
206
+ const sub = c.subreddit.toLowerCase();
207
+ const why = [
208
+ reported.has(c.id) && "reported",
209
+ removed.has(c.id) && "removed",
210
+ notices.has(c.id) && `notice (${notices.get(c.id)})`,
211
+ c.score <= 0 && `downvoted (${c.score})`,
212
+ banned.includes(sub) && "sub banned us",
213
+ cold.includes(sub) && "sub cold",
214
+ badDays.has(day(c.created_utc)) && `posted ${day(c.created_utc)}`,
215
+ ].filter(Boolean);
216
+ const known = rows.get(c.id);
217
+ if (known) {
218
+ // A reason, once seen, stays: a sub coming off cold doesn't make the comment read human.
219
+ known.why = [...new Set([...known.why, ...why])];
220
+ known.score = c.score;
221
+ continue;
222
+ }
223
+ if (why.length === 0) continue;
224
+ added += 1;
225
+ rows.set(c.id, {
226
+ id: c.id,
227
+ bad: true,
228
+ why,
229
+ sub: c.subreddit,
230
+ thread: c.link_id.slice(3),
231
+ score: c.score,
232
+ created: day(c.created_utc),
233
+ permalink: `https://www.reddit.com${c.permalink}`,
234
+ text: c.body,
235
+ });
236
+ }
237
+
238
+ /** Written after the bad comments and after each thread, so a stalled read loses nothing. */
239
+ function save() {
240
+ const sorted = [...rows.values()].toSorted(
241
+ (a, b) =>
242
+ Number(b.bad) - Number(a.bad) ||
243
+ a.created.localeCompare(b.created) ||
244
+ a.id.localeCompare(b.id),
245
+ );
246
+ const next = {
247
+ ...bench,
248
+ harvested: new Date().toISOString().slice(0, 10),
249
+ coldSubs: cold,
250
+ bannedSubs: [...new Set([...bench.bannedSubs, ...banned])].toSorted(),
251
+ threads: [...threads].toSorted(),
252
+ rows: sorted,
253
+ };
254
+ writeFileSync(BENCH, `${JSON.stringify(next, null, 2)}\n`);
255
+ return sorted;
256
+ }
257
+
258
+ // Human negatives from every thread a bad comment sits in, read once per thread.
259
+ const threads = new Set(bench.threads);
260
+ save();
261
+ for (const thread of new Set([...rows.values()].filter((r) => r.bad).map((r) => r.thread))) {
262
+ if (threads.has(thread)) continue;
263
+ const [, comments] = await get(`/comments/${thread}`, { sort: "top", limit: 200 });
264
+ const humans = flatten(comments.data.children)
265
+ .filter(isHuman)
266
+ .toSorted((a, b) => b.score - a.score)
267
+ .slice(0, HUMANS_PER_THREAD);
268
+ for (const c of humans) {
269
+ if (rows.has(c.id)) continue;
270
+ added += 1;
271
+ rows.set(c.id, {
272
+ id: c.id,
273
+ bad: false,
274
+ why: [`human, score ${c.score}`],
275
+ sub: c.subreddit,
276
+ thread,
277
+ score: c.score,
278
+ created: day(c.created_utc),
279
+ permalink: `https://www.reddit.com${c.permalink}`,
280
+ text: c.body,
281
+ });
282
+ }
283
+ threads.add(thread);
284
+ save();
285
+ }
286
+
287
+ const bad = [...rows.values()].filter((r) => r.bad).length;
288
+ console.log(`${added} new rows: ${bad} bad comments, ${rows.size - bad} human replies`);
289
+
290
+ if (process.argv.includes("--no-bench")) process.exit(0);
291
+ const run = spawnSync("node", [join(import.meta.dirname, "reddit-bench.mjs")], {
292
+ stdio: "inherit",
293
+ });
294
+ process.exit(run.status ?? 1);
@@ -0,0 +1,114 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * Runs the forum gate, exactly as `reddit lint` in upsys/app runs it, on every row of
4
+ * data/reddit-bench.json. Recall is bad comments refused; the false positive rate is human
5
+ * replies refused. Exits 1 when a bad comment outside `knownMisses` passes, or the false positive
6
+ * rate tops MAX_FPR. `--accept` writes today's misses to `knownMisses`, after a reviewed gate change.
7
+ *
8
+ * node scripts/reddit-bench.mjs [--accept] [--out=<file.json>]
9
+ *
10
+ * Needs Jev (JEV_BASE_URL and JEV_API_KEY, env or Proton Pass). Scores are cached per sentence,
11
+ * so a rerun after a data-only harvest asks the model only about the new rows.
12
+ */
13
+
14
+ import { execFile } from "node:child_process";
15
+ import { mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
16
+ import { tmpdir } from "node:os";
17
+ import { join } from "node:path";
18
+ import { promisify } from "node:util";
19
+
20
+ // =========================
21
+ // CONSTANTS
22
+ // =========================
23
+ const BENCH = join(import.meta.dirname, "../data/reddit-bench.json");
24
+ const CLI = join(import.meta.dirname, "../bin/heyramzi-slop.js");
25
+ /** upsys/app/cli/src/reddit-lint.ts, less --fix: the bench reads, never rewrites. */
26
+ const FLAGS = ["--register=forum", "--jev", "--shape-block=0.75", "--json"];
27
+ /** Humans refused, at most: the 2 Nov 2026 gate refused 16.6%, so a change may not raise it. */
28
+ const MAX_FPR = 0.17;
29
+ /** Two CLIs at once: four drew Cloudflare's gateway 429 (2 Nov 2026). */
30
+ const CONCURRENCY = 2;
31
+
32
+ const run = promisify(execFile);
33
+
34
+ // =========================
35
+ // FUNCTIONS
36
+ // =========================
37
+ /** The gate's verdict on one row, with every finding id that refused it. */
38
+ async function verdict(row, dir) {
39
+ const file = join(dir, `${row.id}.md`);
40
+ writeFileSync(file, row.text);
41
+ const out = await run(process.execPath, [CLI, file, ...FLAGS], {
42
+ maxBuffer: 8 * 1024 * 1024,
43
+ }).catch((err) => err);
44
+ const result = JSON.parse(out.stdout);
45
+ if (result.jev && !result.jev.ran) throw new Error(`Jev did not run: ${result.jev.reason}`);
46
+ return { ...row, refused: !result.ok, hits: result.findings.map((f) => `${f.kind}:${f.id}`) };
47
+ }
48
+
49
+ async function pooled(rows, fn) {
50
+ const out = [];
51
+ for (let i = 0; i < rows.length; i += CONCURRENCY)
52
+ out.push(...(await Promise.all(rows.slice(i, i + CONCURRENCY).map(fn))));
53
+ return out;
54
+ }
55
+
56
+ const pct = (n, of) => (of === 0 ? "n/a" : `${((n / of) * 100).toFixed(1)}%`);
57
+ const head = (text) => text.replace(/\s+/g, " ").slice(0, 90);
58
+
59
+ // =========================
60
+ // MAIN
61
+ // =========================
62
+ const bench = JSON.parse(readFileSync(BENCH, "utf8"));
63
+ const { rows } = bench;
64
+ const known = new Set(bench.knownMisses);
65
+ const dir = mkdtempSync(join(tmpdir(), "reddit-bench-"));
66
+ let judged;
67
+ try {
68
+ judged = await pooled(rows, (row) => verdict(row, dir));
69
+ } finally {
70
+ rmSync(dir, { recursive: true, force: true });
71
+ }
72
+
73
+ const bad = judged.filter((r) => r.bad);
74
+ const human = judged.filter((r) => !r.bad);
75
+ const missed = bad.filter((r) => !r.refused);
76
+ const flagged = human.filter((r) => r.refused);
77
+
78
+ // Which check carries the load, and which one costs the humans.
79
+ const byHit = {};
80
+ for (const r of judged)
81
+ for (const hit of new Set(r.hits)) {
82
+ byHit[hit] ??= { bad: 0, human: 0 };
83
+ byHit[hit][r.bad ? "bad" : "human"] += 1;
84
+ }
85
+ console.log("check bad human");
86
+ for (const [hit, n] of Object.entries(byHit).toSorted((a, b) => b[1].bad - a[1].bad))
87
+ console.log(`${hit.padEnd(30)} ${String(n.bad).padStart(4)} ${String(n.human).padStart(6)}`);
88
+
89
+ const fresh = missed.filter((r) => !known.has(r.id));
90
+ for (const r of missed)
91
+ console.log(
92
+ `\n${known.has(r.id) ? "miss" : "MISS"} ${r.id} r/${r.sub} (${r.why.join(", ")})\n ${head(r.text)}`,
93
+ );
94
+ for (const r of flagged)
95
+ console.log(`\nHUMAN REFUSED ${r.id} r/${r.sub} ${r.hits.join(" ")}\n ${head(r.text)}`);
96
+
97
+ const recall = bad.length - missed.length;
98
+ console.log(
99
+ `\nrecall ${recall}/${bad.length} (${pct(recall, bad.length)}), ` +
100
+ `false positives ${flagged.length}/${human.length} (${pct(flagged.length, human.length)}), ` +
101
+ `bar ${pct(MAX_FPR, 1)}`,
102
+ );
103
+
104
+ console.log(`${fresh.length} bad comments pass that knownMisses doesn't list`);
105
+
106
+ const outFlag = process.argv.find((a) => a.startsWith("--out="));
107
+ if (outFlag) writeFileSync(outFlag.slice(6), JSON.stringify(judged, null, 2));
108
+ if (process.argv.includes("--accept")) {
109
+ const knownMisses = missed.map((r) => r.id).toSorted();
110
+ writeFileSync(BENCH, `${JSON.stringify({ ...bench, knownMisses }, null, 2)}\n`);
111
+ console.log(`knownMisses: ${knownMisses.length}`);
112
+ process.exit(0);
113
+ }
114
+ process.exit(fresh.length > 0 || flagged.length / Math.max(1, human.length) > MAX_FPR ? 1 : 0);