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,607 @@
1
+ // Ported from mnemosia/select.ts @ f0a8ad4 (MIT; see NOTICE)
2
+ /**
3
+ * Context-set selection (design §10, spec §13 and §15, build-order step 12).
4
+ *
5
+ * Spec §13 opens with the same shape of prohibition spec §12 did: "Do not select context by taking
6
+ * the highest-scoring N candidates." Top-N is what a ranker gives you for free, and it is wrong here
7
+ * for a reason the corpus makes concrete — the twenty highest-utility claims about "the memory
8
+ * adapter" are twenty overlapping excerpts of the same three conversations, and a briefing built
9
+ * from them spends its whole budget saying one thing. So selection is a greedy maximal-marginal-
10
+ * relevance loop with a redundancy penalty and section quotas, exactly design §10:
11
+ *
12
+ * ```
13
+ * m(c) = utility(c)·quota(section(c)) − λ·max_{s∈selected} jaccard₃(c, s) λ = 0.5
14
+ * ```
15
+ *
16
+ * **The budget is hard.** Design §16 gates token-budget compliance at 100%, and this module is where
17
+ * that is either true or not. Nothing is ever placed without first asking the `Budget` whether it
18
+ * fits, `Budget.spend` throws rather than clamps when it would overflow (tokens.ts:77-82), and the
19
+ * failure mode when the mandatory set alone does not fit is a **PARTIAL_BRIEFING with a named gap**,
20
+ * never an overrun. Spec §15's last resort — "Return a partial briefing if required evidence still
21
+ * cannot fit" — is the design's answer too, and it is implemented as the highest-utility prefix so
22
+ * that what survives truncation is the most useful part of it rather than the first part.
23
+ *
24
+ * **Exclusion is explained.** Spec §23 requires Mnemosia to "explain inclusion and exclusion
25
+ * decisions", and the second half of that is the one systems skip. Every candidate that is not
26
+ * selected gets an `ExclusionRecord` naming which of the four design §10 reasons applied, with the
27
+ * numbers behind it. There is no "did not make the cut" bucket.
28
+ *
29
+ * **Knapsack is the documented future path** (design §10): the greedy loop can leave utility on the
30
+ * table when a large high-utility item blocks two medium ones. That is `LATER_RECOMMENDED`, gated on
31
+ * the §16 eval showing a measurable gap, and it is not pre-empted here by a half-built optimizer.
32
+ */
33
+ import { normalizeClaimText } from "./claims.js";
34
+ import { compareCandidates } from "./rank.js";
35
+ import { jaccard, shingleSet } from "./similarity.js";
36
+ import { createBudget, estimateTokens, selectableRemaining, spend } from "./tokens.js";
37
+ import { ADDENDUM_BUDGET_SHARE } from "./agents.js";
38
+ import { SCHEMA_VERSION } from "./types.js";
39
+ import { createHash } from "node:crypto";
40
+ /* ------------------------------------------------------------------------------------------------
41
+ * Classification
42
+ * ---------------------------------------------------------------------------------------------- */
43
+ /**
44
+ * Markers that route a claim into `known_failures_or_rejected`.
45
+ *
46
+ * Design §10 gives that section a 0.10 share, which makes it reachable only if something can be
47
+ * routed there, and Phase 1 has no classifier that could do it semantically. These two tables are
48
+ * the deterministic stand-in, and they are kept deliberately narrow: a false positive here moves a
49
+ * fact out of `confirmed_facts`, which is worse than leaving the section thin. They are keyword
50
+ * rules and this comment is the only place they are described as anything more.
51
+ */
52
+ export const FAILURE_MARKERS = /\b(?:fail(?:s|ed|ing|ure|ures)?|errors?|broke|broken|crash(?:ed|es|ing)?|regressions?|does\s?n[o']?t work|did\s?n[o']?t work|timed out|timeout|blocked|blocker)\b/iu;
53
+ export const REJECTED_MARKERS = /\b(?:rejected|reject|instead of|decided against|ruled out|abandoned|discarded|prohibited|do not use|don'?t use|won'?t|will not|not going to|dropped in favou?r)\b/iu;
54
+ /**
55
+ * Claim → the internal section whose soft share it draws against.
56
+ *
57
+ * The nine sections here are design §10's budget sections; brief.ts fans them out onto spec §16's
58
+ * larger field list. First match wins, and the order matters: a DISPUTED or superseded claim is a
59
+ * conflict *before* it is a fact, which is the mechanism behind design §16's "stale inclusion = 0"
60
+ * gate — a demoted claim cannot reach `confirmed_facts` because it never gets asked.
61
+ */
62
+ export function sectionForClaim(candidate, conflicted) {
63
+ if (conflicted)
64
+ return "conflicts";
65
+ const claim = candidate.claim;
66
+ switch (claim.claimType) {
67
+ case "CONSTRAINT":
68
+ return "constraints";
69
+ case "PREFERENCE":
70
+ return "preferences";
71
+ case "HYPOTHESIS":
72
+ return "uncertainties_or_gaps";
73
+ case "PLAN":
74
+ return "open_tasks";
75
+ case "DECISION":
76
+ return REJECTED_MARKERS.test(claim.text) ? "known_failures_or_rejected" : "previous_decisions";
77
+ case "OBSERVATION":
78
+ // An UNKNOWN-certainty observation is claims.ts's honest label for a summary section whose
79
+ // heading it did not recognize (claims.ts:582-597). It is not current state; it is a thing
80
+ // Mnemosia read and could not classify, which is what `uncertainties_or_gaps` is for.
81
+ if (claim.certainty === "UNKNOWN")
82
+ return "uncertainties_or_gaps";
83
+ return FAILURE_MARKERS.test(claim.text) ? "known_failures_or_rejected" : "current_state";
84
+ default:
85
+ return FAILURE_MARKERS.test(claim.text) ? "known_failures_or_rejected" : "confirmed_facts";
86
+ }
87
+ }
88
+ /**
89
+ * Claim → one of spec §5.5's ten kinds.
90
+ *
91
+ * This is the field the human rendering groups by, so spec §16's "must clearly distinguish facts,
92
+ * observations, inferences, plans, preferences, and unresolved claims" is decided here rather than
93
+ * in the renderer. The interesting case is `inference`: an observation that reached us only through
94
+ * a summary is a model's account of what happened, not the thing that happened, and labelling it
95
+ * `tool_observation` would launder derivation into observation.
96
+ */
97
+ export function kindForClaim(candidate, conflicted) {
98
+ if (conflicted)
99
+ return "conflict";
100
+ const claim = candidate.claim;
101
+ switch (claim.claimType) {
102
+ case "CONSTRAINT":
103
+ return "constraint";
104
+ case "PREFERENCE":
105
+ return "preference";
106
+ case "HYPOTHESIS":
107
+ return "hypothesis";
108
+ case "PLAN":
109
+ return "plan";
110
+ case "OBSERVATION": {
111
+ if (!candidate.basis.directness.includes("direct"))
112
+ return "inference";
113
+ const classes = candidate.basis.authorityClasses;
114
+ if (classes.includes("tool_output"))
115
+ return "tool_observation";
116
+ if (classes.includes("user_message"))
117
+ return "user_claim";
118
+ return "inference";
119
+ }
120
+ default:
121
+ return "confirmed_fact";
122
+ }
123
+ }
124
+ /**
125
+ * The item's channel, taken from the artifacts that produced it.
126
+ *
127
+ * Never a privileged channel. `AdapterChannel` excludes `SYSTEM_POLICY` and `AGENT_POLICY` by
128
+ * construction (types.ts:84-85) and `RankBasis.channels` is typed as `AdapterChannel[]`, so a
129
+ * retrieved claim cannot acquire instruction authority by passing through selection. When a merged
130
+ * claim's artifacts disagree, `RETRIEVED_EVIDENCE` wins: it is the reading with the least authority
131
+ * of the three, and a tie between channels is not the moment to grant the stronger one.
132
+ */
133
+ export function channelForCandidate(candidate) {
134
+ const channels = candidate.basis.channels;
135
+ if (channels.length === 1 && channels[0] !== undefined)
136
+ return channels[0];
137
+ return "RETRIEVED_EVIDENCE";
138
+ }
139
+ function itemIdFor(claimId, section) {
140
+ return `mnemosia-item:${createHash("sha256").update(`${claimId}${section}`, "utf8").digest("hex").slice(0, 16)}`;
141
+ }
142
+ /**
143
+ * The exact line a ContextItem occupies in the Markdown briefing.
144
+ *
145
+ * `tokenCost` is `estimateTokens` of **this string**, not of the claim text, and that is the whole
146
+ * point: the budget is a promise about the briefing that is delivered, so it has to be measured
147
+ * against the bytes that are delivered. Charging only for the claim text would under-count the
148
+ * provenance footer on every item and quietly overrun by a few percent per line — a 100%-compliance
149
+ * gate lost to bookkeeping rather than to a decision.
150
+ *
151
+ * It lives here rather than in brief.ts so that the renderer and the meter cannot drift apart.
152
+ */
153
+ export function renderContextItemLine(selected) {
154
+ const { item, candidate } = selected;
155
+ const label = `${candidate.claim.claimType} · ${candidate.claim.certainty} · ${candidate.basis.authorityClasses.join("/") || "unknown"}`;
156
+ const scope = item.scope.level === "global" ? "global" : `project ${item.scope.project ?? "-"}`;
157
+ const claims = item.claimIds.map((id) => id.slice(0, 12)).join(", ");
158
+ const evidence = item.evidenceIds.map((id) => id.slice(0, 12)).join(", ");
159
+ const lines = [
160
+ `- [${label}] ${item.text.replace(/\s+/gu, " ").trim()}`,
161
+ ` ↳ claim ${claims} · evidence ${evidence} · ${scope} · effective ${new Date(item.effectiveAt).toISOString().slice(0, 10)} · utility ${candidate.score.utility.toFixed(3)}`,
162
+ ];
163
+ for (const qualification of selected.qualifications)
164
+ lines.push(` ⚠ ${qualification}`);
165
+ return lines.join("\n");
166
+ }
167
+ /**
168
+ * Whether a claim belongs in the `conflicts` section rather than in a factual one.
169
+ *
170
+ * **Narrowed in Phase 2, toward the design rather than away from it.** Phase 1 routed *every*
171
+ * participant in *any* conflict here, because its two classes were both cases where nobody had won.
172
+ * Phase 2's taxonomy resolves most of what it detects — `SELECT_NEWER_VALID` names a winner,
173
+ * `KEEP_SCOPE_SPECIFIC_VARIANTS` says both sides are correct where they were recorded — and filing
174
+ * the *winner* of a settled supersession under "unresolved conflicts" would tell the reader there is
175
+ * an open question when the whole point of the record is that there is not.
176
+ *
177
+ * So the section is for the two populations that genuinely belong there: claims a conflict **demoted**
178
+ * (they may not stand as facts, and their absence from the factual sections has to be explained), and
179
+ * parties to a conflict nothing **resolved**.
180
+ */
181
+ function conflictedFor(resolution, claimId) {
182
+ if (resolution.demoted.has(claimId))
183
+ return true;
184
+ // Phase 4: the third population. A seat on `both_with_qualification` receives the *winning* side of
185
+ // a resolved conflict here too, beside the side it beat, so the reader gets the disagreement rather
186
+ // than Mnemosia's answer to it (`conflicts.ts:applyConflictPresentation`). Empty for six of eight.
187
+ if (resolution.presented.has(claimId))
188
+ return true;
189
+ return (resolution.byClaimId.get(claimId) ?? []).some((entry) => entry.unresolved);
190
+ }
191
+ function buildItem(candidate, resolution, mandatory) {
192
+ const conflicts = resolution.byClaimId.get(candidate.claim.claimId) ?? [];
193
+ const conflicted = conflictedFor(resolution, candidate.claim.claimId);
194
+ const section = sectionForClaim(candidate, conflicted);
195
+ const item = {
196
+ schemaVersion: SCHEMA_VERSION.contextItem,
197
+ itemId: itemIdFor(candidate.claim.claimId, section),
198
+ kind: kindForClaim(candidate, conflicted),
199
+ channel: channelForCandidate(candidate),
200
+ text: candidate.claim.text,
201
+ claimIds: [candidate.claim.claimId],
202
+ evidenceIds: candidate.claim.evidence.map((entry) => entry.evidenceId).sort(),
203
+ scope: candidate.claim.scope,
204
+ effectiveAt: candidate.claim.effectiveAt,
205
+ // Filled in immediately below: the cost is the cost of the rendered line, which needs the item.
206
+ tokenCost: 0,
207
+ section,
208
+ score: candidate.score,
209
+ mandatory,
210
+ };
211
+ const selected = { item, candidate, qualifications: conflicts.map((entry) => entry.qualification), superseded: resolution.demoted.has(candidate.claim.claimId), conflicts };
212
+ item.tokenCost = estimateTokens(renderContextItemLine(selected));
213
+ return selected;
214
+ }
215
+ /* ------------------------------------------------------------------------------------------------
216
+ * Redundancy
217
+ * ---------------------------------------------------------------------------------------------- */
218
+ /**
219
+ * The 3-token shingle set of a claim, over its **normalized** text.
220
+ *
221
+ * Normalizing first (claims.ts:102-114) means two renderings of the same sentence — one bulleted,
222
+ * one bare, one with a trailing ellipsis from an excerpt window — produce identical shingles, which
223
+ * is exactly the redundancy the penalty is supposed to catch. A text shorter than the window yields
224
+ * one shingle of its whole token list rather than none, so a two-word claim is still comparable
225
+ * instead of being scored as maximally novel against everything.
226
+ */
227
+ export function shingles(text, size) {
228
+ return shingleSet(normalizeClaimText(text), size);
229
+ }
230
+ /**
231
+ * Re-exported from `similarity.ts`, where Phase 2 moved the implementation so that `conflicts.ts`
232
+ * could use it without an import cycle (this module already imports `conflicts.ts`). The signature
233
+ * and behaviour are unchanged; `test/select.test.ts` still pins both from here.
234
+ */
235
+ export { jaccard } from "./similarity.js";
236
+ /**
237
+ * Design §10: "quota(sec) = 1 below soft share, 0.5 once at 1.5× share".
238
+ *
239
+ * The design fixes the two endpoints and leaves the interval between them open. A step function
240
+ * would make the multiplier — and therefore the selection order — hinge on a single token crossing
241
+ * a threshold, so the interval is a straight line between the stated endpoints: monotone, exactly
242
+ * 1.0 at the share, exactly 0.5 at 1.5× it, and nothing invented outside what the design fixed.
243
+ */
244
+ export function quotaMultiplier(usedInSection, share, policy) {
245
+ if (share <= 0)
246
+ return policy.selection.quotaFloor;
247
+ if (usedInSection <= share)
248
+ return 1;
249
+ const ceiling = share * policy.selection.quotaOverFactor;
250
+ if (usedInSection >= ceiling)
251
+ return policy.selection.quotaFloor;
252
+ return 1 - (1 - policy.selection.quotaFloor) * ((usedInSection - share) / (ceiling - share));
253
+ }
254
+ /* ------------------------------------------------------------------------------------------------
255
+ * Selection
256
+ * ---------------------------------------------------------------------------------------------- */
257
+ /** Design §10's four reasons, plus the one the mandatory-overflow path needs. */
258
+ export const EXCLUSION_REASONS = ["budget", "redundant", "below_floor", "quota", "mandatory_overflow"];
259
+ function emptyByReason() {
260
+ return { budget: 0, redundant: 0, below_floor: 0, quota: 0, mandatory_overflow: 0 };
261
+ }
262
+ function emptyBySection() {
263
+ return {
264
+ confirmed_facts: { items: 0, tokens: 0 },
265
+ previous_decisions: { items: 0, tokens: 0 },
266
+ current_state: { items: 0, tokens: 0 },
267
+ constraints: { items: 0, tokens: 0 },
268
+ known_failures_or_rejected: { items: 0, tokens: 0 },
269
+ preferences: { items: 0, tokens: 0 },
270
+ conflicts: { items: 0, tokens: 0 },
271
+ open_tasks: { items: 0, tokens: 0 },
272
+ uncertainties_or_gaps: { items: 0, tokens: 0 },
273
+ };
274
+ }
275
+ /**
276
+ * Is this candidate mandatory (design §10)?
277
+ *
278
+ * "Active CONSTRAINTs in scope + security restrictions + unresolved conflicts + objective echo."
279
+ * Three of those four are here; the objective echo is a budget reservation rather than a retrieved
280
+ * claim and is charged separately below. *Security restrictions* has no retrieved half in Phase 1 —
281
+ * there is no per-record ACL anywhere in the corpus (types.ts:139-158), so the security material a
282
+ * briefing must carry is the authorization refusals and the quarantine count, which brief.ts
283
+ * assembles from the run rather than selecting from candidates. Inventing a "security claim" type to
284
+ * fill the slot would be the placeholder abstraction §26 forbids.
285
+ */
286
+ function isMandatory(candidate, resolution) {
287
+ // Phase 2: `resolution.mandatory` is the *unresolved* conflicts plus every demoted claim, which is
288
+ // design §10's wording read literally. Phase 1 reserved capacity for every conflict participant,
289
+ // a superset that was harmless when there were two classes and would now spend the whole
290
+ // reservation on settled questions — pushing the open ones out of the budget.
291
+ if (resolution.mandatory.has(candidate.claim.claimId))
292
+ return true;
293
+ if (candidate.claim.claimType !== "CONSTRAINT")
294
+ return false;
295
+ // Phase 2: a constraint that is not yet in force is not a standing rule *yet*. It reaches the
296
+ // briefing through its temporal-validity conflict record instead of through the mandatory
297
+ // reservation, so the reader is told it is scheduled rather than told to obey it.
298
+ if (!candidate.basis.temporal.inForce)
299
+ return false;
300
+ // "Active" in the governance sense. An ungoverned claim (lifecycle null) is active by default —
301
+ // nothing has said otherwise — and a DISPUTED constraint is mandatory too, via the conflict test
302
+ // above, so it reaches the briefing as a conflict rather than as a standing rule.
303
+ return candidate.claim.lifecycle === null || candidate.claim.lifecycle === "ACTIVE";
304
+ }
305
+ /** Spec §15's "Reserve guaranteed capacity for: Current objective". Rendered as brief.ts renders it. */
306
+ export function objectiveEchoTokens(objective) {
307
+ return estimateTokens(`## Objective\n\n${objective.replace(/\s+/gu, " ").trim()}\n`);
308
+ }
309
+ /**
310
+ * What the briefing's own frame costs, in tokens, before a single claim is placed.
311
+ *
312
+ * **This constant exists because the first live run overran.** The item ledger said 5,386 of 6,000
313
+ * and the briefing that was actually delivered measured 8,331 — the scaffolding (header, scope, the
314
+ * untrusted-reference fence, ten section headings, the gap list, the exclusion summary, the
315
+ * provenance block) was never charged to anything. Design §16 gates token-budget compliance at 100%,
316
+ * and the thing that has to comply is the artifact the caller receives, not the subtotal Mnemosia
317
+ * kept for itself. Charging it here is what makes the budget a promise about the delivered bytes.
318
+ *
319
+ * `tokens.ts:15` describes the 10% reserve as being held back "for the briefing's own scaffolding",
320
+ * and that turned out to be measurably too small: 600 tokens against a measured 740. So the reserve
321
+ * stays what it is — a margin — and the scaffolding is charged explicitly, like the objective echo.
322
+ *
323
+ * Measured, not guessed. Against the live corpus and `brief.ts`'s renderer:
324
+ *
325
+ * ```
326
+ * a briefing with no items at all (the pure frame) 653 tokens
327
+ * the standard-mode task-A briefing below (5 exclusion examples,
328
+ * 2 gaps, 1 follow-up, 4 unpopulated sections, 60-claim provenance) 917 tokens
329
+ * a synthetic worst case (4 long gaps, 6 long follow-ups) 1,395 tokens
330
+ * ```
331
+ *
332
+ * 1,000 covers the frame plus the parts that vary with the run, and the 10% reserve is the second
333
+ * margin behind it. The frame cannot grow with the *corpus*: brief.ts caps the rendered exclusion
334
+ * examples at five, renders `unpopulated_sections` as a list of names rather than a paragraph each,
335
+ * and summarizes provenance instead of listing it — so the only things that scale are the gap and
336
+ * follow-up lists, which are bounded by the number of sources and detected conflicts.
337
+ *
338
+ * `test/brief.test.ts` measures a real rendering against this number, which is what keeps the two
339
+ * from drifting, and `validateBriefing`'s `rendered_over_budget` is the backstop if they ever do.
340
+ */
341
+ export const BRIEFING_SCAFFOLDING_TOKENS = 1_000;
342
+ /**
343
+ * The smallest budget that can hold a *conforming* briefing, derived rather than guessed.
344
+ *
345
+ * Chunk C measured the floor at "roughly 1,150 tokens" and left the consequence to step 15. This is
346
+ * the arithmetic behind that number, so it moves when the scaffolding constant or the reserve ratio
347
+ * moves instead of drifting away from them:
348
+ *
349
+ * ```
350
+ * overhead = objectiveEchoTokens(objective) + scaffoldingTokens
351
+ * selectable pool = budget − ceil(reserveRatio · budget)
352
+ * conforming ⟺ overhead ≤ selectable pool
353
+ * ⟺ budget ≥ ceil(overhead / (1 − reserveRatio))
354
+ * ```
355
+ *
356
+ * At the shipped constants (1,000 scaffolding, 0.10 reserve) that is 1,112 tokens for an empty
357
+ * objective and about 1,130–1,160 for a real one — the design's "~1,150", now computed.
358
+ *
359
+ * Below it, `selectContext` still produces a briefing and marks it structurally partial
360
+ * (`selectContext` step 0), and `validateBriefing` refuses to certify it. The orchestrator turns the
361
+ * same condition into a clean `CLARIFICATION_REQUIRED` exit *before* any source is queried, because
362
+ * the caller has to change the request either way and reading 11,000 events first would only make
363
+ * the refusal slower.
364
+ */
365
+ export function minimumConformingBudget(objective, policy, scaffoldingTokens = BRIEFING_SCAFFOLDING_TOKENS) {
366
+ const overhead = objectiveEchoTokens(objective) + scaffoldingTokens;
367
+ return Math.ceil(overhead / (1 - policy.selection.reserveRatio));
368
+ }
369
+ /**
370
+ * The same floor for a Conclave seat, where the overhead **depends on the budget being solved for**.
371
+ *
372
+ * Phase 4 charges the seat's agent addendum alongside the frame, and `effectiveAddendumReserve` caps
373
+ * that charge at `ADDENDUM_BUDGET_SHARE` of the budget. So the conforming condition
374
+ *
375
+ * ```
376
+ * echo + frame + min(ceiling, share·B) ≤ (1 − reserveRatio)·B
377
+ * ```
378
+ *
379
+ * has `B` on both sides, and calling `minimumConformingBudget` with the seat's *ceiling* — which is
380
+ * what the first version of this wiring did — computes the floor for a briefing the run would never
381
+ * produce: at a budget near the floor the share cap binds long before the ceiling does, so the floor
382
+ * came out several hundred tokens too high and `CLARIFICATION_REQUIRED` was returned for budgets that
383
+ * could in fact have held a conforming briefing.
384
+ *
385
+ * It is solved rather than iterated, because `min` splits it into two linear cases:
386
+ *
387
+ * - **the share cap binds** (`share·B ≤ ceiling`) → `B ≥ overhead / (1 − reserveRatio − share)`;
388
+ * - **the seat's ceiling binds** → `B ≥ (overhead + ceiling) / (1 − reserveRatio)`.
389
+ *
390
+ * The first is tried first and accepted only if its own premise holds at the answer, which is what
391
+ * makes the case split total rather than a guess. `1 − 0.10 − 0.08 = 0.82 > 0`, so the first case is
392
+ * never a division by a non-positive number; the guard states that rather than relying on it.
393
+ */
394
+ export function minimumConformingBudgetForSeat(objective, policy, baseScaffolding, addendumCeiling) {
395
+ const overhead = objectiveEchoTokens(objective) + baseScaffolding;
396
+ const usable = 1 - policy.selection.reserveRatio;
397
+ if (addendumCeiling <= 0)
398
+ return Math.ceil(overhead / usable);
399
+ const slope = usable - ADDENDUM_BUDGET_SHARE;
400
+ if (slope > 0) {
401
+ const shareBound = Math.ceil(overhead / slope);
402
+ if (Math.floor(ADDENDUM_BUDGET_SHARE * shareBound) <= addendumCeiling)
403
+ return shareBound;
404
+ }
405
+ return Math.ceil((overhead + addendumCeiling) / usable);
406
+ }
407
+ export function selectContext(input) {
408
+ const policy = input.policy;
409
+ const { lambda, marginalFloor, shingleSize, sectionShares } = policy.selection;
410
+ let budget = createBudget(input.budget, policy.selection.reserveRatio);
411
+ const selectablePool = Math.max(0, budget.total - budget.reserve);
412
+ const all = [...input.candidates].sort(compareCandidates).map((candidate) => buildItem(candidate, input.conflicts, isMandatory(candidate, input.conflicts)));
413
+ const shingleIndex = new Map(all.map((entry) => [entry.item.itemId, shingles(entry.item.text, shingleSize)]));
414
+ const selected = [];
415
+ const excluded = [];
416
+ const bySection = emptyBySection();
417
+ const byReason = emptyByReason();
418
+ const gaps = [];
419
+ let partial = false;
420
+ const place = (entry) => {
421
+ budget = spend(budget, entry.item.tokenCost);
422
+ selected.push(entry);
423
+ bySection[entry.item.section].items += 1;
424
+ bySection[entry.item.section].tokens += entry.item.tokenCost;
425
+ input.trace?.append({ state: "SELECT_CONTEXT_SET", event: "selection", payload: { itemId: entry.item.itemId, claimId: entry.candidate.claim.claimId, section: entry.item.section, mandatory: entry.item.mandatory, tokenCost: entry.item.tokenCost, utility: entry.candidate.score.utility } });
426
+ };
427
+ /* --- step 0: the objective echo and the briefing frame -------------------------------------- */
428
+ //
429
+ // Charged before anything is selected, because spec §15 lists the current objective first among
430
+ // the things that get *guaranteed* capacity. A briefing that dropped the objective to fit one
431
+ // more fact would have lost the one line that tells the reader what the rest of it is for. The
432
+ // frame is charged in the same breath: see `BRIEFING_SCAFFOLDING_TOKENS` for what it costs and
433
+ // why leaving it uncharged made the first live run overrun by 39%.
434
+ const objectiveTokens = objectiveEchoTokens(input.objective);
435
+ // Each conflict that has a participant in the conflicts section renders a heading, its rationale,
436
+ // its qualification and a follow-up line. That grows with the number of conflicts, so it is
437
+ // charged here with the frame rather than hidden inside the fixed frame constant.
438
+ const sectioned = new Set(all.filter((entry) => entry.item.section === "conflicts").map((entry) => entry.candidate.claim.claimId));
439
+ const conflictChrome = input.conflicts.conflicts.filter((record) => record.claimIds.some((id) => sectioned.has(id))).reduce((sum, record) => sum + estimateTokens(`### ${record.conflictClass} → ${record.outcome} (${record.detector})\n_${record.rationale}_\n> ${record.qualification}\nResolve conflict ${record.conflictId.slice(0, 12)} (${record.conflictClass}/${record.outcome}) before relying on the affected statements.`), 0);
440
+ const scaffoldingTokens = (input.scaffoldingTokens ?? BRIEFING_SCAFFOLDING_TOKENS) + conflictChrome;
441
+ const overhead = objectiveTokens + scaffoldingTokens;
442
+ if (overhead <= selectablePool)
443
+ budget = spend(budget, overhead);
444
+ else {
445
+ // A budget too small to hold its own objective and frame is not a briefing. Recorded, not
446
+ // clamped: the run still produces a briefing, and it says out loud that it is structurally
447
+ // partial rather than quietly rendering past the ceiling.
448
+ partial = true;
449
+ gaps.push({ sourceId: "mnemosia/selection", reason: "budget", detail: `the ${budget.total}-token budget cannot hold the ${objectiveTokens}-token objective echo plus the ${scaffoldingTokens}-token briefing frame; the briefing is structurally partial`, code: null });
450
+ }
451
+ /* --- step 1: mandatory reservation --------------------------------------------------------- */
452
+ const mandatory = all.filter((entry) => entry.item.mandatory);
453
+ const mandatoryTotal = mandatory.reduce((sum, entry) => sum + entry.item.tokenCost, 0);
454
+ const mandatoryOverflowed = mandatoryTotal > selectableRemaining(budget);
455
+ for (const entry of mandatory) {
456
+ if (entry.item.tokenCost <= selectableRemaining(budget)) {
457
+ place(entry);
458
+ continue;
459
+ }
460
+ // Design §10: "If Σ > budget − reserve → PARTIAL_BRIEFING with highest-utility prefix +
461
+ // explicit retrieval_gap". `mandatory` is already in utility order, so what has been placed by
462
+ // the time this fires *is* the highest-utility prefix.
463
+ partial = true;
464
+ excluded.push({
465
+ claimId: entry.candidate.claim.claimId,
466
+ itemId: entry.item.itemId,
467
+ section: entry.item.section,
468
+ reason: "mandatory_overflow",
469
+ detail: `mandatory item costs ${entry.item.tokenCost} tokens; ${selectableRemaining(budget)} of the ${selectablePool}-token selectable pool remained after the higher-utility mandatory prefix`,
470
+ utility: entry.candidate.score.utility,
471
+ tokenCost: entry.item.tokenCost,
472
+ maxSimilarity: 0,
473
+ });
474
+ byReason.mandatory_overflow += 1;
475
+ }
476
+ if (mandatoryOverflowed) {
477
+ gaps.push({
478
+ sourceId: "mnemosia/selection",
479
+ reason: "budget",
480
+ detail: `the mandatory set (${mandatory.length} item(s), ${mandatoryTotal} tokens) exceeds the ${selectablePool}-token selectable pool; ${byReason.mandatory_overflow} mandatory item(s) were dropped and this briefing is PARTIAL`,
481
+ code: null,
482
+ });
483
+ }
484
+ /* --- step 2: the MMR loop ------------------------------------------------------------------ */
485
+ const pool = all.filter((entry) => !entry.item.mandatory);
486
+ const chosen = new Set(selected.map((entry) => entry.item.itemId));
487
+ let iterations = 0;
488
+ let stopReason = "pool_exhausted";
489
+ const similarityTo = (entry) => {
490
+ const own = shingleIndex.get(entry.item.itemId) ?? new Set();
491
+ let best = 0;
492
+ for (const other of selected) {
493
+ const compare = shingleIndex.get(other.item.itemId);
494
+ if (compare === undefined)
495
+ continue;
496
+ best = Math.max(best, jaccard(own, compare));
497
+ }
498
+ return best;
499
+ };
500
+ while (true) {
501
+ iterations += 1;
502
+ const remaining = selectableRemaining(budget);
503
+ let best = null;
504
+ let anyFits = false;
505
+ for (const entry of pool) {
506
+ if (chosen.has(entry.item.itemId))
507
+ continue;
508
+ if (entry.item.tokenCost > remaining)
509
+ continue;
510
+ anyFits = true;
511
+ const quota = quotaMultiplier(bySection[entry.item.section].tokens, sectionShares[entry.item.section] * selectablePool, policy);
512
+ const marginal = entry.candidate.score.utility * quota - lambda * similarityTo(entry);
513
+ if (best === null || marginal > best.marginal + 1e-9) {
514
+ best = { entry, marginal };
515
+ continue;
516
+ }
517
+ // Design §10's tie-break: (utility desc, effectiveAt desc, claimId asc). `all` was sorted
518
+ // into exactly that order, so an earlier candidate already holds the tie and nothing needs
519
+ // to change — but the comparison is written out rather than relied on implicitly, because
520
+ // "the array happened to be sorted" is not something the §16 determinism gate can read.
521
+ if (Math.abs(marginal - best.marginal) <= 1e-9 && compareCandidates(entry.candidate, best.entry.candidate) < 0)
522
+ best = { entry, marginal };
523
+ }
524
+ if (best === null) {
525
+ stopReason = anyFits ? "pool_exhausted" : pool.some((entry) => !chosen.has(entry.item.itemId)) ? "budget" : "pool_exhausted";
526
+ break;
527
+ }
528
+ if (best.marginal < marginalFloor) {
529
+ stopReason = "below_floor";
530
+ break;
531
+ }
532
+ place(best.entry);
533
+ chosen.add(best.entry.item.itemId);
534
+ }
535
+ /* --- step 3: exclusion records ------------------------------------------------------------- */
536
+ //
537
+ // Attributed against the *final* selected set, so the reason a reader is given is the reason that
538
+ // was true when the loop stopped, not a snapshot from some intermediate iteration.
539
+ const finalRemaining = selectableRemaining(budget);
540
+ for (const entry of pool) {
541
+ if (chosen.has(entry.item.itemId))
542
+ continue;
543
+ const similarity = similarityTo(entry);
544
+ const share = sectionShares[entry.item.section] * selectablePool;
545
+ const quota = quotaMultiplier(bySection[entry.item.section].tokens, share, policy);
546
+ const marginal = entry.candidate.score.utility * quota - lambda * similarity;
547
+ // Which of the three terms was *decisive*, not merely present.
548
+ //
549
+ // The loop only ever stops for two reasons — nothing fits, or the best marginal fell below the
550
+ // floor — so for anything that fits, `marginal < marginalFloor` is guaranteed here. What a
551
+ // reader needs to know is which term took it there. Reporting "below_floor" for a claim that
552
+ // would have cleared the floor on its own but was cancelled by a near-duplicate would be
553
+ // technically true and useless: design §10 names `redundant(λ·sim)` and `quota` as distinct
554
+ // reasons precisely because they suggest different fixes (drop the duplicate; raise the share).
555
+ const base = entry.candidate.score.utility;
556
+ const afterQuota = base * quota;
557
+ let reason;
558
+ let detail;
559
+ if (entry.item.tokenCost > finalRemaining) {
560
+ reason = "budget";
561
+ detail = `costs ${entry.item.tokenCost} tokens, ${finalRemaining} remained in the selectable pool`;
562
+ }
563
+ else if (afterQuota >= marginalFloor) {
564
+ reason = "redundant";
565
+ detail = `utility·quota = ${afterQuota.toFixed(3)} cleared the ${marginalFloor} floor, but λ·jaccard₃ = ${(lambda * similarity).toFixed(3)} against the selected set took its marginal value to ${marginal.toFixed(3)}`;
566
+ }
567
+ else if (base >= marginalFloor) {
568
+ reason = "quota";
569
+ detail = `section ${entry.item.section} held ${bySection[entry.item.section].tokens} tokens against a ${Math.round(share)}-token soft share, so its quota multiplier fell to ${quota.toFixed(2)} and utility ${base.toFixed(3)} became ${afterQuota.toFixed(3)}`;
570
+ }
571
+ else {
572
+ reason = "below_floor";
573
+ detail = `utility ${base.toFixed(3)} is below the ${marginalFloor} floor before any penalty applies`;
574
+ }
575
+ if (reason === "budget")
576
+ partial = true;
577
+ byReason[reason] += 1;
578
+ excluded.push({ claimId: entry.candidate.claim.claimId, itemId: entry.item.itemId, section: entry.item.section, reason, detail, utility: entry.candidate.score.utility, tokenCost: entry.item.tokenCost, maxSimilarity: similarity });
579
+ input.trace?.append({ state: "SELECT_CONTEXT_SET", event: "exclusion", payload: { itemId: entry.item.itemId, claimId: entry.candidate.claim.claimId, section: entry.item.section, reason, detail, utility: entry.candidate.score.utility, tokenCost: entry.item.tokenCost, maxSimilarity: similarity } });
580
+ }
581
+ if (byReason.budget > 0) {
582
+ gaps.push({ sourceId: "mnemosia/selection", reason: "budget", detail: `${byReason.budget} candidate(s) did not fit the ${budget.total}-token budget and were excluded; the briefing is PARTIAL`, code: null });
583
+ }
584
+ // Selection order is stable, but the sections are rendered in design §10's order and a reader
585
+ // expects the strongest item first inside each of them.
586
+ selected.sort((a, b) => compareCandidates(a.candidate, b.candidate));
587
+ excluded.sort((a, b) => b.utility - a.utility || (a.claimId < b.claimId ? -1 : a.claimId > b.claimId ? 1 : 0));
588
+ return {
589
+ items: selected,
590
+ excluded,
591
+ budget,
592
+ partial,
593
+ gaps,
594
+ stats: {
595
+ candidates: all.length,
596
+ mandatoryCandidates: mandatory.length,
597
+ selected: selected.length,
598
+ excluded: excluded.length,
599
+ byReason,
600
+ bySection,
601
+ iterations,
602
+ stopReason,
603
+ objectiveTokens,
604
+ scaffoldingTokens,
605
+ },
606
+ };
607
+ }