@acemarke/diffloupe 0.1.0 → 0.2.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 (60) hide show
  1. package/README.md +202 -135
  2. package/dist/index.js +599 -535
  3. package/dist/review-core/opencode/governor.ts +709 -0
  4. package/dist/review-core/opencode/tools.md +104 -0
  5. package/dist/review-core/system.md +52 -0
  6. package/dist/wasm/tree-sitter-cpp.wasm +0 -0
  7. package/dist/wasm/tree-sitter-tsx.wasm +0 -0
  8. package/dist/wasm/tree-sitter-typescript.wasm +0 -0
  9. package/dist/wasm/web-tree-sitter.wasm +0 -0
  10. package/dist/web/assets/arktype-bg7F_Ihs.js +34 -0
  11. package/dist/web/assets/diffs-D52k9AsX.js +157 -0
  12. package/dist/web/assets/index-BjtH6rIF.js +12 -0
  13. package/dist/web/assets/index-FlD9qnmN.css +1 -0
  14. package/dist/web/assets/langs/c-B7uRR5me.js +1 -0
  15. package/dist/web/assets/langs/cmake-Bj61d0ZC.js +1 -0
  16. package/dist/web/assets/langs/cpp-CsVjRphN.js +1 -0
  17. package/dist/web/assets/langs/css-C8fQr_0Q.js +1 -0
  18. package/dist/web/assets/langs/diff-woXpYk--.js +1 -0
  19. package/dist/web/assets/langs/docker-IyjqRm3v.js +1 -0
  20. package/dist/web/assets/langs/glsl-D4jN2Gfq.js +1 -0
  21. package/dist/web/assets/langs/go-rLFTqkRN.js +1 -0
  22. package/dist/web/assets/langs/graphql-CraUZO0h.js +1 -0
  23. package/dist/web/assets/langs/html-DA4kSGiR.js +1 -0
  24. package/dist/web/assets/langs/ini-B5eOa1yu.js +1 -0
  25. package/dist/web/assets/langs/java-BXcb2rRD.js +1 -0
  26. package/dist/web/assets/langs/javascript-BgS3c2Ky.js +1 -0
  27. package/dist/web/assets/langs/json-qhed-kSA.js +1 -0
  28. package/dist/web/assets/langs/json5-BR5RXkoi.js +1 -0
  29. package/dist/web/assets/langs/jsonc-CYpm1nAK.js +1 -0
  30. package/dist/web/assets/langs/jsx-Bz0zcwM4.js +1 -0
  31. package/dist/web/assets/langs/make-Dixweg8N.js +1 -0
  32. package/dist/web/assets/langs/markdown-BYOwaDjH.js +1 -0
  33. package/dist/web/assets/langs/objective-cpp-BsSzOQcm.js +1 -0
  34. package/dist/web/assets/langs/plain-text-BONI54VU.js +1 -0
  35. package/dist/web/assets/langs/postcss-BXeXVLqQ.js +1 -0
  36. package/dist/web/assets/langs/powershell-QtSnmXcu.js +1 -0
  37. package/dist/web/assets/langs/python-gzcpVVnB.js +1 -0
  38. package/dist/web/assets/langs/regexp-Cw_s_VJJ.js +1 -0
  39. package/dist/web/assets/langs/rust-DpiIf5JO.js +1 -0
  40. package/dist/web/assets/langs/scss-CHVQqdPx.js +1 -0
  41. package/dist/web/assets/langs/shellscript-CLZ0U2zV.js +1 -0
  42. package/dist/web/assets/langs/sql-CEbI0hMM.js +1 -0
  43. package/dist/web/assets/langs/svelte-CfPQtCMR.js +1 -0
  44. package/dist/web/assets/langs/toml-CcmNWLt0.js +1 -0
  45. package/dist/web/assets/langs/tsx-udAQXfEw.js +1 -0
  46. package/dist/web/assets/langs/typescript-bsJCZSQ-.js +1 -0
  47. package/dist/web/assets/langs/vue-DEcQttJD.js +1 -0
  48. package/dist/web/assets/langs/xml-D5JPTzE5.js +1 -0
  49. package/dist/web/assets/langs/yaml-rwi0_p6S.js +1 -0
  50. package/dist/web/assets/react-jlQz0HNM.js +9 -0
  51. package/dist/web/assets/rolldown-runtime-hePW80VL.js +1 -0
  52. package/dist/web/assets/router-DvNvfdSS.js +2 -0
  53. package/dist/web/assets/shiki-CbbI7yl6.js +153 -0
  54. package/dist/web/assets/state-a-GRkbSP.js +1 -0
  55. package/dist/web/assets/themes/pierre-dark-CpLgRqie.js +1 -0
  56. package/dist/web/assets/themes/pierre-light-CoaEpmwp.js +1 -0
  57. package/dist/web/assets/unused-C8e4aDKx.js +1 -0
  58. package/dist/web/assets/worker-uPqQ0MJ1.js +164 -0
  59. package/dist/web/index.html +26 -0
  60. package/package.json +34 -15
