paperlint 18.2.1 → 18.3.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.
Files changed (71) hide show
  1. package/.github/dependabot.yml +17 -0
  2. package/.github/workflows/ci.yml +30 -5
  3. package/CLAUDE.md +2 -1
  4. package/dist/domain/register.d.ts +1 -1
  5. package/dist/domain/register.d.ts.map +1 -1
  6. package/dist/domain/sentences.d.ts +3 -11
  7. package/dist/domain/sentences.d.ts.map +1 -1
  8. package/dist/domain/sentences.js +53 -8
  9. package/dist/domain/sentences.js.map +1 -1
  10. package/dist/eslint-rules/CLAUDE.md.spec.js +2 -2
  11. package/dist/eslint-rules/CLAUDE.md.spec.js.map +1 -1
  12. package/dist/folder-venue-rule.js +1 -1
  13. package/dist/readability.d.ts +12 -9
  14. package/dist/readability.d.ts.map +1 -1
  15. package/dist/readability.js +3 -3
  16. package/dist/readability.js.map +1 -1
  17. package/docs/design/paper-sources.md +1 -1
  18. package/docs/e2e.md +2 -2
  19. package/docs/optional-rules.md +2 -2
  20. package/docs/rules/pdf/body-size.md +1 -1
  21. package/docs/rules/tex/heading-case.md +2 -2
  22. package/docs/rules/tex/max-paragraph-numbers.md +13 -7
  23. package/docs/rules/tex/max-paragraph-words.md +17 -28
  24. package/docs/rules/tex/max-sentence-words.md +3 -2
  25. package/docs/rules/tex/negated-sentences.md +2 -2
  26. package/docs/rules/tex/register.md +1 -1
  27. package/docs/rules/tex/term-before-definition.md +1 -1
  28. package/docs/rules.md +3 -3
  29. package/docs/venues.md +1 -1
  30. package/docs/website.md +61 -5
  31. package/eslint-rules/CLAUDE.md +3 -3
  32. package/eslint-rules/CLAUDE.md.spec.ts +2 -2
  33. package/eslint.config.mjs +15 -4
  34. package/fixtures/real-papers.test.ts +24 -19
  35. package/package.json +4 -5
  36. package/presets/acm-sigconf.jsonc +1 -1
  37. package/presets/aidc-2026.jsonc +4 -4
  38. package/presets/aidc-2026.md +1 -1
  39. package/presets/ase-2026.md +1 -1
  40. package/presets/ieee-conference.jsonc +1 -1
  41. package/presets/msr-2027.jsonc +1 -1
  42. package/presets/neurips-style.jsonc +2 -2
  43. package/presets/neurips-style.md +1 -1
  44. package/presets/sp-2027.md +1 -1
  45. package/presets/venue-profile.schema.json +1 -1
  46. package/scripts/check.ts +9 -1
  47. package/scripts/coverage-config.test.ts +2 -0
  48. package/scripts/grow-real-papers/archive.test.ts +294 -0
  49. package/scripts/grow-real-papers/archive.ts +287 -0
  50. package/scripts/grow-real-papers/collect.test.ts +329 -0
  51. package/scripts/grow-real-papers/collect.ts +316 -0
  52. package/scripts/grow-real-papers/http.test.ts +95 -0
  53. package/scripts/grow-real-papers/http.ts +76 -0
  54. package/scripts/grow-real-papers/main.test.ts +295 -0
  55. package/scripts/grow-real-papers/main.ts +221 -0
  56. package/scripts/grow-real-papers/paper.test.ts +305 -0
  57. package/scripts/grow-real-papers/paper.ts +241 -0
  58. package/scripts/grow-real-papers/rules.test.ts +222 -0
  59. package/scripts/grow-real-papers/rules.ts +250 -0
  60. package/scripts/grow-real-papers/sources.test.ts +275 -0
  61. package/scripts/grow-real-papers/sources.ts +239 -0
  62. package/scripts/grow-real-papers/testkit.ts +79 -0
  63. package/src/domain/register.ts +1 -1
  64. package/src/domain/sentences.test.ts +128 -0
  65. package/src/domain/sentences.ts +60 -11
  66. package/src/folder-venue-rule.test.ts +1 -1
  67. package/src/folder-venue-rule.ts +1 -1
  68. package/src/readability.test.ts +82 -41
  69. package/src/readability.ts +12 -9
  70. package/src/register-bands.test.ts +4 -4
  71. package/src/rule-cases.test.ts +6 -6
