@ftrdotdev/pi-delegates 0.0.0-stage → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (138) hide show
  1. package/CHANGELOG.md +128 -0
  2. package/LICENSE +21 -0
  3. package/OPERATIONS.md +130 -0
  4. package/README.md +456 -2
  5. package/ROADMAP.md +179 -0
  6. package/TESTING.md +896 -0
  7. package/agents.ts +8 -0
  8. package/examples/README.md +114 -0
  9. package/examples/gated.ts +28 -0
  10. package/index.ts +9 -0
  11. package/package.json +94 -4
  12. package/skills/pi-delegates/SKILL.md +176 -0
  13. package/skills/pi-delegates/references/control.md +159 -0
  14. package/skills/pi-delegates/references/definitions.md +163 -0
  15. package/skills/pi-delegates/references/gates.md +175 -0
  16. package/skills/pi-delegates/references/launch.md +184 -0
  17. package/src/docs-contract.test.ts +106 -0
  18. package/src/domain/definitions.test.ts +41 -0
  19. package/src/domain/definitions.ts +163 -0
  20. package/src/domain/failure.ts +33 -0
  21. package/src/domain/ids.ts +13 -0
  22. package/src/domain/model-source.ts +30 -0
  23. package/src/domain/names.ts +35 -0
  24. package/src/domain/orchestration/admission.ts +78 -0
  25. package/src/domain/orchestration/control.test.ts +1332 -0
  26. package/src/domain/orchestration/control.ts +457 -0
  27. package/src/domain/orchestration/fanout.test.ts +524 -0
  28. package/src/domain/orchestration/fanout.ts +372 -0
  29. package/src/domain/orchestration/gates.test.ts +685 -0
  30. package/src/domain/orchestration/gates.ts +360 -0
  31. package/src/domain/orchestration/launch.test.ts +372 -0
  32. package/src/domain/orchestration/launch.ts +691 -0
  33. package/src/domain/orchestration/requests.test.ts +695 -0
  34. package/src/domain/orchestration/requests.ts +782 -0
  35. package/src/domain/orchestration/review.test.ts +292 -0
  36. package/src/domain/orchestration/review.ts +168 -0
  37. package/src/domain/orchestration/run-wait.test.ts +265 -0
  38. package/src/domain/orchestration/run-wait.ts +256 -0
  39. package/src/domain/orchestration/workflow-section.test.ts +62 -0
  40. package/src/domain/orchestration/workflow-section.ts +99 -0
  41. package/src/domain/orchestration/workflow.test.ts +1566 -0
  42. package/src/domain/orchestration/workflow.ts +778 -0
  43. package/src/domain/run-records.test.ts +27 -0
  44. package/src/domain/run-records.ts +689 -0
  45. package/src/domain/settlement.test.ts +186 -0
  46. package/src/domain/settlement.ts +137 -0
  47. package/src/domain/shapes.test.ts +185 -0
  48. package/src/domain/skills.test.ts +477 -0
  49. package/src/domain/skills.ts +114 -0
  50. package/src/domain/tool-schema.test.ts +46 -0
  51. package/src/domain/tool-schema.ts +20 -0
  52. package/src/domain/toolkit.test.ts +215 -0
  53. package/src/domain/toolkit.ts +374 -0
  54. package/src/domain/turn-budget.test.ts +37 -0
  55. package/src/domain/turn-budget.ts +23 -0
  56. package/src/domain/view.test.ts +803 -0
  57. package/src/domain/view.ts +491 -0
  58. package/src/example.test.ts +15 -0
  59. package/src/extension/commands.test.ts +485 -0
  60. package/src/extension/commands.ts +230 -0
  61. package/src/extension/entry.test.ts +1276 -0
  62. package/src/extension/entry.ts +380 -0
  63. package/src/extension/gate-alerts.test.ts +237 -0
  64. package/src/extension/gate-alerts.ts +143 -0
  65. package/src/extension/guard.test.ts +48 -0
  66. package/src/extension/guard.ts +31 -0
  67. package/src/extension/host-signals.test.ts +20 -0
  68. package/src/extension/host-signals.ts +13 -0
  69. package/src/extension/inspector-command.test.ts +1343 -0
  70. package/src/extension/inspector-command.ts +685 -0
  71. package/src/extension/prompt.test.ts +108 -0
  72. package/src/extension/prompt.ts +50 -0
  73. package/src/extension/request-alerts.test.ts +183 -0
  74. package/src/extension/request-alerts.ts +181 -0
  75. package/src/extension/retry-observer.test.ts +292 -0
  76. package/src/extension/retry-observer.ts +150 -0
  77. package/src/extension/revocation.test.ts +81 -0
  78. package/src/extension/revocation.ts +84 -0
  79. package/src/extension/settle-alerts.test.ts +579 -0
  80. package/src/extension/settle-alerts.ts +175 -0
  81. package/src/extension/shortcut.test.ts +62 -0
  82. package/src/extension/shortcut.ts +105 -0
  83. package/src/extension/tools.test.ts +1294 -0
  84. package/src/extension/tools.ts +553 -0
  85. package/src/extension/version.test.ts +115 -0
  86. package/src/extension/version.ts +97 -0
  87. package/src/goldens.test.ts +294 -0
  88. package/src/harness-policy.test.ts +76 -0
  89. package/src/layers.test.ts +309 -0
  90. package/src/layers.ts +405 -0
  91. package/src/package-manifest.test.ts +170 -0
  92. package/src/presentation/actions.test.ts +221 -0
  93. package/src/presentation/actions.ts +85 -0
  94. package/src/presentation/activity.test.ts +386 -0
  95. package/src/presentation/activity.ts +66 -0
  96. package/src/presentation/close.test.ts +359 -0
  97. package/src/presentation/inspector.test.ts +682 -0
  98. package/src/presentation/inspector.ts +442 -0
  99. package/src/presentation/overlay.test.ts +553 -0
  100. package/src/presentation/overlay.ts +229 -0
  101. package/src/presentation/repaint.test.ts +365 -0
  102. package/src/presentation/shortcut.ts +2 -0
  103. package/src/presentation/snapshot.test.ts +535 -0
  104. package/src/presentation/snapshot.ts +306 -0
  105. package/src/presentation/status.test.ts +43 -0
  106. package/src/presentation/status.ts +30 -0
  107. package/src/presentation/strip.test.ts +203 -0
  108. package/src/presentation/strip.ts +67 -0
  109. package/src/presentation/wording.test.ts +388 -0
  110. package/src/presentation/wording.ts +294 -0
  111. package/src/runtime/bridge.test.ts +131 -0
  112. package/src/runtime/bridge.ts +128 -0
  113. package/src/runtime/clock.test.ts +31 -0
  114. package/src/runtime/clock.ts +31 -0
  115. package/src/runtime/config.test.ts +63 -0
  116. package/src/runtime/config.ts +92 -0
  117. package/src/runtime/context.test.ts +19 -0
  118. package/src/runtime/context.ts +9 -0
  119. package/src/runtime/execution-env.test.ts +33 -0
  120. package/src/runtime/execution-env.ts +15 -0
  121. package/src/runtime/extensions.test.ts +86 -0
  122. package/src/runtime/extensions.ts +152 -0
  123. package/src/runtime/handle.ts +54 -0
  124. package/src/runtime/log.test.ts +140 -0
  125. package/src/runtime/log.ts +91 -0
  126. package/src/runtime/mcp.test.ts +1450 -0
  127. package/src/runtime/mcp.ts +1005 -0
  128. package/src/runtime/models.test.ts +145 -0
  129. package/src/runtime/models.ts +259 -0
  130. package/src/runtime/observe.test.ts +50 -0
  131. package/src/runtime/observe.ts +150 -0
  132. package/src/runtime/runtime-state.test.ts +25 -0
  133. package/src/runtime/runtime-state.ts +36 -0
  134. package/src/runtime/session-tag.ts +11 -0
  135. package/src/runtime/session.test.ts +352 -0
  136. package/src/runtime/session.ts +263 -0
  137. package/src/runtime/storage.ts +29 -0
  138. package/src/test-hygiene.test.ts +97 -0
