@cortexkit/opencode-magic-context 0.49.84 → 0.49.86

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 (107) 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-xesm7rj3.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/memory/verification-paths.d.ts.map +1 -1
  15. package/dist/features/magic-context/project-embedding-registry.d.ts +6 -1
  16. package/dist/features/magic-context/project-embedding-registry.d.ts.map +1 -1
  17. package/dist/features/magic-context/storage-db.d.ts.map +1 -1
  18. package/dist/hooks/magic-context/lkg-recovery-fence.d.ts.map +1 -1
  19. package/dist/{index-xjfan0za.js → index-022w6314.js} +37 -37
  20. package/dist/{index-tvbkemec.js → index-08jfpny9.js} +1 -1
  21. package/dist/{index-fgy6hnr3.js → index-1bqkqde0.js} +5 -4
  22. package/dist/{index-0wehkw71.js → index-1pf5qrx4.js} +4 -4
  23. package/dist/{index-tqnvn9pa.js → index-25nktq8n.js} +3 -3
  24. package/dist/{index-98qy103c.js → index-2kf73btc.js} +1 -1
  25. package/dist/{index-vpw46557.js → index-3dtzyred.js} +1 -1
  26. package/dist/{index-bd34njzg.js → index-4ntnt8ee.js} +1 -1
  27. package/dist/{index-w2wpx7t5.js → index-4w5rx7de.js} +1 -1
  28. package/dist/{index-xd0ww0ns.js → index-798s7c8s.js} +1 -1
  29. package/dist/{index-fpqdbb67.js → index-7svecf3m.js} +3 -3
  30. package/dist/{v2/server-fvnzcnww.js → index-c5tmzym6.js} +192 -11
  31. package/dist/{index-k0jnsjcp.js → index-d0rtbv0f.js} +6 -6
  32. package/dist/{index-qybp04ff.js → index-e32b3x4n.js} +3 -3
  33. package/dist/{index-cfy5k1pa.js → index-gxdc95cp.js} +5 -5
  34. package/dist/{index-w8dcjt7f.js → index-k0tb2z28.js} +1 -1
  35. package/dist/{index-zb4h9nrk.js → index-k50xhjw1.js} +202 -14
  36. package/dist/{index-szwrpyac.js → index-nny4gm06.js} +1 -1
  37. package/dist/{index-shpyv8gq.js → index-s8ks5nz4.js} +16 -9
  38. package/dist/{index-d028gmgp.js → index-ttk3trse.js} +14 -14
  39. package/dist/{index-skwwbcnv.js → index-w6v4dw5f.js} +24 -24
  40. package/dist/{index-5wjv4c41.js → index-xccywqdj.js} +15 -15
  41. package/dist/{index-kthfyf45.js → index-zmqx48vt.js} +3 -3
  42. package/dist/index.js +33 -33
  43. package/dist/migration-worker.js +4 -3
  44. package/dist/{project-embedding-registry-y3z36mjy.js → project-embedding-registry-q80scexh.js} +6 -4
  45. package/dist/raw-ordinal-warmup-worker.js +2 -2
  46. package/dist/{recomp-orchestrator-m2s3jpvj.js → recomp-orchestrator-7ecg8ryx.js} +16 -15
  47. package/dist/{render-p2j7rn9a.js → render-yqp7q79f.js} +8 -7
  48. package/dist/{search-archive-hz9xh7nh.js → search-archive-r4h96j2z.js} +2 -2
  49. package/dist/{search-ksx0f1qd.js → search-bw22d7zc.js} +12 -10
  50. package/dist/shared/storage-file-mutex.d.ts.map +1 -1
  51. package/dist/shared/storage-permissions.d.ts +5 -3
  52. package/dist/shared/storage-permissions.d.ts.map +1 -1
  53. package/dist/{store-x0swqb5c.js → store-n4yz3n66.js} +2 -2
  54. package/dist/{store-reader-tsv1w4vt.js → store-reader-nf8z86n9.js} +1 -1
  55. package/dist/{transform-postprocess-phase-1wb2rrr1.js → transform-postprocess-phase-t99yj9vt.js} +17 -16
  56. package/dist/v2/auto-search-worker.js +3 -3
  57. package/dist/v2/chunk-embedding-write-worker.js +5 -4
  58. package/dist/v2/{context-at9nje0j.js → context-k8sx1nyy.js} +39 -39
  59. package/dist/v2/{derive-budgets-xbwcap8k.js → derive-budgets-ecjy1aqh.js} +4 -2
  60. package/dist/v2/{embedding-backfill-hjvjxp7d.js → embedding-backfill-k8kqnwfq.js} +7 -5
  61. package/dist/v2/embedding-worker.js +15 -27
  62. package/dist/v2/migration-worker.js +4 -3
  63. package/dist/v2/{project-embedding-registry-mzsvyads.js → project-embedding-registry-2jp1antr.js} +6 -4
  64. package/dist/v2/raw-ordinal-warmup-worker.js +2 -2
  65. package/dist/v2/{recomp-orchestrator-nhef90gc.js → recomp-orchestrator-ssde9ft1.js} +17 -16
  66. package/dist/v2/{render-c9r2g2jv.js → render-fezgh7pa.js} +8 -7
  67. package/dist/v2/{search-archive-80ckv9kq.js → search-archive-zz1kza50.js} +2 -2
  68. package/dist/v2/{search-t06js5dc.js → search-m251amra.js} +11 -9
  69. package/dist/v2/{server-4z964n1c.js → server-3p6b0qya.js} +1 -1
  70. package/dist/v2/{server-3cndh146.js → server-4wwwm2ya.js} +24 -24
  71. package/dist/v2/{server-mr9rqn0y.js → server-97w51d8n.js} +4 -4
  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-3hhakg5a.js → server-fsw8kbng.js} +13 -13
  77. package/dist/v2/{server-68q80y27.js → server-hn8b7sfe.js} +16 -9
  78. package/dist/v2/{server-pejjj0nv.js → server-mbkwcwgw.js} +1 -1
  79. package/dist/v2/{server-ry6rpspz.js → server-n5zr7190.js} +15 -15
  80. package/dist/v2/{server-210rc0z9.js → server-ps6rz88g.js} +1 -1
  81. package/dist/{index-fvnzcnww.js → v2/server-r2es6zt7.js} +192 -11
  82. package/dist/v2/{server-bt546axy.js → server-rz4snd3x.js} +3 -3
  83. package/dist/v2/{server-863bwkga.js → server-ssg29wjg.js} +6 -6
  84. package/dist/v2/{server-hhw6rzsn.js → server-w7mpvkpj.js} +1 -1
  85. package/dist/v2/{server-sy98vksf.js → server-xa8fefhw.js} +3 -3
  86. package/dist/v2/{server-gx1s06dx.js → server-y31y6gws.js} +5 -4
  87. package/dist/v2/{server-cce6m31c.js → server-ytqps2xa.js} +1 -1
  88. package/dist/v2/server.js +6 -4
  89. package/dist/v2/{store-reader-paamf0ac.js → store-reader-2vhx33n6.js} +1 -1
  90. package/dist/v2/{store-h3s95ywe.js → store-y56y034s.js} +2 -2
  91. package/dist/v2/{v2-archive-reader-1zzteaa5.js → v2-archive-reader-e2w39c3p.js} +1 -1
  92. package/dist/v2/{wrapup-orchestrator-9y98qcqz.js → wrapup-orchestrator-eg5b1p89.js} +16 -15
  93. package/dist/{v2-archive-reader-3yjxaj5z.js → v2-archive-reader-8dsngf2j.js} +1 -1
  94. package/dist/{wrapup-orchestrator-sa3a075a.js → wrapup-orchestrator-nmk6yf7f.js} +17 -16
  95. package/package.json +1 -1
  96. package/src/shared/storage-file-mutex-review.test.ts +125 -2
  97. package/src/shared/storage-file-mutex.ts +17 -8
  98. package/src/shared/storage-permissions-creators.test.ts +194 -0
  99. package/src/shared/storage-permissions-startup.test.ts +476 -0
  100. package/src/shared/storage-permissions.ts +227 -12
  101. package/src/tui/compaction-off.ts +2 -2
  102. package/src/tui/slots/sidebar-content-render.test.ts +309 -0
  103. package/src/tui/slots/sidebar-content.tsx +134 -99
  104. package/src/tui-compiled/compaction-off.ts +2 -2
  105. package/src/tui-compiled/slots/sidebar-content.tsx +321 -247
  106. /package/dist/{index-rdh63md0.js → index-1y4y98r1.js} +0 -0
  107. /package/dist/v2/{server-9nk5h6w6.js → server-qyazxy92.js} +0 -0