@@ -0,0 +1,95 @@
1
+ /**
2
+ * The transport over a fake `fetch` and a fake clock: arXiv's 3-second gap shared by all its hosts,
3
+ * Semantic Scholar's own gap, and the retries. No real request, no real wait.
4
+ */
5
+ import { describe, expect, test } from "vitest";
6
+ import { realClock, serviceOf, throttledGet, USER_AGENT } from "./http.ts";
7
+
8
+ type Answer = number | "drop";
9
+
10
+ /** A clock whose sleeps only move its time, and a `fetch` that answers from a script. */
11
+ function world(answers: readonly Answer[]) {
12
+ const t = { now: 0 };
13
+ const sleeps: number[] = [];
14
+ const calls: (readonly [string, number])[] = [];
15
+ const queue = [...answers];
16
+ const fetchFn: typeof fetch = (input, init) => {
17
+ const url = typeof input === "string" ? input : "not a string URL";
18
+ calls.push([url, t.now]);
19
+ // Guards: every request names this package.
20
+ expect(init?.headers).toEqual({ "user-agent": USER_AGENT });
21
+ const a = queue.shift() ?? 200;
22
+ return a === "drop"
23
+ ? Promise.reject(new Error("socket hang up"))
24
+ : Promise.resolve(new Response(a === 200 ? "body" : "", { status: a }));
25
+ };
26
+ const clock = {
27
+ now: () => t.now,
28
+ sleep: (ms: number) => {
29
+ sleeps.push(ms);
30
+ t.now += ms;
31
+ return Promise.resolve();
32
+ },
33
+ };
34
+ return { get: throttledGet(fetchFn, clock), sleeps, calls };
35
+ }
36
+
37
+ describe("the gap between requests", () => {
38
+ test("arXiv's hosts share one gap; another service has its own", async () => {
39
+ const w = world([]);
40
+ await w.get("https://export.arxiv.org/api/query?a");
41
+ await w.get("https://api.semanticscholar.org/x");
42
+ await w.get("https://arxiv.org/src/1");
43
+ // Guards: the e-print waits 3.1 s after the export API, while S2 did not wait for arXiv.
44
+ expect(w.calls).toEqual([
45
+ ["https://export.arxiv.org/api/query?a", 0],
46
+ ["https://api.semanticscholar.org/x", 0],
47
+ ["https://arxiv.org/src/1", 3100],
48
+ ]);
49
+ // Guards: which hosts are arXiv.
50
+ expect(
51
+ [
52
+ "https://arxiv.org/",
53
+ "https://export.arxiv.org/",
54
+ "https://notarxiv.org/",
55
+ ].map((u) => serviceOf(u)),
56
+ ).toEqual([
57
+ { key: "arxiv", gapMs: 3100 },
58
+ { key: "arxiv", gapMs: 3100 },
59
+ { key: "notarxiv.org", gapMs: 1100 },
60
+ ]);
61
+ });
62
+ });
63
+
64
+ describe("retries", () => {
65
+ test("a 429, a 5xx and a dropped connection are retried with a growing pause", async () => {
66
+ const w = world([429, 503, "drop", 200]);
67
+ const r = await w.get("https://api.semanticscholar.org/x");
68
+ // Guards: the fourth attempt's answer comes back.
69
+ expect(r).toEqual({ ok: true, bytes: new Uint8Array(Buffer.from("body")) });
70
+ // Guards: 10, 20, 30 s between attempts (the 1.1 s gap already passed).
71
+ expect(w.sleeps).toEqual([10_000, 20_000, 30_000]);
72
+ });
73
+
74
+ test("a 404 is final, and four failures give up", async () => {
75
+ const w = world([404, 500, 500, 500, 500]);
76
+ // Guards: a client error is not retried.
77
+ expect(await w.get("https://api.semanticscholar.org/a")).toEqual({
78
+ ok: false,
79
+ status: "404",
80
+ });
81
+ // Guards: the last status, with the number of attempts.
82
+ expect(await w.get("https://api.semanticscholar.org/b")).toEqual({
83
+ ok: false,
84
+ status: "500 after 4 attempts",
85
+ });
86
+ expect(w.calls.length).toBe(5);
87
+ });
88
+ });
89
+
90
+ test("the real clock sleeps and tells the time", async () => {
91
+ const before = realClock.now();
92
+ await realClock.sleep(1);
93
+ // Guards: time moves forward across a sleep.
94
+ expect(realClock.now()).toBeGreaterThanOrEqual(before);
95
+ });
@@ -0,0 +1,76 @@
1
+ /**
2
+ * The transport behind `Get`: one request at a time per service, a fixed gap between two requests
3
+ * to the same service (arXiv asks for 3 s between ANY two of its requests, export API and e-prints
4
+ * alike), and a retry after a 429, a 5xx or a dropped connection. `fetch` and the clock are passed
5
+ * in, so a test runs it on fakes without waiting.
6
+ */
7
+ import type { Fetched, Get } from "./sources.ts";
8
+
9
+ export type Clock = Readonly<{
10
+ now: () => number;
11
+ sleep: (ms: number) => Promise<void>;
12
+ }>;
13
+
14
+ /** The real clock. */
15
+ export const realClock: Clock = {
16
+ now: Date.now,
17
+ sleep: (ms) => new Promise<void>((done) => setTimeout(done, ms)),
18
+ };
19
+
20
+ export const USER_AGENT =
21
+ "paperlint-fixtures/1.0 (+https://github.com/zernie/paperlint)";
22
+
23
+ /** arXiv's hosts share one gap (3.1 s); any other host, Semantic Scholar's, has its own (1.1 s). */
24
+ export const serviceOf = (
25
+ url: string,
26
+ ): Readonly<{ key: string; gapMs: number }> => {
27
+ const host = new URL(url).hostname;
28
+ return host === "arxiv.org" || host.endsWith(".arxiv.org")
29
+ ? { key: "arxiv", gapMs: 3100 }
30
+ : { key: host, gapMs: 1100 };
31
+ };
32
+
33
+ /** One request: its answer, or the status worth a retry (429, 5xx, a dropped connection). */
34
+ const once = async (
35
+ fetchFn: typeof fetch,
36
+ url: string,
37
+ ): Promise<Fetched | Readonly<{ retry: string }>> => {
38
+ try {
39
+ const res = await fetchFn(url, { headers: { "user-agent": USER_AGENT } });
40
+ if (res.ok)
41
+ return { ok: true, bytes: new Uint8Array(await res.arrayBuffer()) };
42
+ const status = String(res.status);
43
+ return res.status === 429 || res.status >= 500
44
+ ? { retry: status }
45
+ : { ok: false, status };
46
+ } catch (e) {
47
+ return { retry: String(e) };
48
+ }
49
+ };
50
+
51
+ export function throttledGet(
52
+ fetchFn: typeof fetch,
53
+ clock: Clock,
54
+ attempts = 4,
55
+ ): Get {
56
+ const last = new Map<string, number>();
57
+ const wait = async (key: string, gapMs: number): Promise<void> => {
58
+ const due = (last.get(key) ?? -Infinity) + gapMs - clock.now();
59
+ if (due > 0) await clock.sleep(due);
60
+ last.set(key, clock.now());
61
+ };
62
+ const tryFrom = async (url: string, attempt: number): Promise<Fetched> => {
63
+ const { key, gapMs } = serviceOf(url);
64
+ await wait(key, gapMs);
65
+ const r = await once(fetchFn, url);
66
+ if (!("retry" in r)) return r;
67
+ if (attempt >= attempts)
68
+ return {
69
+ ok: false,
70
+ status: `${r.retry} after ${String(attempts)} attempts`,
71
+ };
72
+ await clock.sleep(10_000 * attempt);
73
+ return tryFrom(url, attempt + 1);
74
+ };
75
+ return (url) => tryFrom(url, 1);
76
+ }
@@ -0,0 +1,295 @@
1
+ /**
2
+ * The command line: its options, a dry run that writes nothing, `--write` staging into a directory
3
+ * laid out as `fixtures/` is, and a resumed run reading the log it left. The world is a temp
4
+ * directory and a fake `Get`; the spawned CLI is given a queries file that asks for nothing.
5
+ */
6
+ import { readdirSync, readFileSync, writeFileSync } from "node:fs";
7
+ import { join, resolve } from "node:path";
8
+ import { describe, expect, test } from "vitest";
9
+ import { z } from "zod";
10
+ import {
11
+ parseJson,
12
+ runNode,
13
+ useTempDir,
14
+ writeTree,
15
+ } from "../../test/support.ts";
16
+ import { argsOf, FIXTURES, run, type Args, type World } from "./main.ts";
17
+ import { fakeGet, mainTex, tarGz } from "./testkit.ts";
18
+
19
+ const NOW = Date.parse("2026-11-20T00:00:00Z");
20
+ const DEFAULT_QUERIES = join(
21
+ FIXTURES,
22
+ "real-papers",
23
+ "accepted",
24
+ "sampling",
25
+ "queries.json",
26
+ );
27
+
28
+ describe("the options", () => {
29
+ test.each([
30
+ [
31
+ [],
32
+ { queries: DEFAULT_QUERIES, only: null, deadline: Infinity, write: null },
33
+ ],
34
+ [
35
+ [
36
+ "--only",
37
+ "ml,nlp",
38
+ "--minutes",
39
+ "30",
40
+ "--deadline",
41
+ "2026-11-20T00:10:00Z",
42
+ "--write",
43
+ "out",
44
+ "--queries",
45
+ "q.json",
46
+ ],
47
+ {
48
+ queries: "q.json",
49
+ only: ["ml", "nlp"],
50
+ deadline: NOW + 600_000,
51
+ write: resolve("out"),
52
+ },
53
+ ],
54
+ [
55
+ ["--minutes", "1"],
56
+ {
57
+ queries: DEFAULT_QUERIES,
58
+ only: null,
59
+ deadline: NOW + 60_000,
60
+ write: null,
61
+ },
62
+ ],
63
+ ])("%j", (argv, args) => {
64
+ // Guards: the parsed command line; the earlier of the two limits wins.
65
+ expect(argsOf(argv, NOW)).toEqual(args);
66
+ });
67
+
68
+ test.each([
69
+ [["--force"], "unknown option --force"],
70
+ [
71
+ ["--minutes", "soon"],
72
+ "--minutes takes a number and --deadline an ISO date",
73
+ ],
74
+ [["--deadline"], "--minutes takes a number and --deadline an ISO date"],
75
+ [["--write"], "--write takes the fixtures directory to stage into"],
76
+ ])("%j is refused", (argv, message) => {
77
+ // Guards: each refusal by its message.
78
+ expect(argsOf(argv, NOW)).toBe(message);
79
+ });
80
+ });
81
+
82
+ const BY = "http://creativecommons.org/licenses/by/4.0/";
83
+ const queriesJson = JSON.stringify({
84
+ hardCap: 5,
85
+ maxPages: 1,
86
+ quotas: { nlp: 2 },
87
+ slots: [
88
+ {
89
+ field: "nlp",
90
+ series: "ACL",
91
+ year: 2025,
92
+ cap: 2,
93
+ queries: ['co:"ACL 2025"'],
94
+ max_results: 50,
95
+ venue: "acl",
96
+ classSpec: "acl",
97
+ },
98
+ ],
99
+ });
100
+ const entry = (id: string) =>
101
+ `<entry><id>http://arxiv.org/abs/${id}</id><updated>2025-05-01</updated><title>T</title><arxiv:comment>Accepted at ACL 2025</arxiv:comment></entry>`;
102
+ const camera = tarGz([
103
+ {
104
+ name: "main.tex",
105
+ body: mainTex("Hi.", "\\documentclass{article}\\usepackage{acl}"),
106
+ },
107
+ ]);
108
+
109
+ const TMP = useTempDir("grow-main-");
110
+ const ids = (path: string) =>
111
+ z
112
+ .array(z.object({ arxiv_id: z.string() }))
113
+ .parse(parseJson(readFileSync(path, "utf8")))
114
+ .map((e) => e.arxiv_id);
115
+
116
+ /** A fixtures tree with one earlier entry, one preprint, and a world over a fake `Get`. */
117
+ function setup(name: string) {
118
+ const root = join(TMP, name);
119
+ writeTree(root, {
120
+ "fixtures/venue-manifest.json": JSON.stringify([
121
+ { arxiv_id: "old", field: "nlp" },
122
+ ]),
123
+ "fixtures/arxiv-manifest.json": JSON.stringify([{ arxiv_id: "pre1v1" }]),
124
+ "presets/acl-2025.jsonc": "{}",
125
+ "presets/README.md": "",
126
+ "queries.json": queriesJson,
127
+ });
128
+ const { get, asked } = fakeGet([
129
+ ["api/query", `<feed>${entry("pre1v2")}${entry("k1v1")}</feed>`],
130
+ ["oai2", `<license>${BY}</license>`],
131
+ ["src/", camera],
132
+ ]);
133
+ const out: string[] = [];
134
+ const world: World = {
135
+ get,
136
+ now: () => NOW,
137
+ log: (l) => out.push(l),
138
+ fixtures: join(root, "fixtures"),
139
+ presets: join(root, "presets"),
140
+ };
141
+ const args = (write: string | null): Args => ({
142
+ queries: join(root, "queries.json"),
143
+ only: null,
144
+ deadline: Infinity,
145
+ write,
146
+ });
147
+ return { root, world, out, asked, args };
148
+ }
149
+
150
+ describe("a run", () => {
151
+ test("a dry run prints each decision and every staged path, and writes nothing", async () => {
152
+ const s = setup("dry");
153
+ const before = readdirSync(join(s.root, "fixtures"));
154
+ // Guards: a dry run succeeds.
155
+ expect(await run(s.args(null), s.world)).toBe(0);
156
+ // Guards: the printed record, in order (it is the output).
157
+ expect(s.out).toEqual([
158
+ "#1 pre1v2 ACL 2025: rejected — already in the corpora",
159
+ "#2 k1v1 ACL 2025: kept — passes rules 1-4",
160
+ " stage paper.tex",
161
+ " stage record-by-hand.json",
162
+ " stage PIPELINE-STATUS.md",
163
+ " stage paperlint.json",
164
+ " stage README.md",
165
+ "nlp/ACL 2025: full at rank 2",
166
+ "dry run: 1 paper(s) would be added; nothing written (--write DIR stages them)",
167
+ ]);
168
+ // Guards: nothing written into fixtures/.
169
+ expect(readdirSync(join(s.root, "fixtures"))).toEqual(before);
170
+ });
171
+ });
172
+
173
+ describe("a run with --write", () => {
174
+ test("--write stages into the directory, and a rerun resumes from its log", async () => {
175
+ const s = setup("write");
176
+ const out = join(s.root, "staged");
177
+ expect(await run(s.args(out), s.world)).toBe(0);
178
+ const sampling = join(out, "real-papers", "accepted", "sampling");
179
+ const reasons = readFileSync(join(sampling, "probe-log.jsonl"), "utf8")
180
+ .trim()
181
+ .split("\n")
182
+ .map((l) => z.object({ reason: z.string() }).parse(parseJson(l)).reason);
183
+ // Guards: one log line per candidate, with its reason.
184
+ expect(reasons).toEqual(["already in the corpora", "passes rules 1-4"]);
185
+ const notes = z
186
+ .record(z.string(), z.unknown())
187
+ .parse(
188
+ parseJson(readFileSync(join(sampling, "staging-notes.json"), "utf8")),
189
+ );
190
+ // Guards: the paper's directory, its note and its manifest entry.
191
+ expect([
192
+ readdirSync(join(out, "real-papers", "accepted", "k1v1")).toSorted(),
193
+ Object.keys(notes),
194
+ ids(join(out, "venue-manifest.json")),
195
+ ]).toEqual([
196
+ [
197
+ "PIPELINE-STATUS.md",
198
+ "README.md",
199
+ "paper.tex",
200
+ "paperlint.json",
201
+ "record-by-hand.json",
202
+ ],
203
+ ["k1v1"],
204
+ ["k1v1"],
205
+ ]);
206
+ const asked = s.asked.length;
207
+ s.out.length = 0;
208
+ expect(await run(s.args(out), s.world)).toBe(0);
209
+ // Guards: the rerun counts the staged paper, so the quota of 2 is met and nothing is asked.
210
+ expect([s.out, s.asked.length]).toEqual([
211
+ ["staged 0 paper(s) into " + out],
212
+ asked,
213
+ ]);
214
+ });
215
+ });
216
+
217
+ describe("a run with --write that stops halfway", () => {
218
+ test("a paper whose files fail to write is not logged as kept, so a rerun judges it again", async () => {
219
+ const s = setup("broken");
220
+ const out = join(s.root, "staged");
221
+ // A file where the paper's directory must go makes staging its files fail.
222
+ writeTree(out, { "real-papers/accepted/k1v1": "" });
223
+ await expect(run(s.args(out), s.world)).rejects.toThrow();
224
+ const log = join(
225
+ out,
226
+ "real-papers",
227
+ "accepted",
228
+ "sampling",
229
+ "probe-log.jsonl",
230
+ );
231
+ const outcomes = readFileSync(log, "utf8")
232
+ .trim()
233
+ .split("\n")
234
+ .map((l) =>
235
+ z.object({ id: z.string(), outcome: z.string() }).parse(parseJson(l)),
236
+ );
237
+ // Guards: only the decision whose staging finished is in the log.
238
+ expect(outcomes).toEqual([{ id: "pre1v2", outcome: "rejected" }]);
239
+ });
240
+ });
241
+
242
+ describe("a run with --write into fixtures/", () => {
243
+ test("a second paper adds to the staged notes and manifest", async () => {
244
+ const s = setup("inplace");
245
+ const out = join(s.root, "fixtures");
246
+ writeFileSync(
247
+ join(s.root, "queries.json"),
248
+ queriesJson.replace('"nlp": 2', '"nlp": 3'),
249
+ );
250
+ // Guards: staging in place (--write fixtures) appends to the existing manifest.
251
+ expect(await run(s.args(out), s.world)).toBe(0);
252
+ expect(ids(join(out, "venue-manifest.json"))).toEqual(["old", "k1v1"]);
253
+ });
254
+ });
255
+
256
+ describe("the command", () => {
257
+ test("refuses a bad option with exit 2, and runs a queries file that asks for nothing", () => {
258
+ const main = join(import.meta.dirname, "main.ts");
259
+ const bad = runNode(main, ["--write"]);
260
+ // Guards: a bad command line exits 2 with its reason.
261
+ expect([bad.status, bad.stderr.trim()]).toEqual([
262
+ 2,
263
+ "--write takes the fixtures directory to stage into",
264
+ ]);
265
+ const root = join(TMP, "cli");
266
+ writeTree(root, {
267
+ "q.json": JSON.stringify({
268
+ hardCap: 5,
269
+ maxPages: 1,
270
+ quotas: {},
271
+ slots: [],
272
+ }),
273
+ });
274
+ const ok = runNode(main, ["--queries", join(root, "q.json")]);
275
+ // Guards: no slot, no request, a dry run that says so.
276
+ expect([ok.status, ok.stdout.trim()]).toEqual([
277
+ 0,
278
+ "dry run: 0 paper(s) would be added; nothing written (--write DIR stages them)",
279
+ ]);
280
+ });
281
+ });
282
+
283
+ describe("a run whose search fails", () => {
284
+ test("prints the edition's error", async () => {
285
+ const s = setup("fails");
286
+ const world: World = { ...s.world, get: fakeGet([]).get };
287
+ // Guards: a failed search still ends the run cleanly.
288
+ expect(await run(s.args(null), world)).toBe(0);
289
+ // Guards: the edition's end names the error.
290
+ expect(s.out).toEqual([
291
+ 'nlp/ACL 2025: search error at rank 0 (co:"ACL 2025" page 0: 404)',
292
+ "dry run: 0 paper(s) would be added; nothing written (--write DIR stages them)",
293
+ ]);
294
+ });
295
+ });
@@ -0,0 +1,221 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * Grow the accepted set (fixtures/real-papers/accepted/README.md, «Growing this set without bias»).
4
+ *
5
+ * node scripts/grow-real-papers/main.ts [--only ml,nlp] [--minutes N | --deadline ISO]
6
+ * [--queries FILE] [--write FIXTURES-DIR]
7
+ *
8
+ * Without `--write`, a dry run: it fetches and judges exactly as a real run, prints each candidate
9
+ * with its rank and reason and, for each kept paper, where each staged file would go — and writes
10
+ * nothing. `--write DIR` stages into DIR laid out as `fixtures/` is: `DIR/venue-manifest.json`
11
+ * (entries appended), `DIR/real-papers/accepted/<id>/`, and `probe-log.jsonl` and
12
+ * `staging-notes.json` in `DIR/real-papers/accepted/sampling/`, each written as soon as a candidate
13
+ * is decided, so a stopped run resumes from its log. `--write fixtures` stages in place.
14
+ */
15
+ import {
16
+ appendFileSync,
17
+ existsSync,
18
+ mkdirSync,
19
+ readdirSync,
20
+ readFileSync,
21
+ writeFileSync,
22
+ } from "node:fs";
23
+ import { dirname, join, resolve } from "node:path";
24
+ import { fileURLToPath } from "node:url";
25
+ import * as R from "remeda";
26
+ import { z } from "zod";
27
+ import { isMain } from "../../skills/paper-pipeline/scripts/consumer.mjs";
28
+ import { presetsDir } from "../../src/package-dirs.ts";
29
+ import {
30
+ collect,
31
+ CountedSchema,
32
+ ProbeLineSchema,
33
+ QueriesSchema,
34
+ type Counted,
35
+ type ProbeLine,
36
+ type SlotEnd,
37
+ } from "./collect.ts";
38
+ import { realClock, throttledGet } from "./http.ts";
39
+ import type { KeptPaper } from "./paper.ts";
40
+ import { baseId, type Get } from "./sources.ts";
41
+
42
+ /** This repository's `fixtures/`, found from this file, never from the caller's directory. */
43
+ export const FIXTURES = fileURLToPath(
44
+ new URL("../../fixtures/", import.meta.url),
45
+ );
46
+ const SAMPLING = join("real-papers", "accepted", "sampling");
47
+
48
+ export type Args = Readonly<{
49
+ queries: string;
50
+ only: readonly string[] | null;
51
+ deadline: number;
52
+ write: string | null;
53
+ }>;
54
+
55
+ const KNOWN = ["--only", "--minutes", "--deadline", "--queries", "--write"];
56
+
57
+ /** The value after a flag: undefined when the flag is absent, "" when it has none. */
58
+ const valueOf = (argv: readonly string[], flag: string): string | undefined =>
59
+ argv.includes(flag) ? (argv[argv.indexOf(flag) + 1] ?? "") : undefined;
60
+
61
+ /** The earlier of `--minutes` from now and `--deadline`; Infinity when neither is given. */
62
+ const deadlineOf = (argv: readonly string[], now: number): number | string => {
63
+ const minutes = valueOf(argv, "--minutes");
64
+ const deadline = valueOf(argv, "--deadline");
65
+ const limits = [
66
+ minutes === undefined ? Infinity : now + Number(minutes) * 60_000,
67
+ deadline === undefined ? Infinity : Date.parse(deadline),
68
+ ];
69
+ return limits.some((t) => Number.isNaN(t)) || [minutes, deadline].includes("")
70
+ ? "--minutes takes a number and --deadline an ISO date"
71
+ : Math.min(...limits);
72
+ };
73
+
74
+ /** The command line, or what is wrong with it. */
75
+ export function argsOf(argv: readonly string[], now: number): Args | string {
76
+ const unknown = argv.filter((a) => a.startsWith("--") && !KNOWN.includes(a));
77
+ if (unknown.length > 0) return `unknown option ${unknown.join(", ")}`;
78
+ const deadline = deadlineOf(argv, now);
79
+ if (typeof deadline === "string") return deadline;
80
+ const write = valueOf(argv, "--write");
81
+ if (write === "") return "--write takes the fixtures directory to stage into";
82
+ return {
83
+ queries:
84
+ valueOf(argv, "--queries") ?? join(FIXTURES, SAMPLING, "queries.json"),
85
+ only: valueOf(argv, "--only")?.split(",") ?? null,
86
+ deadline,
87
+ write: write === undefined ? null : resolve(write),
88
+ };
89
+ }
90
+
91
+ const json = (v: unknown): string => `${JSON.stringify(v, null, 2)}\n`;
92
+ const readJson = (path: string, fallback: unknown): unknown =>
93
+ existsSync(path) ? JSON.parse(readFileSync(path, "utf8")) : fallback;
94
+ const Entries = z.array(CountedSchema);
95
+ const Notes = z.record(z.string(), z.unknown());
96
+ const logLines = (path: string): readonly ProbeLine[] =>
97
+ existsSync(path)
98
+ ? readFileSync(path, "utf8")
99
+ .split("\n")
100
+ .filter((l) => l !== "")
101
+ .map((l) => ProbeLineSchema.parse(JSON.parse(l)))
102
+ : [];
103
+
104
+ /** What `run` needs from the world. */
105
+ export type World = Readonly<{
106
+ get: Get;
107
+ now: () => number;
108
+ log: (line: string) => void;
109
+ /** The repository's `fixtures/`: the manifests and the log every run reads. */
110
+ fixtures: string;
111
+ presets: string;
112
+ }>;
113
+
114
+ /**
115
+ * Writes one decided candidate into `out`: when kept, its files and entries first; its log line
116
+ * last, so a run that stops halfway leaves no logged decision whose files are missing.
117
+ */
118
+ function stage(out: string, line: ProbeLine, paper?: KeptPaper): void {
119
+ const sampling = join(out, SAMPLING);
120
+ mkdirSync(sampling, { recursive: true });
121
+ if (paper !== undefined) {
122
+ const dir = join(out, "real-papers", "accepted", paper.id);
123
+ for (const [path, body] of paper.files) {
124
+ mkdirSync(dirname(join(dir, path)), { recursive: true });
125
+ writeFileSync(join(dir, path), body);
126
+ }
127
+ const notes = join(sampling, "staging-notes.json");
128
+ writeFileSync(
129
+ notes,
130
+ json({ ...Notes.parse(readJson(notes, {})), [paper.id]: paper.note }),
131
+ );
132
+ const manifest = join(out, "venue-manifest.json");
133
+ writeFileSync(
134
+ manifest,
135
+ json([...Entries.parse(readJson(manifest, [])), paper.entry]),
136
+ );
137
+ }
138
+ appendFileSync(
139
+ join(sampling, "probe-log.jsonl"),
140
+ `${JSON.stringify(line)}\n`,
141
+ );
142
+ }
143
+
144
+ /** Everything a run reads before it starts: the counts, the ids to skip, the log so far. */
145
+ function load(args: Args, world: World) {
146
+ const dirs = [
147
+ ...new Set(
148
+ [world.fixtures, args.write ?? world.fixtures].map((d) => resolve(d)),
149
+ ),
150
+ ];
151
+ const entries = R.uniqueBy(
152
+ dirs.flatMap((d) =>
153
+ Entries.parse(readJson(join(d, "venue-manifest.json"), [])),
154
+ ),
155
+ (e) => e.arxiv_id,
156
+ );
157
+ const preprints = Entries.parse(
158
+ readJson(join(world.fixtures, "arxiv-manifest.json"), []),
159
+ );
160
+ return {
161
+ queries: QueriesSchema.parse(readJson(args.queries, null)),
162
+ entries,
163
+ otherIds: new Set(preprints.map((e) => baseId(e.arxiv_id))),
164
+ logged: dirs.flatMap((d) => logLines(join(d, SAMPLING, "probe-log.jsonl"))),
165
+ shipped: new Set(
166
+ readdirSync(world.presets)
167
+ .filter((f) => f.endsWith(".jsonc"))
168
+ .map((f) => f.replace(/\.jsonc$/, "")),
169
+ ),
170
+ };
171
+ }
172
+
173
+ const endLine = (e: SlotEnd): string =>
174
+ `${e.slot}: ${e.ended} at rank ${String(e.walkedTo)}${e.error === undefined ? "" : ` (${e.error})`}`;
175
+
176
+ /** Runs the walk; prints what it decided; with `--write`, stages as it goes. Returns the exit code. */
177
+ export async function run(args: Args, world: World): Promise<number> {
178
+ const before = load(args, world);
179
+ const added: Counted[] = [];
180
+ const emit = (line: ProbeLine, paper?: KeptPaper): void => {
181
+ world.log(
182
+ `#${String(line.rank)} ${line.id} ${line.series} ${String(line.year)}: ${line.outcome} — ${line.reason}`,
183
+ );
184
+ if (paper !== undefined) {
185
+ added.push(paper.entry);
186
+ for (const path of paper.files.keys()) world.log(` stage ${path}`);
187
+ }
188
+ if (args.write !== null) stage(args.write, line, paper);
189
+ };
190
+ const ends = await collect({
191
+ ...before,
192
+ only: args.only,
193
+ get: world.get,
194
+ outOfTime: () => world.now() > args.deadline,
195
+ emit,
196
+ });
197
+ for (const e of ends) world.log(endLine(e));
198
+ world.log(
199
+ args.write === null
200
+ ? `dry run: ${String(added.length)} paper(s) would be added; nothing written (--write DIR stages them)`
201
+ : `staged ${String(added.length)} paper(s) into ${args.write}`,
202
+ );
203
+ return 0;
204
+ }
205
+
206
+ if (isMain(import.meta.url)) {
207
+ const args = argsOf(process.argv.slice(2), Date.now());
208
+ if (typeof args === "string") {
209
+ console.error(args);
210
+ process.exit(2);
211
+ }
212
+ process.exit(
213
+ await run(args, {
214
+ get: throttledGet(fetch, realClock),
215
+ now: Date.now,
216
+ log: console.log,
217
+ fixtures: FIXTURES,
218
+ presets: presetsDir(),
219
+ }),
220
+ );
221
+ }