@mcoda/mswarm 0.1.135-codali.42 → 0.1.135-codali.47

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 (92) hide show
  1. package/dist/vendor/codali/eval/fixtures/ContractReviewProvider.d.ts +5 -0
  2. package/dist/vendor/codali/eval/fixtures/ContractReviewProvider.d.ts.map +1 -1
  3. package/dist/vendor/codali/eval/fixtures/ContractReviewProvider.js +63 -0
  4. package/dist/vendor/codali/eval/fixtures/MixedMediaRecoveryJourney.js +2 -2
  5. package/dist/vendor/codali/eval/fixtures/TerminalRecoveryJourney.js +2 -2
  6. package/dist/vendor/codali/permissions/PermissionGate.js +1 -1
  7. package/dist/vendor/codali/providers/ClaudeCliProvider.d.ts.map +1 -1
  8. package/dist/vendor/codali/providers/ClaudeCliProvider.js +1 -0
  9. package/dist/vendor/codali/providers/CodexCliProvider.d.ts.map +1 -1
  10. package/dist/vendor/codali/providers/CodexCliProvider.js +1 -0
  11. package/dist/vendor/codali/providers/ModelServiceError.d.ts +14 -0
  12. package/dist/vendor/codali/providers/ModelServiceError.d.ts.map +1 -1
  13. package/dist/vendor/codali/providers/ModelServiceError.js +15 -2
  14. package/dist/vendor/codali/providers/OllamaRemoteProvider.d.ts.map +1 -1
  15. package/dist/vendor/codali/providers/OllamaRemoteProvider.js +1 -0
  16. package/dist/vendor/codali/providers/OpenAiCompatibleProvider.d.ts.map +1 -1
  17. package/dist/vendor/codali/providers/OpenAiCompatibleProvider.js +4 -0
  18. package/dist/vendor/codali/providers/ProviderTypes.d.ts +4 -0
  19. package/dist/vendor/codali/providers/ProviderTypes.d.ts.map +1 -1
  20. package/dist/vendor/codali/runtime/AnswerEdits.d.ts +39 -0
  21. package/dist/vendor/codali/runtime/AnswerEdits.d.ts.map +1 -0
  22. package/dist/vendor/codali/runtime/AnswerEdits.js +134 -0
  23. package/dist/vendor/codali/runtime/AnswerVerification.d.ts.map +1 -1
  24. package/dist/vendor/codali/runtime/AnswerVerification.js +4 -2
  25. package/dist/vendor/codali/runtime/AuditGuards.d.ts +41 -0
  26. package/dist/vendor/codali/runtime/AuditGuards.d.ts.map +1 -0
  27. package/dist/vendor/codali/runtime/AuditGuards.js +81 -0
  28. package/dist/vendor/codali/runtime/CompletionReport.d.ts +4 -2
  29. package/dist/vendor/codali/runtime/CompletionReport.d.ts.map +1 -1
  30. package/dist/vendor/codali/runtime/CompletionReport.js +8 -3
  31. package/dist/vendor/codali/runtime/DeliveryDocs.d.ts +21 -0
  32. package/dist/vendor/codali/runtime/DeliveryDocs.d.ts.map +1 -0
  33. package/dist/vendor/codali/runtime/DeliveryDocs.js +148 -0
  34. package/dist/vendor/codali/runtime/FigureCheck.d.ts +61 -2
  35. package/dist/vendor/codali/runtime/FigureCheck.d.ts.map +1 -1
  36. package/dist/vendor/codali/runtime/FigureCheck.js +210 -14
  37. package/dist/vendor/codali/runtime/GatewayRequest.d.ts +13 -0
  38. package/dist/vendor/codali/runtime/GatewayRequest.d.ts.map +1 -1
  39. package/dist/vendor/codali/runtime/GatewayRequest.js +54 -1
  40. package/dist/vendor/codali/runtime/InspectionConvergence.d.ts +4 -0
  41. package/dist/vendor/codali/runtime/InspectionConvergence.d.ts.map +1 -1
  42. package/dist/vendor/codali/runtime/InspectionConvergence.js +24 -1
  43. package/dist/vendor/codali/runtime/NumericProvenance.d.ts +102 -0
  44. package/dist/vendor/codali/runtime/NumericProvenance.d.ts.map +1 -0
  45. package/dist/vendor/codali/runtime/NumericProvenance.js +411 -0
  46. package/dist/vendor/codali/runtime/OutageWait.d.ts +13 -0
  47. package/dist/vendor/codali/runtime/OutageWait.d.ts.map +1 -1
  48. package/dist/vendor/codali/runtime/OutageWait.js +13 -0
  49. package/dist/vendor/codali/runtime/ResearchEvidence.d.ts.map +1 -1
  50. package/dist/vendor/codali/runtime/ResearchEvidence.js +79 -3
  51. package/dist/vendor/codali/runtime/ReviewCoordinator.d.ts +22 -0
  52. package/dist/vendor/codali/runtime/ReviewCoordinator.d.ts.map +1 -1
  53. package/dist/vendor/codali/runtime/ReviewCoordinator.js +201 -24
  54. package/dist/vendor/codali/runtime/SessionController.d.ts +31 -22
  55. package/dist/vendor/codali/runtime/SessionController.d.ts.map +1 -1
  56. package/dist/vendor/codali/runtime/SessionController.js +592 -176
  57. package/dist/vendor/codali/runtime/StructuralEvidence.d.ts +10 -0
  58. package/dist/vendor/codali/runtime/StructuralEvidence.d.ts.map +1 -1
  59. package/dist/vendor/codali/runtime/StructuralEvidence.js +10 -0
  60. package/dist/vendor/codali/runtime/TaskReview.d.ts +10 -0
  61. package/dist/vendor/codali/runtime/TaskReview.d.ts.map +1 -1
  62. package/dist/vendor/codali/runtime/TaskReview.js +14 -1
  63. package/dist/vendor/codali/tools/ToolRegistry.d.ts.map +1 -1
  64. package/dist/vendor/codali/tools/ToolRegistry.js +11 -2
  65. package/dist/vendor/codali/tools/browser/BrowserWorker.js +142 -2
  66. package/dist/vendor/codali/tools/calculation/CalculatorTool.d.ts +1 -1
  67. package/dist/vendor/codali/tools/calculation/CalculatorTool.d.ts.map +1 -1
  68. package/dist/vendor/codali/tools/calculation/CalculatorTool.js +209 -41
  69. package/dist/vendor/codali/tools/deterministic/DeterministicTools.js +1 -1
  70. package/dist/vendor/codali/tools/deterministic/node-worker.cjs +10 -10
  71. package/dist/vendor/codali/tools/shell/AsyncProcess.d.ts +2 -0
  72. package/dist/vendor/codali/tools/shell/AsyncProcess.d.ts.map +1 -1
  73. package/dist/vendor/codali/tools/shell/AsyncProcess.js +32 -5
  74. package/dist/vendor/codali/tools/shell/IsolatedExecutor.d.ts +29 -1
  75. package/dist/vendor/codali/tools/shell/IsolatedExecutor.d.ts.map +1 -1
  76. package/dist/vendor/codali/tools/shell/IsolatedExecutor.js +169 -7
  77. package/dist/vendor/codali/tools/shell/ShellTool.js +1 -1
  78. package/dist/vendor/codali/tools/verification/CodeRunTool.d.ts +19 -0
  79. package/dist/vendor/codali/tools/verification/CodeRunTool.d.ts.map +1 -0
  80. package/dist/vendor/codali/tools/verification/CodeRunTool.js +104 -0
  81. package/dist/vendor/codali/tools/verification/JavaScriptVerificationTool.d.ts.map +1 -1
  82. package/dist/vendor/codali/tools/verification/JavaScriptVerificationTool.js +21 -10
  83. package/dist/vendor/codali/tools/verification/VitestTool.d.ts +27 -0
  84. package/dist/vendor/codali/tools/verification/VitestTool.d.ts.map +1 -1
  85. package/dist/vendor/codali/tools/verification/VitestTool.js +160 -16
  86. package/dist/vendor/config/deterministic/node-worker.mjs +15 -2
  87. package/dist/vendor/config/skills/code-implementation/SKILL.md +1 -1
  88. package/dist/vendor/config/skills/planning/SKILL.md +1 -1
  89. package/dist/vendor/config/skills/ui-ux-design/SKILL.md +1 -1
  90. package/dist/vendor/config/skills/webapp-testing/SKILL.md +2 -11
  91. package/dist/vendor/config/skills/webapp-testing/journey-driver.mjs +104 -3
  92. package/package.json +3 -3
