@facthouse/mcp 0.33.0 → 0.35.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 (93) hide show
  1. package/README.md +19 -13
  2. package/dist/cli/inspect-html.d.ts.map +1 -1
  3. package/dist/cli/inspect-html.js +14 -2
  4. package/dist/cli/inspect-html.js.map +1 -1
  5. package/dist/cli/inspect-payload.d.ts +21 -0
  6. package/dist/cli/inspect-payload.d.ts.map +1 -1
  7. package/dist/cli/inspect-payload.js +58 -2
  8. package/dist/cli/inspect-payload.js.map +1 -1
  9. package/dist/cli/inspect.d.ts.map +1 -1
  10. package/dist/cli/inspect.js +3 -0
  11. package/dist/cli/inspect.js.map +1 -1
  12. package/dist/cli/query.d.ts.map +1 -1
  13. package/dist/cli/query.js +8 -1
  14. package/dist/cli/query.js.map +1 -1
  15. package/dist/cli/run.d.ts.map +1 -1
  16. package/dist/cli/run.js +4 -0
  17. package/dist/cli/run.js.map +1 -1
  18. package/dist/db/fact-relations.d.ts +67 -0
  19. package/dist/db/fact-relations.d.ts.map +1 -0
  20. package/dist/db/fact-relations.js +106 -0
  21. package/dist/db/fact-relations.js.map +1 -0
  22. package/dist/db/postgres-schema.js +22 -0
  23. package/dist/db/postgres-schema.js.map +1 -1
  24. package/dist/db/postgres.d.ts.map +1 -1
  25. package/dist/db/postgres.js +2 -0
  26. package/dist/db/postgres.js.map +1 -1
  27. package/dist/db/schema-version.d.ts +1 -1
  28. package/dist/db/schema-version.js +1 -1
  29. package/dist/db/schema.d.ts.map +1 -1
  30. package/dist/db/schema.js +36 -0
  31. package/dist/db/schema.js.map +1 -1
  32. package/dist/db/sessions.d.ts +9 -0
  33. package/dist/db/sessions.d.ts.map +1 -1
  34. package/dist/db/sessions.js +23 -0
  35. package/dist/db/sessions.js.map +1 -1
  36. package/dist/intelligence/cli.d.ts.map +1 -1
  37. package/dist/intelligence/cli.js +16 -8
  38. package/dist/intelligence/cli.js.map +1 -1
  39. package/dist/intelligence/consolidate.d.ts +40 -0
  40. package/dist/intelligence/consolidate.d.ts.map +1 -1
  41. package/dist/intelligence/consolidate.js +432 -37
  42. package/dist/intelligence/consolidate.js.map +1 -1
  43. package/dist/intelligence/heuristic.d.ts +4 -0
  44. package/dist/intelligence/heuristic.d.ts.map +1 -1
  45. package/dist/intelligence/heuristic.js +40 -11
  46. package/dist/intelligence/heuristic.js.map +1 -1
  47. package/dist/intelligence/http.d.ts.map +1 -1
  48. package/dist/intelligence/http.js +17 -8
  49. package/dist/intelligence/http.js.map +1 -1
  50. package/dist/intelligence/sampling.d.ts.map +1 -1
  51. package/dist/intelligence/sampling.js +23 -11
  52. package/dist/intelligence/sampling.js.map +1 -1
  53. package/dist/intelligence/stage-router.d.ts.map +1 -1
  54. package/dist/intelligence/stage-router.js +7 -0
  55. package/dist/intelligence/stage-router.js.map +1 -1
  56. package/dist/intelligence/supersession.d.ts +46 -0
  57. package/dist/intelligence/supersession.d.ts.map +1 -0
  58. package/dist/intelligence/supersession.js +56 -0
  59. package/dist/intelligence/supersession.js.map +1 -0
  60. package/dist/intelligence/token-budget.d.ts +26 -0
  61. package/dist/intelligence/token-budget.d.ts.map +1 -1
  62. package/dist/intelligence/token-budget.js +65 -18
  63. package/dist/intelligence/token-budget.js.map +1 -1
  64. package/dist/intelligence/types.d.ts +28 -3
  65. package/dist/intelligence/types.d.ts.map +1 -1
  66. package/dist/intelligence/usage.d.ts +5 -0
  67. package/dist/intelligence/usage.d.ts.map +1 -1
  68. package/dist/intelligence/usage.js +8 -0
  69. package/dist/intelligence/usage.js.map +1 -1
  70. package/dist/search/entity.d.ts.map +1 -1
  71. package/dist/search/entity.js +10 -2
  72. package/dist/search/entity.js.map +1 -1
  73. package/dist/search/index.d.ts.map +1 -1
  74. package/dist/search/index.js +8 -0
  75. package/dist/search/index.js.map +1 -1
  76. package/dist/server.js +5 -1
  77. package/dist/server.js.map +1 -1
  78. package/dist/sources/resolve.d.ts +26 -0
  79. package/dist/sources/resolve.d.ts.map +1 -1
  80. package/dist/sources/resolve.js +55 -0
  81. package/dist/sources/resolve.js.map +1 -1
  82. package/dist/tools/fact-manager.d.ts +38 -0
  83. package/dist/tools/fact-manager.d.ts.map +1 -1
  84. package/dist/tools/fact-manager.js +44 -17
  85. package/dist/tools/fact-manager.js.map +1 -1
  86. package/dist/tools/read-tools.d.ts.map +1 -1
  87. package/dist/tools/read-tools.js +5 -2
  88. package/dist/tools/read-tools.js.map +1 -1
  89. package/dist/types/data.d.ts +29 -0
  90. package/dist/types/data.d.ts.map +1 -1
  91. package/dist/types/data.js +21 -0
  92. package/dist/types/data.js.map +1 -1
  93. package/package.json +1 -1
