@remnic/core 10.0.139 → 10.0.141

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 (189) hide show
  1. package/dist/access-admin-ops-surface.js +44 -44
  2. package/dist/access-cli.js +44 -44
  3. package/dist/access-extraction-force-flush-preempt.js +44 -44
  4. package/dist/access-extraction-force-flush.js +44 -44
  5. package/dist/access-http-briefing.js +44 -44
  6. package/dist/access-http-query.js +44 -44
  7. package/dist/access-http.js +44 -44
  8. package/dist/access-identity-continuity-surface.js +44 -44
  9. package/dist/access-lcm-surface.js +44 -44
  10. package/dist/access-mcp.js +44 -44
  11. package/dist/access-observe-write-surface.js +44 -44
  12. package/dist/access-operations-batch.js +44 -44
  13. package/dist/access-operations.js +44 -44
  14. package/dist/access-recall-concurrency.js +44 -44
  15. package/dist/access-recall-response.js +44 -44
  16. package/dist/access-recall-surface.js +44 -44
  17. package/dist/access-service.js +44 -44
  18. package/dist/active-recall.js +6 -6
  19. package/dist/briefing.js +7 -7
  20. package/dist/buffer-persistence.d.ts +44 -1
  21. package/dist/buffer-persistence.d.ts.map +1 -1
  22. package/dist/buffer-persistence.js +5 -1
  23. package/dist/buffer-turn-helpers.d.ts +8 -1
  24. package/dist/buffer-turn-helpers.d.ts.map +1 -1
  25. package/dist/buffer-turn-helpers.js +5 -1
  26. package/dist/buffer.d.ts +11 -4
  27. package/dist/buffer.d.ts.map +1 -1
  28. package/dist/buffer.js +6 -6
  29. package/dist/causal-consolidation.js +8 -8
  30. package/dist/{chunk-MP6V4CLP.js → chunk-27N6SGEY.js} +2 -2
  31. package/dist/{chunk-AV6R66KO.js → chunk-2HI22OK7.js} +2 -2
  32. package/dist/{chunk-A33VT7GC.js → chunk-342VFB56.js} +2 -2
  33. package/dist/{chunk-NB2BKYUS.js → chunk-3GHQCNNG.js} +2 -2
  34. package/dist/{chunk-LT35JWKZ.js → chunk-3RJU7QFE.js} +2 -2
  35. package/dist/{chunk-JEAMQL63.js → chunk-4IMMF5W6.js} +3 -3
  36. package/dist/chunk-4Y26S76X.js +109 -0
  37. package/dist/chunk-4Y26S76X.js.map +1 -0
  38. package/dist/{chunk-EEY326VH.js → chunk-63JPXUFA.js} +2 -2
  39. package/dist/{chunk-OFMK76LD.js → chunk-6WV76JHC.js} +2 -2
  40. package/dist/{chunk-VF3EVRUN.js → chunk-7NSGKXFD.js} +2 -2
  41. package/dist/{chunk-KCLHHANX.js → chunk-7YD5XSJK.js} +2 -2
  42. package/dist/{chunk-KCVPKFDG.js → chunk-AA6G3W3B.js} +2 -2
  43. package/dist/{chunk-2UW3EM3U.js → chunk-AZFQXYIJ.js} +45 -2
  44. package/dist/chunk-AZFQXYIJ.js.map +1 -0
  45. package/dist/{chunk-66MBMBSH.js → chunk-BDIXKROL.js} +78 -73
  46. package/dist/chunk-BDIXKROL.js.map +1 -0
  47. package/dist/{chunk-VRWQUUZ7.js → chunk-BYWNF25B.js} +2 -2
  48. package/dist/{chunk-NOZDET3Q.js → chunk-DGLNT6VO.js} +3 -3
  49. package/dist/{chunk-HOSS72UP.js → chunk-EGDUG2ZX.js} +2 -2
  50. package/dist/{chunk-GOYLBPSW.js → chunk-EIZUL6JC.js} +2 -2
  51. package/dist/{chunk-YMNFHNZH.js → chunk-F476AJQJ.js} +2 -2
  52. package/dist/{chunk-POB7N5UM.js → chunk-FJTRNFI4.js} +2 -2
  53. package/dist/{chunk-PQ5FYNY2.js → chunk-FONPAA43.js} +2 -2
  54. package/dist/{chunk-JG6AHBJW.js → chunk-FREKFMCA.js} +2 -2
  55. package/dist/{chunk-N7IJEGSE.js → chunk-GNIMBEOK.js} +2 -2
  56. package/dist/{chunk-YDOLJQ55.js → chunk-H6VQ7L5D.js} +6 -6
  57. package/dist/{chunk-LEH4FVBJ.js → chunk-IUXTKLZY.js} +3 -3
  58. package/dist/{chunk-OJJ73HLA.js → chunk-JCBKGPFE.js} +3 -3
  59. package/dist/{chunk-QZ5JZNXN.js → chunk-JLD44JR7.js} +37 -37
  60. package/dist/{chunk-PNT3SZRY.js → chunk-K5CM4M65.js} +7 -7
  61. package/dist/{chunk-3BRHOVRU.js → chunk-LPDOCXHH.js} +2 -2
  62. package/dist/{chunk-MXE42X3I.js → chunk-NCS2NXSP.js} +3 -3
  63. package/dist/{chunk-DI2QWY6J.js → chunk-NM6UL4W5.js} +7 -7
  64. package/dist/{chunk-N6JGLQV7.js → chunk-QZUT4VTV.js} +2 -2
  65. package/dist/{chunk-F4DXTUHY.js → chunk-SZ6QV3DY.js} +2 -2
  66. package/dist/{chunk-OI3UMEW3.js → chunk-UF5RTFN3.js} +2 -2
  67. package/dist/{chunk-SRW4IKHM.js → chunk-UM22PKA3.js} +2 -2
  68. package/dist/{chunk-U3GJUARA.js → chunk-USVA4XWY.js} +2 -2
  69. package/dist/{chunk-PKV3NNM2.js → chunk-UX7KPVAM.js} +2 -2
  70. package/dist/{chunk-2DWTO7XP.js → chunk-VH4UCI3R.js} +92 -38
  71. package/dist/chunk-VH4UCI3R.js.map +1 -0
  72. package/dist/{chunk-JCWI43TO.js → chunk-VRBGYSSQ.js} +2 -2
  73. package/dist/{chunk-LUDXM7MD.js → chunk-WBOJMAAV.js} +78 -25
  74. package/dist/chunk-WBOJMAAV.js.map +1 -0
  75. package/dist/{chunk-JY327EH4.js → chunk-WGM2KSWN.js} +2 -2
  76. package/dist/{chunk-K4DBE5MH.js → chunk-WIV37T4U.js} +2 -2
  77. package/dist/{chunk-VSZEV7HG.js → chunk-XOOYE37V.js} +2 -2
  78. package/dist/{chunk-JVQNRSWO.js → chunk-YCNSMVWG.js} +2 -2
  79. package/dist/{chunk-CKG7T4AD.js → chunk-YXFY4YOF.js} +2 -2
  80. package/dist/cli.js +44 -44
  81. package/dist/coding/export-okf-codegraph.js +6 -6
  82. package/dist/compounding/engine.js +8 -8
  83. package/dist/config.js +6 -6
  84. package/dist/connectors/codex-materialize-runner.js +7 -7
  85. package/dist/connectors/index.js +7 -7
  86. package/dist/convergence-refresh.js +9 -9
  87. package/dist/corpus-watermark.js +9 -9
  88. package/dist/entity-retrieval.js +7 -7
  89. package/dist/explicit-capture.js +44 -44
  90. package/dist/extraction.js +11 -11
  91. package/dist/harmonic-retrieval.js +7 -7
  92. package/dist/index.js +44 -44
  93. package/dist/location/index.js +8 -8
  94. package/dist/maintenance/memory-governance.js +7 -7
  95. package/dist/maintenance/rebuild-memory-lifecycle-ledger.js +7 -7
  96. package/dist/maintenance/rebuild-memory-projection-runner.js +9 -9
  97. package/dist/maintenance/rebuild-memory-projection.js +8 -8
  98. package/dist/memory-browse.js +4 -4
  99. package/dist/namespaces/migrate.js +8 -8
  100. package/dist/namespaces/search.js +3 -3
  101. package/dist/namespaces/storage.js +7 -7
  102. package/dist/operator-doctor-corpus.js +10 -10
  103. package/dist/operator-toolkit.js +13 -13
  104. package/dist/orchestration/backlog-scheduler.js +45 -45
  105. package/dist/orchestration/buffer-drain-runner.js +45 -45
  106. package/dist/orchestration/maintenance.js +15 -15
  107. package/dist/orchestrator.js +44 -44
  108. package/dist/qmd.d.ts +15 -0
  109. package/dist/qmd.d.ts.map +1 -1
  110. package/dist/qmd.js +3 -1
  111. package/dist/recall-navigation.js +44 -44
  112. package/dist/recall-state-view-admission.js +4 -4
  113. package/dist/recall-why-service.js +4 -4
  114. package/dist/rerank.d.ts +8 -8
  115. package/dist/rerank.d.ts.map +1 -1
  116. package/dist/rerank.js +11 -3
  117. package/dist/resume-bundles.js +6 -6
  118. package/dist/schemas.d.ts +4 -4
  119. package/dist/search/factory.js +2 -2
  120. package/dist/search/index.js +2 -2
  121. package/dist/semantic-consolidation.js +8 -8
  122. package/dist/semantic-rule-promotion.js +7 -7
  123. package/dist/semantic-rule-verifier.js +7 -7
  124. package/dist/source-agent-qualifier.js +10 -10
  125. package/dist/standup/build.js +7 -7
  126. package/dist/storage/buffer-drain-claims.js +2 -2
  127. package/dist/storage/buffer-session-files.js +2 -2
  128. package/dist/storage.js +6 -6
  129. package/dist/transfer/export-okf.js +7 -7
  130. package/dist/verified-recall.js +7 -7
  131. package/dist/who-knows-cli.js +8 -8
  132. package/dist/who-knows.js +7 -7
  133. package/package.json +2 -2
  134. package/src/buffer-large-session-defer.test.ts +472 -0
  135. package/src/buffer-persistence.ts +100 -7
  136. package/src/buffer-turn-helpers.ts +72 -1
  137. package/src/buffer.ts +103 -102
  138. package/src/qmd-client.test.ts +26 -15
  139. package/src/qmd-daemon-congestion.test.ts +233 -0
  140. package/src/qmd-mcp-cancel.test.ts +3 -3
  141. package/src/qmd.ts +149 -45
  142. package/src/rerank.test.ts +162 -25
  143. package/src/rerank.ts +102 -24
  144. package/dist/chunk-2DWTO7XP.js.map +0 -1
  145. package/dist/chunk-2UW3EM3U.js.map +0 -1
  146. package/dist/chunk-66MBMBSH.js.map +0 -1
  147. package/dist/chunk-LUDXM7MD.js.map +0 -1
  148. package/dist/chunk-XO23OKMK.js +0 -67
  149. package/dist/chunk-XO23OKMK.js.map +0 -1
  150. /package/dist/{chunk-MP6V4CLP.js.map → chunk-27N6SGEY.js.map} +0 -0
  151. /package/dist/{chunk-AV6R66KO.js.map → chunk-2HI22OK7.js.map} +0 -0
  152. /package/dist/{chunk-A33VT7GC.js.map → chunk-342VFB56.js.map} +0 -0
  153. /package/dist/{chunk-NB2BKYUS.js.map → chunk-3GHQCNNG.js.map} +0 -0
  154. /package/dist/{chunk-LT35JWKZ.js.map → chunk-3RJU7QFE.js.map} +0 -0
  155. /package/dist/{chunk-JEAMQL63.js.map → chunk-4IMMF5W6.js.map} +0 -0
  156. /package/dist/{chunk-EEY326VH.js.map → chunk-63JPXUFA.js.map} +0 -0
  157. /package/dist/{chunk-OFMK76LD.js.map → chunk-6WV76JHC.js.map} +0 -0
  158. /package/dist/{chunk-VF3EVRUN.js.map → chunk-7NSGKXFD.js.map} +0 -0
  159. /package/dist/{chunk-KCLHHANX.js.map → chunk-7YD5XSJK.js.map} +0 -0
  160. /package/dist/{chunk-KCVPKFDG.js.map → chunk-AA6G3W3B.js.map} +0 -0
  161. /package/dist/{chunk-VRWQUUZ7.js.map → chunk-BYWNF25B.js.map} +0 -0
  162. /package/dist/{chunk-NOZDET3Q.js.map → chunk-DGLNT6VO.js.map} +0 -0
  163. /package/dist/{chunk-HOSS72UP.js.map → chunk-EGDUG2ZX.js.map} +0 -0
  164. /package/dist/{chunk-GOYLBPSW.js.map → chunk-EIZUL6JC.js.map} +0 -0
  165. /package/dist/{chunk-YMNFHNZH.js.map → chunk-F476AJQJ.js.map} +0 -0
  166. /package/dist/{chunk-POB7N5UM.js.map → chunk-FJTRNFI4.js.map} +0 -0
  167. /package/dist/{chunk-PQ5FYNY2.js.map → chunk-FONPAA43.js.map} +0 -0
  168. /package/dist/{chunk-JG6AHBJW.js.map → chunk-FREKFMCA.js.map} +0 -0
  169. /package/dist/{chunk-N7IJEGSE.js.map → chunk-GNIMBEOK.js.map} +0 -0
  170. /package/dist/{chunk-YDOLJQ55.js.map → chunk-H6VQ7L5D.js.map} +0 -0
  171. /package/dist/{chunk-LEH4FVBJ.js.map → chunk-IUXTKLZY.js.map} +0 -0
  172. /package/dist/{chunk-OJJ73HLA.js.map → chunk-JCBKGPFE.js.map} +0 -0
  173. /package/dist/{chunk-QZ5JZNXN.js.map → chunk-JLD44JR7.js.map} +0 -0
  174. /package/dist/{chunk-PNT3SZRY.js.map → chunk-K5CM4M65.js.map} +0 -0
  175. /package/dist/{chunk-3BRHOVRU.js.map → chunk-LPDOCXHH.js.map} +0 -0
  176. /package/dist/{chunk-MXE42X3I.js.map → chunk-NCS2NXSP.js.map} +0 -0
  177. /package/dist/{chunk-DI2QWY6J.js.map → chunk-NM6UL4W5.js.map} +0 -0
  178. /package/dist/{chunk-N6JGLQV7.js.map → chunk-QZUT4VTV.js.map} +0 -0
  179. /package/dist/{chunk-F4DXTUHY.js.map → chunk-SZ6QV3DY.js.map} +0 -0
  180. /package/dist/{chunk-OI3UMEW3.js.map → chunk-UF5RTFN3.js.map} +0 -0
  181. /package/dist/{chunk-SRW4IKHM.js.map → chunk-UM22PKA3.js.map} +0 -0
  182. /package/dist/{chunk-U3GJUARA.js.map → chunk-USVA4XWY.js.map} +0 -0
  183. /package/dist/{chunk-PKV3NNM2.js.map → chunk-UX7KPVAM.js.map} +0 -0
  184. /package/dist/{chunk-JCWI43TO.js.map → chunk-VRBGYSSQ.js.map} +0 -0
  185. /package/dist/{chunk-JY327EH4.js.map → chunk-WGM2KSWN.js.map} +0 -0
  186. /package/dist/{chunk-K4DBE5MH.js.map → chunk-WIV37T4U.js.map} +0 -0
  187. /package/dist/{chunk-VSZEV7HG.js.map → chunk-XOOYE37V.js.map} +0 -0
  188. /package/dist/{chunk-JVQNRSWO.js.map → chunk-YCNSMVWG.js.map} +0 -0
  189. /package/dist/{chunk-CKG7T4AD.js.map → chunk-YXFY4YOF.js.map} +0 -0
