paperlint 20.0.1 → 20.1.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.
Files changed (59) hide show
  1. package/.claude-plugin/plugin.json +1 -1
  2. package/dist/cli.d.ts.map +1 -1
  3. package/dist/cli.js +5 -1
  4. package/dist/cli.js.map +1 -1
  5. package/dist/domain/paper-folder.d.ts.map +1 -1
  6. package/dist/domain/paper-folder.js +4 -0
  7. package/dist/domain/paper-folder.js.map +1 -1
  8. package/dist/domain/paper-layout.d.ts +18 -6
  9. package/dist/domain/paper-layout.d.ts.map +1 -1
  10. package/dist/domain/paper-layout.js +44 -38
  11. package/dist/domain/paper-layout.js.map +1 -1
  12. package/dist/folder-layout-hook.js +1 -1
  13. package/dist/hook-counts.d.ts +30 -0
  14. package/dist/hook-counts.d.ts.map +1 -0
  15. package/dist/hook-counts.js +35 -0
  16. package/dist/hook-counts.js.map +1 -0
  17. package/dist/hooks-settings.d.ts +8 -10
  18. package/dist/hooks-settings.d.ts.map +1 -1
  19. package/dist/hooks-settings.js +31 -35
  20. package/dist/hooks-settings.js.map +1 -1
  21. package/dist/lint-edited-block.d.ts +8 -0
  22. package/dist/lint-edited-block.d.ts.map +1 -0
  23. package/dist/lint-edited-block.js +30 -0
  24. package/dist/lint-edited-block.js.map +1 -0
  25. package/dist/lint-edited-hook.d.ts +5 -6
  26. package/dist/lint-edited-hook.d.ts.map +1 -1
  27. package/dist/lint-edited-hook.js +47 -25
  28. package/dist/lint-edited-hook.js.map +1 -1
  29. package/dist/lint-edited-shell.d.ts +15 -0
  30. package/dist/lint-edited-shell.d.ts.map +1 -0
  31. package/dist/lint-edited-shell.js +49 -0
  32. package/dist/lint-edited-shell.js.map +1 -0
  33. package/docs/e2e.md +1 -1
  34. package/docs/install.md +11 -11
  35. package/docs/layout.md +19 -4
  36. package/docs/rules/paper/allowed-files-only.md +31 -28
  37. package/package.json +1 -1
  38. package/plugin/hooks/hooks.json +11 -0
  39. package/src/cli.harness.mjs +1 -1
  40. package/src/cli.test.ts +1 -1
  41. package/src/cli.ts +5 -1
  42. package/src/doctor.test.ts +23 -6
  43. package/src/domain/paper-folder.ts +3 -0
  44. package/src/domain/paper-layout.test.ts +89 -49
  45. package/src/domain/paper-layout.ts +61 -42
  46. package/src/folder-layout-hook.test.ts +1 -1
  47. package/src/folder-layout-hook.ts +1 -1
  48. package/src/folder-layout-rule.test.ts +1 -1
  49. package/src/hook-counts.test.ts +67 -0
  50. package/src/hook-counts.ts +64 -0
  51. package/src/hooks-settings.harness.ts +15 -18
  52. package/src/hooks-settings.ts +43 -49
  53. package/src/init-plugin.test.ts +8 -2
  54. package/src/layout-docs.test.ts +47 -0
  55. package/src/lint-edited-bash.test.ts +324 -0
  56. package/src/lint-edited-block.ts +44 -0
  57. package/src/lint-edited-hook.test.ts +10 -11
  58. package/src/lint-edited-hook.ts +72 -35
  59. package/src/lint-edited-shell.ts +72 -0
