@remnic/core 10.0.187 → 10.0.189

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 (193) hide show
  1. package/dist/access-admin-ops-surface.js +39 -39
  2. package/dist/access-cli.js +39 -39
  3. package/dist/access-extraction-force-flush-preempt.js +39 -39
  4. package/dist/access-extraction-force-flush.d.ts.map +1 -1
  5. package/dist/access-extraction-force-flush.js +39 -39
  6. package/dist/access-http-briefing.js +39 -39
  7. package/dist/access-http-query.js +39 -39
  8. package/dist/access-http.js +39 -39
  9. package/dist/access-identity-continuity-surface.js +39 -39
  10. package/dist/access-lcm-surface.js +39 -39
  11. package/dist/access-mcp.js +39 -39
  12. package/dist/access-observe-helpers.d.ts +1 -4
  13. package/dist/access-observe-helpers.d.ts.map +1 -1
  14. package/dist/access-observe-helpers.js +1 -1
  15. package/dist/access-observe-write-surface.d.ts +0 -4
  16. package/dist/access-observe-write-surface.d.ts.map +1 -1
  17. package/dist/access-observe-write-surface.js +39 -39
  18. package/dist/access-operations-batch.js +39 -39
  19. package/dist/access-operations.js +39 -39
  20. package/dist/access-recall-concurrency.js +39 -39
  21. package/dist/access-recall-response.js +39 -39
  22. package/dist/access-recall-surface.js +39 -39
  23. package/dist/access-service.d.ts +0 -2
  24. package/dist/access-service.d.ts.map +1 -1
  25. package/dist/access-service.js +39 -39
  26. package/dist/active-recall.js +1 -1
  27. package/dist/briefing.js +2 -2
  28. package/dist/buffer-add-turns-bounded.js +2 -2
  29. package/dist/buffer-admission-idempotency.d.ts.map +1 -1
  30. package/dist/buffer-admission-idempotency.js +1 -1
  31. package/dist/buffer-persistence.d.ts +14 -0
  32. package/dist/buffer-persistence.d.ts.map +1 -1
  33. package/dist/buffer-persistence.js +3 -1
  34. package/dist/buffer.js +4 -4
  35. package/dist/calibration.js +3 -3
  36. package/dist/causal-consolidation.js +3 -3
  37. package/dist/{chunk-2ZS7CB5H.js → chunk-2I3ETW3G.js} +2 -2
  38. package/dist/{chunk-PSUSA5SM.js → chunk-2VNMSEZR.js} +2 -2
  39. package/dist/{chunk-LANV6I63.js → chunk-56BNHKZM.js} +7 -7
  40. package/dist/{chunk-3FEQNKMB.js → chunk-5WDUY2ZZ.js} +2 -2
  41. package/dist/{chunk-BANMPRSC.js → chunk-65DWWJKI.js} +2 -2
  42. package/dist/{chunk-O5ZCDK32.js → chunk-6AMFGXG2.js} +39 -11
  43. package/dist/chunk-6AMFGXG2.js.map +1 -0
  44. package/dist/{chunk-VZBKCRU7.js → chunk-6MDHK6NO.js} +2 -2
  45. package/dist/{chunk-2RAVHJCD.js → chunk-6OHCNTKU.js} +2 -2
  46. package/dist/{chunk-P5FF44G3.js → chunk-7X6EZ2QB.js} +4 -4
  47. package/dist/{chunk-K5RGHUX7.js → chunk-A32EBVCZ.js} +2 -2
  48. package/dist/{chunk-L2DYRQQH.js → chunk-ABPOW3SX.js} +73 -103
  49. package/dist/chunk-ABPOW3SX.js.map +1 -0
  50. package/dist/{chunk-KVM3BS5K.js → chunk-ATPY63F5.js} +2 -2
  51. package/dist/chunk-B256MMS7.js +205 -0
  52. package/dist/chunk-B256MMS7.js.map +1 -0
  53. package/dist/{chunk-MOWLANEJ.js → chunk-C6Y2YHJL.js} +2 -2
  54. package/dist/{chunk-IMT7NTFV.js → chunk-CIAQK2OU.js} +6 -1
  55. package/dist/{chunk-IMT7NTFV.js.map → chunk-CIAQK2OU.js.map} +1 -1
  56. package/dist/{chunk-AJVCM2E3.js → chunk-CYX7JI4O.js} +2 -2
  57. package/dist/{chunk-76KL37ON.js → chunk-D3FP4JQI.js} +2 -2
  58. package/dist/{chunk-TQXKUQFX.js → chunk-FZU62GIV.js} +7 -6
  59. package/dist/chunk-FZU62GIV.js.map +1 -0
  60. package/dist/{chunk-YDGQYG4L.js → chunk-H442UKDV.js} +8 -8
  61. package/dist/{chunk-FXDQO7VX.js → chunk-HL53XYHC.js} +3 -3
  62. package/dist/{chunk-4VFEN3WT.js → chunk-IMSLPQJB.js} +2 -2
  63. package/dist/{chunk-FKLSIQBF.js → chunk-K3JGILZC.js} +3 -3
  64. package/dist/{chunk-JRHOL6B5.js → chunk-K6BS5RB4.js} +2 -2
  65. package/dist/{chunk-HHCLV572.js → chunk-KVTUUU7H.js} +2 -2
  66. package/dist/{chunk-TRFSTCQK.js → chunk-LL6WEMTC.js} +34 -6
  67. package/dist/chunk-LL6WEMTC.js.map +1 -0
  68. package/dist/{chunk-2WITFW6F.js → chunk-NKHRIDYP.js} +2 -2
  69. package/dist/{chunk-KYZMCH4I.js → chunk-NN3LMWKA.js} +12 -4
  70. package/dist/chunk-NN3LMWKA.js.map +1 -0
  71. package/dist/{chunk-CYTTY4M2.js → chunk-OPXK5IQU.js} +47 -47
  72. package/dist/chunk-OPXK5IQU.js.map +1 -0
  73. package/dist/{chunk-CTWWMEGR.js → chunk-PCGBESAN.js} +2 -2
  74. package/dist/{chunk-MDXZIU5X.js → chunk-QGT5KNQT.js} +2 -2
  75. package/dist/{chunk-YJZDRM33.js → chunk-QXHWOUS6.js} +3 -3
  76. package/dist/{chunk-OVJAQWHO.js → chunk-RPOG6HLI.js} +2 -2
  77. package/dist/{chunk-2QQCCUXF.js → chunk-RVODERA5.js} +2 -2
  78. package/dist/{chunk-FQE5QN5Q.js → chunk-TAPF7T26.js} +2 -2
  79. package/dist/{chunk-7UTCETGK.js → chunk-TQODBIMW.js} +2 -2
  80. package/dist/{chunk-KZJEKKK6.js → chunk-VQQZJ6KJ.js} +3 -3
  81. package/dist/{chunk-I233SAGS.js → chunk-X3ERYOLO.js} +2 -2
  82. package/dist/{chunk-UCCXPMTP.js → chunk-XQF2KLV5.js} +2 -2
  83. package/dist/{chunk-LPYGM6RE.js → chunk-XWPYK5T4.js} +2 -2
  84. package/dist/{chunk-7EPEZYX3.js → chunk-YVXR7CPS.js} +2 -2
  85. package/dist/cli.js +39 -39
  86. package/dist/coding/export-okf-codegraph.js +1 -1
  87. package/dist/compounding/engine.js +3 -3
  88. package/dist/config.js +1 -1
  89. package/dist/connectors/codex-materialize-runner.js +2 -2
  90. package/dist/connectors/index.js +2 -2
  91. package/dist/convergence-refresh.js +4 -4
  92. package/dist/corpus-watermark.js +4 -4
  93. package/dist/entity-retrieval.js +2 -2
  94. package/dist/explicit-capture.js +39 -39
  95. package/dist/extraction.js +6 -6
  96. package/dist/harmonic-retrieval.js +2 -2
  97. package/dist/index.js +39 -39
  98. package/dist/local-llm-helpers.d.ts.map +1 -1
  99. package/dist/local-llm-helpers.js +2 -2
  100. package/dist/local-llm-transport.d.ts +82 -9
  101. package/dist/local-llm-transport.d.ts.map +1 -1
  102. package/dist/local-llm-transport.js +11 -3
  103. package/dist/local-llm.d.ts.map +1 -1
  104. package/dist/local-llm.js +3 -3
  105. package/dist/location/index.js +3 -3
  106. package/dist/maintenance/memory-governance.js +2 -2
  107. package/dist/maintenance/rebuild-memory-lifecycle-ledger.js +2 -2
  108. package/dist/maintenance/rebuild-memory-projection-runner.js +4 -4
  109. package/dist/maintenance/rebuild-memory-projection.js +3 -3
  110. package/dist/namespaces/migrate.js +3 -3
  111. package/dist/namespaces/storage.js +2 -2
  112. package/dist/operator-doctor-corpus.js +5 -5
  113. package/dist/operator-toolkit.js +8 -8
  114. package/dist/orchestration/backlog-scheduler.js +40 -40
  115. package/dist/orchestration/buffer-drain-runner.js +40 -40
  116. package/dist/orchestration/extraction-queue-coordinator.d.ts +14 -1
  117. package/dist/orchestration/extraction-queue-coordinator.d.ts.map +1 -1
  118. package/dist/orchestration/maintenance.js +13 -13
  119. package/dist/orchestrator.js +39 -39
  120. package/dist/recall-navigation.js +39 -39
  121. package/dist/resume-bundles.js +1 -1
  122. package/dist/semantic-consolidation.js +3 -3
  123. package/dist/semantic-rule-promotion.js +2 -2
  124. package/dist/semantic-rule-verifier.js +2 -2
  125. package/dist/source-agent-qualifier.js +2 -2
  126. package/dist/standup/build.js +2 -2
  127. package/dist/storage/entity-canonical-id-migration-runner.d.ts.map +1 -1
  128. package/dist/storage.js +1 -1
  129. package/dist/summarizer.js +4 -4
  130. package/dist/support-passport/index.js +4 -4
  131. package/dist/transfer/export-okf.js +2 -2
  132. package/dist/verified-recall.js +2 -2
  133. package/dist/who-knows-cli.js +3 -3
  134. package/dist/who-knows.js +2 -2
  135. package/package.json +2 -2
  136. package/src/access-extraction-force-flush-preempt-coordinator.test.ts +71 -0
  137. package/src/access-extraction-force-flush.ts +20 -56
  138. package/src/access-observe-helpers.test.ts +71 -88
  139. package/src/access-observe-helpers.ts +60 -73
  140. package/src/access-observe-write-surface.ts +1 -22
  141. package/src/access-service-observe-lcm-parity.test.ts +176 -89
  142. package/src/access-service-observe-scope.test.ts +18 -86
  143. package/src/access-service.ts +0 -13
  144. package/src/buffer-admission-idempotency.test.ts +115 -0
  145. package/src/buffer-admission-idempotency.ts +67 -11
  146. package/src/buffer-persistence.ts +46 -5
  147. package/src/local-llm-headers-timeout.test.ts +246 -16
  148. package/src/local-llm-helpers.ts +14 -4
  149. package/src/local-llm-transport.ts +253 -16
  150. package/src/local-llm.ts +7 -8
  151. package/src/orchestration/extraction-queue-coordinator.ts +34 -3
  152. package/src/storage/entity-canonical-id-migration-runner.test.ts +90 -0
  153. package/src/storage/entity-canonical-id-migration-runner.ts +10 -0
  154. package/dist/chunk-5YQXWVCP.js +0 -74
  155. package/dist/chunk-5YQXWVCP.js.map +0 -1
  156. package/dist/chunk-CYTTY4M2.js.map +0 -1
  157. package/dist/chunk-KYZMCH4I.js.map +0 -1
  158. package/dist/chunk-L2DYRQQH.js.map +0 -1
  159. package/dist/chunk-O5ZCDK32.js.map +0 -1
  160. package/dist/chunk-TQXKUQFX.js.map +0 -1
  161. package/dist/chunk-TRFSTCQK.js.map +0 -1
  162. /package/dist/{chunk-2ZS7CB5H.js.map → chunk-2I3ETW3G.js.map} +0 -0
  163. /package/dist/{chunk-PSUSA5SM.js.map → chunk-2VNMSEZR.js.map} +0 -0
  164. /package/dist/{chunk-LANV6I63.js.map → chunk-56BNHKZM.js.map} +0 -0
  165. /package/dist/{chunk-3FEQNKMB.js.map → chunk-5WDUY2ZZ.js.map} +0 -0
  166. /package/dist/{chunk-BANMPRSC.js.map → chunk-65DWWJKI.js.map} +0 -0
  167. /package/dist/{chunk-VZBKCRU7.js.map → chunk-6MDHK6NO.js.map} +0 -0
  168. /package/dist/{chunk-2RAVHJCD.js.map → chunk-6OHCNTKU.js.map} +0 -0
  169. /package/dist/{chunk-P5FF44G3.js.map → chunk-7X6EZ2QB.js.map} +0 -0
  170. /package/dist/{chunk-K5RGHUX7.js.map → chunk-A32EBVCZ.js.map} +0 -0
  171. /package/dist/{chunk-KVM3BS5K.js.map → chunk-ATPY63F5.js.map} +0 -0
  172. /package/dist/{chunk-MOWLANEJ.js.map → chunk-C6Y2YHJL.js.map} +0 -0
  173. /package/dist/{chunk-AJVCM2E3.js.map → chunk-CYX7JI4O.js.map} +0 -0
  174. /package/dist/{chunk-76KL37ON.js.map → chunk-D3FP4JQI.js.map} +0 -0
  175. /package/dist/{chunk-YDGQYG4L.js.map → chunk-H442UKDV.js.map} +0 -0
  176. /package/dist/{chunk-FXDQO7VX.js.map → chunk-HL53XYHC.js.map} +0 -0
  177. /package/dist/{chunk-4VFEN3WT.js.map → chunk-IMSLPQJB.js.map} +0 -0
  178. /package/dist/{chunk-FKLSIQBF.js.map → chunk-K3JGILZC.js.map} +0 -0
  179. /package/dist/{chunk-JRHOL6B5.js.map → chunk-K6BS5RB4.js.map} +0 -0
  180. /package/dist/{chunk-HHCLV572.js.map → chunk-KVTUUU7H.js.map} +0 -0
  181. /package/dist/{chunk-2WITFW6F.js.map → chunk-NKHRIDYP.js.map} +0 -0
  182. /package/dist/{chunk-CTWWMEGR.js.map → chunk-PCGBESAN.js.map} +0 -0
  183. /package/dist/{chunk-MDXZIU5X.js.map → chunk-QGT5KNQT.js.map} +0 -0
  184. /package/dist/{chunk-YJZDRM33.js.map → chunk-QXHWOUS6.js.map} +0 -0
  185. /package/dist/{chunk-OVJAQWHO.js.map → chunk-RPOG6HLI.js.map} +0 -0
  186. /package/dist/{chunk-2QQCCUXF.js.map → chunk-RVODERA5.js.map} +0 -0
  187. /package/dist/{chunk-FQE5QN5Q.js.map → chunk-TAPF7T26.js.map} +0 -0
  188. /package/dist/{chunk-7UTCETGK.js.map → chunk-TQODBIMW.js.map} +0 -0
  189. /package/dist/{chunk-KZJEKKK6.js.map → chunk-VQQZJ6KJ.js.map} +0 -0
  190. /package/dist/{chunk-I233SAGS.js.map → chunk-X3ERYOLO.js.map} +0 -0
  191. /package/dist/{chunk-UCCXPMTP.js.map → chunk-XQF2KLV5.js.map} +0 -0
  192. /package/dist/{chunk-LPYGM6RE.js.map → chunk-XWPYK5T4.js.map} +0 -0
  193. /package/dist/{chunk-7EPEZYX3.js.map → chunk-YVXR7CPS.js.map} +0 -0
