@cortexkit/opencode-magic-context 0.49.104 → 0.49.105

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 (149) hide show
  1. package/dist/auto-search-worker.js +3 -3
  2. package/dist/chunk-embedding-write-worker.js +8 -5
  3. package/dist/{context-7hbmnpe8.js → context-wtnrsjkp.js} +113 -136
  4. package/dist/{embedding-backfill-aratv25b.js → embedding-backfill-kqwx0vhj.js} +4 -4
  5. package/dist/features/magic-context/chunk-embedding-write-worker-install-failure.fixture.d.ts +2 -0
  6. package/dist/features/magic-context/chunk-embedding-write-worker-install-failure.fixture.d.ts.map +1 -0
  7. package/dist/features/magic-context/chunk-scope-repair-revision.d.ts +16 -1
  8. package/dist/features/magic-context/chunk-scope-repair-revision.d.ts.map +1 -1
  9. package/dist/features/magic-context/dreamer/task-executor.d.ts.map +1 -1
  10. package/dist/features/magic-context/dreamer/verify-checkout.d.ts +2 -0
  11. package/dist/features/magic-context/dreamer/verify-checkout.d.ts.map +1 -0
  12. package/dist/features/magic-context/memory/embedding-worker-observer.fixture.d.ts +26 -0
  13. package/dist/features/magic-context/memory/embedding-worker-observer.fixture.d.ts.map +1 -0
  14. package/dist/features/magic-context/message-fts-rowid-map-startup-worker-test-support.d.ts +2 -0
  15. package/dist/features/magic-context/message-fts-rowid-map-startup-worker-test-support.d.ts.map +1 -0
  16. package/dist/features/magic-context/project-embedding-registry.d.ts +5 -0
  17. package/dist/features/magic-context/project-embedding-registry.d.ts.map +1 -1
  18. package/dist/features/magic-context/search-pool-fixture.d.ts +15 -0
  19. package/dist/features/magic-context/search-pool-fixture.d.ts.map +1 -1
  20. package/dist/features/magic-context/storage-db.d.ts.map +1 -1
  21. package/dist/hooks/magic-context/compartment-runner-incremental.d.ts.map +1 -1
  22. package/dist/hooks/magic-context/compartment-runner-types.d.ts +4 -1
  23. package/dist/hooks/magic-context/compartment-runner-types.d.ts.map +1 -1
  24. package/dist/hooks/magic-context/compartment-runner.d.ts.map +1 -1
  25. package/dist/hooks/magic-context/history-boundary-repair.d.ts +7 -2
  26. package/dist/hooks/magic-context/history-boundary-repair.d.ts.map +1 -1
  27. package/dist/hooks/magic-context/transform-compartment-phase.d.ts +1 -0
  28. package/dist/hooks/magic-context/transform-compartment-phase.d.ts.map +1 -1
  29. package/dist/hooks/magic-context/transform.d.ts +1 -0
  30. package/dist/hooks/magic-context/transform.d.ts.map +1 -1
  31. package/dist/{index-3nxhxeeg.js → index-1j4q0bd6.js} +4 -4
  32. package/dist/{index-fd3hkyk1.js → index-42fsf88t.js} +1 -1
  33. package/dist/{index-jjxpmypb.js → index-7z5cvfpg.js} +1 -1
  34. package/dist/{index-a9wn0d9h.js → index-8vv7axxg.js} +3 -3
  35. package/dist/{index-8yj4vd7k.js → index-92p5yfpp.js} +1 -1
  36. package/dist/{index-sqvkh5d0.js → index-9m2b5mwf.js} +20 -7
  37. package/dist/{index-mwjvjn0p.js → index-a3t1ck7g.js} +6 -6
  38. package/dist/{index-4ba3zp54.js → index-as8bg7eh.js} +365 -113
  39. package/dist/{index-8eke8yh2.js → index-cxh5g5bt.js} +1 -1
  40. package/dist/{index-vegw385y.js → index-cy5fn70d.js} +89 -1
  41. package/dist/{index-4dywj733.js → index-dzb1yc9w.js} +1 -1
  42. package/dist/{index-tvh3y650.js → index-edafv9d7.js} +5 -5
  43. package/dist/{index-8gzmeyae.js → index-ff1hqh4a.js} +3 -3
  44. package/dist/{index-ke0mkz7g.js → index-g1h1efr0.js} +1 -1
  45. package/dist/{index-f455a0g3.js → index-k37h4yrb.js} +5 -3
  46. package/dist/{index-3rp2b482.js → index-mg6cwqw2.js} +217 -24
  47. package/dist/{index-4536jdzj.js → index-xzs1fxzz.js} +2 -2
  48. package/dist/{index-hyvxmz3e.js → index-y1875y4h.js} +1 -1
  49. package/dist/{index-4v50y0jr.js → index-ydevzvfs.js} +1 -1
  50. package/dist/{index-ab86c21b.js → index-zj0ra8vs.js} +1 -1
  51. package/dist/index.js +50 -59
  52. package/dist/migration-worker.js +3 -3
  53. package/dist/{project-embedding-registry-1n4cexsv.js → project-embedding-registry-0z0nd73p.js} +3 -3
  54. package/dist/raw-ordinal-warmup-worker.js +2 -2
  55. package/dist/{recomp-orchestrator-16rs8aty.js → recomp-orchestrator-zagjzbz5.js} +12 -12
  56. package/dist/{render-f32trg2t.js → render-vwp72qd0.js} +6 -6
  57. package/dist/{search-v9ywqb4f.js → search-7e1rcqb7.js} +9 -9
  58. package/dist/{search-archive-yh6xtvrx.js → search-archive-6tr0gcf7.js} +2 -2
  59. package/dist/shared/sqlite-busy-test-support.d.ts +21 -0
  60. package/dist/shared/sqlite-busy-test-support.d.ts.map +1 -0
  61. package/dist/shared/sqlite-write-locker-test-support.d.ts +12 -0
  62. package/dist/shared/sqlite-write-locker-test-support.d.ts.map +1 -1
  63. package/dist/{store-wpx314rk.js → store-4eeezg83.js} +2 -2
  64. package/dist/{store-reader-c5fwa9qx.js → store-reader-g8w2wp88.js} +1 -1
  65. package/dist/{transform-postprocess-phase-yef4mxk3.js → transform-postprocess-phase-v3p3q2gf.js} +13 -13
  66. package/dist/v2/auto-search-worker.js +3 -3
  67. package/dist/v2/chunk-embedding-write-worker.js +8 -5
  68. package/dist/v2/{context-mk2h2ven.js → context-fbdac7qt.js} +163 -147
  69. package/dist/v2/{embedding-backfill-kyn5sv0f.js → embedding-backfill-e44pv5db.js} +4 -4
  70. package/dist/v2/event-subscription.fixture.d.ts +9 -0
  71. package/dist/v2/event-subscription.fixture.d.ts.map +1 -0
  72. package/dist/v2/hidden-model-activity.d.ts +13 -0
  73. package/dist/v2/hidden-model-activity.d.ts.map +1 -1
  74. package/dist/v2/hooks/context.d.ts +1 -0
  75. package/dist/v2/hooks/context.d.ts.map +1 -1
  76. package/dist/v2/hooks/dream-trigger.d.ts +2 -1
  77. package/dist/v2/hooks/dream-trigger.d.ts.map +1 -1
  78. package/dist/v2/hooks/event-subscription-worker.d.ts +11 -0
  79. package/dist/v2/hooks/event-subscription-worker.d.ts.map +1 -0
  80. package/dist/v2/hooks/types.d.ts +1 -0
  81. package/dist/v2/hooks/types.d.ts.map +1 -1
  82. package/dist/v2/hooks/update-check.d.ts +1 -0
  83. package/dist/v2/hooks/update-check.d.ts.map +1 -1
  84. package/dist/v2/{message-index-bounded-j1sxtefe.js → message-index-bounded-nwqfb1p5.js} +3 -3
  85. package/dist/v2/migration-worker.js +3 -3
  86. package/dist/v2/{project-embedding-registry-1jv2rxhb.js → project-embedding-registry-rhzjnypp.js} +3 -3
  87. package/dist/v2/raw-ordinal-warmup-worker.js +4 -4
  88. package/dist/v2/{read-session-chunk-p6z3kmdj.js → read-session-chunk-brqatg83.js} +2 -2
  89. package/dist/v2/{recomp-orchestrator-5t2csd46.js → recomp-orchestrator-1ech6k2n.js} +14 -14
  90. package/dist/v2/{render-jpj43axy.js → render-pfe3smhx.js} +10 -10
  91. package/dist/v2/{search-archive-wbhxp0p1.js → search-archive-r8krrz47.js} +5 -5
  92. package/dist/v2/{search-w9m2fd5c.js → search-sffewrs4.js} +12 -12
  93. package/dist/v2/{server-47ajg9xc.js → server-16115spd.js} +1 -1
  94. package/dist/v2/server-28jqb7s0.js +6 -0
  95. package/dist/v2/{server-qg8jyfxa.js → server-5xx10mqe.js} +1 -1
  96. package/dist/v2/{server-t45hgcsg.js → server-7jw608jk.js} +2 -2
  97. package/dist/v2/{server-8f92sd2r.js → server-7pxjk184.js} +6 -4
  98. package/dist/v2/{server-3mb205v9.js → server-83rjf4df.js} +1 -1
  99. package/dist/v2/{server-3gnpqjez.js → server-9t4yjj20.js} +26 -11
  100. package/dist/v2/{server-ga6y57vh.js → server-c32505fr.js} +6 -4
  101. package/dist/v2/{server-8m5wk6aq.js → server-cpb7b1f9.js} +5 -5
  102. package/dist/v2/{server-qdpd8h27.js → server-fn6k1ack.js} +1 -1
  103. package/dist/v2/{server-zsbc0n4v.js → server-ghb2q1z9.js} +1 -1
  104. package/dist/v2/{server-af51b1zg.js → server-hqcdvs2n.js} +11 -11
  105. package/dist/v2/{server-9ms9b75c.js → server-j00jprwm.js} +4 -6
  106. package/dist/v2/{server-xpy46ddq.js → server-jtd5vq5e.js} +3 -3
  107. package/dist/v2/{server-b01a7dhj.js → server-kk2kbzq3.js} +1 -1
  108. package/dist/v2/{server-mc5t7k8v.js → server-ma0qhqg9.js} +1 -1
  109. package/dist/v2/{server-x22jtpna.js → server-n3bfqd0j.js} +4 -2
  110. package/dist/v2/{server-wmpgvvc4.js → server-pjvqyg6g.js} +365 -113
  111. package/dist/v2/{server-jrs4gny6.js → server-qtajgx1e.js} +89 -1
  112. package/dist/v2/server-t104h957.js +177 -0
  113. package/dist/v2/{server-j09jx1n9.js → server-v2r04xds.js} +1 -1
  114. package/dist/v2/{server-7c5p0bh1.js → server-z77hman6.js} +1 -1
  115. package/dist/v2/server.js +31 -40
  116. package/dist/v2/{storage-tags-s7nvvyg8.js → storage-tags-ee72g2zv.js} +1 -1
  117. package/dist/v2/{store-mba47sxn.js → store-9rsrj5pt.js} +2 -2
  118. package/dist/v2/{store-reader-w7w8vfsy.js → store-reader-tb0f9621.js} +1 -1
  119. package/dist/v2/store-reader.d.ts +1 -1
  120. package/dist/v2/store-reader.d.ts.map +1 -1
  121. package/dist/v2/tui/index.d.ts.map +1 -1
  122. package/dist/v2/{v2-archive-reader-5njmg3a3.js → v2-archive-reader-0xysfgxh.js} +1 -1
  123. package/dist/v2/{wrapup-orchestrator-ykgx8hw8.js → wrapup-orchestrator-8d4ak3x3.js} +14 -14
  124. package/dist/{v2-archive-reader-y38khjax.js → v2-archive-reader-fac1zmhj.js} +1 -1
  125. package/dist/{wrapup-orchestrator-a9tshrp4.js → wrapup-orchestrator-wz10b94c.js} +13 -13
  126. package/package.json +1 -1
  127. package/src/config/migrate-config-location.test.ts +41 -29
  128. package/src/shared/model-suggestion-retry.test.ts +137 -90
  129. package/src/shared/off-thread-migration-clock.test.ts +19 -9
  130. package/src/shared/prompt-async-transport.test.ts +125 -42
  131. package/src/shared/rpc-async-probes.test.ts +56 -36
  132. package/src/shared/rpc-client.test.ts +51 -18
  133. package/src/shared/sqlite-acquisition-routing.test.ts +79 -22
  134. package/src/shared/sqlite-busy-budget-review.test.ts +129 -111
  135. package/src/shared/sqlite-busy-test-support.ts +154 -0
  136. package/src/shared/sqlite-foreground-wait.test.ts +213 -156
  137. package/src/shared/sqlite-pass-scope.test.ts +142 -105
  138. package/src/shared/sqlite-turn-deadline.test.ts +149 -124
  139. package/src/shared/sqlite-write-locker-test-support.ts +44 -12
  140. package/src/shared/stable-json-linear.test.ts +29 -11
  141. package/src/shared/startup-maintenance-policy.test.ts +72 -2
  142. package/src/shared/storage-busy.test.ts +45 -18
  143. package/src/shared/storage-file-mutex-review.test.ts +65 -51
  144. package/src/shared/tui-preferences.test.ts +15 -5
  145. package/src/shared/worker-shutdown.test.ts +26 -20
  146. package/src/tui/data/notification-socket.test.ts +220 -108
  147. package/src/v2/tui/index.ts +5 -1
  148. package/src/v2/tui/status-dialog-fallback.test.ts +23 -1
  149. package/dist/v2/server-84w6rvvf.js +0 -14
