paperlint 18.6.0 → 18.8.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 (165) hide show
  1. package/.claude-plugin/marketplace.json +11 -0
  2. package/.claude-plugin/plugin.json +7 -0
  3. package/CLAUDE.md +3 -3
  4. package/CONTRIBUTING.md +5 -2
  5. package/README.md +6 -6
  6. package/dist/adapters/clack/index.d.ts +3 -0
  7. package/dist/adapters/clack/index.d.ts.map +1 -0
  8. package/dist/adapters/clack/index.js +3 -0
  9. package/dist/adapters/clack/index.js.map +1 -0
  10. package/dist/adapters/clack/prompts.io.d.ts +8 -0
  11. package/dist/adapters/clack/prompts.io.d.ts.map +1 -0
  12. package/dist/adapters/clack/prompts.io.js +20 -0
  13. package/dist/adapters/clack/prompts.io.js.map +1 -0
  14. package/dist/adapters/claude-code/claude.io.d.ts +13 -0
  15. package/dist/adapters/claude-code/claude.io.d.ts.map +1 -0
  16. package/dist/adapters/claude-code/claude.io.js +68 -0
  17. package/dist/adapters/claude-code/claude.io.js.map +1 -0
  18. package/dist/adapters/claude-code/index.d.ts +4 -0
  19. package/dist/adapters/claude-code/index.d.ts.map +1 -0
  20. package/dist/adapters/claude-code/index.js +4 -0
  21. package/dist/adapters/claude-code/index.js.map +1 -0
  22. package/dist/adapters/claude-code/plugin.d.ts +19 -0
  23. package/dist/adapters/claude-code/plugin.d.ts.map +1 -0
  24. package/dist/adapters/claude-code/plugin.js +66 -0
  25. package/dist/adapters/claude-code/plugin.js.map +1 -0
  26. package/dist/adapters/package-manager/index.d.ts +4 -0
  27. package/dist/adapters/package-manager/index.d.ts.map +1 -0
  28. package/dist/adapters/package-manager/index.js +4 -0
  29. package/dist/adapters/package-manager/index.js.map +1 -0
  30. package/dist/adapters/package-manager/install.io.d.ts +3 -0
  31. package/dist/adapters/package-manager/install.io.d.ts.map +1 -0
  32. package/dist/adapters/package-manager/install.io.js +23 -0
  33. package/dist/adapters/package-manager/install.io.js.map +1 -0
  34. package/dist/adapters/package-manager/manager.d.ts +13 -0
  35. package/dist/adapters/package-manager/manager.d.ts.map +1 -0
  36. package/dist/adapters/package-manager/manager.js +22 -0
  37. package/dist/adapters/package-manager/manager.js.map +1 -0
  38. package/dist/adapters/study-registry/index.d.ts +2 -2
  39. package/dist/cli.d.ts +9 -1
  40. package/dist/cli.d.ts.map +1 -1
  41. package/dist/cli.js +73 -13
  42. package/dist/cli.js.map +1 -1
  43. package/dist/doctor-plugin.d.ts +23 -0
  44. package/dist/doctor-plugin.d.ts.map +1 -0
  45. package/dist/doctor-plugin.js +56 -0
  46. package/dist/doctor-plugin.js.map +1 -0
  47. package/dist/doctor.d.ts +6 -1
  48. package/dist/doctor.d.ts.map +1 -1
  49. package/dist/doctor.js +69 -26
  50. package/dist/doctor.js.map +1 -1
  51. package/dist/hooks-settings.d.ts +18 -0
  52. package/dist/hooks-settings.d.ts.map +1 -1
  53. package/dist/hooks-settings.js +25 -0
  54. package/dist/hooks-settings.js.map +1 -1
  55. package/dist/init.d.ts +47 -16
  56. package/dist/init.d.ts.map +1 -1
  57. package/dist/init.js +231 -86
  58. package/dist/init.js.map +1 -1
  59. package/dist/link-skills.d.ts +15 -0
  60. package/dist/link-skills.d.ts.map +1 -1
  61. package/dist/link-skills.js +18 -1
  62. package/dist/link-skills.js.map +1 -1
  63. package/dist/plugin-offer.d.ts +73 -0
  64. package/dist/plugin-offer.d.ts.map +1 -0
  65. package/dist/plugin-offer.js +96 -0
  66. package/dist/plugin-offer.js.map +1 -0
  67. package/dist/ports/claude-code.d.ts +31 -0
  68. package/dist/ports/claude-code.d.ts.map +1 -0
  69. package/dist/ports/claude-code.js +2 -0
  70. package/dist/ports/claude-code.js.map +1 -0
  71. package/dist/ports/project-install.d.ts +19 -0
  72. package/dist/ports/project-install.d.ts.map +1 -0
  73. package/dist/ports/project-install.js +2 -0
  74. package/dist/ports/project-install.js.map +1 -0
  75. package/dist/ports/prompts.d.ts +31 -0
  76. package/dist/ports/prompts.d.ts.map +1 -0
  77. package/dist/ports/prompts.js +2 -0
  78. package/dist/ports/prompts.js.map +1 -0
  79. package/dist/self-install.d.ts +65 -0
  80. package/dist/self-install.d.ts.map +1 -0
  81. package/dist/self-install.js +145 -0
  82. package/dist/self-install.js.map +1 -0
  83. package/dist/skill-chunks/chunk-65X5HVIJ.js +26462 -0
  84. package/dist/skill-chunks/chunk-6NU6CXUS.js +258 -0
  85. package/dist/skill-chunks/chunk-GRSXIWYF.js +352 -0
  86. package/dist/skill-chunks/chunk-IREAROCV.js +84 -0
  87. package/dist/skill-chunks/chunk-KWK6RT4T.js +24267 -0
  88. package/dist/skill-chunks/chunk-NPQVDEE4.js +19681 -0
  89. package/dist/skill-chunks/chunk-PJ4KNV4J.js +45 -0
  90. package/dist/skill-chunks/dist-UPCJMLBM.js +385 -0
  91. package/dist/skill-chunks/pdfjs-LUMEFOH2.js +39518 -0
  92. package/dist/types.d.ts +4 -0
  93. package/dist/types.d.ts.map +1 -1
  94. package/docs/e2e.md +10 -0
  95. package/docs/install.md +88 -29
  96. package/docs/prior-art/README.md +2 -0
  97. package/docs/prior-art/one-command-install.md +33 -0
  98. package/docs/prior-art/prompt-libraries.md +32 -0
  99. package/eslint.config.mjs +1 -0
  100. package/hooks/CLAUDE.md +2 -2
  101. package/hooks/CLAUDE.md.spec.ts +1 -1
  102. package/lib/skill-checks.mjs +13 -6
  103. package/lib/skill-checks.test.mjs +28 -15
  104. package/lib/skill-corpus.mjs +5 -2
  105. package/package.json +8 -3
  106. package/plugin/CLAUDE.md +22 -14
  107. package/plugin/CLAUDE.md.spec.ts +20 -12
  108. package/scripts/bundle-skills.test.ts +226 -0
  109. package/scripts/bundle-skills.ts +304 -0
  110. package/scripts/plugin-version.test.ts +80 -0
  111. package/scripts/plugin-version.ts +58 -0
  112. package/skills/CLAUDE.md +2 -2
  113. package/skills/CLAUDE.md.spec.ts +1 -1
  114. package/skills/argument-arc/SKILL.md +2 -2
  115. package/skills/argument-arc/SKILL.md.spec.ts +1 -1
  116. package/skills/argument-arc/scripts/headings.js +57 -13
  117. package/skills/build-label-page/scripts/label-page.js +2005 -93
  118. package/skills/cold-read-diff/scripts/cold-read.js +221 -14
  119. package/skills/label-agent-runs/scripts/labels.js +272 -348
  120. package/skills/paper-pipeline/references/anonymization.md +4 -3
  121. package/skills/paper-pipeline/scripts/extract-ref-facts.js +304 -0
  122. package/skills/pc-panel-review/scripts/prior-reviews.js +7244 -12
  123. package/skills/run-agent-grid/scripts/grid-guard.js +562 -627
  124. package/skills/submit-paper/SKILL.md +5 -4
  125. package/skills/submit-paper/SKILL.md.spec.ts +4 -3
  126. package/skills/submit-paper/check-deanon.sh +17 -2
  127. package/skills/submit-paper/check-deanon.test.ts +141 -0
  128. package/skills/verify-citations/SKILL.md +9 -9
  129. package/skills/verify-citations/SKILL.md.spec.ts +8 -8
  130. package/skills/verify-citations/scripts/bib-authors.js +228 -0
  131. package/skills/verify-citations/scripts/verify-cites.js +816 -0
  132. package/src/adapters/clack/index.ts +2 -0
  133. package/src/adapters/clack/prompts.io.ts +35 -0
  134. package/src/adapters/clack/prompts.test.ts +58 -0
  135. package/src/adapters/claude-code/claude.io.ts +103 -0
  136. package/src/adapters/claude-code/index.test.ts +233 -0
  137. package/src/adapters/claude-code/index.ts +11 -0
  138. package/src/adapters/claude-code/plugin.ts +82 -0
  139. package/src/adapters/package-manager/index.test.ts +67 -0
  140. package/src/adapters/package-manager/index.ts +3 -0
  141. package/src/adapters/package-manager/install.io.ts +27 -0
  142. package/src/adapters/package-manager/manager.ts +33 -0
  143. package/src/cli.harness.mjs +47 -26
  144. package/src/cli.test.ts +179 -2
  145. package/src/cli.ts +130 -10
  146. package/src/doctor-plugin.test.ts +103 -0
  147. package/src/doctor-plugin.ts +83 -0
  148. package/src/doctor.test.ts +111 -2
  149. package/src/doctor.ts +83 -32
  150. package/src/hooks-notice.test.ts +82 -0
  151. package/src/hooks-settings.ts +49 -0
  152. package/src/init-plugin.test.ts +178 -0
  153. package/src/init.test.ts +138 -27
  154. package/src/init.ts +341 -124
  155. package/src/link-skills.test.ts +34 -1
  156. package/src/link-skills.ts +34 -0
  157. package/src/parse-args.test.ts +2 -0
  158. package/src/plugin-offer.test.ts +276 -0
  159. package/src/plugin-offer.ts +160 -0
  160. package/src/ports/claude-code.ts +30 -0
  161. package/src/ports/project-install.ts +18 -0
  162. package/src/ports/prompts.ts +27 -0
  163. package/src/self-install.test.ts +267 -0
  164. package/src/self-install.ts +224 -0
  165. package/src/types.ts +4 -0