@@ -0,0 +1,292 @@
1
+ import { MemoryStorage } from "@earendil-works/pi-durable";
2
+ import { assert, it } from "@effect/vitest";
3
+ import { makeTempDir } from "../../../test-support/platform.ts";
4
+ import { PROPERTY_RUNS } from "@ftrdotdev/pi-test-kit";
5
+ import {
6
+ dispositionArbitrary,
7
+ dispositionsArbitrary,
8
+ freeTextArbitrary,
9
+ noteArbitrary,
10
+ } from "../../../test-support/arbitraries.ts";
11
+ import { stubHostSource } from "../../../test-support/stub-model-source.ts";
12
+ import { createCatalogue } from "../definitions.ts";
13
+ import { launch, type HostDefaults } from "./launch.ts";
14
+ import {
15
+ aggregate,
16
+ parseDisposition,
17
+ ReviewDoc,
18
+ type Disposition as DispositionType,
19
+ } from "./review.ts";
20
+ import { viewRun, viewSession } from "../view.ts";
21
+ import { RunDoc } from "../run-records.ts";
22
+ import { waitFor } from "../../../test-support/wait.ts";
23
+ import { DEFAULTS } from "../../runtime/config.ts";
24
+ import { HostModelAdapter } from "../../runtime/models.ts";
25
+ import { type SessionIdentity } from "../../runtime/session.ts";
26
+ import { openTestSession } from "../../../test-support/seams.ts";
27
+
28
+ const host: HostDefaults = {
29
+ model: { provider: "stub", modelId: "stub-1" },
30
+ thinkingLevel: "low",
31
+ };
32
+
33
+ const identityFor = async (sessionId: string): Promise<SessionIdentity> => {
34
+ const sessionDir = await makeTempDir("delegates-review-");
35
+ return { sessionId, sessionDir, cwd: sessionDir, agentDir: sessionDir };
36
+ };
37
+
38
+ const corpus = (texts: readonly string[]) => stubHostSource({ texts });
39
+
40
+ const reviewers = [{ agent: "reviewer" }, { agent: "reviewer" }, { agent: "reviewer" }];
41
+
42
+ it("each reviewer gets a disposition row", async () => {
43
+ const runtime = await openTestSession({
44
+ identity: await identityFor("s-1"),
45
+ models: new HostModelAdapter(
46
+ corpus([
47
+ '{"disposition":"accepted"}',
48
+ '{"disposition":"changes_requested","note":"fix it"}',
49
+ '{"disposition":"accepted"}',
50
+ ]),
51
+ ),
52
+ storage: new MemoryStorage(),
53
+ });
54
+ try {
55
+ const result = await launch(
56
+ { kind: "review", reviewers, task: "review the diff" },
57
+ { runtime, catalogue: createCatalogue(), host, waitMs: 20_000 },
58
+ );
59
+ const record = await runtime.snapshot(ReviewDoc, result.view.runId);
60
+ assert.strictEqual(record?.reviewers.length, 3);
61
+ assert.deepStrictEqual(record?.reviewers.map((row) => row.disposition).sort(), [
62
+ "accepted",
63
+ "accepted",
64
+ "changes_requested",
65
+ ]);
66
+ assert.strictEqual(record?.aggregate, "changes_requested");
67
+ assert.strictEqual(result.view.answer, "changes_requested");
68
+ assert.strictEqual(result.text, `Run ${result.view.runId}: changes_requested`);
69
+ } finally {
70
+ await runtime.close();
71
+ }
72
+ });
73
+
74
+ const cases: ReadonlyArray<readonly [readonly DispositionType[], DispositionType]> = [
75
+ [["rejected", "accepted"], "rejected"],
76
+ [["changes_requested", "accepted"], "changes_requested"],
77
+ [["inconclusive", "accepted"], "inconclusive"],
78
+ [["accepted", "accepted"], "accepted"],
79
+ ];
80
+
81
+ it.each(cases)("aggregation follows the policy order: %j", (dispositions, expected) => {
82
+ assert.strictEqual(aggregate(dispositions), expected);
83
+ });
84
+
85
+ it("a reviewer that fails yields inconclusive", async () => {
86
+ const runtime = await openTestSession({
87
+ identity: await identityFor("s-1"),
88
+ models: new HostModelAdapter(
89
+ stubHostSource({
90
+ failAt: [2],
91
+ texts: ['{"disposition":"accepted"}', "", '{"disposition":"accepted"}'],
92
+ }),
93
+ ),
94
+ storage: new MemoryStorage(),
95
+ config: { ...DEFAULTS, laneCap: 1, sessionCeiling: 8, diagnostics: [] },
96
+ });
97
+ try {
98
+ const result = await launch(
99
+ { kind: "review", reviewers, task: "review the diff" },
100
+ { runtime, catalogue: createCatalogue(), host, waitMs: 20_000 },
101
+ );
102
+ const record = await runtime.snapshot(ReviewDoc, result.view.runId);
103
+ assert.strictEqual(record?.reviewers[1]?.disposition, "inconclusive");
104
+ assert.ok(record?.reviewers[1]?.diagnostic !== null);
105
+ assert.strictEqual(record?.aggregate, "inconclusive");
106
+ } finally {
107
+ await runtime.close();
108
+ }
109
+ });
110
+
111
+ it("a malformed answer is inconclusive and keeps the raw text", async () => {
112
+ const runtime = await openTestSession({
113
+ identity: await identityFor("s-1"),
114
+ models: new HostModelAdapter(corpus(["looks good to me", '{"disposition":"maybe"}'])),
115
+ storage: new MemoryStorage(),
116
+ });
117
+ try {
118
+ const result = await launch(
119
+ { kind: "review", reviewers: reviewers.slice(0, 2), task: "review the diff" },
120
+ { runtime, catalogue: createCatalogue(), host, waitMs: 20_000 },
121
+ );
122
+ const record = await runtime.snapshot(ReviewDoc, result.view.runId);
123
+ assert.deepStrictEqual(
124
+ record?.reviewers.map((row) => row.disposition),
125
+ ["inconclusive", "inconclusive"],
126
+ );
127
+ assert.strictEqual(record?.reviewers[0]?.diagnostic, "looks good to me");
128
+ assert.strictEqual(record?.reviewers[1]?.diagnostic, '{"disposition":"maybe"}');
129
+ } finally {
130
+ await runtime.close();
131
+ }
132
+ });
133
+
134
+ it.prop(
135
+ "only a well-formed answer parses",
136
+ { disposition: dispositionArbitrary, note: noteArbitrary },
137
+ ({ disposition, note }) => {
138
+ const json = JSON.stringify({ disposition, note });
139
+ assert.deepStrictEqual(parseDisposition(json), { disposition, note });
140
+ assert.deepStrictEqual(parseDisposition(`Here is my review.\n${json}`), {
141
+ disposition,
142
+ note,
143
+ });
144
+ assert.deepStrictEqual(parseDisposition(` ${json} `), { disposition, note });
145
+ },
146
+ { arbitrary: { runs: PROPERTY_RUNS } },
147
+ );
148
+
149
+ it.prop(
150
+ "aggregation follows the policy order",
151
+ { dispositions: dispositionsArbitrary },
152
+ ({ dispositions }) => {
153
+ const value = aggregate(dispositions);
154
+ if (dispositions.includes("rejected")) assert.strictEqual(value, "rejected");
155
+ else if (dispositions.includes("changes_requested")) {
156
+ assert.strictEqual(value, "changes_requested");
157
+ } else if (dispositions.includes("inconclusive") || dispositions.length === 0) {
158
+ assert.strictEqual(value, "inconclusive");
159
+ } else {
160
+ assert.strictEqual(value, "accepted");
161
+ }
162
+ assert.strictEqual(aggregate([...dispositions, "accepted"]), value);
163
+ },
164
+ { arbitrary: { runs: PROPERTY_RUNS } },
165
+ );
166
+
167
+ it.prop(
168
+ "text without a disposition object never parses",
169
+ { text: freeTextArbitrary },
170
+ ({ text }) => {
171
+ if (text.includes("{")) return;
172
+ assert.strictEqual(parseDisposition(text), undefined);
173
+ },
174
+ { arbitrary: { runs: PROPERTY_RUNS } },
175
+ );
176
+
177
+ it("dispositions survive a reopen", async () => {
178
+ const identity = await identityFor("s-1");
179
+ const first = await openTestSession({
180
+ identity,
181
+ models: new HostModelAdapter(
182
+ corpus(['{"disposition":"accepted"}', '{"disposition":"rejected"}']),
183
+ ),
184
+ });
185
+ const result = await launch(
186
+ { kind: "review", reviewers: reviewers.slice(0, 2), task: "review" },
187
+ { runtime: first, catalogue: createCatalogue(), host, waitMs: 20_000 },
188
+ );
189
+ await first.close();
190
+
191
+ const second = await openTestSession({ identity, models: new HostModelAdapter(corpus([])) });
192
+ try {
193
+ const session = await viewSession(second);
194
+ const review = session.reviews[0];
195
+ assert.strictEqual(review?.reviewers.length, 2);
196
+ assert.strictEqual(review?.aggregate, "rejected");
197
+ assert.strictEqual(review?.runId, result.view.runId);
198
+ } finally {
199
+ await second.close();
200
+ }
201
+ });
202
+
203
+ it("ignores a disposition object followed by trailing prose", () => {
204
+ assert.strictEqual(parseDisposition('{"disposition":"accepted"}\nthanks for reading'), undefined);
205
+ });
206
+
207
+ it("chooses the last valid object after prose with two objects", () => {
208
+ const answer =
209
+ 'First I thought {"disposition":"inconclusive"}; then I decided ' +
210
+ '{"disposition":"changes_requested","note":"fix it"}';
211
+ assert.deepStrictEqual(parseDisposition(answer), {
212
+ disposition: "changes_requested",
213
+ note: "fix it",
214
+ });
215
+ });
216
+
217
+ const deferred = (): { readonly promise: Promise<void>; readonly release: () => void } => {
218
+ let release: () => void = () => {};
219
+ const promise = new Promise<void>((resolve) => {
220
+ release = resolve;
221
+ });
222
+ return { promise, release };
223
+ };
224
+
225
+ it("a detached review returns the group status without waiting", async () => {
226
+ const held = deferred();
227
+ const runtime = await openTestSession({
228
+ identity: await identityFor("s-detached"),
229
+ models: new HostModelAdapter(
230
+ stubHostSource({
231
+ text: '{"disposition":"accepted"}',
232
+ hold: () => held.promise,
233
+ holdAt: [1, 2],
234
+ }),
235
+ ),
236
+ storage: new MemoryStorage(),
237
+ });
238
+ try {
239
+ const result = await launch(
240
+ {
241
+ kind: "review",
242
+ task: "review the diff",
243
+ reviewers: [{ agent: "reviewer" }, { agent: "reviewer" }],
244
+ execution: "detached",
245
+ },
246
+ { runtime, catalogue: createCatalogue(), host, waitMs: 5_000 },
247
+ );
248
+ assert.notStrictEqual(result.view.status, "answered");
249
+ assert.strictEqual(await runtime.snapshot(ReviewDoc, result.view.runId), undefined);
250
+ assert.strictEqual((await runtime.snapshot(RunDoc, result.view.runId))?.execution, "detached");
251
+ held.release();
252
+ await waitFor(
253
+ async () => (await viewRun(result.view.runId, runtime)).status === "answered",
254
+ "the detached review settles",
255
+ 10_000,
256
+ );
257
+ } finally {
258
+ await runtime.close();
259
+ }
260
+ }, 20_000);
261
+
262
+ it("a review honours a reviewer's own budget", async () => {
263
+ const runtime = await openTestSession({
264
+ identity: await identityFor("s-budget"),
265
+ models: new HostModelAdapter(
266
+ corpus(['{"disposition":"accepted"}', '{"disposition":"accepted"}']),
267
+ ),
268
+ storage: new MemoryStorage(),
269
+ });
270
+ try {
271
+ const result = await launch(
272
+ {
273
+ kind: "review",
274
+ task: "review the diff",
275
+ maxTurns: 120,
276
+ reviewers: [{ agent: "reviewer", maxTurns: 40 }, { agent: "reviewer" }],
277
+ },
278
+ { runtime, catalogue: createCatalogue(), host, waitMs: 20_000 },
279
+ );
280
+ const parent = await runtime.snapshot(RunDoc, result.view.runId);
281
+ const docs = [];
282
+ for (const runId of parent?.childRunIds ?? []) {
283
+ docs.push(await runtime.snapshot(RunDoc, runId));
284
+ }
285
+ assert.deepStrictEqual(
286
+ docs.map((doc) => doc?.maxTurns),
287
+ [40, 120],
288
+ );
289
+ } finally {
290
+ await runtime.close();
291
+ }
292
+ }, 20_000);
@@ -0,0 +1,168 @@
1
+ import { defineDocFamily, type JsonObject } from "@earendil-works/pi-durable";
2
+ import { Option, Schema } from "effect";
3
+
4
+ export const Disposition = Schema.Literals([
5
+ "accepted",
6
+ "changes_requested",
7
+ "rejected",
8
+ "inconclusive",
9
+ ]);
10
+ export type Disposition = typeof Disposition.Type;
11
+
12
+ export const DISPOSITIONS = ["accepted", "changes_requested", "rejected", "inconclusive"] as const;
13
+
14
+ /** The reviewer's whole answer. One Schema serves decoding, generation and the message. */
15
+ export const DispositionAnswer = Schema.Struct({
16
+ disposition: Disposition,
17
+ note: Schema.optional(Schema.String),
18
+ });
19
+
20
+ export const ReviewEntry = Schema.Struct({
21
+ child: Schema.Finite,
22
+ runId: Schema.String,
23
+ disposition: Disposition,
24
+ note: Schema.NullOr(Schema.String),
25
+ diagnostic: Schema.NullOr(Schema.String),
26
+ });
27
+
28
+ export const ReviewRecord = Schema.Struct({
29
+ runId: Schema.String,
30
+ reviewers: Schema.Array(ReviewEntry),
31
+ aggregate: Disposition,
32
+ });
33
+ export type ReviewRecord = typeof ReviewRecord.Type;
34
+ export type ReviewEntry = typeof ReviewEntry.Type;
35
+
36
+ export const ReviewDoc = defineDocFamily<
37
+ ReviewRecord & JsonObject,
38
+ { readonly runId: string } & JsonObject
39
+ >({
40
+ kind: "delegates.review",
41
+ version: 1,
42
+ scope: "session",
43
+ family: true,
44
+ initial: (seed) => ({ runId: seed.runId, reviewers: [], aggregate: "inconclusive" }),
45
+ checkpointWhen: () => true,
46
+ });
47
+
48
+ /** Rejection wins; then a change request; then inconclusive; otherwise accepted. */
49
+ export const aggregate = (dispositions: readonly Disposition[]): Disposition => {
50
+ if (dispositions.includes("rejected")) return "rejected";
51
+ if (dispositions.includes("changes_requested")) return "changes_requested";
52
+ if (dispositions.includes("inconclusive") || dispositions.length === 0) return "inconclusive";
53
+ return "accepted";
54
+ };
55
+
56
+ export interface ReviewOutcome {
57
+ readonly disposition: Disposition;
58
+ readonly note: string | null;
59
+ }
60
+
61
+ const decode = Schema.decodeUnknownOption(DispositionAnswer);
62
+
63
+ const parseObject = (text: string): ReviewOutcome | undefined => {
64
+ let value: unknown;
65
+ try {
66
+ value = JSON.parse(text);
67
+ } catch {
68
+ return undefined;
69
+ }
70
+ const result = decode(value);
71
+ if (Option.isSome(result)) {
72
+ return {
73
+ disposition: result.value.disposition,
74
+ note: result.value.note ?? null,
75
+ };
76
+ }
77
+ return undefined;
78
+ };
79
+
80
+ /** The brace-balanced objects in the text, outermost first. */
81
+ const objects = (text: string): readonly string[] => {
82
+ const found: string[] = [];
83
+ for (let start = 0; start < text.length; start += 1) {
84
+ if (text[start] !== "{") continue;
85
+ let depth = 0;
86
+ let inString = false;
87
+ let escaped = false;
88
+ for (let end = start; end < text.length; end += 1) {
89
+ const character = text[end];
90
+ if (inString) {
91
+ if (escaped) escaped = false;
92
+ else if (character === "\\") escaped = true;
93
+ else if (character === '"') inString = false;
94
+ } else if (character === '"') inString = true;
95
+ else if (character === "{") depth += 1;
96
+ else if (character === "}") {
97
+ depth -= 1;
98
+ if (depth === 0) {
99
+ found.push(text.slice(start, end + 1));
100
+ start = end;
101
+ break;
102
+ }
103
+ }
104
+ }
105
+ }
106
+ return found;
107
+ };
108
+
109
+ /** The last object in the text that decodes as a disposition answer and ends the text. */
110
+ const lastObject = (text: string): ReviewOutcome | undefined => {
111
+ const trimmed = text.trimEnd();
112
+ for (const candidate of [...objects(trimmed)].reverse()) {
113
+ if (!trimmed.endsWith(candidate)) continue;
114
+ const parsed = parseObject(candidate);
115
+ if (parsed !== undefined) return parsed;
116
+ }
117
+ return undefined;
118
+ };
119
+
120
+ /**
121
+ * Accepts the whole trimmed answer as one JSON object, or the last such object
122
+ * at the end of a prose answer. Any other text yields `undefined`; never throws.
123
+ */
124
+ export const parseDisposition = (answer: string): ReviewOutcome | undefined =>
125
+ parseObject(answer.trim()) ?? lastObject(answer);
126
+
127
+ export const REVIEW_INSTRUCTION =
128
+ 'End your answer with one JSON object: {"disposition":"accepted"|"changes_requested"|"rejected"|"inconclusive","note":"..."}';
129
+
130
+ export const reviewRow = (input: {
131
+ readonly child: number;
132
+ readonly runId: string;
133
+ readonly answer: string | null;
134
+ readonly failure?: string;
135
+ }): ReviewEntry => {
136
+ if (input.answer === null) {
137
+ return {
138
+ child: input.child,
139
+ runId: input.runId,
140
+ disposition: "inconclusive",
141
+ note: null,
142
+ diagnostic: input.failure ?? "no answer",
143
+ };
144
+ }
145
+ const parsed = parseDisposition(input.answer);
146
+ if (parsed === undefined) {
147
+ return {
148
+ child: input.child,
149
+ runId: input.runId,
150
+ disposition: "inconclusive",
151
+ note: null,
152
+ diagnostic: input.answer,
153
+ };
154
+ }
155
+ return {
156
+ child: input.child,
157
+ runId: input.runId,
158
+ disposition: parsed.disposition,
159
+ note: parsed.note,
160
+ diagnostic: null,
161
+ };
162
+ };
163
+
164
+ export const reviewRecord = (runId: string, rows: readonly ReviewEntry[]): ReviewRecord => ({
165
+ runId,
166
+ reviewers: [...rows],
167
+ aggregate: aggregate(rows.map((row) => row.disposition)),
168
+ });