@cortexkit/opencode-magic-context 0.49.84 → 0.49.85

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 (101) hide show
  1. package/dist/{announcement-p41dde4h.js → announcement-fnyxaahs.js} +3 -1
  2. package/dist/auto-search-worker.js +3 -3
  3. package/dist/chunk-embedding-write-worker.js +5 -4
  4. package/dist/{context-3sajdysh.js → context-bjfwzbts.js} +27 -26
  5. package/dist/{derive-budgets-0kcek5ex.js → derive-budgets-90869322.js} +3 -1
  6. package/dist/{embedding-backfill-k994xdas.js → embedding-backfill-v6sw58m8.js} +7 -5
  7. package/dist/embedding-worker.js +15 -27
  8. package/dist/features/magic-context/memory/embedding-worker-boundary.test-support.d.ts +24 -0
  9. package/dist/features/magic-context/memory/embedding-worker-boundary.test-support.d.ts.map +1 -0
  10. package/dist/features/magic-context/memory/embedding-worker-client.d.ts +35 -1
  11. package/dist/features/magic-context/memory/embedding-worker-client.d.ts.map +1 -1
  12. package/dist/features/magic-context/memory/embedding-worker-loop.d.ts +57 -0
  13. package/dist/features/magic-context/memory/embedding-worker-loop.d.ts.map +1 -0
  14. package/dist/features/magic-context/project-embedding-registry.d.ts +6 -1
  15. package/dist/features/magic-context/project-embedding-registry.d.ts.map +1 -1
  16. package/dist/features/magic-context/storage-db.d.ts.map +1 -1
  17. package/dist/hooks/magic-context/lkg-recovery-fence.d.ts.map +1 -1
  18. package/dist/{index-tvbkemec.js → index-08jfpny9.js} +1 -1
  19. package/dist/{index-k0jnsjcp.js → index-0rge5rkh.js} +6 -6
  20. package/dist/{index-0wehkw71.js → index-1pf5qrx4.js} +4 -4
  21. package/dist/{index-98qy103c.js → index-2kf73btc.js} +1 -1
  22. package/dist/{index-vpw46557.js → index-3dtzyred.js} +1 -1
  23. package/dist/{index-bd34njzg.js → index-4ntnt8ee.js} +1 -1
  24. package/dist/{index-w2wpx7t5.js → index-4w5rx7de.js} +1 -1
  25. package/dist/{index-xd0ww0ns.js → index-798s7c8s.js} +1 -1
  26. package/dist/{index-fpqdbb67.js → index-7svecf3m.js} +3 -3
  27. package/dist/{index-tqnvn9pa.js → index-9fsxmjs6.js} +3 -3
  28. package/dist/{v2/server-fvnzcnww.js → index-c5tmzym6.js} +192 -11
  29. package/dist/{index-w8dcjt7f.js → index-k0tb2z28.js} +1 -1
  30. package/dist/{index-zb4h9nrk.js → index-k50xhjw1.js} +202 -14
  31. package/dist/{index-qybp04ff.js → index-kqnef2tg.js} +3 -3
  32. package/dist/{index-szwrpyac.js → index-nny4gm06.js} +1 -1
  33. package/dist/{index-fgy6hnr3.js → index-pw279hmt.js} +2 -2
  34. package/dist/{index-xjfan0za.js → index-qvn3q9f1.js} +37 -37
  35. package/dist/{index-shpyv8gq.js → index-s8ks5nz4.js} +16 -9
  36. package/dist/{index-cfy5k1pa.js → index-sbr58jaf.js} +5 -5
  37. package/dist/{index-d028gmgp.js → index-tzbcb8yt.js} +14 -14
  38. package/dist/{index-skwwbcnv.js → index-w6v4dw5f.js} +24 -24
  39. package/dist/{index-5wjv4c41.js → index-xccywqdj.js} +15 -15
  40. package/dist/{index-kthfyf45.js → index-zmqx48vt.js} +3 -3
  41. package/dist/index.js +33 -33
  42. package/dist/migration-worker.js +4 -3
  43. package/dist/{project-embedding-registry-y3z36mjy.js → project-embedding-registry-q80scexh.js} +6 -4
  44. package/dist/raw-ordinal-warmup-worker.js +2 -2
  45. package/dist/{recomp-orchestrator-m2s3jpvj.js → recomp-orchestrator-xzs0a455.js} +16 -15
  46. package/dist/{render-p2j7rn9a.js → render-yqp7q79f.js} +8 -7
  47. package/dist/{search-archive-hz9xh7nh.js → search-archive-r4h96j2z.js} +2 -2
  48. package/dist/{search-ksx0f1qd.js → search-ztgy3ya6.js} +12 -10
  49. package/dist/shared/storage-file-mutex.d.ts.map +1 -1
  50. package/dist/shared/storage-permissions.d.ts +5 -3
  51. package/dist/shared/storage-permissions.d.ts.map +1 -1
  52. package/dist/{store-x0swqb5c.js → store-n4yz3n66.js} +2 -2
  53. package/dist/{store-reader-tsv1w4vt.js → store-reader-nf8z86n9.js} +1 -1
  54. package/dist/{transform-postprocess-phase-1wb2rrr1.js → transform-postprocess-phase-39a5hm2a.js} +17 -16
  55. package/dist/v2/auto-search-worker.js +3 -3
  56. package/dist/v2/chunk-embedding-write-worker.js +5 -4
  57. package/dist/v2/{context-at9nje0j.js → context-k2rrqzf4.js} +39 -39
  58. package/dist/v2/{derive-budgets-xbwcap8k.js → derive-budgets-ecjy1aqh.js} +4 -2
  59. package/dist/v2/{embedding-backfill-hjvjxp7d.js → embedding-backfill-k8kqnwfq.js} +7 -5
  60. package/dist/v2/embedding-worker.js +15 -27
  61. package/dist/v2/migration-worker.js +4 -3
  62. package/dist/v2/{project-embedding-registry-mzsvyads.js → project-embedding-registry-2jp1antr.js} +6 -4
  63. package/dist/v2/raw-ordinal-warmup-worker.js +2 -2
  64. package/dist/v2/{recomp-orchestrator-nhef90gc.js → recomp-orchestrator-jnbxbsc8.js} +17 -16
  65. package/dist/v2/{render-c9r2g2jv.js → render-fezgh7pa.js} +8 -7
  66. package/dist/v2/{search-archive-80ckv9kq.js → search-archive-zz1kza50.js} +2 -2
  67. package/dist/v2/{search-t06js5dc.js → search-h5w7510x.js} +11 -9
  68. package/dist/v2/{server-4z964n1c.js → server-3p6b0qya.js} +1 -1
  69. package/dist/v2/{server-3cndh146.js → server-4wwwm2ya.js} +24 -24
  70. package/dist/v2/{server-mr9rqn0y.js → server-97w51d8n.js} +4 -4
  71. package/dist/v2/{server-gx1s06dx.js → server-98hsp35q.js} +2 -2
  72. package/dist/v2/{server-d706s5xn.js → server-b93f0bqh.js} +205 -17
  73. package/dist/v2/{server-dfesqfv1.js → server-brgandk4.js} +1 -1
  74. package/dist/v2/{server-w1jfaxas.js → server-cwtehwbb.js} +1 -1
  75. package/dist/v2/{server-y4favn4d.js → server-e2k9mt86.js} +1 -1
  76. package/dist/v2/{server-68q80y27.js → server-hn8b7sfe.js} +16 -9
  77. package/dist/v2/{server-pejjj0nv.js → server-mbkwcwgw.js} +1 -1
  78. package/dist/v2/{server-ry6rpspz.js → server-n5zr7190.js} +15 -15
  79. package/dist/v2/{server-210rc0z9.js → server-ps6rz88g.js} +1 -1
  80. package/dist/{index-fvnzcnww.js → v2/server-r2es6zt7.js} +192 -11
  81. package/dist/v2/{server-bt546axy.js → server-rz4snd3x.js} +3 -3
  82. package/dist/v2/{server-3hhakg5a.js → server-s76ty4ws.js} +13 -13
  83. package/dist/v2/{server-hhw6rzsn.js → server-w7mpvkpj.js} +1 -1
  84. package/dist/v2/{server-863bwkga.js → server-x77hd658.js} +6 -6
  85. package/dist/v2/{server-sy98vksf.js → server-xa8fefhw.js} +3 -3
  86. package/dist/v2/{server-cce6m31c.js → server-ytqps2xa.js} +1 -1
  87. package/dist/v2/server.js +6 -4
  88. package/dist/v2/{store-reader-paamf0ac.js → store-reader-2vhx33n6.js} +1 -1
  89. package/dist/v2/{store-h3s95ywe.js → store-y56y034s.js} +2 -2
  90. package/dist/v2/{v2-archive-reader-1zzteaa5.js → v2-archive-reader-e2w39c3p.js} +1 -1
  91. package/dist/v2/{wrapup-orchestrator-9y98qcqz.js → wrapup-orchestrator-mmje3etf.js} +16 -15
  92. package/dist/{v2-archive-reader-3yjxaj5z.js → v2-archive-reader-8dsngf2j.js} +1 -1
  93. package/dist/{wrapup-orchestrator-sa3a075a.js → wrapup-orchestrator-sm6pwf3p.js} +17 -16
  94. package/package.json +1 -1
  95. package/src/shared/storage-file-mutex-review.test.ts +125 -2
  96. package/src/shared/storage-file-mutex.ts +17 -8
  97. package/src/shared/storage-permissions-creators.test.ts +194 -0
  98. package/src/shared/storage-permissions-startup.test.ts +476 -0
  99. package/src/shared/storage-permissions.ts +227 -12
  100. /package/dist/{index-rdh63md0.js → index-1y4y98r1.js} +0 -0
  101. /package/dist/v2/{server-9nk5h6w6.js → server-qyazxy92.js} +0 -0