@@ -0,0 +1,324 @@
1
+ /**
2
+ * The `lint-edited` hook after a Bash command (`src/lint-edited-hook.ts`): the `.tex` files a command
3
+ * names — as a word, or as the target of a redirection that writes — are linted the way an Edit's file
4
+ * is, against the snapshot. Both halves, over in-memory files, a linter that answers from a table, and
5
+ * vigiles' real shell parser: it blocks on an error the snapshot did not hold in a file a command named
6
+ * (one paper or two); it stays quiet on a command that names no `.tex`, on a `.tex` outside every paper,
7
+ * on a relative path with no `cwd`, and on a file the snapshot has not seen, whose written lines a
8
+ * command does not say (the snapshot is written, so the next change is judged exactly). The last case
9
+ * runs `paperlint hook lint-edited` in-process on a real paper with the real engine.
10
+ */
11
+ import { readFileSync, writeFileSync } from "node:fs";
12
+ import { join } from "node:path";
13
+ import { describe, expect, it } from "vitest";
14
+ import { leafCommandsNormalized } from "vigiles/hook";
15
+ import { z } from "zod";
16
+ import { useTempDir, writeTree } from "../test/support.ts";
17
+ import { runHook } from "./cli.ts";
18
+ import { memoryFiles, type MemoryFiles } from "./adapters/memory/index.ts";
19
+ import { absolutePath } from "./domain/paths.ts";
20
+ import { fileHookGate } from "./domain/paper-folder.ts";
21
+ import {
22
+ SNAPSHOT_FILE,
23
+ lintEdited,
24
+ type LintMessage,
25
+ type PaperLinter,
26
+ } from "./lint-edited-hook.ts";
27
+
28
+ const ROOT = "/work";
29
+ const P = `${ROOT}/papers/p`;
30
+ const Q = `${ROOT}/papers/q`;
31
+ const STATUS = "PIPELINE-STATUS.md";
32
+
33
+ const ERROR = {
34
+ rule: "tex/max-sentence-words",
35
+ message: "a sentence of 64 words",
36
+ };
37
+ const finding = (line: number): LintMessage => ({
38
+ ruleId: ERROR.rule,
39
+ severity: 2,
40
+ message: ERROR.message,
41
+ line,
42
+ column: 1,
43
+ endLine: line,
44
+ });
45
+ /** A snapshot that has seen `rels`, each with no error. */
46
+ const seen = (...rels: readonly string[]): string =>
47
+ JSON.stringify({ files: Object.fromEntries(rels.map((r) => [r, []])) });
48
+
49
+ /** A Bash payload; `cwd: null` leaves the field out. */
50
+ const bash = (command: string, cwd: string | null = ROOT) => ({
51
+ tool_name: "Bash",
52
+ tool_input: { command },
53
+ ...(cwd === null ? {} : { cwd }),
54
+ });
55
+
56
+ /** The hook over `files`, with a linter per paper whose findings per file are `table[file]`. */
57
+ function run(
58
+ payload: unknown,
59
+ files: MemoryFiles,
60
+ table: Readonly<Record<string, readonly LintMessage[]>> = {},
61
+ ) {
62
+ const asked: string[][] = [];
63
+ const linter = (): PaperLinter => ({
64
+ isLinted: (f) => Promise.resolve(f.endsWith(".tex")),
65
+ lint: (fs) => {
66
+ asked.push([...fs]);
67
+ return Promise.resolve(
68
+ fs.map((filePath) => ({ filePath, messages: table[filePath] ?? [] })),
69
+ );
70
+ },
71
+ format: (rs) =>
72
+ Promise.resolve(
73
+ rs
74
+ .flatMap((r) =>
75
+ r.messages.map(
76
+ (m) => `${r.filePath}:${String(m.line)} ${m.message}`,
77
+ ),
78
+ )
79
+ .join("\n"),
80
+ ),
81
+ });
82
+ const said = lintEdited(payload, {
83
+ files,
84
+ linter: () => Promise.resolve(linter()),
85
+ shellLeaves: leafCommandsNormalized,
86
+ });
87
+ return { said, asked, linter: () => Promise.resolve(linter()) };
88
+ }
89
+
90
+ const KEPT =
91
+ "paperlint lint-edited: the edit was kept; the errors above are the ones it introduced.";
92
+
93
+ describe("lint-edited after Bash — blocks", () => {
94
+ it("🔴 sed -i on a paper's .tex: the error the snapshot did not hold is reported", async () => {
95
+ const files = memoryFiles({
96
+ [`${P}/${STATUS}`]: "# s\n",
97
+ [`${P}/paper.tex`]: "A long sentence.\n",
98
+ [`${P}/${SNAPSHOT_FILE}`]: seen("paper.tex"),
99
+ });
100
+ const { said, asked } = run(
101
+ bash(`sed -i 's/a/b/' papers/p/paper.tex`),
102
+ files,
103
+ { [`${P}/paper.tex`]: [finding(1)] },
104
+ );
105
+ expect(await said).toEqual({
106
+ decision: "block",
107
+ reason: `${P}/paper.tex:1 ${ERROR.message}\n${KEPT}`,
108
+ });
109
+ expect(asked).toEqual([[`${P}/paper.tex`]]);
110
+ });
111
+
112
+ it("a redirection that writes a body file: that file and paper.tex are linted", async () => {
113
+ const fig = `${P}/figures/fig.tex`;
114
+ const files = memoryFiles({
115
+ [`${P}/${STATUS}`]: "# s\n",
116
+ [`${P}/paper.tex`]: "x\n",
117
+ [fig]: "y\n",
118
+ [`${P}/${SNAPSHOT_FILE}`]: seen("paper.tex", "figures/fig.tex"),
119
+ });
120
+ const { said, asked } = run(
121
+ bash(`printf 'y\\n' >> ${fig}`, "/elsewhere"),
122
+ files,
123
+ { [fig]: [finding(1)] },
124
+ );
125
+ expect(await said).toEqual({
126
+ decision: "block",
127
+ reason: `${fig}:1 ${ERROR.message}\n${KEPT}`,
128
+ });
129
+ expect(asked).toEqual([[fig, `${P}/paper.tex`]]);
130
+ });
131
+
132
+ it("one command over two papers: each paper is linted with its own snapshot, both reported", async () => {
133
+ const files = memoryFiles({
134
+ [`${P}/${STATUS}`]: "# s\n",
135
+ [`${P}/paper.tex`]: "x\n",
136
+ [`${P}/${SNAPSHOT_FILE}`]: seen("paper.tex"),
137
+ [`${Q}/${STATUS}`]: "# s\n",
138
+ [`${Q}/paper.tex`]: "x\n",
139
+ [`${Q}/${SNAPSHOT_FILE}`]: seen("paper.tex"),
140
+ });
141
+ const { said, asked } = run(
142
+ bash(`perl -pi -e 's/a/b/' papers/p/paper.tex papers/q/paper.tex`),
143
+ files,
144
+ { [`${P}/paper.tex`]: [finding(1)], [`${Q}/paper.tex`]: [finding(1)] },
145
+ );
146
+ expect(await said).toEqual({
147
+ decision: "block",
148
+ reason: `${P}/paper.tex:1 ${ERROR.message}\n${Q}/paper.tex:1 ${ERROR.message}\n${KEPT}`,
149
+ });
150
+ expect(asked).toEqual([[`${P}/paper.tex`], [`${Q}/paper.tex`]]);
151
+ });
152
+ });
153
+
154
+ describe("lint-edited after Bash — one paper failing", () => {
155
+ it("🔴 a paper whose lint throws does not swallow another paper's block and is named; alone, it throws", async () => {
156
+ const files = memoryFiles({
157
+ [`${P}/${STATUS}`]: "# s\n",
158
+ [`${P}/paper.tex`]: "x\n",
159
+ [`${P}/${SNAPSHOT_FILE}`]: seen("paper.tex"),
160
+ [`${Q}/${STATUS}`]: "# s\n",
161
+ [`${Q}/paper.tex`]: "x\n",
162
+ });
163
+ const healthy = run(bash("true"), files, {
164
+ [`${P}/paper.tex`]: [finding(1)],
165
+ });
166
+ const deps = {
167
+ files,
168
+ linter: (dir: string) =>
169
+ dir === Q
170
+ ? Promise.reject(new Error("paperlint.json: bad JSON\nat line 2"))
171
+ : healthy.linter(),
172
+ shellLeaves: leafCommandsNormalized,
173
+ };
174
+ const both = bash("sed -i x papers/p/paper.tex papers/q/paper.tex");
175
+ expect(await lintEdited(both, deps)).toEqual({
176
+ decision: "block",
177
+ reason: `${P}/paper.tex:1 ${ERROR.message}\npaperlint lint-edited: ${Q} was not linted: paperlint.json: bad JSON\n${KEPT}`,
178
+ });
179
+ // Every paper failing: the first failure is thrown, for the hook's one line on stderr.
180
+ const onlyQ = bash("sed -i x papers/q/paper.tex");
181
+ await expect(lintEdited(onlyQ, deps)).rejects.toThrow("bad JSON");
182
+ });
183
+ });
184
+
185
+ describe("lint-edited after Bash — quiet", () => {
186
+ it("a command that names no .tex, a .tex outside every paper, a relative path with no cwd: nothing linted", async () => {
187
+ const files = memoryFiles({
188
+ [`${P}/${STATUS}`]: "# s\n",
189
+ [`${P}/paper.tex`]: "x\n",
190
+ [`${ROOT}/notes/draft.tex`]: "x\n",
191
+ });
192
+ for (const payload of [
193
+ bash("ls papers/p"),
194
+ bash("sed -i 's/a/b/' notes/draft.tex"),
195
+ bash("sed -i 's/a/b/' papers/p/paper.tex", null),
196
+ bash("sed -i 's/a/b/' papers/p/missing.tex"),
197
+ bash("sed -i 's/a/b/' papers/p/paper.tex", "work"),
198
+ bash("wc -l < papers/p/paper.tex"),
199
+ bash('printf x > "$OUT.tex"'),
200
+ { tool_name: "Bash", tool_input: {}, cwd: ROOT },
201
+ ]) {
202
+ const { said, asked } = run(payload, files, {
203
+ [`${P}/paper.tex`]: [finding(1)],
204
+ });
205
+ expect(await said).toBeNull();
206
+ expect(asked).toEqual([]);
207
+ }
208
+ expect(files.isFile(absolutePath(`${P}/${SNAPSHOT_FILE}`))).toBe(false);
209
+ });
210
+
211
+ it("🔴 a file the snapshot has not seen: a command does not say which lines it wrote, so nothing is reported, and the snapshot is written", async () => {
212
+ const files = memoryFiles({
213
+ [`${P}/${STATUS}`]: "# s\n",
214
+ [`${P}/paper.tex`]: "A long sentence.\n",
215
+ });
216
+ const { said } = run(bash(`sed -i 's/a/b/' papers/p/paper.tex`), files, {
217
+ [`${P}/paper.tex`]: [finding(1)],
218
+ });
219
+ expect(await said).toBeNull();
220
+ const text = new TextDecoder().decode(
221
+ files.readBytes(absolutePath(`${P}/${SNAPSHOT_FILE}`)) ??
222
+ new Uint8Array(),
223
+ );
224
+ expect(JSON.parse(text)).toEqual({
225
+ files: { "paper.tex": [{ ...ERROR, text: "A long sentence." }] },
226
+ });
227
+ });
228
+ });
229
+
230
+ describe("lint-edited — a file gone by the time its text is read", () => {
231
+ it("an Edit's file the linter still reports on but the disk no longer has: no line placed, nothing reported", async () => {
232
+ const files = memoryFiles({ [`${P}/${STATUS}`]: "# s\n" });
233
+ const edit = {
234
+ tool_name: "Edit",
235
+ tool_input: { file_path: `${P}/paper.tex`, new_string: "x" },
236
+ };
237
+ const { said } = run(edit, files, { [`${P}/paper.tex`]: [finding(1)] });
238
+ expect(await said).toBeNull();
239
+ });
240
+ });
241
+
242
+ describe("lint-edited — paper.tex linted beside a body file, with no snapshot yet", () => {
243
+ it("an error in paper.tex, which the Edit did not write: not blamed on the edit", async () => {
244
+ const fig = `${P}/figures/fig.tex`;
245
+ const files = memoryFiles({
246
+ [`${P}/${STATUS}`]: "# s\n",
247
+ [`${P}/paper.tex`]: "Old long sentence.\n",
248
+ [fig]: "x\n",
249
+ });
250
+ const edit = {
251
+ tool_name: "Edit",
252
+ tool_input: { file_path: fig, new_string: "x" },
253
+ };
254
+ const { said, asked } = run(edit, files, {
255
+ [`${P}/paper.tex`]: [finding(1)],
256
+ });
257
+ expect(await said).toBeNull();
258
+ expect(asked).toEqual([[fig, `${P}/paper.tex`]]);
259
+ });
260
+ });
261
+
262
+ describe("lint-edited after Bash — the gate before the CLI loads", () => {
263
+ it("🔴 a Bash payload goes to the hook: the `if` in the wiring already chose the command", () => {
264
+ const files = { isFile: () => false };
265
+ const stdin = () => JSON.stringify(bash("sed -i x papers/p/paper.tex"));
266
+ expect(fileHookGate(["hook", "lint-edited"], stdin, files).kind).toBe(
267
+ "hook",
268
+ );
269
+ });
270
+ });
271
+
272
+ const tmp = useTempDir("lint-edited-bash-");
273
+ const sentence = (n: number): string =>
274
+ `${Array.from({ length: n - 1 }, () => "word").join(" ")} end.`;
275
+
276
+ /** `paperlint hook lint-edited` in-process on a Bash payload run in `cwd`. */
277
+ async function hookOn(command: string, cwd: string) {
278
+ const out: string[] = [];
279
+ const err: string[] = [];
280
+ const code = await runHook("lint-edited", {
281
+ stdin: () =>
282
+ JSON.stringify({ tool_name: "Bash", tool_input: { command }, cwd }),
283
+ out: (t) => {
284
+ out.push(t);
285
+ },
286
+ err: (m: string) => {
287
+ err.push(m);
288
+ },
289
+ });
290
+ return { code, out: out.join(""), err };
291
+ }
292
+
293
+ describe("lint-edited after Bash — the real parser and engine", () => {
294
+ it("🔴 the first command records the snapshot; a later one that added a long sentence is a block naming only it", async () => {
295
+ const dir = writeTree(join(tmp, "real"), {
296
+ "package.json": "{}\n",
297
+ "papers/p/PIPELINE-STATUS.md": "# status\n",
298
+ "papers/p/paperlint.json": JSON.stringify({
299
+ extends: null,
300
+ rules: { "tex/max-sentence-words": "error" },
301
+ }),
302
+ "papers/p/paper.tex": `\\documentclass{article}\n\\begin{document}\nShort one.\n\n${sentence(64)}\n\\end{document}\n`,
303
+ });
304
+ const tex = join(dir, "papers/p/paper.tex");
305
+ // No snapshot yet, and a command says no line: the old 64-word sentence is recorded, not reported.
306
+ expect(
307
+ await hookOn("sed -i 's/Short/Brief/' papers/p/paper.tex", dir),
308
+ ).toEqual({ code: 0, out: "", err: [] });
309
+ const end = "\\end{document}";
310
+ writeFileSync(
311
+ tex,
312
+ readFileSync(tex, "utf8").replace(end, `\n${sentence(70)}\n${end}`),
313
+ );
314
+ const long = await hookOn(`perl -pi -e 's/Brief/Short/' ${tex}`, dir);
315
+ expect([long.code, long.err]).toEqual([0, []]);
316
+ const { reason } = z
317
+ .object({ decision: z.literal("block"), reason: z.string() })
318
+ .strict()
319
+ .parse(JSON.parse(long.out));
320
+ // Guards: only the new sentence (line 7), not the old one on line 5 the snapshot holds.
321
+ expect(reason).toMatch(/\n +7:1 +error +.+ +tex\/max-sentence-words\n/u);
322
+ expect(reason).not.toMatch(/\n +5:1 /u);
323
+ });
324
+ });
@@ -0,0 +1,44 @@
1
+ /**
2
+ * The block `lint-edited` prints for one tool call (`src/lint-edited-hook.ts`), from each paper's
3
+ * outcome. One Bash command can name files in two papers, and each is linted on its own: a paper
4
+ * that throws must not drop another's report, because that paper's snapshot is already written and
5
+ * its errors would never be shown again. A paper that failed is named in the block; when no paper
6
+ * has a report, the first failure is thrown, for the hook's one line on stderr.
7
+ */
8
+ import { zip } from "remeda";
9
+ import { messageOf } from "./domain/text.ts";
10
+
11
+ /** What Claude Code reads from a PostToolUse hook's stdout: the reason goes next to the tool result. */
12
+ export interface BlockOutput {
13
+ readonly decision: "block";
14
+ readonly reason: string;
15
+ }
16
+
17
+ /** The line after the findings: what happened to the edit, and what the findings are. */
18
+ const KEPT =
19
+ "paperlint lint-edited: the edit was kept; the errors above are the ones it introduced.";
20
+
21
+ const whyOf = (r: Readonly<PromiseRejectedResult>): unknown => r.reason;
22
+
23
+ /** Each paper's formatted report ("" for none) or its failure, in the order of `dirs`. */
24
+ export function blockOf(
25
+ outcomes: readonly PromiseSettledResult<string>[],
26
+ dirs: readonly string[],
27
+ ): BlockOutput | null {
28
+ const reports = outcomes.flatMap((r) =>
29
+ r.status === "fulfilled" && r.value !== "" ? [r.value] : [],
30
+ );
31
+ const failed = zip(outcomes, dirs).flatMap(([r, dir]) =>
32
+ r.status === "rejected" ? [{ dir, why: whyOf(r) }] : [],
33
+ );
34
+ if (reports.length === 0 && failed[0] !== undefined) throw failed[0].why;
35
+ if (reports.length === 0) return null;
36
+ const notLinted = failed.map(({ dir, why }) => {
37
+ const [first] = messageOf(why).split("\n");
38
+ return `paperlint lint-edited: ${dir} was not linted: ${String(first)}`;
39
+ });
40
+ return {
41
+ decision: "block",
42
+ reason: `${[...reports, ...notLinted].join("\n")}\n${KEPT}`,
43
+ };
44
+ }
@@ -73,6 +73,9 @@ function linterOf(
73
73
  return { linter, asked };
74
74
  }
