opencastle 1.1.0 → 1.2.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 (276) hide show
  1. package/README.md +23 -6
  2. package/bin/cli.mjs +6 -0
  3. package/dist/cli/adapters/codex.d.ts +19 -6
  4. package/dist/cli/adapters/codex.d.ts.map +1 -1
  5. package/dist/cli/adapters/codex.js +24 -7
  6. package/dist/cli/adapters/codex.js.map +1 -1
  7. package/dist/cli/adapters/single-file-base.d.ts +7 -0
  8. package/dist/cli/adapters/single-file-base.d.ts.map +1 -1
  9. package/dist/cli/adapters/single-file-base.js +59 -22
  10. package/dist/cli/adapters/single-file-base.js.map +1 -1
  11. package/dist/cli/agent-plugin.d.ts +119 -0
  12. package/dist/cli/agent-plugin.d.ts.map +1 -0
  13. package/dist/cli/agent-plugin.js +449 -0
  14. package/dist/cli/agent-plugin.js.map +1 -0
  15. package/dist/cli/agent-plugin.test.d.ts +2 -0
  16. package/dist/cli/agent-plugin.test.d.ts.map +1 -0
  17. package/dist/cli/agent-plugin.test.js +227 -0
  18. package/dist/cli/agent-plugin.test.js.map +1 -0
  19. package/dist/cli/baseline.d.ts.map +1 -1
  20. package/dist/cli/baseline.js +99 -26
  21. package/dist/cli/baseline.js.map +1 -1
  22. package/dist/cli/codex-target.test.d.ts +2 -0
  23. package/dist/cli/codex-target.test.d.ts.map +1 -0
  24. package/dist/cli/codex-target.test.js +154 -0
  25. package/dist/cli/codex-target.test.js.map +1 -0
  26. package/dist/cli/convoy/gates.d.ts +2 -20
  27. package/dist/cli/convoy/gates.d.ts.map +1 -1
  28. package/dist/cli/convoy/gates.js +3 -111
  29. package/dist/cli/convoy/gates.js.map +1 -1
  30. package/dist/cli/copy.d.ts +0 -8
  31. package/dist/cli/copy.d.ts.map +1 -1
  32. package/dist/cli/copy.js +0 -21
  33. package/dist/cli/copy.js.map +1 -1
  34. package/dist/cli/dispatcher.test.js +2 -2
  35. package/dist/cli/dispatcher.test.js.map +1 -1
  36. package/dist/cli/docs-accuracy.test.js +2 -0
  37. package/dist/cli/docs-accuracy.test.js.map +1 -1
  38. package/dist/cli/doctor.d.ts.map +1 -1
  39. package/dist/cli/doctor.js +4 -1
  40. package/dist/cli/doctor.js.map +1 -1
  41. package/dist/cli/init.d.ts.map +1 -1
  42. package/dist/cli/init.js +5 -4
  43. package/dist/cli/init.js.map +1 -1
  44. package/dist/cli/init.test.js +58 -34
  45. package/dist/cli/init.test.js.map +1 -1
  46. package/dist/cli/layers.d.ts +8 -0
  47. package/dist/cli/layers.d.ts.map +1 -1
  48. package/dist/cli/layers.js +130 -13
  49. package/dist/cli/layers.js.map +1 -1
  50. package/dist/cli/layers.test.js +2 -2
  51. package/dist/cli/layers.test.js.map +1 -1
  52. package/dist/cli/legacy-install.test.js +8 -1
  53. package/dist/cli/legacy-install.test.js.map +1 -1
  54. package/dist/cli/lesson-command.test.d.ts +2 -0
  55. package/dist/cli/lesson-command.test.d.ts.map +1 -0
  56. package/dist/cli/lesson-command.test.js +100 -0
  57. package/dist/cli/lesson-command.test.js.map +1 -0
  58. package/dist/cli/lesson.d.ts +0 -9
  59. package/dist/cli/lesson.d.ts.map +1 -1
  60. package/dist/cli/lesson.js +212 -276
  61. package/dist/cli/lesson.js.map +1 -1
  62. package/dist/cli/lessons.d.ts +134 -0
  63. package/dist/cli/lessons.d.ts.map +1 -0
  64. package/dist/cli/lessons.js +493 -0
  65. package/dist/cli/lessons.js.map +1 -0
  66. package/dist/cli/lessons.test.d.ts +2 -0
  67. package/dist/cli/lessons.test.d.ts.map +1 -0
  68. package/dist/cli/lessons.test.js +214 -0
  69. package/dist/cli/lessons.test.js.map +1 -0
  70. package/dist/cli/managed-paths.d.ts.map +1 -1
  71. package/dist/cli/managed-paths.js +2 -0
  72. package/dist/cli/managed-paths.js.map +1 -1
  73. package/dist/cli/mcp-audit.d.ts.map +1 -1
  74. package/dist/cli/mcp-audit.js +7 -3
  75. package/dist/cli/mcp-audit.js.map +1 -1
  76. package/dist/cli/mcp-file.d.ts +37 -0
  77. package/dist/cli/mcp-file.d.ts.map +1 -0
  78. package/dist/cli/mcp-file.js +291 -0
  79. package/dist/cli/mcp-file.js.map +1 -0
  80. package/dist/cli/mcp-file.test.d.ts +2 -0
  81. package/dist/cli/mcp-file.test.d.ts.map +1 -0
  82. package/dist/cli/mcp-file.test.js +121 -0
  83. package/dist/cli/mcp-file.test.js.map +1 -0
  84. package/dist/cli/mcp.d.ts +15 -0
  85. package/dist/cli/mcp.d.ts.map +1 -1
  86. package/dist/cli/mcp.js +123 -56
  87. package/dist/cli/mcp.js.map +1 -1
  88. package/dist/cli/pack-plugins.d.ts +8 -0
  89. package/dist/cli/pack-plugins.d.ts.map +1 -0
  90. package/dist/cli/pack-plugins.js +70 -0
  91. package/dist/cli/pack-plugins.js.map +1 -0
  92. package/dist/cli/plugin-command.test.d.ts +2 -0
  93. package/dist/cli/plugin-command.test.d.ts.map +1 -0
  94. package/dist/cli/plugin-command.test.js +114 -0
  95. package/dist/cli/plugin-command.test.js.map +1 -0
  96. package/dist/cli/plugin.d.ts +30 -0
  97. package/dist/cli/plugin.d.ts.map +1 -0
  98. package/dist/cli/plugin.js +291 -0
  99. package/dist/cli/plugin.js.map +1 -0
  100. package/dist/cli/promote-command.test.d.ts +2 -0
  101. package/dist/cli/promote-command.test.d.ts.map +1 -0
  102. package/dist/cli/promote-command.test.js +151 -0
  103. package/dist/cli/promote-command.test.js.map +1 -0
  104. package/dist/cli/promote.d.ts +12 -0
  105. package/dist/cli/promote.d.ts.map +1 -0
  106. package/dist/cli/promote.js +364 -0
  107. package/dist/cli/promote.js.map +1 -0
  108. package/dist/cli/remove.d.ts.map +1 -1
  109. package/dist/cli/remove.js +23 -4
  110. package/dist/cli/remove.js.map +1 -1
  111. package/dist/cli/secret-scan.d.ts +21 -0
  112. package/dist/cli/secret-scan.d.ts.map +1 -0
  113. package/dist/cli/secret-scan.js +114 -0
  114. package/dist/cli/secret-scan.js.map +1 -0
  115. package/dist/cli/sync-check.d.ts.map +1 -1
  116. package/dist/cli/sync-check.js +13 -3
  117. package/dist/cli/sync-check.js.map +1 -1
  118. package/dist/cli/sync-check.test.js +2 -2
  119. package/dist/cli/sync-check.test.js.map +1 -1
  120. package/dist/cli/team-commands.test.js +2 -2
  121. package/dist/cli/team-commands.test.js.map +1 -1
  122. package/dist/cli/types.d.ts +5 -2
  123. package/dist/cli/types.d.ts.map +1 -1
  124. package/dist/cli/types.js +3 -0
  125. package/dist/cli/types.js.map +1 -1
  126. package/dist/cli/unreadable-report.d.ts +7 -0
  127. package/dist/cli/unreadable-report.d.ts.map +1 -1
  128. package/dist/cli/unreadable-report.js +14 -0
  129. package/dist/cli/unreadable-report.js.map +1 -1
  130. package/dist/cli/update.d.ts.map +1 -1
  131. package/dist/cli/update.js +73 -5
  132. package/dist/cli/update.js.map +1 -1
  133. package/dist/orchestrator/plugins/agent-plugins.test.d.ts +2 -0
  134. package/dist/orchestrator/plugins/agent-plugins.test.d.ts.map +1 -0
  135. package/dist/orchestrator/plugins/agent-plugins.test.js +32 -0
  136. package/dist/orchestrator/plugins/agent-plugins.test.js.map +1 -0
  137. package/package.json +3 -1
  138. package/src/cli/adapters/codex.ts +25 -7
  139. package/src/cli/adapters/single-file-base.ts +69 -26
  140. package/src/cli/agent-plugin.test.ts +267 -0
  141. package/src/cli/agent-plugin.ts +469 -0
  142. package/src/cli/baseline.ts +99 -26
  143. package/src/cli/codex-target.test.ts +178 -0
  144. package/src/cli/convoy/gates.ts +9 -142
  145. package/src/cli/copy.ts +0 -25
  146. package/src/cli/dispatcher.test.ts +2 -2
  147. package/src/cli/docs-accuracy.test.ts +2 -0
  148. package/src/cli/doctor.ts +5 -2
  149. package/src/cli/fixtures/lessons-template-1.0.md +70 -0
  150. package/src/cli/init.test.ts +59 -34
  151. package/src/cli/init.ts +5 -4
  152. package/src/cli/layers.test.ts +2 -2
  153. package/src/cli/layers.ts +144 -14
  154. package/src/cli/legacy-install.test.ts +11 -1
  155. package/src/cli/lesson-command.test.ts +117 -0
  156. package/src/cli/lesson.ts +215 -266
  157. package/src/cli/lessons.test.ts +254 -0
  158. package/src/cli/lessons.ts +540 -0
  159. package/src/cli/managed-paths.ts +2 -0
  160. package/src/cli/mcp-audit.ts +7 -3
  161. package/src/cli/mcp-file.test.ts +138 -0
  162. package/src/cli/mcp-file.ts +302 -0
  163. package/src/cli/mcp.ts +130 -60
  164. package/src/cli/pack-plugins.ts +70 -0
  165. package/src/cli/plugin-command.test.ts +125 -0
  166. package/src/cli/plugin.ts +309 -0
  167. package/src/cli/promote-command.test.ts +170 -0
  168. package/src/cli/promote.ts +371 -0
  169. package/src/cli/remove.ts +20 -4
  170. package/src/cli/secret-scan.ts +154 -0
  171. package/src/cli/sync-check.test.ts +2 -2
  172. package/src/cli/sync-check.ts +13 -3
  173. package/src/cli/team-commands.test.ts +2 -2
  174. package/src/cli/types.ts +5 -2
  175. package/src/cli/unreadable-report.ts +14 -0
  176. package/src/cli/update.ts +81 -5
  177. package/src/dashboard/node_modules/.vite/deps/_metadata.json +6 -6
  178. package/src/orchestrator/agents/researcher.agent.md +1 -1
  179. package/src/orchestrator/customizations/LESSONS-LEARNED.md +10 -66
  180. package/src/orchestrator/customizations/README.md +2 -1
  181. package/src/orchestrator/customizations/logs/README.md +1 -1
  182. package/src/orchestrator/plugins/agent-plugins.test.ts +34 -0
  183. package/src/orchestrator/plugins/astro/mcp.json +9 -0
  184. package/src/orchestrator/plugins/astro/plugin.json +21 -0
  185. package/src/orchestrator/plugins/chrome-devtools/mcp.json +13 -0
  186. package/src/orchestrator/plugins/chrome-devtools/plugin.json +21 -0
  187. package/src/orchestrator/plugins/cloudflare/mcp.json +9 -0
  188. package/src/orchestrator/plugins/cloudflare/plugin.json +21 -0
  189. package/src/orchestrator/plugins/contentful/mcp.json +13 -0
  190. package/src/orchestrator/plugins/contentful/plugin.json +21 -0
  191. package/src/orchestrator/plugins/convex/mcp.json +15 -0
  192. package/src/orchestrator/plugins/convex/plugin.json +21 -0
  193. package/src/orchestrator/plugins/coolify/mcp.json +13 -0
  194. package/src/orchestrator/plugins/coolify/plugin.json +25 -0
  195. package/src/orchestrator/plugins/cypress/plugin.json +21 -0
  196. package/src/orchestrator/plugins/drizzle/plugin.json +21 -0
  197. package/src/orchestrator/plugins/expo/mcp.json +9 -0
  198. package/src/orchestrator/plugins/expo/plugin.json +21 -0
  199. package/src/orchestrator/plugins/figma/mcp.json +9 -0
  200. package/src/orchestrator/plugins/figma/plugin.json +21 -0
  201. package/src/orchestrator/plugins/hetzner/plugin.json +24 -0
  202. package/src/orchestrator/plugins/jira/mcp.json +9 -0
  203. package/src/orchestrator/plugins/jira/plugin.json +21 -0
  204. package/src/orchestrator/plugins/linear/mcp.json +9 -0
  205. package/src/orchestrator/plugins/linear/plugin.json +21 -0
  206. package/src/orchestrator/plugins/netlify/mcp.json +13 -0
  207. package/src/orchestrator/plugins/netlify/plugin.json +21 -0
  208. package/src/orchestrator/plugins/nextjs/mcp.json +13 -0
  209. package/src/orchestrator/plugins/nextjs/plugin.json +21 -0
  210. package/src/orchestrator/plugins/notion/mcp.json +9 -0
  211. package/src/orchestrator/plugins/notion/plugin.json +21 -0
  212. package/src/orchestrator/plugins/nx/mcp.json +14 -0
  213. package/src/orchestrator/plugins/nx/plugin.json +21 -0
  214. package/src/orchestrator/plugins/playwright/mcp.json +13 -0
  215. package/src/orchestrator/plugins/playwright/plugin.json +21 -0
  216. package/src/orchestrator/plugins/prisma/mcp.json +14 -0
  217. package/src/orchestrator/plugins/prisma/plugin.json +21 -0
  218. package/src/orchestrator/plugins/resend/mcp.json +13 -0
  219. package/src/orchestrator/plugins/resend/plugin.json +24 -0
  220. package/src/orchestrator/plugins/sanity/mcp.json +9 -0
  221. package/src/orchestrator/plugins/sanity/plugin.json +21 -0
  222. package/src/orchestrator/plugins/sentry/mcp.json +12 -0
  223. package/src/orchestrator/plugins/sentry/plugin.json +24 -0
  224. package/src/orchestrator/plugins/slack/mcp.json +13 -0
  225. package/src/orchestrator/plugins/slack/plugin.json +24 -0
  226. package/src/orchestrator/plugins/strapi/mcp.json +13 -0
  227. package/src/orchestrator/plugins/strapi/plugin.json +21 -0
  228. package/src/orchestrator/plugins/stripe/mcp.json +9 -0
  229. package/src/orchestrator/plugins/stripe/plugin.json +21 -0
  230. package/src/orchestrator/plugins/supabase/mcp.json +9 -0
  231. package/src/orchestrator/plugins/supabase/plugin.json +21 -0
  232. package/src/orchestrator/plugins/teams/plugin.json +24 -0
  233. package/src/orchestrator/plugins/trello/mcp.json +13 -0
  234. package/src/orchestrator/plugins/trello/plugin.json +25 -0
  235. package/src/orchestrator/plugins/turborepo/plugin.json +21 -0
  236. package/src/orchestrator/plugins/vercel/mcp.json +9 -0
  237. package/src/orchestrator/plugins/vercel/plugin.json +21 -0
  238. package/src/orchestrator/plugins/vitest/plugin.json +21 -0
  239. package/src/orchestrator/skill-config-links.test.ts +2 -1
  240. package/src/orchestrator/skills/agent-hooks/HOOKS-REFERENCE.md +1 -1
  241. package/src/orchestrator/skills/agent-hooks/SKILL.md +1 -1
  242. package/src/orchestrator/skills/decomposition/SKILL.md +1 -1
  243. package/src/orchestrator/skills/memory-merger/SKILL.md +17 -21
  244. package/src/orchestrator/skills/self-improvement/LESSON-CATEGORIES.md +44 -23
  245. package/src/orchestrator/skills/self-improvement/SKILL.md +30 -15
  246. /package/src/orchestrator/plugins/astro/{SKILL.md → skills/astro-framework/SKILL.md} +0 -0
  247. /package/src/orchestrator/plugins/chrome-devtools/{SKILL.md → skills/browser-testing/SKILL.md} +0 -0
  248. /package/src/orchestrator/plugins/cloudflare/{SKILL.md → skills/cloudflare-platform/SKILL.md} +0 -0
  249. /package/src/orchestrator/plugins/contentful/{SKILL.md → skills/contentful-cms/SKILL.md} +0 -0
  250. /package/src/orchestrator/plugins/convex/{SKILL.md → skills/convex-database/SKILL.md} +0 -0
  251. /package/src/orchestrator/plugins/coolify/{SKILL.md → skills/coolify-deployment/SKILL.md} +0 -0
  252. /package/src/orchestrator/plugins/cypress/{SKILL.md → skills/cypress-testing/SKILL.md} +0 -0
  253. /package/src/orchestrator/plugins/drizzle/{SKILL.md → skills/drizzle-orm/SKILL.md} +0 -0
  254. /package/src/orchestrator/plugins/expo/{SKILL.md → skills/expo-development/SKILL.md} +0 -0
  255. /package/src/orchestrator/plugins/figma/{SKILL.md → skills/figma-design/SKILL.md} +0 -0
  256. /package/src/orchestrator/plugins/hetzner/{SKILL.md → skills/hetzner-cloud/SKILL.md} +0 -0
  257. /package/src/orchestrator/plugins/jira/{SKILL.md → skills/jira-management/SKILL.md} +0 -0
  258. /package/src/orchestrator/plugins/linear/{SKILL.md → skills/linear-task-management/SKILL.md} +0 -0
  259. /package/src/orchestrator/plugins/netlify/{SKILL.md → skills/netlify-deployment/SKILL.md} +0 -0
  260. /package/src/orchestrator/plugins/nextjs/{SKILL.md → skills/nextjs-framework/SKILL.md} +0 -0
  261. /package/src/orchestrator/plugins/notion/{SKILL.md → skills/notion-knowledge-management/SKILL.md} +0 -0
  262. /package/src/orchestrator/plugins/nx/{SKILL.md → skills/nx-workspace/SKILL.md} +0 -0
  263. /package/src/orchestrator/plugins/playwright/{SKILL.md → skills/playwright-testing/SKILL.md} +0 -0
  264. /package/src/orchestrator/plugins/prisma/{SKILL.md → skills/prisma-database/SKILL.md} +0 -0
  265. /package/src/orchestrator/plugins/resend/{SKILL.md → skills/resend-email/SKILL.md} +0 -0
  266. /package/src/orchestrator/plugins/sanity/{SKILL.md → skills/sanity-cms/SKILL.md} +0 -0
  267. /package/src/orchestrator/plugins/sentry/{SKILL.md → skills/sentry-monitoring/SKILL.md} +0 -0
  268. /package/src/orchestrator/plugins/slack/{SKILL.md → skills/slack-notifications/SKILL.md} +0 -0
  269. /package/src/orchestrator/plugins/strapi/{SKILL.md → skills/strapi-cms/SKILL.md} +0 -0
  270. /package/src/orchestrator/plugins/stripe/{SKILL.md → skills/stripe-payments/SKILL.md} +0 -0
  271. /package/src/orchestrator/plugins/supabase/{SKILL.md → skills/supabase-database/SKILL.md} +0 -0
  272. /package/src/orchestrator/plugins/teams/{SKILL.md → skills/teams-notifications/SKILL.md} +0 -0
  273. /package/src/orchestrator/plugins/trello/{SKILL.md → skills/trello-task-management/SKILL.md} +0 -0
  274. /package/src/orchestrator/plugins/turborepo/{SKILL.md → skills/turborepo-monorepo/SKILL.md} +0 -0
  275. /package/src/orchestrator/plugins/vercel/{SKILL.md → skills/vercel-deployment/SKILL.md} +0 -0
  276. /package/src/orchestrator/plugins/vitest/{SKILL.md → skills/vitest-testing/SKILL.md} +0 -0
