dsh-taskbridge 0.0.0-stage → 1.3.2

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 (75) hide show
  1. package/CHANGELOG.md +763 -0
  2. package/LICENSE +21 -0
  3. package/README.md +622 -3
  4. package/bin/dsh-delegate-codex-agent.js +115 -0
  5. package/bin/dsh-delegate-control.d.ts +90 -0
  6. package/bin/dsh-delegate-control.js +450 -0
  7. package/bin/dsh-delegate-mcp.d.ts +121 -0
  8. package/bin/dsh-delegate-mcp.js +273 -0
  9. package/codex/dsh-taskbridge.toml +247 -0
  10. package/cordis.patch.yml +6 -0
  11. package/docs/INTRODUCTION.md +15 -0
  12. package/docs/INTRODUCTION.zh.md +34 -0
  13. package/docs/auth-contract.md +138 -0
  14. package/docs/claude-code.md +31 -0
  15. package/docs/codex-integration.md +937 -0
  16. package/docs/contracts-stage-b.md +443 -0
  17. package/docs/conversation-placement.md +304 -0
  18. package/docs/plugin-market.md +30 -0
  19. package/docs/redaction-contract.md +127 -0
  20. package/docs/runtime-compatibility.md +223 -0
  21. package/docs/silent-wait.md +191 -0
  22. package/docs/taskbridge-upgrade.md +28 -0
  23. package/docs/taskdispatch-upgrade.md +25 -0
  24. package/docs/worker-permissions.md +347 -0
  25. package/docs/workspace-contract.md +538 -0
  26. package/icon.svg +1 -0
  27. package/lib/client.d.ts +118 -0
  28. package/lib/client.js +3232 -0
  29. package/locale/en.json +7 -0
  30. package/locale/zh.json +7 -0
  31. package/package.json +138 -4
  32. package/src/auth/fence.js +361 -0
  33. package/src/auth/grants.js +789 -0
  34. package/src/client/api.js +2322 -0
  35. package/src/client/index.jsx +2333 -0
  36. package/src/client/styles.js +251 -0
  37. package/src/codex/installer.js +3299 -0
  38. package/src/codex/seam.js +429 -0
  39. package/src/codex/toml.js +784 -0
  40. package/src/config/defaults.js +164 -0
  41. package/src/config/redact.js +184 -0
  42. package/src/config/settings.js +629 -0
  43. package/src/config/store.js +186 -0
  44. package/src/config/validate.js +763 -0
  45. package/src/credentials/seam.js +202 -0
  46. package/src/http/execution-plane.js +456 -0
  47. package/src/http/respond.js +175 -0
  48. package/src/http/user-plane.js +1122 -0
  49. package/src/index.d.ts +332 -0
  50. package/src/index.js +657 -0
  51. package/src/jobs/activity.js +1008 -0
  52. package/src/jobs/engine.js +3614 -0
  53. package/src/jobs/history.js +1467 -0
  54. package/src/jobs/title.js +17 -0
  55. package/src/mcp/server.js +1821 -0
  56. package/src/mcp/wait.js +536 -0
  57. package/src/model/connectivity.js +371 -0
  58. package/src/model/discovery.js +582 -0
  59. package/src/model/native-catalog.js +68 -0
  60. package/src/model/openai-adapter.js +671 -0
  61. package/src/model/probe.js +264 -0
  62. package/src/model/providers.js +756 -0
  63. package/src/model/routing.js +321 -0
  64. package/src/review/preset.js +868 -0
  65. package/src/review/prompts.js +126 -0
  66. package/src/review/reviewer.js +933 -0
  67. package/src/runtime/agent-runner.js +1740 -0
  68. package/src/runtime/endpoint-discovery.js +118 -0
  69. package/src/runtime/permissions.js +1429 -0
  70. package/src/runtime/sandbox.js +358 -0
  71. package/src/runtime/session-placement.js +1121 -0
  72. package/src/workspace/audit.js +775 -0
  73. package/src/workspace/locks.js +167 -0
  74. package/src/workspace/preflight.js +424 -0
  75. package/src/workspace/worktrees.js +613 -0