75
75
 
76
+ /** No Edit or Write payload reaches the shell parser. */
77
+ const shellLeaves = () => [];
78
+
76
79
  const edit = (file: string, newString: string) => ({
77
80
  tool_name: "Edit",
78
81
  tool_input: { file_path: file, old_string: "x", new_string: newString },
@@ -93,6 +96,7 @@ const run = (
93
96
  expect(dir).toBe(DIR);
94
97
  return Promise.resolve(linter);
95
98
  },
99
+ shellLeaves,
96
100
  }),
97
101
  };
98
102
  };
@@ -468,12 +472,10 @@ describe("lint-edited — quiet", () => {
468
472
  });
469
473
 
470
474
  it("outside every paper, or no path in the payload: the linter is never built", async () => {
471
- const files = memoryFiles(PAPER);
472
475
  const never = () => Promise.reject(new Error("built a linter"));
473
- expect(
474
- await lintEdited(edit("/work/README.md", "x"), { files, linter: never }),
475
- ).toBeNull();
476
- expect(await lintEdited({}, { files, linter: never })).toBeNull();
476
+ const deps = { files: memoryFiles(PAPER), linter: never, shellLeaves };
477
+ expect(await lintEdited(edit("/work/README.md", "x"), deps)).toBeNull();
478
+ expect(await lintEdited({}, deps)).toBeNull();
477
479
  });
