@cortexkit/opencode-magic-context 0.49.34 → 0.49.35

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 (220) hide show
  1. package/dist/auto-search-worker.js +11 -6
  2. package/dist/chunk-embedding-write-worker.js +16 -14
  3. package/dist/{compaction-marker-candidates-31h86ph0.js → compaction-marker-candidates-g0p67ced.js} +3 -2
  4. package/dist/compaction-marker-candidates-worker.js +1 -1
  5. package/dist/{compartment-chunk-embedding-5q5gj67r.js → compartment-chunk-embedding-y4136are.js} +8 -7
  6. package/dist/{conflict-warning-hook-xgskea1v.js → conflict-warning-hook-hhw8z5ak.js} +9 -8
  7. package/dist/{context-p3xrarzt.js → context-fk8e3h9p.js} +1400 -701
  8. package/dist/{derive-budgets-pqybnx09.js → derive-budgets-htj16n4x.js} +3 -2
  9. package/dist/embedding-backfill-q6n72sy0.js +27 -0
  10. package/dist/embedding-worker-process.js +2 -1
  11. package/dist/embedding-worker.js +5 -4
  12. package/dist/expand-attachments-h33jbgyz.js +21 -0
  13. package/dist/features/magic-context/auto-search-diagnostics.d.ts +21 -0
  14. package/dist/features/magic-context/auto-search-diagnostics.d.ts.map +1 -0
  15. package/dist/features/magic-context/compartment-chunk-embedding.d.ts +1 -1
  16. package/dist/features/magic-context/compartment-chunk-embedding.d.ts.map +1 -1
  17. package/dist/features/magic-context/search.d.ts +4 -0
  18. package/dist/features/magic-context/search.d.ts.map +1 -1
  19. package/dist/features/magic-context/store-generation-rebase-labels.d.ts +6 -0
  20. package/dist/features/magic-context/store-generation-rebase-labels.d.ts.map +1 -0
  21. package/dist/features/magic-context/store-generation-rebase.d.ts.map +1 -1
  22. package/dist/{history-owner-36wp3mkb.js → history-owner-0z620wgz.js} +3 -2
  23. package/dist/hooks/magic-context/apply-operations.d.ts +20 -3
  24. package/dist/hooks/magic-context/apply-operations.d.ts.map +1 -1
  25. package/dist/hooks/magic-context/auto-search-observation.d.ts +13 -0
  26. package/dist/hooks/magic-context/auto-search-observation.d.ts.map +1 -0
  27. package/dist/hooks/magic-context/auto-search-runner.d.ts.map +1 -1
  28. package/dist/hooks/magic-context/auto-search-worker-client.d.ts +5 -1
  29. package/dist/hooks/magic-context/auto-search-worker-client.d.ts.map +1 -1
  30. package/dist/hooks/magic-context/compartment-commit-hashes.d.ts +4 -0
  31. package/dist/hooks/magic-context/compartment-commit-hashes.d.ts.map +1 -0
  32. package/dist/hooks/magic-context/compartment-runner-validation.d.ts +1 -0
  33. package/dist/hooks/magic-context/compartment-runner-validation.d.ts.map +1 -1
  34. package/dist/hooks/magic-context/event-resolvers.d.ts.map +1 -1
  35. package/dist/hooks/magic-context/final-wire-completeness.d.ts +15 -0
  36. package/dist/hooks/magic-context/final-wire-completeness.d.ts.map +1 -0
  37. package/dist/hooks/magic-context/final-wire-token-estimate.d.ts.map +1 -1
  38. package/dist/hooks/magic-context/raw-ordinal-warmup.d.ts +1 -0
  39. package/dist/hooks/magic-context/raw-ordinal-warmup.d.ts.map +1 -1
  40. package/dist/hooks/magic-context/read-session-chunk.d.ts +11 -0
  41. package/dist/hooks/magic-context/read-session-chunk.d.ts.map +1 -1
  42. package/dist/hooks/magic-context/read-session-formatting.d.ts +2 -0
  43. package/dist/hooks/magic-context/read-session-formatting.d.ts.map +1 -1
  44. package/dist/hooks/magic-context/transform-postprocess-phase.d.ts.map +1 -1
  45. package/dist/hooks/magic-context/transform.d.ts.map +1 -1
  46. package/dist/{index-as2amvn3.js → index-0c7p8mq5.js} +6 -531
  47. package/dist/{index-51rdvtkz.js → index-1rhgxqs8.js} +2 -2
  48. package/dist/index-2amn2s73.js +123 -0
  49. package/dist/{index-c7phnbvk.js → index-2p37txes.js} +1 -1
  50. package/dist/index-2qbtqg1w.js +529 -0
  51. package/dist/{index-waktfbjy.js → index-2v6nvy3k.js} +4 -4
  52. package/dist/{index-ftr84kkv.js → index-3d3872c6.js} +7 -5
  53. package/dist/{index-0677w9sd.js → index-3j9t1v4n.js} +55 -21
  54. package/dist/{index-atekmqef.js → index-4bgk5ztz.js} +363 -5499
  55. package/dist/{index-b88dwwrh.js → index-4xyjr62e.js} +1 -1
  56. package/dist/index-66a50f3e.js +777 -0
  57. package/dist/{index-04z754rd.js → index-87ctnzz9.js} +33 -5
  58. package/dist/{index-xrnsygfq.js → index-9wnbnx8f.js} +1 -1
  59. package/dist/{index-97spytxq.js → index-b6xz3qbe.js} +246 -420
  60. package/dist/{index-7g9dr8gy.js → index-brg2w6qc.js} +113 -133
  61. package/dist/{index-spwjbkc7.js → index-dnqqqc5f.js} +1 -1
  62. package/dist/index-dy7w6wm4.js +194 -0
  63. package/dist/{index-m1x9ghk5.js → index-ezv6dz3y.js} +37 -7
  64. package/dist/index-f297z1n8.js +4557 -0
  65. package/dist/{index-qgh1qwjj.js → index-f9b3vtt1.js} +1 -1
  66. package/dist/{index-v15ne3a3.js → index-faxb7mck.js} +2 -2
  67. package/dist/{index-rrv26qjz.js → index-fw42ms3m.js} +1 -1
  68. package/dist/{index-t5pck3ss.js → index-fxbk7gk3.js} +1 -1
  69. package/dist/{index-wfybj1dw.js → index-g4t7850m.js} +2 -2
  70. package/dist/{index-fm36bjv4.js → index-gyaa159j.js} +18 -276
  71. package/dist/{index-4pnsgvfk.js → index-hacf2tyx.js} +1 -1
  72. package/dist/{index-s1n8dd2n.js → index-jkanybgq.js} +2 -2
  73. package/dist/{index-2743x98y.js → index-jn0ddrhp.js} +29 -138
  74. package/dist/{index-h7tgn49j.js → index-jrfre9ah.js} +5 -222
  75. package/dist/{index-kfyb3k6n.js → index-jz5bk7xd.js} +2 -2
  76. package/dist/{index-np3rgfw4.js → index-ksv0a31x.js} +3 -3
  77. package/dist/{index-7kkphb6c.js → index-nj360hcs.js} +4 -4
  78. package/dist/{index-gkee6p4g.js → index-p56dszfp.js} +3 -3
  79. package/dist/{index-9gpw8hrm.js → index-pq0dpwrc.js} +4 -4
  80. package/dist/{index-rfxzazzy.js → index-pswsyf1w.js} +4 -4
  81. package/dist/{index-y1qwzvxn.js → index-pztqab6k.js} +2 -2
  82. package/dist/{index-rverk2vz.js → index-qncw9hey.js} +1 -1
  83. package/dist/index-qx8j6kds.js +270 -0
  84. package/dist/{index-kq5w68dp.js → index-txs8tce6.js} +1 -1
  85. package/dist/index-vzhhr1ht.js +532 -0
  86. package/dist/index-wh9fxds5.js +265 -0
  87. package/dist/{index-hbx7m8he.js → index-x2mrq5xv.js} +170 -48
  88. package/dist/{index-07vskjn8.js → index-xwwsbsd3.js} +15 -13
  89. package/dist/index-z4p0ry94.js +222 -0
  90. package/dist/index-z9zygwse.js +89 -0
  91. package/dist/{index-v7287tzq.js → index-zhqwda72.js} +19 -8
  92. package/dist/index.js +83 -72
  93. package/dist/{logger-94kew5wm.js → logger-qwnbcfj9.js} +2 -1
  94. package/dist/{message-fts-rowid-map-va36knh4.js → message-fts-rowid-map-xg7hr0mk.js} +5 -4
  95. package/dist/{message-index-bounded-qh91fdr3.js → message-index-bounded-narw7bnz.js} +12 -11
  96. package/dist/{message-time-backfill-4qva0b4f.js → message-time-backfill-39bm498k.js} +3 -2
  97. package/dist/migration-worker.js +13 -11
  98. package/dist/{project-embedding-registry-6yex0r9f.js → project-embedding-registry-tdz7985n.js} +13 -11
  99. package/dist/raw-ordinal-warmup-worker.js +12 -7
  100. package/dist/{read-session-chunk-kaghtr75.js → read-session-chunk-vmg1zjg0.js} +15 -10
  101. package/dist/{read-session-raw-b2sd67v4.js → read-session-raw-mncmzbm9.js} +3 -2
  102. package/dist/recomp-orchestrator-qyyhnc9b.js +68 -0
  103. package/dist/render-c5p0k846.js +43 -0
  104. package/dist/{safe-notification-target-mkr9yzvr.js → safe-notification-target-wztd7bgk.js} +3 -2
  105. package/dist/{search-archive-1kw2rp19.js → search-archive-0ny7p3bw.js} +13 -11
  106. package/dist/{search-p684j8ww.js → search-f6hwvcxk.js} +26 -23
  107. package/dist/{send-session-notification-vz86nt79.js → send-session-notification-0gwcz3fw.js} +7 -6
  108. package/dist/{storage-tags-6hvkk01c.js → storage-tags-zx1023km.js} +5 -4
  109. package/dist/store-620rjzt9.js +21 -0
  110. package/dist/store-reader-yh19h38c.js +14 -0
  111. package/dist/tools/ctx-expand/render.d.ts +5 -3
  112. package/dist/tools/ctx-expand/render.d.ts.map +1 -1
  113. package/dist/tools/ctx-expand/search-archive.d.ts.map +1 -1
  114. package/dist/tools/ctx-expand/tools.d.ts +2 -0
  115. package/dist/tools/ctx-expand/tools.d.ts.map +1 -1
  116. package/dist/tools/ctx-expand/v2-archive-reader.d.ts +33 -0
  117. package/dist/tools/ctx-expand/v2-archive-reader.d.ts.map +1 -0
  118. package/dist/{transform-postprocess-phase-ph38mhrs.js → transform-postprocess-phase-807ff6t2.js} +36 -30
  119. package/dist/v2/auto-search-worker.js +11 -6
  120. package/dist/v2/chunk-embedding-write-worker.js +16 -14
  121. package/dist/v2/{compaction-marker-candidates-m4vmye3w.js → compaction-marker-candidates-t1aq6gsj.js} +3 -2
  122. package/dist/v2/compaction-marker-candidates-worker.js +1 -1
  123. package/dist/v2/{compartment-chunk-embedding-rc31e6md.js → compartment-chunk-embedding-ncsk0r9e.js} +8 -7
  124. package/dist/v2/{context-s60hcatx.js → context-znqfkap4.js} +1725 -1095
  125. package/dist/v2/{derive-budgets-knf763tt.js → derive-budgets-sa0v7bz0.js} +4 -3
  126. package/dist/v2/embedding-backfill-11j425e0.js +26 -0
  127. package/dist/v2/embedding-worker-process.js +2 -1
  128. package/dist/v2/embedding-worker.js +5 -4
  129. package/dist/v2/expand-attachments-h33jbgyz.js +21 -0
  130. package/dist/v2/fold/idle.d.ts +15 -0
  131. package/dist/v2/fold/idle.d.ts.map +1 -0
  132. package/dist/v2/fold/native-replay-v3.d.ts +68 -0
  133. package/dist/v2/fold/native-replay-v3.d.ts.map +1 -0
  134. package/dist/v2/fold/native-replay.d.ts +58 -2
  135. package/dist/v2/fold/native-replay.d.ts.map +1 -1
  136. package/dist/v2/fold/policy.d.ts +2 -1
  137. package/dist/v2/fold/policy.d.ts.map +1 -1
  138. package/dist/v2/{history-owner-ad0crnrn.js → history-owner-fpka43cn.js} +3 -2
  139. package/dist/v2/hooks/context.d.ts.map +1 -1
  140. package/dist/v2/hooks/expand-attachments.d.ts +8 -0
  141. package/dist/v2/hooks/expand-attachments.d.ts.map +1 -0
  142. package/dist/v2/hooks/overflow-recovery.d.ts +45 -0
  143. package/dist/v2/hooks/overflow-recovery.d.ts.map +1 -0
  144. package/dist/v2/hooks/store.d.ts +7 -2
  145. package/dist/v2/hooks/store.d.ts.map +1 -1
  146. package/dist/v2/{logger-p34mjtja.js → logger-4cj6d03m.js} +2 -1
  147. package/dist/v2/{message-fts-rowid-map-78awh03v.js → message-fts-rowid-map-rmk571mb.js} +5 -4
  148. package/dist/v2/{message-index-bounded-4htdr1j6.js → message-index-bounded-620bppw7.js} +12 -11
  149. package/dist/v2/{message-time-backfill-zvthw6xb.js → message-time-backfill-0c4h7sg6.js} +3 -2
  150. package/dist/v2/migration-worker.js +13 -11
  151. package/dist/v2/ordinal-range.fixture.d.ts +7 -0
  152. package/dist/v2/ordinal-range.fixture.d.ts.map +1 -0
  153. package/dist/v2/{project-embedding-registry-1x5qe2fy.js → project-embedding-registry-bm5fe1a8.js} +13 -11
  154. package/dist/v2/raw-ordinal-warmup-worker.js +12 -7
  155. package/dist/v2/{read-session-chunk-1fa9qzwb.js → read-session-chunk-qfwv1k71.js} +15 -10
  156. package/dist/v2/{read-session-raw-5x088amc.js → read-session-raw-q294t8xs.js} +3 -2
  157. package/dist/v2/recomp-orchestrator-fcnjref7.js +67 -0
  158. package/dist/v2/render-98a1qv0b.js +42 -0
  159. package/dist/v2/{safe-notification-target-khnzg57c.js → safe-notification-target-gphhast7.js} +3 -2
  160. package/dist/v2/{search-archive-xfp51s0g.js → search-archive-r0y1bafr.js} +13 -11
  161. package/dist/v2/{search-wf8rqxhm.js → search-z1zqzsmh.js} +25 -22
  162. package/dist/v2/{send-session-notification-x5nzy34v.js → send-session-notification-fst6hkg7.js} +7 -6
  163. package/dist/v2/{server-qvy4qavp.js → server-1xesqm5h.js} +113 -133
  164. package/dist/v2/server-2amn2s73.js +123 -0
  165. package/dist/v2/{server-6g98c227.js → server-3schkz95.js} +4 -4
  166. package/dist/v2/server-468mya5v.js +209 -0
  167. package/dist/v2/server-55v5hpth.js +270 -0
  168. package/dist/v2/server-5jp38p98.js +532 -0
  169. package/dist/v2/{server-qjvk4a9t.js → server-69m30b21.js} +1 -1
  170. package/dist/v2/{server-jw5qe9y8.js → server-7ccxt4nq.js} +14 -216
  171. package/dist/v2/{server-3mz2qh5a.js → server-969cdpmg.js} +1 -1
  172. package/dist/v2/{server-835q39kd.js → server-9k0mjef7.js} +2 -2
  173. package/dist/v2/{server-qc915kw2.js → server-bez34e60.js} +4 -4
  174. package/dist/v2/{server-nxas8v1d.js → server-bpvsvtph.js} +3 -3
  175. package/dist/v2/{server-ab8017gw.js → server-bxpz2dcn.js} +29 -138
  176. package/dist/v2/{server-bsgd4dk1.js → server-dcws5831.js} +2 -2
  177. package/dist/v2/server-ef1mskas.js +777 -0
  178. package/dist/v2/{server-1bw1wcbp.js → server-f0j864ma.js} +1 -1
  179. package/dist/v2/{server-z2wft9zv.js → server-fqj6ddpr.js} +402 -5497
  180. package/dist/v2/{server-grakwy1v.js → server-hnknwaz8.js} +37 -7
  181. package/dist/v2/{server-h1byrhwx.js → server-hsf0qsn5.js} +19 -8
  182. package/dist/v2/{server-6495nmn9.js → server-jb6tjyeb.js} +5 -222
  183. package/dist/v2/{server-2aasmpsp.js → server-kkxzwa6w.js} +4 -4
  184. package/dist/v2/{server-a7x00tw8.js → server-mfn1yf9d.js} +1 -1
  185. package/dist/v2/{server-tkdabx8q.js → server-q0z2q2dx.js} +5 -530
  186. package/dist/v2/{server-ajxhrgjv.js → server-qa74bj91.js} +77 -17
  187. package/dist/v2/server-qf2kzsh2.js +4513 -0
  188. package/dist/v2/{server-gyy4k6mf.js → server-qmmkhz2z.js} +1 -1
  189. package/dist/v2/{server-29qp8nz4.js → server-qxzbmtqt.js} +1 -1
  190. package/dist/v2/{server-m1pfg2d4.js → server-r3chnxs5.js} +4 -4
  191. package/dist/v2/{server-vr4szghm.js → server-rktnzs89.js} +2 -2
  192. package/dist/v2/{server-6vd2n183.js → server-s9xgyyj9.js} +1 -1
  193. package/dist/v2/{server-53eh1r8r.js → server-sd8hvzte.js} +2 -2
  194. package/dist/v2/{server-k3t06fxr.js → server-sefxj8k1.js} +1 -1
  195. package/dist/v2/{server-v77xa5wj.js → server-tpt7bwq8.js} +1 -1
  196. package/dist/v2/{server-awr8qa4c.js → server-ws5exe6q.js} +2 -2
  197. package/dist/v2/server-x4m6xcn4.js +194 -0
  198. package/dist/v2/{server-806rzhs6.js → server-xbtw0p9t.js} +1 -1
  199. package/dist/v2/{server-cqjvxyrp.js → server-xy7w7hrd.js} +2 -2
  200. package/dist/v2/server-ypf1ap0v.js +529 -0
  201. package/dist/v2/server-z4p0ry94.js +222 -0
  202. package/dist/v2/server-z9zygwse.js +89 -0
  203. package/dist/v2/{server-ab1g0wn9.js → server-zzgtgqmd.js} +2 -2
  204. package/dist/v2/server.js +6 -5
  205. package/dist/v2/{storage-tags-18nbaanf.js → storage-tags-19s0ebf0.js} +5 -4
  206. package/dist/v2/store-reader-cgx47zkp.js +14 -0
  207. package/dist/v2/store-reader.d.ts +9 -2
  208. package/dist/v2/store-reader.d.ts.map +1 -1
  209. package/dist/v2/store-vdm8v3jd.js +21 -0
  210. package/dist/v2/v2-archive-reader-t2c0eypn.js +11 -0
  211. package/dist/v2/{wrapup-orchestrator-wxf7n5k6.js → wrapup-orchestrator-aqpqsveg.js} +46 -39
  212. package/dist/v2-archive-reader-tm2eayp2.js +11 -0
  213. package/dist/wrapup-orchestrator-k5yp19a6.js +55 -0
  214. package/package.json +1 -1
  215. package/src/shared/sqlite-transaction-mode-guard.test.ts +2 -0
  216. package/dist/embedding-backfill-0jgtqxen.js +0 -25
  217. package/dist/recomp-orchestrator-0y983w7h.js +0 -62
  218. package/dist/v2/embedding-backfill-f43hd8y6.js +0 -24
  219. package/dist/v2/recomp-orchestrator-7q9nvxte.js +0 -61
  220. package/dist/wrapup-orchestrator-ys2nrkkb.js +0 -49
