@remnic/core 10.0.174 → 10.0.175

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 (222) hide show
  1. package/dist/access-admin-ops-surface.js +68 -67
  2. package/dist/access-audit.js +2 -2
  3. package/dist/access-cli.js +68 -67
  4. package/dist/access-cli.js.map +1 -1
  5. package/dist/access-extraction-force-flush-preempt.js +68 -67
  6. package/dist/access-extraction-force-flush.js +68 -67
  7. package/dist/access-http-briefing.js +68 -67
  8. package/dist/access-http-query.js +68 -67
  9. package/dist/access-http.js +68 -67
  10. package/dist/access-identity-continuity-surface.js +68 -67
  11. package/dist/access-lcm-surface.js +68 -67
  12. package/dist/access-mcp.js +68 -67
  13. package/dist/access-observe-write-surface.js +68 -67
  14. package/dist/access-operations-batch.js +68 -67
  15. package/dist/access-operations.js +68 -67
  16. package/dist/access-recall-concurrency.js +68 -67
  17. package/dist/access-recall-response.js +68 -67
  18. package/dist/access-recall-surface.js +68 -67
  19. package/dist/access-service.js +68 -67
  20. package/dist/active-recall.js +14 -13
  21. package/dist/active-recall.js.map +1 -1
  22. package/dist/adapters/index.js +4 -4
  23. package/dist/adapters/registry.js +2 -2
  24. package/dist/briefing.js +14 -13
  25. package/dist/buffer.js +9 -8
  26. package/dist/causal-consolidation.js +15 -14
  27. package/dist/causal-consolidation.js.map +1 -1
  28. package/dist/{chunk-IO4AAVYZ.js → chunk-2EKXMZ6E.js} +2 -2
  29. package/dist/{chunk-TOQK5A4Y.js → chunk-2LXROA34.js} +6 -6
  30. package/dist/{chunk-IUM3VSHI.js → chunk-2WREX7KD.js} +10 -1
  31. package/dist/chunk-2WREX7KD.js.map +1 -0
  32. package/dist/{chunk-Y2LZW3EQ.js → chunk-2ZWTTXMV.js} +2 -2
  33. package/dist/{chunk-IHB3JO4B.js → chunk-3FS6IVSU.js} +2 -2
  34. package/dist/{chunk-UBQ2ZOWA.js → chunk-3SP7EZWA.js} +2 -2
  35. package/dist/{chunk-4PBHMJRC.js → chunk-4GI2IGUK.js} +2 -2
  36. package/dist/{chunk-HHVK2JRE.js → chunk-4TPU36X4.js} +2 -2
  37. package/dist/{chunk-DMPZABKG.js → chunk-4TZOOUMK.js} +2 -2
  38. package/dist/{chunk-5MTKGNZ5.js → chunk-5RBHL5TF.js} +121 -41
  39. package/dist/chunk-5RBHL5TF.js.map +1 -0
  40. package/dist/{chunk-HR3DKJCU.js → chunk-6SROXED4.js} +2 -2
  41. package/dist/{chunk-L3DDKXQJ.js → chunk-76LDFLAG.js} +2 -2
  42. package/dist/{chunk-5RONA5FF.js → chunk-7DFJ4JX2.js} +4 -4
  43. package/dist/{chunk-OK3X3TBR.js → chunk-7L73PLRG.js} +2 -2
  44. package/dist/{chunk-WKNMKV52.js → chunk-AQ6V47Q7.js} +2 -2
  45. package/dist/{chunk-H4KIMZJD.js → chunk-B4ZA2PZC.js} +3 -3
  46. package/dist/{chunk-DLR3SBOM.js → chunk-B7GZL7PR.js} +2 -2
  47. package/dist/{chunk-XYNUEXLC.js → chunk-BAMF6J4W.js} +4 -4
  48. package/dist/{chunk-NTR72OL5.js → chunk-CXIBBZ6N.js} +2 -2
  49. package/dist/{chunk-V6UFCV6T.js → chunk-DIXXS4HS.js} +78 -78
  50. package/dist/{chunk-3DJ6R4CC.js → chunk-DLPS5YP3.js} +2 -2
  51. package/dist/{chunk-RSUNBJ4I.js → chunk-DWQAMPLW.js} +7 -7
  52. package/dist/{chunk-6OMSYPOL.js → chunk-F2XXZR6A.js} +3 -3
  53. package/dist/{chunk-OWD365QW.js → chunk-FDAXNHEX.js} +5 -5
  54. package/dist/{chunk-CY2C5LM4.js → chunk-FDLPNFKE.js} +2 -2
  55. package/dist/{chunk-KAGLV5KH.js → chunk-FTQF3G3B.js} +2 -2
  56. package/dist/{chunk-2GQVYLQK.js → chunk-FTV2C3CA.js} +2 -2
  57. package/dist/{chunk-B7HYXVME.js → chunk-FZF7JX76.js} +1 -1
  58. package/dist/chunk-FZF7JX76.js.map +1 -0
  59. package/dist/{chunk-ZKXNSPGQ.js → chunk-G77MHQFZ.js} +2 -2
  60. package/dist/{chunk-66DUCUOC.js → chunk-GGQ3CJVH.js} +2 -2
  61. package/dist/{chunk-BN5SK2RZ.js → chunk-HHKUWNHQ.js} +2 -2
  62. package/dist/{chunk-KMOH6W5B.js → chunk-HOTAHSO3.js} +3 -3
  63. package/dist/{chunk-OY3IULYL.js → chunk-IFXQGDMG.js} +2 -2
  64. package/dist/{chunk-OWBI5477.js → chunk-JUROR7PB.js} +2 -2
  65. package/dist/{chunk-4ACKO4U2.js → chunk-JXYFXVPB.js} +2 -2
  66. package/dist/{chunk-ASWECJXS.js → chunk-KYPFQO43.js} +3 -3
  67. package/dist/{chunk-4WOEEMGK.js → chunk-KZBE4KBZ.js} +2 -2
  68. package/dist/{chunk-V6MN37WG.js → chunk-MFJM35R7.js} +2 -2
  69. package/dist/{chunk-LKXW6W42.js → chunk-OTE5E44O.js} +2 -2
  70. package/dist/{chunk-KPLKABGR.js → chunk-P3SMXKFR.js} +2 -2
  71. package/dist/{chunk-27BH67PT.js → chunk-PCLTJUOY.js} +2 -2
  72. package/dist/{chunk-JDH2BA2P.js → chunk-RXAWE76Y.js} +2 -2
  73. package/dist/{chunk-IXI6S2VJ.js → chunk-S45VECVD.js} +29 -2
  74. package/dist/chunk-S45VECVD.js.map +1 -0
  75. package/dist/{chunk-WTFHZQXM.js → chunk-T3NEDSLZ.js} +3 -3
  76. package/dist/{chunk-HB2PRTXX.js → chunk-V425GW5W.js} +2 -2
  77. package/dist/{chunk-XKFL2WQO.js → chunk-V5FCMJW4.js} +2 -2
  78. package/dist/{chunk-SNI526DD.js → chunk-VR6NF6VX.js} +2 -2
  79. package/dist/{chunk-EXGY5TPU.js → chunk-W3O3OEQ7.js} +2 -2
  80. package/dist/chunk-XBJOO7G5.js +87 -0
  81. package/dist/chunk-XBJOO7G5.js.map +1 -0
  82. package/dist/{chunk-AM6H7BIY.js → chunk-YMNPQMHA.js} +2 -2
  83. package/dist/{chunk-QVXRE66C.js → chunk-ZBDTOWGX.js} +7 -7
  84. package/dist/{chunk-YCK26VSL.js → chunk-ZMEEOLQG.js} +2 -2
  85. package/dist/{chunk-R2AJAAHJ.js → chunk-ZNHLUYIT.js} +90 -16
  86. package/dist/chunk-ZNHLUYIT.js.map +1 -0
  87. package/dist/{chunk-DAOMWGO2.js → chunk-ZX5N5D6M.js} +4 -4
  88. package/dist/cli.js +68 -67
  89. package/dist/coding/export-okf-codegraph.js +13 -12
  90. package/dist/coding/export-okf-codegraph.js.map +1 -1
  91. package/dist/compounding/engine.js +15 -14
  92. package/dist/config.js +14 -13
  93. package/dist/connectors/codex-materialize-runner.js +14 -13
  94. package/dist/connectors/index.js +14 -13
  95. package/dist/convergence-refresh.js +16 -15
  96. package/dist/corpus-watermark.js +16 -15
  97. package/dist/entity-retrieval.js +14 -13
  98. package/dist/explicit-capture.js +68 -67
  99. package/dist/extraction.js +18 -17
  100. package/dist/{first-start-migration-CCZ5SM3V.js → first-start-migration-TCPK2I7J.js} +4 -4
  101. package/dist/harmonic-retrieval.js +14 -13
  102. package/dist/index.js +101 -100
  103. package/dist/lcm/index.js +3 -3
  104. package/dist/location/index.js +15 -14
  105. package/dist/maintenance/memory-governance.js +14 -13
  106. package/dist/maintenance/rebuild-memory-lifecycle-ledger.js +14 -13
  107. package/dist/maintenance/rebuild-memory-projection-runner.js +16 -15
  108. package/dist/maintenance/rebuild-memory-projection.js +15 -14
  109. package/dist/memory-browse.js +9 -8
  110. package/dist/namespaces/migrate.js +15 -14
  111. package/dist/namespaces/search.d.ts +5 -1
  112. package/dist/namespaces/search.d.ts.map +1 -1
  113. package/dist/namespaces/search.js +12 -11
  114. package/dist/namespaces/storage.js +14 -13
  115. package/dist/operator-doctor-corpus.js +17 -16
  116. package/dist/operator-toolkit.js +21 -20
  117. package/dist/orchestration/backlog-scheduler.js +69 -68
  118. package/dist/orchestration/backlog-scheduler.js.map +1 -1
  119. package/dist/orchestration/buffer-drain-runner.js +69 -68
  120. package/dist/orchestration/maintenance.js +22 -21
  121. package/dist/orchestrator.js +68 -67
  122. package/dist/qmd-daemon-session.d.ts +8 -0
  123. package/dist/qmd-daemon-session.d.ts.map +1 -1
  124. package/dist/qmd-daemon-session.js +1 -1
  125. package/dist/qmd-health-metadata.d.ts +39 -0
  126. package/dist/qmd-health-metadata.d.ts.map +1 -0
  127. package/dist/qmd-health-metadata.js +12 -0
  128. package/dist/qmd-health-metadata.js.map +1 -0
  129. package/dist/qmd-status.d.ts.map +1 -1
  130. package/dist/qmd-status.js +1 -1
  131. package/dist/qmd.d.ts +5 -1
  132. package/dist/qmd.d.ts.map +1 -1
  133. package/dist/qmd.js +8 -7
  134. package/dist/recall-composition-decision.js +2 -2
  135. package/dist/recall-navigation.js +68 -67
  136. package/dist/recall-state-view-admission.js +9 -8
  137. package/dist/recall-why-service.js +9 -8
  138. package/dist/resume-bundles.js +17 -16
  139. package/dist/search/factory.js +11 -10
  140. package/dist/search/index.js +11 -10
  141. package/dist/search/lancedb-backend.js +2 -2
  142. package/dist/search/meilisearch-backend.js +2 -2
  143. package/dist/search/orama-backend.js +2 -2
  144. package/dist/search/port.d.ts +21 -0
  145. package/dist/search/port.d.ts.map +1 -1
  146. package/dist/search/port.js +1 -1
  147. package/dist/search/remote-backend.js +2 -2
  148. package/dist/semantic-consolidation.js +15 -14
  149. package/dist/semantic-rule-promotion.js +14 -13
  150. package/dist/semantic-rule-verifier.js +14 -13
  151. package/dist/source-agent-qualifier.js +17 -16
  152. package/dist/standup/build.js +14 -13
  153. package/dist/storage.js +13 -12
  154. package/dist/transcript.js +2 -2
  155. package/dist/transfer/export-okf.js +14 -13
  156. package/dist/verified-recall.js +14 -13
  157. package/dist/who-knows-cli.js +15 -14
  158. package/dist/who-knows.js +14 -13
  159. package/package.json +2 -2
  160. package/src/namespaces/search.test.ts +320 -4
  161. package/src/namespaces/search.ts +147 -51
  162. package/src/qmd-client.test.ts +34 -3
  163. package/src/qmd-daemon-session.ts +34 -1
  164. package/src/qmd-health-metadata.test.ts +493 -0
  165. package/src/qmd-health-metadata.ts +95 -0
  166. package/src/qmd-status.ts +10 -1
  167. package/src/qmd.ts +83 -3
  168. package/src/search/port.ts +23 -0
  169. package/dist/chunk-5MTKGNZ5.js.map +0 -1
  170. package/dist/chunk-B7HYXVME.js.map +0 -1
  171. package/dist/chunk-IUM3VSHI.js.map +0 -1
  172. package/dist/chunk-IXI6S2VJ.js.map +0 -1
  173. package/dist/chunk-R2AJAAHJ.js.map +0 -1
  174. /package/dist/{chunk-IO4AAVYZ.js.map → chunk-2EKXMZ6E.js.map} +0 -0
  175. /package/dist/{chunk-TOQK5A4Y.js.map → chunk-2LXROA34.js.map} +0 -0
  176. /package/dist/{chunk-Y2LZW3EQ.js.map → chunk-2ZWTTXMV.js.map} +0 -0
  177. /package/dist/{chunk-IHB3JO4B.js.map → chunk-3FS6IVSU.js.map} +0 -0
  178. /package/dist/{chunk-UBQ2ZOWA.js.map → chunk-3SP7EZWA.js.map} +0 -0
  179. /package/dist/{chunk-4PBHMJRC.js.map → chunk-4GI2IGUK.js.map} +0 -0
  180. /package/dist/{chunk-HHVK2JRE.js.map → chunk-4TPU36X4.js.map} +0 -0
  181. /package/dist/{chunk-DMPZABKG.js.map → chunk-4TZOOUMK.js.map} +0 -0
  182. /package/dist/{chunk-HR3DKJCU.js.map → chunk-6SROXED4.js.map} +0 -0
  183. /package/dist/{chunk-L3DDKXQJ.js.map → chunk-76LDFLAG.js.map} +0 -0
  184. /package/dist/{chunk-5RONA5FF.js.map → chunk-7DFJ4JX2.js.map} +0 -0
  185. /package/dist/{chunk-OK3X3TBR.js.map → chunk-7L73PLRG.js.map} +0 -0
  186. /package/dist/{chunk-WKNMKV52.js.map → chunk-AQ6V47Q7.js.map} +0 -0
  187. /package/dist/{chunk-H4KIMZJD.js.map → chunk-B4ZA2PZC.js.map} +0 -0
  188. /package/dist/{chunk-DLR3SBOM.js.map → chunk-B7GZL7PR.js.map} +0 -0
  189. /package/dist/{chunk-XYNUEXLC.js.map → chunk-BAMF6J4W.js.map} +0 -0
  190. /package/dist/{chunk-NTR72OL5.js.map → chunk-CXIBBZ6N.js.map} +0 -0
  191. /package/dist/{chunk-V6UFCV6T.js.map → chunk-DIXXS4HS.js.map} +0 -0
  192. /package/dist/{chunk-3DJ6R4CC.js.map → chunk-DLPS5YP3.js.map} +0 -0
  193. /package/dist/{chunk-RSUNBJ4I.js.map → chunk-DWQAMPLW.js.map} +0 -0
  194. /package/dist/{chunk-6OMSYPOL.js.map → chunk-F2XXZR6A.js.map} +0 -0
  195. /package/dist/{chunk-OWD365QW.js.map → chunk-FDAXNHEX.js.map} +0 -0
  196. /package/dist/{chunk-CY2C5LM4.js.map → chunk-FDLPNFKE.js.map} +0 -0
  197. /package/dist/{chunk-KAGLV5KH.js.map → chunk-FTQF3G3B.js.map} +0 -0
  198. /package/dist/{chunk-2GQVYLQK.js.map → chunk-FTV2C3CA.js.map} +0 -0
  199. /package/dist/{chunk-ZKXNSPGQ.js.map → chunk-G77MHQFZ.js.map} +0 -0
  200. /package/dist/{chunk-66DUCUOC.js.map → chunk-GGQ3CJVH.js.map} +0 -0
  201. /package/dist/{chunk-BN5SK2RZ.js.map → chunk-HHKUWNHQ.js.map} +0 -0
  202. /package/dist/{chunk-KMOH6W5B.js.map → chunk-HOTAHSO3.js.map} +0 -0
  203. /package/dist/{chunk-OY3IULYL.js.map → chunk-IFXQGDMG.js.map} +0 -0
  204. /package/dist/{chunk-OWBI5477.js.map → chunk-JUROR7PB.js.map} +0 -0
  205. /package/dist/{chunk-4ACKO4U2.js.map → chunk-JXYFXVPB.js.map} +0 -0
  206. /package/dist/{chunk-ASWECJXS.js.map → chunk-KYPFQO43.js.map} +0 -0
  207. /package/dist/{chunk-4WOEEMGK.js.map → chunk-KZBE4KBZ.js.map} +0 -0
  208. /package/dist/{chunk-V6MN37WG.js.map → chunk-MFJM35R7.js.map} +0 -0
  209. /package/dist/{chunk-LKXW6W42.js.map → chunk-OTE5E44O.js.map} +0 -0
  210. /package/dist/{chunk-KPLKABGR.js.map → chunk-P3SMXKFR.js.map} +0 -0
  211. /package/dist/{chunk-27BH67PT.js.map → chunk-PCLTJUOY.js.map} +0 -0
  212. /package/dist/{chunk-JDH2BA2P.js.map → chunk-RXAWE76Y.js.map} +0 -0
  213. /package/dist/{chunk-WTFHZQXM.js.map → chunk-T3NEDSLZ.js.map} +0 -0
  214. /package/dist/{chunk-HB2PRTXX.js.map → chunk-V425GW5W.js.map} +0 -0
  215. /package/dist/{chunk-XKFL2WQO.js.map → chunk-V5FCMJW4.js.map} +0 -0
  216. /package/dist/{chunk-SNI526DD.js.map → chunk-VR6NF6VX.js.map} +0 -0
  217. /package/dist/{chunk-EXGY5TPU.js.map → chunk-W3O3OEQ7.js.map} +0 -0
  218. /package/dist/{chunk-AM6H7BIY.js.map → chunk-YMNPQMHA.js.map} +0 -0
  219. /package/dist/{chunk-QVXRE66C.js.map → chunk-ZBDTOWGX.js.map} +0 -0
  220. /package/dist/{chunk-YCK26VSL.js.map → chunk-ZMEEOLQG.js.map} +0 -0
  221. /package/dist/{chunk-DAOMWGO2.js.map → chunk-ZX5N5D6M.js.map} +0 -0
  222. /package/dist/{first-start-migration-CCZ5SM3V.js.map → first-start-migration-TCPK2I7J.js.map} +0 -0