478
480
  });
479
481
 
@@ -482,7 +484,7 @@ const hook = async (stdin: () => string, linter: () => Promise<never>) => {
482
484
  const err: string[] = [];
483
485
  const code = await lintEditedHook(
484
486
  stdin,
485
- { files: memoryFiles({ ...PAPER, [MAIN]: "x\n" }), linter },
487
+ { files: memoryFiles({ ...PAPER, [MAIN]: "x\n" }), linter, shellLeaves },
486
488
  { out: (t) => out.push(t), err: (m) => err.push(m) },
487
489
  );
488
490
  return { code, out, err };
@@ -530,14 +532,11 @@ describe("lint-edited — never in the way: the block", () => {
530
532
  const out: string[] = [];
531
533
  const { linter } = linterOf({ [MAIN]: [finding(1)] });
532
534
  const code = await lintEditedHook(
533
- () =>
534
- JSON.stringify({
535
- tool_name: "Write",
536
- tool_input: { file_path: MAIN, content: "x\n" },
537
- }),
535
+ () => JSON.stringify(edit(MAIN, "x\n")),
538
536
  {
539
537
  files: memoryFiles({ ...PAPER, [MAIN]: "x\n" }),
540
538
  linter: () => Promise.resolve(linter),
539
+ shellLeaves,
541
540
  },
542
541
  { out: (t) => out.push(t), err: () => {} },
543
542
  );
@@ -7,7 +7,11 @@
7
7
  * instead of at the next lint, or in CI.
8
8
  *
9
9
  * ── WHAT IT LINTS ────────────────────────────────────────────────────────────────
10
- * The edited file and the paper's `paper.tex`, with the ESLint `paperlint lint` builds for that paper
10
+ * The edited file and the paper's `paper.tex`. After a Bash command (PostToolUse on `Bash`, wired with
11
+ * `"if": "Bash(*.tex*)"`, so Claude Code does not even start the hook for a command that names no
12
+ * `.tex`): every `.tex` file the command names, as a word or as the target of a redirection that
13
+ * writes, read by vigiles' shell parser and resolved against the payload's `cwd`, grouped by paper. Each
14
+ * paper is linted with the ESLint `paperlint lint` builds for that paper
11
15
  * (`paperEslint`, src/cli.ts — one function for both, so the two cannot drift): the same config, the
12
16
  * same rules, the same body files from `_build/sources.json`. Whether the edited file is one paperlint
13
17
  * lints is ESLint's own answer (`isPathIgnored` on that config), not a second list of patterns: a
@@ -25,8 +29,13 @@
25
29
  * `_build/` is gitignored and allowed by the layout.
26
30
  *
27
31
  * ── WHAT IT CANNOT SEE ───────────────────────────────────────────────────────────
28
- * - A file written by a shell command (`sed -i`, a script, `mv`): no Edit or Write, no hook. The
29
- * guarantee stays `paperlint lint` in CI.
32
+ * - A shell command whose `.tex` is not one of its words: a path inside an interpreter's code
33
+ * (`python3 -c "open('p.tex')…"`), a relative path after a `cd` in the same command, a word built at
34
+ * run time. And a write by redirection alone (`cat > paper.tex <<EOF`): Claude Code 2.1.330 leaves
35
+ * the redirection's target out of the text the `if` matches, so the hook never starts (measured,
36
+ * zernie/vigiles#214). The guarantee stays `paperlint lint` in CI.
37
+ * - The lines a shell command wrote: it has no patch, so in a file the snapshot has not seen it
38
+ * reports nothing, and only writes the snapshot the next change is judged against.
30
39
  * - The body files of a paper whose build record is stale: `_build/sources.json` hashes every file TeX
31
40
  * read, so the first edit to any of them makes the record stale, and from then until the next
32
41
  * `paperlint build` the paper is `paper.tex` alone — to the hook exactly as to `paperlint lint`. A
@@ -51,6 +60,8 @@ import { SOURCES_DIR } from "./domain/sources-record.ts";
51
60
  import { fieldOf } from "./domain/record.ts";
52
61
  import { messageOf } from "./domain/text.ts";
53
62
  import type { Files } from "./ports/files.ts";
63
+ import { shellPapers, type ShellLeaf } from "./lint-edited-shell.ts";
64
+ import { blockOf, type BlockOutput } from "./lint-edited-block.ts";
54
65
 
55
66
  /** The snapshot, relative to the paper folder. */
56
67
  export const SNAPSHOT_FILE = `${SOURCES_DIR}/edit-lint.json`;
@@ -87,18 +98,10 @@ export interface LintEditedDeps {
87
98
  readonly files: Files;
88
99
  /** The engine for the paper in `paperDir`; it throws when the paper's config does not read. */
89
100
  readonly linter: (paperDir: string) => Promise<PaperLinter>;
101
+ /** Every simple command of a Bash command line; none when it does not parse. */
102
+ readonly shellLeaves: (command: string) => readonly ShellLeaf[];
90
103
  }
91
104
 
92
- /** What Claude Code reads from a PostToolUse hook's stdout: the reason goes next to the tool result. */
93
- export interface BlockOutput {
94
- readonly decision: "block";
95
- readonly reason: string;
96
- }
97
-
98
- /** The line after the findings: what happened to the edit, and what the findings are. */
99
- const KEPT =
100
- "paperlint lint-edited: the edit was kept; the errors above are the ones it introduced.";
101
-
102
105
  /** One error as the snapshot holds it: no line number, the text of its line instead. */
103
106
  const Entry = z.object({
104
107
  rule: z.string().nullable(),
@@ -273,7 +276,7 @@ function newAgainst(
273
276
  function introducedBy(
274
277
  now: readonly FileErrors[],
275
278
  before: Snapshot,
276
- edited: { readonly file: string; readonly lines: readonly Lines[] },
279
+ linesOf: (file: string) => readonly Lines[],
277
280
  ): readonly LintResult[] {
278
281
  return now
279
282
  .map((f) => {
@@ -284,9 +287,7 @@ function introducedBy(
284
287
  seen === undefined
285
288
  ? f.errors
286
289
  .map((e) => e.message)
287
- .filter(
288
- (m) => f.file === edited.file && touches(m, edited.lines),
289
- )
290
+ .filter((m) => touches(m, linesOf(f.file)))
290
291
  : newAgainst(f.errors, seen),
291
292
  };
292
293
  })
@@ -306,29 +307,65 @@ const nextSnapshot = (
306
307
  },
307
308
  });
308
309
 
309
- /** The hook: the payload of an Edit or a Write in, Claude Code's block out, or null to say nothing. */
310
- export async function lintEdited(
311
- payload: unknown,
312
- deps: LintEditedDeps,
313
- ): Promise<BlockOutput | null> {
310
+ /** What one tool call wrote in one paper: the files, and the lines of each it says it wrote. */
311
+ interface Written {
312
+ readonly dir: string;
313
+ readonly files: readonly string[];
314
+ readonly lines: (file: string, text: string) => readonly Lines[];
315
+ }
316
+
317
+ /** The file an Edit or a Write names, in its paper, with the lines it wrote. */
318
+ function editWritten(payload: unknown, files: Files): readonly Written[] {
314
319
  const file = writtenPath(payload);
315
- const dir = file === null ? null : paperFolderOf(file, deps.files);
316
- if (file === null || dir === null) return null;
317
- const linter = await deps.linter(dir);
318
- if (!(await linter.isLinted(file))) return null;
319
- const main = join(dir, MAIN);
320
+ const dir = file === null ? null : paperFolderOf(file, files);
321
+ return file === null || dir === null
322
+ ? []
323
+ : [{ dir, files: [file], lines: (_, text) => writtenLines(payload, text) }];
324
+ }
325
+
326
+ /** One paper linted for what a tool call wrote in it: the errors it introduced, as the engine prints them ("" for none). */
327
+ async function introducedIn(w: Written, deps: LintEditedDeps): Promise<string> {
328
+ const linter = await deps.linter(w.dir);
329
+ const asked = await Promise.all(
330
+ w.files.map(async (f) => ((await linter.isLinted(f)) ? [f] : [])),
331
+ );
332
+ const linted = asked.flat();
333
+ if (linted.length === 0) return "";
334
+ const main = join(w.dir, MAIN);
320
335
  const has = deps.files.isFile(callerPath(main));
321
- const results = await linter.lint(unique([file, ...(has ? [main] : [])]));
322
- const snapshot = callerPath(join(dir, SNAPSHOT_FILE));
336
+ const results = await linter.lint(
337
+ unique([...linted, ...(has ? [main] : [])]),
338
+ );
339
+ const snapshot = callerPath(join(w.dir, SNAPSHOT_FILE));
323
340
  const before = readSnapshot(deps.files, snapshot);
324
- const now = results.map((r) => errorsOf(r, dir, deps.files));
325
- const lines = writtenLines(payload, textOf(deps.files, file) ?? "");
326
- const shown = introducedBy(now, before, { file, lines });
341
+ const now = results.map((r) => errorsOf(r, w.dir, deps.files));
342
+ const shown = introducedBy(now, before, (file) =>
343
+ linted.includes(file) ? w.lines(file, textOf(deps.files, file) ?? "") : [],
344
+ );
327
345
  const next = JSON.stringify(nextSnapshot(before, now), null, 1);
328
346
  deps.files.writeAtomic(snapshot, new TextEncoder().encode(`${next}\n`));
329
- if (shown.length === 0) return null;
330
- const report = (await linter.format(shown)).trim();
331
- return { decision: "block", reason: `${report}\n${KEPT}` };
347
+ return shown.length === 0 ? "" : (await linter.format(shown)).trim();
348
+ }
349
+
350
+ /** The hook: the payload of an Edit, a Write or a Bash command in, Claude Code's block out, or null. */
351
+ export async function lintEdited(
352
+ payload: unknown,
353
+ deps: LintEditedDeps,
354
+ ): Promise<BlockOutput | null> {
355
+ const written =
356
+ fieldOf(payload, "tool_name") === "Bash"
357
+ ? shellPapers(payload, deps.files, deps.shellLeaves).map((p) => ({
358
+ ...p,
359
+ lines: () => [],
360
+ }))
361
+ : editWritten(payload, deps.files);
362
+ const each = await Promise.allSettled(
363
+ written.map((w) => introducedIn(w, deps)),
364
+ );
365
+ return blockOf(
366
+ each,
367
+ written.map((w) => w.dir),
368
+ );
332
369
  }
333
370
 
334
371
  /**
@@ -0,0 +1,72 @@
1
+ /**
2
+ * Which paper files a Bash command wrote, as far as its words say: the half of the `lint-edited`
3
+ * hook (`src/lint-edited-hook.ts`) that reads a shell command instead of an Edit's `file_path`.
4
+ *
5
+ * The wiring starts the hook only for a command that names a `.tex` (`"if": "Bash(*.tex*)"` in
6
+ * `plugin/hooks/hooks.json`, written by hand until zernie/vigiles#496 lets a compiled hook declare
7
+ * it). The command is read by vigiles' shell parser, handed in as `leaves` (vigiles is a tool
8
+ * package: only `src/cli.ts` imports it), never by a pattern over its text: every `.tex` that is a word
9
+ * of a simple command, or the target of a redirection that writes, resolved against the payload's
10
+ * `cwd`. A file that does not exist, or is in no paper, is dropped. A command says no line it wrote.
11
+ */
12
+ import { isAbsolute, resolve } from "node:path";
13
+ import { groupBy, unique } from "remeda";
14
+ import { callerPath } from "./caller-path.ts";
15
+ import { paperFolderOf } from "./domain/paper-folder.ts";
16
+ import { fieldOf } from "./domain/record.ts";
17
+ import type { Files } from "./ports/files.ts";
18
+
19
+ /** One simple command as the shell reads it: what this module reads of vigiles' `NormalizedLeaf`. */
20
+ export interface ShellLeaf {
21
+ readonly args: readonly string[];
22
+ readonly redirects: readonly {
23
+ readonly target: string | null;
24
+ readonly writes: boolean;
25
+ }[];
26
+ }
27
+
28
+ /** The extension of the files a command is read for; the wiring's `if` names the same. */
29
+ const TEX = ".tex";
30
+
31
+ /** Every word of `leaves` and every target they write by redirection. */
32
+ const wordsOf = (leaves: readonly ShellLeaf[]): readonly string[] =>
33
+ leaves.flatMap((l) => [
34
+ ...l.args,
35
+ ...l.redirects.flatMap((r) =>
36
+ r.writes && r.target !== null ? [r.target] : [],
37
+ ),
38
+ ]);
39
+
40
+ /** The `.tex` files the command in `payload` names, absolute; none without a command or an absolute cwd. */
41
+ function namedTex(
42
+ payload: unknown,
43
+ leaves: (command: string) => readonly ShellLeaf[],
44
+ ): readonly string[] {
45
+ const command = fieldOf(fieldOf(payload, "tool_input"), "command");
46
+ const cwd = fieldOf(payload, "cwd");
47
+ if (typeof command !== "string" || typeof cwd !== "string") return [];
48
+ if (!isAbsolute(cwd)) return [];
49
+ return unique(
50
+ wordsOf(leaves(command))
51
+ .filter((w) => w.endsWith(TEX))
52
+ .map((w) => resolve(cwd, w)),
53
+ );
54
+ }
55
+
56
+ /** The papers a Bash command wrote in, each with the existing `.tex` files it names there. */
57
+ export function shellPapers(
58
+ payload: unknown,
59
+ files: Files,
60
+ leaves: (command: string) => readonly ShellLeaf[],
61
+ ): readonly { readonly dir: string; readonly files: readonly string[] }[] {
62
+ const placed = namedTex(payload, leaves).flatMap((file) => {
63
+ const dir = files.isFile(callerPath(file))
64
+ ? paperFolderOf(file, files)
65
+ : null;
66
+ return dir === null ? [] : [{ dir, file }];
67
+ });
68
+ return Object.entries(groupBy(placed, (p) => p.dir)).map(([dir, ps]) => ({
69
+ dir,
70
+ files: ps.map((p) => p.file),
71
+ }));
72
+ }