opencastle 0.38.2 → 1.1.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 (299) hide show
  1. package/README.md +89 -4
  2. package/bin/cli.mjs +20 -3
  3. package/dist/cli/adapters/antigravity.d.ts +1 -1
  4. package/dist/cli/adapters/antigravity.d.ts.map +1 -1
  5. package/dist/cli/adapters/claude-code.d.ts +8 -4
  6. package/dist/cli/adapters/claude-code.d.ts.map +1 -1
  7. package/dist/cli/adapters/claude-code.js +13 -7
  8. package/dist/cli/adapters/claude-code.js.map +1 -1
  9. package/dist/cli/adapters/codex.d.ts +1 -1
  10. package/dist/cli/adapters/codex.d.ts.map +1 -1
  11. package/dist/cli/adapters/cursor.d.ts +1 -1
  12. package/dist/cli/adapters/cursor.d.ts.map +1 -1
  13. package/dist/cli/adapters/opencode.d.ts +1 -1
  14. package/dist/cli/adapters/opencode.d.ts.map +1 -1
  15. package/dist/cli/adapters/rules-dir-base.d.ts +3 -2
  16. package/dist/cli/adapters/rules-dir-base.d.ts.map +1 -1
  17. package/dist/cli/adapters/rules-dir-base.js +13 -25
  18. package/dist/cli/adapters/rules-dir-base.js.map +1 -1
  19. package/dist/cli/adapters/single-file-base.d.ts +8 -1
  20. package/dist/cli/adapters/single-file-base.d.ts.map +1 -1
  21. package/dist/cli/adapters/single-file-base.js +43 -46
  22. package/dist/cli/adapters/single-file-base.js.map +1 -1
  23. package/dist/cli/adapters/vscode.d.ts +14 -3
  24. package/dist/cli/adapters/vscode.d.ts.map +1 -1
  25. package/dist/cli/adapters/vscode.js +63 -75
  26. package/dist/cli/adapters/vscode.js.map +1 -1
  27. package/dist/cli/adapters/windsurf.d.ts +1 -1
  28. package/dist/cli/adapters/windsurf.d.ts.map +1 -1
  29. package/dist/cli/baseline.d.ts +3 -0
  30. package/dist/cli/baseline.d.ts.map +1 -0
  31. package/dist/cli/baseline.js +280 -0
  32. package/dist/cli/baseline.js.map +1 -0
  33. package/dist/cli/ci.d.ts +18 -0
  34. package/dist/cli/ci.d.ts.map +1 -0
  35. package/dist/cli/ci.js +279 -0
  36. package/dist/cli/ci.js.map +1 -0
  37. package/dist/cli/command-namespace.d.ts +91 -0
  38. package/dist/cli/command-namespace.d.ts.map +1 -0
  39. package/dist/cli/command-namespace.js +218 -0
  40. package/dist/cli/command-namespace.js.map +1 -0
  41. package/dist/cli/command-namespace.test.d.ts +2 -0
  42. package/dist/cli/command-namespace.test.d.ts.map +1 -0
  43. package/dist/cli/command-namespace.test.js +356 -0
  44. package/dist/cli/command-namespace.test.js.map +1 -0
  45. package/dist/cli/copy.d.ts +1 -1
  46. package/dist/cli/copy.d.ts.map +1 -1
  47. package/dist/cli/copy.js +3 -2
  48. package/dist/cli/copy.js.map +1 -1
  49. package/dist/cli/dispatcher.test.js +2 -2
  50. package/dist/cli/dispatcher.test.js.map +1 -1
  51. package/dist/cli/docs-accuracy.test.js +5 -0
  52. package/dist/cli/docs-accuracy.test.js.map +1 -1
  53. package/dist/cli/doctor.d.ts +3 -3
  54. package/dist/cli/doctor.d.ts.map +1 -1
  55. package/dist/cli/doctor.js +66 -9
  56. package/dist/cli/doctor.js.map +1 -1
  57. package/dist/cli/doctor.test.js +2 -2
  58. package/dist/cli/doctor.test.js.map +1 -1
  59. package/dist/cli/explain.d.ts +3 -0
  60. package/dist/cli/explain.d.ts.map +1 -0
  61. package/dist/cli/explain.js +222 -0
  62. package/dist/cli/explain.js.map +1 -0
  63. package/dist/cli/fleet.d.ts +30 -0
  64. package/dist/cli/fleet.d.ts.map +1 -0
  65. package/dist/cli/fleet.js +149 -0
  66. package/dist/cli/fleet.js.map +1 -0
  67. package/dist/cli/github-report.d.ts +49 -0
  68. package/dist/cli/github-report.d.ts.map +1 -0
  69. package/dist/cli/github-report.js +161 -0
  70. package/dist/cli/github-report.js.map +1 -0
  71. package/dist/cli/github-report.test.d.ts +2 -0
  72. package/dist/cli/github-report.test.d.ts.map +1 -0
  73. package/dist/cli/github-report.test.js +146 -0
  74. package/dist/cli/github-report.test.js.map +1 -0
  75. package/dist/cli/init.d.ts.map +1 -1
  76. package/dist/cli/init.js +171 -96
  77. package/dist/cli/init.js.map +1 -1
  78. package/dist/cli/init.test.js +35 -29
  79. package/dist/cli/init.test.js.map +1 -1
  80. package/dist/cli/layers.d.ts +152 -0
  81. package/dist/cli/layers.d.ts.map +1 -0
  82. package/dist/cli/layers.js +932 -0
  83. package/dist/cli/layers.js.map +1 -0
  84. package/dist/cli/layers.test.d.ts +2 -0
  85. package/dist/cli/layers.test.d.ts.map +1 -0
  86. package/dist/cli/layers.test.js +483 -0
  87. package/dist/cli/layers.test.js.map +1 -0
  88. package/dist/cli/lock.d.ts +130 -0
  89. package/dist/cli/lock.d.ts.map +1 -0
  90. package/dist/cli/lock.js +320 -0
  91. package/dist/cli/lock.js.map +1 -0
  92. package/dist/cli/managed-paths.d.ts +18 -1
  93. package/dist/cli/managed-paths.d.ts.map +1 -1
  94. package/dist/cli/managed-paths.js +72 -2
  95. package/dist/cli/managed-paths.js.map +1 -1
  96. package/dist/cli/manifest.d.ts.map +1 -1
  97. package/dist/cli/manifest.js +2 -0
  98. package/dist/cli/manifest.js.map +1 -1
  99. package/dist/cli/mcp-audit.d.ts +164 -0
  100. package/dist/cli/mcp-audit.d.ts.map +1 -0
  101. package/dist/cli/mcp-audit.js +504 -0
  102. package/dist/cli/mcp-audit.js.map +1 -0
  103. package/dist/cli/mcp-audit.test.d.ts +2 -0
  104. package/dist/cli/mcp-audit.test.d.ts.map +1 -0
  105. package/dist/cli/mcp-audit.test.js +215 -0
  106. package/dist/cli/mcp-audit.test.js.map +1 -0
  107. package/dist/cli/mcp-upgrade.test.d.ts +2 -0
  108. package/dist/cli/mcp-upgrade.test.d.ts.map +1 -0
  109. package/dist/cli/mcp-upgrade.test.js +118 -0
  110. package/dist/cli/mcp-upgrade.test.js.map +1 -0
  111. package/dist/cli/mcp.d.ts +74 -5
  112. package/dist/cli/mcp.d.ts.map +1 -1
  113. package/dist/cli/mcp.js +340 -32
  114. package/dist/cli/mcp.js.map +1 -1
  115. package/dist/cli/policy.d.ts +58 -0
  116. package/dist/cli/policy.d.ts.map +1 -0
  117. package/dist/cli/policy.js +194 -0
  118. package/dist/cli/policy.js.map +1 -0
  119. package/dist/cli/publish-workflow.test.js +55 -1
  120. package/dist/cli/publish-workflow.test.js.map +1 -1
  121. package/dist/cli/remove.d.ts.map +1 -1
  122. package/dist/cli/remove.js +25 -6
  123. package/dist/cli/remove.js.map +1 -1
  124. package/dist/cli/review.d.ts +25 -0
  125. package/dist/cli/review.d.ts.map +1 -0
  126. package/dist/cli/review.js +437 -0
  127. package/dist/cli/review.js.map +1 -0
  128. package/dist/cli/status.d.ts +2 -0
  129. package/dist/cli/status.d.ts.map +1 -1
  130. package/dist/cli/status.js +25 -4
  131. package/dist/cli/status.js.map +1 -1
  132. package/dist/cli/status.test.js +5 -3
  133. package/dist/cli/status.test.js.map +1 -1
  134. package/dist/cli/sync-check.d.ts +16 -1
  135. package/dist/cli/sync-check.d.ts.map +1 -1
  136. package/dist/cli/sync-check.js +241 -17
  137. package/dist/cli/sync-check.js.map +1 -1
  138. package/dist/cli/sync-check.test.js +14 -8
  139. package/dist/cli/sync-check.test.js.map +1 -1
  140. package/dist/cli/sync.d.ts.map +1 -1
  141. package/dist/cli/sync.js +2 -0
  142. package/dist/cli/sync.js.map +1 -1
  143. package/dist/cli/team-ci.test.d.ts +2 -0
  144. package/dist/cli/team-ci.test.d.ts.map +1 -0
  145. package/dist/cli/team-ci.test.js +169 -0
  146. package/dist/cli/team-ci.test.js.map +1 -0
  147. package/dist/cli/team-commands.test.d.ts +2 -0
  148. package/dist/cli/team-commands.test.d.ts.map +1 -0
  149. package/dist/cli/team-commands.test.js +233 -0
  150. package/dist/cli/team-commands.test.js.map +1 -0
  151. package/dist/cli/team-config.d.ts +88 -0
  152. package/dist/cli/team-config.d.ts.map +1 -0
  153. package/dist/cli/team-config.js +261 -0
  154. package/dist/cli/team-config.js.map +1 -0
  155. package/dist/cli/team-health.d.ts +49 -0
  156. package/dist/cli/team-health.d.ts.map +1 -0
  157. package/dist/cli/team-health.js +205 -0
  158. package/dist/cli/team-health.js.map +1 -0
  159. package/dist/cli/team-sources.test.d.ts +2 -0
  160. package/dist/cli/team-sources.test.d.ts.map +1 -0
  161. package/dist/cli/team-sources.test.js +542 -0
  162. package/dist/cli/team-sources.test.js.map +1 -0
  163. package/dist/cli/types.d.ts +48 -2
  164. package/dist/cli/types.d.ts.map +1 -1
  165. package/dist/cli/types.js.map +1 -1
  166. package/dist/cli/update.d.ts.map +1 -1
  167. package/dist/cli/update.js +218 -44
  168. package/dist/cli/update.js.map +1 -1
  169. package/dist/cli/version-range.d.ts +24 -0
  170. package/dist/cli/version-range.d.ts.map +1 -0
  171. package/dist/cli/version-range.js +157 -0
  172. package/dist/cli/version-range.js.map +1 -0
  173. package/dist/cli/website-plugins.test.d.ts +2 -0
  174. package/dist/cli/website-plugins.test.d.ts.map +1 -0
  175. package/dist/cli/website-plugins.test.js +34 -0
  176. package/dist/cli/website-plugins.test.js.map +1 -0
  177. package/dist/orchestrator/plugins/chrome-devtools/config.d.ts.map +1 -1
  178. package/dist/orchestrator/plugins/chrome-devtools/config.js +11 -1
  179. package/dist/orchestrator/plugins/chrome-devtools/config.js.map +1 -1
  180. package/dist/orchestrator/plugins/contentful/config.d.ts.map +1 -1
  181. package/dist/orchestrator/plugins/contentful/config.js +11 -1
  182. package/dist/orchestrator/plugins/contentful/config.js.map +1 -1
  183. package/dist/orchestrator/plugins/convex/config.d.ts.map +1 -1
  184. package/dist/orchestrator/plugins/convex/config.js +11 -1
  185. package/dist/orchestrator/plugins/convex/config.js.map +1 -1
  186. package/dist/orchestrator/plugins/coolify/config.d.ts.map +1 -1
  187. package/dist/orchestrator/plugins/coolify/config.js +14 -1
  188. package/dist/orchestrator/plugins/coolify/config.js.map +1 -1
  189. package/dist/orchestrator/plugins/figma/config.d.ts.map +1 -1
  190. package/dist/orchestrator/plugins/figma/config.js +24 -13
  191. package/dist/orchestrator/plugins/figma/config.js.map +1 -1
  192. package/dist/orchestrator/plugins/linear/config.d.ts.map +1 -1
  193. package/dist/orchestrator/plugins/linear/config.js +27 -17
  194. package/dist/orchestrator/plugins/linear/config.js.map +1 -1
  195. package/dist/orchestrator/plugins/netlify/config.d.ts.map +1 -1
  196. package/dist/orchestrator/plugins/netlify/config.js +23 -9
  197. package/dist/orchestrator/plugins/netlify/config.js.map +1 -1
  198. package/dist/orchestrator/plugins/nextjs/config.d.ts.map +1 -1
  199. package/dist/orchestrator/plugins/nextjs/config.js +11 -1
  200. package/dist/orchestrator/plugins/nextjs/config.js.map +1 -1
  201. package/dist/orchestrator/plugins/nx/config.d.ts.map +1 -1
  202. package/dist/orchestrator/plugins/nx/config.js +11 -1
  203. package/dist/orchestrator/plugins/nx/config.js.map +1 -1
  204. package/dist/orchestrator/plugins/pins.test.d.ts +2 -0
  205. package/dist/orchestrator/plugins/pins.test.d.ts.map +1 -0
  206. package/dist/orchestrator/plugins/pins.test.js +78 -0
  207. package/dist/orchestrator/plugins/pins.test.js.map +1 -0
  208. package/dist/orchestrator/plugins/playwright/config.d.ts.map +1 -1
  209. package/dist/orchestrator/plugins/playwright/config.js +11 -1
  210. package/dist/orchestrator/plugins/playwright/config.js.map +1 -1
  211. package/dist/orchestrator/plugins/prisma/config.d.ts.map +1 -1
  212. package/dist/orchestrator/plugins/prisma/config.js +17 -2
  213. package/dist/orchestrator/plugins/prisma/config.js.map +1 -1
  214. package/dist/orchestrator/plugins/resend/config.d.ts.map +1 -1
  215. package/dist/orchestrator/plugins/resend/config.js +17 -1
  216. package/dist/orchestrator/plugins/resend/config.js.map +1 -1
  217. package/dist/orchestrator/plugins/sentry/config.d.ts.map +1 -1
  218. package/dist/orchestrator/plugins/sentry/config.js +13 -1
  219. package/dist/orchestrator/plugins/sentry/config.js.map +1 -1
  220. package/dist/orchestrator/plugins/slack/config.d.ts.map +1 -1
  221. package/dist/orchestrator/plugins/slack/config.js +20 -1
  222. package/dist/orchestrator/plugins/slack/config.js.map +1 -1
  223. package/dist/orchestrator/plugins/strapi/config.d.ts.map +1 -1
  224. package/dist/orchestrator/plugins/strapi/config.js +11 -1
  225. package/dist/orchestrator/plugins/strapi/config.js.map +1 -1
  226. package/dist/orchestrator/plugins/trello/config.d.ts.map +1 -1
  227. package/dist/orchestrator/plugins/trello/config.js +21 -1
  228. package/dist/orchestrator/plugins/trello/config.js.map +1 -1
  229. package/dist/orchestrator/plugins/types.d.ts +22 -0
  230. package/dist/orchestrator/plugins/types.d.ts.map +1 -1
  231. package/package.json +4 -2
  232. package/src/cli/adapters/claude-code.ts +13 -7
  233. package/src/cli/adapters/rules-dir-base.ts +23 -44
  234. package/src/cli/adapters/single-file-base.ts +65 -50
  235. package/src/cli/adapters/vscode.ts +75 -77
  236. package/src/cli/baseline.ts +289 -0
  237. package/src/cli/ci.ts +289 -0
  238. package/src/cli/command-namespace.test.ts +417 -0
  239. package/src/cli/command-namespace.ts +222 -0
  240. package/src/cli/copy.ts +6 -2
  241. package/src/cli/dispatcher.test.ts +2 -2
  242. package/src/cli/docs-accuracy.test.ts +5 -0
  243. package/src/cli/doctor.test.ts +2 -2
  244. package/src/cli/doctor.ts +92 -6
  245. package/src/cli/explain.ts +222 -0
  246. package/src/cli/fleet.ts +176 -0
  247. package/src/cli/github-report.test.ts +158 -0
  248. package/src/cli/github-report.ts +179 -0
  249. package/src/cli/init.test.ts +36 -31
  250. package/src/cli/init.ts +174 -96
  251. package/src/cli/layers.test.ts +525 -0
  252. package/src/cli/layers.ts +1089 -0
  253. package/src/cli/lock.ts +395 -0
  254. package/src/cli/managed-paths.ts +73 -3
  255. package/src/cli/manifest.ts +2 -0
  256. package/src/cli/mcp-audit.test.ts +259 -0
  257. package/src/cli/mcp-audit.ts +619 -0
  258. package/src/cli/mcp-upgrade.test.ts +135 -0
  259. package/src/cli/mcp.ts +373 -34
  260. package/src/cli/policy.ts +207 -0
  261. package/src/cli/publish-workflow.test.ts +60 -1
  262. package/src/cli/remove.ts +28 -6
  263. package/src/cli/review.ts +457 -0
  264. package/src/cli/status.test.ts +5 -3
  265. package/src/cli/status.ts +29 -4
  266. package/src/cli/sync-check.test.ts +16 -8
  267. package/src/cli/sync-check.ts +264 -17
  268. package/src/cli/sync.ts +2 -0
  269. package/src/cli/team-ci.test.ts +195 -0
  270. package/src/cli/team-commands.test.ts +253 -0
  271. package/src/cli/team-config.ts +289 -0
  272. package/src/cli/team-health.ts +234 -0
  273. package/src/cli/team-sources.test.ts +578 -0
  274. package/src/cli/types.ts +51 -1
  275. package/src/cli/update.ts +229 -44
  276. package/src/cli/version-range.ts +150 -0
  277. package/src/cli/website-plugins.test.ts +41 -0
  278. package/src/dashboard/node_modules/.vite/deps/_metadata.json +6 -6
  279. package/src/orchestrator/plugins/chrome-devtools/config.ts +11 -1
  280. package/src/orchestrator/plugins/contentful/config.ts +11 -1
  281. package/src/orchestrator/plugins/convex/config.ts +11 -1
  282. package/src/orchestrator/plugins/coolify/config.ts +14 -1
  283. package/src/orchestrator/plugins/figma/SKILL.md +18 -14
  284. package/src/orchestrator/plugins/figma/config.ts +24 -13
  285. package/src/orchestrator/plugins/linear/SKILL.md +6 -14
  286. package/src/orchestrator/plugins/linear/config.ts +27 -17
  287. package/src/orchestrator/plugins/netlify/config.ts +23 -9
  288. package/src/orchestrator/plugins/nextjs/config.ts +11 -1
  289. package/src/orchestrator/plugins/nx/config.ts +11 -1
  290. package/src/orchestrator/plugins/pins.test.ts +80 -0
  291. package/src/orchestrator/plugins/playwright/config.ts +11 -1
  292. package/src/orchestrator/plugins/prisma/config.ts +17 -2
  293. package/src/orchestrator/plugins/resend/config.ts +17 -1
  294. package/src/orchestrator/plugins/sentry/config.ts +13 -1
  295. package/src/orchestrator/plugins/slack/config.ts +20 -1
  296. package/src/orchestrator/plugins/strapi/config.ts +11 -1
  297. package/src/orchestrator/plugins/trello/config.ts +21 -1
  298. package/src/orchestrator/plugins/types.ts +24 -0
  299. package/src/orchestrator/prompts/bootstrap-customizations.prompt.md +4 -4