@@ -1,700 +1,635 @@
1
1
  #!/usr/bin/env node
2
- /**
3
- * grid-guard — the checks of the run-agent-grid skill that a driver or a commit hook calls, so
4
- * that a rule of the skill is a refusal and not a sentence.
5
- *
6
- * lock <root> --owner <id> [--pid <pid>] [--attached]
7
- * take the lock on a working-copy root; the holder
8
- * must be detached (its own session) unless --attached
9
- * release <root> --owner <id> give it back
10
- * gate --registry <f> --ledger <f> --unit <u> --arm <a> --model <m> --seed <s>
11
- * --attempt <id> [--reserve-sec <n>] may this cell run now? If so it is RESERVED for
12
- * <id> in the ledger, atomically, until the attempt's
13
- * end record or n seconds (default 6 h)
14
- * overlap <ledger> attempts that shared a root at the same time
15
- * env-probe [--allow <NAME>]... [--git] secret-named variables, and whether git still works
16
- * scan-keys <path>... key-shaped strings in files on disk
17
- * precommit [--runs <dir>] [--done <file>] the same scan over the staged files, and staged run
18
- * folders that have no completion record
19
- *
20
- * EXIT CODES — a driver branches on them:
21
- * 0 allowed, clean, done 1 refused, or a finding 2 usage
22
- * 3 (gate) the cell is already counted: skip it, do not run it again
23
- *
24
- * TypeScript, compiled beside itself to `grid-guard.js` by `npm run build`: a consumer runs the
25
- * skill from `node_modules`, where Node does not strip types. The skill names the `.js`.
26
- *
27
- * A value that looks like a key is NEVER printed, not even in part: the output of this script
28
- * goes into logs and transcripts, which are exactly where a leaked key gets committed.
29
- */
2
+ import { createRequire as __plCreateRequire } from "node:module";
3
+ import { fileURLToPath as __plFileURLToPath } from "node:url";
4
+ import { dirname as __plDirname } from "node:path";
5
+ const require = __plCreateRequire(import.meta.url);
6
+ const __filename = __plFileURLToPath(import.meta.url);
7
+ const __dirname = __plDirname(__filename);
8
+ import {
9
+ external_exports
10
+ } from "../../../dist/skill-chunks/chunk-NPQVDEE4.js";
11
+ import "../../../dist/skill-chunks/chunk-PJ4KNV4J.js";
12
+
13
+ // skills/run-agent-grid/scripts/grid-guard.ts
30
14
  import { spawnSync } from "node:child_process";
31
- import { appendFileSync, existsSync, mkdtempSync, readFileSync, readdirSync, realpathSync, rmSync, statSync, writeFileSync, } from "node:fs";
15
+ import {
16
+ appendFileSync,
17
+ existsSync,
18
+ mkdtempSync,
19
+ readFileSync,
20
+ readdirSync,
21
+ realpathSync,
22
+ rmSync,
23
+ statSync,
24
+ writeFileSync
25
+ } from "node:fs";
32
26
  import { hostname, tmpdir } from "node:os";
33
27
  import { dirname, join, relative, resolve, sep } from "node:path";
34
28
  import { parseArgs } from "node:util";
