@cortexkit/opencode-magic-context 0.49.86 → 0.49.89

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 (182) hide show
  1. package/dist/{announcement-fnyxaahs.js → announcement-4ynkaf0d.js} +2 -2
  2. package/dist/auto-search-worker.js +13 -7
  3. package/dist/chunk-embedding-write-worker.js +7 -7
  4. package/dist/{compartment-chunk-embedding-ymc9mtwv.js → compartment-chunk-embedding-fey2bsyf.js} +3 -1
  5. package/dist/{conflict-warning-hook-a0wrnzch.js → conflict-warning-hook-kbq6ppjf.js} +2 -2
  6. package/dist/{context-xesm7rj3.js → context-grdg1k2k.js} +132 -52
  7. package/dist/{derive-budgets-90869322.js → derive-budgets-hzzq71rm.js} +2 -2
  8. package/dist/{embedding-backfill-v6sw58m8.js → embedding-backfill-qjkaee9s.js} +8 -8
  9. package/dist/{v2/embedding-cache-mgyr73ef.js → embedding-cache-zn4r1c31.js} +5 -1
  10. package/dist/embedding-worker.js +2 -2
  11. package/dist/features/magic-context/compartment-chunk-embedding.d.ts +1 -0
  12. package/dist/features/magic-context/compartment-chunk-embedding.d.ts.map +1 -1
  13. package/dist/features/magic-context/dreamer/task-executor.d.ts.map +1 -1
  14. package/dist/features/magic-context/dreamer/token-budget.d.ts +8 -3
  15. package/dist/features/magic-context/dreamer/token-budget.d.ts.map +1 -1
  16. package/dist/features/magic-context/memory/embedding-cache.d.ts +7 -0
  17. package/dist/features/magic-context/memory/embedding-cache.d.ts.map +1 -1
  18. package/dist/features/magic-context/search.d.ts +6 -0
  19. package/dist/features/magic-context/search.d.ts.map +1 -1
  20. package/dist/features/magic-context/storage-db.d.ts.map +1 -1
  21. package/dist/features/magic-context/tool-definition-tokens.d.ts +2 -0
  22. package/dist/features/magic-context/tool-definition-tokens.d.ts.map +1 -1
  23. package/dist/hooks/magic-context/auto-search-worker-client.d.ts.map +1 -1
  24. package/dist/hooks/magic-context/auto-search-worker-probe.fixture.d.ts +2 -0
  25. package/dist/hooks/magic-context/auto-search-worker-probe.fixture.d.ts.map +1 -0
  26. package/dist/hooks/magic-context/compartment-runner-partial-recomp.d.ts.map +1 -1
  27. package/dist/hooks/magic-context/compartment-runner-recomp-carry.d.ts +4 -0
  28. package/dist/hooks/magic-context/compartment-runner-recomp-carry.d.ts.map +1 -0
  29. package/dist/hooks/magic-context/compartment-runner-recomp.d.ts +8 -2
  30. package/dist/hooks/magic-context/compartment-runner-recomp.d.ts.map +1 -1
  31. package/dist/hooks/magic-context/dropped-input-guard.d.ts.map +1 -1
  32. package/dist/hooks/magic-context/emergency-fail-closed.d.ts +2 -0
  33. package/dist/hooks/magic-context/emergency-fail-closed.d.ts.map +1 -1
  34. package/dist/hooks/magic-context/recomp-orchestrator.d.ts +3 -5
  35. package/dist/hooks/magic-context/recomp-orchestrator.d.ts.map +1 -1
  36. package/dist/hooks/magic-context/send-session-notification.d.ts +11 -1
  37. package/dist/hooks/magic-context/send-session-notification.d.ts.map +1 -1
  38. package/dist/hooks/magic-context/transform.d.ts +1 -0
  39. package/dist/hooks/magic-context/transform.d.ts.map +1 -1
  40. package/dist/{index-s8ks5nz4.js → index-2pdgy88n.js} +5 -5
  41. package/dist/{index-7j2zv9nm.js → index-2qsca7h7.js} +47 -11
  42. package/dist/{index-1bqkqde0.js → index-39rzef89.js} +9 -7
  43. package/dist/{index-snbpdpa3.js → index-3pdknr07.js} +4 -4
  44. package/dist/{index-c5tmzym6.js → index-5df2fw5b.js} +108 -13
  45. package/dist/{index-7svecf3m.js → index-5pgyqgmx.js} +1 -1
  46. package/dist/{index-xrnhxkz7.js → index-60wnwcwz.js} +1 -1
  47. package/dist/{index-k50xhjw1.js → index-60x5d68t.js} +1 -1
  48. package/dist/{index-4ntnt8ee.js → index-61knrt52.js} +1 -1
  49. package/dist/{index-g6hfh4h4.js → index-6zewd2n5.js} +14 -8
  50. package/dist/{index-70cv85b0.js → index-78t37mcq.js} +2 -2
  51. package/dist/{index-stx8zd81.js → index-83qd3n7s.js} +2 -2
  52. package/dist/{index-nny4gm06.js → index-9d3qgwq0.js} +2 -2
  53. package/dist/{index-jjvbk92s.js → index-9emdjcb5.js} +1 -1
  54. package/dist/{index-05bm2ndp.js → index-chpzb6xy.js} +1 -1
  55. package/dist/{index-2kf73btc.js → index-cr483vx6.js} +1 -1
  56. package/dist/{index-d0rtbv0f.js → index-dk3hy2a2.js} +21 -14
  57. package/dist/{index-gxdc95cp.js → index-g0mb2kb4.js} +585 -82
  58. package/dist/{index-w6v4dw5f.js → index-h9hybzr5.js} +5 -5
  59. package/dist/{index-1pf5qrx4.js → index-jzfsnbmm.js} +3 -3
  60. package/dist/{index-jrj95cce.js → index-m6dnydf8.js} +9 -2
  61. package/dist/{index-xccywqdj.js → index-mrjat4eq.js} +77 -14
  62. package/dist/{index-022w6314.js → index-n1ty0vd3.js} +116 -512
  63. package/dist/{index-ttk3trse.js → index-q7msfgwz.js} +311 -111
  64. package/dist/{index-e32b3x4n.js → index-qfcjrnpe.js} +7 -6
  65. package/dist/{v2/server-4dhv7mqz.js → index-qjwpqvnf.js} +48 -1
  66. package/dist/{index-3dtzyred.js → index-r4y0dczp.js} +1 -1
  67. package/dist/{index-4w5rx7de.js → index-tt0vs4x5.js} +2 -2
  68. package/dist/{index-k0tb2z28.js → index-w51n3576.js} +2 -2
  69. package/dist/{index-25nktq8n.js → index-wmb2mcdw.js} +7 -7
  70. package/dist/{index-zmqx48vt.js → index-xsqw8kbd.js} +1 -1
  71. package/dist/{index-fzgyvsb1.js → index-y14pawe1.js} +3 -0
  72. package/dist/{index-798s7c8s.js → index-zxhev8ze.js} +2 -2
  73. package/dist/index.d.ts.map +1 -1
  74. package/dist/index.js +68 -59
  75. package/dist/{message-index-bounded-6fr624zf.js → message-index-bounded-r1qys471.js} +4 -4
  76. package/dist/migration-worker.js +5 -5
  77. package/dist/plugin/messages-transform.d.ts +3 -4
  78. package/dist/plugin/messages-transform.d.ts.map +1 -1
  79. package/dist/plugin/refusal-notice.d.ts +3 -0
  80. package/dist/plugin/refusal-notice.d.ts.map +1 -0
  81. package/dist/{project-embedding-registry-q80scexh.js → project-embedding-registry-m3fp1pa4.js} +7 -7
  82. package/dist/raw-ordinal-warmup-worker.js +4 -4
  83. package/dist/{read-session-chunk-6wedfths.js → read-session-chunk-xv9f0wgb.js} +3 -3
  84. package/dist/{recomp-orchestrator-7ecg8ryx.js → recomp-orchestrator-dgyb394j.js} +23 -23
  85. package/dist/{render-yqp7q79f.js → render-d014e603.js} +12 -12
  86. package/dist/{rpc-notifications-t9q0ynq7.js → rpc-notifications-ta2zsxpq.js} +1 -1
  87. package/dist/{search-bw22d7zc.js → search-9gceftb9.js} +18 -18
  88. package/dist/{search-archive-r4h96j2z.js → search-archive-gybn6q7s.js} +5 -5
  89. package/dist/{send-session-notification-7x518gew.js → send-session-notification-gzxz88vq.js} +1 -1
  90. package/dist/shared/assistant-message-extractor.d.ts +2 -0
  91. package/dist/shared/assistant-message-extractor.d.ts.map +1 -1
  92. package/dist/shared/prompt-async-transport.d.ts.map +1 -1
  93. package/dist/shared/recomp-outcome.d.ts +4 -0
  94. package/dist/shared/recomp-outcome.d.ts.map +1 -0
  95. package/dist/shared/rpc-notifications.d.ts +1 -1
  96. package/dist/shared/rpc-notifications.d.ts.map +1 -1
  97. package/dist/shared/storage-permissions.d.ts +16 -2
  98. package/dist/shared/storage-permissions.d.ts.map +1 -1
  99. package/dist/shared/user-facing-codes.d.ts +4 -1
  100. package/dist/shared/user-facing-codes.d.ts.map +1 -1
  101. package/dist/{storage-memory-e6a7mb0k.js → storage-memory-hhrvfw0x.js} +2 -2
  102. package/dist/{storage-tags-y2mrb8e6.js → storage-tags-f1ftvjpw.js} +2 -2
  103. package/dist/{transform-postprocess-phase-t99yj9vt.js → transform-postprocess-phase-34k1zwsy.js} +24 -24
  104. package/dist/v2/auto-search-worker.js +13 -7
  105. package/dist/v2/chunk-embedding-write-worker.js +7 -7
  106. package/dist/v2/{compartment-chunk-embedding-x6qw6mjk.js → compartment-chunk-embedding-knt2468v.js} +3 -1
  107. package/dist/v2/{context-k8sx1nyy.js → context-8bzydxfy.js} +227 -70
  108. package/dist/v2/{derive-budgets-ecjy1aqh.js → derive-budgets-hr4qqrnv.js} +3 -3
  109. package/dist/v2/{embedding-backfill-k8kqnwfq.js → embedding-backfill-0ar1bm97.js} +8 -8
  110. package/dist/{embedding-cache-mgyr73ef.js → v2/embedding-cache-zn4r1c31.js} +5 -1
  111. package/dist/v2/embedding-worker.js +2 -2
  112. package/dist/v2/fold/native-replay.d.ts +3 -1
  113. package/dist/v2/fold/native-replay.d.ts.map +1 -1
  114. package/dist/v2/hidden-child-record.d.ts +1 -0
  115. package/dist/v2/hidden-child-record.d.ts.map +1 -1
  116. package/dist/v2/hidden-completion.d.ts.map +1 -1
  117. package/dist/v2/hooks/context.d.ts.map +1 -1
  118. package/dist/v2/{message-index-bounded-jqy7283g.js → message-index-bounded-b07r9cjv.js} +4 -4
  119. package/dist/v2/migration-worker.js +5 -5
  120. package/dist/v2/{project-embedding-registry-2jp1antr.js → project-embedding-registry-gx2waee8.js} +7 -7
  121. package/dist/v2/raw-ordinal-warmup-worker.js +4 -4
  122. package/dist/v2/{read-session-chunk-n3nhfvd7.js → read-session-chunk-38wdy8nd.js} +3 -3
  123. package/dist/v2/{recomp-orchestrator-ssde9ft1.js → recomp-orchestrator-wq7gbkqa.js} +24 -24
  124. package/dist/v2/{render-fezgh7pa.js → render-2dan17xc.js} +12 -12
  125. package/dist/v2/{rpc-notifications-t9q0ynq7.js → rpc-notifications-ta2zsxpq.js} +1 -1
  126. package/dist/v2/{search-archive-zz1kza50.js → search-archive-89hdy0a2.js} +5 -5
  127. package/dist/v2/{search-m251amra.js → search-nyqykx7q.js} +17 -17
  128. package/dist/v2/{send-session-notification-p52rhjzy.js → send-session-notification-zazaxxpf.js} +1 -1
  129. package/dist/v2/{server-4wwwm2ya.js → server-09h2vyvs.js} +5 -5
  130. package/dist/v2/{server-r2es6zt7.js → server-0tv6kytx.js} +108 -13
  131. package/dist/v2/{server-rz4snd3x.js → server-1rrmxhd1.js} +1 -1
  132. package/dist/v2/{server-wdq85mxj.js → server-6250cxzs.js} +14 -8
  133. package/dist/v2/{server-xa8fefhw.js → server-96nm9vk4.js} +1 -1
  134. package/dist/v2/{server-jjvbk92s.js → server-9emdjcb5.js} +1 -1
  135. package/dist/v2/{server-ap81bk3c.js → server-9n2qgk29.js} +1 -1
  136. package/dist/v2/{server-ps6rz88g.js → server-a85j3kam.js} +2 -2
  137. package/dist/v2/{server-y31y6gws.js → server-add0j5n3.js} +9 -7
  138. package/dist/v2/{server-97w51d8n.js → server-b0a9h3ds.js} +3 -3
  139. package/dist/v2/{server-2k8tkbhz.js → server-c7awk5s2.js} +10 -4
  140. package/dist/v2/{server-hn8b7sfe.js → server-dgjqvpgd.js} +5 -5
  141. package/dist/v2/{server-fsw8kbng.js → server-dtcwkdqj.js} +314 -114
  142. package/dist/v2/{server-mbkwcwgw.js → server-f7tzvmzs.js} +2 -2
  143. package/dist/v2/{server-n5zr7190.js → server-fb5hvvfc.js} +77 -14
  144. package/dist/v2/{server-w7mpvkpj.js → server-fn4ky6mn.js} +1 -1
  145. package/dist/v2/{server-3p6b0qya.js → server-gqkdfdvw.js} +1 -1
  146. package/dist/v2/{server-cwtehwbb.js → server-j4jjtdc5.js} +1 -1
  147. package/dist/v2/{server-b93f0bqh.js → server-pjk9spbf.js} +1 -1
  148. package/dist/v2/{server-s15knz0w.js → server-pmws7we9.js} +1 -1
  149. package/dist/{index-4dhv7mqz.js → v2/server-qjwpqvnf.js} +48 -1
  150. package/dist/v2/{server-a2f1bhyj.js → server-stjy5dxv.js} +9 -2
  151. package/dist/v2/{server-ssg29wjg.js → server-ta4h0fch.js} +21 -14
  152. package/dist/v2/{server-e2k9mt86.js → server-tj65pgvg.js} +1 -1
  153. package/dist/v2/{server-brgandk4.js → server-vy0beygw.js} +2 -2
  154. package/dist/v2/{server-fzgyvsb1.js → server-y14pawe1.js} +3 -0
  155. package/dist/v2/{server-8pdfmc27.js → server-y17r5ryz.js} +4 -4
  156. package/dist/v2/{server-sxfbjdye.js → server-yx0nyj1q.js} +2 -2
  157. package/dist/v2/server.js +6 -6
  158. package/dist/v2/{storage-memory-e6a7mb0k.js → storage-memory-hhrvfw0x.js} +2 -2
  159. package/dist/v2/{storage-tags-xq81zgt2.js → storage-tags-pmw33chf.js} +2 -2
  160. package/dist/v2/{v2-archive-reader-e2w39c3p.js → v2-archive-reader-gh1jghf7.js} +1 -1
  161. package/dist/v2/{wrapup-orchestrator-eg5b1p89.js → wrapup-orchestrator-2h7ayss9.js} +24 -24
  162. package/dist/{v2-archive-reader-8dsngf2j.js → v2-archive-reader-8158kyfd.js} +1 -1
  163. package/dist/{wrapup-orchestrator-nmk6yf7f.js → wrapup-orchestrator-ct59br0c.js} +24 -24
  164. package/package.json +1 -1
  165. package/src/shared/assistant-message-extractor.test.ts +22 -0
  166. package/src/shared/assistant-message-extractor.ts +13 -0
  167. package/src/shared/model-suggestion-retry.test.ts +43 -12
  168. package/src/shared/prompt-async-transport.test.ts +275 -8
  169. package/src/shared/prompt-async-transport.ts +41 -2
  170. package/src/shared/recomp-outcome.ts +8 -0
  171. package/src/shared/reusable-worker.fixture.ts +15 -3
  172. package/src/shared/reusable-worker.test.ts +20 -10
  173. package/src/shared/rpc-notifications.ts +4 -1
  174. package/src/shared/sqlite-foreground-wait.test.ts +2 -2
  175. package/src/shared/startup-maintenance-policy.test.ts +4 -2
  176. package/src/shared/storage-permissions-startup.test.ts +296 -6
  177. package/src/shared/storage-permissions.ts +143 -18
  178. package/src/shared/user-facing-codes.ts +5 -2
  179. package/src/tui/dialogs/status-dialog.tsx +3 -0
  180. package/src/tui/slots/sidebar-content.tsx +6 -2
  181. package/src/tui-compiled/dialogs/status-dialog.tsx +12 -0
  182. package/src/tui-compiled/slots/sidebar-content.tsx +7 -2