@@ -1,21 +1,21 @@
1
1
  import {
2
2
  runManagedWrapup2
3
- } from "./index-tqnvn9pa.js";
4
- import"./index-qybp04ff.js";
5
- import"./index-d028gmgp.js";
3
+ } from "./index-9fsxmjs6.js";
4
+ import"./index-kqnef2tg.js";
5
+ import"./index-tzbcb8yt.js";
6
6
  import"./index-832w615x.js";
7
7
  import"./index-sd3egckz.js";
8
- import"./index-fgy6hnr3.js";
9
- import"./index-w8dcjt7f.js";
8
+ import"./index-pw279hmt.js";
9
+ import"./index-k0tb2z28.js";
10
10
  import"./index-jjvbk92s.js";
11
- import"./index-shpyv8gq.js";
11
+ import"./index-s8ks5nz4.js";
12
12
  import"./index-4dhv7mqz.js";
13
- import"./index-skwwbcnv.js";
14
- import"./index-bd34njzg.js";
13
+ import"./index-w6v4dw5f.js";
14
+ import"./index-4ntnt8ee.js";
15
15
  import"./index-05bm2ndp.js";
16
16
  import"./index-2amn2s73.js";
17
- import"./index-rdh63md0.js";
18
- import"./index-kthfyf45.js";
17
+ import"./index-1y4y98r1.js";
18
+ import"./index-zmqx48vt.js";
19
19
  import"./index-g6hfh4h4.js";
