@facthouse/mcp 0.26.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.
- package/LICENSE +21 -0
- package/README.md +611 -0
- package/dist/cli/index.d.ts +30 -0
- package/dist/cli/index.d.ts.map +1 -0
- package/dist/cli/index.js +785 -0
- package/dist/cli/index.js.map +1 -0
- package/dist/cli/init-backfill.d.ts +26 -0
- package/dist/cli/init-backfill.d.ts.map +1 -0
- package/dist/cli/init-backfill.js +56 -0
- package/dist/cli/init-backfill.js.map +1 -0
- package/dist/cli/init-knobs.d.ts +137 -0
- package/dist/cli/init-knobs.d.ts.map +1 -0
- package/dist/cli/init-knobs.js +400 -0
- package/dist/cli/init-knobs.js.map +1 -0
- package/dist/cli/init-wizard.d.ts +67 -0
- package/dist/cli/init-wizard.d.ts.map +1 -0
- package/dist/cli/init-wizard.js +319 -0
- package/dist/cli/init-wizard.js.map +1 -0
- package/dist/cli/init.d.ts +124 -0
- package/dist/cli/init.d.ts.map +1 -0
- package/dist/cli/init.js +286 -0
- package/dist/cli/init.js.map +1 -0
- package/dist/cli/inspect-html.d.ts +15 -0
- package/dist/cli/inspect-html.d.ts.map +1 -0
- package/dist/cli/inspect-html.js +491 -0
- package/dist/cli/inspect-html.js.map +1 -0
- package/dist/cli/inspect-intelligence.d.ts +8 -0
- package/dist/cli/inspect-intelligence.d.ts.map +1 -0
- package/dist/cli/inspect-intelligence.js +103 -0
- package/dist/cli/inspect-intelligence.js.map +1 -0
- package/dist/cli/inspect-model.d.ts +42 -0
- package/dist/cli/inspect-model.d.ts.map +1 -0
- package/dist/cli/inspect-model.js +108 -0
- package/dist/cli/inspect-model.js.map +1 -0
- package/dist/cli/inspect-payload.d.ts +122 -0
- package/dist/cli/inspect-payload.d.ts.map +1 -0
- package/dist/cli/inspect-payload.js +338 -0
- package/dist/cli/inspect-payload.js.map +1 -0
- package/dist/cli/inspect-theme.d.ts +44 -0
- package/dist/cli/inspect-theme.d.ts.map +1 -0
- package/dist/cli/inspect-theme.js +118 -0
- package/dist/cli/inspect-theme.js.map +1 -0
- package/dist/cli/inspect.d.ts +24 -0
- package/dist/cli/inspect.d.ts.map +1 -0
- package/dist/cli/inspect.js +172 -0
- package/dist/cli/inspect.js.map +1 -0
- package/dist/cli/log-event.d.ts +55 -0
- package/dist/cli/log-event.d.ts.map +1 -0
- package/dist/cli/log-event.js +149 -0
- package/dist/cli/log-event.js.map +1 -0
- package/dist/cli/package-version.d.ts +2 -0
- package/dist/cli/package-version.d.ts.map +1 -0
- package/dist/cli/package-version.js +15 -0
- package/dist/cli/package-version.js.map +1 -0
- package/dist/cli/query.d.ts +53 -0
- package/dist/cli/query.d.ts.map +1 -0
- package/dist/cli/query.js +325 -0
- package/dist/cli/query.js.map +1 -0
- package/dist/cli/record.d.ts +55 -0
- package/dist/cli/record.d.ts.map +1 -0
- package/dist/cli/record.js +149 -0
- package/dist/cli/record.js.map +1 -0
- package/dist/cli/settings.d.ts +26 -0
- package/dist/cli/settings.d.ts.map +1 -0
- package/dist/cli/settings.js +161 -0
- package/dist/cli/settings.js.map +1 -0
- package/dist/cli/spend-dashboard.d.ts +53 -0
- package/dist/cli/spend-dashboard.d.ts.map +1 -0
- package/dist/cli/spend-dashboard.js +297 -0
- package/dist/cli/spend-dashboard.js.map +1 -0
- package/dist/cli/stats-html.d.ts +20 -0
- package/dist/cli/stats-html.d.ts.map +1 -0
- package/dist/cli/stats-html.js +879 -0
- package/dist/cli/stats-html.js.map +1 -0
- package/dist/cli/web.d.ts +60 -0
- package/dist/cli/web.d.ts.map +1 -0
- package/dist/cli/web.js +416 -0
- package/dist/cli/web.js.map +1 -0
- package/dist/config.d.ts +102 -0
- package/dist/config.d.ts.map +1 -0
- package/dist/config.js +302 -0
- package/dist/config.js.map +1 -0
- package/dist/db/connection.d.ts +96 -0
- package/dist/db/connection.d.ts.map +1 -0
- package/dist/db/connection.js +200 -0
- package/dist/db/connection.js.map +1 -0
- package/dist/db/consolidation-lock.d.ts +16 -0
- package/dist/db/consolidation-lock.d.ts.map +1 -0
- package/dist/db/consolidation-lock.js +67 -0
- package/dist/db/consolidation-lock.js.map +1 -0
- package/dist/db/consolidations.d.ts +41 -0
- package/dist/db/consolidations.d.ts.map +1 -0
- package/dist/db/consolidations.js +165 -0
- package/dist/db/consolidations.js.map +1 -0
- package/dist/db/disk-budget.d.ts +44 -0
- package/dist/db/disk-budget.d.ts.map +1 -0
- package/dist/db/disk-budget.js +177 -0
- package/dist/db/disk-budget.js.map +1 -0
- package/dist/db/domains.d.ts +14 -0
- package/dist/db/domains.d.ts.map +1 -0
- package/dist/db/domains.js +37 -0
- package/dist/db/domains.js.map +1 -0
- package/dist/db/embeddings-hnsw.d.ts +30 -0
- package/dist/db/embeddings-hnsw.d.ts.map +1 -0
- package/dist/db/embeddings-hnsw.js +129 -0
- package/dist/db/embeddings-hnsw.js.map +1 -0
- package/dist/db/embeddings.d.ts +68 -0
- package/dist/db/embeddings.d.ts.map +1 -0
- package/dist/db/embeddings.js +139 -0
- package/dist/db/embeddings.js.map +1 -0
- package/dist/db/entities.d.ts +157 -0
- package/dist/db/entities.d.ts.map +1 -0
- package/dist/db/entities.js +489 -0
- package/dist/db/entities.js.map +1 -0
- package/dist/db/extract-watermarks.d.ts +55 -0
- package/dist/db/extract-watermarks.d.ts.map +1 -0
- package/dist/db/extract-watermarks.js +171 -0
- package/dist/db/extract-watermarks.js.map +1 -0
- package/dist/db/facts.d.ts +117 -0
- package/dist/db/facts.d.ts.map +1 -0
- package/dist/db/facts.js +326 -0
- package/dist/db/facts.js.map +1 -0
- package/dist/db/index.d.ts +26 -0
- package/dist/db/index.d.ts.map +1 -0
- package/dist/db/index.js +23 -0
- package/dist/db/index.js.map +1 -0
- package/dist/db/inferences.d.ts +36 -0
- package/dist/db/inferences.d.ts.map +1 -0
- package/dist/db/inferences.js +212 -0
- package/dist/db/inferences.js.map +1 -0
- package/dist/db/intelligence-runs.d.ts +20 -0
- package/dist/db/intelligence-runs.d.ts.map +1 -0
- package/dist/db/intelligence-runs.js +60 -0
- package/dist/db/intelligence-runs.js.map +1 -0
- package/dist/db/pg-backend.d.ts +14 -0
- package/dist/db/pg-backend.d.ts.map +1 -0
- package/dist/db/pg-backend.js +53 -0
- package/dist/db/pg-backend.js.map +1 -0
- package/dist/db/postgres-schema.d.ts +13 -0
- package/dist/db/postgres-schema.d.ts.map +1 -0
- package/dist/db/postgres-schema.js +392 -0
- package/dist/db/postgres-schema.js.map +1 -0
- package/dist/db/postgres.d.ts +30 -0
- package/dist/db/postgres.d.ts.map +1 -0
- package/dist/db/postgres.js +154 -0
- package/dist/db/postgres.js.map +1 -0
- package/dist/db/prune.d.ts +67 -0
- package/dist/db/prune.d.ts.map +1 -0
- package/dist/db/prune.js +113 -0
- package/dist/db/prune.js.map +1 -0
- package/dist/db/scheduler-signal.d.ts +20 -0
- package/dist/db/scheduler-signal.d.ts.map +1 -0
- package/dist/db/scheduler-signal.js +32 -0
- package/dist/db/scheduler-signal.js.map +1 -0
- package/dist/db/schema-version.d.ts +7 -0
- package/dist/db/schema-version.d.ts.map +1 -0
- package/dist/db/schema-version.js +7 -0
- package/dist/db/schema-version.js.map +1 -0
- package/dist/db/schema.d.ts +12 -0
- package/dist/db/schema.d.ts.map +1 -0
- package/dist/db/schema.js +983 -0
- package/dist/db/schema.js.map +1 -0
- package/dist/db/session-facts.d.ts +108 -0
- package/dist/db/session-facts.d.ts.map +1 -0
- package/dist/db/session-facts.js +244 -0
- package/dist/db/session-facts.js.map +1 -0
- package/dist/db/sessions.d.ts +85 -0
- package/dist/db/sessions.d.ts.map +1 -0
- package/dist/db/sessions.js +169 -0
- package/dist/db/sessions.js.map +1 -0
- package/dist/db/sources.d.ts +22 -0
- package/dist/db/sources.d.ts.map +1 -0
- package/dist/db/sources.js +43 -0
- package/dist/db/sources.js.map +1 -0
- package/dist/db/stats.d.ts +94 -0
- package/dist/db/stats.d.ts.map +1 -0
- package/dist/db/stats.js +79 -0
- package/dist/db/stats.js.map +1 -0
- package/dist/db/store.d.ts +19 -0
- package/dist/db/store.d.ts.map +1 -0
- package/dist/db/store.js +58 -0
- package/dist/db/store.js.map +1 -0
- package/dist/db/watermarks.d.ts +20 -0
- package/dist/db/watermarks.d.ts.map +1 -0
- package/dist/db/watermarks.js +30 -0
- package/dist/db/watermarks.js.map +1 -0
- package/dist/embedding/ollama.d.ts +31 -0
- package/dist/embedding/ollama.d.ts.map +1 -0
- package/dist/embedding/ollama.js +148 -0
- package/dist/embedding/ollama.js.map +1 -0
- package/dist/embedding/provider.d.ts +37 -0
- package/dist/embedding/provider.d.ts.map +1 -0
- package/dist/embedding/provider.js +71 -0
- package/dist/embedding/provider.js.map +1 -0
- package/dist/embedding/types.d.ts +61 -0
- package/dist/embedding/types.d.ts.map +1 -0
- package/dist/embedding/types.js +13 -0
- package/dist/embedding/types.js.map +1 -0
- package/dist/embedding/voyage.d.ts +31 -0
- package/dist/embedding/voyage.d.ts.map +1 -0
- package/dist/embedding/voyage.js +105 -0
- package/dist/embedding/voyage.js.map +1 -0
- package/dist/identity.d.ts +32 -0
- package/dist/identity.d.ts.map +1 -0
- package/dist/identity.js +53 -0
- package/dist/identity.js.map +1 -0
- package/dist/index.d.ts +9 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +275 -0
- package/dist/index.js.map +1 -0
- package/dist/intelligence/backing.d.ts +19 -0
- package/dist/intelligence/backing.d.ts.map +1 -0
- package/dist/intelligence/backing.js +88 -0
- package/dist/intelligence/backing.js.map +1 -0
- package/dist/intelligence/cli.d.ts +90 -0
- package/dist/intelligence/cli.d.ts.map +1 -0
- package/dist/intelligence/cli.js +823 -0
- package/dist/intelligence/cli.js.map +1 -0
- package/dist/intelligence/consolidate.d.ts +84 -0
- package/dist/intelligence/consolidate.d.ts.map +1 -0
- package/dist/intelligence/consolidate.js +1234 -0
- package/dist/intelligence/consolidate.js.map +1 -0
- package/dist/intelligence/extract-prompt.d.ts +78 -0
- package/dist/intelligence/extract-prompt.d.ts.map +1 -0
- package/dist/intelligence/extract-prompt.js +146 -0
- package/dist/intelligence/extract-prompt.js.map +1 -0
- package/dist/intelligence/heuristic.d.ts +15 -0
- package/dist/intelligence/heuristic.d.ts.map +1 -0
- package/dist/intelligence/heuristic.js +224 -0
- package/dist/intelligence/heuristic.js.map +1 -0
- package/dist/intelligence/http.d.ts +77 -0
- package/dist/intelligence/http.d.ts.map +1 -0
- package/dist/intelligence/http.js +496 -0
- package/dist/intelligence/http.js.map +1 -0
- package/dist/intelligence/provider-type.d.ts +6 -0
- package/dist/intelligence/provider-type.d.ts.map +1 -0
- package/dist/intelligence/provider-type.js +18 -0
- package/dist/intelligence/provider-type.js.map +1 -0
- package/dist/intelligence/provider.d.ts +49 -0
- package/dist/intelligence/provider.d.ts.map +1 -0
- package/dist/intelligence/provider.js +52 -0
- package/dist/intelligence/provider.js.map +1 -0
- package/dist/intelligence/related-k.d.ts +15 -0
- package/dist/intelligence/related-k.d.ts.map +1 -0
- package/dist/intelligence/related-k.js +57 -0
- package/dist/intelligence/related-k.js.map +1 -0
- package/dist/intelligence/routing-view.d.ts +33 -0
- package/dist/intelligence/routing-view.d.ts.map +1 -0
- package/dist/intelligence/routing-view.js +54 -0
- package/dist/intelligence/routing-view.js.map +1 -0
- package/dist/intelligence/sampling.d.ts +20 -0
- package/dist/intelligence/sampling.d.ts.map +1 -0
- package/dist/intelligence/sampling.js +324 -0
- package/dist/intelligence/sampling.js.map +1 -0
- package/dist/intelligence/stage-router.d.ts +32 -0
- package/dist/intelligence/stage-router.d.ts.map +1 -0
- package/dist/intelligence/stage-router.js +251 -0
- package/dist/intelligence/stage-router.js.map +1 -0
- package/dist/intelligence/steps.d.ts +65 -0
- package/dist/intelligence/steps.d.ts.map +1 -0
- package/dist/intelligence/steps.js +86 -0
- package/dist/intelligence/steps.js.map +1 -0
- package/dist/intelligence/subject.d.ts +42 -0
- package/dist/intelligence/subject.d.ts.map +1 -0
- package/dist/intelligence/subject.js +44 -0
- package/dist/intelligence/subject.js.map +1 -0
- package/dist/intelligence/token-budget.d.ts +86 -0
- package/dist/intelligence/token-budget.d.ts.map +1 -0
- package/dist/intelligence/token-budget.js +312 -0
- package/dist/intelligence/token-budget.js.map +1 -0
- package/dist/intelligence/types.d.ts +179 -0
- package/dist/intelligence/types.d.ts.map +1 -0
- package/dist/intelligence/types.js +7 -0
- package/dist/intelligence/types.js.map +1 -0
- package/dist/intelligence/usage.d.ts +104 -0
- package/dist/intelligence/usage.d.ts.map +1 -0
- package/dist/intelligence/usage.js +233 -0
- package/dist/intelligence/usage.js.map +1 -0
- package/dist/ipc/scheduler-ipc.d.ts +52 -0
- package/dist/ipc/scheduler-ipc.d.ts.map +1 -0
- package/dist/ipc/scheduler-ipc.js +214 -0
- package/dist/ipc/scheduler-ipc.js.map +1 -0
- package/dist/paths.d.ts +29 -0
- package/dist/paths.d.ts.map +1 -0
- package/dist/paths.js +47 -0
- package/dist/paths.js.map +1 -0
- package/dist/scheduler.d.ts +39 -0
- package/dist/scheduler.d.ts.map +1 -0
- package/dist/scheduler.js +93 -0
- package/dist/scheduler.js.map +1 -0
- package/dist/schemas/domains.d.ts +89 -0
- package/dist/schemas/domains.d.ts.map +1 -0
- package/dist/schemas/domains.js +160 -0
- package/dist/schemas/domains.js.map +1 -0
- package/dist/schemas/starter-vocabulary.d.ts +34 -0
- package/dist/schemas/starter-vocabulary.d.ts.map +1 -0
- package/dist/schemas/starter-vocabulary.js +91 -0
- package/dist/schemas/starter-vocabulary.js.map +1 -0
- package/dist/search/ann.d.ts +36 -0
- package/dist/search/ann.d.ts.map +1 -0
- package/dist/search/ann.js +59 -0
- package/dist/search/ann.js.map +1 -0
- package/dist/search/entity.d.ts +43 -0
- package/dist/search/entity.d.ts.map +1 -0
- package/dist/search/entity.js +147 -0
- package/dist/search/entity.js.map +1 -0
- package/dist/search/episodes.d.ts +28 -0
- package/dist/search/episodes.d.ts.map +1 -0
- package/dist/search/episodes.js +102 -0
- package/dist/search/episodes.js.map +1 -0
- package/dist/search/hnsw-graph.d.ts +35 -0
- package/dist/search/hnsw-graph.d.ts.map +1 -0
- package/dist/search/hnsw-graph.js +177 -0
- package/dist/search/hnsw-graph.js.map +1 -0
- package/dist/search/hnsw-ram.d.ts +29 -0
- package/dist/search/hnsw-ram.d.ts.map +1 -0
- package/dist/search/hnsw-ram.js +95 -0
- package/dist/search/hnsw-ram.js.map +1 -0
- package/dist/search/index.d.ts +119 -0
- package/dist/search/index.d.ts.map +1 -0
- package/dist/search/index.js +420 -0
- package/dist/search/index.js.map +1 -0
- package/dist/search/interlocutor-rank.d.ts +10 -0
- package/dist/search/interlocutor-rank.d.ts.map +1 -0
- package/dist/search/interlocutor-rank.js +21 -0
- package/dist/search/interlocutor-rank.js.map +1 -0
- package/dist/search/key-facts.d.ts +34 -0
- package/dist/search/key-facts.d.ts.map +1 -0
- package/dist/search/key-facts.js +43 -0
- package/dist/search/key-facts.js.map +1 -0
- package/dist/search/profile.d.ts +31 -0
- package/dist/search/profile.d.ts.map +1 -0
- package/dist/search/profile.js +43 -0
- package/dist/search/profile.js.map +1 -0
- package/dist/search/vector.d.ts +90 -0
- package/dist/search/vector.d.ts.map +1 -0
- package/dist/search/vector.js +187 -0
- package/dist/search/vector.js.map +1 -0
- package/dist/sources/claude-code.d.ts +35 -0
- package/dist/sources/claude-code.d.ts.map +1 -0
- package/dist/sources/claude-code.js +401 -0
- package/dist/sources/claude-code.js.map +1 -0
- package/dist/sources/copy.d.ts +58 -0
- package/dist/sources/copy.d.ts.map +1 -0
- package/dist/sources/copy.js +104 -0
- package/dist/sources/copy.js.map +1 -0
- package/dist/sources/cursor.d.ts +44 -0
- package/dist/sources/cursor.d.ts.map +1 -0
- package/dist/sources/cursor.js +99 -0
- package/dist/sources/cursor.js.map +1 -0
- package/dist/sources/jsonl-copy.d.ts +58 -0
- package/dist/sources/jsonl-copy.d.ts.map +1 -0
- package/dist/sources/jsonl-copy.js +195 -0
- package/dist/sources/jsonl-copy.js.map +1 -0
- package/dist/sources/jsonl-ingest.d.ts +58 -0
- package/dist/sources/jsonl-ingest.d.ts.map +1 -0
- package/dist/sources/jsonl-ingest.js +195 -0
- package/dist/sources/jsonl-ingest.js.map +1 -0
- package/dist/sources/pull.d.ts +85 -0
- package/dist/sources/pull.d.ts.map +1 -0
- package/dist/sources/pull.js +145 -0
- package/dist/sources/pull.js.map +1 -0
- package/dist/sources/resolve.d.ts +38 -0
- package/dist/sources/resolve.d.ts.map +1 -0
- package/dist/sources/resolve.js +91 -0
- package/dist/sources/resolve.js.map +1 -0
- package/dist/tools/capture-fact-description.d.ts +18 -0
- package/dist/tools/capture-fact-description.d.ts.map +1 -0
- package/dist/tools/capture-fact-description.js +41 -0
- package/dist/tools/capture-fact-description.js.map +1 -0
- package/dist/tools/fact-manager.d.ts +69 -0
- package/dist/tools/fact-manager.d.ts.map +1 -0
- package/dist/tools/fact-manager.js +332 -0
- package/dist/tools/fact-manager.js.map +1 -0
- package/dist/tools/inference-descriptions.d.ts +8 -0
- package/dist/tools/inference-descriptions.d.ts.map +1 -0
- package/dist/tools/inference-descriptions.js +16 -0
- package/dist/tools/inference-descriptions.js.map +1 -0
- package/dist/tools/inferences.d.ts +11 -0
- package/dist/tools/inferences.d.ts.map +1 -0
- package/dist/tools/inferences.js +98 -0
- package/dist/tools/inferences.js.map +1 -0
- package/dist/tools/read-tools.d.ts +21 -0
- package/dist/tools/read-tools.d.ts.map +1 -0
- package/dist/tools/read-tools.js +276 -0
- package/dist/tools/read-tools.js.map +1 -0
- package/dist/tools/resources.d.ts +62 -0
- package/dist/tools/resources.d.ts.map +1 -0
- package/dist/tools/resources.js +199 -0
- package/dist/tools/resources.js.map +1 -0
- package/dist/tools/session-manager.d.ts +44 -0
- package/dist/tools/session-manager.d.ts.map +1 -0
- package/dist/tools/session-manager.js +227 -0
- package/dist/tools/session-manager.js.map +1 -0
- package/dist/types/config.d.ts +400 -0
- package/dist/types/config.d.ts.map +1 -0
- package/dist/types/config.js +105 -0
- package/dist/types/config.js.map +1 -0
- package/dist/types/data.d.ts +357 -0
- package/dist/types/data.d.ts.map +1 -0
- package/dist/types/data.js +36 -0
- package/dist/types/data.js.map +1 -0
- package/dist/types/index.d.ts +6 -0
- package/dist/types/index.d.ts.map +1 -0
- package/dist/types/index.js +6 -0
- package/dist/types/index.js.map +1 -0
- package/dist/types.d.ts +115 -0
- package/dist/types.d.ts.map +1 -0
- package/dist/types.js +6 -0
- package/dist/types.js.map +1 -0
- package/dist/warnings.d.ts.map +1 -0
- package/dist/warnings.js.map +1 -0
- package/package.json +62 -0
|
@@ -0,0 +1,1234 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Consolidation pipeline — the core intelligence engine.
|
|
3
|
+
* Three steps, each optional per run (see ./steps.ts):
|
|
4
|
+
* copy: sources → D, through the caller's copier
|
|
5
|
+
* extract: D → I, candidate facts from raw events, capped per run
|
|
6
|
+
* integrate: I → K, classify, entities, reconcile, supersede, embed
|
|
7
|
+
* consolidate = all three. Which moments run which steps is MOMENT_POLICY.
|
|
8
|
+
*
|
|
9
|
+
* Loose analogy to human memory: rapid, context-rich capture during a session
|
|
10
|
+
* is separated from a later batch that integrates new information with prior
|
|
11
|
+
* knowledge. Not a model of hippocampal-cortical dynamics, and not a dream
|
|
12
|
+
* that invents facts nobody said.
|
|
13
|
+
*/
|
|
14
|
+
import { randomUUID } from "node:crypto";
|
|
15
|
+
import { withTransaction } from "../db/connection.js";
|
|
16
|
+
import { DEFAULT_CONFIDENCE, DEFAULT_IMPORTANCE, DEFAULT_CONFIG, } from "../types/config.js";
|
|
17
|
+
import { EXTRACT_EVIDENCE_SLICE, EXTRACT_REREAD_CONFIDENCE, EXTRACT_REREAD_WINDOW, capReferents, } from "./extract-prompt.js";
|
|
18
|
+
import { relatedFactsForExtract } from "./related-k.js";
|
|
19
|
+
import { latestConversationSituation, applySituation, NEWEST_CONSOLIDATION, } from "../db/consolidations.js";
|
|
20
|
+
import { normaliseForDedup } from "./heuristic.js";
|
|
21
|
+
import { attachBackingSources } from "./backing.js";
|
|
22
|
+
import { claimForConsolidation, getClaimedFacts, insertSessionFact, linkFactSource, primaryEventForFact, speakerRoleOf, speakerNameOf, UTTERED_BY, } from "../db/session-facts.js";
|
|
23
|
+
import { insertFact, getFactsByDomain, supersedeFact, } from "../db/facts.js";
|
|
24
|
+
import { createSource } from "../db/sources.js";
|
|
25
|
+
import { findOrCreateEntity, resolveEntityFamily, foldEntityToken, storedCanonicalName, getEntityById, linkFactEntity, upsertEntityEdge, recordSameAsForLinkedFoldPair, isSaidFoldIdentityPair, ensureSelfEntity, SUBJECT_OF, listEntityTypes, } from "../db/entities.js";
|
|
26
|
+
import { isAboutTheUser } from "./subject.js";
|
|
27
|
+
import { ensureDomain, loadStoreVocabulary } from "../db/domains.js";
|
|
28
|
+
import { importanceDefaults, normaliseDomainName } from "../schemas/domains.js";
|
|
29
|
+
import { acquireLock, releaseLock } from "../db/consolidation-lock.js";
|
|
30
|
+
import { advanceExtractMarksToCurrentMax, conversationExtractThrough, extractWatermark, listUnexaminedConversations, setConversationExtractThrough, unexaminedEventCount, } from "../db/extract-watermarks.js";
|
|
31
|
+
import { ALL_STEPS, EXTRACT_CAP_EVENTS, } from "./steps.js";
|
|
32
|
+
import { getFactsMissingEmbeddings, insertEmbeddings, } from "../db/embeddings.js";
|
|
33
|
+
import { insertIntelligenceRun, listIntelligenceRunsSince } from "../db/intelligence-runs.js";
|
|
34
|
+
import { takeProviderUsage, } from "./usage.js";
|
|
35
|
+
import { INTEGRATE_STAGE_NAMES, resolveStageProviderType, setHttpExtractCliFallback, } from "./stage-router.js";
|
|
36
|
+
import { getBoundTokenBudget, isBilledProvider, loadRunsForBudget, parseIntelligenceTokenBudget, evaluateTokenBudget, verdictForProvider, } from "./token-budget.js";
|
|
37
|
+
/**
|
|
38
|
+
* Named speaker is source. After `same_as`, the family can hold several
|
|
39
|
+
* person rows that are one identity — still link, preferring the row whose
|
|
40
|
+
* stored name matches the speaker string. No person in the family: do not
|
|
41
|
+
* guess (leave unlinked). Do not mint from a display name.
|
|
42
|
+
*/
|
|
43
|
+
function pickUtteredByPerson(persons, speakerName) {
|
|
44
|
+
if (persons.length === 0)
|
|
45
|
+
return null;
|
|
46
|
+
const canon = storedCanonicalName(speakerName);
|
|
47
|
+
return persons.find((e) => e.canonical_name === canon) ?? persons[0];
|
|
48
|
+
}
|
|
49
|
+
// ---------------------------------------------------------------------------
|
|
50
|
+
// Pipeline
|
|
51
|
+
// ---------------------------------------------------------------------------
|
|
52
|
+
export async function consolidate(db, intelligence, config,
|
|
53
|
+
/**
|
|
54
|
+
* Optional — null means semantic search is off, which is the shipped default.
|
|
55
|
+
* Passed in rather than constructed here so consolidation keeps no opinion
|
|
56
|
+
* about providers, exactly as it keeps none about intelligence providers.
|
|
57
|
+
*/
|
|
58
|
+
embeddingProvider = null, steps = ALL_STEPS, caller = {}) {
|
|
59
|
+
const consolidationId = randomUUID();
|
|
60
|
+
const doExtract = steps.extract;
|
|
61
|
+
const doIntegrate = steps.integrate;
|
|
62
|
+
// Extract is bounded per run unless the caller lifted the cap (null).
|
|
63
|
+
const extractLimit = caller.extractLimit === undefined ? EXTRACT_CAP_EVENTS : caller.extractLimit;
|
|
64
|
+
const remainingEvents = () => unexaminedEventCount(db);
|
|
65
|
+
// Step 1: copy. Sources → D through the caller's copier. Runs before the
|
|
66
|
+
// lock: copying is an append and needs no exclusivity.
|
|
67
|
+
let eventsCopied = 0;
|
|
68
|
+
if (steps.copy && caller.copy) {
|
|
69
|
+
eventsCopied = (await caller.copy()).events_inserted;
|
|
70
|
+
}
|
|
71
|
+
const extractionEnabled = config?.extraction?.enabled ?? false;
|
|
72
|
+
// Read from the vocabulary the user configured, not a separate map. Importance
|
|
73
|
+
// is a property of a domain — a domain's calibration belongs with the domain,
|
|
74
|
+
// and a second list keyed by name is one more thing to drift. Whoever owns the
|
|
75
|
+
// vocabulary owns its calibration: a missed allergy is the costliest error in a
|
|
76
|
+
// personal store, a missed SLA breach in a corporate one, and the engine cannot
|
|
77
|
+
// know which it is looking at.
|
|
78
|
+
const storeVocabulary = await loadStoreVocabulary(db, config?.domains ?? []);
|
|
79
|
+
const defaultsByDomain = importanceDefaults(storeVocabulary);
|
|
80
|
+
// Phase A: Acquire lock
|
|
81
|
+
const locked = await acquireLock(db, consolidationId);
|
|
82
|
+
if (!locked) {
|
|
83
|
+
return {
|
|
84
|
+
consolidationId,
|
|
85
|
+
factsIn: 0,
|
|
86
|
+
factsIntegrated: 0,
|
|
87
|
+
factsRejected: 0,
|
|
88
|
+
entitiesCreated: 0,
|
|
89
|
+
entitiesLinked: 0,
|
|
90
|
+
supersessions: 0,
|
|
91
|
+
summary: null,
|
|
92
|
+
openThreads: [],
|
|
93
|
+
skipped: true,
|
|
94
|
+
skipReason: "Another consolidation is in progress",
|
|
95
|
+
eventsCopied,
|
|
96
|
+
eventsRemaining: await remainingEvents(),
|
|
97
|
+
examinedThrough: await extractWatermark(db),
|
|
98
|
+
};
|
|
99
|
+
}
|
|
100
|
+
// Live extract clock, not MAX(consolidations.last_event_sequence).
|
|
101
|
+
// An empty run that does not advance this number is not worth a row.
|
|
102
|
+
const prevWatermark = await extractWatermark(db);
|
|
103
|
+
// Set when the configured extractor could not run. The events it was meant to
|
|
104
|
+
// read have not been examined, so the watermark must stay where it was and
|
|
105
|
+
// leave them eligible for the next run. Advancing regardless is what made a
|
|
106
|
+
// transient provider failure discard a batch of conversation for good.
|
|
107
|
+
let extractionDegraded = false;
|
|
108
|
+
let extractPending = [];
|
|
109
|
+
let prefixCommitted = false;
|
|
110
|
+
let phaseDCommitted = false;
|
|
111
|
+
const finish = async (result) => {
|
|
112
|
+
const usage = await persistIntelligenceUsage(db, intelligence, consolidationId, caller);
|
|
113
|
+
if (usage)
|
|
114
|
+
result.usage = usage;
|
|
115
|
+
return result;
|
|
116
|
+
};
|
|
117
|
+
const intel = config?.intelligence ?? {
|
|
118
|
+
provider: "cli",
|
|
119
|
+
api_key: null,
|
|
120
|
+
};
|
|
121
|
+
let skipExtract = false;
|
|
122
|
+
let skipIntegrate = false;
|
|
123
|
+
let budgetReason;
|
|
124
|
+
let allowHttpCliFallback = true;
|
|
125
|
+
const parsedBudget = getBoundTokenBudget(db) ?? parseIntelligenceTokenBudget(intel);
|
|
126
|
+
if (parsedBudget && (doExtract || doIntegrate)) {
|
|
127
|
+
const runs = await loadRunsForBudget((since) => listIntelligenceRunsSince(db, since), parsedBudget);
|
|
128
|
+
const report = evaluateTokenBudget(runs, parsedBudget);
|
|
129
|
+
if (doExtract) {
|
|
130
|
+
const extractType = resolveStageProviderType(intel, "extract");
|
|
131
|
+
if (isBilledProvider(extractType)) {
|
|
132
|
+
const verdict = verdictForProvider(report, extractType);
|
|
133
|
+
if (verdict.skip) {
|
|
134
|
+
skipExtract = true;
|
|
135
|
+
budgetReason = verdict.reason;
|
|
136
|
+
}
|
|
137
|
+
}
|
|
138
|
+
if (extractType === "http") {
|
|
139
|
+
allowHttpCliFallback = !verdictForProvider(report, "cli").skip;
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
if (doIntegrate) {
|
|
143
|
+
for (const stage of INTEGRATE_STAGE_NAMES) {
|
|
144
|
+
const stageType = resolveStageProviderType(intel, stage);
|
|
145
|
+
if (!isBilledProvider(stageType))
|
|
146
|
+
continue;
|
|
147
|
+
const verdict = verdictForProvider(report, stageType);
|
|
148
|
+
if (verdict.skip) {
|
|
149
|
+
skipIntegrate = true;
|
|
150
|
+
budgetReason = verdict.reason;
|
|
151
|
+
break;
|
|
152
|
+
}
|
|
153
|
+
}
|
|
154
|
+
}
|
|
155
|
+
const extractWillRun = doExtract && !skipExtract;
|
|
156
|
+
const integrateWillRun = doIntegrate && !skipIntegrate;
|
|
157
|
+
if (!extractWillRun && !integrateWillRun && (skipExtract || skipIntegrate)) {
|
|
158
|
+
await releaseLock(db, consolidationId);
|
|
159
|
+
return {
|
|
160
|
+
consolidationId,
|
|
161
|
+
factsIn: 0,
|
|
162
|
+
factsIntegrated: 0,
|
|
163
|
+
factsRejected: 0,
|
|
164
|
+
entitiesCreated: 0,
|
|
165
|
+
entitiesLinked: 0,
|
|
166
|
+
supersessions: 0,
|
|
167
|
+
summary: null,
|
|
168
|
+
openThreads: [],
|
|
169
|
+
skipped: true,
|
|
170
|
+
skipReason: budgetReason,
|
|
171
|
+
eventsCopied,
|
|
172
|
+
eventsRemaining: await remainingEvents(),
|
|
173
|
+
examinedThrough: prevWatermark,
|
|
174
|
+
};
|
|
175
|
+
}
|
|
176
|
+
}
|
|
177
|
+
const extractNow = doExtract && !skipExtract;
|
|
178
|
+
const integrateNow = doIntegrate && !skipIntegrate;
|
|
179
|
+
setHttpExtractCliFallback(intelligence, allowHttpCliFallback);
|
|
180
|
+
try {
|
|
181
|
+
// Phase B: D→I event extraction (if this run examines events).
|
|
182
|
+
// Session facts land unclaimed so a later run that includes integrate
|
|
183
|
+
// can claim them; which moments run which steps is MOMENT_POLICY.
|
|
184
|
+
if (extractNow && extractionEnabled) {
|
|
185
|
+
const extracted = await extractFactsFromEvents(db, intelligence, config, extractLimit);
|
|
186
|
+
extractionDegraded = extracted.degraded;
|
|
187
|
+
extractPending = extracted.pending;
|
|
188
|
+
prefixCommitted = extracted.prefixCommitted;
|
|
189
|
+
}
|
|
190
|
+
else if (extractNow && !extractionEnabled) {
|
|
191
|
+
// Policy decline, not provider-down: every conversation is examined
|
|
192
|
+
// as empty through its current max sequence.
|
|
193
|
+
await advanceExtractMarksToCurrentMax(db);
|
|
194
|
+
}
|
|
195
|
+
// Integrate-only leaves extract marks untouched. Extract writes per-id
|
|
196
|
+
// marks as it goes; the run row audits the global MIN through.
|
|
197
|
+
const effectiveWatermark = await extractWatermark(db);
|
|
198
|
+
if (integrateNow) {
|
|
199
|
+
await claimForConsolidation(db, consolidationId);
|
|
200
|
+
}
|
|
201
|
+
const sessionFacts = integrateNow
|
|
202
|
+
? await getClaimedFacts(db, consolidationId)
|
|
203
|
+
: [];
|
|
204
|
+
if (sessionFacts.length === 0) {
|
|
205
|
+
// Only record an empty run when this run examined events and the
|
|
206
|
+
// watermark actually advances. Integrate-only with nothing pending is
|
|
207
|
+
// a PreCompact no-op — do not spam rows or pretend D was read.
|
|
208
|
+
if (extractNow && effectiveWatermark > prevWatermark) {
|
|
209
|
+
const onlyId = extractPending.length === 1 ? extractPending[0].group.ref.id : null;
|
|
210
|
+
await db.prepare(`INSERT INTO consolidations
|
|
211
|
+
(id, session_id, facts_in, facts_integrated, facts_rejected,
|
|
212
|
+
entities_created, entities_linked, supersessions,
|
|
213
|
+
summary, open_threads, last_event_sequence, created_at)
|
|
214
|
+
VALUES (?, ?, 0, 0, 0, 0, 0, 0, NULL, NULL, ?, ?)`).run(consolidationId, onlyId, effectiveWatermark, new Date().toISOString());
|
|
215
|
+
await persistSituations(db, consolidationId, onlyId, extractPending, effectiveWatermark);
|
|
216
|
+
}
|
|
217
|
+
// Backfill on the empty path too. This branch is "nothing new integrated",
|
|
218
|
+
// which is exactly the state a store is in when it has a backlog and no
|
|
219
|
+
// fresh input — semantic search switched on over an existing store, or a
|
|
220
|
+
// previous run whose provider was down. Returning here without embedding
|
|
221
|
+
// would mean the backlog only ever drains on runs that happen to have new
|
|
222
|
+
// facts, which for a quiet store is never.
|
|
223
|
+
if (integrateNow) {
|
|
224
|
+
await embedIntegratedFacts(db, embeddingProvider, config);
|
|
225
|
+
}
|
|
226
|
+
await releaseLock(db, consolidationId);
|
|
227
|
+
const extractedCount = extractPending.reduce((n, p) => n + p.facts.length, 0);
|
|
228
|
+
return await finish({
|
|
229
|
+
consolidationId,
|
|
230
|
+
extractionDegraded,
|
|
231
|
+
factsIn: extractedCount,
|
|
232
|
+
factsIntegrated: 0,
|
|
233
|
+
factsRejected: 0,
|
|
234
|
+
entitiesCreated: 0,
|
|
235
|
+
entitiesLinked: 0,
|
|
236
|
+
supersessions: 0,
|
|
237
|
+
eventsCopied,
|
|
238
|
+
eventsRemaining: await remainingEvents(),
|
|
239
|
+
summary: null,
|
|
240
|
+
openThreads: [],
|
|
241
|
+
skipped: false,
|
|
242
|
+
...(budgetReason ? { skipReason: budgetReason } : {}),
|
|
243
|
+
examinedThrough: effectiveWatermark,
|
|
244
|
+
prefixCommitted,
|
|
245
|
+
});
|
|
246
|
+
}
|
|
247
|
+
// Phase C: I→K integration pipeline (LLM calls happen here, outside transaction)
|
|
248
|
+
// Build lookup map for O(1) access in Phase C and D
|
|
249
|
+
const sessionFactMap = new Map(sessionFacts.map((f) => [f.id, f]));
|
|
250
|
+
// Step 1: Classify domains. For session_facts that carry a domain_hint
|
|
251
|
+
// from extraction (set by CLI/sampling providers via subdomain_hint etc.),
|
|
252
|
+
// trust that directly and don't re-call the classifier. Falls through to
|
|
253
|
+
// the heuristic (or configured provider) for explicit-capture facts.
|
|
254
|
+
const needsClassification = sessionFacts.filter((f) => !f.domain_hint);
|
|
255
|
+
const autoClassified = sessionFacts
|
|
256
|
+
.filter((f) => f.domain_hint)
|
|
257
|
+
.map((f) => ({
|
|
258
|
+
id: f.id,
|
|
259
|
+
content: f.content,
|
|
260
|
+
domain: f.domain_hint,
|
|
261
|
+
subdomain: f.subdomain_hint ?? null,
|
|
262
|
+
}));
|
|
263
|
+
const explicitClassified = needsClassification.length
|
|
264
|
+
? await intelligence.classifyFacts(needsClassification)
|
|
265
|
+
: [];
|
|
266
|
+
// Canonicalise every domain's spelling, whatever produced it: a caller's
|
|
267
|
+
// hint (which skips classification) or a provider's output. This merges
|
|
268
|
+
// "Preferences" into "preferences" so one domain cannot exist twice.
|
|
269
|
+
//
|
|
270
|
+
// It deliberately does not coerce an unknown domain into `general`. The
|
|
271
|
+
// taxonomy is open beyond the core, and the label a classifier chose is the
|
|
272
|
+
// most distinctive thing about a fact that fits nothing else — discarding it
|
|
273
|
+
// is the lossy step. Retrieval must therefore never depend on the label
|
|
274
|
+
// matching exactly; see docs/design/data-model.md § Domains.
|
|
275
|
+
const classified = [...autoClassified, ...explicitClassified].map((cf) => ({
|
|
276
|
+
...cf,
|
|
277
|
+
domain: normaliseDomainName(cf.domain),
|
|
278
|
+
}));
|
|
279
|
+
// Step 2: Build entity map. Prefer pre-extracted entities stored on the
|
|
280
|
+
// session_fact (populated by the CLI provider's holistic extraction) —
|
|
281
|
+
// saves an LLM call. Facts without entities_json go through the provider's
|
|
282
|
+
// extractEntities path.
|
|
283
|
+
const entityMap = new Map();
|
|
284
|
+
const needsEntityExtraction = [];
|
|
285
|
+
for (const sf of sessionFacts) {
|
|
286
|
+
if (sf.entities_json) {
|
|
287
|
+
try {
|
|
288
|
+
const pre = JSON.parse(sf.entities_json);
|
|
289
|
+
if (Array.isArray(pre) && pre.length > 0) {
|
|
290
|
+
entityMap.set(sf.id, pre);
|
|
291
|
+
continue;
|
|
292
|
+
}
|
|
293
|
+
}
|
|
294
|
+
catch {
|
|
295
|
+
// Malformed JSON — fall through to provider extraction.
|
|
296
|
+
}
|
|
297
|
+
}
|
|
298
|
+
needsEntityExtraction.push(sf);
|
|
299
|
+
}
|
|
300
|
+
if (needsEntityExtraction.length > 0) {
|
|
301
|
+
const extracted = await intelligence.extractEntities(needsEntityExtraction);
|
|
302
|
+
for (const [id, ents] of extracted.entries()) {
|
|
303
|
+
entityMap.set(id, ents);
|
|
304
|
+
}
|
|
305
|
+
}
|
|
306
|
+
// Domain cache shared between reconcile and supersession passes.
|
|
307
|
+
// Domain scan gives both passes a consistent candidate pool and avoids re-fetching.
|
|
308
|
+
// FTS5 would miss paraphrased duplicates (AND-semantics requires all terms to match).
|
|
309
|
+
const domainCache = new Map();
|
|
310
|
+
const getDomainFacts = async (domain) => {
|
|
311
|
+
let cached = domainCache.get(domain);
|
|
312
|
+
if (!cached) {
|
|
313
|
+
cached = await getFactsByDomain(db, domain);
|
|
314
|
+
domainCache.set(domain, cached);
|
|
315
|
+
}
|
|
316
|
+
return cached;
|
|
317
|
+
};
|
|
318
|
+
// Step 3: Reconcile each fact against existing knowledge
|
|
319
|
+
const toIntegrate = [];
|
|
320
|
+
let rejected = 0;
|
|
321
|
+
/** Confidence boosts to apply to existing facts via Mem0's "enrich"
|
|
322
|
+
* reconcile decision — candidate is a paraphrase / corroboration of an
|
|
323
|
+
* existing fact, so instead of integrating we strengthen the existing one. */
|
|
324
|
+
const enrichments = [];
|
|
325
|
+
// Intra-batch dedup: track normalised content already queued for integration.
|
|
326
|
+
// Without this, two session_facts with identical content from different sessions
|
|
327
|
+
// both pass same-session hash dedup and both pass reconcile (neither has a integrated
|
|
328
|
+
// twin yet), producing duplicate rows in the facts table.
|
|
329
|
+
const seenBatchContent = new Set();
|
|
330
|
+
for (const cf of classified) {
|
|
331
|
+
const sessionFact = sessionFactMap.get(cf.id);
|
|
332
|
+
if (!sessionFact)
|
|
333
|
+
continue;
|
|
334
|
+
// Shared normalisation with cross-batch reconcile (heuristic.ts) so
|
|
335
|
+
// "I prefer coffee" vs "I prefer coffee." is consistently handled.
|
|
336
|
+
const normalised = normaliseForDedup(cf.content);
|
|
337
|
+
if (seenBatchContent.has(normalised)) {
|
|
338
|
+
rejected++;
|
|
339
|
+
continue;
|
|
340
|
+
}
|
|
341
|
+
const domainFacts = await getDomainFacts(cf.domain);
|
|
342
|
+
const decision = await intelligence.reconcile(sessionFact, domainFacts);
|
|
343
|
+
if (decision.kind === "noop") {
|
|
344
|
+
rejected++;
|
|
345
|
+
continue;
|
|
346
|
+
}
|
|
347
|
+
if (decision.kind === "enrich") {
|
|
348
|
+
// Validate the targeted ID is in our domain candidates. If the LLM
|
|
349
|
+
// hallucinated an id, fall through to the add path as a safer default.
|
|
350
|
+
const target = domainFacts.find((f) => f.id === decision.existingFactId);
|
|
351
|
+
if (target) {
|
|
352
|
+
enrichments.push({
|
|
353
|
+
existingFactId: decision.existingFactId,
|
|
354
|
+
confidenceDelta: 0.1,
|
|
355
|
+
});
|
|
356
|
+
rejected++;
|
|
357
|
+
continue;
|
|
358
|
+
}
|
|
359
|
+
// else: hallucinated id → treat as add
|
|
360
|
+
}
|
|
361
|
+
seenBatchContent.add(normalised);
|
|
362
|
+
// Confidence/importance: explicit captures carry their own values; for
|
|
363
|
+
// inferred facts the extraction signals are the most informative input.
|
|
364
|
+
// Precedence: explicit > LLM signal > default.
|
|
365
|
+
const resolvedConfidence = sessionFact.confidence ??
|
|
366
|
+
sessionFact.confidence_signal ??
|
|
367
|
+
DEFAULT_CONFIDENCE;
|
|
368
|
+
// Resolution order, per data-model.md: the assistant's explicit value, a
|
|
369
|
+
// provider's signal, the domain's default, then the neutral baseline.
|
|
370
|
+
//
|
|
371
|
+
// The domain default is applied HERE rather than at capture because this
|
|
372
|
+
// is the first point the domain is actually known. capture_fact resolves
|
|
373
|
+
// it from the caller's domain_hint, which callers rarely pass — so for an
|
|
374
|
+
// ordinary capture the config layer never fired and everything landed on
|
|
375
|
+
// DEFAULT_IMPORTANCE. Keying off the classified domain is what makes the
|
|
376
|
+
// documented order real.
|
|
377
|
+
const resolvedImportance = sessionFact.importance ??
|
|
378
|
+
sessionFact.importance_signal ??
|
|
379
|
+
defaultsByDomain[cf.domain] ??
|
|
380
|
+
DEFAULT_IMPORTANCE;
|
|
381
|
+
toIntegrate.push({
|
|
382
|
+
sessionFactId: cf.id,
|
|
383
|
+
content: cf.content,
|
|
384
|
+
domain: cf.domain,
|
|
385
|
+
subdomain: cf.subdomain,
|
|
386
|
+
confidence: resolvedConfidence,
|
|
387
|
+
importance: resolvedImportance,
|
|
388
|
+
});
|
|
389
|
+
}
|
|
390
|
+
// The run row carries this id when every fact this batch belongs to one
|
|
391
|
+
// conversation. Mixed batches leave it null — per-session rolling
|
|
392
|
+
// summaries are written as satellite consolidations rows below, not
|
|
393
|
+
// dropped.
|
|
394
|
+
const uniqueSessionIds = new Set(sessionFacts.map((f) => f.session_id));
|
|
395
|
+
const recordSessionId = uniqueSessionIds.size === 1 ? [...uniqueSessionIds][0] : null;
|
|
396
|
+
// Step 4: Detect supersessions (outside transaction — may involve LLM)
|
|
397
|
+
// Known limitation: supersession only checks new facts against EXISTING
|
|
398
|
+
// integrated facts (from the domainCache populated above). Two facts in the
|
|
399
|
+
// SAME batch cannot supersede each other. If a user captures "I prefer
|
|
400
|
+
// coffee" then "I no longer prefer coffee" in one session, both integrate
|
|
401
|
+
// as active facts. Fix: add an intra-batch supersession pass over
|
|
402
|
+
// toIntegrate before the write transaction.
|
|
403
|
+
const supersessionMap = new Map(); // sessionFactId → existingFactId to supersede
|
|
404
|
+
const alreadySuperseded = new Set(); // existingFactId already claimed by another candidate
|
|
405
|
+
// Track supersession intents that were dropped because another candidate
|
|
406
|
+
// in the same batch claimed the target first. Surfaced via openThreads so
|
|
407
|
+
// the user knows their contradiction signal was partially lost.
|
|
408
|
+
const droppedSupersessions = [];
|
|
409
|
+
// toIntegrate is ordered by capture time (classifyFacts preserves input order).
|
|
410
|
+
// First candidate to claim an existing fact wins — temporal priority.
|
|
411
|
+
for (const item of toIntegrate) {
|
|
412
|
+
// Supersession is domain-scoped. FTS5 is the wrong tool here: it fails
|
|
413
|
+
// when the new fact contains negation tokens ("no longer", "stopped")
|
|
414
|
+
// that don't appear in the old fact. Use cached domain scan instead.
|
|
415
|
+
const candidates = await getDomainFacts(item.domain);
|
|
416
|
+
const candidate = { id: item.sessionFactId, content: item.content, domain: item.domain, subdomain: item.subdomain };
|
|
417
|
+
const result = await intelligence.detectSupersession(candidate, candidates);
|
|
418
|
+
// Intentional: confidence is NOT compared here. A low-confidence new fact
|
|
419
|
+
// with a clear negation marker ("I no longer prefer X") can supersede a
|
|
420
|
+
// high-confidence prior. The negation signal is itself strong evidence
|
|
421
|
+
// of a belief update; requiring confidence parity would make it impossible
|
|
422
|
+
// for tentative corrections to update stale knowledge.
|
|
423
|
+
if (result) {
|
|
424
|
+
if (!alreadySuperseded.has(result.existingFactId)) {
|
|
425
|
+
supersessionMap.set(item.sessionFactId, result.existingFactId);
|
|
426
|
+
alreadySuperseded.add(result.existingFactId);
|
|
427
|
+
}
|
|
428
|
+
else {
|
|
429
|
+
// Another candidate already claimed this target. This candidate will
|
|
430
|
+
// integrate as a plain insert rather than a supersession — record the
|
|
431
|
+
// conflict so it can surface in openThreads.
|
|
432
|
+
const targeted = candidates.find((c) => c.id === result.existingFactId);
|
|
433
|
+
droppedSupersessions.push({
|
|
434
|
+
newContent: item.content,
|
|
435
|
+
targetedContent: targeted?.content ?? result.existingFactId,
|
|
436
|
+
});
|
|
437
|
+
}
|
|
438
|
+
}
|
|
439
|
+
}
|
|
440
|
+
const supersessionCount = supersessionMap.size;
|
|
441
|
+
const integratedFacts = [];
|
|
442
|
+
// Phase D: Write results in a transaction
|
|
443
|
+
const writeResults = await withTransaction(db, async () => {
|
|
444
|
+
let entitiesCreated = 0;
|
|
445
|
+
let entitiesLinked = 0;
|
|
446
|
+
// Ensure all unique domains exist once, before the per-fact loop
|
|
447
|
+
const uniqueDomains = new Set(toIntegrate.map((item) => item.domain));
|
|
448
|
+
for (const domain of uniqueDomains) {
|
|
449
|
+
await ensureDomain(db, domain);
|
|
450
|
+
}
|
|
451
|
+
for (const item of toIntegrate) {
|
|
452
|
+
const sessionFact = sessionFactMap.get(item.sessionFactId);
|
|
453
|
+
// Write provenance source linking integrated fact back to its session_fact
|
|
454
|
+
// (and through session_fact_sources, to the originating events).
|
|
455
|
+
const source = await createSource(db, {
|
|
456
|
+
type: "session-fact",
|
|
457
|
+
tool_id: sessionFact.source_tool,
|
|
458
|
+
raw_content: sessionFact.content,
|
|
459
|
+
metadata: {
|
|
460
|
+
session_fact_id: sessionFact.id,
|
|
461
|
+
session_id: sessionFact.session_id,
|
|
462
|
+
source_origin: sessionFact.source_origin,
|
|
463
|
+
},
|
|
464
|
+
});
|
|
465
|
+
const supersededId = supersessionMap.get(item.sessionFactId);
|
|
466
|
+
// Capture context: prefer the LLM-derived hint over the explicit one.
|
|
467
|
+
const captureContext = sessionFact.capture_context ?? null;
|
|
468
|
+
// World time if extract stated a real ISO day; explicit null if not.
|
|
469
|
+
// Do not omit the field — insertFact would then default to now, and a
|
|
470
|
+
// past event would look as if it became true at integration.
|
|
471
|
+
const validFrom = sessionFact.valid_from_hint;
|
|
472
|
+
const integratedFact = supersededId
|
|
473
|
+
? await supersedeFact(db, supersededId, {
|
|
474
|
+
content: item.content,
|
|
475
|
+
domain: item.domain,
|
|
476
|
+
subdomain: item.subdomain,
|
|
477
|
+
confidence: item.confidence,
|
|
478
|
+
importance: item.importance,
|
|
479
|
+
source_type: "conversation",
|
|
480
|
+
source_tool: sessionFact.source_tool,
|
|
481
|
+
source_id: source.id,
|
|
482
|
+
session_id: sessionFact.session_id,
|
|
483
|
+
capture_context: captureContext,
|
|
484
|
+
source_quality: sessionFact.source_quality,
|
|
485
|
+
speaker_role: sessionFact.speaker_role,
|
|
486
|
+
speaker: sessionFact.speaker,
|
|
487
|
+
valid_from: validFrom,
|
|
488
|
+
}, {
|
|
489
|
+
// Fourth clock is config-gated: simple mode (the default) never
|
|
490
|
+
// writes system_retired_at. Bi-temporal mode stamps the instant
|
|
491
|
+
// the system retracted belief in the old fact.
|
|
492
|
+
retireSystemTime: config?.temporal?.mode === "bitemporal",
|
|
493
|
+
})
|
|
494
|
+
: await insertFact(db, {
|
|
495
|
+
content: item.content,
|
|
496
|
+
domain: item.domain,
|
|
497
|
+
subdomain: item.subdomain,
|
|
498
|
+
confidence: item.confidence,
|
|
499
|
+
importance: item.importance,
|
|
500
|
+
source_type: "conversation",
|
|
501
|
+
source_tool: sessionFact.source_tool,
|
|
502
|
+
source_id: source.id,
|
|
503
|
+
session_id: sessionFact.session_id,
|
|
504
|
+
capture_context: captureContext,
|
|
505
|
+
source_quality: sessionFact.source_quality,
|
|
506
|
+
speaker_role: sessionFact.speaker_role,
|
|
507
|
+
speaker: sessionFact.speaker,
|
|
508
|
+
valid_from: validFrom,
|
|
509
|
+
});
|
|
510
|
+
integratedFacts.push(integratedFact);
|
|
511
|
+
// Link entities
|
|
512
|
+
const extractedEntities = entityMap.get(item.sessionFactId);
|
|
513
|
+
if (extractedEntities) {
|
|
514
|
+
const factId = integratedFact.id;
|
|
515
|
+
const resolvedIds = [];
|
|
516
|
+
const resolvedEntities = [];
|
|
517
|
+
for (const entity of extractedEntities) {
|
|
518
|
+
let resolved = null;
|
|
519
|
+
// LLM-resolved existing entity — validate the id, fall through if
|
|
520
|
+
// hallucinated.
|
|
521
|
+
if (entity.existing_id) {
|
|
522
|
+
resolved = await getEntityById(db, entity.existing_id);
|
|
523
|
+
}
|
|
524
|
+
if (!resolved) {
|
|
525
|
+
const created = await findOrCreateEntity(db, {
|
|
526
|
+
type: entity.type,
|
|
527
|
+
name: entity.name,
|
|
528
|
+
});
|
|
529
|
+
if (created.created)
|
|
530
|
+
entitiesCreated++;
|
|
531
|
+
resolved = created.entity;
|
|
532
|
+
}
|
|
533
|
+
resolvedIds.push(resolved.id);
|
|
534
|
+
resolvedEntities.push(resolved);
|
|
535
|
+
await linkFactEntity(db, factId, resolved.id, entity.relationship);
|
|
536
|
+
entitiesLinked++;
|
|
537
|
+
}
|
|
538
|
+
await recordSameAsForLinkedFoldPair(db, resolvedEntities);
|
|
539
|
+
// Create entity-entity edges for co-occurring entities (using cached IDs).
|
|
540
|
+
// co_mentioned is undirected — canonicalise by putting smaller id first
|
|
541
|
+
// so (A, B) and (B, A) collapse to one row. Skip a pair that the said
|
|
542
|
+
// rule just united: identity is not co-mention.
|
|
543
|
+
for (let i = 0; i < resolvedIds.length; i++) {
|
|
544
|
+
for (let j = i + 1; j < resolvedIds.length; j++) {
|
|
545
|
+
if (isSaidFoldIdentityPair(resolvedEntities[i], resolvedEntities[j])) {
|
|
546
|
+
continue;
|
|
547
|
+
}
|
|
548
|
+
const [a, b] = resolvedIds[i] < resolvedIds[j]
|
|
549
|
+
? [resolvedIds[i], resolvedIds[j]]
|
|
550
|
+
: [resolvedIds[j], resolvedIds[i]];
|
|
551
|
+
await upsertEntityEdge(db, a, b, "co_mentioned");
|
|
552
|
+
}
|
|
553
|
+
}
|
|
554
|
+
}
|
|
555
|
+
// Mark the subject, where it can be known without guessing.
|
|
556
|
+
//
|
|
557
|
+
// Outside the `extractedEntities` branch above deliberately: a fact can
|
|
558
|
+
// be about the user and name nobody at all ("The user prefers dark
|
|
559
|
+
// mode"), which is precisely the fact that most needs an anchor and the
|
|
560
|
+
// one an extractor returns nothing for.
|
|
561
|
+
//
|
|
562
|
+
// Only the deterministic self-case is handled here. Third-party
|
|
563
|
+
// subjects come from the provider's entity list (subject_of). A wrong
|
|
564
|
+
// automatic guess is worse than a mention-only link.
|
|
565
|
+
if (isAboutTheUser(integratedFact.content)) {
|
|
566
|
+
await linkFactEntity(db, integratedFact.id, (await ensureSelfEntity(db)).id, SUBJECT_OF);
|
|
567
|
+
entitiesLinked++;
|
|
568
|
+
}
|
|
569
|
+
// Named speaker is source, not subject. Link only when the person
|
|
570
|
+
// already exists — do not mint an entity from a Teams display name.
|
|
571
|
+
if (sessionFact.speaker) {
|
|
572
|
+
const family = await resolveEntityFamily(db, sessionFact.speaker);
|
|
573
|
+
const persons = family.filter((e) => foldEntityToken(e.type) === "person");
|
|
574
|
+
const speakerEntity = pickUtteredByPerson(persons, sessionFact.speaker);
|
|
575
|
+
if (speakerEntity) {
|
|
576
|
+
await linkFactEntity(db, integratedFact.id, speakerEntity.id, UTTERED_BY);
|
|
577
|
+
entitiesLinked++;
|
|
578
|
+
}
|
|
579
|
+
}
|
|
580
|
+
else if (sessionFact.speaker_role === "user") {
|
|
581
|
+
// Unnamed user-channel speech is said by the store's owner.
|
|
582
|
+
// Do not write speaker "self" or "the user" — the link is the id.
|
|
583
|
+
await linkFactEntity(db, integratedFact.id, (await ensureSelfEntity(db)).id, UTTERED_BY);
|
|
584
|
+
entitiesLinked++;
|
|
585
|
+
}
|
|
586
|
+
}
|
|
587
|
+
// Apply enrich decisions — boost existing facts' confidence (capped at 1.0)
|
|
588
|
+
// for each paraphrase/corroboration the LLM identified.
|
|
589
|
+
const enrichStmt = db.prepare(`UPDATE facts SET confidence = MIN(1.0, confidence + ?) WHERE id = ?`);
|
|
590
|
+
for (const e of enrichments) {
|
|
591
|
+
await enrichStmt.run(e.confidenceDelta, e.existingFactId);
|
|
592
|
+
}
|
|
593
|
+
// Insert consolidation record
|
|
594
|
+
await db.prepare(`INSERT INTO consolidations
|
|
595
|
+
(id, session_id, facts_in, facts_integrated, facts_rejected,
|
|
596
|
+
entities_created, entities_linked, supersessions,
|
|
597
|
+
summary, open_threads, last_event_sequence, created_at)
|
|
598
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`).run(consolidationId, recordSessionId, sessionFacts.length, toIntegrate.length, rejected, entitiesCreated, entitiesLinked, supersessionCount, null, // summary filled below
|
|
599
|
+
null, effectiveWatermark, new Date().toISOString());
|
|
600
|
+
return { entitiesCreated, entitiesLinked };
|
|
601
|
+
});
|
|
602
|
+
phaseDCommitted = true;
|
|
603
|
+
// Phase E: embed the facts that just integrated, if semantic search is on.
|
|
604
|
+
//
|
|
605
|
+
// After the commit, deliberately. An embedding is derived data, and no
|
|
606
|
+
// failure here may cost a fact: the provider is a network call or a local
|
|
607
|
+
// service, and both fail in ways consolidation must survive. Facts are
|
|
608
|
+
// already durable at this point, so the worst case is that they carry no
|
|
609
|
+
// vector until the next run picks them up.
|
|
610
|
+
//
|
|
611
|
+
// Also outside the lock — like summarise() below, and for the same reason.
|
|
612
|
+
await embedIntegratedFacts(db, embeddingProvider, config);
|
|
613
|
+
// Release lock before summary generation. summarise() is async on the
|
|
614
|
+
// IntelligenceProvider interface — LLM-based providers make calls that
|
|
615
|
+
// should not hold the advisory lock. If the process crashes between release
|
|
616
|
+
// and the summary UPDATE, the consolidation record has summary=NULL, which
|
|
617
|
+
// is acceptable (all facts are already integrated).
|
|
618
|
+
await releaseLock(db, consolidationId);
|
|
619
|
+
// Build open threads from summary + any dropped supersessions
|
|
620
|
+
const conflictMessages = droppedSupersessions.map((d) => `Conflict: "${d.newContent}" also targeted "${d.targetedContent}" for supersession but another candidate won. Integrated as an independent fact — review manually.`);
|
|
621
|
+
// Generate summaries (non-critical — don't lose a successful consolidation
|
|
622
|
+
// on failure). One conversation updates the run row. Several conversations
|
|
623
|
+
// leave the run row as the watermark clock and write a satellite row per
|
|
624
|
+
// session so the next extract of that id still has a rolling summary.
|
|
625
|
+
let summaryText = null;
|
|
626
|
+
let threads = [...conflictMessages];
|
|
627
|
+
if (recordSessionId) {
|
|
628
|
+
const priorSessionSummary = await latestSessionSummary(db, recordSessionId, consolidationId);
|
|
629
|
+
try {
|
|
630
|
+
await persistSituations(db, consolidationId, recordSessionId, extractPending, effectiveWatermark);
|
|
631
|
+
const closed = closedGistsFor(extractPending, recordSessionId);
|
|
632
|
+
const summaryResult = await intelligence.summarise(sessionFacts, integratedFacts, priorSessionSummary, closed);
|
|
633
|
+
summaryText = summaryResult.summary;
|
|
634
|
+
threads = [...conflictMessages, ...summaryResult.openThreads];
|
|
635
|
+
await db.prepare(`UPDATE consolidations SET summary = ?, open_threads = ? WHERE id = ?`).run(summaryText, JSON.stringify(threads), consolidationId);
|
|
636
|
+
}
|
|
637
|
+
catch {
|
|
638
|
+
if (conflictMessages.length > 0) {
|
|
639
|
+
await db.prepare(`UPDATE consolidations SET open_threads = ? WHERE id = ?`).run(JSON.stringify(conflictMessages), consolidationId);
|
|
640
|
+
}
|
|
641
|
+
}
|
|
642
|
+
}
|
|
643
|
+
else {
|
|
644
|
+
if (conflictMessages.length > 0) {
|
|
645
|
+
await db.prepare(`UPDATE consolidations SET open_threads = ? WHERE id = ?`).run(JSON.stringify(conflictMessages), consolidationId);
|
|
646
|
+
}
|
|
647
|
+
const situationRows = await persistSituations(db, consolidationId, null, extractPending, effectiveWatermark);
|
|
648
|
+
for (const sessionId of uniqueSessionIds) {
|
|
649
|
+
const factsFor = sessionFacts.filter((f) => f.session_id === sessionId);
|
|
650
|
+
const integratedFor = integratedFacts.filter((f) => f.session_id === sessionId);
|
|
651
|
+
const prior = await latestSessionSummary(db, sessionId, consolidationId);
|
|
652
|
+
const closed = closedGistsFor(extractPending, sessionId);
|
|
653
|
+
try {
|
|
654
|
+
const summaryResult = await intelligence.summarise(factsFor, integratedFor, prior, closed);
|
|
655
|
+
const existingId = situationRows.get(sessionId);
|
|
656
|
+
if (existingId) {
|
|
657
|
+
await db.prepare(`UPDATE consolidations SET summary = ?, open_threads = ? WHERE id = ?`).run(summaryResult.summary, JSON.stringify(summaryResult.openThreads), existingId);
|
|
658
|
+
}
|
|
659
|
+
else {
|
|
660
|
+
await db.prepare(`INSERT INTO consolidations
|
|
661
|
+
(id, session_id, facts_in, facts_integrated, facts_rejected,
|
|
662
|
+
entities_created, entities_linked, supersessions,
|
|
663
|
+
summary, open_threads, last_event_sequence, created_at)
|
|
664
|
+
VALUES (?, ?, 0, 0, 0, 0, 0, 0, ?, ?, ?, ?)`).run(randomUUID(), sessionId, summaryResult.summary, JSON.stringify(summaryResult.openThreads), effectiveWatermark, new Date().toISOString());
|
|
665
|
+
}
|
|
666
|
+
}
|
|
667
|
+
catch {
|
|
668
|
+
// Satellite summary is non-critical — the run row already advanced
|
|
669
|
+
// the watermark and the facts are integrated.
|
|
670
|
+
}
|
|
671
|
+
}
|
|
672
|
+
}
|
|
673
|
+
return await finish({
|
|
674
|
+
consolidationId,
|
|
675
|
+
extractionDegraded,
|
|
676
|
+
factsIn: sessionFacts.length,
|
|
677
|
+
factsIntegrated: toIntegrate.length,
|
|
678
|
+
factsRejected: rejected,
|
|
679
|
+
entitiesCreated: writeResults.entitiesCreated,
|
|
680
|
+
entitiesLinked: writeResults.entitiesLinked,
|
|
681
|
+
supersessions: supersessionCount,
|
|
682
|
+
eventsCopied,
|
|
683
|
+
eventsRemaining: await remainingEvents(),
|
|
684
|
+
summary: summaryText,
|
|
685
|
+
openThreads: threads,
|
|
686
|
+
skipped: false,
|
|
687
|
+
...(budgetReason ? { skipReason: budgetReason } : {}),
|
|
688
|
+
examinedThrough: effectiveWatermark,
|
|
689
|
+
prefixCommitted,
|
|
690
|
+
});
|
|
691
|
+
}
|
|
692
|
+
catch (err) {
|
|
693
|
+
// Only unclaim if Phase D hasn't committed — otherwise the facts are
|
|
694
|
+
// already integrated and unclaiming would cause re-processing on the next run.
|
|
695
|
+
if (!phaseDCommitted) {
|
|
696
|
+
await db.prepare(`UPDATE session_facts SET consolidation_id = NULL WHERE consolidation_id = ?`).run(consolidationId);
|
|
697
|
+
}
|
|
698
|
+
// Release lock on error if not already released
|
|
699
|
+
await releaseLock(db, consolidationId);
|
|
700
|
+
await persistIntelligenceUsage(db, intelligence, consolidationId, caller);
|
|
701
|
+
throw err;
|
|
702
|
+
}
|
|
703
|
+
}
|
|
704
|
+
/** Persist billed usage for this run. Must not fail the pipeline. */
|
|
705
|
+
async function persistIntelligenceUsage(db, intelligence, consolidationId, caller = {}) {
|
|
706
|
+
const usage = takeProviderUsage(intelligence);
|
|
707
|
+
if (!usage || usage.calls < 1)
|
|
708
|
+
return usage;
|
|
709
|
+
try {
|
|
710
|
+
await insertIntelligenceRun(db, {
|
|
711
|
+
kind: "consolidate",
|
|
712
|
+
consolidationId,
|
|
713
|
+
usage,
|
|
714
|
+
trigger: caller.trigger ?? null,
|
|
715
|
+
sourceTool: caller.sourceTool ?? null,
|
|
716
|
+
project: caller.project ?? null,
|
|
717
|
+
});
|
|
718
|
+
}
|
|
719
|
+
catch {
|
|
720
|
+
// Spend is derived. A failed insert must not cost integrated facts.
|
|
721
|
+
}
|
|
722
|
+
return usage;
|
|
723
|
+
}
|
|
724
|
+
function parseEventRow(row) {
|
|
725
|
+
return {
|
|
726
|
+
...row,
|
|
727
|
+
metadata: row.metadata
|
|
728
|
+
? JSON.parse(row.metadata)
|
|
729
|
+
: null,
|
|
730
|
+
};
|
|
731
|
+
}
|
|
732
|
+
async function latestSessionSummary(db, sessionId, excludeId) {
|
|
733
|
+
const row = excludeId
|
|
734
|
+
? (await db
|
|
735
|
+
.prepare(`SELECT summary FROM consolidations
|
|
736
|
+
WHERE session_id = ? AND id != ? AND summary IS NOT NULL
|
|
737
|
+
ORDER BY ${NEWEST_CONSOLIDATION}
|
|
738
|
+
LIMIT 1`)
|
|
739
|
+
.get(sessionId, excludeId))
|
|
740
|
+
: (await db
|
|
741
|
+
.prepare(`SELECT summary FROM consolidations
|
|
742
|
+
WHERE session_id = ? AND summary IS NOT NULL
|
|
743
|
+
ORDER BY ${NEWEST_CONSOLIDATION}
|
|
744
|
+
LIMIT 1`)
|
|
745
|
+
.get(sessionId));
|
|
746
|
+
return row?.summary ?? null;
|
|
747
|
+
}
|
|
748
|
+
async function loadSessionWindow(db, watermark, ref, limit, fromSequence) {
|
|
749
|
+
if (limit <= 0)
|
|
750
|
+
return [];
|
|
751
|
+
// Kind-branched on purpose: binding the same string to both columns is how
|
|
752
|
+
// two conversations share a window. Client-keyed groups match the client
|
|
753
|
+
// column only; mcp-keyed groups match mcp-only rows (no client id).
|
|
754
|
+
const fromClause = fromSequence != null ? " AND sequence >= ?" : "";
|
|
755
|
+
const sql = ref.kind === "client"
|
|
756
|
+
? `SELECT * FROM session_events
|
|
757
|
+
WHERE sequence <= ? AND client_session_id = ?${fromClause}
|
|
758
|
+
ORDER BY sequence DESC
|
|
759
|
+
LIMIT ?`
|
|
760
|
+
: `SELECT * FROM session_events
|
|
761
|
+
WHERE sequence <= ? AND client_session_id IS NULL AND mcp_session_id = ?${fromClause}
|
|
762
|
+
ORDER BY sequence DESC
|
|
763
|
+
LIMIT ?`;
|
|
764
|
+
const params = fromSequence != null
|
|
765
|
+
? [watermark, ref.id, fromSequence, limit]
|
|
766
|
+
: [watermark, ref.id, limit];
|
|
767
|
+
const rows = (await db.prepare(sql).all(...params));
|
|
768
|
+
return rows.map(parseEventRow).reverse();
|
|
769
|
+
}
|
|
770
|
+
/** All events in a conversation, including lines too short to extract. */
|
|
771
|
+
async function loadConversationEvents(db, ref) {
|
|
772
|
+
const sql = ref.kind === "client"
|
|
773
|
+
? `SELECT * FROM session_events WHERE client_session_id = ? ORDER BY sequence ASC`
|
|
774
|
+
: `SELECT * FROM session_events
|
|
775
|
+
WHERE client_session_id IS NULL AND mcp_session_id = ?
|
|
776
|
+
ORDER BY sequence ASC`;
|
|
777
|
+
const rows = (await db.prepare(sql).all(ref.id));
|
|
778
|
+
return rows.map(parseEventRow);
|
|
779
|
+
}
|
|
780
|
+
async function loadConversationEventsAfter(db, ref, afterSequence, limit = Number.POSITIVE_INFINITY) {
|
|
781
|
+
// The cap is applied in SQL so a capped run over a long transcript does
|
|
782
|
+
// not materialise and parse the whole conversation to examine 50 lines.
|
|
783
|
+
const bounded = Number.isFinite(limit);
|
|
784
|
+
const sql = (ref.kind === "client"
|
|
785
|
+
? `SELECT * FROM session_events
|
|
786
|
+
WHERE sequence > ? AND client_session_id = ?
|
|
787
|
+
ORDER BY sequence ASC`
|
|
788
|
+
: `SELECT * FROM session_events
|
|
789
|
+
WHERE sequence > ? AND client_session_id IS NULL AND mcp_session_id = ?
|
|
790
|
+
ORDER BY sequence ASC`) + (bounded ? ` LIMIT ?` : ``);
|
|
791
|
+
const rows = (bounded
|
|
792
|
+
? await db.prepare(sql).all(afterSequence, ref.id, Math.max(0, Math.floor(limit)))
|
|
793
|
+
: await db.prepare(sql).all(afterSequence, ref.id));
|
|
794
|
+
return rows.map(parseEventRow);
|
|
795
|
+
}
|
|
796
|
+
async function linkExtractedFactToEvents(db, sessionFactId, factContent, groupEvents) {
|
|
797
|
+
// Only the FIRST match is primary. `groupEvents` is ordered by sequence, so
|
|
798
|
+
// that is the earliest occurrence — the point the information actually
|
|
799
|
+
// arrived. Later matches are the same text appearing again, which is what
|
|
800
|
+
// `corroborating` means ("mentioned again"), and repeated tool output
|
|
801
|
+
// makes that common: one fact in a real store claimed 145 separate events
|
|
802
|
+
// as the one it came from. Provenance answers "where did this come from",
|
|
803
|
+
// and a question with 145 answers has none.
|
|
804
|
+
//
|
|
805
|
+
// Scoped to this conversation. A mixed pull of two JSONL files used to
|
|
806
|
+
// walk every candidate in the watermark window, so a fact from A could
|
|
807
|
+
// claim B's rows as contextual origin.
|
|
808
|
+
let linkedPrimary = false;
|
|
809
|
+
let primary = null;
|
|
810
|
+
for (const event of groupEvents) {
|
|
811
|
+
if (event.content && event.content.includes(factContent)) {
|
|
812
|
+
if (!linkedPrimary) {
|
|
813
|
+
await linkFactSource(db, {
|
|
814
|
+
session_fact_id: sessionFactId,
|
|
815
|
+
event_id: event.id,
|
|
816
|
+
relevance: 0.8,
|
|
817
|
+
extraction_type: "primary",
|
|
818
|
+
});
|
|
819
|
+
linkedPrimary = true;
|
|
820
|
+
primary = event;
|
|
821
|
+
}
|
|
822
|
+
}
|
|
823
|
+
}
|
|
824
|
+
if (!linkedPrimary) {
|
|
825
|
+
// Rewritten extracts are not a substring of any event. Linking every
|
|
826
|
+
// event in the conversation as contextual makes provenance unanswerable
|
|
827
|
+
// (hundreds of 0.3 rows, one primary). Leave the fact unlinked rather
|
|
828
|
+
// than claiming the whole episode as origin.
|
|
829
|
+
return;
|
|
830
|
+
}
|
|
831
|
+
await attachBackingSources(db, sessionFactId, factContent, groupEvents);
|
|
832
|
+
// Same speaker repeating the sentence is fluency, not backing.
|
|
833
|
+
for (const event of groupEvents) {
|
|
834
|
+
if (!primary || event.id === primary.id)
|
|
835
|
+
continue;
|
|
836
|
+
if (!event.content || !event.content.includes(factContent))
|
|
837
|
+
continue;
|
|
838
|
+
if (event.speaker !== primary.speaker || event.role !== primary.role)
|
|
839
|
+
continue;
|
|
840
|
+
await linkFactSource(db, {
|
|
841
|
+
session_fact_id: sessionFactId,
|
|
842
|
+
event_id: event.id,
|
|
843
|
+
relevance: 0.5,
|
|
844
|
+
extraction_type: "corroborating",
|
|
845
|
+
});
|
|
846
|
+
}
|
|
847
|
+
}
|
|
848
|
+
function needsReread(outcome) {
|
|
849
|
+
if (outcome.degraded)
|
|
850
|
+
return false;
|
|
851
|
+
if (typeof outcome.confidence !== "number")
|
|
852
|
+
return false;
|
|
853
|
+
return outcome.confidence < EXTRACT_REREAD_CONFIDENCE;
|
|
854
|
+
}
|
|
855
|
+
function buildSituation(prev, outcome, watermark, firstCandidateSeq) {
|
|
856
|
+
const hasNow = outcome.now !== undefined;
|
|
857
|
+
const hasReferents = outcome.referents !== undefined;
|
|
858
|
+
const shifted = outcome.topic_shifted === true;
|
|
859
|
+
if (!hasNow && !hasReferents && !shifted) {
|
|
860
|
+
return { situation: null, closedGist: null };
|
|
861
|
+
}
|
|
862
|
+
const prevReferents = prev?.referents ?? [];
|
|
863
|
+
const prevSegments = prev?.segments ?? [];
|
|
864
|
+
const prevNow = prev?.now ?? null;
|
|
865
|
+
const prevStart = prev?.now_start_sequence ?? null;
|
|
866
|
+
const referents = hasReferents ? capReferents(outcome.referents) : prevReferents;
|
|
867
|
+
const now = hasNow ? (outcome.now ?? null) : prevNow;
|
|
868
|
+
if (shifted && (prevNow != null || prevReferents.length > 0)) {
|
|
869
|
+
const closed = {
|
|
870
|
+
start_sequence: prevStart ?? watermark,
|
|
871
|
+
end_sequence: watermark,
|
|
872
|
+
gist: prevNow ?? "",
|
|
873
|
+
referents: prevReferents,
|
|
874
|
+
};
|
|
875
|
+
return {
|
|
876
|
+
situation: {
|
|
877
|
+
now,
|
|
878
|
+
now_start_sequence: firstCandidateSeq,
|
|
879
|
+
referents,
|
|
880
|
+
segments: [...prevSegments, closed],
|
|
881
|
+
},
|
|
882
|
+
closedGist: closed.gist,
|
|
883
|
+
};
|
|
884
|
+
}
|
|
885
|
+
return {
|
|
886
|
+
situation: {
|
|
887
|
+
now,
|
|
888
|
+
now_start_sequence: prevStart ?? firstCandidateSeq,
|
|
889
|
+
referents,
|
|
890
|
+
segments: prevSegments,
|
|
891
|
+
},
|
|
892
|
+
closedGist: null,
|
|
893
|
+
};
|
|
894
|
+
}
|
|
895
|
+
function situationChanged(prev, next) {
|
|
896
|
+
if (!prev)
|
|
897
|
+
return true;
|
|
898
|
+
return JSON.stringify(prev) !== JSON.stringify(next);
|
|
899
|
+
}
|
|
900
|
+
function closedGistsFor(pending, sessionId) {
|
|
901
|
+
return pending
|
|
902
|
+
.filter((p) => p.group.ref.id === sessionId && p.closedGist)
|
|
903
|
+
.map((p) => p.closedGist);
|
|
904
|
+
}
|
|
905
|
+
async function persistSituations(db, runId, recordSessionId, pending, watermark) {
|
|
906
|
+
const rows = new Map();
|
|
907
|
+
const withState = pending.filter((p) => p.situation != null);
|
|
908
|
+
if (withState.length === 0)
|
|
909
|
+
return rows;
|
|
910
|
+
if (recordSessionId) {
|
|
911
|
+
const match = withState.find((p) => p.group.ref.id === recordSessionId);
|
|
912
|
+
if (match) {
|
|
913
|
+
await applySituation(db, runId, match.situation);
|
|
914
|
+
rows.set(recordSessionId, runId);
|
|
915
|
+
}
|
|
916
|
+
return rows;
|
|
917
|
+
}
|
|
918
|
+
for (const item of withState) {
|
|
919
|
+
const id = randomUUID();
|
|
920
|
+
await db.prepare(`INSERT INTO consolidations
|
|
921
|
+
(id, session_id, facts_in, facts_integrated, facts_rejected,
|
|
922
|
+
entities_created, entities_linked, supersessions,
|
|
923
|
+
summary, open_threads, last_event_sequence, created_at,
|
|
924
|
+
now, now_start_sequence, now_referents, segments)
|
|
925
|
+
VALUES (?, ?, 0, 0, 0, 0, 0, 0, NULL, NULL, ?, ?, ?, ?, ?, ?)`).run(id, item.group.ref.id, watermark, new Date().toISOString(), item.situation.now, item.situation.now_start_sequence, JSON.stringify(item.situation.referents), JSON.stringify(item.situation.segments));
|
|
926
|
+
rows.set(item.group.ref.id, id);
|
|
927
|
+
}
|
|
928
|
+
return rows;
|
|
929
|
+
}
|
|
930
|
+
function truncateForPrompt(events, maxContentLength) {
|
|
931
|
+
return events.map((e) => ({
|
|
932
|
+
...e,
|
|
933
|
+
content: e.content && e.content.length > maxContentLength
|
|
934
|
+
? e.content.slice(0, maxContentLength)
|
|
935
|
+
: e.content,
|
|
936
|
+
}));
|
|
937
|
+
}
|
|
938
|
+
function chunkEvents(events, batchSize) {
|
|
939
|
+
const size = Math.max(1, batchSize);
|
|
940
|
+
const chunks = [];
|
|
941
|
+
for (let i = 0; i < events.length; i += size) {
|
|
942
|
+
chunks.push(events.slice(i, i + size));
|
|
943
|
+
}
|
|
944
|
+
return chunks;
|
|
945
|
+
}
|
|
946
|
+
function lastSeq(events) {
|
|
947
|
+
if (events.length === 0)
|
|
948
|
+
return null;
|
|
949
|
+
return Math.max(...events.map((e) => e.sequence));
|
|
950
|
+
}
|
|
951
|
+
function prefixIsHonest(examined, remaining) {
|
|
952
|
+
if (examined.length === 0)
|
|
953
|
+
return false;
|
|
954
|
+
// Math.min(...[]) is Infinity, which would make any non-empty examined look honest.
|
|
955
|
+
// Empty remaining on a degrade path is a programming error, not a prefix — fail closed.
|
|
956
|
+
if (remaining.length === 0)
|
|
957
|
+
return false;
|
|
958
|
+
const maxExamined = Math.max(...examined.map((e) => e.sequence));
|
|
959
|
+
const minRemaining = Math.min(...remaining.map((e) => e.sequence));
|
|
960
|
+
return maxExamined < minRemaining;
|
|
961
|
+
}
|
|
962
|
+
function mergeChunk(pending, chunk) {
|
|
963
|
+
const last = pending[pending.length - 1];
|
|
964
|
+
const same = last &&
|
|
965
|
+
last.group.ref.kind === chunk.group.ref.kind &&
|
|
966
|
+
last.group.ref.id === chunk.group.ref.id;
|
|
967
|
+
if (!same) {
|
|
968
|
+
pending.push(chunk);
|
|
969
|
+
return;
|
|
970
|
+
}
|
|
971
|
+
last.group.events.push(...chunk.group.events);
|
|
972
|
+
last.facts.push(...chunk.facts);
|
|
973
|
+
if (chunk.situation)
|
|
974
|
+
last.situation = chunk.situation;
|
|
975
|
+
if (chunk.closedGist)
|
|
976
|
+
last.closedGist = chunk.closedGist;
|
|
977
|
+
}
|
|
978
|
+
async function persistPending(db, pending) {
|
|
979
|
+
for (const { group, facts } of pending) {
|
|
980
|
+
for (const item of facts) {
|
|
981
|
+
const primary = primaryEventForFact(group.events, item.content);
|
|
982
|
+
const fact = await insertSessionFact(db, {
|
|
983
|
+
session_id: group.ref.id,
|
|
984
|
+
content: item.content,
|
|
985
|
+
source_origin: "inferred",
|
|
986
|
+
domain_hint: item.domain_hint,
|
|
987
|
+
subdomain_hint: item.subdomain_hint ?? null,
|
|
988
|
+
confidence_signal: item.confidence_signal ?? null,
|
|
989
|
+
importance_signal: item.importance_signal ?? null,
|
|
990
|
+
capture_context: item.capture_context ?? null,
|
|
991
|
+
valid_from_hint: item.valid_from ?? null,
|
|
992
|
+
valid_until_hint: item.valid_until ?? null,
|
|
993
|
+
entities_json: item.entities ? JSON.stringify(item.entities) : null,
|
|
994
|
+
source_quality: item.source_quality ?? "heuristic",
|
|
995
|
+
speaker_role: speakerRoleOf(primary?.role),
|
|
996
|
+
speaker: speakerNameOf(primary?.speaker),
|
|
997
|
+
// Unclaimed: a later integrate-only run (shutdown) picks these up.
|
|
998
|
+
consolidation_id: null,
|
|
999
|
+
});
|
|
1000
|
+
if (fact) {
|
|
1001
|
+
// Assent lines are shorter than min_content_length, so they are not
|
|
1002
|
+
// extract candidates. Backing still needs the whole conversation.
|
|
1003
|
+
const window = await loadConversationEvents(db, group.ref);
|
|
1004
|
+
await linkExtractedFactToEvents(db, fact.id, item.content, window.length > 0 ? window : group.events);
|
|
1005
|
+
}
|
|
1006
|
+
}
|
|
1007
|
+
}
|
|
1008
|
+
}
|
|
1009
|
+
function isEligibleEvent(event, eventTypes, roles, minContentLength) {
|
|
1010
|
+
if (eventTypes && !eventTypes.includes(event.event_type))
|
|
1011
|
+
return false;
|
|
1012
|
+
if (roles && !roles.includes(event.role))
|
|
1013
|
+
return false;
|
|
1014
|
+
return (event.content?.length ?? 0) >= minContentLength;
|
|
1015
|
+
}
|
|
1016
|
+
async function extractFactsFromEvents(db, intelligence, config, limit = null) {
|
|
1017
|
+
const empty = {
|
|
1018
|
+
degraded: false,
|
|
1019
|
+
pending: [],
|
|
1020
|
+
prefixCommitted: false,
|
|
1021
|
+
};
|
|
1022
|
+
const workingMemorySize = config?.extraction?.working_memory_size ??
|
|
1023
|
+
DEFAULT_CONFIG.extraction.working_memory_size;
|
|
1024
|
+
const maxContentLength = config?.extraction?.max_content_length ??
|
|
1025
|
+
DEFAULT_CONFIG.extraction.max_content_length;
|
|
1026
|
+
const batchSize = Math.max(1, config?.extraction?.batch_size ?? DEFAULT_CONFIG.extraction.batch_size);
|
|
1027
|
+
const eventTypes = config?.extraction?.event_types ?? null;
|
|
1028
|
+
const roles = config?.extraction?.roles ?? null;
|
|
1029
|
+
const minContentLength = config?.extraction?.min_content_length ?? 0;
|
|
1030
|
+
const evidenceLimit = Math.min(EXTRACT_EVIDENCE_SLICE, workingMemorySize);
|
|
1031
|
+
const rereadLimit = Math.min(EXTRACT_REREAD_WINDOW, workingMemorySize);
|
|
1032
|
+
const conversations = await listUnexaminedConversations(db);
|
|
1033
|
+
if (conversations.length === 0)
|
|
1034
|
+
return empty;
|
|
1035
|
+
const vocabulary = await loadStoreVocabulary(db, config?.domains ?? []);
|
|
1036
|
+
const entityTypes = await listEntityTypes(db);
|
|
1037
|
+
const pending = [];
|
|
1038
|
+
let degraded = false;
|
|
1039
|
+
let advanced = false;
|
|
1040
|
+
// Oldest conversations first, bounded by `limit` events across the run. A
|
|
1041
|
+
// per-conversation mark advances only through what this run examined, so a
|
|
1042
|
+
// truncated tail is simply the next run's work — never a claim to have read it.
|
|
1043
|
+
let budget = limit ?? Number.POSITIVE_INFINITY;
|
|
1044
|
+
for (const conv of conversations) {
|
|
1045
|
+
if (budget <= 0)
|
|
1046
|
+
break;
|
|
1047
|
+
if (conv.kind === "unkeyed") {
|
|
1048
|
+
await setConversationExtractThrough(db, conv, conv.minSequence);
|
|
1049
|
+
advanced = true;
|
|
1050
|
+
continue;
|
|
1051
|
+
}
|
|
1052
|
+
const ref = { kind: conv.kind, id: conv.id };
|
|
1053
|
+
const through = await conversationExtractThrough(db, ref);
|
|
1054
|
+
const loaded = await loadConversationEventsAfter(db, ref, through, budget);
|
|
1055
|
+
if (loaded.length === 0)
|
|
1056
|
+
continue;
|
|
1057
|
+
budget -= loaded.length;
|
|
1058
|
+
const eligible = loaded.filter((e) => isEligibleEvent(e, eventTypes, roles, minContentLength));
|
|
1059
|
+
if (eligible.length === 0) {
|
|
1060
|
+
const maxLoaded = lastSeq(loaded);
|
|
1061
|
+
if (maxLoaded != null) {
|
|
1062
|
+
await setConversationExtractThrough(db, ref, maxLoaded);
|
|
1063
|
+
advanced = true;
|
|
1064
|
+
}
|
|
1065
|
+
continue;
|
|
1066
|
+
}
|
|
1067
|
+
const thisPending = [];
|
|
1068
|
+
const truncated = truncateForPrompt(eligible, maxContentLength);
|
|
1069
|
+
const chunks = chunkEvents(truncated, batchSize);
|
|
1070
|
+
let prior = await latestConversationSituation(db, ref.id);
|
|
1071
|
+
const priorSummary = await latestSessionSummary(db, ref.id);
|
|
1072
|
+
const dbEvidence = truncateForPrompt(await loadSessionWindow(db, through, ref, evidenceLimit), maxContentLength);
|
|
1073
|
+
const earlierThisRun = [];
|
|
1074
|
+
let conversationDegraded = false;
|
|
1075
|
+
for (let i = 0; i < chunks.length; i++) {
|
|
1076
|
+
const chunk = chunks[i];
|
|
1077
|
+
const evidence = earlierThisRun.length > 0
|
|
1078
|
+
? truncateForPrompt([...dbEvidence, ...earlierThisRun].slice(-evidenceLimit), maxContentLength)
|
|
1079
|
+
: dbEvidence;
|
|
1080
|
+
const relatedFacts = await relatedFactsForExtract(db, chunk);
|
|
1081
|
+
const extras = {
|
|
1082
|
+
now: prior?.now ?? null,
|
|
1083
|
+
referents: prior?.referents ?? [],
|
|
1084
|
+
segments: prior?.segments ?? [],
|
|
1085
|
+
relatedFacts,
|
|
1086
|
+
vocabulary,
|
|
1087
|
+
entityTypes,
|
|
1088
|
+
};
|
|
1089
|
+
let outcome = await intelligence.extractFactsFromEvents(chunk, evidence, priorSummary, relatedFacts, extras);
|
|
1090
|
+
if (outcome.degraded) {
|
|
1091
|
+
const remaining = [...chunk, ...chunks.slice(i + 1).flat()];
|
|
1092
|
+
const examined = thisPending.flatMap((p) => p.group.events);
|
|
1093
|
+
if (prefixIsHonest(examined, remaining)) {
|
|
1094
|
+
await persistPending(db, thisPending);
|
|
1095
|
+
const maxExamined = lastSeq(examined);
|
|
1096
|
+
if (maxExamined != null) {
|
|
1097
|
+
await setConversationExtractThrough(db, ref, maxExamined);
|
|
1098
|
+
advanced = true;
|
|
1099
|
+
}
|
|
1100
|
+
pending.push(...thisPending);
|
|
1101
|
+
}
|
|
1102
|
+
conversationDegraded = true;
|
|
1103
|
+
degraded = true;
|
|
1104
|
+
break;
|
|
1105
|
+
}
|
|
1106
|
+
if (needsReread(outcome)) {
|
|
1107
|
+
const reminder = truncateForPrompt(await loadSessionWindow(db, through, ref, rereadLimit, prior?.now_start_sequence ?? undefined), maxContentLength);
|
|
1108
|
+
outcome = await intelligence.extractFactsFromEvents(chunk, evidence, priorSummary, relatedFacts, {
|
|
1109
|
+
...extras,
|
|
1110
|
+
reminderEvents: truncateForPrompt(reminder.concat(earlierThisRun).slice(-rereadLimit), maxContentLength),
|
|
1111
|
+
});
|
|
1112
|
+
if (outcome.degraded) {
|
|
1113
|
+
const remaining = [...chunk, ...chunks.slice(i + 1).flat()];
|
|
1114
|
+
const examined = thisPending.flatMap((p) => p.group.events);
|
|
1115
|
+
if (prefixIsHonest(examined, remaining)) {
|
|
1116
|
+
await persistPending(db, thisPending);
|
|
1117
|
+
const maxExamined = lastSeq(examined);
|
|
1118
|
+
if (maxExamined != null) {
|
|
1119
|
+
await setConversationExtractThrough(db, ref, maxExamined);
|
|
1120
|
+
advanced = true;
|
|
1121
|
+
}
|
|
1122
|
+
pending.push(...thisPending);
|
|
1123
|
+
}
|
|
1124
|
+
conversationDegraded = true;
|
|
1125
|
+
degraded = true;
|
|
1126
|
+
break;
|
|
1127
|
+
}
|
|
1128
|
+
if (needsReread(outcome)) {
|
|
1129
|
+
mergeChunk(thisPending, {
|
|
1130
|
+
group: { ref, events: [...chunk] },
|
|
1131
|
+
facts: [],
|
|
1132
|
+
situation: null,
|
|
1133
|
+
closedGist: null,
|
|
1134
|
+
});
|
|
1135
|
+
earlierThisRun.push(...chunk);
|
|
1136
|
+
continue;
|
|
1137
|
+
}
|
|
1138
|
+
}
|
|
1139
|
+
const firstSeq = chunk[0]?.sequence ?? through + 1;
|
|
1140
|
+
const built = buildSituation(prior, outcome, lastSeq(earlierThisRun) ?? through, firstSeq);
|
|
1141
|
+
const situation = built.situation && situationChanged(prior, built.situation)
|
|
1142
|
+
? built.situation
|
|
1143
|
+
: null;
|
|
1144
|
+
if (built.situation)
|
|
1145
|
+
prior = built.situation;
|
|
1146
|
+
mergeChunk(thisPending, {
|
|
1147
|
+
group: { ref, events: [...chunk] },
|
|
1148
|
+
facts: outcome.facts,
|
|
1149
|
+
situation,
|
|
1150
|
+
closedGist: built.closedGist,
|
|
1151
|
+
});
|
|
1152
|
+
earlierThisRun.push(...chunk);
|
|
1153
|
+
}
|
|
1154
|
+
if (!conversationDegraded) {
|
|
1155
|
+
await persistPending(db, thisPending);
|
|
1156
|
+
const maxLoaded = lastSeq(loaded);
|
|
1157
|
+
if (maxLoaded != null) {
|
|
1158
|
+
await setConversationExtractThrough(db, ref, maxLoaded);
|
|
1159
|
+
advanced = true;
|
|
1160
|
+
}
|
|
1161
|
+
pending.push(...thisPending);
|
|
1162
|
+
}
|
|
1163
|
+
}
|
|
1164
|
+
return { degraded, pending, prefixCommitted: degraded && advanced };
|
|
1165
|
+
}
|
|
1166
|
+
// ---------------------------------------------------------------------------
|
|
1167
|
+
// Phase E: embedding
|
|
1168
|
+
// ---------------------------------------------------------------------------
|
|
1169
|
+
/**
|
|
1170
|
+
* Embed facts that have no vector for the configured model.
|
|
1171
|
+
*
|
|
1172
|
+
* Works from *the store*, not from what this run happened to integrate. That is
|
|
1173
|
+
* what makes it a backfill as well as a write: a run whose provider was down, a
|
|
1174
|
+
* store where semantic search was switched on later, and a model change all
|
|
1175
|
+
* present identically — facts with no row for the current model — and all drain
|
|
1176
|
+
* through this one path with no separate retry bookkeeping.
|
|
1177
|
+
*
|
|
1178
|
+
* Never throws. Semantic search is an enhancement to retrieval; losing it for a
|
|
1179
|
+
* run costs recall until the next consolidation, and the alternative — failing
|
|
1180
|
+
* a consolidation that has already committed its facts — costs far more.
|
|
1181
|
+
*/
|
|
1182
|
+
async function embedIntegratedFacts(db, provider, config) {
|
|
1183
|
+
if (!provider)
|
|
1184
|
+
return;
|
|
1185
|
+
const batchSize = config?.embedding?.batch_size ?? 128;
|
|
1186
|
+
try {
|
|
1187
|
+
// Dimension is only known after the provider's first call on some backends,
|
|
1188
|
+
// so probe with a trivial embed rather than assuming a configured value.
|
|
1189
|
+
const probe = await provider.embed(["dimension probe"], "document");
|
|
1190
|
+
const { model, dimensions } = probe;
|
|
1191
|
+
if (!dimensions)
|
|
1192
|
+
return;
|
|
1193
|
+
// Drain the queue rather than taking one batch. `batch_size` bounds the
|
|
1194
|
+
// size of a request, which is a property of the provider; it must not also
|
|
1195
|
+
// decide how much of the backlog a run clears, or turning semantic search
|
|
1196
|
+
// on over an existing store would need one consolidation per 128 facts
|
|
1197
|
+
// with no indication that more were owed. The backlog is a one-off — a
|
|
1198
|
+
// steady-state run embeds the handful of facts that just integrated.
|
|
1199
|
+
const attempted = new Set();
|
|
1200
|
+
for (;;) {
|
|
1201
|
+
const pending = await getFactsMissingEmbeddings(db, model, dimensions, batchSize);
|
|
1202
|
+
if (pending.length === 0)
|
|
1203
|
+
return;
|
|
1204
|
+
// If a batch comes back entirely made of facts already written this run,
|
|
1205
|
+
// the writes are not clearing the queue and another pass would repeat
|
|
1206
|
+
// itself for ever. Stop rather than spin; the rows still missing are the
|
|
1207
|
+
// queue, exactly as after any other failure.
|
|
1208
|
+
if (pending.every((f) => attempted.has(f.id)))
|
|
1209
|
+
return;
|
|
1210
|
+
for (const f of pending)
|
|
1211
|
+
attempted.add(f.id);
|
|
1212
|
+
const result = await provider.embed(pending.map((f) => f.content),
|
|
1213
|
+
// Stored facts are documents. Embedding them as queries would put them
|
|
1214
|
+
// in the wrong half of an asymmetrically-trained model and silently
|
|
1215
|
+
// degrade every subsequent search.
|
|
1216
|
+
"document");
|
|
1217
|
+
if (result.vectors.length !== pending.length) {
|
|
1218
|
+
// Misalignment would attach each fact to a different fact's meaning —
|
|
1219
|
+
// wrong in a way no downstream check could detect.
|
|
1220
|
+
throw new Error(`embedding returned ${result.vectors.length} vectors for ${pending.length} facts`);
|
|
1221
|
+
}
|
|
1222
|
+
// Committed per batch, so a failure part-way through a long backlog keeps
|
|
1223
|
+
// everything embedded so far instead of costing the whole run.
|
|
1224
|
+
await insertEmbeddings(db, pending.map((f, i) => ({ fact_id: f.id, vector: result.vectors[i] })), result.model, result.dimensions);
|
|
1225
|
+
if (pending.length < batchSize)
|
|
1226
|
+
return;
|
|
1227
|
+
}
|
|
1228
|
+
}
|
|
1229
|
+
catch {
|
|
1230
|
+
// Swallowed on purpose. The missing rows are the retry queue; the next run
|
|
1231
|
+
// finds exactly these facts again and tries once more.
|
|
1232
|
+
}
|
|
1233
|
+
}
|
|
1234
|
+
//# sourceMappingURL=consolidate.js.map
|