@@ -52,7 +52,6 @@ export function pendingObserveScopeHint(options: {
52
52
  type PendingObserveExtraction = {
53
53
  promise: Promise<void>;
54
54
  running: Promise<void>;
55
- controllers: Set<AbortController>;
56
55
  };
57
56
 
58
57
  export class PendingObserveExtractionTracker {
@@ -130,7 +129,7 @@ export class PendingObserveExtractionTracker {
130
129
  return `${sessionKey}\u0000${principal ?? ""}\u0000${namespace ?? ""}`;
131
130
  }
132
131
 
133
- track(key: string, extraction: Promise<void>, controller: AbortController): void {
132
+ track(key: string, extraction: Promise<void>): void {
134
133
  const previous = this.entries.get(key);
135
134
  const promise = previous
136
135
  ? Promise.allSettled([previous.promise, extraction]).then((results) => {
@@ -142,13 +141,11 @@ export class PendingObserveExtractionTracker {
142
141
  if (rejected) throw rejected.reason;
143
142
  })
144
143
  : extraction;
145
- const controllers = previous?.controllers ?? new Set<AbortController>();
146
- controllers.add(controller);
147
- const entry = { promise, running: previous?.running ?? extraction, controllers };
144
+ const entry = { promise, running: previous?.running ?? extraction };
148
145
  this.entries.set(key, entry);
149
146
  // Any settle (success OR rejection — preemption is just one rejection
150
147
  // kind) ends the pending entry; leaving a settled failure tracked wedged
151
- // the key and kept every controller ever registered for it alive.
148
+ // the key and chained later observes onto a dead promise.
152
149
  void promise
153
150
  .then(() => {
154
151
  if (this.entries.get(key) === entry) this.entries.delete(key);
@@ -158,53 +155,6 @@ export class PendingObserveExtractionTracker {
158
155
  });
159
156
  }
160
157
 
161
- cancelPreparations(sessionKey: string, scopeHint?: string): void {
162
- for (const reservation of this.preparations.get(sessionKey) ?? []) {
163
- if (
164
- scopeHint !== undefined &&
165
- reservation.scopeHint !== undefined &&
166
- reservation.scopeHint !== scopeHint
167
- ) {
168
- continue;
169
- }
170
- reservation.cancelled = true;
171
- }
172
- }
173
-
174
- cancel(
175
- sessionKey: string,
176
- principal?: string,
177
- namespace?: string,
178
- scopeHint?: string,
179
- reason?: Error,
180
- ): void {
181
- for (const reservation of this.preparations.get(sessionKey) ?? []) {
182
- if (!preparationMatchesScope(reservation, principal, namespace, scopeHint)) continue;
183
- reservation.cancelled = true;
184
- }
185
-
186
- this.abortTracked(sessionKey, principal, namespace, reason);
187
- }
188
-
189
- private abortTracked(
190
- sessionKey: string,
191
- principal: string | undefined,
192
- namespace: string | undefined,
193
- reason?: Error,
194
- ): void {
195
- for (const [key, entry] of this.entries) {
196
- const [entrySessionKey, entryPrincipal, entryNamespace] = key.split("\u0000");
197
- if (
198
- entrySessionKey !== sessionKey ||
199
- (principal !== undefined && entryPrincipal !== (principal ?? "")) ||
200
- (namespace !== undefined && entryNamespace !== (namespace ?? ""))
201
- ) continue;
202
- // Snapshot: an abort listener may track() synchronously; iterating the
203
- // shared live set would abort that new admission or never terminate.
204
- for (const controller of [...entry.controllers]) controller.abort(reason);
205
- }
206
- }
207
-
208
158
  async wait(
209
159
  sessionKey: string,
210
160
  principal: string | undefined,
@@ -215,45 +165,82 @@ export class PendingObserveExtractionTracker {
215
165
  preemptAfterAdmission?: () => void,
216
166
  ): Promise<void> {
217
167
  const key = this.key(sessionKey, principal, namespace);
218
- let cancelled = abortSignal?.aborted === true;
219
- const abortTracked = (): void => {
220
- cancelled = true;
221
- this.cancel(sessionKey, principal, namespace, scopeHint);
168
+ // COS-825: a dead force-flush caller (abort or deadline) stops only its
169
+ // own WAIT. The tracked extractions were accepted by other observes and
170
+ // keep running to completion — stopping must never cancel them.
171
+ let stopped = abortSignal?.aborted === true;
172
+ const { promise: stoppedPromise, resolve: stopWaiting } = Promise.withResolvers<void>();
173
+ const stop = (): void => {
174
+ if (stopped) return;
175
+ stopped = true;
176
+ stopWaiting();
177
+ };
178
+ let abortHandler: (() => void) | undefined;
179
+ if (abortSignal) {
180
+ abortHandler = () => stop();
181
+ abortSignal.addEventListener("abort", abortHandler, { once: true });
182
+ }
183
+ registerCancellation?.(stop);
184
+ // The outcome is TAGGED at the reaction site: a rejection must reach the
185
+ // caller even when the tracker's own settle handler deletes the entry
186
+ // first (a bare `Promise.race` loses that race to the deletion).
187
+ type SettleOutcome =
188
+ | { kind: "stopped" }
189
+ | { kind: "settled" }
190
+ | { kind: "rejected"; error: unknown };
191
+ const raceSettle = async (work: Promise<void>): Promise<SettleOutcome> => {
192
+ try {
193
+ await Promise.race([work, stoppedPromise]);
194
+ } catch (error) {
195
+ return { kind: "rejected", error };
196
+ }
197
+ return stopped ? { kind: "stopped" } : { kind: "settled" };
222
198
  };
223
- registerCancellation?.(abortTracked);
224
- abortSignal?.addEventListener("abort", abortTracked, { once: true });
225
199
  try {
226
- await this.waitForPreparations(sessionKey, principal, namespace, scopeHint);
227
- if (cancelled || abortSignal?.aborted) return;
200
+ await Promise.race([
201
+ this.waitForPreparations(sessionKey, principal, namespace, scopeHint),
202
+ stoppedPromise,
203
+ ]);
204
+ if (stopped) return;
228
205
  if (preemptAfterAdmission) {
229
206
  preemptAfterAdmission();
230
207
  const running = this.entries.get(key)?.running;
231
208
  if (!running) return;
232
- try {
233
- await running;
234
- } catch (error) {
209
+ const outcome = await raceSettle(running);
210
+ if (outcome.kind === "stopped") return;
211
+ if (outcome.kind === "rejected") {
235
212
  if (this.entries.get(key)?.running === running) this.entries.delete(key);
236
- if (!(error instanceof Error && isPreemptedExtraction(error))) throw error;
213
+ if (!(outcome.error instanceof Error && isPreemptedExtraction(outcome.error))) {
214
+ throw outcome.error;
215
+ }
237
216
  }
238
217
  return;
239
218
  }
240
219
  while (true) {
241
220
  const entry = this.entries.get(key);
242
221
  if (!entry) return;
243
- try {
244
- await entry.promise;
245
- } catch (error) {
246
- if (this.entries.get(key) !== entry) continue;
247
- this.entries.delete(key);
248
- if (error instanceof Error && isPreemptedExtraction(error)) return;
249
- throw error;
222
+ const outcome = await raceSettle(entry.promise);
223
+ if (outcome.kind === "stopped") return;
224
+ if (outcome.kind === "rejected") {
225
+ if (!(outcome.error instanceof Error && isPreemptedExtraction(outcome.error))) {
226
+ // A replaced entry means a newer generation owns the wait; a
227
+ // REMOVED entry means this generation settled — its failure is
228
+ // ours to surface.
229
+ if (this.entries.get(key) === undefined) {
230
+ this.entries.delete(key);
231
+ throw outcome.error;
232
+ }
233
+ continue;
234
+ }
235
+ if (this.entries.get(key) === entry) this.entries.delete(key);
236
+ return;
250
237
  }
251
238
  if (this.entries.get(key) !== entry) continue;
252
239
  this.entries.delete(key);
253
240
  return;
254
241
  }
255
242
  } finally {
256
- abortSignal?.removeEventListener("abort", abortTracked);
243
+ if (abortHandler && abortSignal) abortSignal.removeEventListener("abort", abortHandler);
257
244
  }
258
245
  }
259
246
  }
@@ -121,14 +121,6 @@ export interface AccessObserveWriteSurfaceDeps {
121
121
  authenticatedPrincipal?: string;
122
122
  }
123
123
  ): Promise<MemoryScopePlan>;
124
- cancelPendingObservePreparations?(sessionKey: string, scopeHint?: string): void;
125
- cancelPendingObserveExtractions?(
126
- sessionKey: string,
127
- principal?: string,
128
- namespace?: string,
129
- scopeHint?: string,
130
- reason?: Error,
131
- ): void;
132
124
  resolveReadableNamespace(namespace: string | undefined, principal?: string): string;
133
125
  validateWriteCandidate(
134
126
  request: EngramAccessMemoryStoreRequest | EngramAccessSuggestionSubmitRequest,
@@ -146,19 +138,6 @@ export class AccessObserveWriteSurface {
146
138
  private readonly pendingObserveExtractions = new PendingObserveExtractionTracker();
147
139
  private readonly observeTranscriptPersister = new ObserveTranscriptPersister();
148
140
 
149
- public cancelPendingObservePreparations(sessionKey: string, scopeHint?: string): void {
150
- this.pendingObserveExtractions.cancelPreparations(sessionKey, scopeHint);
151
- }
152
-
153
- public cancelPendingObserveExtractions(
154
- sessionKey: string,
155
- principal?: string,
156
- namespace?: string,
157
- scopeHint?: string,
158
- reason?: Error,
159
- ): void {
160
- this.pendingObserveExtractions.cancel(sessionKey, principal, namespace, scopeHint, reason);
161
- }
162
141
  constructor(private readonly deps: AccessObserveWriteSurfaceDeps) {}
163
142
 
164
143
  private quarantineStore(): WriteQuarantineStore {
@@ -898,7 +877,7 @@ export class AccessObserveWriteSurface {
898
877
  extraction.catch((err) => {
899
878
  log.error(`access-observe background extraction failed: ${err}`);
900
879
  });
901
- this.pendingObserveExtractions.track(trackedExtractionKey, extraction, observeAbortController);
880
+ this.pendingObserveExtractions.track(trackedExtractionKey, extraction);
902
881
  extractionQueued = true;
903
882
  };
904
883
  }
@@ -33,6 +33,7 @@ import { EngramAccessInputError, EngramAccessService } from "./access-service.js
33
33
  import { EngramAccessForbiddenError } from "./access-errors.js";
34
34
  import { Orchestrator } from "./orchestrator.js";
35
35
  import { ExtractionDeadlineError } from "./orchestration/extraction-run.js";
36
+ import { ExtractionQueueCoordinator } from "./orchestration/extraction-queue-coordinator.js";
36
37
  import { SessionOwnershipError } from "./orchestration/session-context.js";
37
38
  import type { EngramAccessObserveRequest, MemoryScopePlan } from "./access-service.js";
38
39
  import {
@@ -656,55 +657,53 @@ test("#2128: a failed observe extraction is consumed after force-flush reports i
656
657
  await assert.doesNotReject(() => service.extractionForceFlush({ sessionKey }));
657
658
  });
658
659
 
659
- test("#2128: force-flush deadline cancels the pending observe extraction", async () => {
660
+ test("#2128/COS-825: force-flush deadline stops the wait but not the pending observe extraction", async (t) => {
660
661
  const probe = makeParityProbe({ namespacesEnabled: false } as Partial<PluginConfig>);
661
662
  let extractionSignal: AbortSignal | undefined;
663
+ const { promise: pendingExtraction, resolve: resolveExtraction } = Promise.withResolvers<void>();
662
664
  probe.orch.ingestReplayBatch = async (_turns, options = {}) => {
663
665
  extractionSignal = options.abortSignal;
664
- const { promise, reject } = Promise.withResolvers<void>();
665
- options.abortSignal?.addEventListener(
666
- "abort",
667
- () => reject(new Error("extraction cancelled")),
668
- { once: true },
669
- );
670
- options.onExtractionQueued?.(promise);
666
+ options.onExtractionQueued?.(pendingExtraction);
671
667
  };
672
668
  const service = new EngramAccessService(probe.orch);
673
- const sessionKey = "deadline-cancelled-extraction";
669
+ const sessionKey = "deadline-keeps-extraction";
674
670
 
675
671
  await service.observe(observeRequest({ sessionKey, skipExtraction: false }));
676
- const keepAlive = setInterval(() => {}, 5);
672
+ // Mocked clock, same reason as the #2206 deadline test below: the flush
673
+ // deadline is a real unref'd timer in production, and a drained event loop
674
+ // on a loaded runner can otherwise strand the flush.
675
+ t.mock.timers.enable({ apis: ["setTimeout", "Date"] });
677
676
  try {
677
+ const flush = service.extractionForceFlush({ sessionKey, deadlineMs: 25 });
678
+ await new Promise<void>((resolve) => setImmediate(resolve));
679
+ t.mock.timers.tick(25);
678
680
  await assert.rejects(
679
- service.extractionForceFlush({
680
- sessionKey,
681
- deadlineMs: 25,
682
- }),
681
+ flush,
683
682
  (error: unknown) =>
684
683
  error instanceof EngramAccessInputError &&
685
684
  error.message.includes("pending_observe_extraction"),
686
685
  );
687
686
  } finally {
688
- clearInterval(keepAlive);
687
+ t.mock.timers.reset();
689
688
  }
690
- assert.equal(extractionSignal?.aborted, true);
689
+ // The queued extraction was accepted by another observe: a flush caller's
690
+ // own budget expiring must not cancel it (COS-825).
691
+ assert.equal(extractionSignal?.aborted, false);
692
+ resolveExtraction();
693
+ await pendingExtraction;
694
+ assert.equal((await service.extractionForceFlush({ sessionKey })).flushed, true);
691
695
  });
692
696
 
693
- test("#2128: force-flush abort signal cancels the pending observe extraction", async () => {
697
+ test("#2128/COS-825: force-flush abort stops the wait but not the pending observe extraction", async () => {
694
698
  const probe = makeParityProbe({ namespacesEnabled: false } as Partial<PluginConfig>);
695
699
  let extractionSignal: AbortSignal | undefined;
700
+ const { promise: pendingExtraction, resolve: resolveExtraction } = Promise.withResolvers<void>();
696
701
  probe.orch.ingestReplayBatch = async (_turns, options = {}) => {
697
702
  extractionSignal = options.abortSignal;
698
- const { promise, reject } = Promise.withResolvers<void>();
699
- options.abortSignal?.addEventListener(
700
- "abort",
701
- () => reject(new Error("extraction cancelled")),
702
- { once: true },
703
- );
704
- options.onExtractionQueued?.(promise);
703
+ options.onExtractionQueued?.(pendingExtraction);
705
704
  };
706
705
  const service = new EngramAccessService(probe.orch);
707
- const sessionKey = "abort-cancelled-extraction";
706
+ const sessionKey = "abort-keeps-extraction";
708
707
  const abortController = new AbortController();
709
708
 
710
709
  await service.observe(observeRequest({ sessionKey, skipExtraction: false }));
@@ -718,10 +717,15 @@ test("#2128: force-flush abort signal cancels the pending observe extraction", a
718
717
  flushPromise,
719
718
  (error: unknown) => error instanceof Error && error.message === "extraction force-flush aborted",
720
719
  );
721
- assert.equal(extractionSignal?.aborted, true);
720
+ // The queued extraction belongs to another observe: a disconnecting flush
721
+ // caller must not cancel it (COS-825).
722
+ assert.equal(extractionSignal?.aborted, false);
723
+ resolveExtraction();
724
+ await pendingExtraction;
725
+ assert.equal((await service.extractionForceFlush({ sessionKey })).flushed, true);
722
726
  });
723
727
 
724
- test("#2128: force-flush abort only cancels the resolved namespace barrier", async () => {
728
+ test("#2128/COS-825: force-flush abort leaves every namespace barrier untouched", async () => {
725
729
  const probe = makeParityProbe({
726
730
  namespacePolicies: [
727
731
  { name: "project-a", readPrincipals: ["pi-geek"], writePrincipals: ["pi-geek"] },
@@ -733,13 +737,8 @@ test("#2128: force-flush abort only cancels the resolved namespace barrier", asy
733
737
  probe.orch.ingestReplayBatch = async (_turns, options = {}) => {
734
738
  const namespace = options.writeNamespaceOverride ?? "";
735
739
  extractionSignals.set(namespace, options.abortSignal);
736
- const { promise, resolve, reject } = Promise.withResolvers<void>();
740
+ const { promise, resolve } = Promise.withResolvers<void>();
737
741
  extractionResolvers.set(namespace, resolve);
738
- options.abortSignal?.addEventListener(
739
- "abort",
740
- () => reject(options.abortSignal?.reason ?? new Error("extraction cancelled")),
741
- { once: true },
742
- );
743
742
  options.onExtractionQueued?.(promise);
744
743
  };
745
744
  const service = new EngramAccessService(probe.orch);
@@ -779,10 +778,18 @@ test("#2128: force-flush abort only cancels the resolved namespace barrier", asy
779
778
  flushA,
780
779
  (error: unknown) => error instanceof Error && error.message === "extraction force-flush aborted",
781
780
  );
782
- assert.equal(extractionSignals.get(namespaceA)?.aborted, true);
781
+ // Neither scope's accepted extraction may be cancelled by the dead caller.
782
+ assert.equal(extractionSignals.get(namespaceA)?.aborted, false);
783
783
  assert.equal(extractionSignals.get(namespaceB)?.aborted, false);
784
-
784
+ extractionResolvers.get(namespaceA)?.();
785
785
  extractionResolvers.get(namespaceB)?.();
786
+ await assert.doesNotReject(() =>
787
+ service.extractionForceFlush({
788
+ sessionKey,
789
+ authenticatedPrincipal: "pi-geek",
790
+ namespace: namespaceA,
791
+ }),
792
+ );
786
793
  await assert.doesNotReject(() =>
787
794
  service.extractionForceFlush({
788
795
  sessionKey,
@@ -1055,7 +1062,7 @@ test("#3140: a duration deadline reaches scope resolution and aborts it when it
1055
1062
  assert.equal(probe.extractionForceFlushCalls.length, 0);
1056
1063
  });
1057
1064
 
1058
- test("#2206: abort during scope resolution cancels pre-resolution observe preparations", async () => {
1065
+ test("#2206/COS-825: abort during scope resolution leaves pre-resolution observe preparations intact", async () => {
1059
1066
  const probe = makeParityProbe(withSelfPolicyPrefix("pi-geek"));
1060
1067
  const service = new EngramAccessService(probe.orch);
1061
1068
  const abortController = new AbortController();
@@ -1086,6 +1093,15 @@ test("#2206: abort during scope resolution cancels pre-resolution observe prepar
1086
1093
  signalFlushScopeStarted();
1087
1094
  return new Promise<never>(() => {});
1088
1095
  };
1096
+ probe.orch.ingestReplayBatch = async (turns, options = {}) => {
1097
+ probe.extractionCalls.push({
1098
+ sessionKeys: turns.map((turn) => turn.sessionKey),
1099
+ writeNamespaceOverride: options.writeNamespaceOverride,
1100
+ principalOverride: options.principalOverride,
1101
+ sessionOwnerPrincipal: options.sessionOwnerPrincipal,
1102
+ });
1103
+ options.onExtractionQueued?.(Promise.resolve());
1104
+ };
1089
1105
 
1090
1106
  const observe = service.observe(observeRequest({
1091
1107
  sessionKey: "pi-geek:abort-scope-resolution",
@@ -1106,13 +1122,13 @@ test("#2206: abort during scope resolution cancels pre-resolution observe prepar
1106
1122
  await assert.rejects(flush, /extraction force-flush aborted/);
1107
1123
  releaseObserveScope();
1108
1124
  const response = await observe;
1109
- // Cancelled preparation aborts only the extraction; the durable capture is
1110
- // preserved (#3252), so ingest is still called once with nothing queued.
1111
- assert.equal(response.extractionQueued, false);
1125
+ // The observe's work is its own: a dead flush caller must not cancel its
1126
+ // preparation, so the accepted capture still queues extraction (COS-825).
1127
+ assert.equal(response.extractionQueued, true);
1112
1128
  assert.equal(probe.extractionCalls.length, 1);
1113
1129
  });
1114
1130
 
1115
- test("#2206: scope-resolution deadline cancels preparations by raw projectTag and cwd hints", async (t) => {
1131
+ test("#2206/COS-825: scope-resolution deadline leaves raw projectTag and cwd preparations intact", async (t) => {
1116
1132
  // The deadline budget is a real, unref'd timer in production
1117
1133
  // (session-context.ts), so a 1ms wall-clock budget can elapse BEFORE the
1118
1134
  // flush enters the blocked scope stub on a loaded runner (assertion then
@@ -1154,6 +1170,15 @@ test("#2206: scope-resolution deadline cancels preparations by raw projectTag an
1154
1170
  flushScopeStarted = true;
1155
1171
  return new Promise<never>(() => {});
1156
1172
  };
1173
+ probe.orch.ingestReplayBatch = async (turns, options = {}) => {
1174
+ probe.extractionCalls.push({
1175
+ sessionKeys: turns.map((turn) => turn.sessionKey),
1176
+ writeNamespaceOverride: options.writeNamespaceOverride,
1177
+ principalOverride: options.principalOverride,
1178
+ sessionOwnerPrincipal: options.sessionOwnerPrincipal,
1179
+ });
1180
+ options.onExtractionQueued?.(Promise.resolve());
1181
+ };
1157
1182
 
1158
1183
  const observe = service.observe(observeRequest({
1159
1184
  sessionKey: "pi-geek:raw-hint-deadline",
@@ -1186,9 +1211,9 @@ test("#2206: scope-resolution deadline cancels preparations by raw projectTag an
1186
1211
  releaseObserveScope();
1187
1212
  }
1188
1213
  const response = await observe;
1189
- // Cancelled preparation aborts only the extraction; the durable capture
1190
- // is preserved (#3252), so ingest is still called once with nothing queued.
1191
- assert.equal(response.extractionQueued, false);
1214
+ // The flush budget expiring is the flush's problem only: the observe's
1215
+ // preparation survives and its capture still queues extraction (COS-825).
1216
+ assert.equal(response.extractionQueued, true);
1192
1217
  assert.equal(probe.extractionCalls.length, 1);
1193
1218
  }
1194
1219
  });
@@ -1229,52 +1254,6 @@ test("#2128: aborted or expired extraction force-flush never touches a buffer",
1229
1254
  assert.equal(probe.extractionForceFlushCalls.length, 0);
1230
1255
  });
1231
1256
 
1232
- test("#2128: self-deps wires force-flush cancellation into the observe tracker", async () => {
1233
- const probe = makeParityProbe(withSelfPolicyPrefix("pi-geek"));
1234
- const service = new EngramAccessService(probe.orch);
1235
- const cancellations: Array<{
1236
- sessionKey: string;
1237
- principal?: string;
1238
- namespace?: string;
1239
- }> = [];
1240
- const surface = (service as unknown as {
1241
- accessObserveWriteSurface: {
1242
- cancelPendingObserveExtractions(
1243
- sessionKey: string,
1244
- principal?: string,
1245
- namespace?: string,
1246
- ): void;
1247
- };
1248
- }).accessObserveWriteSurface;
1249
- surface.cancelPendingObserveExtractions = (sessionKey, principal, namespace) => {
1250
- cancellations.push({ sessionKey, principal, namespace });
1251
- };
1252
-
1253
- // #3140: a tiny budget elapsing while scope work is blocked still cancels
1254
- // the pending observe preparations via the same deadline hook.
1255
- const internals = service as unknown as {
1256
- resolveMemoryScopePlan: (request: unknown) => Promise<never>;
1257
- };
1258
- internals.resolveMemoryScopePlan = async () => new Promise<never>(() => {});
1259
- await assert.rejects(
1260
- () =>
1261
- service.extractionForceFlush({
1262
- sessionKey: "pi-geek:cancel-hook",
1263
- namespace: "pi-geek",
1264
- authenticatedPrincipal: "pi-geek",
1265
- deadlineMs: 1,
1266
- }),
1267
- (error: unknown) =>
1268
- error instanceof EngramAccessInputError &&
1269
- error.message === "replay extraction deadline exceeded (scope_resolution)",
1270
- );
1271
- assert.deepEqual(cancellations, [{
1272
- sessionKey: "pi-geek:cancel-hook",
1273
- principal: "pi-geek",
1274
- namespace: "pi-geek",
1275
- }]);
1276
- });
1277
-
1278
1257
  test("#2128: late extraction deadline is surfaced as an access input error", async () => {
1279
1258
  const probe = makeParityProbe(withSelfPolicyPrefix("pi-geek"));
1280
1259
  probe.orch.flushSession = async () => {
@@ -1295,6 +1274,114 @@ test("#2128: late extraction deadline is surfaced as an access input error", asy
1295
1274
  );
1296
1275
  });
1297
1276
 
1277
+ test("COS-825: a session already preempted once is waited for, not re-preempted, by the next flush", async () => {
1278
+ // SAFETY: { namespacesEnabled: false } is a valid PluginConfig override —
1279
+ // the same single-store shape every other test in this file passes.
1280
+ const probe = makeParityProbe({ namespacesEnabled: false } as Partial<PluginConfig>);
1281
+ const coordinator = new ExtractionQueueCoordinator(2);
1282
+ // The flush's preempt callback reads the coordinator off the orchestrator
1283
+ // stub at runtime; Object.assign avoids narrowing the Orchestrator type.
1284
+ Object.assign(probe.orch, { extractionQueueCoordinator: coordinator });
1285
+ const abortedKeys: string[] = [];
1286
+ const slot = coordinator.registerPreemptSlot("repreempt-guarded");
1287
+ slot.arm(() => void abortedKeys.push("repreempt-guarded"));
1288
+ // An earlier flush already preempted this session's running extraction once;
1289
+ // the slot here stands in for its retry, which must be allowed to finish.
1290
+ coordinator.preemptKeyed("repreempt-guarded");
1291
+ assert.deepEqual(abortedKeys, ["repreempt-guarded"]);
1292
+
1293
+ const { promise: pendingExtraction, resolve: resolveExtraction } = Promise.withResolvers<void>();
1294
+ probe.orch.ingestReplayBatch = async (_turns, options = {}) => {
1295
+ options.onExtractionQueued?.(pendingExtraction);
1296
+ };
1297
+ const service = new EngramAccessService(probe.orch);
1298
+ const sessionKey = "repreempt-guarded";
1299
+ await service.observe(observeRequest({ sessionKey, skipExtraction: false }));
1300
+
1301
+ const flushPromise = service.extractionForceFlush({ sessionKey, deadlineMs: 5000 });
1302
+ await new Promise<void>((resolve) => setImmediate(resolve));
1303
+ // The flush's wait admission must not kill the retried generation.
1304
+ assert.deepEqual(abortedKeys, ["repreempt-guarded"]);
1305
+ resolveExtraction();
1306
+ assert.equal((await flushPromise).flushed, true);
1307
+ assert.equal(probe.extractionForceFlushCalls.length, 1);
1308
+ });
1309
+
1310
+ test("COS-825: the first flush still preempts the running extraction for its own session", async () => {
1311
+ // SAFETY: { namespacesEnabled: false } is a valid PluginConfig override —
1312
+ // the same single-store shape every other test in this file passes.
1313
+ const probe = makeParityProbe({ namespacesEnabled: false } as Partial<PluginConfig>);
1314
+ const coordinator = new ExtractionQueueCoordinator(2);
1315
+ // The flush's preempt callback reads the coordinator off the orchestrator
1316
+ // stub at runtime; Object.assign avoids narrowing the Orchestrator type.
1317
+ Object.assign(probe.orch, { extractionQueueCoordinator: coordinator });
1318
+ const abortedKeys: string[] = [];
1319
+ const slot = coordinator.registerPreemptSlot("first-preempt");
1320
+ slot.arm(() => void abortedKeys.push("first-preempt"));
1321
+
1322
+ const { promise: pendingExtraction, resolve: resolveExtraction } = Promise.withResolvers<void>();
1323
+ probe.orch.ingestReplayBatch = async (_turns, options = {}) => {
1324
+ options.onExtractionQueued?.(pendingExtraction);
1325
+ };
1326
+ const service = new EngramAccessService(probe.orch);
1327
+ const sessionKey = "first-preempt";
1328
+ await service.observe(observeRequest({ sessionKey, skipExtraction: false }));
1329
+
1330
+ const flushPromise = service.extractionForceFlush({ sessionKey, deadlineMs: 5000 });
1331
+ await new Promise<void>((resolve) => setImmediate(resolve));
1332
+ // Force-flush priority is kept: the first preemption per session still fires.
1333
+ assert.deepEqual(abortedKeys, ["first-preempt"]);
1334
+ resolveExtraction();
1335
+ assert.equal((await flushPromise).flushed, true);
1336
+ });
1337
+
1338
+ test("COS-825: one dead flush caller cannot abort a deep queue of observe extractions", async () => {
1339
+ // SAFETY: { namespacesEnabled: false } is a valid PluginConfig override —
1340
+ // the same single-store shape every other test in this file passes.
1341
+ const probe = makeParityProbe({ namespacesEnabled: false } as Partial<PluginConfig>);
1342
+ const queued: Array<{
1343
+ promise: Promise<void>;
1344
+ signal: AbortSignal | undefined;
1345
+ resolve: () => void;
1346
+ }> = [];
1347
+ probe.orch.ingestReplayBatch = async (_turns, options = {}) => {
1348
+ const { promise, resolve } = Promise.withResolvers<void>();
1349
+ queued.push({ promise, signal: options.abortSignal, resolve });
1350
+ options.onExtractionQueued?.(promise);
1351
+ };
1352
+ const service = new EngramAccessService(probe.orch);
1353
+ const sessionKey = "deep-queue-one-cascade";
1354
+
1355
+ // The production failure shape: one force-flush call whose caller times out
1356
+ // used to abort EVERY generation queued under the session (thousands of
1357
+ // `extraction aborted (during_storage)` per call, versus ~2 preemptions,
1358
+ // because preemption kills only the running task while the cancel cascade
1359
+ // killed all queued ones).
1360
+ for (let index = 0; index < 50; index += 1) {
1361
+ await service.observe(observeRequest({ sessionKey, skipExtraction: false }));
1362
+ }
1363
+ assert.equal(queued.length, 50);
1364
+
1365
+ const abortController = new AbortController();
1366
+ const flushPromise = service.extractionForceFlush({
1367
+ sessionKey,
1368
+ abortSignal: abortController.signal,
1369
+ });
1370
+ await new Promise<void>((resolve) => setImmediate(resolve));
1371
+ abortController.abort();
1372
+ await assert.rejects(
1373
+ flushPromise,
1374
+ (error) => error instanceof Error && error.message === "extraction force-flush aborted",
1375
+ );
1376
+ assert.ok(
1377
+ queued.every((entry) => entry.signal?.aborted === false),
1378
+ "no queued generation may be aborted by a dead flush caller",
1379
+ );
1380
+ for (const entry of queued) entry.resolve();
1381
+ await Promise.all(queued.map((entry) => entry.promise));
1382
+ assert.equal((await service.extractionForceFlush({ sessionKey })).flushed, true);
1383
+ });
1384
+
1298
1385
  test("#2128: force-flush scope resolution does not overwrite a concurrent observe context", async () => {
1299
1386
  const probe = makeParityProbe(withSelfPolicyPrefix("pi-geek"));
1300
1387
  const service = new EngramAccessService(probe.orch);