@@ -0,0 +1,209 @@
1
+ import {
2
+ sanitizeDiagnosticText
3
+ } from "./server-z4p0ry94.js";
4
+
5
+ // src/features/magic-context/fail-closed-block.ts
6
+ var FAIL_CLOSED_DOCTOR_COMMAND = "npx @cortexkit/magic-context@latest doctor";
7
+ function attachFailClosedBlockingProcessEvidence(process, evidence) {
8
+ Object.defineProperties(process, {
9
+ startTime: { configurable: true, value: evidence.startTime },
10
+ commandLine: { configurable: true, value: evidence.commandLine }
11
+ });
12
+ return process;
13
+ }
14
+
15
+ class FailClosedBlockingError extends Error {
16
+ code = "FAIL_CLOSED_BLOCKING";
17
+ reason;
18
+ constructor(message, reason, options) {
19
+ super(message, options);
20
+ this.name = "FailClosedBlockingError";
21
+ this.reason = reason;
22
+ }
23
+ }
24
+ var OPENCODE_INTERNAL_AGENT_NAMES = new Set(["title", "summary", "compaction"]);
25
+ function isMagicContextHiddenAgentName(agent) {
26
+ if (agent === "smart-note-compiler" || agent.startsWith("smart-note-")) {
27
+ return true;
28
+ }
29
+ if (agent === "historian" || agent.startsWith("historian-"))
30
+ return true;
31
+ if (agent === "dreamer" || agent.startsWith("dreamer-"))
32
+ return true;
33
+ return false;
34
+ }
35
+ var MAX_FORMATTED_BLOCKING_PROCESSES = 8;
36
+ var MAX_FORMATTED_COMMAND_LINE_LENGTH = 80;
37
+ function normalizeFailClosedProcessKind(process) {
38
+ switch (process.kind) {
39
+ case "OpenCode server":
40
+ case "OpenCode instance (TUI/CLI)":
41
+ case "Pi":
42
+ case "process":
43
+ return process.kind;
44
+ }
45
+ switch (process.harness?.trim().toLowerCase()) {
46
+ case "opencode server":
47
+ return "OpenCode server";
48
+ case "opencode instance (tui/cli)":
49
+ case "opencode instance":
50
+ return "OpenCode instance (TUI/CLI)";
51
+ case "pi":
52
+ case "pi harness":
53
+ case "omp":
54
+ return "Pi";
55
+ default:
56
+ return "process";
57
+ }
58
+ }
59
+ function formatFailClosedProcessStartTime(startTime) {
60
+ if (!Number.isFinite(startTime) || startTime <= 0)
61
+ return "unverified";
62
+ try {
63
+ const parts = new Intl.DateTimeFormat("en-US", {
64
+ day: "numeric",
65
+ hour: "2-digit",
66
+ minute: "2-digit",
67
+ month: "short",
68
+ hour12: false
69
+ }).formatToParts(new Date(startTime));
70
+ const values = Object.fromEntries(parts.map(({ type, value }) => [type, value]));
71
+ if (!values.month || !values.day || !values.hour || !values.minute)
72
+ return "unverified";
73
+ return `${values.month} ${values.day} ${values.hour}:${values.minute}`;
74
+ } catch {
75
+ return "unverified";
76
+ }
77
+ }
78
+ function formatFailClosedCommandLine(commandLine) {
79
+ if (typeof commandLine !== "string" || commandLine.trim().length === 0)
80
+ return "unverified";
81
+ try {
82
+ const normalized = commandLine.replaceAll("\x00", " ").replace(/\s+/g, " ").trim();
83
+ if (normalized.length === 0)
84
+ return "unverified";
85
+ const sanitized = sanitizeDiagnosticText(normalized).trim();
86
+ if (sanitized.length === 0)
87
+ return "unverified";
88
+ return sanitized.length > MAX_FORMATTED_COMMAND_LINE_LENGTH ? `${sanitized.slice(0, MAX_FORMATTED_COMMAND_LINE_LENGTH - 3)}...` : sanitized;
89
+ } catch {
90
+ return "unverified";
91
+ }
92
+ }
93
+ function formatFailClosedBlockingProcesses(processes) {
94
+ const uniqueProcesses = new Map;
95
+ for (const process of processes) {
96
+ if (!Number.isInteger(process.pid) || process.pid <= 0)
97
+ continue;
98
+ const candidate = {
99
+ kind: normalizeFailClosedProcessKind(process),
100
+ pid: process.pid,
101
+ startTime: process.startTime,
102
+ commandLine: process.commandLine
103
+ };
104
+ const previous = uniqueProcesses.get(process.pid);
105
+ if (!previous || previous.kind === "process" && candidate.kind !== "process") {
106
+ uniqueProcesses.set(process.pid, candidate);
107
+ } else {
108
+ uniqueProcesses.set(process.pid, {
109
+ ...previous,
110
+ startTime: previous.startTime ?? candidate.startTime,
111
+ commandLine: previous.commandLine ?? candidate.commandLine
112
+ });
113
+ }
114
+ }
115
+ const entries = [...uniqueProcesses.values()];
116
+ const visible = entries.slice(0, MAX_FORMATTED_BLOCKING_PROCESSES);
117
+ const rendered = visible.map(({ kind, pid }) => `${kind} (PID ${pid})`);
118
+ const omitted = entries.length - visible.length;
119
+ if (omitted > 0)
120
+ rendered.push(`${omitted} more blocking process(es)`);
121
+ if (rendered.length === 0)
122
+ return "a live process";
123
+ const summary = rendered.length === 1 ? rendered[0] : `${rendered.slice(0, -1).join(", ")}, and ${rendered.at(-1)}`;
124
+ const evidence = entries.map(({ kind, pid, startTime, commandLine }) => `- PID ${pid}: ${kind}, started ${formatFailClosedProcessStartTime(startTime)}, cmd: ${formatFailClosedCommandLine(commandLine)}`).join(`
125
+ `);
126
+ return `${summary}
127
+ Blocking process evidence:
128
+ ${evidence}`;
129
+ }
130
+ function formatFailClosedBlockingMessage(reason) {
131
+ if (reason.kind === "migration_guard") {
132
+ if (reason.unreadableFile) {
133
+ const arm = reason.unreadableArm ?? "io";
134
+ const recovery = arm === "io" ? `If none of these processes are running, it is safe to delete ${reason.unreadableFile} and retry.` : `The file may be a recent incomplete write; retry after the file is older than the ten-minute grace window, or stop the relevant process before deleting it.`;
135
+ return [
136
+ `Magic Context cannot migrate the shared database because RPC discovery file ${reason.unreadableFile} is uncertain (${arm} arm), so the absence of a live process cannot be proven.`,
137
+ recovery,
138
+ `Recovery: ${FAIL_CLOSED_DOCTOR_COMMAND}`
139
+ ].join(" ");
140
+ }
141
+ return [
142
+ `Magic Context cannot migrate the shared database (one database serves every project on this machine) because ${formatFailClosedBlockingProcesses(reason.blockingProcesses)} may be running an older Magic Context build that would fail against the migrated database.`,
143
+ `The database is at upstream migration v${reason.persistedVersion}; this build needs v${reason.supportedVersion}.`,
144
+ "Restart the blocking process — even one from a different project — and it will pick up the new build and migrate on start; or shut it down and retry.",
145
+ "If that host loads a pinned or cached older Magic Context build, a restart alone is not enough: stop it or update its Magic Context build, then start this host once so it migrates the database with nothing older attached.",
146
+ `Recovery: ${FAIL_CLOSED_DOCTOR_COMMAND}`
147
+ ].join(" ");
148
+ }
149
+ if (reason.kind === "schema_fence") {
150
+ return [
151
+ `Magic Context cannot operate: this Magic Context build is older than the database; upgrade/restart this harness (upstream migration lane v${reason.persistedVersion}, build supports through v${reason.supportedVersion}).`,
152
+ `Recovery: ${FAIL_CLOSED_DOCTOR_COMMAND}`
153
+ ].join(" ");
154
+ }
155
+ const cause = reason.cause.trim().length > 0 ? reason.cause.trim() : "unknown storage error";
156
+ return [
157
+ `Magic Context cannot operate: persistent storage failed (${cause}).`,
158
+ "The plugin will not silently degrade to native compaction while enabled.",
159
+ `Recovery: ${FAIL_CLOSED_DOCTOR_COMMAND}`
160
+ ].join(" ");
161
+ }
162
+ function formatFailClosedBlockingSummary(reason) {
163
+ if (reason.kind === "migration_guard") {
164
+ if (reason.unreadableFile) {
165
+ return `Magic Context cannot migrate the shared database from v${reason.persistedVersion} to v${reason.supportedVersion}: RPC discovery file ${reason.unreadableFile} could not be read, so an older host may still be attached.`;
166
+ }
167
+ const blockers = reason.blockingProcesses.filter((process) => Number.isInteger(process.pid) && process.pid > 0).map((process) => `${normalizeFailClosedProcessKind(process)} (PID ${process.pid})`);
168
+ const named = blockers.length > 0 ? blockers.join(", ") : "a live process";
169
+ return `Magic Context cannot migrate the shared database from v${reason.persistedVersion} to v${reason.supportedVersion} while ${named} may still run an older Magic Context build. Stop or update that host, then start this one once.`;
170
+ }
171
+ if (reason.kind === "schema_fence") {
172
+ return `Magic Context cannot operate: the shared database is at v${reason.persistedVersion}, newer than this build supports (v${reason.supportedVersion}). Update and restart this host.`;
173
+ }
174
+ const cause = reason.cause.trim().length > 0 ? reason.cause.trim() : "unknown storage error";
175
+ return `Magic Context cannot operate: persistent storage failed (${cause}).`;
176
+ }
177
+ function createFailClosedBlockingError(reason, options) {
178
+ return new FailClosedBlockingError(formatFailClosedBlockingMessage(reason), reason, options);
179
+ }
180
+ function isFailClosedBlockingError(error) {
181
+ return error instanceof FailClosedBlockingError || typeof error === "object" && error !== null && error.name === "FailClosedBlockingError" && error.code === "FAIL_CLOSED_BLOCKING";
182
+ }
183
+ function shouldBypassFailClosedBlock(input) {
184
+ if (input.isPiSubagentEnv === true)
185
+ return true;
186
+ if (input.isInternalChildSession === true)
187
+ return true;
188
+ const agent = typeof input.agent === "string" ? input.agent.trim() : "";
189
+ if (agent.length === 0)
190
+ return false;
191
+ if (OPENCODE_INTERNAL_AGENT_NAMES.has(agent))
192
+ return true;
193
+ if (isMagicContextHiddenAgentName(agent))
194
+ return true;
195
+ return false;
196
+ }
197
+ function resolveAgentNameFromMessages(messages) {
198
+ for (let i = messages.length - 1;i >= 0; i -= 1) {
199
+ const info = messages[i]?.info;
200
+ if (!info || typeof info !== "object")
201
+ continue;
202
+ const agent = info.agent;
203
+ if (typeof agent === "string" && agent.length > 0)
204
+ return agent;
205
+ }
206
+ return;
207
+ }
208
+
209
+ export { FAIL_CLOSED_DOCTOR_COMMAND, attachFailClosedBlockingProcessEvidence, formatFailClosedBlockingMessage, formatFailClosedBlockingSummary, createFailClosedBlockingError, isFailClosedBlockingError, shouldBypassFailClosedBlock, resolveAgentNameFromMessages };
@@ -0,0 +1,270 @@
1
+ import {
2
+ estimateTokens
3
+ } from "./server-969cdpmg.js";
4
+ import {
5
+ expandToolPart,
6
+ visitRawSessionMessages2,
7
+ readRawSessionMessageById2
8
+ } from "./server-1xesqm5h.js";
9
+ import {
10
+ getTagById2
11
+ } from "./server-bpvsvtph.js";
12
+
13
+ // src/tools/ctx-expand/render.ts
14
+ import { createHash } from "node:crypto";
15
+ function recoveryParts(sessionId, message, attachments) {
16
+ return attachments ? [...message.parts, ...attachments(sessionId, message.id)] : message.parts;
17
+ }
18
+ function attachmentNotice(part) {
19
+ const field = (value) => typeof value === "string" ? value.trim().replace(/[\r\n]+/g, " ") : "";
20
+ const source = isRecord(part.source) ? part.source : {};
21
+ const location = [part.url, part.path, source.uri, source.url, source.path].map(field).find((value) => value && !/^(data|blob):/i.test(value));
22
+ const name = field(part.filename) || field(part.name);
23
+ const mime = field(part.mime) || field(part.mimeType) || field(part.mediaType);
24
+ return `[file]${name ? ` ${name}` : ""}${mime ? ` (${mime})` : ""}` + `${location ? ` — stored location: ${location}` : ""}` + "; content not recovered. If needed, ask the user to attach it again.";
25
+ }
26
+ function isRecord(value) {
27
+ return value !== null && typeof value === "object" && !Array.isArray(value);
28
+ }
29
+ function roleLabel(role) {
30
+ if (role === "assistant")
31
+ return "A (assistant)";
32
+ if (role === "user")
33
+ return "U (user)";
34
+ return role;
35
+ }
36
+ function verboseRoleLabel(msg) {
37
+ if (msg.role === "user" && msg.parts.length > 0 && msg.parts.every((part) => {
38
+ if (!isRecord(part))
39
+ return false;
40
+ if (part.type === "tool_result")
41
+ return true;
42
+ return part.type === "tool" && asToolPart(part)?.output != null;
43
+ }))
44
+ return "tool results";
45
+ return roleLabel(msg.role);
46
+ }
47
+ function truncate(value, max) {
48
+ const t = value.trim();
49
+ return t.length <= max ? t : `${t.slice(0, max)}…`;
50
+ }
51
+ function keyArg(input) {
52
+ if (!input)
53
+ return "";
54
+ for (const k of ["filePath", "path", "pattern", "query", "symbol", "module", "action"]) {
55
+ const v = input[k];
56
+ if (typeof v === "string" && v.length > 0)
57
+ return truncate(v, 60);
58
+ }
59
+ if (typeof input.description === "string")
60
+ return truncate(input.description, 60);
61
+ return "";
62
+ }
63
+ function asToolPart(part) {
64
+ const type = typeof part.type === "string" ? part.type : "";
65
+ if (type === "tool") {
66
+ const state = isRecord(part.state) ? part.state : null;
67
+ const output = state && typeof state.output === "string" ? state.output : state && state.output != null ? JSON.stringify(state.output) : null;
68
+ const metadata = state && isRecord(state.metadata) ? state.metadata : null;
69
+ const title = state && typeof state.title === "string" && state.title || metadata && typeof metadata.title === "string" && metadata.title || null;
70
+ return {
71
+ name: typeof part.tool === "string" ? part.tool : "tool",
72
+ callId: typeof part.callID === "string" ? part.callID : "",
73
+ title,
74
+ input: state && isRecord(state.input) ? state.input : null,
75
+ output
76
+ };
77
+ }
78
+ if (type === "tool_use") {
79
+ return {
80
+ name: typeof part.name === "string" ? part.name : "tool",
81
+ callId: typeof part.id === "string" ? part.id : "",
82
+ title: null,
83
+ input: isRecord(part.input) ? part.input : null,
84
+ output: null
85
+ };
86
+ }
87
+ if (type === "tool_result") {
88
+ const content = part.content;
89
+ const output = typeof content === "string" ? content : content != null ? JSON.stringify(content) : null;
90
+ return {
91
+ name: "tool_result",
92
+ callId: typeof part.tool_use_id === "string" ? part.tool_use_id : "",
93
+ title: null,
94
+ input: null,
95
+ output
96
+ };
97
+ }
98
+ return null;
99
+ }
100
+ function textOf(part) {
101
+ if (part.type === "text" && typeof part.text === "string")
102
+ return part.text;
103
+ return null;
104
+ }
105
+ function reasoningOf(part) {
106
+ if ((part.type === "reasoning" || part.type === "thinking") && typeof part.text === "string") {
107
+ return part.text;
108
+ }
109
+ return null;
110
+ }
111
+ function renderPartPreview(part, expandTools) {
112
+ if (!isRecord(part))
113
+ return null;
114
+ const expansion = expandToolPart(part, expandTools, true);
115
+ if (expansion !== null)
116
+ return ` • tool ${part.tool}: ${expansion}`;
117
+ const text = textOf(part);
118
+ if (text !== null) {
119
+ const t = truncate(text, 200);
120
+ return t.length > 0 ? ` • ${t}` : null;
121
+ }
122
+ const tool = asToolPart(part);
123
+ if (tool) {
124
+ const arg = keyArg(tool.input);
125
+ const head = arg ? `${tool.name}(${arg})` : tool.name;
126
+ return tool.output !== null ? ` • tool ${head} → output ~${estimateTokens(tool.output)} tok` : ` • tool ${head}`;
127
+ }
128
+ const reasoning = reasoningOf(part);
129
+ if (reasoning !== null)
130
+ return ` • [reasoning] ${truncate(reasoning, 120)}`;
131
+ const type = typeof part.type === "string" ? part.type : "part";
132
+ if (type === "file" || type === "image")
133
+ return ` • ${attachmentNotice(part)}`;
134
+ if (type === "step-start" || type === "step-finish")
135
+ return null;
136
+ return ` • [${type}]`;
137
+ }
138
+ function renderPartFull(part) {
139
+ if (!isRecord(part))
140
+ return null;
141
+ const text = textOf(part);
142
+ if (text !== null) {
143
+ return text.trim().length > 0 ? ` [text]
144
+ ${text}` : null;
145
+ }
146
+ const tool = asToolPart(part);
147
+ if (tool) {
148
+ const lines = [];
149
+ const idSuffix = tool.callId ? ` #${tool.callId}` : "";
150
+ lines.push(` [tool: ${tool.name}${idSuffix}]`);
151
+ if (tool.title && tool.title.trim().length > 0) {
152
+ lines.push(` description: ${tool.title.trim()}`);
153
+ }
154
+ if (tool.input)
155
+ lines.push(` input: ${JSON.stringify(tool.input)}`);
156
+ if (tool.output !== null)
157
+ lines.push(` output:
158
+ ${tool.output}`);
159
+ return lines.join(`
160
+ `);
161
+ }
162
+ const type = typeof part.type === "string" ? part.type : "part";
163
+ if (type === "file" || type === "image")
164
+ return ` ${attachmentNotice(part)}`;
165
+ return null;
166
+ }
167
+ function renderMessageByOrdinal2(sessionId, ordinal, attachments) {
168
+ const found = [];
169
+ visitRawSessionMessages2(sessionId, ordinal, ordinal, (m) => {
170
+ if (m.ordinal === ordinal)
171
+ found.push(m);
172
+ return false;
173
+ });
174
+ const msg = found[0];
175
+ if (!msg) {
176
+ return `No message at ordinal ${ordinal} in this session's stored history — it was deleted ` + `(session prune/revert) or the ordinal is wrong, so it can't be recovered. ` + `Re-run the tool if you still need the data.`;
177
+ }
178
+ const rendered = recoveryParts(sessionId, msg, attachments).map(renderPartFull).filter((l) => l !== null);
179
+ const lines = [`[${msg.ordinal}] ${roleLabel(msg.role)} — full recovery:`, ""];
180
+ if (rendered.length === 0) {
181
+ lines.push(" (no recoverable content — message had only structural/reasoning parts)");
182
+ } else {
183
+ lines.push(...rendered);
184
+ }
185
+ return lines.join(`
186
+ `);
187
+ }
188
+ function renderVerboseRange(sessionId, start, end, tokenBudget, expandTools, attachments) {
189
+ const out = [];
190
+ let usedTokens = 0;
191
+ let lastOrdinal = start - 1;
192
+ let truncated = false;
193
+ visitRawSessionMessages2(sessionId, start, end, (msg) => {
194
+ const header = `[${msg.ordinal}] ${verboseRoleLabel(msg)}`;
195
+ const partLines = recoveryParts(sessionId, msg, attachments).map((part) => renderPartPreview(part, expandTools)).filter((l) => l !== null);
196
+ const block = partLines.length > 0 ? `${header}
197
+ ${partLines.join(`
198
+ `)}` : header;
199
+ const blockTokens = estimateTokens(block);
200
+ if (usedTokens + blockTokens > tokenBudget && out.length > 0) {
201
+ truncated = true;
202
+ return false;
203
+ }
204
+ out.push(block);
205
+ usedTokens += blockTokens;
206
+ lastOrdinal = msg.ordinal;
207
+ return true;
208
+ });
209
+ return { text: out.join(`
210
+
211
+ `), lastOrdinal, truncated };
212
+ }
213
+ function renderVerboseRangeForTool2(sessionId, start, end, tokenBudget, expandTools, attachments) {
214
+ const v = renderVerboseRange(sessionId, start, end, tokenBudget, expandTools, attachments);
215
+ if (!v.text) {
216
+ return `No messages found in range ${start}-${end}. The range may be outside this session's history.`;
217
+ }
218
+ const out = [
219
+ `Messages ${start}-${v.lastOrdinal} (verbose). Recover any one in full with ctx_expand(message=<ordinal>):`,
220
+ "",
221
+ v.text
222
+ ];
223
+ if (v.truncated) {
224
+ out.push("", `Truncated at message ${v.lastOrdinal} (budget: ~${tokenBudget} tokens). Call again with start=${v.lastOrdinal + 1} end=${end} verbose=true for more.`);
225
+ }
226
+ return out.join(`
227
+ `);
228
+ }
229
+ function renderItemByTag2(db, sessionId, number, textIndexDomain = "part", attachments) {
230
+ const tag = getTagById2(db, sessionId, number);
231
+ if (!tag)
232
+ return `no tag ${number} in this session; if ${number} came from a <session-history> heading or a ctx_search hit, it is an ordinal: use message=${number}`;
233
+ if (tag.type === "tool") {
234
+ const owner = tag.toolOwnerMessageId;
235
+ if (!owner)
236
+ return `Tag ${number}'s tool owner is unknown; its original call cannot be resolved safely.`;
237
+ const message = readRawSessionMessageById2(sessionId, owner);
238
+ if (!message)
239
+ return `Tag ${number}'s original tool owner is no longer in stored history.`;
240
+ const parts = message?.parts.filter((part) => isRecord(part) && asToolPart(part)?.callId === tag.messageId) ?? [];
241
+ if (!parts.some((part) => isRecord(part) && asToolPart(part)?.output !== null)) {
242
+ visitRawSessionMessages2(sessionId, message.ordinal + 1, Number.MAX_SAFE_INTEGER, (candidate) => {
243
+ const matching = candidate.parts.filter((part) => isRecord(part) && asToolPart(part)?.callId === tag.messageId);
244
+ if (matching.some((part) => isRecord(part) && part.type === "tool_use"))
245
+ return false;
246
+ parts.push(...matching);
247
+ return matching.length === 0;
248
+ });
249
+ }
250
+ const rendered = parts.map(renderPartFull).filter((part) => part !== null);
251
+ return rendered.length ? rendered.join(`
252
+ `) : `Tag ${number}'s original tool call is no longer in stored history.`;
253
+ }
254
+ const scoped = /^(.*):(?:p|file)(\d+)$/.exec(tag.messageId);
255
+ const derived = /^(.*):mc-text-v1:([a-f0-9]+):([a-f0-9]+):o(\d+)$/.exec(tag.messageId);
256
+ const owner = scoped?.[1] ?? derived?.[1] ?? tag.messageId;
257
+ const message = readRawSessionMessageById2(sessionId, owner);
258
+ if (!message)
259
+ return `Tag ${number}'s original text is no longer in stored history.`;
260
+ const index = scoped ? Number(scoped[2]) : 0;
261
+ const attached = attachments?.(sessionId, message.id) ?? [];
262
+ const parts = [...message.parts, ...attached];
263
+ const piText = parts.filter((part) => isRecord(part) && part.type === "text");
264
+ const part = tag.type === "file" ? attached.find((part) => isRecord(part) && part.partIndex === index) ?? message.parts[index] : parts[index];
265
+ const matching = derived ? piText.filter((part) => isRecord(part) && typeof part.text === "string" && createHash("sha256").update(part.text).digest("hex") === derived[3]) : [];
266
+ const selected = derived ? matching[Number(derived[4])] : textIndexDomain === "text" && tag.type !== "file" ? piText[index] : part;
267
+ return selected ? renderPartFull(selected) ?? "" : `Tag ${number}'s original text part is no longer in stored history.`;
268
+ }
269
+
270
+ export { renderMessageByOrdinal2, renderVerboseRangeForTool2, renderItemByTag2 };