@cortexkit/opencode-magic-context 0.49.104 → 0.49.106

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 (157) 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-ywdwfzg5.js} +116 -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/hook.d.ts +1 -0
  28. package/dist/hooks/magic-context/hook.d.ts.map +1 -1
  29. package/dist/hooks/magic-context/lkg-persist.d.ts +1 -0
  30. package/dist/hooks/magic-context/lkg-persist.d.ts.map +1 -1
  31. package/dist/hooks/magic-context/lkg-slot.d.ts +7 -0
  32. package/dist/hooks/magic-context/lkg-slot.d.ts.map +1 -1
  33. package/dist/hooks/magic-context/transform-compartment-phase.d.ts +1 -0
  34. package/dist/hooks/magic-context/transform-compartment-phase.d.ts.map +1 -1
  35. package/dist/hooks/magic-context/transform.d.ts +3 -0
  36. package/dist/hooks/magic-context/transform.d.ts.map +1 -1
  37. package/dist/{index-8gzmeyae.js → index-20e7w8v8.js} +3 -3
  38. package/dist/{index-a9wn0d9h.js → index-3p08zzfq.js} +3 -3
  39. package/dist/{index-fd3hkyk1.js → index-42fsf88t.js} +1 -1
  40. package/dist/{index-tvh3y650.js → index-5phmpcme.js} +5 -5
  41. package/dist/{index-8yj4vd7k.js → index-92p5yfpp.js} +1 -1
  42. package/dist/{index-mwjvjn0p.js → index-a3t1ck7g.js} +6 -6
  43. package/dist/{index-4ba3zp54.js → index-as8bg7eh.js} +365 -113
  44. package/dist/{index-8eke8yh2.js → index-cxh5g5bt.js} +1 -1
  45. package/dist/{index-vegw385y.js → index-cy5fn70d.js} +89 -1
  46. package/dist/{index-4dywj733.js → index-dzb1yc9w.js} +1 -1
  47. package/dist/{index-3rp2b482.js → index-e4szqthq.js} +299 -37
  48. package/dist/{index-jjxpmypb.js → index-e7awy9eb.js} +1 -1
  49. package/dist/{index-ke0mkz7g.js → index-g1h1efr0.js} +1 -1
  50. package/dist/{index-f455a0g3.js → index-k37h4yrb.js} +5 -3
  51. package/dist/{index-3nxhxeeg.js → index-sfgz2h7y.js} +4 -4
  52. package/dist/{index-sqvkh5d0.js → index-xa8jgw6w.js} +20 -7
  53. package/dist/{index-hyvxmz3e.js → index-y1875y4h.js} +1 -1
  54. package/dist/{index-4v50y0jr.js → index-ydevzvfs.js} +1 -1
  55. package/dist/{index-4536jdzj.js → index-ze1t940p.js} +68 -25
  56. package/dist/{index-ab86c21b.js → index-zj0ra8vs.js} +1 -1
  57. package/dist/index.js +50 -59
  58. package/dist/migration-worker.js +3 -3
  59. package/dist/plugin/hooks/create-session-hooks.d.ts +2 -0
  60. package/dist/plugin/hooks/create-session-hooks.d.ts.map +1 -1
  61. package/dist/{project-embedding-registry-1n4cexsv.js → project-embedding-registry-0z0nd73p.js} +3 -3
  62. package/dist/raw-ordinal-warmup-worker.js +2 -2
  63. package/dist/{recomp-orchestrator-16rs8aty.js → recomp-orchestrator-7sf94073.js} +12 -12
  64. package/dist/{render-f32trg2t.js → render-93qzv0vk.js} +6 -6
  65. package/dist/{search-v9ywqb4f.js → search-7e1rcqb7.js} +9 -9
  66. package/dist/{search-archive-yh6xtvrx.js → search-archive-dv483a5c.js} +2 -2
  67. package/dist/shared/sqlite-busy-test-support.d.ts +21 -0
  68. package/dist/shared/sqlite-busy-test-support.d.ts.map +1 -0
  69. package/dist/shared/sqlite-write-locker-test-support.d.ts +12 -0
  70. package/dist/shared/sqlite-write-locker-test-support.d.ts.map +1 -1
  71. package/dist/{store-wpx314rk.js → store-4eeezg83.js} +2 -2
  72. package/dist/{store-reader-c5fwa9qx.js → store-reader-g8w2wp88.js} +1 -1
  73. package/dist/{transform-postprocess-phase-yef4mxk3.js → transform-postprocess-phase-vd9rckyd.js} +13 -13
  74. package/dist/v2/auto-search-worker.js +3 -3
  75. package/dist/v2/chunk-embedding-write-worker.js +8 -5
  76. package/dist/v2/{context-mk2h2ven.js → context-6g9j3tq9.js} +248 -160
  77. package/dist/v2/{embedding-backfill-kyn5sv0f.js → embedding-backfill-e44pv5db.js} +4 -4
  78. package/dist/v2/event-subscription.fixture.d.ts +9 -0
  79. package/dist/v2/event-subscription.fixture.d.ts.map +1 -0
  80. package/dist/v2/hidden-model-activity.d.ts +13 -0
  81. package/dist/v2/hidden-model-activity.d.ts.map +1 -1
  82. package/dist/v2/hooks/context.d.ts +1 -0
  83. package/dist/v2/hooks/context.d.ts.map +1 -1
  84. package/dist/v2/hooks/dream-trigger.d.ts +2 -1
  85. package/dist/v2/hooks/dream-trigger.d.ts.map +1 -1
  86. package/dist/v2/hooks/event-subscription-worker.d.ts +11 -0
  87. package/dist/v2/hooks/event-subscription-worker.d.ts.map +1 -0
  88. package/dist/v2/hooks/types.d.ts +1 -0
  89. package/dist/v2/hooks/types.d.ts.map +1 -1
  90. package/dist/v2/hooks/update-check.d.ts +1 -0
  91. package/dist/v2/hooks/update-check.d.ts.map +1 -1
  92. package/dist/v2/{message-index-bounded-j1sxtefe.js → message-index-bounded-nwqfb1p5.js} +3 -3
  93. package/dist/v2/migration-worker.js +3 -3
  94. package/dist/v2/{project-embedding-registry-1jv2rxhb.js → project-embedding-registry-rhzjnypp.js} +3 -3
  95. package/dist/v2/raw-ordinal-warmup-worker.js +4 -4
  96. package/dist/v2/{read-session-chunk-p6z3kmdj.js → read-session-chunk-brqatg83.js} +2 -2
  97. package/dist/v2/{recomp-orchestrator-5t2csd46.js → recomp-orchestrator-j84xfa80.js} +14 -14
  98. package/dist/v2/{render-jpj43axy.js → render-tzs5r2pg.js} +10 -10
  99. package/dist/v2/{search-archive-wbhxp0p1.js → search-archive-31dpm5zs.js} +5 -5
  100. package/dist/v2/{search-w9m2fd5c.js → search-sffewrs4.js} +12 -12
  101. package/dist/v2/{server-47ajg9xc.js → server-16115spd.js} +1 -1
  102. package/dist/v2/server-28jqb7s0.js +6 -0
  103. package/dist/v2/{server-qg8jyfxa.js → server-5xx10mqe.js} +1 -1
  104. package/dist/v2/{server-t45hgcsg.js → server-7jw608jk.js} +2 -2
  105. package/dist/v2/{server-3mb205v9.js → server-83rjf4df.js} +1 -1
  106. package/dist/v2/{server-xpy46ddq.js → server-af25mmb6.js} +3 -3
  107. package/dist/v2/{server-ga6y57vh.js → server-c32505fr.js} +6 -4
  108. package/dist/v2/{server-qdpd8h27.js → server-fn6k1ack.js} +1 -1
  109. package/dist/v2/{server-8m5wk6aq.js → server-ggs7sxp6.js} +5 -5
  110. package/dist/v2/{server-zsbc0n4v.js → server-ghb2q1z9.js} +1 -1
  111. package/dist/v2/{server-af51b1zg.js → server-hqcdvs2n.js} +11 -11
  112. package/dist/v2/{server-9ms9b75c.js → server-j00jprwm.js} +4 -6
  113. package/dist/v2/{server-8f92sd2r.js → server-jqk6g663.js} +72 -27
  114. package/dist/v2/{server-b01a7dhj.js → server-kk2kbzq3.js} +1 -1
  115. package/dist/v2/{server-mc5t7k8v.js → server-ma0qhqg9.js} +1 -1
  116. package/dist/v2/{server-x22jtpna.js → server-n3bfqd0j.js} +4 -2
  117. package/dist/v2/{server-wmpgvvc4.js → server-pjvqyg6g.js} +365 -113
  118. package/dist/v2/{server-jrs4gny6.js → server-qtajgx1e.js} +89 -1
  119. package/dist/v2/server-t104h957.js +177 -0
  120. package/dist/v2/{server-j09jx1n9.js → server-v2r04xds.js} +1 -1
  121. package/dist/v2/{server-3gnpqjez.js → server-v60f6dk3.js} +26 -11
  122. package/dist/v2/{server-7c5p0bh1.js → server-z77hman6.js} +1 -1
  123. package/dist/v2/server.js +31 -40
  124. package/dist/v2/{storage-tags-s7nvvyg8.js → storage-tags-ee72g2zv.js} +1 -1
  125. package/dist/v2/{store-mba47sxn.js → store-9rsrj5pt.js} +2 -2
  126. package/dist/v2/{store-reader-w7w8vfsy.js → store-reader-tb0f9621.js} +1 -1
  127. package/dist/v2/store-reader.d.ts +1 -1
  128. package/dist/v2/store-reader.d.ts.map +1 -1
  129. package/dist/v2/tui/index.d.ts.map +1 -1
  130. package/dist/v2/{v2-archive-reader-5njmg3a3.js → v2-archive-reader-7vrma2dm.js} +1 -1
  131. package/dist/v2/{wrapup-orchestrator-ykgx8hw8.js → wrapup-orchestrator-m1ymvccg.js} +14 -14
  132. package/dist/{v2-archive-reader-y38khjax.js → v2-archive-reader-aqck4zea.js} +1 -1
  133. package/dist/{wrapup-orchestrator-a9tshrp4.js → wrapup-orchestrator-k7azmnym.js} +13 -13
  134. package/package.json +1 -1
  135. package/src/config/migrate-config-location.test.ts +41 -29
  136. package/src/shared/model-suggestion-retry.test.ts +137 -90
  137. package/src/shared/off-thread-migration-clock.test.ts +19 -9
  138. package/src/shared/prompt-async-transport.test.ts +125 -42
  139. package/src/shared/rpc-async-probes.test.ts +56 -36
  140. package/src/shared/rpc-client.test.ts +51 -18
  141. package/src/shared/sqlite-acquisition-routing.test.ts +79 -22
  142. package/src/shared/sqlite-busy-budget-review.test.ts +129 -111
  143. package/src/shared/sqlite-busy-test-support.ts +154 -0
  144. package/src/shared/sqlite-foreground-wait.test.ts +213 -156
  145. package/src/shared/sqlite-pass-scope.test.ts +142 -105
  146. package/src/shared/sqlite-turn-deadline.test.ts +149 -124
  147. package/src/shared/sqlite-write-locker-test-support.ts +44 -12
  148. package/src/shared/stable-json-linear.test.ts +29 -11
  149. package/src/shared/startup-maintenance-policy.test.ts +72 -2
  150. package/src/shared/storage-busy.test.ts +45 -18
  151. package/src/shared/storage-file-mutex-review.test.ts +65 -51
  152. package/src/shared/tui-preferences.test.ts +15 -5
  153. package/src/shared/worker-shutdown.test.ts +26 -20
  154. package/src/tui/data/notification-socket.test.ts +220 -108
  155. package/src/v2/tui/index.ts +5 -1
  156. package/src/v2/tui/status-dialog-fallback.test.ts +23 -1
  157. package/dist/v2/server-84w6rvvf.js +0 -14