20
20
  import"./index-qt1qqasc.js";
21
21
  import"./index-7j2zv9nm.js";
@@ -24,25 +24,26 @@ import"./index-1zx87sdm.js";
24
24
  import"./index-x40zr813.js";
25
25
  import"./index-fzgyvsb1.js";
26
26
  import"./index-e6ncz7a6.js";
27
- import"./index-zb4h9nrk.js";
27
+ import"./index-k50xhjw1.js";
28
28
  import"./index-6nqz8hsz.js";
29
- import"./index-vpw46557.js";
29
+ import"./index-3dtzyred.js";
30
30
  import"./index-snbpdpa3.js";
31
31
  import"./index-pxnzyvjc.js";
32
- import"./index-5wjv4c41.js";
32
+ import"./index-xccywqdj.js";
33
33
  import"./index-fb3zxn06.js";
34
- import"./index-w2wpx7t5.js";
34
+ import"./index-4w5rx7de.js";
35
35
  import"./index-fr0wbhdn.js";
36
- import"./index-fpqdbb67.js";
36
+ import"./index-7svecf3m.js";
37
37
  import"./index-s32f8y67.js";
38
38
  import"./index-wh9fxds5.js";
39
- import"./index-gqf8r04r.js";
40
39
  import"./index-jrj95cce.js";
41
40
  import"./index-q7q6qp1f.js";
42
41
  import"./index-96ztjvkn.js";
43
42
  import"./index-v0p37hm2.js";
44
43
  import"./index-58e3y90n.js";
45
44
  import"./index-m0pwswv9.js";
45
+ import"./index-c5tmzym6.js";
46
+ import"./index-gqf8r04r.js";
46
47
  import"./index-5vsk2cpp.js";
47
48
  import"./index-gzy5w8ya.js";
48
49
  import"./index-ywrz4wy2.js";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cortexkit/opencode-magic-context",