@@ -0,0 +1,138 @@
1
+ import { describe, it, expect } from 'vitest'
2
+ import { parse as parseToml } from 'smol-toml'
3
+ import { parseMcpConfigText, serialiseMcpConfig, TomlEditError } from './mcp-file.js'
4
+
5
+ /**
6
+ * `.codex/config.toml` holds a user's whole Codex setup — model, approvals,
7
+ * sandbox, profiles — beside the MCP servers OpenCastle writes. These pin the
8
+ * promise the JSON configs already keep: our servers change, nothing of theirs
9
+ * does, byte for byte.
10
+ */
11
+
12
+ const REL = '.codex/config.toml'
13
+
14
+ const USERS_OWN = `# My Codex setup
15
+ model = "gpt-5-codex"
16
+ approval_policy = "on-request"
17
+
18
+ [profiles.fast]
19
+ model = "gpt-5-codex-mini" # quick tasks
20
+
21
+ [mcp_servers.mine]
22
+ command = "my-server"
23
+ args = ["--port", "1234"]
24
+
25
+ [mcp_servers.mine.tools.dangerous]
26
+ approval_mode = "approve"
27
+ `
28
+
29
+ function serversOf(text: string): Record<string, unknown> {
30
+ return (parseToml(text) as { mcp_servers?: Record<string, unknown> }).mcp_servers ?? {}
31
+ }
32
+
33
+ describe('Codex config.toml', () => {
34
+ it('parses to a plain object with mcp_servers as the container', () => {
35
+ const parsed = parseMcpConfigText(USERS_OWN, REL)
36
+ expect(Object.getPrototypeOf(parsed)).toBe(Object.prototype)
37
+ expect(Object.keys(parsed.mcp_servers as object)).toEqual(['mine'])
38
+ })
39
+
40
+ it('adds a server after the user’s content and changes nothing of theirs', () => {
41
+ const value = parseMcpConfigText(USERS_OWN, REL)
42
+ ;(value.mcp_servers as Record<string, unknown>).Linear = { url: 'https://mcp.linear.app/mcp' }
43
+ const text = serialiseMcpConfig(USERS_OWN, value, REL)
44
+ expect(text.startsWith(USERS_OWN)).toBe(true)
45
+ expect(text.slice(USERS_OWN.length)).toBe('\n[mcp_servers.Linear]\nurl = "https://mcp.linear.app/mcp"\n')
46
+ })
47
+
48
+ it('removes only the server it was asked to, with its sub-tables', () => {
49
+ const withOurs = USERS_OWN + '\n[mcp_servers.Sanity]\ncommand = "npx"\nargs = ["-y", "@sanity/mcp-server@1.2.3"]\n'
50
+ const value = parseMcpConfigText(withOurs, REL)
51
+ delete (value.mcp_servers as Record<string, unknown>).Sanity
52
+ expect(serialiseMcpConfig(withOurs, value, REL)).toBe(USERS_OWN)
53
+ })
54
+
55
+ it('gives the user their file back byte for byte after an add and a remove', () => {
56
+ const value = parseMcpConfigText(USERS_OWN, REL)
57
+ ;(value.mcp_servers as Record<string, unknown>).Linear = { url: 'https://mcp.linear.app/mcp' }
58
+ const added = serialiseMcpConfig(USERS_OWN, value, REL)
59
+ const back = parseMcpConfigText(added, REL)
60
+ delete (back.mcp_servers as Record<string, unknown>).Linear
61
+ expect(serialiseMcpConfig(added, back, REL)).toBe(USERS_OWN)
62
+ })
63
+
64
+ it('rewrites a changed server in place and keeps the tables around it', () => {
65
+ const before =
66
+ 'model = "x"\n\n[mcp_servers.Sentry]\nurl = "https://old.example/mcp"\n\n[profiles.a]\nmodel = "y"\n'
67
+ const value = parseMcpConfigText(before, REL)
68
+ ;(value.mcp_servers as Record<string, Record<string, unknown>>).Sentry = { url: 'https://mcp.sentry.dev/mcp' }
69
+ const text = serialiseMcpConfig(before, value, REL)
70
+ expect(text).toBe('model = "x"\n\n[mcp_servers.Sentry]\nurl = "https://mcp.sentry.dev/mcp"\n\n[profiles.a]\nmodel = "y"\n')
71
+ })
72
+
73
+ it('quotes a server name that is not a bare key', () => {
74
+ const value = { mcp_servers: { 'Chrome DevTools': { command: 'npx', args: ['chrome-devtools-mcp@0.1.0'] } } }
75
+ const text = serialiseMcpConfig(null, value, REL)
76
+ expect(text).toContain('[mcp_servers."Chrome DevTools"]')
77
+ expect(serversOf(text)).toEqual(value.mcp_servers)
78
+ })
79
+
80
+ it('writes env, env_vars and headers as values Codex reads back the same', () => {
81
+ const entry = {
82
+ url: 'https://api.example.com/mcp',
83
+ bearer_token_env_var: 'EXAMPLE_TOKEN',
84
+ http_headers: { 'X-Tenant': 'acme' },
85
+ env_http_headers: { 'X-Key': 'EXAMPLE_KEY' },
86
+ }
87
+ const stdio = { command: 'npx', args: ['-y', 'x@1.0.0'], env: { MODE: 'ci "quoted"\\path' }, env_vars: ['API_TOKEN'] }
88
+ const value = { mcp_servers: { remote: entry, local: stdio } }
89
+ const text = serialiseMcpConfig(null, value, REL)
90
+ expect(serversOf(text)).toEqual(value.mcp_servers)
91
+ })
92
+
93
+ it('keeps CRLF line endings', () => {
94
+ const before = USERS_OWN.replace(/\n/g, '\r\n')
95
+ const value = parseMcpConfigText(before, REL)
96
+ ;(value.mcp_servers as Record<string, unknown>).Linear = { url: 'https://mcp.linear.app/mcp' }
97
+ const text = serialiseMcpConfig(before, value, REL)
98
+ expect(text.startsWith(before)).toBe(true)
99
+ expect(text.replace(/\r\n/g, '')).not.toContain('\n')
100
+ })
101
+
102
+ it('does not mistake a header-like line inside a multi-line string for a table', () => {
103
+ const before = 'instructions = """\n[mcp_servers.fake]\nnot a table\n"""\n\n[mcp_servers.real]\ncommand = "a"\n'
104
+ const value = parseMcpConfigText(before, REL)
105
+ ;(value.mcp_servers as Record<string, Record<string, unknown>>).real = { command: 'b' }
106
+ const text = serialiseMcpConfig(before, value, REL)
107
+ expect(text).toContain('[mcp_servers.fake]\nnot a table')
108
+ expect(serversOf(text)).toEqual({ real: { command: 'b' } })
109
+ })
110
+
111
+ it('refuses rather than rewrites servers written as inline tables', () => {
112
+ const before = '[mcp_servers]\nmine = { command = "a" }\n'
113
+ const value = parseMcpConfigText(before, REL)
114
+ ;(value.mcp_servers as Record<string, Record<string, unknown>>).mine = { command: 'b' }
115
+ expect(() => serialiseMcpConfig(before, value, REL)).toThrow(TomlEditError)
116
+ })
117
+
118
+ it('refuses to change anything outside [mcp_servers]', () => {
119
+ const value = parseMcpConfigText(USERS_OWN, REL)
120
+ value.model = 'something-else'
121
+ expect(() => serialiseMcpConfig(USERS_OWN, value, REL)).toThrow(TomlEditError)
122
+ })
123
+
124
+ it('leaves no [mcp_servers] residue when the last of ours goes', () => {
125
+ const before = 'model = "x"\n\n[mcp_servers.Linear]\nurl = "https://mcp.linear.app/mcp"\n'
126
+ const value = parseMcpConfigText(before, REL)
127
+ delete value.mcp_servers
128
+ expect(serialiseMcpConfig(before, value, REL)).toBe('model = "x"\n')
129
+ })
130
+ })
131
+
132
+ describe('JSON configs are untouched by the TOML path', () => {
133
+ it('keeps the file’s indentation', () => {
134
+ const before = '{\n\t"mcpServers": {}\n}\n'
135
+ const text = serialiseMcpConfig(before, { mcpServers: { a: { command: 'x' } } }, '.mcp.json')
136
+ expect(text).toBe('{\n\t"mcpServers": {\n\t\t"a": {\n\t\t\t"command": "x"\n\t\t}\n\t}\n}\n')
137
+ })
138
+ })
@@ -0,0 +1,302 @@
1
+ import { parse as parseToml } from 'smol-toml'
2
+
3
+ /**
4
+ * Reading and writing an MCP config file in whatever language it is written in.
5
+ *
6
+ * Every target but one keeps its servers in JSON. Codex CLI keeps them in
7
+ * `.codex/config.toml`, beside the rest of the project's Codex settings, and
8
+ * OpenCastle wrote `.codex/mcp.json` — a file Codex has never read — so no
9
+ * integration or team server reached Codex at all. The merge, strip, audit and
10
+ * drift logic all work on a parsed object; this is the one place that knows a
11
+ * config can be TOML, so none of them has to.
12
+ *
13
+ * `config.toml` is co-owned the way `opencode.json` is: the user's model,
14
+ * approval and sandbox settings sit beside our servers. Re-serialising it whole
15
+ * would restyle it and drop every comment, so a TOML write changes only the
16
+ * `[mcp_servers.<name>]` tables whose value changed and leaves every other byte
17
+ * as it was.
18
+ */
19
+
20
+ /** Thrown when a TOML config is shaped so that a change cannot be made without rewriting the user's text. */
21
+ export class TomlEditError extends Error {
22
+ constructor(message: string) {
23
+ super(message)
24
+ this.name = 'TomlEditError'
25
+ }
26
+ }
27
+
28
+ export function isTomlConfig(rel: string): boolean {
29
+ return rel.endsWith('.toml')
30
+ }
31
+
32
+ /** Parse a config's text. Throws, as `JSON.parse` does, when it does not parse. */
33
+ export function parseMcpConfigText(text: string, rel: string): Record<string, unknown> {
34
+ if (isTomlConfig(rel)) return plain(parseToml(text)) as Record<string, unknown>
35
+ return JSON.parse(text) as Record<string, unknown>
36
+ }
37
+
38
+ /**
39
+ * The text to write for `value`, given what the file held before (`null` when
40
+ * it is being created).
41
+ */
42
+ export function serialiseMcpConfig(before: string | null, value: Record<string, unknown>, rel: string): string {
43
+ if (isTomlConfig(rel)) return writeToml(before ?? '', value)
44
+ return before === null ? JSON.stringify(value, null, 2) + '\n' : serialiseLike(before, value)
45
+ }
46
+
47
+ // ── JSON ──────────────────────────────────────────────────────
48
+
49
+ /**
50
+ * The indentation a file already uses, so merging into it does not restyle it.
51
+ *
52
+ * `JSON.stringify(x, null, 2)` re-indented every co-owned config we touched. A
53
+ * hand-written tab-indented `opencode.json` — OpenCode's entire project config —
54
+ * came back two-space indented from a merge that added one key, and never came back
55
+ * from the uninstall at all: 111 bytes in, 114 out, for a strip that took nothing
56
+ * of theirs. Byte fidelity is a claim this tool makes about co-owned files, and a
57
+ * JSON config is one of those.
58
+ *
59
+ * Read from the first indented line, which is what every formatter agrees on.
60
+ * Falls back to two spaces for a file we are creating or one written on a single
61
+ * line, which is what this always did.
62
+ */
63
+ function indentOf(text: string): string | number {
64
+ const m = /\n([ \t]+)\S/.exec(text)
65
+ if (m) return m[1].includes('\t') ? '\t' : m[1].length
66
+ // A config written on one line has no indentation, and expanding it to three is
67
+ // as much a restyle as collapsing it would be. `0` is what `JSON.stringify` takes
68
+ // for "no whitespace".
69
+ return text.trim().includes('\n') ? 2 : 0
70
+ }
71
+
72
+ /**
73
+ * Re-serialise a config the way the file was already written.
74
+ *
75
+ * Indentation and line endings both, because `JSON.stringify` emits `\n` whatever
76
+ * it was handed and a CRLF config came back LF from a merge that added one key.
77
+ * The same rule `.gitignore` follows: a CRLF file stays CRLF.
78
+ */
79
+ export function serialiseLike(original: string, value: unknown): string {
80
+ const text = JSON.stringify(value, null, indentOf(original)) + '\n'
81
+ return /\r\n/.test(original) ? text.replace(/\n/g, '\r\n') : text
82
+ }
83
+
84
+ // ── TOML ──────────────────────────────────────────────────────
85
+
86
+ const SERVERS = 'mcp_servers'
87
+
88
+ /** smol-toml builds objects with no prototype; the rest of the code expects plain ones. */
89
+ function plain(value: unknown): unknown {
90
+ if (Array.isArray(value)) return value.map(plain)
91
+ if (value && typeof value === 'object' && !(value instanceof Date)) {
92
+ return Object.fromEntries(Object.entries(value).map(([k, v]) => [k, plain(v)]))
93
+ }
94
+ return value
95
+ }
96
+
97
+ /** Key order is not meaning. */
98
+ function canonical(value: unknown): string {
99
+ return JSON.stringify(value, (_key, v) =>
100
+ v && typeof v === 'object' && !Array.isArray(v) && !(v instanceof Date)
101
+ ? Object.fromEntries(Object.entries(v as Record<string, unknown>).sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0)))
102
+ : v,
103
+ )
104
+ }
105
+
106
+ function tomlKey(key: string): string {
107
+ return /^[A-Za-z0-9_-]+$/.test(key) ? key : tomlString(key)
108
+ }
109
+
110
+ /**
111
+ * A TOML basic string. JSON's escapes are TOML's, except that TOML also forbids
112
+ * a raw DEL, which JSON leaves alone.
113
+ */
114
+ function tomlString(s: string): string {
115
+ return JSON.stringify(s).replace(/\u007f/g, '\\u007F')
116
+ }
117
+
118
+ function tomlValue(value: unknown): string {
119
+ if (typeof value === 'string') return tomlString(value)
120
+ if (typeof value === 'number' || typeof value === 'boolean') return String(value)
121
+ if (Array.isArray(value)) return `[${value.map(tomlValue).join(', ')}]`
122
+ if (value && typeof value === 'object') {
123
+ const fields = Object.entries(value).filter(([, v]) => v !== undefined)
124
+ return fields.length === 0 ? '{}' : `{ ${fields.map(([k, v]) => `${tomlKey(k)} = ${tomlValue(v)}`).join(', ')} }`
125
+ }
126
+ throw new TomlEditError(`cannot write ${String(value)} as TOML`)
127
+ }
128
+
129
+ /** One server as a `[mcp_servers.<key>]` table. */
130
+ function serverTable(key: string, entry: unknown, eol: string): string {
131
+ const lines = [`[${SERVERS}.${tomlKey(key)}]`]
132
+ for (const [k, v] of Object.entries((entry ?? {}) as Record<string, unknown>)) {
133
+ if (v === undefined) continue
134
+ lines.push(`${tomlKey(k)} = ${tomlValue(v)}`)
135
+ }
136
+ return lines.join(eol) + eol
137
+ }
138
+
139
+ interface Segment {
140
+ /** The table this run of lines belongs to, as its dotted key; `null` before the first header. */
141
+ path: string[] | null
142
+ lines: string[]
143
+ }
144
+
145
+ const HEADER = /^[ \t]*\[\[?[ \t]*(.+?)[ \t]*\]\]?[ \t]*(?:#.*)?\r?\n?$/
146
+
147
+ /** Split a dotted key into its parts, unquoting quoted ones. */
148
+ function splitKey(key: string): string[] {
149
+ const parts: string[] = []
150
+ let current = ''
151
+ let quote: string | null = null
152
+ for (let i = 0; i < key.length; i++) {
153
+ const ch = key[i]
154
+ if (quote) {
155
+ if (ch === '\\' && quote === '"') {
156
+ current += key[++i] ?? ''
157
+ } else if (ch === quote) {
158
+ quote = null
159
+ } else {
160
+ current += ch
161
+ }
162
+ } else if (ch === '"' || ch === "'") {
163
+ quote = ch
164
+ } else if (ch === '.') {
165
+ parts.push(current.trim())
166
+ current = ''
167
+ } else {
168
+ current += ch
169
+ }
170
+ }
171
+ parts.push(current.trim())
172
+ return parts
173
+ }
174
+
175
+ /**
176
+ * The file as runs of lines, one per table.
177
+ *
178
+ * A line that looks like a header inside a multi-line string is not one; the
179
+ * string delimiters are tracked so it stays with the table it belongs to. Odd
180
+ * layouts this misreads are caught afterwards: every write is parsed back and
181
+ * compared with what was meant.
182
+ */
183
+ function segments(text: string): Segment[] {
184
+ const lines = text.split(/(?<=\n)/)
185
+ const out: Segment[] = [{ path: null, lines: [] }]
186
+ let open: '"""' | "'''" | null = null
187
+ for (const line of lines) {
188
+ if (!open) {
189
+ const header = HEADER.exec(line)
190
+ if (header && !line.trimStart().startsWith('#')) {
191
+ out.push({ path: splitKey(header[1]), lines: [line] })
192
+ continue
193
+ }
194
+ }
195
+ out[out.length - 1].lines.push(line)
196
+ for (const m of line.matchAll(/"""|'''/g)) {
197
+ if (!open) open = m[0] as '"""' | "'''"
198
+ else if (open === m[0]) open = null
199
+ }
200
+ }
201
+ return out
202
+ }
203
+
204
+ /** The blank and comment lines a segment ends with — they introduce whatever follows it. */
205
+ function tailOf(seg: Segment): string[] {
206
+ const tail: string[] = []
207
+ for (let i = seg.lines.length - 1; i > 0; i--) {
208
+ const t = seg.lines[i].trim()
209
+ if (t === '' || t.startsWith('#')) tail.unshift(seg.lines[i])
210
+ else break
211
+ }
212
+ return tail
213
+ }
214
+
215
+ function serverOf(seg: Segment): string | undefined {
216
+ return seg.path && seg.path[0] === SERVERS && seg.path.length >= 2 ? seg.path[1] : undefined
217
+ }
218
+
219
+ function without(value: Record<string, unknown>, key: string): Record<string, unknown> {
220
+ const { [key]: _drop, ...rest } = value
221
+ return rest
222
+ }
223
+
224
+ /** An empty `[mcp_servers]` and none at all say the same thing to Codex. */
225
+ function normalised(value: unknown): unknown {
226
+ const v = value as Record<string, unknown>
227
+ const servers = v[SERVERS]
228
+ return servers && typeof servers === 'object' && Object.keys(servers).length === 0 ? without(v, SERVERS) : v
229
+ }
230
+
231
+ /**
232
+ * Write `value` over `before`, touching only the server tables that changed.
233
+ *
234
+ * Everything outside `[mcp_servers]` must be what the file already says —
235
+ * OpenCastle never edits a user's Codex settings — and the result is parsed
236
+ * back before it is returned, so a layout this cannot edit cleanly is refused
237
+ * rather than written wrong.
238
+ */
239
+ function writeToml(before: string, value: Record<string, unknown>): string {
240
+ const eol = /\r\n/.test(before) ? '\r\n' : '\n'
241
+ const old = (before.trim() === '' ? {} : plain(parseToml(before))) as Record<string, unknown>
242
+ if (canonical(without(old, SERVERS)) !== canonical(without(value, SERVERS))) {
243
+ throw new TomlEditError('only the [mcp_servers] tables of a Codex config are ours to change')
244
+ }
245
+ const oldServers = (old[SERVERS] ?? {}) as Record<string, unknown>
246
+ const newServers = (value[SERVERS] ?? {}) as Record<string, unknown>
247
+
248
+ const out: string[] = []
249
+ const rewritten = new Set<string>()
250
+ // Whether the file now ends where a dropped table used to be. The blank line
251
+ // that separated our first table from the user's last one was ours, written
252
+ // when we appended; left behind, an install and uninstall would not give the
253
+ // user back their file byte for byte.
254
+ let endsOnDrop = false
255
+ for (const seg of segments(before)) {
256
+ const key = serverOf(seg)
257
+ if (key === undefined) {
258
+ out.push(...seg.lines)
259
+ endsOnDrop = false
260
+ continue
261
+ }
262
+ const tail = tailOf(seg)
263
+ if (!(key in newServers)) {
264
+ // A comment before the next table is about that table; keep it.
265
+ if (tail.some((l) => l.trim().startsWith('#'))) out.push(...tail)
266
+ endsOnDrop = true
267
+ continue
268
+ }
269
+ endsOnDrop = false
270
+ if (canonical(oldServers[key]) === canonical(newServers[key])) {
271
+ out.push(...seg.lines)
272
+ continue
273
+ }
274
+ // A changed server is written whole at its first table; its sub-tables go.
275
+ if (rewritten.has(key)) {
276
+ if (tail.some((l) => l.trim().startsWith('#'))) out.push(...tail)
277
+ continue
278
+ }
279
+ rewritten.add(key)
280
+ out.push(serverTable(key, newServers[key], eol), ...tail)
281
+ }
282
+
283
+ let text = out.join('')
284
+ if (endsOnDrop) text = text.trim() === '' ? '' : text.replace(/(\r?\n)+$/, eol)
285
+ const added = Object.keys(newServers).filter((k) => !(k in oldServers))
286
+ if (added.length > 0) {
287
+ if (text !== '' && !text.endsWith('\n')) text += eol
288
+ if (text.trim() !== '' && !/(\r?\n){2}$/.test(text)) text += eol
289
+ text += added.map((k) => serverTable(k, newServers[k], eol)).join(eol)
290
+ }
291
+
292
+ let check: unknown
293
+ try {
294
+ check = plain(parseToml(text))
295
+ } catch (err) {
296
+ throw new TomlEditError(`the edit would not parse — ${(err as Error).message}`)
297
+ }
298
+ if (canonical(normalised(check)) !== canonical(normalised(value))) {
299
+ throw new TomlEditError('its [mcp_servers] are written in a way this cannot edit line by line, e.g. as inline tables')
300
+ }
301
+ return text
302
+ }