@facthouse/mcp 0.28.0 → 0.29.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (61) hide show
  1. package/README.md +35 -33
  2. package/dist/cli/index.d.ts +5 -21
  3. package/dist/cli/index.d.ts.map +1 -1
  4. package/dist/cli/index.js +6 -783
  5. package/dist/cli/index.js.map +1 -1
  6. package/dist/cli/init-backfill.d.ts.map +1 -1
  7. package/dist/cli/init-backfill.js +2 -0
  8. package/dist/cli/init-backfill.js.map +1 -1
  9. package/dist/cli/init-knobs.d.ts +12 -3
  10. package/dist/cli/init-knobs.d.ts.map +1 -1
  11. package/dist/cli/init-knobs.js +20 -5
  12. package/dist/cli/init-knobs.js.map +1 -1
  13. package/dist/cli/init-wizard.d.ts.map +1 -1
  14. package/dist/cli/init-wizard.js +39 -8
  15. package/dist/cli/init-wizard.js.map +1 -1
  16. package/dist/cli/init.d.ts +2 -0
  17. package/dist/cli/init.d.ts.map +1 -1
  18. package/dist/cli/init.js +23 -2
  19. package/dist/cli/init.js.map +1 -1
  20. package/dist/cli/run.d.ts +35 -0
  21. package/dist/cli/run.d.ts.map +1 -0
  22. package/dist/cli/run.js +801 -0
  23. package/dist/cli/run.js.map +1 -0
  24. package/dist/cli/settings.d.ts.map +1 -1
  25. package/dist/cli/settings.js +1 -1
  26. package/dist/cli/settings.js.map +1 -1
  27. package/dist/cli/web.d.ts +24 -1
  28. package/dist/cli/web.d.ts.map +1 -1
  29. package/dist/cli/web.js +235 -68
  30. package/dist/cli/web.js.map +1 -1
  31. package/dist/index.d.ts +4 -0
  32. package/dist/index.d.ts.map +1 -1
  33. package/dist/index.js +4 -272
  34. package/dist/index.js.map +1 -1
  35. package/dist/intelligence/cli.d.ts +11 -3
  36. package/dist/intelligence/cli.d.ts.map +1 -1
  37. package/dist/intelligence/cli.js +115 -23
  38. package/dist/intelligence/cli.js.map +1 -1
  39. package/dist/intelligence/consolidate.d.ts +4 -0
  40. package/dist/intelligence/consolidate.d.ts.map +1 -1
  41. package/dist/intelligence/consolidate.js +14 -2
  42. package/dist/intelligence/consolidate.js.map +1 -1
  43. package/dist/intelligence/types.d.ts +5 -0
  44. package/dist/intelligence/types.d.ts.map +1 -1
  45. package/dist/intelligence/usage.d.ts +1 -1
  46. package/dist/intelligence/usage.js +1 -1
  47. package/dist/paths.d.ts +7 -0
  48. package/dist/paths.d.ts.map +1 -1
  49. package/dist/paths.js +25 -0
  50. package/dist/paths.js.map +1 -1
  51. package/dist/server.d.ts +8 -0
  52. package/dist/server.d.ts.map +1 -0
  53. package/dist/server.js +274 -0
  54. package/dist/server.js.map +1 -0
  55. package/dist/suppress-sqlite-warning.js +15 -3
  56. package/dist/suppress-sqlite-warning.js.map +1 -1
  57. package/dist/types/config.d.ts +5 -3
  58. package/dist/types/config.d.ts.map +1 -1
  59. package/dist/types/config.js +3 -1
  60. package/dist/types/config.js.map +1 -1
  61. package/package.json +2 -2
package/dist/index.js CHANGED
@@ -1,276 +1,8 @@
1
1
  #!/usr/bin/env node
2
- import "./suppress-sqlite-warning.js";
3
2
  /**
4
- * Facthouse MCP Server
5
- *
6
- * AI memory engine exposed as an MCP server.
7
- * Structured knowledge with server-side intelligence. Any AI tool can query it via MCP.
3
+ * Thin loader so `suppress-sqlite-warning` evaluates before `node:sqlite` is
4
+ * even translated. See src/cli/index.ts.
8
5
  */