@@ -0,0 +1,933 @@
1
+ // Independent additional review.
2
+ //
3
+ // Review exists to give the host a second opinion, not to approve work. Three
4
+ // properties make it independent rather than decorative:
5
+ // 1. It uses its own provider/model/effort selection. Reusing the worker's
6
+ // selection would reproduce the worker's blind spots.
7
+ // 2. It is read-only by construction: a visibility restriction intersected with
8
+ // the tools this agent actually has, a deny-by-default execution guard, and a
9
+ // model-facing assembly transform that filters the tools the request is
10
+ // actually sent with. All three are installed through the shared `runAgent`
11
+ // lifecycle, so review and execution cannot drift apart. Read-only here is a
12
+ // TOOL PERMISSION, not an OS sandbox: a reviewer that somehow obtained a
13
+ // shell would not be confined by this guard.
14
+ // 3. It is off unless enabled, and it has no loop back into execution: a
15
+ // "changes requested" verdict is reported to the host, never turned into an
16
+ // automatic repair round.
17
+ //
18
+ // Review errors are tracked separately from execution errors so a broken
19
+ // reviewer never looks like a broken task.
20
+ //
21
+ // Fail-closed rules. Review refuses to prompt when any read-only mechanism is
22
+ // missing or cannot be installed:
23
+ // - no native tool inventory (`tools.schemas(scope)`),
24
+ // - no `tools.restrict()`,
25
+ // - no `tools.guard()`,
26
+ // - no `system-prompt/assemble` registration facility (`agentCtx.on`),
27
+ // - no read-only tool in the inventory to allow,
28
+ // - an assembly that is missing, malformed, or still carries a name outside the
29
+ // computed read-only set,
30
+ // - an inventory that does not look exactly like the read-only evidence it was
31
+ // drawn from.
32
+ // A review that cannot prove it is restricted does not run at all.
33
+ //
34
+ // Why the restriction alone is not enough (`assertAdvertised`). Native
35
+ // `tools.restrict()` is deliberately NOT a per-agent capability filter over
36
+ // everything an agent can see: `ToolRuntime.view()` applies restrictions to the
37
+ // surface a scope INHERITS (the global layer and every ancestor scope on its
38
+ // chain) and always keeps what the scope's OWN layer registers. That exemption
39
+ // is native design — the delegation runtime registers a child's own structured
40
+ // output tool into the child's layer — and `dsh-tool-subagent` uses the same
41
+ // mechanism to install a live `subagent` tool into a composing agent's own
42
+ // layer before its setup hook runs. So the reviewer's own scope CAN hold tools
43
+ // the restriction cannot remove, and there is no supported API to take another
44
+ // plugin's scope-local tool away.
45
+ //
46
+ // What removes them from the model's view (`installAssemblyFilter`). The Agent
47
+ // loop builds each request from `systemPrompt.assemble(...)`, whose
48
+ // `tools` field is exactly what the provider is sent
49
+ // (`dsh-agent-loop` passes `assembly.tools` into the request). The
50
+ // `system-prompt/assemble` waterfall transforms `PromptAssembly`
51
+ // (`(assembly, context, next)` over `{ sections, contexts, tools, variables }`),
52
+ // so review registers a scoped transform during setup that returns the
53
+ // downstream assembly with `tools` filtered to the fixed allow-list intersected
54
+ // with the native names, and proves the resulting names are exactly that set
55
+ // before returning it. A missing or malformed assembly, or a filter that cannot
56
+ // be registered, fails the review before any request is made.
57
+ //
58
+ // Scope of the claim. The transform filters the MODEL-FACING assembly of this
59
+ // reviewer. It does not remove anyone's registration from the runtime registry:
60
+ // a sibling agent's `subagent` still exists there, and this module never claims
61
+ // otherwise. The execution guard is what makes the tool non-executable for the
62
+ // reviewer regardless of where the name came from, and the assembly filter is
63
+ // what keeps it out of the request in the first place.
64
+ //
65
+ // Which composition the reviewer joins (`planComposition`). The deployment's
66
+ // DEFAULT preset is not a read-only surface: the shipped `standard` composition
67
+ // mounts `dsh-tool-subagent`, whose tool survives a scope restriction by design,
68
+ // so a reviewer joining it cannot be proven read-only. Refusing every review on
69
+ // such a deployment would make the feature unreachable; mounting the default
70
+ // anyway would be a false claim. So review composes its own: one dedicated,
71
+ // plugin-owned native preset whose only rows are `dsh-tool-fs`
72
+ // (`read`/`read_image` on, `write`/`edit` off) and `dsh-tool-fs-search`. There is
73
+ // no delegation row, so nothing agent-local is injected, and the scoped
74
+ // restriction still removes anything inherited. The composition is decided by
75
+ // capability probes on the registry this review was handed — never by a name:
76
+ // - `register()` + `mount()` + `resolve()` present -> the plugin-owned
77
+ // composition is used, and its preparation is verified before any agent
78
+ // exists;
79
+ // - a registry that mounts but cannot register -> the default composition, and
80
+ // the advertised-surface proof still refuses anything it cannot prove
81
+ // (`REVIEW_TOOL_SCOPE_UNENFORCEABLE`), so an unusable registry fails closed
82
+ // with a distinct reason instead of pretending to be read-only.
83
+
84
+ import { randomUUID } from 'node:crypto';
85
+ import { LIMITS } from '../config/defaults.js';
86
+ import { redactText } from '../config/redact.js';
87
+ import { DEFAULT_MAX_TOKENS, RUN_OUTCOMES, RunError, diagnostic, runAgent } from '../runtime/agent-runner.js';
88
+ import { PRESET_CODES, reviewCompositionRows } from './preset.js';
89
+ import { REDACTED_PLACEHOLDER } from './prompts.js';
90
+
91
+ /** Review verdicts. `unknown` is used when the reviewer produced no parsable verdict. */
92
+ export const REVIEW_VERDICTS = Object.freeze(['approve', 'changes-requested', 'unknown']);
93
+
94
+ /**
95
+ * Review outcome states, kept distinct from the execution outcome.
96
+ *
97
+ * `cancelled` is its own state rather than a flavour of `failed`: a cancelled
98
+ * review says nothing about the work, so the host must not read it as a finding.
99
+ */
100
+ export const REVIEW_STATES = Object.freeze({
101
+ disabled: 'disabled',
102
+ notRun: 'not_run',
103
+ completed: 'completed',
104
+ failed: 'failed',
105
+ cancelled: 'cancelled',
106
+ });
107
+
108
+ /** Stable review error codes. None of them can be produced by execution. */
109
+ export const REVIEW_CODES = Object.freeze({
110
+ agentsUnavailable: 'REVIEW_AGENTS_UNAVAILABLE',
111
+ presetsUnavailable: 'REVIEW_PRESETS_UNAVAILABLE',
112
+ // The registry cannot register the dedicated read-only composition, so this
113
+ // deployment cannot compose a provably read-only reviewer. Distinct from
114
+ // `presetsUnavailable` (no registry at all) and from `scopeUnenforceable` (a
115
+ // composition that mounted but still advertises a non-read tool).
116
+ presetUnavailable: PRESET_CODES.unsupported,
117
+ // Preparation of the plugin-owned composition failed: registration refused,
118
+ // an unusable row, absent tool packages, or its own bounded deadline.
119
+ presetPrepareFailed: 'REVIEW_PRESET_PREPARE_FAILED',
120
+ promptEmpty: 'REVIEW_PROMPT_EMPTY',
121
+ promptTooLarge: 'REVIEW_PROMPT_TOO_LARGE',
122
+ restrictUnavailable: 'REVIEW_TOOL_RESTRICT_UNAVAILABLE',
123
+ guardUnavailable: 'REVIEW_TOOL_GUARD_UNAVAILABLE',
124
+ inventoryUnavailable: 'REVIEW_TOOL_INVENTORY_UNAVAILABLE',
125
+ restrictRefused: 'REVIEW_TOOL_RESTRICT_REFUSED',
126
+ // The agent context cannot register the `system-prompt/assemble` transform, so
127
+ // the reviewer has no supported way to keep unremovable names out of the
128
+ // model-facing request. Distinct from a transform that runs and reports a bad
129
+ // assembly (`assemblyMismatch`).
130
+ assemblyUnavailable: 'REVIEW_ASSEMBLY_HOOK_UNAVAILABLE',
131
+ // The model-facing assembly could not be filtered or proven: the downstream
132
+ // value was missing or malformed, or its tool names were not exactly the fixed
133
+ // read-only set intersected with the native inventory. Review fails closed
134
+ // instead of sending a request whose tools it cannot account for.
135
+ assemblyMismatch: 'REVIEW_ASSEMBLY_MISMATCH',
136
+ // The registry advertises tools the read-only policy cannot remove. Native
137
+ // restrictions never filter a scope's own layer, so an agent-local tool (the
138
+ // composing `subagent`) survives them. Retained as a code because a pre-policy
139
+ // inventory that already differs from the read-only evidence is still refused;
140
+ // unremovable names that survive INTO the assembly are now reported as
141
+ // `assemblyMismatch`.
142
+ scopeUnenforceable: 'REVIEW_TOOL_SCOPE_UNENFORCEABLE',
143
+ // The advertised surface after the policy is installed is not exactly the
144
+ // read-only set: the restriction did not take effect as computed.
145
+ surfaceMismatch: 'REVIEW_TOOL_SURFACE_MISMATCH',
146
+ noReadTools: 'REVIEW_NO_READ_TOOLS',
147
+ cancelled: 'REVIEW_CANCELLED',
148
+ timeout: 'REVIEW_TIMEOUT',
149
+ failed: 'REVIEW_FAILED',
150
+ });
151
+
152
+ /**
153
+ * The tools an additional review may execute, by their real native names.
154
+ *
155
+ * These are the names the shipped DSH filesystem plugins register
156
+ * (`dsh-tool-fs`: `read`, `write`, `edit`, `read_image`; `dsh-tool-fs-search`:
157
+ * `glob`, `grep`). Invented names such as `read_file` are not here on purpose:
158
+ * `tools.restrict()` throws on an unknown name, so a wrong name would turn into
159
+ * a runtime failure instead of a restriction. Capability tools outside the list
160
+ * (`subagent`, a shell, any workflow transport) are excluded for the opposite
161
+ * reason: each one can act on the workspace or start another agent, which a
162
+ * read-only reviewer must not be able to do.
163
+ */
164
+ const REVIEW_TOOLS = Object.freeze(['read', 'read_image', 'glob', 'grep']);
165
+
166
+ /** Bound on recorded tool denials, so a hostile reviewer cannot grow history. */
167
+ const MAX_DENIALS = 100;
168
+
169
+ /** Bound on a tool name or denial reason retained in review evidence. */
170
+ const MAX_TOOL_CHARS = 64;
171
+ const MAX_REASON_CHARS = 200;
172
+
173
+ /** Bound on an error message projected into a review record. */
174
+ const MAX_ERROR_CHARS = 400;
175
+
176
+ /**
177
+ * Default bound on preparing the review composition (registration + verification).
178
+ *
179
+ * Registering a two-row composition is import-and-activate work, not model work;
180
+ * it is normally fast. The bound exists so a registry waiting on another plugin
181
+ * cannot hold a review open, and it is deliberately far below the review's own
182
+ * time budget so the failure reads as "composition unavailable", not "review
183
+ * timed out".
184
+ */
185
+ const PREPARE_TIMEOUT_MS = 30_000;
186
+
187
+ /**
188
+ * Tools the reviewer may execute.
189
+ *
190
+ * The set is fixed. `extra` is accepted for call-site compatibility with earlier
191
+ * builds, but it is deliberately ignored: an operator-supplied list must never
192
+ * widen a read-only review into something that can mutate the workspace it is
193
+ * judging. The effective allow-list an agent receives is this set intersected
194
+ * with that agent's real tool inventory.
195
+ * @param {string[]} [extra] - ignored; retained so older callers keep working.
196
+ * @returns {ReadonlySet<string>} allowed tool names.
197
+ */
198
+ export function reviewerToolAllowList(extra = []) {
199
+ // Intentionally not merged: see the doc comment above.
200
+ void extra;
201
+ return new Set(REVIEW_TOOLS);
202
+ }
203
+
204
+ /**
205
+ * Whether a tool name looks like a mutation.
206
+ *
207
+ * Kept for diagnostics only. It is NOT the read-only mechanism: the guard denies
208
+ * every name outside the allow-list, so a write tool with an unexpected name is
209
+ * still denied. Using a name regex as the mechanism would let a new tool name
210
+ * through by accident.
211
+ * @param {string} name - tool name.
212
+ * @returns {boolean} true when the name looks like a mutation.
213
+ */
214
+ export function looksMutating(name) {
215
+ return /(^|[_\-. ])(write|edit|apply|patch|delete|remove|move|rename|chmod|chown|create_file|mkdir|touch|exec|shell|bash|run|spawn|install|git_commit|commit|push|merge|reset|checkout|add)([_\-. ]|$)/i
216
+ .test(String(name ?? ''));
217
+ }
218
+
219
+ /**
220
+ * Decide which composition a review joins, and prepare it.
221
+ *
222
+ * The order of preference is fixed and capability-based, never name-based:
223
+ * 1. a plugin-owned dedicated composition (`composer`), registered and verified
224
+ * once per plugin instance — the supported, read-only-by-construction path.
225
+ * Its preparation replaces the default composition, so no delegation row can
226
+ * inject a scope-local tool in the first place;
227
+ * 2. otherwise the registry's configured default, which `assertAdvertised` will
228
+ * still refuse unless it advertises exactly the read-only set.
229
+ *
230
+ * A preparation failure of the owned composition is NOT silently downgraded to
231
+ * the default: the failure is reported with its own code, because a deployment
232
+ * that *can* compose a read-only reviewer but cannot do so right now is a
233
+ * different problem from one that never could, and falling back would turn a
234
+ * composition bug into a review whose read-only claim rests on a weaker proof.
235
+ * @param {object} deps - review dependencies (`agentPresets`, optional `reviewPresets`).
236
+ * @param {{ presetUnavailable?: string|null }} options - the registry verdict for the reason text.
237
+ * @param {{ timeoutMs: number|null, signal: AbortSignal|null }} bounds - preparation deadline.
238
+ * @returns {Promise<{ presetId: string|undefined, composition: string }>} mount plan.
239
+ * @throws {RunError} with a `REVIEW_*` code when preparation fails.
240
+ */
241
+ async function prepareComposition(deps, registry, bounds) {
242
+ const composer = deps?.reviewPresets;
243
+ if (composer !== undefined && composer !== null && typeof composer.preparation === 'function') {
244
+ // The composer owns the id it created and refuses everything else; a
245
+ // registry that cannot register reports its own distinct code from here.
246
+ const presetId = await composer.preparation(bounds);
247
+ return { presetId, composition: 'dedicated' };
248
+ }
249
+ // No composer in the dependency set: the plugin was not activated with the
250
+ // preset lifecycle wired in. That is a composition fact, not a policy claim,
251
+ // so it is reported as unsupported rather than degrading the proof.
252
+ void registry;
253
+ throw new RunError(
254
+ PRESET_CODES.unsupported,
255
+ 'no read-only review composition is available to this review, so it cannot be composed',
256
+ { composition: 'none' },
257
+ );
258
+ }
259
+
260
+ /**
261
+ * Review the delivered work with a separate model selection, read-only.
262
+ *
263
+ * The review runs through the same native lifecycle as delegation (`runAgent`):
264
+ * preset mount, installed model selection, one prompt, bounded redacted output,
265
+ * timeout and cancellation that also cover pending creation. Review only adds
266
+ * the read-only tool policy and the review-shaped result.
267
+ *
268
+ * @param {object} deps - `agents`, `agentPresets`, optional `reviewPresets` (the
269
+ * plugin-owned composition), `sessions`, `logger`.
270
+ * @param {object} input - `taskId`, `cwd`, `selection`, `prompt`, `timeoutMs`,
271
+ * `signal`, `prepareTimeoutMs`, `extraAllowedTools` (ignored).
272
+ * @returns {Promise<object>} review record with verdict and its own diagnostics.
273
+ */
274
+ export async function reviewWork(deps, input) {
275
+ const options = input ?? {};
276
+ const selection = options.selection ?? {};
277
+ const denials = [];
278
+
279
+ const agents = deps?.agents;
280
+ if (agents === undefined || agents === null || typeof agents.create !== 'function') {
281
+ return failed(REVIEW_CODES.agentsUnavailable, 'the native agent registry is not available', selection, denials);
282
+ }
283
+ // Review reuses the run lifecycle, which joins a preset before installing a
284
+ // tool policy. A missing preset registry means no composition would be
285
+ // mounted, and the restriction would then be computed over the wrong surface.
286
+ const presets = deps?.agentPresets;
287
+ if (presets === undefined || presets === null || typeof presets.mount !== 'function') {
288
+ return failed(
289
+ REVIEW_CODES.presetsUnavailable,
290
+ 'the native agent preset registry is not available, so no tool inventory can be restricted',
291
+ selection,
292
+ denials,
293
+ );
294
+ }
295
+
296
+ const prompt = typeof options.prompt === 'string' ? options.prompt : '';
297
+ if (prompt === '') {
298
+ return failed(REVIEW_CODES.promptEmpty, 'the review prompt is empty', selection, denials);
299
+ }
300
+ if (prompt.length > LIMITS.promptChars) {
301
+ return failed(REVIEW_CODES.promptTooLarge, `the review prompt exceeds ${LIMITS.promptChars} characters`, selection, denials);
302
+ }
303
+
304
+ // Fixed by construction; `extraAllowedTools` cannot widen it.
305
+ const allowed = reviewerToolAllowList(options.extraAllowedTools ?? []);
306
+ const timeoutMs = Number.isInteger(options.timeoutMs) && options.timeoutMs > 0 ? options.timeoutMs : null;
307
+ // Preparation (registering and verifying the composition) has its own bound so
308
+ // it cannot wait out the review's own budget, and it observes the same
309
+ // cancellation the review does.
310
+ const prepareTimeoutMs = Number.isInteger(options.prepareTimeoutMs) && options.prepareTimeoutMs > 0
311
+ ? options.prepareTimeoutMs
312
+ : PREPARE_TIMEOUT_MS;
313
+ const signal = options.signal ?? null;
314
+ const composer = deps?.reviewPresets;
315
+
316
+ let composition;
317
+ try {
318
+ composition = await prepareComposition(deps, presets, { timeoutMs: prepareTimeoutMs, signal });
319
+ } catch (error) {
320
+ // An interruption is terminal but says nothing about the work being reviewed,
321
+ // so it is reported as `cancelled` (its own state) rather than as a review
322
+ // failure. Every other preparation problem is a real failure.
323
+ const reason = typeof error?.code === 'string' ? error.code : '';
324
+ if (reason === PRESET_CODES.cancelled || reason === PRESET_CODES.disposed) {
325
+ return {
326
+ state: REVIEW_STATES.cancelled,
327
+ error: { code: REVIEW_CODES.cancelled, message: 'the additional review was cancelled before it started' },
328
+ verdict: null,
329
+ text: '',
330
+ selection: summarizeSelection(selection),
331
+ denials,
332
+ };
333
+ }
334
+ return failureRecord(error, selection, denials);
335
+ }
336
+ // A cancellation that landed while the composition was preparing must not be
337
+ // followed by an agent creation: the caller asked to stop.
338
+ if (signal?.aborted === true) {
339
+ return {
340
+ state: REVIEW_STATES.cancelled,
341
+ error: { code: REVIEW_CODES.cancelled, message: 'the additional review was cancelled while preparing' },
342
+ verdict: null,
343
+ text: '',
344
+ selection: summarizeSelection(selection),
345
+ denials,
346
+ };
347
+ }
348
+
349
+ try {
350
+ const run = await runAgent(deps, {
351
+ sessionId: options.sessionId ?? randomUUID(),
352
+ prompt,
353
+ cwd: options.cwd,
354
+ selection,
355
+ timeoutMs,
356
+ signal,
357
+ // The same practical output allowance the worker asks for. A reviewer reads
358
+ // evidence (a patch can be long) and then reasons about it, so a smaller
359
+ // budget would starve it into an apparent timeout rather than a verdict. An
360
+ // explicit, valid `maxTokens` on the review input is preserved unchanged.
361
+ maxTokens: options.maxTokens ?? DEFAULT_MAX_TOKENS,
362
+ // The composition this review measured as read-only. `undefined` keeps the
363
+ // registry's configured default; a named id is the plugin-owned one and is
364
+ // only mounted when the composer still owns it.
365
+ presetId: composition.presetId,
366
+ presetOwnership: composer ?? null,
367
+ // The review is not part of the operator's conversation history: it composes
368
+ // its own read-only preset and drives a throwaway session under the id above.
369
+ // Claiming a Workspace (and creating a Session in it) would put a review in
370
+ // the same group as the work it examined and would make it resumable by a
371
+ // later `reuse` run.
372
+ allowUnplaced: true,
373
+ // Runs inside `agents.create` after the preset mount and before the prompt
374
+ // is delivered: the tool policy is in place for every turn this reviewer
375
+ // will ever take, and a policy that cannot be installed fails creation
376
+ // rather than degrading into an unrestricted review.
377
+ setup: (agentCtx, agent) => installReadOnlyTools(agentCtx, agent, allowed, denials),
378
+ });
379
+
380
+ const text = redactText(typeof run.text === 'string' ? run.text : '').trim();
381
+ const base = { selection: summarizeSelection(selection), denials, chars: text.length };
382
+
383
+ if (run.outcome === RUN_OUTCOMES.completed) {
384
+ return {
385
+ state: REVIEW_STATES.completed,
386
+ error: null,
387
+ verdict: parseVerdict(text),
388
+ text: text.slice(0, LIMITS.reviewPromptChars),
389
+ ...base,
390
+ };
391
+ }
392
+ if (run.outcome === RUN_OUTCOMES.cancelled) {
393
+ return {
394
+ state: REVIEW_STATES.cancelled,
395
+ error: { code: REVIEW_CODES.cancelled, message: 'the additional review was cancelled' },
396
+ verdict: null,
397
+ text: text.slice(0, LIMITS.reviewPromptChars),
398
+ ...base,
399
+ };
400
+ }
401
+ if (run.outcome === RUN_OUTCOMES.timedOut) {
402
+ return {
403
+ state: REVIEW_STATES.failed,
404
+ error: { code: REVIEW_CODES.timeout, message: 'the additional review exceeded its time budget' },
405
+ verdict: null,
406
+ text: text.slice(0, LIMITS.reviewPromptChars),
407
+ ...base,
408
+ };
409
+ }
410
+ return {
411
+ state: REVIEW_STATES.failed,
412
+ error: {
413
+ code: REVIEW_CODES.failed,
414
+ message: 'the additional review did not complete',
415
+ // Already bounded and redacted by the runner.
416
+ detail: typeof run.error === 'string' ? run.error.slice(0, MAX_ERROR_CHARS) : null,
417
+ },
418
+ verdict: null,
419
+ text: text.slice(0, LIMITS.reviewPromptChars),
420
+ ...base,
421
+ };
422
+ } catch (error) {
423
+ return failureRecord(error, selection, denials);
424
+ }
425
+ }
426
+
427
+ /**
428
+ * Install the read-only tool policy on one reviewer agent.
429
+ *
430
+ * Four mechanisms, on purpose, because they answer four different questions:
431
+ * - `restrict()` removes disallowed tools from what this agent INHERITS;
432
+ * - `guard()` denies execution even if a name reaches the model another way;
433
+ * - a `system-prompt/assemble` transform filters the tools the request is
434
+ * actually sent with, which is the only supported way to keep a scope-local
435
+ * tool (the composing `subagent`) out of the model's view;
436
+ * - a post-install re-read of the advertised surface proves the restriction
437
+ * took effect exactly as computed before any prompt is delivered.
438
+ *
439
+ * Guards have no allow result, so listener ordering cannot turn a denial back
440
+ * into permission. The transform is registered inside this scoped agent
441
+ * context, so it participates only in this reviewer's assemblies.
442
+ *
443
+ * The allow-list handed to `restrict()` is the intersection of the fixed
444
+ * read-only names and the agent's real inventory. `tools.restrict()` throws on a
445
+ * name the registry does not know, so restricting with the fixed list alone
446
+ * would fail whenever the deployment lacks (say) the image reader. The same
447
+ * intersection is the sole authority for the assembly filter: caller input
448
+ * (`extraAllowedTools`) is ignored by {@link reviewerToolAllowList}, so neither
449
+ * mechanism can be widened.
450
+ * @param {object} agentCtx - the agent's scoped context.
451
+ * @param {object} agent - the agent itself; the scope key for `tools.schemas()`.
452
+ * @param {ReadonlySet<string>} allowed - fixed read-only names.
453
+ * @param {object[]} denials - this review's denial log.
454
+ * @returns {Promise<void>} resolves when the policy is installed and proven.
455
+ * @throws {RunError} when any mechanism is missing, refuses, or the advertised
456
+ * surface is not the read-only set.
457
+ */
458
+ async function installReadOnlyTools(agentCtx, agent, allowed, denials) {
459
+ const tools = agentCtx?.tools;
460
+ if (tools === null || tools === undefined) {
461
+ throw new RunError(REVIEW_CODES.restrictUnavailable, 'the reviewer agent has no tool registry to restrict', {});
462
+ }
463
+ if (typeof tools.restrict !== 'function') {
464
+ throw new RunError(REVIEW_CODES.restrictUnavailable, 'the native tool registry cannot restrict a reviewer agent', {});
465
+ }
466
+ if (typeof tools.guard !== 'function') {
467
+ throw new RunError(REVIEW_CODES.guardUnavailable, 'the native tool registry cannot guard a reviewer agent', {});
468
+ }
469
+ if (typeof tools.schemas !== 'function') {
470
+ throw new RunError(
471
+ REVIEW_CODES.inventoryUnavailable,
472
+ 'the native tool registry cannot report the reviewer tool inventory',
473
+ {},
474
+ );
475
+ }
476
+ // Checked before anything is installed: a reviewer that cannot filter its
477
+ // model-facing assembly must not be half-configured and then prompted.
478
+ if (typeof agentCtx.on !== 'function') {
479
+ throw new RunError(
480
+ REVIEW_CODES.assemblyUnavailable,
481
+ 'the reviewer agent cannot register a system-prompt assembly transform, so its model-facing tools cannot be filtered',
482
+ {},
483
+ );
484
+ }
485
+
486
+ const available = readInventory(tools, agent);
487
+ const usable = REVIEW_TOOLS.filter((name) => available.has(name));
488
+ if (usable.length === 0) {
489
+ throw new RunError(
490
+ REVIEW_CODES.noReadTools,
491
+ 'the reviewer agent has none of the read-only tools, so no review can be proven read-only',
492
+ { inventory: [...available].sort().slice(0, MAX_DENIALS) },
493
+ );
494
+ }
495
+
496
+ const usableSet = new Set(usable);
497
+ try {
498
+ tools.restrict({ allow: usable });
499
+ } catch (error) {
500
+ // Unknown names, an empty filter and a scope the registry refuses all land
501
+ // here. Review must not continue unrestricted.
502
+ throw new RunError(REVIEW_CODES.restrictRefused, 'the reviewer tool restriction was refused', {
503
+ cause: diagnostic(error?.message ?? error),
504
+ });
505
+ }
506
+ tools.guard((execution) => guardExecution(execution, usableSet, allowed, denials));
507
+
508
+ // The model-facing surface. `restrict()` only filters the INHERITED surface,
509
+ // so the visible set can still hold this agent's own registrations (a live
510
+ // `subagent`), and no supported API removes another plugin's scope-local tool.
511
+ // The Agent loop builds each request from `systemPrompt.assemble(...)`, whose
512
+ // `tools` are the schemas the provider is sent, so this scoped transform is
513
+ // what actually keeps those names out of the request. Registering it fails the
514
+ // review closed if the context cannot hold a listener.
515
+ let disposeAssembly;
516
+ try {
517
+ disposeAssembly = agentCtx.on('system-prompt/assemble', (assembly, context, next) => (
518
+ filterAssembledTools(assembly, context, next, usableSet)
519
+ ));
520
+ } catch (error) {
521
+ throw new RunError(
522
+ REVIEW_CODES.assemblyUnavailable,
523
+ 'the reviewer agent could not register a system-prompt assembly transform',
524
+ { cause: diagnostic(error?.message ?? error) },
525
+ );
526
+ }
527
+ if (disposeAssembly === false) {
528
+ throw new RunError(
529
+ REVIEW_CODES.assemblyUnavailable,
530
+ 'the reviewer agent assembly transform was refused by the native context',
531
+ {},
532
+ );
533
+ }
534
+
535
+ // The proof. Reading the surface again is the only supported way to see what
536
+ // the restriction actually left behind, and it happens before the prompt
537
+ // exists. Names it could not remove are expected (a scope-local tool); they
538
+ // are removed from the request by the transform above, and the transform
539
+ // proves that per request. What remains checkable here is that the policy did
540
+ // not remove or fail to apply something it promised.
541
+ assertAdvertised(readInventory(tools, agent), usable, available);
542
+ return undefined;
543
+ }
544
+
545
+ /**
546
+ * Filter one model-facing prompt assembly down to the reviewer's tool set.
547
+ *
548
+ * The native contract of `system-prompt/assemble` is
549
+ * `(assembly, context, next)` where the listener returns the assembly the model
550
+ * will be sent, and `PromptAssembly` is `{ sections, contexts, tools, variables }`.
551
+ * Only `tools` is replaced; every other field is passed through untouched, so
552
+ * sections, contexts and variables stay exactly what the harness assembled.
553
+ *
554
+ * Fail-closed, before the request: a downstream value that is not an object, a
555
+ * `tools` field that is not an array, a schema with no usable `name`, or a
556
+ * provider that returns nothing all throw out of the waterfall. The Agent loop
557
+ * propagates that instead of issuing a request, so the reviewer never runs with
558
+ * tools this function could not account for.
559
+ * @param {unknown} assembly - the assembly collected before the waterfall.
560
+ * @param {unknown} context - the caller's assembly context (unused: the listener
561
+ * is registered on the reviewer's own scope, so it only sees this agent).
562
+ * @param {unknown} next - the continuation returning the downstream assembly.
563
+ * @param {ReadonlySet<string>} usable - the computed read-only set.
564
+ * @returns {Promise<object>} the downstream assembly with only `tools` filtered.
565
+ * @throws {RunError} with `REVIEW_ASSEMBLY_MISMATCH` when the assembly cannot be
566
+ * filtered or proven.
567
+ */
568
+ async function filterAssembledTools(assembly, context, next, usable) {
569
+ // Referenced so the listener signature mirrors the native one; the filter is
570
+ // fixed per agent and never depends on the assembly's own context.
571
+ void context;
572
+ if (typeof next !== 'function') {
573
+ throw new RunError(
574
+ REVIEW_CODES.assemblyMismatch,
575
+ 'the reviewer assembly transform was called without a continuation, so its tools cannot be filtered',
576
+ {},
577
+ );
578
+ }
579
+ if (assembly === null || typeof assembly !== 'object' || !Array.isArray(assembly.tools)) {
580
+ throw new RunError(
581
+ REVIEW_CODES.assemblyMismatch,
582
+ 'the reviewer prompt assembly is missing its tools, so the request cannot be proven read-only',
583
+ {},
584
+ );
585
+ }
586
+
587
+ const downstream = await next();
588
+ if (downstream === null || typeof downstream !== 'object' || Array.isArray(downstream)) {
589
+ throw new RunError(
590
+ REVIEW_CODES.assemblyMismatch,
591
+ 'the reviewer prompt assembly produced no downstream assembly to filter',
592
+ {},
593
+ );
594
+ }
595
+ const schemas = downstream.tools;
596
+ if (!Array.isArray(schemas)) {
597
+ throw new RunError(
598
+ REVIEW_CODES.assemblyMismatch,
599
+ 'the assembled reviewer tools are not a list, so the request cannot be proven read-only',
600
+ {},
601
+ );
602
+ }
603
+
604
+ const kept = [];
605
+ const observed = [];
606
+ for (const schema of schemas) {
607
+ const name = schema?.name;
608
+ if (typeof name !== 'string' || name === '') {
609
+ throw new RunError(
610
+ REVIEW_CODES.assemblyMismatch,
611
+ 'an assembled reviewer tool has no name, so the request cannot be proven read-only',
612
+ {},
613
+ );
614
+ }
615
+ observed.push(name);
616
+ if (usable.has(name)) kept.push(schema);
617
+ }
618
+
619
+ // The proof, on the exact list that will be sent. Dropping a name is the
620
+ // transform's job, so the check is on what SURVIVES: every remaining schema
621
+ // must be one the restriction installed, and the set of them must be exactly
622
+ // the computed read-only set. A read-only name the assembly never carried
623
+ // would mean the reviewer is missing evidence it is supposed to have, which is
624
+ // also a refusal — an under-provisioned reviewer cannot certify anything.
625
+ const survivors = kept.map((schema) => schema.name).sort();
626
+ const expected = [...usable].sort();
627
+ const escaped = survivors.filter((name) => !usable.has(name));
628
+ const missing = expected.filter((name) => !observed.includes(name));
629
+ if (escaped.length > 0 || missing.length > 0 || survivors.length !== expected.length) {
630
+ throw new RunError(
631
+ REVIEW_CODES.assemblyMismatch,
632
+ 'the reviewer prompt assembly does not carry exactly the read-only tool set, so no request is made',
633
+ {
634
+ // Bounded, fixed-shape evidence: only names the harness itself reported.
635
+ escaped: escaped.slice(0, MAX_DENIALS).map((name) => redactText(name).slice(0, MAX_TOOL_CHARS)),
636
+ missing: missing.slice(0, MAX_DENIALS),
637
+ expected,
638
+ observed: observed.slice(0, MAX_DENIALS).map((name) => redactText(name).slice(0, MAX_TOOL_CHARS)),
639
+ },
640
+ );
641
+ }
642
+
643
+ return { ...downstream, tools: kept };
644
+ }
645
+
646
+ /**
647
+ * Read the tool names a scope currently advertises.
648
+ *
649
+ * The agent is the scope key: an agent's tools are mounted on its own scope
650
+ * plane, so the unscoped (global) view would miss them.
651
+ * @param {object} tools - the native tool registry.
652
+ * @param {object} scope - the agent whose surface is read.
653
+ * @returns {Set<string>} advertised tool names.
654
+ * @throws {RunError} when the inventory cannot be read.
655
+ */
656
+ function readInventory(tools, scope) {
657
+ let inventory;
658
+ try {
659
+ inventory = tools.schemas(scope);
660
+ } catch (error) {
661
+ throw new RunError(REVIEW_CODES.inventoryUnavailable, 'the reviewer tool inventory could not be read', {
662
+ cause: diagnostic(error?.message ?? error),
663
+ });
664
+ }
665
+ return new Set(
666
+ (Array.isArray(inventory) ? inventory : [])
667
+ .map((schema) => schema?.name)
668
+ .filter((name) => typeof name === 'string' && name !== ''),
669
+ );
670
+ }
671
+
672
+ /**
673
+ * Refuse a reviewer surface the restriction did not install as computed.
674
+ *
675
+ * What this check does NOT do any more: fail because the agent's own layer
676
+ * still holds a name (the composing `subagent`). Native restrictions keep a
677
+ * scope's own registrations, no supported API removes them, and the request
678
+ * tools are decided by the `system-prompt/assemble` transform, which proves the
679
+ * model-facing list on every request. Treating the surviving registration as a
680
+ * failure therefore refused every review on a real deployment without making
681
+ * the request any safer.
682
+ *
683
+ * What it still does, and must:
684
+ * - a read-only name the registry advertised in the pre-policy inventory but
685
+ * which is no longer visible afterwards means the restriction removed
686
+ * something it was supposed to keep — `surfaceMismatch`;
687
+ * - an advertised name that was never in the pre-policy inventory means the
688
+ * registry's evidence no longer describes what is visible, so the computed
689
+ * set cannot be trusted — `scopeUnenforceable`.
690
+ * Neither is a reason to widen the policy, patch the registry, or prompt anyway.
691
+ * @param {Set<string>} advertised - names the registry advertises after the policy.
692
+ * @param {string[]} usable - the read-only names the policy installed.
693
+ * @param {ReadonlySet<string>} [evidence] - the pre-policy inventory the set was
694
+ * computed from; defaults to `advertised` when the caller has none.
695
+ * @returns {void}
696
+ * @throws {RunError} when the surface is not exactly `usable`.
697
+ */
698
+ function assertAdvertised(advertised, usable, evidence = advertised) {
699
+ const missing = usable.filter((name) => !advertised.has(name));
700
+ if (missing.length > 0) {
701
+ throw new RunError(
702
+ REVIEW_CODES.surfaceMismatch,
703
+ 'the reviewer tool restriction did not leave the read-only set advertised',
704
+ { missing: missing.slice(0, MAX_DENIALS) },
705
+ );
706
+ }
707
+ const usableSet = new Set(usable);
708
+ const unknown = [...advertised].filter((name) => !usableSet.has(name) && !evidence.has(name)).sort();
709
+ if (unknown.length > 0) {
710
+ throw new RunError(
711
+ REVIEW_CODES.scopeUnenforceable,
712
+ 'the reviewer agent advertises tools that were not in the inventory the read-only set was computed from',
713
+ {
714
+ // Bounded, fixed-shape evidence: only names the registry itself reported.
715
+ unremovable: unknown.slice(0, MAX_DENIALS).map((name) => redactText(name).slice(0, MAX_TOOL_CHARS)),
716
+ allowed: [...usable],
717
+ },
718
+ );
719
+ }
720
+ }
721
+
722
+ /**
723
+ * Build the deny-by-default execution guard.
724
+ *
725
+ * Only names on the computed read-only set may run. Mutation-shaped names are
726
+ * denied explicitly as well, but the allow-list — not the name pattern — is the
727
+ * mechanism.
728
+ * @param {object} execution - the identity-protected tool call.
729
+ * @param {ReadonlySet<string>} usable - names installed by the restriction.
730
+ * @param {ReadonlySet<string>} allowed - the fixed read-only names.
731
+ * @param {object[]} denials - this review's denial log.
732
+ * @returns {string | undefined} a denial reason, or undefined to allow.
733
+ */
734
+ function guardExecution(execution, usable, allowed, denials) {
735
+ const name = execution?.name;
736
+ if (typeof name !== 'string' || name === '') {
737
+ recordDenial(denials, undefined, 'tool identity missing');
738
+ return 'the additional review cannot run a tool with no identity';
739
+ }
740
+ if (!allowed.has(name) || !usable.has(name)) {
741
+ recordDenial(denials, name, 'not on the read-only allow-list');
742
+ return `the additional review is read-only; ${redactText(name).slice(0, MAX_TOOL_CHARS)} is not permitted`;
743
+ }
744
+ if (looksMutating(name)) {
745
+ // Defence in depth: a read-only name that nevertheless reads as a mutation
746
+ // is a composition bug, not something to allow.
747
+ recordDenial(denials, name, 'mutation-shaped tool name');
748
+ return `the additional review is read-only and cannot run ${redactText(name).slice(0, MAX_TOOL_CHARS)}`;
749
+ }
750
+ return undefined;
751
+ }
752
+
753
+ /**
754
+ * Append one bounded, redacted denial to a review's log.
755
+ *
756
+ * The log is bounded rather than append-forever: a reviewer that calls denied
757
+ * tools in a loop must not be able to grow durable history.
758
+ * @param {object[]} denials - the record's denial list.
759
+ * @param {string | undefined} name - raw tool name.
760
+ * @param {string} reason - short, fixed reason.
761
+ * @returns {void}
762
+ */
763
+ function recordDenial(denials, name, reason) {
764
+ if (!Array.isArray(denials) || denials.length >= MAX_DENIALS) return;
765
+ const tool = typeof name === 'string' && name !== ''
766
+ ? redactText(name).slice(0, MAX_TOOL_CHARS)
767
+ : '(unnamed)';
768
+ denials.push({ tool, reason: redactText(String(reason)).slice(0, MAX_REASON_CHARS) });
769
+ }
770
+
771
+ /**
772
+ * Bounded, redacted detail text for a refused review.
773
+ *
774
+ * A refused restriction or surface mismatch is only actionable if the operator
775
+ * can see WHICH names failed, so those detail fields are rendered. Every value is
776
+ * a tool name the registry itself reported, is redacted, and is clamped.
777
+ * @param {RunError} error - the thrown review error.
778
+ * @returns {string|null} bounded detail, or null when the error carries none.
779
+ */
780
+ function errorDetail(error) {
781
+ const details = error?.details ?? {};
782
+ const names = (value) => (Array.isArray(value) ? value : []).filter((entry) => typeof entry === 'string');
783
+ const unremovable = names(details.unremovable);
784
+ const escaped = names(details.escaped);
785
+ const missing = names(details.missing);
786
+ const absent = names(details.missingPackages);
787
+ // A failed composition names the rows that kept it from mounting, so the
788
+ // operator can fix the deployment instead of guessing.
789
+ const unusable = names(details.unusable);
790
+ const text = unremovable.length > 0
791
+ ? `tools the read-only policy cannot remove: ${unremovable.join(', ')}`
792
+ : escaped.length > 0
793
+ ? `tools the model-facing assembly still carried: ${escaped.join(', ')}`
794
+ : missing.length > 0
795
+ ? `read-only tools missing from the advertised surface: ${missing.join(', ')}`
796
+ : absent.length > 0
797
+ ? `native packages the review composition needs are absent: ${absent.join(', ')}`
798
+ : unusable.length > 0
799
+ ? `unusable composition rows: ${unusable.join(', ')}`
800
+ : typeof details.cause === 'string'
801
+ ? details.cause
802
+ : null;
803
+ if (text === null || text === '') return null;
804
+ return redactText(text).slice(0, MAX_ERROR_CHARS);
805
+ }
806
+
807
+ /**
808
+ * Project a thrown review error into a review record.
809
+ *
810
+ * Three kinds of thrown value reach here, and each keeps its own code so an
811
+ * operator can tell them apart: a `REVIEW_*` code is already review-shaped, a
812
+ * `REVIEW_PRESET_*` code names a composition failure, and anything else is a run
813
+ * error mapped onto its review meaning.
814
+ * @param {unknown} error - the thrown value.
815
+ * @param {object} selection - review selection.
816
+ * @param {object[]} denials - collected denials.
817
+ * @returns {object} review record.
818
+ */
819
+ function failureRecord(error, selection, denials) {
820
+ const base = { verdict: null, text: '', selection: summarizeSelection(selection), denials };
821
+ if (error instanceof RunError) {
822
+ const code = typeof error.code === 'string' ? error.code : '';
823
+ if (code.startsWith('REVIEW_PRESET_')) {
824
+ // A distinct, non-tool code: the review could not be COMPOSED, which is a
825
+ // different failure from a composition that was composed and refused.
826
+ return {
827
+ state: REVIEW_STATES.failed,
828
+ error: {
829
+ code: REVIEW_CODES.presetPrepareFailed,
830
+ reason: code,
831
+ message: redactText(String(error.message ?? '')).slice(0, MAX_ERROR_CHARS),
832
+ detail: errorDetail(error),
833
+ },
834
+ ...base,
835
+ };
836
+ }
837
+ if (code.startsWith('REVIEW_')) {
838
+ return {
839
+ state: REVIEW_STATES.failed,
840
+ error: {
841
+ code,
842
+ message: redactText(String(error.message ?? '')).slice(0, MAX_ERROR_CHARS),
843
+ detail: errorDetail(error),
844
+ },
845
+ ...base,
846
+ };
847
+ }
848
+ const mapped = RUN_TO_REVIEW.get(code) ?? REVIEW_CODES.failed;
849
+ return {
850
+ state: REVIEW_STATES.failed,
851
+ error: {
852
+ code: mapped,
853
+ // Preserve the original code so a refusal that came from the RUN layer
854
+ // (for example a preset the review does not own) is still traceable.
855
+ ...(mapped === REVIEW_CODES.presetPrepareFailed ? { reason: code } : {}),
856
+ message: redactText(String(error.message ?? 'the additional review could not complete')).slice(0, MAX_ERROR_CHARS),
857
+ detail: errorDetail(error),
858
+ },
859
+ ...base,
860
+ };
861
+ }
862
+ return {
863
+ state: REVIEW_STATES.failed,
864
+ error: {
865
+ code: REVIEW_CODES.failed,
866
+ message: 'the additional review could not complete',
867
+ detail: diagnostic(error?.message ?? error, MAX_ERROR_CHARS),
868
+ },
869
+ ...base,
870
+ };
871
+ }
872
+
873
+ /** Run error codes that have a distinct review meaning. */
874
+ const RUN_TO_REVIEW = new Map([
875
+ ['RUN_AGENTS_UNAVAILABLE', REVIEW_CODES.agentsUnavailable],
876
+ ['RUN_AGENT_PRESETS_UNAVAILABLE', REVIEW_CODES.presetsUnavailable],
877
+ ['RUN_PROMPT_TOO_LARGE', REVIEW_CODES.promptTooLarge],
878
+ // A review never names a preset it does not own; if that invariant is ever
879
+ // broken the run is refused and reported as a composition failure.
880
+ ['RUN_PRESET_NOT_OWNED', REVIEW_CODES.presetPrepareFailed],
881
+ ['RUN_PRESET_MOUNT_FAILED', REVIEW_CODES.presetPrepareFailed],
882
+ ]);
883
+
884
+ /**
885
+ * Build a failed review record for a precondition refusal.
886
+ * @param {string} code - review error code.
887
+ * @param {string} message - bounded explanation.
888
+ * @param {object} selection - review selection.
889
+ * @param {object[]} denials - collected denials.
890
+ * @returns {object} review record.
891
+ */
892
+ function failed(code, message, selection, denials) {
893
+ return {
894
+ state: REVIEW_STATES.failed,
895
+ error: { code, message },
896
+ verdict: null,
897
+ text: '',
898
+ selection: summarizeSelection(selection),
899
+ denials,
900
+ };
901
+ }
902
+
903
+ /**
904
+ * Extract a verdict from reviewer text.
905
+ *
906
+ * The reviewer is constrained by the prompt to emit a machine-readable line.
907
+ * Absence of that line yields `unknown`, which the host must treat as "not
908
+ * approved" — never as approval by default.
909
+ * @param {string} text - reviewer output.
910
+ * @returns {{ verdict: string, reason: string | null } | null} parsed verdict.
911
+ */
912
+ export function parseVerdict(text) {
913
+ if (typeof text !== 'string' || text.trim() === '') return null;
914
+ const match = /VERDICT:\s*(approve|changes-requested)\b/i.exec(text);
915
+ if (match === null) return { verdict: 'unknown', reason: null };
916
+ const verdict = match[1].toLowerCase() === 'approve' ? 'approve' : 'changes-requested';
917
+ const reasonMatch = /REASON:\s*(.+)/i.exec(text);
918
+ return {
919
+ verdict,
920
+ reason: reasonMatch === null ? null : redactText(reasonMatch[1].trim()).slice(0, 400),
921
+ };
922
+ }
923
+
924
+ function summarizeSelection(selection) {
925
+ if (selection === null || selection === undefined) return null;
926
+ return {
927
+ providerId: selection.providerId ?? null,
928
+ model: selection.model ?? null,
929
+ reasoningEffort: selection.reasoningEffort ?? null,
930
+ };
931
+ }
932
+
933
+ export { REDACTED_PLACEHOLDER };