@@ -1,7 +1,7 @@
1
1
  import assert from "node:assert/strict";
2
2
  import test from "node:test";
3
3
 
4
- import { QmdClient, parseQmdStatusOutput } from "./qmd.js";
4
+ import { QmdClient, parseQmdStatusOutput, resolveQmdCapabilities } from "./qmd.js";
5
5
  import type { QmdSearchResult } from "./types.js";
6
6
 
7
7
  type DaemonCheckInternals = {
@@ -402,8 +402,15 @@ test("parseQmdStatusOutput returns nulls for unparseable output", () => {
402
402
  assert.equal(report.oldestPendingAgeMs, null);
403
403
  });
404
404
 
405
+ test("an omitted count does not make malformed or unrecognized status healthy", () => {
406
+ const summary = "Total: 1 files indexed\nVectors: 8 embedded";
407
+ assert.equal(parseQmdStatusOutput(summary).pendingEmbeddings, null);
408
+ assert.equal(parseQmdStatusOutput("QMD Status\nTotal: 1 files indexed").pendingEmbeddings, null);
409
+ assert.equal(parseQmdStatusOutput(`QMD Status\n${summary}\nPending: unavailable`).pendingEmbeddings, null);
410
+ });
411
+
405
412
  test("QmdClient.status() returns parsed report on success", async () => {
406
- const client = new QmdClient("test-col", 3);
413
+ const client = new QmdClient("test-col", 3, { qmdSupportedVersion: "2.8.3" });
407
414
  const internals = client as unknown as {
408
415
  available: boolean;
409
416
  qmdCapabilities: { safeStatusDeviceProbe: boolean };
@@ -411,6 +418,7 @@ test("QmdClient.status() returns parsed report on success", async () => {
411
418
  };
412
419
  internals.available = true;
413
420
  internals.qmdCapabilities = { safeStatusDeviceProbe: true };
421
+ Object.assign(client, { cliVersion: "2.8.3" });
414
422
  let capturedArgs: string[] = [];
415
423
  internals.runQmdCommand = async (args: string[]) => {
416
424
  capturedArgs = args;
@@ -422,15 +430,38 @@ test("QmdClient.status() returns parsed report on success", async () => {
422
430
  assert.equal(report.oldestPendingAgeMs, 300_000);
423
431
  });
424
432
 
425
- test("QmdClient.status() returns null fields when unavailable", async () => {
433
+ test("QmdClient.status() explains unavailable counts without resetting flags", async () => {
426
434
  const client = new QmdClient("test-col", 3);
427
435
  const internals = client as unknown as { available: boolean };
428
436
  internals.available = false;
429
437
  const report = await client.status();
430
438
  assert.equal(report.pendingEmbeddings, null);
431
439
  assert.equal(report.oldestPendingAgeMs, null);
440
+ assert.equal(report.error, "qmd unavailable");
441
+ assert.equal(internals.available, false);
432
442
  });
433
443
 
444
+ for (const [version, expectedError] of [
445
+ ["2.4.0", "qmd status device probe is unsafe for this version"],
446
+ ["2.5.0", "qmd version is unsupported"],
447
+ [null, "qmd status device probe is unsafe for this version"],
448
+ ] as const) {
449
+ test(`QmdClient.status() refuses unsafe or unsupported version ${version}`, async () => {
450
+ const client = new QmdClient("test-col", 3, { qmdSupportedVersion: "2.8.3" });
451
+ const capabilities = resolveQmdCapabilities(version);
452
+ Object.assign(client, {
453
+ available: true, daemonAvailable: true, cliVersion: version, qmdCapabilities: capabilities,
454
+ runQmdCommand: async () => { assert.fail("Refused status must not run a command"); },
455
+ });
456
+ const report = await client.status();
457
+ assert.equal(report.error, expectedError);
458
+ assert.equal(report.pendingEmbeddings, null);
459
+ assert.equal(client.isAvailable(), true);
460
+ assert.equal(client.isDaemonMode(), true);
461
+ assert.equal(client.getVersionStatus().capabilities, capabilities);
462
+ });
463
+ }
464
+
434
465
  test("QmdClient.embedFiles() runs update then embed", async () => {
435
466
  const client = new QmdClient("test-col", 3);
436
467
  const internals = client as unknown as {
@@ -1,3 +1,4 @@
1
+ import { z } from "zod";
1
2
  import { abortError, throwIfAborted } from "./abort-error.js";
2
3
  import { log } from "./logger.js";
3
4
  import { type CommandChildProcess, launchProcess } from "./runtime/child-process.js";
@@ -6,6 +7,15 @@ import { sleep } from "./utils/sleep.js";
6
7
 
7
8
  export type QmdRuntimeEnv = Record<string, string | undefined>;
8
9
 
10
+ const initializeHealthSchema = z.object({
11
+ isError: z.literal(false).optional(),
12
+ capabilities: z.object({
13
+ experimental: z.object({
14
+ "qmd/healthMetadata": z.strictObject({ schemaVersion: z.literal(1) }).optional(),
15
+ }).optional(),
16
+ }),
17
+ });
18
+
9
19
  export type QmdDaemonSpawn = (
10
20
  command: string,
11
21
  args: string[],
@@ -64,9 +74,13 @@ function isTimeoutMessage(message: string): boolean {
64
74
  * than the recall budget, and a slow query would then take the warm process
65
75
  * down on every timeout.
66
76
  */
77
+ type HealthMetadataCapability = "available" | "absent" | "invalid";
78
+
67
79
  export class QmdDaemonSession {
68
80
  private child: CommandChildProcess | null = null;
69
81
  private initialized = false;
82
+ private processIdentity: object | null = null;
83
+ private healthMetadataCapability: HealthMetadataCapability | null = null;
70
84
  private buffer = "";
71
85
  private startPromise: Promise<boolean> | null = null;
72
86
  private pendingRequests = new Map<number, PendingRequest>();
@@ -108,6 +122,7 @@ export class QmdDaemonSession {
108
122
  stdio: ["pipe", "pipe", "pipe"],
109
123
  });
110
124
  this.child = child;
125
+ this.processIdentity = {};
111
126
  this.buffer = "";
112
127
 
113
128
  child.stdout?.on("data", (data: Buffer) => {
@@ -141,6 +156,7 @@ export class QmdDaemonSession {
141
156
  log.debug("QMD mcp: process already running, retrying handshake");
142
157
  }
143
158
 
159
+ const processIdentity = this.processIdentity;
144
160
  try {
145
161
  const result = await this.sendRequest(
146
162
  "initialize",
@@ -151,15 +167,20 @@ export class QmdDaemonSession {
151
167
  },
152
168
  60_000
153
169
  );
170
+ if (this.processIdentity !== processIdentity) return false;
154
171
  if (!result) {
155
172
  this.cleanup({ killChild: true });
156
173
  return false;
157
174
  }
158
175
  this.sendNotification("notifications/initialized");
176
+ const metadata = initializeHealthSchema.safeParse(result).data;
177
+ this.healthMetadataCapability = !metadata ? "invalid"
178
+ : metadata.capabilities.experimental?.["qmd/healthMetadata"] ? "available" : "absent";
159
179
  this.initialized = true;
160
180
  log.info("QMD mcp: stdio session initialized");
161
181
  return true;
162
182
  } catch (err) {
183
+ if (this.processIdentity !== processIdentity) return false;
163
184
  const msg = err instanceof Error ? err.message : String(err);
164
185
  if (isTimeoutMessage(msg)) {
165
186
  log.debug("QMD mcp: handshake timed out — process still loading, will retry later");
@@ -170,7 +191,7 @@ export class QmdDaemonSession {
170
191
  }
171
192
  return false;
172
193
  } finally {
173
- this.startPromise = null;
194
+ if (this.processIdentity === processIdentity) this.startPromise = null;
174
195
  }
175
196
  })();
176
197
  return this.startPromise;
@@ -226,6 +247,16 @@ export class QmdDaemonSession {
226
247
  return this.child !== null && !this.child.killed && this.initialized;
227
248
  }
228
249
 
250
+ /** Opaque identity; health readers cannot adopt or restart a different child. */
251
+ activeProcessIdentity(): object | null {
252
+ return this.isActive() ? this.processIdentity : null;
253
+ }
254
+
255
+ /** Passive, generation-scoped metadata from the operational initialize handshake. */
256
+ getHealthMetadataCapability(): HealthMetadataCapability | null {
257
+ return this.isActive() ? this.healthMetadataCapability : null;
258
+ }
259
+
229
260
  /** True while the process is spawned but the MCP handshake has not yet completed. */
230
261
  isLoading(): boolean {
231
262
  return this.child !== null && !this.child.killed && !this.initialized;
@@ -361,6 +392,8 @@ export class QmdDaemonSession {
361
392
  this.pendingRequests.clear();
362
393
  this.startPromise = null;
363
394
  this.child = null;
395
+ this.processIdentity = null;
396
+ this.healthMetadataCapability = null;
364
397
  this.buffer = "";
365
398
  }
366
399
  }
@@ -0,0 +1,493 @@
1
+ import assert from "node:assert/strict";
2
+ import test, { type TestContext } from "node:test";
3
+ import { createHash } from "node:crypto";
4
+ import { EventEmitter } from "node:events";
5
+ import { PassThrough, Writable } from "node:stream";
6
+ import os from "node:os";
7
+ import path from "node:path";
8
+ import {
9
+ QmdClient, resolveQmdCapabilities, retainSharedDaemonSessionForTest, releaseSharedDaemonSessionForTest,
10
+ } from "./qmd.js";
11
+ import { NamespaceSearchRouter } from "./namespaces/search.js";
12
+ import { parseConfig } from "./config.js";
13
+ import type { JsonValue } from "./extraction-reply-diagnostic.js";
14
+
15
+ const NAMES = [
16
+ "HOME", "USERPROFILE", "PATH", "XDG_CONFIG_HOME", "XDG_CACHE_HOME",
17
+ "QMD_CONFIG_DIR", "INDEX_PATH", "QMD_EMBED_MODEL", "QMD_GENERATE_MODEL",
18
+ "QMD_RERANK_MODEL", "QMD_FORCE_CPU", "QMD_LLAMA_GPU", "QMD_EMBED_PARALLELISM",
19
+ "QMD_EMBED_CONTEXT_SIZE", "QMD_EXPAND_CONTEXT_SIZE", "QMD_RERANK_CONTEXT_SIZE", "QMD_SOURCE_MODE",
20
+ "PWD", "WSL_DISTRO_NAME", "WSL_INTEROP",
21
+ ];
22
+ const memoryDir = path.join(os.tmpdir(), "fixture-notes");
23
+ const collection = "fixture-notes";
24
+ let fixtureId = 0;
25
+
26
+ function hash(value: JsonValue): string {
27
+ return createHash("sha256").update(JSON.stringify(value)).digest("hex");
28
+ }
29
+
30
+ function packet() {
31
+ return { structuredContent: { health: {
32
+ schemaVersion: 1,
33
+ environment: {
34
+ names: NAMES,
35
+ digest: hash([process.cwd(), NAMES.map(name => [name, process.env[name] ?? null])]),
36
+ },
37
+ active: { index: hash("fixture-index"), configuration: hash("fixture-config"), embeddingModel: hash("fixture-model") },
38
+ current: { index: hash("fixture-index"), configuration: hash("fixture-config"), embeddingModel: hash("fixture-model") },
39
+ countModel: hash("fixture-model"),
40
+ pendingEmbeddings: 0,
41
+ catalog: { complete: true, entries: [{ name: hash(collection), path: hash(memoryDir), documents: 0 }] },
42
+ } } };
43
+ }
44
+
45
+ async function operationalClient(
46
+ t: TestContext,
47
+ respond: () => JsonValue | Promise<JsonValue> = packet,
48
+ advertisement: { marker?: JsonValue } = { marker: { schemaVersion: 1 } },
49
+ ) {
50
+ const stdout = new PassThrough();
51
+ const stderr = new PassThrough();
52
+ let spawnCalls = 0;
53
+ let initializeCalls = 0;
54
+ let statusCalls = 0;
55
+ let capabilityCalls = 0;
56
+ let cliCalls = 0;
57
+ const stdin = new Writable({
58
+ write(chunk, _encoding, done) {
59
+ const message = JSON.parse(chunk.toString());
60
+ done();
61
+ if (message.id === undefined) return;
62
+ queueMicrotask(() => {
63
+ void (async () => {
64
+ let result: JsonValue;
65
+ if (message.method === "initialize") {
66
+ initializeCalls++;
67
+ result = {
68
+ capabilities: {
69
+ experimental: advertisement.marker === undefined ? {} : { "qmd/healthMetadata": advertisement.marker },
70
+ },
71
+ serverInfo: { name: "fixture", version: "2.8.3" },
72
+ };
73
+ } else if (message.method === "tools/list") {
74
+ capabilityCalls++;
75
+ throw new Error("Health must not discover tools");
76
+ } else {
77
+ assert.equal(message.method, "tools/call");
78
+ assert.equal(message.params.name, "status");
79
+ statusCalls++;
80
+ result = await respond();
81
+ }
82
+ stdout.write(JSON.stringify({ jsonrpc: "2.0", id: message.id, result }) + "\n");
83
+ })().catch(() => stdout.write(JSON.stringify({
84
+ jsonrpc: "2.0", id: message.id, error: { code: -1, message: "Synthetic RPC failure" },
85
+ }) + "\n"));
86
+ });
87
+ },
88
+ });
89
+ const child = Object.assign(new EventEmitter(), {
90
+ stdout, stderr, stdin, killed: false,
91
+ kill() {
92
+ child.killed = true;
93
+ queueMicrotask(() => child.emit("close", 0));
94
+ return true;
95
+ },
96
+ });
97
+ const binary = `fixture-qmd-health-${++fixtureId}`;
98
+ const session = retainSharedDaemonSessionForTest(binary, {}, undefined, "2.8.3");
99
+ Object.assign(session, { spawn: () => { spawnCalls++; return child; } });
100
+ const client = new QmdClient(collection, 3, {
101
+ qmdPath: binary, daemonUrl: "stdio://fixture", qmdSupportedVersion: "2.8.3",
102
+ });
103
+ Object.assign(client, {
104
+ available: true,
105
+ daemonAvailable: true,
106
+ daemonSession: session,
107
+ daemonSessionPath: [binary, "", "2.8.3"].join("\0"),
108
+ cliVersion: "2.8.3",
109
+ qmdCapabilities: resolveQmdCapabilities("2.8.3"),
110
+ runQmdCommand: async () => { cliCalls++; throw new Error("No CLI work on operational metadata path"); },
111
+ probeDaemon: async () => { throw new Error("Health must not probe"); },
112
+ });
113
+ t.after(async () => {
114
+ await client.dispose();
115
+ stdin.destroy(); stdout.destroy(); stderr.destroy();
116
+ assert.equal(cliCalls, 0);
117
+ assert.equal(capabilityCalls, 0);
118
+ assert.equal(spawnCalls, 1);
119
+ });
120
+ assert.deepEqual(await Promise.all([session.start(), session.start()]), [true, true]);
121
+ assert.equal(initializeCalls, 1);
122
+ return {
123
+ client, session, binary,
124
+ initializeCalls: () => initializeCalls,
125
+ statusCalls: () => statusCalls,
126
+ capabilityCalls: () => capabilityCalls,
127
+ };
128
+ }
129
+
130
+ test("operational health accepts a configured-empty collection with fresh same-model counts", async t => {
131
+ const fixture = await operationalClient(t);
132
+ const health = await fixture.client.readOperationalHealth(memoryDir);
133
+ assert.equal(health?.collectionState, "present");
134
+ assert.equal(health?.totalFiles, 0);
135
+ assert.equal(health?.pendingEmbeddings, 0);
136
+ assert.equal(fixture.session.isActive(), true);
137
+ assert.equal(health?.isCurrent?.(), true);
138
+ assert.equal(fixture.statusCalls(), 1);
139
+ assert.equal(fixture.capabilityCalls(), 0);
140
+ });
141
+
142
+ test("operational health passively recognizes old capability without calling its status reader", async t => {
143
+ const fixture = await operationalClient(t, packet, {});
144
+ assert.equal(await fixture.client.readOperationalHealth(memoryDir), undefined);
145
+ assert.equal(fixture.statusCalls(), 0);
146
+ });
147
+
148
+ test("operational health refuses an unsupported advertised capability without CLI retry", async t => {
149
+ const fixture = await operationalClient(t, packet, { marker: { schemaVersion: 99 } });
150
+ assert.equal((await fixture.client.readOperationalHealth(memoryDir))?.collectionState, "unknown");
151
+ assert.equal(fixture.statusCalls(), 0);
152
+ });
153
+
154
+ const invalidMarkers: JsonValue[] = [
155
+ null, "1", true, 1, {}, [], { schemaVersion: "1" }, { schemaVersion: null },
156
+ { schemaVersion: true }, { schemaVersion: 0 }, { schemaVersion: 1, unsupported: true },
157
+ ];
158
+ for (const marker of invalidMarkers) {
159
+ test(`operational health refuses malformed advertised marker ${JSON.stringify(marker)}`, { timeout: 2_000 }, async t => {
160
+ const fixture = await operationalClient(t, packet, { marker });
161
+ assert.equal(fixture.session.getHealthMetadataCapability(), "invalid");
162
+ assert.equal((await fixture.client.readOperationalHealth(memoryDir))?.collectionState, "unknown");
163
+ assert.equal(fixture.statusCalls(), 0);
164
+ });
165
+ }
166
+
167
+ test("concurrent health reads reuse passive discovery and each send exactly one snapshot RPC", { timeout: 2_000 }, async t => {
168
+ const fixture = await operationalClient(t);
169
+ assert.equal(fixture.session.getHealthMetadataCapability(), "available");
170
+ assert.equal(fixture.initializeCalls(), 1);
171
+ assert.equal(fixture.statusCalls(), 0);
172
+ const snapshots = await Promise.all([
173
+ fixture.client.readOperationalHealth(memoryDir),
174
+ fixture.client.readOperationalHealth(memoryDir),
175
+ ]);
176
+ assert.deepEqual(snapshots.map(snapshot => snapshot?.collectionState), ["present", "present"]);
177
+ assert.equal(fixture.statusCalls(), 2);
178
+ assert.equal(fixture.capabilityCalls(), 0);
179
+ assert.equal(fixture.initializeCalls(), 1);
180
+ for (const snapshot of snapshots) {
181
+ assert.equal(snapshot?.isCurrent?.(), true);
182
+ assert.equal(snapshot?.isCurrent?.(), true);
183
+ }
184
+ assert.equal(fixture.statusCalls(), 2, "Publishability checks must not send RPCs");
185
+ await fixture.client.dispose();
186
+ assert.equal(fixture.session.isActive(), false, "Health must not retain a session lease");
187
+ assert.equal(snapshots[0]?.isCurrent?.(), false);
188
+ assert.equal(snapshots[1]?.isCurrent?.(), false);
189
+ });
190
+
191
+ test("operational health reads fresh metadata after a healthy result while caching only static capability", async t => {
192
+ let changed = false;
193
+ const fixture = await operationalClient(t, () => {
194
+ const value = packet();
195
+ if (changed) value.structuredContent.health.current.embeddingModel = hash("changed-model");
196
+ return value;
197
+ });
198
+ assert.equal((await fixture.client.readOperationalHealth(memoryDir))?.collectionState, "present");
199
+ changed = true;
200
+ assert.equal((await fixture.client.readOperationalHealth(memoryDir))?.collectionState, "unknown");
201
+ assert.equal(fixture.statusCalls(), 2);
202
+ assert.equal(fixture.capabilityCalls(), 0);
203
+ assert.equal(fixture.initializeCalls(), 1);
204
+ });
205
+
206
+ test("operational health reports real model-bound backlog rather than hiding it", async t => {
207
+ const fixture = await operationalClient(t, () => {
208
+ const value = packet();
209
+ value.structuredContent.health.pendingEmbeddings = 50_000;
210
+ return value;
211
+ });
212
+ const health = await fixture.client.readOperationalHealth(memoryDir);
213
+ assert.equal(health?.collectionState, "present");
214
+ assert.equal(health?.pendingEmbeddings, 50_000);
215
+ });
216
+
217
+ test("operational health returns missing for authoritative removal despite stale active configuration", async t => {
218
+ const fixture = await operationalClient(t, () => {
219
+ const value = packet();
220
+ value.structuredContent.health.current.configuration = hash("removed-configuration");
221
+ value.structuredContent.health.catalog.entries = [];
222
+ return value;
223
+ });
224
+ assert.equal((await fixture.client.readOperationalHealth(memoryDir))?.collectionState, "missing");
225
+ });
226
+
227
+ test("operational health refuses malformed counts even when the catalog is empty", async t => {
228
+ let corruptModel = false;
229
+ const fixture = await operationalClient(t, () => {
230
+ const value = packet();
231
+ const health = value.structuredContent.health;
232
+ health.catalog.entries = [];
233
+ if (corruptModel) health.countModel = hash("wrong-model");
234
+ else health.pendingEmbeddings = -1;
235
+ return value;
236
+ });
237
+ assert.equal((await fixture.client.readOperationalHealth(memoryDir))?.collectionState, "unknown");
238
+ corruptModel = true;
239
+ assert.equal((await fixture.client.readOperationalHealth(memoryDir))?.collectionState, "unknown");
240
+ });
241
+
242
+ const corruptions: Array<[string, (value: ReturnFixture) => JsonValue]> = [
243
+ ["null metadata", () => ({ structuredContent: { health: null } })],
244
+ ["missing advertised metadata", () => ({ structuredContent: {} })],
245
+ ["unsupported schema", value => { value.structuredContent.health.schemaVersion = 99; return value; }],
246
+ ["wrong index", value => { value.structuredContent.health.current.index = hash("foreign-index"); return value; }],
247
+ ["changed configuration", value => { value.structuredContent.health.current.configuration = hash("changed"); return value; }],
248
+ ["wrong collection path", value => { value.structuredContent.health.catalog.entries[0]!.path = hash("foreign-path"); return value; }],
249
+ ["count model mismatch", value => { value.structuredContent.health.countModel = hash("wrong-model"); return value; }],
250
+ ["incomplete catalog", value => { value.structuredContent.health.catalog.complete = false; return value; }],
251
+ ["invalid count", value => { value.structuredContent.health.pendingEmbeddings = -1; return value; }],
252
+ ["RPC tool failure", () => ({ isError: true, structuredContent: {} })],
253
+ ];
254
+
255
+ type ReturnFixture = {
256
+ structuredContent: {
257
+ health: {
258
+ schemaVersion: number;
259
+ environment: { names: string[]; digest: string };
260
+ active: { index: string; configuration: string; embeddingModel: string };
261
+ current: { index: string; configuration: string; embeddingModel: string };
262
+ countModel: string;
263
+ pendingEmbeddings: number;
264
+ catalog: { complete: boolean; entries: Array<{ name: string; path: string; documents: number }> };
265
+ };
266
+ };
267
+ };
268
+
269
+ for (const [name, corrupt] of corruptions) {
270
+ test(`operational health refuses ${name}`, async t => {
271
+ const fixture = await operationalClient(t, () => corrupt(packet()));
272
+ assert.equal((await fixture.client.readOperationalHealth(memoryDir))?.collectionState, "unknown");
273
+ });
274
+ }
275
+
276
+ for (const flag of [true, "false", null, 0, {}, []]) {
277
+ for (const name of ["isError", "unavailable"] as const) {
278
+ test(`operational health refuses ${name}=${JSON.stringify(flag)} at the RPC boundary`, { timeout: 2_000 }, async t => {
279
+ const fixture = await operationalClient(t, () => {
280
+ const value = packet();
281
+ Object.assign(name === "isError" ? value : value.structuredContent.health, { [name]: flag });
282
+ return value;
283
+ });
284
+ const health = await fixture.client.readOperationalHealth(memoryDir);
285
+ assert.equal(health?.collectionState, "unknown");
286
+ assert.equal(health?.pendingEmbeddings, null);
287
+ assert.equal(fixture.statusCalls(), 1);
288
+ });
289
+ }
290
+ }
291
+
292
+ test("operational health accepts literal false error and unavailable flags", { timeout: 2_000 }, async t => {
293
+ const fixture = await operationalClient(t, () => {
294
+ const value = packet();
295
+ Object.assign(value, { isError: false });
296
+ Object.assign(value.structuredContent.health, { unavailable: false });
297
+ return value;
298
+ });
299
+ assert.equal((await fixture.client.readOperationalHealth(memoryDir))?.collectionState, "present");
300
+ });
301
+
302
+ test("operational health requires the exact native environment key contract", { timeout: 2_000 }, async t => {
303
+ const fixture = await operationalClient(t, () => {
304
+ const value = packet();
305
+ value.structuredContent.health.environment.names = NAMES.filter(name => name !== "QMD_EMBED_CONTEXT_SIZE");
306
+ return value;
307
+ });
308
+ assert.equal((await fixture.client.readOperationalHealth(memoryDir))?.collectionState, "unknown");
309
+ });
310
+
311
+ test("operational health refuses inherited environment drift before or during RPC", async t => {
312
+ const old = process.env.QMD_EMBED_MODEL;
313
+ const original = packet();
314
+ t.after(() => { if (old === undefined) delete process.env.QMD_EMBED_MODEL; else process.env.QMD_EMBED_MODEL = old; });
315
+ const fixture = await operationalClient(t, () => original);
316
+ process.env.QMD_EMBED_MODEL = "fixture:changed-before-rpc";
317
+ assert.equal((await fixture.client.readOperationalHealth(memoryDir))?.collectionState, "unknown");
318
+ if (old === undefined) delete process.env.QMD_EMBED_MODEL; else process.env.QMD_EMBED_MODEL = old;
319
+ const during = await operationalClient(t, () => {
320
+ const value = packet();
321
+ process.env.QMD_EMBED_MODEL = "fixture:changed-during-rpc";
322
+ return value;
323
+ });
324
+ assert.equal((await during.client.readOperationalHealth(memoryDir))?.collectionState, "unknown");
325
+ });
326
+
327
+ test("operational health refuses pre-abort and a late result after session invalidation", async t => {
328
+ const aborted = new AbortController();
329
+ aborted.abort();
330
+ const fixture = await operationalClient(t);
331
+ assert.equal((await fixture.client.readOperationalHealth(memoryDir, { signal: aborted.signal }))?.collectionState, "unknown");
332
+ assert.equal(fixture.statusCalls(), 0);
333
+ const late = await operationalClient(t, async () => {
334
+ late.session.invalidate();
335
+ return packet();
336
+ });
337
+ assert.equal((await late.client.readOperationalHealth(memoryDir))?.collectionState, "unknown");
338
+ });
339
+
340
+ test("operational health refuses RPC cancellation without killing the owned session", async t => {
341
+ const controller = new AbortController();
342
+ const fixture = await operationalClient(t, () => {
343
+ controller.abort();
344
+ return packet();
345
+ });
346
+ assert.equal((await fixture.client.readOperationalHealth(memoryDir, { signal: controller.signal }))?.collectionState, "unknown");
347
+ assert.equal(fixture.session.isActive(), true);
348
+ });
349
+
350
+ test("operational health does not start a cold client", async () => {
351
+ const client = new QmdClient(collection, 3, { daemonUrl: "stdio://fixture" });
352
+ Object.assign(client, { probeDaemon: async () => { throw new Error("Unexpected process acquisition"); } });
353
+ assert.equal(await client.readOperationalHealth(memoryDir), undefined);
354
+ });
355
+
356
+ test("operational health refuses an elapsed absolute deadline before timers can fire", { timeout: 2_000 }, async t => {
357
+ let now = 0;
358
+ t.mock.method(performance, "now", () => now);
359
+ const fixture = await operationalClient(t, () => {
360
+ now = 5_001;
361
+ return packet();
362
+ });
363
+ const health = await fixture.client.readOperationalHealth(memoryDir);
364
+ assert.equal(health?.collectionState, "unknown");
365
+ assert.equal(health?.pendingEmbeddings, null);
366
+ assert.equal(health?.isCurrent?.(), false);
367
+ assert.equal(fixture.statusCalls(), 1);
368
+ assert.equal(fixture.session.isActive(), true);
369
+ });
370
+
371
+ test("snapshot publishability expires at its absolute monotonic deadline", { timeout: 2_000 }, async t => {
372
+ let now = 0;
373
+ t.mock.method(performance, "now", () => now);
374
+ const fixture = await operationalClient(t);
375
+ const health = await fixture.client.readOperationalHealth(memoryDir);
376
+ assert.equal(health?.isCurrent?.(), true);
377
+ now = 5_000;
378
+ assert.equal(health?.isCurrent?.(), false);
379
+ assert.equal(fixture.statusCalls(), 1);
380
+ });
381
+
382
+ test("snapshot publishability ends on client release even while another owner keeps the process alive", { timeout: 2_000 }, async t => {
383
+ const fixture = await operationalClient(t);
384
+ const otherOwner = retainSharedDaemonSessionForTest(fixture.binary, {}, undefined, "2.8.3");
385
+ t.after(() => releaseSharedDaemonSessionForTest(otherOwner));
386
+ const health = await fixture.client.readOperationalHealth(memoryDir);
387
+ assert.equal(health?.isCurrent?.(), true);
388
+ const disposal = fixture.client.dispose();
389
+ assert.equal(health?.isCurrent?.(), false, "Release invalidates before its first await");
390
+ assert.equal(fixture.client.operationalHealthIdentity(), null);
391
+ await disposal;
392
+ assert.equal(otherOwner.isActive(), true);
393
+ });
394
+
395
+ test("snapshot publishability ends on process invalidation and capability resets", { timeout: 2_000 }, async t => {
396
+ const fixture = await operationalClient(t);
397
+ const health = await fixture.client.readOperationalHealth(memoryDir);
398
+ assert.equal(health?.isCurrent?.(), true);
399
+ fixture.session.invalidate();
400
+ assert.equal(fixture.session.getHealthMetadataCapability(), null);
401
+ assert.equal(health?.isCurrent?.(), false);
402
+ });
403
+
404
+ for (const [name, patch] of [
405
+ ["generation", { daemonGeneration: 1 }],
406
+ ["owner path", { daemonSessionPath: "other-owner" }],
407
+ ["binary", { qmdPath: "other-binary" }],
408
+ ["version", { cliVersion: "2.8.4" }],
409
+ ["capabilities", { qmdCapabilities: resolveQmdCapabilities("2.8.3") }],
410
+ ["index", { qmdIndexName: "other-index" }],
411
+ ["runtime environment", { qmdRuntimeEnv: { QMD_EMBED_CONTEXT_SIZE: "8192" } }],
412
+ ] as const) {
413
+ test(`snapshot publishability ends on client ${name} change`, { timeout: 2_000 }, async t => {
414
+ const fixture = await operationalClient(t);
415
+ const health = await fixture.client.readOperationalHealth(memoryDir);
416
+ assert.equal(health?.isCurrent?.(), true);
417
+ Object.assign(fixture.client, patch);
418
+ assert.equal(health?.isCurrent?.(), false);
419
+ assert.equal(fixture.statusCalls(), 1);
420
+ });
421
+ }
422
+
423
+ test("snapshot publishability ends on inherited environment, cwd, or abort changes", { timeout: 2_000 }, async t => {
424
+ const old = process.env.QMD_EMBED_CONTEXT_SIZE;
425
+ const restore = () => {
426
+ if (old === undefined) delete process.env.QMD_EMBED_CONTEXT_SIZE;
427
+ else process.env.QMD_EMBED_CONTEXT_SIZE = old;
428
+ };
429
+ t.after(restore);
430
+ const fixture = await operationalClient(t);
431
+ const controller = new AbortController();
432
+ const health = await fixture.client.readOperationalHealth(memoryDir, { signal: controller.signal });
433
+ assert.equal(health?.isCurrent?.(), true);
434
+ process.env.QMD_EMBED_CONTEXT_SIZE = `${old ?? ""}-changed`;
435
+ assert.equal(health?.isCurrent?.(), false);
436
+ restore();
437
+ const originalCwd = process.cwd();
438
+ const cwd = t.mock.method(process, "cwd", () => path.join(originalCwd, "changed"));
439
+ assert.equal(health?.isCurrent?.(), false);
440
+ cwd.mock.restore();
441
+ controller.abort();
442
+ assert.equal(health?.isCurrent?.(), false);
443
+ });
444
+
445
+ for (const [pausedStorageCall, absentCapability] of [[1, false], [2, false], [1, true], [2, true]] as const) {
446
+ test(`router refuses actual client invalidation across storage await ${pausedStorageCall} (absent=${absentCapability})`, { timeout: 2_000 }, async t => {
447
+ const fixture = await operationalClient(t, packet, absentCapability ? {} : { marker: { schemaVersion: 1 } });
448
+ const replacement = absentCapability ? await operationalClient(t, packet, {}) : null;
449
+ const identity = fixture.client.operationalHealthIdentity();
450
+ assert.notEqual(identity, null);
451
+ const { promise: paused, resolve: entered } = Promise.withResolvers<void>();
452
+ const { promise: gate, resolve: release } = Promise.withResolvers<void>();
453
+ t.after(() => release());
454
+ t.mock.method(fixture.client, "probe", async () => true);
455
+ t.mock.method(fixture.client, "checkCollection", async () => "present");
456
+ let storageCalls = 0;
457
+ let created = 0;
458
+ const router = new NamespaceSearchRouter(parseConfig({
459
+ defaultNamespace: "main", memoryDir, qmdCollection: collection,
460
+ qmdEnabled: true, qmdEmbeddingBacklogThreshold: 100,
461
+ }), {
462
+ storageFor: async () => {
463
+ if (created > 0 && ++storageCalls === pausedStorageCall) {
464
+ entered();
465
+ await gate;
466
+ }
467
+ return { dir: memoryDir };
468
+ },
469
+ }, () => {
470
+ if (++created === 1) return fixture.client;
471
+ throw new Error("Ownership loss must not fall back to a diagnostic backend");
472
+ });
473
+ await router.ensureNamespaceCollection("main");
474
+ t.after(() => router.dispose());
475
+ const pending = router.healthForNamespace("main");
476
+ await paused;
477
+ if (replacement) Object.assign(fixture.client, { daemonSession: replacement.session });
478
+ else if (pausedStorageCall === 1) await fixture.client.dispose();
479
+ else fixture.session.invalidate();
480
+ assert.notEqual(fixture.client.operationalHealthIdentity(), identity);
481
+ release();
482
+ try {
483
+ const health = await pending;
484
+ assert.equal(health.collectionState, "unknown");
485
+ assert.equal(health.pendingEmbeddings, null);
486
+ assert.equal(created, 1);
487
+ assert.equal(fixture.statusCalls(), absentCapability ? 0 : pausedStorageCall - 1);
488
+ assert.equal(fixture.capabilityCalls(), 0);
489
+ } finally {
490
+ if (replacement) Object.assign(fixture.client, { daemonSession: fixture.session });
491
+ }
492
+ });
493
+ }