@heyramzi/lint 2.5.0 → 2.6.1

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
+ }
@@ -1,7 +1,7 @@
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
- * `readBefore` gives a file as the last commit had it, so a rule can judge only what
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
5
  * the commit adds; it's absent under `--all`, where everything counts as new.
6
6
  * Pure here: the caller supplies `read` and `readBefore`.
7
7
  */
@@ -22,8 +22,17 @@ export function parseJsonc(text) {
22
22
  }
23
23
  }
24
24
 
25
- export function createTree({ touched, added = [], tracked, read, readBefore = () => null }) {
25
+ export function createTree({
26
+ touched,
27
+ added = [],
28
+ tracked,
29
+ untracked = [],
30
+ read,
31
+ readBefore = () => null,
32
+ }) {
26
33
  const cache = new Map();
34
+ const trackedSet = new Set(tracked);
35
+ const untrackedSet = new Set(untracked);
27
36
  const text = (file) => {
28
37
  if (!cache.has(file)) cache.set(file, read(file) ?? "");
29
38
  return cache.get(file);
@@ -32,6 +41,7 @@ export function createTree({ touched, added = [], tracked, read, readBefore = ()
32
41
  touched,
33
42
  added,
34
43
  tracked,
44
+ untracked,
35
45
  text,
36
46
  json(file) {
37
47
  return parseJsonc(text(file));
@@ -42,7 +52,8 @@ export function createTree({ touched, added = [], tracked, read, readBefore = ()
42
52
  return before === null ? null : parseJsonc(before);
43
53
  },
44
54
  textBefore: (file) => readBefore(file) ?? "",
45
- isTracked: (file) => tracked.includes(file),
55
+ isTracked: (file) => trackedSet.has(file),
56
+ isUntracked: (file) => untrackedSet.has(file),
46
57
  touchedMatching: (pattern) => touched.filter((file) => pattern.test(file)),
47
58
  trackedMatching: (pattern) => tracked.filter((file) => pattern.test(file)),
48
59
  };
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,62 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * Files Ramzi's verdict on a reply, posted or not, as a bad row in data/reddit-bench.json.
4
+ *
5
+ * node packages/lint/scripts/reddit-bench-flag.mjs --file <reply.md> --note "<his words>" \
6
+ * [--thread <reddit id or URL>] [--sub <sub>]
7
+ *
8
+ * A text already in the bench gets the note added. The next harvest reads the thread's text.
9
+ */
10
+
11
+ import { createHash } from "node:crypto";
12
+ import { readFileSync, writeFileSync } from "node:fs";
13
+ import { join } from "node:path";
14
+ import { parseArgs } from "node:util";
15
+
16
+ const BENCH = join(import.meta.dirname, "../data/reddit-bench.json");
17
+
18
+ const { values } = parseArgs({
19
+ options: {
20
+ file: { type: "string" },
21
+ note: { type: "string" },
22
+ thread: { type: "string" },
23
+ sub: { type: "string" },
24
+ },
25
+ });
26
+ if (!values.file || !values.note) {
27
+ process.stderr.write(
28
+ 'usage: reddit-bench-flag.mjs --file <reply.md> --note "<his words>" [--thread <id|url>] [--sub <sub>]\n',
29
+ );
30
+ process.exit(2);
31
+ }
32
+
33
+ /** The id out of a thread URL (`/comments/<id>/`), or the id as given. */
34
+ const threadId = (value) => value?.match(/comments\/(\w+)/)?.[1] ?? value?.replace(/^t3_/, "");
35
+ const normalize = (text) => text.normalize("NFC").replace(/\s+/g, " ").trim();
36
+
37
+ const text = readFileSync(values.file, "utf8").trim();
38
+ const bench = JSON.parse(readFileSync(BENCH, "utf8"));
39
+ const why = `ramzi-flagged: ${values.note}`;
40
+ const known = bench.rows.find((row) => normalize(row.text) === normalize(text));
41
+
42
+ if (known) {
43
+ known.bad = true;
44
+ known.flagged = true;
45
+ known.why = [...new Set([...known.why, why])];
46
+ } else {
47
+ const thread = threadId(values.thread);
48
+ bench.rows.push({
49
+ id: `flag-${createHash("sha256").update(normalize(text)).digest("hex").slice(0, 10)}`,
50
+ bad: true,
51
+ flagged: true,
52
+ why: [why],
53
+ sub: values.sub?.replace(/^r\//, "") ?? "",
54
+ thread: thread ?? "",
55
+ score: null,
56
+ created: new Date().toISOString().slice(0, 10),
57
+ permalink: thread ? `https://www.reddit.com/comments/${thread}/` : "",
58
+ text,
59
+ });
60
+ }
61
+ writeFileSync(BENCH, `${JSON.stringify(bench, null, 2)}\n`);
62
+ console.log(`${known ? "noted on" : "added"} ${known?.id ?? bench.rows.at(-1).id}: ${why}`);
@@ -0,0 +1,308 @@
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
+ const normalize = (text) => text.normalize("NFC").replace(/\s+/g, " ").trim();
195
+ /** A reply Ramzi flagged before it posted shows up later under its Reddit id: same row. */
196
+ const byText = new Map(bench.rows.map((row) => [normalize(row.text), row]));
197
+
198
+ const ours = await listing(`/user/${ACCOUNT}/comments`);
199
+ const subs = [...new Set(ours.map((c) => c.subreddit))];
200
+ const banned = await bannedSubs(subs);
201
+ const cold = coldSubs() ?? bench.coldSubs;
202
+ const removed = new Set(appRemovals());
203
+ const notices = await noticed(ours);
204
+ const badDays = new Set(bench.badDays);
205
+ const reported = new Set(bench.reported);
206
+
207
+ let added = 0;
208
+ for (const c of ours) {
209
+ const sub = c.subreddit.toLowerCase();
210
+ const why = [
211
+ reported.has(c.id) && "reported",
212
+ removed.has(c.id) && "removed",
213
+ notices.has(c.id) && `notice (${notices.get(c.id)})`,
214
+ c.score <= 0 && `downvoted (${c.score})`,
215
+ banned.includes(sub) && "sub banned us",
216
+ cold.includes(sub) && "sub cold",
217
+ badDays.has(day(c.created_utc)) && `posted ${day(c.created_utc)}`,
218
+ ].filter(Boolean);
219
+ const known = rows.get(c.id) ?? byText.get(normalize(c.body));
220
+ if (known) {
221
+ // A reason, once seen, stays: a sub coming off cold doesn't make the comment read human.
222
+ known.why = [...new Set([...known.why, ...why])];
223
+ known.score = c.score;
224
+ continue;
225
+ }
226
+ if (why.length === 0) continue;
227
+ added += 1;
228
+ rows.set(c.id, {
229
+ id: c.id,
230
+ bad: true,
231
+ why,
232
+ sub: c.subreddit,
233
+ thread: c.link_id.slice(3),
234
+ score: c.score,
235
+ created: day(c.created_utc),
236
+ permalink: `https://www.reddit.com${c.permalink}`,
237
+ text: c.body,
238
+ });
239
+ }
240
+
241
+ /** Written after the bad comments and after each thread, so a stalled read loses nothing. */
242
+ function save() {
243
+ const sorted = [...rows.values()].toSorted(
244
+ (a, b) =>
245
+ Number(b.bad) - Number(a.bad) ||
246
+ a.created.localeCompare(b.created) ||
247
+ a.id.localeCompare(b.id),
248
+ );
249
+ const next = {
250
+ ...bench,
251
+ harvested: new Date().toISOString().slice(0, 10),
252
+ coldSubs: cold,
253
+ bannedSubs: [...new Set([...bench.bannedSubs, ...banned])].toSorted(),
254
+ threads: [...threads].toSorted(),
255
+ threadText,
256
+ rows: sorted,
257
+ };
258
+ writeFileSync(BENCH, `${JSON.stringify(next, null, 2)}\n`);
259
+ return sorted;
260
+ }
261
+
262
+ // Human negatives from every thread a bad comment sits in, read once per thread, with the thread's
263
+ // own words: a check on what a reply brings that the thread never said needs them.
264
+ const threads = new Set(bench.threads);
265
+ const threadText = bench.threadText ?? {};
266
+ save();
267
+ for (const thread of new Set(
268
+ [...rows.values()].filter((r) => r.bad && r.thread).map((r) => r.thread),
269
+ )) {
270
+ if (threads.has(thread) && threadText[thread]) continue;
271
+ const [post, comments] = await get(`/comments/${thread}`, { sort: "top", limit: 200 });
272
+ const op = post.data.children[0]?.data ?? {};
273
+ threadText[thread] = { title: op.title ?? "", body: (op.selftext ?? "").slice(0, 4000) };
274
+ if (threads.has(thread)) {
275
+ save();
276
+ continue;
277
+ }
278
+ const humans = flatten(comments.data.children)
279
+ .filter(isHuman)
280
+ .toSorted((a, b) => b.score - a.score)
281
+ .slice(0, HUMANS_PER_THREAD);
282
+ for (const c of humans) {
283
+ if (rows.has(c.id)) continue;
284
+ added += 1;
285
+ rows.set(c.id, {
286
+ id: c.id,
287
+ bad: false,
288
+ why: [`human, score ${c.score}`],
289
+ sub: c.subreddit,
290
+ thread,
291
+ score: c.score,
292
+ created: day(c.created_utc),
293
+ permalink: `https://www.reddit.com${c.permalink}`,
294
+ text: c.body,
295
+ });
296
+ }
297
+ threads.add(thread);
298
+ save();
299
+ }
300
+
301
+ const bad = [...rows.values()].filter((r) => r.bad).length;
302
+ console.log(`${added} new rows: ${bad} bad comments, ${rows.size - bad} human replies`);
303
+
304
+ if (process.argv.includes("--no-bench")) process.exit(0);
305
+ const run = spawnSync("node", [join(import.meta.dirname, "reddit-bench.mjs")], {
306
+ stdio: "inherit",
307
+ });
308
+ process.exit(run.status ?? 1);
@@ -0,0 +1,126 @@
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 thread = threadText[row.thread];
42
+ const args = [CLI, file, ...FLAGS];
43
+ if (thread) {
44
+ writeFileSync(`${file}.thread`, `${thread.title}\n\n${thread.body}`.trim());
45
+ args.push(`--thread=${file}.thread`);
46
+ }
47
+ const out = await run(process.execPath, args, {
48
+ maxBuffer: 8 * 1024 * 1024,
49
+ }).catch((err) => err);
50
+ const result = JSON.parse(out.stdout);
51
+ if (result.jev && !result.jev.ran) throw new Error(`Jev did not run: ${result.jev.reason}`);
52
+ return { ...row, refused: !result.ok, hits: result.findings.map((f) => `${f.kind}:${f.id}`) };
53
+ }
54
+
55
+ async function pooled(rows, fn) {
56
+ const out = [];
57
+ for (let i = 0; i < rows.length; i += CONCURRENCY)
58
+ out.push(...(await Promise.all(rows.slice(i, i + CONCURRENCY).map(fn))));
59
+ return out;
60
+ }
61
+
62
+ const pct = (n, of) => (of === 0 ? "n/a" : `${((n / of) * 100).toFixed(1)}%`);
63
+ const head = (text) => text.replace(/\s+/g, " ").slice(0, 90);
64
+
65
+ // =========================
66
+ // MAIN
67
+ // =========================
68
+ const bench = JSON.parse(readFileSync(BENCH, "utf8"));
69
+ const { rows, threadText = {} } = bench;
70
+ const known = new Set(bench.knownMisses);
71
+ const dir = mkdtempSync(join(tmpdir(), "reddit-bench-"));
72
+ let judged;
73
+ try {
74
+ judged = await pooled(rows, (row) => verdict(row, dir));
75
+ } finally {
76
+ rmSync(dir, { recursive: true, force: true });
77
+ }
78
+
79
+ const bad = judged.filter((r) => r.bad && !r.flagged);
80
+ const ramzi = judged.filter((r) => r.flagged);
81
+ const human = judged.filter((r) => !r.bad);
82
+ const missed = judged.filter((r) => r.bad && !r.refused);
83
+ const refusedHumans = human.filter((r) => r.refused);
84
+
85
+ // Which check carries the load, and which one costs the humans.
86
+ const byHit = {};
87
+ for (const r of judged)
88
+ for (const hit of new Set(r.hits)) {
89
+ byHit[hit] ??= { bad: 0, flagged: 0, human: 0 };
90
+ byHit[hit][r.flagged ? "flagged" : r.bad ? "bad" : "human"] += 1;
91
+ }
92
+ console.log("check bad flagged human");
93
+ for (const [hit, n] of Object.entries(byHit).toSorted((a, b) => b[1].bad - a[1].bad))
94
+ console.log(
95
+ `${hit.padEnd(30)} ${String(n.bad).padStart(4)} ${String(n.flagged).padStart(7)} ${String(n.human).padStart(6)}`,
96
+ );
97
+
98
+ const fresh = missed.filter((r) => !known.has(r.id));
99
+ for (const r of missed)
100
+ console.log(
101
+ `\n${known.has(r.id) ? "miss" : "MISS"} ${r.id} r/${r.sub} (${r.why.join(", ")})\n ${head(r.text)}`,
102
+ );
103
+ for (const r of refusedHumans)
104
+ console.log(`\nHUMAN REFUSED ${r.id} r/${r.sub} ${r.hits.join(" ")}\n ${head(r.text)}`);
105
+
106
+ const caught = (rs) => rs.filter((r) => r.refused).length;
107
+ console.log(
108
+ `\nbad caught ${caught(bad)}/${bad.length} (${pct(caught(bad), bad.length)}), ` +
109
+ `flagged caught ${caught(ramzi)}/${ramzi.length} (${pct(caught(ramzi), ramzi.length)}), ` +
110
+ `humans refused ${refusedHumans.length}/${human.length} (${pct(refusedHumans.length, human.length)}), ` +
111
+ `bar ${pct(MAX_FPR, 1)}`,
112
+ );
113
+
114
+ console.log(`${fresh.length} bad comments pass that knownMisses doesn't list`);
115
+
116
+ const outFlag = process.argv.find((a) => a.startsWith("--out="));
117
+ if (outFlag) writeFileSync(outFlag.slice(6), JSON.stringify(judged, null, 2));
118
+ if (process.argv.includes("--accept")) {
119
+ const knownMisses = missed.map((r) => r.id).toSorted();
120
+ writeFileSync(BENCH, `${JSON.stringify({ ...bench, knownMisses }, null, 2)}\n`);
121
+ console.log(`knownMisses: ${knownMisses.length}`);
122
+ process.exit(0);
123
+ }
124
+ process.exit(
125
+ fresh.length > 0 || refusedHumans.length / Math.max(1, human.length) > MAX_FPR ? 1 : 0,
126
+ );
package/slop.d.ts CHANGED
@@ -49,5 +49,10 @@ export declare function auditSlop(text: string): SlopAudit;
49
49
  /** Clean, then audit. The one call a publishing path makes. */
50
50
  export declare function slopGate(
51
51
  raw: string,
52
- options?: { markup?: boolean; normalizeSpaces?: boolean },
52
+ options?: {
53
+ markup?: boolean;
54
+ code?: boolean;
55
+ normalizeSpaces?: boolean;
56
+ register?: import("./register.js").RegisterName;
57
+ },
53
58
  ): SlopLint;