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,525 @@
1
+ // Ported from mnemosia/rank.ts @ f0a8ad4 (MIT; see NOTICE)
2
+ /**
3
+ * The seven signals (design §9, spec §12, build-order step 10).
4
+ *
5
+ * Spec §12's central instruction is negative — "Keep these concepts separate" — and it names seven
6
+ * things that are routinely collapsed into one number: authority, evidence_strength, confidence,
7
+ * integrity, freshness, relevance and utility. This module computes the first six from disjoint
8
+ * inputs and composes the seventh out of them. Nothing here reads a signal it is not computing, so
9
+ * "separate" is a property of the call graph rather than of a comment:
10
+ *
11
+ * | signal | reads |
12
+ * |-----------------|----------------------------------------------------|
13
+ * | authority | the source's class, via the policy table |
14
+ * | evidenceStrength| directness and how many distinct artifacts support |
15
+ * | confidence | the claim's own certainty (+ curated importance) |
16
+ * | integrity | whether a hash check ran and passed |
17
+ * | freshness | effectiveAt against the claim type's half-life |
18
+ * | relevance | the task's terms, entities and scope |
19
+ * | utility | **only** the six above, through the policy weights |
20
+ *
21
+ * **Ranking never sees a hard-filter rejection.** `filters.ts` runs first and returns two disjoint
22
+ * lists; this module is handed the accepted one. That is why there is no threshold here that could
23
+ * readmit a rejected claim, and no code path that could: spec §11's "a candidate rejected by a hard
24
+ * filter must not be restored by a high semantic-relevance score" is enforced by the pipeline's
25
+ * shape, not by a check inside the ranker (see filters.ts's header for the other half of this).
26
+ *
27
+ * **Everything is recorded.** Spec §12: "All signal values and policy weights must be recorded in
28
+ * the orchestration trace." `rankCandidates` therefore emits one `score` event per candidate
29
+ * carrying every signal value, every weight, the resolved `policyId`, and the raw quantities each
30
+ * signal was computed from — because a recorded 0.43 that cannot be re-derived is a number, not an
31
+ * audit trail.
32
+ */
33
+ import { resolveAgent } from "./agents.js";
34
+ import { MODE_CONFIGS, RANK_SIGNALS, resolvePolicy } from "./policy.js";
35
+ import { buildProvenanceGraph, provenanceOf } from "./provenance.js";
36
+ import { temporalValidity } from "./temporal.js";
37
+ import { scopeKey } from "./types.js";
38
+ /* ------------------------------------------------------------------------------------------------
39
+ * Source classification
40
+ * ---------------------------------------------------------------------------------------------- */
41
+ function originOf(envelope, kind) {
42
+ for (const entry of envelope.provenance) {
43
+ if (entry !== null && typeof entry === "object" && entry.kind === kind)
44
+ return entry;
45
+ }
46
+ return null;
47
+ }
48
+ /**
49
+ * Envelope → the class design §9's authority table is keyed on.
50
+ *
51
+ * The `conversation_message` branch is the reason this function exists rather than being a map
52
+ * lookup on `sourceType`: user, assistant and tool turns all arrive under that one source type and
53
+ * the design separates them by 0.25 of authority. An event kind the adapter did not
54
+ * recognize falls to `unknown` rather than to the nearest neighbour, matching how claims.ts assigns
55
+ * its certainty (claims.ts:530-540) — the two must agree or a turn would be trusted by one module
56
+ * and doubted by the other.
57
+ */
58
+ export function authorityClassOf(envelope) {
59
+ switch (envelope.sourceType) {
60
+ case "curated_memory":
61
+ return "curated_memory";
62
+ case "compaction_summary":
63
+ return "compaction_summary";
64
+ case "tool_output":
65
+ return "tool_output";
66
+ case "conversation_message": {
67
+ const origin = originOf(envelope, "mnemosia/origin/conversation");
68
+ switch (origin?.eventKind) {
69
+ case "user":
70
+ return "user_message";
71
+ case "assistant":
72
+ return "assistant_message";
73
+ case "tool":
74
+ return "tool_output";
75
+ default:
76
+ return "unknown";
77
+ }
78
+ }
79
+ default:
80
+ return "unknown";
81
+ }
82
+ }
83
+ /* ------------------------------------------------------------------------------------------------
84
+ * The six input signals
85
+ * ---------------------------------------------------------------------------------------------- */
86
+ /**
87
+ * The standing of the best source that carried this claim.
88
+ *
89
+ * `max`, not `min` or a mean. Deduplication unions evidence across artifacts (claims.ts:746), so a
90
+ * sentence that appears in both a curated memory and an assistant turn ends up on one claim; taking
91
+ * the minimum would let the assistant turn *lower* the standing of a human-curated statement, i.e.
92
+ * corroboration would become a penalty. Authority is a claim about the source's right to be
93
+ * believed, and the strongest source that said it is the one that answers that.
94
+ */
95
+ export function authoritySignal(classes, policy) {
96
+ let best = 0;
97
+ for (const entry of classes)
98
+ best = Math.max(best, policy.authority[entry]);
99
+ return best;
100
+ }
101
+ /**
102
+ * **PHASE 2 — the graph replaces the list.**
103
+ *
104
+ * Phase 1: `min(1, 0.4·direct + 0.2·log2(1+supports))`, ceiling 0.4 when nothing was direct. That
105
+ * formula could ask two questions of a flat evidence array — how many artifacts, was any of them
106
+ * first-hand — and design §9's own note (kept below) recorded that the second question was answered
107
+ * the same way for every summary claim in the corpus, because Phase 1 had no way to tell a summary
108
+ * whose events were reachable from one whose events were nowhere.
109
+ *
110
+ * Phase 2 computes it from `provenance.ts`'s graph:
111
+ *
112
+ * ```
113
+ * raw = directBase·[distance = 1] + supportCoefficient·log2(1 + supportingArtifacts)
114
+ * + min(corroborationCap, corroborationBonus·(independentGroups − 1))
115
+ * ceiling = distance 1 → 1.0 · distance 2 → derivedCeiling · distance 3 → ungroundedCeiling
116
+ * value = clamp(min(raw, ceiling) − contradictionPenalty·contradictions, 0, 1)
117
+ * ```
118
+ *
119
+ * Three properties worth stating because each was a decision:
120
+ *
121
+ * - **Independence, not volume.** `supportingArtifacts` counts distinct artifacts, which stops one
122
+ * artifact cited three times looking like three witnesses. `independentGroups` counts distinct
123
+ * `sourceId | taskScope` groups, which stops one *session* cited three times doing the same — the
124
+ * common case on a corpus of 253 sessions. Only the second term is a corroboration bonus.
125
+ * - **The contradiction penalty applies *after* the ceiling.** This was written the other way round
126
+ * first and `test/rank.test.ts` caught it: subtracting before the cap means the penalty is
127
+ * swallowed whenever the uncapped value already exceeds the ceiling, which is the common case for a
128
+ * summary claim repeated across several artifacts — so a contradicted derived claim and an
129
+ * uncontradicted one both flattened onto exactly 0.4. The cap is a statement about *derivation*
130
+ * ("a summary may not outrank its evidence"); the penalty is a statement about *dispute*. They are
131
+ * different claims and composing them in the wrong order silences one of them.
132
+ * - **It reduces exactly to Phase 1's formula** when `independentGroups ≤ 1`, `contradictions = 0`
133
+ * and `graphDistance ≤ 2`. That is what keeps design §16's threshold table comparable across the
134
+ * phase boundary rather than silently re-baselined by a scoring change.
135
+ *
136
+ * Design §9's original sentence — "summaries without reachable raw events cap at 0.4" — is now
137
+ * literally implemented rather than approximated: *with* reachable events is 0.4, *without* is
138
+ * `ungroundedCeiling`.
139
+ */
140
+ export function evidenceStrengthSignal(input, policy) {
141
+ const { directBase, supportCoefficient, derivedCeiling, ungroundedCeiling, corroborationBonus, corroborationCap, contradictionPenalty } = policy.evidence;
142
+ const direct = input.graphDistance === 1 ? 1 : 0;
143
+ const corroboration = Math.min(corroborationCap, corroborationBonus * Math.max(0, input.independentGroups - 1));
144
+ const raw = directBase * direct + supportCoefficient * Math.log2(1 + Math.max(0, input.supportingArtifacts)) + corroboration;
145
+ const ceiling = input.graphDistance <= 1 ? 1 : input.graphDistance === 2 ? derivedCeiling : ungroundedCeiling;
146
+ const capped = Math.min(raw, ceiling);
147
+ return Math.max(0, Math.min(1, capped - contradictionPenalty * Math.max(0, input.contradictions)));
148
+ }
149
+ /**
150
+ * The claim's own certainty, blended with the curator's importance for governed rows.
151
+ *
152
+ * Confidence is deliberately the only signal that reads `certainty`. It is "calibrated certainty in
153
+ * the normalized claim" (spec §12) — a statement about the claim, not about who stored it — so the
154
+ * source's standing stays in `authority` and the hash check stays in `integrity`.
155
+ *
156
+ * See `RankingPolicy.curatedImportanceWeight` for why the design's "× importance/10" is applied as a
157
+ * weighted mean rather than a product; measured against the live vault, the product form ranks a
158
+ * human-curated memory below a model's paraphrase.
159
+ */
160
+ export function confidenceSignal(certainty, importance, policy) {
161
+ const base = policy.certaintyConfidence[certainty];
162
+ if (importance === null)
163
+ return base;
164
+ const normalized = Math.max(0, Math.min(1, importance / 10));
165
+ const weight = policy.curatedImportanceWeight;
166
+ return (1 - weight) * base + weight * normalized;
167
+ }
168
+ /**
169
+ * Whether verification ran and passed.
170
+ *
171
+ * `max` over the claim's artifacts, for the same reason as `authority`: a claim standing on one
172
+ * hash-verified curated row and one unverifiable conversation event *has* been verified by the first, and
173
+ * the second cannot un-verify it. `failed` never appears here — filters.ts removed those artifacts,
174
+ * and a claim with no surviving artifact was rejected outright.
175
+ */
176
+ export function integritySignal(statuses, policy) {
177
+ let best = 0;
178
+ for (const status of statuses)
179
+ best = Math.max(best, policy.integrityScore[status]);
180
+ return best;
181
+ }
182
+ /** Design §9: `exp(-ln2 · ageDays / halfLife)`. A future `effectiveAt` is clamped to age 0, not -n. */
183
+ export function freshnessSignal(ageDays, halfLifeDays) {
184
+ if (halfLifeDays <= 0)
185
+ return 0;
186
+ return Math.exp((-Math.LN2 * Math.max(0, ageDays)) / halfLifeDays);
187
+ }
188
+ /**
189
+ * Design §9: relevance + 0.1 tag + 0.1 entity + 0.05 exact-scope, clamped.
190
+ *
191
+ * **PHASE 6 — the base term is FTS5's `bm25()`, with term coverage as the deterministic fallback.**
192
+ * Design §3 pre-registered the foundation ask (*"the DB computes a better relevance signal than term
193
+ * coverage and currently discards it"*), §18 risk 1 put it first in the fallback order and §19 item 5
194
+ * made it an approval item; §16's Phase 1E note deferred it because the cheaper planner fix had
195
+ * already cleared the absolute gate. It is exercised now because the *residual* 0.127 is ranking
196
+ * work: six items over nineteen tasks, all of them reached by a **single common word** shared with
197
+ * the task. That is the one distinction term coverage structurally cannot draw — `matched/|terms|`
198
+ * prices every matched word identically, so a shared `role` and a shared `compaction` are the
199
+ * same evidence to it. bm25 prices a word by its inverse document frequency, which is exactly the
200
+ * missing quantity.
201
+ *
202
+ * Coverage is still computed on every claim and still recorded, for three reasons: it is the
203
+ * fallback spec §12 requires whenever the read published no score (every recency scan); keeping it in the trace lets a replay see both numbers and judge the substitution; and
204
+ * a signal that quietly stopped being computed is a signal nobody can audit.
205
+ *
206
+ * Coverage is measured against `TaskAnalysis.terms` — the **wide** set — and not against the three
207
+ * terms `plan.ts` actually sent to FTS5. plan.ts:15-21 explains the split from the other side: the
208
+ * query is narrow because the store ANDs its terms, but relevance is the fine discrimination that
209
+ * narrowing gave up, so measuring it against the narrow set would score every retrieved artifact at
210
+ * or near 1.0 and the signal would carry no information at all.
211
+ *
212
+ * The claim text is tokenized with the store's own tokenizer (injected, see task.ts:239) so that a
213
+ * term and a claim word are compared on the same rules the index was built with.
214
+ *
215
+ * **The two are not on the same scale, and that is stated rather than smoothed over.** A run in
216
+ * which some claims are priced by bm25 and others by coverage is mixing two orderings; the mixture
217
+ * is confined to the *base* term, both numbers ride in the trace, and `basis` names which one was
218
+ * used per candidate. The alternative — blending them — would produce a number that is neither, and
219
+ * spec §12 asks for a fallback, not an average.
220
+ */
221
+ export function relevanceSignal(claimText, tokenize, terms, entities, claimScope, ownScopeKeys, tags, policy, rank = { raw: null, normalized: null }) {
222
+ const claimTokens = new Set(tokenize(claimText).map((token) => token.toLowerCase()));
223
+ let matched = 0;
224
+ for (const term of terms) {
225
+ if (claimTokens.has(term.toLowerCase()))
226
+ matched += 1;
227
+ }
228
+ const coverage = terms.length === 0 ? 0 : matched / terms.length;
229
+ // A tag bonus asks whether the *curator* filed this row under a word the task used. Only curated
230
+ // rows carry tags, so this is structurally a curated-memory bonus and is priced as one.
231
+ let tagHit = false;
232
+ for (const term of terms) {
233
+ if (tags.has(term.toLowerCase())) {
234
+ tagHit = true;
235
+ break;
236
+ }
237
+ }
238
+ // Entities are matched as substrings of the raw text rather than as tokens: `store.ts` and
239
+ // `d:\mnemosia\src` do not survive tokenization intact, and they are exactly the spans the author
240
+ // typed deliberately (task.ts:195-224).
241
+ const haystack = claimText.toLowerCase();
242
+ let entityHit = false;
243
+ for (const entity of entities) {
244
+ if (entity.length >= 3 && haystack.includes(entity)) {
245
+ entityHit = true;
246
+ break;
247
+ }
248
+ }
249
+ const tag = tagHit ? policy.relevanceBonus.tag : 0;
250
+ const entity = entityHit ? policy.relevanceBonus.entity : 0;
251
+ const exactScope = ownScopeKeys.has(claimScope) ? policy.relevanceBonus.exactScope : 0;
252
+ const basis = rank.normalized === null ? "term_coverage" : "bm25";
253
+ const base = rank.normalized ?? coverage;
254
+ return {
255
+ coverage,
256
+ matchedTerms: matched,
257
+ queryTerms: terms.length,
258
+ rankRaw: rank.raw,
259
+ rankNormalized: rank.normalized,
260
+ basis,
261
+ base,
262
+ tag,
263
+ entity,
264
+ exactScope,
265
+ value: Math.max(0, Math.min(1, base + tag + entity + exactScope)),
266
+ };
267
+ }
268
+ /**
269
+ * The scale each source's raw bm25 values are divided by, computed once per run.
270
+ *
271
+ * **bm25 is a per-query, per-index quantity and this is what makes it a signal.** Two things set its
272
+ * magnitude, and only one of them is information:
273
+ *
274
+ * - *How surprising the matched words are* — `Σ idf(t)·tfNorm(t,d)`. This is the signal. A document
275
+ * that answered a rare word scores far below one that answered a common word, and on this corpus
276
+ * FTS5 clamps the IDF of a term occurring in half the index or more to `1e-6`, so a match on a
277
+ * genuinely common word scores ≈ 0. That is the discrimination §16's residual 0.127 needs.
278
+ * - *How large the index is and how many terms the query carried* — an artifact. A large corpus holds
279
+ * 11,182 documents and the curated vault holds ten, so the same rare word is worth `ln(11182/1.5)`
280
+ * ≈ 8.9 there and at most `ln(9.5/1.5)` ≈ 1.85 here. Comparing the two raw would demote every
281
+ * curated memory against every conversation event for a reason that has nothing to do with either.
282
+ *
283
+ * Dividing by the best magnitude **that same source produced in this run** removes the second
284
+ * without touching the first: every element of a source's set was scored by one query specification
285
+ * against one index, so the division is by a constant within the set and the within-source ordering
286
+ * is preserved exactly. What survives across sources is each artifact's share of the discriminative
287
+ * mass its own source found — which is a comparison that means something, where the raw numbers were
288
+ * not.
289
+ *
290
+ * Three consequences, stated because each is a cost:
291
+ *
292
+ * 1. **The best artifact of every source scores 1.0**, however weak the match objectively was. That
293
+ * is the price of scale-freeness, and it is why relevance stays one weighted signal of six rather
294
+ * than a gate — nothing here can readmit a hard-filter rejection or outvote the other five.
295
+ * *Measured, and recorded here rather than fixed quietly:* on gold task G11 a source returned
296
+ * three documents, the best of them a generic "read this before every web-design task" guidance
297
+ * note, and this normalization gives it `relevance = 1.000` where term coverage gave it 0.111.
298
+ * The reading is literally true — of the three, it matched best — but a *relative* quantity
299
+ * summed with five absolute ones is a category error whenever a source's whole result set is
300
+ * weak. The absolute alternative (divide by the index's achievable maximum, `|query| · maxIdf(N)
301
+ * · (k1+1)`) needs the index size FTS5 does not expose and a saturation constant nobody has
302
+ * measured, and design §19 item 3 makes a number chosen after seeing the corpus a human decision.
303
+ * So the relative form ships, the counterexample is written down, and the absolute form is the
304
+ * next thing to measure. It changed no §16 number in either direction (see §16's Phase 6 note).
305
+ * 2. **A source whose every match scored ≈ 0** (all query terms clamped) has `best = 0`, and every
306
+ * artifact from it takes `0`. That is the correct reading — the index says those words separate
307
+ * nothing — rather than a division that would amplify noise into 1.0.
308
+ * 3. **An artifact's relevance depends on what else the same source returned.** Any per-query
309
+ * normalization has this property. It is deterministic given the run, it is recorded raw in the
310
+ * trace so a replay can re-derive it, and the alternative — an absolute scale — does not exist
311
+ * without the index statistics FTS5 does not expose.
312
+ *
313
+ * Grouping is by `sourceId` rather than by query string because a source issues exactly one query
314
+ * specification per run: the term ladder retries only on an *empty* result, so at most one
315
+ * rung contributes envelopes, and the curated disjunction is summed back into a single score per row
316
+ * by the adapter (see `akashic-memories.ts`).
317
+ */
318
+ export function normalizeRetrievalScores(envelopes) {
319
+ const best = {};
320
+ let scored = 0;
321
+ let unscored = 0;
322
+ for (const envelope of envelopes) {
323
+ if (envelope.retrievalScore === null) {
324
+ unscored += 1;
325
+ continue;
326
+ }
327
+ scored += 1;
328
+ const magnitude = Math.abs(envelope.retrievalScore);
329
+ best[envelope.sourceId] = Math.max(best[envelope.sourceId] ?? 0, magnitude);
330
+ }
331
+ return { best, scored, unscored };
332
+ }
333
+ /**
334
+ * The best normalized score among the artifacts behind one claim, or `null` when none published one.
335
+ *
336
+ * `max` of the normalized values, for the same reason `authority` and `integrity` take a max: a
337
+ * claim that appears in both a strongly-matching artifact and a weakly-matching one *was* found by
338
+ * the strong one, and letting the weak one drag it down would make corroboration a penalty. The raw
339
+ * score reported alongside is the raw score of the artifact that won, not the raw maximum, so the
340
+ * two fields in the trace describe the same artifact.
341
+ */
342
+ export function claimRetrievalScore(envelopes, scale) {
343
+ let bestNormalized = null;
344
+ let bestRaw = null;
345
+ for (const envelope of envelopes) {
346
+ if (envelope.retrievalScore === null)
347
+ continue;
348
+ const divisor = scale.best[envelope.sourceId] ?? 0;
349
+ const normalized = divisor === 0 ? 0 : Math.min(1, Math.abs(envelope.retrievalScore) / divisor);
350
+ if (bestNormalized === null || normalized > bestNormalized) {
351
+ bestNormalized = normalized;
352
+ bestRaw = envelope.retrievalScore;
353
+ }
354
+ }
355
+ return { raw: bestRaw, normalized: bestNormalized };
356
+ }
357
+ /* ------------------------------------------------------------------------------------------------
358
+ * Composition
359
+ * ---------------------------------------------------------------------------------------------- */
360
+ /**
361
+ * `Σ wᵢ·signalᵢ` over the six inputs, and nothing else.
362
+ *
363
+ * Token cost and redundancy are *not* applied here even though design §9's utility row mentions
364
+ * them, because they are properties of a candidate's position in a partially-built briefing rather
365
+ * than of the candidate: the same claim is cheap when it is the first thing selected and redundant
366
+ * when it is the fifth. Discounting them at scoring time would freeze one particular selection order
367
+ * into the score. select.ts applies both, at selection time, exactly as design §10 writes it.
368
+ */
369
+ export function composeUtility(signals, weights) {
370
+ let total = 0;
371
+ for (const signal of RANK_SIGNALS)
372
+ total += weights[signal] * signals[signal];
373
+ return total;
374
+ }
375
+ const DAY_MS = 86_400_000;
376
+ /**
377
+ * The total order design §10 tie-breaks with: `(utility desc, effectiveAt desc, claimId asc)`.
378
+ *
379
+ * Exported and used by both this module and select.ts, because two definitions of "the same order"
380
+ * are two chances for the §16 determinism gate to fail on a machine with a different sort stability.
381
+ */
382
+ export function compareCandidates(a, b) {
383
+ if (a.score.utility !== b.score.utility)
384
+ return b.score.utility - a.score.utility;
385
+ if (a.claim.effectiveAt !== b.claim.effectiveAt)
386
+ return b.claim.effectiveAt - a.claim.effectiveAt;
387
+ return a.claim.claimId < b.claim.claimId ? -1 : a.claim.claimId > b.claim.claimId ? 1 : 0;
388
+ }
389
+ export function scoreCandidate(claim, envelopes, analysis, policy, tokenize, ownScopeKeys, entities, now, graph,
390
+ /** Absent means no source published a bm25 in this run; every candidate then falls back to coverage. */
391
+ scale = { best: {}, scored: 0, unscored: 0 }) {
392
+ const artifactIds = [...new Set(claim.evidence.map((item) => item.artifactId))];
393
+ const resolved = artifactIds.map((artifactId) => envelopes.get(artifactId)).filter((entry) => entry !== undefined);
394
+ const missingArtifacts = artifactIds.length - resolved.length;
395
+ const authorityClasses = resolved.map(authorityClassOf);
396
+ const integrityStatuses = resolved.map((envelope) => envelope.integrityStatus);
397
+ const memoryOrigins = resolved.map((envelope) => originOf(envelope, "mnemosia/origin/akashic-memory")).filter((entry) => entry !== null);
398
+ // The highest importance among the curated rows backing this claim, or null when none is curated.
399
+ const importance = memoryOrigins.length === 0 ? null : Math.max(...memoryOrigins.map((origin) => origin.importance));
400
+ const tags = new Set();
401
+ for (const origin of memoryOrigins)
402
+ for (const tag of origin.tags)
403
+ tags.add(tag.toLowerCase());
404
+ // `SUPPORTS` only. A SUPERSEDES link is a statement about another claim, not corroboration of
405
+ // this one, and counting it would let a claim strengthen itself by retiring something.
406
+ const supportingArtifacts = new Set(claim.evidence.filter((item) => item.relation === "SUPPORTS").map((item) => item.artifactId)).size;
407
+ const directness = [...new Set(claim.evidence.map((item) => item.directness))];
408
+ const memoryKind = memoryOrigins[0]?.memoryKind;
409
+ const overriddenHalfLife = memoryKind === undefined ? undefined : policy.halfLifeDaysByMemoryKind[memoryKind];
410
+ const halfLifeDays = overriddenHalfLife ?? policy.halfLifeDays[claim.claimType];
411
+ const halfLifeSource = overriddenHalfLife === undefined ? "claim_type" : "memory_kind";
412
+ const ageDays = (now - claim.effectiveAt) / DAY_MS;
413
+ const relevance = relevanceSignal(claim.text, tokenize, analysis.terms.value, entities, scopeKey(claim.scope), ownScopeKeys, tags, policy, claimRetrievalScore(resolved, scale));
414
+ const provenance = provenanceOf(graph, claim.claimId, temporalValidity(claim, now));
415
+ const signals = {
416
+ authority: authoritySignal(authorityClasses, policy),
417
+ evidenceStrength: evidenceStrengthSignal({ graphDistance: provenance.graphDistance, supportingArtifacts, independentGroups: provenance.independentGroups, contradictions: provenance.contradictedBy.length }, policy),
418
+ confidence: confidenceSignal(claim.certainty, importance, policy),
419
+ integrity: integritySignal(integrityStatuses, policy),
420
+ freshness: freshnessSignal(ageDays, halfLifeDays),
421
+ relevance: relevance.value,
422
+ };
423
+ return {
424
+ claim,
425
+ score: { ...signals, utility: composeUtility(signals, policy.weights) },
426
+ weights: policy.weights,
427
+ policyId: policy.policyId,
428
+ basis: {
429
+ authorityClasses,
430
+ channels: [...new Set(resolved.map((envelope) => envelope.channel))],
431
+ directness,
432
+ supportingArtifacts,
433
+ certainty: claim.certainty,
434
+ importance,
435
+ integrityStatuses,
436
+ ageDays,
437
+ halfLifeDays,
438
+ halfLifeSource,
439
+ relevance,
440
+ missingArtifacts,
441
+ graphDistance: provenance.graphDistance,
442
+ distanceBasis: provenance.distanceBasis,
443
+ independentGroups: provenance.independentGroups,
444
+ grounding: provenance.grounding,
445
+ contradictions: provenance.contradictedBy.length,
446
+ supersedesTransitive: provenance.supersedesTransitive.length,
447
+ temporal: provenance.temporal,
448
+ qualifiers: provenance.qualifiers,
449
+ },
450
+ };
451
+ }
452
+ /**
453
+ * Scores every accepted claim and returns them in the canonical order.
454
+ *
455
+ * The `mode` fed to the policy chain is the analysis's mode. `MODE_CONFIGS` is consulted only to
456
+ * record the candidate cap alongside the scores: a run whose candidate set was clipped by the mode
457
+ * ranked a prefix of the corpus, and a replay that cannot see that would over-read the scores.
458
+ */
459
+ export function rankCandidates(input) {
460
+ const now = input.now ?? Date.now();
461
+ const analysis = input.analysis;
462
+ const resolution = input.policy === undefined
463
+ ? resolvePolicy(analysis.requestingAgent, analysis.taskType.value, analysis.mode.value)
464
+ : { policy: input.policy, matchedBy: "default", attempted: ["(supplied by the caller)"], resolvedAgent: resolveAgent(analysis.requestingAgent).agent };
465
+ const policy = resolution.policy;
466
+ const graph = input.graph ?? buildProvenanceGraph({ claims: input.claims, envelopes: input.envelopes, now, shingleSize: policy.selection.shingleSize, neighbourhoodThreshold: policy.conflict.neighbourhoodThreshold });
467
+ const envelopeIndex = new Map(input.envelopes.map((envelope) => [envelope.artifactId, envelope]));
468
+ // Computed over **every** envelope the run normalized, not over the post-filter survivors: the
469
+ // scale is a property of what the source found, and letting hard filtering move it would make an
470
+ // artifact's relevance depend on whether an unrelated claim was quarantined.
471
+ const scale = normalizeRetrievalScores(input.envelopes);
472
+ const ownScopeKeys = new Set();
473
+ if (analysis.project.value !== null)
474
+ ownScopeKeys.add(scopeKey({ level: "project", project: analysis.project.value }));
475
+ const entities = analysis.entities.value.map((entity) => entity.text.toLowerCase());
476
+ input.trace?.append({
477
+ state: "SCORE_CANDIDATES",
478
+ event: "transition",
479
+ policyId: policy.policyId,
480
+ policyVersion: policy.version,
481
+ payload: {
482
+ resolvedBy: resolution.matchedBy,
483
+ attempted: resolution.attempted,
484
+ weights: policy.weights,
485
+ rationale: policy.rationale,
486
+ candidates: input.claims.length,
487
+ modeCandidateCap: MODE_CONFIGS[analysis.mode.value].maxCandidates,
488
+ // Spec §12: every input to a ranking decision must be recoverable. The bm25 scale is an
489
+ // input to `relevance` on every candidate, and it is one object rather than a repeated
490
+ // field, so it belongs on the transition instead of inside each `score` payload.
491
+ retrievalScoreScale: scale,
492
+ },
493
+ });
494
+ const candidates = input.claims.map((claim) => scoreCandidate(claim, envelopeIndex, analysis, policy, input.tokenize, ownScopeKeys, entities, now, graph, scale));
495
+ candidates.sort(compareCandidates);
496
+ const byAuthorityClass = {};
497
+ let total = 0;
498
+ let max = 0;
499
+ let min = candidates.length === 0 ? 0 : 1;
500
+ for (const candidate of candidates) {
501
+ total += candidate.score.utility;
502
+ max = Math.max(max, candidate.score.utility);
503
+ min = Math.min(min, candidate.score.utility);
504
+ for (const entry of new Set(candidate.basis.authorityClasses))
505
+ byAuthorityClass[entry] = (byAuthorityClass[entry] ?? 0) + 1;
506
+ // Spec §12: every signal value and every policy weight, per candidate, in the trace.
507
+ input.trace?.append({
508
+ state: "SCORE_CANDIDATES",
509
+ event: "score",
510
+ policyId: policy.policyId,
511
+ policyVersion: policy.version,
512
+ payload: { claimId: candidate.claim.claimId, claimType: candidate.claim.claimType, signals: candidate.score, weights: candidate.weights, basis: candidate.basis },
513
+ });
514
+ }
515
+ return {
516
+ candidates,
517
+ resolution,
518
+ graph,
519
+ stats: { scored: candidates.length, meanUtility: candidates.length === 0 ? 0 : total / candidates.length, maxUtility: max, minUtility: min, byAuthorityClass },
520
+ };
521
+ }
522
+ /** Convenience for the trace and for `explainDecision`: the signal vector as an ordered list. */
523
+ export function signalBreakdown(candidate) {
524
+ return RANK_SIGNALS.map((signal) => ({ signal, value: candidate.score[signal], weight: candidate.weights[signal], contribution: candidate.weights[signal] * candidate.score[signal] }));
525
+ }