@@ -1,5 +1,6 @@
1
- import type { BufferEntryState, BufferState, BufferTurn } from "./types.js";
1
+ import type { BufferEntryState, BufferState, BufferTurn, PluginConfig, SignalLevel } from "./types.js";
2
2
  import type { BufferEvictionHooks } from "./buffer-eviction.js";
3
+ import type { TriggerDecision } from "./buffer-types.js";
3
4
 
4
5
  /**
5
6
  * Eviction hooks are pure functions of an entry; one shared instance serves
@@ -459,3 +460,73 @@ export function normalizeBufferState(state: BufferState): BufferState {
459
460
  entries,
460
461
  };
461
462
  }
463
+
464
+ /** Trigger-mode decision for a buffer entry (extracted from SmartBuffer to
465
+ * keep buffer.ts under the file-size ratchet). */
466
+ export function evaluateTriggerDecision(
467
+ config: Pick<PluginConfig, "triggerMode" | "bufferMaxTurns" | "bufferMaxMinutes">,
468
+ entry: BufferEntryState,
469
+ signalLevel: SignalLevel,
470
+ ): TriggerDecision {
471
+ if (config.triggerMode === "smart") {
472
+ if (signalLevel === "high") return "extract_now";
473
+
474
+ if (entry.turns.length >= config.bufferMaxTurns) {
475
+ return "extract_batch";
476
+ }
477
+
478
+ if (entry.lastExtractionAt) {
479
+ const elapsed = Date.now() - new Date(entry.lastExtractionAt).getTime();
480
+ if (elapsed >= config.bufferMaxMinutes * 60_000) {
481
+ return "extract_batch";
482
+ }
483
+ }
484
+
485
+ return "keep_buffering";
486
+ }
487
+
488
+ if (config.triggerMode === "every_n") {
489
+ return entry.turns.length >= config.bufferMaxTurns
490
+ ? "extract_batch"
491
+ : "keep_buffering";
492
+ }
493
+
494
+ if (config.triggerMode === "time_based") {
495
+ if (!entry.lastExtractionAt) {
496
+ return entry.turns.length >= config.bufferMaxTurns
497
+ ? "extract_batch"
498
+ : "keep_buffering";
499
+ }
500
+ const elapsed = Date.now() - new Date(entry.lastExtractionAt).getTime();
501
+ return elapsed >= config.bufferMaxMinutes * 60_000
502
+ ? "extract_batch"
503
+ : "keep_buffering";
504
+ }
505
+
506
+ return "keep_buffering";
507
+ }
508
+
509
+ /** Buffer keys holding turns for `sessionKey` — the direct entry plus any
510
+ * entries whose active or retained turns reference the session. */
511
+ export function matchingSessionBufferKeys(
512
+ entries: Record<string, BufferEntryState>,
513
+ directEntry: BufferEntryState | null,
514
+ sessionKey: string,
515
+ ): string[] {
516
+ const matches: string[] = [];
517
+ const hasSessionTurns = (entry: BufferEntryState | null | undefined): boolean =>
518
+ [...(entry?.turns ?? []), ...(entry?.retainedTurns ?? [])].some(
519
+ (turn) => turn.sessionKey === sessionKey,
520
+ );
521
+ if (hasSessionTurns(directEntry)) {
522
+ matches.push(sessionKey);
523
+ }
524
+
525
+ for (const [bufferKey, entry] of Object.entries(entries)) {
526
+ if (!matches.includes(bufferKey) && hasSessionTurns(entry)) {
527
+ matches.push(bufferKey);
528
+ }
529
+ }
530
+
531
+ return matches;
532
+ }
package/src/buffer.ts CHANGED
@@ -9,7 +9,6 @@ import type {
9
9
  BufferSurpriseEvent,
10
10
  BufferTurn,
11
11
  PluginConfig,
12
- SignalLevel,
13
12
  } from "./types.js";
