opencastle 1.1.1 → 1.3.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 (307) hide show
  1. package/README.md +26 -9
  2. package/bin/cli.mjs +6 -0
  3. package/dist/cli/adapters/antigravity.d.ts +0 -1
  4. package/dist/cli/adapters/antigravity.d.ts.map +1 -1
  5. package/dist/cli/adapters/antigravity.js +2 -1
  6. package/dist/cli/adapters/antigravity.js.map +1 -1
  7. package/dist/cli/adapters/claude-code.d.ts +0 -1
  8. package/dist/cli/adapters/claude-code.d.ts.map +1 -1
  9. package/dist/cli/adapters/claude-code.js +0 -1
  10. package/dist/cli/adapters/claude-code.js.map +1 -1
  11. package/dist/cli/adapters/cursor.d.ts.map +1 -1
  12. package/dist/cli/adapters/cursor.js +8 -1
  13. package/dist/cli/adapters/cursor.js.map +1 -1
  14. package/dist/cli/adapters/opencode.d.ts +12 -5
  15. package/dist/cli/adapters/opencode.d.ts.map +1 -1
  16. package/dist/cli/adapters/opencode.js +17 -5
  17. package/dist/cli/adapters/opencode.js.map +1 -1
  18. package/dist/cli/adapters/rules-dir-base.d.ts +12 -1
  19. package/dist/cli/adapters/rules-dir-base.d.ts.map +1 -1
  20. package/dist/cli/adapters/rules-dir-base.js +43 -57
  21. package/dist/cli/adapters/rules-dir-base.js.map +1 -1
  22. package/dist/cli/adapters/rules-dir-base.test.js +27 -18
  23. package/dist/cli/adapters/rules-dir-base.test.js.map +1 -1
  24. package/dist/cli/adapters/single-file-base.d.ts +11 -0
  25. package/dist/cli/adapters/single-file-base.d.ts.map +1 -1
  26. package/dist/cli/adapters/single-file-base.js +44 -14
  27. package/dist/cli/adapters/single-file-base.js.map +1 -1
  28. package/dist/cli/adapters/vscode.d.ts +2 -1
  29. package/dist/cli/adapters/vscode.d.ts.map +1 -1
  30. package/dist/cli/adapters/vscode.js +2 -1
  31. package/dist/cli/adapters/vscode.js.map +1 -1
  32. package/dist/cli/adapters/windsurf.d.ts.map +1 -1
  33. package/dist/cli/adapters/windsurf.js +11 -1
  34. package/dist/cli/adapters/windsurf.js.map +1 -1
  35. package/dist/cli/agent-plugin.d.ts +119 -0
  36. package/dist/cli/agent-plugin.d.ts.map +1 -0
  37. package/dist/cli/agent-plugin.js +449 -0
  38. package/dist/cli/agent-plugin.js.map +1 -0
  39. package/dist/cli/agent-plugin.test.d.ts +2 -0
  40. package/dist/cli/agent-plugin.test.d.ts.map +1 -0
  41. package/dist/cli/agent-plugin.test.js +227 -0
  42. package/dist/cli/agent-plugin.test.js.map +1 -0
  43. package/dist/cli/baseline.d.ts.map +1 -1
  44. package/dist/cli/baseline.js +114 -34
  45. package/dist/cli/baseline.js.map +1 -1
  46. package/dist/cli/ci.d.ts.map +1 -1
  47. package/dist/cli/ci.js +18 -4
  48. package/dist/cli/ci.js.map +1 -1
  49. package/dist/cli/codex-target.test.js +14 -1
  50. package/dist/cli/codex-target.test.js.map +1 -1
  51. package/dist/cli/convoy/gates.d.ts +2 -20
  52. package/dist/cli/convoy/gates.d.ts.map +1 -1
  53. package/dist/cli/convoy/gates.js +3 -111
  54. package/dist/cli/convoy/gates.js.map +1 -1
  55. package/dist/cli/copy.d.ts +0 -8
  56. package/dist/cli/copy.d.ts.map +1 -1
  57. package/dist/cli/copy.js +0 -21
  58. package/dist/cli/copy.js.map +1 -1
  59. package/dist/cli/dispatcher.test.js +2 -2
  60. package/dist/cli/dispatcher.test.js.map +1 -1
  61. package/dist/cli/docs-accuracy.test.js +2 -0
  62. package/dist/cli/docs-accuracy.test.js.map +1 -1
  63. package/dist/cli/doctor.d.ts.map +1 -1
  64. package/dist/cli/doctor.js +2 -0
  65. package/dist/cli/doctor.js.map +1 -1
  66. package/dist/cli/doctor.test.js +2 -2
  67. package/dist/cli/doctor.test.js.map +1 -1
  68. package/dist/cli/explain.d.ts +5 -0
  69. package/dist/cli/explain.d.ts.map +1 -1
  70. package/dist/cli/explain.js +38 -2
  71. package/dist/cli/explain.js.map +1 -1
  72. package/dist/cli/init.test.js +78 -42
  73. package/dist/cli/init.test.js.map +1 -1
  74. package/dist/cli/layers.d.ts +8 -0
  75. package/dist/cli/layers.d.ts.map +1 -1
  76. package/dist/cli/layers.js +130 -13
  77. package/dist/cli/layers.js.map +1 -1
  78. package/dist/cli/layers.test.js +2 -2
  79. package/dist/cli/layers.test.js.map +1 -1
  80. package/dist/cli/legacy-install.test.js +8 -1
  81. package/dist/cli/legacy-install.test.js.map +1 -1
  82. package/dist/cli/lesson-command.test.d.ts +2 -0
  83. package/dist/cli/lesson-command.test.d.ts.map +1 -0
  84. package/dist/cli/lesson-command.test.js +100 -0
  85. package/dist/cli/lesson-command.test.js.map +1 -0
  86. package/dist/cli/lesson.d.ts +0 -9
  87. package/dist/cli/lesson.d.ts.map +1 -1
  88. package/dist/cli/lesson.js +212 -276
  89. package/dist/cli/lesson.js.map +1 -1
  90. package/dist/cli/lessons.d.ts +134 -0
  91. package/dist/cli/lessons.d.ts.map +1 -0
  92. package/dist/cli/lessons.js +493 -0
  93. package/dist/cli/lessons.js.map +1 -0
  94. package/dist/cli/lessons.test.d.ts +2 -0
  95. package/dist/cli/lessons.test.d.ts.map +1 -0
  96. package/dist/cli/lessons.test.js +214 -0
  97. package/dist/cli/lessons.test.js.map +1 -0
  98. package/dist/cli/managed-paths.d.ts.map +1 -1
  99. package/dist/cli/managed-paths.js +3 -1
  100. package/dist/cli/managed-paths.js.map +1 -1
  101. package/dist/cli/mcp-audit.d.ts.map +1 -1
  102. package/dist/cli/mcp-audit.js +2 -0
  103. package/dist/cli/mcp-audit.js.map +1 -1
  104. package/dist/cli/mcp-upgrade.test.js +24 -1
  105. package/dist/cli/mcp-upgrade.test.js.map +1 -1
  106. package/dist/cli/mcp.d.ts.map +1 -1
  107. package/dist/cli/mcp.js +22 -3
  108. package/dist/cli/mcp.js.map +1 -1
  109. package/dist/cli/pack-plugins.d.ts +8 -0
  110. package/dist/cli/pack-plugins.d.ts.map +1 -0
  111. package/dist/cli/pack-plugins.js +70 -0
  112. package/dist/cli/pack-plugins.js.map +1 -0
  113. package/dist/cli/plugin-command.test.d.ts +2 -0
  114. package/dist/cli/plugin-command.test.d.ts.map +1 -0
  115. package/dist/cli/plugin-command.test.js +114 -0
  116. package/dist/cli/plugin-command.test.js.map +1 -0
  117. package/dist/cli/plugin.d.ts +30 -0
  118. package/dist/cli/plugin.d.ts.map +1 -0
  119. package/dist/cli/plugin.js +291 -0
  120. package/dist/cli/plugin.js.map +1 -0
  121. package/dist/cli/promote-command.test.d.ts +2 -0
  122. package/dist/cli/promote-command.test.d.ts.map +1 -0
  123. package/dist/cli/promote-command.test.js +151 -0
  124. package/dist/cli/promote-command.test.js.map +1 -0
  125. package/dist/cli/promote.d.ts +12 -0
  126. package/dist/cli/promote.d.ts.map +1 -0
  127. package/dist/cli/promote.js +364 -0
  128. package/dist/cli/promote.js.map +1 -0
  129. package/dist/cli/secret-scan.d.ts +21 -0
  130. package/dist/cli/secret-scan.d.ts.map +1 -0
  131. package/dist/cli/secret-scan.js +114 -0
  132. package/dist/cli/secret-scan.js.map +1 -0
  133. package/dist/cli/sync-check.d.ts.map +1 -1
  134. package/dist/cli/sync-check.js +9 -0
  135. package/dist/cli/sync-check.js.map +1 -1
  136. package/dist/cli/sync-check.test.js +5 -4
  137. package/dist/cli/sync-check.test.js.map +1 -1
  138. package/dist/cli/team-commands.test.js +14 -2
  139. package/dist/cli/team-commands.test.js.map +1 -1
  140. package/dist/cli/team-sources.test.js +10 -0
  141. package/dist/cli/team-sources.test.js.map +1 -1
  142. package/dist/cli/types.d.ts +1 -1
  143. package/dist/cli/types.d.ts.map +1 -1
  144. package/dist/cli/update.d.ts.map +1 -1
  145. package/dist/cli/update.js +18 -0
  146. package/dist/cli/update.js.map +1 -1
  147. package/dist/cli/windsurf-target.test.d.ts +2 -0
  148. package/dist/cli/windsurf-target.test.d.ts.map +1 -0
  149. package/dist/cli/windsurf-target.test.js +62 -0
  150. package/dist/cli/windsurf-target.test.js.map +1 -0
  151. package/dist/orchestrator/plugins/agent-plugins.test.d.ts +2 -0
  152. package/dist/orchestrator/plugins/agent-plugins.test.d.ts.map +1 -0
  153. package/dist/orchestrator/plugins/agent-plugins.test.js +32 -0
  154. package/dist/orchestrator/plugins/agent-plugins.test.js.map +1 -0
  155. package/dist/orchestrator/plugins/registry.test.d.ts +2 -0
  156. package/dist/orchestrator/plugins/registry.test.d.ts.map +1 -0
  157. package/dist/orchestrator/plugins/registry.test.js +37 -0
  158. package/dist/orchestrator/plugins/registry.test.js.map +1 -0
  159. package/package.json +2 -1
  160. package/src/cli/adapters/antigravity.ts +2 -1
  161. package/src/cli/adapters/claude-code.ts +0 -1
  162. package/src/cli/adapters/cursor.ts +8 -1
  163. package/src/cli/adapters/opencode.ts +18 -6
  164. package/src/cli/adapters/rules-dir-base.test.ts +28 -18
  165. package/src/cli/adapters/rules-dir-base.ts +51 -90
  166. package/src/cli/adapters/single-file-base.ts +53 -14
  167. package/src/cli/adapters/vscode.ts +2 -1
  168. package/src/cli/adapters/windsurf.ts +11 -1
  169. package/src/cli/agent-plugin.test.ts +267 -0
  170. package/src/cli/agent-plugin.ts +469 -0
  171. package/src/cli/baseline.ts +115 -32
  172. package/src/cli/ci.ts +19 -4
  173. package/src/cli/codex-target.test.ts +15 -1
  174. package/src/cli/convoy/gates.ts +9 -142
  175. package/src/cli/copy.ts +0 -25
  176. package/src/cli/dispatcher.test.ts +2 -2
  177. package/src/cli/docs-accuracy.test.ts +2 -0
  178. package/src/cli/doctor.test.ts +2 -2
  179. package/src/cli/doctor.ts +2 -0
  180. package/src/cli/explain.ts +36 -2
  181. package/src/cli/fixtures/lessons-template-1.0.md +70 -0
  182. package/src/cli/init.test.ts +82 -42
  183. package/src/cli/layers.test.ts +2 -2
  184. package/src/cli/layers.ts +144 -14
  185. package/src/cli/legacy-install.test.ts +11 -1
  186. package/src/cli/lesson-command.test.ts +117 -0
  187. package/src/cli/lesson.ts +215 -266
  188. package/src/cli/lessons.test.ts +254 -0
  189. package/src/cli/lessons.ts +540 -0
  190. package/src/cli/managed-paths.ts +3 -1
  191. package/src/cli/mcp-audit.ts +2 -0
  192. package/src/cli/mcp-upgrade.test.ts +26 -1
  193. package/src/cli/mcp.ts +22 -3
  194. package/src/cli/pack-plugins.ts +70 -0
  195. package/src/cli/plugin-command.test.ts +125 -0
  196. package/src/cli/plugin.ts +309 -0
  197. package/src/cli/promote-command.test.ts +170 -0
  198. package/src/cli/promote.ts +371 -0
  199. package/src/cli/secret-scan.ts +154 -0
  200. package/src/cli/sync-check.test.ts +5 -4
  201. package/src/cli/sync-check.ts +9 -0
  202. package/src/cli/team-commands.test.ts +18 -2
  203. package/src/cli/team-sources.test.ts +11 -0
  204. package/src/cli/types.ts +1 -1
  205. package/src/cli/update.ts +20 -0
  206. package/src/cli/windsurf-target.test.ts +70 -0
  207. package/src/dashboard/node_modules/.vite/deps/_metadata.json +6 -6
  208. package/src/orchestrator/agents/researcher.agent.md +1 -1
  209. package/src/orchestrator/customizations/LESSONS-LEARNED.md +10 -66
  210. package/src/orchestrator/customizations/README.md +2 -1
  211. package/src/orchestrator/customizations/logs/README.md +1 -1
  212. package/src/orchestrator/plugins/agent-plugins.test.ts +34 -0
  213. package/src/orchestrator/plugins/astro/mcp.json +9 -0
  214. package/src/orchestrator/plugins/astro/plugin.json +21 -0
  215. package/src/orchestrator/plugins/chrome-devtools/mcp.json +13 -0
  216. package/src/orchestrator/plugins/chrome-devtools/plugin.json +21 -0
  217. package/src/orchestrator/plugins/cloudflare/mcp.json +9 -0
  218. package/src/orchestrator/plugins/cloudflare/plugin.json +21 -0
  219. package/src/orchestrator/plugins/contentful/mcp.json +13 -0
  220. package/src/orchestrator/plugins/contentful/plugin.json +21 -0
  221. package/src/orchestrator/plugins/convex/mcp.json +15 -0
  222. package/src/orchestrator/plugins/convex/plugin.json +21 -0
  223. package/src/orchestrator/plugins/coolify/mcp.json +13 -0
  224. package/src/orchestrator/plugins/coolify/plugin.json +25 -0
  225. package/src/orchestrator/plugins/cypress/plugin.json +21 -0
  226. package/src/orchestrator/plugins/drizzle/plugin.json +21 -0
  227. package/src/orchestrator/plugins/expo/mcp.json +9 -0
  228. package/src/orchestrator/plugins/expo/plugin.json +21 -0
  229. package/src/orchestrator/plugins/figma/mcp.json +9 -0
  230. package/src/orchestrator/plugins/figma/plugin.json +21 -0
  231. package/src/orchestrator/plugins/hetzner/plugin.json +24 -0
  232. package/src/orchestrator/plugins/jira/mcp.json +9 -0
  233. package/src/orchestrator/plugins/jira/plugin.json +21 -0
  234. package/src/orchestrator/plugins/linear/mcp.json +9 -0
  235. package/src/orchestrator/plugins/linear/plugin.json +21 -0
  236. package/src/orchestrator/plugins/netlify/mcp.json +13 -0
  237. package/src/orchestrator/plugins/netlify/plugin.json +21 -0
  238. package/src/orchestrator/plugins/nextjs/mcp.json +13 -0
  239. package/src/orchestrator/plugins/nextjs/plugin.json +21 -0
  240. package/src/orchestrator/plugins/notion/mcp.json +9 -0
  241. package/src/orchestrator/plugins/notion/plugin.json +21 -0
  242. package/src/orchestrator/plugins/nx/mcp.json +14 -0
  243. package/src/orchestrator/plugins/nx/plugin.json +21 -0
  244. package/src/orchestrator/plugins/playwright/mcp.json +13 -0
  245. package/src/orchestrator/plugins/playwright/plugin.json +21 -0
  246. package/src/orchestrator/plugins/prisma/mcp.json +14 -0
  247. package/src/orchestrator/plugins/prisma/plugin.json +21 -0
  248. package/src/orchestrator/plugins/registry.test.ts +42 -0
  249. package/src/orchestrator/plugins/resend/mcp.json +13 -0
  250. package/src/orchestrator/plugins/resend/plugin.json +24 -0
  251. package/src/orchestrator/plugins/sanity/mcp.json +9 -0
  252. package/src/orchestrator/plugins/sanity/plugin.json +21 -0
  253. package/src/orchestrator/plugins/sentry/mcp.json +12 -0
  254. package/src/orchestrator/plugins/sentry/plugin.json +24 -0
  255. package/src/orchestrator/plugins/slack/mcp.json +13 -0
  256. package/src/orchestrator/plugins/slack/plugin.json +24 -0
  257. package/src/orchestrator/plugins/strapi/mcp.json +13 -0
  258. package/src/orchestrator/plugins/strapi/plugin.json +21 -0
  259. package/src/orchestrator/plugins/stripe/mcp.json +9 -0
  260. package/src/orchestrator/plugins/stripe/plugin.json +21 -0
  261. package/src/orchestrator/plugins/supabase/mcp.json +9 -0
  262. package/src/orchestrator/plugins/supabase/plugin.json +21 -0
  263. package/src/orchestrator/plugins/teams/plugin.json +24 -0
  264. package/src/orchestrator/plugins/trello/mcp.json +13 -0
  265. package/src/orchestrator/plugins/trello/plugin.json +25 -0
  266. package/src/orchestrator/plugins/turborepo/plugin.json +21 -0
  267. package/src/orchestrator/plugins/vercel/mcp.json +9 -0
  268. package/src/orchestrator/plugins/vercel/plugin.json +21 -0
  269. package/src/orchestrator/plugins/vitest/plugin.json +21 -0
  270. package/src/orchestrator/skill-config-links.test.ts +2 -1
  271. package/src/orchestrator/skills/agent-hooks/HOOKS-REFERENCE.md +1 -1
  272. package/src/orchestrator/skills/agent-hooks/SKILL.md +1 -1
  273. package/src/orchestrator/skills/decomposition/SKILL.md +1 -1
  274. package/src/orchestrator/skills/memory-merger/SKILL.md +17 -21
  275. package/src/orchestrator/skills/self-improvement/LESSON-CATEGORIES.md +44 -23
  276. package/src/orchestrator/skills/self-improvement/SKILL.md +30 -15
  277. /package/src/orchestrator/plugins/astro/{SKILL.md → skills/astro-framework/SKILL.md} +0 -0
  278. /package/src/orchestrator/plugins/chrome-devtools/{SKILL.md → skills/browser-testing/SKILL.md} +0 -0
  279. /package/src/orchestrator/plugins/cloudflare/{SKILL.md → skills/cloudflare-platform/SKILL.md} +0 -0
  280. /package/src/orchestrator/plugins/contentful/{SKILL.md → skills/contentful-cms/SKILL.md} +0 -0
  281. /package/src/orchestrator/plugins/convex/{SKILL.md → skills/convex-database/SKILL.md} +0 -0
  282. /package/src/orchestrator/plugins/coolify/{SKILL.md → skills/coolify-deployment/SKILL.md} +0 -0
  283. /package/src/orchestrator/plugins/cypress/{SKILL.md → skills/cypress-testing/SKILL.md} +0 -0
  284. /package/src/orchestrator/plugins/drizzle/{SKILL.md → skills/drizzle-orm/SKILL.md} +0 -0
  285. /package/src/orchestrator/plugins/expo/{SKILL.md → skills/expo-development/SKILL.md} +0 -0
  286. /package/src/orchestrator/plugins/figma/{SKILL.md → skills/figma-design/SKILL.md} +0 -0
  287. /package/src/orchestrator/plugins/hetzner/{SKILL.md → skills/hetzner-cloud/SKILL.md} +0 -0
  288. /package/src/orchestrator/plugins/jira/{SKILL.md → skills/jira-management/SKILL.md} +0 -0
  289. /package/src/orchestrator/plugins/linear/{SKILL.md → skills/linear-task-management/SKILL.md} +0 -0
  290. /package/src/orchestrator/plugins/netlify/{SKILL.md → skills/netlify-deployment/SKILL.md} +0 -0
  291. /package/src/orchestrator/plugins/nextjs/{SKILL.md → skills/nextjs-framework/SKILL.md} +0 -0
  292. /package/src/orchestrator/plugins/notion/{SKILL.md → skills/notion-knowledge-management/SKILL.md} +0 -0
  293. /package/src/orchestrator/plugins/nx/{SKILL.md → skills/nx-workspace/SKILL.md} +0 -0
  294. /package/src/orchestrator/plugins/playwright/{SKILL.md → skills/playwright-testing/SKILL.md} +0 -0
  295. /package/src/orchestrator/plugins/prisma/{SKILL.md → skills/prisma-database/SKILL.md} +0 -0
  296. /package/src/orchestrator/plugins/resend/{SKILL.md → skills/resend-email/SKILL.md} +0 -0
  297. /package/src/orchestrator/plugins/sanity/{SKILL.md → skills/sanity-cms/SKILL.md} +0 -0
  298. /package/src/orchestrator/plugins/sentry/{SKILL.md → skills/sentry-monitoring/SKILL.md} +0 -0
  299. /package/src/orchestrator/plugins/slack/{SKILL.md → skills/slack-notifications/SKILL.md} +0 -0
  300. /package/src/orchestrator/plugins/strapi/{SKILL.md → skills/strapi-cms/SKILL.md} +0 -0
  301. /package/src/orchestrator/plugins/stripe/{SKILL.md → skills/stripe-payments/SKILL.md} +0 -0
  302. /package/src/orchestrator/plugins/supabase/{SKILL.md → skills/supabase-database/SKILL.md} +0 -0
  303. /package/src/orchestrator/plugins/teams/{SKILL.md → skills/teams-notifications/SKILL.md} +0 -0
  304. /package/src/orchestrator/plugins/trello/{SKILL.md → skills/trello-task-management/SKILL.md} +0 -0
  305. /package/src/orchestrator/plugins/turborepo/{SKILL.md → skills/turborepo-monorepo/SKILL.md} +0 -0
  306. /package/src/orchestrator/plugins/vercel/{SKILL.md → skills/vercel-deployment/SKILL.md} +0 -0
  307. /package/src/orchestrator/plugins/vitest/{SKILL.md → skills/vitest-testing/SKILL.md} +0 -0
