piroboros 0.0.0-stage → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (118) hide show
  1. package/CHANGELOG.md +43 -0
  2. package/LICENSE +21 -0
  3. package/NOTICE +39 -0
  4. package/README.md +140 -2
  5. package/agents/astrelia.md +31 -0
  6. package/agents/avaritia.md +31 -0
  7. package/agents/elaria.md +31 -0
  8. package/agents/nytheria.md +32 -0
  9. package/agents/raskreia.md +32 -0
  10. package/agents/samaela.md +40 -0
  11. package/agents/vaelia.md +35 -0
  12. package/agents/vesperia.md +45 -0
  13. package/bin/piroboros.mjs +17 -0
  14. package/dist/auth.js +105 -0
  15. package/dist/base.js +19 -0
  16. package/dist/chat/budget.js +87 -0
  17. package/dist/chat/compactloop.js +63 -0
  18. package/dist/chat/compactor.js +530 -0
  19. package/dist/chat/extension.js +36 -0
  20. package/dist/chat/hook.js +40 -0
  21. package/dist/chat/log.js +317 -0
  22. package/dist/chat/outbound.js +114 -0
  23. package/dist/chat/plan.js +64 -0
  24. package/dist/chat/prompt.js +115 -0
  25. package/dist/chat/status.js +37 -0
  26. package/dist/chat/stuck.js +83 -0
  27. package/dist/chat/tools.js +163 -0
  28. package/dist/chat/tree.js +73 -0
  29. package/dist/chat/turn.js +305 -0
  30. package/dist/chat/view.js +163 -0
  31. package/dist/conclave/agents.js +113 -0
  32. package/dist/conclave/pipeline.js +715 -0
  33. package/dist/conclave/report.js +43 -0
  34. package/dist/config.js +614 -0
  35. package/dist/durable.js +177 -0
  36. package/dist/guard.js +346 -0
  37. package/dist/lock.js +56 -0
  38. package/dist/main.js +348 -0
  39. package/dist/memory/akashic/api.js +121 -0
  40. package/dist/memory/akashic/confusables.js +41 -0
  41. package/dist/memory/akashic/scanner.js +67 -0
  42. package/dist/memory/akashic/snapshot.js +31 -0
  43. package/dist/memory/akashic/store.js +1254 -0
  44. package/dist/memory/akashic/tools.js +168 -0
  45. package/dist/memory/akashic/vault.js +984 -0
  46. package/dist/memory/host.js +124 -0
  47. package/dist/memory/mnemosia/adapters/akashic-memories.js +180 -0
  48. package/dist/memory/mnemosia/adapters/contract.js +219 -0
  49. package/dist/memory/mnemosia/agents.js +387 -0
  50. package/dist/memory/mnemosia/brief.js +890 -0
  51. package/dist/memory/mnemosia/claims.js +609 -0
  52. package/dist/memory/mnemosia/conflicts.js +769 -0
  53. package/dist/memory/mnemosia/escalation.js +257 -0
  54. package/dist/memory/mnemosia/feedback.js +108 -0
  55. package/dist/memory/mnemosia/filters.js +248 -0
  56. package/dist/memory/mnemosia/intent.js +221 -0
  57. package/dist/memory/mnemosia/open.js +34 -0
  58. package/dist/memory/mnemosia/orchestrator.js +926 -0
  59. package/dist/memory/mnemosia/plan.js +266 -0
  60. package/dist/memory/mnemosia/policy.js +426 -0
  61. package/dist/memory/mnemosia/progressive.js +550 -0
  62. package/dist/memory/mnemosia/provenance.js +458 -0
  63. package/dist/memory/mnemosia/qualifiers.js +428 -0
  64. package/dist/memory/mnemosia/rank.js +525 -0
  65. package/dist/memory/mnemosia/relations.js +156 -0
  66. package/dist/memory/mnemosia/requirements.js +138 -0
  67. package/dist/memory/mnemosia/rerank.js +253 -0
  68. package/dist/memory/mnemosia/retention.js +174 -0
  69. package/dist/memory/mnemosia/rollback.js +337 -0
  70. package/dist/memory/mnemosia/select.js +607 -0
  71. package/dist/memory/mnemosia/similarity.js +164 -0
  72. package/dist/memory/mnemosia/situation.js +251 -0
  73. package/dist/memory/mnemosia/task.js +418 -0
  74. package/dist/memory/mnemosia/temporal.js +136 -0
  75. package/dist/memory/mnemosia/tokens.js +66 -0
  76. package/dist/memory/mnemosia/tools.js +160 -0
  77. package/dist/memory/mnemosia/trace.js +306 -0
  78. package/dist/memory/mnemosia/types.js +298 -0
  79. package/dist/models.js +360 -0
  80. package/dist/paths.js +103 -0
  81. package/dist/redact.js +79 -0
  82. package/dist/runtime.js +378 -0
  83. package/dist/search-format.js +102 -0
  84. package/dist/search.js +351 -0
  85. package/dist/setup.js +366 -0
  86. package/dist/shell.js +110 -0
  87. package/dist/skills.js +311 -0
  88. package/dist/telemetry.js +84 -0
  89. package/dist/tui/app.js +1011 -0
  90. package/dist/tui/commands.js +121 -0
  91. package/dist/tui/keys.js +83 -0
  92. package/dist/tui/pane.js +387 -0
  93. package/dist/tui/panel.js +60 -0
  94. package/dist/tui/picker.js +25 -0
  95. package/dist/tui/sanitize.js +59 -0
  96. package/dist/tui/settings.js +198 -0
  97. package/dist/tui/setup.js +256 -0
  98. package/dist/tui/theme.js +26 -0
  99. package/dist/tui/thinking/parse.js +1094 -0
  100. package/dist/tui/thinking/select.js +86 -0
  101. package/dist/tui/thinking/state.js +137 -0
  102. package/dist/tui/thinking/types.js +3 -0
  103. package/dist/tui/thinking/view.js +74 -0
  104. package/dist/tui/viewport.js +208 -0
  105. package/dist/undo.js +258 -0
  106. package/dist/web.js +933 -0
  107. package/docs/conclave.md +21 -0
  108. package/docs/configuration.md +48 -0
  109. package/docs/development.md +25 -0
  110. package/docs/interface.md +33 -0
  111. package/docs/memory.md +11 -0
  112. package/docs/privacy.md +13 -0
  113. package/docs/tools.md +20 -0
  114. package/docs/web.md +38 -0
  115. package/models.json.example +34 -0
  116. package/package.json +76 -4
  117. package/settings.json.example +29 -0
  118. package/skills/conclave/SKILL.md +76 -0