3
- "version": "0.49.84",
3
+ "version": "0.49.85",
4
4
  "type": "module",
5
5
  "description": "OpenCode plugin for Magic Context — cross-session memory and context management",
6
6
  "main": "dist/index.js",
@@ -1,5 +1,6 @@
1
1
  import { expect, spyOn, test } from "bun:test";
2
- import { readdirSync, readFileSync, rmdirSync, writeFileSync } from "node:fs";
2
+ import * as fs from "node:fs";
3
+ import { existsSync, readdirSync, readFileSync, rmdirSync, rmSync, writeFileSync } from "node:fs";
3
4
  import { join } from "node:path";
4
5
  import { __resetRpcIdentityTestHooks, __setRpcIdentityTestHooks } from "./rpc-utils";
5
6
  import { withStorageFileMutex } from "./storage-file-mutex";
@@ -9,6 +10,46 @@ import { createTestTempDir } from "./test-temp-dir";
9
10
 
10
11
  const mutex = join(import.meta.dir, "storage-file-mutex.ts");
11
12
 
13
+ test("mutex removes its empty directory after sequential operations and thrown work", () => {
14
+ const { dir: root, cleanup } = createTestTempDir("mc-mutex-sequence-");
15
+ const directory = join(root, "locks");
16
+ try {
17
+ for (let i = 0; i < 2; i++) {
18
+ expect(withStorageFileMutex(directory, () => i)).toBe(i);
19
+ expect(existsSync(directory)).toBe(false);
20
+ }
21
+ expect(() =>
22
+ withStorageFileMutex(directory, () => {
23
+ throw new Error("work failed");
24
+ }),
25
+ ).toThrow("work failed");
26
+ expect(existsSync(directory)).toBe(false);
27
+ } finally {
28
+ cleanup();
29
+ }
30
+ });
31
+
32
+ test("mutex directory cleanup preserves a ticket published during locked work", () => {
33
+ const { dir: root, cleanup } = createTestTempDir("mc-mutex-ticket-");
34
+ const directory = join(root, "locks");
35
+ const contender = join(directory, `${process.pid}-00000000-0000-0000-0000-000000000000.lock`);
36
+ try {
37
+ expect(
38
+ withStorageFileMutex(directory, () => {
39
+ writeFileSync(contender, "choosing", { mode: 0o600 });
40
+ return "done";
41
+ }),
42
+ ).toBe("done");
43
+ expect(readFileSync(contender, "utf8")).toBe("choosing");
44
+ expect(readdirSync(directory)).toHaveLength(1);
45
+ rmSync(contender);
46
+ withStorageFileMutex(directory, () => undefined);
47
+ expect(existsSync(directory)).toBe(false);
48
+ } finally {
49
+ cleanup();
50
+ }
51
+ });
52
+
12
53
  test("mutex retries ticket creation when empty-directory cleanup wins the mkdir race", () => {
13
54
  const { dir: root, cleanup } = createTestTempDir("mc-mutex-rmdir-");
14
55
  const directory = join(root, "locks");
@@ -28,6 +69,88 @@ test("mutex retries ticket creation when empty-directory cleanup wins the mkdir
28
69
  }
29
70
  });
30
71
 
