pi-harness-runtime 1.1.461 → 1.1.463

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 (64) hide show
  1. package/CHANGELOG.md +79 -0
  2. package/harness/pending-wait.ts +34 -14
  3. package/index.ts +63 -41
  4. package/package.json +1 -1
  5. package/packages/agent-policy/package.json +1 -1
  6. package/packages/auth/package.json +1 -1
  7. package/packages/autonomous-runtime/package.json +1 -1
  8. package/packages/checkpoint/package.json +1 -1
  9. package/packages/clipboard/package.json +1 -1
  10. package/packages/codex-watcher/package.json +1 -1
  11. package/packages/config-capture/package.json +1 -1
  12. package/packages/contracts/package.json +1 -1
  13. package/packages/cookie-sanitizer/package.json +1 -1
  14. package/packages/evaluation-engine/package.json +1 -1
  15. package/packages/event-bus/package.json +1 -1
  16. package/packages/event-store/package.json +1 -1
  17. package/packages/experience-replay/package.json +1 -1
  18. package/packages/file-copy-helper/package.json +1 -1
  19. package/packages/intent-analyzer/package.json +1 -1
  20. package/packages/jev-judge/dist/auto-continue.d.ts.map +1 -1
  21. package/packages/jev-judge/dist/auto-continue.js +40 -5
  22. package/packages/jev-judge/dist/auto-continue.js.map +1 -1
  23. package/packages/jev-judge/dist/decision-context.d.ts +211 -0
  24. package/packages/jev-judge/dist/decision-context.d.ts.map +1 -0
  25. package/packages/jev-judge/dist/decision-context.js +633 -0
  26. package/packages/jev-judge/dist/decision-context.js.map +1 -0
  27. package/packages/jev-judge/dist/index.d.ts +2 -0
  28. package/packages/jev-judge/dist/index.d.ts.map +1 -1
  29. package/packages/jev-judge/dist/index.js +1 -0
  30. package/packages/jev-judge/dist/index.js.map +1 -1
  31. package/packages/jev-judge/package.json +1 -1
  32. package/packages/jev-judge/src/auto-continue.ts +52 -5
  33. package/packages/jev-judge/src/decision-context.ts +900 -0
  34. package/packages/jev-judge/src/index.ts +20 -0
  35. package/packages/knowledge-retrieval/package.json +1 -1
  36. package/packages/learning-engine/package.json +1 -1
  37. package/packages/logging/package.json +1 -1
  38. package/packages/memory-engine/package.json +1 -1
  39. package/packages/notification/dist/pending-question.d.ts +4 -2
  40. package/packages/notification/dist/pending-question.d.ts.map +1 -1
  41. package/packages/notification/dist/pending-question.js +30 -15
  42. package/packages/notification/dist/pending-question.js.map +1 -1
  43. package/packages/notification/package.json +1 -1
  44. package/packages/notification/src/pending-question.ts +31 -15
  45. package/packages/paperclip-integration/package.json +1 -1
  46. package/packages/performance-optimizer/package.json +1 -1
  47. package/packages/privilege-broker/package.json +1 -1
  48. package/packages/prompt-compiler/package.json +1 -1
  49. package/packages/providers/package.json +1 -1
  50. package/packages/qdrant-skills/package.json +1 -1
  51. package/packages/quota-manager/package.json +1 -1
  52. package/packages/relay/package.json +1 -1
  53. package/packages/skill-mcp-client/package.json +1 -1
  54. package/packages/skills/package.json +1 -1
  55. package/packages/todo-bd-sync/package.json +1 -1
  56. package/packages/token-estimation/package.json +1 -1
  57. package/packages/tooling-preference/package.json +1 -1
  58. package/packages/trajectory/package.json +1 -1
  59. package/packages/tui/package.json +1 -1
  60. package/packages/two-phase-review/package.json +1 -1
  61. package/packages/types/package.json +1 -1
  62. package/packages/webmcp-tester/package.json +1 -1
  63. package/packages/wiki/package.json +1 -1
  64. package/packages/write-review/package.json +1 -1