9
- import { parseArgs } from "node:util";
10
- import { mkdirSync, readFileSync } from "node:fs";
11
- import { CLI_NAME, DEFAULT_MCP_SERVER_NAME, envValue, } from "./identity.js";
12
- import { dataDirFromEnvOrDefault, resolveUserPath } from "./paths.js";
13
- import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
14
- import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
15
- import { closeDatabase } from "./db/connection.js";
16
- import { openStore } from "./db/store.js";
17
- import { applySchema } from "./db/schema.js";
18
- import { ensureSelfEntity } from "./db/entities.js";
19
- import { loadStoreVocabulary } from "./db/domains.js";
20
- import { createEmbeddingProvider } from "./embedding/provider.js";
21
- import { createSessionManager, registerSessionReadTools } from "./tools/session-manager.js";
22
- import { createFactManager } from "./tools/fact-manager.js";
23
- import { createHeuristicProvider } from "./intelligence/heuristic.js";
24
- import { createIntelligenceProvider } from "./intelligence/provider.js";
25
- import { registerReadTools } from "./tools/read-tools.js";
26
- import { registerInferenceTools } from "./tools/inferences.js";
27
- import { registerResources, SESSION_BOOTSTRAP_INSTRUCTIONS } from "./tools/resources.js";
28
- import { startScheduler } from "./scheduler.js";
29
- import { loadShippedStoreConfig, ensureBitemporalSince } from "./config.js";
30
- import { startNotifyListener } from "./ipc/scheduler-ipc.js";
31
- import { createCopyHeartbeat } from "./sources/copy.js";
32
- // ---------------------------------------------------------------------------
33
- // Parse arguments
34
- // ---------------------------------------------------------------------------
35
- const { values } = parseArgs({
36
- options: {
37
- data: {
38
- type: "string",
39
- default: dataDirFromEnvOrDefault(),
40
- },
41
- },
42
- strict: false, // Allow unknown flags (MCP clients may pass extras).
43
- });
44
- const dataDir = resolveUserPath(values.data);
45
- mkdirSync(dataDir, { recursive: true });
46
- // Storage check before opening an engine. Unknown providers and postgres
47
- // without a URL must not create memory.db. Print the message and exit rather
48
- // than dumping a stack into the MCP stdio stream.
49
- let loadedConfig;
50
- try {
51
- loadedConfig = loadShippedStoreConfig(dataDir);
52
- }
53
- catch (err) {
54
- console.error(err instanceof Error ? err.message : String(err));
55
- process.exit(1);
56
- }
57
- const pkg = JSON.parse(readFileSync(new URL("../package.json", import.meta.url), "utf-8"));
58
- // ---------------------------------------------------------------------------
59
- // Lifecycle
60
- // ---------------------------------------------------------------------------
61
- let db;
62
- let scheduler;
63
- let triggers = new Set();
64
- let ipcListener = null;
65
- // Idempotent shutdown path — may be invoked by MCP transport close, SIGINT,
66
- // or SIGTERM. Guards against double-run so concurrent signals don't race.
67
- let shuttingDown = false;
68
- async function shutdown() {
69
- if (shuttingDown)
70
- return;
71
- shuttingDown = true;
72
- ipcListener?.close();
73
- if (scheduler && triggers.has("shutdown")) {
74
- await scheduler.run("shutdown").catch(() => undefined);
75
- }
76
- if (db)
77
- await closeDatabase(db);
78
- }
79
- async function main() {
80
- // ---------------------------------------------------------------------------
81
- // Database
82
- // ---------------------------------------------------------------------------
83
- let database;
84
- try {
85
- database = await openStore(dataDir, loadedConfig);
86
- }
87
- catch (err) {
88
- console.error(err instanceof Error ? err.message : String(err));
89
- process.exit(1);
90
- return;
91
- }
92
- db = database;
93
- await applySchema(database);
94
- // Also here, not only in `facthouse init` — init is optional, and a store the
95
- // server created on first boot needs the anchor just as much as one that was
96
- // set up ahead of time. Idempotent.
97
- await ensureSelfEntity(database);
98
- // ---------------------------------------------------------------------------
99
- // MCP Server
100
- // ---------------------------------------------------------------------------
101
- // `subscribe` must be declared here: registering a resource auto-registers
102
- // `resources: { listChanged: true }`, but not subscribe, and capabilities are
103
- // frozen once a transport is attached. Without it, clients can't ask to be told
104
- // when the briefing changes.
105
- const server = new McpServer({
106
- name: DEFAULT_MCP_SERVER_NAME,
107
- version: pkg.version,
108
- }, {
109
- capabilities: { resources: { subscribe: true, listChanged: true } },
110
- // Tools-only clients never fetch memory://briefing. This is the session-start
111
- // result that tells them to call get_session_context instead — same briefing.
112
- instructions: SESSION_BOOTSTRAP_INSTRUCTIONS,
113
- });
114
- const clientSessionId = envValue("CLIENT_SESSION") ?? null;
115
- const sessionManager = createSessionManager(database, clientSessionId);
116
- sessionManager.registerTools(server);
117
- // A store that has just switched to bi-temporal mode gets `bitemporal_since`
118
- // stamped here — historical supersessions cannot be backfilled.
119
- const config = ensureBitemporalSince(dataDir, loadedConfig);
120
- const triggerSet = new Set(config.consolidation.triggers);
121
- triggers = triggerSet;
122
- // Provider selector — heuristic is always the terminal fallback. Defaults to
123
- // the CLI provider: subprocess `claude -p` for real LLM consolidation
124
- // via the user's own subscription. The FACTHOUSE_PROVIDER env var overrides
125
- // the config.json choice (kill-switch, e.g. FACTHOUSE_PROVIDER=heuristic).
126
- const storeVocabulary = await loadStoreVocabulary(database, config.domains ?? []);
127
- const heuristic = createHeuristicProvider(storeVocabulary);
128
- const intelligence = createIntelligenceProvider(config.intelligence, {
129
- vocabulary: storeVocabulary,
130
- server: server.server,
131
- heuristic,
132
- });
133
- // Semantic search, if this store has opted in. Null is the shipped default and
134
- // means keyword-only retrieval — nothing is downloaded and nothing is called.
135
- // Built once at boot: resolution reads config and the environment, neither of
136
- // which changes mid-process.
137
- const embeddingProvider = createEmbeddingProvider(config.embedding, {
138
- onUnavailable: (reason) => console.error(`[facthouse] ${reason}`),
139
- });
140
- // Named sources: copy new lines when a tool or resource is read if the
141
- // files grew. Empty sources never walks a client home. Does not extract.
142
- const heartbeat = createCopyHeartbeat({
143
- db: database,
144
- sources: config.sources,
145
- onCopied: (copied) => {
146
- console.error(`[facthouse] Copied ${copied.events_inserted} line(s) from ${copied.files} source file(s).`);
147
- },
148
- onError: (err) => {
149
- console.error(`[facthouse] Source copy failed: ${err.message}`);
150
- },
151
- });
152
- const beforeRead = async () => {
153
- try {
154
- await heartbeat.copyIfGrown();
155
- }
156
- catch {
157
- // copyIfGrown already swallows; a throwing hook must not fail search.
158
- }
159
- };
160
- // Resources are automatically-loaded context (memory://briefing, memory://profile).
161
- // Registered before connect(), because registering one registers the resources
162
- // capability and capabilities are frozen once the transport attaches.
163
- const resources = registerResources(server, database, beforeRead);
164
- const factManager = createFactManager(database, sessionManager, {
165
- intelligence,
166
- embedding: embeddingProvider,
167
- serverConfig: {
168
- extraction: config.extraction,
169
- temporal: config.temporal,
170
- intelligence: config.intelligence,
171
- },
172
- // Both of these shipped in the default config and never reached the code that
173
- // reads them, so the hardcoded defaults always won whatever a store set.
174
- captureConfig: config.capture,
175
- autoLinkEvents: config.consolidation.auto_link_events,
176
- sources: config.sources,
177
- beforeRead,
178
- // The copy step of consolidate is this same heartbeat.
179
- copy: () => heartbeat.copyIfGrown({ force: true }),
180
- // Consolidation is the only thing that changes integrated knowledge, so it's
181
- // the only thing that can change what these resources render.
182
- onConsolidated: () => resources.notifyUpdated(),
183
- });
184
- registerSessionReadTools(server, sessionManager, database, beforeRead);
185
- factManager.registerTools(server);
186
- if (config.inferences.enabled) {
187
- registerInferenceTools(server, database, {
188
- onConfirmed: () => resources.notifyUpdated(),
189
- });
190
- }
191
- registerReadTools(server, database, embeddingProvider, {
192
- minSimilarityRatio: config.embedding?.min_similarity_ratio,
193
- minSimilarity: config.embedding?.min_similarity ?? undefined,
194
- ann: config.embedding?.ann,
195
- annMaxBytes: config.embedding?.ann_max_bytes,
196
- }, config.temporal, config.interlocutor, beforeRead);
197
- const sched = startScheduler({
198
- db: database,
199
- runConsolidate: (steps) => factManager.runConsolidate(steps, {
200
- trigger: "scheduler",
201
- project: envValue("PROJECT") ?? null,
202
- }),
203
- threshold: config.consolidation.threshold,
204
- });
205
- scheduler = sched;
206
- const transport = new StdioServerTransport();
207
- // Start session when the MCP handshake completes.
208
- server.server.oninitialized = async () => {
209
- const clientInfo = server.server.getClientVersion();
210
- sessionManager.startSession(clientInfo?.name ?? null, envValue("PROJECT") ?? null);
211
- // Listener for moments another process reports (threshold, compaction).
212
- // The moment → steps policy is MOMENT_POLICY; the listener only relays.
213
- if (triggerSet.has("threshold") || triggerSet.has("compaction")) {
214
- try {
215
- // A delivered moment is an explicit request from another process
216
- // (a hook, `facthouse notify`); `triggers` decides whether this server
217
- // listens at all, not whether it honours what it was told.
218
- ipcListener = await startNotifyListener(dataDir, (moment) => {
219
- void sched.run(moment);
220
- });
221
- if (!ipcListener.bound) {
222
- console.error("[facthouse] Another MCP server is handling notifications for this data dir.");
223
- }
224
- }
225
- catch (err) {
226
- console.error(`[facthouse] Could not start IPC listener: ${err.message}. ` +
227
- `Threshold / compaction triggers will not fire.`);
228
- }
229
- }
230
- // session_start: copy, extract (capped), integrate. The copy step is the
231
- // same heartbeat every tool read uses, so a first get_session_context
232
- // cannot race a second walk of the same file. A large first backfill is
233
- // not extracted on the lot: the cap bounds the run and the remainder is
234
- // reported once.
235
- if (triggerSet.has("session_start")) {
236
- void sched.run("session_start").then((result) => {
237
- // Only the cap earns this line: a skipped or degraded run has its own
238
- // reason, and pointing at --all there would spawn the model on the lot.
239
- if (result &&
240
- !result.skipped &&
241
- !result.extractionDegraded &&
242
- result.eventsRemaining > 0) {
243
- console.error(`[facthouse] ${result.eventsRemaining} line(s) still waiting to be extracted ` +
244
- `after this run's cap. Run ${CLI_NAME} consolidate --all, or let the ` +
245
- `next session start take the next batch.`);
246
- }
247
- });
248
- }
249
- else {
250
- // No session_start trigger: still keep D current for the first read.
251
- await heartbeat.copyIfGrown();
252
- }
253
- };
254
- // The MCP SDK calls onclose synchronously and doesn't await our handler.
255
- // Run the shutdown sequence explicitly and exit only after it completes —
256
- // otherwise Node may exit before the shutdown-trigger integrate finishes
257
- // its LLM calls and DB writes.
258
- server.server.onclose = () => {
259
- void shutdown().then(() => process.exit(0));
260
- };
261
- await server.connect(transport);
262
- }
263
- // Graceful shutdown — same path for SIGINT and SIGTERM.
264
- process.on("SIGINT", () => {
265
- void shutdown().then(() => process.exit(0));
266
- });
267
- process.on("SIGTERM", () => {
268
- void shutdown().then(() => process.exit(0));
269
- });
270
- main().catch(async (error) => {
271
- console.error("Fatal error:", error);
272
- if (db)
273
- await closeDatabase(db).catch(() => undefined);
274
- process.exit(1);
275
- });
6
+ import "./suppress-sqlite-warning.js";
7
+ await import("./server.js");
276
8
  //# sourceMappingURL=index.js.map
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":";AAEA,OAAO,8BAA8B,CAAC;AAEtC;;;;;GAKG;AAEH,OAAO,EAAE,SAAS,EAAE,MAAM,WAAW,CAAC;AACtC,OAAO,EAAE,SAAS,EAAE,YAAY,EAAE,MAAM,SAAS,CAAC;AAClD,OAAO,EACL,QAAQ,EACR,uBAAuB,EACvB,QAAQ,GACT,MAAM,eAAe,CAAC;AACvB,OAAO,EAAE,uBAAuB,E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+B;IAC/B,MAAM,CAAC,MAAM,CAAC,OAAO,GAAG,GAAG,EAAE;QAC3B,KAAK,QAAQ,EAAE,CAAC,IAAI,CAAC,GAAG,EAAE,CAAC,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,CAAC;IAC9C,CAAC,CAAC;IAEF,MAAM,MAAM,CAAC,OAAO,CAAC,SAAS,CAAC,CAAC;AAClC,CAAC;AAED,wDAAwD;AACxD,OAAO,CAAC,EAAE,CAAC,QAAQ,EAAE,GAAG,EAAE;IACxB,KAAK,QAAQ,EAAE,CAAC,IAAI,CAAC,GAAG,EAAE,CAAC,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,CAAC;AAC9C,CAAC,CAAC,CAAC;AACH,OAAO,CAAC,EAAE,CAAC,SAAS,EAAE,GAAG,EAAE;IACzB,KAAK,QAAQ,EAAE,CAAC,IAAI,CAAC,GAAG,EAAE,CAAC,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,CAAC;AAC9C,CAAC,CAAC,CAAC;AAEH,IAAI,EAAE,CAAC,KAAK,CAAC,KAAK,EAAE,KAAK,EAAE,EAAE;IAC3B,OAAO,CAAC,KAAK,CAAC,cAAc,EAAE,KAAK,CAAC,CAAC;IACrC,IAAI,EAAE;QAAE,MAAM,aAAa,CAAC,EAAE,CAAC,CAAC,KAAK,CAAC,GAAG,EAAE,CAAC,SAAS,CAAC,CAAC;IACvD,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;AAClB,CAAC,CAAC,CAAC"}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":";AAEA;;;GAGG;AACH,OAAO,8BAA8B,CAAC;AACtC,MAAM,MAAM,CAAC,aAAa,CAAC,CAAC"}
@@ -1,8 +1,8 @@
1
1
  /**
2
2
  * CLI-subprocess intelligence provider.
3
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
4
+ * Spawns `claude -p --output-format stream-json --json-schema ...` for each
5
+ * semantic stage of consolidation. Uses the user's existing Claude subscription via
6
6
  * OAuth, so no API key is needed — the subprocess inherits the parent's
7
7
  * environment and claude's keychain/file-based credentials resolve naturally.
8
8
  *
@@ -33,7 +33,7 @@ export interface CliProviderOpts {
33
33
  command?: string[];
34
34
  /** Model alias (passed via --model). Default: CLI_DEFAULT_MODEL. */