@@ -97,6 +97,34 @@ function request(signal?: AbortSignal) {
97
97
  };
98
98
  }
99
99
 
100
+ function freezePollClock() {
101
+ jest.useFakeTimers({ doNotFake: ["setImmediate"] });
102
+ jest.setSystemTime(new Date("2026-08-11T12:00:00Z"));
103
+ }
104
+
105
+ const drainHostReplies = () => new Promise<void>((resolve) => setImmediate(resolve));
106
+
107
+ async function advancePoll(ms: number) {
108
+ jest.advanceTimersByTime(ms);
109
+ // Let the mock host replies reach the waiter before driving its next timer.
110
+ await drainHostReplies();
111
+ }
112
+
113
+ function observeRun(run: Promise<unknown>) {
114
+ let result: { status: "fulfilled" | "rejected"; value: unknown } | undefined;
115
+ void run.then(
116
+ (value) => {
117
+ result = { status: "fulfilled", value };
118
+ },
119
+ (value: unknown) => {
120
+ result = { status: "rejected", value };
121
+ },
122
+ );
123
+ return () => result;
124
+ }
125
+
126
+ afterEach(() => jest.useRealTimers());
127
+
100
128
  describe("supportsPromptAsync", () => {
101
129
  test("requires both prompt_async and session status", () => {
102
130
  expect(supportsPromptAsync(asyncHost({ plan: ["settle"] }).client)).toBe(true);
@@ -157,15 +185,26 @@ describe("promptAsyncAndWaitForIdle", () => {
157
185
  });
158
186
 
159
187
  test("fails when no run starts within the start grace", async () => {
188
+ freezePollClock();
160
189
  const host = asyncHost({ plan: ["idle-pending"] });
161
190
  host.promptAsync.mockImplementation(async () => ({ data: undefined }));
162
191
 
163
- await expect(
192
+ const result = observeRun(
164
193
  promptAsyncAndWaitForIdle(host.client, request(), {
165
194
  pollIntervalMs: 1,
166
195
  startGraceMs: 20,
167
196
  }),
168
- ).rejects.toThrow("did not start a run");
197
+ );
198
+ await drainHostReplies();
199
+ await advancePoll(19);
200
+ expect(result()).toBeUndefined();
201
+ await advancePoll(1);
202
+ expect(result()).toEqual({
203
+ status: "rejected",
204
+ value: expect.objectContaining({
205
+ message: expect.stringContaining("did not start a run"),
206
+ }),
207
+ });
169
208
  });
170
209
 
171
210
  test("ignores provider errors and retry parts from before the current send", async () => {
@@ -217,15 +256,23 @@ describe("promptAsyncAndWaitForIdle", () => {
217
256
  });
218
257
 
219
258
  test("stops waiting as soon as the caller's signal aborts", async () => {
259
+ freezePollClock();
220
260
  const host = asyncHost({ plan: ["busy"] });
221
261
  const controller = new AbortController();
222
- setTimeout(() => controller.abort(), 20);
223
-
224
- await expect(
262
+ const result = observeRun(
225
263
  promptAsyncAndWaitForIdle(host.client, request(controller.signal), {
226
264
  pollIntervalMs: 5,
227
265
  }),
228
- ).rejects.toBeDefined();
266
+ );
267
+ await drainHostReplies();
268
+ await advancePoll(5);
269
+ expect(host.polls()).toBe(1);
270
+ expect(result()).toBeUndefined();
271
+ const reason = new Error("caller cancelled");
272
+ controller.abort(reason);
273
+ await drainHostReplies();
274
+ expect(result()).toEqual({ status: "rejected", value: reason });
275
+ expect(host.polls()).toBe(1);
229
276
  });
230
277
  });
231
278
 
@@ -253,6 +300,7 @@ describe("dreamer budget on an async child", () => {
253
300
  expect(states).toEqual([{ spent: 58, finalizeFired: true, sessionId: "ses-child" }]);
254
301
  });
255
302
  test("finalizes a zero-usage OpenCode mapper at 58 steps, before the hard ceiling", async () => {
303
+ freezePollClock();
256
304
  const messages: unknown[] = [];
257
305
  let sends = 0;
258
306
  let aborted = false;
@@ -303,22 +351,28 @@ describe("dreamer budget on an async child", () => {
303
351
  },
304
352
  },
305
353
  };
306
- await promptAsyncAndWaitForIdle(
307
- client as never,
308
- {
309
- ...request(),
310
- signal: AbortSignal.timeout(200),
311
- body: { ...request().body, agent: "dreamer-memory-mapper" },
312
- },
313
- {
314
- tokenBudget: 3_000_000,
315
- pollIntervalMs: 1,
316
- startGraceMs: 100,
317
- onBudgetUpdate: (state) => states.push(state),
318
- },
354
+ const result = observeRun(
355
+ promptAsyncAndWaitForIdle(
356
+ client as never,
357
+ {
358
+ ...request(),
359
+ body: { ...request().body, agent: "dreamer-memory-mapper" },
360
+ },
361
+ {
362
+ tokenBudget: 3_000_000,
363
+ pollIntervalMs: 1,
364
+ startGraceMs: 100,
365
+ onBudgetUpdate: (state) => states.push(state),
366
+ },
367
+ ),
319
368
  );
369
+ await drainHostReplies();
370
+ await advancePoll(1);
320
371
  expect(sends).toBe(2);
372
+ expect(aborted).toBe(true);
321
373
  expect(states).toContainEqual(expect.objectContaining({ finalizeFired: true, spent: 0 }));
374
+ await advancePoll(1);
375
+ expect(result()).toEqual({ status: "fulfilled", value: undefined });
322
376
  });
323
377
  test("sums prompt usage across validation retries in the same child", async () => {
324
378
  const messages: unknown[] = [];
@@ -527,6 +581,7 @@ describe("dreamer budget on an async child", () => {
527
581
  });
528
582
  }
529
583
  test("finalizes once, refuses two tool calls, and keeps agent and tools unchanged", async () => {
584
+ freezePollClock();
530
585
  const messages: Array<{
531
586
  info: {
532
587
  id: string;
@@ -584,16 +639,22 @@ describe("dreamer budget on an async child", () => {
584
639
  },
585
640
  },
586
641
  } as never;
587
- const run = promptAsyncAndWaitForIdle(
588
- client,
589
- {
590
- ...request(),
591
- body: { agent: "dreamer-memory-mapper", parts: [{ type: "text", text: "go" }] },
592
- },
593
- { pollIntervalMs: 1, tokenBudget: 100 },
642
+ const result = observeRun(
643
+ promptAsyncAndWaitForIdle(
644
+ client,
645
+ {
646
+ ...request(),
647
+ body: { agent: "dreamer-memory-mapper", parts: [{ type: "text", text: "go" }] },
648
+ },
649
+ { pollIntervalMs: 1, tokenBudget: 100 },
650
+ ),
594
651
  );
595
- // Wait for the follow-up to be enqueued before simulating the tool hook.
596
- while (prompts.length < 2) await new Promise((resolve) => setTimeout(resolve, 1));
652
+ await drainHostReplies();
653
+ await advancePoll(1);
654
+ // The follow-up has been sent; leave its next status poll parked while
655
+ // the host attempts the tool calls.
656
+ expect(prompts).toHaveLength(2);
657
+ expect(result()).toBeUndefined();
597
658
  const before = createDroppedInputToolExecuteBeforeHook();
598
659
  await expect(
599
660
  before({ sessionID: "ses-child", tool: "read" }, { args: { path: "a" } }),
@@ -601,7 +662,11 @@ describe("dreamer budget on an async child", () => {
601
662
  await expect(
602
663
  before({ sessionID: "ses-child", tool: "read" }, { args: { path: "b" } }),
603
664
  ).rejects.toThrow("Out of token budget");
604
- await expect(run).rejects.toThrow("token_budget");
665
+ await advancePoll(1);
666
+ expect(result()).toEqual({
667
+ status: "rejected",
668
+ value: expect.objectContaining({ message: expect.stringContaining("token_budget") }),
669
+ });
605
670
  expect(prompts).toHaveLength(2);
606
671
  expect(capturedTools[0]).not.toBe("[]");
607
672
  expect(capturedTools[1]).toBe(capturedTools[0]);
@@ -842,26 +907,32 @@ describe("tool refusals at finalize submission", () => {
842
907
 
843
908
  describe("prompt_async transport under the retry chain", () => {
844
909
  test("our slice stays the only timer and aborts the busy child when it expires", async () => {
910
+ freezePollClock();
845
911
  const host = asyncHost({ plan: ["busy"] });
846
912
  const transport = createPromptAsyncTransport(host.client, "ses-child", {
847
913
  pollIntervalMs: 5,
848
914
  });
849
915
  expect(transport).toBeDefined();
850
916
 
851
- let caught: unknown;
852
- try {
853
- await promptSyncWithValidatedOutputRetry(host.client, request(), {
917
+ const result = observeRun(
918
+ promptSyncWithValidatedOutputRetry(host.client, request(), {
854
919
  transport,
855
920
  timeoutMs: 60,
856
921
  fallbackModels: ["anthropic/claude-sonnet-4-6"],
857
922
  fetchOutput: async () => "unused",
858
923
  validateOutput: (output: string) => output,
859
- });
860
- } catch (error) {
861
- caught = error;
862
- }
863
-
864
- expect((caught as Error).message).toBe("prompt timed out after 60ms");
924
+ }),
925
+ );
926
+ await drainHostReplies();
927
+ await advancePoll(59);
928
+ expect(host.polls()).toBeGreaterThan(0);
929
+ expect(host.abort).not.toHaveBeenCalled();
930
+ expect(result()).toBeUndefined();
931
+ await advancePoll(1);
932
+ expect(result()).toEqual({
933
+ status: "rejected",
934
+ value: expect.objectContaining({ message: "prompt timed out after 60ms" }),
935
+ });
865
936
  expect(host.promptAsync).toHaveBeenCalledTimes(1);
866
937
  expect(host.prompt).not.toHaveBeenCalled();
867
938
  expect(host.abort).toHaveBeenCalledWith({ path: { id: "ses-child" } });
@@ -869,13 +940,25 @@ describe("prompt_async transport under the retry chain", () => {
869
940
  });
870
941
 
871
942
  test("an idle accepted user row is not a no-output completion after 30 seconds", async () => {
943
+ freezePollClock();
872
944
  const host = asyncHost({ plan: ["idle-pending"] });
873
- await expect(
945
+ const result = observeRun(
874
946
  promptAsyncAndWaitForIdle(host.client, request(), {
875
- pollIntervalMs: 1,
876
- startGraceMs: 20,
947
+ pollIntervalMs: 10_000,
948
+ startGraceMs: 30_000,
877
949
  }),
878
- ).rejects.toThrow("settled assistant");
950
+ );
951
+ await drainHostReplies();
952
+ await advancePoll(10_000);
953
+ expect(host.polls()).toBe(1);
954
+ await advancePoll(10_000);
955
+ await advancePoll(9_999);
956
+ expect(result()).toBeUndefined();
957
+ await advancePoll(1);
958
+ expect(result()).toEqual({
959
+ status: "rejected",
960
+ value: expect.objectContaining({ message: expect.stringContaining("settled assistant") }),
961
+ });
879
962
  });
880
963
 
881
964
  test("an early child session error preserves DeepSeek's unsupported-model 400 without waiting for an assistant", async () => {
@@ -1,4 +1,4 @@
1
- import { afterEach, expect, test } from "bun:test";
1
+ import { afterEach, expect, jest, test } from "bun:test";
2
2
  import type { execFileSync } from "node:child_process";
3
3
  import { mkdirSync, rmSync, writeFileSync } from "node:fs";
4
4
  import { tmpdir } from "node:os";
@@ -16,6 +16,7 @@ import {
16
16
  inspectProcessesAsync,
17
17
  } from "./rpc-utils";
18
18
  import { Database } from "./sqlite";
19
+ import { startGatedSqliteWriteLocker } from "./sqlite-write-locker-test-support";
19
20
  import { createTestTempDirFromPath } from "./test-temp-dir";
20
21
 
21
22
  afterEach(() => {
@@ -24,37 +25,40 @@ afterEach(() => {
24
25
  __setAsyncProcessProbeForTests();
25
26
  });
26
27
 
28
+ const heartbeat = () => new Promise<void>((resolve) => setImmediate(resolve));
29
+
27
30
  test("async Windows inspection bypasses slow synchronous probes and shares a bounded snapshot", async () => {
28
31
  let synchronousCalls = 0;
29
32
  const slow = (() => {
30
33
  synchronousCalls++;
31
- Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, 5000);
32
34
  return "";
33
35
  }) as typeof execFileSync;
34
36
  __setRpcIdentityTestHooks({
35
37
  platform: "win32",
36
38
  execFileSync: slow,
37
39
  processListExecFileSync: slow,
40
+ nowMs: () => 1,
38
41
  });
39
- let release!: (value: string) => void;
42
+ const probe = Promise.withResolvers<string>();
40
43
  let calls = 0;
41
44
  __setAsyncProcessProbeForTests(async (file, _args, timeout) => {
42
45
  expect(file).toBe("powershell");
43
46
  expect(timeout).toBe(5000);
44
47
  calls++;
45
- return new Promise<string>((resolve) => {
46
- release = resolve;
47
- });
48
+ return probe.promise;
48
49
  });
49
50
  const first = inspectProcessesAsync();
50
51
  const second = inspectProcessesAsync();
51
52
  expect(second).toBe(first);
52
- const heartbeat = await Promise.race([
53
- first.then(() => "probe"),
54
- new Promise<string>((resolve) => setTimeout(() => resolve("heartbeat"), 10)),
55
- ]);
56
- expect(heartbeat).toBe("heartbeat");
57
- release(
53
+ let completed = false;
54
+ void first.then(() => {
55
+ completed = true;
56
+ });
57
+ await heartbeat();
58
+ expect(calls).toBe(1);
59
+ expect(synchronousCalls).toBe(0);
60
+ expect(completed).toBe(false);
61
+ probe.resolve(
58
62
  JSON.stringify([
59
63
  {
60
64
  ProcessId: 12345,
@@ -74,7 +78,7 @@ test("async Windows inspection bypasses slow synchronous probes and shares a bou
74
78
  });
75
79
 
76
80
  test("offline process inspection can bypass a cached snapshot", async () => {
77
- __setRpcIdentityTestHooks({ platform: "win32" });
81
+ __setRpcIdentityTestHooks({ platform: "win32", nowMs: () => 1 });
78
82
  let calls = 0;
79
83
  __setAsyncProcessProbeForTests(async () => {
80
84
  calls++;
@@ -99,7 +103,7 @@ test("offline process inspection can bypass a cached snapshot", async () => {
99
103
  });
100
104
 
101
105
  test("async Windows inspection bounds CIM and tasklist fallback and caches failure", async () => {
102
- __setRpcIdentityTestHooks({ platform: "win32" });
106
+ __setRpcIdentityTestHooks({ platform: "win32", nowMs: () => 1 });
103
107
  const calls: Array<[string, number]> = [];
104
108
  __setAsyncProcessProbeForTests(async (file, _args, timeout) => {
105
109
  calls.push([file, timeout]);
@@ -123,51 +127,62 @@ test("boot storage wait stays responsive with a locked v90 store and slow Window
123
127
  seeded.exec(
124
128
  "CREATE TABLE schema_migrations(version INTEGER PRIMARY KEY); INSERT INTO schema_migrations VALUES(90)",
125
129
  );
126
- seeded.exec("BEGIN IMMEDIATE");
130
+ seeded.exec("PRAGMA busy_timeout=0");
131
+ const locker = await startGatedSqliteWriteLocker(dbPath);
127
132
  mkdirSync(join(root, "rpc", "blocker"), { recursive: true });
128
133
  writeFileSync(
129
134
  join(root, "rpc", "blocker", "port-12345.json"),
130
135
  JSON.stringify({
131
136
  pid: 12345,
132
137
  port: 43123,
133
- started_at: Date.now(),
138
+ started_at: Date.parse("2026-01-02T00:00:00Z"),
134
139
  kind: "OpenCode server",
135
140
  }),
136
141
  );
137
142
  let syncCalls = 0;
138
143
  const slow = (() => {
139
144
  syncCalls++;
140
- Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, 5000);
141
145
  return "";
142
146
  }) as typeof execFileSync;
143
147
  __setRpcIdentityTestHooks({
144
148
  platform: "win32",
145
149
  execFileSync: slow,
146
150
  processListExecFileSync: slow,
151
+ nowMs: () => Date.parse("2026-01-02T00:00:00Z"),
147
152
  });
148
- let release!: (value: string) => void;
149
- __setAsyncProcessProbeForTests(
150
- () =>
151
- new Promise<string>((resolve) => {
152
- release = resolve;
153
- }),
154
- );
153
+ const probe = Promise.withResolvers<string>();
154
+ let calls = 0;
155
+ __setAsyncProcessProbeForTests(() => {
156
+ calls++;
157
+ return probe.promise;
158
+ });
159
+ jest.useFakeTimers({ doNotFake: ["setImmediate"] });
155
160
  try {
161
+ // The migration guard should refuse before needing a writer. Verify a
162
+ // writer really is blocked throughout the asynchronous probe.
163
+ expect(() => seeded.exec("BEGIN IMMEDIATE")).toThrow(
164
+ expect.objectContaining({ code: "SQLITE_BUSY" }),
165
+ );
156
166
  const gate = createV2StorageGate({
157
167
  open: () => openDatabaseAsync({ dbPath, busyTimeoutMs: 0 }),
158
168
  });
159
- const started = performance.now();
160
169
  const boot = probeV2StorageAtBoot(gate);
161
170
  const opening = gate.probe();
162
- expect(
163
- await Promise.race([
164
- opening.then(() => "opened"),
165
- new Promise<string>((resolve) => setTimeout(() => resolve("responsive"), 10)),
166
- ]),
167
- ).toBe("responsive");
168
- expect(performance.now() - started).toBeLessThan(300);
171
+ let opened = false;
172
+ let bootFinished = false;
173
+ void opening.then(() => {
174
+ opened = true;
175
+ });
176
+ void boot.then(() => {
177
+ bootFinished = true;
178
+ });
179
+ await heartbeat();
180
+ expect(calls).toBe(1);
181
+ expect(syncCalls).toBe(0);
182
+ expect(opened).toBe(false);
183
+ expect(bootFinished).toBe(false);
169
184
  expect(gate.current()).toBeUndefined();
170
- release(
185
+ probe.resolve(
171
186
  JSON.stringify([
172
187
  {
173
188
  ProcessId: 12345,
@@ -182,12 +197,17 @@ test("boot storage wait stays responsive with a locked v90 store and slow Window
182
197
  expect(gate.reason()?.kind).toBe("migration_guard");
183
198
  expect(getMigrationOnOpenRefusal()?.serverPids).toEqual([12345]);
184
199
  expect(syncCalls).toBe(0);
185
- const checked = new Database(dbPath);
186
200
  expect(
187
- checked.prepare("SELECT MAX(version) AS version FROM schema_migrations").get(),
201
+ seeded.prepare("SELECT MAX(version) AS version FROM schema_migrations").get(),
188
202
  ).toEqual({ version: 90 });
189
- checked.close();
203
+ locker.release();
204
+ expect(await locker.exited).toBe(0);
205
+ expect(() => seeded.exec("BEGIN IMMEDIATE; ROLLBACK")).not.toThrow();
190
206
  } finally {
207
+ probe.resolve("[]");
208
+ jest.useRealTimers();
209
+ locker.release();
210
+ await locker.exited;
191
211
  seeded.close();
192
212
  rmSync(root, { recursive: true, force: true });
193
213
  }
@@ -1,4 +1,4 @@
1
- import { afterEach, describe, expect, test } from "bun:test";
1
+ import { afterEach, describe, expect, jest, spyOn, test } from "bun:test";
2
2
  import { mkdirSync, readdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";
3
3
  import { createServer } from "node:http";
4
4
  import { tmpdir } from "node:os";
@@ -96,7 +96,7 @@ async function waitFor(condition: () => boolean, label: string, timeoutMs = 2_00
96
96
  if (condition()) return;
97
97
  await new Promise((resolve) => setTimeout(resolve, 25));
98
98
  }
99
- throw new Error(`Timed out waiting for ${label}`);
99
+ throw new Error(`Watchdog: still waiting for ${label}`);
100
100
  }
101
101
 
102
102
  async function openSocket(
@@ -110,7 +110,10 @@ async function openSocket(
110
110
  headers: { Authorization: `Bearer ${token}` },
111
111
  });
112
112
  await new Promise<void>((resolve, reject) => {
113
- const timeout = setTimeout(() => reject(new Error("socket open timed out")), 2_000);
113
+ const timeout = setTimeout(
114
+ () => reject(new Error("Watchdog: waiting for RPC socket open")),
115
+ 2_000,
116
+ );
114
117
  ws.addEventListener(
115
118
  "open",
116
119
  () => {
@@ -139,7 +142,7 @@ function waitForJsonMessage<T extends { type?: string }>(
139
142
  return new Promise((resolve, reject) => {
140
143
  const timeout = setTimeout(() => {
141
144
  ws.removeEventListener("message", onMessage);
142
- reject(new Error("socket message timed out"));
145
+ reject(new Error("Watchdog: waiting for a matching RPC socket message"));
143
146
  }, timeoutMs);
144
147
  const onMessage = (event: MessageEvent) => {
145
148
  let message: T;
@@ -326,23 +329,32 @@ describe("MagicContextRpcClient", () => {
326
329
  };
327
330
  if (message.type === "notification") notifications.push(message.notification);
328
331
  });
332
+ const hello = async (sessionId: string) => {
333
+ const ack = waitForJsonMessage(ws, (message) => message.type === "hello-ack");
334
+ ws.send(JSON.stringify({ type: "hello", token: record?.token, sessionId }));
335
+ await ack;
336
+ };
329
337
 
330
338
  try {
331
- ws.send(JSON.stringify({ type: "hello", token: record?.token, sessionId: "ses_A" }));
332
- await waitForJsonMessage(ws, (message) => message.type === "hello-ack");
339
+ await hello("ses_A");
333
340
  expect(isTuiConnected("ses_A")).toBe(true);
334
341
 
335
- ws.send(JSON.stringify({ type: "hello", token: record?.token, sessionId: "ses_B" }));
336
- await waitForJsonMessage(ws, (message) => message.type === "hello-ack");
342
+ await hello("ses_B");
337
343
  expect(isTuiConnected("ses_A")).toBe(false);
338
344
  expect(isTuiConnected("ses_B")).toBe(true);
339
345
 
340
- ws.send(JSON.stringify({ type: "hello", token: record?.token, sessionId: "ses_B" }));
341
- await waitForJsonMessage(ws, (message) => message.type === "hello-ack");
342
- pushNotification("live", { ok: true }, "ses_B");
343
- await waitFor(() => notifications.length >= 1, "one live notification");
344
- await new Promise((resolve) => setTimeout(resolve, 50));
345
- expect(notifications).toHaveLength(1);
346
+ await hello("ses_B");
347
+ pushNotification("live", { ok: true }, "ses_B", { liveOnly: true });
348
+ // The next ack follows every live send on the same socket. The live-only
349
+ // push is not replayed by this hello, so any duplicate came from a live sink.
350
+ await hello("ses_B");
351
+ expect(notifications).toEqual([
352
+ expect.objectContaining({
353
+ type: "live",
354
+ sessionId: "ses_B",
355
+ payload: { ok: true },
356
+ }),
357
+ ]);
346
358
 
347
359
  ws.close();
348
360
  await waitFor(() => !isTuiConnected(), "socket sink cleanup");
@@ -438,11 +450,32 @@ describe("MagicContextRpcClient", () => {
438
450
  await closeServer(dead);
439
451
  writePortFile(storageDir, directory, port);
440
452
 
441
- const client = new MagicContextRpcClient(storageDir, directory);
442
- await expect(client.call("value")).rejects.toThrow(
443
- "Magic Context RPC server not available",
453
+ jest.useFakeTimers({ doNotFake: ["queueMicrotask", "setImmediate"] });
454
+ const schedule = setTimeout;
455
+ let retries = 0;
456
+ const timer = spyOn(globalThis, "setTimeout").mockImplementation(
457
+ (callback, ms, ...args) => {
458
+ const handle = schedule(callback, ms, ...args);
459
+ if (ms === 500) {
460
+ retries++;
461
+ // A failed health probe schedules its own backoff. Keep probe
462
+ // deadlines parked until the real socket has refused the connection.
463
+ queueMicrotask(() => jest.advanceTimersByTime(500));
464
+ }
465
+ return handle;
466
+ },
444
467
  );
445
- }, 20_000);
468
+ try {
469
+ const client = new MagicContextRpcClient(storageDir, directory);
470
+ await expect(client.call("value")).rejects.toThrow(
471
+ "Magic Context RPC server not available",
472
+ );
473
+ expect(retries).toBe(27);
474
+ } finally {
475
+ timer.mockRestore();
476
+ jest.useRealTimers();
477
+ }
478
+ });
446
479
 
447
480
  test("re-resolves and retries transient 5xx responses", async () => {
448
481
  const storageDir = makeTempDir();