@heyramzi/lint 2.5.0 → 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.
@@ -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,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);
package/slop.js CHANGED
@@ -49,7 +49,7 @@ import {
49
49
  import { phrases, words } from "#lint/data/slop-words.js";
50
50
  import { artifacts } from "#lint/data/slop/artifacts.js";
51
51
  import { patterns } from "#lint/data/slop/patterns.js";
52
- import { auditRegister } from "#lint/register.js";
52
+ import { REGISTERS, auditRegister } from "#lint/register.js";
53
53
  import {
54
54
  FAQ_TITLE,
55
55
  copyStrings,
@@ -548,8 +548,10 @@ export function slopGate(
548
548
  const registerAudit = register ? auditRegister(cleaned.text, register) : null;
549
549
  // A Short also owes a hook from the library and a counted, reply-ending skeleton.
550
550
  const shortsAudit = register === "shorts" ? auditShorts(cleaned.text) : null;
551
+ // A register may count only some exact kinds: on Reddit the rest refused most human replies.
552
+ const exact = REGISTERS[register]?.exact;
551
553
  const findings = [
552
- ...audit.findings,
554
+ ...(exact ? audit.findings.filter((f) => exact.includes(f.kind)) : audit.findings),
553
555
  ...(registerAudit?.findings ?? []),
554
556
  ...(shortsAudit?.findings ?? []),
555
557
  ];