@jbkjr/relay 0.0.0-stage → 1.2.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 (296) hide show
  1. package/LICENSE +21 -0
  2. package/LICENSES/Apache-2.0.txt +201 -0
  3. package/LICENSES/README.md +19 -0
  4. package/LICENSES/codex-NOTICE.txt +6 -0
  5. package/README.md +393 -2
  6. package/SECURITY.md +145 -0
  7. package/adapters/briefs/claude.md +43 -0
  8. package/adapters/briefs/codex.md +56 -0
  9. package/adapters/briefs/models.json +33 -0
  10. package/adapters/build.mjs +8 -0
  11. package/adapters/claude/.claude-plugin/marketplace.json +13 -0
  12. package/adapters/claude/relay/.claude-plugin/plugin.json +5 -0
  13. package/adapters/claude/relay/agents/codex.md +21 -0
  14. package/adapters/claude/relay/agents/operator.md +21 -0
  15. package/adapters/claude/relay/skills/ask/SKILL.md +20 -0
  16. package/adapters/claude/relay/skills/chat/SKILL.md +13 -0
  17. package/adapters/claude/relay/skills/delegate/SKILL.md +21 -0
  18. package/adapters/claude/relay/skills/discuss/SKILL.md +19 -0
  19. package/adapters/claude/relay/skills/review/SKILL.md +21 -0
  20. package/adapters/claude/relay/skills/tree/SKILL.md +10 -0
  21. package/adapters/claude/relay/skills/write-for-codex/SKILL.md +78 -0
  22. package/adapters/codex/.agents/plugins/marketplace.json +20 -0
  23. package/adapters/codex/AGENTS.snippet.md +5 -0
  24. package/adapters/codex/relay/.codex-plugin/plugin.json +6 -0
  25. package/adapters/codex/relay/skills/relay-ask/SKILL.md +20 -0
  26. package/adapters/codex/relay/skills/relay-chat/SKILL.md +13 -0
  27. package/adapters/codex/relay/skills/relay-delegate/SKILL.md +21 -0
  28. package/adapters/codex/relay/skills/relay-discuss/SKILL.md +19 -0
  29. package/adapters/codex/relay/skills/relay-review/SKILL.md +21 -0
  30. package/adapters/codex/relay/skills/relay-tree/SKILL.md +10 -0
  31. package/adapters/codex/relay/skills/relay-write-for-claude/SKILL.md +66 -0
  32. package/adapters/generate.mjs +124 -0
  33. package/bin/relay +59 -0
  34. package/codex-pin.json +12 -0
  35. package/dist/backends/acp.js +1424 -0
  36. package/dist/backends/claude.js +890 -0
  37. package/dist/backends/cli-version.js +112 -0
  38. package/dist/backends/codex-app.js +1539 -0
  39. package/dist/backends/codex-daybreak.js +75 -0
  40. package/dist/backends/codex-env.js +656 -0
  41. package/dist/backends/codex-network.js +304 -0
  42. package/dist/backends/codex-pin.js +345 -0
  43. package/dist/backends/codex-shell-policy.js +182 -0
  44. package/dist/backends/codex-stage2.js +998 -0
  45. package/dist/backends/codex-subagents.js +47 -0
  46. package/dist/backends/codex.js +641 -0
  47. package/dist/backends/copilot.js +246 -0
  48. package/dist/backends/env.js +147 -0
  49. package/dist/backends/gemini.js +607 -0
  50. package/dist/backends/grok.js +337 -0
  51. package/dist/backends/index.js +8 -0
  52. package/dist/backends/native-temp.js +187 -0
  53. package/dist/backends/never-admission.js +90 -0
  54. package/dist/backends/run.js +67 -0
  55. package/dist/backends/stream.js +230 -0
  56. package/dist/backends/tool-discovery.js +15 -0
  57. package/dist/backends/types.js +264 -0
  58. package/dist/build-info.json +5 -0
  59. package/dist/cli.js +344 -0
  60. package/dist/confine/bridge.js +113 -0
  61. package/dist/confine/broker-core.js +76 -0
  62. package/dist/confine/broker-http.js +650 -0
  63. package/dist/confine/broker-names.js +9 -0
  64. package/dist/confine/broker.js +258 -0
  65. package/dist/confine/canary.js +380 -0
  66. package/dist/confine/diagnostics.js +122 -0
  67. package/dist/confine/gemini-tools-main.js +8 -0
  68. package/dist/confine/gemini-tools.js +181 -0
  69. package/dist/confine/hardlinks.js +58 -0
  70. package/dist/confine/harness-config.js +16 -0
  71. package/dist/confine/index.js +117 -0
  72. package/dist/confine/leases.js +217 -0
  73. package/dist/confine/paths.js +6 -0
  74. package/dist/confine/peer.js +115 -0
  75. package/dist/confine/port-policy.js +8 -0
  76. package/dist/confine/ports.js +365 -0
  77. package/dist/confine/private-root.js +208 -0
  78. package/dist/confine/probe-stage2.js +501 -0
  79. package/dist/confine/probe.js +1109 -0
  80. package/dist/confine/proxy.js +783 -0
  81. package/dist/confine/sbcheck.js +208 -0
  82. package/dist/confine/seatbelt-never.js +41 -0
  83. package/dist/confine/seatbelt-stage2.js +139 -0
  84. package/dist/confine/seatbelt.js +1129 -0
  85. package/dist/confine/sockets.js +36 -0
  86. package/dist/confine/turn-probe.js +19 -0
  87. package/dist/confine/turn.js +86 -0
  88. package/dist/core/adoption.js +124 -0
  89. package/dist/core/api-keys.js +423 -0
  90. package/dist/core/approvals.js +740 -0
  91. package/dist/core/build-identity.js +248 -0
  92. package/dist/core/caller.js +749 -0
  93. package/dist/core/calls.js +102 -0
  94. package/dist/core/claude-settings.js +1045 -0
  95. package/dist/core/config.js +453 -0
  96. package/dist/core/context.js +186 -0
  97. package/dist/core/db.js +753 -0
  98. package/dist/core/dispatch.js +110 -0
  99. package/dist/core/env-broker.js +505 -0
  100. package/dist/core/env-policy.js +182 -0
  101. package/dist/core/escalation-authority.js +76 -0
  102. package/dist/core/escalation-contract.js +13 -0
  103. package/dist/core/escalation-person-path.js +131 -0
  104. package/dist/core/escalation-policy.js +79 -0
  105. package/dist/core/escalation-runtime.js +135 -0
  106. package/dist/core/escalation-state.js +42 -0
  107. package/dist/core/escalations.js +191 -0
  108. package/dist/core/events.js +235 -0
  109. package/dist/core/executables.js +147 -0
  110. package/dist/core/extensions.js +645 -0
  111. package/dist/core/families.js +204 -0
  112. package/dist/core/git.js +657 -0
  113. package/dist/core/identity.js +113 -0
  114. package/dist/core/liveness.js +68 -0
  115. package/dist/core/mediated-network-provider.js +81 -0
  116. package/dist/core/never-checkpoint.js +76 -0
  117. package/dist/core/never-coverage.js +97 -0
  118. package/dist/core/never-network.js +49 -0
  119. package/dist/core/never-policy.js +302 -0
  120. package/dist/core/never-proxy-policy.js +109 -0
  121. package/dist/core/never-schema.js +61 -0
  122. package/dist/core/never-tools.js +56 -0
  123. package/dist/core/notices.js +48 -0
  124. package/dist/core/ops.js +959 -0
  125. package/dist/core/outcome.js +224 -0
  126. package/dist/core/params.js +32 -0
  127. package/dist/core/presence.js +174 -0
  128. package/dist/core/procs.js +546 -0
  129. package/dist/core/prompts.js +363 -0
  130. package/dist/core/protected-config.js +238 -0
  131. package/dist/core/raw-network.js +192 -0
  132. package/dist/core/redact.js +152 -0
  133. package/dist/core/refusal.js +33 -0
  134. package/dist/core/relay-command.js +310 -0
  135. package/dist/core/reported.js +3 -0
  136. package/dist/core/restart-overlay.js +651 -0
  137. package/dist/core/retention.js +1135 -0
  138. package/dist/core/secrets.js +329 -0
  139. package/dist/core/session-token.js +175 -0
  140. package/dist/core/session.js +744 -0
  141. package/dist/core/shell.js +2 -0
  142. package/dist/core/shipped-pin.js +47 -0
  143. package/dist/core/shown.js +42 -0
  144. package/dist/core/slots.js +67 -0
  145. package/dist/core/stage2-executors.js +453 -0
  146. package/dist/core/stage2-switch.js +5 -0
  147. package/dist/core/steering.js +149 -0
  148. package/dist/core/storage.js +358 -0
  149. package/dist/core/toml.js +175 -0
  150. package/dist/core/views.js +324 -0
  151. package/dist/core/wait.js +114 -0
  152. package/dist/core/wake.js +207 -0
  153. package/dist/core/watch.js +247 -0
  154. package/dist/core/worktree.js +213 -0
  155. package/dist/hosts/claude-desktop.js +274 -0
  156. package/dist/hosts/claude.js +249 -0
  157. package/dist/hosts/codex.js +345 -0
  158. package/dist/hosts/desktop-shared.js +20 -0
  159. package/dist/hosts/index.js +11 -0
  160. package/dist/hosts/types.js +4 -0
  161. package/dist/install/basics.js +18 -0
  162. package/dist/install/claude-init.js +133 -0
  163. package/dist/install/common.js +655 -0
  164. package/dist/install/doctor.js +635 -0
  165. package/dist/install/qualify-codex.js +205 -0
  166. package/dist/install.js +524 -0
  167. package/dist/mcp/elicit.js +209 -0
  168. package/dist/mcp/gateway.js +218 -0
  169. package/dist/mcp/host.js +253 -0
  170. package/dist/mcp/server.js +1124 -0
  171. package/dist/mcp/stdio.js +37 -0
  172. package/dist/modes/discussion.js +393 -0
  173. package/dist/modes/review.js +722 -0
  174. package/dist/native/relay-sbcheck +0 -0
  175. package/dist/targets/briefs.js +86 -0
  176. package/dist/targets/claude.js +94 -0
  177. package/dist/targets/codex.js +66 -0
  178. package/dist/targets/copilot.js +93 -0
  179. package/dist/targets/gemini.js +119 -0
  180. package/dist/targets/grok.js +126 -0
  181. package/dist/targets/index.js +192 -0
  182. package/dist/targets/types.js +18 -0
  183. package/dist/targets/verified.js +35 -0
  184. package/dist/worker.js +113 -0
  185. package/docs/UPGRADING.md +1518 -0
  186. package/docs/pinned-codex.md +333 -0
  187. package/experiments/stage2-redteam/lib/oracles.mjs +214 -0
  188. package/experiments/stage2-redteam/lib/report.mjs +35 -0
  189. package/npm-shrinkwrap.json +1632 -0
  190. package/package.json +82 -4
  191. package/scripts/codex-qualify/codex-pin-store.mjs +353 -0
  192. package/scripts/codex-qualify/codex-qualifier-process.mjs +265 -0
  193. package/scripts/codex-qualify/codex-qualifier.example.json +5 -0
  194. package/scripts/codex-qualify/codex-qualifier.mjs +281 -0
  195. package/scripts/codex-qualify/codex-shipped-pin.mjs +158 -0
  196. package/scripts/codex-qualify/codex-stage2-pin.mjs +48 -0
  197. package/scripts/codex-qualify/codex-stage2.mjs +2381 -0
  198. package/scripts/codex-qualify/install-codex-qualifier.mjs +98 -0
  199. package/scripts/codex-qualify/main-module.mjs +14 -0
  200. package/scripts/codex-qualify/relay-codex-qualifier.plist +37 -0
  201. package/scripts/codex-qualify/scratch-env.mjs +31 -0
  202. package/scripts/codex-qualify/session.mjs +96 -0
  203. package/scripts/codex-qualify/stage2-escalation-cases.mjs +125 -0
  204. package/test/codex-permissions.test.ts +875 -0
  205. package/test/fixtures/boundary-probes.mjs +17 -0
  206. package/test/fixtures/denial-stream-host.mjs +7 -0
  207. package/test/fixtures/families.json +246 -0
  208. package/test/fixtures/install-snapshots/claude-desktop-foreign.txt +158 -0
  209. package/test/fixtures/install-snapshots/claude-desktop-fresh.txt +101 -0
  210. package/test/fixtures/install-snapshots/claude-desktop-installed.txt +161 -0
  211. package/test/fixtures/install-snapshots/claude-foreign.txt +133 -0
  212. package/test/fixtures/install-snapshots/claude-fresh.txt +77 -0
  213. package/test/fixtures/install-snapshots/claude-installed.txt +133 -0
  214. package/test/fixtures/install-snapshots/codex-foreign.txt +159 -0
  215. package/test/fixtures/install-snapshots/codex-fresh.txt +107 -0
  216. package/test/fixtures/install-snapshots/codex-installed.txt +161 -0
  217. package/test/fixtures/link-parent.mjs +6 -0
  218. package/test/fixtures/mediated-command.cjs +72 -0
  219. package/test/fixtures/native-skill-isolation.json +280 -0
  220. package/test/fixtures/pinned-codex-app-server.mjs +25 -0
  221. package/test/fixtures/qualified-ext-adapters.mjs +36 -0
  222. package/test/fixtures/refusals/README.md +52 -0
  223. package/test/fixtures/refusals/claude-source-result.json +7 -0
  224. package/test/fixtures/refusals/openai-app-capacity.json +24 -0
  225. package/test/fixtures/refusals/openai-app-cyberPolicy.json +24 -0
  226. package/test/fixtures/refusals/openai-gpt-6-astra-max.json +12 -0
  227. package/test/fixtures/refusals/openai-gpt-6.1-sol-xhigh.json +12 -0
  228. package/test/fixtures/refusals/openai-review-capacity.json +24 -0
  229. package/test/fixtures/relay-0.2.0.sql +57 -0
  230. package/test/fixtures/relay-0.9.1.gen.mjs +212 -0
  231. package/test/fixtures/relay-0.9.1.sql +340 -0
  232. package/test/fixtures/slow-boundary-probes.mjs +37 -0
  233. package/test/fixtures/stable-surfaces/config.json +1122 -0
  234. package/test/fixtures/stable-surfaces/escalation.json +128 -0
  235. package/test/fixtures/stable-surfaces/events.json +37 -0
  236. package/test/fixtures/stable-surfaces/gemini-native-resume.json +4 -0
  237. package/test/fixtures/stable-surfaces/inbox.jsonl +2 -0
  238. package/test/fixtures/stable-surfaces/notice.txt +1 -0
  239. package/test/fixtures/stable-surfaces/refusal-item.json +28 -0
  240. package/test/fixtures/stable-surfaces/refusal-review.json +23 -0
  241. package/test/fixtures/stable-surfaces/registry.json +49 -0
  242. package/test/fixtures/stable-surfaces/tools-desktop.json +575 -0
  243. package/test/fixtures/stable-surfaces/tools.json +716 -0
  244. package/test/fixtures/stable-surfaces/usage.txt +46 -0
  245. package/test/fixtures/stage2-acp-native.mjs +138 -0
  246. package/test/fixtures/stage2-app-server.mjs +23 -0
  247. package/test/fixtures/stage2-catalog.json +91 -0
  248. package/test/fixtures/stage2-hostile-web.mjs +35 -0
  249. package/test/fixtures/stage2-native-network.mjs +62 -0
  250. package/test/fixtures/stage2-worker.ts +87 -0
  251. package/test/fixtures/status-views/expected.json +7825 -0
  252. package/test/fixtures/status-views/registries.json +1 -0
  253. package/test/fixtures/steering.json +209 -0
  254. package/test/helpers.ts +740 -0
  255. package/test/host-env.ts +7 -0
  256. package/test/keychain-decoy.ts +197 -0
  257. package/test/live-scope.ts +44 -0
  258. package/test/mediated-network.test.ts +192 -0
  259. package/test/mediated-proxy.test.ts +264 -0
  260. package/test/native-temp-alias.ts +10 -0
  261. package/test/never-policy.test.ts +629 -0
  262. package/test/never-tools.test.ts +136 -0
  263. package/test/process-home.ts +18 -0
  264. package/test/proxy.test.ts +531 -0
  265. package/test/restart-overlay-live.test.ts +85 -0
  266. package/test/restart-overlay-profile.test.ts +66 -0
  267. package/test/restart-overlay.test.ts +416 -0
  268. package/test/stable-surfaces.test.ts +249 -0
  269. package/test/stage2-escalation-live.test.ts +544 -0
  270. package/test/stage2-escalation-qualification.test.ts +170 -0
  271. package/test/stage2-escalation.test.ts +747 -0
  272. package/test/stage2-executor.test.ts +849 -0
  273. package/test/stage2-grant.test.ts +603 -0
  274. package/test/stage2-native-live.test.ts +647 -0
  275. package/test/stage2-network-decisions.test.ts +70 -0
  276. package/test/stage2-probe.test.ts +845 -0
  277. package/test/stage2-standing-live.test.ts +203 -0
  278. package/test/stubs/broker-host.mjs +59 -0
  279. package/test/stubs/broker-peer.mjs +20 -0
  280. package/test/stubs/confined-harness.mjs +91 -0
  281. package/test/stubs/ext-broken-server.mjs +2 -0
  282. package/test/stubs/ext-odd-server.mjs +21 -0
  283. package/test/stubs/ext-server.mjs +31 -0
  284. package/test/stubs/fake-host-cli.mjs +218 -0
  285. package/test/stubs/procargs.mjs +30 -0
  286. package/test/stubs/stub-acp +4 -0
  287. package/test/stubs/stub-agent.mjs +322 -0
  288. package/test/stubs/stub-claude +4 -0
  289. package/test/stubs/stub-codex +4 -0
  290. package/test/stubs/targets/acp.mjs +307 -0
  291. package/test/stubs/targets/claude.mjs +149 -0
  292. package/test/stubs/targets/codex.mjs +479 -0
  293. package/test/stubs/targets/gemini.mjs +604 -0
  294. package/test/temp-root.ts +11 -0
  295. package/test/wp4-adapters.test.ts +353 -0
  296. package/test/wp4-interlock.test.ts +136 -0