@@ -0,0 +1,540 @@
1
+ import { createHash } from 'node:crypto'
2
+ import { existsSync, mkdirSync, readFileSync, readdirSync, statSync, writeFileSync } from 'node:fs'
3
+ import { dirname, isAbsolute, join, relative, resolve, sep } from 'node:path'
4
+ import { parse as parseYaml, stringify as stringifyYaml } from 'yaml'
5
+
6
+ /**
7
+ * Lessons: what agents on a project learned the hard way, kept as one file each.
8
+ *
9
+ * They used to be entries appended to `.opencastle/LESSONS-LEARNED.md`, each
10
+ * numbered one past the highest number in the file. On a team that is the
11
+ * shape of a merge conflict: two branches each append at the end and each
12
+ * call theirs LES-042. One file per lesson, named by date and title, merges
13
+ * like any other new file, and the index agents read first is compiled from
14
+ * them — rewritten by every `sync`, checked by `sync --check`, never edited.
15
+ *
16
+ * A lesson can cite the code it is about. Copilot Memory showed the value of
17
+ * that: a memory checked against the current code before use does not mislead
18
+ * an agent after a refactor. Here each cited file's fingerprint, taken when the
19
+ * lesson was last verified, lets `doctor` say which lessons the code has moved
20
+ * under — without git history, which a shallow CI clone does not have.
21
+ */
22
+
23
+ export const LESSON_CATEGORIES = [
24
+ 'task-management',
25
+ 'jira',
26
+ 'mcp-tools',
27
+ 'codebase-tool',
28
+ 'terminal',
29
+ 'framework',
30
+ 'cms',
31
+ 'database',
32
+ 'git',
33
+ 'deployment',
34
+ 'browser-testing',
35
+ 'general',
36
+ ] as const
37
+ export type LessonCategory = (typeof LESSON_CATEGORIES)[number]
38
+
39
+ export const LESSON_SEVERITIES = ['high', 'medium', 'low'] as const
40
+ export type LessonSeverity = (typeof LESSON_SEVERITIES)[number]
41
+
42
+ /** Relative to `.opencastle/`. */
43
+ export const LESSONS_DIR = 'lessons'
44
+ export const LESSONS_INDEX = 'LESSONS-LEARNED.md'
45
+
46
+ /** The first line of a compiled index; a file without it is the old single-file log. */
47
+ export const INDEX_MARKER =
48
+ '<!-- Generated by OpenCastle from the files in lessons/. Add a lesson with "opencastle lesson"; this index is rewritten by every sync. -->'
49
+
50
+ export interface Lesson {
51
+ id: string
52
+ title: string
53
+ category: string
54
+ severity: string
55
+ /** YYYY-MM-DD. */
56
+ added: string
57
+ /** Project-relative paths, optionally `:line`, the lesson is about. */
58
+ citations: string[]
59
+ /** YYYY-MM-DD of the last check that the lesson still holds. */
60
+ verified?: string
61
+ /** Each cited file's content fingerprint at that check, by path. */
62
+ fingerprints?: Record<string, string>
63
+ status: 'active' | 'archived'
64
+ /** The skill or instruction file an archived lesson was merged into. */
65
+ mergedInto?: string
66
+ /** Where a lesson came from, when not from `opencastle lesson`. */
67
+ source?: string
68
+ /** Markdown: Problem, Wrong approach, Correct approach, Why. */
69
+ body: string
70
+ /** File name within `lessons/`. */
71
+ file: string
72
+ }
73
+
74
+ export function isLessonCategory(s: string): s is LessonCategory {
75
+ return (LESSON_CATEGORIES as ReadonlyArray<string>).includes(s)
76
+ }
77
+
78
+ export function isLessonSeverity(s: string): s is LessonSeverity {
79
+ return (LESSON_SEVERITIES as ReadonlyArray<string>).includes(s)
80
+ }
81
+
82
+ export function today(): string {
83
+ return new Date().toISOString().slice(0, 10)
84
+ }
85
+
86
+ /** `quote shell variables` → `quote-shell-variables`, cut at a word under 50 characters. */
87
+ export function slugOf(title: string): string {
88
+ const words = title
89
+ .toLowerCase()
90
+ .normalize('NFKD')
91
+ .replace(/[\u0300-\u036f]/g, '')
92
+ .replace(/[^a-z0-9]+/g, ' ')
93
+ .trim()
94
+ .split(/\s+/)
95
+ .filter(Boolean)
96
+ let slug = ''
97
+ for (const w of words) {
98
+ const next = slug ? `${slug}-${w}` : w
99
+ if (next.length > 50) break
100
+ slug = next
101
+ }
102
+ return slug || 'lesson'
103
+ }
104
+
105
+ /** A new lesson's id: its date and title, made unique among `taken`. */
106
+ export function newLessonId(title: string, date: string, taken: Set<string>): string {
107
+ const base = `${date}-${slugOf(title)}`
108
+ let id = base
109
+ for (let n = 2; taken.has(id); n++) id = `${base}-${n}`
110
+ return id
111
+ }
112
+
113
+ // ── One lesson file ──────────────────────────────────────────
114
+
115
+ export function renderLesson(lesson: Omit<Lesson, 'file'>): string {
116
+ const meta: Record<string, unknown> = {
117
+ id: lesson.id,
118
+ title: lesson.title,
119
+ category: lesson.category,
120
+ severity: lesson.severity,
121
+ added: lesson.added,
122
+ }
123
+ if (lesson.citations.length > 0) meta.citations = lesson.citations
124
+ if (lesson.verified) meta.verified = lesson.verified
125
+ if (lesson.fingerprints && Object.keys(lesson.fingerprints).length > 0) meta.fingerprints = lesson.fingerprints
126
+ if (lesson.status === 'archived') meta.status = 'archived'
127
+ if (lesson.mergedInto) meta.mergedInto = lesson.mergedInto
128
+ if (lesson.source) meta.source = lesson.source
129
+ // Strings stay strings: an unquoted date would come back from YAML as a Date.
130
+ const yaml = stringifyYaml(meta, { defaultStringType: 'QUOTE_DOUBLE', defaultKeyType: 'PLAIN', lineWidth: 0 })
131
+ return `---\n${yaml}---\n\n${lesson.body.trim()}\n`
132
+ }
133
+
134
+ /** The body for a lesson written from its parts. */
135
+ export function lessonBody(parts: { problem: string; wrong?: string; correct?: string; why?: string }): string {
136
+ const out = [`**Problem:** ${parts.problem.trim()}`]
137
+ if (parts.wrong) out.push(`**Wrong approach:** ${parts.wrong.trim()}`)
138
+ if (parts.correct) out.push(`**Correct approach:** ${parts.correct.trim()}`)
139
+ if (parts.why) out.push(`**Why:** ${parts.why.trim()}`)
140
+ return out.join('\n\n')
141
+ }
142
+
143
+ const FRONTMATTER = /^\uFEFF?---\r?\n([\s\S]*?)\r?\n---\r?\n?([\s\S]*)$/
144
+
145
+ /** Parse one lesson file. Returns an error string for one that cannot be read as a lesson. */
146
+ export function parseLesson(text: string, file: string): Lesson | string {
147
+ const m = FRONTMATTER.exec(text)
148
+ if (!m) return 'has no frontmatter'
149
+ let meta: Record<string, unknown>
150
+ try {
151
+ meta = (parseYaml(m[1]) ?? {}) as Record<string, unknown>
152
+ } catch (err) {
153
+ return `has frontmatter that is not valid YAML — ${(err as Error).message}`
154
+ }
155
+ const str = (k: string): string | undefined => {
156
+ const v = meta[k]
157
+ if (v instanceof Date) return v.toISOString().slice(0, 10)
158
+ return typeof v === 'string' || typeof v === 'number' ? String(v) : undefined
159
+ }
160
+ const id = str('id') ?? file.replace(/\.md$/, '')
161
+ const title = str('title')
162
+ if (!title) return 'has no title'
163
+ const citations = Array.isArray(meta.citations) ? meta.citations.filter((c): c is string => typeof c === 'string') : []
164
+ const prints = meta.fingerprints && typeof meta.fingerprints === 'object' && !Array.isArray(meta.fingerprints)
165
+ ? Object.fromEntries(Object.entries(meta.fingerprints).filter((e): e is [string, string] => typeof e[1] === 'string'))
166
+ : undefined
167
+ return {
168
+ id,
169
+ title,
170
+ category: str('category') ?? 'general',
171
+ severity: str('severity') ?? 'medium',
172
+ added: str('added') ?? '',
173
+ citations,
174
+ verified: str('verified'),
175
+ ...(prints && Object.keys(prints).length > 0 && { fingerprints: prints }),
176
+ status: str('status') === 'archived' ? 'archived' : 'active',
177
+ mergedInto: str('mergedInto'),
178
+ source: str('source'),
179
+ body: m[2].trim(),
180
+ file,
181
+ }
182
+ }
183
+
184
+ /** Every lesson in `<customizations>/lessons/`, and the files that could not be read as one. */
185
+ export function readLessons(customizationsDir: string): { lessons: Lesson[]; problems: string[] } {
186
+ const dir = join(customizationsDir, LESSONS_DIR)
187
+ const lessons: Lesson[] = []
188
+ const problems: string[] = []
189
+ let names: string[]
190
+ try {
191
+ names = readdirSync(dir)
192
+ } catch {
193
+ return { lessons, problems }
194
+ }
195
+ for (const name of names.sort()) {
196
+ if (!name.endsWith('.md') || name.startsWith('.')) continue
197
+ let text: string
198
+ try {
199
+ text = readFileSync(join(dir, name), 'utf8')
200
+ } catch (err) {
201
+ problems.push(`${LESSONS_DIR}/${name} cannot be read — ${(err as Error).message}`)
202
+ continue
203
+ }
204
+ const parsed = parseLesson(text, name)
205
+ if (typeof parsed === 'string') problems.push(`${LESSONS_DIR}/${name} ${parsed}`)
206
+ else lessons.push(parsed)
207
+ }
208
+ return { lessons, problems }
209
+ }
210
+
211
+ export function findLesson(lessons: Lesson[], idOrFile: string): Lesson | undefined {
212
+ const want = idOrFile.replace(/^.*[\\/]/, '').replace(/\.md$/, '')
213
+ return lessons.find((l) => l.id === want || l.file.replace(/\.md$/, '') === want)
214
+ }
215
+
216
+ // ── The index agents read ────────────────────────────────────
217
+
218
+ const byDate = (a: Lesson, b: Lesson): number =>
219
+ a.added < b.added ? -1 : a.added > b.added ? 1 : a.id < b.id ? -1 : a.id > b.id ? 1 : 0
220
+
221
+ /** One line of Markdown, whatever a title holds. */
222
+ function inline(text: string): string {
223
+ return text.replace(/[\r\n]+/g, ' ').trim()
224
+ }
225
+
226
+ export function renderIndex(lessons: Lesson[]): string {
227
+ const active = lessons.filter((l) => l.status === 'active')
228
+ const archived = lessons.filter((l) => l.status === 'archived')
229
+ const out: string[] = [
230
+ INDEX_MARKER,
231
+ '',
232
+ '# Lessons Learned',
233
+ '',
234
+ 'What agents on this project learned the hard way: a command that failed, a',
235
+ 'tool quirk, a convention written down nowhere else. **Read this before you',
236
+ 'start work**, then open the lessons that match your task.',
237
+ '',
238
+ 'Each lesson is a file in [`lessons/`](lessons/). Add one with',
239
+ '`opencastle lesson --title ... --category ... --severity ... --problem ...`',
240
+ '(and `--cite <path>` for the code it is about). Do not edit this index:',
241
+ 'it is rewritten from those files by every `opencastle sync`.',
242
+ ]
243
+ if (active.length === 0) out.push('', 'No lessons yet.')
244
+ const categories = [...new Set(active.map((l) => l.category))].sort()
245
+ for (const category of categories) {
246
+ out.push('', `## ${category}`, '')
247
+ for (const l of active.filter((x) => x.category === category).sort(byDate)) {
248
+ const cites = l.citations.length > 0 ? ` · cites ${l.citations.map((c) => `\`${c}\``).join(', ')}` : ''
249
+ out.push(`- **${inline(l.title)}** — \`${l.severity}\` · ${l.added || 'undated'}${cites} · [${LESSONS_DIR}/${l.file}](${LESSONS_DIR}/${l.file})`)
250
+ }
251
+ }
252
+ if (archived.length > 0) {
253
+ out.push('', '## Archived', '', 'Merged into a skill or instruction file, where agents now meet them. Kept for the record.', '')
254
+ for (const l of archived.sort(byDate)) {
255
+ const into = l.mergedInto ? ` → \`${l.mergedInto}\`` : ''
256
+ out.push(`- **${inline(l.title)}**${into} · [${LESSONS_DIR}/${l.file}](${LESSONS_DIR}/${l.file})`)
257
+ }
258
+ }
259
+ return out.join('\n') + '\n'
260
+ }
261
+
262
+ export function isCompiledIndex(text: string): boolean {
263
+ return text.replace(/^\uFEFF/, '').trimStart().startsWith(INDEX_MARKER)
264
+ }
265
+
266
+ // ── The old single-file log ──────────────────────────────────
267
+
268
+ /**
269
+ * The shipped template, whitespace-normalised and hashed, in every version a
270
+ * release copied into projects. A file that is still exactly one of these has
271
+ * nothing of the team's in it, so moving to the new index needs no backup.
272
+ */
273
+ const LEGACY_TEMPLATES = new Set([
274
+ '575e04ca16faf38f222e8d367c18f829de34f15131aa97a48ed30eeb32bf6fb2',
275
+ '81360338e425d73813368b4d15c950da7b48f858df3c364e461223f766599b11',
276
+ ])
277
+
278
+ function templateHash(text: string): string {
279
+ return createHash('sha256').update(text.replace(/\s+/g, ' ').trim()).digest('hex')
280
+ }
281
+
282
+ /**
283
+ * The lessons in an old `LESSONS-LEARNED.md`, wherever in the file they are.
284
+ *
285
+ * Agents appended them wherever they saw fit — after the index as often as
286
+ * before it — and with categories and severities the CLI never offered, so
287
+ * this reads each `### LES-NNN:` block on its own and keeps what it says.
288
+ */
289
+ export function parseLegacyLessons(text: string): Array<Omit<Lesson, 'file'>> {
290
+ const lines = text.replace(/\r\n/g, '\n').split('\n')
291
+ const out: Array<Omit<Lesson, 'file'>> = []
292
+ for (let i = 0; i < lines.length; i++) {
293
+ const head = /^###\s+(LES-\d+)\s*:\s*(.+?)\s*$/.exec(lines[i])
294
+ if (!head) continue
295
+ const block: string[] = []
296
+ let j = i + 1
297
+ for (; j < lines.length; j++) {
298
+ if (/^#{1,3}\s/.test(lines[j])) break
299
+ block.push(lines[j])
300
+ }
301
+ i = j - 1
302
+ const field = (name: string): string | undefined => {
303
+ for (const line of block) {
304
+ const m = new RegExp(`^\\|\\s*\\*\\*${name}\\*\\*\\s*\\|\\s*(.*?)\\s*\\|\\s*$`).exec(line)
305
+ if (m) return m[1]
306
+ }
307
+ return undefined
308
+ }
309
+ const firstWord = (v: string | undefined): string | undefined => {
310
+ if (!v) return undefined
311
+ const ticked = /`([^`]+)`/.exec(v)
312
+ return (ticked ? ticked[1] : v.split(/\s+/)[0]).trim() || undefined
313
+ }
314
+ const body = block
315
+ .filter((l) => !/^\s*\|.*\|\s*$/.test(l))
316
+ .filter((l) => !/^\s*`{3,}\s*(markdown)?\s*$/.test(l))
317
+ .join('\n')
318
+ .replace(/(\n\s*---\s*)+\s*$/, '')
319
+ .trim()
320
+ out.push({
321
+ id: head[1],
322
+ title: head[2],
323
+ category: firstWord(field('Category')) ?? 'general',
324
+ severity: firstWord(field('Severity')) ?? 'medium',
325
+ added: firstWord(field('Added')) ?? '',
326
+ citations: [],
327
+ status: 'active',
328
+ body,
329
+ })
330
+ }
331
+ return out
332
+ }
333
+
334
+ export interface LessonsSync {
335
+ /** Lessons moved out of the old single file. */
336
+ migrated: number
337
+ /** Where the old file was kept, when it held anything of the team's. */
338
+ backup?: string
339
+ index: 'created' | 'updated' | 'unchanged' | 'absent'
340
+ problems: string[]
341
+ }
342
+
343
+ /**
344
+ * Bring `.opencastle/` to the current shape: lessons in the old single file
345
+ * moved into `lessons/`, and the index rewritten from the files. Run by `sync`
346
+ * and by every `opencastle lesson` that writes.
347
+ *
348
+ * A project with neither an index nor a `lessons/` directory is left as it is:
349
+ * someone removed the file, and putting it back is not ours to decide.
350
+ */
351
+ export function syncLessons(customizationsDir: string): LessonsSync {
352
+ const indexPath = join(customizationsDir, LESSONS_INDEX)
353
+ const dir = join(customizationsDir, LESSONS_DIR)
354
+ const result: LessonsSync = { migrated: 0, index: 'absent', problems: [] }
355
+ let current: string | null = null
356
+ try {
357
+ current = readFileSync(indexPath, 'utf8')
358
+ } catch {
359
+ current = null
360
+ }
361
+
362
+ if (current !== null && !isCompiledIndex(current)) {
363
+ const legacy = parseLegacyLessons(current)
364
+ const { lessons: existing } = readLessons(customizationsDir)
365
+ const taken = new Set(existing.map((l) => l.id))
366
+ for (const lesson of legacy) {
367
+ // Run twice — an interrupted sync, or a teammate's sync merged in — and
368
+ // the lesson is already there under its number.
369
+ if (taken.has(lesson.id)) continue
370
+ mkdirSync(dir, { recursive: true })
371
+ writeFileSync(join(dir, `${lesson.id}-${slugOf(lesson.title)}.md`), renderLesson(lesson))
372
+ taken.add(lesson.id)
373
+ result.migrated++
374
+ }
375
+ if (legacy.length > 0 || !LEGACY_TEMPLATES.has(templateHash(current))) {
376
+ const backup = `${indexPath}.opencastle-backup`
377
+ if (!existsSync(backup)) writeFileSync(backup, current)
378
+ result.backup = relative(dirname(customizationsDir), backup).split(sep).join('/')
379
+ }
380
+ }
381
+
382
+ if (current === null && !existsSync(dir)) return result
383
+ const { lessons, problems } = readLessons(customizationsDir)
384
+ result.problems = problems
385
+ const next = renderIndex(lessons)
386
+ if (current === next) {
387
+ result.index = 'unchanged'
388
+ } else {
389
+ writeFileSync(indexPath, next)
390
+ result.index = current === null ? 'created' : 'updated'
391
+ }
392
+ return result
393
+ }
394
+
395
+ /**
396
+ * What `sync --check` and `doctor` say about the index, or null when it is
397
+ * current. Never writes.
398
+ */
399
+ export function lessonsIndexDrift(customizationsDir: string): string | null {
400
+ const indexPath = join(customizationsDir, LESSONS_INDEX)
401
+ const dir = join(customizationsDir, LESSONS_DIR)
402
+ let current: string | null
403
+ try {
404
+ current = readFileSync(indexPath, 'utf8')
405
+ } catch {
406
+ current = null
407
+ }
408
+ if (current !== null && !isCompiledIndex(current)) {
409
+ const n = parseLegacyLessons(current).length
410
+ return n > 0
411
+ ? `holds ${n} lesson(s) in the old single-file format; sync moves each into ${LESSONS_DIR}/`
412
+ : 'is the old single-file log; sync replaces it with an index of lessons/'
413
+ }
414
+ if (current === null) return existsSync(dir) ? `is missing, while ${LESSONS_DIR}/ has lessons to list` : null
415
+ const { lessons } = readLessons(customizationsDir)
416
+ return current === renderIndex(lessons) ? null : `does not list what is in ${LESSONS_DIR}/ — a lesson was added, changed or merged in`
417
+ }
418
+
419
+ // ── Citations ────────────────────────────────────────────────
420
+
421
+ /** The path part of a citation: `src/a.ts:12` and `src/a.ts#L12` both cite `src/a.ts`. */
422
+ export function citedPath(citation: string): string {
423
+ return citation.replace(/#L\d+(-L?\d+)?$/, '').replace(/:\d+(-\d+)?$/, '').replace(/^\.\//, '')
424
+ }
425
+
426
+ /** Why a citation cannot be recorded, or null when it can. */
427
+ export function citationProblem(projectRoot: string, citation: string): string | null {
428
+ const path = citedPath(citation)
429
+ if (!path || isAbsolute(path) || /^[A-Za-z]:[\\/]/.test(path)) return `cite a path relative to the project root, not ${citation}`
430
+ const abs = resolve(projectRoot, path)
431
+ if (relative(projectRoot, abs).startsWith('..')) return `${citation} is outside the project`
432
+ if (!existsSync(abs)) return `${citation} does not exist`
433
+ return null
434
+ }
435
+
436
+ /**
437
+ * A short digest of a file's content, line endings normalised so a checkout
438
+ * with `core.autocrlf` does not read as a change. Null for what is not a file.
439
+ */
440
+ export function fingerprintOf(projectRoot: string, path: string): string | null {
441
+ try {
442
+ const text = readFileSync(resolve(projectRoot, path), 'utf8').replace(/\r\n/g, '\n')
443
+ return createHash('sha256').update(text).digest('hex').slice(0, 12)
444
+ } catch {
445
+ return null
446
+ }
447
+ }
448
+
449
+ /** The fingerprint of every file a lesson cites, by path. */
450
+ export function fingerprintsOf(projectRoot: string, citations: string[]): Record<string, string> {
451
+ const out: Record<string, string> = {}
452
+ for (const c of citations) {
453
+ const path = citedPath(c)
454
+ const print = fingerprintOf(projectRoot, path)
455
+ if (print) out[path] = print
456
+ }
457
+ return out
458
+ }
459
+
460
+ export interface StaleCitation {
461
+ lesson: Lesson
462
+ citation: string
463
+ why: 'missing' | 'changed'
464
+ }
465
+
466
+ /**
467
+ * Citations whose file is gone, or whose content differs from its fingerprint
468
+ * when the lesson was last verified. A citation recorded with no fingerprint —
469
+ * a directory, or a lesson written by hand — is checked for existence only.
470
+ */
471
+ export function staleCitations(projectRoot: string, lessons: Lesson[]): StaleCitation[] {
472
+ const out: StaleCitation[] = []
473
+ for (const lesson of lessons) {
474
+ if (lesson.status !== 'active') continue
475
+ for (const citation of lesson.citations) {
476
+ const path = citedPath(citation)
477
+ const abs = resolve(projectRoot, path)
478
+ if (!existsSync(abs)) {
479
+ out.push({ lesson, citation, why: 'missing' })
480
+ continue
481
+ }
482
+ if (!statSync(abs).isFile()) continue
483
+ const want = lesson.fingerprints?.[path]
484
+ if (want && fingerprintOf(projectRoot, path) !== want) out.push({ lesson, citation, why: 'changed' })
485
+ }
486
+ }
487
+ return out
488
+ }
489
+
490
+ /** The check `doctor` runs on a project's lessons. */
491
+ export function checkLessons(projectRoot: string): {
492
+ ok: boolean
493
+ label: string
494
+ detail?: string
495
+ warning?: boolean
496
+ fix?: string
497
+ } {
498
+ const label = 'Lessons'
499
+ const dir = join(projectRoot, '.opencastle')
500
+ const drift = lessonsIndexDrift(dir)
501
+ if (drift) {
502
+ return { ok: true, warning: true, label, detail: `.opencastle/${LESSONS_INDEX} ${drift}`, fix: 'opencastle sync' }
503
+ }
504
+ const { lessons, problems } = readLessons(dir)
505
+ if (problems.length > 0) {
506
+ return {
507
+ ok: true,
508
+ warning: true,
509
+ label,
510
+ detail: problems.map((p) => `.opencastle/${p}`).join('; '),
511
+ fix: 'fix the frontmatter of each, or delete it',
512
+ }
513
+ }
514
+ const active = lessons.filter((l) => l.status === 'active')
515
+ if (active.length === 0) return { ok: true, label, detail: 'none recorded yet' }
516
+ const stale = staleCitations(projectRoot, active)
517
+ if (stale.length > 0) {
518
+ const said = stale.map((s) =>
519
+ s.why === 'missing'
520
+ ? `${s.lesson.id} cites ${s.citation}, which no longer exists`
521
+ : `${s.lesson.id} cites ${s.citation}, which has changed since it was verified${s.lesson.verified ? ` on ${s.lesson.verified}` : ''}`,
522
+ )
523
+ const ids = [...new Set(stale.map((s) => s.lesson.id))]
524
+ return {
525
+ ok: true,
526
+ warning: true,
527
+ label,
528
+ detail: said.join('; '),
529
+ fix:
530
+ `check that each still holds, then opencastle lesson verify ${ids[0]}${ids.length > 1 ? ' (and the others)' : ''} — ` +
531
+ 'with --cite <path> for a file that moved — or retire it with opencastle lesson archive <id> --into <file>',
532
+ }
533
+ }
534
+ const cited = active.filter((l) => l.citations.length > 0).length
535
+ return {
536
+ ok: true,
537
+ label,
538
+ detail: `${active.length} lesson(s)${cited > 0 ? `; the ${cited} that cite code match it` : ''}`,
539
+ }
540
+ }
@@ -49,8 +49,10 @@ export const ROOT_INSTRUCTION_FILES = [
49
49
  */
50
50
  const SUPERSEDED_FRAMEWORK: Record<string, string> = {
51
51
  '.claude/commands/': `.claude/${CLAUDE_COMMANDS_DIR}/`,
52
- // Codex never read `.codex/skills/`; its skills moved to the shared location.
52
+ // Codex never read `.codex/skills/`; its skills moved to the shared location,
53
+ // and OpenCode's followed.
53
54
  '.codex/skills/': '.agents/skills/',
55
+ '.opencode/skills/': '.agents/skills/',
54
56
  }
55
57
 
56
58
  function unique(values: string[]): string[] {
@@ -441,6 +441,8 @@ const OWN_SPELLING: Partial<Record<IdeChoice, (name: string) => string>> = {
441
441
  // Codex expands nothing: a variable reaches a server only by being named in
442
442
  // a field that reads one.
443
443
  codex: (n) => `env_vars, bearer_token_env_var or env_http_headers naming ${n}`,
444
+ // Antigravity expands none either, and has no field that reads a variable.
445
+ antigravity: (n) => `the value in your own ~/.gemini/config/mcp_config.json — Antigravity expands no variables, and a local server inherits ${n} from the environment`,
444
446
  }
445
447
 
446
448
  /** The first `${NAME}` this target would pass through literally, as `NAME → spelling`, or null. */
@@ -11,7 +11,8 @@ import { describe, it, expect, beforeEach, afterEach } from 'vitest'
11
11
  import { mkdtempSync, writeFileSync, readFileSync, rmSync, realpathSync, mkdirSync } from 'node:fs'
12
12
  import { join } from 'node:path'
13
13
  import { tmpdir } from 'node:os'
14
- import { upgradeGeneratedServers, rebuildMcpConfig, scaffoldMcpConfig } from './mcp.js'
14
+ import { upgradeGeneratedServers, rebuildMcpConfig, scaffoldMcpConfig, teamEntryFor } from './mcp.js'
15
+ import { auditMcpConfig } from './mcp-audit.js'
15
16
  import type { StackConfig } from './types.js'
16
17
 
17
18
  describe('upgradeGeneratedServers', () => {
@@ -22,6 +23,30 @@ describe('upgradeGeneratedServers', () => {
22
23
  expect(servers.Supabase).toEqual({ type: 'http', url: 'https://mcp.supabase.com/mcp' })
23
24
  })
24
25
 
26
+ it('moves Antigravity entries to serverUrl, and drops a ${NAME} it would send as text', () => {
27
+ // As every release before this one wrote them into .agents/mcp_config.json.
28
+ const servers: Record<string, unknown> = {
29
+ Supabase: { url: 'https://mcp.supabase.com/mcp' },
30
+ Coolify: {
31
+ command: 'npx',
32
+ args: ['-y', '@masonator/coolify-mcp@3.7.0'],
33
+ env: { COOLIFY_ACCESS_TOKEN: '${COOLIFY_ACCESS_TOKEN}', COOLIFY_BASE_URL: '${COOLIFY_BASE_URL}' },
34
+ },
35
+ }
36
+ expect(upgradeGeneratedServers(servers, 'antigravity', new Set(['Supabase', 'Coolify'])).sort()).toEqual(['Coolify', 'Supabase'])
37
+ expect(servers.Supabase).toEqual({ serverUrl: 'https://mcp.supabase.com/mcp' })
38
+ expect(servers.Coolify).toEqual({ command: 'npx', args: ['-y', '@masonator/coolify-mcp@3.7.0'] })
39
+ })
40
+
41
+ it('writes a team server for Antigravity in its shape, and the audit names what it cannot expand', () => {
42
+ const remote = teamEntryFor('docs', { url: 'https://docs.acme.example/mcp', headers: { Authorization: 'Bearer ${DOCS_TOKEN}' } }, 'antigravity').entry
43
+ expect(remote).toEqual({ serverUrl: 'https://docs.acme.example/mcp', headers: { Authorization: 'Bearer ${DOCS_TOKEN}' } })
44
+ const local = teamEntryFor('db', { command: 'npx', args: ['-y', 'db-mcp@1.0.0'], env: { DB_URL: '${DB_URL}', MODE: 'ro' } }, 'antigravity').entry
45
+ expect(local).toEqual({ command: 'npx', args: ['-y', 'db-mcp@1.0.0'], env: { MODE: 'ro' } })
46
+ const audit = auditMcpConfig({ mcpServers: { docs: remote } }, 'antigravity')
47
+ expect(audit.findings.find((f) => f.problem === 'unexpanded-variable')?.subject).toContain('${DOCS_TOKEN} →')
48
+ })
49
+
25
50
  it('moves a retired default to the current one, env vars and all', () => {
26
51
  // What earlier releases wrote into .mcp.json for Figma: a package that was
27
52
  // never published, with the token they asked for spelled into `env`.
package/src/cli/mcp.ts CHANGED
@@ -96,13 +96,24 @@ function transformMcpForIde(
96
96
  case 'windsurf':
97
97
  case 'antigravity': {
98
98
  // mcpServers format — no 'type' field
99
+ //
100
+ // Antigravity expands no variables in its MCP config: a `${NAME}` reaches
101
+ // the server as those characters. An entry that only forwards a variable
102
+ // under its own name therefore replaced the value the server would have
103
+ // inherited with literal text; it is left out, and the server reads the
104
+ // environment Antigravity was started in. Its MCP docs also require
105
+ // `serverUrl` for a remote server and call `url` a legacy field.
106
+ const antigravity = ide === 'antigravity' && !options.legacy;
99
107
  const mcpServers: Record<string, unknown> = {};
100
108
  for (const [name, server] of Object.entries(servers)) {
101
109
  if (server.type === 'stdio') {
110
+ const env = antigravity && server.env
111
+ ? Object.fromEntries(Object.entries(server.env).filter(([k, v]) => wholeReference(v) !== k))
112
+ : server.env;
102
113
  mcpServers[name] = {
103
114
  command: server.command,
104
115
  args: server.args,
105
- ...(server.env && { env: server.env }),
116
+ ...(env && Object.keys(env).length > 0 && { env }),
106
117
  };
107
118
  } else if (server.type === 'http') {
108
119
  // Strip VS Code ${input:...} placeholders for non-VS Code IDEs
@@ -115,7 +126,11 @@ function transformMcpForIde(
115
126
  // other targets in this group take the bare `url`.
116
127
  const headers = server.headers && { headers: server.headers };
117
128
  mcpServers[name] =
118
- ide === 'claude-code' && !options.legacy ? { type: 'http', url, ...headers } : { url, ...headers };
129
+ ide === 'claude-code' && !options.legacy
130
+ ? { type: 'http', url, ...headers }
131
+ : antigravity
132
+ ? { serverUrl: url, ...headers }
133
+ : { url, ...headers };
119
134
  }
120
135
  }
121
136
  return { mcpServers };
@@ -594,7 +609,7 @@ export function getMcpConfigRelPath(ide: IdeChoice): string {
594
609
  case 'opencode':
595
610
  return 'opencode.json';
596
611
  case 'windsurf':
597
- return '.windsurf/mcp.json';
612
+ return '.devin/mcp_config.json';
598
613
  case 'codex':
599
614
  return '.codex/config.toml';
600
615
  case 'antigravity':
@@ -718,6 +733,10 @@ export async function stripManagedMcpServers(
718
733
  */
719
734
  export const LEGACY_MCP_CONFIGS: Partial<Record<IdeChoice, string>> = {
720
735
  codex: '.codex/mcp.json',
736
+ // Windsurf, now Devin Desktop, never read a project `.windsurf/mcp.json`:
737
+ // Cascade reads one global file, and the default Devin Local agent reads
738
+ // `.devin/mcp_config.json`.
739
+ windsurf: '.windsurf/mcp.json',
721
740
  };
722
741
 
723
742
  /**