35
35
  model?: string;
36
- /** Per-stage timeout in ms. Default: CLI_DEFAULT_TIMEOUT_MS. */
36
+ /** Idle silence on the subprocess pipes before kill. Default: CLI_DEFAULT_TIMEOUT_MS. */
37
37
  timeoutMs?: number;
38
38
  /** Cwd for subprocess. Default: OS tempdir (out of project scope). */
39
39
  cwd?: string;
@@ -48,6 +48,14 @@ export declare const CLI_EXTRACT_RETRIES = 1;
48
48
  export declare const CLI_FAILURE_SLICE = 300;
49
49
  /** Max wait after SIGKILL before the timeout result is returned. Join, not backoff. */
50
50
  export declare const CLI_TIMEOUT_JOIN_MS = 2000;
51
+ /** Absolute ceiling per stage, even if the stream keeps ticking. Idle is `timeoutMs`. */
52
+ export declare const CLI_HARD_TIMEOUT_MS: number;
53
+ /**
54
+ * Parse `claude -p --output-format stream-json` (NDJSON) or a single JSON
55
+ * envelope (`--output-format json`, tests). Prefer the last `type: result`
56
+ * line; otherwise the last object with `structured_output`.
57
+ */
58
+ export declare function parseClaudeCliStdout(stdout: string): Record<string, unknown>;
51
59
  /** How the runner reports back. Only the exit status matters. */
