@mxalbert/context-mode 2.0.0

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 (365) hide show
  1. package/.claude-plugin/marketplace.json +33 -0
  2. package/.claude-plugin/plugin.json +31 -0
  3. package/.codex-plugin/hooks.json +65 -0
  4. package/.codex-plugin/mcp.json +13 -0
  5. package/.codex-plugin/plugin.json +31 -0
  6. package/.openclaw-plugin/index.ts +12 -0
  7. package/.openclaw-plugin/openclaw.plugin.json +38 -0
  8. package/.openclaw-plugin/package.json +28 -0
  9. package/LICENSE +94 -0
  10. package/README.md +1619 -0
  11. package/bin/statusline.mjs +378 -0
  12. package/build/adapters/antigravity/index.d.ts +51 -0
  13. package/build/adapters/antigravity/index.js +169 -0
  14. package/build/adapters/antigravity-cli/index.d.ts +51 -0
  15. package/build/adapters/antigravity-cli/index.js +342 -0
  16. package/build/adapters/base.d.ts +92 -0
  17. package/build/adapters/base.js +135 -0
  18. package/build/adapters/claude-code/config.d.ts +8 -0
  19. package/build/adapters/claude-code/config.js +8 -0
  20. package/build/adapters/claude-code/hooks.d.ts +106 -0
  21. package/build/adapters/claude-code/hooks.js +183 -0
  22. package/build/adapters/claude-code/index.d.ts +80 -0
  23. package/build/adapters/claude-code/index.js +569 -0
  24. package/build/adapters/claude-code-base.d.ts +49 -0
  25. package/build/adapters/claude-code-base.js +113 -0
  26. package/build/adapters/client-map.d.ts +10 -0
  27. package/build/adapters/client-map.js +42 -0
  28. package/build/adapters/codex/config.d.ts +8 -0
  29. package/build/adapters/codex/config.js +8 -0
  30. package/build/adapters/codex/hooks.d.ts +55 -0
  31. package/build/adapters/codex/hooks.js +64 -0
  32. package/build/adapters/codex/index.d.ts +87 -0
  33. package/build/adapters/codex/index.js +995 -0
  34. package/build/adapters/codex/paths.d.ts +1 -0
  35. package/build/adapters/codex/paths.js +12 -0
  36. package/build/adapters/codex/usage.d.ts +107 -0
  37. package/build/adapters/codex/usage.js +227 -0
  38. package/build/adapters/copilot-base.d.ts +94 -0
  39. package/build/adapters/copilot-base.js +297 -0
  40. package/build/adapters/copilot-cli/hooks.d.ts +33 -0
  41. package/build/adapters/copilot-cli/hooks.js +64 -0
  42. package/build/adapters/copilot-cli/index.d.ts +48 -0
  43. package/build/adapters/copilot-cli/index.js +341 -0
  44. package/build/adapters/cursor/config.d.ts +4 -0
  45. package/build/adapters/cursor/config.js +4 -0
  46. package/build/adapters/cursor/hooks.d.ts +55 -0
  47. package/build/adapters/cursor/hooks.js +82 -0
  48. package/build/adapters/cursor/index.d.ts +64 -0
  49. package/build/adapters/cursor/index.js +517 -0
  50. package/build/adapters/detect.d.ts +136 -0
  51. package/build/adapters/detect.js +623 -0
  52. package/build/adapters/gemini-cli/config.d.ts +8 -0
  53. package/build/adapters/gemini-cli/config.js +8 -0
  54. package/build/adapters/gemini-cli/hooks.d.ts +83 -0
  55. package/build/adapters/gemini-cli/hooks.js +115 -0
  56. package/build/adapters/gemini-cli/index.d.ts +80 -0
  57. package/build/adapters/gemini-cli/index.js +483 -0
  58. package/build/adapters/jetbrains-copilot/config.d.ts +8 -0
  59. package/build/adapters/jetbrains-copilot/config.js +8 -0
  60. package/build/adapters/jetbrains-copilot/hooks.d.ts +59 -0
  61. package/build/adapters/jetbrains-copilot/hooks.js +87 -0
  62. package/build/adapters/jetbrains-copilot/index.d.ts +31 -0
  63. package/build/adapters/jetbrains-copilot/index.js +131 -0
  64. package/build/adapters/kimi/config.d.ts +8 -0
  65. package/build/adapters/kimi/config.js +8 -0
  66. package/build/adapters/kimi/hooks.d.ts +28 -0
  67. package/build/adapters/kimi/hooks.js +34 -0
  68. package/build/adapters/kimi/index.d.ts +66 -0
  69. package/build/adapters/kimi/index.js +537 -0
  70. package/build/adapters/kimi/paths.d.ts +21 -0
  71. package/build/adapters/kimi/paths.js +52 -0
  72. package/build/adapters/kimi/usage.d.ts +82 -0
  73. package/build/adapters/kimi/usage.js +217 -0
  74. package/build/adapters/kiro/hooks.d.ts +61 -0
  75. package/build/adapters/kiro/hooks.js +94 -0
  76. package/build/adapters/kiro/index.d.ts +61 -0
  77. package/build/adapters/kiro/index.js +301 -0
  78. package/build/adapters/omp/index.d.ts +65 -0
  79. package/build/adapters/omp/index.js +182 -0
  80. package/build/adapters/omp/plugin.d.ts +81 -0
  81. package/build/adapters/omp/plugin.js +331 -0
  82. package/build/adapters/omp/usage.d.ts +49 -0
  83. package/build/adapters/omp/usage.js +110 -0
  84. package/build/adapters/openclaw/config.d.ts +8 -0
  85. package/build/adapters/openclaw/config.js +8 -0
  86. package/build/adapters/openclaw/hooks.d.ts +50 -0
  87. package/build/adapters/openclaw/hooks.js +61 -0
  88. package/build/adapters/openclaw/index.d.ts +74 -0
  89. package/build/adapters/openclaw/index.js +439 -0
  90. package/build/adapters/openclaw/mcp-tools.d.ts +54 -0
  91. package/build/adapters/openclaw/mcp-tools.js +207 -0
  92. package/build/adapters/openclaw/plugin.d.ts +141 -0
  93. package/build/adapters/openclaw/plugin.js +818 -0
  94. package/build/adapters/openclaw/session-db.d.ts +55 -0
  95. package/build/adapters/openclaw/session-db.js +88 -0
  96. package/build/adapters/openclaw/usage.d.ts +34 -0
  97. package/build/adapters/openclaw/usage.js +52 -0
  98. package/build/adapters/openclaw/workspace-router.d.ts +29 -0
  99. package/build/adapters/openclaw/workspace-router.js +64 -0
  100. package/build/adapters/opencode/config.d.ts +8 -0
  101. package/build/adapters/opencode/config.js +8 -0
  102. package/build/adapters/opencode/hooks.d.ts +38 -0
  103. package/build/adapters/opencode/hooks.js +50 -0
  104. package/build/adapters/opencode/index.d.ts +144 -0
  105. package/build/adapters/opencode/index.js +638 -0
  106. package/build/adapters/opencode/plugin.d.ts +249 -0
  107. package/build/adapters/opencode/plugin.js +1536 -0
  108. package/build/adapters/opencode/v2.d.ts +117 -0
  109. package/build/adapters/opencode/v2.js +224 -0
  110. package/build/adapters/opencode/zod3tov4.d.ts +1 -0
  111. package/build/adapters/opencode/zod3tov4.js +132 -0
  112. package/build/adapters/pi/extension.d.ts +81 -0
  113. package/build/adapters/pi/extension.js +861 -0
  114. package/build/adapters/pi/index.d.ts +57 -0
  115. package/build/adapters/pi/index.js +173 -0
  116. package/build/adapters/pi/mcp-bridge.d.ts +268 -0
  117. package/build/adapters/pi/mcp-bridge.js +894 -0
  118. package/build/adapters/qwen-code/hooks.d.ts +26 -0
  119. package/build/adapters/qwen-code/hooks.js +29 -0
  120. package/build/adapters/qwen-code/index.d.ts +40 -0
  121. package/build/adapters/qwen-code/index.js +361 -0
  122. package/build/adapters/qwen-code/usage.d.ts +90 -0
  123. package/build/adapters/qwen-code/usage.js +222 -0
  124. package/build/adapters/types.d.ts +360 -0
  125. package/build/adapters/types.js +118 -0
  126. package/build/adapters/vscode-copilot/config.d.ts +8 -0
  127. package/build/adapters/vscode-copilot/config.js +8 -0
  128. package/build/adapters/vscode-copilot/hooks.d.ts +71 -0
  129. package/build/adapters/vscode-copilot/hooks.js +98 -0
  130. package/build/adapters/vscode-copilot/index.d.ts +32 -0
  131. package/build/adapters/vscode-copilot/index.js +222 -0
  132. package/build/adapters/zed/index.d.ts +40 -0
  133. package/build/adapters/zed/index.js +163 -0
  134. package/build/cli.d.ts +34 -0
  135. package/build/cli.js +1828 -0
  136. package/build/db-base.d.ts +250 -0
  137. package/build/db-base.js +756 -0
  138. package/build/executor.d.ts +72 -0
  139. package/build/executor.js +678 -0
  140. package/build/exit-classify.d.ts +19 -0
  141. package/build/exit-classify.js +12 -0
  142. package/build/fetch/blocks.d.ts +145 -0
  143. package/build/fetch/blocks.js +244 -0
  144. package/build/fetch/extract.d.ts +68 -0
  145. package/build/fetch/extract.js +123 -0
  146. package/build/fetch/page-store.d.ts +66 -0
  147. package/build/fetch/page-store.js +174 -0
  148. package/build/fetch-cache.d.ts +13 -0
  149. package/build/fetch-cache.js +15 -0
  150. package/build/lifecycle.d.ts +124 -0
  151. package/build/lifecycle.js +278 -0
  152. package/build/package-identity.d.ts +26 -0
  153. package/build/package-identity.js +28 -0
  154. package/build/runPool.d.ts +36 -0
  155. package/build/runPool.js +51 -0
  156. package/build/runtime.d.ts +71 -0
  157. package/build/runtime.js +659 -0
  158. package/build/search/auto-memory.d.ts +47 -0
  159. package/build/search/auto-memory.js +170 -0
  160. package/build/search/ctx-search-schema.d.ts +90 -0
  161. package/build/search/ctx-search-schema.js +135 -0
  162. package/build/search/flood-guard.d.ts +57 -0
  163. package/build/search/flood-guard.js +80 -0
  164. package/build/search/unified.d.ts +56 -0
  165. package/build/search/unified.js +104 -0
  166. package/build/security.d.ts +206 -0
  167. package/build/security.js +780 -0
  168. package/build/server.d.ts +240 -0
  169. package/build/server.js +5034 -0
  170. package/build/session/analytics.d.ts +773 -0
  171. package/build/session/analytics.js +2420 -0
  172. package/build/session/db.d.ts +468 -0
  173. package/build/session/db.js +1330 -0
  174. package/build/session/error-classifier.d.ts +87 -0
  175. package/build/session/error-classifier.js +303 -0
  176. package/build/session/event-emit.d.ts +48 -0
  177. package/build/session/event-emit.js +101 -0
  178. package/build/session/extract.d.ts +333 -0
  179. package/build/session/extract.js +2688 -0
  180. package/build/session/model-prices.json +429 -0
  181. package/build/session/persist-tool-calls.d.ts +54 -0
  182. package/build/session/persist-tool-calls.js +105 -0
  183. package/build/session/pricing.d.ts +64 -0
  184. package/build/session/pricing.js +151 -0
  185. package/build/session/project-attribution.d.ts +73 -0
  186. package/build/session/project-attribution.js +245 -0
  187. package/build/session/purge.d.ts +138 -0
  188. package/build/session/purge.js +240 -0
  189. package/build/session/retrieval-marker.d.ts +39 -0
  190. package/build/session/retrieval-marker.js +65 -0
  191. package/build/session/snapshot.d.ts +46 -0
  192. package/build/session/snapshot.js +532 -0
  193. package/build/store-directory.d.ts +56 -0
  194. package/build/store-directory.js +254 -0
  195. package/build/store.d.ts +147 -0
  196. package/build/store.js +1714 -0
  197. package/build/truncate.d.ts +57 -0
  198. package/build/truncate.js +142 -0
  199. package/build/types.d.ts +117 -0
  200. package/build/types.js +20 -0
  201. package/build/util/claude-config.d.ts +32 -0
  202. package/build/util/claude-config.js +84 -0
  203. package/build/util/hook-config.d.ts +27 -0
  204. package/build/util/hook-config.js +76 -0
  205. package/build/util/jsonc.d.ts +14 -0
  206. package/build/util/jsonc.js +104 -0
  207. package/build/util/plugin-cache-integrity.d.ts +51 -0
  208. package/build/util/plugin-cache-integrity.js +146 -0
  209. package/build/util/project-dir.d.ts +149 -0
  210. package/build/util/project-dir.js +340 -0
  211. package/build/util/sibling-mcp.d.ts +79 -0
  212. package/build/util/sibling-mcp.js +181 -0
  213. package/cli.bundle.mjs +1495 -0
  214. package/configs/antigravity/GEMINI.md +68 -0
  215. package/configs/antigravity/mcp_config.json +7 -0
  216. package/configs/antigravity-cli/hooks/hooks.json +37 -0
  217. package/configs/antigravity-cli/hooks.json +37 -0
  218. package/configs/antigravity-cli/mcp_config.json +10 -0
  219. package/configs/antigravity-cli/plugin.json +14 -0
  220. package/configs/antigravity-cli/rules/context-mode.md +77 -0
  221. package/configs/antigravity-cli/skills/context-mode/SKILL.md +77 -0
  222. package/configs/claude-code/CLAUDE.md +91 -0
  223. package/configs/codex/AGENTS.md +99 -0
  224. package/configs/codex/config.toml +8 -0
  225. package/configs/codex/hooks.json +47 -0
  226. package/configs/copilot-cli/.github/plugin/plugin.json +23 -0
  227. package/configs/copilot-cli/.mcp.json +12 -0
  228. package/configs/copilot-cli/README.md +47 -0
  229. package/configs/copilot-cli/hooks.json +41 -0
  230. package/configs/copilot-cli/skills/context-mode/SKILL.md +38 -0
  231. package/configs/cursor/context-mode.mdc +76 -0
  232. package/configs/cursor/hooks.json +21 -0
  233. package/configs/cursor/mcp.json +7 -0
  234. package/configs/gemini-cli/GEMINI.md +88 -0
  235. package/configs/gemini-cli/mcp.json +7 -0
  236. package/configs/gemini-cli/settings.json +60 -0
  237. package/configs/jetbrains-copilot/copilot-instructions.md +80 -0
  238. package/configs/jetbrains-copilot/hooks.json +16 -0
  239. package/configs/jetbrains-copilot/mcp.json +7 -0
  240. package/configs/kilo/AGENTS.md +84 -0
  241. package/configs/kilo/kilo.json +6 -0
  242. package/configs/kimi/hooks.json +54 -0
  243. package/configs/kiro/KIRO.md +84 -0
  244. package/configs/kiro/agent.json +18 -0
  245. package/configs/kiro/mcp.json +7 -0
  246. package/configs/omp/SYSTEM.md +85 -0
  247. package/configs/omp/mcp.json +7 -0
  248. package/configs/openclaw/AGENTS.md +87 -0
  249. package/configs/openclaw/openclaw.json +13 -0
  250. package/configs/opencode/AGENTS.md +84 -0
  251. package/configs/opencode/opencode.json +6 -0
  252. package/configs/pi/AGENTS.md +3 -0
  253. package/configs/qwen-code/QWEN.md +91 -0
  254. package/configs/vscode-copilot/copilot-instructions.md +80 -0
  255. package/configs/vscode-copilot/hooks.json +16 -0
  256. package/configs/vscode-copilot/mcp.json +7 -0
  257. package/configs/zed/AGENTS.md +68 -0
  258. package/hooks/antigravity-cli/payload.mjs +98 -0
  259. package/hooks/antigravity-cli/posttooluse.mjs +138 -0
  260. package/hooks/antigravity-cli/pretooluse.mjs +78 -0
  261. package/hooks/antigravity-cli/stop.mjs +58 -0
  262. package/hooks/auto-injection.mjs +102 -0
  263. package/hooks/cache-heal-utils.mjs +379 -0
  264. package/hooks/codex/platform.mjs +1 -0
  265. package/hooks/codex/posttooluse.mjs +66 -0
  266. package/hooks/codex/precompact.mjs +70 -0
  267. package/hooks/codex/pretooluse.mjs +42 -0
  268. package/hooks/codex/sessionstart.mjs +121 -0
  269. package/hooks/codex/stop.mjs +138 -0
  270. package/hooks/codex/userpromptsubmit.mjs +75 -0
  271. package/hooks/copilot-cli/posttooluse.mjs +79 -0
  272. package/hooks/copilot-cli/precompact.mjs +66 -0
  273. package/hooks/copilot-cli/pretooluse.mjs +41 -0
  274. package/hooks/copilot-cli/sessionstart.mjs +121 -0
  275. package/hooks/copilot-cli/stop.mjs +59 -0
  276. package/hooks/copilot-cli/userpromptsubmit.mjs +77 -0
  277. package/hooks/core/codex-caps.mjs +112 -0
  278. package/hooks/core/formatters.mjs +356 -0
  279. package/hooks/core/mcp-ready.mjs +109 -0
  280. package/hooks/core/platform-detect.mjs +49 -0
  281. package/hooks/core/routing.mjs +1050 -0
  282. package/hooks/core/stdin.mjs +90 -0
  283. package/hooks/core/tool-naming.mjs +57 -0
  284. package/hooks/cursor/afteragentresponse.mjs +74 -0
  285. package/hooks/cursor/hooks.json +31 -0
  286. package/hooks/cursor/posttooluse.mjs +72 -0
  287. package/hooks/cursor/pretooluse.mjs +26 -0
  288. package/hooks/cursor/sessionstart.mjs +97 -0
  289. package/hooks/cursor/stop.mjs +48 -0
  290. package/hooks/ensure-deps.mjs +254 -0
  291. package/hooks/formatters/claude-code.mjs +113 -0
  292. package/hooks/formatters/cursor.mjs +37 -0
  293. package/hooks/formatters/gemini-cli.mjs +55 -0
  294. package/hooks/formatters/vscode-copilot.mjs +55 -0
  295. package/hooks/gemini-cli/aftermodel.mjs +70 -0
  296. package/hooks/gemini-cli/aftertool.mjs +61 -0
  297. package/hooks/gemini-cli/beforeagent.mjs +99 -0
  298. package/hooks/gemini-cli/beforetool.mjs +27 -0
  299. package/hooks/gemini-cli/precompress.mjs +55 -0
  300. package/hooks/gemini-cli/sessionstart.mjs +137 -0
  301. package/hooks/heal-partial-install.mjs +712 -0
  302. package/hooks/hooks.json +143 -0
  303. package/hooks/jetbrains-copilot/posttooluse.mjs +61 -0
  304. package/hooks/jetbrains-copilot/precompact.mjs +55 -0
  305. package/hooks/jetbrains-copilot/pretooluse.mjs +27 -0
  306. package/hooks/jetbrains-copilot/sessionstart.mjs +124 -0
  307. package/hooks/kimi/platform.mjs +1 -0
  308. package/hooks/kimi/posttooluse.mjs +72 -0
  309. package/hooks/kimi/precompact.mjs +80 -0
  310. package/hooks/kimi/pretooluse.mjs +42 -0
  311. package/hooks/kimi/sessionend.mjs +61 -0
  312. package/hooks/kimi/sessionstart.mjs +113 -0
  313. package/hooks/kimi/stop.mjs +132 -0
  314. package/hooks/kimi/userpromptsubmit.mjs +90 -0
  315. package/hooks/kiro/agentspawn.mjs +97 -0
  316. package/hooks/kiro/posttooluse.mjs +51 -0
  317. package/hooks/kiro/pretooluse.mjs +64 -0
  318. package/hooks/kiro/userpromptsubmit.mjs +88 -0
  319. package/hooks/normalize-hooks.mjs +323 -0
  320. package/hooks/platform-bridge.mjs +340 -0
  321. package/hooks/posttooluse.mjs +225 -0
  322. package/hooks/precompact.mjs +100 -0
  323. package/hooks/pretooluse.mjs +227 -0
  324. package/hooks/qwen-code/platform.mjs +1 -0
  325. package/hooks/qwen-code/stop.mjs +168 -0
  326. package/hooks/routing-block.mjs +105 -0
  327. package/hooks/run-hook.mjs +95 -0
  328. package/hooks/security.bundle.mjs +2 -0
  329. package/hooks/session-attribution.bundle.mjs +1 -0
  330. package/hooks/session-db.bundle.mjs +145 -0
  331. package/hooks/session-directive.mjs +520 -0
  332. package/hooks/session-extract.bundle.mjs +3 -0
  333. package/hooks/session-helpers.mjs +428 -0
  334. package/hooks/session-loaders.mjs +448 -0
  335. package/hooks/session-snapshot.bundle.mjs +32 -0
  336. package/hooks/sessionstart.mjs +464 -0
  337. package/hooks/stop.mjs +82 -0
  338. package/hooks/suppress-stderr.mjs +25 -0
  339. package/hooks/userpromptsubmit.mjs +108 -0
  340. package/hooks/vscode-copilot/posttooluse.mjs +61 -0
  341. package/hooks/vscode-copilot/precompact.mjs +55 -0
  342. package/hooks/vscode-copilot/pretooluse.mjs +27 -0
  343. package/hooks/vscode-copilot/sessionstart.mjs +129 -0
  344. package/openclaw.plugin.json +38 -0
  345. package/package.json +132 -0
  346. package/scripts/heal-better-sqlite3.mjs +430 -0
  347. package/scripts/heal-installed-plugins.mjs +635 -0
  348. package/scripts/plugin-cache-integrity.mjs +248 -0
  349. package/scripts/postinstall.mjs +397 -0
  350. package/server.bundle.mjs +1421 -0
  351. package/server.js +5 -0
  352. package/skills/.ignore +7 -0
  353. package/skills/context-mode/SKILL.md +300 -0
  354. package/skills/context-mode/references/anti-patterns.md +283 -0
  355. package/skills/context-mode/references/patterns-javascript.md +298 -0
  356. package/skills/context-mode/references/patterns-python.md +304 -0
  357. package/skills/context-mode/references/patterns-shell.md +277 -0
  358. package/skills/ctx-doctor/SKILL.md +22 -0
  359. package/skills/ctx-index/SKILL.md +46 -0
  360. package/skills/ctx-insight/SKILL.md +24 -0
  361. package/skills/ctx-purge/SKILL.md +49 -0
  362. package/skills/ctx-search/SKILL.md +35 -0
  363. package/skills/ctx-stats/SKILL.md +26 -0
  364. package/skills/ctx-upgrade/SKILL.md +31 -0
  365. package/start.mjs +616 -0
