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,458 @@
1
+ // Ported from mnemosia/provenance.ts @ f0a8ad4 (MIT; see NOTICE)
2
+ /**
3
+ * The provenance graph (spec §25 Phase 2, spec §12 `graph_distance`, design §7 `Evidence.relation`).
4
+ *
5
+ * Phase 1 carried provenance as a **flat list**: each claim held an array of `Evidence`, every entry
6
+ * of which was `SUPPORTS`, and the only question anything asked of it was "how many artifacts are in
7
+ * this array". That is enough to answer *whether* a claim is sourced. It cannot answer the two
8
+ * questions Phase 2 exists to answer — **how directly** a claim is supported, and **what else in the
9
+ * run relates to it** — because both are questions about a structure, and a list is not one.
10
+ *
11
+ * This module builds the structure. Nodes are artifacts and claims; edges are the five relations
12
+ * design §7 declared and Phase 1 left mostly unused:
13
+ *
14
+ * | relation | Phase 1 | Phase 2 |
15
+ * |-----------------|---------|---------|
16
+ * | `SUPPORTS` | emitted | unchanged — a claim standing on an artifact |
17
+ * | `SUPERSEDES` | declared, never emitted as an edge | claim → the claim it retires, transitively closed |
18
+ * | `CONTRADICTS` | never | claim ↔ claim, from `relations.ts`'s deterministic predicates |
19
+ * | `QUALIFIES` | never | claim ↔ claim, where a branch/environment qualifier diverges |
20
+ * | `TEMPORAL_BOUND`| never | claim → claim, where one's validity interval ends before the other's begins |
21
+ *
22
+ * **Why the graph is built before ranking rather than inside conflict detection.** The state machine
23
+ * runs `SCORE_CANDIDATES` before `DETECT_CONFLICTS` (spec §7), and Phase 2's evidence-strength signal
24
+ * needs corroboration counts and contradiction counts — both graph properties. Deriving them inside
25
+ * `conflicts.ts` would mean either reordering the machine or scoring against a graph that does not
26
+ * exist yet. So the graph is the shared substrate: it computes *structure*, deterministically, from
27
+ * the accepted claim set alone, and `conflicts.ts` computes *classification and resolution* on top of
28
+ * it. Neither duplicates the other's work, and the trace records the graph once.
29
+ *
30
+ * **`graph_distance` is distance to the nearest primary observation**, not to an arbitrary root:
31
+ *
32
+ * ```
33
+ * 1 the claim stands on an artifact directly — a curated row, a user turn, a tool transcript
34
+ * 2 the claim reached us only through a summary, and that summary's own sources are in this run
35
+ * 3 the claim reached us only through a summary whose sources this run could not reach
36
+ * ```
37
+ *
38
+ * Distance 3 is the honest label for "a polished account of something nobody here can check". It is
39
+ * not by itself a conflict — absence of the underlying events is a *corpus* fact, exactly as design
40
+ * §16's Phase 1E note distinguishes `INSUFFICIENT_INFORMATION` from `RETRIEVAL_UNAVAILABLE` — but it
41
+ * is the ceiling that stops such a claim outranking the raw evidence it paraphrases.
42
+ */
43
+ import { extractQualifiers, QUALIFIER_RANKING } from "./qualifiers.js";
44
+ import { branchDifference, environmentDifference, keyValueDivergence, negationDivergence } from "./relations.js";
45
+ import { candidatePairs, profileOf } from "./similarity.js";
46
+ import { temporalValidity, temporallyDisjoint } from "./temporal.js";
47
+ /* ------------------------------------------------------------------------------------------------
48
+ * Grounding
49
+ * ---------------------------------------------------------------------------------------------- */
50
+ /** Source types that are an observation rather than an account of one. */
51
+ export const PRIMARY_SOURCE_TYPES = new Set(["curated_memory", "conversation_message", "tool_output"]);
52
+ /**
53
+ * How well an artifact's own sources can be reached from inside this run.
54
+ *
55
+ * `session_absent` and `refs_unresolved` are deliberately different states even though both mean
56
+ * "the underlying events are not here". The first is a property of *this retrieval* — the corpus
57
+ * holds far more events than a run reads, so a summary whose session contributed
58
+ * nothing to the candidate set is unremarkable. The second is a property of the *artifact*: an
59
+ * artifact that declares source references names them as part of its own contract, so refs that name
60
+ * nothing are a defect in the summary rather than a limit on the reader. Only the second is a
61
+ * conflict (design §11's `SUMMARY_SOURCE_MISMATCH`); collapsing them would report every summary in
62
+ * the corpus as poisoned.
63
+ */
64
+ export const GROUNDING_STATES = ["primary", "grounded", "session_absent", "refs_unresolved", "refs_absent", "integrity_failed"];
65
+ /**
66
+ * Resolves one declared source reference against the artifacts this run normalized.
67
+ *
68
+ * Only an exact artifact id resolves. A reference that names nothing this run normalized is
69
+ * reported as unresolved, so the answer "this run holds nothing by that name" is reached by having
70
+ * looked rather than by assuming.
71
+ */
72
+ function resolveRef(ref, artifactIds) {
73
+ if (artifactIds.has(ref))
74
+ return ref;
75
+ return null;
76
+ }
77
+ /**
78
+ * Grounding for every artifact in the run.
79
+ *
80
+ * Computed over the whole envelope set rather than over the artifacts that produced claims, because
81
+ * "does this summary's session appear in the candidate set" is a question about what was *read*, and
82
+ * an envelope that produced no claims still proves its session was reachable.
83
+ */
84
+ export function groundArtifacts(envelopes) {
85
+ // sourceId|sessionId -> the primary artifacts read from that session.
86
+ const primaryBySession = new Map();
87
+ for (const envelope of envelopes) {
88
+ if (!PRIMARY_SOURCE_TYPES.has(envelope.sourceType))
89
+ continue;
90
+ if (envelope.taskScope === null)
91
+ continue;
92
+ const key = `${envelope.sourceId}${envelope.taskScope}`;
93
+ const bucket = primaryBySession.get(key);
94
+ if (bucket === undefined)
95
+ primaryBySession.set(key, [envelope.artifactId]);
96
+ else
97
+ bucket.push(envelope.artifactId);
98
+ }
99
+ const result = new Map();
100
+ for (const envelope of envelopes) {
101
+ if (envelope.integrityStatus === "failed") {
102
+ result.set(envelope.artifactId, { artifactId: envelope.artifactId, sourceType: envelope.sourceType, state: "integrity_failed", groundedBy: [], unresolvedRefs: [], detail: "the artifact's integrity check failed, so nothing it carries can be grounded" });
103
+ continue;
104
+ }
105
+ if (PRIMARY_SOURCE_TYPES.has(envelope.sourceType)) {
106
+ result.set(envelope.artifactId, { artifactId: envelope.artifactId, sourceType: envelope.sourceType, state: "primary", groundedBy: [], unresolvedRefs: [], detail: "a primary observation: it is the evidence rather than an account of it" });
107
+ continue;
108
+ }
109
+ // AkashicForge compaction summary: no per-claim source references exist in the schema, so the
110
+ // session it was written into is the only handle on its evidence.
111
+ const key = envelope.taskScope === null ? null : `${envelope.sourceId}${envelope.taskScope}`;
112
+ const siblings = key === null ? undefined : primaryBySession.get(key);
113
+ if (siblings === undefined || siblings.length === 0) {
114
+ result.set(envelope.artifactId, {
115
+ artifactId: envelope.artifactId,
116
+ sourceType: envelope.sourceType,
117
+ state: "session_absent",
118
+ groundedBy: [],
119
+ unresolvedRefs: [],
120
+ detail: envelope.taskScope === null ? "the summary carries no session, so its underlying events cannot be located at all" : `this run normalized no primary event from session ${envelope.taskScope}`,
121
+ });
122
+ continue;
123
+ }
124
+ result.set(envelope.artifactId, {
125
+ artifactId: envelope.artifactId,
126
+ sourceType: envelope.sourceType,
127
+ state: "grounded",
128
+ groundedBy: [...siblings].sort(),
129
+ unresolvedRefs: [],
130
+ detail: `${siblings.length} primary event(s) from session ${envelope.taskScope} are in this run`,
131
+ });
132
+ }
133
+ return result;
134
+ }
135
+ /* ------------------------------------------------------------------------------------------------
136
+ * Construction
137
+ * ---------------------------------------------------------------------------------------------- */
138
+ function emptyByRelation() {
139
+ return { SUPPORTS: 0, CONTRADICTS: 0, SUPERSEDES: 0, QUALIFIES: 0, TEMPORAL_BOUND: 0 };
140
+ }
141
+ function emptyByGrounding() {
142
+ return { primary: 0, grounded: 0, session_absent: 0, refs_unresolved: 0, refs_absent: 0, integrity_failed: 0 };
143
+ }
144
+ /**
145
+ * The transitive closure of `supersedes`, with cycle protection.
146
+ *
147
+ * A cycle — A retires B retires A — is not hypothetical once supersession links can come from
148
+ * content rather than only from a governance column: a poisoned artifact could assert one. It is
149
+ * broken by the visited set rather than by trusting the data, and the claims involved keep every
150
+ * link they declared, so the cycle is visible in the graph instead of being silently pruned.
151
+ */
152
+ function transitiveClosure(direct, start) {
153
+ const reachable = new Set();
154
+ let depth = 0;
155
+ let frontier = [...(direct.get(start) ?? [])];
156
+ while (frontier.length > 0) {
157
+ depth += 1;
158
+ const next = [];
159
+ for (const claimId of frontier) {
160
+ if (claimId === start || reachable.has(claimId))
161
+ continue;
162
+ reachable.add(claimId);
163
+ next.push(...(direct.get(claimId) ?? []));
164
+ }
165
+ frontier = next;
166
+ // A chain cannot be longer than the claim set; the visited set already guarantees termination,
167
+ // and this bound only stops a pathological self-referential frontier from spinning.
168
+ if (depth > direct.size + 1)
169
+ break;
170
+ }
171
+ return { reachable: [...reachable].sort(), depth: reachable.size === 0 ? 0 : depth };
172
+ }
173
+ export function buildProvenanceGraph(input) {
174
+ const { claims, envelopes, now } = input;
175
+ const shingleSize = input.shingleSize ?? 3;
176
+ const threshold = input.neighbourhoodThreshold ?? 0.6;
177
+ const envelopeIndex = new Map(envelopes.map((envelope) => [envelope.artifactId, envelope]));
178
+ const grounding = groundArtifacts(envelopes);
179
+ const edges = [];
180
+ const claimsByArtifact = new Map();
181
+ const qualifiersByClaim = new Map();
182
+ const profilesByClaim = new Map();
183
+ const partial = new Map();
184
+ for (const claim of claims) {
185
+ qualifiersByClaim.set(claim.claimId, extractQualifiers(claim.text));
186
+ profilesByClaim.set(claim.claimId, profileOf(claim.dedupKey, shingleSize));
187
+ const supporting = [];
188
+ const groups = new Set();
189
+ let bestDistance = Number.POSITIVE_INFINITY;
190
+ let bestBasis = "no supporting artifact resolved in this run";
191
+ let bestGrounding = "session_absent";
192
+ const unresolvedRefs = [];
193
+ for (const evidence of claim.evidence) {
194
+ const envelope = envelopeIndex.get(evidence.artifactId);
195
+ const bucket = claimsByArtifact.get(evidence.artifactId);
196
+ if (bucket === undefined)
197
+ claimsByArtifact.set(evidence.artifactId, [claim.claimId]);
198
+ else if (!bucket.includes(claim.claimId))
199
+ bucket.push(claim.claimId);
200
+ edges.push({
201
+ from: claim.claimId,
202
+ to: evidence.artifactId,
203
+ toKind: envelope === undefined ? "external" : "artifact",
204
+ relation: evidence.relation,
205
+ directness: evidence.directness,
206
+ locator: evidence.locator,
207
+ basis: envelope === undefined ? "the evidence names an artifact this run did not normalize" : `${evidence.relation.toLowerCase()} via ${envelope.sourceType}`,
208
+ });
209
+ if (evidence.relation !== "SUPPORTS")
210
+ continue;
211
+ if (envelope === undefined)
212
+ continue;
213
+ supporting.push(evidence.artifactId);
214
+ groups.add(`${envelope.sourceId}${envelope.taskScope ?? evidence.artifactId}`);
215
+ const state = grounding.get(evidence.artifactId)?.state ?? "session_absent";
216
+ const refs = grounding.get(evidence.artifactId)?.unresolvedRefs ?? [];
217
+ for (const ref of refs)
218
+ if (!unresolvedRefs.includes(ref))
219
+ unresolvedRefs.push(ref);
220
+ // The claim's own directness wins over the artifact's source type: `claims.ts` marks a
221
+ // summary-derived claim `derived` even though the summary artifact is itself a real
222
+ // document, and it is the *claim's* route to evidence that distance measures.
223
+ const distance = evidence.directness === "direct" && state === "primary" ? 1 : state === "grounded" ? 2 : 3;
224
+ if (distance < bestDistance) {
225
+ bestDistance = distance;
226
+ bestGrounding = state;
227
+ bestBasis =
228
+ distance === 1
229
+ ? `direct evidence on ${envelope.sourceType} ${evidence.artifactId}`
230
+ : distance === 2
231
+ ? `derived through ${envelope.sourceType} ${evidence.artifactId}, whose own sources are in this run (${grounding.get(evidence.artifactId)?.detail ?? ""})`
232
+ : `derived through ${envelope.sourceType} ${evidence.artifactId}, whose sources this run could not reach (${grounding.get(evidence.artifactId)?.detail ?? ""})`;
233
+ }
234
+ }
235
+ partial.set(claim.claimId, {
236
+ supporting: [...new Set(supporting)].sort(),
237
+ groupKeys: [...groups].sort(),
238
+ grounding: bestGrounding,
239
+ unresolvedRefs: unresolvedRefs.sort(),
240
+ graphDistance: Number.isFinite(bestDistance) ? bestDistance : 3,
241
+ distanceBasis: bestBasis,
242
+ });
243
+ }
244
+ /* --- SUPERSEDES edges, direct then transitive ----------------------------------------------- */
245
+ //
246
+ // A claim's `supersedes` names *artifacts* (claims.ts converts AkashicForge's bare memory id into
247
+ // artifact-id form so both namespaces agree). Every claim standing on a retired artifact is
248
+ // retired by that link, which is what turns an artifact-level governance fact into the claim-level
249
+ // edges the graph needs.
250
+ //
251
+ // References resolve against the union of the normalized envelopes and the artifacts the run's
252
+ // own evidence names. The second half matters: a caller that hands `buildProvenanceGraph` claims
253
+ // without their envelopes — a replayed trace, or `conflicts.ts` used standalone in a test — must
254
+ // still see supersession, because that link is carried on the claim and does not need the
255
+ // artifact's bytes to be resolvable.
256
+ const referenceable = new Set([...envelopeIndex.keys(), ...claimsByArtifact.keys()]);
257
+ const directSupersedes = new Map();
258
+ for (const claim of [...claims].sort((a, b) => (a.claimId < b.claimId ? -1 : 1))) {
259
+ const targets = new Set();
260
+ for (const reference of [...claim.supersedes].sort()) {
261
+ const resolvedArtifact = resolveRef(reference, referenceable);
262
+ const viaArtifact = resolvedArtifact === null ? [] : (claimsByArtifact.get(resolvedArtifact) ?? []);
263
+ edges.push({
264
+ from: claim.claimId,
265
+ to: resolvedArtifact ?? reference,
266
+ toKind: resolvedArtifact === null ? "external" : "artifact",
267
+ relation: "SUPERSEDES",
268
+ directness: "direct",
269
+ locator: "claim.supersedes",
270
+ basis: resolvedArtifact === null ? "declares supersession of something this run did not retrieve" : "declares supersession of an artifact in this run",
271
+ });
272
+ for (const target of viaArtifact) {
273
+ if (target === claim.claimId)
274
+ continue;
275
+ targets.add(target);
276
+ }
277
+ }
278
+ if (targets.size > 0)
279
+ directSupersedes.set(claim.claimId, [...targets].sort());
280
+ }
281
+ for (const [from, targets] of [...directSupersedes.entries()].sort((a, b) => (a[0] < b[0] ? -1 : 1))) {
282
+ for (const to of targets) {
283
+ edges.push({ from, to, toKind: "claim", relation: "SUPERSEDES", directness: "direct", locator: "claim.supersedes", basis: "retires the claim that stands on the superseded artifact" });
284
+ }
285
+ }
286
+ const supersededBy = new Map();
287
+ for (const [from, targets] of directSupersedes) {
288
+ for (const to of targets) {
289
+ const bucket = supersededBy.get(to);
290
+ if (bucket === undefined)
291
+ supersededBy.set(to, [from]);
292
+ else
293
+ bucket.push(from);
294
+ }
295
+ }
296
+ /* --- pairwise edges: CONTRADICTS, QUALIFIES, TEMPORAL_BOUND --------------------------------- */
297
+ const ordered = [...claims].sort((a, b) => (a.claimId < b.claimId ? -1 : a.claimId > b.claimId ? 1 : 0));
298
+ const neighbours = candidatePairs(ordered, (claim) => profilesByClaim.get(claim.claimId) ?? profileOf("", shingleSize), (claim) => claim.claimId, threshold);
299
+ const contradictedBy = new Map();
300
+ const qualifiedBy = new Map();
301
+ const temporalBoundOn = new Map();
302
+ const link = (index, key, value) => {
303
+ const bucket = index.get(key);
304
+ if (bucket === undefined)
305
+ index.set(key, [value]);
306
+ else if (!bucket.includes(value))
307
+ bucket.push(value);
308
+ };
309
+ for (const pair of neighbours) {
310
+ const a = pair.a;
311
+ const b = pair.b;
312
+ const qa = qualifiersByClaim.get(a.claimId) ?? [];
313
+ const qb = qualifiersByClaim.get(b.claimId) ?? [];
314
+ const branch = branchDifference(qa, qb);
315
+ const environment = environmentDifference(qa, qb);
316
+ if (branch.diverges || environment.diverges) {
317
+ const detail = branch.diverges ? `branch ${branch.left.join("/")} vs ${branch.right.join("/")}` : `environment ${environment.left.join("/")} vs ${environment.right.join("/")}`;
318
+ edges.push({ from: a.claimId, to: b.claimId, toKind: "claim", relation: "QUALIFIES", directness: "direct", locator: "qualifier", basis: detail });
319
+ edges.push({ from: b.claimId, to: a.claimId, toKind: "claim", relation: "QUALIFIES", directness: "direct", locator: "qualifier", basis: detail });
320
+ link(qualifiedBy, a.claimId, b.claimId);
321
+ link(qualifiedBy, b.claimId, a.claimId);
322
+ // A pair explained by a qualifier is not also a contradiction: two statements about two
323
+ // branches disagree about nothing. Reporting both would double-count the same divergence
324
+ // and would put a `DIRECT_CONTRADICTION` in front of the reader for a difference that has
325
+ // a perfectly ordinary explanation.
326
+ //
327
+ // **This is the seam design §17 ambiguity 4 gated, and the gate is why it is conditional.**
328
+ // Suppressing the contradiction does not only change what the reader is told; `contradictions`
329
+ // is a term in `evidence_strength` (§9), so a suppressed pair keeps a `−0.15` it would
330
+ // otherwise lose. That is a qualifier reaching a *score*, and doing it on the strength of an
331
+ // extractor measured at 0.281 was the silent damage the ambiguity was written about. The
332
+ // extractor now measures 0.837 over 620 hits on a sample drawn after its corrections
333
+ // (`qualifiers.ts:QUALIFIER_RANKING`), so the suppression applies. With the flag off the
334
+ // `QUALIFIES` edge is still emitted — classification is §2's job for these qualifiers and was
335
+ // never gated — but it no longer decides anything a weight will multiply.
336
+ if (QUALIFIER_RANKING.enabled)
337
+ continue;
338
+ }
339
+ const negation = negationDivergence(a.text, b.text);
340
+ const keyValues = keyValueDivergence(a.text, b.text);
341
+ if (negation.diverges || keyValues.length > 0) {
342
+ const detail = negation.diverges
343
+ ? `exactly one side carries a negation marker (${negation.negatedSide === "a" ? a.claimId.slice(0, 12) : b.claimId.slice(0, 12)})`
344
+ : keyValues.map((entry) => `${entry.key}: ${entry.left} vs ${entry.right}`).join("; ");
345
+ edges.push({ from: a.claimId, to: b.claimId, toKind: "claim", relation: "CONTRADICTS", directness: "direct", locator: "text", basis: detail });
346
+ edges.push({ from: b.claimId, to: a.claimId, toKind: "claim", relation: "CONTRADICTS", directness: "direct", locator: "text", basis: detail });
347
+ link(contradictedBy, a.claimId, b.claimId);
348
+ link(contradictedBy, b.claimId, a.claimId);
349
+ }
350
+ if (temporallyDisjoint(a, b)) {
351
+ const [earlier, later] = a.effectiveAt <= b.effectiveAt ? [a, b] : [b, a];
352
+ edges.push({ from: later.claimId, to: earlier.claimId, toKind: "claim", relation: "TEMPORAL_BOUND", directness: "direct", locator: "validity interval", basis: `${earlier.claimId.slice(0, 12)}'s validity ends before ${later.claimId.slice(0, 12)}'s begins` });
353
+ link(temporalBoundOn, later.claimId, earlier.claimId);
354
+ }
355
+ }
356
+ /* --- assembly ------------------------------------------------------------------------------- */
357
+ const byClaim = new Map();
358
+ const stats = {
359
+ claims: claims.length,
360
+ artifacts: envelopes.length,
361
+ edges: edges.length,
362
+ byRelation: emptyByRelation(),
363
+ byGrounding: emptyByGrounding(),
364
+ byDistance: {},
365
+ corroborated: 0,
366
+ contradicted: 0,
367
+ transitiveChains: 0,
368
+ deepestChain: 0,
369
+ neighbourPairs: neighbours.length,
370
+ branchQualified: 0,
371
+ environmentQualified: 0,
372
+ notYetEffective: 0,
373
+ };
374
+ for (const claim of claims) {
375
+ const base = partial.get(claim.claimId);
376
+ if (base === undefined)
377
+ continue;
378
+ const closure = transitiveClosure(directSupersedes, claim.claimId);
379
+ const direct = directSupersedes.get(claim.claimId) ?? [];
380
+ const qualifiers = qualifiersByClaim.get(claim.claimId) ?? [];
381
+ const temporal = temporalValidity(claim, now);
382
+ const entry = {
383
+ claimId: claim.claimId,
384
+ graphDistance: base.graphDistance,
385
+ distanceBasis: base.distanceBasis,
386
+ supportingArtifacts: base.supporting,
387
+ independentGroups: base.groupKeys.length,
388
+ groupKeys: base.groupKeys,
389
+ grounding: base.grounding,
390
+ unresolvedRefs: base.unresolvedRefs,
391
+ contradictedBy: (contradictedBy.get(claim.claimId) ?? []).sort(),
392
+ qualifiedBy: (qualifiedBy.get(claim.claimId) ?? []).sort(),
393
+ supersedes: direct,
394
+ supersedesTransitive: closure.reachable,
395
+ supersededBy: (supersededBy.get(claim.claimId) ?? []).sort(),
396
+ supersessionDepth: closure.depth,
397
+ temporalBoundOn: (temporalBoundOn.get(claim.claimId) ?? []).sort(),
398
+ temporal,
399
+ qualifiers,
400
+ };
401
+ byClaim.set(claim.claimId, entry);
402
+ stats.byGrounding[entry.grounding] += 1;
403
+ stats.byDistance[String(entry.graphDistance)] = (stats.byDistance[String(entry.graphDistance)] ?? 0) + 1;
404
+ if (entry.independentGroups > 1)
405
+ stats.corroborated += 1;
406
+ if (entry.contradictedBy.length > 0)
407
+ stats.contradicted += 1;
408
+ if (entry.supersessionDepth > 1)
409
+ stats.transitiveChains += 1;
410
+ stats.deepestChain = Math.max(stats.deepestChain, entry.supersessionDepth);
411
+ if (qualifiers.some((hit) => hit.kind === "branch"))
412
+ stats.branchQualified += 1;
413
+ if (qualifiers.some((hit) => hit.kind === "environment"))
414
+ stats.environmentQualified += 1;
415
+ if (temporal.status === "not_yet_effective")
416
+ stats.notYetEffective += 1;
417
+ }
418
+ for (const edge of edges)
419
+ stats.byRelation[edge.relation] += 1;
420
+ // A total order, so two runs that read the same corpus serialize the graph byte-identically (§16).
421
+ edges.sort((a, b) => (a.from < b.from ? -1 : a.from > b.from ? 1 : a.relation < b.relation ? -1 : a.relation > b.relation ? 1 : a.to < b.to ? -1 : a.to > b.to ? 1 : 0));
422
+ return { edges, byClaim, grounding, claimsByArtifact, neighbours, stats };
423
+ }
424
+ /**
425
+ * The provenance of one claim, or a conservative default when the graph does not know it.
426
+ *
427
+ * The default is deliberately the *weakest* reading — distance 3, no corroboration, ungrounded —
428
+ * rather than a neutral one. A caller holding a claim the graph never saw is in an unknown state,
429
+ * and an unknown state must not be scored as a well-supported one.
430
+ */
431
+ export function provenanceOf(graph, claimId, temporal) {
432
+ const found = graph.byClaim.get(claimId);
433
+ if (found !== undefined)
434
+ return found;
435
+ return {
436
+ claimId,
437
+ graphDistance: 3,
438
+ distanceBasis: "this claim is not in the provenance graph; treated as maximally indirect",
439
+ supportingArtifacts: [],
440
+ independentGroups: 0,
441
+ groupKeys: [],
442
+ grounding: "session_absent",
443
+ unresolvedRefs: [],
444
+ contradictedBy: [],
445
+ qualifiedBy: [],
446
+ supersedes: [],
447
+ supersedesTransitive: [],
448
+ supersededBy: [],
449
+ supersessionDepth: 0,
450
+ temporalBoundOn: [],
451
+ temporal,
452
+ qualifiers: [],
453
+ };
454
+ }
455
+ /** Every edge leaving a claim, for `explainDecision` and the briefing's provenance entry. */
456
+ export function edgesFrom(graph, claimId) {
457
+ return graph.edges.filter((edge) => edge.from === claimId);
458
+ }