@@ -0,0 +1,900 @@
1
+ /**
2
+ * The decision context of a choice question.
3
+ *
4
+ * A choice is only decidable when the evaluation sees what the alternatives
5
+ * MEAN. The detection layer extracts short labels ("implement A", "A+B"), and
6
+ * a label alone does not carry the meaning, the caveats or the boundaries of
7
+ * an option. This module is the single place where the runtime turns the
8
+ * source message into the facts of a decision.
9
+ *
10
+ * The rules of the module:
11
+ *
12
+ * - Structured facts supplied by the agent win over extracted ones.
13
+ * - Extracted text is verbatim: negation, dependencies and caveats are kept
14
+ * as they were written, never paraphrased into something weaker.
15
+ * - Nothing here decides: the module never selects an option and never
16
+ * invents an approval. Missing information is surfaced as an uncertainty
17
+ * so that a wait outcome stays possible.
18
+ * - Every bound is declared and every cut is reported, so a reader can tell
19
+ * what the evaluation did not see.
20
+ */
21
+
22
+ /** How many options reach the evaluation. */
23
+ export const MAX_CHOICE_OPTIONS = 10;
24
+ /** How much of the problem statement reaches the evaluation. */
25
+ export const MAX_PROBLEM_CHARS = 600;
26
+ /** How much of the question reaches the evaluation. */
27
+ export const MAX_CHOICE_QUESTION_CHARS = 600;
28
+ /** How much of one option description reaches the evaluation. */
29
+ export const MAX_OPTION_DESCRIPTION_CHARS = 600;
30
+ /** How many tradeoffs or constraints per option reach the evaluation. */
31
+ export const MAX_OPTION_FACTS = 6;
32
+ /** How much of one fact (a tradeoff, a constraint) reaches the evaluation. */
33
+ export const MAX_OPTION_FACT_CHARS = 400;
34
+ /** How much of the rendered excerpt reaches the evaluation. */
35
+ export const MAX_CHOICE_EXCERPT_CHARS = 2000;
36
+ /** How much of one criterion reaches the evaluation. */
37
+ export const MAX_OPTION_CRITERION_CHARS = 400;
38
+ /**
39
+ * How far into a paragraph a name of an option is looked for.
40
+ *
41
+ * A paragraph that names an option in its first line talks about that
42
+ * option; a paragraph that names it much later talks about something else.
43
+ */
44
+ export const MENTION_WINDOW_CHARS = 80;
45
+
46
+ /** One option of a choice, with the facts the evaluation needs. */
47
+ export interface ChoiceOptionFacts {
48
+ /** The stable id of the option: `option_1`, `option_2`, ... */
49
+ id: string;
50
+ /** The label the agent offered, unchanged. */
51
+ label: string;
52
+ /** What the option means, or an empty string when the source does not say. */
53
+ description: string;
54
+ /** What the option costs or changes. */
55
+ tradeoffs: string[];
56
+ /** What restricts the option, kept verbatim. */
57
+ constraints: string[];
58
+ }
59
+
60
+ /** The facts of a decision about a choice. */
61
+ export interface ChoiceDecisionContext {
62
+ /** The problem the choice is about. */
63
+ problem: string;
64
+ /** The question the agent asked. */
65
+ question: string;
66
+ /** The options, with stable ids. */
67
+ options: ChoiceOptionFacts[];
68
+ /** What is authorized, and what is not. */
69
+ authorization: {
70
+ approved: string[];
71
+ notEstablished: string[];
72
+ };
73
+ /** What could not be established from the source. */
74
+ uncertainties: string[];
75
+ /** The provenance of the facts and the completeness signal. */
76
+ source: {
77
+ /** How long the source message is. */
78
+ originalChars: number;
79
+ /** Whether a bound cut something away. */
80
+ truncated: boolean;
81
+ /** What the evaluation does not see. */
82
+ omittedInformation: string[];
83
+ /** Where the facts came from. */
84
+ derived: "structured" | "extracted" | "mixed";
85
+ /** Whether every option carries its meaning. */
86
+ complete: boolean;
87
+ };
88
+ }
89
+
90
+ /** One option as the agent supplied it. */
91
+ type StructuredOption = NonNullable<StructuredChoiceFacts["options"]>[number];
92
+
93
+ /** The facts the agent supplied itself. They win over extracted ones. */
94
+ export interface StructuredChoiceFacts {
95
+ /** The problem the choice is about. */
96
+ problem?: string;
97
+ /** The options, with their meaning. */
98
+ options?: Array<{
99
+ id?: string;
100
+ label?: string;
101
+ description?: string;
102
+ tradeoffs?: string[];
103
+ constraints?: string[];
104
+ }>;
105
+ /** What a human authorized, and what nobody authorized. */
106
+ authorization?: {
107
+ approved?: string[];
108
+ notEstablished?: string[];
109
+ };
110
+ /** What the agent itself could not establish. */
111
+ uncertainties?: string[];
112
+ }
113
+
114
+ /** The input of the helper. */
115
+ export interface ChoiceContextInput {
116
+ /** The question the agent asked. */
117
+ question: string;
118
+ /** The alternatives the detection layer extracted. */
119
+ alternatives: string[];
120
+ /** The complete assistant message the question was detected in. */
121
+ contextText?: string;
122
+ /** Facts supplied by the agent. */
123
+ structured?: StructuredChoiceFacts;
124
+ /**
125
+ * Whether the earlier turns of the conversation were available.
126
+ *
127
+ * The runtime usually has only the message the question was detected in.
128
+ * The difference between "the context is in this message" and "the
129
+ * context was in an earlier message" has to stay visible, so the default
130
+ * is "not supplied" and it is reported as missing.
131
+ */
132
+ history?: { available: boolean; note?: string };
133
+ }
134
+
135
+ /** The parts of an option that the extraction found in the source message. */
136
+ export interface ExtractedOption {
137
+ description: string;
138
+ tradeoffs: string[];
139
+ constraints: string[];
140
+ /** Whether the source stated what the option means. */
141
+ found: boolean;
142
+ /** The line of the header the facts were found at, -1 when there was none. */
143
+ headerIndex: number;
144
+ }
145
+
146
+ /** What the extraction needs to know about one option. */
147
+ export interface OptionExtractionInput {
148
+ /** The complete assistant message. */
149
+ source: string;
150
+ /** The tokens that can locate the header of the option. */
151
+ headerCandidates: string[];
152
+ /** The tokens that name the option in prose. */
153
+ mentionAnchors: string[];
154
+ /** The header candidates of the other options. */
155
+ otherHeaderCandidates: string[];
156
+ /** The mention anchors of the other options. */
157
+ otherMentionAnchors: string[];
158
+ /** The header lines that other options already own. */
159
+ claimed: Set<number>;
160
+ /** The question, so that the region ends where the question begins. */
161
+ question: string;
162
+ }
163
+
164
+ /** A paragraph of the source message. */
165
+ interface Paragraph {
166
+ text: string;
167
+ /** Where the paragraph starts in the source message. */
168
+ start: number;
169
+ }
170
+
171
+ /**
172
+ * Normalize a label for a comparison: case and spacing do not change what a
173
+ * label means, but a different label is a different option.
174
+ */
175
+ function normalizeLabel(label: string): string {
176
+ return label.trim().toLowerCase().replace(/\s+/g, " ");
177
+ }
178
+
179
+ /**
180
+ * The primary tokens of a label: the short uppercase ones.
181
+ *
182
+ * "implement A" has the primary "A", "A+B" has the primary "A+B".
183
+ */
184
+ export function derivePrimaryAnchors(label: string): string[] {
185
+ const tokens = label
186
+ .split(/\s+/)
187
+ .map((token) => token.replace(/^[^\w+]+/, "").replace(/[^\w+]+$/, ""))
188
+ .filter((token) => token.length > 0);
189
+ if (tokens.length === 0) return [];
190
+
191
+ const upper = tokens.filter(
192
+ (token) =>
193
+ /^[A-Z0-9+]{1,6}$/.test(token) &&
194
+ /[A-Z0-9]/.test(token) &&
195
+ token !== token.toLowerCase(),
196
+ );
197
+ if (upper.length === 0) {
198
+ return [tokens[tokens.length - 1] as string];
199
+ }
200
+ return upper;
201
+ }
202
+
203
+ /**
204
+ * The primary anchor of an option: the token that names it.
205
+ */
206
+ export function deriveOptionAnchor(label: string): string {
207
+ return derivePrimaryAnchors(label)[0] ?? "";
208
+ }
209
+
210
+ /**
211
+ * The tokens that can name an option in the source message.
212
+ *
213
+ * A combination like "A+B" also names its parts, because the message writes
214
+ * the second part as its own header ("**B. ...**").
215
+ */
216
+ export function deriveOptionAnchors(label: string): string[] {
217
+ const anchors: string[] = [];
218
+ for (const token of derivePrimaryAnchors(label)) {
219
+ if (!anchors.includes(token)) anchors.push(token);
220
+ for (const part of token.split("+")) {
221
+ if (part.length > 0 && !anchors.includes(part)) anchors.push(part);
222
+ }
223
+ }
224
+ return anchors;
225
+ }
226
+
227
+ /**
228
+ * The tokens that name an option in prose.
229
+ *
230
+ * A part of a combination is dropped when it is the primary token of
231
+ * another option: in "implement A" against "A+B", the "A" belongs to the
232
+ * first option, and the second option is named by "A+B" and "B".
233
+ *
234
+ * A token that does not look like an identifier ("so" in "make it so") never
235
+ * becomes a mention anchor: a common word would make every paragraph that
236
+ * contains it a fact of the option.
237
+ */
238
+ function deriveMentionAnchors(
239
+ primaries: string[],
240
+ otherPrimaries: string[],
241
+ ): string[] {
242
+ const anchors: string[] = [];
243
+ for (const token of primaries) {
244
+ if (!isIdentifierToken(token)) continue;
245
+ if (!anchors.includes(token)) anchors.push(token);
246
+ for (const part of token.split("+")) {
247
+ if (part.length === 0) continue;
248
+ if (!isIdentifierToken(part)) continue;
249
+ if (otherPrimaries.includes(part)) continue;
250
+ if (!anchors.includes(part)) anchors.push(part);
251
+ }
252
+ }
253
+ return anchors;
254
+ }
255
+
256
+ /**
257
+ * Whether a token names something: it carries a capital letter or a digit.
258
+ */
259
+ function isIdentifierToken(token: string): boolean {
260
+ return /[A-Z0-9]/.test(token) && token !== token.toLowerCase();
261
+ }
262
+
263
+ /**
264
+ * Split the source message into paragraphs.
265
+ *
266
+ * A paragraph is a block of text separated by an empty line. The position of
267
+ * every paragraph is kept, so a fact can be pointed at.
268
+ */
269
+ function splitParagraphs(source: string): Paragraph[] {
270
+ const paragraphs: Paragraph[] = [];
271
+ const pattern = /\S[\s\S]*?(?=\n\s*\n|$)/g;
272
+ let match: RegExpExecArray | null;
273
+ while ((match = pattern.exec(source)) !== null) {
274
+ const text = match[0].trim();
275
+ if (text.length > 0) {
276
+ paragraphs.push({ text, start: match.index });
277
+ }
278
+ }
279
+ return paragraphs;
280
+ }
281
+
282
+ /** The characters that end the anchor of an option header. */
283
+ const HEADER_SEPARATORS = [".", ":", ")", "-", "–", "—"];
284
+
285
+ function isWordCharacter(character: string): boolean {
286
+ return /[A-Za-z0-9]/.test(character);
287
+ }
288
+
289
+ /**
290
+ * Whether a line is the header of an option: the line starts with the
291
+ * anchor, followed by a separator.
292
+ *
293
+ * The anchor comes from the text of the agent, so the check is a string
294
+ * comparison and never a pattern built from that text.
295
+ */
296
+ function isOptionHeader(line: string, anchor: string): boolean {
297
+ if (anchor.length === 0) return false;
298
+ const stripped = line.replace(/^\s*(?:[-*+]\s+)?(?:\*\*|__)?\s*/, "");
299
+ if (!stripped.startsWith(anchor)) return false;
300
+ const next = stripped.charAt(anchor.length);
301
+ if (next === "") return true;
302
+ if (isWordCharacter(next)) return false;
303
+ return HEADER_SEPARATORS.includes(next);
304
+ }
305
+
306
+ /** Whether a line mentions the anchor as a word. */
307
+ function mentionsAnchor(line: string, anchor: string): boolean {
308
+ if (anchor.length === 0) return false;
309
+ let from = 0;
310
+ for (;;) {
311
+ const index = line.indexOf(anchor, from);
312
+ if (index === -1) return false;
313
+ const before = index > 0 ? line.charAt(index - 1) : "";
314
+ const after = line.charAt(index + anchor.length);
315
+ if (
316
+ (before === "" || !isWordCharacter(before)) &&
317
+ (after === "" || !isWordCharacter(after))
318
+ ) {
319
+ return true;
320
+ }
321
+ from = index + 1;
322
+ }
323
+ }
324
+
325
+ /** Strip the markdown markers of a heading or a bold label. */
326
+ function stripMarkdown(value: string): string {
327
+ return value
328
+ .replace(/^\s*(?:[-*+]\s+)+/, "")
329
+ .replace(/(\*\*|__|`)/g, "")
330
+ .trim();
331
+ }
332
+
333
+ /**
334
+ * Remove the anchor of an option from the beginning of its description, so
335
+ * the description starts with the meaning and not with the label.
336
+ */
337
+ function stripLeadingAnchor(text: string, anchor: string): string {
338
+ const stripped = text.replace(/^\s*(?:\*\*|__)?\s*/, "");
339
+ if (anchor.length === 0 || !stripped.startsWith(anchor)) return stripped;
340
+ const next = stripped.charAt(anchor.length);
341
+ if (next !== "" && isWordCharacter(next)) return stripped;
342
+ return stripped.slice(anchor.length).replace(/^[.:)\-–—\s]+/, "").trim();
343
+ }
344
+
345
+ /**
346
+ * A paragraph states a restriction when it names a duty, a prohibition or a
347
+ * condition. The markers are conservative: a paragraph that is not
348
+ * recognized is a consequence, not a restriction.
349
+ */
350
+ function statesConstraint(paragraph: string): boolean {
351
+ return (
352
+ /^\s*(caveat|caveats?|careful|note|warning|constraint|constraints?|however|but|instead|only if|never|must|do not|don't|cannot|can't)\b/i.test(
353
+ paragraph,
354
+ ) ||
355
+ /\b(must|never|cannot|can not|only if|is required to|has to|not just)\b/i.test(
356
+ paragraph,
357
+ )
358
+ );
359
+ }
360
+
361
+ /**
362
+ * Whether a text mentions an anchor as a word.
363
+ */
364
+ function mentionsAny(text: string, anchors: string[]): boolean {
365
+ return anchors.some((anchor) => mentionsAnchor(text, anchor));
366
+ }
367
+
368
+ /**
369
+ * Whether a paragraph is a fact of one option.
370
+ *
371
+ * The paragraph has to name the option near its beginning, and it must not
372
+ * name another option there: a paragraph about two options says something
373
+ * about both, and it belongs to neither of them alone.
374
+ */
375
+ function belongsToOption(
376
+ text: string,
377
+ ownAnchors: string[],
378
+ otherAnchors: string[],
379
+ ): boolean {
380
+ const window = text.slice(0, MENTION_WINDOW_CHARS);
381
+ if (!mentionsAny(window, ownAnchors)) return false;
382
+ return !mentionsAny(window, otherAnchors);
383
+ }
384
+
385
+ /**
386
+ * The line of the header of an option.
387
+ *
388
+ * The candidates are tried in order, and a header that another option
389
+ * already claims is skipped: the label "A+B" must not land on the header of
390
+ * the option "A".
391
+ */
392
+ function locateHeader(
393
+ lines: string[],
394
+ candidates: string[],
395
+ claimed: Set<number>,
396
+ ): number {
397
+ for (const candidate of candidates) {
398
+ for (let index = 0; index < lines.length; index += 1) {
399
+ if (claimed.has(index)) continue;
400
+ if (isOptionHeader(lines[index] as string, candidate)) return index;
401
+ }
402
+ }
403
+ return -1;
404
+ }
405
+
406
+ /**
407
+ * Extract the facts of one option from the source message.
408
+ *
409
+ * The extraction is anchored on the option header, not on the beginning of
410
+ * the message: a decisive caveat that stands behind the two thousandth
411
+ * character of the message is as much a part of the option as the sentence
412
+ * in front of it.
413
+ *
414
+ * A paragraph belongs to an option when it names that option and no other.
415
+ * A paragraph that names two options says something about both, and it is
416
+ * left out instead of being filed under one of them.
417
+ */
418
+ export function extractOptionFacts(
419
+ input: OptionExtractionInput,
420
+ ): ExtractedOption {
421
+ const {
422
+ source,
423
+ headerCandidates,
424
+ mentionAnchors,
425
+ otherHeaderCandidates,
426
+ otherMentionAnchors,
427
+ claimed,
428
+ question,
429
+ } = input;
430
+ const empty: ExtractedOption = {
431
+ description: "",
432
+ tradeoffs: [],
433
+ constraints: [],
434
+ found: false,
435
+ headerIndex: -1,
436
+ };
437
+ if (headerCandidates.length === 0 || source.length === 0) return empty;
438
+
439
+ const lines = source.split("\n");
440
+ const headerIndex = locateHeader(lines, headerCandidates, claimed);
441
+
442
+ const paragraphs = splitParagraphs(source);
443
+ let description = "";
444
+ let region: Paragraph[] = [];
445
+
446
+ if (headerIndex >= 0) {
447
+ // The region of the option ends at the next option header, at the
448
+ // next heading of the message, or at the question itself.
449
+ const regionLines: string[] = [];
450
+ const questionMarker = question.trim().slice(0, 40);
451
+ for (let index = headerIndex; index < lines.length; index += 1) {
452
+ const line = lines[index] as string;
453
+ if (index > headerIndex) {
454
+ if (/^\s*#{1,6}\s/.test(line)) break;
455
+ if (questionMarker.length > 0 && line.includes(questionMarker)) break;
456
+ if (
457
+ otherHeaderCandidates.some((other) =>
458
+ isOptionHeader(line, other),
459
+ )
460
+ ) {
461
+ break;
462
+ }
463
+ }
464
+ regionLines.push(line);
465
+ }
466
+ region = splitParagraphs(regionLines.join("\n"));
467
+ if (region.length > 0) {
468
+ const anchor =
469
+ headerCandidates.find((candidate) =>
470
+ isOptionHeader(lines[headerIndex] as string, candidate),
471
+ ) ?? (headerCandidates[0] as string);
472
+ description = stripMarkdown(
473
+ stripLeadingAnchor((region[0] as Paragraph).text, anchor),
474
+ );
475
+ }
476
+ } else {
477
+ // No header: the first paragraph that names the option and no other
478
+ // one carries its meaning.
479
+ const own = region;
480
+ const candidate = paragraphs.find((paragraph) =>
481
+ belongsToOption(
482
+ paragraph.text,
483
+ mentionAnchors,
484
+ otherMentionAnchors,
485
+ ),
486
+ );
487
+ if (candidate) {
488
+ const anchor =
489
+ mentionAnchors.find((token) =>
490
+ mentionsAnchor(candidate.text.slice(0, MENTION_WINDOW_CHARS), token),
491
+ ) ?? (mentionAnchors[0] as string);
492
+ description = stripMarkdown(stripLeadingAnchor(candidate.text, anchor));
493
+ region = own;
494
+ }
495
+ }
496
+
497
+ const tradeoffs: string[] = [];
498
+ const constraints: string[] = [];
499
+ const addFact = (text: string): void => {
500
+ const value = stripMarkdown(text);
501
+ if (value.length === 0) return;
502
+ if (!belongsToOption(value, mentionAnchors, otherMentionAnchors)) return;
503
+ if (statesConstraint(value)) {
504
+ if (!constraints.includes(value)) constraints.push(value);
505
+ } else if (!tradeoffs.includes(value)) {
506
+ tradeoffs.push(value);
507
+ }
508
+ };
509
+
510
+ // The paragraphs of the region after the description.
511
+ for (const paragraph of region.slice(1)) {
512
+ addFact(paragraph.text);
513
+ }
514
+
515
+ // A caveat that names the option belongs to the option, even when it
516
+ // stands outside the region: "Caveat for B: ..." is about B.
517
+ const regionStart = region[0]?.start ?? Number.MAX_SAFE_INTEGER;
518
+ for (const paragraph of paragraphs) {
519
+ if (paragraph.start <= regionStart) continue;
520
+ addFact(paragraph.text);
521
+ }
522
+
523
+ return {
524
+ description,
525
+ tradeoffs,
526
+ constraints,
527
+ found: description.length > 0,
528
+ headerIndex,
529
+ };
530
+ }
531
+
532
+ /**
533
+ * The paragraph of the source message that stands directly before the
534
+ * question: it states the problem the question is about.
535
+ */
536
+ function extractProblem(source: string, question: string): string {
537
+ if (source.length === 0) return "";
538
+ const questionIndex = question.length > 0 ? source.indexOf(question) : -1;
539
+ if (questionIndex > 0) {
540
+ const before = source.slice(0, questionIndex);
541
+ const paragraphs = splitParagraphs(before);
542
+ const last = paragraphs[paragraphs.length - 1];
543
+ if (last) return stripMarkdown(last.text);
544
+ }
545
+ const paragraphs = splitParagraphs(source);
546
+ const first = paragraphs[0];
547
+ return first ? stripMarkdown(first.text) : "";
548
+ }
549
+
550
+ /**
551
+ * Build the decision context of a choice question.
552
+ *
553
+ * The function never decides and never authorizes: it prepares the facts
554
+ * that a decision is made of, and it names what it could not establish.
555
+ */
556
+ export function buildChoiceDecisionContext(
557
+ input: ChoiceContextInput,
558
+ ): ChoiceDecisionContext {
559
+ const omitted: string[] = [];
560
+ const uncertainties: string[] = [];
561
+ const structured = input.structured ?? {};
562
+ const structuredOptions = Array.isArray(structured.options)
563
+ ? structured.options
564
+ : [];
565
+
566
+ // The question itself.
567
+ let question = input.question.trim();
568
+ if (question.length > MAX_CHOICE_QUESTION_CHARS) {
569
+ question = question.slice(0, MAX_CHOICE_QUESTION_CHARS);
570
+ omitted.push(
571
+ `the question was cut at ${MAX_CHOICE_QUESTION_CHARS} characters`,
572
+ );
573
+ }
574
+
575
+ // The alternatives, with their stable ids.
576
+ const allAlternatives = input.alternatives.filter(
577
+ (alternative) => alternative.trim().length > 0,
578
+ );
579
+ const alternatives = allAlternatives.slice(0, MAX_CHOICE_OPTIONS);
580
+ if (allAlternatives.length > alternatives.length) {
581
+ omitted.push(
582
+ `${allAlternatives.length - alternatives.length} alternative(s) beyond the limit of ${MAX_CHOICE_OPTIONS} did not reach the evaluation`,
583
+ );
584
+ }
585
+
586
+ const source = input.contextText ?? "";
587
+ const primarySets = alternatives.map((alternative) =>
588
+ derivePrimaryAnchors(alternative),
589
+ );
590
+ const headerSets = alternatives.map((alternative) =>
591
+ deriveOptionAnchors(alternative),
592
+ );
593
+ // The mention anchors of every option: a part of a combination belongs
594
+ // to the option that names it and to no other.
595
+ const mentionSets = primarySets.map((primaries) =>
596
+ deriveMentionAnchors(
597
+ primaries,
598
+ primarySets
599
+ .flat()
600
+ .filter((token) => !primaries.includes(token)),
601
+ ),
602
+ );
603
+ const structuredByLabel = new Map<string, StructuredOption>();
604
+ for (const option of structuredOptions) {
605
+ if (typeof option?.label !== "string") continue;
606
+ structuredByLabel.set(normalizeLabel(option.label), option);
607
+ }
608
+
609
+ const options: ChoiceOptionFacts[] = [];
610
+ const claimed = new Set<number>();
611
+ let derivedFromStructured = 0;
612
+ let derivedFromMessage = 0;
613
+ let missingMeaning = false;
614
+
615
+ const readFacts = (
616
+ values: unknown,
617
+ fallback: string[],
618
+ ): { facts: string[]; cut: boolean } => {
619
+ const list = Array.isArray(values)
620
+ ? values.filter(
621
+ (value): value is string =>
622
+ typeof value === "string" && value.trim().length > 0,
623
+ )
624
+ : fallback;
625
+ const facts = list.slice(0, MAX_OPTION_FACTS).map((fact) => {
626
+ const trimmed = fact.trim();
627
+ return trimmed.length > MAX_OPTION_FACT_CHARS
628
+ ? trimmed.slice(0, MAX_OPTION_FACT_CHARS)
629
+ : trimmed;
630
+ });
631
+ return { facts, cut: list.length > MAX_OPTION_FACTS };
632
+ };
633
+
634
+ for (const [index, alternative] of alternatives.entries()) {
635
+ const id = `option_${index + 1}`;
636
+ const label = alternative.trim();
637
+ const headerCandidates = headerSets[index] ?? [];
638
+ const mentionAnchors = mentionSets[index] ?? [];
639
+ const otherHeaderCandidates = headerSets
640
+ .flat()
641
+ .filter((candidate) => !headerCandidates.includes(candidate));
642
+ const otherMentionAnchors = mentionSets
643
+ .flat()
644
+ .filter((anchor) => !mentionAnchors.includes(anchor));
645
+
646
+ // A labelled fact belongs to its label. The positional fallback is
647
+ // only for a supplied option that carries no label at all.
648
+ const labelled = structuredByLabel.get(normalizeLabel(label));
649
+ const unlabelled =
650
+ structuredOptions.length === alternatives.length
651
+ ? structuredOptions[index]
652
+ : undefined;
653
+ const supplied =
654
+ labelled ??
655
+ (unlabelled && typeof unlabelled.label !== "string"
656
+ ? unlabelled
657
+ : undefined);
658
+
659
+ const suppliedDescription =
660
+ supplied && typeof supplied.description === "string"
661
+ ? supplied.description.trim()
662
+ : "";
663
+ if (supplied && supplied.description !== undefined && !suppliedDescription) {
664
+ uncertainties.push(
665
+ `${id} (${label}): the supplied description is empty or malformed, the message was used instead`,
666
+ );
667
+ }
668
+
669
+ const extracted =
670
+ suppliedDescription.length > 0
671
+ ? null
672
+ : extractOptionFacts({
673
+ source,
674
+ headerCandidates,
675
+ mentionAnchors,
676
+ otherHeaderCandidates,
677
+ otherMentionAnchors,
678
+ claimed,
679
+ question: input.question,
680
+ });
681
+ if (extracted && extracted.headerIndex >= 0) {
682
+ claimed.add(extracted.headerIndex);
683
+ }
684
+
685
+ let description =
686
+ suppliedDescription.length > 0
687
+ ? suppliedDescription
688
+ : (extracted?.description ?? "");
689
+ if (description.length > MAX_OPTION_DESCRIPTION_CHARS) {
690
+ description = description.slice(0, MAX_OPTION_DESCRIPTION_CHARS);
691
+ omitted.push(
692
+ `${id} (${label}): the description was cut at ${MAX_OPTION_DESCRIPTION_CHARS} characters`,
693
+ );
694
+ }
695
+
696
+ const tradeoffsResult = readFacts(
697
+ supplied?.tradeoffs,
698
+ extracted?.tradeoffs ?? [],
699
+ );
700
+ const constraintsResult = readFacts(
701
+ supplied?.constraints,
702
+ extracted?.constraints ?? [],
703
+ );
704
+ if (tradeoffsResult.cut || constraintsResult.cut) {
705
+ omitted.push(
706
+ `${id} (${label}): facts beyond the limit of ${MAX_OPTION_FACTS} did not reach the evaluation`,
707
+ );
708
+ }
709
+ if (
710
+ tradeoffsResult.facts.some(
711
+ (fact) => fact.length === MAX_OPTION_FACT_CHARS,
712
+ ) ||
713
+ constraintsResult.facts.some(
714
+ (fact) => fact.length === MAX_OPTION_FACT_CHARS,
715
+ )
716
+ ) {
717
+ omitted.push(
718
+ `${id} (${label}): a fact was cut at ${MAX_OPTION_FACT_CHARS} characters`,
719
+ );
720
+ }
721
+
722
+ if (suppliedDescription.length > 0) {
723
+ derivedFromStructured += 1;
724
+ } else if (extracted?.found) {
725
+ derivedFromMessage += 1;
726
+ } else {
727
+ missingMeaning = true;
728
+ uncertainties.push(
729
+ `${id} (${label}): the source does not state what this option means`,
730
+ );
731
+ }
732
+
733
+ options.push({
734
+ id:
735
+ supplied?.id && typeof supplied.id === "string" && supplied.id.trim().length > 0
736
+ ? supplied.id
737
+ : id,
738
+ label,
739
+ description,
740
+ tradeoffs: tradeoffsResult.facts,
741
+ constraints: constraintsResult.facts,
742
+ });
743
+ }
744
+
745
+ // The problem.
746
+ let problem =
747
+ typeof structured.problem === "string" ? structured.problem.trim() : "";
748
+ if (problem.length === 0) {
749
+ problem = extractProblem(source, input.question);
750
+ }
751
+ if (problem.length > MAX_PROBLEM_CHARS) {
752
+ problem = problem.slice(0, MAX_PROBLEM_CHARS);
753
+ omitted.push(`the problem was cut at ${MAX_PROBLEM_CHARS} characters`);
754
+ }
755
+ if (problem.length === 0) {
756
+ uncertainties.push(
757
+ "the source does not state the problem the choice is about",
758
+ );
759
+ }
760
+
761
+ // The authorization. Only supplied facts establish an authorization:
762
+ // the message of the agent is not a human answer.
763
+ const approved = Array.isArray(structured.authorization?.approved)
764
+ ? structured.authorization.approved.filter(
765
+ (value): value is string => typeof value === "string",
766
+ )
767
+ : [];
768
+ const notEstablished = Array.isArray(structured.authorization?.notEstablished)
769
+ ? structured.authorization.notEstablished.filter(
770
+ (value): value is string => typeof value === "string",
771
+ )
772
+ : [];
773
+ if (!structured.authorization) {
774
+ notEstablished.push(
775
+ "no human selection between the alternatives is recorded in this evaluation input",
776
+ );
777
+ if (/\bapproved\b/i.test(source)) {
778
+ notEstablished.push(
779
+ "the source reports an approval of an earlier action; it does not establish a selection between the alternatives",
780
+ );
781
+ }
782
+ }
783
+
784
+ // The uncertainties the agent reported itself.
785
+ if (Array.isArray(structured.uncertainties)) {
786
+ for (const uncertainty of structured.uncertainties) {
787
+ if (typeof uncertainty === "string" && uncertainty.trim().length > 0) {
788
+ uncertainties.push(uncertainty.trim());
789
+ }
790
+ }
791
+ }
792
+
793
+ // The earlier turns of the conversation. Their absence stays visible.
794
+ if (input.history && input.history.available === true) {
795
+ if (input.history.note) {
796
+ omitted.push(input.history.note);
797
+ }
798
+ } else {
799
+ const note =
800
+ input.history?.note ??
801
+ "the earlier turns of the conversation were not supplied";
802
+ uncertainties.push(note);
803
+ omitted.push(note);
804
+ }
805
+
806
+ const derived =
807
+ derivedFromStructured > 0 && derivedFromMessage > 0
808
+ ? "mixed"
809
+ : derivedFromStructured > 0
810
+ ? "structured"
811
+ : "extracted";
812
+
813
+ return {
814
+ problem,
815
+ question,
816
+ options,
817
+ authorization: { approved, notEstablished },
818
+ uncertainties,
819
+ source: {
820
+ originalChars: source.length,
821
+ truncated: omitted.length > 0,
822
+ omittedInformation: omitted,
823
+ derived,
824
+ complete: !missingMeaning,
825
+ },
826
+ };
827
+ }
828
+
829
+ /**
830
+ * The criterion text of one option: the label, the meaning and the
831
+ * constraints that restrict it.
832
+ *
833
+ * The label alone does not tell the evaluation what the option does, so the
834
+ * meaning travels with it. The constraint is part of the criterion because
835
+ * an option whose restriction is invisible is an option the evaluation
836
+ * cannot judge correctly.
837
+ */
838
+ export function describeChoiceOption(
839
+ id: string,
840
+ label: string,
841
+ description: string,
842
+ constraints: string[],
843
+ ): string {
844
+ const meaning =
845
+ description.length > 0
846
+ ? description
847
+ : "the source does not state what this option means";
848
+ const parts = [`${id} (${label}): ${meaning}`];
849
+ if (constraints.length > 0) {
850
+ parts.push(`constraints: ${constraints.join(" ")}`);
851
+ }
852
+ return parts.join(" - ").slice(0, MAX_OPTION_CRITERION_CHARS);
853
+ }
854
+
855
+ /**
856
+ * The bounded text of a choice that reaches the evaluation.
857
+ *
858
+ * The excerpt carries the facts, not the beginning of the message: the
859
+ * relevant sentence of a long message stands behind the two thousandth
860
+ * character far more often than the first one does.
861
+ */
862
+ export function renderChoiceExcerpt(context: ChoiceDecisionContext): string {
863
+ const lines: string[] = [];
864
+ lines.push(`Question: ${context.question}`);
865
+ for (const option of context.options) {
866
+ lines.push(
867
+ `${option.id} (${option.label}): ${
868
+ option.description || "the source does not state what this option means"
869
+ }`,
870
+ );
871
+ // The constraints come first: a restriction is the fact that decides
872
+ // the option, and it must not be pushed out by the consequences.
873
+ for (const constraint of option.constraints) {
874
+ lines.push(` - constraint: ${constraint}`);
875
+ }
876
+ for (const tradeoff of option.tradeoffs) {
877
+ lines.push(` - consequence: ${tradeoff}`);
878
+ }
879
+ }
880
+ if (context.problem.length > 0) {
881
+ lines.push(`Problem: ${context.problem}`);
882
+ }
883
+ if (context.authorization.approved.length > 0) {
884
+ lines.push(
885
+ `Authorized: ${context.authorization.approved.join("; ")}`,
886
+ );
887
+ }
888
+ for (const entry of context.authorization.notEstablished) {
889
+ lines.push(`Not authorized: ${entry}`);
890
+ }
891
+ for (const uncertainty of context.uncertainties) {
892
+ lines.push(`Uncertain: ${uncertainty}`);
893
+ }
894
+ if (context.source.omittedInformation.length > 0) {
895
+ lines.push(
896
+ `Not in the evaluation input: ${context.source.omittedInformation.join("; ")}`,
897
+ );
898
+ }
899
+ return lines.join("\n").slice(0, MAX_CHOICE_EXCERPT_CHARS);
900
+ }