@@ -14,6 +14,10 @@
14
14
  import { randomUUID } from "node:crypto";
15
15
  import { withTransaction } from "../db/connection.js";
16
16
  import { DEFAULT_CONFIDENCE, DEFAULT_IMPORTANCE, DEFAULT_CONFIG, } from "../types/config.js";
17
+ import { NEGATION_WORDS, SUPERSESSION_JACCARD_MIN, jaccardSimilarity, } from "./heuristic.js";
18
+ import { getProjectsForSessions } from "../db/sessions.js";
19
+ import { insertFactRelation } from "../db/fact-relations.js";
20
+ import { projectKey, projectRelation } from "../sources/resolve.js";
17
21
  import { EXTRACT_EVIDENCE_SLICE, EXTRACT_REREAD_CONFIDENCE, EXTRACT_REREAD_WINDOW, capReferents, packEventsForExtract, } from "./extract-prompt.js";
18
22
  import { lineTimeMs } from "./line-time.js";
19
23
  import { ConsolidateAbortError, isConsolidateAbort, throwIfAborted } from "./abort.js";
@@ -33,9 +37,9 @@ import { advanceExtractMarksToCurrentMax, conversationExtractThrough, extractWat
33
37
  import { ALL_STEPS, EXTRACT_CAP_EVENTS, } from "./steps.js";
34
38
  import { countFactsMissingEmbeddings, getFactsMissingEmbeddings, insertEmbeddings, } from "../db/embeddings.js";
35
39
  import { insertIntelligenceRun, listIntelligenceRunsSince } from "../db/intelligence-runs.js";
36
- import { takeProviderUsage, } from "./usage.js";
40
+ import { peekProviderUsage, takeProviderUsage, } from "./usage.js";
37
41
  import { INTEGRATE_STAGE_NAMES, resolveStageProviderType, setHttpExtractCliFallback, } from "./stage-router.js";
38
- import { getBoundTokenBudget, isBilledProvider, loadRunsForBudget, parseIntelligenceTokenBudget, evaluateTokenBudget, verdictForProvider, } from "./token-budget.js";
42
+ import { billedCapName, breachForProvider, evaluateTokenBudget, getBoundTokenBudget, isBilledProvider, loadRunsForBudget, parseIntelligenceTokenBudget, verdictForProvider, } from "./token-budget.js";
39
43
  /** Same predicate as `formatConsolidate` / MCP consolidate JSON. */
40
44
  export function embedReportVisible(e) {
41
45
  return Boolean(e && (e.error || (e.model && e.dimensions)));
@@ -94,6 +98,9 @@ embeddingProvider = null, steps = ALL_STEPS, caller = {}) {
94
98
  entitiesCreated: 0,
95
99
  entitiesLinked: 0,
96
100
  supersessions: 0,
101
+ keptAlongside: 0,
102
+ corroborations: 0,
103
+ relations: [],
97
104
  summary: null,
98
105
  openThreads: [],
99
106
  skipped: true,
@@ -129,9 +136,12 @@ embeddingProvider = null, steps = ALL_STEPS, caller = {}) {
129
136
  let budgetReason;
130
137
  let allowHttpCliFallback = true;
131
138
  const parsedBudget = getBoundTokenBudget(db) ?? parseIntelligenceTokenBudget(intel);
139
+ // One clock for the whole run so a long extract does not slide the window.
140
+ const budgetNow = new Date();
141
+ let budgetRuns = [];
132
142
  if (parsedBudget && (doExtract || doIntegrate)) {
133
- const runs = await loadRunsForBudget((since) => listIntelligenceRunsSince(db, since), parsedBudget);
134
- const report = evaluateTokenBudget(runs, parsedBudget);
143
+ budgetRuns = await loadRunsForBudget((since) => listIntelligenceRunsSince(db, since), parsedBudget, budgetNow);
144
+ const report = evaluateTokenBudget(budgetRuns, parsedBudget, budgetNow);
135
145
  if (doExtract) {
136
146
  const extractType = resolveStageProviderType(intel, "extract");
137
147
  if (isBilledProvider(extractType)) {
@@ -170,6 +180,9 @@ embeddingProvider = null, steps = ALL_STEPS, caller = {}) {
170
180
  entitiesCreated: 0,
171
181
  entitiesLinked: 0,
172
182
  supersessions: 0,
183
+ keptAlongside: 0,
184
+ corroborations: 0,
185
+ relations: [],
173
186
  summary: null,
174
187
  openThreads: [],
175
188
  skipped: true,
@@ -181,17 +194,65 @@ embeddingProvider = null, steps = ALL_STEPS, caller = {}) {
181
194
  }
182
195
  }
183
196
  const extractNow = doExtract && !skipExtract;
184
- const integrateNow = doIntegrate && !skipIntegrate;
197
+ let integrateNow = doIntegrate && !skipIntegrate;
185
198
  setHttpExtractCliFallback(intelligence, allowHttpCliFallback);
199
+ // Prior window usage plus tokens this run has billed so far. The in-flight
200
+ // row is not written until the run finishes; peek leaves that envelope intact.
201
+ const liveBreach = (provider) => {
202
+ if (!parsedBudget || !isBilledProvider(provider))
203
+ return null;
204
+ const usage = peekProviderUsage(intelligence);
205
+ if (!usage)
206
+ return null;
207
+ const inFlight = {
208
+ id: consolidationId,
209
+ kind: "consolidate",
210
+ consolidation_id: consolidationId,
211
+ created_at: budgetNow.toISOString(),
212
+ usage,
213
+ };
214
+ const report = evaluateTokenBudget([...budgetRuns, inFlight], parsedBudget, budgetNow);
215
+ return breachForProvider(report, provider);
216
+ };
217
+ const budgetStopFor = (eventsUnexamined, breach, stopped) => {
218
+ if (!stopped || !breach)
219
+ return undefined;
220
+ return {
221
+ stopped: true,
222
+ provider: breach.provider,
223
+ scale: breach.scale,
224
+ used: breach.used,
225
+ cap: breach.cap,
226
+ capName: billedCapName(breach.provider, breach.scale),
227
+ resetsAt: breach.resets_at,
228
+ eventsUnexamined,
229
+ ...(breach.unmetered ? { unmetered: true } : {}),
230
+ };
231
+ };
186
232
  try {
187
233
  // Phase B: D→I event extraction (if this run examines events).
188
234
  // Session facts land unclaimed so a later run that includes integrate
189
235
  // can claim them; which moments run which steps is MOMENT_POLICY.
236
+ let tokenBreach = null;
237
+ let stoppedForBudget = false;
190
238
  if (extractNow && extractionEnabled) {
191
- const extracted = await extractFactsFromEvents(db, intelligence, config, extractLimit, caller.extractSince, caller.onExtractProgress, caller.onExtractTimeout, caller.abort, caller.progressTotal, caller.onModelChunk);
239
+ const extracted = await extractFactsFromEvents(db, intelligence, config, extractLimit, caller.extractSince, caller.onExtractProgress, caller.onExtractTimeout, caller.abort, caller.progressTotal, caller.onModelChunk, parsedBudget
240
+ ? async () => {
241
+ const extractType = resolveStageProviderType(intel, "extract");
242
+ // Local HTTP is not a billed provider. Its tokens must not stop
243
+ // the run, including when a CLI cap is set beside it.
244
+ if (!isBilledProvider(extractType))
245
+ return null;
246
+ return liveBreach(extractType);
247
+ }
248
+ : undefined);
192
249
  extractionDegraded = extracted.degraded;
193
250
  extractPending = extracted.pending;
194
251
  prefixCommitted = extracted.prefixCommitted;
252
+ if (extracted.extractStopped && extracted.tokenBreach) {
253
+ tokenBreach = extracted.tokenBreach;
254
+ stoppedForBudget = true;
255
+ }
195
256
  }
196
257
  else if (extractNow && !extractionEnabled) {
197
258
  // Policy decline, not provider-down: every conversation is examined
@@ -201,6 +262,23 @@ embeddingProvider = null, steps = ALL_STEPS, caller = {}) {
201
262
  // Integrate-only leaves extract marks untouched. Extract writes per-id
202
263
  // marks as it goes; the run row audits the global MIN through.
203
264
  const effectiveWatermark = await extractWatermark(db);
265
+ // One check, before integrate starts. A batch that already crossed the
266
+ // cap leaves its session facts unclaimed. Once integrate begins it runs
267
+ // to completion, even if that step itself crosses the cap.
268
+ if (integrateNow && parsedBudget) {
269
+ for (const stage of INTEGRATE_STAGE_NAMES) {
270
+ const stageType = resolveStageProviderType(intel, stage);
271
+ if (!isBilledProvider(stageType))
272
+ continue;
273
+ const breach = liveBreach(stageType);
274
+ if (breach) {
275
+ integrateNow = false;
276
+ tokenBreach = tokenBreach ?? breach;
277
+ stoppedForBudget = true;
278
+ break;
279
+ }
280
+ }
281
+ }
204
282
  if (integrateNow) {
205
283
  throwIfAborted(caller.abort);
206
284
  caller.onIntegrateStart?.((await getUnconsolidatedFacts(db)).length);
@@ -233,6 +311,8 @@ embeddingProvider = null, steps = ALL_STEPS, caller = {}) {
233
311
  : undefined;
234
312
  await releaseLock(db, consolidationId);
235
313
  const extractedCount = extractPending.reduce((n, p) => n + p.facts.length, 0);
314
+ const eventsRemaining = await remainingEvents();
315
+ const budgetStop = budgetStopFor(eventsRemaining, tokenBreach, stoppedForBudget);
236
316
  return await finish({
237
317
  consolidationId,
238
318
  extractionDegraded,
@@ -242,8 +322,11 @@ embeddingProvider = null, steps = ALL_STEPS, caller = {}) {
242
322
  entitiesCreated: 0,
243
323
  entitiesLinked: 0,
244
324
  supersessions: 0,
325
+ keptAlongside: 0,
326
+ corroborations: 0,
327
+ relations: [],
245
328
  eventsCopied,
246
- eventsRemaining: await remainingEvents(),
329
+ eventsRemaining,
247
330
  summary: null,
248
331
  openThreads: [],
249
332
  skipped: false,
@@ -251,11 +334,13 @@ embeddingProvider = null, steps = ALL_STEPS, caller = {}) {
251
334
  examinedThrough: effectiveWatermark,
252
335
  prefixCommitted,
253
336
  ...(embedding ? { embedding } : {}),
337
+ ...(budgetStop ? { budgetStop } : {}),
254
338
  });
255
339
  }
256
340
  // Phase C: I→K integration pipeline (LLM calls happen here, outside transaction)
257
341
  // Build lookup map for O(1) access in Phase C and D
258
342
  const sessionFactMap = new Map(sessionFacts.map((f) => [f.id, f]));
343
+ const projectBySession = await getProjectsForSessions(db, [...new Set(sessionFacts.map((f) => f.session_id))]);
259
344
  // Step 1: Classify domains. For session_facts that carry a domain_hint
260
345
  // from extraction (set by CLI/sampling providers via subdomain_hint etc.),
261
346
  // trust that directly and don't re-call the classifier. Falls through to
@@ -323,6 +408,20 @@ embeddingProvider = null, steps = ALL_STEPS, caller = {}) {
323
408
  if (!cached) {
324
409
  cached = await getFactsByDomain(db, domain);
325
410
  domainCache.set(domain, cached);
411
+ const missing = [];
412
+ const seen = new Set();
413
+ for (const fact of cached) {
414
+ const id = fact.session_id;
415
+ if (!id || projectBySession.has(id) || seen.has(id))
416
+ continue;
417
+ seen.add(id);
418
+ missing.push(id);
419
+ }
420
+ if (missing.length > 0) {
421
+ const more = await getProjectsForSessions(db, missing);
422
+ for (const [id, project] of more)
423
+ projectBySession.set(id, project);
424
+ }
326
425
  }
327
426
  return cached;
328
427
  };
@@ -333,11 +432,27 @@ embeddingProvider = null, steps = ALL_STEPS, caller = {}) {
333
432
  * reconcile decision — candidate is a paraphrase / corroboration of an
334
433
  * existing fact, so instead of integrating we strengthen the existing one. */
335
434
  const enrichments = [];
336
- // Intra-batch dedup: track normalised content already queued for integration.
337
- // Without this, two session_facts with identical content from different sessions
338
- // both pass same-session hash dedup and both pass reconcile (neither has a integrated
339
- // twin yet), producing duplicate rows in the facts table.
340
- const seenBatchContent = new Set();
435
+ // Intra-batch dedup. The value is the session fact that will receive the
436
+ // one K. A later twin recorded in a different project does not get a
437
+ // second K; the winner is explicit-first, then earliest created_at.
438
+ // That choice does not reorder `classified`.
439
+ const seenBatchContent = new Map();
440
+ const batchTwins = [];
441
+ const absorbedTwins = [];
442
+ const projectOf = (sessionId) => {
443
+ if (!sessionId)
444
+ return null;
445
+ return projectBySession.get(sessionId) ?? null;
446
+ };
447
+ const preferRestatementWinner = (current, incumbent) => {
448
+ const currentExplicit = current.source_origin === "explicit";
449
+ const incumbentExplicit = incumbent.source_origin === "explicit";
450
+ if (currentExplicit !== incumbentExplicit)
451
+ return currentExplicit ? current : incumbent;
452
+ if (current.created_at < incumbent.created_at)
453
+ return current;
454
+ return incumbent;
455
+ };
341
456
  let integrateDone = 0;
342
457
  for (const cf of classified) {
343
458
  throwIfAborted(caller.abort);
@@ -347,15 +462,49 @@ embeddingProvider = null, steps = ALL_STEPS, caller = {}) {
347
462
  // Shared normalisation with cross-batch reconcile (heuristic.ts) so
348
463
  // "I prefer coffee" vs "I prefer coffee." is consistently handled.
349
464
  const normalised = normaliseForDedup(cf.content);
350
- if (seenBatchContent.has(normalised)) {
351
- rejected++;
352
- continue;
465
+ const incumbentId = seenBatchContent.get(normalised);
466
+ let displacedId = null;
467
+ if (incumbentId) {
468
+ const incumbent = sessionFactMap.get(incumbentId);
469
+ const relation = projectRelation(projectOf(sessionFact.session_id), projectOf(incumbent?.session_id));
470
+ if (relation === "different" && incumbent && preferRestatementWinner(sessionFact, incumbent).id === sessionFact.id) {
471
+ // This fact becomes the single K. The incumbent is rejected below,
472
+ // once reconcile agrees it should be integrated.
473
+ displacedId = incumbentId;
474
+ seenBatchContent.delete(normalised);
475
+ }
476
+ else {
477
+ if (relation === "different" && incumbent) {
478
+ batchTwins.push({
479
+ winnerSessionFactId: incumbentId,
480
+ loserSessionFactId: sessionFact.id,
481
+ });
482
+ }
483
+ rejected++;
484
+ continue;
485
+ }
353
486
  }
354
487
  const domainFacts = await getDomainFacts(cf.domain);
355
488
  const decision = await intelligence.reconcile(sessionFact, domainFacts);
356
489
  integrateDone += 1;
357
490
  caller.onIntegrateProgress?.(integrateDone, classified.length);
358
491
  if (decision.kind === "noop") {
492
+ if (displacedId)
493
+ seenBatchContent.set(normalised, displacedId);
494
+ const twin = domainFacts.find((fact) => normaliseForDedup(fact.content) === normalised);
495
+ if (twin) {
496
+ const relation = projectRelation(projectOf(sessionFact.session_id), projectOf(twin.session_id));
497
+ if (relation === "different") {
498
+ absorbedTwins.push({
499
+ factId: twin.id,
500
+ sessionFactId: sessionFact.id,
501
+ verdict: relation,
502
+ factProject: projectOf(twin.session_id),
503
+ candidateProject: projectOf(sessionFact.session_id),
504
+ reason: "restatement",
505
+ });
506
+ }
507
+ }
359
508
  rejected++;
360
509
  continue;
361
510
  }
@@ -364,16 +513,36 @@ embeddingProvider = null, steps = ALL_STEPS, caller = {}) {
364
513
  // hallucinated an id, fall through to the add path as a safer default.
365
514
  const target = domainFacts.find((f) => f.id === decision.existingFactId);
366
515
  if (target) {
516
+ if (displacedId)
517
+ seenBatchContent.set(normalised, displacedId);
367
518
  enrichments.push({
368
519
  existingFactId: decision.existingFactId,
369
520
  confidenceDelta: 0.1,
370
521
  });
522
+ absorbedTwins.push({
523
+ factId: target.id,
524
+ sessionFactId: sessionFact.id,
525
+ verdict: projectRelation(projectOf(sessionFact.session_id), projectOf(target.session_id)),
526
+ factProject: projectOf(target.session_id),
527
+ candidateProject: projectOf(sessionFact.session_id),
528
+ reason: "paraphrase (enrich)",
529
+ });
371
530
  rejected++;
372
531
  continue;
373
532
  }
374
533
  // else: hallucinated id → treat as add
375
534
  }
376
- seenBatchContent.add(normalised);
535
+ if (displacedId) {
536
+ const idx = toIntegrate.findIndex((item) => item.sessionFactId === displacedId);
537
+ if (idx >= 0)
538
+ toIntegrate.splice(idx, 1);
539
+ rejected++;
540
+ batchTwins.push({
541
+ winnerSessionFactId: sessionFact.id,
542
+ loserSessionFactId: displacedId,
543
+ });
544
+ }
545
+ seenBatchContent.set(normalised, cf.id);
377
546
  // Confidence/importance: explicit captures carry their own values; for
378
547
  // inferred facts the extraction signals are the most informative input.
379
548
  // Precedence: explicit > LLM signal > default.
@@ -421,33 +590,124 @@ embeddingProvider = null, steps = ALL_STEPS, caller = {}) {
421
590
  // in the same batch claimed the target first. Surfaced via openThreads so
422
591
  // the user knows their contradiction signal was partially lost.
423
592
  const droppedSupersessions = [];
593
+ const pendingRelations = [];
594
+ let keptAlongside = 0;
595
+ const recordedProject = (sessionId) => {
596
+ if (!sessionId)
597
+ return null;
598
+ return projectBySession.get(sessionId) ?? null;
599
+ };
424
600
  // toIntegrate is ordered by capture time (classifyFacts preserves input order).
425
601
  // First candidate to claim an existing fact wins — temporal priority.
602
+ // The candidate pool is the domain scan. The project each fact was
603
+ // recorded in is evidence on the decision, not a filter on that pool.
426
604
  for (const item of toIntegrate) {
427
- // Supersession is domain-scoped. FTS5 is the wrong tool here: it fails
428
- // when the new fact contains negation tokens ("no longer", "stopped")
429
- // that don't appear in the old fact. Use cached domain scan instead.
605
+ const sessionFact = sessionFactMap.get(item.sessionFactId);
430
606
  const candidates = await getDomainFacts(item.domain);
431
- const candidate = { id: item.sessionFactId, content: item.content, domain: item.domain, subdomain: item.subdomain };
432
- const result = await intelligence.detectSupersession(candidate, candidates);
607
+ const factProject = recordedProject(sessionFact?.session_id);
608
+ const verdicts = new Map();
609
+ const projects = new Map();
610
+ for (const existing of candidates) {
611
+ const candidateProject = recordedProject(existing.session_id);
612
+ verdicts.set(existing.id, projectRelation(factProject, candidateProject));
613
+ projects.set(existing.id, projectKey(candidateProject));
614
+ }
615
+ const context = {
616
+ project: projectKey(factProject),
617
+ verdicts,
618
+ projects,
619
+ };
620
+ const candidate = {
621
+ id: item.sessionFactId,
622
+ content: item.content,
623
+ domain: item.domain,
624
+ subdomain: item.subdomain,
625
+ };
626
+ const result = await intelligence.detectSupersession(candidate, candidates, context);
433
627
  // Intentional: confidence is NOT compared here. A low-confidence new fact
434
628
  // with a clear negation marker ("I no longer prefer X") can supersede a
435
629
  // high-confidence prior. The negation signal is itself strong evidence
436
630
  // of a belief update; requiring confidence parity would make it impossible
437
631
  // for tentative corrections to update stale knowledge.
438
- if (result) {
439
- if (!alreadySuperseded.has(result.existingFactId)) {
440
- supersessionMap.set(item.sessionFactId, result.existingFactId);
441
- alreadySuperseded.add(result.existingFactId);
632
+ const decidedBy = context.answeredBy ?? result?.source_quality ?? null;
633
+ const proposedId = result?.existingFactId;
634
+ const proposedVerdict = proposedId ? verdicts.get(proposedId) : undefined;
635
+ if (result && proposedId) {
636
+ const basis = result.basis;
637
+ const accept = basis === "coexists" ? false
638
+ : basis === "uncertain" ? false
639
+ : proposedVerdict !== "different" ? true
640
+ : basis === "update" ? true
641
+ : NEGATION_WORDS.test(item.content);
642
+ const related = candidates.find((c) => c.id === proposedId);
643
+ const reason = result.reason.trim() !== "" ? result.reason : "no reason returned";
644
+ if (accept) {
645
+ if (!alreadySuperseded.has(proposedId)) {
646
+ supersessionMap.set(item.sessionFactId, proposedId);
647
+ alreadySuperseded.add(proposedId);
648
+ pendingRelations.push({
649
+ sessionFactId: item.sessionFactId,
650
+ kind: "supersedes",
651
+ relatedFactId: proposedId,
652
+ verdict: proposedVerdict ?? "not_comparable",
653
+ basis: basis ?? null,
654
+ reason,
655
+ decidedBy,
656
+ factProject,
657
+ candidateProject: recordedProject(related?.session_id),
658
+ });
659
+ }
660
+ else {
661
+ droppedSupersessions.push({
662
+ newContent: item.content,
663
+ targetedContent: related?.content ?? proposedId,
664
+ });
665
+ }
442
666
  }
443
667
  else {
444
- // Another candidate already claimed this target. This candidate will
445
- // integrate as a plain insert rather than a supersession — record the
446
- // conflict so it can surface in openThreads.
447
- const targeted = candidates.find((c) => c.id === result.existingFactId);
448
- droppedSupersessions.push({
449
- newContent: item.content,
450
- targetedContent: targeted?.content ?? result.existingFactId,
668
+ keptAlongside += 1;
669
+ pendingRelations.push({
670
+ sessionFactId: item.sessionFactId,
671
+ kind: "kept_alongside",
672
+ relatedFactId: proposedId,
673
+ verdict: proposedVerdict ?? "not_comparable",
674
+ basis: basis ?? null,
675
+ reason,
676
+ decidedBy,
677
+ factProject,
678
+ candidateProject: recordedProject(related?.session_id),
679
+ });
680
+ }
681
+ }
682
+ if (proposedVerdict !== "different") {
683
+ let best = null;
684
+ for (const existing of candidates) {
685
+ if (existing.id === proposedId)
686
+ continue;
687
+ if (verdicts.get(existing.id) !== "different")
688
+ continue;
689
+ const similarity = jaccardSimilarity(item.content, existing.content);
690
+ if (similarity < SUPERSESSION_JACCARD_MIN)
691
+ continue;
692
+ if (!best || similarity > best.similarity)
693
+ best = { id: existing.id, similarity };
694
+ }
695
+ if (best) {
696
+ const related = candidates.find((c) => c.id === best.id);
697
+ const pct = (best.similarity * 100).toFixed(0);
698
+ let reason = `no supersession proposed; overlap ${pct}%`;
699
+ if (NEGATION_WORDS.test(item.content))
700
+ reason += "; lexical trigger fired";
701
+ pendingRelations.push({
702
+ sessionFactId: item.sessionFactId,
703
+ kind: "overlap_noted",
704
+ relatedFactId: best.id,
705
+ verdict: "different",
706
+ basis: null,
707
+ reason,
708
+ decidedBy,
709
+ factProject,
710
+ candidateProject: recordedProject(related?.session_id),
451
711
  });
452
712
  }
453
713
  }
@@ -458,6 +718,7 @@ embeddingProvider = null, steps = ALL_STEPS, caller = {}) {
458
718
  const writeResults = await withTransaction(db, async () => {
459
719
  let entitiesCreated = 0;
460
720
  let entitiesLinked = 0;
721
+ const factIdBySessionFact = new Map();
461
722
  // Ensure all unique domains exist once, before the per-fact loop
462
723
  const uniqueDomains = new Set(toIntegrate.map((item) => item.domain));
463
724
  for (const domain of uniqueDomains) {
@@ -523,6 +784,7 @@ embeddingProvider = null, steps = ALL_STEPS, caller = {}) {
523
784
  valid_from: validFrom,
524
785
  });
525
786
  integratedFacts.push(integratedFact);
787
+ factIdBySessionFact.set(item.sessionFactId, integratedFact.id);
526
788
  // Link entities
527
789
  const extractedEntities = entityMap.get(item.sessionFactId);
528
790
  if (extractedEntities) {
@@ -599,6 +861,71 @@ embeddingProvider = null, steps = ALL_STEPS, caller = {}) {
599
861
  entitiesLinked++;
600
862
  }
601
863
  }
864
+ const relations = [];
865
+ for (const rel of pendingRelations) {
866
+ const factId = factIdBySessionFact.get(rel.sessionFactId);
867
+ if (!factId)
868
+ continue;
869
+ await insertFactRelation(db, {
870
+ consolidationId,
871
+ factId,
872
+ relatedFactId: rel.relatedFactId,
873
+ sessionFactId: rel.sessionFactId,
874
+ kind: rel.kind,
875
+ contextVerdict: rel.verdict,
876
+ factProject: rel.factProject,
877
+ candidateProject: rel.candidateProject,
878
+ basis: rel.basis,
879
+ reason: rel.reason,
880
+ decidedBy: rel.decidedBy,
881
+ });
882
+ relations.push({
883
+ kind: rel.kind,
884
+ fact_id: factId,
885
+ related_fact_id: rel.relatedFactId,
886
+ context_verdict: rel.verdict,
887
+ reason: rel.reason,
888
+ });
889
+ }
890
+ const writeCorroboration = async (row) => {
891
+ await insertFactRelation(db, {
892
+ consolidationId,
893
+ factId: row.factId,
894
+ relatedFactId: null,
895
+ sessionFactId: row.sessionFactId,
896
+ kind: "corroborated_by",
897
+ contextVerdict: row.verdict,
898
+ factProject: row.factProject,
899
+ candidateProject: row.candidateProject,
900
+ basis: null,
901
+ reason: row.reason,
902
+ decidedBy: null,
903
+ });
904
+ relations.push({
905
+ kind: "corroborated_by",
906
+ fact_id: row.factId,
907
+ related_fact_id: null,
908
+ context_verdict: row.verdict,
909
+ reason: row.reason,
910
+ });
911
+ };
912
+ for (const twin of batchTwins) {
913
+ const factId = factIdBySessionFact.get(twin.winnerSessionFactId);
914
+ if (!factId)
915
+ continue;
916
+ const winner = sessionFactMap.get(twin.winnerSessionFactId);
917
+ const loser = sessionFactMap.get(twin.loserSessionFactId);
918
+ await writeCorroboration({
919
+ factId,
920
+ sessionFactId: twin.loserSessionFactId,
921
+ verdict: "different",
922
+ factProject: projectOf(winner?.session_id),
923
+ candidateProject: projectOf(loser?.session_id),
924
+ reason: "restatement",
925
+ });
926
+ }
927
+ for (const twin of absorbedTwins)
928
+ await writeCorroboration(twin);
602
929
  // Apply enrich decisions — boost existing facts' confidence (capped at 1.0)
603
930
  // for each paraphrase/corroboration the LLM identified.
604
931
  const enrichStmt = db.prepare(`UPDATE facts SET confidence = MIN(1.0, confidence + ?) WHERE id = ?`);
@@ -612,7 +939,7 @@ embeddingProvider = null, steps = ALL_STEPS, caller = {}) {
612
939
  summary, open_threads, last_event_sequence, created_at)
613
940
  VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`).run(consolidationId, recordSessionId, sessionFacts.length, toIntegrate.length, rejected, entitiesCreated, entitiesLinked, supersessionCount, null, // summary filled below
614
941
  null, effectiveWatermark, new Date().toISOString());
615
- return { entitiesCreated, entitiesLinked };
942
+ return { entitiesCreated, entitiesLinked, relations };
616
943
  });
617
944
  phaseDCommitted = true;
618
945
  // Phase E: embed the facts that just integrated, if semantic search is on.
@@ -685,6 +1012,8 @@ embeddingProvider = null, steps = ALL_STEPS, caller = {}) {
685
1012
  }
686
1013
  }
687
1014
  }
1015
+ const eventsRemaining = await remainingEvents();
1016
+ const budgetStop = budgetStopFor(eventsRemaining, tokenBreach, stoppedForBudget);
688
1017
  return await finish({
689
1018
  consolidationId,
690
1019
  extractionDegraded,
@@ -694,8 +1023,12 @@ embeddingProvider = null, steps = ALL_STEPS, caller = {}) {
694
1023
  entitiesCreated: writeResults.entitiesCreated,
695
1024
  entitiesLinked: writeResults.entitiesLinked,
696
1025
  supersessions: supersessionCount,
1026
+ keptAlongside,
1027
+ corroborations: writeResults.relations.filter((row) => row.kind === "corroborated_by")
1028
+ .length,
1029
+ relations: writeResults.relations,
697
1030
  eventsCopied,
698
- eventsRemaining: await remainingEvents(),
1031
+ eventsRemaining,
699
1032
  embedding,
700
1033
  summary: summaryText,
701
1034
  openThreads: threads,
@@ -703,6 +1036,7 @@ embeddingProvider = null, steps = ALL_STEPS, caller = {}) {
703
1036
  ...(budgetReason ? { skipReason: budgetReason } : {}),
704
1037
  examinedThrough: effectiveWatermark,
705
1038
  prefixCommitted,
1039
+ ...(budgetStop ? { budgetStop } : {}),
706
1040
  });
707
1041
  }
708
1042
  catch (err) {
@@ -1021,11 +1355,13 @@ function isEligibleEvent(event, eventTypes, roles, minContentLength) {
1021
1355
  return false;
1022
1356
  return (event.content?.length ?? 0) >= minContentLength;
1023
1357
  }
1024
- async function extractFactsFromEvents(db, intelligence, config, limit = null, since, onProgress, onTimeout, abort, progressTotal, onModelChunk) {
1358
+ async function extractFactsFromEvents(db, intelligence, config, limit = null, since, onProgress, onTimeout, abort, progressTotal, onModelChunk, onTokenBudget) {
1025
1359
  const empty = {
1026
1360
  degraded: false,
1027
1361
  pending: [],
1028
1362
  prefixCommitted: false,
1363
+ tokenBreach: null,
1364
+ extractStopped: false,
1029
1365
  };
1030
1366
  const workingMemorySize = config?.extraction?.working_memory_size ??
1031
1367
  DEFAULT_CONFIG.extraction.working_memory_size;
@@ -1050,12 +1386,15 @@ async function extractFactsFromEvents(db, intelligence, config, limit = null, si
1050
1386
  const pending = [];
1051
1387
  let degraded = false;
1052
1388
  let advanced = false;
1389
+ let tokenBreach = null;
1390
+ let extractStopped = false;
1053
1391
  // Oldest conversations first, bounded by `limit` events across the run. A
1054
1392
  // per-conversation mark advances only through what this run examined, so a
1055
1393
  // truncated tail is simply the next run's work — never a claim to have read it.
1056
1394
  let budget = since ? Number.POSITIVE_INFINITY : (limit ?? Number.POSITIVE_INFINITY);
1057
1395
  const sinceMs = since?.getTime();
1058
- for (const conv of conversations) {
1396
+ for (let convIndex = 0; convIndex < conversations.length; convIndex++) {
1397
+ const conv = conversations[convIndex];
1059
1398
  throwIfAborted(abort);
1060
1399
  if (budget <= 0)
1061
1400
  break;
@@ -1103,6 +1442,29 @@ async function extractFactsFromEvents(db, intelligence, config, limit = null, si
1103
1442
  const earlierThisRun = [];
1104
1443
  let conversationDegraded = false;
1105
1444
  const work = [...chunks];
1445
+ // True when this conversation still has chunks the cap said not to start.
1446
+ // The mark must stay on the last finished batch, not the loaded tail.
1447
+ let budgetCut = false;
1448
+ async function noteBudgetAfterBatch() {
1449
+ if (!onTokenBudget)
1450
+ return "ok";
1451
+ const breach = await onTokenBudget();
1452
+ if (!breach)
1453
+ return "ok";
1454
+ tokenBreach = breach;
1455
+ if (work.length > 0) {
1456
+ await persistPending(db, thisPending);
1457
+ const examined = thisPending.flatMap((p) => p.group.events);
1458
+ const maxExamined = lastSeq(examined);
1459
+ if (maxExamined != null) {
1460
+ await setConversationExtractThrough(db, ref, maxExamined);
1461
+ advanced = true;
1462
+ }
1463
+ pending.push(...thisPending);
1464
+ return "cut";
1465
+ }
1466
+ return "stop-after";
1467
+ }
1106
1468
  while (work.length > 0) {
1107
1469
  throwIfAborted(abort);
1108
1470
  const chunk = work.shift();
@@ -1195,6 +1557,14 @@ async function extractFactsFromEvents(db, intelligence, config, limit = null, si
1195
1557
  earlierThisRun.push(...chunk);
1196
1558
  examinedLines += chunk.length;
1197
1559
  onProgress?.(examinedLines, total);
1560
+ const rereadBudget = await noteBudgetAfterBatch();
1561
+ if (rereadBudget === "cut") {
1562
+ budgetCut = true;
1563
+ extractStopped = true;
1564
+ break;
1565
+ }
1566
+ if (rereadBudget === "stop-after")
1567
+ break;
1198
1568
  continue;
1199
1569
  }
1200
1570
  }
@@ -1215,7 +1585,17 @@ async function extractFactsFromEvents(db, intelligence, config, limit = null, si
1215
1585
  earlierThisRun.push(...chunk);
1216
1586
  examinedLines += chunk.length;
1217
1587
  onProgress?.(examinedLines, total);
1588
+ const batchBudget = await noteBudgetAfterBatch();
1589
+ if (batchBudget === "cut") {
1590
+ budgetCut = true;
1591
+ extractStopped = true;
1592
+ break;
1593
+ }
1594
+ if (batchBudget === "stop-after")
1595
+ break;
1218
1596
  }
1597
+ if (budgetCut)
1598
+ break;
1219
1599
  if (!conversationDegraded) {
1220
1600
  await persistPending(db, thisPending);
1221
1601
  const maxLoaded = lastSeq(loaded);
@@ -1231,8 +1611,23 @@ async function extractFactsFromEvents(db, intelligence, config, limit = null, si
1231
1611
  }
1232
1612
  pending.push(...thisPending);
1233
1613
  }
1614
+ // The conversation's own chunks are done. Stop before the next
1615
+ // conversation's first batch. The last conversation has nothing further
1616
+ // to skip — integrate makes its own check.
1617
+ if (tokenBreach && convIndex < conversations.length - 1) {
1618
+ extractStopped = true;
1619
+ break;
1620
+ }
1621
+ if (tokenBreach && !extractStopped)
1622
+ tokenBreach = null;
1234
1623
  }
1235
- return { degraded, pending, prefixCommitted: degraded && advanced };
1624
+ return {
1625
+ degraded,
1626
+ pending,
1627
+ prefixCommitted: degraded && advanced,
1628
+ tokenBreach: extractStopped ? tokenBreach : null,
1629
+ extractStopped,
1630
+ };
1236
1631
  }
1237
1632
  // ---------------------------------------------------------------------------
1238
1633
  // Phase E: embedding