@@ -200,6 +200,38 @@ function messageId(message: unknown): string | null {
200
200
  return typeof id === "string" ? id : null;
201
201
  }
202
202
 
203
+ function inFlightAtAbort(messages: unknown[], initialBaseline: Set<string>): Set<string> {
204
+ // OpenCode finishes a reply's tool batch before starting the next reply.
205
+ // Cleanup can mark the cancelled reply's outstanding parts as errors even
206
+ // though their callbacks may still reach the hook. Exempt each of those
207
+ // call IDs once at most: even with reused IDs, the stop takes no more than
208
+ // this many post-submission refusals plus the two counted refusals.
209
+ const reply = messages
210
+ .slice()
211
+ .reverse()
212
+ .find((message) => {
213
+ const id = messageId(message);
214
+ return id !== null && !initialBaseline.has(id) && infoOf(message).role === "assistant";
215
+ });
216
+ const parts = (reply as { parts?: unknown } | undefined)?.parts;
217
+ const ids = new Set<string>();
218
+ if (Array.isArray(parts)) {
219
+ for (const part of parts) {
220
+ if (part?.type !== "tool" || typeof part.callID !== "string") continue;
221
+ const state = part.state;
222
+ if (
223
+ state?.status === "pending" ||
224
+ state?.status === "running" ||
225
+ (state?.status === "error" &&
226
+ state.error === "Tool execution aborted" &&
227
+ state.metadata?.interrupted === true)
228
+ )
229
+ ids.add(part.callID);
230
+ }
231
+ }
232
+ return ids;
233
+ }
234
+
203
235
  function recordedAssistantError(message: unknown): unknown {
204
236
  const info = infoOf(message);
205
237
  if (info.error != null) return info.error;
@@ -520,7 +552,7 @@ export async function promptAsyncAndWaitForIdle(
520
552
  budget.snapshot(),
521
553
  );
522
554
  budgetAbortedSessions.add(sessionId);
523
- registerBudgetFinalizeChild(sessionId, budget);
555
+ const countRefusals = registerBudgetFinalizeChild(sessionId, budget);
524
556
  if (!session.abort)
525
557
  throw new DreamTokenBudgetExceeded(sessionId, budget.snapshot().spent);
526
558
  await session.abort({ path: { id: sessionId } });
@@ -535,12 +567,19 @@ export async function promptAsyncAndWaitForIdle(
535
567
  if ((await readStatus(session, sessionId, dir, signal)) !== "idle") {
536
568
  throw new DreamTokenBudgetExceeded(sessionId, budget.snapshot().spent);
537
569
  }
570
+ const cancelled = await readMessages(session, sessionId, dir, signal);
538
571
  // An aborted assistant is not the answer to the new user turn.
539
572
  completionBaseline = new Set(
540
- (await readMessages(session, sessionId, dir, signal))
573
+ (cancelled.length ? cancelled : messages)
541
574
  .map(messageId)
542
575
  .filter((value): value is string => value !== null),
543
576
  );
577
+ const exemptCallIds = inFlightAtAbort(cancelled, initialBaseline);
578
+ countRefusals(exemptCallIds);
579
+ sessionLog(sessionId, "dreamer token budget: counting tool refusals", {
580
+ snapshot: cancelled.length ? "read" : "unreadable",
581
+ exemptCallIds: [...exemptCallIds],
582
+ });
544
583
  const finalizeResponse = await session.promptAsync?.({
545
584
  ...request,
546
585
  body: {
@@ -0,0 +1,8 @@
1
+ export const RECOMP_PAUSED_HEADING = "## Magic Recomp — Paused";
2
+
3
+ /** Read the text after the paused-rebuild heading, for the sidebar and status dialog. */
4
+ export function pausedRecompReason(message: string | undefined): string | null {
5
+ const prefix = `${RECOMP_PAUSED_HEADING}\n`;
6
+ if (!message?.startsWith(prefix)) return null;
7
+ return message.slice(prefix.length).replace(/\s+/g, " ").trim();
8
+ }
@@ -1,16 +1,23 @@
1
1
  import { parentPort, threadId } from "node:worker_threads";
2
2
  import { serveWorkerJobs } from "./reusable-worker-entry";
3
3
 
4
+ let replyToReleasedJob: (() => void) | undefined;
5
+
4
6
  serveWorkerJobs<{
5
7
  crash?: boolean;
6
8
  hang?: boolean;
9
+ acknowledgeHang?: boolean;
7
10
  late?: boolean;
11
+ deliverLate?: boolean;
8
12
  exitCode?: boolean;
9
13
  value?: string;
10
14
  shared?: SharedArrayBuffer;
11
15
  }>(async (input, port) => {
12
16
  if (input.crash) throw new Error("injected worker crash");
13
- if (input.hang) return await new Promise<void>(() => {});
17
+ if (input.hang) {
18
+ if (input.acknowledgeHang) port.postMessage({ threadId, hanging: true });
19
+ return await new Promise<void>(() => {});
20
+ }
14
21
  if (input.exitCode) process.exitCode = 1;
15
22
  if (input.shared) {
16
23
  const state = new Int32Array(input.shared);
@@ -25,11 +32,16 @@ serveWorkerJobs<{
25
32
  return;
26
33
  }
27
34
  if (input.late)
28
- setTimeout(() => {
35
+ replyToReleasedJob = () => {
29
36
  port.postMessage({ value: "stale" });
30
37
  // Bypass the job port to verify the owner ignores a mismatched job id.
31
38
  parentPort?.postMessage({ jobId: -1, value: { value: "stale" } });
32
- }, 20);
39
+ };
40
+ if (input.deliverLate) {
41
+ if (!replyToReleasedJob) throw new Error("fixture did not reuse the prior thread");
42
+ replyToReleasedJob();
43
+ replyToReleasedJob = undefined;
44
+ }
33
45
  port.postMessage({ threadId, value: input.value });
34
46
  port.close();
35
47
  });
@@ -1,4 +1,4 @@
1
- import { describe, expect, test } from "bun:test";
1
+ import { afterEach, describe, expect, jest, test } from "bun:test";
2
2
  import { spawnSync } from "node:child_process";
3
3
  import { once } from "node:events";
4
4
  import { readFileSync, writeFileSync } from "node:fs";
@@ -22,6 +22,8 @@ async function result(worker: Worker) {
22
22
  }
23
23
 
24
24
  describe("reusable job workers", () => {
25
+ afterEach(() => jest.useRealTimers());
26
+
25
27
  test("reuses a thread but gives each job fresh input and port state", async () => {
26
28
  const path = `reuse-${++key}`;
27
29
  const first = await result(start(path, { value: "first" }));
@@ -45,20 +47,27 @@ describe("reusable job workers", () => {
45
47
  test("terminates a hung job and replaces its thread", async () => {
46
48
  const path = `hang-${++key}`;
47
49
  const first = await result(start(path));
48
- const hung = start(path, { hang: true });
49
- // Allow dispatch, then terminate the worker to exercise the hard-stop behavior.
50
- await new Promise((resolve) => setTimeout(resolve, 25));
51
- await hung.terminate();
50
+ const hung = start(path, { hang: true, acknowledgeHang: true });
51
+ try {
52
+ const [reply] = await once(hung, "message");
53
+ expect(reply).toEqual({ threadId: first.threadId, hanging: true });
54
+ } finally {
55
+ await hung.terminate();
56
+ }
52
57
  const next = await result(start(path));
53
58
  expect(next.threadId).not.toBe(first.threadId);
54
59
  });
55
60
 
56
61
  test("shuts the thread down after its idle lifetime", async () => {
62
+ jest.useFakeTimers({ doNotFake: ["setImmediate"] });
57
63
  const path = `idle-${++key}`;
58
64
  const first = await result(start(path, {}, 20));
59
- await new Promise((resolve) => setTimeout(resolve, 80));
65
+ jest.advanceTimersByTime(19);
66
+ expect((await result(start(path, {}, 20))).threadId).toBe(first.threadId);
67
+ jest.advanceTimersByTime(20);
60
68
  const next = await result(start(path, {}, 20));
61
69
  expect(next.threadId).not.toBe(first.threadId);
70
+ jest.advanceTimersByTime(20);
62
71
  });
63
72
 
64
73
  test("rejects late replies from a released job", async () => {
@@ -67,13 +76,14 @@ describe("reusable job workers", () => {
67
76
  const oldReplies: unknown[] = [];
68
77
  prior.on("message", (reply) => oldReplies.push(reply));
69
78
  const first = await result(prior);
70
- const next = start(path, { hang: true });
79
+ const next = start(path, { deliverLate: true, value: "next" });
71
80
  const replies: unknown[] = [];
72
81
  next.on("message", (reply) => replies.push(reply));
73
- await new Promise((resolve) => setTimeout(resolve, 60));
82
+ // The fixture sends both stale packets before acknowledging the next job.
83
+ const nextReply = await result(next);
84
+ expect(nextReply).toEqual({ threadId: first.threadId, value: "next" });
74
85
  expect(oldReplies).toHaveLength(1);
75
- expect(replies).toEqual([]);
76
- await next.terminate();
86
+ expect(replies).toEqual([nextReply]);
77
87
  expect(first.threadId).toBeGreaterThan(0);
78
88
  });
79
89
 
@@ -63,16 +63,19 @@ export function pushLiveNotification(
63
63
  type: string,
64
64
  payload: Record<string, unknown>,
65
65
  sessionId: string,
66
- ): void {
66
+ ): boolean {
67
67
  const notification: RpcNotification = { id: nextNotificationId++, type, payload, sessionId };
68
+ let delivered = false;
68
69
  for (const sink of sinks) {
69
70
  if (sink.sessionId !== sessionId) continue;
70
71
  try {
71
72
  sink.send(notification);
73
+ delivered = true;
72
74
  } catch {
73
75
  // A socket that closed during the send has no live terminal to notify.
74
76
  }
75
77
  }
78
+ return delivered;
76
79
  }
77
80
 
78
81
  /** Push a notification to the TUI. Fans out to any live WS sink immediately and
@@ -57,7 +57,7 @@ for (const holdMs of [1000, 2500]) {
57
57
  const diagnostics: string[] = [];
58
58
  registerSqliteDiagnosticSink((line) => diagnostics.push(line));
59
59
  const handler = createMessagesTransformHandler({
60
- onStorageBusyRefusal: async (id) => {
60
+ onRefusal: async (id) => {
61
61
  expect(id).toBe(sessionId);
62
62
  refusals++;
63
63
  },
@@ -128,7 +128,7 @@ for (const holdMs of [1000, 2500]) {
128
128
  ],
129
129
  };
130
130
  const handler = createMessagesTransformHandler({
131
- onStorageBusyRefusal: async () => {
131
+ onRefusal: async () => {
132
132
  refusals++;
133
133
  },
134
134
  magicContext: {
@@ -44,7 +44,8 @@ test.each([
44
44
  );
45
45
  const statements = source.statements.map((statement) => statement.getText(source));
46
46
  // Inspect statements, not comments: a commented-out policy must fail this guard.
47
- expect(statements[0]).toBe(
47
+ expect(statements[0]).toBe("delete process.env.OPENCODE_DB;");
48
+ expect(statements[1]).toBe(
48
49
  'await import(new URL("../test-preload.ts", import.meta.url).href);',
49
50
  );
50
51
  expect(statements.at(-1)).toBe("__setScheduleStartupMaintenanceOnOpenForTests(false);");
@@ -52,7 +53,7 @@ test.each([
52
53
  packageName === "plugin"
53
54
  ? "./features/magic-context/storage-db"
54
55
  : "@magic-context/core/features/magic-context/storage-db";
55
- expect(statements[1]).toMatch(
56
+ expect(statements[2]).toMatch(
56
57
  new RegExp(
57
58
  `const \\{ __setScheduleStartupMaintenanceOnOpenForTests \\} = await import\\(\\s*"${storageModule}"\\s*\\);`,
58
59
  ),
@@ -63,6 +64,7 @@ test("CLI uses the unit policy while end-to-end tests retain the shared isolatio
63
64
  expect(preloads("cli")).toEqual(["../plugin/src/test-preload.ts"]);
64
65
  expect(preloads("e2e-tests")).toEqual(["../plugin/test-preload.ts"]);
65
66
  const isolation = readFileSync(join(root, "packages/plugin/test-preload.ts"), "utf8");
67
+ expect(isolation).not.toContain("delete process.env.OPENCODE_DB");
66
68
  expect(isolation).not.toContain("__setScheduleStartupMaintenanceOnOpenForTests");
67
69
  expect(isolation).not.toContain("src/test-preload");
68
70
  });
@@ -1,6 +1,7 @@
1
1
  import { afterEach, describe, expect, it, spyOn } from "bun:test";
2
2
  import * as fs from "node:fs";
3
- import { join } from "node:path";
3
+ import * as os from "node:os";
4
+ import * as path from "node:path";
4
5
  import { withStorageFileMutex } from "./storage-file-mutex";
5
6
  import {
6
7
  __resetStoragePrivatePermissionEnforcementForTests,
@@ -13,11 +14,46 @@ import { cleanupTestTempDir, createTestTempDir } from "./test-temp-dir";
13
14
 
14
15
  const roots: string[] = [];
15
16
  const markerName = ".storage-permissions-v1";
17
+ const { join } = path;
18
+
19
+ function linkedFixture(name: string): { parent: string; root: string; alias: string } {
20
+ const { dir } = createTestTempDir(`mc-storage-link-${name}-`);
21
+ roots.push(dir);
22
+ const parent = fs.realpathSync(dir);
23
+ const root = join(parent, "storage");
24
+ const alias = join(parent, "alias");
25
+ fs.mkdirSync(root);
26
+ fs.chmodSync(root, 0o755);
27
+ fs.symlinkSync(root, alias);
28
+ return { parent, root, alias };
29
+ }
30
+
31
+ function mode(file: string): number {
32
+ return fs.lstatSync(file).mode & 0o777;
33
+ }
34
+
35
+ function writeLooseOwnedTree(root: string): void {
36
+ const models = join(root, "models");
37
+ fs.mkdirSync(models);
38
+ fs.writeFileSync(join(root, "context.db"), "");
39
+ fs.writeFileSync(join(models, "weights"), "cache fixture");
40
+ for (const [file, permissions] of [
41
+ [root, 0o755],
42
+ [models, 0o755],
43
+ [join(root, "context.db"), 0o644],
44
+ [join(models, "weights"), 0o755],
45
+ ] as const)
46
+ fs.chmodSync(file, permissions);
47
+ }
48
+
49
+ function ownedTreeModes(root: string): number[] {
50
+ return [".", "context.db", "models", "models/weights"].map((name) => mode(join(root, name)));
51
+ }
16
52
 
17
53
  function fixture(): string {
18
54
  const { dir: parent } = createTestTempDir("mc-storage-startup-");
19
55
  roots.push(parent);
20
- const root = join(parent, "storage");
56
+ const root = join(fs.realpathSync(parent), "storage");
21
57
  fs.mkdirSync(root, { mode: 0o700 });
22
58
  fs.mkdirSync(join(root, "lkg-recovery-fences"), { mode: 0o700 });
23
59
  for (let i = 0; i < 2000; i++) {
@@ -203,14 +239,248 @@ describe.skipIf(process.platform === "win32")("startup permission certificate",
203
239
  expect(fs.lstatSync(loose).mode & 0o777).toBe(0o600);
204
240
  });
205
241
 
206
- it("does not certify a storage root that is a symbolic link", () => {
242
+ it("tightens and certifies the target of a linked storage root", () => {
243
+ const root = fixture();
244
+ const alias = join(root, "..", "alias");
245
+ fs.symlinkSync("storage", alias);
246
+ const before = fs.lstatSync(alias);
247
+ const db = join(root, "context.db");
248
+ const fence = join(root, "lkg-recovery-fences", "5.json");
249
+ fs.chmodSync(root, 0o755);
250
+ fs.chmodSync(db, 0o644);
251
+ fs.chmodSync(fence, 0o644);
252
+
253
+ tightenStorageTreeSync(alias);
254
+
255
+ expect(fs.lstatSync(root).mode & 0o777).toBe(0o700);
256
+ expect(fs.lstatSync(db).mode & 0o777).toBe(0o600);
257
+ expect(fs.lstatSync(fence).mode & 0o777).toBe(0o600);
258
+ expect(fs.readFileSync(join(root, markerName), "utf8")).toBe("1\n");
259
+ expect(fs.lstatSync(join(root, markerName)).mode & 0o777).toBe(0o600);
260
+ const after = fs.lstatSync(alias);
261
+ expect(after.isSymbolicLink()).toBe(true);
262
+ expect(after.ino).toBe(before.ino);
263
+ expect(after.mode).toBe(before.mode);
264
+ expect(fs.readlinkSync(alias)).toBe("storage");
265
+ });
266
+
267
+ it("uses the bounded check on the target of a certified root link chain", () => {
268
+ const root = fixture();
269
+ const alias = join(root, "..", "alias");
270
+ const intermediate = join(root, "..", "intermediate");
271
+ fs.symlinkSync(intermediate, alias);
272
+ fs.symlinkSync(root, intermediate);
273
+ expect(tightenStorageTreeSync(alias).failures).toBe(0);
274
+
275
+ const lstat = spyOn(fs, "lstatSync");
276
+ try {
277
+ expect(tightenStorageTreeSync(alias, join(alias, "context.db")).failures).toBe(0);
278
+ expect(lstat.mock.calls.map(([path]) => path)).toContain(join(root, "context.db"));
279
+ expect(lstat.mock.calls.length).toBeLessThanOrEqual(10);
280
+ } finally {
281
+ lstat.mockRestore();
282
+ }
283
+ });
284
+
285
+ it("retarget between starts: new target fully walked, old untouched", () => {
286
+ const { root, alias } = linkedFixture("retarget-between");
287
+ const { root: next } = linkedFixture("retarget-next");
288
+ writeLooseOwnedTree(root);
289
+ writeLooseOwnedTree(next);
290
+ expect(tightenStorageTreeSync(alias).failures).toBe(0);
291
+ const before = ownedTreeModes(root);
292
+ const oldMarker = fs.lstatSync(join(root, markerName));
293
+ fs.unlinkSync(alias);
294
+ fs.symlinkSync(next, alias);
295
+
296
+ expect(tightenStorageTreeSync(alias).failures).toBe(0);
297
+ expect(ownedTreeModes(next)).toEqual([0o700, 0o600, 0o700, 0o600]);
298
+ expect(fs.existsSync(join(next, markerName))).toBe(true);
299
+ expect(ownedTreeModes(root)).toEqual(before);
300
+ expect(fs.lstatSync(join(root, markerName))).toMatchObject({
301
+ ino: oldMarker.ino,
302
+ mtimeMs: oldMarker.mtimeMs,
303
+ });
304
+ });
305
+
306
+ it("retarget during the walk: marker and every chmod stay in the first target", () => {
307
+ const { root, alias } = linkedFixture("retarget-during");
308
+ const { root: next } = linkedFixture("retarget-during-next");
309
+ writeLooseOwnedTree(root);
310
+ writeLooseOwnedTree(next);
311
+ const before = ownedTreeModes(next);
312
+ const realReaddir = fs.readdirSync;
313
+ let swapped = false;
314
+ const readdir = spyOn(fs, "readdirSync").mockImplementation((...args) => {
315
+ // The top-level eligibility probe is read-only. Redirect from inside the walk.
316
+ if (!swapped && args[0] === join(root, "models")) {
317
+ swapped = true;
318
+ fs.unlinkSync(alias);
319
+ fs.symlinkSync(next, alias);
320
+ }
321
+ return realReaddir(...args);
322
+ });
323
+ const chmod = spyOn(fs, "chmodSync");
324
+ try {
325
+ expect(tightenStorageTreeSync(alias, join(alias, "context.db")).failures).toBe(0);
326
+ expect(swapped).toBe(true);
327
+ expect(chmod.mock.calls.length).toBeGreaterThan(1);
328
+ expect(
329
+ chmod.mock.calls.every(
330
+ ([file]) => file === root || String(file).startsWith(`${root}/`),
331
+ ),
332
+ ).toBe(true);
333
+ } finally {
334
+ readdir.mockRestore();
335
+ chmod.mockRestore();
336
+ }
337
+ expect(fs.existsSync(join(root, markerName))).toBe(true);
338
+ expect(fs.existsSync(join(next, markerName))).toBe(false);
339
+ expect(ownedTreeModes(next)).toEqual(before);
340
+ });
341
+
342
+ it("does not follow an interior link to a loose directory outside storage", () => {
207
343
  const root = fixture();
208
- const alias = join(root, "alias");
344
+ const outside = join(root, "..", "outside");
345
+ const outsideFile = join(outside, "private.json");
346
+ const link = join(root, "models");
347
+ fs.mkdirSync(outside);
348
+ fs.writeFileSync(outsideFile, "{}");
349
+ fs.chmodSync(outside, 0o755);
350
+ fs.chmodSync(outsideFile, 0o644);
351
+ fs.symlinkSync(outside, link);
352
+ const linkMode = fs.lstatSync(link).mode;
353
+
354
+ for (let start = 0; start < 2; start++) {
355
+ expect(tightenStorageTreeSync(root).failures).toBe(0);
356
+ expect(fs.lstatSync(link).mode).toBe(linkMode);
357
+ expect(fs.readlinkSync(link)).toBe(outside);
358
+ expect(fs.lstatSync(outside).mode & 0o777).toBe(0o755);
359
+ expect(fs.lstatSync(outsideFile).mode & 0o777).toBe(0o644);
360
+ }
361
+ });
362
+
363
+ it("does not tighten through a root link with enforcement off", () => {
364
+ const root = fixture();
365
+ const alias = join(root, "..", "alias");
366
+ const file = join(root, "context.db");
209
367
  fs.symlinkSync(root, alias);
210
- expect(tightenStorageTreeSync(alias).failures).toBe(1);
368
+ fs.chmodSync(root, 0o755);
369
+ fs.chmodSync(file, 0o644);
370
+ fs.writeFileSync(join(root, markerName), "1\n", { mode: 0o600 });
371
+ setStoragePrivatePermissionEnforcement(false);
372
+
373
+ expect(tightenStorageTreeSync(alias)).toMatchObject({ tightened: 0, failures: 0 });
374
+ expect(fs.lstatSync(root).mode & 0o777).toBe(0o755);
375
+ expect(fs.lstatSync(file).mode & 0o777).toBe(0o644);
211
376
  expect(fs.existsSync(join(root, markerName))).toBe(false);
212
377
  });
213
378
 
379
+ it("does not tighten a linked filesystem root", () => {
380
+ const { root, alias } = linkedFixture("filesystem-root");
381
+ const realDirname = path.dirname;
382
+ // Model the root predicate without pointing the link at a real filesystem root.
383
+ const dirname = spyOn(path, "dirname").mockImplementation((file) =>
384
+ file === root ? root : realDirname(file),
385
+ );
386
+ try {
387
+ expect(tightenStorageTreeSync(alias)).toMatchObject({ tightened: 0, failures: 0 });
388
+ } finally {
389
+ dirname.mockRestore();
390
+ }
391
+ expect(mode(root)).toBe(0o755);
392
+ expect(fs.existsSync(join(root, markerName))).toBe(false);
393
+ });
394
+
395
+ it("does not tighten a linked target that resolves to the user's home folder", () => {
396
+ const { parent, root, alias } = linkedFixture("home");
397
+ const homePath = join(parent, "home-link");
398
+ fs.symlinkSync(root, homePath);
399
+ const home = spyOn(os, "homedir").mockReturnValue(homePath);
400
+ try {
401
+ expect(tightenStorageTreeSync(alias)).toMatchObject({ tightened: 0, failures: 0 });
402
+ } finally {
403
+ home.mockRestore();
404
+ }
405
+ expect(mode(root)).toBe(0o755);
406
+ expect(fs.existsSync(join(root, markerName))).toBe(false);
407
+ });
408
+
409
+ it("does not tighten a linked mount point on a different device from its parent", () => {
410
+ const { parent, root, alias } = linkedFixture("mount");
411
+ const realLstat = fs.lstatSync;
412
+ const lstat = spyOn(fs, "lstatSync").mockImplementation((...args) => {
413
+ const stat = realLstat(...args);
414
+ if (args[0] === parent) stat.dev = realLstat(root).dev + 1;
415
+ return stat;
416
+ });
417
+ try {
418
+ expect(tightenStorageTreeSync(alias)).toMatchObject({ tightened: 0, failures: 0 });
419
+ } finally {
420
+ lstat.mockRestore();
421
+ }
422
+ expect(mode(root)).toBe(0o755);
423
+ expect(fs.existsSync(join(root, markerName))).toBe(false);
424
+ });
425
+
426
+ it("leaves a linked target with only foreign entries alone", () => {
427
+ const { root, alias } = linkedFixture("foreign-only");
428
+ const foreign = join(root, "other-executable");
429
+ fs.writeFileSync(foreign, "other");
430
+ fs.chmodSync(foreign, 0o755);
431
+
432
+ expect(tightenStorageTreeSync(alias)).toMatchObject({ tightened: 0, failures: 0 });
433
+ expect(mode(foreign)).toBe(0o755);
434
+ expect(mode(root)).toBe(0o755);
435
+ expect(fs.existsSync(join(root, markerName))).toBe(false);
436
+ });
437
+
438
+ it("rechecks a linked target even with a marker and rejects lookalike entries", () => {
439
+ const { root, alias } = linkedFixture("foreign-with-marker");
440
+ writeLooseOwnedTree(root);
441
+ expect(tightenStorageTreeSync(alias).failures).toBe(0);
442
+ const marker = join(root, markerName);
443
+ const oldMarker = fs.lstatSync(marker);
444
+ const foreign = [
445
+ "context.db-wal-unrelated",
446
+ "context.db.corrupt-backup-20260811T123656789Z-not-a-backup",
447
+ "last_announced_version.123.not-hex-temp.tmp",
448
+ "identity-merge-backup-too-long",
449
+ "opencode.db",
450
+ "run-index.db",
451
+ ];
452
+ for (const name of foreign) fs.writeFileSync(join(root, name), "unrelated");
453
+ fs.chmodSync(root, 0o755);
454
+
455
+ expect(tightenStorageTreeSync(alias)).toMatchObject({
456
+ tightened: 0,
457
+ failures: 0,
458
+ rootLink: { skipped: foreign.length },
459
+ });
460
+ expect(mode(root)).toBe(0o755);
461
+ expect(fs.lstatSync(marker)).toMatchObject({
462
+ ino: oldMarker.ino,
463
+ mtimeMs: oldMarker.mtimeMs,
464
+ });
465
+ });
466
+
467
+ it("tightens a linked target containing only Finder's .DS_Store", () => {
468
+ const { root, alias } = linkedFixture("finder");
469
+ fs.writeFileSync(join(root, ".DS_Store"), "Finder fixture");
470
+ fs.chmodSync(join(root, ".DS_Store"), 0o600);
471
+ expect(tightenStorageTreeSync(alias)).toMatchObject({ tightened: 1, failures: 0 });
472
+ expect(mode(root)).toBe(0o700);
473
+ expect(fs.existsSync(join(root, markerName))).toBe(true);
474
+ });
475
+
476
+ it("does not count unresolved linked roots when enforcement is off", () => {
477
+ const { parent, alias } = linkedFixture("broken-off");
478
+ fs.unlinkSync(alias);
479
+ fs.symlinkSync(join(parent, "missing"), alias);
480
+ setStoragePrivatePermissionEnforcement(false);
481
+ expect(tightenStorageTreeSync(alias)).toEqual({ tightened: 0, failures: 0 });
482
+ });
483
+
214
484
  for (const target of ["context.db", ".", "context.db-wal", "context.db-shm"]) {
215
485
  it(`invalidates after repairing ${target}, then walks fully on the next open`, () => {
216
486
  const root = fixture();
@@ -239,7 +509,10 @@ describe.skipIf(process.platform === "win32")("startup permission certificate",
239
509
  const root = fixture();
240
510
  const marker = join(root, markerName);
241
511
  if (kind === "symlink") fs.symlinkSync("context.db", marker);
242
- else fs.writeFileSync(marker, "1\n", { mode: 0o644 });
512
+ else {
513
+ fs.writeFileSync(marker, "1\n", { mode: 0o600 });
514
+ fs.chmodSync(marker, 0o644);
515
+ }
243
516
  const lstat = spyOn(fs, "lstatSync");
244
517
  try {
245
518
  tightenStorageTreeSync(root);
@@ -403,6 +676,23 @@ describe.skipIf(process.platform === "win32")("startup permission certificate",
403
676
  expect(fs.existsSync(decoy)).toBe(true);
404
677
  });
405
678
 
679
+ it("stops marker invalidation at the linked storage boundary", () => {
680
+ const root = fixture();
681
+ const alias = join(root, "..", "alias");
682
+ const decoy = join(root, "..", markerName);
683
+ fs.symlinkSync(root, alias);
684
+ expect(tightenStorageTreeSync(alias).failures).toBe(0);
685
+ expect(fs.existsSync(join(root, markerName))).toBe(true);
686
+ fs.writeFileSync(decoy, "1\n", { mode: 0o600 });
687
+
688
+ const directory = join(alias, "lkg-recovery-fences");
689
+ fs.chmodSync(directory, 0o755);
690
+ ensurePrivateStorageDirectorySync(directory);
691
+
692
+ expect(fs.existsSync(join(root, markerName))).toBe(false);
693
+ expect(fs.existsSync(decoy)).toBe(true);
694
+ });
695
+
406
696
  it("removes certification while enforcement is off before a later private open", () => {
407
697
  const root = fixture();
408
698
  fs.writeFileSync(join(root, markerName), "1\n", { mode: 0o600 });