@@ -0,0 +1,395 @@
1
+ import { createHash } from 'node:crypto'
2
+ import { existsSync, readFileSync, statSync } from 'node:fs'
3
+ import { writeFile, mkdir } from 'node:fs/promises'
4
+ import { join, dirname } from 'node:path'
5
+ import { PLUGINS } from '../orchestrator/plugins/index.js'
6
+ import { getIncludedMcpServers } from './stack-config.js'
7
+ import { splitFrontmatter, parseFrontmatterString } from './adapters/frontmatter.js'
8
+ import { compiledPath, filesUnder, type CompileSource, type LayerKind } from './layers.js'
9
+ import { serverTransport, envNamesIn, type ContentKind } from './team-config.js'
10
+ import type { RepoInfo, StackConfig } from './types.js'
11
+
12
+ /**
13
+ * `.opencastle/lock.json`: what every assistant in this repository is given,
14
+ * written by `sync` and committed.
15
+ *
16
+ * A source change regenerates dozens of files across seven targets, and nobody
17
+ * reviews a hundred-line diff of generated Markdown. This is the one file that
18
+ * says, in a reviewable shape, which layers were compiled at which versions,
19
+ * where every skill, agent and instruction came from, which MCP servers every
20
+ * assistant can start, and how much context is loaded before the task is read.
21
+ * `opencastle review` diffs it between two commits; `sync --check` fails when it
22
+ * is out of date, so it cannot drift from what was compiled.
23
+ *
24
+ * Deterministic by construction — no timestamps, no absolute paths, keys in a
25
+ * fixed order — so it changes only when what the assistants get changes, and
26
+ * two branches that both sync conflict only when they really disagree.
27
+ */
28
+
29
+ export const LOCK_REL = '.opencastle/lock.json'
30
+ export const LOCKFILE_VERSION = 1
31
+
32
+ export interface LockItem {
33
+ /** The layer that provides it. */
34
+ from: string
35
+ /** The first 12 hex digits of the compiled content's SHA-256. */
36
+ sha: string
37
+ overrides?: string
38
+ description?: string
39
+ /** Estimated tokens, for always-loaded instructions. */
40
+ tokens?: number
41
+ }
42
+
43
+ export interface LockServer {
44
+ /** `plugin:<id>` for an integration, otherwise the layer that defines it. */
45
+ from: string
46
+ transport: 'stdio' | 'http'
47
+ /** The command line, or the URL. */
48
+ launch: string
49
+ env?: string[]
50
+ auth?: string
51
+ /**
52
+ * For a team server, a digest of its whole definition. The launch line and
53
+ * the variable names do not show a literal environment value or header —
54
+ * `NODE_OPTIONS`, an API base URL — and a change there has to move the lock,
55
+ * or the review and the owners the lock routes to never see it.
56
+ */
57
+ sha?: string
58
+ }
59
+
60
+ export interface LockLayer {
61
+ id: string
62
+ kind: LayerKind
63
+ version?: string
64
+ integrity?: string
65
+ }
66
+
67
+ export interface LockPolicy {
68
+ allow?: Record<string, string[]>
69
+ remoteHosts?: Record<string, string[]>
70
+ requirePinned?: string
71
+ require?: string[]
72
+ contextBudget?: number
73
+ opencastle?: Record<string, string>
74
+ }
75
+
76
+ export interface Lock {
77
+ $comment?: string
78
+ lockfileVersion: number
79
+ opencastle: string
80
+ targets: string[]
81
+ integrations: string[]
82
+ layers: LockLayer[]
83
+ content: Record<string, LockItem>
84
+ excluded?: Record<string, string>
85
+ mcp: Record<string, LockServer>
86
+ blocked?: Record<string, string>
87
+ policy?: LockPolicy
88
+ context: { tokens: number; instructions: number; index: number }
89
+ }
90
+
91
+ const COMMENT = 'Written by opencastle sync — do not edit. Change .opencastle/ (or a baseline) and run sync; opencastle review explains a change.'
92
+
93
+ function sha12(parts: Array<[string, Buffer]>): string {
94
+ const hash = createHash('sha256')
95
+ for (const [name, data] of parts) hash.update(name).update('\0').update(data).update('\0')
96
+ return hash.digest('hex').slice(0, 12)
97
+ }
98
+
99
+ export function tokensOf(chars: number): number {
100
+ return Math.ceil(chars / 4)
101
+ }
102
+
103
+ function frontmatterOf(text: string): { meta: Record<string, string>; body: string } {
104
+ const { frontmatter, body } = splitFrontmatter(text.replace(/\r\n/g, '\n'))
105
+ return { meta: parseFrontmatterString(frontmatter), body }
106
+ }
107
+
108
+ function clip(text: string, max = 200): string {
109
+ const one = text.replace(/\s+/g, ' ').trim()
110
+ return one.length > max ? `${one.slice(0, max - 1)}…` : one
111
+ }
112
+
113
+ function sorted<T>(entries: Array<[string, T]>): Record<string, T> {
114
+ const out: Record<string, T> = {}
115
+ for (const [k, v] of entries.sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0))) out[k] = v
116
+ return out
117
+ }
118
+
119
+ /** A server definition as a string that does not depend on key order. */
120
+ function canonicalServer(value: unknown): string {
121
+ return JSON.stringify(value, (_k, v) =>
122
+ v && typeof v === 'object' && !Array.isArray(v)
123
+ ? Object.fromEntries(Object.entries(v as Record<string, unknown>).sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0)))
124
+ : v,
125
+ )
126
+ }
127
+
128
+ /** The command line a stdio server runs, as one string. */
129
+ function launchLine(command: string | string[] | undefined, args: string[] | undefined): string {
130
+ const parts = Array.isArray(command) ? command : [command ?? '', ...(args ?? [])]
131
+ return parts.filter((p) => p !== '').join(' ')
132
+ }
133
+
134
+ export interface LockOptions {
135
+ ides: string[]
136
+ stack: StackConfig
137
+ repoInfo?: RepoInfo
138
+ }
139
+
140
+ export interface ContentReport {
141
+ entries: Array<[string, LockItem]>
142
+ instructionChars: number
143
+ indexChars: number
144
+ /** What each item costs in always-loaded context, in characters. */
145
+ cost: Array<{ ref: string; from: string; chars: number }>
146
+ }
147
+
148
+ /** Every compiled item with its digest, and what the always-loaded part costs. */
149
+ export function contentReport(source: CompileSource): ContentReport {
150
+ const { resolved } = source
151
+ const content: Array<[string, LockItem]> = []
152
+ const cost: ContentReport['cost'] = []
153
+ let instructionChars = 0
154
+ let indexChars = 0
155
+ for (const item of resolved.items.values()) {
156
+ const abs = join(source.root, compiledPath(item.kind as ContentKind, item.name))
157
+ if (!existsSync(abs)) continue
158
+ let sha: string
159
+ let main: string
160
+ if (statSync(abs).isDirectory()) {
161
+ const files = filesUnder(abs)
162
+ sha = sha12(files.map((f) => [f, readFileSync(join(abs, f))]))
163
+ main = existsSync(join(abs, 'SKILL.md')) ? readFileSync(join(abs, 'SKILL.md'), 'utf8') : ''
164
+ } else {
165
+ const buf = readFileSync(abs)
166
+ sha = sha12([['', buf]])
167
+ main = buf.toString('utf8')
168
+ }
169
+ const { meta, body } = frontmatterOf(main)
170
+ const entry: LockItem = { from: item.plugin ? `plugin:${item.plugin}` : item.layer, sha }
171
+ if (item.overrides) entry.overrides = item.overrides
172
+ const ref = `${item.kind}/${item.name}`
173
+ if (item.kind === 'instructions') {
174
+ const chars = body.trim().length
175
+ instructionChars += chars
176
+ entry.tokens = tokensOf(chars)
177
+ cost.push({ ref, from: entry.from, chars })
178
+ } else if (meta.description) {
179
+ entry.description = clip(meta.description)
180
+ }
181
+ // What the index every single-file target writes costs, per entry: its
182
+ // name twice (the name and the path) and its description.
183
+ if (item.kind === 'skills' || item.kind === 'agents') {
184
+ const chars = item.name.length * 2 + (meta.description ?? '').length + 32
185
+ indexChars += chars
186
+ cost.push({ ref, from: entry.from, chars })
187
+ }
188
+ content.push([ref, entry])
189
+ }
190
+ return { entries: content, instructionChars, indexChars, cost }
191
+ }
192
+
193
+ /** Build the lock for a compile. Reads the materialized source, not the layers, so it records what was compiled. */
194
+ export function buildLock(source: CompileSource, opts: LockOptions): Lock {
195
+ const { resolved } = source
196
+ const { entries: content, instructionChars, indexChars } = contentReport(source)
197
+
198
+ // ── MCP ─────────────────────────────────────────────────────
199
+ const mcp: Array<[string, LockServer]> = []
200
+ const included = getIncludedMcpServers(opts.stack, opts.repoInfo)
201
+ for (const plugin of Object.values(PLUGINS)) {
202
+ const key = plugin.mcpServerKey
203
+ const cfg = plugin.mcpConfig
204
+ if (!key || !cfg || !included.has(key)) continue
205
+ if (resolved.servers.has(key) || resolved.blocked.has(key)) continue
206
+ const server: LockServer =
207
+ cfg.type === 'http'
208
+ ? { from: `plugin:${plugin.id}`, transport: 'http', launch: cfg.url ?? '' }
209
+ : { from: `plugin:${plugin.id}`, transport: 'stdio', launch: launchLine(cfg.command, cfg.args) }
210
+ const env = plugin.envVars.map((e) => e.name).sort()
211
+ if (env.length > 0) server.env = env
212
+ server.auth = plugin.authType
213
+ mcp.push([key, server])
214
+ }
215
+ for (const ts of resolved.servers.values()) {
216
+ const t = serverTransport(ts.server) ?? 'stdio'
217
+ const server: LockServer =
218
+ t === 'http'
219
+ ? { from: ts.from, transport: 'http', launch: ts.server.url ?? '' }
220
+ : { from: ts.from, transport: 'stdio', launch: launchLine(ts.server.command, ts.server.args) }
221
+ const names = new Set<string>()
222
+ for (const value of [
223
+ ...Object.values(ts.server.env ?? {}),
224
+ ...Object.values(ts.server.headers ?? {}),
225
+ ...(ts.server.args ?? []),
226
+ ts.server.url ?? '',
227
+ ts.server.command ?? '',
228
+ ]) {
229
+ for (const name of envNamesIn(value)) names.add(name)
230
+ }
231
+ if (names.size > 0) server.env = [...names].sort()
232
+ // `description` is for people reading the config and is written nowhere,
233
+ // so it is not part of what the assistants are given.
234
+ const { description: _description, ...definition } = ts.server
235
+ server.sha = sha12([['', Buffer.from(canonicalServer(definition))]])
236
+ mcp.push([ts.key, server])
237
+ }
238
+
239
+ // ── Policy ──────────────────────────────────────────────────
240
+ const p = resolved.policy
241
+ const policy: LockPolicy = {}
242
+ if (p.allowLists.length > 0) policy.allow = sorted(p.allowLists.map((l) => [l.by, [...l.patterns].sort()]))
243
+ if (p.hostLists.length > 0) policy.remoteHosts = sorted(p.hostLists.map((l) => [l.by, [...l.patterns].sort()]))
244
+ if (p.requirePinned) policy.requirePinned = p.requirePinned
245
+ if (p.require.length > 0) policy.require = [...new Set(p.require.map((r) => r.ref))].sort()
246
+ if (p.contextBudget) policy.contextBudget = p.contextBudget.tokens
247
+ if (p.versionRanges.length > 0) policy.opencastle = sorted(p.versionRanges.map((r) => [r.by, r.range]))
248
+
249
+ const lock: Lock = {
250
+ $comment: COMMENT,
251
+ lockfileVersion: LOCKFILE_VERSION,
252
+ opencastle: resolved.cliVersion,
253
+ targets: [...opts.ides].sort(),
254
+ integrations: [...opts.stack.techTools, ...opts.stack.teamTools].map(String).sort(),
255
+ layers: resolved.layers
256
+ .filter((l) => l.kind !== 'project' || Object.keys(l.config).length > 0 || [...resolved.items.values()].some((i) => i.layer === 'project'))
257
+ .map((l) => ({
258
+ id: l.id,
259
+ kind: l.kind,
260
+ ...(l.version && { version: l.version }),
261
+ ...(l.integrity && { integrity: l.integrity }),
262
+ })),
263
+ content: sorted(content),
264
+ mcp: sorted(mcp),
265
+ context: {
266
+ tokens: tokensOf(instructionChars + indexChars),
267
+ instructions: tokensOf(instructionChars),
268
+ index: tokensOf(indexChars),
269
+ },
270
+ }
271
+ if (resolved.excluded.length > 0) lock.excluded = sorted(resolved.excluded.map((e) => [e.ref, e.by]))
272
+ if (resolved.blocked.size > 0) lock.blocked = sorted([...resolved.blocked.entries()])
273
+ if (Object.keys(policy).length > 0) lock.policy = policy
274
+ // Keys in a fixed order, whatever order they were assigned in above.
275
+ return {
276
+ $comment: lock.$comment,
277
+ lockfileVersion: lock.lockfileVersion,
278
+ opencastle: lock.opencastle,
279
+ targets: lock.targets,
280
+ integrations: lock.integrations,
281
+ layers: lock.layers,
282
+ content: lock.content,
283
+ ...(lock.excluded && { excluded: lock.excluded }),
284
+ mcp: lock.mcp,
285
+ ...(lock.blocked && { blocked: lock.blocked }),
286
+ ...(lock.policy && { policy: lock.policy }),
287
+ context: lock.context,
288
+ }
289
+ }
290
+
291
+ export function serializeLock(lock: Lock): string {
292
+ return JSON.stringify(lock, null, 2) + '\n'
293
+ }
294
+
295
+ /**
296
+ * A lock, or null when the text is not one this release can read. Checked
297
+ * field by field: `fleet` reads locks from many repositories, and one written
298
+ * by hand or by a future release must not take the whole report down.
299
+ */
300
+ export function parseLock(text: string): Lock | null {
301
+ let parsed: Lock
302
+ try {
303
+ parsed = JSON.parse(text) as Lock
304
+ } catch {
305
+ return null
306
+ }
307
+ const obj = (v: unknown): boolean => Boolean(v) && typeof v === 'object' && !Array.isArray(v)
308
+ if (
309
+ !obj(parsed) ||
310
+ parsed.lockfileVersion !== LOCKFILE_VERSION ||
311
+ typeof parsed.opencastle !== 'string' ||
312
+ !Array.isArray(parsed.targets) ||
313
+ !Array.isArray(parsed.integrations) ||
314
+ !Array.isArray(parsed.layers) ||
315
+ !parsed.layers.every((l) => obj(l) && typeof l.id === 'string') ||
316
+ !obj(parsed.content) ||
317
+ !obj(parsed.mcp) ||
318
+ !Object.values(parsed.mcp).every((m) => obj(m) && typeof m.from === 'string' && typeof m.launch === 'string') ||
319
+ !obj(parsed.context) ||
320
+ typeof parsed.context.tokens !== 'number'
321
+ ) {
322
+ return null
323
+ }
324
+ return parsed
325
+ }
326
+
327
+ /** The committed lock, or null when there is none or it cannot be read. */
328
+ export function readLock(projectRoot: string): Lock | null {
329
+ const abs = join(projectRoot, LOCK_REL)
330
+ if (!existsSync(abs)) return null
331
+ try {
332
+ return parseLock(readFileSync(abs, 'utf8'))
333
+ } catch {
334
+ return null
335
+ }
336
+ }
337
+
338
+ /** Write the lock if it changed. Returns whether it did. */
339
+ export async function writeLock(projectRoot: string, lock: Lock): Promise<boolean> {
340
+ const abs = join(projectRoot, LOCK_REL)
341
+ const text = serializeLock(lock)
342
+ try {
343
+ if (existsSync(abs) && readFileSync(abs, 'utf8').replace(/\r\n/g, '\n') === text) return false
344
+ } catch {
345
+ // Unreadable: overwrite it — it is generated.
346
+ }
347
+ await mkdir(dirname(abs), { recursive: true })
348
+ await writeFile(abs, text)
349
+ return true
350
+ }
351
+
352
+ /** The servers a lock records as the team's own, not an integration's. */
353
+ export function teamServerKeys(lock: Lock | null): string[] {
354
+ if (!lock?.mcp) return []
355
+ return Object.entries(lock.mcp)
356
+ .filter(([, s]) => !s.from.startsWith('plugin:'))
357
+ .map(([k]) => k)
358
+ }
359
+
360
+ /**
361
+ * Resolve a project's sources and write the lock `sync` would write for it.
362
+ * For callers that compile through the adapters directly — tests, mostly — and
363
+ * so need the one file a real compile also produces.
364
+ */
365
+ export async function recordLockFor(
366
+ pkgRoot: string,
367
+ projectRoot: string,
368
+ manifest: { ide?: string; ides?: string[]; stack?: StackConfig; repoInfo?: RepoInfo },
369
+ ): Promise<void> {
370
+ const { resolveStack } = await import('./stack-config.js')
371
+ const { resolveSources, materialize, hasErrors, formatIssues } = await import('./layers.js')
372
+ const ides = (manifest.ides?.length ? manifest.ides : [manifest.ide]).filter((i): i is string => Boolean(i))
373
+ const stack = resolveStack({ ...manifest, ides })
374
+ const resolved = resolveSources({ pkgRoot, projectRoot, stack, repoInfo: manifest.repoInfo })
375
+ if (hasErrors(resolved)) throw new Error(formatIssues(resolved.issues).join('\n'))
376
+ const source = materialize(resolved, pkgRoot, ...priorTeam(projectRoot))
377
+ try {
378
+ await writeLock(projectRoot, buildLock(source, { ides, stack, repoInfo: manifest.repoInfo }))
379
+ } finally {
380
+ source.dispose()
381
+ }
382
+ }
383
+
384
+ /**
385
+ * What the committed lock says a previous sync wrote for the team: its server
386
+ * keys, and the variables those servers read (VS Code inputs among them).
387
+ * Passed to `materialize` so `sync` can take back what no layer defines now.
388
+ */
389
+ export function priorTeam(projectRoot: string): [string[], string[]] {
390
+ const lock = readLock(projectRoot)
391
+ const keys = teamServerKeys(lock)
392
+ const vars = new Set<string>()
393
+ for (const k of keys) for (const v of lock?.mcp[k]?.env ?? []) vars.add(v)
394
+ return [keys, [...vars].sort()]
395
+ }
@@ -1,7 +1,8 @@
1
- import { existsSync } from 'node:fs'
1
+ import { existsSync, readdirSync, rmdirSync, rmSync, statSync } from 'node:fs'
2
2
  import { resolve } from 'node:path'
