@remnic/core 9.40.0 → 9.42.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 (278) hide show
  1. package/dist/access-admin-ops-surface.d.ts +10 -10
  2. package/dist/access-admin-ops-surface.js +5 -4
  3. package/dist/access-authorization-probe.d.ts +10 -10
  4. package/dist/access-authorization-probe.js +6 -5
  5. package/dist/access-boundary.d.ts +10 -10
  6. package/dist/access-boundary.js +5 -4
  7. package/dist/access-cli.js +16 -15
  8. package/dist/access-cli.js.map +1 -1
  9. package/dist/access-extraction-force-flush.d.ts +10 -10
  10. package/dist/access-extraction-force-flush.js +5 -4
  11. package/dist/access-health-types.d.ts +1 -1
  12. package/dist/access-http-lcm-compaction.d.ts +10 -10
  13. package/dist/access-http-lifecycle-flush.d.ts +10 -10
  14. package/dist/access-http.d.ts +10 -10
  15. package/dist/access-http.js +10 -9
  16. package/dist/access-identity-continuity-surface.d.ts +8 -8
  17. package/dist/access-identity-continuity-surface.js +5 -4
  18. package/dist/access-lcm-surface.d.ts +10 -10
  19. package/dist/access-lcm-surface.js +5 -4
  20. package/dist/access-mcp.d.ts +10 -10
  21. package/dist/access-mcp.js +8 -7
  22. package/dist/access-memory-search-fanout.d.ts +2 -2
  23. package/dist/{access-namespace-preflight-BbDJBq0e.d.ts → access-namespace-preflight-47dOyty9.d.ts} +1 -1
  24. package/dist/access-namespace-preflight.d.ts +3 -3
  25. package/dist/access-namespace-preflight.js +5 -4
  26. package/dist/access-observe-write-surface.d.ts +10 -10
  27. package/dist/access-observe-write-surface.js +5 -4
  28. package/dist/access-operations-batch.js +6 -5
  29. package/dist/access-operations.d.ts +13 -13
  30. package/dist/access-operations.js +7 -6
  31. package/dist/access-recall-concurrency.d.ts +10 -10
  32. package/dist/access-recall-concurrency.js +5 -4
  33. package/dist/access-recall-response.d.ts +10 -10
  34. package/dist/access-recall-response.js +5 -4
  35. package/dist/access-recall-surface.d.ts +10 -10
  36. package/dist/access-recall-surface.js +5 -4
  37. package/dist/access-schema.d.ts +84 -84
  38. package/dist/{access-service-B2h6rITp.d.ts → access-service-D1BkxwSf.d.ts} +7 -7
  39. package/dist/access-service-helpers.d.ts +10 -10
  40. package/dist/access-service.d.ts +10 -10
  41. package/dist/access-service.js +5 -4
  42. package/dist/access-surface-catalog.d.ts +10 -10
  43. package/dist/access-wearables-meetings-surface.d.ts +3 -3
  44. package/dist/action-confidence.d.ts +1 -1
  45. package/dist/active-memory-bridge.d.ts +1 -1
  46. package/dist/active-recall.d.ts +1 -1
  47. package/dist/active-recall.js +2 -2
  48. package/dist/behavior-learner.d.ts +1 -1
  49. package/dist/behavior-signals.d.ts +1 -1
  50. package/dist/bootstrap.d.ts +8 -8
  51. package/dist/briefing.d.ts +2 -2
  52. package/dist/buffer-surprise-report.d.ts +1 -1
  53. package/dist/buffer-turn-helpers.d.ts +1 -1
  54. package/dist/buffer.d.ts +2 -2
  55. package/dist/bulk-import/index.d.ts +3 -3
  56. package/dist/calibration.d.ts +1 -1
  57. package/dist/capabilities.d.ts +1 -1
  58. package/dist/{catalog-Bz2LxGNb.d.ts → catalog-DPQynQZG.d.ts} +1 -1
  59. package/dist/causal-behavior.d.ts +1 -1
  60. package/dist/causal-consolidation.d.ts +1 -1
  61. package/dist/causal-trajectory-graph.d.ts +1 -1
  62. package/dist/{chunk-443XCR34.js → chunk-3SG4FGDV.js} +53 -41
  63. package/dist/chunk-3SG4FGDV.js.map +1 -0
  64. package/dist/{chunk-XPQ5ZTL6.js → chunk-6I2C3EOH.js} +6 -6
  65. package/dist/chunk-7VIB7PAE.js +142 -0
  66. package/dist/chunk-7VIB7PAE.js.map +1 -0
  67. package/dist/{chunk-AYICY7IE.js → chunk-AXUU7SG3.js} +2 -2
  68. package/dist/{chunk-RK6WMGTX.js → chunk-CQ5MR2HQ.js} +13 -9
  69. package/dist/chunk-CQ5MR2HQ.js.map +1 -0
  70. package/dist/{chunk-KW4ZFTUS.js → chunk-CWPDM66T.js} +5 -5
  71. package/dist/{chunk-NEO4QCID.js → chunk-FHEJ22B7.js} +10 -4
  72. package/dist/chunk-FHEJ22B7.js.map +1 -0
  73. package/dist/{chunk-EBWOOJEP.js → chunk-GDC4INBF.js} +2 -2
  74. package/dist/{chunk-UIVRPXRR.js → chunk-KXGN6G2Y.js} +3 -3
  75. package/dist/chunk-KXGN6G2Y.js.map +1 -0
  76. package/dist/{chunk-AXHMCRS3.js → chunk-OYFDEJZB.js} +23 -6
  77. package/dist/chunk-OYFDEJZB.js.map +1 -0
  78. package/dist/{chunk-SD4A6IZY.js → chunk-PWKZV4A3.js} +2 -2
  79. package/dist/{chunk-XYXYEDPL.js → chunk-Q4XL7LJW.js} +26 -5
  80. package/dist/chunk-Q4XL7LJW.js.map +1 -0
  81. package/dist/{chunk-MOHZIKZM.js → chunk-TM72UOX2.js} +2 -2
  82. package/dist/{chunk-GLBK35BT.js → chunk-UGCUVLOL.js} +14 -10
  83. package/dist/chunk-UGCUVLOL.js.map +1 -0
  84. package/dist/{chunk-Q6QYN56R.js → chunk-UQVGDEAJ.js} +2 -2
  85. package/dist/{chunk-KYYRJVE6.js → chunk-XRWVXPEM.js} +2 -2
  86. package/dist/{cli-CO8qKPM5.d.ts → cli-IUhV-lmk.d.ts} +5 -5
  87. package/dist/cli.d.ts +12 -12
  88. package/dist/cli.js +15 -14
  89. package/dist/compounding/engine.d.ts +2 -2
  90. package/dist/compounding/preference-consolidator.d.ts +1 -1
  91. package/dist/compression-optimizer.d.ts +1 -1
  92. package/dist/config.d.ts +1 -1
  93. package/dist/config.js +2 -2
  94. package/dist/connectors/codex-materialize-runner.d.ts +1 -1
  95. package/dist/connectors/codex-materialize.d.ts +1 -1
  96. package/dist/connectors/index.d.ts +1 -1
  97. package/dist/consolidation-provenance-check.d.ts +2 -2
  98. package/dist/consolidation-undo.d.ts +2 -2
  99. package/dist/contradiction/index.d.ts +2 -2
  100. package/dist/conversation-index/backend.d.ts +1 -1
  101. package/dist/conversation-index/chunker.d.ts +1 -1
  102. package/dist/conversation-index/faiss-adapter.d.ts +1 -1
  103. package/dist/conversation-index/indexer.d.ts +1 -1
  104. package/dist/conversation-index/search.d.ts +1 -1
  105. package/dist/corpus-watermark.d.ts +7 -1
  106. package/dist/corpus-watermark.js +2 -2
  107. package/dist/day-summary.d.ts +1 -1
  108. package/dist/delinearize.d.ts +1 -1
  109. package/dist/direct-answer-wiring.d.ts +1 -1
  110. package/dist/direct-answer.d.ts +1 -1
  111. package/dist/embedding-fallback.d.ts +1 -1
  112. package/dist/enrichment/index.d.ts +1 -1
  113. package/dist/entity-retrieval.d.ts +2 -2
  114. package/dist/entity-schema.d.ts +1 -1
  115. package/dist/explicit-capture.d.ts +8 -8
  116. package/dist/extraction-error-classification.d.ts +1 -1
  117. package/dist/extraction-faithfulness.d.ts +1 -1
  118. package/dist/extraction-judge-telemetry.d.ts +1 -1
  119. package/dist/extraction-judge-training.d.ts +1 -1
  120. package/dist/extraction-judge.d.ts +1 -1
  121. package/dist/extraction-liveness.d.ts +1 -1
  122. package/dist/extraction-liveness.js +3 -1
  123. package/dist/extraction-source-grounding-rules.d.ts +1 -1
  124. package/dist/extraction-source-grounding.d.ts +1 -1
  125. package/dist/extraction.d.ts +1 -1
  126. package/dist/fallback-llm.d.ts +1 -1
  127. package/dist/graph-dashboard-diff.d.ts +1 -1
  128. package/dist/graph-dashboard-key.d.ts +1 -1
  129. package/dist/graph-dashboard-parser.d.ts +1 -1
  130. package/dist/graph-edge-reinforcement.d.ts +1 -1
  131. package/dist/graph-snapshot.d.ts +1 -1
  132. package/dist/graph.d.ts +1 -1
  133. package/dist/importance.d.ts +1 -1
  134. package/dist/importers/index.d.ts +1 -1
  135. package/dist/in-flight-reads.d.ts +1 -1
  136. package/dist/index.d.ts +407 -407
  137. package/dist/index.js +16 -15
  138. package/dist/intent.d.ts +1 -1
  139. package/dist/lcm/engine.d.ts +1 -1
  140. package/dist/lcm/index.d.ts +1 -1
  141. package/dist/lcm/tools.d.ts +1 -1
  142. package/dist/lifecycle.d.ts +1 -1
  143. package/dist/live-connectors-runner.d.ts +1 -1
  144. package/dist/local-llm.d.ts +1 -1
  145. package/dist/local-model-endpoint.d.ts +1 -1
  146. package/dist/maintenance/memory-governance.d.ts +1 -1
  147. package/dist/maintenance/rebuild-memory-lifecycle-ledger.d.ts +2 -2
  148. package/dist/maintenance/rebuild-memory-projection.d.ts +2 -2
  149. package/dist/{maintenance-D2jkiT9r.d.ts → maintenance-DVBLXkFw.d.ts} +3 -3
  150. package/dist/mcp-memory-inspector-app.d.ts +10 -10
  151. package/dist/memory-action-policy.d.ts +1 -1
  152. package/dist/memory-cache.d.ts +1 -1
  153. package/dist/memory-lifecycle-ledger-utils.d.ts +1 -1
  154. package/dist/memory-projection-store.d.ts +1 -1
  155. package/dist/memory-provenance.d.ts +1 -1
  156. package/dist/memory-worth-outcomes.d.ts +2 -2
  157. package/dist/models-json.d.ts +1 -1
  158. package/dist/namespaces/migrate.d.ts +4 -3
  159. package/dist/namespaces/migrate.js +1 -1
  160. package/dist/namespaces/principal.d.ts +1 -1
  161. package/dist/namespaces/search.d.ts +1 -1
  162. package/dist/namespaces/storage.d.ts +3 -3
  163. package/dist/native-knowledge.d.ts +1 -1
  164. package/dist/offline-sync-impression-drain.d.ts +1 -1
  165. package/dist/operator-doctor-corpus.d.ts +1 -1
  166. package/dist/operator-doctor-corpus.js +3 -3
  167. package/dist/operator-doctor-replica.d.ts +1 -1
  168. package/dist/operator-toolkit.d.ts +5 -4
  169. package/dist/operator-toolkit.js +7 -6
  170. package/dist/orchestration/compression-guideline-coordinator.d.ts +2 -2
  171. package/dist/orchestration/maintenance.d.ts +4 -4
  172. package/dist/{orchestrator-SHaRXCUF.d.ts → orchestrator-fYTncnLy.d.ts} +7 -7
  173. package/dist/orchestrator.d.ts +8 -8
  174. package/dist/orchestrator.js +16 -15
  175. package/dist/patterns-cli.d.ts +1 -1
  176. package/dist/{pipeline-B5_tS1Yc.d.ts → pipeline-Cs76XC-p.d.ts} +1 -1
  177. package/dist/policy-runtime.d.ts +1 -1
  178. package/dist/proactive-contention.d.ts +1 -1
  179. package/dist/provenance.d.ts +1 -1
  180. package/dist/{qmd-CkEV_SPG.d.ts → qmd-WJwvBgiF.d.ts} +1 -1
  181. package/dist/qmd-preflight.d.ts +2 -2
  182. package/dist/qmd-recall-cache.d.ts +1 -1
  183. package/dist/qmd.d.ts +2 -2
  184. package/dist/recall-concurrency-config.d.ts +1 -1
  185. package/dist/recall-disclosure-escalation.d.ts +1 -1
  186. package/dist/recall-explain-renderer.d.ts +1 -1
  187. package/dist/recall-memory-map.d.ts +1 -1
  188. package/dist/recall-planner-llm.d.ts +1 -1
  189. package/dist/recall-state.d.ts +1 -1
  190. package/dist/recall-tag-filter.d.ts +1 -1
  191. package/dist/recall-timings.d.ts +1 -1
  192. package/dist/recall-xray-cli.d.ts +1 -1
  193. package/dist/recall-xray-renderer.d.ts +1 -1
  194. package/dist/recall-xray.d.ts +1 -1
  195. package/dist/replay/normalizers/chatgpt.d.ts +1 -1
  196. package/dist/replay/normalizers/claude.d.ts +1 -1
  197. package/dist/replay/normalizers/openclaw.d.ts +1 -1
  198. package/dist/replay/normalizers/shared.d.ts +1 -1
  199. package/dist/replay/runner.d.ts +1 -1
  200. package/dist/replay/types.d.ts +1 -1
  201. package/dist/replica-divergence.d.ts +1 -1
  202. package/dist/replica-peers-config.d.ts +1 -1
  203. package/dist/resolve-auth-token.d.ts +1 -1
  204. package/dist/resume-bundles.js +3 -3
  205. package/dist/retrieval-agents.d.ts +2 -2
  206. package/dist/retrieval-tiers.d.ts +1 -1
  207. package/dist/routing/engine.d.ts +1 -1
  208. package/dist/routing/store.d.ts +1 -1
  209. package/dist/salvage-envelope.d.ts +1 -1
  210. package/dist/schemas.d.ts +76 -76
  211. package/dist/{scope-profiles-DeAdnocS.d.ts → scope-profiles-CQ0NAleS.d.ts} +1 -1
  212. package/dist/search/embed-helper.d.ts +1 -1
  213. package/dist/search/factory.d.ts +1 -1
  214. package/dist/search/index.d.ts +1 -1
  215. package/dist/search/lancedb-backend.d.ts +1 -1
  216. package/dist/search/meilisearch-backend.d.ts +1 -1
  217. package/dist/search/noop-backend.d.ts +1 -1
  218. package/dist/search/orama-backend.d.ts +1 -1
  219. package/dist/search/port.d.ts +1 -1
  220. package/dist/search/remote-backend.d.ts +1 -1
  221. package/dist/{semantic-consolidation-DR_h-JUD.d.ts → semantic-consolidation-BWxOBMtz.d.ts} +1 -1
  222. package/dist/semantic-consolidation.d.ts +2 -2
  223. package/dist/semantic-rule-verifier.d.ts +1 -1
  224. package/dist/{service-BTb94UPJ.d.ts → service-CLuMO-pa.d.ts} +2 -2
  225. package/dist/session-observer-bands.d.ts +1 -1
  226. package/dist/session-observer-state.d.ts +1 -1
  227. package/dist/shared-context/manager.d.ts +9 -9
  228. package/dist/signal.d.ts +1 -1
  229. package/dist/source-agent-qualifier.d.ts +1 -1
  230. package/dist/{storage-ax2EIsVS.d.ts → storage-Blr71GpS.d.ts} +1 -1
  231. package/dist/storage.d.ts +2 -2
  232. package/dist/summarizer.d.ts +1 -1
  233. package/dist/summary-snapshot.d.ts +1 -1
  234. package/dist/temporal-supersession.d.ts +2 -2
  235. package/dist/temporal-timeline-recall.d.ts +1 -1
  236. package/dist/temporal-validity.d.ts +1 -1
  237. package/dist/threading.d.ts +1 -1
  238. package/dist/tier-migration.d.ts +2 -2
  239. package/dist/tier-routing.d.ts +1 -1
  240. package/dist/topics.d.ts +1 -1
  241. package/dist/transcript.d.ts +1 -1
  242. package/dist/transfer/types.d.ts +66 -66
  243. package/dist/trust-score-stage.d.ts +1 -1
  244. package/dist/trust-score.d.ts +1 -1
  245. package/dist/{types-CCGL-9NX.d.ts → types-CqWwMPr_.d.ts} +41 -59
  246. package/dist/types.d.ts +1 -1
  247. package/dist/utility-runtime.d.ts +1 -1
  248. package/dist/write-envelope.d.ts +1 -1
  249. package/package.json +2 -2
  250. package/src/access-http.test.ts +2 -2
  251. package/src/access-service-health.test.ts +39 -17
  252. package/src/access-service.ts +25 -3
  253. package/src/cli.ts +3 -3
  254. package/src/corpus-watermark.test.ts +16 -0
  255. package/src/corpus-watermark.ts +28 -5
  256. package/src/extraction-liveness.test.ts +81 -19
  257. package/src/extraction-liveness.ts +96 -98
  258. package/src/extraction-watermark.test.ts +290 -0
  259. package/src/namespaces/migrate.ts +10 -2
  260. package/src/operator-doctor-corpus.test.ts +7 -0
  261. package/src/operator-doctor-corpus.ts +1 -1
  262. package/src/operator-toolkit.ts +8 -8
  263. package/src/orchestration/extraction-watermark.ts +188 -0
  264. package/dist/chunk-443XCR34.js.map +0 -1
  265. package/dist/chunk-AXHMCRS3.js.map +0 -1
  266. package/dist/chunk-GLBK35BT.js.map +0 -1
  267. package/dist/chunk-NEO4QCID.js.map +0 -1
  268. package/dist/chunk-RK6WMGTX.js.map +0 -1
  269. package/dist/chunk-UIVRPXRR.js.map +0 -1
  270. package/dist/chunk-XYXYEDPL.js.map +0 -1
  271. /package/dist/{chunk-XPQ5ZTL6.js.map → chunk-6I2C3EOH.js.map} +0 -0
  272. /package/dist/{chunk-AYICY7IE.js.map → chunk-AXUU7SG3.js.map} +0 -0
  273. /package/dist/{chunk-KW4ZFTUS.js.map → chunk-CWPDM66T.js.map} +0 -0
  274. /package/dist/{chunk-EBWOOJEP.js.map → chunk-GDC4INBF.js.map} +0 -0
  275. /package/dist/{chunk-SD4A6IZY.js.map → chunk-PWKZV4A3.js.map} +0 -0
  276. /package/dist/{chunk-MOHZIKZM.js.map → chunk-TM72UOX2.js.map} +0 -0
  277. /package/dist/{chunk-Q6QYN56R.js.map → chunk-UQVGDEAJ.js.map} +0 -0
  278. /package/dist/{chunk-KYYRJVE6.js.map → chunk-XRWVXPEM.js.map} +0 -0