72
+ test("mutex retries mkdir after EEXIST during lock directory cleanup", () => {
73
+ const { dir: root, cleanup } = createTestTempDir("mc-mutex-mkdir-race-");
74
+ const directory = join(root, "locks");
75
+ const mkdir = fs.mkdirSync;
76
+ let attempts = 0;
77
+ const mkdirSpy = spyOn(fs, "mkdirSync").mockImplementation((...args) => {
78
+ if (args[0] === directory && attempts++ === 0) {
79
+ throw Object.assign(new Error("lock mkdir raced with cleanup"), { code: "EEXIST" });
80
+ }
81
+ return mkdir(...args);
82
+ });
83
+ try {
84
+ expect(withStorageFileMutex(directory, () => "acquired")).toBe("acquired");
85
+ expect(attempts).toBeGreaterThan(1);
86
+ } finally {
87
+ mkdirSpy.mockRestore();
88
+ cleanup();
89
+ }
90
+ });
91
+
92
+ test("mutex retries ticket creation after EINVAL during lock directory cleanup", () => {
93
+ const { dir: root, cleanup } = createTestTempDir("mc-mutex-open-race-");
94
+ const directory = join(root, "locks");
95
+ const write = permissions.writeStorageFileSync;
96
+ let attempts = 0;
97
+ const writer = spyOn(permissions, "writeStorageFileSync").mockImplementation((...args) => {
98
+ if (attempts++ === 0) {
99
+ rmdirSync(directory);
100
+ throw Object.assign(new Error("ticket open raced with cleanup"), { code: "EINVAL" });
101
+ }
102
+ return write(...args);
103
+ });
104
+ try {
105
+ expect(withStorageFileMutex(directory, () => "acquired")).toBe("acquired");
106
+ expect(attempts).toBe(3);
107
+ } finally {
108
+ writer.mockRestore();
109
+ cleanup();
110
+ }
111
+ });
112
+
113
+ test("mutex keeps retrying ticket creation while cleanups remove the directory", () => {
114
+ const { dir: root, cleanup } = createTestTempDir("mc-mutex-rmdir-repeat-");
115
+ const directory = join(root, "locks");
116
+ const write = permissions.writeStorageFileSync;
117
+ let attempts = 0;
118
+ const writer = spyOn(permissions, "writeStorageFileSync").mockImplementation((...args) => {
119
+ // Three releases in sequence each remove the empty directory.
120
+ if (attempts++ < 3) rmdirSync(directory);
121
+ return write(...args);
122
+ });
123
+ try {
124
+ expect(withStorageFileMutex(directory, () => "acquired")).toBe("acquired");
125
+ expect(attempts).toBe(5);
126
+ } finally {
127
+ writer.mockRestore();
128
+ cleanup();
129
+ }
130
+ });
131
+
132
+ test("mutex retries when retirement removes the lock directory before validation", () => {
133
+ const { dir: root, cleanup } = createTestTempDir("mc-mutex-validate-race-");
134
+ const directory = join(root, "locks");
135
+ const lstatSync = fs.lstatSync;
136
+ let removals = 0;
137
+ const lstat = spyOn(fs, "lstatSync").mockImplementation((...args) => {
138
+ if (args[0] === directory && removals < 2) {
139
+ rmdirSync(directory);
140
+ removals++;
141
+ }
142
+ return lstatSync(...args);
143
+ });
144
+ try {
145
+ expect(withStorageFileMutex(directory, () => "acquired")).toBe("acquired");
146
+ expect(removals).toBe(2);
147
+ expect(existsSync(directory)).toBe(false);
148
+ } finally {
149
+ lstat.mockRestore();
150
+ cleanup();
151
+ }
152
+ });
153
+
31
154
  async function holder(root: string) {
32
155
  const script = `
33
156
  import { existsSync } from 'node:fs';
@@ -99,7 +222,7 @@ test.skipIf(process.platform === "win32")(
99
222
  200,
100
223
  );
101
224
  expect(reached).toBe(true);
102
- expect(readdirSync(join(root, "locks"))).toEqual([]);
225
+ expect(existsSync(join(root, "locks"))).toBe(false);
103
226
  } finally {
104
227
  if (child.exitCode === null) {
105
228
  child.kill("SIGKILL");
@@ -1,6 +1,6 @@
1
1
  import { execFileSync } from "node:child_process";
2
2
  import { createHash, randomUUID } from "node:crypto";
3
- import { readdirSync, readFileSync, rmSync } from "node:fs";
3
+ import { readdirSync, readFileSync, rmdirSync, rmSync } from "node:fs";
4
4
  import { join } from "node:path";
5
5
  import { isPidAlive, readProcessStartTime } from "./rpc-utils";
6
6
  import {
@@ -61,25 +61,29 @@ const pause = new Int32Array(new SharedArrayBuffer(4));
61
61
  * Unique names mean reclaiming a dead ticket cannot unlink a successor's lock.
62
62
  */
63
63
  export function withStorageFileMutex<T>(directory: string, work: () => T, timeoutMs = 1000): T {
64
- ensurePrivateStorageDirectorySync(directory);
64
+ const deadline = performance.now() + timeoutMs;
65
65
  const name = `${process.pid}-${randomUUID()}.lock`;
66
66
  const ownPath = join(directory, name);
67
67
  const birth = processBirth(process.pid);
68
68
  const ticket: Ticket = { choosing: true, number: 0, birth, checksum: "" };
69
69
  const encodedTicket = () =>
70
70
  JSON.stringify({ ...ticket, checksum: ticketChecksum(name, ticket) });
71
- for (let attempt = 0; ; attempt++) {
71
+ for (;;) {
72
72
  try {
73
+ ensurePrivateStorageDirectorySync(directory);
73
74
  writeStorageFileSync(ownPath, encodedTicket(), { flag: "wx", forcePrivate: true });
74
75
  break;
75
76
  } catch (error) {
76
- // A session cleanup can remove an empty directory between mkdir and
77
- // ticket creation. No ticket exists yet, so retry before contending.
78
- if ((error as NodeJS.ErrnoException).code !== "ENOENT" || attempt >= 2) throw error;
79
- ensurePrivateStorageDirectorySync(directory);
77
+ // A peer can remove the empty directory before this process writes its ticket.
78
+ // On macOS, this race can also give EEXIST from mkdir or EINVAL from open.
79
+ const code = (error as NodeJS.ErrnoException).code;
80
+ if (
81
+ (code !== "ENOENT" && code !== "EEXIST" && code !== "EINVAL") ||
82
+ performance.now() >= deadline
83
+ )
84
+ throw error;
80
85
  }
81
86
  }
82
- const deadline = performance.now() + timeoutMs;
83
87
  const peers = (): [string, Ticket | null][] => {
84
88
  const found: [string, Ticket | null][] = [];
85
89
  for (const other of readdirSync(directory)) {
@@ -136,5 +140,10 @@ export function withStorageFileMutex<T>(directory: string, work: () => T, timeou
136
140
  return result;
137
141
  } finally {
138
142
  rmSync(ownPath, { force: true });
143
+ try {
144
+ rmdirSync(directory);
145
+ } catch {
146
+ // Do not remove a live contender's ticket.
147
+ }
139
148
  }
140
149
  }
@@ -0,0 +1,194 @@
1
+ import { afterEach, describe, expect, it } from "bun:test";
2
+ import { spawnSync } from "node:child_process";
3
+ import { lstatSync, readdirSync } from "node:fs";
4
+ import { join } from "node:path";
5
+ import { cleanupTestTempDir, createTestTempDir } from "./test-temp-dir";
6
+
7
+ const roots: string[] = [];
8
+
9
+ afterEach(() => {
10
+ for (const root of roots.splice(0)) cleanupTestTempDir(root);
11
+ });
12
+
13
+ function child(root: string, script: string) {
14
+ return spawnSync(process.execPath, ["--eval", script], {
15
+ cwd: import.meta.dir,
16
+ encoding: "utf8",
17
+ timeout: 120_000,
18
+ windowsHide: true,
19
+ env: {
20
+ ...process.env,
21
+ NODE_ENV: "test",
22
+ XDG_DATA_HOME: root,
23
+ XDG_CONFIG_HOME: root,
24
+ MAGIC_CONTEXT_TEST_DATA_DIR: root,
25
+ MAGIC_CONTEXT_STORAGE_DIR: root,
26
+ },
27
+ });
28
+ }
29
+
30
+ describe.skipIf(process.platform === "win32")("storage creation under umask 0", () => {
31
+ it("creates helper outputs and public storage records privately before any startup walk", () => {
32
+ const { dir: root } = createTestTempDir("mc-storage-creators-");
33
+ roots.push(root);
34
+ const result = child(
35
+ root,
36
+ `
37
+ import { closeSync, lstatSync, readdirSync } from 'node:fs';
38
+ import { once } from 'node:events';
39
+ import { join } from 'node:path';
40
+ import * as p from './storage-permissions.ts';
41
+ import { withStorageFileMutex } from './storage-file-mutex.ts';
42
+ import { markAnnouncementSeen } from './announcement.ts';
43
+ import { rememberGitIdentity } from '../features/magic-context/memory/project-identity-cache.ts';
44
+ import { refreshModelLimitsFromApi } from './models-dev-cache.ts';
45
+ import { appendWindowReport } from '../features/magic-context/window-report-ledger.ts';
46
+ import { markLkgRecoveryDirty } from '../hooks/magic-context/lkg-recovery-fence.ts';
47
+ import { MagicContextRpcServer } from './rpc-server.ts';
48
+ import { rpcPortDir } from './rpc-utils.ts';
49
+ import { emitStallReport } from './host-stall-profiler-common.ts';
50
+ const root = process.env.MAGIC_CONTEXT_STORAGE_DIR;
51
+ const check = (path) => {
52
+ const stat = lstatSync(path);
53
+ if (stat.isSymbolicLink()) return;
54
+ const expected = stat.isDirectory() ? 0o700 : 0o600;
55
+ if ((stat.mode & 0o777) !== expected) throw new Error(path + ' mode=' + (stat.mode & 0o777).toString(8));
56
+ if (stat.isDirectory()) for (const entry of readdirSync(path)) check(join(path, entry));
57
+ };
58
+ const previous = process.umask(0);
59
+ let rpc;
60
+ try {
61
+ p.ensureStorageDirectorySync(join(root, 'helpers', 'nested'));
62
+ p.ensurePrivateStorageDirectorySync(join(root, 'private'));
63
+ p.writeStorageFileSync(join(root, 'sync'), 'x');
64
+ p.writeStorageFileAtomicSync(join(root, 'atomic'), 'x');
65
+ p.writeStorageFileDurableAtomicSync(join(root, 'durable', 'record'), 'x');
66
+ p.copyStorageFileSync(join(root, 'sync'), join(root, 'copy'));
67
+ p.copyStorageTreeSync(join(root, 'durable'), join(root, 'copy-tree'));
68
+ closeSync(p.openStorageFileSync(join(root, 'open'), 'wx'));
69
+ await p.writeStorageFileAsync(join(root, 'async', 'file'), 'x');
70
+ const stream = p.createStorageWriteStream(join(root, 'stream'));
71
+ const finished = once(stream, 'close');
72
+ stream.end('x');
73
+ await finished;
74
+ const handle = await p.createStorageFileHandleAsync(join(root, 'handle'), 'wx');
75
+ await p.writeStorageFileHandleAsync(handle, 'x');
76
+ await handle.close();
77
+ withStorageFileMutex(join(root, 'mutex'), () => check(root));
78
+ markAnnouncementSeen('0.49.37');
79
+ rememberGitIdentity(join(root, 'project'), 'git:0123456789abcdef');
80
+ await refreshModelLimitsFromApi({ config: { providers: async () => ({ data: { providers: [
81
+ { id: 'test', models: { model: { limit: { context: 100000, output: 10000 } } } }
82
+ ] } }) } });
83
+ appendWindowReport({ access_path: 'api', geometry: 'unknown', observed_at_ms: 123 });
84
+ markLkgRecoveryDirty({ sessionId: 'private-creation', processLocalProof: false, slot: {
85
+ jsonPrefix: '[{"text":"old"}]', inputIdSeq: ['one'], inputContentDigests: ['digest'],
86
+ lastInputMessageId: 'one', modelKey: 'provider/model', providerKey: 'provider', capturedAt: 1,
87
+ } });
88
+ emitStallReport({ profilerDir: () => join(root, 'host-profiler'), wallNow: () => 1000,
89
+ now: () => 1000, pid: process.pid, bunVersion: process.versions.bun, log: () => {},
90
+ }, { startMs: 0, endMs: 1000, traces: [], windowed: [], windowFilter: 'all',
91
+ options: { thresholdMs: 500, sampleIntervalMs: 10 }, before: null,
92
+ after: { at: 'fixture', heap_size_bytes: null, jsc_memory: null, rss_bytes: null,
93
+ percent_available_memory_in_use: null }, backend: 'jsc' });
94
+ rpc = new MagicContextRpcServer(root, join(root, 'project'));
95
+ if (await rpc.start() <= 0) throw new Error('RPC server did not start');
96
+ if (!readdirSync(rpcPortDir(root, join(root, 'project'))).some(name => name.endsWith('.json')))
97
+ throw new Error('RPC discovery record was not published');
98
+ check(root);
99
+ console.log('PRIVATE_CREATORS_OK');
100
+ } finally {
101
+ rpc?.stop();
102
+ process.umask(previous);
103
+ }
104
+ `,
105
+ );
106
+ expect(result.status, result.stdout + result.stderr).toBe(0);
107
+ expect(result.stdout).toContain("PRIVATE_CREATORS_OK");
108
+ console.log(result.stdout.trim());
109
+ const storage = join(root, "cortexkit", "magic-context");
110
+ for (const name of ["project-identities", "lkg-recovery-fences"])
111
+ expect(lstatSync(join(storage, name)).mode & 0o777).toBe(0o700);
112
+ expect(lstatSync(join(root, "host-profiler")).mode & 0o777).toBe(0o700);
113
+ expect(readdirSync(storage)).toContain("window-reports.jsonl");
114
+ expect(readdirSync(storage)).toContain("model-context-limits-opencode.json");
115
+ });
116
+
117
+ it("keeps SQLite DB, WAL and SHM private and bounded on a later real open", () => {
118
+ const { dir: root } = createTestTempDir("mc-storage-sqlite-");
119
+ roots.push(root);
120
+ const result = child(
121
+ root,
122
+ `
123
+ import { expect, spyOn } from 'bun:test';
124
+ import * as fs from 'node:fs';
125
+ import { join } from 'node:path';
126
+ import { openDatabase, closeDatabase } from '../features/magic-context/storage-db.ts';
127
+ const root = process.env.MAGIC_CONTEXT_STORAGE_DIR;
128
+ const path = join(root, 'custom.sqlite');
129
+ const previous = process.umask(0);
130
+ try {
131
+ const db = openDatabase({ dbPath: path });
132
+ db.exec('CREATE TABLE permission_probe (id INTEGER); INSERT INTO permission_probe VALUES (1)');
133
+ for (const suffix of ['', '-wal', '-shm']) {
134
+ expect(fs.lstatSync(path + suffix).mode & 0o777).toBe(0o600);
135
+ }
136
+ closeDatabase();
137
+ fs.mkdirSync(join(root, 'lkg-recovery-fences'), { mode: 0o700 });
138
+ for (let i = 0; i < 2000; i++) fs.writeFileSync(join(root, 'lkg-recovery-fences', i + '.json'), '{}', { mode: 0o600 });
139
+ const lstat = spyOn(fs, 'lstatSync');
140
+ try {
141
+ expect(openDatabase({ dbPath: path })).not.toBeNull();
142
+ expect(lstat.mock.calls.length).toBeLessThanOrEqual(16);
143
+ console.log('SQLITE_PRIVATE_OK lstat=' + lstat.mock.calls.length);
144
+ } finally { lstat.mockRestore(); }
145
+ } finally {
146
+ closeDatabase();
147
+ process.umask(previous);
148
+ }
149
+ `,
150
+ );
151
+ expect(result.status, result.stdout + result.stderr).toBe(0);
152
+ expect(result.stdout).toContain("SQLITE_PRIVATE_OK");
153
+ console.log(result.stdout.trim());
154
+ });
155
+
156
+ it("retains the full check for third-party model downloads under umask 0", () => {
157
+ const { dir: root } = createTestTempDir("mc-storage-models-");
158
+ roots.push(root);
159
+ const result = child(
160
+ root,
161
+ `
162
+ import { expect, spyOn } from 'bun:test';
163
+ import * as fs from 'node:fs';
164
+ import { join } from 'node:path';
165
+ import { FileCache } from '../../node_modules/@huggingface/transformers/src/utils/cache/FileCache.js';
166
+ import { tightenStorageTreeSync, writeStorageFileSync } from './storage-permissions.ts';
167
+ const root = process.env.MAGIC_CONTEXT_STORAGE_DIR;
168
+ const cache = join(root, 'models');
169
+ const file = join(cache, 'org/model/onnx/weights.bin');
170
+ const previous = process.umask(0);
171
+ try {
172
+ await new FileCache(cache).put('org/model/onnx/weights.bin', new Response('fixture'));
173
+ expect(fs.lstatSync(cache).mode & 0o777).toBe(0o777);
174
+ expect(fs.lstatSync(file).mode & 0o777).toBe(0o666);
175
+ writeStorageFileSync(join(root, '.storage-permissions-v1'), '1\\n');
176
+ const lstat = spyOn(fs, 'lstatSync');
177
+ try {
178
+ expect(tightenStorageTreeSync(root)).toEqual({ tightened: 5, failures: 0 });
179
+ // The bounded check (11 calls) plus one full walk of this small tree,
180
+ // because the bounded check tightened entries.
181
+ expect(lstat.mock.calls.length).toBeLessThanOrEqual(18);
182
+ } finally { lstat.mockRestore(); }
183
+ expect(fs.lstatSync(cache).mode & 0o777).toBe(0o700);
184
+ expect(fs.lstatSync(file).mode & 0o777).toBe(0o600);
185
+ expect(fs.existsSync(join(root, '.storage-permissions-v1'))).toBe(false);
186
+ console.log('MODELS_CHECK_OK entries=5 before=0777/0666 after=0700/0600');
187
+ } finally { process.umask(previous); }
188
+ `,
189
+ );
190
+ expect(result.status, result.stdout + result.stderr).toBe(0);
191
+ expect(result.stdout).toContain("MODELS_CHECK_OK entries=5");
192
+ console.log(result.stdout.trim());
193
+ });
194
+ });