3
3
  import { IDE_ADAPTERS } from './adapters/index.js'
4
- import type { ManagedPaths, Manifest } from './types.js'
4
+ import type { IdeAdapter, ManagedPaths, Manifest } from './types.js'
5
+ import { CLAUDE_COMMANDS_DIR } from './command-namespace.js'
5
6
 
6
7
  /**
7
8
  * What the manifest *should* say, given what the adapters declare today.
@@ -36,6 +37,20 @@ export const ROOT_INSTRUCTION_FILES = [
36
37
  '.github/copilot-instructions.md',
37
38
  ] as const
38
39
 
40
+ /**
41
+ * Framework paths a release recorded that today's compiler has narrowed.
42
+ *
43
+ * Before the `oc:` namespace the whole of `.claude/commands/` was generated, and manifests
44
+ * recorded it. Commands now live under `.claude/commands/oc/`, and the rest of
45
+ * the directory is the user's — so a stored `.claude/commands/` must not stay
46
+ * in `framework`, where `remove` and a dropped target's cleanup would delete
47
+ * every command a person wrote there. What those releases left at the top is
48
+ * found by its banner instead (`getLegacyOutputs`).
49
+ */
50
+ const SUPERSEDED_FRAMEWORK: Record<string, string> = {
51
+ '.claude/commands/': `.claude/${CLAUDE_COMMANDS_DIR}/`,
52
+ }
53
+
39
54
  function unique(values: string[]): string[] {
40
55
  return [...new Set(values)]
41
56
  }
