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,755 @@
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
+ /** How many options reach the evaluation. */
22
+ export const MAX_CHOICE_OPTIONS = 10;
23
+ /** How much of the problem statement reaches the evaluation. */
24
+ export const MAX_PROBLEM_CHARS = 600;
25
+ /** How much of the question reaches the evaluation. */
26
+ export const MAX_CHOICE_QUESTION_CHARS = 600;
27
+ /** How much of one option description reaches the evaluation. */
28
+ export const MAX_OPTION_DESCRIPTION_CHARS = 600;
29
+ /** How many tradeoffs or constraints per option reach the evaluation. */
30
+ export const MAX_OPTION_FACTS = 6;
31
+ /** How much of one fact (a tradeoff, a constraint) reaches the evaluation. */
32
+ export const MAX_OPTION_FACT_CHARS = 400;
33
+ /** How much of the rendered excerpt reaches the evaluation. */
34
+ export const MAX_CHOICE_EXCERPT_CHARS = 2000;
35
+ /** How much of one criterion reaches the evaluation. */
36
+ export const MAX_OPTION_CRITERION_CHARS = 400;
37
+ /**
38
+ * How far into a paragraph a name of an option is looked for.
39
+ *
40
+ * A paragraph that names an option in its first line talks about that
41
+ * option; a paragraph that names it much later talks about something else.
42
+ */
43
+ export const MENTION_WINDOW_CHARS = 80;
44
+ /**
45
+ * Normalize a label for a comparison: case and spacing do not change what a
46
+ * label means, but a different label is a different option.
47
+ */
48
+ function normalizeLabel(label) {
49
+ return label.trim().toLowerCase().replace(/\s+/g, " ");
50
+ }
51
+ /**
52
+ * The primary tokens of a label: the short uppercase ones.
53
+ *
54
+ * "implement A" has the primary "A", "A+B" has the primary "A+B".
55
+ */
56
+ export function derivePrimaryAnchors(label) {
57
+ const tokens = label
58
+ .split(/\s+/)
59
+ .map((token) => token.replace(/^[^\w+]+/, "").replace(/[^\w+]+$/, ""))
60
+ .filter((token) => token.length > 0);
61
+ if (tokens.length === 0)
62
+ return [];
63
+ const upper = tokens.filter((token) => /^[A-Z0-9+]{1,6}$/.test(token) &&
64
+ /[A-Z0-9]/.test(token) &&
65
+ token !== token.toLowerCase());
66
+ if (upper.length === 0) {
67
+ return [tokens[tokens.length - 1]];
68
+ }
69
+ return upper;
70
+ }
71
+ /**
72
+ * The primary anchor of an option: the token that names it.
73
+ */
74
+ export function deriveOptionAnchor(label) {
75
+ return derivePrimaryAnchors(label)[0] ?? "";
76
+ }
77
+ /**
78
+ * The tokens that can name an option in the source message.
79
+ *
80
+ * A combination like "A+B" also names its parts, because the message writes
81
+ * the second part as its own header ("**B. ...**").
82
+ */
83
+ export function deriveOptionAnchors(label) {
84
+ const anchors = [];
85
+ for (const token of derivePrimaryAnchors(label)) {
86
+ if (!anchors.includes(token))
87
+ anchors.push(token);
88
+ for (const part of token.split("+")) {
89
+ if (part.length > 0 && !anchors.includes(part))
90
+ anchors.push(part);
91
+ }
92
+ }
93
+ return anchors;
94
+ }
95
+ /**
96
+ * The tokens that name an option in prose.
97
+ *
98
+ * A part of a combination is dropped when it is the primary token of
99
+ * another option: in "implement A" against "A+B", the "A" belongs to the
100
+ * first option, and the second option is named by "A+B" and "B".
101
+ *
102
+ * A token that does not look like an identifier ("so" in "make it so") never
103
+ * becomes a mention anchor: a common word would make every paragraph that
104
+ * contains it a fact of the option.
105
+ */
106
+ function deriveMentionAnchors(primaries, otherPrimaries) {
107
+ const anchors = [];
108
+ for (const token of primaries) {
109
+ if (!isIdentifierToken(token))
110
+ continue;
111
+ if (!anchors.includes(token))
112
+ anchors.push(token);
113
+ for (const part of token.split("+")) {
114
+ if (part.length === 0)
115
+ continue;
116
+ if (!isIdentifierToken(part))
117
+ continue;
118
+ if (otherPrimaries.includes(part))
119
+ continue;
120
+ if (!anchors.includes(part))
121
+ anchors.push(part);
122
+ }
123
+ }
124
+ return anchors;
125
+ }
126
+ /**
127
+ * Whether a token names something: it carries a capital letter or a digit.
128
+ */
129
+ function isIdentifierToken(token) {
130
+ return /[A-Z0-9]/.test(token) && token !== token.toLowerCase();
131
+ }
132
+ /**
133
+ * Split the source message into paragraphs.
134
+ *
135
+ * A paragraph is a block of text separated by an empty line. The position of
136
+ * every paragraph is kept, so a fact can be pointed at.
137
+ */
138
+ function splitParagraphs(source) {
139
+ const paragraphs = [];
140
+ const pattern = /\S[\s\S]*?(?=\n\s*\n|$)/g;
141
+ let match;
142
+ while ((match = pattern.exec(source)) !== null) {
143
+ const text = match[0].trim();
144
+ if (text.length > 0) {
145
+ paragraphs.push({ text, start: match.index });
146
+ }
147
+ }
148
+ return paragraphs;
149
+ }
150
+ /** The characters that end the anchor of an option header. */
151
+ const HEADER_SEPARATORS = [".", ":", ")", "-", "–", "—"];
152
+ function isWordCharacter(character) {
153
+ return /[A-Za-z0-9]/.test(character);
154
+ }
155
+ /**
156
+ * Whether a line is the header of an option: the line starts with the
157
+ * anchor, followed by a separator.
158
+ *
159
+ * The anchor comes from the text of the agent, so the check is a string
160
+ * comparison and never a pattern built from that text.
161
+ */
162
+ function isOptionHeader(line, anchor) {
163
+ if (anchor.length === 0)
164
+ return false;
165
+ const stripped = line.replace(/^\s*(?:[-*+]\s+)?(?:\*\*|__)?\s*/, "");
166
+ if (!stripped.startsWith(anchor))
167
+ return false;
168
+ const next = stripped.charAt(anchor.length);
169
+ if (next === "")
170
+ return true;
171
+ if (isWordCharacter(next))
172
+ return false;
173
+ return HEADER_SEPARATORS.includes(next);
174
+ }
175
+ /** Whether a line mentions the anchor as a word. */
176
+ function mentionsAnchor(line, anchor) {
177
+ if (anchor.length === 0)
178
+ return false;
179
+ let from = 0;
180
+ for (;;) {
181
+ const index = line.indexOf(anchor, from);
182
+ if (index === -1)
183
+ return false;
184
+ const before = index > 0 ? line.charAt(index - 1) : "";
185
+ const after = line.charAt(index + anchor.length);
186
+ if ((before === "" || !isWordCharacter(before)) &&
187
+ (after === "" || !isWordCharacter(after))) {
188
+ return true;
189
+ }
190
+ from = index + 1;
191
+ }
192
+ }
193
+ /** Strip the markdown markers of a heading or a bold label. */
194
+ function stripMarkdown(value) {
195
+ return value
196
+ .replace(/^\s*(?:[-*+]\s+)+/, "")
197
+ .replace(/(\*\*|__|`)/g, "")
198
+ .trim();
199
+ }
200
+ /**
201
+ * Remove the anchor of an option from the beginning of its description, so
202
+ * the description starts with the meaning and not with the label.
203
+ */
204
+ function stripLeadingAnchor(text, anchor) {
205
+ const stripped = text.replace(/^\s*(?:\*\*|__)?\s*/, "");
206
+ if (anchor.length === 0 || !stripped.startsWith(anchor))
207
+ return stripped;
208
+ const next = stripped.charAt(anchor.length);
209
+ if (next !== "" && isWordCharacter(next))
210
+ return stripped;
211
+ return stripped.slice(anchor.length).replace(/^[.:)\-–—\s]+/, "").trim();
212
+ }
213
+ /**
214
+ * A paragraph states a restriction when it names a duty, a prohibition or a
215
+ * condition. The markers are conservative: a paragraph that is not
216
+ * recognized is a consequence, not a restriction.
217
+ */
218
+ function statesConstraint(paragraph) {
219
+ return (/^\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(paragraph) ||
220
+ /\b(must|never|cannot|can not|only if|is required to|has to|not just)\b/i.test(paragraph));
221
+ }
222
+ /**
223
+ * Whether a text mentions an anchor as a word.
224
+ */
225
+ function mentionsAny(text, anchors) {
226
+ return anchors.some((anchor) => mentionsAnchor(text, anchor));
227
+ }
228
+ /**
229
+ * The offset of a line in the source message.
230
+ */
231
+ function lineOffset(lines, index) {
232
+ let offset = 0;
233
+ for (let position = 0; position < index; position += 1) {
234
+ offset += lines[position].length + 1;
235
+ }
236
+ return offset;
237
+ }
238
+ /**
239
+ * Whether a paragraph is a fact of one option.
240
+ *
241
+ * The paragraph has to name the option near its beginning, and it must not
242
+ * name another option there: a paragraph about two options says something
243
+ * about both, and it belongs to neither of them alone.
244
+ */
245
+ function belongsToOption(text, ownAnchors, otherAnchors) {
246
+ const window = text.slice(0, MENTION_WINDOW_CHARS);
247
+ if (!mentionsAny(window, ownAnchors))
248
+ return false;
249
+ return !mentionsAny(window, otherAnchors);
250
+ }
251
+ /**
252
+ * The line of the header of an option.
253
+ *
254
+ * The candidates are tried in order, and a header that another option
255
+ * already claims is skipped: the label "A+B" must not land on the header of
256
+ * the option "A".
257
+ */
258
+ function locateHeader(lines, candidates, claimed) {
259
+ for (const candidate of candidates) {
260
+ for (let index = 0; index < lines.length; index += 1) {
261
+ if (claimed.has(index))
262
+ continue;
263
+ if (isOptionHeader(lines[index], candidate))
264
+ return index;
265
+ }
266
+ }
267
+ return -1;
268
+ }
269
+ /**
270
+ * Extract the facts of one option from the source message.
271
+ *
272
+ * The extraction is anchored on the option header, not on the beginning of
273
+ * the message: a decisive caveat that stands behind the two thousandth
274
+ * character of the message is as much a part of the option as the sentence
275
+ * in front of it.
276
+ *
277
+ * A paragraph belongs to an option when it names that option and no other.
278
+ * A paragraph that names two options says something about both, and it is
279
+ * left out instead of being filed under one of them.
280
+ */
281
+ export function extractOptionFacts(input) {
282
+ const { source, headerCandidates, mentionAnchors, otherHeaderCandidates, otherMentionAnchors, claimed, question, } = input;
283
+ const empty = {
284
+ description: "",
285
+ tradeoffs: [],
286
+ constraints: [],
287
+ found: false,
288
+ headerIndex: -1,
289
+ descriptionConstraint: false,
290
+ };
291
+ if (headerCandidates.length === 0 || source.length === 0)
292
+ return empty;
293
+ const lines = source.split("\n");
294
+ const headerIndex = locateHeader(lines, headerCandidates, claimed);
295
+ const paragraphs = splitParagraphs(source);
296
+ let description = "";
297
+ let region = [];
298
+ // The range of the section of the option in the source message.
299
+ let sectionRange = null;
300
+ // The paragraphs of the source that the section of the option covers.
301
+ const covered = new Set();
302
+ if (headerIndex >= 0) {
303
+ // The region of the option ends at the next option header, at the
304
+ // next heading of the message, or at the question itself.
305
+ const regionLines = [];
306
+ const questionMarker = question.trim().slice(0, 40);
307
+ let lastIndex = headerIndex;
308
+ for (let index = headerIndex; index < lines.length; index += 1) {
309
+ const line = lines[index];
310
+ if (index > headerIndex) {
311
+ if (/^\s*#{1,6}\s/.test(line))
312
+ break;
313
+ if (questionMarker.length > 0 && line.includes(questionMarker))
314
+ break;
315
+ if (otherHeaderCandidates.some((other) => isOptionHeader(line, other))) {
316
+ break;
317
+ }
318
+ }
319
+ regionLines.push(line);
320
+ lastIndex = index;
321
+ }
322
+ sectionRange = {
323
+ start: lineOffset(lines, headerIndex),
324
+ end: lineOffset(lines, lastIndex) +
325
+ lines[lastIndex].length,
326
+ };
327
+ region = splitParagraphs(regionLines.join("\n"));
328
+ if (region.length > 0) {
329
+ const anchor = headerCandidates.find((candidate) => isOptionHeader(lines[headerIndex], candidate)) ?? headerCandidates[0];
330
+ description = stripMarkdown(stripLeadingAnchor(region[0].text, anchor));
331
+ }
332
+ }
333
+ else {
334
+ // No header: the first paragraph that names the option and no other
335
+ // one carries its meaning.
336
+ const candidateIndex = paragraphs.findIndex((paragraph) => belongsToOption(paragraph.text, mentionAnchors, otherMentionAnchors));
337
+ const candidate = candidateIndex >= 0
338
+ ? paragraphs[candidateIndex]
339
+ : undefined;
340
+ if (candidate) {
341
+ const anchor = mentionAnchors.find((token) => mentionsAnchor(candidate.text.slice(0, MENTION_WINDOW_CHARS), token)) ?? mentionAnchors[0];
342
+ description = stripMarkdown(stripLeadingAnchor(candidate.text, anchor));
343
+ covered.add(candidateIndex);
344
+ }
345
+ }
346
+ // The paragraphs that the section of the option covers: they belong to
347
+ // the option, and they are not looked at a second time.
348
+ if (sectionRange) {
349
+ paragraphs.forEach((paragraph, paragraphIndex) => {
350
+ const paragraphEnd = paragraph.start + paragraph.text.length;
351
+ if (paragraph.start < sectionRange.end &&
352
+ paragraphEnd > sectionRange.start) {
353
+ covered.add(paragraphIndex);
354
+ }
355
+ });
356
+ }
357
+ const tradeoffs = [];
358
+ const constraints = [];
359
+ /** Remember a fact, as a constraint when it states a restriction. */
360
+ const recordFact = (value) => {
361
+ if (statesConstraint(value)) {
362
+ if (!constraints.includes(value))
363
+ constraints.push(value);
364
+ }
365
+ else if (!tradeoffs.includes(value)) {
366
+ tradeoffs.push(value);
367
+ }
368
+ };
369
+ /**
370
+ * A fact of the section of the option belongs to it by position: the
371
+ * section writes about that option, and a paragraph that names it with
372
+ * a pronoun ("it must actually connect") is still about it. A paragraph
373
+ * that names another option belongs to that one.
374
+ */
375
+ const addSectionFact = (text) => {
376
+ const value = stripMarkdown(text);
377
+ if (value.length === 0)
378
+ return;
379
+ if (mentionsAny(value.slice(0, MENTION_WINDOW_CHARS), otherMentionAnchors)) {
380
+ return;
381
+ }
382
+ recordFact(value);
383
+ };
384
+ /**
385
+ * A fact from outside the section has to name the option, and it must
386
+ * not name another one: "Caveat for B: ..." is about B.
387
+ */
388
+ const addNamedFact = (text) => {
389
+ const value = stripMarkdown(text);
390
+ if (value.length === 0)
391
+ return;
392
+ if (!belongsToOption(value, mentionAnchors, otherMentionAnchors))
393
+ return;
394
+ recordFact(value);
395
+ };
396
+ // The paragraphs of the section after the description.
397
+ for (const paragraph of region.slice(1)) {
398
+ addSectionFact(paragraph.text);
399
+ }
400
+ // A caveat that names the option belongs to the option, even when it
401
+ // stands outside the section: "Caveat for B: ..." is about B.
402
+ for (const [paragraphIndex, paragraph] of paragraphs.entries()) {
403
+ if (covered.has(paragraphIndex))
404
+ continue;
405
+ addNamedFact(paragraph.text);
406
+ }
407
+ return {
408
+ description,
409
+ tradeoffs,
410
+ constraints,
411
+ found: description.length > 0,
412
+ headerIndex,
413
+ descriptionConstraint: statesConstraint(description),
414
+ };
415
+ }
416
+ /**
417
+ * The paragraph of the source message that stands directly before the
418
+ * question: it states the problem the question is about.
419
+ */
420
+ function extractProblem(source, question) {
421
+ if (source.length === 0)
422
+ return "";
423
+ const questionIndex = question.length > 0 ? source.indexOf(question) : -1;
424
+ if (questionIndex > 0) {
425
+ const before = source.slice(0, questionIndex);
426
+ const paragraphs = splitParagraphs(before);
427
+ const last = paragraphs[paragraphs.length - 1];
428
+ if (last)
429
+ return stripMarkdown(last.text);
430
+ }
431
+ const paragraphs = splitParagraphs(source);
432
+ const first = paragraphs[0];
433
+ return first ? stripMarkdown(first.text) : "";
434
+ }
435
+ /**
436
+ * Build the decision context of a choice question.
437
+ *
438
+ * The function never decides and never authorizes: it prepares the facts
439
+ * that a decision is made of, and it names what it could not establish.
440
+ */
441
+ export function buildChoiceDecisionContext(input) {
442
+ const omitted = [];
443
+ const uncertainties = [];
444
+ const structured = input.structured ?? {};
445
+ const structuredOptions = Array.isArray(structured.options)
446
+ ? structured.options
447
+ : [];
448
+ // The question itself.
449
+ let question = input.question.trim();
450
+ if (question.length > MAX_CHOICE_QUESTION_CHARS) {
451
+ question = question.slice(0, MAX_CHOICE_QUESTION_CHARS);
452
+ omitted.push(`the question was cut at ${MAX_CHOICE_QUESTION_CHARS} characters`);
453
+ }
454
+ // The alternatives, with their stable ids.
455
+ const allAlternatives = input.alternatives.filter((alternative) => alternative.trim().length > 0);
456
+ const alternatives = allAlternatives.slice(0, MAX_CHOICE_OPTIONS);
457
+ if (allAlternatives.length > alternatives.length) {
458
+ omitted.push(`${allAlternatives.length - alternatives.length} alternative(s) beyond the limit of ${MAX_CHOICE_OPTIONS} did not reach the evaluation`);
459
+ }
460
+ const source = input.contextText ?? "";
461
+ const primarySets = alternatives.map((alternative) => derivePrimaryAnchors(alternative));
462
+ const headerSets = alternatives.map((alternative, index) => {
463
+ // A token that is the primary label of another option belongs to
464
+ // that option and to no other: the header of "A+B" is not the header
465
+ // of the option "A", whatever the order of the alternatives is.
466
+ const otherPrimaries = primarySets
467
+ .flat()
468
+ .filter((token) => !primarySets[index]?.includes(token));
469
+ return deriveOptionAnchors(alternative).filter((token) => !otherPrimaries.includes(token));
470
+ });
471
+ // The mention anchors of every option: a part of a combination belongs
472
+ // to the option that names it and to no other.
473
+ const mentionSets = primarySets.map((primaries) => deriveMentionAnchors(primaries, primarySets
474
+ .flat()
475
+ .filter((token) => !primaries.includes(token))));
476
+ const structuredByLabel = new Map();
477
+ for (const option of structuredOptions) {
478
+ if (typeof option?.label !== "string")
479
+ continue;
480
+ structuredByLabel.set(normalizeLabel(option.label), option);
481
+ }
482
+ const options = [];
483
+ const claimed = new Set();
484
+ let derivedFromStructured = 0;
485
+ let derivedFromMessage = 0;
486
+ let derivedFromBoth = 0;
487
+ let missingMeaning = false;
488
+ const readFacts = (values, fallback) => {
489
+ const list = Array.isArray(values)
490
+ ? values.filter((value) => typeof value === "string" && value.trim().length > 0)
491
+ : fallback;
492
+ const facts = list.slice(0, MAX_OPTION_FACTS).map((fact) => {
493
+ const trimmed = fact.trim();
494
+ return trimmed.length > MAX_OPTION_FACT_CHARS
495
+ ? trimmed.slice(0, MAX_OPTION_FACT_CHARS)
496
+ : trimmed;
497
+ });
498
+ return { facts, cut: list.length > MAX_OPTION_FACTS };
499
+ };
500
+ /**
501
+ * The facts of an option: the supplied ones come first, the facts of the
502
+ * source follow. A fact that is in both lists is kept once.
503
+ *
504
+ * The result is undefined when the supplied facts are not a list: the
505
+ * facts of the source are then the only ones, and the caller reports
506
+ * the malformed facts itself.
507
+ */
508
+ const mergeFacts = (supplied, sourceFacts) => {
509
+ if (!Array.isArray(supplied))
510
+ return undefined;
511
+ const merged = [];
512
+ for (const value of supplied) {
513
+ if (typeof value !== "string")
514
+ continue;
515
+ const trimmed = value.trim();
516
+ if (trimmed.length === 0)
517
+ continue;
518
+ if (!merged.includes(trimmed))
519
+ merged.push(trimmed);
520
+ }
521
+ for (const fact of sourceFacts) {
522
+ if (!merged.includes(fact))
523
+ merged.push(fact);
524
+ }
525
+ return merged;
526
+ };
527
+ for (const [index, alternative] of alternatives.entries()) {
528
+ const id = `option_${index + 1}`;
529
+ const label = alternative.trim();
530
+ const headerCandidates = headerSets[index] ?? [];
531
+ const mentionAnchors = mentionSets[index] ?? [];
532
+ const otherHeaderCandidates = headerSets
533
+ .flat()
534
+ .filter((candidate) => !headerCandidates.includes(candidate));
535
+ const otherMentionAnchors = mentionSets
536
+ .flat()
537
+ .filter((anchor) => !mentionAnchors.includes(anchor));
538
+ // A labelled fact belongs to its label. The positional fallback is
539
+ // only for a supplied option that carries no label at all.
540
+ const labelled = structuredByLabel.get(normalizeLabel(label));
541
+ const unlabelled = structuredOptions.length === alternatives.length
542
+ ? structuredOptions[index]
543
+ : undefined;
544
+ const supplied = labelled ??
545
+ (unlabelled && typeof unlabelled.label !== "string"
546
+ ? unlabelled
547
+ : undefined);
548
+ const suppliedDescription = supplied && typeof supplied.description === "string"
549
+ ? supplied.description.trim()
550
+ : "";
551
+ if (supplied && supplied.description !== undefined && !suppliedDescription) {
552
+ uncertainties.push(`${id} (${label}): the supplied description is empty or malformed, the message was used instead`);
553
+ }
554
+ // The extraction always runs. A supplied description is the meaning
555
+ // of the option, not a replacement for the facts of the message: a
556
+ // caveat that only the message carries has to survive it.
557
+ const extracted = extractOptionFacts({
558
+ source,
559
+ headerCandidates,
560
+ mentionAnchors,
561
+ otherHeaderCandidates,
562
+ otherMentionAnchors,
563
+ claimed,
564
+ question: input.question,
565
+ });
566
+ if (extracted.headerIndex >= 0) {
567
+ claimed.add(extracted.headerIndex);
568
+ }
569
+ let description = suppliedDescription.length > 0
570
+ ? suppliedDescription
571
+ : extracted.description;
572
+ if (description.length > MAX_OPTION_DESCRIPTION_CHARS) {
573
+ description = description.slice(0, MAX_OPTION_DESCRIPTION_CHARS);
574
+ omitted.push(`${id} (${label}): the description was cut at ${MAX_OPTION_DESCRIPTION_CHARS} characters`);
575
+ }
576
+ // The wording of the source for the option survives a supplied
577
+ // description: it can carry the caveat of the option ("it must
578
+ // actually connect").
579
+ const sourceWording = suppliedDescription.length > 0 &&
580
+ extracted.description.length > 0 &&
581
+ extracted.description !== suppliedDescription
582
+ ? extracted.description
583
+ : "";
584
+ const sourceConstraints = [
585
+ ...(sourceWording.length > 0 && extracted.descriptionConstraint
586
+ ? [sourceWording]
587
+ : []),
588
+ ...extracted.constraints,
589
+ ];
590
+ const sourceTradeoffs = [
591
+ ...(sourceWording.length > 0 && !extracted.descriptionConstraint
592
+ ? [sourceWording]
593
+ : []),
594
+ ...extracted.tradeoffs,
595
+ ];
596
+ const sourceFacts = sourceConstraints.length > 0 || sourceTradeoffs.length > 0;
597
+ const tradeoffsResult = readFacts(mergeFacts(supplied?.tradeoffs, sourceTradeoffs), sourceTradeoffs);
598
+ const constraintsResult = readFacts(mergeFacts(supplied?.constraints, sourceConstraints), sourceConstraints);
599
+ if (tradeoffsResult.cut || constraintsResult.cut) {
600
+ omitted.push(`${id} (${label}): facts beyond the limit of ${MAX_OPTION_FACTS} did not reach the evaluation`);
601
+ }
602
+ if (tradeoffsResult.facts.some((fact) => fact.length === MAX_OPTION_FACT_CHARS) ||
603
+ constraintsResult.facts.some((fact) => fact.length === MAX_OPTION_FACT_CHARS)) {
604
+ omitted.push(`${id} (${label}): a fact was cut at ${MAX_OPTION_FACT_CHARS} characters`);
605
+ }
606
+ if (suppliedDescription.length > 0 && sourceFacts) {
607
+ // The meaning comes from the structure, the facts of the message
608
+ // are merged with it: the provenance is mixed.
609
+ derivedFromBoth += 1;
610
+ }
611
+ else if (suppliedDescription.length > 0) {
612
+ derivedFromStructured += 1;
613
+ }
614
+ else if (extracted.found) {
615
+ derivedFromMessage += 1;
616
+ }
617
+ else {
618
+ missingMeaning = true;
619
+ uncertainties.push(`${id} (${label}): the source does not state what this option means`);
620
+ }
621
+ options.push({
622
+ id: supplied?.id && typeof supplied.id === "string" && supplied.id.trim().length > 0
623
+ ? supplied.id
624
+ : id,
625
+ label,
626
+ description,
627
+ tradeoffs: tradeoffsResult.facts,
628
+ constraints: constraintsResult.facts,
629
+ });
630
+ }
631
+ // The problem.
632
+ let problem = typeof structured.problem === "string" ? structured.problem.trim() : "";
633
+ if (problem.length === 0) {
634
+ problem = extractProblem(source, input.question);
635
+ }
636
+ if (problem.length > MAX_PROBLEM_CHARS) {
637
+ problem = problem.slice(0, MAX_PROBLEM_CHARS);
638
+ omitted.push(`the problem was cut at ${MAX_PROBLEM_CHARS} characters`);
639
+ }
640
+ if (problem.length === 0) {
641
+ uncertainties.push("the source does not state the problem the choice is about");
642
+ }
643
+ // The authorization. Only supplied facts establish an authorization:
644
+ // the message of the agent is not a human answer.
645
+ const approved = Array.isArray(structured.authorization?.approved)
646
+ ? structured.authorization.approved.filter((value) => typeof value === "string")
647
+ : [];
648
+ const notEstablished = Array.isArray(structured.authorization?.notEstablished)
649
+ ? structured.authorization.notEstablished.filter((value) => typeof value === "string")
650
+ : [];
651
+ if (!structured.authorization) {
652
+ notEstablished.push("no human selection between the alternatives is recorded in this evaluation input");
653
+ if (/\bapproved\b/i.test(source)) {
654
+ notEstablished.push("the source reports an approval of an earlier action; it does not establish a selection between the alternatives");
655
+ }
656
+ }
657
+ // The uncertainties the agent reported itself.
658
+ if (Array.isArray(structured.uncertainties)) {
659
+ for (const uncertainty of structured.uncertainties) {
660
+ if (typeof uncertainty === "string" && uncertainty.trim().length > 0) {
661
+ uncertainties.push(uncertainty.trim());
662
+ }
663
+ }
664
+ }
665
+ // The earlier turns of the conversation. Their absence stays visible.
666
+ if (input.history && input.history.available === true) {
667
+ if (input.history.note) {
668
+ omitted.push(input.history.note);
669
+ }
670
+ }
671
+ else {
672
+ const note = input.history?.note ??
673
+ "the earlier turns of the conversation were not supplied";
674
+ uncertainties.push(note);
675
+ omitted.push(note);
676
+ }
677
+ const derived = derivedFromBoth > 0 ||
678
+ (derivedFromStructured > 0 && derivedFromMessage > 0)
679
+ ? "mixed"
680
+ : derivedFromStructured > 0
681
+ ? "structured"
682
+ : "extracted";
683
+ return {
684
+ problem,
685
+ question,
686
+ options,
687
+ authorization: { approved, notEstablished },
688
+ uncertainties,
689
+ source: {
690
+ originalChars: source.length,
691
+ truncated: omitted.length > 0,
692
+ omittedInformation: omitted,
693
+ derived,
694
+ complete: !missingMeaning,
695
+ },
696
+ };
697
+ }
698
+ /**
699
+ * The criterion text of one option: the label, the meaning and the
700
+ * constraints that restrict it.
701
+ *
702
+ * The label alone does not tell the evaluation what the option does, so the
703
+ * meaning travels with it. The constraint is part of the criterion because
704
+ * an option whose restriction is invisible is an option the evaluation
705
+ * cannot judge correctly.
706
+ */
707
+ export function describeChoiceOption(id, label, description, constraints) {
708
+ const meaning = description.length > 0
709
+ ? description
710
+ : "the source does not state what this option means";
711
+ const parts = [`${id} (${label}): ${meaning}`];
712
+ if (constraints.length > 0) {
713
+ parts.push(`constraints: ${constraints.join(" ")}`);
714
+ }
715
+ return parts.join(" - ").slice(0, MAX_OPTION_CRITERION_CHARS);
716
+ }
717
+ /**
718
+ * The bounded text of a choice that reaches the evaluation.
719
+ *
720
+ * The excerpt carries the facts, not the beginning of the message: the
721
+ * relevant sentence of a long message stands behind the two thousandth
722
+ * character far more often than the first one does.
723
+ */
724
+ export function renderChoiceExcerpt(context) {
725
+ const lines = [];
726
+ lines.push(`Question: ${context.question}`);
727
+ for (const option of context.options) {
728
+ lines.push(`${option.id} (${option.label}): ${option.description || "the source does not state what this option means"}`);
729
+ // The constraints come first: a restriction is the fact that decides
730
+ // the option, and it must not be pushed out by the consequences.
731
+ for (const constraint of option.constraints) {
732
+ lines.push(` - constraint: ${constraint}`);
733
+ }
734
+ for (const tradeoff of option.tradeoffs) {
735
+ lines.push(` - consequence: ${tradeoff}`);
736
+ }
737
+ }
738
+ if (context.problem.length > 0) {
739
+ lines.push(`Problem: ${context.problem}`);
740
+ }
741
+ if (context.authorization.approved.length > 0) {
742
+ lines.push(`Authorized: ${context.authorization.approved.join("; ")}`);
743
+ }
744
+ for (const entry of context.authorization.notEstablished) {
745
+ lines.push(`Not authorized: ${entry}`);
746
+ }
747
+ for (const uncertainty of context.uncertainties) {
748
+ lines.push(`Uncertain: ${uncertainty}`);
749
+ }
750
+ if (context.source.omittedInformation.length > 0) {
751
+ lines.push(`Not in the evaluation input: ${context.source.omittedInformation.join("; ")}`);
752
+ }
753
+ return lines.join("\n").slice(0, MAX_CHOICE_EXCERPT_CHARS);
754
+ }
755
+ //# sourceMappingURL=decision-context.js.map