@@ -0,0 +1,550 @@
1
+ // Ported from mnemosia/progressive.ts @ f0a8ad4 (MIT; see NOTICE)
2
+ /**
3
+ * Phase C — progressive retrieval with bounded multi-round evaluation.
4
+ *
5
+ * Phase B derives knowledge requirements but never spends a second query on them; this module
6
+ * consumes them. The shape is deliberately small: run the standard single-pass pipeline, ask what it
7
+ * failed to cover, and — only while a bounded policy says it is worth it — re-run with gap terms
8
+ * derived from the uncovered requirements, merging what comes back into what is already held.
9
+ *
10
+ * **Every number here is a deterministic approximation, and says so.** `estimateInformationGain` is
11
+ * not information theory: it is shingle-overlap penalty plus token novelty, the same similarity
12
+ * vocabulary `select.ts` already uses, so a round that re-retrieves what earlier rounds already hold
13
+ * scores zero and stops the loop. Nothing here calls a model, reads a clock of its own, or mutates a
14
+ * store — given identical orchestration results, every function returns an identical value, which is
15
+ * what lets `runProgressiveRetrieval` sit inside the §16 determinism gate rather than beside it.
16
+ *
17
+ * **The loop is bounded by policy, not by hope.** It stops on the first of: sufficient evidence,
18
+ * no additional information gain, budget exhausted in selection, a deadline gap reported by the
19
+ * underlying run, a source returning nothing new, an authorization or clarification early exit — or
20
+ * simply running out of rounds. A maxRounds cap reached without any named reason fires is recorded
21
+ * as a stop with no reason at all rather than dressed up as one of the seven: "the caller's bound"
22
+ * is honest, and inventing a diagnosis would not be.
23
+ */
24
+ import { normalizeClaimText } from "./claims.js";
25
+ import { shingleSet, tokenSet } from "./similarity.js";
26
+ import { edgesFrom } from "./provenance.js";
27
+ /* ------------------------------------------------------------------------------------------------
28
+ * Types
29
+ * ---------------------------------------------------------------------------------------------- */
30
+ export const RETRIEVAL_STOP_REASONS = ["SUFFICIENT_EVIDENCE", "SUFFICIENT_WITH_CAVEATS", "NO_ADDITIONAL_INFORMATION_GAIN", "BUDGET_EXHAUSTED", "DEADLINE_REACHED", "SOURCE_EXHAUSTED", "AUTHORIZATION_BLOCKED", "CLARIFICATION_REQUIRED"];
31
+ /* ------------------------------------------------------------------------------------------------
32
+ * Coverage
33
+ * ---------------------------------------------------------------------------------------------- */
34
+ /** Words too generic to count as category evidence on their own. */
35
+ const CATEGORY_STOP_WORDS = new Set(["the", "and", "for", "with", "evidence", "state"]);
36
+ /**
37
+ * The significant words of a requirement category, normalized the way claims are.
38
+ *
39
+ * `"open-work-state"` → `["open", "work", "state"]`; `"discriminating-evidence:h1"` drops both the
40
+ * hypothesis id fragment and the generic head noun. These are the weak-match vocabulary: a selected
41
+ * item sharing one of them *may* be about the requirement, which is worth a `partial`, never a
42
+ * `sufficient`.
43
+ */
44
+ function categoryWords(category) {
45
+ return normalizeClaimText(category.replace(/:/gu, " "))
46
+ .split(" ")
47
+ .filter((word) => word.length >= 3 && !CATEGORY_STOP_WORDS.has(word));
48
+ }
49
+ function wordBoundaryPatterns(hints) {
50
+ // Word-boundary match, not substring: normalized text has punctuation replaced by spaces
51
+ // (claims.ts normalizeClaimText), so `\b` is exact token equality for single-word hints and
52
+ // phrase-with-boundaries for multi-word ones — "stated" must not match the hint "state".
53
+ return hints.map((hint) => new RegExp(`\\b${hint.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}\\b`));
54
+ }
55
+ /**
56
+ * Maps each requirement to how well the selected items address it.
57
+ *
58
+ * Three deterministic tiers, in order of strength:
59
+ *
60
+ * - **sufficient** — some item's text contains one of the requirement's own `queryHints`. The hints
61
+ * are the vocabulary Phase B chose for retrieving against this requirement; finding them in
62
+ * selected text is the strongest cheap signal that the requirement was addressed.
63
+ * - **partial** — no hint matched, but some item shares a significant category word ("work" for
64
+ * `open-work-state`). Related material, not clearly the requirement.
65
+ * - **insufficient** — nothing selected even shares vocabulary with it.
66
+ *
67
+ * This is keyword overlap, not semantics; it will under-credit an item that answers a requirement in
68
+ * different words. That bias is the safe direction for a retrieval loop: it may spend one extra
69
+ * round, but it will not declare victory on a mismatch.
70
+ */
71
+ export function evaluateCoverage(requirements, selectedItems) {
72
+ const coverage = {};
73
+ const texts = selectedItems.map((entry) => normalizeClaimText(entry.item.text));
74
+ for (const requirement of requirements) {
75
+ let level = "insufficient";
76
+ const hints = (requirement.queryHints ?? []).map((hint) => hint.toLowerCase()).filter((hint) => hint.length > 0);
77
+ const hintPatterns = wordBoundaryPatterns(hints);
78
+ for (const text of texts) {
79
+ if (hintPatterns.some((pattern) => pattern.test(text))) {
80
+ level = "sufficient";
81
+ break;
82
+ }
83
+ }
84
+ if (level === "insufficient") {
85
+ const words = categoryWords(requirement.category);
86
+ for (const text of texts) {
87
+ if (words.some((word) => text.split(" ").includes(word))) {
88
+ level = "partial";
89
+ break;
90
+ }
91
+ }
92
+ }
93
+ coverage[requirement.category] = level;
94
+ }
95
+ return coverage;
96
+ }
97
+ /* ------------------------------------------------------------------------------------------------
98
+ * Information gain
99
+ * ---------------------------------------------------------------------------------------------- */
100
+ /** Shingle width for gain estimation — the same 3-token window selection's redundancy penalty uses. */
101
+ export const INFO_GAIN_SHINGLE_SIZE = 3;
102
+ /** Weight of shingle novelty vs single-token novelty in the blended score. */
103
+ const SHINGLE_WEIGHT = 0.7;
104
+ /**
105
+ * A deterministic *approximation* of the information `newText` adds beyond `existingTexts`, in [0, 1].
106
+ *
107
+ * Not information theory, and not claimed to be: true gain needs a semantic model of what the reader
108
+ * already knows. What is computable cheaply and deterministically is lexical novelty:
109
+ *
110
+ * ```
111
+ * gain ≈ 0.7 · |new shingles − seen shingles| / |new shingles|
112
+ * + 0.3 · |new tokens − seen tokens| / |new tokens|
113
+ * ```
114
+ *
115
+ * over the same normalized text and 3-token shingles selection uses. The blend exists because
116
+ * shingles alone under-credit genuinely new sentences built from known vocabulary (a new fact about
117
+ * a familiar subject), while tokens alone over-credit paraphrase; the weighting is fixed here so a
118
+ * change is a diff to two constants rather than to a formula. Text fully contained in the existing
119
+ * set scores exactly 0 — which is the property the stop policy depends on. Empty input scores 0.
120
+ */
121
+ export function estimateInformationGain(newText, existingTexts) {
122
+ const normalizedNew = normalizeClaimText(newText);
123
+ const newShingles = shingleSet(normalizedNew, INFO_GAIN_SHINGLE_SIZE);
124
+ const newTokens = tokenSet(normalizedNew);
125
+ if (newShingles.size === 0 && newTokens.size === 0)
126
+ return 0;
127
+ const seenShingles = new Set();
128
+ const seenTokens = new Set();
129
+ for (const existing of existingTexts) {
130
+ const normalized = normalizeClaimText(existing);
131
+ for (const shingle of shingleSet(normalized, INFO_GAIN_SHINGLE_SIZE))
132
+ seenShingles.add(shingle);
133
+ for (const token of tokenSet(normalized))
134
+ seenTokens.add(token);
135
+ }
136
+ let novelShingles = 0;
137
+ for (const shingle of newShingles)
138
+ if (!seenShingles.has(shingle))
139
+ novelShingles += 1;
140
+ let novelTokens = 0;
141
+ for (const token of newTokens)
142
+ if (!seenTokens.has(token))
143
+ novelTokens += 1;
144
+ const shingleNovelty = newShingles.size === 0 ? 0 : novelShingles / newShingles.size;
145
+ const tokenNovelty = newTokens.size === 0 ? 0 : novelTokens / newTokens.size;
146
+ return Math.min(1, Math.max(0, SHINGLE_WEIGHT * shingleNovelty + (1 - SHINGLE_WEIGHT) * tokenNovelty));
147
+ }
148
+ /* ------------------------------------------------------------------------------------------------
149
+ * Sufficiency
150
+ * ---------------------------------------------------------------------------------------------- */
151
+ const STATUS_RANK = { insufficient: 0, sufficient_with_caveats: 1, sufficient: 2 };
152
+ /**
153
+ * Turns coverage plus the run's conflicts into a sufficiency verdict.
154
+ *
155
+ * - all requirements `sufficient` → `sufficient`;
156
+ * - any **high-priority** requirement `insufficient` → `insufficient` (risk high);
157
+ * - otherwise → `sufficient_with_caveats` (partials remain, low-priority holes remain, or unresolved
158
+ * conflicts stand), risk medium.
159
+ *
160
+ * With no requirements there is nothing to be insufficient about: the report reads `sufficient`,
161
+ * because a task that derived no knowledge requirements cannot fail coverage.
162
+ */
163
+ export function evaluateSufficiency(requirements, selectedItems, conflicts) {
164
+ const coverage = evaluateCoverage(requirements, selectedItems);
165
+ const strongest = [];
166
+ const gaps = [];
167
+ let anyPartial = false;
168
+ let highInsufficient = false;
169
+ for (const requirement of requirements) {
170
+ const level = coverage[requirement.category] ?? "not_required";
171
+ if (level === "sufficient")
172
+ continue;
173
+ gaps.push(requirement.requirementId);
174
+ if (level === "partial")
175
+ anyPartial = true;
176
+ if (level === "insufficient" && requirement.priority === "high")
177
+ highInsufficient = true;
178
+ }
179
+ // Strongest evidence: the claim ids behind items that carried a strong (hint) match, deduplicated
180
+ // and sorted so the report serializes identically across runs (§16). Word-boundary matching, same
181
+ // as evaluateCoverage — a coincidental substring ("state" inside "stated") must not credit evidence.
182
+ const hintSet = new Set(requirements.flatMap((requirement) => (requirement.queryHints ?? []).map((hint) => hint.toLowerCase())));
183
+ const patterns = wordBoundaryPatterns([...hintSet]);
184
+ for (const item of selectedItems) {
185
+ const text = normalizeClaimText(item.item.text);
186
+ if (patterns.some((pattern) => pattern.test(text)))
187
+ strongest.push(...item.item.claimIds);
188
+ }
189
+ strongest.sort();
190
+ const contradictionIds = new Set();
191
+ if (conflicts !== null) {
192
+ for (const record of conflicts.conflicts)
193
+ if (record.unresolved)
194
+ for (const claimId of record.claimIds)
195
+ contradictionIds.add(claimId);
196
+ }
197
+ const contradictions = [...contradictionIds].sort();
198
+ const overall_status = requirements.length === 0 || gaps.length === 0 ? "sufficient" : highInsufficient ? "insufficient" : "sufficient_with_caveats";
199
+ const caveats = anyPartial || contradictions.length > 0;
200
+ const risk_of_proceeding = highInsufficient ? "high" : caveats || overall_status === "sufficient_with_caveats" ? "medium" : "low";
201
+ let recommended_action;
202
+ if (overall_status === "sufficient")
203
+ recommended_action = "proceed: every derived knowledge requirement is covered by the selected context";
204
+ else if (highInsufficient)
205
+ recommended_action = `stop or clarify first: ${gaps.length} requirement(s) uncovered including high-priority ones (${gaps.join(", ")})`;
206
+ else
207
+ recommended_action = caveats ? `proceed with care: ${gaps.length} requirement(s) partially covered (${gaps.join(", ")})${contradictions.length > 0 ? ` and ${contradictions.length} unresolved conflict participant(s)` : ""}` : `consider another retrieval round for ${gaps.length} low-priority gap(s)`;
208
+ return {
209
+ overall_status,
210
+ coverage,
211
+ strongest_evidence: strongest,
212
+ contradictions,
213
+ unresolved_gaps: gaps.sort(),
214
+ risk_of_proceeding,
215
+ recommended_action,
216
+ // Filled by the caller that knows how many rounds ran and what they cost; a bare evaluation
217
+ // has neither number to report.
218
+ rounds_completed: 0,
219
+ total_tokens_spent: 0,
220
+ };
221
+ }
222
+ /* ------------------------------------------------------------------------------------------------
223
+ * Gap terms
224
+ * ---------------------------------------------------------------------------------------------- */
225
+ /**
226
+ * Query terms for the next round, derived from whatever coverage still lacks.
227
+ *
228
+ * **Why OR groups and not a flat AND-conjunction.** The original derivation returned at most four
229
+ * terms that `plan.ts` would have ANDed inside a narrow query — under FTS5's default operator every
230
+ * extra term is a hard filter, so a fourth term the corpus does not contain zeroes the result set
231
+ * and the round structurally cannot find anything new. The fix is disjunction, in two places:
232
+ *
233
+ * 1. **OR groups of at most two terms** (`MAX_TERMS_PER_GAP_GROUP`). One group per uncovered
234
+ * requirement, pairing its own targeted `queryHints` with its category words — the two halves of
235
+ * one requirement's vocabulary, either of which matching is evidence about that requirement.
236
+ * Today every group lands flattened into the curated any-match set (already disjunctive), so the
237
+ * grouping is documentation plus a seam; when spec Stage 4's source sequencing arrives, each
238
+ * group maps onto one query against the requirement's own `sourcePreference` without changing
239
+ * this function's contract.
240
+ * 2. **Corpus-vocabulary expansion** (`corpusTexts`). Hints are what Phase B guessed; the words the
241
+ * corpus actually uses are better recall material. Any sentence of an already-retrieved claim
242
+ * that contains one of an uncovered requirement's category words contributes its other
243
+ * significant tokens as related terms — co-occurrence is the cheapest deterministic proxy for
244
+ * relatedness, drawn from text this run has already paid to read.
245
+ *
246
+ * Bounded: at most `MAX_GAP_GROUPS` groups. Broader-match fallback is structural rather than coded:
247
+ * single-term groups are already the broadest match available short of `plan.ts`'s rejected
248
+ * unbounded recency scan, and a round whose narrow query returns empty still leaves the next
249
+ * group's terms free to match alone inside the any-match set.
250
+ */
251
+ export const MAX_TERMS_PER_GAP_GROUP = 2;
252
+ export const MAX_GAP_GROUPS = 4;
253
+ export function deriveGapTerms(requirements, coverage, corpusTexts = []) {
254
+ const groups = [];
255
+ const seen = new Set();
256
+ const addTerm = (term) => {
257
+ const normalized = term.trim().toLowerCase();
258
+ if (normalized.length < 3 || seen.has(normalized))
259
+ return false;
260
+ seen.add(normalized);
261
+ return true;
262
+ };
263
+ // 1. Direct vocabulary: hints first, then category words, grouped per uncovered requirement.
264
+ const uncoveredWords = new Set();
265
+ for (const requirement of requirements) {
266
+ if (groups.length >= MAX_GAP_GROUPS)
267
+ break;
268
+ if ((coverage[requirement.category] ?? "not_required") === "sufficient")
269
+ continue;
270
+ const words = categoryWords(requirement.category);
271
+ for (const word of words)
272
+ uncoveredWords.add(word);
273
+ for (const hint of requirement.queryHints ?? [])
274
+ if (hint.trim().toLowerCase().length >= 4)
275
+ uncoveredWords.add(hint.trim().toLowerCase());
276
+ const group = [];
277
+ for (const term of [...(requirement.queryHints ?? []), ...words]) {
278
+ if (group.length >= MAX_TERMS_PER_GAP_GROUP)
279
+ break;
280
+ if (addTerm(term))
281
+ group.push(term.trim().toLowerCase());
282
+ }
283
+ if (group.length > 0)
284
+ groups.push(group);
285
+ }
286
+ // 2. Related terms from the corpus's own vocabulary: sentences that talk about an uncovered
287
+ // requirement contribute their other significant words as single-term (broadest) groups.
288
+ // Sentence qualification uses prefix matching in either direction so "failure" catches
289
+ // "failures" and vice versa — exact-token equality would miss morphological variants of the
290
+ // very vocabulary the requirement is phrased in.
291
+ if (groups.length < MAX_GAP_GROUPS && uncoveredWords.size > 0) {
292
+ const relates = (word) => [...uncoveredWords].some((mine) => word.startsWith(mine) || mine.startsWith(word));
293
+ for (const text of corpusTexts) {
294
+ if (groups.length >= MAX_GAP_GROUPS)
295
+ break;
296
+ for (const sentence of normalizeClaimText(text).split(/[.;\n]/)) {
297
+ if (groups.length >= MAX_GAP_GROUPS)
298
+ break;
299
+ const words = sentence.split(" ").filter((word) => word.length >= 4);
300
+ if (!words.some(relates))
301
+ continue;
302
+ for (const word of words) {
303
+ if (groups.length >= MAX_GAP_GROUPS)
304
+ break;
305
+ if (relates(word))
306
+ continue;
307
+ // One related word per group: it stands alone, so a miss costs nothing.
308
+ if (addTerm(word))
309
+ groups.push([word]);
310
+ }
311
+ }
312
+ }
313
+ }
314
+ return groups;
315
+ }
316
+ /* ------------------------------------------------------------------------------------------------
317
+ * Phase D — bounded graph traversal between rounds
318
+ * ---------------------------------------------------------------------------------------------- */
319
+ /**
320
+ * The relations a between-round walk may follow. `SUPERSEDES` is deliberately absent: a retired claim
321
+ * is by definition not fresh evidence, and walking into it would re-retrieve exactly what the corpus
322
+ * already moved past.
323
+ */
324
+ export const TRAVERSAL_RELATIONS = ["SUPPORTS", "CONTRADICTS", "QUALIFIES", "TEMPORAL_BOUND"];
325
+ const TRAVERSAL_RELATION_SET = new Set(TRAVERSAL_RELATIONS);
326
+ /** How many of the previous round's selected claims may act as traversal seeds, at most. */
327
+ export const TRAVERSAL_SEED_CAP = 8;
328
+ /** Grounding states whose targets must not be treated as evidence (`provenance.ts`'s own vocabulary). */
329
+ const UNGROUNDED_STATES = new Set(["refs_absent", "session_absent", "refs_unresolved", "integrity_failed"]);
330
+ /**
331
+ * One-hop walk over the provenance graph from the round's selected claims.
332
+ *
333
+ * Seeds are the selection items ordered by utility descending then itemId ascending — the same total
334
+ * order selection itself tie-breaks with — capped at `TRAVERSAL_SEED_CAP`. From each seed's claims,
335
+ * every edge whose relation is in `TRAVERSAL_RELATIONS` and whose target is a *claim* contributes
336
+ * that target once; artifact targets are terminal (a document is not a term source) and ungrounded
337
+ * targets are skipped, because an unreachable summary is not evidence a next round can build on.
338
+ * Targets already seen in earlier rounds are dropped, so the walk can only ever propose new material.
339
+ * Deterministic throughout: same graph, same selection, same seen set → same list.
340
+ */
341
+ export function collectTraversalTargets(graph, selectedItems, seenClaimIds) {
342
+ if (graph === null || graph === undefined || !Array.isArray(graph.edges))
343
+ return [];
344
+ const seeds = [...selectedItems]
345
+ .sort((a, b) => b.candidate.score.utility - a.candidate.score.utility || (a.item.itemId < b.item.itemId ? -1 : a.item.itemId > b.item.itemId ? 1 : 0))
346
+ .slice(0, TRAVERSAL_SEED_CAP);
347
+ const collected = new Set(seenClaimIds);
348
+ const targets = [];
349
+ for (const seed of seeds) {
350
+ for (const claimId of seed.item.claimIds) {
351
+ for (const edge of edgesFrom(graph, claimId)) {
352
+ if (!TRAVERSAL_RELATION_SET.has(edge.relation))
353
+ continue; // SUPERSEDES excluded as stale
354
+ if (edge.toKind !== "claim")
355
+ continue; // artifact targets are terminal
356
+ if (collected.has(edge.to))
357
+ continue;
358
+ const grounding = graph.byClaim.get(edge.to)?.grounding;
359
+ if (grounding === undefined || UNGROUNDED_STATES.has(grounding))
360
+ continue;
361
+ collected.add(edge.to);
362
+ targets.push(edge.to);
363
+ }
364
+ }
365
+ }
366
+ return targets;
367
+ }
368
+ /**
369
+ * Traversal vocabulary for the next round's curated any-match set: significant words (normalized,
370
+ * length ≥ 4, the same floor deriveGapTerms' related-term pass uses) of each grounded target claim,
371
+ * in target order, deduplicated case-insensitively against the derived gap terms and against each
372
+ * other. Empty on a zero-edge corpus, so a run that cannot traverse is byte-identical to one that
373
+ * never heard of traversal.
374
+ */
375
+ export function termsFromTargets(targets, textsByClaimId, priorTerms = []) {
376
+ const seen = new Set(priorTerms.map((term) => term.trim().toLowerCase()));
377
+ const terms = [];
378
+ for (const target of targets) {
379
+ const text = textsByClaimId.get(target);
380
+ if (text === undefined)
381
+ continue;
382
+ for (const word of normalizeClaimText(text).split(" ")) {
383
+ if (word.length < 4 || seen.has(word))
384
+ continue;
385
+ seen.add(word);
386
+ terms.push(word);
387
+ }
388
+ }
389
+ return terms;
390
+ }
391
+ /* ------------------------------------------------------------------------------------------------
392
+ * The bounded loop
393
+ * ---------------------------------------------------------------------------------------------- */
394
+ /** Below this estimated gain a further round is judged unable to add anything worth its budget. */
395
+ export const INFO_GAIN_FLOOR = 0.02;
396
+ /**
397
+ * Picks the round whose result becomes the final answer.
398
+ *
399
+ * Later rounds do not automatically win: a second round that came back *worse* (fewer sources, a
400
+ * deadline gap) must not overwrite a delivered briefing from the first. The rule is: prefer
401
+ * delivered results; among them prefer the better sufficiency status; ties go to the latest round,
402
+ * since a later equal-status round saw strictly more of the corpus. Undelivered runs are eligible
403
+ * only when nothing was ever delivered — the caller still gets the best shell available, with its
404
+ * gaps intact.
405
+ */
406
+ export function selectFinalRound(results, statuses) {
407
+ let bestRank = -1;
408
+ let index = -1;
409
+ for (let i = 0; i < results.length; i += 1) {
410
+ if (!results[i].delivered)
411
+ continue;
412
+ const rank = STATUS_RANK[statuses[i] ?? "insufficient"];
413
+ if (rank >= bestRank) {
414
+ bestRank = rank;
415
+ index = i;
416
+ }
417
+ }
418
+ // Nothing was ever delivered: the last shell, gaps intact, is still more useful than a throw.
419
+ return results[index >= 0 ? index : results.length - 1];
420
+ }
421
+ /**
422
+ * Runs bounded multi-round retrieval.
423
+ *
424
+ * Round 0 calls `orchestrateFn(0)` — the standard single pass, unchanged. Each subsequent round
425
+ * passes the previous round's gap terms **and** its Phase D traversal terms (see
426
+ * `collectTraversalTargets` and `termsFromTargets`: one hop through the provenance graph from the round's selected claims,
427
+ * never after a stop decision — the traversal is computed only where the loop continues). Selection
428
+ * items and candidate claims are merged across rounds, deduplicated by item id and claim id respectively, and sufficiency is evaluated against
429
+ * the *cumulative* merge: a later round is credited for the whole picture, not just its own slice.
430
+ *
431
+ * Stop order per round (first match wins):
432
+ *
433
+ * 1. `CLARIFICATION_REQUIRED` / `AUTHORIZATION_BLOCKED` — the run ended before evidence could help;
434
+ * 2. `SUFFICIENT_EVIDENCE` — cumulative coverage is sufficient;
435
+ * 3. `SUFFICIENT_WITH_CAVEATS` — only low-priority gaps, partials, or unresolved conflicts remain
436
+ * (locked selective doctrine: escalation is reserved for a report whose **required** evidence is
437
+ * missing, i.e. `insufficient`; caveated coverage never earns another round);
438
+ * 4. `DEADLINE_REACHED` — the underlying run reported a deadline gap;
439
+ * 5. `NO_ADDITIONAL_INFORMATION_GAIN` — estimated gain ≤ `INFO_GAIN_FLOOR`;
440
+ * 6. `SOURCE_EXHAUSTED` — a repeat round retrieved zero new claims;
441
+ * 7. `BUDGET_EXHAUSTED` — selection stopped on budget with coverage still lacking;
442
+ * 8. the round bound — loop ends, final record carries no reason.
443
+ *
444
+ * The loop decides on the cumulative merge but **reports on the delivery**: the returned
445
+ * `sufficiency` is re-evaluated against the selected round's own selection items, because the
446
+ * briefing a consumer receives is a single-round artifact and its report must not certify evidence
447
+ * the merge held and the delivery dropped.
448
+ */
449
+ export function runProgressiveRetrieval(orchestrateFn, requirements, config) {
450
+ const maxRounds = Math.max(1, Math.floor(config.maxRounds));
451
+ const rounds = [];
452
+ const results = [];
453
+ const statuses = [];
454
+ const mergedItems = new Map();
455
+ const seenClaims = new Map(); // claimId → text, the corpus info gain is measured against
456
+ let totalCandidates = 0;
457
+ let totalTokensSpent = 0;
458
+ let bestIndex = -1;
459
+ let bestStatusRank = -1;
460
+ let pendingGapTerms;
461
+ let pendingTraversalTerms = [];
462
+ // Claim ids previous walks already proposed as targets. A same-round graph neighbour is by
463
+ // construction already in the retrieval corpus (`seenClaims`), so deduping targets against that
464
+ // would kill every hop; what must not repeat is re-proposing the same neighbour on later walks.
465
+ const traversedTargets = new Set();
466
+ for (let round = 0; round < maxRounds; round += 1) {
467
+ const result = orchestrateFn(round, round === 0 ? undefined : (pendingGapTerms ?? []).flat(), round === 0 ? undefined : pendingTraversalTerms);
468
+ results.push(result);
469
+ totalCandidates += result.candidates.length;
470
+ totalTokensSpent += result.selection?.budget.used ?? 0;
471
+ // Merge, dedup by id. Insertion-ordered maps keep the merge deterministic.
472
+ for (const entry of result.selection?.items ?? [])
473
+ if (!mergedItems.has(entry.item.itemId))
474
+ mergedItems.set(entry.item.itemId, entry);
475
+ let newClaims = 0;
476
+ const priorTexts = [...seenClaims.values()];
477
+ const newTexts = [];
478
+ for (const claim of result.candidates.map((candidate) => candidate.claim)) {
479
+ if (seenClaims.has(claim.claimId))
480
+ continue;
481
+ seenClaims.set(claim.claimId, claim.text);
482
+ newClaims += 1;
483
+ newTexts.push(claim.text);
484
+ }
485
+ const cumulativeItems = [...mergedItems.values()];
486
+ const sufficiency = evaluateSufficiency(requirements, cumulativeItems, result.conflicts);
487
+ statuses.push(sufficiency.overall_status);
488
+ if (sufficiency.overall_status !== "insufficient") {
489
+ const rank = STATUS_RANK[sufficiency.overall_status];
490
+ if (result.delivered && rank >= bestStatusRank) {
491
+ bestStatusRank = rank;
492
+ bestIndex = results.length - 1;
493
+ }
494
+ }
495
+ /* --- stop policy ---------------------------------------------------------------------------- */
496
+ const roundInfoGain = round === 0 ? 1 : estimateInformationGain(newTexts.join("\n"), priorTexts);
497
+ let shouldStop = true;
498
+ let reason;
499
+ if (result.outcome === "CLARIFICATION_REQUIRED")
500
+ reason = "CLARIFICATION_REQUIRED";
501
+ else if (result.outcome === "INSUFFICIENT_AUTHORIZATION")
502
+ reason = "AUTHORIZATION_BLOCKED";
503
+ else if (sufficiency.overall_status === "sufficient")
504
+ reason = "SUFFICIENT_EVIDENCE";
505
+ // Locked selective policy (decision 9db78664): escalate only on missing required evidence.
506
+ // `sufficient_with_caveats` means every high-priority requirement is covered (only low-priority
507
+ // gaps/partials/conflicts remain), so the loop stops here instead of buying another round.
508
+ else if (sufficiency.overall_status === "sufficient_with_caveats")
509
+ reason = "SUFFICIENT_WITH_CAVEATS";
510
+ else if (result.gaps.some((gap) => gap.reason === "deadline"))
511
+ reason = "DEADLINE_REACHED";
512
+ else if (round > 0 && roundInfoGain <= INFO_GAIN_FLOOR)
513
+ reason = "NO_ADDITIONAL_INFORMATION_GAIN";
514
+ else if (round > 0 && newClaims === 0)
515
+ reason = "SOURCE_EXHAUSTED";
516
+ else if (result.selection?.stats.stopReason === "budget")
517
+ reason = "BUDGET_EXHAUSTED";
518
+ else if (round + 1 >= maxRounds)
519
+ reason = undefined; // the caller's round bound, honestly unnamed
520
+ else
521
+ shouldStop = false;
522
+ rounds.push({ round, candidatesEvaluated: result.candidates.length, newClaims, infoGainScore: Number(roundInfoGain.toFixed(6)), stopCheck: { shouldStop, ...(reason === undefined ? {} : { reason }) } });
523
+ if (shouldStop)
524
+ break;
525
+ // Gap terms are OR groups; the consumer here is the curated any-match set, which is already a
526
+ // disjunction, so flattening preserves the semantics while keeping the orchestrateFn boundary
527
+ // a plain term list (see deriveGapTerms for why the grouping exists).
528
+ pendingGapTerms = deriveGapTerms(requirements, sufficiency.coverage, [...seenClaims.values()]);
529
+ // Phase D: one bounded hop through the round's own provenance graph, computed only because the
530
+ // loop is continuing — a stopped run (early exit, sufficiency, budget, deadline, the round bound)
531
+ // never traverses. Derived terms keep priority; these only fill what they leave open.
532
+ const targets = collectTraversalTargets(result.graph ?? null, result.selection?.items ?? [], traversedTargets);
533
+ pendingTraversalTerms = termsFromTargets(targets, seenClaims, pendingGapTerms.flat());
534
+ for (const target of targets)
535
+ traversedTargets.add(target);
536
+ }
537
+ const finalResult = bestIndex >= 0 ? results[bestIndex] : selectFinalRound(results, statuses);
538
+ if (finalResult?.briefing == null)
539
+ throw new Error("progressive retrieval produced no briefing in any round; nothing to return");
540
+ // **The report describes what was delivered, not what was merged.** The loop's stop policy runs on
541
+ // the cumulative merge (a later round is credited for the whole picture while deciding whether to
542
+ // continue), but the caller receives a single round's briefing — and reporting cumulative
543
+ // coverage against a one-round artifact would certify evidence the reader does not hold. So the
544
+ // returned report re-evaluates coverage against exactly the items the selected round selected,
545
+ // with that round's conflicts; only the run-level totals (rounds, tokens) stay cumulative.
546
+ const deliveredItems = finalResult.selection?.items ?? [];
547
+ const deliveredSufficiency = evaluateSufficiency(requirements, deliveredItems, finalResult.conflicts);
548
+ const sufficiency = { ...deliveredSufficiency, rounds_completed: rounds.length, total_tokens_spent: totalTokensSpent };
549
+ return { finalBriefing: finalResult.briefing, sufficiency, rounds, totalCandidates };
550
+ }