pi-harness-runtime 1.1.462 → 1.1.464

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