@@ -78,7 +93,7 @@ export async function resolveManagedPaths(manifest: Manifest): Promise<Required<
78
93
 
79
94
  return {
80
95
  framework: unique([
81
- ...(stored?.framework ?? []),
96
+ ...(stored?.framework ?? []).map((p) => SUPERSEDED_FRAMEWORK[p] ?? p),
82
97
  ...declared.framework,
83
98
  ]).filter((p) => !isMerged(p)),
84
99
  customizable: unique([
@@ -95,6 +110,61 @@ export async function resolveManagedPaths(manifest: Manifest): Promise<Required<
95
110
  }
96
111
  }
97
112
 
113
+ /**
114
+ * Which files in a framework directory the given targets wrote, when one of
115
+ * them shares that directory with the user — `undefined` when the directory is
116
+ * wholly generated and can be removed whole.
117
+ */
118
+ export function ownerOf(
119
+ adapters: IdeAdapter[],
120
+ dir: string,
121
+ projectRoot: string,
122
+ ): ((_rel: string) => boolean) | undefined {
123
+ const sharing = adapters.filter((a) => a.ownsFile && a.getSharedDirs?.().includes(dir))
124
+ if (sharing.length === 0) return undefined
125
+ return (rel) => sharing.every((a) => a.ownsFile!(rel, projectRoot))
126
+ }
127
+
128
+ /**
129
+ * Delete the files at the top of a shared directory that `owns` claims, and the
130
+ * directory itself if that empties it — never anything of the user's.
131
+ *
132
+ * Only the top level: the one shared directory, `.github/prompts/`, is read
133
+ * there and nowhere deeper, so nothing below it is ours, and walking into a
134
+ * person's subfolders could only delete their empty ones or stop at one it
135
+ * cannot read. A path that is not a readable directory is left for a person.
136
+ * Returns how many files went.
137
+ */
138
+ export function removeOwnedFiles(projectRoot: string, dir: string, owns: (_rel: string) => boolean): number {
139
+ const root = resolve(projectRoot, dir)
140
+ const prefix = dir.endsWith('/') ? dir : `${dir}/`
141
+ let entries
142
+ try {
143
+ if (!statSync(root).isDirectory()) return 0
144
+ entries = readdirSync(root, { withFileTypes: true })
145
+ } catch {
146
+ return 0
147
+ }
148
+ let removed = 0
149
+ for (const entry of entries) {
150
+ if (entry.isDirectory() || !owns(`${prefix}${entry.name}`)) continue
151
+ try {
152
+ // `rmSync` rather than `unlinkSync`: on Windows it gets past a read-only
153
+ // file, which `unlink` fails on with EPERM.
154
+ rmSync(resolve(root, entry.name), { force: true })
155
+ removed++
156
+ } catch {
157
+ // Left for a person; one stubborn file must not stop the uninstall.
158
+ }
159
+ }
160
+ try {
161
+ if (readdirSync(root).length === 0) rmdirSync(root)
162
+ } catch {
163
+ // As above.
164
+ }
165
+ return removed
166
+ }
167
+
98
168
  /**
99
169
  * Files an install is not complete without.
100
170
  *
@@ -3,6 +3,7 @@ import { resolve, dirname, relative } from 'node:path';
3
3
  import { existsSync, readdirSync } from 'node:fs';
4
4
  import type { Manifest } from './types.js';
5
5
  import { UnreadableConfigError } from './types.js';
6
+ import { COMMAND_NAMESPACE } from './command-namespace.js';
6
7
 
7
8
  const MANIFEST_FILE = '.opencastle/manifest.json';
8
9
 
@@ -91,5 +92,6 @@ export function createManifest(version: string, ide: string, ides?: string[]): M
91
92
  ides: ides ?? [ide],
92
93
  installedAt: new Date().toISOString(),
93
94
  updatedAt: new Date().toISOString(),
95
+ commandNamespace: COMMAND_NAMESPACE,
94
96
  };
95
97
  }