@@ -17,11 +17,11 @@ import {
17
17
  } from "./server-x6fn9x8q.js";
18
18
  import {
19
19
  LocalEmbeddingProvider
20
- } from "./server-d706s5xn.js";
20
+ } from "./server-b93f0bqh.js";
21
21
  import {
22
22
  OpenAICompatibleEmbeddingProvider,
23
23
  embedTextForProject2
24
- } from "./server-68q80y27.js";
24
+ } from "./server-hn8b7sfe.js";
25
25
  import {
26
26
  saveEmbeddingIfHashMatches
27
27
  } from "./server-4dhv7mqz.js";
@@ -777,6 +777,7 @@ async function readGitFileChangeTimesSince(cwd, sinceMs, knownGitRoot) {
777
777
  }
778
778
  return times;
779
779
  }
780
+ var TRACKED_FILES_ARGS = ["ls-files", "--recurse-submodules", "-z", "--full-name"];
780
781
  async function gitTrackedPath(gitRoot, repoRelativePath) {
781
782
  const stdout = await runGit(gitRoot, [
782
783
  "ls-files",
@@ -786,7 +787,7 @@ async function gitTrackedPath(gitRoot, repoRelativePath) {
786
787
  "--",
787
788
  repoRelativePath
788
789
  ]);
789
- const fallbackStdout = stdout === null ? await runGit(gitRoot, ["ls-files", "-z", "--full-name"]) : null;
790
+ const fallbackStdout = stdout === null ? await runGit(gitRoot, TRACKED_FILES_ARGS) : null;
790
791
  if (stdout === null && fallbackStdout === null)
791
792
  return null;
792
793
  const matches = (stdout ?? fallbackStdout ?? "").split("\x00").filter(Boolean);
@@ -853,7 +854,7 @@ async function normalizeVerificationFiles(args) {
853
854
  if (!trackedPaths) {
854
855
  let trackedOutput = null;
855
856
  try {
856
- trackedOutput = await runGit(gitRoot, ["ls-files", "-z", "--full-name"]);
857
+ trackedOutput = await runGit(gitRoot, TRACKED_FILES_ARGS);
857
858
  } catch {}
858
859
  trackedPaths = new Set(trackedOutput?.split("\x00").filter(Boolean) ?? []);
859
860
  }
@@ -3,7 +3,7 @@ import {
3
3
  } from "./server-39bcszk4.js";
4
4
  import {
5
5
  RAW_MESSAGE_TYPES2
6
- } from "./server-9nk5h6w6.js";
6
+ } from "./server-qyazxy92.js";
7
7
  import {
8
8
  markHostUnservedRow
9
9
  } from "./server-s9x93tfs.js";
package/dist/v2/server.js CHANGED
@@ -1,6 +1,6 @@
1
1
  import {
2
2
  loadPluginConfigDetailed
3
- } from "./server-y4favn4d.js";
3
+ } from "./server-e2k9mt86.js";
4
4
  import {
5
5
  setHarness2
6
6
  } from "./server-pavzsdc6.js";
@@ -13,7 +13,9 @@ import {
13
13
  flushLogger2
14
14
  } from "./server-j8376q08.js";
15
15
  import"./server-z4p0ry94.js";
16
- import"./server-sy98vksf.js";
16
+ import"./server-jdfe07mp.js";
17
+ import"./server-r2es6zt7.js";
18
+ import"./server-xa8fefhw.js";
17
19
  import {
18
20
  string,
19
21
  unknown,
@@ -7875,7 +7877,7 @@ var require_src2 = __commonJS(function(exports, module) {
7875
7877
  // package.json
7876
7878
  var package_default = {
7877
7879
  name: "@cortexkit/opencode-magic-context",
7878
- version: "0.49.84",
7880
+ version: "0.49.86",
7879
7881
  type: "module",
7880
7882
  description: "OpenCode plugin for Magic Context — cross-session memory and context management",
7881
7883
  main: "dist/index.js",
@@ -8196,7 +8198,7 @@ async function setup(context) {
8196
8198
  if (claimStorageBackupWarningCheck() && isMagicContextStorageOutsideEngram(storageDir)) {
8197
8199
  log2(`[magic-context] Magic Context storage is at ${storageDir}, outside the folder Engram backs up (~/.local/share/cortexkit/magic-context). It is not included in CortexKit backups.`);
8198
8200
  }
8199
- const { registerContext } = await import("./context-at9nje0j.js");
8201
+ const { registerContext } = await import("./context-k8sx1nyy.js");
8200
8202
  setHarness2("opencode2");
8201
8203
  bindStaleBuildNotice({}, import.meta.url, "opencode2");
8202
8204
  const duties = await registerContext(context);
@@ -3,7 +3,7 @@ import {
3
3
  RAW_MESSAGE_TYPES2,
4
4
  V2StoreReaderPool2,
5
5
  V2StoreReader2
6
- } from "./server-9nk5h6w6.js";
6
+ } from "./server-qyazxy92.js";
7
7
  import"./server-2ra6pwf3.js";
8
8
  import"./server-gzy5w8ya.js";
9
9
  export {
@@ -8,8 +8,8 @@ import {
8
8
  readV2RawMessagePagesForConversion2,
9
9
  createV2RawMessageReader2,
10
10
  createV2RawMessageProvider2
11
- } from "./server-cce6m31c.js";
12
- import"./server-9nk5h6w6.js";
11
+ } from "./server-ytqps2xa.js";
12
+ import"./server-qyazxy92.js";
13
13
  import"./server-39bcszk4.js";
14
14
  import"./server-2ra6pwf3.js";
15
15
  import"./server-gzy5w8ya.js";
@@ -1,7 +1,7 @@
1
1
  import {
2
2
  readV2ArchiveOffThread2,
3
3
  serveV2ArchiveReads2
4
- } from "./server-mr9rqn0y.js";
4
+ } from "./server-97w51d8n.js";
5
5
  import"./server-v0p37hm2.js";
6
6
  import"./server-gzy5w8ya.js";
7
7
  import"./server-1d042x6w.js";
@@ -12,7 +12,7 @@ import {
12
12
  getCompartments,
13
13
  getLastCompartmentEndMessage,
14
14
  requestPendingMaterialization
15
- } from "./server-3cndh146.js";
15
+ } from "./server-4wwwm2ya.js";
16
16
  import"./server-2amn2s73.js";
17
17
  import"./server-y8xjr8rx.js";
18
18
  import"./server-x6fn9x8q.js";
@@ -35,7 +35,7 @@ import {
35
35
  clearEmergencyRecovery
36
36
  } from "./server-s15knz0w.js";
37
37
  import"./server-a2f1bhyj.js";
38
- import"./server-ry6rpspz.js";
38
+ import"./server-n5zr7190.js";
39
39
  import"./server-1zx87sdm.js";
40
40
  import"./server-rz6g5xne.js";
41
41
  import"./server-2ra6pwf3.js";
@@ -44,12 +44,13 @@ import {
44
44
  prepareRawSessionOrdinals2
45
45
  } from "./server-2k8tkbhz.js";
46
46
  import"./server-fr0wbhdn.js";
47
- import"./server-210rc0z9.js";
48
- import"./server-bt546axy.js";
49
- import"./server-9nk5h6w6.js";
47
+ import"./server-ps6rz88g.js";
48
+ import"./server-r2es6zt7.js";
49
+ import"./server-rz4snd3x.js";
50
+ import"./server-qyazxy92.js";
50
51
  import"./server-fb3zxn06.js";
51
52
  import"./server-39bcszk4.js";
52
- import"./server-hhw6rzsn.js";
53
+ import"./server-w7mpvkpj.js";
53
54
  import {
54
55
  pushNotification2
55
56
  } from "./server-fzgyvsb1.js";
@@ -64,18 +65,18 @@ import {
64
65
  registerActiveCompartmentRun,
65
66
  setRecompStarting2,
66
67
  setRecompTerminal2
67
- } from "./server-3hhakg5a.js";
68
+ } from "./server-fsw8kbng.js";
68
69
  import"./server-qt1qqasc.js";
69
- import"./server-68q80y27.js";
70
- import"./server-4z964n1c.js";
70
+ import"./server-hn8b7sfe.js";
71
+ import"./server-3p6b0qya.js";
71
72
  import"./server-4dhv7mqz.js";
72
- import"./server-d706s5xn.js";
73
- import"./server-gx1s06dx.js";
74
- import"./server-pejjj0nv.js";
73
+ import"./server-b93f0bqh.js";
74
+ import"./server-y31y6gws.js";
75
+ import"./server-mbkwcwgw.js";
75
76
  import"./server-jjvbk92s.js";
76
- import"./server-y4favn4d.js";
77
- import"./server-sy98vksf.js";
78
- import"./server-w1jfaxas.js";
77
+ import"./server-e2k9mt86.js";
78
+ import"./server-xa8fefhw.js";
79
+ import"./server-cwtehwbb.js";
79
80
  import"./server-npdey91q.js";
80
81
  import {
81
82
  sendStatusNotification2
@@ -1,7 +1,7 @@
1
1
  import {
2
2
  readV2ArchiveOffThread2,
3
3
  serveV2ArchiveReads2
4
- } from "./index-0wehkw71.js";
4
+ } from "./index-1pf5qrx4.js";
5
5
  import"./index-v0p37hm2.js";
6
6
  import"./index-gzy5w8ya.js";
7
7
  import"./index-1d042x6w.js";
@@ -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-25nktq8n.js";
4
+ import"./index-e32b3x4n.js";
5
+ import"./index-ttk3trse.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-1bqkqde0.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.86",
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
+ });