14
13
  import { resolvePresentationCapabilities, resolveNamespaceCapabilities } from "./capabilities.js";
15
14
  import { resolvePrincipal } from "./namespaces/principal.js";
@@ -25,9 +24,11 @@ import {
25
24
  describeError,
26
25
  EVICTION_HOOKS,
27
26
  entryHoldsAcceptedCapture,
27
+ evaluateTriggerDecision,
28
28
  hasPinnedCaptureScope,
29
29
  liveTurnsFromExtractionSnapshot,
30
30
  matchingQueuedExtractionPrefixLength,
31
+ matchingSessionBufferKeys,
31
32
  normalizeBufferState,
32
33
  probeWithTimeout,
33
34
  selectRetainedDeferredTurns,
@@ -67,6 +68,11 @@ const BUFFER_SAVE_MAX_DEFER_MULTIPLIER = 5;
67
68
  */
68
69
  const MAX_SET_TIMEOUT_MS = 2_147_483_647;
69
70
 
71
+ /** Retry delay for a failed save when `bufferSaveDebounceMs` is 0: a transient
72
+ * failure must still re-arm (PR 3481 review round 3); 1s bounds the dirty
73
+ * window without a hot retry loop on a persistently failing backend. */
74
+ const BUFFER_SAVE_RETRY_DELAY_MS = 1_000;
75
+
70
76
  export class SmartBuffer {
71
77
  private state: BufferState;
72
78
  private loaded = false;
@@ -106,17 +112,18 @@ export class SmartBuffer {
106
112
  private firstPendingAtMs: number | null = null;
107
113
 
108
114
  /** Which sessions' persisted files are stale (per-session incremental saves). */
109
- private readonly persistence = new BufferSessionPersistence();
115
+ private readonly persistence: BufferSessionPersistence;
110
116
 
111
117
  constructor(
112
118
  private readonly config: PluginConfig,
113
119
  private readonly storage: BufferStorage,
114
120
  surpriseProbe: BufferSurpriseProbe | null = null,
115
- /** #3444 test seam: `false` disables the ingress counters (pure pass-through control). */
116
- options: { countIngress?: boolean } = {},
121
+ /** #3444 test seam: `false` disables the ingress counters; `persistence` injects a test-clocked tracker (#3389). */
122
+ options: { countIngress?: boolean; persistence?: BufferSessionPersistence } = {},
117
123
  ) {
118
124
  this.state = { turns: [], lastExtractionAt: null, extractionCount: 0 };
119
125
  this.surpriseProbe = surpriseProbe;
126
+ this.persistence = options.persistence ?? new BufferSessionPersistence();
120
127
  this.ingress = new BufferIngressCounters(undefined, options.countIngress !== false);
121
128
  }
122
129
 
@@ -239,8 +246,12 @@ export class SmartBuffer {
239
246
  this.loaded = true;
240
247
  }
241
248
 
242
- private async saveUnlocked(reconcile?: { key: string; drained: import("./buffer-turn-helpers.js").DrainedTurnSets }): Promise<void> {
243
- const { handedOver, drainedTurns } = await this.persistence.persist(this.storage, this.state, (key) => this.peekEntry(key) ?? undefined, reconcile);
249
+ private async saveUnlocked(
250
+ reconcile?: { key: string; drained: import("./buffer-turn-helpers.js").DrainedTurnSets },
251
+ opts?: { allowDeferral?: boolean },
252
+ ): Promise<import("./buffer-persistence.js").BufferPersistOutcome> {
253
+ const outcome = await this.persistence.persist(this.storage, this.state, (key) => this.peekEntry(key) ?? undefined, reconcile, { allowDeferral: opts?.allowDeferral === true });
254
+ const { handedOver, drainedTurns } = outcome;
244
255
  // A drain tombstone: the turns the drain extracted leave this copy too,
245
256
  // so a stale owner never extracts (or persists) them a second time.
246
257
  for (const [key, drained] of drainedTurns) {
@@ -253,19 +264,20 @@ export class SmartBuffer {
253
264
  }
254
265
  if (key === "default") this.state.turns = entry.turns;
255
266
  }
256
- if (handedOver.length === 0) return;
267
+ if (handedOver.length === 0) return outcome;
257
268
  // A drain claim now owns these sessions' turns (durable in the claim
258
269
  // file): drop the in-memory entries so this process cannot resurrect
259
270
  // them. A later observe for the same key starts a fresh entry whose
260
271
  // turns flow into the claim at the next handover.
261
272
  const entries = this.state.entries;
262
- if (!entries) return;
273
+ if (!entries) return outcome;
263
274
  for (const key of handedOver) {
264
275
  delete entries[key];
265
276
  if (key === "default") {
266
277
  this.state.turns = [];
267
278
  }
268
279
  }
280
+ return outcome;
269
281
  }
270
282
 
271
283
  /** Sync gate for the extraction queue: is this session claimed by a buffer drain? */
@@ -300,21 +312,29 @@ export class SmartBuffer {
300
312
  this.pendingSave = true;
301
313
  if (this.firstPendingAtMs === null) this.firstPendingAtMs = now;
302
314
  if (now - this.firstPendingAtMs >= ms * BUFFER_SAVE_MAX_DEFER_MULTIPLIER) {
303
- // Staleness cap hit: persist now rather than deferring further. Drop the
304
- // armed timer, attempt the write, and only mark clean on success — a
315
+ // Staleness cap hit: run the persist pass inline rather than re-arming
316
+ // the debounce. Session-level deferral (#3389) may still rate-limit a
317
+ // large rewrite; when it does, armDeferredRetry keeps the save pending
318
+ // and retries at the session's eligibility time, so the pass's tail
319
+ // cannot sit in memory waiting for a turn that may never come (3481
320
+ // review). Drop the armed timer and only mark clean on success — a
305
321
  // failure keeps the save pending + re-arms so shutdown/the next timer
306
322
  // retries (issue #1909 review round 2), never diverging memory from disk.
307
323
  clearTimeout(this.saveTimer ?? undefined);
308
324
  this.saveTimer = null;
309
325
  try {
310
- await this.saveUnlocked();
311
- this.pendingSave = false;
312
- this.firstPendingAtMs = null;
326
+ const outcome = await this.saveUnlocked(undefined, { allowDeferral: true });
327
+ if (outcome.deferredRetryDelayMs !== undefined) {
328
+ this.armDeferredRetry(outcome.deferredRetryDelayMs);
329
+ } else {
330
+ this.pendingSave = false;
331
+ this.firstPendingAtMs = null;
332
+ }
313
333
  } catch (err) {
314
334
  log.warn(`buffer.scheduleSave: staleness-cap save failed, keeping it pending: ${describeError(err)}`);
315
335
  this.saveTimer = setTimeout(() => {
316
336
  this.saveTimer = null;
317
- void this.flushPendingSave();
337
+ void this.flushPendingSave({ allowDeferral: true });
318
338
  }, ms);
319
339
  this.saveTimer.unref?.();
320
340
  }
@@ -324,11 +344,28 @@ export class SmartBuffer {
324
344
  clearTimeout(this.saveTimer ?? undefined);
325
345
  this.saveTimer = setTimeout(() => {
326
346
  this.saveTimer = null;
327
- void this.flushPendingSave();
347
+ void this.flushPendingSave({ allowDeferral: true });
328
348
  }, ms);
329
349
  this.saveTimer.unref?.();
330
350
  }
331
351
 
352
+ /**
353
+ * A persist pass deferred one or more large sessions (#3389): keep the save
354
+ * pending and arm a retry for when the earliest becomes rewrite-eligible.
355
+ * Without this the tail of a burst sat in memory until the next turn or a
356
+ * barrier — wider than the sanctioned crash-loss window (PR 3481 review).
357
+ */
358
+ private armDeferredRetry(delayMs: number): void {
359
+ this.pendingSave = true;
360
+ if (this.firstPendingAtMs === null) this.firstPendingAtMs = Date.now();
361
+ clearTimeout(this.saveTimer ?? undefined);
362
+ this.saveTimer = setTimeout(() => {
363
+ this.saveTimer = null;
364
+ void this.flushPendingSave({ allowDeferral: true });
365
+ }, Math.min(Math.max(0, delayMs), MAX_SET_TIMEOUT_MS));
366
+ this.saveTimer.unref?.();
367
+ }
368
+
332
369
  /** Cancel any armed debounced save without persisting. */
333
370
  private cancelScheduledSave(): void {
334
371
  if (this.saveTimer) {
@@ -349,26 +386,33 @@ export class SmartBuffer {
349
386
  * only in the debounced pending state. The pending flag is cleared (and any
350
387
  * armed timer dropped) only after a durable write.
351
388
  */
352
- private async saveNowRetainingPendingOnFailure(context: string): Promise<void> {
389
+ private async saveNowRetainingPendingOnFailure(context: string, opts?: { allowDeferral?: boolean }): Promise<void> {
353
390
  this.pendingSave = true;
354
391
  if (this.firstPendingAtMs === null) this.firstPendingAtMs = Date.now();
355
392
  try {
356
- await this.saveUnlocked();
393
+ const outcome = await this.saveUnlocked(undefined, opts);
394
+ if (outcome.deferredRetryDelayMs !== undefined) {
395
+ this.armDeferredRetry(outcome.deferredRetryDelayMs);
396
+ } else {
397
+ this.cancelScheduledSave();
398
+ }
357
399
  } catch (err) {
358
400
  log.warn(
359
401
  `buffer.${context}: inline save failed, keeping it pending for retry: ${describeError(err)}`,
360
402
  );
361
- const ms = Math.min(this.config.bufferSaveDebounceMs, MAX_SET_TIMEOUT_MS);
362
- if (ms > 0 && !this.saveTimer) {
403
+ const ms = Math.min(
404
+ this.config.bufferSaveDebounceMs || BUFFER_SAVE_RETRY_DELAY_MS,
405
+ MAX_SET_TIMEOUT_MS,
406
+ );
407
+ if (!this.saveTimer) {
363
408
  this.saveTimer = setTimeout(() => {
364
409
  this.saveTimer = null;
365
- void this.flushPendingSave();
410
+ void this.flushPendingSave({ allowDeferral: opts?.allowDeferral === true });
366
411
  }, ms);
367
412
  this.saveTimer.unref?.();
368
413
  }
369
414
  throw err;
370
415
  }
371
- this.cancelScheduledSave();
372
416
  }
373
417
 
374
418
  /**
@@ -385,7 +429,7 @@ export class SmartBuffer {
385
429
  * proceeding to extract_now on a non-durable triggering turn. Default false
386
430
  * keeps the fail-open behavior for the timer/shutdown callers.
387
431
  */
388
- async flushPendingSave(opts?: { throwOnFailure?: boolean }): Promise<void> {
432
+ async flushPendingSave(opts?: { throwOnFailure?: boolean; allowDeferral?: boolean }): Promise<void> {
389
433
  if (this.saveTimer) {
390
434
  clearTimeout(this.saveTimer);
391
435
  this.saveTimer = null;
@@ -400,30 +444,36 @@ export class SmartBuffer {
400
444
  // writes). resetToEmpty-only deletions also land here without a
401
445
  // pending-save flag.
402
446
  if (!this.pendingSave && !this.persistence.hasPending()) return;
403
- await this.saveUnlocked();
447
+ const outcome = await this.saveUnlocked(undefined, { allowDeferral: opts?.allowDeferral === true });
404
448
  // Clear the pending flag INSIDE the same serialized mutation as the
405
- // write (issue #1909 review). Clearing it after the enqueue await
406
- // resolved raced an addTurn interleaving between the write and the
407
- // clear: that turn's scheduleSave re-armed pendingSave + a timer, then
408
- // this clear wiped it and the debounced flush was lost. Atomic
409
- // write+clear means any addTurn runs wholly before (its turn is in the
410
- // write) or wholly after (its pendingSave survives and its timer
411
- // persists it).
412
- this.pendingSave = false;
413
- this.firstPendingAtMs = null;
449
+ // write (issue #1909 review): an addTurn interleaving between the
450
+ // write and the clear would lose its re-armed timer. Deferred
451
+ // sessions keep the flag — still dirty — and armDeferredRetry
452
+ // schedules their write at eligibility.
453
+ if (outcome.deferredRetryDelayMs !== undefined) {
454
+ this.armDeferredRetry(outcome.deferredRetryDelayMs);
455
+ } else {
456
+ this.pendingSave = false;
457
+ this.firstPendingAtMs = null;
458
+ }
414
459
  });
415
460
  } catch (err) {
416
461
  // The write failed: memory and disk diverge (issue #1909 review round 2).
417
462
  // Keep the save PENDING (do NOT clear pendingSave/firstPendingAtMs) so a
418
463
  // graceful shutdown flush and the re-armed timer both retry it — clearing
419
464
  // the flag here would drop the buffered turns permanently. Re-arm a
420
- // background retry when debounced.
465
+ // background retry even when debounce is off (3481 review round 3).
421
466
  log.warn(`buffer.flushPendingSave: save failed, keeping it pending for retry: ${describeError(err)}`);
422
- const ms = Math.min(this.config.bufferSaveDebounceMs, MAX_SET_TIMEOUT_MS);
423
- if (ms > 0 && !this.saveTimer) {
467
+ const ms = Math.min(
468
+ this.config.bufferSaveDebounceMs || BUFFER_SAVE_RETRY_DELAY_MS,
469
+ MAX_SET_TIMEOUT_MS,
470
+ );
471
+ if (!this.saveTimer) {
424
472
  this.saveTimer = setTimeout(() => {
425
473
  this.saveTimer = null;
426
- void this.flushPendingSave();
474
+ // A steady-state retry must not escalate into a barrier write of a
475
+ // rate-limited session (3481 review).
476
+ void this.flushPendingSave({ allowDeferral: opts?.allowDeferral === true });
427
477
  }, ms);
428
478
  this.saveTimer.unref?.();
429
479
  }
@@ -648,7 +698,7 @@ export class SmartBuffer {
648
698
  // see the current turn (it must only flag turns already in the entry).
649
699
  this.ingress.noteAppendedTurn(entry, turn);
650
700
  entry.turns.push(turn);
651
- const decision = this.evaluate(entry, signal.level);
701
+ const decision = evaluateTriggerDecision(this.config, entry, signal.level);
652
702
  // Snapshots serve only extraction decisions and surprise-eligible keep_buffering turns (probe, smart mode, sub-high signal); steady-state buffering copies nothing.
653
703
  const surpriseEligible = this.surpriseProbe !== null && this.config.triggerMode === "smart" && signal.level !== "high";
654
704
  const snapshotsNeeded = decision !== "keep_buffering" || surpriseEligible;
@@ -672,7 +722,12 @@ export class SmartBuffer {
672
722
  // Round 8 thread 4: the write is attempted BEFORE the pending state is
673
723
  // cleared, and a failed write leaves it pending (+ a re-armed timer) for
674
724
  // shutdown/timer retry instead of dropping the in-memory turns.
675
- await this.saveNowRetainingPendingOnFailure("recordTurn");
725
+ // #3389: a keep_buffering turn has no extraction barrier, so this pass
726
+ // may defer rewriting a large session file that was just persisted —
727
+ // the rewrite cadence for huge sessions collapses from per-turn to
728
+ // once per BUFFER_SESSION_DEFER_INTERVAL_MS. A triggering turn is a
729
+ // durability barrier and passes allowDeferral: false.
730
+ await this.saveNowRetainingPendingOnFailure("recordTurn", { allowDeferral: decision === "keep_buffering" });
676
731
  }
677
732
  return {
678
733
  decision,
@@ -823,47 +878,6 @@ export class SmartBuffer {
823
878
  }
824
879
  }
825
880
 
826
- private evaluate(entry: BufferEntryState, signalLevel: SignalLevel): TriggerDecision {
827
- if (this.config.triggerMode === "smart") {
828
- if (signalLevel === "high") return "extract_now";
829
-
830
- if (entry.turns.length >= this.config.bufferMaxTurns) {
831
- return "extract_batch";
832
- }
833
-
834
- if (entry.lastExtractionAt) {
835
- const elapsed =
836
- Date.now() - new Date(entry.lastExtractionAt).getTime();
837
- if (elapsed >= this.config.bufferMaxMinutes * 60_000) {
838
- return "extract_batch";
839
- }
840
- }
841
-
842
- return "keep_buffering";
843
- }
844
-
845
- if (this.config.triggerMode === "every_n") {
846
- return entry.turns.length >= this.config.bufferMaxTurns
847
- ? "extract_batch"
848
- : "keep_buffering";
849
- }
850
-
851
- if (this.config.triggerMode === "time_based") {
852
- if (!entry.lastExtractionAt) {
853
- return entry.turns.length >= this.config.bufferMaxTurns
854
- ? "extract_batch"
855
- : "keep_buffering";
856
- }
857
- const elapsed =
858
- Date.now() - new Date(entry.lastExtractionAt).getTime();
859
- return elapsed >= this.config.bufferMaxMinutes * 60_000
860
- ? "extract_batch"
861
- : "keep_buffering";
862
- }
863
-
864
- return "keep_buffering";
865
- }
866
-
867
881
  getTurns(bufferKey = "default"): BufferTurn[] {
868
882
  const entry = this.peekEntry(bufferKey);
869
883
  if (!entry) return [];
@@ -943,7 +957,11 @@ export class SmartBuffer {
943
957
  }
944
958
  await this.loadUnlocked();
945
959
  assertLifecycle();
946
- const bufferKeys = this.matchingSessionBufferKeysUnlocked(sessionKey);
960
+ const bufferKeys = matchingSessionBufferKeys(
961
+ this.state.entries ?? {},
962
+ this.peekEntry(sessionKey),
963
+ sessionKey,
964
+ );
947
965
  if (bufferKeys.length === 0) {
948
966
  if (hadPendingSave) {
949
967
  assertLifecycle();
@@ -1016,32 +1034,15 @@ export class SmartBuffer {
1016
1034
  return bufferKeys[0] ?? null;
1017
1035
  }
1018
1036
 
1019
- private matchingSessionBufferKeysUnlocked(sessionKey: string): string[] {
1020
- const matches: string[] = [];
1021
- const hasSessionTurns = (entry: BufferEntryState | null | undefined): boolean =>
1022
- [...(entry?.turns ?? []), ...(entry?.retainedTurns ?? [])].some(
1023
- (turn) => typeof turn.sessionKey === "string" && turn.sessionKey === sessionKey,
1024
- );
1025
- const directEntry = this.peekEntry(sessionKey);
1026
- if (hasSessionTurns(directEntry)) {
1027
- matches.push(sessionKey);
1028
- }
1029
-
1030
- const entries = this.state.entries ?? {};
1031
- for (const [bufferKey, entry] of Object.entries(entries)) {
1032
- if (!matches.includes(bufferKey) && hasSessionTurns(entry)) {
1033
- matches.push(bufferKey);
1034
- }
1035
- }
1036
-
1037
- return matches;
1038
- }
1039
-
1040
1037
  async findBufferKeysForSession(sessionKey: string): Promise<string[]> {
1041
1038
  if (typeof sessionKey !== "string" || sessionKey.length === 0) return [];
1042
1039
  await this.mutationChain.catch(() => {});
1043
1040
  await this.load();
1044
- return this.matchingSessionBufferKeysUnlocked(sessionKey);
1041
+ return matchingSessionBufferKeys(
1042
+ this.state.entries ?? {},
1043
+ this.peekEntry(sessionKey),
1044
+ sessionKey,
1045
+ );
1045
1046
  }
1046
1047
 
1047
1048
  async clearAfterExtraction(
@@ -4,17 +4,25 @@ import test from "node:test";
4
4
  import { QmdClient, parseQmdStatusOutput } from "./qmd.js";
5
5
  import type { QmdSearchResult } from "./types.js";
6
6
 
7
+ type DaemonCheckInternals = {
8
+ available: boolean;
9
+ daemonAvailable: boolean;
10
+ probeDaemon: () => Promise<boolean>;
11
+ searchViaDaemon: (
12
+ query: string,
13
+ collection: string | undefined,
14
+ maxResults: number
15
+ ) => Promise<{ results: QmdSearchResult[]; degraded: boolean } | null>;
16
+ };
17
+
7
18
  test("QmdClient rechecks daemon availability before returning unavailable", async () => {
8
19
  const client = new QmdClient("memories", 3, {
9
20
  daemonUrl: "stdio://qmd",
10
21
  daemonRecheckIntervalMs: 0,
11
22
  });
12
- const internals = client as unknown as {
13
- available: boolean;
14
- daemonAvailable: boolean;
15
- probeDaemon: () => Promise<boolean>;
16
- searchViaDaemon: (query: string, collection: string | undefined, maxResults: number) => Promise<QmdSearchResult[]>;
17
- };
23
+ // SAFETY: the stub drives private QmdClient fields by name; every member
24
+ // it touches is exercised below.
25
+ const internals: DaemonCheckInternals = client as never;
18
26
  let probeCount = 0;
19
27
  internals.available = false;
20
28
  internals.daemonAvailable = false;
@@ -23,15 +31,18 @@ test("QmdClient rechecks daemon availability before returning unavailable", asyn
23
31
  internals.daemonAvailable = true;
24
32
  return true;
25
33
  };
26
- internals.searchViaDaemon = async (query, collection, maxResults) => [
27
- {
28
- docid: `${collection}:${maxResults}`,
29
- path: "memory.md",
30
- snippet: query,
31
- score: 1,
32
- transport: "daemon",
33
- },
34
- ];
34
+ internals.searchViaDaemon = async (query, collection, maxResults) => ({
35
+ degraded: false,
36
+ results: [
37
+ {
38
+ docid: `${collection}:${maxResults}`,
39
+ path: "memory.md",
40
+ snippet: query,
41
+ score: 1,
42
+ transport: "daemon",
43
+ },
44
+ ],
45
+ });
35
46
 
36
47
  const results = await client.search("slow startup", "memories", 3);
37
48