@@ -0,0 +1,722 @@
1
+ // A review: the calling agent reviews the target itself (or with its own subagents) while one
2
+ // reviewer of the other family does the same, with the reviews withheld through relay's tools;
3
+ // host transcripts and drafts can still expose them. Then the two reconcile
4
+ // their lists in a discussion (modes/discussion.ts). What a review is made of: each reviewer's
5
+ // verdict, declared coverage and numbered items, and the consensus list the two reconcile them into.
6
+ import fs from "node:fs";
7
+ import { REFUSAL_POLICY, refusalNote } from "../core/refusal.js";
8
+ import os from "node:os";
9
+ import { recordStart, addContribution, callerLabel, familiesOf } from "../core/families.js";
10
+ import { ownReviewFamilyNote } from "../core/steering.js";
11
+ import path from "node:path";
12
+ import { admitExisting, admitNew, admitSpeed, admitWork, callerSide, familyOf, knownCaller, refused } from "../core/caller.js";
13
+ import { noteCall } from "../core/calls.js";
14
+ import { expandHome, harnessHome, inside, nodeDir, runDir } from "../core/config.js";
15
+ import { busy, db, getNode, insertNode, insertTurn, newId, nodeTurns, now, runConfig, speedAfter, tx, updateNode } from "../core/db.js";
16
+ import { dispatch } from "../core/dispatch.js";
17
+ import { discussionParams, reviewParams, sessionParams, speedOf } from "../core/params.js";
18
+ import { lastJsonBlock, PASS_RULE, reviewDiscussionRules, reviewerPrompt, reviewJsonShape } from "../core/prompts.js";
19
+ import { CALLER_LABEL, inSideOrder, sideOfItem, sidePrefix, targetDef, targetLabel } from "../targets/index.js";
20
+ import { keepRecord, readProblem, writeProblem } from "../core/storage.js";
21
+ import { notesView, pendingHandle, runRecovery, speedView } from "../core/views.js";
22
+ import { settled, waitOpts, waitUntil } from "../core/wait.js";
23
+ import { discuss, legacyRefusal, legacyTwoSided, otherSide } from "./discussion.js";
24
+ export const VERDICTS = ["pass", "fail", "unknown"];
25
+ /** The sides that raised the items, by their ids' prefixes. */
26
+ const raisedBy = (ids) => [...new Set(ids.map((i) => sideOfItem(i) ?? "unknown"))];
27
+ const str = (v) => (typeof v === "string" && v.trim() ? v : undefined);
28
+ /** A list of strings, from a string or an array. Entries of other types are kept as their JSON rather than dropped, so that nothing declared is lost. */
29
+ const strs = (v) => v === undefined || v === null ? undefined
30
+ : typeof v === "string" ? (v.trim() ? [v] : [])
31
+ : (Array.isArray(v) ? v : [v]).map((e) => (typeof e === "string" ? e : JSON.stringify(e)));
32
+ /** An inclusive line range, from [start, end], [line] or a single line number. Anything else is left out rather than guessed at. */
33
+ function lineRange(v) {
34
+ const ns = typeof v === "number" ? [v] : Array.isArray(v) ? v : null;
35
+ if (!ns || ns.length < 1 || ns.length > 2 || !ns.every((n) => Number.isInteger(n) && n > 0))
36
+ return undefined;
37
+ const [a, b = a] = ns;
38
+ return a <= b ? [a, b] : undefined;
39
+ }
40
+ /**
41
+ * A coverage statement as declared, with its fields' types checked: complete only as a boolean, and
42
+ * the lists as strings (anything listed as not examined, of whatever type, keeps the coverage partial).
43
+ * Not a judgment of what the reviewer actually read.
44
+ */
45
+ export function coverageOf(v) {
46
+ if (!v || typeof v !== "object" || Array.isArray(v))
47
+ return null;
48
+ const c = v;
49
+ const out = {};
50
+ if (typeof c.complete === "boolean")
51
+ out.complete = c.complete;
52
+ const examined = strs(c.examined);
53
+ const notExamined = strs(c.not_examined);
54
+ if (examined)
55
+ out.examined = examined;
56
+ if (notExamined)
57
+ out.not_examined = notExamined;
58
+ return out;
59
+ }
60
+ /** Whether a declared coverage is full: `complete: true`, and nothing listed as not examined. A missing statement is not full. */
61
+ export const fullCoverage = (c) => c?.complete === true && !c.not_examined?.length;
62
+ /**
63
+ * The verdict that stands, applied mechanically from what the reviewer declared: a "pass" over
64
+ * coverage that is not declared full becomes "unknown"; "fail" and "unknown" stand as given; any
65
+ * other value, or none, is no verdict. Relay never judges coverage itself.
66
+ */
67
+ export function standingVerdict(declared, coverage) {
68
+ const v = typeof declared === "string" ? declared.trim().toLowerCase() : null;
69
+ if (!VERDICTS.includes(v))
70
+ return null;
71
+ return v === "pass" && !fullCoverage(coverage) ? "unknown" : v;
72
+ }
73
+ /** A declared value as text: a string as it is, anything else as its JSON. Never String(), which runs whatever toString a parsed object carries. */
74
+ const shown = (v) => (typeof v === "string" ? v : (JSON.stringify(v) ?? typeof v));
75
+ const verdictNote = (declared, verdict) => verdict === "unknown" && typeof declared === "string" && declared.trim().toLowerCase() === "pass"
76
+ ? "a pass over coverage not declared full stands as unknown"
77
+ : declared !== undefined && declared !== null && verdict === null ? `${typeof declared === "string" ? `"${declared}"` : shown(declared)} is not a verdict (pass, fail or unknown)` : undefined;
78
+ /** A block that is a review's closing block: an object with items, a verdict or a coverage statement. */
79
+ const isReviewBlock = (v) => !!v && typeof v === "object" && !Array.isArray(v) && ("items" in v || "verdict" in v || "coverage" in v);
80
+ /**
81
+ * A side's review from its message: the last fenced JSON block with items, a verdict or a coverage
82
+ * statement, so that a verdict declared without items is not lost. `side` is a side label: a target id, or CALLER_LABEL.
83
+ */
84
+ export function parseReview(side, message) {
85
+ const block = lastJsonBlock(message, (v) => (isReviewBlock(v) ? v : null));
86
+ const notes = [];
87
+ if (block && !Array.isArray(block.items))
88
+ notes.push(block.items === undefined ? "the block had no items array" : "the block's items is not an array");
89
+ const entries = (Array.isArray(block?.items) ? block.items : []);
90
+ // An item's id carries its own n where that is a positive whole number not used before; any other
91
+ // item gets the next number above every n given, so that no two items share an id, and the note says which.
92
+ const isItem = (it) => !!it && typeof it === "object";
93
+ const used = new Set();
94
+ const own = entries.map((it) => {
95
+ const n = isItem(it) ? it.n : undefined;
96
+ if (typeof n !== "number" || !Number.isInteger(n) || n < 1 || used.has(n))
97
+ return null;
98
+ used.add(n);
99
+ return n;
100
+ });
101
+ let next = Math.max(0, ...used);
102
+ const renumbered = [];
103
+ const left = [];
104
+ const items = entries.flatMap((it, i) => {
105
+ if (!isItem(it)) {
106
+ left.push(i + 1);
107
+ return [];
108
+ }
109
+ const item = { id: `${sidePrefix(side)}${own[i] ?? ++next}` };
110
+ if (own[i] === null) {
111
+ const why = it.n === undefined ? "no n" : typeof it.n === "number" && Number.isInteger(it.n) && it.n > 0 ? `n ${it.n}, used before` : `n ${JSON.stringify(it.n)}, not a positive whole number`;
112
+ renumbered.push(`entry ${i + 1} of items (${why}) is ${item.id}`);
113
+ }
114
+ const set = (k, v) => {
115
+ if (v !== undefined)
116
+ item[k] = v;
117
+ };
118
+ set("severity", str(it.severity));
119
+ set("confidence", str(it.confidence));
120
+ set("file", str(it.file));
121
+ set("lines", lineRange(it.lines));
122
+ set("location", str(it.location));
123
+ set("summary", str(it.summary));
124
+ set("evidence", str(it.evidence));
125
+ set("fix", str(it.fix));
126
+ return [item];
127
+ });
128
+ if (left.length)
129
+ notes.push(`${left.map((n) => `entry ${n}`).join(", ")} of items ${left.length > 1 ? "are not objects and were" : "is not an object and was"} left out`);
130
+ if (renumbered.length)
131
+ notes.push(`relay gave its own ids to items whose n was missing, not a positive whole number, or used before: ${renumbered.join(", ")}`);
132
+ const coverage = coverageOf(block?.coverage);
133
+ const declared = block && block.verdict !== undefined ? block.verdict : null;
134
+ const verdict = standingVerdict(declared, coverage);
135
+ const vnote = verdictNote(declared, verdict);
136
+ if (vnote)
137
+ notes.push(vnote);
138
+ const note = notes.join("; ");
139
+ return { declared: declared === null ? null : shown(declared), verdict, coverage, items, ...(note ? { note } : {}), ...(renumbered.length ? { renumbered } : {}) };
140
+ }
141
+ /** A sentence naming the items of a side's review that relay gave ids of its own, or "" if there are none. */
142
+ const renumberedNote = (r) => r?.renumbered?.length ? `Relay gave its own ids to items whose n was missing, not a positive whole number, or used before: ${r.renumbered.join(", ")}.` : "";
143
+ /** A side's numbered items, with ids carrying the side's prefix. */
144
+ export const parseItems = (side, message) => parseReview(side, message).items;
145
+ const parseConsensus = (message) => message === null
146
+ ? null
147
+ : lastJsonBlock(message, (v) => {
148
+ const b = v;
149
+ return Array.isArray(b?.consensus)
150
+ ? { consensus: b.consensus.filter((e) => e && Array.isArray(e.ids)), verdict: b.verdict, coverage: b.coverage }
151
+ : null;
152
+ });
153
+ /**
154
+ * Entries with their fields checked as an item's are: text fields as non-empty strings, lines as an
155
+ * inclusive range. A value of any other type is left out, so that the original item's value stands.
156
+ * A status that is not a string is kept as its JSON, so that a side's position shows what it wrote.
157
+ */
158
+ const entriesOf = (es) => es?.map((e) => {
159
+ const out = { ids: e.ids.filter((id) => typeof id === "string") };
160
+ for (const f of ["severity", "confidence", "status", "summary", "file", "location", "evidence", "fix"]) {
161
+ const v = str(e[f]);
162
+ if (v !== undefined)
163
+ out[f] = v;
164
+ }
165
+ if (out.status === undefined && e.status !== undefined && e.status !== null && typeof e.status !== "string")
166
+ out.status = shown(e.status);
167
+ const lines = lineRange(e.lines);
168
+ if (lines)
169
+ out.lines = lines;
170
+ return out;
171
+ }) ?? null;
172
+ /** The fields an entry carries over from its first original item, or from the entries where both give the same value. */
173
+ const FIELDS = ["severity", "confidence", "summary", "file", "lines", "location", "evidence", "fix"];
174
+ const pick = (from) => Object.fromEntries(FIELDS.map((f) => [f, from?.[f]]));
175
+ /** The two statuses that settle an item, where both closing blocks give it the same one at the same severity. */
176
+ const SETTLED = ["agreed", "dropped"];
177
+ const sameIds = (x, y) => [...x].sort().join() === [...y].sort().join();
178
+ /**
179
+ * Builds the consensus list: a join of the two sides' closing blocks on item id, whether or not the
180
+ * reconciliation ended in agreement, so that the block of the side that closed it (often the caller,
181
+ * whose work is under review) never settles an item alone. An item is agreed or dropped only where
182
+ * both blocks give it that status and the same severity; a block that gives an entry no severity
183
+ * holds the one its items share in the reviews. Anything else, a missing or malformed status
184
+ * included, is unresolved, with each side's position as its block gave it. A merge both blocks make
185
+ * stands. An entry's other fields replace the original item's only where both blocks give the same
186
+ * value; where they rate confidence differently, both ratings are kept.
187
+ * `sides` holds the two sides' final entries, keyed by side label, in the order they are to be named.
188
+ */
189
+ export function buildConsensus(items, sidesAs) {
190
+ const sides = Object.fromEntries(Object.entries(sidesAs).map(([l, es]) => [l, entriesOf(es)]));
191
+ const [la, lb] = Object.keys(sides);
192
+ const byId = new Map(items.map((i) => [i.id, i]));
193
+ const find = (side, id) => side?.find((e) => e.ids.includes(id));
194
+ const severityOf = (e) => {
195
+ if (e.severity !== undefined)
196
+ return e.severity;
197
+ const held = new Set(e.ids.filter((id) => byId.has(id)).map((id) => byId.get(id).severity));
198
+ return held.size === 1 ? [...held][0] : undefined;
199
+ };
200
+ const positionOf = (e, ids) => e ? { status: e.status ?? "not stated", ...(e.severity !== undefined ? { severity: e.severity } : {}), ...(sameIds(e.ids, ids) ? {} : { ids: e.ids }) } : { status: "not stated" };
201
+ const out = [];
202
+ const covered = new Set();
203
+ for (const item of items) {
204
+ if (covered.has(item.id))
205
+ continue;
206
+ const a = find(sides[la], item.id);
207
+ const b = find(sides[lb], item.id);
208
+ // A merge stands where both sides merged the same ids; its ids are listed in the reviews' order.
209
+ const merged = a && b && sameIds(a.ids, b.ids) ? new Set(a.ids) : new Set([item.id]);
210
+ const ids = items.filter((i) => merged.has(i.id) && !covered.has(i.id)).map((i) => i.id);
211
+ ids.forEach((id) => covered.add(id));
212
+ const first = byId.get(ids[0]);
213
+ if (a && b && a.status === b.status && SETTLED.includes(a.status) && severityOf(a) === severityOf(b)) {
214
+ const both = (f) => (a[f] !== undefined && JSON.stringify(a[f]) === JSON.stringify(b[f]) ? a[f] : first[f]);
215
+ const confidence = a.confidence === undefined && b.confidence === undefined ? first.confidence : a.confidence === b.confidence ? a.confidence : `${a.confidence ?? "?"} (${la}) / ${b.confidence ?? "?"} (${lb})`;
216
+ out.push({ ids, raised_by: raisedBy(ids), status: a.status, ...Object.fromEntries(FIELDS.map((f) => [f, both(f)])), severity: severityOf(a), confidence });
217
+ }
218
+ else {
219
+ out.push({ ids, raised_by: raisedBy(ids), status: "unresolved", ...pick(first), positions: { [la]: positionOf(a, ids), [lb]: positionOf(b, ids) } });
220
+ }
221
+ }
222
+ return out;
223
+ }
224
+ /**
225
+ * The review's verdict once reconciled, by the same rule as each side's, from both sides' closing
226
+ * blocks whether or not they agreed: a verdict both blocks reach stands, and anything else is
227
+ * unresolved, with each side's position. One side's block alone never settles it, so the side that
228
+ * closes the discussion (often the caller, whose work is under review) cannot set the verdict on
229
+ * its own. Each side's closing declaration is kept in `closing`.
230
+ *
231
+ * `reviews` is the two independent reviews' declared coverage. Anything both declared not examined
232
+ * was examined by neither, so a closing block's pass stands only if that block lists it as examined
233
+ * (the same words, ignoring case and surrounding space); otherwise it is unknown. This compares
234
+ * declarations only: two partial reviews can still reach a pass together when they cover different
235
+ * things, or when the reconciliation examined what both left out and says so.
236
+ */
237
+ export function reconciledVerdict(sides, reviews = []) {
238
+ const key = (e) => e.trim().toLowerCase();
239
+ const [ra, rb] = reviews.map((c) => c?.not_examined ?? []);
240
+ const leftOut = reviews.length === 2 ? ra.filter((e, i) => rb.some((f) => key(f) === key(e)) && ra.findIndex((g) => key(g) === key(e)) === i) : [];
241
+ const closing = Object.fromEntries(Object.entries(sides).map(([l, b]) => {
242
+ if (!b)
243
+ return [l, null];
244
+ const coverage = coverageOf(b.coverage);
245
+ let verdict = standingVerdict(b.verdict, coverage);
246
+ let note = verdictNote(b.verdict, verdict);
247
+ const unlisted = leftOut.filter((e) => !coverage?.examined?.some((x) => key(x) === key(e)));
248
+ if (verdict === "pass" && unlisted.length) {
249
+ verdict = "unknown";
250
+ note = `a pass stands as unknown: both reviews declared ${unlisted.map((e) => JSON.stringify(e)).join(", ")} not examined, and this block does not list it as examined`;
251
+ }
252
+ const declared = b.verdict === undefined || b.verdict === null ? null : shown(b.verdict);
253
+ return [l, { verdict: verdict ?? "not stated", declared_verdict: declared, coverage, ...(note ? { note } : {}) }];
254
+ }));
255
+ const each = Object.values(closing).map((c) => c?.verdict ?? "not stated");
256
+ const verdict = each.length === 2 && each[0] === each[1] ? each[0] : "unresolved";
257
+ return {
258
+ verdict,
259
+ ...(verdict === "unresolved" ? { verdict_positions: Object.fromEntries(Object.entries(closing).map(([l, c]) => [l, c?.verdict ?? "not stated"])) } : {}),
260
+ closing,
261
+ };
262
+ }
263
+ const warningsOf = (w) => (w.length ? { warnings: w } : {});
264
+ /**
265
+ * The open review a job is the reviewer of, if any. While a review is open its reviewer (which is
266
+ * also the other side of its reconciliation) is reached only through the review: resuming it, or
267
+ * holding another discussion with it, would put words into its session ahead of the blind review
268
+ * or the reconciliation, and could bring out its result before the caller has handed in its own.
269
+ */
270
+ export function openReviewOf(n) {
271
+ if (n.kind !== "job")
272
+ return null;
273
+ const rid = sessionParams(n).review_id;
274
+ const r = rid ? getNode(rid) : undefined;
275
+ return r && r.kind === "review" && r.status === "open" ? r : null;
276
+ }
277
+ export const reviewOnly = (n, r, verb) => `${n.id} is the reviewer of review ${r.id}, which is still open, and until it ends the reviewer is reached only through the review: call review with review_id "${r.id}" (and discuss on its reconciliation). You can ${verb} it once the review has ended.`;
278
+ /** The reviewer's side label. In an older row it is the reviewer job's target. */
279
+ const reviewerSide = (p) => p.other ?? getNode(p.reviewer)?.target ?? CALLER_LABEL;
280
+ const reviewDir = (r) => path.join(runDir(r.run_id), "reviews", r.id);
281
+ const readSide = (file) => (fs.existsSync(file) ? JSON.parse(fs.readFileSync(file, "utf8")) : null);
282
+ const readItems = (file) => readSide(file)?.items ?? [];
283
+ /** What the result says of one side's review: the verdict that stands, the one declared, the declared coverage. */
284
+ const sideSummary = (r) => r ? { verdict: r.verdict ?? "not stated", declared_verdict: r.declared ?? null, coverage: r.coverage ?? null, items: r.items?.length ?? 0, ...(r.note ? { note: r.note } : {}) } : null;
285
+ /**
286
+ * Writes one side's review to its files, with the secrets relay knows the shape of cut out
287
+ * (core/storage.ts keepRecord): they are records a person reads, and what the reconciliation and
288
+ * the consensus are built from. A file that cannot be written (a full disk, say) throws what to do
289
+ * about it, with `consequence`, what the caller can do then; neither file is left, so that a later
290
+ * call does not find half a review.
291
+ */
292
+ function writeSide(dir, label, subject, text, consequence) {
293
+ const parsed = parseReview(label, text);
294
+ const renumbered = renumberedNote(parsed);
295
+ const md = path.join(dir, `${label}.md`);
296
+ const json = path.join(dir, `${label}.json`);
297
+ const o = { consequence: `the ${label} review was not saved; ${consequence}` };
298
+ const problem = keepRecord(md, `# ${label} review of ${subject}\n\nItem ids: ${sidePrefix(label)}<n>, where n is the item number below.${renumbered ? ` ${renumbered}` : ""}\n\n${text.trim()}\n`, o)
299
+ ?? keepRecord(json, JSON.stringify(parsed, null, 2), o);
300
+ if (problem) {
301
+ for (const f of [md, json]) {
302
+ try {
303
+ fs.rmSync(f, { force: true });
304
+ }
305
+ catch {
306
+ // Left: a review without its .json is read as having no items.
307
+ }
308
+ }
309
+ throw new Error(problem);
310
+ }
311
+ return parsed;
312
+ }
313
+ /**
314
+ * A plan given as one line naming a file is that file, which the reviewer reads (relay does not);
315
+ * anything else is the plan's text. One word that names no file is refused rather than reviewed as text.
316
+ * For a launched agent (`confined`) only a file inside its own directory counts, and relay does not
317
+ * look outside it at all, so that the reply cannot tell it whether a file elsewhere exists.
318
+ */
319
+ function planSubject(plan, cwd, confined) {
320
+ const v = plan.trim();
321
+ if (!v)
322
+ return { error: "plan is empty: give the path of the plan's file, or its full text" };
323
+ if (!v.includes("\n")) {
324
+ const file = path.resolve(cwd, expandHome(v));
325
+ if ((!confined || inside(file, cwd)) && fs.existsSync(file) && fs.statSync(file).isFile())
326
+ return { kind: "plan", path: file };
327
+ if (!/\s/.test(v))
328
+ return { error: `plan "${v}" is not a file in ${cwd}. Give the path of the plan's file, or the plan's full text.` };
329
+ }
330
+ return { kind: "plan", text: v };
331
+ }
332
+ function ownReviewNote(p, reviewId) {
333
+ const kind = p.plan ? "plan" : "code";
334
+ const job = getNode(p.reviewer);
335
+ const working = job && busy(job);
336
+ return ((working ? "The other reviewer is still working. " : "The other reviewer has settled; hand in your own review to continue. ") +
337
+ (p.submission_tried ? "Your review is accepted only once the reviewer settles. A submission call still waiting will be accepted then; one that returned pending was not, so resend it after the reviewer settles. " : "") +
338
+ `Review the same ${kind === "plan" ? "plan" : "target"} yourself or with your own subagents, without reading theirs: ` +
339
+ "relay keeps it out of its replies until yours is saved (or you skip it); do not open the reviewer's log or files before then. Relay accepts yours only after the reviewer settles. " +
340
+ "Relay defers its review files and redacts own_review arguments in identified relay review tool calls from logs and structured reply echoes. Host transcripts, drafts and free-form echoes can still expose your review: withholding is a safeguard for normal use, not a guarantee of independence. " +
341
+ (kind === "plan" ? `The plan (${p.plan}) is work not yet done: judge whether it would work and is the right plan, without expecting the code it proposes to exist. ` : "") +
342
+ "Give numbered items, each with severity (blocker, major, minor or nit), confidence (high, medium or low), file and lines ([start, end]) where it has them, location, summary, evidence and fix; " +
343
+ `then your verdict (pass, fail or unknown) and your coverage: what you examined, what you did not, and complete: true only if you examined everything. ${PASS_RULE} ` +
344
+ `End with them as one fenced JSON block: ${reviewJsonShape(kind)}. ` +
345
+ `Then call review with review_id "${reviewId}" and own_review set to your review's full text. If you have no review of your own to give, pass skip_own: true.` + ownReviewFamilyNote(familiesOf(getNode(reviewId))));
346
+ }
347
+ /**
348
+ * The reviewer's speed where it is not standard (views.ts speedView), with the one a call has kept
349
+ * for the reconciliation's first turn (reviewer_speed) as `next` until the reconciliation opens.
350
+ */
351
+ function reviewerSpeed(p, job) {
352
+ const seen = job ? speedView(job) : null;
353
+ const kept = p.discussion ? undefined : p.reviewer_speed;
354
+ const now_ = seen?.requested ?? (job ? speedOf(job) : "standard");
355
+ return kept && kept !== now_ ? { ...(seen ?? { requested: now_ }), next: kept } : seen;
356
+ }
357
+ export function reviewView(id) {
358
+ // Like discussion settlement, this is safe on repeated reads. A safety stop needs no
359
+ // reconciliation turn. An own_review still in a caller's pending call may be accepted later.
360
+ tx(() => {
361
+ const r = getNode(id);
362
+ const p = reviewParams(r);
363
+ if (r.status === "open" && (!p.discussion || p.discussion === "opening")) {
364
+ const job = getNode(p.reviewer);
365
+ if (job?.status === "refused")
366
+ endRefusedReview(r, p, JSON.parse(job.result_json ?? "{}"));
367
+ }
368
+ });
369
+ const r = getNode(id);
370
+ const p = reviewParams(r);
371
+ const speed = reviewerSpeed(p, getNode(p.reviewer));
372
+ const phase = r.status !== "open" ? "finished" : !p.own ? "waiting for your own review" : !p.discussion ? "ready to reconcile: call review with this review_id" : "reconciling";
373
+ return {
374
+ review_id: id, ...runRecovery(r.run_id), status: r.status, phase, reviewer: reviewerSide(p), reviewer_job: p.reviewer, ...(speed ? { speed } : {}), ...(p.plan ? { plan: p.plan } : {}),
375
+ ...(r.target && !targetDef(r.target).qualified ? { target_label: targetLabel(targetDef(r.target)) } : {}),
376
+ ...(p.discussion && p.discussion !== "opening" ? { discussion_id: p.discussion } : {}),
377
+ ...(r.error ? { error: r.error } : {}),
378
+ ...(r.result_json ? JSON.parse(r.result_json) : {}),
379
+ families: familiesOf(r, "review"),
380
+ ...notesView(r),
381
+ ...(r.status === "open" && !p.own ? { next: ownReviewNote(p, id) } : {}),
382
+ ...(r.status === "refused" && !p.own ? { next: `You may still submit own_review or skip_own with review_id "${id}"; it will be recorded without restarting the reviewer.` } : {}),
383
+ };
384
+ }
385
+ function endReview(id, result, error) {
386
+ const r = getNode(id);
387
+ const families = familiesOf(r, "review");
388
+ // Relay owns the header and metadata; raw agent text stays as written. A file that cannot be
389
+ // annotated (a full disk, a directory that is not writable) does not keep the review from ending:
390
+ // its result, which says the families too, names the file.
391
+ const dir = reviewDir(r);
392
+ const unkept = [];
393
+ let names = [];
394
+ try {
395
+ names = fs.readdirSync(dir).filter((f) => /\.(md|json)$/.test(f) && f !== "plan.md");
396
+ }
397
+ catch (err) {
398
+ unkept.push(readProblem(dir, err, "its files do not say which families took part, though the review's result does"));
399
+ }
400
+ const consequence = "that file does not say which families took part, though the review's result does";
401
+ for (const file of names) {
402
+ const at = path.join(dir, file);
403
+ let problem;
404
+ try {
405
+ problem = file.endsWith(".md") ? keepRecord(at, `\n(relay) Families: ${families.summary}\n`, { append: true, consequence })
406
+ : keepRecord(at, JSON.stringify({ ...JSON.parse(fs.readFileSync(at, "utf8")), families }, null, 2), { consequence });
407
+ }
408
+ catch (err) {
409
+ // keepRecord says what it could not write; what throws here is the read of the side's .json.
410
+ problem = readProblem(at, err, consequence);
411
+ }
412
+ if (problem)
413
+ unkept.push(problem);
414
+ }
415
+ const warnings = [...(result.warnings ?? []), ...unkept];
416
+ result = { ...result, families, ...warningsOf(warnings) };
417
+ updateNode(id, { result_json: JSON.stringify(result), error: error ?? null, ended_at: now() });
418
+ db().prepare("UPDATE nodes SET status = ? WHERE id = ? AND status IN ('open', 'refused')").run(result.outcome === "refused" ? "refused" : error ? "failed" : "done", id);
419
+ }
420
+ /** Keeps even an empty submitted review; a refusal never supplies an independent verdict. */
421
+ function endRefusedReview(r, p, result) {
422
+ const other = reviewerSide(p);
423
+ const own = readSide(path.join(reviewDir(r), `${p.caller}.json`));
424
+ const paths = Object.fromEntries(inSideOrder([p.caller, other]).filter((l) => fs.existsSync(path.join(reviewDir(r), `${l}.md`))).map((l) => [l, path.join(reviewDir(r), `${l}.md`)]));
425
+ const fresh = reviewParams(getNode(r.id));
426
+ if (fresh.discussion === "opening") {
427
+ delete fresh.discussion;
428
+ updateNode(r.id, { params_json: JSON.stringify(fresh) });
429
+ }
430
+ endReview(r.id, {
431
+ outcome: "refused", refusal: result.refusal, unfinished: true, verdict: "unknown",
432
+ verdict_note: `no independent review was obtained: the ${other} turn was stopped by its vendor's safety system`,
433
+ sides: own ? { [p.caller]: sideSummary(own) } : {},
434
+ consensus: (own?.items ?? []).map((i) => ({ ...i, id: undefined, ids: [i.id], raised_by: [p.caller], status: "unresolved" })),
435
+ reviews: paths, reviewer_job: p.reviewer, ...(p.plan ? { plan: p.plan } : {}),
436
+ note: `The ${other} family produced no completed review. ${result.refusal ? refusalNote(result.refusal) : REFUSAL_POLICY}${own ? " Your own review is preserved and stands alone." : ""}`,
437
+ ...(result.warnings ? { warnings: result.warnings } : {}),
438
+ }, r.error ?? getNode(p.reviewer)?.error ?? undefined);
439
+ }
440
+ /** Builds the consensus list once the reconciliation has ended, however it ended. */
441
+ export function finishReview(reviewId, discussionId) {
442
+ const r = getNode(reviewId);
443
+ if (!r || r.status !== "open")
444
+ return;
445
+ const p = reviewParams(r);
446
+ // Only the review's own reconciliation ends it. (It may close before its id is recorded.)
447
+ if (p.discussion && p.discussion !== "opening" && p.discussion !== discussionId)
448
+ return;
449
+ const d = getNode(discussionId);
450
+ const dp = discussionParams(d);
451
+ const res = JSON.parse(d.result_json ?? "{}");
452
+ const dir = reviewDir(r);
453
+ // Each side's files and final list, in registry order whoever called.
454
+ const labels = inSideOrder([p.caller, reviewerSide(p)]);
455
+ const reviews = Object.fromEntries(labels.map((l) => [l, readSide(path.join(dir, `${l}.json`))]));
456
+ const items = labels.flatMap((l) => reviews[l]?.items ?? []);
457
+ // Both sides' closing blocks, however it ended: the one that closed it never settles the list or the verdict alone.
458
+ const sides = Object.fromEntries(inSideOrder([dp.caller, otherSide(dp)]).map((l) => [l, parseConsensus(dp.state.last[l] ?? null)]));
459
+ const entries = Object.fromEntries(Object.entries(sides).map(([l, b]) => [l, b?.consensus ?? null]));
460
+ endReview(reviewId, {
461
+ outcome: res.outcome, ...(res.refusal ? { refusal: res.refusal, note: res.note, unfinished: true } : {}), ...reconciledVerdict(sides, labels.map((l) => reviews[l]?.coverage)), consensus: buildConsensus(items, entries), cruxes: res.cruxes ?? null, conclusion: res.conclusion,
462
+ sides: Object.fromEntries(labels.map((l) => [l, sideSummary(reviews[l])])), ...(p.plan ? { plan: p.plan } : {}),
463
+ reviews: Object.fromEntries(labels.filter((l) => fs.existsSync(path.join(dir, `${l}.md`))).map((l) => [l, path.join(dir, `${l}.md`)])),
464
+ transcript_path: d.transcript_path, discussion_id: discussionId, reviewer_job: p.reviewer,
465
+ ...warningsOf([...(p.reviewer_warnings ?? []), ...(res.warnings ?? [])]),
466
+ }, res.outcome === "error" || res.outcome === "refused" ? String(res.error) : undefined);
467
+ }
468
+ /** Starts a review or carries one on. ops.ts review, the tool, answers a repeated request_id first. */
469
+ export async function review(inst, a, w = {}) {
470
+ if (!a.review_id) {
471
+ if (a.target && a.plan !== undefined)
472
+ return { error: "give either target (code to review) or plan (a plan to review), not both" };
473
+ if (!a.target && a.plan === undefined)
474
+ return { error: "say what to review: target (a path, a diff range, a branch), or plan (the path of a plan's file, or its text)" };
475
+ const admitted = admitNew(inst, { target: a.reviewer, model: a.model, cwd: a.cwd });
476
+ if ("reason" in admitted)
477
+ return refused(admitted.reason);
478
+ const { caller, to } = admitted;
479
+ // The reviewer's session goes on to reconcile the two reviews in a discussion. A review takes no grant.
480
+ const work = admitWork(caller, to.target, { mode: "read", continues: true }, w);
481
+ if ("reason" in work)
482
+ return refused(work.reason);
483
+ const sp = admitSpeed(caller, to.target, { speed: a.speed, model: to.model ?? a.model }, w);
484
+ if ("reason" in sp)
485
+ return refused(sp.reason);
486
+ const subject = a.plan !== undefined ? planSubject(a.plan, caller.cwd, caller.node !== null) : { kind: "code", target: a.target };
487
+ if ("error" in subject)
488
+ return subject;
489
+ const label = subject.kind === "code" ? subject.target : "path" in subject ? `the plan in ${subject.path}` : "the plan given as text";
490
+ // The review's directory, and a plan given as text, are written before the review is made: one
491
+ // that cannot be written (a full disk, a directory that is not writable) leaves no review open
492
+ // with nothing to run it, only the reason. The reviewer is given the plan's text itself; its
493
+ // copy in plan.md has the secrets relay knows the shape of cut out (core/storage.ts keepRecord).
494
+ const id = newId("review");
495
+ const dir = path.join(runDir(caller.runId), "reviews", id);
496
+ try {
497
+ fs.mkdirSync(dir, { recursive: true });
498
+ }
499
+ catch (err) {
500
+ return { error: writeProblem(dir, err, "no review was started") };
501
+ }
502
+ const plan = subject.kind === "code" ? undefined : "path" in subject ? subject.path : path.join(dir, "plan.md");
503
+ const unkept = subject.kind === "plan" && "text" in subject ? keepRecord(plan, `${subject.text}\n`, { consequence: "no review was started" }) : null;
504
+ if (unkept) {
505
+ fs.rmSync(dir, { recursive: true, force: true });
506
+ return { error: unkept };
507
+ }
508
+ const { r, job } = tx(() => {
509
+ const r = insertNode({
510
+ id, run_id: caller.runId, parent_id: caller.node?.id ?? null, kind: "review", target: to.target, mode: "read",
511
+ depth: caller.depth + 1, allow_delegation: 0, task: `review: ${label}`, cwd: caller.cwd, status: "open",
512
+ });
513
+ const job = insertNode({
514
+ id: newId("job"), run_id: caller.runId, parent_id: r.id, kind: "job", target: to.target, mode: "read", depth: caller.depth + 1,
515
+ allow_delegation: 0, task: `independent review: ${label}`, cwd: caller.cwd, model: to.model ?? a.model ?? null, effort: a.effort ?? null,
516
+ params_json: JSON.stringify({ review_id: r.id, speed: sp.speed }),
517
+ });
518
+ insertTurn(job.id, `review:${r.id}`, reviewerPrompt(subject, a.focus), "read");
519
+ // A contradicted registration still identifies a candidate transcript home, even though
520
+ // it cannot establish routing identity. With no registration, protect both known stores.
521
+ const family = familyOf(inst) ?? inst.registration?.host;
522
+ const codexHome = process.env.CODEX_HOME || path.join(os.homedir(), ".codex");
523
+ const claudeHome = process.env.CLAUDE_CONFIG_DIR || path.join(os.homedir(), ".claude");
524
+ const transcriptHomes = family === "codex" ? [codexHome] : family === "claude" ? [claudeHome] : [codexHome, claudeHome];
525
+ const callerTranscripts = [...new Set([
526
+ ...transcriptHomes.map((home) => path.resolve(expandHome(home))),
527
+ ...(caller.node ? [path.join(harnessHome(), caller.runId, caller.node.id), nodeDir(caller.runId, caller.node.id)] : []),
528
+ ])];
529
+ const p = { target: label, focus: a.focus ?? null, caller: callerSide(inst, to.target), other: to.target, reviewer: job.id, caller_transcripts: callerTranscripts, own: false, ...(plan ? { plan } : {}) };
530
+ updateNode(r.id, { params_json: JSON.stringify(p), started_at: now() });
531
+ const cfg = runConfig(r.run_id);
532
+ recordStart(r.id, inst, w, to.target, job.model, cfg);
533
+ recordStart(job.id, inst, w, to.target, job.model, cfg);
534
+ // Recorded once the review is complete enough to be answered from.
535
+ noteCall(inst, a, r.id);
536
+ return { r, job };
537
+ });
538
+ const warning = dispatch(job.id);
539
+ return { ...reviewView(r.id), ...(warning ? { warning } : {}) };
540
+ }
541
+ const r = getNode(a.review_id);
542
+ if (!r || r.kind !== "review")
543
+ return { error: `${a.review_id} is not a review` };
544
+ if (legacyTwoSided(r))
545
+ return legacyRefusal(r);
546
+ const caller = admitExisting(inst, r, "continue", a.cwd);
547
+ if ("reason" in caller)
548
+ return refused(caller.reason);
549
+ const unknown = knownCaller(inst);
550
+ if (unknown)
551
+ return refused(unknown);
552
+ const p = reviewParams(r);
553
+ const submitting = !!a.own_review || !!a.skip_own;
554
+ const unused = { submission_note: "A submission was already saved or skipped for this review; this call's text was not used." };
555
+ const notSaved = () => ({ ...reviewView(r.id), ...(submitting && reviewParams(getNode(r.id)).own ? unused : {}) });
556
+ const acceptsOwn = (n) => n.status === "open" || n.status === "refused" && !reviewParams(n).own && !reviewParams(n).discussion;
557
+ if (!acceptsOwn(r))
558
+ return notSaved();
559
+ // A speed given here is the reviewer's from its next turn: the reconciliation's first, which this
560
+ // call or a later one opens. It is kept with the review until then (reviewer_speed) and set on the
561
+ // reviewer only as that turn is queued (discuss), so the reviewer's own turn, still running perhaps,
562
+ // keeps its speed. Asked whether or not the call names one: a launched agent may not carry on a
563
+ // reviewer faster than itself.
564
+ const reviewer = getNode(p.reviewer);
565
+ let unapplied;
566
+ if (reviewer?.target) {
567
+ // Until the reconciliation opens, the reviewer goes on at the speed kept for it; from then on, at its own (discuss changes it).
568
+ const current = (!p.discussion && p.reviewer_speed) || speedAfter(reviewer);
569
+ const sp = admitSpeed(caller, reviewer.target, { speed: a.speed, current, model: reviewer.model }, w);
570
+ if ("reason" in sp)
571
+ return refused(sp.reason);
572
+ if (a.speed && p.discussion) {
573
+ unapplied = `The reconciliation is already open, so this call changed no speed: pass speed to discuss${p.discussion === "opening" ? "" : ` with discussion_id "${p.discussion}"`}, from the turn that call queues.`;
574
+ }
575
+ else if (a.speed && sp.speed !== p.reviewer_speed) {
576
+ p.reviewer_speed = sp.speed;
577
+ updateNode(r.id, { params_json: JSON.stringify({ ...reviewParams(getNode(r.id)), reviewer_speed: sp.speed }) });
578
+ }
579
+ }
580
+ const other = reviewerSide(p);
581
+ if (!p.own && !a.own_review && !a.skip_own)
582
+ return reviewView(r.id);
583
+ if (p.discussion)
584
+ return unapplied ? { ...notSaved(), speed_note: unapplied } : notSaved();
585
+ if (submitting && !p.own)
586
+ tx(() => {
587
+ const row = getNode(r.id), q = reviewParams(row);
588
+ if (row.status === "open" && !q.own && !q.submission_tried)
589
+ updateNode(r.id, { params_json: JSON.stringify({ ...q, submission_tried: true }) });
590
+ });
591
+ // Do not accept the submission until the reviewer settles. In particular, own stays false:
592
+ // a timed-out call, a different connection or a restarted server must still withhold everything.
593
+ // Use the status wait machinery, including progress, cancellation, slot lending and host cap.
594
+ const done = await waitUntil(() => {
595
+ const row = getNode(r.id);
596
+ return !row || row.status !== "open" || !!reviewParams(row).discussion || settled(p.reviewer);
597
+ }, waitOpts(inst, r.run_id, w, { progressOf: p.reviewer, awaits: [r.id] }));
598
+ const fresh = getNode(r.id);
599
+ if (!acceptsOwn(fresh) || reviewParams(fresh).discussion)
600
+ return notSaved();
601
+ if (!done || w.signal?.aborted) {
602
+ const again = p.own ? "" : a.own_review ? " and own_review" : " and skip_own: true";
603
+ return { ...pendingHandle(r.id, { review_id: r.id }, inst), next: `The ${other} reviewer is still working; call status with id "${p.reviewer}" and wait_s until it settles, then call review with review_id "${r.id}"${again} again.${!p.own ? " Relay has not accepted or stored your review." : ""}` };
604
+ }
605
+ // A launched caller's turn or authority may have ended while this call waited.
606
+ const stillAllowed = admitExisting(inst, fresh, "continue", a.cwd);
607
+ if ("reason" in stillAllowed)
608
+ return refused(stillAllowed.reason);
609
+ // Save the caller's review and claim reconciliation together. Concurrent waiters keep the
610
+ // first saved submission and only one opens the discussion; no process-local state survives.
611
+ const claimed = tx(() => {
612
+ const fresh = getNode(r.id);
613
+ const q = reviewParams(fresh);
614
+ if (!acceptsOwn(fresh) || q.discussion || !settled(q.reviewer))
615
+ return false;
616
+ const alreadyAccepted = q.own;
617
+ let saved = q;
618
+ if (!alreadyAccepted) {
619
+ // The caller's family is recorded only for the submission relay accepts, in the same transaction.
620
+ const contribution = callerLabel(inst, w);
621
+ addContribution(r.id, contribution);
622
+ addContribution(q.reviewer, contribution);
623
+ saved = reviewParams(getNode(r.id));
624
+ if (a.own_review)
625
+ writeSide(reviewDir(r), saved.caller, saved.target, a.own_review, "nothing else was changed, and the call can be made again");
626
+ saved.own = true;
627
+ saved.skipped = !a.own_review;
628
+ }
629
+ updateNode(r.id, { params_json: JSON.stringify({ ...saved, discussion: "opening" }) });
630
+ return { params: saved, alreadyAccepted };
631
+ });
632
+ if (!claimed)
633
+ return notSaved();
634
+ const submissionNote = submitting && claimed.alreadyAccepted ? unused : {};
635
+ try {
636
+ return { ...await reconcileReview(inst, r, claimed.params, w), ...submissionNote };
637
+ }
638
+ catch (e) {
639
+ // Whatever went wrong, the claim is let go, so that the review is not left opening for ever and can be tried again.
640
+ const q = reviewParams(getNode(r.id));
641
+ if (q.discussion === "opening") {
642
+ delete q.discussion;
643
+ updateNode(r.id, { params_json: JSON.stringify(q) });
644
+ }
645
+ throw e;
646
+ }
647
+ }
648
+ /** Once the reviewer has finished and this call holds the claim: ends the review unreconciled, or opens the reconciliation. */
649
+ async function reconcileReview(inst, r, p, w) {
650
+ const dir = reviewDir(r);
651
+ const other = reviewerSide(p);
652
+ const job = getNode(p.reviewer);
653
+ const text = nodeTurns(job.id)[0]?.reply ?? "";
654
+ const own = readItems(path.join(dir, `${p.caller}.json`));
655
+ const unresolved = (items, by) => items.map((i) => ({ ids: [i.id], raised_by: [by], status: "unresolved", ...i, id: undefined }));
656
+ const paths = () => Object.fromEntries(inSideOrder([p.caller, other]).filter((l) => fs.existsSync(path.join(dir, `${l}.md`))).map((l) => [l, path.join(dir, `${l}.md`)]));
657
+ const jobResult = JSON.parse(job.result_json ?? "{}");
658
+ if (job.status === "refused" || r.status === "refused") {
659
+ endRefusedReview(r, p, r.status === "refused" ? JSON.parse(r.result_json ?? "{}") : JSON.parse(job.result_json ?? "{}"));
660
+ return reviewView(r.id);
661
+ }
662
+ const jobWarnings = [...(jobResult.warnings ?? []), ...(jobResult.blocked?.length ? [`was refused ${jobResult.blocked.join("; ")}`] : [])].map((w) => `${other} reviewer: ${w}`);
663
+ // Unreconciled, the verdict is the one review's own.
664
+ const alone = (label, s) => ({ verdict: s?.verdict ?? "not stated", sides: { [label]: sideSummary(s) }, ...(p.plan ? { plan: p.plan } : {}) });
665
+ // A reviewer that was refused something still wrote its review.
666
+ if ((job.status !== "done" && job.status !== "blocked") || !text) {
667
+ const why = job.error ?? `the ${other} reviewer ended as ${job.status}`;
668
+ // Without an independent review there is no verdict to give: the caller's own is kept under sides, never as the review's.
669
+ // The review fails unless the caller's own raised something, as before verdicts existed.
670
+ const ownReview = readSide(path.join(dir, `${p.caller}.json`));
671
+ endReview(r.id, {
672
+ outcome: own.length ? "partial" : "error", ...alone(p.caller, ownReview), verdict: "unknown", verdict_note: `no independent review was obtained: the ${other} reviewer failed`,
673
+ reviews: paths(), errors: { [other]: why }, consensus: unresolved(own, p.caller), reviewer_job: job.id,
674
+ note: `The ${other} reviewer failed, so nothing was reconciled.${own.length ? " Your own review stands alone." : ""}`, ...(jobWarnings.length ? { warnings: jobWarnings } : {}),
675
+ }, own.length ? undefined : why);
676
+ return reviewView(r.id);
677
+ }
678
+ const theirReview = writeSide(dir, other, p.target, text, `your ${p.skipped ? "choice to skip your own review" : "own review"} was saved, so make the call again with review_id alone once it can be written`);
679
+ const theirs = theirReview.items;
680
+ if (p.skipped) {
681
+ endReview(r.id, {
682
+ outcome: "partial", ...alone(other, theirReview), reviews: paths(), consensus: unresolved(theirs, other), reviewer_job: job.id,
683
+ note: "You gave no review of your own, so nothing was reconciled. This is the other reviewer's list as it stands.", ...(jobWarnings.length ? { warnings: jobWarnings } : {}),
684
+ });
685
+ return reviewView(r.id);
686
+ }
687
+ // Kept with the review: the reconciliation's turns run on the reviewer's session and replace its job's result.
688
+ if (jobWarnings.length)
689
+ updateNode(r.id, { params_json: JSON.stringify({ ...reviewParams(getNode(r.id)), reviewer_warnings: jobWarnings }) });
690
+ const mine = fs.readFileSync(path.join(dir, `${p.caller}.md`), "utf8");
691
+ // Where relay gave items ids of their own, each side is told: the reviewer of its own here, and of the caller's in that file's header.
692
+ const theirIds = renumberedNote(theirReview);
693
+ const opening = `Your own review is the one you wrote earlier in this session; its items are ${sidePrefix(other)}1, ${sidePrefix(other)}2, … in the order you numbered them.${theirIds ? ` ${theirIds}` : ""}\n` +
694
+ `Mine follows; its items are ${sidePrefix(p.caller)}<n>.\n\n----- ${p.caller} review -----\n${mine.trim()}\n----- end of ${p.caller} review -----\n\n` +
695
+ "Go through both lists: say which items you hold to be real and at what severity, which you would drop and why, which are the same finding under two ids, and what verdict and coverage the two reviews reach between them.\nCONTINUE";
696
+ const rules = reviewDiscussionRules([p.caller, other]);
697
+ // At the speed a call carrying on the review gave for the reviewer, if one did; else the reviewer goes on at its own.
698
+ const speed = reviewParams(getNode(r.id)).reviewer_speed;
699
+ const out = await discuss(inst, { topic: `Reconcile two independent reviews of ${p.target} into one consensus list.`, message: opening, with: job.id, role: "peer", ...(speed ? { speed } : {}) }, w, { extraRules: rules, reviewId: r.id, caller: p.caller });
700
+ if (typeof out.discussion_id !== "string") {
701
+ const q = reviewParams(getNode(r.id));
702
+ delete q.discussion;
703
+ updateNode(r.id, { params_json: JSON.stringify(q) });
704
+ return { review_id: r.id, ...out, families: familiesOf(getNode(r.id), "review") };
705
+ }
706
+ const now_ = reviewParams(getNode(r.id));
707
+ now_.discussion = out.discussion_id;
708
+ updateNode(r.id, { params_json: JSON.stringify(now_) });
709
+ // The reconciliation can end on its opening turn (the reviewer refused by its vendor, or failed):
710
+ // the review has then settled, so the caller gets its result, not an invitation to carry on.
711
+ if (getNode(r.id).status !== "open")
712
+ return { ...reviewView(r.id), ...(jobWarnings.length ? { reviewer_warnings: jobWarnings } : {}) };
713
+ const idsNote = [[`your review`, readSide(path.join(dir, `${p.caller}.json`))], [`the ${other} review`, theirReview]]
714
+ .filter(([, s]) => s?.renumbered?.length).map(([whose, s]) => `${whose}: ${s.renumbered.join(", ")}`);
715
+ return {
716
+ review_id: r.id, phase: "reconciling", their_review: path.join(dir, `${other}.md`), their_items: theirs.length, your_items: own.length,
717
+ ...(idsNote.length ? { ids_note: `Relay gave its own ids to items whose n was missing, not a positive whole number, or used before. In ${idsNote.join("; in ")}.` } : {}), ...out,
718
+ families: familiesOf(getNode(r.id), "review"), rules,
719
+ next: `Their review is at their_review; their first reconciliation message is in reply. Carry on with discuss (discussion_id "${out.discussion_id}") until you both write AGREE, each AGREE message carrying the consensus JSON block the rules describe. Then result with id "${r.id}" gives the consensus list.`,
720
+ ...(jobWarnings.length ? { reviewer_warnings: jobWarnings } : {}),
721
+ };
722
+ }