@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,823 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* CLI-subprocess intelligence provider.
|
|
3
|
+
*
|
|
4
|
+
* Spawns `claude -p --output-format json --json-schema ...` for each semantic
|
|
5
|
+
* stage of consolidation. Uses the user's existing Claude subscription via
|
|
6
|
+
* OAuth, so no API key is needed — the subprocess inherits the parent's
|
|
7
|
+
* environment and claude's keychain/file-based credentials resolve naturally.
|
|
8
|
+
*
|
|
9
|
+
* Four stages per consolidation (~4 subprocess calls total):
|
|
10
|
+
* 1. Extract-classify-resolve — facts + entities + domain + signals
|
|
11
|
+
* 2. Reconcile — add / noop / enrich against existing domain facts
|
|
12
|
+
* 3. Supersede — detect semantic contradictions against existing active facts
|
|
13
|
+
* 4. Summarise — narrative paragraph + open threads
|
|
14
|
+
*
|
|
15
|
+
* extractEntities and classifyFacts are 0-cost — they reuse stage 1 output
|
|
16
|
+
* stored on session_facts (consolidate() orchestrates this). Heuristic
|
|
17
|
+
* fallback only when the whole subprocess mechanism fails (CLI missing,
|
|
18
|
+
* spawn error, consistent schema validation failure).
|
|
19
|
+
*
|
|
20
|
+
* Recursion prevention (three layers):
|
|
21
|
+
* 1. --setting-sources user → skip project-level hook settings
|
|
22
|
+
* 2. cwd outside project → don't auto-discover project settings
|
|
23
|
+
* 3. FACTHOUSE_SUBPROCESS=1 env → our own hook CLI early-exits if set
|
|
24
|
+
*
|
|
25
|
+
* Probes verified the first two layers independently prevent recursion
|
|
26
|
+
* (baseline logged 2 events, each guard alone logged 0). The env var is
|
|
27
|
+
* belt-and-braces insurance for edge cases.
|
|
28
|
+
*/
|
|
29
|
+
import { spawn, spawnSync } from "node:child_process";
|
|
30
|
+
import { subprocessGuardEnv } from "../identity.js";
|
|
31
|
+
import { existsSync } from "node:fs";
|
|
32
|
+
import { tmpdir } from "node:os";
|
|
33
|
+
import path from "node:path";
|
|
34
|
+
import { UsageAccumulator, parseEnvelopeUsage, } from "./usage.js";
|
|
35
|
+
import { createHeuristicProvider } from "./heuristic.js";
|
|
36
|
+
import { domainRoutingInstruction, normaliseDomainName } from "../schemas/domains.js";
|
|
37
|
+
import { CLI_DEFAULT_MODEL, CLI_DEFAULT_TIMEOUT_MS, } from "../types/config.js";
|
|
38
|
+
import { EXTRACT_CONTEXT_CONTRACT, EXTRACT_DURABLE_JOB, SUBJECT_MARKING_CONTRACT, entityTypeInstruction, extractEventPayload, extractTodayUtcDate, parseExtractedIso, } from "./extract-prompt.js";
|
|
39
|
+
// ---------------------------------------------------------------------------
|
|
40
|
+
// Tracked children for cleanup on parent death
|
|
41
|
+
// ---------------------------------------------------------------------------
|
|
42
|
+
const activeChildren = new Set();
|
|
43
|
+
function trackChild(child) {
|
|
44
|
+
activeChildren.add(child);
|
|
45
|
+
child.once("exit", () => activeChildren.delete(child));
|
|
46
|
+
}
|
|
47
|
+
// Register once at module load to reap children on process exit.
|
|
48
|
+
// Avoids orphaned claude subprocesses if the MCP server crashes.
|
|
49
|
+
if (typeof process !== "undefined") {
|
|
50
|
+
const reap = () => {
|
|
51
|
+
for (const child of activeChildren) {
|
|
52
|
+
try {
|
|
53
|
+
child.kill("SIGTERM");
|
|
54
|
+
}
|
|
55
|
+
catch {
|
|
56
|
+
/* ignore */
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
};
|
|
60
|
+
process.once("exit", reap);
|
|
61
|
+
process.once("SIGINT", reap);
|
|
62
|
+
process.once("SIGTERM", reap);
|
|
63
|
+
}
|
|
64
|
+
/** Transient extract failures that are retried once. Not spawn/parse/is-error. */
|
|
65
|
+
export const CLI_EXTRACT_RETRY_KINDS = ["timeout", "non-zero-exit"];
|
|
66
|
+
export const CLI_EXTRACT_RETRIES = 1; // exactly one retry; two attempts total
|
|
67
|
+
export const CLI_FAILURE_SLICE = 300; // same cap as invokeClaude's stderr slice
|
|
68
|
+
/** Max wait after SIGKILL before the timeout result is returned. Join, not backoff. */
|
|
69
|
+
export const CLI_TIMEOUT_JOIN_MS = 2_000;
|
|
70
|
+
function formatStageFailure(stageName, result, phase, extra) {
|
|
71
|
+
const bits = [
|
|
72
|
+
"[facthouse cli-provider]",
|
|
73
|
+
phase === "retry"
|
|
74
|
+
? `${stageName} retry failed (${result.error})`
|
|
75
|
+
: `${stageName} failed (${result.error})`,
|
|
76
|
+
];
|
|
77
|
+
if (result.error === "non-zero-exit") {
|
|
78
|
+
bits.push(`exit=${result.exitCode == null ? "null" : String(result.exitCode)}`);
|
|
79
|
+
bits.push(`stderr=${JSON.stringify((result.stderr ?? "").slice(0, CLI_FAILURE_SLICE))}`);
|
|
80
|
+
}
|
|
81
|
+
else if (result.error === "timeout") {
|
|
82
|
+
if (extra?.timeoutMs != null)
|
|
83
|
+
bits.push(`after=${extra.timeoutMs}ms`);
|
|
84
|
+
if (result.stderr)
|
|
85
|
+
bits.push(`stderr=${JSON.stringify(result.stderr.slice(0, CLI_FAILURE_SLICE))}`);
|
|
86
|
+
}
|
|
87
|
+
else if (result.detail) {
|
|
88
|
+
bits.push(`detail=${JSON.stringify(result.detail.slice(0, CLI_FAILURE_SLICE))}`);
|
|
89
|
+
}
|
|
90
|
+
if (extra?.retrying)
|
|
91
|
+
bits.push("— retrying once");
|
|
92
|
+
return bits.join(" ");
|
|
93
|
+
}
|
|
94
|
+
async function invokeClaude(prompt, schema, command, opts) {
|
|
95
|
+
const cmd = command[0];
|
|
96
|
+
// Prompt goes on stdin, not argv. Windows CreateProcess caps the command
|
|
97
|
+
// line at 32,767 characters; a stage-1 extract (schema + events + evidence)
|
|
98
|
+
// exceeds that routinely, spawn fails with ENAMETOOLONG, and extract
|
|
99
|
+
// degrades for every run. `claude -p` with no positional prompt reads stdin
|
|
100
|
+
// (`echo "…" | claude -p`). The JSON schema stays on argv — it is small.
|
|
101
|
+
const args = [
|
|
102
|
+
...command.slice(1),
|
|
103
|
+
"-p",
|
|
104
|
+
"--output-format",
|
|
105
|
+
"json",
|
|
106
|
+
"--json-schema",
|
|
107
|
+
JSON.stringify(schema),
|
|
108
|
+
"--setting-sources",
|
|
109
|
+
"user",
|
|
110
|
+
"--no-session-persistence",
|
|
111
|
+
"--model",
|
|
112
|
+
opts.model,
|
|
113
|
+
];
|
|
114
|
+
return new Promise((resolve) => {
|
|
115
|
+
let resolved = false;
|
|
116
|
+
const started = Date.now();
|
|
117
|
+
const finish = (value) => {
|
|
118
|
+
if (resolved)
|
|
119
|
+
return;
|
|
120
|
+
resolved = true;
|
|
121
|
+
if (typeof value.elapsedMs !== "number") {
|
|
122
|
+
value.elapsedMs = Date.now() - started;
|
|
123
|
+
}
|
|
124
|
+
resolve(value);
|
|
125
|
+
};
|
|
126
|
+
let child;
|
|
127
|
+
try {
|
|
128
|
+
child = spawn(cmd, args, {
|
|
129
|
+
cwd: opts.cwd,
|
|
130
|
+
stdio: ["pipe", "pipe", "pipe"],
|
|
131
|
+
windowsHide: true,
|
|
132
|
+
detached: false,
|
|
133
|
+
env: subprocessGuardEnv(),
|
|
134
|
+
});
|
|
135
|
+
}
|
|
136
|
+
catch (err) {
|
|
137
|
+
return finish({ error: "spawn-error", detail: err.message });
|
|
138
|
+
}
|
|
139
|
+
trackChild(child);
|
|
140
|
+
let stdout = "";
|
|
141
|
+
let stderr = "";
|
|
142
|
+
let timedOut = false;
|
|
143
|
+
let joinTimer;
|
|
144
|
+
const timer = setTimeout(() => {
|
|
145
|
+
// Kill immediately and wait for close (or the join cap) before
|
|
146
|
+
// resolving. SIGTERM-and-return used to let the retry spawn overlap
|
|
147
|
+
// a live child.
|
|
148
|
+
timedOut = true;
|
|
149
|
+
try {
|
|
150
|
+
child.kill("SIGKILL");
|
|
151
|
+
}
|
|
152
|
+
catch {
|
|
153
|
+
/* already exited */
|
|
154
|
+
}
|
|
155
|
+
joinTimer = setTimeout(() => {
|
|
156
|
+
finish({
|
|
157
|
+
error: "timeout",
|
|
158
|
+
stderr: stderr.slice(0, CLI_FAILURE_SLICE),
|
|
159
|
+
});
|
|
160
|
+
}, CLI_TIMEOUT_JOIN_MS);
|
|
161
|
+
}, opts.timeoutMs);
|
|
162
|
+
child.stdout?.on("data", (d) => (stdout += d.toString()));
|
|
163
|
+
child.stderr?.on("data", (d) => (stderr += d.toString()));
|
|
164
|
+
child.stdin?.on("error", () => {
|
|
165
|
+
// EPIPE if the child exits before consuming the prompt; close/error
|
|
166
|
+
// handlers below settle the result.
|
|
167
|
+
});
|
|
168
|
+
child.on("error", (err) => {
|
|
169
|
+
clearTimeout(timer);
|
|
170
|
+
if (joinTimer)
|
|
171
|
+
clearTimeout(joinTimer);
|
|
172
|
+
if (timedOut) {
|
|
173
|
+
return finish({
|
|
174
|
+
error: "timeout",
|
|
175
|
+
stderr: stderr.slice(0, CLI_FAILURE_SLICE),
|
|
176
|
+
});
|
|
177
|
+
}
|
|
178
|
+
finish({ error: "spawn-error", detail: err.message });
|
|
179
|
+
});
|
|
180
|
+
child.on("close", (code) => {
|
|
181
|
+
clearTimeout(timer);
|
|
182
|
+
if (joinTimer)
|
|
183
|
+
clearTimeout(joinTimer);
|
|
184
|
+
if (timedOut) {
|
|
185
|
+
return finish({
|
|
186
|
+
error: "timeout",
|
|
187
|
+
stderr: stderr.slice(0, CLI_FAILURE_SLICE),
|
|
188
|
+
});
|
|
189
|
+
}
|
|
190
|
+
if (code !== 0) {
|
|
191
|
+
return finish({
|
|
192
|
+
error: "non-zero-exit",
|
|
193
|
+
exitCode: code,
|
|
194
|
+
stderr: stderr.slice(0, CLI_FAILURE_SLICE),
|
|
195
|
+
});
|
|
196
|
+
}
|
|
197
|
+
let envelope;
|
|
198
|
+
try {
|
|
199
|
+
envelope = JSON.parse(stdout);
|
|
200
|
+
}
|
|
201
|
+
catch (err) {
|
|
202
|
+
return finish({ error: "parse-error", detail: err.message });
|
|
203
|
+
}
|
|
204
|
+
if (envelope.is_error === true) {
|
|
205
|
+
return finish({
|
|
206
|
+
error: "is-error",
|
|
207
|
+
detail: String(envelope.result ?? ""),
|
|
208
|
+
});
|
|
209
|
+
}
|
|
210
|
+
const structured = envelope.structured_output;
|
|
211
|
+
if (structured === undefined || structured === null) {
|
|
212
|
+
return finish({
|
|
213
|
+
error: "no-structured-output",
|
|
214
|
+
detail: String(envelope.result ?? "").slice(0, CLI_FAILURE_SLICE),
|
|
215
|
+
});
|
|
216
|
+
}
|
|
217
|
+
finish({
|
|
218
|
+
envelope,
|
|
219
|
+
structured,
|
|
220
|
+
elapsedMs: Date.now() - started,
|
|
221
|
+
});
|
|
222
|
+
});
|
|
223
|
+
try {
|
|
224
|
+
child.stdin?.end(prompt, "utf8");
|
|
225
|
+
}
|
|
226
|
+
catch {
|
|
227
|
+
// Child already closed stdin; close/error handlers settle the result.
|
|
228
|
+
}
|
|
229
|
+
});
|
|
230
|
+
}
|
|
231
|
+
// ---------------------------------------------------------------------------
|
|
232
|
+
// CLI path resolution
|
|
233
|
+
// ---------------------------------------------------------------------------
|
|
234
|
+
/**
|
|
235
|
+
* Resolve the claude CLI invocation. Returns a spawn-friendly argv prefix.
|
|
236
|
+
*
|
|
237
|
+
* Strategy (first match wins):
|
|
238
|
+
* 1. Explicit opts.command
|
|
239
|
+
* 2. CLAUDE_CLI_PATH env var — either a direct binary or a .cjs path
|
|
240
|
+
* 3. Global npm install's cli-wrapper.cjs invoked via `node` — works
|
|
241
|
+
* universally including Windows where `.cmd` shims can't be spawned
|
|
242
|
+
* directly due to Node's CVE-2024-27980 mitigation
|
|
243
|
+
* 4. Plain `claude` in PATH — works on Unix systems with functioning shims
|
|
244
|
+
*
|
|
245
|
+
* Result is cached; caller invokes resolve() once at provider construction.
|
|
246
|
+
*/
|
|
247
|
+
function resolveCommand(opts) {
|
|
248
|
+
if (opts.command && opts.command.length > 0)
|
|
249
|
+
return opts.command;
|
|
250
|
+
if (process.env.CLAUDE_CLI_PATH) {
|
|
251
|
+
const p = process.env.CLAUDE_CLI_PATH;
|
|
252
|
+
return p.endsWith(".cjs") || p.endsWith(".js")
|
|
253
|
+
? [process.execPath, p]
|
|
254
|
+
: [p];
|
|
255
|
+
}
|
|
256
|
+
// Probe for cli-wrapper.cjs via `npm root -g`. Works on every platform
|
|
257
|
+
// because we spawn node directly — no .cmd/.exe/.sh shim resolution needed.
|
|
258
|
+
const wrapperFromNpmRoot = findWrapperViaNpmRoot();
|
|
259
|
+
if (wrapperFromNpmRoot)
|
|
260
|
+
return [process.execPath, wrapperFromNpmRoot];
|
|
261
|
+
// Fallback: resolve `claude` via where/which and derive wrapper path from
|
|
262
|
+
// the npm bin directory (its parent contains node_modules/@anthropic-ai/).
|
|
263
|
+
const wrapperFromShim = findWrapperViaShimPath();
|
|
264
|
+
if (wrapperFromShim)
|
|
265
|
+
return [process.execPath, wrapperFromShim];
|
|
266
|
+
// Last resort — plain `claude` command. Works on Unix systems with a
|
|
267
|
+
// functioning symlink shim; on Windows Node ≥22 with a .cmd shim this will
|
|
268
|
+
// EINVAL and we'll fall through to heuristic.
|
|
269
|
+
return ["claude"];
|
|
270
|
+
}
|
|
271
|
+
function findWrapperViaNpmRoot() {
|
|
272
|
+
try {
|
|
273
|
+
// One command string rather than (command, args) — with `shell: true` an
|
|
274
|
+
// args array triggers Node's DEP0190 deprecation warning, which lands in
|
|
275
|
+
// the user's terminal during `facthouse init`. The shell is needed on
|
|
276
|
+
// Windows, where `npm` is a `.cmd` shim that cannot be spawned directly.
|
|
277
|
+
const r = spawnSync("npm root -g", {
|
|
278
|
+
encoding: "utf-8",
|
|
279
|
+
shell: true,
|
|
280
|
+
});
|
|
281
|
+
if (r.status !== 0 || !r.stdout)
|
|
282
|
+
return null;
|
|
283
|
+
const candidate = path.join(r.stdout.trim(), "@anthropic-ai", "claude-code", "cli-wrapper.cjs");
|
|
284
|
+
return existsSync(candidate) ? candidate : null;
|
|
285
|
+
}
|
|
286
|
+
catch {
|
|
287
|
+
return null;
|
|
288
|
+
}
|
|
289
|
+
}
|
|
290
|
+
function findWrapperViaShimPath() {
|
|
291
|
+
try {
|
|
292
|
+
const r = spawnSync(process.platform === "win32" ? "where" : "which", ["claude"], { encoding: "utf-8" });
|
|
293
|
+
if (r.status !== 0 || !r.stdout)
|
|
294
|
+
return null;
|
|
295
|
+
const shimPath = r.stdout.split("\n")[0].trim();
|
|
296
|
+
if (!shimPath)
|
|
297
|
+
return null;
|
|
298
|
+
const binDir = path.dirname(shimPath);
|
|
299
|
+
const candidate = path.join(binDir, "node_modules", "@anthropic-ai", "claude-code", "cli-wrapper.cjs");
|
|
300
|
+
return existsSync(candidate) ? candidate : null;
|
|
301
|
+
}
|
|
302
|
+
catch {
|
|
303
|
+
return null;
|
|
304
|
+
}
|
|
305
|
+
}
|
|
306
|
+
/**
|
|
307
|
+
* Ask whether the CLI provider can actually run, rather than whether a path
|
|
308
|
+
* could be constructed for it.
|
|
309
|
+
*
|
|
310
|
+
* `resolveCommand` always returns *something* — its last resort is a bare
|
|
311
|
+
* `claude`, on the chance a working shim is on PATH. So a resolved command is
|
|
312
|
+
* not evidence of an installed CLI, and the difference is invisible until
|
|
313
|
+
* consolidation silently degrades: every stage falls back to the heuristic
|
|
314
|
+
* provider, which extracts no entities and does no routing. The store fills
|
|
315
|
+
* with flat facts and nothing says why.
|
|
316
|
+
*
|
|
317
|
+
* Spawning `--version` is the only answer that settles it. It costs one fast
|
|
318
|
+
* subprocess, needs no model call, and catches the case a file-existence check
|
|
319
|
+
* cannot — a Windows `.cmd` shim that is present but cannot be spawned
|
|
320
|
+
* directly (Node's CVE-2024-27980 mitigation), which is exactly how this fails
|
|
321
|
+
* on the platform most likely to hit it.
|
|
322
|
+
*
|
|
323
|
+
* @param opts provider options, as passed to `createCliProvider`
|
|
324
|
+
* @param run injection seam for tests; defaults to a real subprocess
|
|
325
|
+
*/
|
|
326
|
+
export function probeCliProvider(opts = {}, run = defaultProbeRun) {
|
|
327
|
+
const command = resolveCommand(opts);
|
|
328
|
+
const result = run(command[0], [...command.slice(1), "--version"]);
|
|
329
|
+
return { command, available: result.status === 0 };
|
|
330
|
+
}
|
|
331
|
+
function defaultProbeRun(cmd, args) {
|
|
332
|
+
try {
|
|
333
|
+
const r = spawnSync(cmd, args, {
|
|
334
|
+
encoding: "utf-8",
|
|
335
|
+
timeout: 10_000,
|
|
336
|
+
windowsHide: true,
|
|
337
|
+
env: subprocessGuardEnv(),
|
|
338
|
+
});
|
|
339
|
+
return { status: r.status };
|
|
340
|
+
}
|
|
341
|
+
catch {
|
|
342
|
+
// A spawn that throws (ENOENT, EINVAL) is the same answer as a non-zero
|
|
343
|
+
// exit: this command cannot be run.
|
|
344
|
+
return { status: null };
|
|
345
|
+
}
|
|
346
|
+
}
|
|
347
|
+
// ---------------------------------------------------------------------------
|
|
348
|
+
// Stage schemas (JSON Schema draft-07)
|
|
349
|
+
// ---------------------------------------------------------------------------
|
|
350
|
+
const STAGE_1_SCHEMA = {
|
|
351
|
+
type: "object",
|
|
352
|
+
properties: {
|
|
353
|
+
facts: {
|
|
354
|
+
type: "array",
|
|
355
|
+
items: {
|
|
356
|
+
type: "object",
|
|
357
|
+
properties: {
|
|
358
|
+
content: { type: "string" },
|
|
359
|
+
domain: { type: "string" },
|
|
360
|
+
subdomain: { type: ["string", "null"] },
|
|
361
|
+
confidence: { type: "number", minimum: 0, maximum: 1 },
|
|
362
|
+
importance: { type: "number", minimum: 0, maximum: 1 },
|
|
363
|
+
capture_context: { type: ["string", "null"] },
|
|
364
|
+
valid_from: { type: ["string", "null"] },
|
|
365
|
+
valid_until: { type: ["string", "null"] },
|
|
366
|
+
entities: {
|
|
367
|
+
type: "array",
|
|
368
|
+
items: {
|
|
369
|
+
type: "object",
|
|
370
|
+
properties: {
|
|
371
|
+
name: { type: "string" },
|
|
372
|
+
type: { type: "string" },
|
|
373
|
+
relationship: {
|
|
374
|
+
type: "string",
|
|
375
|
+
description: "How this fact relates to this thing. Use exactly " +
|
|
376
|
+
"'subject_of' for the ONE thing the fact is about; describe " +
|
|
377
|
+
"the connection in your own words for everything else it " +
|
|
378
|
+
"merely mentions.",
|
|
379
|
+
},
|
|
380
|
+
existing_id: { type: ["string", "null"] },
|
|
381
|
+
},
|
|
382
|
+
required: ["name", "type", "relationship"],
|
|
383
|
+
},
|
|
384
|
+
},
|
|
385
|
+
},
|
|
386
|
+
required: ["content", "domain", "entities"],
|
|
387
|
+
},
|
|
388
|
+
},
|
|
389
|
+
session_now: { type: ["string", "null"] },
|
|
390
|
+
referents: {
|
|
391
|
+
type: "array",
|
|
392
|
+
items: {
|
|
393
|
+
type: "object",
|
|
394
|
+
properties: {
|
|
395
|
+
phrase: { type: "string" },
|
|
396
|
+
binding: { type: "string" },
|
|
397
|
+
},
|
|
398
|
+
required: ["phrase", "binding"],
|
|
399
|
+
},
|
|
400
|
+
},
|
|
401
|
+
topic_shifted: { type: "boolean" },
|
|
402
|
+
confidence: { type: "number", minimum: 0, maximum: 1 },
|
|
403
|
+
},
|
|
404
|
+
required: ["facts"],
|
|
405
|
+
};
|
|
406
|
+
const STAGE_CLASSIFY_SCHEMA = {
|
|
407
|
+
type: "object",
|
|
408
|
+
properties: {
|
|
409
|
+
classifications: {
|
|
410
|
+
type: "array",
|
|
411
|
+
items: {
|
|
412
|
+
type: "object",
|
|
413
|
+
properties: {
|
|
414
|
+
id: { type: "string" },
|
|
415
|
+
domain: { type: "string" },
|
|
416
|
+
subdomain: { type: ["string", "null"] },
|
|
417
|
+
},
|
|
418
|
+
required: ["id", "domain"],
|
|
419
|
+
},
|
|
420
|
+
},
|
|
421
|
+
},
|
|
422
|
+
required: ["classifications"],
|
|
423
|
+
};
|
|
424
|
+
const STAGE_ENTITIES_SCHEMA = {
|
|
425
|
+
type: "object",
|
|
426
|
+
properties: {
|
|
427
|
+
facts: {
|
|
428
|
+
type: "array",
|
|
429
|
+
items: {
|
|
430
|
+
type: "object",
|
|
431
|
+
properties: {
|
|
432
|
+
id: { type: "string" },
|
|
433
|
+
entities: {
|
|
434
|
+
type: "array",
|
|
435
|
+
items: {
|
|
436
|
+
type: "object",
|
|
437
|
+
properties: {
|
|
438
|
+
name: { type: "string" },
|
|
439
|
+
type: { type: "string" },
|
|
440
|
+
relationship: {
|
|
441
|
+
type: "string",
|
|
442
|
+
description: "How this fact relates to this thing. Use exactly " +
|
|
443
|
+
"'subject_of' for the ONE thing the fact is about; describe " +
|
|
444
|
+
"the connection in your own words for everything else it " +
|
|
445
|
+
"merely mentions.",
|
|
446
|
+
},
|
|
447
|
+
},
|
|
448
|
+
required: ["name", "type", "relationship"],
|
|
449
|
+
},
|
|
450
|
+
},
|
|
451
|
+
},
|
|
452
|
+
required: ["id", "entities"],
|
|
453
|
+
},
|
|
454
|
+
},
|
|
455
|
+
},
|
|
456
|
+
required: ["facts"],
|
|
457
|
+
};
|
|
458
|
+
const STAGE_2_SCHEMA = {
|
|
459
|
+
type: "object",
|
|
460
|
+
properties: {
|
|
461
|
+
decisions: {
|
|
462
|
+
type: "array",
|
|
463
|
+
items: {
|
|
464
|
+
type: "object",
|
|
465
|
+
properties: {
|
|
466
|
+
id: { type: "string" },
|
|
467
|
+
decision: { type: "string", enum: ["add", "noop", "enrich"] },
|
|
468
|
+
existingFactId: { type: ["string", "null"] },
|
|
469
|
+
},
|
|
470
|
+
required: ["id", "decision"],
|
|
471
|
+
},
|
|
472
|
+
},
|
|
473
|
+
},
|
|
474
|
+
required: ["decisions"],
|
|
475
|
+
};
|
|
476
|
+
const STAGE_3_SCHEMA = {
|
|
477
|
+
type: "object",
|
|
478
|
+
properties: {
|
|
479
|
+
supersessions: {
|
|
480
|
+
type: "array",
|
|
481
|
+
items: {
|
|
482
|
+
type: "object",
|
|
483
|
+
properties: {
|
|
484
|
+
new_id: { type: "string" },
|
|
485
|
+
existing_id: { type: "string" },
|
|
486
|
+
reason: { type: "string" },
|
|
487
|
+
},
|
|
488
|
+
required: ["new_id", "existing_id", "reason"],
|
|
489
|
+
},
|
|
490
|
+
},
|
|
491
|
+
},
|
|
492
|
+
required: ["supersessions"],
|
|
493
|
+
};
|
|
494
|
+
const STAGE_4_SCHEMA = {
|
|
495
|
+
type: "object",
|
|
496
|
+
properties: {
|
|
497
|
+
summary: { type: "string" },
|
|
498
|
+
openThreads: { type: "array", items: { type: "string" } },
|
|
499
|
+
},
|
|
500
|
+
required: ["summary", "openThreads"],
|
|
501
|
+
};
|
|
502
|
+
// ---------------------------------------------------------------------------
|
|
503
|
+
// Provider
|
|
504
|
+
// ---------------------------------------------------------------------------
|
|
505
|
+
export function createCliProvider(userOpts = {}, fallback = createHeuristicProvider(),
|
|
506
|
+
/**
|
|
507
|
+
* The store's configured vocabulary, named in the routing prompt so the model
|
|
508
|
+
* reuses "medical" rather than coining "health". Empty means the model is
|
|
509
|
+
* choosing this store's vocabulary from scratch, which is a legitimate state:
|
|
510
|
+
* the engine ships none.
|
|
511
|
+
*/
|
|
512
|
+
vocabulary = []) {
|
|
513
|
+
const opts = {
|
|
514
|
+
// Resolved lazily below — kept here only to satisfy the Required shape.
|
|
515
|
+
command: [],
|
|
516
|
+
model: userOpts.model ?? CLI_DEFAULT_MODEL,
|
|
517
|
+
// 45s covers the heavier stage 1 (nested schema + entity resolution).
|
|
518
|
+
// Measured: simple prompts 8–15s; stage 1 with full schema 20–35s
|
|
519
|
+
// observed. Budget is per stage, not total — 4 stages × 45s = up to 3
|
|
520
|
+
// minutes worst case, which is still a background job.
|
|
521
|
+
timeoutMs: userOpts.timeoutMs ?? CLI_DEFAULT_TIMEOUT_MS,
|
|
522
|
+
cwd: userOpts.cwd ?? tmpdir(),
|
|
523
|
+
maxCandidates: userOpts.maxCandidates ?? 50,
|
|
524
|
+
debug: userOpts.debug ?? false,
|
|
525
|
+
};
|
|
526
|
+
// Resolve the claude invocation lazily and cache it. Deferring resolution
|
|
527
|
+
// until the first stage call keeps provider construction cheap and
|
|
528
|
+
// side-effect-free: an idle server that never consolidates never shells out
|
|
529
|
+
// to `npm root -g` for wrapper discovery (which on Windows also emits a
|
|
530
|
+
// shell-spawn deprecation warning). Matters because `cli` is the default
|
|
531
|
+
// provider — every boot constructs it, but most boots never invoke it.
|
|
532
|
+
let resolvedCommand = userOpts.command && userOpts.command.length > 0 ? userOpts.command : null;
|
|
533
|
+
const getCommand = () => {
|
|
534
|
+
if (!resolvedCommand)
|
|
535
|
+
resolvedCommand = resolveCommand(userOpts);
|
|
536
|
+
return resolvedCommand;
|
|
537
|
+
};
|
|
538
|
+
const log = (...args) => {
|
|
539
|
+
if (opts.debug)
|
|
540
|
+
console.error("[facthouse cli-provider]", ...args);
|
|
541
|
+
};
|
|
542
|
+
const usageAcc = new UsageAccumulator({
|
|
543
|
+
provider: "cli",
|
|
544
|
+
model: opts.model,
|
|
545
|
+
});
|
|
546
|
+
function recordAttempt(stageName, result) {
|
|
547
|
+
const tokens = "envelope" in result ? parseEnvelopeUsage(result.envelope) : {};
|
|
548
|
+
usageAcc.record(stageName, {
|
|
549
|
+
...tokens,
|
|
550
|
+
elapsed_ms: result.elapsedMs ?? 0,
|
|
551
|
+
provider: "cli",
|
|
552
|
+
model: opts.model,
|
|
553
|
+
});
|
|
554
|
+
}
|
|
555
|
+
/** Standardised stage runner. Returns null on failure so callers can fall back. */
|
|
556
|
+
async function runStage(stageName, systemPrompt, userPayload, schema, retryTransient = false) {
|
|
557
|
+
// Claude's --json-schema flag expects a user prompt; we pass the system
|
|
558
|
+
// prompt prepended to the user content, separated by a marker. We don't
|
|
559
|
+
// use --system-prompt because the help docs note it interacts with
|
|
560
|
+
// --exclude-dynamic-system-prompt-sections and other flags; this keeps
|
|
561
|
+
// behaviour predictable.
|
|
562
|
+
const prompt = `${systemPrompt}\n\nINPUT:\n${JSON.stringify(userPayload)}`;
|
|
563
|
+
const attempt = () => invokeClaude(prompt, schema, getCommand(), opts);
|
|
564
|
+
let result = await attempt();
|
|
565
|
+
recordAttempt(stageName, result);
|
|
566
|
+
if ("error" in result) {
|
|
567
|
+
const retryable = retryTransient &&
|
|
568
|
+
CLI_EXTRACT_RETRY_KINDS.includes(result.error);
|
|
569
|
+
console.error(formatStageFailure(stageName, result, "first", {
|
|
570
|
+
retrying: retryable,
|
|
571
|
+
timeoutMs: result.error === "timeout" ? opts.timeoutMs : undefined,
|
|
572
|
+
}));
|
|
573
|
+
if (retryable) {
|
|
574
|
+
result = await attempt();
|
|
575
|
+
recordAttempt(stageName, result);
|
|
576
|
+
if ("error" in result) {
|
|
577
|
+
console.error(formatStageFailure(stageName, result, "retry", {
|
|
578
|
+
timeoutMs: result.error === "timeout" ? opts.timeoutMs : undefined,
|
|
579
|
+
}));
|
|
580
|
+
return null;
|
|
581
|
+
}
|
|
582
|
+
log(`${stageName} retry ok in ${result.elapsedMs}ms`);
|
|
583
|
+
return result.structured;
|
|
584
|
+
}
|
|
585
|
+
return null;
|
|
586
|
+
}
|
|
587
|
+
log(`${stageName} ok in ${result.elapsedMs}ms`);
|
|
588
|
+
return result.structured;
|
|
589
|
+
}
|
|
590
|
+
return {
|
|
591
|
+
async extractFactsFromEvents(events, workingMemory, sessionSummary, longTermMemory, extras) {
|
|
592
|
+
// Nothing to examine is not a failure — there is no watermark to hold back.
|
|
593
|
+
if (events.length === 0)
|
|
594
|
+
return { facts: [], degraded: false };
|
|
595
|
+
const result = await runStage("stage-1-extract", EXTRACT_DURABLE_JOB +
|
|
596
|
+
" " +
|
|
597
|
+
`${domainRoutingInstruction(extras?.vocabulary ?? vocabulary)} ` +
|
|
598
|
+
"optional subdomain, confidence 0-1, importance 0-1, and any named " +
|
|
599
|
+
"things mentioned (people, organisations, places, projects, products, " +
|
|
600
|
+
"systems, concepts — whatever the fact concerns), each with a short lowercase type. " +
|
|
601
|
+
`${entityTypeInstruction(extras?.entityTypes ?? [])} ` +
|
|
602
|
+
SUBJECT_MARKING_CONTRACT + " " +
|
|
603
|
+
EXTRACT_CONTEXT_CONTRACT + " " +
|
|
604
|
+
"If an entity matches one of the entities referenced in long_term_memory (by name or " +
|
|
605
|
+
"clear reference), set existing_id to the matching id; otherwise omit existing_id " +
|
|
606
|
+
"(= new entity). " +
|
|
607
|
+
"Return strictly {facts: [...], session_now?, referents?, topic_shifted?, confidence?}.", {
|
|
608
|
+
session_now: extras?.now ?? null,
|
|
609
|
+
referents: extras?.referents ?? [],
|
|
610
|
+
topic_segments: extras?.segments ?? [],
|
|
611
|
+
session_summary: sessionSummary ?? null,
|
|
612
|
+
long_term_memory: (longTermMemory ?? []).map((f) => ({
|
|
613
|
+
id: f.id,
|
|
614
|
+
content: f.content,
|
|
615
|
+
domain: f.domain,
|
|
616
|
+
})),
|
|
617
|
+
extract_today: extractTodayUtcDate(),
|
|
618
|
+
recent_events: workingMemory.map(extractEventPayload),
|
|
619
|
+
reminder_events: (extras?.reminderEvents ?? []).map(extractEventPayload),
|
|
620
|
+
candidate_events: events.map(extractEventPayload),
|
|
621
|
+
}, STAGE_1_SCHEMA, true);
|
|
622
|
+
if (!result || !Array.isArray(result.facts)) {
|
|
623
|
+
// The subprocess failed, timed out, or returned something unusable.
|
|
624
|
+
// Falling back keeps consolidation moving, but the caller must know the
|
|
625
|
+
// configured extractor never ran: these events have NOT been examined,
|
|
626
|
+
// and advancing past them would discard them permanently.
|
|
627
|
+
const fell = await fallback.extractFactsFromEvents(events, workingMemory, sessionSummary, longTermMemory, extras);
|
|
628
|
+
return { facts: fell.facts, degraded: true };
|
|
629
|
+
}
|
|
630
|
+
const extracted = result.facts.map((f) => ({
|
|
631
|
+
content: f.content,
|
|
632
|
+
domain_hint: f.domain,
|
|
633
|
+
subdomain_hint: f.subdomain ?? null,
|
|
634
|
+
confidence_signal: typeof f.confidence === "number" ? f.confidence : null,
|
|
635
|
+
importance_signal: typeof f.importance === "number" ? f.importance : null,
|
|
636
|
+
capture_context: f.capture_context ?? null,
|
|
637
|
+
valid_from: parseExtractedIso(f.valid_from),
|
|
638
|
+
valid_until: parseExtractedIso(f.valid_until),
|
|
639
|
+
entities: Array.isArray(f.entities)
|
|
640
|
+
? f.entities.map((e) => ({
|
|
641
|
+
name: e.name,
|
|
642
|
+
type: e.type,
|
|
643
|
+
relationship: e.relationship,
|
|
644
|
+
existing_id: e.existing_id ?? undefined,
|
|
645
|
+
}))
|
|
646
|
+
: [],
|
|
647
|
+
source_quality: "cli",
|
|
648
|
+
}));
|
|
649
|
+
return {
|
|
650
|
+
facts: extracted,
|
|
651
|
+
degraded: false,
|
|
652
|
+
now: result.session_now,
|
|
653
|
+
referents: Array.isArray(result.referents) ? result.referents : undefined,
|
|
654
|
+
topic_shifted: result.topic_shifted,
|
|
655
|
+
confidence: typeof result.confidence === "number" ? result.confidence : undefined,
|
|
656
|
+
};
|
|
657
|
+
},
|
|
658
|
+
async classifyFacts(facts, sessionContext) {
|
|
659
|
+
// Facts inferred from events are routed during stage 1 and arrive with a
|
|
660
|
+
// domain_hint, so consolidation never asks about them. What reaches here
|
|
661
|
+
// is the explicit capture path — capture_fact — which is the path every
|
|
662
|
+
// tool description tells an assistant to use.
|
|
663
|
+
//
|
|
664
|
+
// This used to delegate straight to the heuristic. That was defensible
|
|
665
|
+
// while the heuristic carried a keyword vocabulary; once the engine
|
|
666
|
+
// stopped shipping one, the delegation quietly meant "route everything to
|
|
667
|
+
// the fallback domain". Measured on the same sentence: arriving as an
|
|
668
|
+
// event it was routed to a real domain; arriving through capture_fact it
|
|
669
|
+
// landed in the default one.
|
|
670
|
+
if (facts.length === 0)
|
|
671
|
+
return [];
|
|
672
|
+
const result = await runStage("stage-classify", "You route already-extracted facts into domains. " +
|
|
673
|
+
`${domainRoutingInstruction(vocabulary)} ` +
|
|
674
|
+
"Also give an optional short lowercase subdomain where one is " +
|
|
675
|
+
"genuinely useful, or null. " +
|
|
676
|
+
"Return a classification for EVERY fact you are given, keyed by its " +
|
|
677
|
+
"id. Return strictly {classifications: [{id, domain, subdomain}]}.", {
|
|
678
|
+
session_context: sessionContext ?? null,
|
|
679
|
+
facts: facts.map((f) => ({
|
|
680
|
+
id: f.id,
|
|
681
|
+
content: f.content,
|
|
682
|
+
domain_hint: f.domain_hint ?? null,
|
|
683
|
+
})),
|
|
684
|
+
}, STAGE_CLASSIFY_SCHEMA);
|
|
685
|
+
if (!result || !Array.isArray(result.classifications)) {
|
|
686
|
+
return fallback.classifyFacts(facts, sessionContext);
|
|
687
|
+
}
|
|
688
|
+
// Index the model's answers and reconcile against the input. A fact the
|
|
689
|
+
// model skipped still has to come back classified, or consolidation would
|
|
690
|
+
// silently drop it — so anything missing falls through to the heuristic
|
|
691
|
+
// rather than being invented here.
|
|
692
|
+
const byId = new Map(result.classifications.map((c) => [c.id, c]));
|
|
693
|
+
const missing = facts.filter((f) => !byId.has(f.id));
|
|
694
|
+
const heuristicForMissing = missing.length
|
|
695
|
+
? await fallback.classifyFacts(missing, sessionContext)
|
|
696
|
+
: [];
|
|
697
|
+
const heuristicById = new Map(heuristicForMissing.map((c) => [c.id, c]));
|
|
698
|
+
return facts.map((f) => {
|
|
699
|
+
const c = byId.get(f.id);
|
|
700
|
+
if (!c)
|
|
701
|
+
return heuristicById.get(f.id);
|
|
702
|
+
return {
|
|
703
|
+
id: f.id,
|
|
704
|
+
content: f.content,
|
|
705
|
+
domain: normaliseDomainName(c.domain),
|
|
706
|
+
subdomain: c.subdomain ?? null,
|
|
707
|
+
};
|
|
708
|
+
});
|
|
709
|
+
},
|
|
710
|
+
async extractEntities(facts) {
|
|
711
|
+
// Same story as classifyFacts. Facts inferred from events carry entities
|
|
712
|
+
// extracted during stage 1; what arrives here came through capture_fact,
|
|
713
|
+
// and the heuristic this used to delegate to extracts nothing at all by
|
|
714
|
+
// design. So the primary capture path built no graph whatsoever.
|
|
715
|
+
if (facts.length === 0)
|
|
716
|
+
return new Map();
|
|
717
|
+
const result = await runStage("stage-entities", "You identify the named things each fact concerns — people, " +
|
|
718
|
+
"organisations, places, projects, products, systems, concepts — " +
|
|
719
|
+
"whatever the fact is about, each with a short lowercase type. " +
|
|
720
|
+
SUBJECT_MARKING_CONTRACT + " " +
|
|
721
|
+
"Return an entry for every fact, with an empty list where a fact " +
|
|
722
|
+
"names nothing. Return strictly {facts: [{id, entities}]}.", { facts: facts.map((f) => ({ id: f.id, content: f.content })) }, STAGE_ENTITIES_SCHEMA);
|
|
723
|
+
if (!result || !Array.isArray(result.facts)) {
|
|
724
|
+
return fallback.extractEntities(facts);
|
|
725
|
+
}
|
|
726
|
+
const map = new Map();
|
|
727
|
+
for (const f of result.facts) {
|
|
728
|
+
if (!Array.isArray(f.entities) || f.entities.length === 0)
|
|
729
|
+
continue;
|
|
730
|
+
map.set(f.id, f.entities.map((e) => ({
|
|
731
|
+
name: e.name,
|
|
732
|
+
type: e.type,
|
|
733
|
+
relationship: e.relationship,
|
|
734
|
+
})));
|
|
735
|
+
}
|
|
736
|
+
return map;
|
|
737
|
+
},
|
|
738
|
+
async reconcile(candidate, existingFacts) {
|
|
739
|
+
if (existingFacts.length === 0)
|
|
740
|
+
return { kind: "add" };
|
|
741
|
+
const result = await runStage("stage-2-reconcile", "You decide whether a candidate fact is already covered by an existing fact. " +
|
|
742
|
+
"'noop' = the EXACT same information exists. " +
|
|
743
|
+
"'enrich' = a paraphrase or corroboration of a specific existing fact — " +
|
|
744
|
+
"set existingFactId to that fact's id. " +
|
|
745
|
+
"'add' = the candidate adds something new or stands alone. " +
|
|
746
|
+
"Supersession (contradictions) is handled separately — treat contradictions as 'add'. " +
|
|
747
|
+
"Return strictly {decisions: [{id, decision, existingFactId?}]}.", {
|
|
748
|
+
candidates: [{ id: candidate.id, content: candidate.content }],
|
|
749
|
+
existing: existingFacts.map((f) => ({ id: f.id, content: f.content })),
|
|
750
|
+
}, STAGE_2_SCHEMA);
|
|
751
|
+
if (!result || !Array.isArray(result.decisions) || result.decisions.length === 0) {
|
|
752
|
+
return fallback.reconcile(candidate, existingFacts);
|
|
753
|
+
}
|
|
754
|
+
const decision = result.decisions[0];
|
|
755
|
+
if (decision.decision === "noop")
|
|
756
|
+
return { kind: "noop" };
|
|
757
|
+
if (decision.decision === "enrich" && typeof decision.existingFactId === "string") {
|
|
758
|
+
const exists = existingFacts.some((f) => f.id === decision.existingFactId);
|
|
759
|
+
return exists
|
|
760
|
+
? { kind: "enrich", existingFactId: decision.existingFactId }
|
|
761
|
+
: { kind: "add" };
|
|
762
|
+
}
|
|
763
|
+
return { kind: "add" };
|
|
764
|
+
},
|
|
765
|
+
async detectSupersession(newFact, existingFacts) {
|
|
766
|
+
const candidates = existingFacts.filter((f) => f.domain === newFact.domain && f.status === "active" && f.is_latest);
|
|
767
|
+
if (candidates.length === 0)
|
|
768
|
+
return null;
|
|
769
|
+
const result = await runStage("stage-3-supersede", "You detect whether a new fact supersedes (invalidates and replaces) an existing one. " +
|
|
770
|
+
"Supersession applies for negations, updates, or replacements — e.g. " +
|
|
771
|
+
"'I moved to Porto' supersedes 'I live in Lisbon'; " +
|
|
772
|
+
"'I no longer drink coffee' supersedes 'I prefer coffee'. " +
|
|
773
|
+
"Paraphrase or additional detail is NOT supersession. " +
|
|
774
|
+
"Return strictly {supersessions: [{new_id, existing_id, reason}]} — " +
|
|
775
|
+
"omit entries where no supersession applies.", {
|
|
776
|
+
new: [{ id: newFact.id, content: newFact.content, domain: newFact.domain }],
|
|
777
|
+
existing: candidates.map((f) => ({ id: f.id, content: f.content })),
|
|
778
|
+
}, STAGE_3_SCHEMA);
|
|
779
|
+
if (!result || !Array.isArray(result.supersessions)) {
|
|
780
|
+
return fallback.detectSupersession(newFact, existingFacts);
|
|
781
|
+
}
|
|
782
|
+
// Find the first supersession targeting our newFact.
|
|
783
|
+
const hit = result.supersessions.find((s) => s.new_id === newFact.id);
|
|
784
|
+
if (!hit)
|
|
785
|
+
return null;
|
|
786
|
+
const exists = candidates.some((f) => f.id === hit.existing_id);
|
|
787
|
+
if (!exists)
|
|
788
|
+
return null; // hallucinated id
|
|
789
|
+
return { existingFactId: hit.existing_id, reason: hit.reason };
|
|
790
|
+
},
|
|
791
|
+
async summarise(sessionFacts, integratedFacts, priorSummary, closedTopics) {
|
|
792
|
+
if (integratedFacts.length === 0) {
|
|
793
|
+
return { summary: "No facts integrated.", openThreads: [] };
|
|
794
|
+
}
|
|
795
|
+
const result = await runStage("stage-4-summarise", "You summarise a consolidation run. " +
|
|
796
|
+
"prior_summary is the rolling summary of this session so far (may be null for the " +
|
|
797
|
+
"first consolidation). closed_topics are activity gists closed this run (may be empty). " +
|
|
798
|
+
"Produce a CUMULATIVE summary that folds what was just learned " +
|
|
799
|
+
"(integrated) into prior_summary — one natural paragraph, not a diff — " +
|
|
800
|
+
"and mentions closed topics without treating the paragraph as the topic log. " +
|
|
801
|
+
"List up to 5 open threads — questions or follow-ups the user might want revisited. " +
|
|
802
|
+
"Return strictly {summary, openThreads}.", {
|
|
803
|
+
prior_summary: priorSummary ?? null,
|
|
804
|
+
closed_topics: closedTopics ?? [],
|
|
805
|
+
integrated: integratedFacts.map((f) => ({
|
|
806
|
+
content: f.content,
|
|
807
|
+
domain: f.domain,
|
|
808
|
+
subdomain: f.subdomain,
|
|
809
|
+
})),
|
|
810
|
+
}, STAGE_4_SCHEMA);
|
|
811
|
+
if (!result ||
|
|
812
|
+
typeof result.summary !== "string" ||
|
|
813
|
+
!Array.isArray(result.openThreads)) {
|
|
814
|
+
return fallback.summarise(sessionFacts, integratedFacts, priorSummary);
|
|
815
|
+
}
|
|
816
|
+
return { summary: result.summary, openThreads: result.openThreads };
|
|
817
|
+
},
|
|
818
|
+
takeUsage() {
|
|
819
|
+
return usageAcc.take();
|
|
820
|
+
},
|
|
821
|
+
};
|
|
822
|
+
}
|
|
823
|
+
//# sourceMappingURL=cli.js.map
|