@@ -0,0 +1,290 @@
1
+ import assert from "node:assert/strict";
2
+ import { mkdtemp, mkdir, rm, writeFile } from "node:fs/promises";
3
+ import os from "node:os";
4
+ import path from "node:path";
5
+ import test from "node:test";
6
+
7
+ import { TOKEN_CAPABILITIES_VERSION } from "./access-token-capabilities.js";
8
+ import { parseConfig } from "./config.js";
9
+ import { CorpusWatermarkCache } from "./corpus-watermark.js";
10
+ import { readAggregateExtractionWatermark } from "./orchestration/extraction-watermark.js";
11
+ import type { PluginConfig } from "./types.js";
12
+
13
+ interface FakeWatermarkStorage {
14
+ readonly dir: string;
15
+ loadMeta(): Promise<{ lastExtractionAt: string | null }>;
16
+ }
17
+
18
+ function storage(dir: string, read: () => Promise<string | null>): FakeWatermarkStorage {
19
+ return {
20
+ dir,
21
+ loadMeta: async () => ({ lastExtractionAt: await read() }),
22
+ };
23
+ }
24
+
25
+ async function namespacedFixture(): Promise<{
26
+ memoryDir: string;
27
+ config: PluginConfig;
28
+ namespaceDirs: Record<string, string>;
29
+ }> {
30
+ const memoryDir = await mkdtemp(path.join(os.tmpdir(), "remnic-extraction-watermark-"));
31
+ const namespaceDirs = {
32
+ "team-a": path.join(memoryDir, "namespaces", "team-a"),
33
+ "team-b": path.join(memoryDir, "namespaces", "team-b"),
34
+ };
35
+ await Promise.all(Object.values(namespaceDirs).map((dir) => mkdir(dir, { recursive: true })));
36
+ return {
37
+ memoryDir,
38
+ config: parseConfig({ memoryDir, namespacesEnabled: true, defaultNamespace: "default" }),
39
+ namespaceDirs,
40
+ };
41
+ }
42
+
43
+ test("aggregate watermark selects the most recent extraction across distinct namespace stores", async () => {
44
+ const fixture = await namespacedFixture();
45
+ try {
46
+ const timestamps = {
47
+ default: "2026-07-20T12:00:00.000Z",
48
+ "team-a": "2026-07-21T12:00:00.000Z",
49
+ "team-b": "2026-07-22T12:00:00.000Z",
50
+ };
51
+ const result = await readAggregateExtractionWatermark({
52
+ config: fixture.config,
53
+ rootStorage: storage(fixture.memoryDir, async () => timestamps.default),
54
+ storageForNamespace: async (namespace) =>
55
+ storage(fixture.namespaceDirs[namespace], async () => timestamps[namespace as keyof typeof timestamps]),
56
+ });
57
+
58
+ assert.deepEqual(result, {
59
+ lastExtractionAt: timestamps["team-b"],
60
+ readFailed: false,
61
+ });
62
+ } finally {
63
+ await rm(fixture.memoryDir, { recursive: true, force: true });
64
+ }
65
+ });
66
+
67
+ test("a namespace-isolated extraction advances the daemon aggregate watermark", async () => {
68
+ const fixture = await namespacedFixture();
69
+ try {
70
+ const rootTimestamp = "2026-07-20T12:00:00.000Z";
71
+ let teamTimestamp = "2026-07-19T12:00:00.000Z";
72
+ const options = {
73
+ config: fixture.config,
74
+ rootStorage: storage(fixture.memoryDir, async () => rootTimestamp),
75
+ storageForNamespace: async (namespace: string) =>
76
+ storage(fixture.namespaceDirs[namespace], async () => (namespace === "team-a" ? teamTimestamp : null)),
77
+ };
78
+
79
+ assert.equal((await readAggregateExtractionWatermark(options)).lastExtractionAt, rootTimestamp);
80
+ teamTimestamp = "2026-07-23T12:00:00.000Z";
81
+ assert.equal((await readAggregateExtractionWatermark(options)).lastExtractionAt, teamTimestamp);
82
+ } finally {
83
+ await rm(fixture.memoryDir, { recursive: true, force: true });
84
+ }
85
+ });
86
+
87
+ test("a partial namespace read returns readFailed instead of a survivor's fresh watermark", async () => {
88
+ const fixture = await namespacedFixture();
89
+ try {
90
+ const result = await readAggregateExtractionWatermark({
91
+ config: fixture.config,
92
+ rootStorage: storage(fixture.memoryDir, async () => "2026-07-23T12:00:00.000Z"),
93
+ storageForNamespace: async (namespace) =>
94
+ storage(fixture.namespaceDirs[namespace], async () => {
95
+ if (namespace === "team-b") throw new Error("meta store unavailable");
96
+ return "2026-07-22T12:00:00.000Z";
97
+ }),
98
+ });
99
+
100
+ assert.equal(result.lastExtractionAt, null, "a surviving timestamp must not be reported as complete");
101
+ assert.equal(result.readFailed, true);
102
+ assert.match(result.readError ?? "", /namespace watermark unreadable/);
103
+ assert.match(result.readError ?? "", /meta store unavailable/);
104
+ } finally {
105
+ await rm(fixture.memoryDir, { recursive: true, force: true });
106
+ }
107
+ });
108
+ test("scoped capabilities filter candidate namespaces during aggregate read", async () => {
109
+ const fixture = await namespacedFixture();
110
+ try {
111
+ let scannedTeamB = false;
112
+ const result = await readAggregateExtractionWatermark({
113
+ config: fixture.config,
114
+ rootStorage: storage(fixture.memoryDir, async () => "2026-07-20T12:00:00.000Z"),
115
+ storageForNamespace: async (namespace) => {
116
+ if (namespace === "team-b") scannedTeamB = true;
117
+ return storage(fixture.namespaceDirs[namespace], async () => "2026-07-25T12:00:00.000Z");
118
+ },
119
+ caps: { version: TOKEN_CAPABILITIES_VERSION, namespaces: ["team-a"] },
120
+ });
121
+
122
+ assert.equal(scannedTeamB, false, "team-b should be skipped when token is restricted to team-a");
123
+ assert.equal(result.readFailed, false);
124
+ } finally {
125
+ await rm(fixture.memoryDir, { recursive: true, force: true });
126
+ }
127
+ });
128
+
129
+ test("default root capability check uses normalized aliases for migrated storage", async () => {
130
+ const fixture = await namespacedFixture();
131
+ try {
132
+ const migratedDefaultDir = path.join(fixture.memoryDir, "namespaces", "default");
133
+ await mkdir(migratedDefaultDir, { recursive: true });
134
+ const result = await readAggregateExtractionWatermark({
135
+ config: { ...fixture.config, defaultNamespace: " default " },
136
+ rootStorage: storage(fixture.memoryDir, async () => {
137
+ throw new Error("inactive legacy root is unreadable");
138
+ }),
139
+ storageForNamespace: async (_namespace, rootDir) =>
140
+ storage(rootDir, async () =>
141
+ path.resolve(rootDir) === path.resolve(migratedDefaultDir)
142
+ ? "2026-07-26T12:00:00.000Z"
143
+ : "2026-07-24T12:00:00.000Z",
144
+ ),
145
+ caps: { version: TOKEN_CAPABILITIES_VERSION, namespaces: ["default"] },
146
+ });
147
+
148
+ assert.equal(result.lastExtractionAt, "2026-07-26T12:00:00.000Z");
149
+ assert.equal(result.readFailed, false);
150
+ } finally {
151
+ await rm(fixture.memoryDir, { recursive: true, force: true });
152
+ }
153
+ });
154
+ test("unparsable non-null timestamp in namespace store fails the aggregate read", async () => {
155
+ const fixture = await namespacedFixture();
156
+ try {
157
+ const result = await readAggregateExtractionWatermark({
158
+ config: fixture.config,
159
+ rootStorage: storage(fixture.memoryDir, async () => "2026-07-20T12:00:00.000Z"),
160
+ storageForNamespace: async (namespace) =>
161
+ storage(fixture.namespaceDirs[namespace], async () => (namespace === "team-a" ? "invalid-date-string" : "2026-07-25T12:00:00.000Z")),
162
+ });
163
+
164
+ assert.equal(result.lastExtractionAt, null);
165
+ assert.equal(result.readFailed, true);
166
+ assert.match(result.readError ?? "", /watermark timestamp invalid/);
167
+ } finally {
168
+ await rm(fixture.memoryDir, { recursive: true, force: true });
169
+ }
170
+ });
171
+
172
+ test("namespace discovery I/O failure is an explicit incomplete read", async () => {
173
+ const memoryDir = await mkdtemp(path.join(os.tmpdir(), "remnic-extraction-watermark-enumeration-"));
174
+ try {
175
+ await writeFile(path.join(memoryDir, "namespaces"), "not a directory", "utf8");
176
+ const config = parseConfig({ memoryDir, namespacesEnabled: true });
177
+ const result = await readAggregateExtractionWatermark({
178
+ config,
179
+ rootStorage: storage(memoryDir, async () => "2026-07-23T12:00:00.000Z"),
180
+ storageForNamespace: async (_namespace, rootDir) => storage(rootDir, async () => null),
181
+ });
182
+
183
+ assert.equal(result.lastExtractionAt, null);
184
+ assert.equal(result.readFailed, true);
185
+ assert.match(result.readError ?? "", /namespace watermark enumeration failed/);
186
+ assert.match(result.readError ?? "", /ENOTDIR/);
187
+ } finally {
188
+ await rm(memoryDir, { recursive: true, force: true });
189
+ }
190
+ });
191
+
192
+ test("a failed stale-cache refresh makes later reads incomplete", async () => {
193
+ const fixture = await namespacedFixture();
194
+ try {
195
+ let now = 1;
196
+ const cache = new CorpusWatermarkCache({ ttlMs: 1, clock: () => now });
197
+ const options = {
198
+ config: fixture.config,
199
+ rootStorage: storage(fixture.memoryDir, async () => "2026-07-20T12:00:00.000Z"),
200
+ storageForNamespace: async (namespace: string) =>
201
+ storage(fixture.namespaceDirs[namespace], async () => "2026-07-21T12:00:00.000Z"),
202
+ rootsCache: cache,
203
+ };
204
+
205
+ const coldRead = await readAggregateExtractionWatermark(options);
206
+ assert.equal(coldRead.readFailed, false);
207
+ assert.equal(coldRead.pending, true);
208
+ await cache.whenIdle();
209
+ assert.equal((await readAggregateExtractionWatermark(options)).readFailed, false);
210
+
211
+ await rm(path.join(fixture.memoryDir, "namespaces"), { recursive: true, force: true });
212
+ await writeFile(path.join(fixture.memoryDir, "namespaces"), "not a directory", "utf8");
213
+ now += 2;
214
+ assert.equal(
215
+ (await readAggregateExtractionWatermark(options)).readFailed,
216
+ false,
217
+ "the stale value may be served while refresh is still in flight",
218
+ );
219
+ await cache.whenIdle();
220
+ const failedRefresh = await readAggregateExtractionWatermark(options);
221
+ assert.equal(failedRefresh.lastExtractionAt, null);
222
+ assert.equal(failedRefresh.readFailed, true);
223
+ assert.match(failedRefresh.readError ?? "", /namespace watermark enumeration failed/);
224
+ } finally {
225
+ await rm(fixture.memoryDir, { recursive: true, force: true });
226
+ }
227
+ });
228
+
229
+ test("a cold namespace-root cache is pending, not a failed read", async () => {
230
+ const fixture = await namespacedFixture();
231
+ try {
232
+ let rootReads = 0;
233
+ const result = await readAggregateExtractionWatermark({
234
+ config: fixture.config,
235
+ rootStorage: storage(fixture.memoryDir, async () => {
236
+ rootReads += 1;
237
+ return "2026-07-23T12:00:00.000Z";
238
+ }),
239
+ storageForNamespace: async (namespace) => storage(fixture.namespaceDirs[namespace], async () => null),
240
+ rootsCache: {
241
+ getResolvedRootsStatus: () => ({ roots: undefined, refreshError: undefined }),
242
+ },
243
+ });
244
+
245
+ assert.equal(result.lastExtractionAt, null);
246
+ assert.equal(result.readFailed, false);
247
+ assert.equal(result.pending, true);
248
+ assert.equal(rootReads, 0, "a root survivor is not read or published before enumeration completes");
249
+ } finally {
250
+ await rm(fixture.memoryDir, { recursive: true, force: true });
251
+ }
252
+ });
253
+
254
+ test("namespaces disabled performs exactly one root metadata read", async () => {
255
+ const memoryDir = await mkdtemp(path.join(os.tmpdir(), "remnic-extraction-watermark-single-"));
256
+ try {
257
+ const config = parseConfig({ memoryDir, namespacesEnabled: false });
258
+ let rootReads = 0;
259
+ let namespaceResolutions = 0;
260
+ const timestamp = "2026-07-23T12:00:00.000Z";
261
+ const result = await readAggregateExtractionWatermark({
262
+ config,
263
+ rootStorage: {
264
+ dir: memoryDir,
265
+ loadMeta: async () => {
266
+ rootReads += 1;
267
+ return {
268
+ lastExtractionAt: timestamp,
269
+ extractionCount: 9,
270
+ lastConsolidationAt: null,
271
+ };
272
+ },
273
+ },
274
+ storageForNamespace: async () => {
275
+ namespaceResolutions += 1;
276
+ throw new Error("disabled path must not resolve namespace storage");
277
+ },
278
+ });
279
+
280
+ assert.deepEqual(result, {
281
+ lastExtractionAt: timestamp,
282
+ readFailed: false,
283
+ rootStats: { extractionCount: 9, lastConsolidationAt: null },
284
+ });
285
+ assert.equal(rootReads, 1);
286
+ assert.equal(namespaceResolutions, 0);
287
+ } finally {
288
+ await rm(memoryDir, { recursive: true, force: true });
289
+ }
290
+ });
@@ -65,6 +65,7 @@ async function hasAnyLegacyData(rootDir: string): Promise<boolean> {
65
65
 
66
66
  async function discoverConfiguredNamespaces(
67
67
  config: PluginConfig,
68
+ propagateDiscoveryErrors: boolean,
68
69
  ): Promise<string[]> {
69
70
  const discovered = new Set<string>([
70
71
  config.defaultNamespace,
@@ -85,7 +86,10 @@ async function discoverConfiguredNamespaces(
85
86
  discovered.add(namespace);
86
87
  }
87
88
  }
88
- } catch {
89
+ } catch (error) {
90
+ if (propagateDiscoveryErrors && (error as NodeJS.ErrnoException).code !== "ENOENT") {
91
+ throw error;
92
+ }
89
93
  // No namespace directory yet.
90
94
  }
91
95
 
@@ -95,9 +99,13 @@ async function discoverConfiguredNamespaces(
95
99
  export async function listNamespaces(options: {
96
100
  config: PluginConfig;
97
101
  storageRouter?: NamespaceStorageRouter;
102
+ propagateDiscoveryErrors?: boolean;
98
103
  }): Promise<NamespaceInventoryEntry[]> {
99
104
  const storageRouter = options.storageRouter ?? new NamespaceStorageRouter(options.config);
100
- const namespaces = await discoverConfiguredNamespaces(options.config);
105
+ const namespaces = await discoverConfiguredNamespaces(
106
+ options.config,
107
+ options.propagateDiscoveryErrors ?? false,
108
+ );
101
109
  const items = await Promise.all(
102
110
  namespaces.map(async (namespace) => {
103
111
  const storage = await storageRouter.storageFor(namespace);
@@ -143,11 +143,18 @@ test("runOperatorDoctor: includes the corpus_watermark check", async () => {
143
143
  const { root, memoryDir, configPath, orchestrator } = await makeFixture();
144
144
  try {
145
145
  await writeMemory(memoryDir, "facts/2026-03-08/a.md");
146
+ let metadataReads = 0;
147
+ const loadMeta = orchestrator.storage.loadMeta.bind(orchestrator.storage);
148
+ orchestrator.storage.loadMeta = async () => {
149
+ metadataReads += 1;
150
+ return loadMeta();
151
+ };
146
152
  const report = await runOperatorDoctor({ configPath, orchestrator });
147
153
  const check = report.checks.find((c) => c.key === "corpus_watermark");
148
154
  assert.ok(check, "expected a corpus_watermark check");
149
155
  assert.equal(check?.status, "ok");
150
156
  assert.equal(corpusOf(check)[0]?.memoryFileCount, 1);
157
+ assert.equal(metadataReads, 1, "doctor reuses the root metadata read for extraction liveness");
151
158
  } finally {
152
159
  await rm(root, { recursive: true, force: true });
153
160
  }
@@ -42,7 +42,7 @@ export async function summarizeCorpusWatermark(
42
42
  // The doctor orchestrator has no live namespace catalog, so config-driven
43
43
  // enumeration (deduped by root inside the shared helper) is the whole set.
44
44
  const rootByNamespace = new Map<string, string>();
45
- for (const root of await resolveCorpusNamespaceRoots({ config })) {
45
+ for (const root of await resolveCorpusNamespaceRoots({ config, propagateDiscoveryErrors: true })) {
46
46
  rootByNamespace.set(root.namespace, root.rootDir);
47
47
  }
48
48
  resolved = [...rootByNamespace.keys()];
@@ -4,6 +4,7 @@ import { access, mkdir, readFile, readdir, stat, unlink, writeFile } from "node:
4
4
  import { lintWorkspaceFiles } from "./hygiene.js";
5
5
  import { parseConfig } from "./config.js";
6
6
  import { summarizeExtractionLiveness, type ExtractionBufferSource } from "./extraction-liveness.js";
7
+ import { readAggregateExtractionWatermark } from "./orchestration/extraction-watermark.js";
7
8
  import type { OperatorDoctorCheck } from "./operator-doctor-types.js";
8
9
  import { readEnvVar, resolveHomeDir } from "./runtime/env.js";
9
10
  import { resolvePluginEntry } from "./plugin-entry-resolver.js";
@@ -53,6 +54,7 @@ import type {
53
54
  DreamsPhasesConfig,
54
55
  FileHygieneConfig,
55
56
  MemoryFile,
57
+ MetaState,
56
58
  PluginConfig,
57
59
  } from "./types.js";
58
60
  import { reportBufferSurpriseDistribution } from "./buffer-surprise-report.js";
@@ -155,12 +157,12 @@ interface ConversationIndexLike {
155
157
  }>;
156
158
  };
157
159
  }
158
-
159
160
  export interface OperatorToolkitOrchestrator extends ConversationIndexLike {
160
161
  config: PluginConfig;
161
162
  storage: StorageManager;
162
163
  qmd: QmdRuntimeLike;
163
164
  buffer?: ExtractionBufferSource;
165
+ getStorage?(namespace: string): Promise<StorageManager>;
164
166
  }
165
167
 
166
168
  export interface OperatorConfigLoadResult {
@@ -1496,11 +1498,10 @@ export async function runOperatorDoctor(options: OperatorDoctorOptions): Promise
1496
1498
  checks.push(await summarizeGraphEdgeDecayStatus(config));
1497
1499
 
1498
1500
  // Tier distribution (issue #686 retention-completion).
1499
- // Shows hot/cold counts, per-status breakdown, and forgotten-memory count.
1500
- // Informational only — never errors, never blocks doctor from returning ok.
1501
1501
  checks.push(await summarizeTierDistribution(options.orchestrator.storage));
1502
- checks.push(await summarizeDreamsPhases(config, storage));
1503
- checks.push(await summarizeExtractionLiveness(config, storage, options.orchestrator.buffer));
1502
+ checks.push(await summarizeDreamsPhases(config, storage, meta));
1503
+ const extractionWatermark = await readAggregateExtractionWatermark({ config, rootStorage: storage, rootMeta: meta, storageForNamespace: (ns, rootDir) => options.orchestrator.getStorage?.(ns) ?? new StorageManager(rootDir) });
1504
+ checks.push(await summarizeExtractionLiveness(config, extractionWatermark, options.orchestrator.buffer));
1504
1505
  checks.push(...(await summarizeCorpusAndReplica(config, (d) => new StorageManager(d), options.resolveSecretRef)));
1505
1506
  // Security mitigation status (issue #565).
1506
1507
  // Reports whether the cross-namespace budget and anomaly detection
@@ -1898,11 +1899,10 @@ export async function summarizeTierDistribution(
1898
1899
  export async function summarizeDreamsPhases(
1899
1900
  config: Pick<PluginConfig, "memoryDir" | "dreamsPhases">,
1900
1901
  storage: StorageManager = new StorageManager(config.memoryDir),
1902
+ loadedMeta?: MetaState,
1901
1903
  ): Promise<OperatorDoctorCheck> {
1902
1904
  const phases: DreamsPhasesConfig = config.dreamsPhases;
1903
-
1904
- // Load meta.json for best-available last-run timestamps.
1905
- const meta = await storage.loadMeta();
1905
+ const meta = loadedMeta ?? (await storage.loadMeta());
1906
1906
 
1907
1907
  let deepSleepLastRun: string | null = null;
1908
1908
  let deepSleepLastRunWarning: string | null = null;
@@ -0,0 +1,188 @@
1
+ import path from "node:path";
2
+
3
+ import { capabilityAllowsNamespace, type TokenCapabilities } from "../access-token-capabilities.js";
4
+ import { resolveNamespaceCapabilities } from "../capabilities.js";
5
+ import { resolveCorpusNamespaceRoots, type CorpusNamespaceRoot } from "../corpus-watermark.js";
6
+ import { normalizeNamespaceIdentity } from "../namespaces/identity.js";
7
+ import type { ExtractionRootStats, ExtractionWatermarkRead } from "../extraction-liveness.js";
8
+ import type { MetaState, PluginConfig } from "../types.js";
9
+
10
+ export interface ExtractionWatermarkMeta extends Pick<MetaState, "lastExtractionAt"> {
11
+ extractionCount?: number;
12
+ lastConsolidationAt?: string | null;
13
+ }
14
+
15
+ export interface ExtractionWatermarkStorage {
16
+ readonly dir: string;
17
+ loadMeta(): Promise<ExtractionWatermarkMeta>;
18
+ }
19
+
20
+ export interface ExtractionNamespaceRootCache {
21
+ getResolvedRootsStatus(compute: () => Promise<CorpusNamespaceRoot[]>): {
22
+ roots: CorpusNamespaceRoot[] | undefined;
23
+ refreshError: unknown;
24
+ };
25
+ }
26
+
27
+ export interface AggregateExtractionWatermarkOptions {
28
+ config: PluginConfig;
29
+ rootStorage: ExtractionWatermarkStorage;
30
+ rootMeta?: ExtractionWatermarkMeta;
31
+ storageForNamespace(
32
+ namespace: string,
33
+ rootDir: string
34
+ ): ExtractionWatermarkStorage | Promise<ExtractionWatermarkStorage>;
35
+ rootsCache?: ExtractionNamespaceRootCache;
36
+ caps?: TokenCapabilities;
37
+ }
38
+
39
+ function readFailure(reason: string, rootStats?: ExtractionRootStats): ExtractionWatermarkRead {
40
+ return {
41
+ lastExtractionAt: null,
42
+ readFailed: true,
43
+ readError: reason,
44
+ ...(rootStats ? { rootStats } : {}),
45
+ };
46
+ }
47
+
48
+ function errorMessage(error: unknown): string {
49
+ return error instanceof Error ? error.message : String(error);
50
+ }
51
+
52
+ function watermarkFromMeta(meta: ExtractionWatermarkMeta, name: string): ExtractionWatermarkRead {
53
+ if (meta.lastExtractionAt !== null && meta.lastExtractionAt !== undefined) {
54
+ const parsed = Date.parse(meta.lastExtractionAt);
55
+ if (!Number.isFinite(parsed)) {
56
+ return readFailure(`${name} watermark timestamp invalid`);
57
+ }
58
+ }
59
+ const hasRootStats = meta.extractionCount !== undefined || meta.lastConsolidationAt !== undefined;
60
+ return {
61
+ lastExtractionAt: meta.lastExtractionAt ?? null,
62
+ readFailed: false,
63
+ ...(hasRootStats
64
+ ? {
65
+ rootStats: {
66
+ extractionCount: meta.extractionCount,
67
+ lastConsolidationAt: meta.lastConsolidationAt,
68
+ },
69
+ }
70
+ : {}),
71
+ };
72
+ }
73
+
74
+ async function readWatermark(storage: ExtractionWatermarkStorage, name: string): Promise<ExtractionWatermarkRead> {
75
+ try {
76
+ return watermarkFromMeta(await storage.loadMeta(), name);
77
+ } catch (error) {
78
+ return readFailure(`${name} watermark unreadable: ${errorMessage(error)}`);
79
+ }
80
+ }
81
+
82
+ async function resolveRoots(
83
+ options: AggregateExtractionWatermarkOptions
84
+ ): Promise<CorpusNamespaceRoot[] | ExtractionWatermarkRead> {
85
+ const compute = () =>
86
+ resolveCorpusNamespaceRoots({
87
+ config: options.config,
88
+ propagateDiscoveryErrors: true,
89
+ });
90
+ if (options.rootsCache) {
91
+ const { roots, refreshError } = options.rootsCache.getResolvedRootsStatus(compute);
92
+ if (refreshError !== undefined) {
93
+ return readFailure(`namespace watermark enumeration failed: ${errorMessage(refreshError)}`);
94
+ }
95
+ return roots ?? { lastExtractionAt: null, readFailed: false, pending: true };
96
+ }
97
+ try {
98
+ return await compute();
99
+ } catch (error) {
100
+ return readFailure(`namespace watermark enumeration failed: ${errorMessage(error)}`);
101
+ }
102
+ }
103
+
104
+ function isReadFailure(value: CorpusNamespaceRoot[] | ExtractionWatermarkRead): value is ExtractionWatermarkRead {
105
+ return !Array.isArray(value);
106
+ }
107
+
108
+ function newerWatermark(current: string | null, candidate: string | null): string | null {
109
+ if (candidate === null) return current;
110
+ const candidateMs = Date.parse(candidate);
111
+ if (!Number.isFinite(candidateMs)) return current;
112
+ if (current === null) return candidate;
113
+ const currentMs = Date.parse(current);
114
+ return !Number.isFinite(currentMs) || candidateMs > currentMs ? candidate : current;
115
+ }
116
+
117
+ export async function readAggregateExtractionWatermark(
118
+ options: AggregateExtractionWatermarkOptions
119
+ ): Promise<ExtractionWatermarkRead> {
120
+ if (!resolveNamespaceCapabilities(options.config).namespaces) {
121
+ return options.rootMeta
122
+ ? watermarkFromMeta(options.rootMeta, "root store")
123
+ : readWatermark(options.rootStorage, "root store");
124
+ }
125
+
126
+ const resolved = await resolveRoots(options);
127
+ if (isReadFailure(resolved)) return resolved;
128
+
129
+ const rootDir = path.resolve(options.rootStorage.dir);
130
+ const seenDirs = new Set<string>([rootDir]);
131
+ const targets: CorpusNamespaceRoot[] = [];
132
+ for (const root of resolved) {
133
+ if (
134
+ options.caps &&
135
+ !root.namespaces.some((ns) =>
136
+ capabilityAllowsNamespace(options.caps, normalizeNamespaceIdentity(ns)),
137
+ )
138
+ ) {
139
+ continue;
140
+ }
141
+ const resolvedDir = path.resolve(root.rootDir);
142
+ if (seenDirs.has(resolvedDir)) continue;
143
+ seenDirs.add(resolvedDir);
144
+ targets.push(root);
145
+ }
146
+
147
+ const defaultNamespace = normalizeNamespaceIdentity(options.config.defaultNamespace);
148
+ const hasMigratedDefault = resolved.some(
149
+ (root) =>
150
+ path.resolve(root.rootDir) !== rootDir &&
151
+ root.namespaces.some((namespace) => normalizeNamespaceIdentity(namespace) === defaultNamespace),
152
+ );
153
+ const canAccessRoot =
154
+ !hasMigratedDefault &&
155
+ (!options.caps || capabilityAllowsNamespace(options.caps, defaultNamespace));
156
+ let rootRead: ExtractionWatermarkRead = { lastExtractionAt: null, readFailed: false };
157
+ if (canAccessRoot) {
158
+ rootRead = await readWatermark(options.rootStorage, "root store");
159
+ if (rootRead.readFailed) return rootRead;
160
+ }
161
+ let lastExtractionAt = rootRead.lastExtractionAt;
162
+
163
+ const reads = await Promise.all(
164
+ targets.map(async (target) => {
165
+ try {
166
+ const storage = await options.storageForNamespace(target.namespace, target.rootDir);
167
+ return await readWatermark(storage, "namespace");
168
+ } catch (error) {
169
+ return readFailure(`namespace watermark storage unavailable: ${errorMessage(error)}`);
170
+ }
171
+ })
172
+ );
173
+
174
+ for (const read of reads) {
175
+ if (read.readFailed) {
176
+ return readFailure(
177
+ read.readError ?? "namespace watermark unreadable",
178
+ rootRead.rootStats
179
+ );
180
+ }
181
+ lastExtractionAt = newerWatermark(lastExtractionAt, read.lastExtractionAt);
182
+ }
183
+ return {
184
+ lastExtractionAt,
185
+ readFailed: false,
186
+ ...(rootRead.rootStats ? { rootStats: rootRead.rootStats } : {}),
187
+ };
188
+ }
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/extraction-liveness.ts"],"sourcesContent":["/**\n * Extraction-pipeline liveness (issue #2151).\n *\n * A daemon's implicit extraction can fail continuously for months while\n * `/health` stays green and recall keeps serving: every individual failure is\n * logged (timeouts, fallback-no-parsed-output), but nothing aggregates them\n * into a checkable status. This module surfaces a liveness *watermark* — the\n * last successful extraction plus the current buffer backlog — and decides when\n * that watermark is stale enough to call the pipeline degraded.\n *\n * The §22 error-vs-empty principle applies at the pipeline level: \"no\n * extraction succeeded for 90 days\" (a non-empty buffer with a stale/absent\n * watermark) must be distinguishable from \"nothing to extract\" (an empty\n * buffer). Degradation therefore requires a NON-EMPTY buffer — an idle daemon\n * with nothing buffered is healthy, not degraded.\n *\n * The core decision (`evaluateExtractionLiveness`) is a pure function shared by\n * every surface (authenticated `/health`, `remnic doctor`, `remnic stats`) so\n * the verdict never diverges across code paths.\n */\nimport { coerceBool, coerceNumber } from \"./connectors/coerce.js\";\nimport { log } from \"./logger.js\";\nimport type { OperatorDoctorCheck } from \"./operator-doctor-types.js\";\nimport type { MetaState, PluginConfig } from \"./types.js\";\n\n/** Default staleness window: 24h. A watermark older than this with a non-empty buffer is degraded. */\nconst DEFAULT_STALE_WINDOW_MS = 86_400_000;\n\nexport interface ExtractionLivenessConfig {\n /** Master gate. When false, liveness is never reported degraded. Default true. */\n enabled: boolean;\n /**\n * How stale the last-successful-extraction watermark may get (ms) before a\n * non-empty buffer flags the pipeline degraded. Default 24h.\n */\n staleWindowMs: number;\n}\n\n/**\n * A read-only snapshot of buffered, not-yet-extracted work. Structurally\n * satisfied by `SmartBuffer.getBufferSnapshot()` so callers can pass the live\n * buffer without this module depending on the buffer implementation.\n */\nexport interface ExtractionBufferSnapshot {\n bufferedSessionCount: number;\n pendingTurnCount: number;\n oldestTurnTimestamp: string | null;\n /**\n * Set by the liveness reader (never by `SmartBuffer`) when the buffer exists\n * but its snapshot read threw. An unreadable buffer is a pipeline fault, not\n * an empty queue (§22): it degrades the pipeline with a distinct reason\n * instead of masquerading as a zero-backlog (healthy) snapshot.\n */\n readFailed?: boolean;\n /** Read-failure detail, surfaced in the degraded reason when `readFailed`. */\n readError?: string;\n}\n\nexport interface ExtractionBufferSource {\n getBufferSnapshot(): Promise<ExtractionBufferSnapshot>;\n}\n\n/**\n * The liveness payload surfaced on `/health.extraction` and in the doctor/stats\n * details.\n *\n * DAEMON-SCOPED SIGNAL: a daemon exposes a single extraction verdict; the\n * last-extraction watermark is read from the daemon's default/root store, so\n * `/health` returns the same `extraction` block for every namespace argument.\n *\n * KNOWN LIMITATION (issue #2159): extraction stamps `lastExtractionAt` on the\n * PER-NAMESPACE store (`storageFor(selfNamespace)`), so this watermark reflects\n * only extraction that stamped the root store (default-namespace work). On a\n * single-namespace deployment (the common case) the watermark and buffer share\n * one scope and the verdict is exact. On a multi-namespace deployment the verdict\n * is NOT guaranteed correct for work isolated to a non-default namespace: it can\n * over-report `degraded` (the default namespace idle while another is extracting)\n * or miss a stall confined to a non-default namespace. Aggregating the watermark\n * across namespace stores is tracked in #2159.\n */\nexport interface ExtractionLivenessStatus {\n lastExtractionAt: string | null;\n bufferedSessionCount: number;\n pendingTurnCount: number;\n oldestBufferedTurnAgeMs: number | null;\n degraded: boolean;\n degradedReason: string | null;\n /**\n * Scope of the last-extraction watermark: `root-store` today (read from the\n * daemon's default/root store only), `aggregate` once it is resolved across\n * every namespace store (#2159). A monitor can alert on\n * `watermarkScope !== \"aggregate\"` while namespaces are enabled instead of\n * trusting a number that may be wrong in either direction.\n */\n watermarkScope: \"root-store\" | \"aggregate\";\n}\n\ninterface ExtractionLivenessStorageLike {\n loadMeta(): Promise<Pick<MetaState, \"lastExtractionAt\">>;\n}\n\ninterface ExtractionLivenessOrchestratorLike {\n config: Pick<PluginConfig, \"extractionLiveness\">;\n buffer?: ExtractionBufferSource;\n}\n\n/**\n * Parse the `extractionLiveness` config block. Follows the nested-block shape\n * validation used elsewhere in `config.ts` and coerces string booleans (§24:\n * CLI/JSON deliver `\"false\"`/`\"0\"` as strings, which must read as falsy).\n */\nexport function parseExtractionLivenessConfig(\n cfg: Record<string, unknown>,\n): ExtractionLivenessConfig {\n const raw = cfg.extractionLiveness;\n if (raw !== undefined && (raw === null || typeof raw !== \"object\" || Array.isArray(raw))) {\n throw new Error(`extractionLiveness must be a plain object (got ${JSON.stringify(raw)})`);\n }\n const block = (raw ?? {}) as Record<string, unknown>;\n return {\n // `?? true` keeps the default on when the key is absent while honoring\n // explicit \"false\"/\"0\"/false opt-outs (coerceBool handles the string forms).\n enabled: coerceBool(block.enabled) ?? true,\n staleWindowMs: parseStaleWindowMs(block.staleWindowMs),\n };\n}\n\n/**\n * Parse `extractionLiveness.staleWindowMs`. Absent (`undefined`) → the 24h\n * default; any PRESENT value (including an explicit `null`) must coerce to a\n * positive INTEGER of milliseconds, else THROW. A fractional or non-positive\n * value (\"0.5\" would floor to 0, making every backlog instantly stale; 1.9 would\n * floor to 1) is rejected, never floored/reinterpreted (§1/§17/§39). Mirrors\n * config.ts's `parseIntegerInClosedRange` (round 9 finding 1): only an absent key\n * falls back; an explicit `null` is invalid input, not \"use the default\".\n * Inlined rather than imported because config.ts already imports this module\n * (importing back would be circular), the same reason `recall-concurrency-config.ts`\n * inlines its numeric validation.\n */\nfunction parseStaleWindowMs(value: unknown): number {\n // Only an absent key (undefined) falls back to the default; an explicit `null`\n // is invalid input and proceeds to validation → throw (mirrors\n // parseIntegerInClosedRange, round 9 finding 1).\n if (value === undefined) return DEFAULT_STALE_WINDOW_MS;\n const coerced = coerceNumber(value);\n if (coerced === undefined || !Number.isFinite(coerced) || !Number.isInteger(coerced) || coerced < 1) {\n throw new Error(\n `extractionLiveness.staleWindowMs must be an integer greater than or equal to 1; got ${JSON.stringify(value)}`,\n );\n }\n return coerced;\n}\n\n/** Milliseconds between `timestamp` and `nowMs`, clamped at 0; null when unparsable/absent. */\nfunction ageMsFrom(timestamp: string | null, nowMs: number): number | null {\n if (typeof timestamp !== \"string\") return null;\n const parsed = Date.parse(timestamp);\n if (!Number.isFinite(parsed)) return null;\n return Math.max(0, nowMs - parsed);\n}\n\n/** Compact human-readable duration (\"3d\", \"5h\", \"12m\", \"45s\") for logs and CLI output. */\nexport function formatAgeMs(ms: number): string {\n const s = Math.max(0, Math.floor(ms / 1000));\n if (s >= 86_400) return `${Math.floor(s / 86_400)}d`;\n if (s >= 3_600) return `${Math.floor(s / 3_600)}h`;\n if (s >= 60) return `${Math.floor(s / 60)}m`;\n return `${s}s`;\n}\n\n/**\n * Pure liveness verdict. Degraded when the feature is enabled AND any of: the\n * last-extraction watermark could not be READ (a storage fault, §22), the buffer\n * read failed (a pipeline fault, §22), or the buffer is non-empty and the\n * watermark is absent or stale. Each cause yields a DISTINCT reason so an\n * operator can tell a meta-read failure from a buffer-read failure from a\n * pipeline that has genuinely never extracted.\n *\n * Staleness uses a half-open freshness window (§23): an extraction is fresh\n * while its age is in `[0, staleWindowMs)`, so an age of EXACTLY `staleWindowMs`\n * is stale (the upper bound on \"fresh\" is exclusive). A null/unparsable watermark\n * means \"never succeeded\" and is treated as stale — as is a FUTURE watermark (a\n * clock-skewed or corrupt timestamp ahead of now must not read as a fresh\n * extraction and hide a real backlog stall).\n */\nexport function evaluateExtractionLiveness(input: {\n config: ExtractionLivenessConfig;\n lastExtractionAt: string | null;\n snapshot: ExtractionBufferSnapshot;\n nowMs: number;\n metaReadFailed?: boolean;\n metaReadError?: string;\n watermarkScope?: \"root-store\" | \"aggregate\";\n}): ExtractionLivenessStatus {\n const { config, lastExtractionAt, snapshot, nowMs } = input;\n const lastMs = lastExtractionAt !== null ? Date.parse(lastExtractionAt) : Number.NaN;\n const hasWatermark = Number.isFinite(lastMs);\n const ageMs = nowMs - lastMs;\n // A future watermark (negative age) is clock-skewed or corrupt data, not a\n // fresh extraction: treat it as stale so a real backlog stall is not hidden.\n const stale = !hasWatermark || ageMs < 0 || ageMs >= config.staleWindowMs;\n const hasBacklog = snapshot.bufferedSessionCount > 0;\n // A watermark or buffer that cannot be READ is a fault, not an empty queue\n // (§22): a storage/pipeline outage must not read as healthy, and must stay\n // distinct from a pipeline that has genuinely never extracted.\n const metaReadFailed = input.metaReadFailed === true;\n const readFailed = snapshot.readFailed === true;\n const degraded = config.enabled && (metaReadFailed || readFailed || (hasBacklog && stale));\n\n let degradedReason: string | null = null;\n if (degraded) {\n if (metaReadFailed) {\n degradedReason = `extraction watermark unreadable: ${input.metaReadError ?? \"meta read failed\"}`;\n } else if (readFailed) {\n degradedReason = `extraction buffer unreadable: ${snapshot.readError ?? \"buffer snapshot read failed\"}`;\n } else {\n const watermark = hasWatermark\n ? `last succeeded ${formatAgeMs(nowMs - lastMs)} ago`\n : \"no successful extraction on record\";\n degradedReason =\n `${watermark}; ${snapshot.bufferedSessionCount} buffered session(s), ` +\n `${snapshot.pendingTurnCount} turn(s) pending extraction`;\n }\n }\n\n return {\n lastExtractionAt,\n bufferedSessionCount: snapshot.bufferedSessionCount,\n pendingTurnCount: snapshot.pendingTurnCount,\n oldestBufferedTurnAgeMs: ageMsFrom(snapshot.oldestTurnTimestamp, nowMs),\n degraded,\n degradedReason,\n watermarkScope: input.watermarkScope ?? \"root-store\",\n };\n}\n\nconst EMPTY_SNAPSHOT: ExtractionBufferSnapshot = {\n bufferedSessionCount: 0,\n pendingTurnCount: 0,\n oldestTurnTimestamp: null,\n};\n\n/**\n * Read a buffer snapshot without throwing. An ABSENT buffer degrades to an empty\n * (healthy) snapshot — some service constructions have no orchestrator buffer. A\n * buffer that EXISTS but whose read throws yields a `readFailed` snapshot so the\n * verdict can distinguish a pipeline fault from an empty queue (§22).\n */\nasync function readBufferSnapshot(\n buffer: ExtractionBufferSource | undefined,\n): Promise<ExtractionBufferSnapshot> {\n if (!buffer || typeof buffer.getBufferSnapshot !== \"function\") return EMPTY_SNAPSHOT;\n try {\n return await buffer.getBufferSnapshot();\n } catch (err) {\n return {\n ...EMPTY_SNAPSHOT,\n readFailed: true,\n readError: err instanceof Error ? err.message : String(err),\n };\n }\n}\n\n/**\n * Gather the liveness status from a meta store (last-extraction watermark) and\n * an optional buffer (backlog). A read failure on EITHER side is captured and\n * surfaced as a DEGRADED status with a distinct reason (§22) rather than being\n * swallowed into a healthy-looking verdict; no failure path throws.\n */\nexport async function gatherExtractionLivenessStatus(input: {\n config: ExtractionLivenessConfig;\n storage: ExtractionLivenessStorageLike;\n buffer: ExtractionBufferSource | undefined;\n nowMs: number;\n}): Promise<ExtractionLivenessStatus> {\n const { config, storage, buffer, nowMs } = input;\n let lastExtractionAt: string | null = null;\n let metaReadFailed = false;\n let metaReadError: string | undefined;\n try {\n lastExtractionAt = (await storage.loadMeta()).lastExtractionAt ?? null;\n } catch (err) {\n // A swallowed loadMeta() failure that reads as \"never extracted\" is the\n // exact §22 conflation this feature exists to kill — surface it explicitly.\n metaReadFailed = true;\n metaReadError = err instanceof Error ? err.message : String(err);\n }\n const snapshot = await readBufferSnapshot(buffer);\n return evaluateExtractionLiveness({\n config,\n lastExtractionAt,\n snapshot,\n nowMs,\n metaReadFailed,\n metaReadError,\n // Today the watermark comes from the root store only; #2159 flips this to\n // \"aggregate\" when the resolver reads across every namespace store.\n watermarkScope: \"root-store\",\n });\n}\n\n/**\n * Aggregated-WARN throttle (issue #2151): emit at most ONE warning per\n * staleness window while degraded — not one line per failed extraction attempt.\n * State is instance-scoped (held by the owning service), never a module global\n * (§5), so multiple service instances throttle independently.\n */\nexport class ExtractionLivenessWarnThrottle {\n private lastWarnAtMs: number | null = null;\n\n /** Warn if degraded and outside the throttle window; returns whether a WARN was emitted. */\n maybeWarn(status: ExtractionLivenessStatus, staleWindowMs: number, nowMs: number): boolean {\n if (!status.degraded) {\n // Recovered (or never degraded): reset so a fresh episode warns at once.\n this.lastWarnAtMs = null;\n return false;\n }\n if (this.lastWarnAtMs !== null && nowMs - this.lastWarnAtMs < staleWindowMs) return false;\n this.lastWarnAtMs = nowMs;\n log.warn(\n `extraction pipeline liveness degraded: ${status.degradedReason ?? \"buffered turns are not being extracted\"}`,\n );\n return true;\n }\n}\n\n/**\n * Normalize the `extractionLiveness` block at the read boundary. `parseConfig`\n * always populates it, but a host adapter, an older persisted config, or a\n * hand-built `PluginConfig` can hand us an absent, partial, or loosely-typed\n * block - and every liveness surface (/health, doctor, stats) must degrade to\n * the documented default (enabled, 24h window) rather than throw. Both fields\n * are coerced with the same rules as `parseExtractionLivenessConfig` (§24:\n * `\"false\"`/`\"0\"` read as falsy; a numeric string like `\"5000\"` parses), except a\n * present but non-integer or non-positive `staleWindowMs` falls back to the\n * default here rather than throwing.\n */\nexport function resolveExtractionLivenessConfig(\n block: { enabled?: unknown; staleWindowMs?: unknown } | undefined,\n): ExtractionLivenessConfig {\n const staleWindowMs = coerceNumber(block?.staleWindowMs);\n return {\n enabled: coerceBool(block?.enabled) ?? true,\n staleWindowMs:\n staleWindowMs !== undefined && Number.isInteger(staleWindowMs) && staleWindowMs >= 1\n ? staleWindowMs\n : DEFAULT_STALE_WINDOW_MS,\n };\n}\n\n/**\n * Compute the liveness status for the authenticated `/health` payload and emit\n * the throttled aggregated WARN.\n *\n * The watermark is read from the daemon's default/root store (`orchestrator.storage`),\n * which is why `/health` returns the same `extraction` block for any namespace\n * argument. KNOWN LIMITATION (issue #2159): extraction writes `lastExtractionAt`\n * per-namespace, so this watermark reflects only default-namespace extraction and\n * the verdict is exact only for a single-namespace daemon (see\n * `ExtractionLivenessStatus`).\n */\nexport async function computeExtractionLivenessStatus(\n orchestrator: ExtractionLivenessOrchestratorLike & { storage: ExtractionLivenessStorageLike },\n throttle?: ExtractionLivenessWarnThrottle,\n nowMs: number = Date.now(),\n): Promise<ExtractionLivenessStatus> {\n const config = resolveExtractionLivenessConfig(orchestrator.config.extractionLiveness);\n const status = await gatherExtractionLivenessStatus({\n config,\n storage: orchestrator.storage,\n buffer: orchestrator.buffer,\n nowMs,\n });\n throttle?.maybeWarn(status, config.staleWindowMs, nowMs);\n return status;\n}\n\n/**\n * `remnic doctor` check for extraction-pipeline liveness. Status `warn` when\n * degraded (with a remediation hint), `ok` otherwise.\n */\nexport async function summarizeExtractionLiveness(\n config: Pick<PluginConfig, \"extractionLiveness\">,\n storage: ExtractionLivenessStorageLike,\n buffer?: ExtractionBufferSource,\n nowMs: number = Date.now(),\n): Promise<OperatorDoctorCheck> {\n const livenessConfig = resolveExtractionLivenessConfig(config.extractionLiveness);\n const status = await gatherExtractionLivenessStatus({\n config: livenessConfig,\n storage,\n buffer,\n nowMs,\n });\n const scopeNote =\n ` Watermark scope: ${status.watermarkScope}` +\n (status.watermarkScope === \"root-store\"\n ? \" (default-namespace only; multi-namespace aggregation tracked in #2159).\"\n : \".\");\n const summary =\n (status.degraded\n ? `Extraction pipeline degraded: ${status.degradedReason}.`\n : `Extraction pipeline healthy: last extraction ${status.lastExtractionAt ?? \"never\"}, ` +\n `${status.bufferedSessionCount} buffered session(s), ${status.pendingTurnCount} turn(s) pending` +\n `${livenessConfig.enabled ? \"\" : \" (liveness check disabled)\"}.`) + scopeNote;\n return {\n key: \"extraction_liveness\",\n status: status.degraded ? \"warn\" : \"ok\",\n summary,\n remediation: status.degraded\n ? \"Extraction has stalled while turns are buffered. Inspect daemon logs for extraction \" +\n \"timeouts or fallback-no-parsed-output errors, verify the extraction model/provider is \" +\n \"reachable, then force a flush (e.g. `remnic flush`).\"\n : undefined,\n details: { ...status, staleWindowMs: livenessConfig.staleWindowMs, enabled: livenessConfig.enabled },\n };\n}\n\n/** Meta fields the `remnic stats` view renders directly, beyond the liveness watermark. */\ntype ExtractionStatsMeta = Pick<MetaState, \"extractionCount\" | \"lastExtractionAt\" | \"lastConsolidationAt\">;\n\n/**\n * Lines for `remnic stats`: extraction watermark, buffer backlog, and the\n * liveness verdict so dashboards can alert on a stalled pipeline. The meta\n * watermark is loaded HERE (not by the caller) so a meta-read failure surfaces\n * as an explicit DEGRADED verdict plus \"unavailable\" counts (§22) instead of\n * crashing the whole `stats` command.\n */\nexport async function renderExtractionLivenessStats(\n orchestrator: ExtractionLivenessOrchestratorLike & { storage: { loadMeta(): Promise<ExtractionStatsMeta> } },\n nowMs: number = Date.now(),\n): Promise<string[]> {\n let meta: ExtractionStatsMeta | null = null;\n let metaReadFailed = false;\n let metaReadError: string | undefined;\n try {\n meta = await orchestrator.storage.loadMeta();\n } catch (err) {\n metaReadFailed = true;\n metaReadError = err instanceof Error ? err.message : String(err);\n }\n const status = evaluateExtractionLiveness({\n config: resolveExtractionLivenessConfig(orchestrator.config.extractionLiveness),\n lastExtractionAt: meta?.lastExtractionAt ?? null,\n snapshot: await readBufferSnapshot(orchestrator.buffer),\n nowMs,\n metaReadFailed,\n metaReadError,\n });\n const oldestAge =\n status.oldestBufferedTurnAgeMs !== null ? formatAgeMs(status.oldestBufferedTurnAgeMs) : \"n/a\";\n const unavailable = metaReadFailed ? \"unavailable\" : \"never\";\n return [\n `Extractions: ${meta?.extractionCount ?? unavailable}`,\n `Last extraction: ${meta?.lastExtractionAt ?? unavailable}`,\n `Last consolidation: ${meta?.lastConsolidationAt ?? unavailable}`,\n `Buffered sessions: ${status.bufferedSessionCount} (${status.pendingTurnCount} turns pending)`,\n `Oldest buffered turn age: ${oldestAge}`,\n `Extraction watermark scope: ${status.watermarkScope}`,\n `Extraction liveness: ${status.degraded ? `DEGRADED — ${status.degradedReason}` : \"ok\"}`,\n ];\n}\n"],"mappings":";;;;;;;;;AA0BA,IAAM,0BAA0B;AAqFzB,SAAS,8BACd,KAC0B;AAC1B,QAAM,MAAM,IAAI;AAChB,MAAI,QAAQ,WAAc,QAAQ,QAAQ,OAAO,QAAQ,YAAY,MAAM,QAAQ,GAAG,IAAI;AACxF,UAAM,IAAI,MAAM,kDAAkD,KAAK,UAAU,GAAG,CAAC,GAAG;AAAA,EAC1F;AACA,QAAM,QAAS,OAAO,CAAC;AACvB,SAAO;AAAA;AAAA;AAAA,IAGL,SAAS,WAAW,MAAM,OAAO,KAAK;AAAA,IACtC,eAAe,mBAAmB,MAAM,aAAa;AAAA,EACvD;AACF;AAcA,SAAS,mBAAmB,OAAwB;AAIlD,MAAI,UAAU,OAAW,QAAO;AAChC,QAAM,UAAU,aAAa,KAAK;AAClC,MAAI,YAAY,UAAa,CAAC,OAAO,SAAS,OAAO,KAAK,CAAC,OAAO,UAAU,OAAO,KAAK,UAAU,GAAG;AACnG,UAAM,IAAI;AAAA,MACR,uFAAuF,KAAK,UAAU,KAAK,CAAC;AAAA,IAC9G;AAAA,EACF;AACA,SAAO;AACT;AAGA,SAAS,UAAU,WAA0B,OAA8B;AACzE,MAAI,OAAO,cAAc,SAAU,QAAO;AAC1C,QAAM,SAAS,KAAK,MAAM,SAAS;AACnC,MAAI,CAAC,OAAO,SAAS,MAAM,EAAG,QAAO;AAC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