@@ -3,8 +3,8 @@
3
3
  *
4
4
  * Run directly as `bun sqlite-write-locker-test-support.ts <db> <holdMs>`, the file
5
5
  * opens the database, takes the write lock with BEGIN IMMEDIATE, prints `LOCKED`,
6
- * holds the lock for `holdMs`, commits and prints `RELEASED`. Tests start it
7
- * through `startSqliteWriteLocker`.
6
+ * holds the lock for `holdMs`, commits and prints `RELEASED`. With `--gated`,
7
+ * the hold interval starts only after the parent closes the child's stdin.
8
8
  *
9
9
  * The lock has to come from a different process. A second connection in the
10
10
  * test's own process cannot release its lock while the test's main thread is
@@ -18,12 +18,18 @@ export interface SqliteWriteLocker {
18
18
  exited: Promise<number>;
19
19
  }
20
20
 
21
- /** Start the locker and resolve once it reports that it holds the write lock. */
22
- export async function startSqliteWriteLocker(
21
+ type Lock = "write" | "exclusive" | { read: string };
22
+
23
+ async function startLocker(
23
24
  dbPath: string,
24
25
  holdMs: number,
25
- ): Promise<SqliteWriteLocker> {
26
- const child = Bun.spawn(["bun", import.meta.path, dbPath, String(holdMs)], {
26
+ gated: boolean,
27
+ lock: Lock = "write",
28
+ ): Promise<SqliteWriteLocker & { release: () => void }> {
29
+ const args = ["bun", import.meta.path, dbPath, String(holdMs)];
30
+ if (gated) args.push("--gated", JSON.stringify(lock));
31
+ const child = Bun.spawn(args, {
32
+ stdin: "pipe",
27
33
  stdout: "pipe",
28
34
  stderr: "pipe",
29
35
  windowsHide: true,
@@ -40,11 +46,34 @@ export async function startSqliteWriteLocker(
40
46
  seen += decoder.decode(chunk.value, { stream: true });
41
47
  }
42
48
  reader.releaseLock();
43
- return { exited: child.exited };
49
+ let released = false;
50
+ return {
51
+ exited: child.exited,
52
+ release: () => {
53
+ if (released) return;
54
+ released = true;
55
+ child.stdin.end();
56
+ },
57
+ };
58
+ }
59
+
60
+ /** Start the locker and resolve once it reports that it holds the write lock. */
61
+ export function startSqliteWriteLocker(dbPath: string, holdMs: number): Promise<SqliteWriteLocker> {
62
+ return startLocker(dbPath, holdMs, false);
63
+ }
64
+
65
+ /** Keep the lock until release(); an exit code of zero confirms the commit. */
66
+ export function startGatedSqliteWriteLocker(dbPath: string, holdMs = 0) {
67
+ return startLocker(dbPath, holdMs, true);
68
+ }
69
+
70
+ /** Use an exclusive lock to block reads, or a read transaction to block COMMIT in DELETE mode. */
71
+ export function startGatedSqliteLocker(dbPath: string, lock: Lock) {
72
+ return startLocker(dbPath, 0, true, lock);
44
73
  }
45
74
 
46
- function main(): void {
47
- const [dbPath, holdArg] = process.argv.slice(2);
75
+ async function main(): Promise<void> {
76
+ const [dbPath, holdArg, gate, lockArg] = process.argv.slice(2);
48
77
  const holdMs = Number(holdArg);
49
78
  if (!dbPath || !Number.isFinite(holdMs) || holdMs < 0) {
50
79
  process.stderr.write("usage: sqlite-write-locker-test-support.ts <db> <holdMs>\n");
@@ -52,12 +81,15 @@ function main(): void {
52
81
  }
53
82
  const db = new Database(dbPath);
54
83
  db.exec("PRAGMA busy_timeout = 5000");
55
- db.exec("BEGIN IMMEDIATE");
84
+ const lock: Lock = lockArg ? JSON.parse(lockArg) : "write";
85
+ if (typeof lock === "object") db.exec(`BEGIN; ${lock.read}`);
86
+ else db.exec(lock === "exclusive" ? "BEGIN EXCLUSIVE" : "BEGIN IMMEDIATE");
56
87
  process.stdout.write("LOCKED\n");
57
- Bun.sleepSync(holdMs);
88
+ if (gate === "--gated") await new Response(Bun.stdin.stream()).arrayBuffer();
89
+ if (holdMs > 0) Bun.sleepSync(holdMs);
58
90
  db.exec("COMMIT");
59
91
  db.close();
60
92
  process.stdout.write("RELEASED\n");
61
93
  }
62
94
 
63
- if (import.meta.main) main();
95
+ if (import.meta.main) await main();
@@ -100,17 +100,35 @@ describe("stableStringify", () => {
100
100
  scaleTest(
101
101
  "copies a deeply nested value once, not once per level",
102
102
  (slow) => {
103
- // The slow fixture wraps 2 MB in 3,000 levels: joining at every level
104
- // copied about 6 GB of text; the unit fixture retains nested-byte coverage.
105
- const size = slow ? 2_000_000 : 4096;
106
- let node: unknown = { body: "x".repeat(size) };
107
- for (let depth = 0; depth < (slow ? 3_000 : 64); depth += 1)
108
- node = { child: node, depth };
109
- const started = performance.now();
110
- const text = stableStringify(node);
111
- expect(text.length).toBeGreaterThan(size);
112
- expect(text).toContain("x".repeat(size));
113
- if (slow) expect(performance.now() - started).toBeLessThan(300);
103
+ function joinedCodeUnits(size: number, levels: number) {
104
+ const body = "x".repeat(size);
105
+ let node: unknown = { body };
106
+ for (let depth = 0; depth < levels; depth += 1) node = { child: node, depth };
107
+ const join = Array.prototype.join;
108
+ let copied = 0;
109
+ let text: string;
110
+ Array.prototype.join = function (separator) {
111
+ const joined = join.call(this, separator);
112
+ copied += joined.length;
113
+ return joined;
114
+ };
115
+ try {
116
+ text = stableStringify(node);
117
+ } finally {
118
+ Array.prototype.join = join;
119
+ }
120
+ expect(text.length).toBeGreaterThan(size);
121
+ expect(text).toContain(body);
122
+ return copied;
123
+ }
124
+
125
+ const small = joinedCodeUnits(4096, 64);
126
+ const large = joinedCodeUnits(16_384, 256);
127
+ // Both the nested body and wrapper count quadruple; allow one extra
128
+ // digit in each wrapper without allowing nested text to be rejoined.
129
+ expect(small).toBeGreaterThan(4096);
130
+ expect(large).toBeLessThanOrEqual(4 * small + 256);
131
+ if (slow) expect(joinedCodeUnits(2_000_000, 3_000)).toBeLessThan(2_100_000);
114
132
  },
115
133
  30_000,
116
134
  );
@@ -1,4 +1,4 @@
1
- import { afterEach, expect, spyOn, test } from "bun:test";
1
+ import { afterEach, expect, jest, spyOn, test } from "bun:test";
2
2
  import { readFileSync } from "node:fs";
3
3
  import { join, resolve } from "node:path";
4
4
  import ts from "typescript";
@@ -13,7 +13,11 @@ import {
13
13
  openDatabase,
14
14
  openDatabaseAsync,
15
15
  } from "../features/magic-context/storage-db";
16
+ import * as toolOwner from "../features/magic-context/tool-owner-backfill";
16
17
  import * as warmup from "../hooks/magic-context/raw-ordinal-warmup";
18
+ import { _resetHarnessForTesting, setHarness } from "./harness";
19
+ import { resetReusableWorkersForTests } from "./reusable-worker";
20
+ import * as pluginImports from "./stale-plugin-build";
17
21
  import { createTestTempDir } from "./test-temp-dir";
18
22
 
19
23
  const root = resolve(import.meta.dir, "../../../..");
@@ -60,6 +64,72 @@ test.each([
60
64
  );
61
65
  });
62
66
 
67
+ test("Pi startup maps FTS rows without importing or backfilling the OpenCode store", async () => {
68
+ const home = createTestTempDir("mc-pi-startup-policy-");
69
+ process.env.XDG_DATA_HOME = home.dir;
70
+ _resetHarnessForTesting();
71
+ setHarness("pi");
72
+ const previous = __setScheduleStartupMaintenanceOnOpenForTests(true);
73
+ // Keep an erroneous OpenCode branch observable without opening a host store.
74
+ const toolOwners = spyOn(toolOwner, "runToolOwnerBackfill").mockImplementation(() => {
75
+ throw new Error("This fixture has no OpenCode tool-owner source");
76
+ });
77
+ const messageTimes = spyOn(messageTime, "startMessageTimeBackfill").mockResolvedValue();
78
+ try {
79
+ const db = openDatabase();
80
+ if (!db) throw new Error("Throwaway Pi context store unavailable");
81
+ expect(__getDatabaseStartupStateForTests(db).timerScheduled).toBe(true);
82
+ db.exec(`
83
+ INSERT INTO message_history_fts(session_id, message_ordinal, message_id, role, content)
84
+ VALUES ('legacy-pi', 1, 'pi-message', 'user', 'indexed in Pi');
85
+ UPDATE message_time_backfill_state
86
+ SET cursor_session_id = 'opencode-progress', cursor_ordinal = 42, updated_at = 1234
87
+ WHERE id = 1;
88
+ `);
89
+ const cursor = db.prepare("SELECT * FROM message_time_backfill_state WHERE id = 1");
90
+ const expected = {
91
+ id: 1,
92
+ cursor_session_id: "opencode-progress",
93
+ cursor_ordinal: 42,
94
+ completed: 0,
95
+ updated_at: 1234,
96
+ };
97
+ expect(cursor.get()).toEqual(expected);
98
+
99
+ // The FTS worker only uses context.db. Park its watchdogs while waiting
100
+ // for its real reply, and count lazy imports from the joined startup chain.
101
+ jest.useFakeTimers({ doNotFake: ["setImmediate", "nextTick", "queueMicrotask"] });
102
+ const imports = spyOn(pluginImports, "importPluginModule");
103
+ try {
104
+ await __waitForDatabaseStartupForTests(db);
105
+ expect({
106
+ toolOwners: toolOwners.mock.calls.length,
107
+ readerImports: imports.mock.calls.length,
108
+ messageTimes: messageTimes.mock.calls.length,
109
+ }).toEqual({ toolOwners: 0, readerImports: 0, messageTimes: 0 });
110
+ expect(cursor.get()).toEqual(expected);
111
+ expect(
112
+ db
113
+ .prepare(
114
+ "SELECT message_ordinal FROM message_fts_rowid_map WHERE session_id = ?",
115
+ )
116
+ .get("legacy-pi"),
117
+ ).toEqual({ message_ordinal: 1 });
118
+ } finally {
119
+ imports.mockRestore();
120
+ jest.useRealTimers();
121
+ }
122
+ } finally {
123
+ await closeDatabase();
124
+ await resetReusableWorkersForTests();
125
+ toolOwners.mockRestore();
126
+ messageTimes.mockRestore();
127
+ __setScheduleStartupMaintenanceOnOpenForTests(previous);
128
+ _resetHarnessForTesting();
129
+ home.cleanup();
130
+ }
131
+ });
132
+
63
133
  test("CLI uses the unit policy while end-to-end preloads only isolate test files and stores", () => {
64
134
  expect(preloads("cli")).toEqual(["../plugin/src/test-preload.ts"]);
65
135
  expect(preloads("e2e-tests")).toEqual(["./src/test-preload.ts", "../plugin/test-preload.ts"]);
@@ -92,7 +162,7 @@ test.each([
92
162
  timerScheduled: false,
93
163
  running: null,
94
164
  });
95
- await new Promise<void>((resolve) => setTimeout(resolve, 0));
165
+ await __waitForDatabaseStartupForTests(db);
96
166
  expect(worker).not.toHaveBeenCalled();
97
167
  expect(time).not.toHaveBeenCalled();
98
168
  await closeDatabase();
@@ -8,40 +8,67 @@ import {
8
8
  withAsyncPrivilegedWriter,
9
9
  withPrivilegedWriter,
10
10
  } from "./sqlite";
11
+ import { observeSqliteBusy, startSqliteRetryClock } from "./sqlite-busy-test-support";
12
+ import { startGatedSqliteWriteLocker } from "./sqlite-write-locker-test-support";
11
13
  import { createTestTempDirFromPath } from "./test-temp-dir";
12
14
 
13
15
  describe("writer acquisition", () => {
14
16
  test("exhausted async admission preserves the foreground budget and never invokes the callback", async () => {
15
17
  const dir = createTestTempDirFromPath(join(tmpdir(), "mc-writer-budget-"));
16
18
  const path = join(dir, "context.db");
17
- const blocker = new Database(path);
18
- blocker.exec(
19
- "CREATE TABLE context_privilege_state(id INTEGER PRIMARY KEY, enabled INTEGER)",
19
+ const probe = observeSqliteBusy(
20
+ (sql, method) => method === "exec" && sql === "BEGIN IMMEDIATE",
20
21
  );
21
22
  const db = new Database(path);
22
- db.exec("PRAGMA busy_timeout=5000");
23
- blocker.exec("BEGIN IMMEDIATE");
23
+ db.exec(`PRAGMA journal_mode=WAL; PRAGMA busy_timeout=5000;
24
+ CREATE TABLE context_privilege_state(id INTEGER PRIMARY KEY, enabled INTEGER);
25
+ CREATE TABLE result(value TEXT)`);
26
+ const locker = await startGatedSqliteWriteLocker(path);
27
+ const clock = startSqliteRetryClock();
28
+ const abort = new AbortController();
24
29
  let calls = 0;
25
- let ticks = 0;
26
- const timer = setInterval(() => ticks++, 50);
27
- const started = performance.now();
30
+ let settled = false;
31
+ const write = () => {
32
+ calls++;
33
+ db.exec("INSERT INTO result VALUES ('once')");
34
+ };
35
+ const pending = withAsyncPrivilegedWriter(db, write, { signal: abort.signal }).finally(
36
+ () => {
37
+ settled = true;
38
+ },
39
+ );
40
+ void pending.catch(() => {});
28
41
  try {
29
- await expect(withAsyncPrivilegedWriter(db, () => calls++)).rejects.toThrow(
30
- "acquisition remained busy",
31
- );
32
- expect(performance.now() - started).toBeGreaterThanOrEqual(16_500);
33
- expect(performance.now() - started).toBeLessThan(17_500);
34
- expect(ticks).toBeGreaterThan(100);
42
+ await clock.advance(0);
43
+ await clock.advance(500);
44
+ for (let retry = 0; retry < 15; retry++) await clock.advance(1000);
45
+ await clock.advance(999);
46
+ expect(settled).toBe(false);
47
+ expect(probe.timeouts).toEqual(Array(17).fill(25));
48
+ await clock.advance(1);
49
+ expect(probe.timeouts).toEqual([...Array(17).fill(25), 0]);
50
+ await clock.advance(0);
51
+ expect(settled).toBe(true);
52
+ await expect(pending).rejects.toThrow("acquisition remained busy");
35
53
  expect(calls).toBe(0);
54
+ expect(db.prepare("SELECT * FROM result").all()).toEqual([]);
36
55
  expect(db.prepare("PRAGMA busy_timeout").get()).toEqual({ timeout: 5000 });
56
+ locker.release();
57
+ expect(await locker.exited).toBe(0);
58
+ await withAsyncPrivilegedWriter(db, write);
59
+ expect(calls).toBe(1);
60
+ expect(db.prepare("SELECT * FROM result").all()).toEqual([{ value: "once" }]);
37
61
  } finally {
38
- clearInterval(timer);
39
- blocker.exec("ROLLBACK");
40
- blocker.close();
62
+ abort.abort();
63
+ await pending.catch(() => {});
64
+ clock.restore();
65
+ locker.release();
66
+ await locker.exited;
41
67
  db.close();
68
+ probe.restore();
42
69
  rmSync(dir, { recursive: true, force: true });
43
70
  }
44
- }, 30000);
71
+ });
45
72
 
46
73
  test("busy callback rolls back without retrying mutations", () => {
47
74
  const db = new Database(":memory:");
@@ -1,4 +1,4 @@
1
- import { expect, spyOn, test } from "bun:test";
1
+ import { afterEach, beforeEach, expect, spyOn, test } from "bun:test";
2
2
  import * as fs from "node:fs";
3
3
  import { existsSync, readdirSync, readFileSync, rmdirSync, rmSync, writeFileSync } from "node:fs";
4
4
  import { join } from "node:path";
@@ -10,6 +10,14 @@ import { listOpenFiles } from "./test-open-files";
10
10
  import { createTestTempDir } from "./test-temp-dir";
11
11
 
12
12
  const mutex = join(import.meta.dir, "storage-file-mutex.ts");
13
+ let now = 0;
14
+ let restoreClock: () => void;
15
+ beforeEach(() => {
16
+ now = 0;
17
+ const clock = spyOn(performance, "now").mockImplementation(() => now);
18
+ restoreClock = () => clock.mockRestore();
19
+ });
20
+ afterEach(() => restoreClock());
13
21
 
14
22
  test("mutex removes its empty directory after sequential operations and thrown work", () => {
15
23
  const { dir: root, cleanup } = createTestTempDir("mc-mutex-sequence-");
@@ -154,12 +162,11 @@ test("mutex retries when retirement removes the lock directory before validation
154
162
 
155
163
  async function holder(root: string) {
156
164
  const script = `
157
- import { existsSync } from 'node:fs';
165
+ import { readSync } from 'node:fs';
158
166
  import { withStorageFileMutex } from ${JSON.stringify(mutex)};
159
167
  withStorageFileMutex(${JSON.stringify(join(root, "locks"))}, () => {
160
168
  console.log('HELD');
161
- const pause = new Int32Array(new SharedArrayBuffer(4));
162
- while (!existsSync(${JSON.stringify(join(root, "release"))})) Atomics.wait(pause, 0, 0, 10);
169
+ readSync(0, Buffer.alloc(1), 0, 1, null);
163
170
  });`;
164
171
  const child = Bun.spawn([process.execPath, "--eval", script], {
165
172
  env: {
@@ -171,12 +178,21 @@ withStorageFileMutex(${JSON.stringify(join(root, "locks"))}, () => {
171
178
  },
172
179
  stdout: "pipe",
173
180
  stderr: "pipe",
181
+ stdin: "pipe",
174
182
  windowsHide: true,
175
183
  });
176
184
  const reader = child.stdout.getReader();
177
- const first = await reader.read();
178
- expect(new TextDecoder().decode(first.value)).toContain("HELD");
179
- reader.releaseLock();
185
+ try {
186
+ const decoder = new TextDecoder();
187
+ let ready = "";
188
+ while (!ready.includes("HELD\n")) {
189
+ const chunk = await reader.read();
190
+ if (chunk.done) throw new Error("mutex holder exited before acquiring its ticket");
191
+ ready += decoder.decode(chunk.value, { stream: true });
192
+ }
193
+ } finally {
194
+ reader.releaseLock();
195
+ }
180
196
  if (process.platform === "darwin") {
181
197
  const files = listOpenFiles(child.pid);
182
198
  // A paused child's isolation cannot be established from a missing inventory.
@@ -194,6 +210,35 @@ withStorageFileMutex(${JSON.stringify(join(root, "locks"))}, () => {
194
210
  return child;
195
211
  }
196
212
 
213
+ function expectMutexRefusalAtDeadline(directory: string, budgetMs = 200) {
214
+ const deadline = now + budgetMs;
215
+ const waitedAt: number[] = [];
216
+ const wait = spyOn(Atomics, "wait").mockImplementation(() => {
217
+ waitedAt.push(now);
218
+ // The native retry sleep is synchronous. Move to one tick before
219
+ // expiry on the first suspension and to expiry on the second.
220
+ now = waitedAt.length === 1 ? deadline - 1 : now + 1;
221
+ return "timed-out";
222
+ });
223
+ let entered = false;
224
+ try {
225
+ expect(() =>
226
+ withStorageFileMutex(
227
+ directory,
228
+ () => {
229
+ entered = true;
230
+ },
231
+ budgetMs,
232
+ ),
233
+ ).toThrow("Storage safety publication lock is unavailable");
234
+ expect(entered).toBe(false);
235
+ expect(waitedAt).toEqual([deadline - budgetMs, deadline - 1]);
236
+ expect(readdirSync(directory)).toHaveLength(1);
237
+ } finally {
238
+ wait.mockRestore();
239
+ }
240
+ }
241
+
197
242
  test.skipIf(process.platform === "win32")(
198
243
  "independent mutex: paused live holder is not taken over, dead holder is reclaimed",
199
244
  async () => {
@@ -201,17 +246,7 @@ test.skipIf(process.platform === "win32")(
201
246
  const child = await holder(root);
202
247
  try {
203
248
  process.kill(child.pid, "SIGSTOP");
204
- const start = performance.now();
205
- expect(() =>
206
- withStorageFileMutex(
207
- join(root, "locks"),
208
- () => {
209
- throw new Error("LIVE HOLDER WAS TAKEN OVER");
210
- },
211
- 200,
212
- ),
213
- ).toThrow("Storage safety publication lock is unavailable");
214
- expect(performance.now() - start).toBeLessThan(2500);
249
+ expectMutexRefusalAtDeadline(join(root, "locks"));
215
250
  process.kill(child.pid, "SIGKILL");
216
251
  await child.exited;
217
252
  let reached = false;
@@ -245,22 +280,12 @@ test.skipIf(process.platform === "win32")(
245
280
  const ticket = join(locks, readdirSync(locks)[0]!);
246
281
  expect(JSON.parse(readFileSync(ticket, "utf8")).birth).toBeString();
247
282
  writeFileSync(ticket, "inconclusive owner identity", { mode: 0o600 });
248
- const start = performance.now();
249
- let entered = false;
250
- expect(() =>
251
- withStorageFileMutex(
252
- locks,
253
- () => {
254
- entered = true;
255
- },
256
- 200,
257
- ),
258
- ).toThrow("Storage safety publication lock is unavailable");
259
- expect(entered).toBe(false);
260
- expect(performance.now() - start).toBeLessThan(2500);
261
- expect(readdirSync(locks)).toHaveLength(1);
283
+ expectMutexRefusalAtDeadline(locks);
284
+ child.stdin.end();
285
+ expect(await child.exited).toBe(0);
286
+ expect(withStorageFileMutex(locks, () => "acquired")).toBe("acquired");
262
287
  } finally {
263
- child.kill("SIGKILL");
288
+ if (child.exitCode === null) child.kill("SIGKILL");
264
289
  await child.exited;
265
290
  cleanup();
266
291
  }
@@ -279,23 +304,14 @@ test.skipIf(process.platform === "win32")(
279
304
  throw Object.assign(new Error("Denied PID probe"), { code: "EPERM" });
280
305
  },
281
306
  });
282
- const start = performance.now();
283
- let entered = false;
284
- expect(() =>
285
- withStorageFileMutex(
286
- join(root, "locks"),
287
- () => {
288
- entered = true;
289
- },
290
- 200,
291
- ),
292
- ).toThrow("Storage safety publication lock is unavailable");
293
- expect(entered).toBe(false);
294
- expect(performance.now() - start).toBeLessThan(2500);
295
- expect(readdirSync(join(root, "locks"))).toHaveLength(1);
307
+ const locks = join(root, "locks");
308
+ expectMutexRefusalAtDeadline(locks);
309
+ child.stdin.end();
310
+ expect(await child.exited).toBe(0);
311
+ expect(withStorageFileMutex(locks, () => "acquired")).toBe("acquired");
296
312
  } finally {
297
313
  __resetRpcIdentityTestHooks();
298
- child.kill("SIGKILL");
314
+ if (child.exitCode === null) child.kill("SIGKILL");
299
315
  await child.exited;
300
316
  cleanup();
301
317
  }
@@ -401,9 +417,7 @@ test("when the unwritten ticket cannot be removed, the write error wins and the
401
417
  remover.mockRestore();
402
418
  // The empty ticket still has a live owner, so a later acquisition waits for
403
419
  // it and refuses within its budget.
404
- expect(() => withStorageFileMutex(directory, () => "blocked", 100)).toThrow(
405
- "Storage safety publication lock is unavailable",
406
- );
420
+ expectMutexRefusalAtDeadline(directory, 100);
407
421
  } finally {
408
422
  logged.mockRestore();
409
423
  remover.mockRestore();
@@ -122,11 +122,21 @@ describe("watchTuiPreferences", () => {
122
122
  emitWatchEvent("rename", basename(file));
123
123
  resolveInitialRead(next);
124
124
 
125
- const result = await Promise.race([
126
- observed,
127
- new Promise<"timeout">((resolve) => setTimeout(() => resolve("timeout"), 300)),
128
- ]);
129
- expect(result).toEqual({ memory: false });
125
+ let watchdog: ReturnType<typeof setTimeout> | undefined;
126
+ try {
127
+ const result = await Promise.race([
128
+ observed,
129
+ new Promise<never>((_, reject) => {
130
+ watchdog = setTimeout(
131
+ () => reject(new Error("Watchdog: waiting for the replaced preferences")),
132
+ 300,
133
+ );
134
+ }),
135
+ ]);
136
+ expect(result).toEqual({ memory: false });
137
+ } finally {
138
+ clearTimeout(watchdog);
139
+ }
130
140
  });
131
141
  });
132
142
 
@@ -1,5 +1,5 @@
1
1
  import { Database } from "bun:sqlite";
2
- import { afterEach, expect, test } from "bun:test";
2
+ import { afterEach, beforeEach, expect, jest, spyOn, test } from "bun:test";
3
3
  import { EventEmitter } from "node:events";
4
4
  import { join } from "node:path";
5
5
  import { Worker } from "node:worker_threads";
@@ -12,7 +12,11 @@ import {
12
12
  } from "./worker-shutdown";
13
13
 
14
14
  const cleanups: (() => void)[] = [];
15
+ // Only the parent's fallback timer is controlled; the worker still sends
16
+ // readiness and exits through its real message port on its own thread.
17
+ beforeEach(() => jest.useFakeTimers({ doNotFake: ["setImmediate"] }));
15
18
  afterEach(() => {
19
+ jest.useRealTimers();
16
20
  for (const cleanup of cleanups.splice(0)) cleanup();
17
21
  });
18
22
 
@@ -40,10 +44,7 @@ test("a worker asked to close shuts its connection and exits by itself", async (
40
44
  const { owner, worker, exitCode } = await start("cooperative");
41
45
  const before = counts(site);
42
46
  const shutdown = createWorkerShutdown(worker, site, 10_000);
43
- const started = performance.now();
44
47
  await shutdown.close();
45
- // Well inside the deadline: the worker exited on its own, it was not terminated.
46
- expect(performance.now() - started).toBeLessThan(5_000);
47
48
  expect(await exitCode).toBe(0);
48
49
  expect(counts(site)).toEqual({ graceful: before.graceful + 1, forced: before.forced });
49
50
  owner.exec("PRAGMA busy_timeout=0");
@@ -56,11 +57,23 @@ test("a worker that does not exit is terminated at the deadline", async () => {
56
57
  const { worker, exitCode } = await start("deaf");
57
58
  const before = counts(site);
58
59
  const shutdown = createWorkerShutdown(worker, site, 100);
59
- const started = performance.now();
60
- await shutdown.close();
61
- expect(performance.now() - started).toBeGreaterThanOrEqual(90);
62
- await exitCode;
63
- expect(counts(site)).toEqual({ graceful: before.graceful, forced: before.forced + 1 });
60
+ const terminate = spyOn(worker, "terminate");
61
+ try {
62
+ const closed = shutdown.close();
63
+ jest.advanceTimersByTime(99);
64
+ expect(terminate).not.toHaveBeenCalled();
65
+ expect(counts(site)).toEqual(before);
66
+ jest.advanceTimersByTime(1);
67
+ expect(terminate).toHaveBeenCalledTimes(1);
68
+ await closed;
69
+ await exitCode;
70
+ expect(counts(site)).toEqual({ graceful: before.graceful, forced: before.forced + 1 });
71
+ } finally {
72
+ // A bad fallback might not have sent terminate at all.
73
+ if (terminate.mock.calls.length === 0) void worker.terminate();
74
+ await exitCode;
75
+ terminate.mockRestore();
76
+ }
64
77
  });
65
78
 
66
79
  test("closing twice shares one shutdown, and closing an exited worker is a no-op", async () => {
@@ -102,26 +115,19 @@ function recordingPort() {
102
115
  return { port: port as unknown as WorkerClosePort, events, closedWith };
103
116
  }
104
117
 
105
- test("closePort removes the close listener before the port closes", async () => {
118
+ test("closePort removes the close listener before the port closes", () => {
106
119
  const { port, events, closedWith } = recordingPort();
107
120
  const { closePort } = exitOnWorkerClose(port, () => {});
108
121
  expect(events.listenerCount("message")).toBe(1);
109
122
  closePort();
110
123
  // Closing again does not close the port twice.
111
124
  closePort();
112
- await new Promise((resolve) => setTimeout(resolve, 10));
125
+ jest.runOnlyPendingTimers();
113
126
  // Bun 1.3.14 never ends a worker whose port closes with a listener attached.
114
127
  expect(closedWith).toEqual([0]);
115
128
  });
116
129
 
117
130
  test("a worker that closes its own port through closePort exits by itself", async () => {
118
- const { worker, exitCode } = await start("finish");
119
- const outcome = await Promise.race([
120
- exitCode,
121
- new Promise<string>((resolve) => setTimeout(() => resolve("no exit"), 5_000)),
122
- ]);
123
- // Terminate only a worker that is still running: on Bun 1.3.14,
124
- // terminate() on a worker that has already exited never settles.
125
- if (outcome === "no exit") await worker.terminate();
126
- expect(outcome).toBe(0);
131
+ const { exitCode } = await start("finish");
132
+ expect(await exitCode).toBe(0);
127
133
  });