35
- import { z } from "zod";
36
- import { COMMANDS } from "./grid-guard-commands.js";
37
- class Refusal extends Error {
38
- exitCode;
39
- constructor(exitCode, message) {
40
- super(message);
41
- this.exitCode = exitCode;
42
- }
43
- }
44
- const refuse = (exitCode, message) => {
45
- throw new Refusal(exitCode, message);
29
+
30
+ // skills/run-agent-grid/scripts/grid-guard-commands.ts
31
+ var COMMANDS = {
32
+ lock: "lock",
33
+ release: "release",
34
+ gate: "gate",
35
+ overlap: "overlap",
36
+ envProbe: "env-probe",
37
+ scanKeys: "scan-keys",
38
+ precommit: "precommit"
39
+ };
40
+
41
+ // skills/run-agent-grid/scripts/grid-guard.ts
42
+ var Refusal = class extends Error {
43
+ exitCode;
44
+ constructor(exitCode, message) {
45
+ super(message);
46
+ this.exitCode = exitCode;
47
+ }
46
48
  };
47
- const say = (line) => {
48
- process.stdout.write(`${line}\n`);
49
+ var refuse = (exitCode, message) => {
50
+ throw new Refusal(exitCode, message);
49
51
  };
50
- /** A property of a thrown value, whatever was thrown. */
51
- const prop = (e, key) => Reflect.get(Object(e), key);
52
- // ── lock / release ──────────────────────────────────────────────────────────────────────────
53
- // The lock sits BESIDE the root, not inside it: a driver that deletes the root's tree must not
54
- // delete the lock that was supposed to stop it.
55
- const Lock = z.object({
56
- owner: z.string(),
57
- pid: z.number(),
58
- host: z.string(),
59
- at: z.string(),
52
+ var say = (line) => {
53
+ process.stdout.write(`${line}
54
+ `);
55
+ };
56
+ var prop = (e, key) => Reflect.get(Object(e), key);
57
+ var Lock = external_exports.object({
58
+ owner: external_exports.string(),
59
+ pid: external_exports.number(),
60
+ host: external_exports.string(),
61
+ at: external_exports.string()
60
62
  });
61
- const lockPath = (root) => `${resolve(root)}.lock`;
62
- const readLock = (path) => Lock.parse(JSON.parse(readFileSync(path, "utf8")));
63
- /** Is `pid` a live process on this host? EPERM means it exists and belongs to someone else. */
64
- const alive = (pid) => {
65
- try {
66
- process.kill(pid, 0);
67
- return true;
68
- }
69
- catch (e) {
70
- return prop(e, "code") !== "ESRCH";
71
- }
63
+ var lockPath = (root) => `${resolve(root)}.lock`;
64
+ var readLock = (path) => Lock.parse(JSON.parse(readFileSync(path, "utf8")));
65
+ var alive = (pid) => {
66
+ try {
67
+ process.kill(pid, 0);
68
+ return true;
69
+ } catch (e) {
70
+ return prop(e, "code") !== "ESRCH";
71
+ }
72
72
  };
73
- /** Create the lock file; false when someone holds it already. */
74
73
  function take(path, me) {
75
- try {
76
- writeFileSync(path, `${JSON.stringify(me)}\n`, { flag: "wx" });
77
- return true;
78
- }
79
- catch (e) {
80
- if (prop(e, "code") === "EEXIST")
81
- return false;
82
- throw e;
83
- }
74
+ try {
75
+ writeFileSync(path, `${JSON.stringify(me)}
76
+ `, { flag: "wx" });
77
+ return true;
78
+ } catch (e) {
79
+ if (prop(e, "code") === "EEXIST") return false;
80
+ throw e;
81
+ }
84
82
  }
85
- // ── detached? ───────────────────────────────────────────────────────────────────────────────
86
- // A driver started as a task the agent session tracks dies with the session (its time cap). Only
87
- // a process in a session of its own survives that: `setsid` makes it the session leader, so its
88
- // session id equals its pid. `GRID_GUARD_PROC` stands in for `/proc` in tests.
89
- const procRoot = () => process.env.GRID_GUARD_PROC ?? "/proc";
90
- /** The session id of `pid` from `/proc/<pid>/stat` (field 6), or null where that cannot be read. */
83
+ var procRoot = () => process.env.GRID_GUARD_PROC ?? "/proc";
91
84
  function sessionOf(pid) {
92
- const stat = join(procRoot(), String(pid), "stat");
93
- if (!existsSync(stat))
94
- return null;
95
- // The command name (field 2) is in parentheses and may hold spaces or parentheses itself.
96
- const text = readFileSync(stat, "utf8");
97
- const after = text.slice(text.lastIndexOf(")") + 2);
98
- return Number(after.split(" ")[3]);
85
+ const stat = join(procRoot(), String(pid), "stat");
86
+ if (!existsSync(stat)) return null;
87
+ const text = readFileSync(stat, "utf8");
88
+ const after = text.slice(text.lastIndexOf(")") + 2);
89
+ return Number(after.split(" ")[3]);
99
90
  }
100
- /**
101
- * Why `pid` may not hold a grid lock, or null. Liveness is asked of the kernel (`kill(pid, 0)`),
102
- * which every platform answers; only the session check needs `/proc`, and where it cannot be read
103
- * (macOS, a hidden `/proc`) it warns and passes.
104
- */
105
91
  function detachProblem(pid) {
106
- if (!alive(pid))
107
- return `pid ${String(pid)} is not a live process`;
108
- const sid = sessionOf(pid);
109
- if (sid === null) {
110
- process.stderr.write(`grid-guard: warning: cannot read ${join(procRoot(), String(pid), "stat")} here, so whether pid ${String(pid)} is detached is not checked\n`);
111
- return null;
112
- }
113
- return sid === pid
114
- ? null
115
- : `pid ${String(pid)} is not detached (it runs in session ${String(sid)}), so it dies with the ` +
116
- `session that started it. Start the driver as \`setsid nohup <driver> > driver.log 2>&1 &\` ` +
117
- `and lock with --pid $$ inside it, or pass --attached for a short run.`;
92
+ if (!alive(pid)) return `pid ${String(pid)} is not a live process`;
93
+ const sid = sessionOf(pid);
94
+ if (sid === null) {
95
+ process.stderr.write(
96
+ `grid-guard: warning: cannot read ${join(procRoot(), String(pid), "stat")} here, so whether pid ${String(pid)} is detached is not checked
97
+ `
98
+ );
99
+ return null;
100
+ }
101
+ return sid === pid ? null : `pid ${String(pid)} is not detached (it runs in session ${String(sid)}), so it dies with the session that started it. Start the driver as \`setsid nohup <driver> > driver.log 2>&1 &\` and lock with --pid $$ inside it, or pass --attached for a short run.`;
118
102
  }
119
103
  function lock(root, owner, pid, attached) {
120
- const path = lockPath(root);
121
- const me = {
122
- owner,
123
- pid: Number(pid ?? process.ppid),
124
- host: hostname(),
125
- at: new Date().toISOString(),
126
- };
127
- const notDetached = attached ? null : detachProblem(me.pid);
128
- if (notDetached !== null)
129
- refuse(1, notDetached);
130
- if (take(path, me)) {
131
- say(`locked ${path} for ${me.owner} (pid ${String(me.pid)})`);
132
- return;
133
- }
134
- const held = readLock(path);
135
- if (takeOverStale(path, me, held))
136
- return;
137
- refuse(1, `${path} is held by ${held.owner} (pid ${String(held.pid)} on ${held.host} since ${held.at}). ` +
138
- `Wait for it, or give this driver its own working-copy root.`);
104
+ const path = lockPath(root);
105
+ const me = {
106
+ owner,
107
+ pid: Number(pid ?? process.ppid),
108
+ host: hostname(),
109
+ at: (/* @__PURE__ */ new Date()).toISOString()
110
+ };
111
+ const notDetached = attached ? null : detachProblem(me.pid);
112
+ if (notDetached !== null) refuse(1, notDetached);
113
+ if (take(path, me)) {
114
+ say(`locked ${path} for ${me.owner} (pid ${String(me.pid)})`);
115
+ return;
116
+ }
117
+ const held = readLock(path);
118
+ if (takeOverStale(path, me, held)) return;
119
+ refuse(
120
+ 1,
121
+ `${path} is held by ${held.owner} (pid ${String(held.pid)} on ${held.host} since ${held.at}). Wait for it, or give this driver its own working-copy root.`
122
+ );
139
123
  }
140
- /**
141
- * Take the lock from a holder that is provably gone: same host, and its process is dead. A lock
142
- * from another host cannot be judged from here, so it is never taken over.
143
- */
144
124
  function takeOverStale(path, me, held) {
145
- const stale = held.host === me.host && !alive(held.pid);
146
- if (stale)
147
- rmSync(path, { force: true });
148
- if (!(stale && take(path, me)))
149
- return false;
150
- say(`took over a stale lock on ${path} (holder ${held.owner}, pid ${String(held.pid)}, is gone)`);
151
- return true;
125
+ const stale = held.host === me.host && !alive(held.pid);
126
+ if (stale) rmSync(path, { force: true });
127
+ if (!(stale && take(path, me))) return false;
128
+ say(
129
+ `took over a stale lock on ${path} (holder ${held.owner}, pid ${String(held.pid)}, is gone)`
130
+ );
131
+ return true;
152
132
  }
153
133
  function release(root, owner) {
154
- const path = lockPath(root);
155
- if (!existsSync(path))
156
- refuse(1, `${path} is not held`);
157
- const held = readLock(path);
158
- if (held.owner !== owner)
159
- refuse(1, `${path} is held by ${held.owner}, not ${owner}`);
160
- rmSync(path);
161
- say(`released ${path}`);
134
+ const path = lockPath(root);
135
+ if (!existsSync(path)) refuse(1, `${path} is not held`);
136
+ const held = readLock(path);
137
+ if (held.owner !== owner)
138
+ refuse(1, `${path} is held by ${held.owner}, not ${owner}`);
139
+ rmSync(path);
140
+ say(`released ${path}`);
162
141
  }
163
- // ── the attempt ledger ──────────────────────────────────────────────────────────────────────
164
- const Seed = z.union([z.string(), z.number()]);
165
- /**
166
- * One line of the ledger. A driver appends one line when an attempt starts and one when it
167
- * ends, both carrying the same `attempt` id; later lines add to earlier ones, so a crashed
168
- * attempt is still on record — with a start and no end.
169
- */
170
- const Attempt = z.looseObject({
171
- attempt: z.string(),
172
- agent: z.string().optional(),
173
- unit: z.string().optional(),
174
- arm: z.string().optional(),
175
- model: z.string().optional(),
176
- seed: Seed.optional(),
177
- root: z.string().optional(),
178
- start: z.string().optional(),
179
- end: z.string().optional(),
180
- status: z.string().optional(),
181
- cost: z.number().optional(),
182
- expires: z.string().optional(),
142
+ var Seed = external_exports.union([external_exports.string(), external_exports.number()]);
143
+ var Attempt = external_exports.looseObject({
144
+ attempt: external_exports.string(),
145
+ agent: external_exports.string().optional(),
146
+ unit: external_exports.string().optional(),
147
+ arm: external_exports.string().optional(),
148
+ model: external_exports.string().optional(),
149
+ seed: Seed.optional(),
150
+ root: external_exports.string().optional(),
151
+ start: external_exports.string().optional(),
152
+ end: external_exports.string().optional(),
153
+ status: external_exports.string().optional(),
154
+ cost: external_exports.number().optional(),
155
+ expires: external_exports.string().optional()
183
156
  });
184
- /** A `reserved` record whose time is up: no longer holds its cell, no longer counts as spent. */
185
- const lapsed = (r, now) => r.status === "reserved" && Date.parse(String(r.expires)) <= now;
157
+ var lapsed = (r, now) => r.status === "reserved" && Date.parse(String(r.expires)) <= now;
186
158
  function readLedger(path) {
187
- if (!existsSync(path))
188
- return [];
189
- const byId = new Map();
190
- readFileSync(path, "utf8")
191
- .split("\n")
192
- .filter((line) => line.trim())
193
- .map((line) => Attempt.parse(JSON.parse(line)))
194
- .forEach((rec) => {
195
- byId.set(rec.attempt, { ...byId.get(rec.attempt), ...rec });
196
- });
197
- return [...byId.values()];
159
+ if (!existsSync(path)) return [];
160
+ const byId = /* @__PURE__ */ new Map();
161
+ readFileSync(path, "utf8").split("\n").filter((line) => line.trim()).map((line) => Attempt.parse(JSON.parse(line))).forEach((rec) => {
162
+ byId.set(rec.attempt, { ...byId.get(rec.attempt), ...rec });
163
+ });
164
+ return [...byId.values()];
198
165
  }
199
- const sameCell = (a, b) => a.unit === b.unit &&
200
- a.arm === b.arm &&
201
- a.model === b.model &&
202
- String(a.seed) === b.seed;
203
- // ── gate ────────────────────────────────────────────────────────────────────────────────────
204
- const Unit = z.looseObject({
205
- id: z.string(),
206
- role: z.string().optional(),
207
- reason: z.string().optional(),
208
- approval: z
209
- .looseObject({
210
- by: z.string().optional(),
211
- at: z.string().optional(),
212
- channel: z.string().optional(),
213
- })
214
- .optional(),
215
- proof: z
216
- .looseObject({
217
- toolVisible: z.unknown().optional(),
218
- firesOnPinned: z.unknown().optional(),
219
- acceptsReference: z.unknown().optional(),
220
- })
221
- .optional(),
166
+ var sameCell = (a, b) => a.unit === b.unit && a.arm === b.arm && a.model === b.model && String(a.seed) === b.seed;
167
+ var Unit = external_exports.looseObject({
168
+ id: external_exports.string(),
169
+ role: external_exports.string().optional(),
170
+ reason: external_exports.string().optional(),
171
+ approval: external_exports.looseObject({
172
+ by: external_exports.string().optional(),
173
+ at: external_exports.string().optional(),
174
+ channel: external_exports.string().optional()
175
+ }).optional(),
176
+ proof: external_exports.looseObject({
177
+ toolVisible: external_exports.unknown().optional(),
178
+ firesOnPinned: external_exports.unknown().optional(),
179
+ acceptsReference: external_exports.unknown().optional()
180
+ }).optional()
222
181
  });
223
- const Model = z.looseObject({
224
- id: z.string(),
225
- smoke: z
226
- .looseObject({
227
- timeoutSec: z.unknown().optional(),
228
- costPerRun: z.unknown().optional(),
229
- })
230
- .optional(),
182
+ var Model = external_exports.looseObject({
183
+ id: external_exports.string(),
184
+ smoke: external_exports.looseObject({
185
+ timeoutSec: external_exports.unknown().optional(),
186
+ costPerRun: external_exports.unknown().optional()
187
+ }).optional()
231
188
  });
232
- const Registry = z.looseObject({
233
- author: z.string().optional(),
234
- draw: z.looseObject({ seed: Seed.optional() }).optional(),
235
- arms: z.array(z.string()).default([]),
236
- seeds: z.array(Seed).default([]),
237
- budget: z.looseObject({ cap: z.unknown().optional() }).optional(),
238
- models: z.array(Model).default([]),
239
- units: z.array(Unit).default([]),
189
+ var Registry = external_exports.looseObject({
190
+ author: external_exports.string().optional(),
191
+ draw: external_exports.looseObject({ seed: Seed.optional() }).optional(),
192
+ arms: external_exports.array(external_exports.string()).default([]),
193
+ seeds: external_exports.array(Seed).default([]),
194
+ budget: external_exports.looseObject({ cap: external_exports.unknown().optional() }).optional(),
195
+ models: external_exports.array(Model).default([]),
196
+ units: external_exports.array(Unit).default([])
240
197
  });
241
- /** The registry as COMMITTED: a declaration that exists only in the working tree allows nothing. */
242
198
  function committedRegistry(file) {
243
- const abs = resolve(file);
244
- const git = (...args) => spawnSync("git", ["-C", dirname(abs), ...args], { encoding: "utf8" });
245
- const top = git("rev-parse", "--show-toplevel");
246
- if (top.status !== 0)
247
- refuse(1, `${file} is not inside a git repository; the registry must be committed`);
248
- const rel = relative(top.stdout.trim(), abs).split(sep).join("/");
249
- const head = git("show", `HEAD:${rel}`);
250
- if (head.status !== 0)
251
- refuse(1, `${file} is not committed; commit it before any run it allows`);
252
- if (head.stdout !== readFileSync(abs, "utf8"))
253
- refuse(1, `${file} differs from its committed version; commit the change (a dated addendum) before any run it allows`);
254
- return Registry.parse(JSON.parse(head.stdout));
199
+ const abs = resolve(file);
200
+ const git = (...args) => spawnSync("git", ["-C", dirname(abs), ...args], { encoding: "utf8" });
201
+ const top = git("rev-parse", "--show-toplevel");
202
+ if (top.status !== 0)
203
+ refuse(
204
+ 1,
205
+ `${file} is not inside a git repository; the registry must be committed`
206
+ );
207
+ const rel = relative(top.stdout.trim(), abs).split(sep).join("/");
208
+ const head = git("show", `HEAD:${rel}`);
209
+ if (head.status !== 0)
210
+ refuse(1, `${file} is not committed; commit it before any run it allows`);
211
+ if (head.stdout !== readFileSync(abs, "utf8"))
212
+ refuse(
213
+ 1,
214
+ `${file} differs from its committed version; commit the change (a dated addendum) before any run it allows`
215
+ );
216
+ return Registry.parse(JSON.parse(head.stdout));
255
217
  }
256
- const filled = (v) => typeof v === "string" && v.trim() !== "";
257
- const num = (v) => (typeof v === "number" ? v : null);
258
- /** Everything the gate decides from, computed once. */
218
+ var filled = (v) => typeof v === "string" && v.trim() !== "";
219
+ var num = (v) => typeof v === "number" ? v : null;
259
220
  function facts(reg, cell, ledgerPath) {
260
- const unit = reg.units.find((u) => u.id === cell.unit);
261
- const model = reg.models.find((m) => m.id === cell.model);
262
- const timeoutSec = num(model?.smoke?.timeoutSec);
263
- const costPerRun = num(model?.smoke?.costPerRun);
264
- const smoked = timeoutSec !== null && costPerRun !== null;
265
- const counted = unit?.role === "counted";
266
- const ledger = readLedger(ledgerPath);
267
- const now = Date.now();
268
- const spent = ledger
269
- .filter((r) => !lapsed(r, now))
270
- .reduce((sum, r) => sum + (r.cost ?? 0), 0);
271
- const cap = num(reg.budget?.cap);
272
- const next = counted && costPerRun !== null ? costPerRun : 0;
273
- return {
274
- now,
275
- unit,
276
- model,
277
- smoked,
278
- counted,
279
- ledger,
280
- spent,
281
- cap,
282
- next,
283
- timeoutSec,
284
- };
221
+ const unit = reg.units.find((u) => u.id === cell.unit);
222
+ const model = reg.models.find((m) => m.id === cell.model);
223
+ const timeoutSec = num(model?.smoke?.timeoutSec);
224
+ const costPerRun = num(model?.smoke?.costPerRun);
225
+ const smoked = timeoutSec !== null && costPerRun !== null;
226
+ const counted = unit?.role === "counted";
227
+ const ledger = readLedger(ledgerPath);
228
+ const now = Date.now();
229
+ const spent = ledger.filter((r) => !lapsed(r, now)).reduce((sum, r) => sum + (r.cost ?? 0), 0);
230
+ const cap = num(reg.budget?.cap);
231
+ const next = counted && costPerRun !== null ? costPerRun : 0;
232
+ return {
233
+ now,
234
+ unit,
235
+ model,
236
+ smoked,
237
+ counted,
238
+ ledger,
239
+ spent,
240
+ cap,
241
+ next,
242
+ timeoutSec
243
+ };
285
244
  }
286
- /** Is the cell declared at all? */
287
245
  function declared(reg, cell, f) {
288
- const role = String(f.unit?.role);
289
- const why = filled(f.unit?.reason) ? ` (${String(f.unit?.reason)})` : "";
290
- return [
291
- [!f.unit, `unit "${cell.unit}" is not in the registry`],
292
- [
293
- f.unit !== undefined && !["counted", "smoke"].includes(role),
294
- `unit "${cell.unit}" has role "${role}"${why}; only "counted" and "smoke" units run`,
295
- ],
296
- [!reg.arms.includes(cell.arm), `arm "${cell.arm}" is not declared`],
297
- [!f.model, `model "${cell.model}" is not declared`],
298
- [
299
- !reg.seeds.map(String).includes(cell.seed),
300
- `seed "${cell.seed}" is not declared`,
301
- ],
302
- [
303
- reg.units.some((u) => u.role === "excluded" && !filled(u.reason)),
304
- `an excluded unit has no reason`,
305
- ],
306
- [f.cap === null, `the registry declares no budget.cap`],
307
- ];
246
+ const role = String(f.unit?.role);
247
+ const why = filled(f.unit?.reason) ? ` (${String(f.unit?.reason)})` : "";
248
+ return [
249
+ [!f.unit, `unit "${cell.unit}" is not in the registry`],
250
+ [
251
+ f.unit !== void 0 && !["counted", "smoke"].includes(role),
252
+ `unit "${cell.unit}" has role "${role}"${why}; only "counted" and "smoke" units run`
253
+ ],
254
+ [!reg.arms.includes(cell.arm), `arm "${cell.arm}" is not declared`],
255
+ [!f.model, `model "${cell.model}" is not declared`],
256
+ [
257
+ !reg.seeds.map(String).includes(cell.seed),
258
+ `seed "${cell.seed}" is not declared`
259
+ ],
260
+ [
261
+ reg.units.some((u) => u.role === "excluded" && !filled(u.reason)),
262
+ `an excluded unit has no reason`
263
+ ],
264
+ [f.cap === null, `the registry declares no budget.cap`]
265
+ ];
308
266
  }
309
- /** What a COUNTED run needs on top: approval, proof, a draw, a smoked model. */
310
267
  function countedNeeds(reg, cell, f) {
311
- const a = f.unit?.approval ?? {};
312
- const p = f.unit?.proof ?? {};
313
- const approved = filled(reg.author) &&
314
- a.by === reg.author &&
315
- filled(a.at) &&
316
- filled(a.channel);
317
- const proven = [p.toolVisible, p.firesOnPinned, p.acceptsReference].every((v) => v === true);
318
- return [
319
- [
320
- !approved,
321
- `unit "${cell.unit}" has no approval by the author (approval.by = author, with at and channel)`,
322
- ],
323
- [
324
- !proven,
325
- `unit "${cell.unit}" has no sandbox proof (toolVisible, firesOnPinned, acceptsReference)`,
326
- ],
327
- [reg.draw?.seed === undefined, `the registry records no draw seed`],
328
- [
329
- f.model !== undefined && !f.smoked,
330
- `model "${cell.model}" has no smoke result (smoke.timeoutSec, smoke.costPerRun)`,
331
- ],
332
- ];
268
+ const a = f.unit?.approval ?? {};
269
+ const p = f.unit?.proof ?? {};
270
+ const approved = filled(reg.author) && a.by === reg.author && filled(a.at) && filled(a.channel);
271
+ const proven = [p.toolVisible, p.firesOnPinned, p.acceptsReference].every(
272
+ (v) => v === true
273
+ );
274
+ return [
275
+ [
276
+ !approved,
277
+ `unit "${cell.unit}" has no approval by the author (approval.by = author, with at and channel)`
278
+ ],
279
+ [
280
+ !proven,
281
+ `unit "${cell.unit}" has no sandbox proof (toolVisible, firesOnPinned, acceptsReference)`
282
+ ],
283
+ [reg.draw?.seed === void 0, `the registry records no draw seed`],
284
+ [
285
+ f.model !== void 0 && !f.smoked,
286
+ `model "${cell.model}" has no smoke result (smoke.timeoutSec, smoke.costPerRun)`
287
+ ]
288
+ ];
333
289
  }
334
- /** Every reason this cell may not run, in a fixed order. */
335
290
  function problems(reg, cell, f) {
336
- const over = f.cap !== null && f.spent + f.next > f.cap;
337
- const checks = [
338
- ...declared(reg, cell, f),
339
- ...(f.counted ? countedNeeds(reg, cell, f) : []),
340
- [
341
- over,
342
- `budget: spent ${String(f.spent)} + next ${String(f.next)} exceeds the cap ${String(f.cap)}`,
343
- ],
344
- ];
345
- return checks.filter(([bad]) => bad).map(([, message]) => message);
291
+ const over = f.cap !== null && f.spent + f.next > f.cap;
292
+ const checks = [
293
+ ...declared(reg, cell, f),
294
+ ...f.counted ? countedNeeds(reg, cell, f) : [],
295
+ [
296
+ over,
297
+ `budget: spent ${String(f.spent)} + next ${String(f.next)} exceeds the cap ${String(f.cap)}`
298
+ ]
299
+ ];
300
+ return checks.filter(([bad]) => bad).map(([, message]) => message);
346
301
  }
347
- /** Who already holds this cell: a counted attempt (exit 3), a live reservation (exit 3), or nobody. */
348
302
  function holder(f, cell) {
349
- const mine = f.ledger.filter((r) => sameCell(r, cell));
350
- if (mine.some((r) => r.status === "complete"))
351
- return `${JSON.stringify(cell)} is already counted; skip it`;
352
- const held = mine.find((r) => r.status === "reserved" && !lapsed(r, f.now));
353
- return held
354
- ? `${JSON.stringify(cell)} is reserved by attempt ${held.attempt} until ${String(held.expires)}; skip it`
355
- : null;
303
+ const mine = f.ledger.filter((r) => sameCell(r, cell));
304
+ if (mine.some((r) => r.status === "complete"))
305
+ return `${JSON.stringify(cell)} is already counted; skip it`;
306
+ const held = mine.find((r) => r.status === "reserved" && !lapsed(r, f.now));
307
+ return held ? `${JSON.stringify(cell)} is reserved by attempt ${held.attempt} until ${String(held.expires)}; skip it` : null;
356
308
  }
357
- /**
358
- * May this cell run now — and if so, CLAIM it. Read, check and append happen under the ledger's
359
- * lock, so two drivers asking at once cannot both get one cell, nor both fit under the cap: the
360
- * `reserved` record holds the cell and counts its estimated cost until the driver's end record for
361
- * the same attempt replaces it, or until it lapses.
362
- */
363
- /** The cell a gate call names. */
364
- const cellOf = (o) => ({
365
- unit: String(o.unit),
366
- arm: String(o.arm),
367
- model: String(o.model),
368
- seed: String(o.seed),
309
+ var cellOf = (o) => ({
310
+ unit: String(o.unit),
311
+ arm: String(o.arm),
312
+ model: String(o.model),
313
+ seed: String(o.seed)
369
314
  });
370
315
  function gate(o) {
371
- const reg = committedRegistry(String(o.registry));
372
- const cell = cellOf(o);
373
- const ledgerPath = String(o.ledger);
374
- const attempt = String(o.attempt);
375
- withLedgerLock(ledgerPath, () => {
376
- const f = facts(reg, cell, ledgerPath);
377
- const found = problems(reg, cell, f);
378
- if (found.length)
379
- refuse(1, `refused ${JSON.stringify(cell)}:\n - ${found.join("\n - ")}`);
380
- const taken = holder(f, cell);
381
- if (taken !== null)
382
- refuse(3, taken);
383
- if (f.ledger.some((r) => r.attempt === attempt))
384
- refuse(1, `attempt ${attempt} is already on the ledger; give each attempt its own id`);
385
- reserve(ledgerPath, {
386
- attempt,
387
- cell,
388
- f,
389
- seconds: Number(o["reserve-sec"]),
390
- });
316
+ const reg = committedRegistry(String(o.registry));
317
+ const cell = cellOf(o);
318
+ const ledgerPath = String(o.ledger);
319
+ const attempt = String(o.attempt);
320
+ withLedgerLock(ledgerPath, () => {
321
+ const f = facts(reg, cell, ledgerPath);
322
+ const found = problems(reg, cell, f);
323
+ if (found.length)
324
+ refuse(
325
+ 1,
326
+ `refused ${JSON.stringify(cell)}:
327
+ - ${found.join("\n - ")}`
328
+ );
329
+ const taken = holder(f, cell);
330
+ if (taken !== null) refuse(3, taken);
331
+ if (f.ledger.some((r) => r.attempt === attempt))
332
+ refuse(
333
+ 1,
334
+ `attempt ${attempt} is already on the ledger; give each attempt its own id`
335
+ );
336
+ reserve(ledgerPath, {
337
+ attempt,
338
+ cell,
339
+ f,
340
+ seconds: Number(o["reserve-sec"])
391
341
  });
342
+ });
392
343
  }
393
- /** Append the cell's reservation for `attempt`, and report the gate's answer. */
394
344
  function reserve(ledgerPath, r) {
395
- const record = {
396
- attempt: r.attempt,
397
- ...r.cell,
398
- status: "reserved",
399
- cost: r.f.next,
400
- start: new Date(r.f.now).toISOString(),
401
- expires: new Date(r.f.now + r.seconds * 1000).toISOString(),
402
- };
403
- appendFileSync(ledgerPath, `${JSON.stringify(record)}\n`);
404
- say(JSON.stringify({
405
- allowed: true,
406
- cell: r.cell,
407
- attempt: r.attempt,
408
- counted: r.f.counted,
409
- timeoutSec: r.f.smoked ? r.f.timeoutSec : null,
410
- spent: r.f.spent,
411
- }));
345
+ const record = {
346
+ attempt: r.attempt,
347
+ ...r.cell,
348
+ status: "reserved",
349
+ cost: r.f.next,
350
+ start: new Date(r.f.now).toISOString(),
351
+ expires: new Date(r.f.now + r.seconds * 1e3).toISOString()
352
+ };
353
+ appendFileSync(ledgerPath, `${JSON.stringify(record)}
354
+ `);
355
+ say(
356
+ JSON.stringify({
357
+ allowed: true,
358
+ cell: r.cell,
359
+ attempt: r.attempt,
360
+ counted: r.f.counted,
361
+ timeoutSec: r.f.smoked ? r.f.timeoutSec : null,
362
+ spent: r.f.spent
363
+ })
364
+ );
412
365
  }
413
- // ── the ledger's lock ───────────────────────────────────────────────────────────────────────
414
- /** How long a gate waits for another gate's turn. `GRID_GUARD_LEDGER_WAIT_MS` shortens it in tests. */
415
- const ledgerWaitMs = () => Number(process.env.GRID_GUARD_LEDGER_WAIT_MS ?? 10_000);
416
- /** Sleep without spinning: the process blocks until the time passes. */
417
- const pause = (ms) => {
418
- Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms);
366
+ var ledgerWaitMs = () => Number(process.env.GRID_GUARD_LEDGER_WAIT_MS ?? 1e4);
367
+ var pause = (ms) => {
368
+ Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms);
419
369
  };
420
- /**
421
- * The ledger lock's owner, or null while it cannot be read — another gate may have created the
422
- * file and not yet written it, so an unreadable lock is a held one.
423
- */
424
- const peekLock = (path) => {
425
- try {
426
- return readLock(path);
427
- }
428
- catch {
429
- return null;
430
- }
370
+ var peekLock = (path) => {
371
+ try {
372
+ return readLock(path);
373
+ } catch {
374
+ return null;
375
+ }
431
376
  };
432
- /** Take `<ledger>.lock`, waiting for a live holder and replacing a dead one on this host. */
433
377
  function acquireLedger(path, deadline) {
434
- const me = {
435
- owner: "gate",
436
- pid: process.pid,
437
- host: hostname(),
438
- at: new Date().toISOString(),
439
- };
440
- if (take(path, me))
441
- return;
442
- const held = peekLock(path);
443
- if (held !== null && held.host === me.host && !alive(held.pid))
444
- rmSync(path, { force: true });
445
- else if (Date.now() >= deadline)
446
- refuse(1, held === null
447
- ? `${path} exists and names no owner; if no gate is running, delete it`
448
- : `${path} is held by pid ${String(held.pid)} on ${held.host} since ${held.at}; another gate is writing the ledger — try again`);
449
- else
450
- pause(25);
451
- acquireLedger(path, deadline);
378
+ const me = {
379
+ owner: "gate",
380
+ pid: process.pid,
381
+ host: hostname(),
382
+ at: (/* @__PURE__ */ new Date()).toISOString()
383
+ };
384
+ if (take(path, me)) return;
385
+ const held = peekLock(path);
386
+ if (held !== null && held.host === me.host && !alive(held.pid))
387
+ rmSync(path, { force: true });
388
+ else if (Date.now() >= deadline)
389
+ refuse(
390
+ 1,
391
+ held === null ? `${path} exists and names no owner; if no gate is running, delete it` : `${path} is held by pid ${String(held.pid)} on ${held.host} since ${held.at}; another gate is writing the ledger \u2014 try again`
392
+ );
393
+ else pause(25);
394
+ acquireLedger(path, deadline);
452
395
  }
453
396
  function withLedgerLock(ledger, work) {
454
- const path = `${resolve(ledger)}.lock`;
455
- acquireLedger(path, Date.now() + ledgerWaitMs());
456
- try {
457
- work();
458
- }
459
- finally {
460
- rmSync(path, { force: true });
461
- }
397
+ const path = `${resolve(ledger)}.lock`;
398
+ acquireLedger(path, Date.now() + ledgerWaitMs());
399
+ try {
400
+ work();
401
+ } finally {
402
+ rmSync(path, { force: true });
403
+ }
462
404
  }
463
- /** Pairs of attempts on one root whose windows intersect, at least one of them counted. */
464
- const sharedRoots = (recs) => recs.flatMap((a, i) => recs
465
- .slice(i + 1)
466
- .filter((b) => a.root === b.root &&
467
- (a.status === "complete" || b.status === "complete") &&
468
- a.from < b.to &&
469
- b.from < a.to)
470
- .map((b) => `${a.attempt} and ${b.attempt} shared ${a.root}`));
405
+ var sharedRoots = (recs) => recs.flatMap(
406
+ (a, i) => recs.slice(i + 1).filter(
407
+ (b) => a.root === b.root && (a.status === "complete" || b.status === "complete") && a.from < b.to && b.from < a.to
408
+ ).map((b) => `${a.attempt} and ${b.attempt} shared ${a.root}`)
409
+ );
471
410
  function overlap(file) {
472
- if (!existsSync(file))
473
- refuse(1, `no ledger at ${file}`);
474
- const recs = readLedger(file).map((r) => ({
475
- attempt: r.attempt,
476
- status: r.status,
477
- root: resolve(String(r.root)),
478
- from: Date.parse(String(r.start)),
479
- to: r.end === undefined ? Infinity : Date.parse(r.end),
480
- }));
481
- const findings = [
482
- ...recs
483
- .filter((r) => Number.isNaN(r.from) || Number.isNaN(r.to))
484
- .map((r) => `${r.attempt}: start or end is not a date`),
485
- ...sharedRoots(recs),
486
- ];
487
- if (findings.length)
488
- refuse(1, `${findings.join("\n")}\nmark each contaminated attempt "harness-error" (keep it) and run the cell again`);
489
- say(`no overlap among ${String(recs.length)} attempts`);
411
+ if (!existsSync(file)) refuse(1, `no ledger at ${file}`);
412
+ const recs = readLedger(file).map((r) => ({
413
+ attempt: r.attempt,
414
+ status: r.status,
415
+ root: resolve(String(r.root)),
416
+ from: Date.parse(String(r.start)),
417
+ to: r.end === void 0 ? Infinity : Date.parse(r.end)
418
+ }));
419
+ const findings = [
420
+ ...recs.filter((r) => Number.isNaN(r.from) || Number.isNaN(r.to)).map((r) => `${r.attempt}: start or end is not a date`),
421
+ ...sharedRoots(recs)
422
+ ];
423
+ if (findings.length)
424
+ refuse(
425
+ 1,
426
+ `${findings.join("\n")}
427
+ mark each contaminated attempt "harness-error" (keep it) and run the cell again`
428
+ );
429
+ say(`no overlap among ${String(recs.length)} attempts`);
490
430
  }
491
- // ── env-probe ───────────────────────────────────────────────────────────────────────────────
492
- const SECRET_NAME = /KEY|TOKEN|SECRET|PASSW|CREDENTIAL|COOKIE|SESSION|AUTH(?!OR)/i;
431
+ var SECRET_NAME = /KEY|TOKEN|SECRET|PASSW|CREDENTIAL|COOKIE|SESSION|AUTH(?!OR)/i;
493
432
  function envProbe(allow, withGit) {
494
- const allowed = new Set(allow);
495
- const names = Object.keys(process.env)
496
- .filter((n) => SECRET_NAME.test(n) && !allowed.has(n))
497
- .sort();
498
- if (names.length)
499
- refuse(1, `secret-named variables reach this environment (names only): ${names.join(", ")}`);
500
- if (withGit)
501
- gitProbe();
502
- say(`no secret-named variables${withGit ? "; git init, add and commit work" : ""}`);
433
+ const allowed = new Set(allow);
434
+ const names = Object.keys(process.env).filter((n) => SECRET_NAME.test(n) && !allowed.has(n)).sort();
435
+ if (names.length)
436
+ refuse(
437
+ 1,
438
+ `secret-named variables reach this environment (names only): ${names.join(", ")}`
439
+ );
440
+ if (withGit) gitProbe();
441
+ say(
442
+ `no secret-named variables${withGit ? "; git init, add and commit work" : ""}`
443
+ );
503
444
  }
504
- /** The policy that drops secrets must not drop what the agent's tools need: prove git commits. */
505
445
  function gitProbe() {
506
- const dir = realpathSync(mkdtempSync(join(tmpdir(), "grid-git-probe-")));
507
- try {
508
- writeFileSync(join(dir, "probe.txt"), "probe\n");
509
- [
510
- ["init", "-q"],
511
- ["add", "probe.txt"],
512
- ["commit", "-q", "-m", "probe"],
513
- ].forEach((args) => {
514
- const r = spawnSync("git", ["-C", dir, ...args], { encoding: "utf8" });
515
- if (r.status !== 0)
516
- refuse(1, `git ${String(args[0])} fails in this environment: ${(r.stderr || String(r.error)).trim()}`);
517
- });
518
- }
519
- finally {
520
- rmSync(dir, { recursive: true, force: true });
521
- }
522
- }
523
- // ── scan-keys / precommit ───────────────────────────────────────────────────────────────────
524
- // Shapes, not vendors: each names a FORM a credential takes. The last one catches an
525
- // environment dump — NAME=value lines — which is how secrets got into transcripts.
526
- const KEY_SHAPES = [
527
- ["private key block", /-----BEGIN [A-Z ]*PRIVATE KEY-----/],
528
- ["access key id", /\bAKIA[0-9A-Z]{16}\b/],
529
- [
530
- "git host token",
531
- /\b(?:gh[pousr]_[A-Za-z0-9]{36,}|github_pat_[A-Za-z0-9_]{40,})/,
532
- ],
533
- ["chat bot token", /\bxox[abprs]-[A-Za-z0-9-]{10,}/],
534
- ["cloud api key", /\bAIza[0-9A-Za-z_-]{35}\b/],
535
- ["sk- api key", /\bsk-[A-Za-z0-9_-]{20,}/],
446
+ const dir = realpathSync(mkdtempSync(join(tmpdir(), "grid-git-probe-")));
447
+ try {
448
+ writeFileSync(join(dir, "probe.txt"), "probe\n");
536
449
  [
537
- "secret-named assignment",
538
- /\b[A-Z0-9_]*(?:KEY|TOKEN|SECRET|PASSW(?:OR)?D)[A-Z0-9_]*["']?\s*[=:]\s*["']?(?![<$])[^\s"'<>]{12,}/,
539
- ],
450
+ ["init", "-q"],
451
+ ["add", "probe.txt"],
452
+ ["commit", "-q", "-m", "probe"]
453
+ ].forEach((args) => {
454
+ const r = spawnSync("git", ["-C", dir, ...args], { encoding: "utf8" });
455
+ if (r.status !== 0)
456
+ refuse(
457
+ 1,
458
+ `git ${String(args[0])} fails in this environment: ${(r.stderr || String(r.error)).trim()}`
459
+ );
460
+ });
461
+ } finally {
462
+ rmSync(dir, { recursive: true, force: true });
463
+ }
464
+ }
465
+ var KEY_SHAPES = [
466
+ ["private key block", /-----BEGIN [A-Z ]*PRIVATE KEY-----/],
467
+ ["access key id", /\bAKIA[0-9A-Z]{16}\b/],
468
+ [
469
+ "git host token",
470
+ /\b(?:gh[pousr]_[A-Za-z0-9]{36,}|github_pat_[A-Za-z0-9_]{40,})/
471
+ ],
472
+ ["chat bot token", /\bxox[abprs]-[A-Za-z0-9-]{10,}/],
473
+ ["cloud api key", /\bAIza[0-9A-Za-z_-]{35}\b/],
474
+ ["sk- api key", /\bsk-[A-Za-z0-9_-]{20,}/],
475
+ [
476
+ "secret-named assignment",
477
+ /\b[A-Z0-9_]*(?:KEY|TOKEN|SECRET|PASSW(?:OR)?D)[A-Z0-9_]*["']?\s*[=:]\s*["']?(?![<$])[^\s"'<>]{12,}/
478
+ ]
540
479
  ];
541
- /** `file:line: shape` for every key-shaped string in `text`; the value is never part of it. */
542
- const scanText = (name, text) => text.includes("\0")
543
- ? []
544
- : text
545
- .split("\n")
546
- .flatMap((line, i) => KEY_SHAPES.filter(([, re]) => re.test(line)).map(([shape]) => `${name}:${String(i + 1)}: ${shape}`));
547
- const SKIP_DIRS = new Set([".git", "node_modules"]);
548
- const walk = (path) => statSync(path).isDirectory()
549
- ? readdirSync(path)
550
- .filter((e) => !SKIP_DIRS.has(e))
551
- .flatMap((e) => walk(join(path, e)))
552
- : [path];
480
+ var scanText = (name, text) => text.includes("\0") ? [] : text.split("\n").flatMap(
481
+ (line, i) => KEY_SHAPES.filter(([, re]) => re.test(line)).map(
482
+ ([shape]) => `${name}:${String(i + 1)}: ${shape}`
483
+ )
484
+ );
485
+ var SKIP_DIRS = /* @__PURE__ */ new Set([".git", "node_modules"]);
486
+ var walk = (path) => statSync(path).isDirectory() ? readdirSync(path).filter((e) => !SKIP_DIRS.has(e)).flatMap((e) => walk(join(path, e))) : [path];
553
487
  function reportKeys(findings, scanned) {
554
- if (findings.length)
555
- refuse(1, `key-shaped strings (values not shown):\n${findings.join("\n")}`);
556
- say(`no key-shaped strings in ${String(scanned)} files`);
488
+ if (findings.length)
489
+ refuse(1, `key-shaped strings (values not shown):
490
+ ${findings.join("\n")}`);
491
+ say(`no key-shaped strings in ${String(scanned)} files`);
557
492
  }
558
493
  function scanKeys(paths) {
559
- const files = paths.flatMap(walk);
560
- reportKeys(files.flatMap((f) => scanText(f, readFileSync(f, "utf8"))), files.length);
494
+ const files = paths.flatMap(walk);
495
+ reportKeys(
496
+ files.flatMap((f) => scanText(f, readFileSync(f, "utf8"))),
497
+ files.length
498
+ );
561
499
  }
562
- /** Staged run folders under `runs` whose completion record `done` is not in the index. */
563
- const halfWritten = (staged, index, runs, done) => [
564
- ...new Set(staged
565
- .filter((f) => f.startsWith(`${runs}/`))
566
- .map((f) => f.slice(runs.length + 1).split("/"))
567
- .filter((parts) => parts.length > 1)
568
- .map((parts) => `${runs}/${String(parts[0])}`)),
500
+ var halfWritten = (staged, index, runs, done) => [
501
+ ...new Set(
502
+ staged.filter((f) => f.startsWith(`${runs}/`)).map((f) => f.slice(runs.length + 1).split("/")).filter((parts) => parts.length > 1).map((parts) => `${runs}/${String(parts[0])}`)
503
+ )
569
504
  ].filter((dir) => !index.has(`${dir}/${done}`));
570
- /** stdout of a git command run where the caller stands; a failure is a refusal. */
571
- const gitOut = (...args) => {
572
- const r = spawnSync("git", args, { encoding: "utf8", maxBuffer: 1 << 28 });
573
- if (r.status !== 0)
574
- refuse(1, `git ${String(args[0])}: ${r.stderr.trim()}`);
575
- return r.stdout;
505
+ var gitOut = (...args) => {
506
+ const r = spawnSync("git", args, { encoding: "utf8", maxBuffer: 1 << 28 });
507
+ if (r.status !== 0) refuse(1, `git ${String(args[0])}: ${r.stderr.trim()}`);
508
+ return r.stdout;
576
509
  };
577
- const nulList = (s) => s.split("\0").filter(Boolean);
510
+ var nulList = (s) => s.split("\0").filter(Boolean);
578
511
  function precommit(runsOpt, done) {
579
- const top = gitOut("rev-parse", "--show-toplevel").trim();
580
- const cached = (...filter) => nulList(gitOut("-C", top, "diff", "--cached", "--name-only", "-z", ...filter));
581
- // Content is scanned only where it exists in the index; a run folder is affected by any staged
582
- // path in it, a DELETION included — deleting a completion record must not pass as finished.
583
- const staged = cached("--diff-filter=ACMR");
584
- const touched = cached();
585
- const keys = staged.flatMap((f) => scanText(f, gitOut("-C", top, "show", `:${f}`)));
586
- const index = new Set(nulList(gitOut("-C", top, "ls-files", "-z")));
587
- const half = runsOpt
588
- ? halfWritten(touched, index, runsOpt.replace(/\/+$/, ""), done)
589
- : [];
590
- if (half.length)
591
- refuse(1, `run folders without ${done} are staged (commit only finished runs):\n${half.join("\n")}`);
592
- reportKeys(keys, staged.length);
512
+ const top = gitOut("rev-parse", "--show-toplevel").trim();
513
+ const cached = (...filter) => nulList(
514
+ gitOut("-C", top, "diff", "--cached", "--name-only", "-z", ...filter)
515
+ );
516
+ const staged = cached("--diff-filter=ACMR");
517
+ const touched = cached();
518
+ const keys = staged.flatMap(
519
+ (f) => scanText(f, gitOut("-C", top, "show", `:${f}`))
520
+ );
521
+ const index = new Set(nulList(gitOut("-C", top, "ls-files", "-z")));
522
+ const half = runsOpt ? halfWritten(touched, index, runsOpt.replace(/\/+$/, ""), done) : [];
523
+ if (half.length)
524
+ refuse(
525
+ 1,
526
+ `run folders without ${done} are staged (commit only finished runs):
527
+ ${half.join("\n")}`
528
+ );
529
+ reportKeys(keys, staged.length);
593
530
  }
594
- /**
595
- * Each command: the options it requires, how many paths it takes (-1: one or more), what it does.
596
- * Keyed by the names in `grid-guard-commands.ts`, all of them and nothing else.
597
- */
598
- const DISPATCH = {
599
- lock: [
600
- ["owner"],
601
- 1,
602
- (p, o) => {
603
- lock(String(p[0]), String(o.owner), o.pid, o.attached);
604
- },
605
- ],
606
- release: [
607
- ["owner"],
608
- 1,
609
- (p, o) => {
610
- release(String(p[0]), String(o.owner));
611
- },
612
- ],
613
- gate: [
614
- ["registry", "ledger", "unit", "arm", "model", "seed", "attempt"],
615
- 0,
616
- (_, o) => {
617
- gate(o);
618
- },
619
- ],
620
- overlap: [
621
- [],
622
- 1,
623
- (p) => {
624
- overlap(String(p[0]));
625
- },
626
- ],
627
- "env-probe": [
628
- [],
629
- 0,
630
- (_, o) => {
631
- envProbe(o.allow, o.git);
632
- },
633
- ],
634
- "scan-keys": [
635
- [],
636
- -1,
637
- (p) => {
638
- scanKeys(p);
639
- },
640
- ],
641
- precommit: [
642
- [],
643
- 0,
644
- (_, o) => {
645
- precommit(o.runs, o.done);
646
- },
647
- ],
648
- };
649
- const BY_NAME = new Map(Object.entries(DISPATCH));
650
- const USAGE = `usage: grid-guard.js <${Object.values(COMMANDS).join("|")}> … (see the header of this file)`;
651
- /** The command line, parsed; an unknown option is a usage error. */
652
- function parse() {
653
- try {
654
- const { values: v, positionals } = parseArgs({
655
- allowPositionals: true,
656
- strict: true,
657
- options: {
658
- owner: { type: "string" },
659
- pid: { type: "string" },
660
- registry: { type: "string" },
661
- ledger: { type: "string" },
662
- unit: { type: "string" },
663
- arm: { type: "string" },
664
- model: { type: "string" },
665
- seed: { type: "string" },
666
- attempt: { type: "string" },
667
- "reserve-sec": { type: "string", default: "21600" },
668
- allow: { type: "string", multiple: true, default: [] },
669
- git: { type: "boolean", default: false },
670
- attached: { type: "boolean", default: false },
671
- runs: { type: "string" },
672
- done: { type: "string", default: "done.json" },
673
- },
674
- });
675
- return { positionals, opts: v };
531
+ var DISPATCH = {
532
+ lock: [
533
+ ["owner"],
534
+ 1,
535
+ (p, o) => {
536
+ lock(String(p[0]), String(o.owner), o.pid, o.attached);
537
+ }
538
+ ],
539
+ release: [
540
+ ["owner"],
541
+ 1,
542
+ (p, o) => {
543
+ release(String(p[0]), String(o.owner));
676
544
  }
677
- catch (e) {
678
- return refuse(2, `${String(prop(e, "message"))}\n${USAGE}`);
545
+ ],
546
+ gate: [
547
+ ["registry", "ledger", "unit", "arm", "model", "seed", "attempt"],
548
+ 0,
549
+ (_, o) => {
550
+ gate(o);
679
551
  }
552
+ ],
553
+ overlap: [
554
+ [],
555
+ 1,
556
+ (p) => {
557
+ overlap(String(p[0]));
558
+ }
559
+ ],
560
+ "env-probe": [
561
+ [],
562
+ 0,
563
+ (_, o) => {
564
+ envProbe(o.allow, o.git);
565
+ }
566
+ ],
567
+ "scan-keys": [
568
+ [],
569
+ -1,
570
+ (p) => {
571
+ scanKeys(p);
572
+ }
573
+ ],
574
+ precommit: [
575
+ [],
576
+ 0,
577
+ (_, o) => {
578
+ precommit(o.runs, o.done);
579
+ }
580
+ ]
581
+ };
582
+ var BY_NAME = new Map(Object.entries(DISPATCH));
583
+ var USAGE = `usage: grid-guard.js <${Object.values(COMMANDS).join("|")}> \u2026 (see the header of this file)`;
584
+ function parse() {
585
+ try {
586
+ const { values: v, positionals } = parseArgs({
587
+ allowPositionals: true,
588
+ strict: true,
589
+ options: {
590
+ owner: { type: "string" },
591
+ pid: { type: "string" },
592
+ registry: { type: "string" },
593
+ ledger: { type: "string" },
594
+ unit: { type: "string" },
595
+ arm: { type: "string" },
596
+ model: { type: "string" },
597
+ seed: { type: "string" },
598
+ attempt: { type: "string" },
599
+ "reserve-sec": { type: "string", default: "21600" },
600
+ allow: { type: "string", multiple: true, default: [] },
601
+ git: { type: "boolean", default: false },
602
+ attached: { type: "boolean", default: false },
603
+ runs: { type: "string" },
604
+ done: { type: "string", default: "done.json" }
605
+ }
606
+ });
607
+ return { positionals, opts: v };
608
+ } catch (e) {
609
+ return refuse(2, `${String(prop(e, "message"))}
610
+ ${USAGE}`);
611
+ }
680
612
  }
681
613
  function main() {
682
- const { positionals, opts } = parse();
683
- const [name, ...paths] = positionals;
684
- const command = BY_NAME.get(String(name));
685
- if (!command)
686
- return refuse(2, USAGE);
687
- const [required, arity, run] = command;
688
- const missing = required.filter((k) => opts[k] === undefined);
689
- const badArity = arity === -1 ? paths.length === 0 : paths.length !== arity;
690
- if (missing.length || badArity)
691
- refuse(2, `${String(name)}: ${missing.length ? `needs --${missing.join(", --")}` : "wrong number of paths"}\n${USAGE}`);
692
- run(paths, opts);
614
+ const { positionals, opts } = parse();
615
+ const [name, ...paths] = positionals;
616
+ const command = BY_NAME.get(String(name));
617
+ if (!command) return refuse(2, USAGE);
618
+ const [required, arity, run] = command;
619
+ const missing = required.filter((k) => opts[k] === void 0);
620
+ const badArity = arity === -1 ? paths.length === 0 : paths.length !== arity;
621
+ if (missing.length || badArity)
622
+ refuse(
623
+ 2,
624
+ `${String(name)}: ${missing.length ? `needs --${missing.join(", --")}` : "wrong number of paths"}
625
+ ${USAGE}`
626
+ );
627
+ run(paths, opts);
693
628
  }
694
629
  try {
695
- main();
696
- }
697
- catch (e) {
698
- process.stderr.write(`grid-guard: ${String(prop(e, "message"))}\n`);
699
- process.exitCode = e instanceof Refusal ? e.exitCode : 1;
630
+ main();
631
+ } catch (e) {
632
+ process.stderr.write(`grid-guard: ${String(prop(e, "message"))}
633
+ `);
634
+ process.exitCode = e instanceof Refusal ? e.exitCode : 1;
700
635
  }