@@ -0,0 +1,411 @@
1
+ /** Which numbers in an answer rest on results that were actually executed.
2
+ *
3
+ * Cycle 7 lost three numeric answers (0, 60 and 80 points) whose values were in
4
+ * no tool result at all, or came from a later, simplified rerun that disagreed
5
+ * with an earlier full one; and an equation review with no tools changed a value
6
+ * that executed code had printed. Both the delivery check and the review guard
7
+ * decide here by evidence: a value is backed when an executed result shows it at
8
+ * the precision the answer states it, allowing the usual derivations (rounding,
9
+ * percent and common unit factors, sign). Matching is deliberately lenient: a
10
+ * missed match costs one reconcile turn, a false match only keeps old behaviour. */
11
+ const NUMBER_SOURCE = String.raw `-?(?:\d+(?:\.\d+)?|\.\d+)(?:[eE][-+]?\d+)?`;
12
+ const NUMBER = new RegExp(NUMBER_SOURCE, "g");
13
+ const FRACTION = /(-?\d+(?:\.\d+)?)\s*\/\s*(\d+(?:\.\d+)?)/g;
14
+ const MAX_TEXT = 20000;
15
+ export const normalizedKey = (key) => key.toLowerCase().replace(/[^a-z0-9]/g, "");
16
+ /** Decimal places a token states; "2.8910" states four, "2" none. */
17
+ const decimals = (token) => {
18
+ const [mantissa, exponent] = token.toLowerCase().replace(/^-/, "").split("e");
19
+ return Math.max(0, (mantissa.split(".")[1] ?? "").length - Number(exponent ?? 0));
20
+ };
21
+ const tolerance = (token, value) => 0.5 * 10 ** -decimals(token) * (1 + 1e-9) + 1e-12 * Math.max(1, Math.abs(value));
22
+ /** Factors that turn one correct figure into another correct one: percent, milli/kilo, minutes/hours/days. */
23
+ const DERIVATIONS = [1, 100, 0.01, 1000, 0.001, 60, 1 / 60, 3600, 1 / 3600, 24, 1 / 24];
24
+ /** A whole-number token, or a strict check, matches only the value itself: with
25
+ * unit factors almost any small integer matches something by chance (25 by 0.25,
26
+ * 6 by 0.1 minutes), and a chance match must never count as support. */
27
+ const matches = (token, value, candidate, strict = false, unit) => {
28
+ const allowed = tolerance(token, value);
29
+ // A whole number with its unit stated ("25%", "120 minutes") is a conversion, not a chance match.
30
+ const factors = strict || decimals(token) === 0 && !unit ? [1] : DERIVATIONS;
31
+ return factors.some(factor => Math.abs(Math.abs(candidate * factor) - Math.abs(value)) <= allowed);
32
+ };
33
+ const numbersCache = new WeakMap();
34
+ /** Receipt envelope fields: timings, hashes, versions and settings, never computed values. */
35
+ const ENVELOPE_FIELDS = new Set(["elapsedms", "inputsha256", "workersha256", "sourcesha256", "sha256", "version", "library", "precision", "rounding", "arithmetic",
36
+ "semantics", "scope", "isolation", "warning", "exitcode", "timedout", "index", "passed", "ran", "runonly", "runonlycases", "truncated", "language"]);
37
+ const textNumbers = (text) => {
38
+ const numbers = (text.match(NUMBER) ?? []).map(Number).filter(Number.isFinite);
39
+ for (const [, a, b] of text.matchAll(FRACTION)) {
40
+ const value = Number(a) / Number(b);
41
+ if (Number.isFinite(value))
42
+ numbers.push(value);
43
+ }
44
+ return numbers;
45
+ };
46
+ /** The numbers a result reports, fractions (65/4) evaluated as well. A JSON
47
+ * receipt contributes its values, not its envelope (elapsed time, hashes,
48
+ * library versions); printed output contributes every number it shows. */
49
+ export const resultNumbers = (result) => {
50
+ const cached = numbersCache.get(result);
51
+ if (cached)
52
+ return cached;
53
+ const text = result.text.slice(0, MAX_TEXT);
54
+ let numbers;
55
+ try {
56
+ const parsed = JSON.parse(text);
57
+ numbers = [];
58
+ const walk = (value, key, depth) => {
59
+ if (depth > 16 || key && ENVELOPE_FIELDS.has(normalizedKey(key)))
60
+ return;
61
+ if (typeof value === "number") {
62
+ if (Number.isFinite(value))
63
+ numbers.push(value);
64
+ }
65
+ else if (typeof value === "string") {
66
+ const trimmed = value.trim();
67
+ if (/^[[{]/.test(trimmed)) {
68
+ try {
69
+ walk(JSON.parse(trimmed), key, depth + 1);
70
+ return;
71
+ }
72
+ catch { /* Not JSON. */ }
73
+ }
74
+ if (new RegExp(`^(?:${NUMBER_SOURCE}|${FRACTION.source})$`).test(trimmed))
75
+ numbers.push(...textNumbers(trimmed));
76
+ }
77
+ else if (Array.isArray(value))
78
+ value.forEach(item => walk(item, key, depth + 1));
79
+ else if (value && typeof value === "object")
80
+ for (const [k, v] of Object.entries(value))
81
+ walk(v, k, depth + 1);
82
+ };
83
+ walk(parsed, undefined, 0);
84
+ }
85
+ catch {
86
+ numbers = textNumbers(text);
87
+ }
88
+ numbersCache.set(result, numbers);
89
+ return numbers;
90
+ };
91
+ /** Named values a result reports, last value per name: JSON fields at any depth
92
+ * (JSON inside strings too) and `name: value` / `name = value` lines of printed output. */
93
+ export const keyedValues = (text) => {
94
+ const found = new Map();
95
+ const walk = (value, key, depth) => {
96
+ if (depth > 12)
97
+ return;
98
+ if (typeof value === "number" && key)
99
+ found.set(normalizedKey(key), value);
100
+ else if (typeof value === "string") {
101
+ const trimmed = value.trim();
102
+ if (/^[[{]/.test(trimmed)) {
103
+ try {
104
+ walk(JSON.parse(trimmed), key, depth + 1);
105
+ return;
106
+ }
107
+ catch { /* Not JSON: read as printed text. */ }
108
+ }
109
+ if (key && new RegExp(`^${NUMBER_SOURCE}$`).test(trimmed))
110
+ found.set(normalizedKey(key), Number(trimmed));
111
+ else if (depth > 0)
112
+ for (const [k, v] of printedPairs(value))
113
+ found.set(k, v);
114
+ }
115
+ else if (Array.isArray(value))
116
+ value.forEach(item => walk(item, key, depth + 1));
117
+ else if (value && typeof value === "object")
118
+ for (const [k, v] of Object.entries(value))
119
+ walk(v, /^\d+$/.test(k) && key ? `${key}${k}` : k, depth + 1);
120
+ };
121
+ const slice = text.slice(0, MAX_TEXT);
122
+ try {
123
+ walk(JSON.parse(slice), undefined, 0);
124
+ }
125
+ catch {
126
+ for (const [k, v] of printedPairs(slice))
127
+ found.set(k, v);
128
+ }
129
+ return found;
130
+ };
131
+ const printedPairs = (text) => [...text.matchAll(new RegExp(String.raw `([A-Za-z_][A-Za-z0-9_ ]{0,48}?)\s*[:=]\s*(${NUMBER_SOURCE})(?![\d.])`, "g"))]
132
+ .map(([, key, value]) => [normalizedKey(key), Number(value)]).filter(([key, value]) => key && Number.isFinite(value));
133
+ /** The answer's JSON document, if it is one (bare or in a single json fence). */
134
+ const jsonDocument = (reply) => {
135
+ const trimmed = reply.trim();
136
+ const fenced = trimmed.match(/^```(?:json)?\s*\n([\s\S]*?)\n?```$/i)?.[1] ?? trimmed;
137
+ return /^[[{]/.test(fenced.trim()) ? fenced.trim() : undefined;
138
+ };
139
+ const UNIT_SOURCE = String.raw `%|percent|per cent|ms|milliseconds?|msec|s|secs?|seconds?|min|mins|minutes?|h|hrs?|hours?|d|days?`;
140
+ const UNIT_NAMES = [[/^(?:%|percent|per cent)$/i, "%"], [/^(?:ms|msec|milliseconds?)$/i, "ms"], [/^(?:s|secs?|seconds?)$/i, "s"],
141
+ [/^(?:min|mins|minutes?)$/i, "min"], [/^(?:h|hrs?|hours?)$/i, "h"], [/^(?:d|days?)$/i, "d"]];
142
+ const textUnit = (text) => { const word = text.trim(); return UNIT_NAMES.find(([pattern]) => pattern.test(word))?.[1]; };
143
+ /** A unit named by a JSON field ("utilisationPercent", "waitMinutes", "latency_ms"). */
144
+ const keyUnit = (key) => !key ? undefined
145
+ : /(?:percent|pct)$/i.test(key) ? "%" : /(?:ms|millis|milliseconds)$/i.test(key) ? "ms" : /(?:minutes|mins)$/i.test(key) ? "min"
146
+ : /(?:hours|hrs)$/i.test(key) ? "h" : /(?:seconds|secs)$/i.test(key) ? "s" : /days$/i.test(key) ? "d" : undefined;
147
+ const TOKEN_MARK = "\u0000num:";
148
+ /** Parse JSON keeping each number's own text, so "2.8910" keeps its four places. */
149
+ const parseKeepingTokens = (document) => {
150
+ const marked = document.replace(new RegExp(String.raw `([:\[,]\s*)(${NUMBER_SOURCE})(?=\s*[,}\]])`, "g"), (_, lead, token) => `${lead}"\\u0000num:${token}"`);
151
+ try {
152
+ return JSON.parse(marked);
153
+ }
154
+ catch {
155
+ return JSON.parse(document);
156
+ }
157
+ };
158
+ /** Numeric values in an answer. For JSON answers every numeric leaf with its path;
159
+ * for text answers the numbers that are not restated inputs, with a label when
160
+ * one precedes them ("mean wait: 4.2"). */
161
+ export const answerValues = (reply, prompt = "") => {
162
+ const document = jsonDocument(reply);
163
+ if (document) {
164
+ try {
165
+ const values = [];
166
+ const walk = (value, path, key) => {
167
+ const unit = keyUnit(key);
168
+ if (typeof value === "number")
169
+ values.push({ path, key, token: String(value), value, unit });
170
+ else if (typeof value === "string" && value.startsWith(TOKEN_MARK)) {
171
+ const token = value.slice(TOKEN_MARK.length);
172
+ values.push({ path, key, token, value: Number(token), unit });
173
+ }
174
+ else if (typeof value === "string" && new RegExp(`^${NUMBER_SOURCE}\\s*(?:${UNIT_SOURCE})?$`, "i").test(value.trim())) {
175
+ const token = value.trim().match(NUMBER)[0];
176
+ values.push({ path, key, token, value: Number(token), unit: unit ?? textUnit(value.trim().slice(token.length)) });
177
+ }
178
+ else if (Array.isArray(value))
179
+ value.forEach((item, index) => walk(item, `${path}[${index}]`, key));
180
+ else if (value && typeof value === "object")
181
+ for (const [k, v] of Object.entries(value))
182
+ walk(v, path ? `${path}.${k}` : k, k);
183
+ };
184
+ walk(parseKeepingTokens(document), "", undefined);
185
+ return { json: true, values };
186
+ }
187
+ catch { /* Not valid JSON: read it as text. */ }
188
+ }
189
+ const inputs = new Set((prompt.match(NUMBER) ?? []).map(Number));
190
+ const values = [];
191
+ const text = withoutNonQuantities(reply.replace(/```[\s\S]*?```/g, " "));
192
+ const pattern = new RegExp(String.raw `(?:([A-Za-z][A-Za-z_ ()/-]{0,40}?)\s*(?:[:=]|\bis\b|\bequals\b|≈)\s*\**\s*)?(?<![\w.])(${NUMBER_SOURCE})(?![\w.]*\d)(\s*(?:${UNIT_SOURCE})(?![A-Za-z]))?`, "gi");
193
+ for (const match of text.matchAll(pattern)) {
194
+ const token = match[2], value = Number(token);
195
+ if (!Number.isFinite(value) || inputs.has(value))
196
+ continue;
197
+ values.push({ path: `#${values.length}`, key: match[1]?.trim() || undefined, token, value, unit: match[3] ? textUnit(match[3]) : undefined });
198
+ }
199
+ return { json: false, values };
200
+ };
201
+ /** The executed result (latest first) or prompt input that shows a value at its stated precision. */
202
+ export const backingOf = (item, results, prompt = "", strict = false) => {
203
+ if (decimals(item.token) === 0 && [0, 1].includes(Math.abs(item.value)))
204
+ return { kind: "input" };
205
+ for (const result of [...results].sort((a, b) => b.seq - a.seq)) {
206
+ if (resultNumbers(result).some(candidate => matches(item.token, item.value, candidate, strict, item.unit)))
207
+ return { kind: result.kind, seq: result.seq, tool: result.tool };
208
+ }
209
+ // A restated input backs a value only at the precision the request gave it:
210
+ // "2" in the request does not support a computed "2.000000".
211
+ for (const token of prompt.match(NUMBER) ?? []) {
212
+ if (decimals(item.token) <= decimals(token) && Math.abs(Number(token) - item.value) <= tolerance(item.token, item.value))
213
+ return { kind: "input" };
214
+ }
215
+ return undefined;
216
+ };
217
+ /** Answer fields whose name an executed result also reports, where executed runs
218
+ * disagree with each other or the latest one disagrees with the answer. */
219
+ // Envelope fields of tool receipts, not names of computed quantities.
220
+ const GENERIC_KEYS = new Set(["result", "results", "value", "values", "answer", "output", "actual", "expected", "index", "elapsedms", "precision", "places", "version", "exitcode", "status"]);
221
+ export const receiptConflicts = (values, results) => {
222
+ const ordered = [...results].sort((a, b) => a.seq - b.seq).map(result => ({ result, keyed: keyedValues(result.text) }));
223
+ const conflicts = [];
224
+ for (const item of values) {
225
+ if (!item.key)
226
+ continue;
227
+ const key = normalizedKey(item.key);
228
+ if (key.length < 3 || GENERIC_KEYS.has(key))
229
+ continue;
230
+ const runs = ordered.filter(entry => entry.keyed.has(key)).map(entry => ({ seq: entry.result.seq, tool: entry.result.tool, value: entry.keyed.get(key) }));
231
+ if (!runs.length)
232
+ continue;
233
+ const latest = runs.at(-1);
234
+ const latestDisagrees = !matches(item.token, item.value, latest.value);
235
+ const runsDisagree = runs.some(run => !matches(item.token, latest.value, run.value));
236
+ if (latestDisagrees && backingOf(item, results.filter(result => result.seq > latest.seq)) === undefined || runsDisagree) {
237
+ conflicts.push({ key: item.key, drafted: item.token, runs: runs.slice(-4), latestDisagrees });
238
+ }
239
+ }
240
+ return conflicts;
241
+ };
242
+ /** Delivery check: answer values with no executed result behind them, and named
243
+ * values on which executed runs disagree. */
244
+ export const numericProvenance = (reply, prompt, results) => {
245
+ const { json, values } = answerValues(reply, prompt);
246
+ const unbacked = values.filter(item => !backingOf(item, results, prompt));
247
+ return { json, values, unbacked, conflicts: receiptConflicts(values, results) };
248
+ };
249
+ /** Whether every value of an answer was printed or returned by executed code. */
250
+ export const backedByExecutedCode = (reply, prompt, results) => {
251
+ const code = results.filter(result => result.kind === "code");
252
+ const { values } = answerValues(reply, prompt);
253
+ if (!values.length || !code.length)
254
+ return false;
255
+ return values.every(item => backingOf(item, code, prompt, true) !== undefined);
256
+ };
257
+ /** Whether a review kept a drafted value: judged at the draft's own precision. A
258
+ * review that states fewer places (2.3480 -> 2) changed the value, not kept it. */
259
+ const sameValue = (drafted, revised) => drafted.value === revised.value
260
+ || decimals(revised.token) >= decimals(drafted.token) && Math.abs(drafted.value - revised.value) <= tolerance(drafted.token, drafted.value);
261
+ /** A review value supports itself only by a direct match at no less precision than the draft. */
262
+ const reviewBacking = (drafted, revised, results, prompt) => decimals(revised.token) >= decimals(drafted.token) ? backingOf(revised, results, prompt, true) : undefined;
263
+ /** A review that adds places to a drafted value ("2.004" -> "2.0041") claims the
264
+ * extra digits. When an executed result backs the drafted value but contradicts
265
+ * those digits (2.0040083 -> 2.0040), the receipt's value at the review's
266
+ * precision replaces both; undefined when there is nothing to contradict. */
267
+ const receiptAtReviewPrecision = (drafted, revised, results) => {
268
+ const places = decimals(revised.token);
269
+ if (places <= decimals(drafted.token) || places > 20 || backingOf(revised, results, "", true))
270
+ return undefined;
271
+ let nearest;
272
+ for (const result of results)
273
+ for (const candidate of resultNumbers(result)) {
274
+ if (matches(drafted.token, drafted.value, candidate, true) && (nearest === undefined || Math.abs(candidate - drafted.value) < Math.abs(nearest - drafted.value)))
275
+ nearest = candidate;
276
+ }
277
+ return nearest === undefined ? undefined : nearest.toFixed(places);
278
+ };
279
+ /** Decide a tool-less review's edits field by field, by which side executed
280
+ * results support. A changed value is accepted when the review's value is itself
281
+ * backed, or when neither value has executed support (catching a figure that
282
+ * models the wrong quantity is the review's job). A value printed by executed
283
+ * code is never replaced by an unexecuted one. A value from a calculation receipt
284
+ * that the review contests is a dispute: the expression ran, but the review says
285
+ * it is the wrong expression, and only another executed method can settle that.
286
+ * Until one does, the executed value stays. A number is never replaced by null. */
287
+ export const decideReview = (draft, revised, prompt, results) => {
288
+ const before = answerValues(draft, prompt), after = answerValues(revised, prompt);
289
+ const protectedFields = [], disputes = [];
290
+ let acceptedChanges = 0, refined = 0;
291
+ if (before.json && after.json) {
292
+ const revisedByPath = new Map(after.values.map(item => [item.path, item]));
293
+ const restore = new Map();
294
+ const document = jsonDocument(revised);
295
+ let parsedRevised;
296
+ try {
297
+ parsedRevised = parseKeepingTokens(document);
298
+ }
299
+ catch {
300
+ parsedRevised = undefined;
301
+ }
302
+ for (const item of before.values) {
303
+ const next = revisedByPath.get(item.path);
304
+ if (next && sameValue(item, next)) {
305
+ const corrected = receiptAtReviewPrecision(item, next, results);
306
+ if (corrected !== undefined) {
307
+ protectedFields.push({ field: item.path, drafted: item.token, revised: next.token, backing: backingOf(item, results, prompt, true) });
308
+ restore.set(item.path, corrected);
309
+ refined++;
310
+ }
311
+ else if (next.token !== item.token)
312
+ refined++;
313
+ continue;
314
+ }
315
+ const nextBacking = next ? reviewBacking(item, next, results, prompt) : undefined;
316
+ if (next && nextBacking) {
317
+ acceptedChanges++;
318
+ continue;
319
+ }
320
+ const backing = backingOf(item, results, prompt);
321
+ if (next && !backing) {
322
+ acceptedChanges++;
323
+ continue;
324
+ }
325
+ const dispute = { field: item.path, drafted: item.token, revised: next?.token ?? null, backing };
326
+ if (backing?.kind === "code")
327
+ protectedFields.push(dispute);
328
+ else
329
+ disputes.push(dispute);
330
+ restore.set(item.path, item.token);
331
+ }
332
+ if (!restore.size)
333
+ return { verdict: "accept", answer: revised, protectedFields, disputes, acceptedChanges };
334
+ if (!acceptedChanges && !refined || parsedRevised === undefined)
335
+ return { verdict: "keep", answer: draft, protectedFields, disputes, acceptedChanges };
336
+ // Restore drafted tokens in the review's document, path by path.
337
+ const setPath = (root, path, token) => {
338
+ const parts = [...path.matchAll(/([^.[\]]+)|\[(\d+)\]/g)].map(match => match[1] ?? Number(match[2]));
339
+ let node = root;
340
+ for (const part of parts.slice(0, -1)) {
341
+ node = node?.[part];
342
+ if (!node || typeof node !== "object")
343
+ return false;
344
+ }
345
+ const last = parts.at(-1);
346
+ if (last === undefined || !node || typeof node !== "object")
347
+ return false;
348
+ node[last] = `${TOKEN_MARK}${token}`;
349
+ return true;
350
+ };
351
+ for (const [path, token] of restore)
352
+ if (!setPath(parsedRevised, path, token))
353
+ return { verdict: "keep", answer: draft, protectedFields, disputes, acceptedChanges };
354
+ const pretty = /\n/.test(document) ? 2 : undefined;
355
+ const rendered = JSON.stringify(parsedRevised, (_, value) => value, pretty).replace(new RegExp(`"${TOKEN_MARK.replace("\u0000", "\\\\u0000")}(${NUMBER_SOURCE})"`, "g"), "$1");
356
+ const answer = revised.trim() === document ? rendered : revised.replace(document, rendered);
357
+ return { verdict: "merge", answer, protectedFields, disputes, acceptedChanges };
358
+ }
359
+ // Prose: values cannot be paired by field. A drafted value the review dropped
360
+ // is contested unless one of the review's new values is itself backed.
361
+ const introduced = after.values.filter(next => !before.values.some(item => sameValue(item, next)));
362
+ const introducedBacked = introduced.some(next => backingOf(next, results, prompt, true));
363
+ for (const item of before.values) {
364
+ const kept = after.values.find(next => sameValue(item, next));
365
+ // Extra places the receipts contradict are not a kept value (prose cannot be merged: keep the draft).
366
+ if (kept && receiptAtReviewPrecision(item, kept, results) !== undefined) {
367
+ protectedFields.push({ field: item.key ?? item.path, drafted: item.token, revised: kept.token, backing: backingOf(item, results, prompt, true) });
368
+ continue;
369
+ }
370
+ if (kept)
371
+ continue;
372
+ const backing = backingOf(item, results, prompt);
373
+ if (!backing || introducedBacked) {
374
+ acceptedChanges++;
375
+ continue;
376
+ }
377
+ const dispute = { field: item.key ?? item.path, drafted: item.token, revised: introduced.map(next => next.token).join(", ") || null, backing };
378
+ if (backing.kind === "code")
379
+ protectedFields.push(dispute);
380
+ else
381
+ disputes.push(dispute);
382
+ }
383
+ const contested = protectedFields.length + disputes.length;
384
+ return { verdict: contested ? "keep" : "accept", answer: contested ? draft : revised, protectedFields, disputes, acceptedChanges };
385
+ };
386
+ const COMPUTE_WORDS = /\b(?:simulat|enumerat|comput|calculat|estimat|tally|probabilit|throughput|utili[sz]|round(?:ed)? to|decimal places?|significant (?:figures|digits))\w*|\bsolve for\b|\bhow (?:many|much)\b/i;
387
+ /** Words that ask for a number only when a numeric object follows: "the expected
388
+ * number of", "count the misses", "mean waiting time", not "what do you mean". */
389
+ const OBJECT_WORDS = /\b(?:mean|expect\w*|determin\w*|count\w*|averag\w*|varian\w*|evaluat\w*)\s+(?:(?:the|a|an|of|each|all|total)\s+){0,3}(?:\w+\s+){0,2}?(?:numbers?|values?|totals?|sums?|rates?|times?|costs?|lengths?|sizes?|counts?|probabilit\w*|waits?|waiting|delays?|amounts?|percentages?|fractions?|ratios?|hits?|misses|events?|steps?|orderings?)\b/i;
390
+ const NO_TOOLS = /\b(?:without (?:using )?(?:any )?(?:tools?|a calculator|code)|(?:do not|don't|never) (?:use|run|call) (?:any )?(?:tools?|code|a calculator)|no tools|by hand|mentally|in your head|from memory)\b/i;
391
+ /** A request whose answer is a computed quantity over several stated inputs (an
392
+ * event trace to simulate, orderings to count, a recurrence): one model call
393
+ * cannot work it out reliably in its head. In cycle 7 a 22-event banker's
394
+ * algorithm trace was answered in 24 seconds with counts that could not add up. */
395
+ export const requestNeedsComputation = (prompt) => (COMPUTE_WORDS.test(prompt) || OBJECT_WORDS.test(prompt)) && !NO_TOOLS.test(prompt) && (withoutNonQuantities(prompt).match(NUMBER) ?? []).length >= 4;
396
+ const VERSIONED = String.raw `(?:TLS|SSL|SSH|HTTP|IPv|TCP|QUIC|OAuth|USB|PCIe|DDR|Wi-?Fi|Bluetooth|Python|Node(?:\.js)?|Java|Go|Rust|Ruby|PHP|Perl|Ubuntu|Debian|RHEL|CentOS|Fedora|Alpine|Windows|macOS|iOS|Android|Postgres(?:QL)?|MySQL|MariaDB|SQLite|Redis|Kafka|Kubernetes|Docker|Chrome|Firefox|Safari|Edge|React|Angular|Vue|Django|Rails|Spring|Spark|Hadoop|Elasticsearch|MongoDB|Cassandra|Nginx|Apache|OpenSSL|Linux|v)`;
397
+ const WHOLE_VERSIONED = String.raw `(?:HTTP|IPv|USB|DDR|PCIe|Java|Windows|iOS|Android|Python)`;
398
+ const MONTH = String.raw `(?:Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Sept|Oct|Nov|Dec)[a-z]*\.?`;
399
+ const NON_QUANTITIES = [
400
+ /\b\d{4}-\d{1,2}-\d{1,2}(?:[T ]\d{1,2}:\d{2}(?::\d{2})?)?\b/g, /\b\d{1,2}[/.]\d{1,2}[/.]\d{2,4}\b/g, /\b\d{1,2}:\d{2}(?::\d{2})?\b/g,
401
+ new RegExp(String.raw `\b${MONTH}\s+\d{1,2}(?:st|nd|rd|th)?(?:,?\s+\d{4})?\b`, "g"), new RegExp(String.raw `\b\d{1,2}(?:st|nd|rd|th)?\s+${MONTH}(?:\s+\d{4})?\b`, "g"),
402
+ /\b(?:in|since|by|until|from|before|after|during)\s+(?:19|20)\d{2}\b/gi, /\b\d+(?:st|nd|rd|th)\b/gi,
403
+ /\bv(?:ersion\s*)?\d+(?:\.\d+)*\b/gi, /\b\d+\.\d+\.\d+(?:\.\d+)*\b/g,
404
+ // Named products with version-shaped numbers: TLS 1.2 or 1.3, Python 3.12, Ubuntu 24.04. Only a
405
+ // name, never any capitalised word: "MTBF 2000", "SLA 99.9" and "CPU 4, 8 and 16" are quantities.
406
+ new RegExp(String.raw `\b${VERSIONED}(?:\/|-|\s)?\d+\.\d+(?:\.\d+)*(?:\s*(?:,|or|and|vs\.?|versus|to|\/)\s*\d+\.\d+(?:\.\d+)*)*`, "g"),
407
+ // Products whose versions are whole numbers: HTTP/2 vs 3, IPv6, Java 21, Windows 11.
408
+ new RegExp(String.raw `\b${WHOLE_VERSIONED}(?:\/|-|\s)?\d+(?:\.\d+)*(?:\s*(?:,|or|and|vs\.?|versus|to|\/)\s*\d+(?:\.\d+)*)*`, "g"),
409
+ ];
410
+ /** Text with dates, times of day, ordinals and version numbers blanked out: they are labels, not quantities. */
411
+ export const withoutNonQuantities = (text) => NON_QUANTITIES.reduce((rest, pattern) => rest.replace(pattern, match => " ".repeat(match.length)), text);
@@ -39,4 +39,17 @@ export declare const transportOutage: (error: unknown) => boolean;
39
39
  * slower than those rates is waited for longer each time instead of being cut
40
40
  * off at the same point for ever. */
41
41
  export declare const modelStallAllowanceMs: (inputTokens: number, maxOutputTokens: number, longestModelMs: number, stalledAttempts?: number) => number;
42
+ /** How long a request that is streaming its generation may go without
43
+ * producing anything more before it counts as stalled. Wall-clock time alone
44
+ * cannot tell a live long generation from a lost request, so the full
45
+ * allowance above stays in force until the first generated chunk. Once output
46
+ * arrives the timer is reset by every chunk, and only a stream that stops for
47
+ * this long is abandoned: two minutes, or three times the slowest answered
48
+ * request when longer, never more than the full allowance. A lost request
49
+ * that was streaming is then given up in minutes instead of after the full
50
+ * allowance (ten minutes or more), while a live generation is never cut
51
+ * however long it runs. */
52
+ export declare const modelStreamGapAllowanceMs: (fullAllowanceMs: number, longestModelMs: number) => number;
53
+ /** The shortest silence after which a streaming request counts as stalled. */
54
+ export declare const STREAM_STALL_GAP_MS = 120000;
42
55
  //# sourceMappingURL=OutageWait.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"OutageWait.d.ts","sourceRoot":"","sources":["../../src/runtime/OutageWait.ts"],"names":[],"mappings":"AACA,0GAA0G;AAC1G,eAAO,MAAM,2BAA2B,UAA4D,CAAC;AACrG;kDACkD;AAClD,eAAO,MAAM,aAAa,GAAI,SAAQ,MAAM,GAAG,SAAmD,KAAG,MAAM,EAK1G,CAAC;AACF;;;;;+DAK+D;AAC/D,eAAO,MAAM,oBAAoB,QAAgB,CAAC;AAClD;4EAC4E;AAC5E,eAAO,MAAM,0BAA0B,QAAS,CAAC;AACjD;;;oFAGoF;AACpF,eAAO,MAAM,YAAY,GAAI,SAAS,MAAM,EAAE,oBAAsB,EAAE,SAAQ,MAAM,GAAG,SAAmD,KAAG,MAAM,GAAG,SAWrJ,CAAC;AAEF;iFACiF;AACjF,eAAO,MAAM,kBAAkB,GAAI,SAAS,MAAM,EAAE,aAAa,MAAM,EAAE,WAAW,MAAM,EAAE,mBAAmB,MAAM,EAAE,UAAU,OAAO,EAAE,2BAAgD,KAAG,MAAM,GAAG,SAYrM,CAAC;AAKF;;;6EAG6E;AAC7E,eAAO,MAAM,eAAe,GAAI,OAAO,OAAO,KAAG,OAShD,CAAC;AAEF;;;;;;;;;;;qCAWqC;AACrC,eAAO,MAAM,qBAAqB,GAAI,aAAa,MAAM,EAAE,iBAAiB,MAAM,EAAE,gBAAgB,MAAM,EAAE,wBAAmB,KAAG,MAIjI,CAAC"}
1
+ {"version":3,"file":"OutageWait.d.ts","sourceRoot":"","sources":["../../src/runtime/OutageWait.ts"],"names":[],"mappings":"AACA,0GAA0G;AAC1G,eAAO,MAAM,2BAA2B,UAA4D,CAAC;AACrG;kDACkD;AAClD,eAAO,MAAM,aAAa,GAAI,SAAQ,MAAM,GAAG,SAAmD,KAAG,MAAM,EAK1G,CAAC;AACF;;;;;+DAK+D;AAC/D,eAAO,MAAM,oBAAoB,QAAgB,CAAC;AAClD;4EAC4E;AAC5E,eAAO,MAAM,0BAA0B,QAAS,CAAC;AACjD;;;oFAGoF;AACpF,eAAO,MAAM,YAAY,GAAI,SAAS,MAAM,EAAE,oBAAsB,EAAE,SAAQ,MAAM,GAAG,SAAmD,KAAG,MAAM,GAAG,SAWrJ,CAAC;AAEF;iFACiF;AACjF,eAAO,MAAM,kBAAkB,GAAI,SAAS,MAAM,EAAE,aAAa,MAAM,EAAE,WAAW,MAAM,EAAE,mBAAmB,MAAM,EAAE,UAAU,OAAO,EAAE,2BAAgD,KAAG,MAAM,GAAG,SAYrM,CAAC;AAKF;;;6EAG6E;AAC7E,eAAO,MAAM,eAAe,GAAI,OAAO,OAAO,KAAG,OAShD,CAAC;AAEF;;;;;;;;;;;qCAWqC;AACrC,eAAO,MAAM,qBAAqB,GAAI,aAAa,MAAM,EAAE,iBAAiB,MAAM,EAAE,gBAAgB,MAAM,EAAE,wBAAmB,KAAG,MAIjI,CAAC;AAEF;;;;;;;;;2BAS2B;AAC3B,eAAO,MAAM,yBAAyB,GAAI,iBAAiB,MAAM,EAAE,gBAAgB,MAAM,KAAG,MACd,CAAC;AAC/E,8EAA8E;AAC9E,eAAO,MAAM,mBAAmB,SAAU,CAAC"}
@@ -91,3 +91,16 @@ export const modelStallAllowanceMs = (inputTokens, maxOutputTokens, longestModel
91
91
  const base = Math.max(60000, Math.min(Math.max(600000, longestModelMs * 4), ceiling));
92
92
  return Math.min(base * 2 ** Math.min(Math.max(0, stalledAttempts), 6), Math.max(base, 3600000));
93
93
  };
94
+ /** How long a request that is streaming its generation may go without
95
+ * producing anything more before it counts as stalled. Wall-clock time alone
96
+ * cannot tell a live long generation from a lost request, so the full
97
+ * allowance above stays in force until the first generated chunk. Once output
98
+ * arrives the timer is reset by every chunk, and only a stream that stops for
99
+ * this long is abandoned: two minutes, or three times the slowest answered
100
+ * request when longer, never more than the full allowance. A lost request
101
+ * that was streaming is then given up in minutes instead of after the full
102
+ * allowance (ten minutes or more), while a live generation is never cut
103
+ * however long it runs. */
104
+ export const modelStreamGapAllowanceMs = (fullAllowanceMs, longestModelMs) => Math.min(fullAllowanceMs, Math.max(STREAM_STALL_GAP_MS, longestModelMs * 3));
105
+ /** The shortest silence after which a streaming request counts as stalled. */
106
+ export const STREAM_STALL_GAP_MS = 120000;
@@ -1 +1 @@
1
- {"version":3,"file":"ResearchEvidence.d.ts","sourceRoot":"","sources":["../../src/runtime/ResearchEvidence.ts"],"names":[],"mappings":"AAAA,MAAM,WAAW,cAAc;IAAG,MAAM,EAAE,MAAM,CAAC;IAAC,OAAO,EAAE,MAAM,CAAC;IAAC,IAAI,EAAE,MAAM,CAAC;IAAC,KAAK,CAAC,EAAE,MAAM,CAAC;IAAC,UAAU,CAAC,EAAE,MAAM,CAAC;IAAC,cAAc,CAAC,EAAE,MAAM,EAAE,CAAC;IAC9I,UAAU,CAAC,EAAE,MAAM,CAAC;IAAC,MAAM,CAAC,EAAE,MAAM,CAAC;IAAC,UAAU,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;IAAC,UAAU,CAAC,EAAE,MAAM,CAAC;CAAE;AAE1F;8EAC8E;AAC9E,wBAAgB,cAAc,CAAC,IAAI,EAAE,MAAM,EAAE,KAAK,EAAE,OAAO,EAAE,MAAM,EAAE,MAAM,GAAG,cAAc,GAAG,SAAS,CAmBvG;AAID;qEACqE;AACrE,wBAAgB,YAAY,CAAC,KAAK,EAAE,MAAM,GAAG,MAAM,EAAE,CAUpD;AAED;;;;uEAIuE;AACvE,wBAAgB,sBAAsB,CAAC,OAAO,EAAE,cAAc,EAAE,EAA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AqEpI;AAED;;;;;;8EAM8E;AAC9E,wBAAgB,cAAc,CAAC,OAAO,EAAE,cAAc,EAAE,EAAE,OAAO,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,UAAU,SAAK,GAAG,MAAM,GAAG,SAAS,CAuB9H;AAgBD;;;;wEAIwE;AACxE,wBAAgB,kBAAkB,CAAC,KAAK,EAAE,MAAM,EAAE,KAAK,SAAI,GAAG,MAAM,EAAE,CAwBrE"}
@@ -26,6 +26,16 @@ export function researchPacket(tool, input, output) {
26
26
  catch { /* Docdex may return source-labelled text instead of JSON. */ }
27
27
  return output.trim() ? { source: tool, passage: output.slice(0, 4000), tool, query } : undefined;
28
28
  }
29
+ /** A page's identity across link spellings (scheme, www., trailing slash, fragment). */
30
+ const sourceKey = (value) => {
31
+ try {
32
+ const url = new URL(value);
33
+ return `${url.host.toLowerCase().replace(/^www\./u, "")}${url.pathname.replace(/\/+$/u, "")}${url.search}`;
34
+ }
35
+ catch {
36
+ return value.trim().toLowerCase();
37
+ }
38
+ };
29
39
  const squash = (text) => text.toLowerCase().replace(/[‘’]/gu, "'").replace(/[“”]/gu, '"').replace(/[‐-―−]/gu, "-").replace(/\s+/gu, " ");
30
40
  /** Exact quotes and specific figures/identifiers in a draft: the claims an
31
41
  * audit must be able to check against the passage they came from. */
@@ -55,10 +65,50 @@ export function selectResearchEvidence(packets, request, draft, maxChars = 48000
55
65
  const overlap = [...terms].filter(term => words.has(term)).length;
56
66
  return { packet, index, score: overlap / Math.sqrt(Math.max(1, terms.size)) + (packet.query ? 1 : 0) };
57
67
  }).sort((a, b) => b.score - a.score || a.index - b.index);
68
+ // The pages the draft cites come first: for each, its passages that share
69
+ // most with the lines citing it. In cycle 7 the audit was not shown the
70
+ // passage behind a cited claim with no figure in it ("a further three
71
+ // months") and rewrote the claim as unsupported.
72
+ const anchored = [];
73
+ let anchorChars = 0;
74
+ const citing = new Map();
75
+ for (const line of draft.split(/\n+/u)) {
76
+ for (const url of line.match(/https?:\/\/[^\s<>()\[\]"'`\\]+/gu) ?? []) {
77
+ const key = sourceKey(url.replace(/[.,;:!?*]+$/u, ""));
78
+ const words = citing.get(key) ?? new Set();
79
+ for (const word of line.toLowerCase().match(/[\p{L}\p{N}_]{4,}/gu) ?? [])
80
+ words.add(word);
81
+ citing.set(key, words);
82
+ }
83
+ }
84
+ if (citing.size) {
85
+ const cited = ranked.map(value => {
86
+ const words = citing.get(sourceKey(value.packet.source));
87
+ if (!words)
88
+ return undefined;
89
+ const terms = new Set(value.packet.passage.toLowerCase().match(/[\p{L}\p{N}_]{4,}/gu) ?? []);
90
+ return { value, key: sourceKey(value.packet.source), overlap: [...words].filter(word => terms.has(word)).length };
91
+ }).filter(item => item !== undefined).sort((a, b) => b.overlap - a.overlap || a.value.index - b.value.index);
92
+ // Best passage of every cited page first, then further passages of them.
93
+ const firsts = new Set();
94
+ const order = [...cited.filter(item => !firsts.has(item.key) && firsts.add(item.key)), ...cited];
95
+ for (const { value } of order) {
96
+ if (anchored.includes(value))
97
+ continue;
98
+ const size = JSON.stringify(value.packet).length + 1;
99
+ if (anchorChars + size > maxChars * 0.35)
100
+ continue;
101
+ anchorChars += size;
102
+ anchored.push(value);
103
+ }
104
+ }
58
105
  // Greedy cover of the draft's anchors, within part of the budget.
59
- const anchors = draftAnchors(draft), uncovered = new Set(anchors), anchored = [];
106
+ const anchors = draftAnchors(draft), uncovered = new Set(anchors);
60
107
  const passages = new Map(ranked.map(value => [value.index, squash(value.packet.passage)]));
61
- let anchorChars = 0;
108
+ for (const value of anchored)
109
+ for (const anchor of [...uncovered])
110
+ if (passages.get(value.index).includes(anchor))
111
+ uncovered.delete(anchor);
62
112
  while (uncovered.size) {
63
113
  let best, bestHits = 0;
64
114
  for (const value of ranked) {
@@ -74,7 +124,7 @@ export function selectResearchEvidence(packets, request, draft, maxChars = 48000
74
124
  if (!best)
75
125
  break;
76
126
  const size = JSON.stringify(best.packet).length + 1;
77
- if (anchorChars + size > maxChars * 0.6)
127
+ if (anchorChars + size > maxChars * 0.7)
78
128
  break;
79
129
  anchorChars += size;
80
130
  anchored.push(best);
@@ -135,6 +185,18 @@ export function evidenceReport(packets, request, reason, maxSources = 30) {
135
185
  "", ...ranked.map(([source, { excerpt }], index) => `${index + 1}. ${source}\n "${excerpt}"`)].join("\n");
136
186
  }
137
187
  const OPEN_POINT = /\b(?:unverified|not (?:been )?(?:independently )?verified|unconfirmed|(?:could not|couldn't|can ?not|cannot|was unable to|were unable to|unable to|failed to|did not manage to) (?:be )?(?:independently )?(?:verif(?:y|ied)|confirm(?:ed)?|find|found|locate[d]?|access(?:ed)?|retrieved?|determined?|establish(?:ed)?|open(?:ed)?)|no (?:primary|official|direct|reliable|authoritative) (?:source|page|document|record|figure|confirmation)s? (?:was|were|has been|have been|could be) (?:found|located|retrieved|identified)|(?:was|were) not found (?:during|in) (?:this|the|my) (?:research|search|investigation|review)|remains? (?:unclear|unconfirmed|to be (?:confirmed|verified|determined))|to be (?:confirmed|determined|verified)|tbd)\b/iu;
188
+ /** A whole table cell that says the row's fact was not settled by the research. */
189
+ const GAP_CELL = /^(?:(?:still |yet )?not (?:yet )?(?:been )?(?:established|found|located|confirmed|verified|determined|identified|retrieved)(?: (?:yet|in (?:this|the) (?:research|search)|from (?:a |any )?(?:primary|official) sources?))?|unverified|unconfirmed|no (?:primary |official )?(?:source|data|figure|record)s? found|to be (?:confirmed|determined|verified)|tbd|\?+)[.!]?$/iu;
190
+ /** The row of a markdown table one of whose cells is a gap marker, as "cell — cell". */
191
+ function tableGapRow(block) {
192
+ const row = block.trim();
193
+ if (!row.startsWith("|") || /^\|[\s:|-]+\|?$/u.test(row))
194
+ return undefined;
195
+ const cells = row.replace(/^\||\|$/gu, "").split("|").map(cell => cell.replace(/\*\*|__|`/gu, "").replace(/\s+/gu, " ").trim());
196
+ if (cells.length < 2 || !cells.slice(1).some(cell => GAP_CELL.test(cell)))
197
+ return undefined;
198
+ return cells.filter(cell => cell && !/^[-–—/]+$/u.test(cell)).join(" — ").slice(0, 240);
199
+ }
138
200
  /** The points a research draft itself leaves open: the sentences or list items
139
201
  * in which it says something was not found, not verified or only alleged.
140
202
  * A draft that says so with time left has not finished its research; in cycle
@@ -144,6 +206,20 @@ export function openResearchPoints(draft, limit = 8) {
144
206
  const points = [], seen = new Set();
145
207
  for (const block of draft.split(/\n+/u)) {
146
208
  const line = block.replace(/^[\s>#*|-]+|[\s*|]+$/gu, "").replace(/\*\*/gu, "");
209
+ // A table of findings marks its gaps with a bare status cell ("Not
210
+ // established") rather than a sentence. In cycle 7 a draft with half its
211
+ // rows in that state was read as having no open points.
212
+ const gapRow = tableGapRow(block);
213
+ if (gapRow) {
214
+ const key = gapRow.toLowerCase().slice(0, 80);
215
+ if (!seen.has(key)) {
216
+ seen.add(key);
217
+ points.push(gapRow);
218
+ }
219
+ if (points.length >= limit)
220
+ return points;
221
+ continue;
222
+ }
147
223
  if (line.length < 12 || !OPEN_POINT.test(line))
148
224
  continue;
149
225
  // Only the sentences that carry the admission, not the settled ones beside them.
@@ -10,6 +10,17 @@ export interface TaskReviewAssessment {
10
10
  workspaceSnapshotHash: string;
11
11
  }
12
12
  export declare function reviewWorkspaceHash(hashes: Readonly<Record<string, string>>): string;
13
+ /** Checks of one requirement area are reviewed together, and one call reviews
14
+ * at most this many. A single call over 52 checks passed a build that omitted
15
+ * two of them; smaller portions keep each clause in view. */
16
+ export declare const REVIEW_CHECKS_PER_CALL = 8;
17
+ export declare const MAX_REVIEW_BATCHES = 64;
18
+ /** Content words of a text: identifiers are split at camelCase and
19
+ * snake_case, words are stemmed to five letters, numbers of three or more
20
+ * digits (a status code, a port, a limit) are kept, common words dropped. */
21
+ export declare const contentWords: (text: string) => Set<string>;
22
+ /** Whether a cited quotation is about the check at all: it shares a content word with it. */
23
+ export declare const sharesContent: (quote: string, reference: string) => boolean;
13
24
  /** Review one scope without loading every sibling's source into the prompt.
14
25
  * Assessments are created only by the controller after separate successful
15
26
  * reviews; the caller must fence the complete snapshot before accepting them. */
@@ -30,6 +41,17 @@ export declare function reviewTaskScope(options: {
30
41
  summary: string;
31
42
  assessments?: readonly TaskReviewAssessment[];
32
43
  authoritativeInputs?: readonly ReviewContractSource[];
44
+ /** Statements from delivered documents; whole-goal review checks each one. */
45
+ deliveredClaims?: readonly {
46
+ path: string;
47
+ text: string;
48
+ }[];
49
+ /** At most this many review portions (calls before paging and repair); the
50
+ * caller lowers it as the deadline nears. Checks that do not fit are
51
+ * returned as unreviewed, highest priority reviewed first. */
52
+ maxPortions?: number;
53
+ /** Called once per review portion, so a caller can share one budget across reviews. */
54
+ onPortion?: () => void;
33
55
  readSource: (file: string, maxChars: number) => Promise<{
34
56
  content: string;
35
57
  truncated: boolean;
@@ -1 +1 @@
1
- {"version":3,"file":"ReviewCoordinator.d.ts","sourceRoot":"","sources":["../../src/runtime/ReviewCoordinator.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,QAAQ,EAAmB,MAAM,+BAA+B,CAAC;AAC/E,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,yBAAyB,CAAC;AACxD,OAAO,EAAgD,KAAK,oBAAoB,EAAE,MAAM,qBAAqB,CAAC;AAC9G,OAAO,EAAuB,KAAK,iBAAiB,EAAE,MAAM,wBAAwB,CAAC;AACrF,OAAO,EAAiB,KAAK,gBAAgB,EAAE,KAAK,gBAAgB,EAAE,MAAM,iBAAiB,CAAC;AAI9F,MAAM,WAAW,oBAAoB;IACnC,MAAM,EAAE,MAAM,CAAC;IACf,YAAY,EAAE,MAAM,EAAE,CAAC;IACvB,WAAW,EAAE,MAAM,EAAE,CAAC;IACtB,qBAAqB,EAAE,MAAM,CAAC;CAC/B;AAED,wBAAgB,mBAAmB,CAAC,MAAM,EAAE,QAAQ,CAAC,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC,GAAG,MAAM,CAGpF;AAWD;;iFAEiF;AACjF,wBAAsB,eAAe,CAAC,OAAO,EAAE;IAC7C,QAAQ,EAAE,QAAQ,CAAC;I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