52
60
  export interface ProbeRun {
53
61
  status: number | null;
@@ -1 +1 @@
1
- {"version":3,"file":"cli.d.ts","sourceRoot":"","sources":["../../src/intelligence/cli.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;GA2BG;AAOH,OAAO,KAAK,EAAE,oBAAoB,EAA4C,MAAM,YAAY,CAAC;AAQjG,OAAO,EAGL,KAAK,SAAS,EACf,MAAM,oBAAoB,CAAC;AAe5B,MAAM,WAAW,eAA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AE,oBAAgD;AAC1D;;;;;GAKG;AACH,UAAU,GAAE,SAAS,EAAO,GAC3B,oBAAoB,CAqbtB"}
@@ -1,8 +1,8 @@
1
1
  /**
2
2
  * CLI-subprocess intelligence provider.
3
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
4
+ * Spawns `claude -p --output-format stream-json --json-schema ...` for each
5
+ * semantic stage of consolidation. Uses the user's existing Claude subscription via
6
6
  * OAuth, so no API key is needed — the subprocess inherits the parent's
7
7
  * environment and claude's keychain/file-based credentials resolve naturally.
8
8
  *
@@ -67,6 +67,44 @@ export const CLI_EXTRACT_RETRIES = 1; // exactly one retry; two attempts total
67
67
  export const CLI_FAILURE_SLICE = 300; // same cap as invokeClaude's stderr slice
68
68
  /** Max wait after SIGKILL before the timeout result is returned. Join, not backoff. */
69
69
  export const CLI_TIMEOUT_JOIN_MS = 2_000;
70
+ /** Absolute ceiling per stage, even if the stream keeps ticking. Idle is `timeoutMs`. */
71
+ export const CLI_HARD_TIMEOUT_MS = 15 * 60 * 1000;
72
+ /**
73
+ * Parse `claude -p --output-format stream-json` (NDJSON) or a single JSON
74
+ * envelope (`--output-format json`, tests). Prefer the last `type: result`
75
+ * line; otherwise the last object with `structured_output`.
76
+ */
77
+ export function parseClaudeCliStdout(stdout) {
78
+ const lines = stdout.split(/\r?\n/).map((l) => l.trim()).filter((l) => l.length > 0);
79
+ let lastResult;
80
+ let lastStructured;
81
+ for (const line of lines) {
82
+ let obj;
83
+ try {
84
+ obj = JSON.parse(line);
85
+ }
86
+ catch {
87
+ continue;
88
+ }
89
+ if (obj === null || typeof obj !== "object" || Array.isArray(obj))
90
+ continue;
91
+ const rec = obj;
92
+ if (rec.type === "result")
93
+ lastResult = rec;
94
+ if (rec.structured_output !== undefined && rec.structured_output !== null) {
95
+ lastStructured = rec;
96
+ }
97
+ }
98
+ if (lastResult)
99
+ return lastResult;
100
+ if (lastStructured)
101
+ return lastStructured;
102
+ const whole = JSON.parse(stdout);
103
+ if (whole === null || typeof whole !== "object" || Array.isArray(whole)) {
104
+ throw new SyntaxError("claude stdout is not a JSON object");
105
+ }
106
+ return whole;
107
+ }
70
108
  function formatStageFailure(stageName, result, phase, extra) {
71
109
  const bits = [
72
110
  "[facthouse cli-provider]",
@@ -79,8 +117,15 @@ function formatStageFailure(stageName, result, phase, extra) {
79
117
  bits.push(`stderr=${JSON.stringify((result.stderr ?? "").slice(0, CLI_FAILURE_SLICE))}`);
80
118
  }
81
119
  else if (result.error === "timeout") {
82
- if (extra?.timeoutMs != null)
83
- bits.push(`after=${extra.timeoutMs}ms`);
120
+ if (result.watchdog === "hard") {
121
+ bits.push(`hard=${CLI_HARD_TIMEOUT_MS}ms`);
122
+ }
123
+ else if (extra?.timeoutMs != null) {
124
+ bits.push(`idle=${extra.timeoutMs}ms`);
125
+ }
126
+ if (typeof result.elapsedMs === "number") {
127
+ bits.push(`elapsed=${result.elapsedMs}ms`);
128
+ }
84
129
  if (result.stderr)
85
130
  bits.push(`stderr=${JSON.stringify(result.stderr.slice(0, CLI_FAILURE_SLICE))}`);
86
131
  }
@@ -102,7 +147,10 @@ async function invokeClaude(prompt, schema, command, opts) {
102
147
  ...command.slice(1),
103
148
  "-p",
104
149
  "--output-format",
105
- "json",
150
+ "stream-json",
151
+ "--verbose",
152
+ // Documented trio with -p. Does not flush a block-buffered pipe.
153
+ "--include-partial-messages",
106
154
  "--json-schema",
107
155
  JSON.stringify(schema),
108
156
  "--setting-sources",
@@ -140,12 +188,30 @@ async function invokeClaude(prompt, schema, command, opts) {
140
188
  let stdout = "";
141
189
  let stderr = "";
142
190
  let timedOut = false;
191
+ let timeoutWatchdog;
192
+ let idleTimer;
143
193
  let joinTimer;
144
- const timer = setTimeout(() => {
194
+ const clearWatchdogs = () => {
195
+ if (idleTimer)
196
+ clearTimeout(idleTimer);
197
+ if (hardTimer)
198
+ clearTimeout(hardTimer);
199
+ if (joinTimer)
200
+ clearTimeout(joinTimer);
201
+ };
202
+ const fireTimeout = (watchdog) => {
145
203
  // Kill immediately and wait for close (or the join cap) before
146
204
  // resolving. SIGTERM-and-return used to let the retry spawn overlap
147
- // a live child.
205
+ // a live child. Idle and hard share this path; the second must not
206
+ // arm another join.
207
+ if (timedOut || resolved)
208
+ return;
148
209
  timedOut = true;
210
+ timeoutWatchdog = watchdog;
211
+ if (idleTimer)
212
+ clearTimeout(idleTimer);
213
+ if (hardTimer)
214
+ clearTimeout(hardTimer);
149
215
  try {
150
216
  child.kill("SIGKILL");
151
217
  }
@@ -156,35 +222,53 @@ async function invokeClaude(prompt, schema, command, opts) {
156
222
  finish({
157
223
  error: "timeout",
158
224
  stderr: stderr.slice(0, CLI_FAILURE_SLICE),
225
+ watchdog: timeoutWatchdog,
159
226
  });
160
227
  }, 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()));
228
+ };
229
+ const armIdle = () => {
230
+ if (resolved || timedOut)
231
+ return;
232
+ if (idleTimer)
233
+ clearTimeout(idleTimer);
234
+ idleTimer = setTimeout(() => fireTimeout("idle"), opts.timeoutMs);
235
+ };
236
+ armIdle();
237
+ const hardTimer = setTimeout(() => fireTimeout("hard"), Math.max(CLI_HARD_TIMEOUT_MS, opts.timeoutMs));
238
+ // Spawn and stdin-end are not silence. Windows CreateProcess plus a
239
+ // large extract prompt used to count against the idle window, so the
240
+ // first chunk died before the first stream-json line.
241
+ child.on("spawn", armIdle);
242
+ child.stdout?.on("data", (d) => {
243
+ stdout += d.toString();
244
+ armIdle();
245
+ });
246
+ child.stderr?.on("data", (d) => {
247
+ stderr += d.toString();
248
+ armIdle();
249
+ });
164
250
  child.stdin?.on("error", () => {
165
251
  // EPIPE if the child exits before consuming the prompt; close/error
166
252
  // handlers below settle the result.
167
253
  });
168
254
  child.on("error", (err) => {
169
- clearTimeout(timer);
170
- if (joinTimer)
171
- clearTimeout(joinTimer);
255
+ clearWatchdogs();
172
256
  if (timedOut) {
173
257
  return finish({
174
258
  error: "timeout",
175
259
  stderr: stderr.slice(0, CLI_FAILURE_SLICE),
260
+ watchdog: timeoutWatchdog,
176
261
  });
177
262
  }
178
263
  finish({ error: "spawn-error", detail: err.message });
179
264
  });
180
265
  child.on("close", (code) => {
181
- clearTimeout(timer);
182
- if (joinTimer)
183
- clearTimeout(joinTimer);
266
+ clearWatchdogs();
184
267
  if (timedOut) {
185
268
  return finish({
186
269
  error: "timeout",
187
270
  stderr: stderr.slice(0, CLI_FAILURE_SLICE),
271
+ watchdog: timeoutWatchdog,
188
272
  });
189
273
  }
190
274
  if (code !== 0) {
@@ -196,7 +280,7 @@ async function invokeClaude(prompt, schema, command, opts) {
196
280
  }
197
281
  let envelope;
198
282
  try {
199
- envelope = JSON.parse(stdout);
283
+ envelope = parseClaudeCliStdout(stdout);
200
284
  }
201
285
  catch (err) {
202
286
  return finish({ error: "parse-error", detail: err.message });
@@ -221,7 +305,7 @@ async function invokeClaude(prompt, schema, command, opts) {
221
305
  });
222
306
  });
223
307
  try {
224
- child.stdin?.end(prompt, "utf8");
308
+ child.stdin?.end(prompt, "utf8", armIdle);
225
309
  }
226
310
  catch {
227
311
  // Child already closed stdin; close/error handlers settle the result.
@@ -514,10 +598,9 @@ vocabulary = []) {
514
598
  // Resolved lazily below — kept here only to satisfy the Required shape.
515
599
  command: [],
516
600
  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.
601
+ // Idle silence, not wall-clock. A live stream-json child can run for
602
+ // minutes; CLI_HARD_TIMEOUT_MS is the ceiling. 45s with no spawn, no
603
+ // stdin-end, and no pipe bytes still means hung.
521
604
  timeoutMs: userOpts.timeoutMs ?? CLI_DEFAULT_TIMEOUT_MS,
522
605
  cwd: userOpts.cwd ?? tmpdir(),
523
606
  maxCandidates: userOpts.maxCandidates ?? 50,
@@ -552,6 +635,7 @@ vocabulary = []) {
552
635
  model: opts.model,
553
636
  });
554
637
  }
638
+ let lastStageError = null;
555
639
  /** Standardised stage runner. Returns null on failure so callers can fall back. */
556
640
  async function runStage(stageName, systemPrompt, userPayload, schema, retryTransient = false) {
557
641
  // Claude's --json-schema flag expects a user prompt; we pass the system
@@ -561,9 +645,11 @@ vocabulary = []) {
561
645
  // behaviour predictable.
562
646
  const prompt = `${systemPrompt}\n\nINPUT:\n${JSON.stringify(userPayload)}`;
563
647
  const attempt = () => invokeClaude(prompt, schema, getCommand(), opts);
648
+ lastStageError = null;
564
649
  let result = await attempt();
565
650
  recordAttempt(stageName, result);
566
651
  if ("error" in result) {
652
+ lastStageError = result.error;
567
653
  const retryable = retryTransient &&
568
654
  CLI_EXTRACT_RETRY_KINDS.includes(result.error);
569
655
  console.error(formatStageFailure(stageName, result, "first", {
@@ -574,11 +660,13 @@ vocabulary = []) {
574
660
  result = await attempt();
575
661
  recordAttempt(stageName, result);
576
662
  if ("error" in result) {
663
+ lastStageError = result.error;
577
664
  console.error(formatStageFailure(stageName, result, "retry", {
578
665
  timeoutMs: result.error === "timeout" ? opts.timeoutMs : undefined,
579
666
  }));
580
667
  return null;
581
668
  }
669
+ lastStageError = null;
582
670
  log(`${stageName} retry ok in ${result.elapsedMs}ms`);
583
671
  return result.structured;
584
672
  }
@@ -625,7 +713,11 @@ vocabulary = []) {
625
713
  // configured extractor never ran: these events have NOT been examined,
626
714
  // and advancing past them would discard them permanently.
627
715
  const fell = await fallback.extractFactsFromEvents(events, workingMemory, sessionSummary, longTermMemory, extras);
628
- return { facts: fell.facts, degraded: true };
716
+ return {
717
+ facts: fell.facts,
718
+ degraded: true,
719
+ degradedKind: lastStageError === "timeout" ? "timeout" : "other",
720
+ };
629
721
  }
630
722
  const extracted = result.facts.map((f) => ({
631
723
  content: f.content,