package/start.mjs ADDED
@@ -0,0 +1,616 @@
1
+ #!/usr/bin/env node
2
+ import { execSync, spawn } from "node:child_process";
3
+ import { existsSync, chmodSync, readFileSync, writeFileSync, readdirSync, symlinkSync, mkdirSync, lstatSync, unlinkSync } from "node:fs";
4
+ import { dirname, resolve, join, sep } from "node:path";
5
+ import { fileURLToPath } from "node:url";
6
+ import { homedir } from "node:os";
7
+
8
+ const __dirname = dirname(fileURLToPath(import.meta.url));
9
+ const originalCwd = process.cwd();
10
+ process.chdir(__dirname);
11
+
12
+ // Resolve the Claude Code config dir, honoring $CLAUDE_CONFIG_DIR (incl. leading ~).
13
+ // Mirrors hooks/session-helpers.mjs::resolveConfigDir and hooks/run-hook.mjs (#453).
14
+ // Inlined here because start.mjs runs before any other module loads — we cannot
15
+ // dynamic-import session-helpers without circularity through the bundle path.
16
+ // Fix for #577: cache-heal layer below was hardcoding ~/.claude regardless of
17
+ // the env var, silently no-op'ing for users with a non-default config dir AND
18
+ // creating an unwanted ~/.claude/ directory on disk.
19
+ function resolveClaudeConfigDir() {
20
+ const envVal = process.env.CLAUDE_CONFIG_DIR;
21
+ if (envVal && envVal.trim() !== "") {
22
+ if (envVal.startsWith("~")) {
23
+ return resolve(homedir(), envVal.replace(/^~[/\\]?/, ""));
24
+ }
25
+ return resolve(envVal);
26
+ }
27
+ return resolve(homedir(), ".claude");
28
+ }
29
+
30
+ // Plugin-install-path guard (mirror of src/util/project-dir.ts isPluginInstallPath
31
+ // — duplicated here because start.mjs ships as raw JS and cannot import TS).
32
+ // When Claude Code runs `/ctx-upgrade` it kills + respawns the MCP server with
33
+ // `cwd` pointing at the plugin install dir. Setting CLAUDE_PROJECT_DIR from
34
+ // that path then poisons every downstream ctx_stats / SessionDB / hash
35
+ // computation — sessions silently re-root under the plugin install dir. Skip
36
+ // the env auto-set in that case; getProjectDir() defends a second time inside
37
+ // server.ts via resolveProjectDir(). See src/util/project-dir.ts.
38
+ const isPluginInstallPath = (p) =>
39
+ /[/\\]\.(claude|codex)[/\\]plugins[/\\](cache|marketplaces)[/\\]/.test(p);
40
+ const safeOriginalCwd = isPluginInstallPath(originalCwd) ? null : originalCwd;
41
+
42
+ if (!process.env.CLAUDE_PROJECT_DIR && safeOriginalCwd) {
43
+ process.env.CLAUDE_PROJECT_DIR = safeOriginalCwd;
44
+ }
45
+
46
+ // Platform-agnostic project dir — guaranteed to be set for ALL platforms.
47
+ // Adapters may set their own env var (GEMINI_PROJECT_DIR, etc.) but this
48
+ // is the universal fallback so server.ts getProjectDir() never relies on cwd().
49
+ if (!process.env.CONTEXT_MODE_PROJECT_DIR && safeOriginalCwd) {
50
+ process.env.CONTEXT_MODE_PROJECT_DIR = safeOriginalCwd;
51
+ }
52
+
53
+ // Routing instructions file auto-write DISABLED for all platforms (#158, #164).
54
+ // Env vars like CLAUDE_SESSION_ID may not be set at MCP startup time, making
55
+ // the hook-capability guard unreliable. Writing to project dirs dirties git trees
56
+ // and causes double context injection on hook-capable platforms.
57
+ // Routing is handled by:
58
+ // - Hook-capable platforms: SessionStart hook injects ROUTING_BLOCK
59
+ // - Non-hook platforms: server.ts writeRoutingInstructions() on MCP connect
60
+ // - Future: explicit `context-mode init` command
61
+
62
+ // ── Linux: re-exec with Bun to avoid better-sqlite3 SIGSEGV (#564) ──
63
+ // server.bundle.mjs has two SQLite paths: bun:sqlite (safe) or better-sqlite3
64
+ // (SIGSEGV on Linux under Node's V8). When invoked via node on Linux, detect
65
+ // a Bun installation and re-exec this file under Bun so the bundle takes the
66
+ // safe path. No-op when already running under Bun or on non-Linux platforms.
67
+ if (typeof globalThis.Bun === "undefined" && process.platform === "linux") {
68
+ const bunCandidates = [
69
+ process.env.BUN_INSTALL ? join(process.env.BUN_INSTALL, "bin", "bun") : null,
70
+ join(homedir(), ".bun", "bin", "bun"),
71
+ "/usr/local/bin/bun",
72
+ "/usr/bin/bun",
73
+ ].filter(Boolean);
74
+ const bunBin = bunCandidates.find((p) => existsSync(p));
75
+ if (bunBin) {
76
+ const child = spawn(bunBin, [fileURLToPath(import.meta.url)], {
77
+ stdio: ["pipe", "inherit", "inherit"],
78
+ env: process.env,
79
+ });
80
+ const _keepAlive = setInterval(() => {}, 2147483647);
81
+ let _escTerm;
82
+ let _escKill;
83
+ let _tearingDown = false;
84
+ // #862: propagate parent death to the Bun child. When the MCP client (e.g.
85
+ // Claude Code) exits, its end of our stdin pipe closes. The original proxy
86
+ // ignored that ("end" was a no-op) and parked forever — so the child was
87
+ // never told the session was gone: its stdin (this pipe) stayed open and its
88
+ // direct parent (us) stayed alive, defeating BOTH paths of the child's
89
+ // lifecycle guard (the stdio-EOF assist AND the ppid poll). The pair
90
+ // orphaned to init and pinned a CPU core indefinitely. We now forward EOF
91
+ // (graceful self-reap via the child's own watchdog), then escalate
92
+ // SIGTERM → SIGKILL so a wedged child can never outlive its client. Still
93
+ // re-execs under Bun first, so #564's SIGSEGV avoidance is untouched.
94
+ const teardown = () => {
95
+ if (_tearingDown) return;
96
+ _tearingDown = true;
97
+ clearInterval(_keepAlive);
98
+ try {
99
+ if (child.stdin && !child.stdin.destroyed) child.stdin.end();
100
+ } catch {}
101
+ // NOT unref'd: these short-lived timers are what hold the event loop
102
+ // open through the teardown window (≤5 s). Liveness must not depend on
103
+ // the top-level `await new Promise()` below surviving a future refactor
104
+ // — if escalation is ever skipped, #862's orphan returns. child.on(
105
+ // "exit") clears both the instant the child reaps cleanly.
106
+ _escTerm = setTimeout(() => {
107
+ try {
108
+ child.kill("SIGTERM");
109
+ } catch {}
110
+ }, 2000);
111
+ _escKill = setTimeout(() => {
112
+ try {
113
+ child.kill("SIGKILL");
114
+ } catch {}
115
+ process.exit(0);
116
+ }, 5000);
117
+ };
118
+ process.stdin.on("data", (chunk) => {
119
+ if (!child.stdin.destroyed) child.stdin.write(chunk);
120
+ });
121
+ // EOF, pipe close, or pipe error all mean the client is gone — tear down.
122
+ process.stdin.on("end", teardown);
123
+ process.stdin.on("close", teardown);
124
+ process.stdin.on("error", teardown);
125
+ child.on("exit", (code) => {
126
+ clearInterval(_keepAlive);
127
+ if (_escTerm) clearTimeout(_escTerm);
128
+ if (_escKill) clearTimeout(_escKill);
129
+ process.exit(code ?? 0);
130
+ });
131
+ // Prevent rest of start.mjs from running — child owns the MCP session.
132
+ process.stdin.resume();
133
+ await new Promise(() => {}); // park until the child exits (see child 'exit')
134
+ }
135
+ }
136
+
137
+ // ── Self-heal Layer 1: Fix registry → symlink mismatches (anthropics/claude-code#46915) ──
138
+ // Claude Code auto-update can leave installed_plugins.json pointing to a non-existent
139
+ // directory. We detect this and create symlinks so hooks find the right path.
140
+ const cacheMatch = __dirname.match(
141
+ /^(.*[\/\\]plugins[\/\\]cache[\/\\][^\/\\]+[\/\\][^\/\\]+[\/\\])([^\/\\]+)$/,
142
+ );
143
+ if (cacheMatch) {
144
+ try {
145
+ const cacheParent = cacheMatch[1];
146
+ const myVersion = cacheMatch[2];
147
+ const claudeConfigDir = resolveClaudeConfigDir();
148
+ const ipPath = resolve(claudeConfigDir, "plugins", "installed_plugins.json");
149
+
150
+ // Forward heal: if a newer version dir exists, update registry
151
+ const dirs = readdirSync(cacheParent).filter((d) =>
152
+ /^\d+\.\d+\.\d+/.test(d),
153
+ );
154
+ if (dirs.length > 1) {
155
+ dirs.sort((a, b) => {
156
+ const pa = a.split(".").map(Number);
157
+ const pb = b.split(".").map(Number);
158
+ for (let i = 0; i < 3; i++) {
159
+ if ((pa[i] ?? 0) !== (pb[i] ?? 0))
160
+ return (pa[i] ?? 0) - (pb[i] ?? 0);
161
+ }
162
+ return 0;
163
+ });
164
+ const newest = dirs[dirs.length - 1];
165
+ if (newest && newest !== myVersion) {
166
+ // Issue #727: normalize hooks.json + plugin.json in the newest version
167
+ // dir BEFORE updating the registry. CC's auto-update carries forward
168
+ // files from the old cache dir, including hooks.json and plugin.json
169
+ // with absolute paths baked to the old version. start.mjs's Self-heal
170
+ // Layer 5 would catch this, but plugin.json's stale mcpServers path
171
+ // prevents the new start.mjs from ever booting — chicken-and-egg.
172
+ // Fix: normalize from HERE (the old start.mjs that CC CAN still launch)
173
+ // so the new dir's files are correct before the next session reads them.
174
+ const newestDir = resolve(cacheParent, newest);
175
+ try {
176
+ // #713: use narrow helper — wide normalizeHooksOnStartup would
177
+ // write plugin.json on the NEW cache dir, the exact #711 poison
178
+ // vector. Only hooks.json needs the placeholder→absolute rewrite
179
+ // pre-bump to close the first-hook-fire window.
180
+ const { normalizeHooksJsonOnly } = await import("./hooks/normalize-hooks.mjs");
181
+ normalizeHooksJsonOnly({
182
+ pluginRoot: newestDir,
183
+ nodePath: process.execPath,
184
+ platform: process.platform,
185
+ });
186
+ } catch { /* best effort — never block startup */ }
187
+
188
+ const ip = JSON.parse(readFileSync(ipPath, "utf-8"));
189
+ for (const [key, entries] of Object.entries(ip.plugins || {})) {
190
+ if (key !== "context-mode@@mxalbert/context-mode") continue;
191
+ for (const entry of entries) {
192
+ entry.installPath = newestDir;
193
+ entry.version = newest;
194
+ entry.lastUpdated = new Date().toISOString();
195
+ }
196
+ }
197
+ writeFileSync(ipPath, JSON.stringify(ip, null, 2) + "\n", "utf-8");
198
+ }
199
+ }
200
+
201
+ // Reverse heal: if registry points to non-existent dir, create symlink to us
202
+ const cacheRoot = resolve(claudeConfigDir, "plugins", "cache");
203
+ if (existsSync(ipPath)) {
204
+ const ip = JSON.parse(readFileSync(ipPath, "utf-8"));
205
+ for (const [key, entries] of Object.entries(ip.plugins || {})) {
206
+ if (key !== "context-mode@@mxalbert/context-mode") continue;
207
+ for (const entry of entries) {
208
+ const rp = entry.installPath;
209
+ if (!rp || existsSync(rp) || rp === __dirname) continue;
210
+ // Path traversal guard: only allow paths inside plugin cache
211
+ if (!resolve(rp).startsWith(cacheRoot + sep)) continue;
212
+ try {
213
+ // Remove dangling symlink before creating new one
214
+ try { if (lstatSync(rp).isSymbolicLink()) unlinkSync(rp); } catch {}
215
+ const rpParent = dirname(rp);
216
+ if (!existsSync(rpParent)) mkdirSync(rpParent, { recursive: true });
217
+ symlinkSync(__dirname, rp, process.platform === "win32" ? "junction" : undefined);
218
+ } catch { /* best effort */ }
219
+ }
220
+ }
221
+ }
222
+ } catch {
223
+ /* best effort — don't block server startup */
224
+ }
225
+ }
226
+
227
+ // ── Self-heal Layer 3 + 4: installed_plugins.json registry repair ──
228
+ // v1.0.113 hotfix follow-up. /ctx-upgrade can leave installed_plugins.json
229
+ // with two distinct kinds of poison:
230
+ // HEAL 3: per-entry `version` drifts away from the actual cache dir's
231
+ // plugin.json `version` field. Claude Code's plugin loader then
232
+ // rejects the entry as a manifest mismatch and silently
233
+ // disconnects context-mode.
234
+ // HEAL 4: top-level `enabledPlugins[<key>]` is missing or emptied.
235
+ // Claude Code skips disabled plugins, so MCP never starts and
236
+ // the user has no /ctx-upgrade escape hatch.
237
+ // Logic is shared verbatim with scripts/postinstall.mjs (single source of
238
+ // truth) so users who fix themselves via `npm install -g @mxalbert/context-mode`
239
+ // follow the exact same code path. Best-effort, never blocks MCP boot.
240
+ try {
241
+ const { healInstalledPlugins, healSettingsEnabledPlugins, healPluginJsonMcpServers, sweepStaleMcpJson } =
242
+ await import("./scripts/heal-installed-plugins.mjs");
243
+ const pluginKey = "context-mode@@mxalbert/context-mode";
244
+ const claudeConfigDir = resolveClaudeConfigDir();
245
+ const registryPath = resolve(claudeConfigDir, "plugins", "installed_plugins.json");
246
+ const pluginCacheRoot = resolve(claudeConfigDir, "plugins", "cache");
247
+ const settingsPath = resolve(claudeConfigDir, "settings.json");
248
+ try { healInstalledPlugins({ registryPath, pluginCacheRoot, pluginKey }); }
249
+ catch { /* best effort */ }
250
+ // v1.0.116: Claude Code's plugin loader reads settings.json.enabledPlugins
251
+ // (NOT installed_plugins.json) — heal that one too so /ctx-upgrade-induced
252
+ // disable state is repaired before next /reload-plugins.
253
+ try { healSettingsEnabledPlugins({ settingsPath, pluginKey }); }
254
+ catch { /* best effort */ }
255
+ // v1.0.119 — Layer 5b (Issue #523): heal .claude-plugin/plugin.json's
256
+ // mcpServers["context-mode"].args[0] when /ctx-upgrade left a tmpdir-prefixed
257
+ // path baked in. Iterates EVERY installed cache entry's installPath so
258
+ // multi-version installs all self-recover. Each call is independently wrapped
259
+ // because one poisoned entry must not block heals on the others. Best effort.
260
+ try {
261
+ if (existsSync(registryPath)) {
262
+ const ip = JSON.parse(readFileSync(registryPath, "utf-8"));
263
+ const entries = (ip && ip.plugins && ip.plugins[pluginKey]) || [];
264
+ if (Array.isArray(entries)) {
265
+ for (const entry of entries) {
266
+ const installPath = entry && entry.installPath;
267
+ if (typeof installPath !== "string" || !installPath) continue;
268
+ try {
269
+ healPluginJsonMcpServers({
270
+ pluginRoot: installPath,
271
+ pluginCacheRoot,
272
+ pluginKey,
273
+ });
274
+ } catch { /* best effort — per-entry */ }
275
+ }
276
+ }
277
+ }
278
+ } catch { /* best effort */ }
279
+ // Issue #609 — Layer 5c (replaces v1.0.122 healMcpJsonArgs per-entry loop):
280
+ // sweep stale `.mcp.json` files from every per-version cache dir. cli.ts
281
+ // no longer writes `.mcp.json` (PR fix for #609), so the only `.mcp.json`
282
+ // files in the cache are stale carry-forwards from earlier installs or
283
+ // Claude Code's plugin manager copying them between version dirs. Removing
284
+ // them blocks the previous-version-carry replay vector at MCP boot.
285
+ // One sweep per boot — bounded, idempotent, best-effort.
286
+ try {
287
+ sweepStaleMcpJson({ pluginCacheRoot, pluginKey });
288
+ } catch { /* best effort */ }
289
+ } catch { /* best effort — never block MCP boot */ }
290
+
291
+ // ── Self-heal Layer 4: Deploy global SessionStart hook + register in settings.json ──
292
+ // This hook lives outside the plugin directory (~/.claude/hooks/) so it works
293
+ // even when the plugin cache is completely broken. It creates symlinks for any
294
+ // missing plugin cache directories on every session start.
295
+ // Pure Node.js — no bash dependency. Works on Windows, macOS (SIP), Linux.
296
+ //
297
+ // Brew node upgrade resilience:
298
+ // - On Unix we register the hook command as the bare script path. The script
299
+ // itself carries `#!/usr/bin/env node`, so `env` resolves node from PATH at
300
+ // runtime. This survives Brew/asdf/nvm upgrades that move node binaries.
301
+ // - On Windows there is no shebang; we fall back to "<execPath>" "<scriptPath>".
302
+ // - On every boot we self-heal stale "/opt/homebrew/Cellar/node/<ver>/..." paths
303
+ // left behind by older versions of this code.
304
+ try {
305
+ const { buildHookCommand, selfHealCacheHealHook, ensureShebangAndExecBit } =
306
+ await import("./hooks/cache-heal-utils.mjs");
307
+
308
+ // #577: honor $CLAUDE_CONFIG_DIR — without this, Claude Code spawns hooks
309
+ // from $CLAUDE_CONFIG_DIR/settings.json but we deploy them to ~/.claude/hooks/
310
+ // and register them in ~/.claude/settings.json. The mismatch silently
311
+ // disables the heal AND creates an unwanted ~/.claude directory.
312
+ const claudeConfigDir = resolveClaudeConfigDir();
313
+ const globalHooksDir = resolve(claudeConfigDir, "hooks");
314
+ const healHookPath = resolve(globalHooksDir, "context-mode-cache-heal.mjs");
315
+ // Clean up old bash version if it exists
316
+ const oldBashHook = resolve(globalHooksDir, "context-mode-cache-heal.sh");
317
+ if (existsSync(oldBashHook)) {
318
+ try { unlinkSync(oldBashHook); } catch {}
319
+ }
320
+ if (!existsSync(globalHooksDir)) mkdirSync(globalHooksDir, { recursive: true });
321
+ const healScript = `#!/usr/bin/env node
322
+ // context-mode plugin cache self-heal (auto-deployed)
323
+ // Fixes anthropics/claude-code#46915: auto-update breaks CLAUDE_PLUGIN_ROOT
324
+ // Issue #727: also normalizes stale version paths in existing installPaths
325
+ // Honors CLAUDE_CONFIG_DIR (#577) — checked at this script's runtime so users
326
+ // who set CLAUDE_CONFIG_DIR after install still get healed correctly.
327
+ // Pure Node.js — no bash/shell dependency.
328
+ import{existsSync,readdirSync,statSync,symlinkSync,lstatSync,unlinkSync,readFileSync}from"node:fs";
329
+ import{dirname,join,resolve,sep}from"node:path";
330
+ import{homedir}from"node:os";
331
+ function cfgDir(){const e=process.env.CLAUDE_CONFIG_DIR;if(e&&e.trim()!==""){return e.startsWith("~")?resolve(homedir(),e.replace(/^~[/\\\\]?/,"")):resolve(e)}return resolve(homedir(),".claude")}
332
+ try{
333
+ const f=resolve(cfgDir(),"plugins","installed_plugins.json");
334
+ if(!existsSync(f))process.exit(0);
335
+ const cacheRoot=resolve(cfgDir(),"plugins","cache");
336
+ const ip=JSON.parse(readFileSync(f,"utf-8"));
337
+ for(const[k,es]of Object.entries(ip.plugins||{})){
338
+ if(k!=="context-mode@@mxalbert/context-mode")continue;
339
+ for(const e of es){
340
+ const p=e.installPath;
341
+ if(!p)continue;
342
+ if(!resolve(p).startsWith(cacheRoot+sep))continue;
343
+ if(existsSync(p)){
344
+ // Issue #727: normalize stale version paths in existing installPaths.
345
+ // CC's auto-update can carry forward hooks.json/plugin.json with paths
346
+ // baked to a previous version dir. Import normalize-hooks from the
347
+ // installPath itself and let it detect + rewrite stale segments.
348
+ try{
349
+ // #713: narrow helper only — installPath belongs to a different
350
+ // version's cache dir; writing plugin.json there is the #711 vector.
351
+ const nhPath=join(p,"hooks","normalize-hooks.mjs");
352
+ if(existsSync(nhPath)){
353
+ const mod=await import(nhPath);
354
+ const fn=mod.normalizeHooksJsonOnly||mod.normalizeHooksOnStartup;
355
+ if(fn)fn({pluginRoot:p,nodePath:process.execPath,platform:process.platform});
356
+ }
357
+ }catch{}
358
+ continue;
359
+ }
360
+ const parent=dirname(p);
361
+ if(!existsSync(parent))continue;
362
+ try{if(lstatSync(p).isSymbolicLink())unlinkSync(p)}catch{}
363
+ const dirs=readdirSync(parent).filter(d=>/^\\d+\\.\\d+/.test(d)&&statSync(join(parent,d)).isDirectory());
364
+ if(!dirs.length)continue;
365
+ dirs.sort((a,b)=>{const pa=a.split(".").map(Number),pb=b.split(".").map(Number);for(let i=0;i<3;i++){if((pa[i]||0)!==(pb[i]||0))return(pa[i]||0)-(pb[i]||0)}return 0});
366
+ try{symlinkSync(join(parent,dirs[dirs.length-1]),p,process.platform==="win32"?"junction":undefined)}catch{}
367
+ }
368
+ }
369
+ }catch{}
370
+ `;
371
+ // Deploy or update the heal hook when content changes (not just when missing).
372
+ // Allows new heal logic (e.g. #727 path normalization) to propagate on next boot.
373
+ let needsWrite = !existsSync(healHookPath);
374
+ if (!needsWrite) {
375
+ try { needsWrite = readFileSync(healHookPath, "utf-8") !== healScript; } catch { needsWrite = true; }
376
+ }
377
+ if (needsWrite) {
378
+ writeFileSync(healHookPath, healScript, { mode: 0o755 });
379
+ }
380
+
381
+ // Always re-assert shebang + chmod +x on Unix so the bare-script hook
382
+ // command is spawnable even if the file was created without exec bit.
383
+ if (process.platform !== "win32") {
384
+ try { ensureShebangAndExecBit(healHookPath); } catch { /* best effort */ }
385
+ }
386
+
387
+ // Register the hook in $CLAUDE_CONFIG_DIR/settings.json (Claude Code doesn't auto-discover hook files).
388
+ // #577: must follow the same dir resolution as globalHooksDir above.
389
+ const settingsPath = resolve(claudeConfigDir, "settings.json");
390
+ if (existsSync(settingsPath)) {
391
+ const settings = JSON.parse(readFileSync(settingsPath, "utf-8"));
392
+ const hooks = settings.hooks ?? {};
393
+ const sessionStart = hooks.SessionStart ?? [];
394
+ const alreadyRegistered = sessionStart.some((h) =>
395
+ h.hooks?.some((hh) => hh.command?.includes("context-mode-cache-heal")),
396
+ );
397
+ if (!alreadyRegistered) {
398
+ sessionStart.push({
399
+ hooks: [
400
+ {
401
+ type: "command",
402
+ command: buildHookCommand({
403
+ scriptPath: healHookPath,
404
+ platform: process.platform,
405
+ nodePath: process.execPath,
406
+ }),
407
+ },
408
+ ],
409
+ });
410
+ hooks.SessionStart = sessionStart;
411
+ settings.hooks = hooks;
412
+ writeFileSync(settingsPath, JSON.stringify(settings, null, 2) + "\n", "utf-8");
413
+ }
414
+
415
+ // Self-heal: rewrite an existing cache-heal hook command if it points at
416
+ // a node binary that no longer exists (Brew node upgrade scenario).
417
+ try {
418
+ selfHealCacheHealHook({
419
+ settingsPath,
420
+ scriptPath: healHookPath,
421
+ platform: process.platform,
422
+ nodePath: process.execPath,
423
+ });
424
+ } catch { /* best effort */ }
425
+ }
426
+ } catch { /* best effort */ }
427
+
428
+ // ── Self-heal Layer 5: Windows hooks.json + plugin.json normalization (#378) ──
429
+ // Static committed files use ${CLAUDE_PLUGIN_ROOT} placeholder + bare `node`.
430
+ // On Windows + Claude Code this hits cjs/loader:1479 because:
431
+ // 1. bare `node` may not resolve via PATH (Git Bash, see #369)
432
+ // 2. ${CLAUDE_PLUGIN_ROOT} can hit MSYS path mangling (#372)
433
+ // 3. backslash paths corrupt under shell quoting
434
+ // Rewrites placeholders to absolute paths using process.execPath (Datadog
435
+ // model). Idempotent — only writes when needed. Survives upgrades because
436
+ // it runs at every MCP boot.
437
+ //
438
+ // Skip under vitest: server.test.ts spawns this script from the repo root,
439
+ // and a mutated .claude-plugin/plugin.json poisons sibling tests that read
440
+ // the file (cli.test.ts). VITEST is inherited by spawned subprocesses.
441
+ if (!process.env.VITEST) {
442
+ try {
443
+ const { normalizeHooksOnStartup } = await import("./hooks/normalize-hooks.mjs");
444
+ // #738: probe for Bun ≥1.0 and pass the resolved path so the static
445
+ // hooks/hooks.json rewrite swaps `node` → `bun` (~40-60ms cold-start win
446
+ // per hook). Probe is wrapped in its own try so resolveHookRuntime
447
+ // failures (missing build, missing module) never block boot.
448
+ let jsRuntimePath;
449
+ try {
450
+ const { resolveHookRuntime } = await import("./build/runtime.js");
451
+ const r = resolveHookRuntime();
452
+ if (r.isBun) jsRuntimePath = r.path;
453
+ } catch { /* best effort — fall through to nodePath default */ }
454
+ normalizeHooksOnStartup({
455
+ pluginRoot: __dirname,
456
+ nodePath: process.execPath,
457
+ jsRuntimePath,
458
+ platform: process.platform,
459
+ });
460
+ } catch { /* best effort — never block server startup */ }
461
+ }
462
+
463
+ // Ensure native dependencies + ABI compatibility (shared with hooks via ensure-deps.mjs)
464
+ // ensure-deps handles better-sqlite3 install + ABI cache/rebuild automatically (#148, #203)
465
+ import "./hooks/ensure-deps.mjs";
466
+ // Pure-JS runtime deps used only by `ctx_fetch_and_index` (HTML → Markdown
467
+ // pipeline runs in a sandboxed subprocess that `require.resolve()`s these at
468
+ // call time). Plugin distributions that bypass `npm install` — most notably
469
+ // codex's marketplace, which git-clones into `~/.codex/plugins/cache/<pkg>/`
470
+ // without installing dependencies — land here with no `node_modules/`.
471
+ //
472
+ // Before #634: synchronous `execSync("npm install …")` per package
473
+ // (turndown + turndown-plugin-gfm + @mixmark-io/domino) blocked MCP boot
474
+ // for ~15–25s cold. Codex's per-MCP `startup_timeout_sec` is 30s, so on
475
+ // any host where its prewarm + DNS already eats a few seconds the timer
476
+ // fires before context-mode replies to `initialize` and the MCP child is
477
+ // dropped with "MCP client for `context-mode` timed out after 30 seconds".
478
+ //
479
+ // Fix: spawn each `npm install` detached + unref'd so it runs in the
480
+ // background while the MCP server proceeds with its handshake. The deps
481
+ // land asynchronously, well before any LLM-driven `ctx_fetch_and_index`
482
+ // call can plausibly fire. If a user invokes that tool faster than the
483
+ // install completes, the subprocess's own `require.resolve("turndown")`
484
+ // failure surfaces a typed error to the caller — same posture as any
485
+ // other missing-runtime-dep situation in that code path.
486
+ {
487
+ const NPM_INSTALL_BG_PKGS = ["turndown", "turndown-plugin-gfm", "@mixmark-io/domino"];
488
+ const IS_WIN32 = process.platform === "win32";
489
+ const NPM_BIN = IS_WIN32 ? "npm.cmd" : "npm";
490
+ const NPM_FLAGS = ["--no-package-lock", "--no-save", "--silent", "--no-audit", "--no-fund"];
491
+ // #861: on Windows the npm shim is `npm.cmd`, which needs `shell: true` to
492
+ // run — but Node DROPS the `cwd` option when `shell: true`, so the spawned
493
+ // cmd.exe inherits an arbitrary working dir (C:\Windows under Claude Code).
494
+ // `npm install` then tries to create `C:\Windows\node_modules` → EPERM on
495
+ // every boot, and a cmd.exe window flashes each time. Prefer running npm's
496
+ // own CLI through node directly (no `.cmd` shim, no shell): `shell: false`
497
+ // honors `cwd` and `windowsHide` suppresses the console window. Fall back to
498
+ // the shim only when npm-cli.js can't be located, so a working host (e.g. a
499
+ // POSIX layout where npm-cli.js isn't beside node) can never regress.
500
+ const NPM_CLI_JS = resolve(dirname(process.execPath), "node_modules", "npm", "bin", "npm-cli.js");
501
+ const useNodeCli = existsSync(NPM_CLI_JS);
502
+ for (const pkg of NPM_INSTALL_BG_PKGS) {
503
+ if (existsSync(resolve(__dirname, "node_modules", pkg))) continue;
504
+ try {
505
+ const child = useNodeCli
506
+ ? spawn(process.execPath, [NPM_CLI_JS, "install", pkg, ...NPM_FLAGS], {
507
+ cwd: __dirname,
508
+ stdio: "ignore",
509
+ detached: true,
510
+ shell: false,
511
+ windowsHide: true,
512
+ })
513
+ : spawn(NPM_BIN, ["install", pkg, ...NPM_FLAGS], {
514
+ cwd: __dirname,
515
+ stdio: "ignore",
516
+ detached: true,
517
+ // npm on Windows ships as a `.cmd` shim — must go through cmd.exe.
518
+ shell: IS_WIN32,
519
+ windowsHide: true,
520
+ });
521
+ // #861: this EPERM was invisible for months behind stdio:"ignore" + an
522
+ // empty error handler. Surface both spawn failures and non-zero exits.
523
+ child.on("error", (err) => {
524
+ process.stderr.write(
525
+ `[context-mode] background install of ${pkg} failed to spawn: ${err?.message ?? err}\n`,
526
+ );
527
+ });
528
+ child.on("exit", (code) => {
529
+ if (code) {
530
+ process.stderr.write(
531
+ `[context-mode] background install of ${pkg} exited with code ${code}\n`,
532
+ );
533
+ }
534
+ });
535
+ child.unref();
536
+ } catch { /* best effort — never block MCP boot */ }
537
+ }
538
+ }
539
+
540
+ // Self-heal: create CLI shim if cli.bundle.mjs is missing (marketplace installs)
541
+ if (!existsSync(resolve(__dirname, "cli.bundle.mjs")) && existsSync(resolve(__dirname, "build", "cli.js"))) {
542
+ const shimPath = resolve(__dirname, "cli.bundle.mjs");
543
+ writeFileSync(shimPath, '#!/usr/bin/env node\nawait import("./build/cli.js");\n');
544
+ if (process.platform !== "win32") chmodSync(shimPath, 0o755);
545
+ }
546
+
547
+ // ── Self-heal partial install from marketplace clone ──
548
+ // Runs BEFORE the Algo-D4 integrity check so a fixable partial install
549
+ // gets repaired rather than just reported. Best-effort and idempotent;
550
+ // the integrity check below remains the authoritative gate that decides
551
+ // whether boot proceeds. See hooks/heal-partial-install.mjs for the
552
+ // failure-mode description and module contract.
553
+ if (!process.env.VITEST) {
554
+ try {
555
+ const { healPartialInstallFromMarketplace } = await import(
556
+ "./hooks/heal-partial-install.mjs"
557
+ );
558
+ healPartialInstallFromMarketplace({ pluginRoot: __dirname });
559
+ } catch { /* best effort, never block boot */ }
560
+ }
561
+
562
+ // ── Algo-D4: plugin cache integrity check ──
563
+ // Verify boot-critical siblings exist BEFORE importing server.bundle.mjs.
564
+ // Without this, a partial install (#550) gives an opaque downstream
565
+ // stack trace from `import("./server.bundle.mjs")`. With it, we emit a
566
+ // structured CONTEXT_MODE_PARTIAL_INSTALL stderr block + exit 2 so
567
+ // external monitoring grep + the user both see the actionable signal.
568
+ //
569
+ // Runs AFTER the heal layers above so missing files they can fix
570
+ // (cli.bundle.mjs shim, dangling symlinks, partial-install copy from
571
+ // the marketplace clone) get a chance first. Helper is shared with
572
+ // `ctx doctor` (Algo-D5) — single source of truth so boot + diagnostic
573
+ // agree byte-for-byte. Skipped under VITEST so the repo's own test
574
+ // invocations against in-tree start.mjs don't fail when running before
575
+ // `npm run build` produces the bundles.
576
+ if (!process.env.VITEST) {
577
+ try {
578
+ const { assertPluginCacheIntegrity, formatPartialInstallReport } =
579
+ await import("./scripts/plugin-cache-integrity.mjs");
580
+ const integrity = assertPluginCacheIntegrity({ pluginRoot: __dirname });
581
+ if (!integrity.ok) {
582
+ process.stderr.write(
583
+ formatPartialInstallReport({
584
+ pluginRoot: __dirname,
585
+ missing: integrity.missing,
586
+ }),
587
+ );
588
+ process.exit(2);
589
+ }
590
+ } catch (err) {
591
+ // The helper itself failing is unexpected — keep boot moving rather
592
+ // than blocking on a check infrastructure bug. The downstream
593
+ // import will still surface the actual missing-bundle error.
594
+ if (process.env.CONTEXT_MODE_DEBUG) {
595
+ process.stderr.write(`[start.mjs] integrity check skipped: ${err}\n`);
596
+ }
597
+ }
598
+ }
599
+
600
+ // Bundle exists (CI-built) — start instantly
601
+ if (existsSync(resolve(__dirname, "server.bundle.mjs"))) {
602
+ await import("./server.bundle.mjs");
603
+ } else {
604
+ // Dev or npm install — full build
605
+ if (!existsSync(resolve(__dirname, "node_modules"))) {
606
+ try {
607
+ execSync("npm install --silent", { cwd: __dirname, stdio: "pipe", timeout: 60000 });
608
+ } catch { /* best effort */ }
609
+ }
610
+ if (!existsSync(resolve(__dirname, "build", "server.js"))) {
611
+ try {
612
+ execSync("npx tsc --silent", { cwd: __dirname, stdio: "pipe", timeout: 30000 });
613
+ } catch { /* best effort */ }
614
+ }
615
+ await import("./build/server.js");
616
+ }