@@ -0,0 +1,709 @@
1
+ /**
2
+ * Spend governor for the OpenCode runner.
3
+ *
4
+ * The `claude` binary took `--max-budget-usd` and stopped itself. OpenCode has
5
+ * no equivalent, so the cap is enforced from inside the session instead. This
6
+ * file is copied into the runner's config directory by pipeline.ts and loaded by
7
+ * OpenCode as a plugin; it is not part of the pipeline's own module graph, and
8
+ * the types below are hand-written against the V2 plugin API rather than
9
+ * imported, because `@opencode/plugin` is not a dependency of this repository.
10
+ * `Plugin.define` is the identity function, so a plain `{ id, setup }` default
11
+ * export is the same thing.
12
+ *
13
+ * Stopping by killing the process was the obvious approach and is the wrong one:
14
+ * a slice delivers its findings by writing a JSON file as its last act, so a
15
+ * kill throws away everything the turn had already established. Every stage here
16
+ * is chosen to leave that write reachable.
17
+ *
18
+ * Two limits, cost and elapsed time, drive three stages. Whichever is closer to
19
+ * being reached is the one in force, so a limit that is not configured simply
20
+ * never becomes the binding one:
21
+ *
22
+ * - At `NUDGE_AT` of the limit, a wrap-up notice is appended to the result of
23
+ * each tool call. The agent is still free to work; it just knows the clock is
24
+ * running and can choose to land.
25
+ * - At the limit, every tool except the file write is refused. The refusal is
26
+ * delivered to the model as a tool error, so it reads as an instruction
27
+ * rather than a malfunction, and the one remaining action is the one that
28
+ * delivers findings. Once the findings file exists the write is refused too,
29
+ * which leaves no tool to call and ends the session on its own.
30
+ * - At `ABORT_AT` of the limit the session is interrupted outright, and only
31
+ * while the findings file is still missing. Interrupting is confined to the
32
+ * case where there was nothing to lose: an agent that keeps retrying refused
33
+ * tools instead of writing. `steps` in the agent config is the backstop if
34
+ * even that does not settle it.
35
+ *
36
+ * Time is a limit and not just a proxy for cost because on a cheap model the two
37
+ * come apart completely. Measured on one slice of PR #13202: the same unit that
38
+ * cost Opus 5 $1.58 in 22 steps cost GLM-5.3-Flash $0.10 in 46 steps, and was
39
+ * still going at thirteen minutes. Against a $3 budget every cost stage here
40
+ * stayed inert for the whole run while the thing that needed bounding ran away.
41
+ * Per-step latency barely differs between the two models; step count is what
42
+ * differs, and on a model priced thirty times lower only the clock notices.
43
+ *
44
+ * Every message the governor sends to the model rides on a tool result or a tool
45
+ * error, and never on the system prompt. The system prompt is the prefix of the
46
+ * prompt cache, so appending to it invalidates the cache and the whole context
47
+ * is re-sent at full price. Measured on one slice of PR #13202: injecting the
48
+ * notice into the system prompt dropped cache reads from 85k to 6k, rewrote 83k
49
+ * of cache, and took the per-step cost from $0.05 to $0.54. A governor that
50
+ * makes overspending ten times more expensive is worse than no governor. Tool
51
+ * results append after the cached prefix and cost nothing extra.
52
+ *
53
+ * The same plugin also governs shell use, for the same reason and by the same
54
+ * mechanism. Cost on this runner tracks step count almost exactly, so an agent
55
+ * that reads the codebase in `sed` fragments and searches it with `git grep`
56
+ * costs several times what one using the structured tools costs, and reviews it
57
+ * worse. The tool guidance says so and is partly ignored, so the rules below say
58
+ * it again at the point of use.
59
+ *
60
+ * Two jobs here are not governing at all, and live in this plugin because it is
61
+ * the only code of ours inside the OpenCode process:
62
+ *
63
+ * - Accounting. `opencode run --format json` leaves the final step of a session
64
+ * out of its stream — the text-only step that ends the turn never gets a
65
+ * `step_finish` line — so a total summed from stdout is short by one step on
66
+ * every call. The step events this plugin receives include that step, so the
67
+ * governor writes the authoritative totals to `REVIEW_GOVERNOR_USAGE_FILE`.
68
+ * - Waiting for tilth. MCP servers connect in the background, and a session
69
+ * that starts first gets its first model requests without the MCP tools in
70
+ * the tool list. A reviewer whose first two steps are offered only the shell
71
+ * and the built-in readers starts the habit the rules below exist to break.
72
+ */
73
+
74
+ import { appendFileSync, existsSync, writeFileSync } from "node:fs";
75
+ import path from "node:path";
76
+
77
+ /** Fraction of the binding limit at which tool results carry the wrap-up notice. */
78
+ const NUDGE_AT = 0.75;
79
+ /** Multiple of the binding limit at which an agent with no findings file is interrupted. */
80
+ const ABORT_AT = 2;
81
+ /**
82
+ * Ceiling on any single shell command, in milliseconds.
83
+ *
84
+ * OpenCode's own shell timeout defaults to 120 seconds, and the model may ask for
85
+ * more or for none at all, so the cap is applied here. Measured on one slice of
86
+ * PR #13202: a filesystem-wide `find` burned 111 seconds and returned nothing, a
87
+ * fifth of that run's wall time in one call. Nothing a reviewer legitimately
88
+ * runs takes twenty seconds — the commands that would are builds and tests, and
89
+ * the review checkout has no dependencies installed to run them with. Unlike the
90
+ * pattern rules below, this bounds the damage from commands nobody anticipated.
91
+ */
92
+ const MAX_SHELL_MS = 20_000;
93
+ /** Times a warned shell pattern is tipped before it is refused outright. */
94
+ const WARN_LIMIT = 3;
95
+ /** Longest the first model request is held back waiting for the MCP tools to register. */
96
+ const TOOL_WAIT_MS = 30_000;
97
+
98
+ /**
99
+ * A shell pattern the reviewer should not be using, and what to use instead.
100
+ *
101
+ * `match` and `except` are tested against the command at the head of a shell
102
+ * segment, never against a pipe target: `... | grep foo` is filtering another
103
+ * command's output, which no tool here replaces.
104
+ */
105
+ type ShellRule = {
106
+ /** Short identifier, used in counts, log lines and test names. */
107
+ name: string;
108
+ match: RegExp;
109
+ /** If this also matches, the segment passes silently. */
110
+ except?: RegExp;
111
+ /** One sentence, delivered to the model verbatim. */
112
+ tip: string;
113
+ };
114
+
115
+ const SHELL_RULES: ShellRule[] = [
116
+ {
117
+ name: "bash-search",
118
+ // `git grep` is included deliberately: it was eleven of fourteen shell
119
+ // calls on one measured slice, and it is exactly what tilth_tilth_search
120
+ // does better.
121
+ match: /^(?:rg|grep|egrep|fgrep|ag|git\s+grep)\b/,
122
+ // Counting matches and listing matching files are answers the structured
123
+ // search does not give as directly, so those flags pass.
124
+ except: /(?:^|\s)-(?:c|l|-count|-files-with-matches|-files)\b/,
125
+ tip: "use tilth_tilth_search to search the code (kind:content for text, kind:regex for patterns, kind:symbol for definitions, kind:callers for call sites) — it ranks results and returns definitions first. Filtering another command's output with grep is fine.",
126
+ },
127
+ {
128
+ name: "bash-find",
129
+ match: /^(?:find|fd)\b/,
130
+ // find used to run an action rather than to list files.
131
+ except: /\s-(?:exec|execdir|ok|okdir|delete)\b/,
132
+ tip: "use tilth_tilth_files with a glob pattern to locate files.",
133
+ },
134
+ {
135
+ name: "bash-read",
136
+ // Reading a file through the shell: cat with a file argument, or a slice
137
+ // taken with sed/head/tail. Excludes heredocs, stdin, and redirects, which
138
+ // are writes rather than reads.
139
+ match: /^(?:cat\s+(?!<<|-\s|-$)\S|sed\s+-n\b|head\b|tail\b)/,
140
+ except: /[<>]/,
141
+ tip: "use tilth_tilth_read instead — `mode: \"full\"` for a file under review, `paths` to read several at once, `sections` for ranges of a file you have already read. A review assembled from line-range fragments misses the defects that span a file.",
142
+ },
143
+ ];
144
+
145
+ /**
146
+ * A built-in tool that duplicates a tilth tool, and what to use instead.
147
+ *
148
+ * The shell rules above only ever see the shell tool's `command`, so they are
149
+ * blind to OpenCode's own search tools. On one measured slice a model refused
150
+ * its fourth `rg` switched to the built-in `grep` and used it six more times; on
151
+ * another it skipped the shell entirely and went straight to `grep` nine times,
152
+ * drawing no rule at all. Steering away from the shell while leaving an
153
+ * unpoliced tool that does the same thing just moves the traffic.
154
+ */
155
+ type BuiltinRule = {
156
+ name: string;
157
+ tip: string;
158
+ /**
159
+ * Tipped every time but never refused. Reading a file is the core activity of
160
+ * a review, and a reviewer refused the ability to read has no move left that
161
+ * gets the job done.
162
+ */
163
+ adviseOnly?: boolean;
164
+ };
165
+
166
+ const BUILTIN_RULES: Record<string, BuiltinRule> = {
167
+ grep: {
168
+ name: "builtin-search",
169
+ tip: "use tilth_tilth_search rather than the plain grep tool — it ranks results, returns definitions before usages, and takes kind:content, kind:regex, kind:symbol and kind:callers. Comma-separate up to five symbols to answer several questions in one call.",
170
+ },
171
+ glob: {
172
+ name: "builtin-files",
173
+ tip: "use tilth_tilth_files to locate files by pattern.",
174
+ },
175
+ read: {
176
+ name: "builtin-read",
177
+ adviseOnly: true,
178
+ tip: "prefer tilth_tilth_read — it takes `paths` to read several files in one call and `mode: \"full\"` to force whole-file content for anything under review.",
179
+ },
180
+ };
181
+
182
+ /** Classify a built-in tool call: warned, or fine. */
183
+ const checkBuiltinTool = (tool: string): { rule: string; tip: string; adviseOnly: boolean } | null => {
184
+ const hit = BUILTIN_RULES[tool];
185
+ return hit ? { rule: hit.name, tip: hit.tip, adviseOnly: hit.adviseOnly === true } : null;
186
+ };
187
+
188
+ /**
189
+ * Shell commands refused on sight, with no warning ladder.
190
+ *
191
+ * Reserved for commands that cannot produce a useful answer, so there is no
192
+ * cost to refusing the first one. A filesystem-wide `find` qualifies: the
193
+ * review checkout is a bare git worktree with no dependencies installed, so
194
+ * searching outside it finds nothing that is under review, and the one measured
195
+ * instance spent 111 seconds to return zero bytes.
196
+ */
197
+ const isFilesystemWideFind = (core: string): boolean => {
198
+ if (!/^(?:find|fd)\b/.test(core)) return false;
199
+ const cwd = process.cwd();
200
+ return core
201
+ .split(/\s+/)
202
+ .slice(1)
203
+ .some((tok) => {
204
+ const t = tok.replace(/^['"]/, "").replace(/['"]$/, "");
205
+ if (t.startsWith("~") || t.startsWith("$HOME")) return true;
206
+ if (!t.startsWith("/")) return false;
207
+ return t !== cwd && !t.startsWith(cwd + "/");
208
+ });
209
+ };
210
+
211
+ /**
212
+ * Split a command line into segments and mark each with the separator that
213
+ * introduced it, so pipe targets can be skipped. Quoted regions are stepped
214
+ * over, because a separator inside a search pattern is not a separator.
215
+ */
216
+ const splitSegments = (cmd: string): { sep: string; text: string }[] => {
217
+ const out: { sep: string; text: string }[] = [];
218
+ let sep = "";
219
+ let start = 0;
220
+ let quote = "";
221
+ for (let i = 0; i < cmd.length; i++) {
222
+ const c = cmd[i];
223
+ if (quote) {
224
+ if (c === quote) quote = "";
225
+ continue;
226
+ }
227
+ if (c === "'" || c === '"') {
228
+ quote = c;
229
+ continue;
230
+ }
231
+ const two = cmd.slice(i, i + 2);
232
+ const found = two === "&&" || two === "||" ? two : c === ";" || c === "|" ? c : "";
233
+ if (!found) continue;
234
+ out.push({ sep, text: cmd.slice(start, i) });
235
+ sep = found;
236
+ i += found.length - 1;
237
+ start = i + 1;
238
+ }
239
+ out.push({ sep, text: cmd.slice(start) });
240
+ return out;
241
+ };
242
+
243
+ /** Strip leading environment assignments and wrappers that hide the real command. */
244
+ const commandCore = (segment: string): string =>
245
+ segment
246
+ .trim()
247
+ .replace(/^(?:[A-Za-z_][A-Za-z0-9_]*=(?:'[^']*'|"[^"]*"|\S*)\s+)+/, "")
248
+ .replace(/^(?:command|timeout\s+\S+|env|nohup|xargs)\s+/, "")
249
+ .trim();
250
+
251
+ /**
252
+ * Log-shaped files, including rotated ones. Reading a log through the shell is
253
+ * analysis, not code reading, and the structured tools are not a better fit.
254
+ *
255
+ * Deliberately narrower than the desktop version of these rules, which also
256
+ * exempts anything under `/tmp`. The review checkout itself lives in `/tmp`, so
257
+ * that exemption here would switch every rule off for every file under review.
258
+ */
259
+ const isLogLikeTarget = (target: string): boolean =>
260
+ /\.(?:log|out|err|jsonl|ndjson|csv|tsv)(?:\.\d+)?$/i.test(
261
+ target.replace(/^['"]/, "").replace(/['"]$/, ""),
262
+ );
263
+
264
+ /**
265
+ * File-argument tokens of a command: skip the command name, flags, quoted
266
+ * tokens (search patterns) and bare words with neither a slash nor an
267
+ * extension. A heuristic — a miss only means the rule fires as it would have.
268
+ */
269
+ const fileArgs = (core: string): string[] =>
270
+ core
271
+ .split(/\s+/)
272
+ .slice(1)
273
+ .filter(
274
+ (tok) =>
275
+ tok.length > 0 &&
276
+ !tok.startsWith("-") &&
277
+ !/^['"]/.test(tok) &&
278
+ (tok.includes("/") || /\.[A-Za-z0-9]+$/.test(tok)),
279
+ );
280
+
281
+ /** Classify a shell command: refused outright, warned, or fine. */
282
+ const checkShellCommand = (cmd: string): { rule: string; tip: string; deny: boolean } | null => {
283
+ for (const segment of splitSegments(cmd)) {
284
+ if (segment.sep === "|") continue;
285
+ const core = commandCore(segment.text);
286
+
287
+ if (isFilesystemWideFind(core))
288
+ return {
289
+ rule: "find-outside-checkout",
290
+ deny: true,
291
+ tip: "search outside the review checkout, which is a bare worktree with no dependencies installed and nothing else of yours on disk. Stay inside the checkout and use tilth_tilth_files.",
292
+ };
293
+
294
+ for (const rule of SHELL_RULES) {
295
+ if (rule.except?.test(core)) continue;
296
+ if (!rule.match.test(core)) continue;
297
+ const args = fileArgs(core);
298
+ if (args.length > 0 && args.every(isLogLikeTarget)) continue;
299
+ return { rule: rule.name, tip: rule.tip, deny: false };
300
+ }
301
+ }
302
+ return null;
303
+ };
304
+
305
+ /** File-writing tools whose input names one target file. */
306
+ const PATH_WRITE_TOOLS = new Set(["write", "edit", "multiedit"]);
307
+ /** File-writing tools whose targets are buried in a patch body. */
308
+ const PATCH_WRITE_TOOLS = new Set(["apply_patch", "patch"]);
309
+
310
+ /**
311
+ * Refuse any file write except to the output file.
312
+ *
313
+ * A reviewer has exactly one thing to write, and the pipeline only reads it
314
+ * from the one path the prompt names. Measured on one run: both slices wrote
315
+ * their findings to a path with the 12-character head SHA of their working
316
+ * directory in place of the run tag's shorter one, and the run failed with
317
+ * $1.52 of finished review sitting in files nothing read. Refusing the write
318
+ * at the moment it is made, with the correct path in the error, lets the agent
319
+ * retry it in the same turn.
320
+ */
321
+ const checkWriteTarget = (tool: string, input: unknown, outFile: string, cwd: string): string | null => {
322
+ if (!outFile) return null;
323
+ if (PATCH_WRITE_TOOLS.has(tool)) {
324
+ return `The "${tool}" tool is not available in a review. Write your output with the write tool, to \`${outFile}\`.`;
325
+ }
326
+ if (!PATH_WRITE_TOOLS.has(tool)) return null;
327
+ const fields = (input ?? {}) as { path?: unknown; filePath?: unknown };
328
+ const target = typeof fields.path === "string" ? fields.path : fields.filePath;
329
+ if (typeof target === "string" && path.resolve(cwd, target) === path.resolve(cwd, outFile)) return null;
330
+ return (
331
+ `Writing to "${String(target)}" is refused. The only file you may write is \`${outFile}\` — ` +
332
+ `copy that path exactly as given, character for character. Nothing else may be written during a review.`
333
+ );
334
+ };
335
+
336
+ /**
337
+ * Content parts that are not blocks in the provider's sense. A message can end
338
+ * with one of these after its last real block.
339
+ */
340
+ const isFramePart = (type: string): boolean => type === "effort" || type.startsWith("step");
341
+ const isThinkingPart = (type: string): boolean => type === "reasoning" || type === "thinking";
342
+
343
+ type ContentPart = { type?: string };
344
+ type RepairableMessage = { role?: string; content?: readonly ContentPart[] };
345
+
346
+ /**
347
+ * Drop a thinking block left at the end of an assistant message.
348
+ *
349
+ * Anthropic refuses any request whose history contains an assistant message
350
+ * whose final block is `thinking`, with `messages.N: The final block in an
351
+ * assistant message cannot be "thinking"`. The refusal is fatal: it happens
352
+ * while rebuilding the whole history, so the session cannot continue and the
353
+ * slice delivers nothing. Measured on PR #13202 under OpenCode V1 it killed two
354
+ * consecutive runs at step 9 and step 5, $1.12 for no review. Whether V2 can
355
+ * still produce such a history is not established, so the guard stays; it only
356
+ * ever acts on a request that would otherwise fail.
357
+ *
358
+ * Dropping the block is safe: Anthropic requires thinking blocks be preserved
359
+ * only where they precede a tool call in the same turn, and a block in final
360
+ * position by definition precedes nothing.
361
+ *
362
+ * The history's messages may be frozen, so an affected message is replaced in
363
+ * the array with a copy rather than edited in place.
364
+ */
365
+ const repairTrailingThinking = (messages: RepairableMessage[]): number => {
366
+ let repaired = 0;
367
+ for (let i = 0; i < messages.length; i++) {
368
+ const message = messages[i];
369
+ if (message?.role !== "assistant" || !Array.isArray(message.content)) continue;
370
+ const content = message.content;
371
+ let last = content.length - 1;
372
+ while (last >= 0 && isFramePart(content[last]?.type ?? "")) last--;
373
+ if (last < 0 || !isThinkingPart(content[last]?.type ?? "")) continue;
374
+ const copy = Object.assign(Object.create(Object.getPrototypeOf(message)), message, {
375
+ content: content.filter((_, j) => j !== last),
376
+ });
377
+ messages[i] = copy;
378
+ repaired++;
379
+ }
380
+ return repaired;
381
+ };
382
+
383
+ type Tokens = {
384
+ input?: number;
385
+ output?: number;
386
+ reasoning?: number;
387
+ cache?: { read?: number; write?: number };
388
+ };
389
+
390
+ type StepData = { sessionID?: string; cost?: number; tokens?: Tokens };
391
+
392
+ export type ToolBefore = { tool: string; sessionID?: string; id?: string; input: unknown };
393
+ type ToolAfter = { tool: string; sessionID?: string; id?: string; input?: unknown } & (
394
+ | { status: "completed"; result: { content?: unknown } }
395
+ | { status: "error"; error?: unknown }
396
+ );
397
+
398
+ /** The slice of the V2 plugin context this plugin uses. */
399
+ export type GovernorContext = {
400
+ event: {
401
+ subscribe(options: { signal: AbortSignal }): AsyncIterable<{ type?: string; data?: unknown }>;
402
+ };
403
+ tool: {
404
+ hook(name: "execute.before", fn: (e: ToolBefore) => void | Promise<void>): unknown;
405
+ hook(name: "execute.after", fn: (e: ToolAfter) => void | Promise<void>): unknown;
406
+ list(): Promise<readonly { id: string }[]>;
407
+ };
408
+ session: {
409
+ hook(name: "prompt", fn: (e: unknown) => void | Promise<void>): unknown;
410
+ hook(name: "context", fn: (e: { messages: RepairableMessage[] }) => void | Promise<void>): unknown;
411
+ interrupt(input: { sessionID: string }): Promise<unknown>;
412
+ };
413
+ };
414
+
415
+ /** Append text to a tool result, whichever of its two shapes the result has. */
416
+ const appendToResult = (result: { content?: unknown }, text: string) => {
417
+ if (typeof result.content === "string") {
418
+ result.content += text;
419
+ } else if (Array.isArray(result.content)) {
420
+ result.content.push({ type: "text", text });
421
+ } else {
422
+ result.content = text;
423
+ }
424
+ };
425
+
426
+ const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));
427
+
428
+ async function setup(ctx: GovernorContext) {
429
+ const budget = Number(process.env.REVIEW_GOVERNOR_BUDGET_USD ?? 0);
430
+ const deadlineMs = Number(process.env.REVIEW_GOVERNOR_DEADLINE_MS ?? 0);
431
+ const outFile = process.env.REVIEW_GOVERNOR_OUT_FILE ?? "";
432
+ const logFile = process.env.REVIEW_GOVERNOR_LOG ?? "";
433
+ const usageFile = process.env.REVIEW_GOVERNOR_USAGE_FILE ?? "";
434
+ const waitForTools = process.env.REVIEW_GOVERNOR_WAIT_FOR_TOOLS ?? "";
435
+ const expectTools = (process.env.REVIEW_GOVERNOR_EXPECT_TOOLS ?? "").split(",").filter(Boolean);
436
+
437
+ /**
438
+ * Taken when the plugin loads, which is process start: the whole point is to
439
+ * bound the call the pipeline is waiting on, and that clock starts before the
440
+ * first token.
441
+ */
442
+ const startedAt = Date.now();
443
+ let spent = 0;
444
+ let sessionID = "";
445
+ let aborted = false;
446
+ let waited = false;
447
+ const usage = {
448
+ costUsd: 0,
449
+ numTurns: 0,
450
+ usage: {
451
+ input_tokens: 0,
452
+ output_tokens: 0,
453
+ reasoning_tokens: 0,
454
+ cache_read_input_tokens: 0,
455
+ cache_creation_input_tokens: 0,
456
+ },
457
+ };
458
+ /**
459
+ * Times each shell rule has been tipped. Plugin-wide rather than keyed by
460
+ * session, because one pipeline invocation is one process running one
461
+ * session; the point is to interrupt a habit within a single review.
462
+ */
463
+ const warnCounts = new Map<string, number>();
464
+ /** Start times by call ID, so the log can carry how long each tool took. */
465
+ const started = new Map<string, number>();
466
+
467
+ /**
468
+ * Written straight to a file rather than through OpenCode's logger, so that a
469
+ * governor decision can still be read back when the run is being diagnosed
470
+ * precisely because the session went wrong.
471
+ */
472
+ const log = (event: string, extra: Record<string, unknown> = {}) => {
473
+ if (!logFile) return;
474
+ try {
475
+ appendFileSync(logFile, JSON.stringify({ t: Date.now(), event, spent, ...extra }) + "\n");
476
+ } catch {
477
+ /* diagnostics are never worth failing a review over */
478
+ }
479
+ };
480
+
481
+ /** No limit of either kind configured means no governing: every stage is inert. */
482
+ const capped = budget > 0 || deadlineMs > 0;
483
+ const elapsedMs = () => Date.now() - startedAt;
484
+ /**
485
+ * How far along the binding limit is, as a fraction. An unconfigured limit
486
+ * contributes zero and so can never be the binding one; with both set, the
487
+ * one nearer its ceiling decides, which is what makes cost and time a single
488
+ * ladder rather than two that have to agree.
489
+ */
490
+ const pressure = () =>
491
+ Math.max(budget > 0 ? spent / budget : 0, deadlineMs > 0 ? elapsedMs() / deadlineMs : 0);
492
+ /** Which limit is in force, for messages the model reads. */
493
+ const binding = (): "cost" | "time" =>
494
+ deadlineMs > 0 && (budget <= 0 || elapsedMs() / deadlineMs >= spent / budget) ? "time" : "cost";
495
+ /** One clause naming the limit that is out, in the units it is measured in. */
496
+ const limitNote = () =>
497
+ binding() === "time"
498
+ ? `Time limit reached: ${Math.round(elapsedMs() / 1000)}s of ${Math.round(deadlineMs / 1000)}s`
499
+ : `Budget exhausted: $${spent.toFixed(2)} of $${budget.toFixed(2)}`;
500
+ const over = () => capped && pressure() >= 1;
501
+ const delivered = () => outFile !== "" && existsSync(outFile);
502
+
503
+ const onStep = async (step: StepData) => {
504
+ if (step.sessionID) sessionID = step.sessionID;
505
+ const cost = step.cost ?? 0;
506
+ spent += cost;
507
+ usage.costUsd += cost;
508
+ usage.numTurns += 1;
509
+ usage.usage.input_tokens += step.tokens?.input ?? 0;
510
+ usage.usage.output_tokens += step.tokens?.output ?? 0;
511
+ usage.usage.reasoning_tokens += step.tokens?.reasoning ?? 0;
512
+ usage.usage.cache_read_input_tokens += step.tokens?.cache?.read ?? 0;
513
+ usage.usage.cache_creation_input_tokens += step.tokens?.cache?.write ?? 0;
514
+ if (usageFile) {
515
+ try {
516
+ writeFileSync(usageFile, JSON.stringify(usage));
517
+ } catch {
518
+ /* the stream total is the fallback */
519
+ }
520
+ }
521
+ log("step", { cost, ms: elapsedMs(), tokens: step.tokens ?? null });
522
+
523
+ if (!capped || aborted || pressure() < ABORT_AT) return;
524
+ if (delivered()) return;
525
+ if (!sessionID) return;
526
+ aborted = true;
527
+ log("abort", { sessionID });
528
+ try {
529
+ await ctx.session.interrupt({ sessionID });
530
+ } catch (error) {
531
+ log("abort-failed", { error: error instanceof Error ? error.message : String(error) });
532
+ }
533
+ };
534
+
535
+ const events = new AbortController();
536
+ void (async () => {
537
+ try {
538
+ for await (const event of ctx.event.subscribe({ signal: events.signal })) {
539
+ // A failed step can still have been billed, and says so when it was.
540
+ if (event.type === "session.step.ended" || event.type === "session.step.failed") {
541
+ const data = (event.data ?? {}) as StepData;
542
+ if (event.type === "session.step.failed" && data.cost === undefined) continue;
543
+ await onStep(data);
544
+ }
545
+ }
546
+ } catch (error) {
547
+ if (!events.signal.aborted) {
548
+ log("events-failed", { error: error instanceof Error ? error.message : String(error) });
549
+ }
550
+ }
551
+ })();
552
+
553
+ await ctx.session.hook("prompt", async () => {
554
+ if (!waitForTools || waited) return;
555
+ waited = true;
556
+ const begun = Date.now();
557
+ while (Date.now() - begun < TOOL_WAIT_MS) {
558
+ try {
559
+ const ids = (await ctx.tool.list()).map((t) => t.id);
560
+ const matched = ids.filter((id) => id.startsWith(waitForTools));
561
+ if (matched.length) {
562
+ // Builds of one tool can share a version number and differ in what
563
+ // they expose, so the list itself is the record of which one ran.
564
+ const missing = expectTools.filter((id) => !ids.includes(id));
565
+ log("tools-ready", { ms: Date.now() - begun, tools: matched, ...(missing.length ? { missing } : {}) });
566
+ if (missing.length) console.error(`review-governor: guidance names tools this session lacks: ${missing.join(", ")}`);
567
+ return;
568
+ }
569
+ } catch {
570
+ /* keep waiting; the timeout below still bounds it */
571
+ }
572
+ await sleep(250);
573
+ }
574
+ log("tools-missing", { prefix: waitForTools, ms: Date.now() - begun });
575
+ });
576
+
577
+ await ctx.session.hook("context", (request) => {
578
+ // Mutating the message list is not the same as mutating the system
579
+ // prompt: these are the turns after the cached prefix, so a repair here
580
+ // does not invalidate the cache.
581
+ try {
582
+ const repaired = repairTrailingThinking(request.messages ?? []);
583
+ if (repaired > 0) log("repair-trailing-thinking", { repaired });
584
+ } catch (error) {
585
+ log("repair-failed", { error: error instanceof Error ? error.message : String(error) });
586
+ }
587
+ });
588
+
589
+ await ctx.tool.hook("execute.after", (call) => {
590
+ const begun = call.id ? started.get(call.id) : undefined;
591
+ if (call.id) started.delete(call.id);
592
+ // Logged here rather than only in `before`, so that the next command that
593
+ // spends two minutes returning nothing is one line in this file instead of
594
+ // an afternoon decoding the event stream.
595
+ log("tool-done", { tool: call.tool, status: call.status, ms: begun ? Date.now() - begun : null });
596
+ if (call.status !== "completed") return;
597
+
598
+ const input = (call.input ?? {}) as { command?: unknown };
599
+ const command = call.tool === "shell" && typeof input.command === "string" ? input.command : "";
600
+ const shell = command ? checkShellCommand(command) : null;
601
+ const builtin = call.tool === "shell" ? null : checkBuiltinTool(call.tool);
602
+ const hit = shell && !shell.deny ? shell : builtin;
603
+ if (hit) {
604
+ const advise = "adviseOnly" in hit && hit.adviseOnly;
605
+ const n = warnCounts.get(hit.rule) ?? 0;
606
+ // Appended to the tool's own result rather than pushed into the system
607
+ // prompt: same words, no cache invalidation.
608
+ appendToResult(
609
+ call.result,
610
+ `\n\n[tool tip ${advise ? n : `${n}/${WARN_LIMIT}`}] ${hit.tip}` +
611
+ (!advise && n >= WARN_LIMIT ? " Further uses this session will be refused." : ""),
612
+ );
613
+ }
614
+
615
+ if (!capped || over() || pressure() < NUDGE_AT) return;
616
+ // Above the limit this is silent, because the refusal in `execute.before`
617
+ // carries the message.
618
+ const used =
619
+ binding() === "time"
620
+ ? `You have used ${Math.round(elapsedMs() / 1000)}s of a ${Math.round(deadlineMs / 1000)}s time limit.`
621
+ : `You have spent $${spent.toFixed(2)} of a $${budget.toFixed(2)} budget.`;
622
+ appendToResult(
623
+ call.result,
624
+ `\n\n[WRAP UP] ${used} ` +
625
+ `Begin wrapping up: finish the investigation you are in the middle of, and write your ` +
626
+ `findings file before the limit runs out. A file with fewer findings is worth far more ` +
627
+ `than no file at all.`,
628
+ );
629
+ log("nudge", { tool: call.tool, binding: binding() });
630
+ });
631
+
632
+ await ctx.tool.hook("execute.before", (call) => {
633
+ if (call.sessionID) sessionID = call.sessionID;
634
+ if (call.id) started.set(call.id, Date.now());
635
+
636
+ if (call.tool === "shell") {
637
+ const input = (call.input ?? {}) as { command?: unknown; timeout?: unknown; background?: unknown };
638
+ const command = typeof input.command === "string" ? input.command : "";
639
+ // Applied to every shell call, including the ones no rule below matches.
640
+ // An unset timeout is the two-minute default and zero means none, so
641
+ // both are capped too.
642
+ const asked = typeof input.timeout === "number" && input.timeout > 0 ? input.timeout : Infinity;
643
+ if (asked > MAX_SHELL_MS) input.timeout = MAX_SHELL_MS;
644
+ // A background command has no timeout at all and outlives the call that
645
+ // started it; nothing a reviewer runs needs one.
646
+ if (input.background) input.background = false;
647
+
648
+ const hit = command ? checkShellCommand(command) : null;
649
+ if (hit) {
650
+ const n = (warnCounts.get(hit.rule) ?? 0) + 1;
651
+ warnCounts.set(hit.rule, n);
652
+ const refuse = hit.deny || n > WARN_LIMIT;
653
+ log("bash-rule", { rule: hit.rule, count: n, refused: refuse, ms: elapsedMs(), command });
654
+ // Throwing hands the message to the model verbatim as the tool's
655
+ // error, which is the only channel that can explain itself. Warned
656
+ // patterns get WARN_LIMIT uses first, because an unattended reviewer
657
+ // refused a tool it was relying on can burn its remaining turns
658
+ // flailing; a refusal it has been told about three times cannot
659
+ // surprise it.
660
+ if (refuse) throw new Error(`Do not ${hit.tip}`);
661
+ }
662
+ } else {
663
+ // Past the limit with the file delivered, the refusal below says the
664
+ // review is complete, which is the more useful thing to hear.
665
+ const refusal = over() && delivered() ? null : checkWriteTarget(call.tool, call.input, outFile, process.cwd());
666
+ if (refusal) {
667
+ log("write-refused", { tool: call.tool, refusal });
668
+ throw new Error(refusal);
669
+ }
670
+ // Same ladder, applied to the built-in tools that duplicate a tilth
671
+ // tool. Kept separate from the shell path because these have no command
672
+ // string to inspect: the tool's own name is the whole signal.
673
+ const hit = checkBuiltinTool(call.tool);
674
+ if (hit) {
675
+ const n = (warnCounts.get(hit.rule) ?? 0) + 1;
676
+ warnCounts.set(hit.rule, n);
677
+ const refuse = !hit.adviseOnly && n > WARN_LIMIT;
678
+ log("builtin-rule", { rule: hit.rule, tool: call.tool, count: n, refused: refuse, ms: elapsedMs() });
679
+ if (refuse) throw new Error(`Do not ${hit.tip}`);
680
+ }
681
+ }
682
+
683
+ if (!over()) {
684
+ log("tool", { tool: call.tool, allowed: true });
685
+ return;
686
+ }
687
+ // Once the findings file is on disk there is nothing left worth paying
688
+ // for, so the write goes too and the agent runs out of moves.
689
+ const allow = call.tool === "write" && !delivered();
690
+ log("tool", { tool: call.tool, allowed: allow });
691
+ if (allow) return;
692
+ throw new Error(
693
+ delivered()
694
+ ? `${limitNote()}, and your findings file has been written. This review is complete. ` +
695
+ `Stop calling tools and finish your turn.`
696
+ : `${limitNote()}. The "${call.tool}" tool ` +
697
+ `is switched off. Write your findings file now with what you have already established — ` +
698
+ `that is the only tool still available, and an unwritten file means this review is lost.`,
699
+ );
700
+ });
701
+
702
+ log("setup", { budget, deadlineMs, cwd: process.cwd() });
703
+ return () => events.abort();
704
+ }
705
+
706
+ /** Exposed for the tests. Not a plugin; OpenCode loads only the default export. */
707
+ export const helpers = { checkShellCommand, checkBuiltinTool, checkWriteTarget, repairTrailingThinking };
708
+
709
+ export default { id: "review-governor", setup };