opencastle 0.38.2 → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (267) hide show
  1. package/README.md +81 -1
  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 +1 -1
  6. package/dist/cli/adapters/claude-code.d.ts.map +1 -1
  7. package/dist/cli/adapters/codex.d.ts +1 -1
  8. package/dist/cli/adapters/codex.d.ts.map +1 -1
  9. package/dist/cli/adapters/cursor.d.ts +1 -1
  10. package/dist/cli/adapters/cursor.d.ts.map +1 -1
  11. package/dist/cli/adapters/opencode.d.ts +1 -1
  12. package/dist/cli/adapters/opencode.d.ts.map +1 -1
  13. package/dist/cli/adapters/rules-dir-base.d.ts +3 -2
  14. package/dist/cli/adapters/rules-dir-base.d.ts.map +1 -1
  15. package/dist/cli/adapters/rules-dir-base.js +13 -25
  16. package/dist/cli/adapters/rules-dir-base.js.map +1 -1
  17. package/dist/cli/adapters/single-file-base.d.ts.map +1 -1
  18. package/dist/cli/adapters/single-file-base.js +30 -43
  19. package/dist/cli/adapters/single-file-base.js.map +1 -1
  20. package/dist/cli/adapters/vscode.d.ts +3 -2
  21. package/dist/cli/adapters/vscode.d.ts.map +1 -1
  22. package/dist/cli/adapters/vscode.js +19 -71
  23. package/dist/cli/adapters/vscode.js.map +1 -1
  24. package/dist/cli/adapters/windsurf.d.ts +1 -1
  25. package/dist/cli/adapters/windsurf.d.ts.map +1 -1
  26. package/dist/cli/baseline.d.ts +3 -0
  27. package/dist/cli/baseline.d.ts.map +1 -0
  28. package/dist/cli/baseline.js +280 -0
  29. package/dist/cli/baseline.js.map +1 -0
  30. package/dist/cli/ci.d.ts +18 -0
  31. package/dist/cli/ci.d.ts.map +1 -0
  32. package/dist/cli/ci.js +279 -0
  33. package/dist/cli/ci.js.map +1 -0
  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 +5 -0
  37. package/dist/cli/docs-accuracy.test.js.map +1 -1
  38. package/dist/cli/doctor.d.ts +3 -3
  39. package/dist/cli/doctor.d.ts.map +1 -1
  40. package/dist/cli/doctor.js +66 -9
  41. package/dist/cli/doctor.js.map +1 -1
  42. package/dist/cli/explain.d.ts +3 -0
  43. package/dist/cli/explain.d.ts.map +1 -0
  44. package/dist/cli/explain.js +210 -0
  45. package/dist/cli/explain.js.map +1 -0
  46. package/dist/cli/fleet.d.ts +30 -0
  47. package/dist/cli/fleet.d.ts.map +1 -0
  48. package/dist/cli/fleet.js +149 -0
  49. package/dist/cli/fleet.js.map +1 -0
  50. package/dist/cli/github-report.d.ts +49 -0
  51. package/dist/cli/github-report.d.ts.map +1 -0
  52. package/dist/cli/github-report.js +161 -0
  53. package/dist/cli/github-report.js.map +1 -0
  54. package/dist/cli/github-report.test.d.ts +2 -0
  55. package/dist/cli/github-report.test.d.ts.map +1 -0
  56. package/dist/cli/github-report.test.js +146 -0
  57. package/dist/cli/github-report.test.js.map +1 -0
  58. package/dist/cli/init.d.ts.map +1 -1
  59. package/dist/cli/init.js +135 -94
  60. package/dist/cli/init.js.map +1 -1
  61. package/dist/cli/init.test.js +26 -25
  62. package/dist/cli/init.test.js.map +1 -1
  63. package/dist/cli/layers.d.ts +152 -0
  64. package/dist/cli/layers.d.ts.map +1 -0
  65. package/dist/cli/layers.js +932 -0
  66. package/dist/cli/layers.js.map +1 -0
  67. package/dist/cli/layers.test.d.ts +2 -0
  68. package/dist/cli/layers.test.d.ts.map +1 -0
  69. package/dist/cli/layers.test.js +483 -0
  70. package/dist/cli/layers.test.js.map +1 -0
  71. package/dist/cli/lock.d.ts +130 -0
  72. package/dist/cli/lock.d.ts.map +1 -0
  73. package/dist/cli/lock.js +320 -0
  74. package/dist/cli/lock.js.map +1 -0
  75. package/dist/cli/mcp-audit.d.ts +164 -0
  76. package/dist/cli/mcp-audit.d.ts.map +1 -0
  77. package/dist/cli/mcp-audit.js +504 -0
  78. package/dist/cli/mcp-audit.js.map +1 -0
  79. package/dist/cli/mcp-audit.test.d.ts +2 -0
  80. package/dist/cli/mcp-audit.test.d.ts.map +1 -0
  81. package/dist/cli/mcp-audit.test.js +215 -0
  82. package/dist/cli/mcp-audit.test.js.map +1 -0
  83. package/dist/cli/mcp-upgrade.test.d.ts +2 -0
  84. package/dist/cli/mcp-upgrade.test.d.ts.map +1 -0
  85. package/dist/cli/mcp-upgrade.test.js +118 -0
  86. package/dist/cli/mcp-upgrade.test.js.map +1 -0
  87. package/dist/cli/mcp.d.ts +74 -5
  88. package/dist/cli/mcp.d.ts.map +1 -1
  89. package/dist/cli/mcp.js +340 -32
  90. package/dist/cli/mcp.js.map +1 -1
  91. package/dist/cli/policy.d.ts +58 -0
  92. package/dist/cli/policy.d.ts.map +1 -0
  93. package/dist/cli/policy.js +194 -0
  94. package/dist/cli/policy.js.map +1 -0
  95. package/dist/cli/publish-workflow.test.js +55 -1
  96. package/dist/cli/publish-workflow.test.js.map +1 -1
  97. package/dist/cli/remove.d.ts.map +1 -1
  98. package/dist/cli/remove.js +3 -2
  99. package/dist/cli/remove.js.map +1 -1
  100. package/dist/cli/review.d.ts +25 -0
  101. package/dist/cli/review.d.ts.map +1 -0
  102. package/dist/cli/review.js +437 -0
  103. package/dist/cli/review.js.map +1 -0
  104. package/dist/cli/status.d.ts +2 -0
  105. package/dist/cli/status.d.ts.map +1 -1
  106. package/dist/cli/status.js +25 -4
  107. package/dist/cli/status.js.map +1 -1
  108. package/dist/cli/status.test.js +5 -3
  109. package/dist/cli/status.test.js.map +1 -1
  110. package/dist/cli/sync-check.d.ts +16 -1
  111. package/dist/cli/sync-check.d.ts.map +1 -1
  112. package/dist/cli/sync-check.js +219 -13
  113. package/dist/cli/sync-check.js.map +1 -1
  114. package/dist/cli/sync-check.test.js +14 -8
  115. package/dist/cli/sync-check.test.js.map +1 -1
  116. package/dist/cli/sync.d.ts.map +1 -1
  117. package/dist/cli/sync.js +2 -0
  118. package/dist/cli/sync.js.map +1 -1
  119. package/dist/cli/team-ci.test.d.ts +2 -0
  120. package/dist/cli/team-ci.test.d.ts.map +1 -0
  121. package/dist/cli/team-ci.test.js +169 -0
  122. package/dist/cli/team-ci.test.js.map +1 -0
  123. package/dist/cli/team-commands.test.d.ts +2 -0
  124. package/dist/cli/team-commands.test.d.ts.map +1 -0
  125. package/dist/cli/team-commands.test.js +233 -0
  126. package/dist/cli/team-commands.test.js.map +1 -0
  127. package/dist/cli/team-config.d.ts +88 -0
  128. package/dist/cli/team-config.d.ts.map +1 -0
  129. package/dist/cli/team-config.js +261 -0
  130. package/dist/cli/team-config.js.map +1 -0
  131. package/dist/cli/team-health.d.ts +49 -0
  132. package/dist/cli/team-health.d.ts.map +1 -0
  133. package/dist/cli/team-health.js +205 -0
  134. package/dist/cli/team-health.js.map +1 -0
  135. package/dist/cli/team-sources.test.d.ts +2 -0
  136. package/dist/cli/team-sources.test.d.ts.map +1 -0
  137. package/dist/cli/team-sources.test.js +542 -0
  138. package/dist/cli/team-sources.test.js.map +1 -0
  139. package/dist/cli/types.d.ts +16 -2
  140. package/dist/cli/types.d.ts.map +1 -1
  141. package/dist/cli/types.js.map +1 -1
  142. package/dist/cli/update.d.ts.map +1 -1
  143. package/dist/cli/update.js +204 -44
  144. package/dist/cli/update.js.map +1 -1
  145. package/dist/cli/version-range.d.ts +24 -0
  146. package/dist/cli/version-range.d.ts.map +1 -0
  147. package/dist/cli/version-range.js +157 -0
  148. package/dist/cli/version-range.js.map +1 -0
  149. package/dist/cli/website-plugins.test.d.ts +2 -0
  150. package/dist/cli/website-plugins.test.d.ts.map +1 -0
  151. package/dist/cli/website-plugins.test.js +34 -0
  152. package/dist/cli/website-plugins.test.js.map +1 -0
  153. package/dist/orchestrator/plugins/chrome-devtools/config.d.ts.map +1 -1
  154. package/dist/orchestrator/plugins/chrome-devtools/config.js +11 -1
  155. package/dist/orchestrator/plugins/chrome-devtools/config.js.map +1 -1
  156. package/dist/orchestrator/plugins/contentful/config.d.ts.map +1 -1
  157. package/dist/orchestrator/plugins/contentful/config.js +11 -1
  158. package/dist/orchestrator/plugins/contentful/config.js.map +1 -1
  159. package/dist/orchestrator/plugins/convex/config.d.ts.map +1 -1
  160. package/dist/orchestrator/plugins/convex/config.js +11 -1
  161. package/dist/orchestrator/plugins/convex/config.js.map +1 -1
  162. package/dist/orchestrator/plugins/coolify/config.d.ts.map +1 -1
  163. package/dist/orchestrator/plugins/coolify/config.js +14 -1
  164. package/dist/orchestrator/plugins/coolify/config.js.map +1 -1
  165. package/dist/orchestrator/plugins/figma/config.d.ts.map +1 -1
  166. package/dist/orchestrator/plugins/figma/config.js +24 -13
  167. package/dist/orchestrator/plugins/figma/config.js.map +1 -1
  168. package/dist/orchestrator/plugins/linear/config.d.ts.map +1 -1
  169. package/dist/orchestrator/plugins/linear/config.js +27 -17
  170. package/dist/orchestrator/plugins/linear/config.js.map +1 -1
  171. package/dist/orchestrator/plugins/netlify/config.d.ts.map +1 -1
  172. package/dist/orchestrator/plugins/netlify/config.js +23 -9
  173. package/dist/orchestrator/plugins/netlify/config.js.map +1 -1
  174. package/dist/orchestrator/plugins/nextjs/config.d.ts.map +1 -1
  175. package/dist/orchestrator/plugins/nextjs/config.js +11 -1
  176. package/dist/orchestrator/plugins/nextjs/config.js.map +1 -1
  177. package/dist/orchestrator/plugins/nx/config.d.ts.map +1 -1
  178. package/dist/orchestrator/plugins/nx/config.js +11 -1
  179. package/dist/orchestrator/plugins/nx/config.js.map +1 -1
  180. package/dist/orchestrator/plugins/pins.test.d.ts +2 -0
  181. package/dist/orchestrator/plugins/pins.test.d.ts.map +1 -0
  182. package/dist/orchestrator/plugins/pins.test.js +78 -0
  183. package/dist/orchestrator/plugins/pins.test.js.map +1 -0
  184. package/dist/orchestrator/plugins/playwright/config.d.ts.map +1 -1
  185. package/dist/orchestrator/plugins/playwright/config.js +11 -1
  186. package/dist/orchestrator/plugins/playwright/config.js.map +1 -1
  187. package/dist/orchestrator/plugins/prisma/config.d.ts.map +1 -1
  188. package/dist/orchestrator/plugins/prisma/config.js +17 -2
  189. package/dist/orchestrator/plugins/prisma/config.js.map +1 -1
  190. package/dist/orchestrator/plugins/resend/config.d.ts.map +1 -1
  191. package/dist/orchestrator/plugins/resend/config.js +17 -1
  192. package/dist/orchestrator/plugins/resend/config.js.map +1 -1
  193. package/dist/orchestrator/plugins/sentry/config.d.ts.map +1 -1
  194. package/dist/orchestrator/plugins/sentry/config.js +13 -1
  195. package/dist/orchestrator/plugins/sentry/config.js.map +1 -1
  196. package/dist/orchestrator/plugins/slack/config.d.ts.map +1 -1
  197. package/dist/orchestrator/plugins/slack/config.js +20 -1
  198. package/dist/orchestrator/plugins/slack/config.js.map +1 -1
  199. package/dist/orchestrator/plugins/strapi/config.d.ts.map +1 -1
  200. package/dist/orchestrator/plugins/strapi/config.js +11 -1
  201. package/dist/orchestrator/plugins/strapi/config.js.map +1 -1
  202. package/dist/orchestrator/plugins/trello/config.d.ts.map +1 -1
  203. package/dist/orchestrator/plugins/trello/config.js +21 -1
  204. package/dist/orchestrator/plugins/trello/config.js.map +1 -1
  205. package/dist/orchestrator/plugins/types.d.ts +22 -0
  206. package/dist/orchestrator/plugins/types.d.ts.map +1 -1
  207. package/package.json +3 -1
  208. package/src/cli/adapters/rules-dir-base.ts +23 -44
  209. package/src/cli/adapters/single-file-base.ts +43 -46
  210. package/src/cli/adapters/vscode.ts +28 -71
  211. package/src/cli/baseline.ts +289 -0
  212. package/src/cli/ci.ts +289 -0
  213. package/src/cli/dispatcher.test.ts +2 -2
  214. package/src/cli/docs-accuracy.test.ts +5 -0
  215. package/src/cli/doctor.ts +92 -6
  216. package/src/cli/explain.ts +210 -0
  217. package/src/cli/fleet.ts +176 -0
  218. package/src/cli/github-report.test.ts +158 -0
  219. package/src/cli/github-report.ts +179 -0
  220. package/src/cli/init.test.ts +27 -27
  221. package/src/cli/init.ts +135 -93
  222. package/src/cli/layers.test.ts +525 -0
  223. package/src/cli/layers.ts +1089 -0
  224. package/src/cli/lock.ts +395 -0
  225. package/src/cli/mcp-audit.test.ts +259 -0
  226. package/src/cli/mcp-audit.ts +619 -0
  227. package/src/cli/mcp-upgrade.test.ts +135 -0
  228. package/src/cli/mcp.ts +373 -34
  229. package/src/cli/policy.ts +207 -0
  230. package/src/cli/publish-workflow.test.ts +60 -1
  231. package/src/cli/remove.ts +8 -2
  232. package/src/cli/review.ts +457 -0
  233. package/src/cli/status.test.ts +5 -3
  234. package/src/cli/status.ts +29 -4
  235. package/src/cli/sync-check.test.ts +16 -8
  236. package/src/cli/sync-check.ts +245 -14
  237. package/src/cli/sync.ts +2 -0
  238. package/src/cli/team-ci.test.ts +195 -0
  239. package/src/cli/team-commands.test.ts +253 -0
  240. package/src/cli/team-config.ts +289 -0
  241. package/src/cli/team-health.ts +234 -0
  242. package/src/cli/team-sources.test.ts +578 -0
  243. package/src/cli/types.ts +19 -1
  244. package/src/cli/update.ts +217 -44
  245. package/src/cli/version-range.ts +150 -0
  246. package/src/cli/website-plugins.test.ts +41 -0
  247. package/src/dashboard/node_modules/.vite/deps/_metadata.json +6 -6
  248. package/src/orchestrator/plugins/chrome-devtools/config.ts +11 -1
  249. package/src/orchestrator/plugins/contentful/config.ts +11 -1
  250. package/src/orchestrator/plugins/convex/config.ts +11 -1
  251. package/src/orchestrator/plugins/coolify/config.ts +14 -1
  252. package/src/orchestrator/plugins/figma/SKILL.md +18 -14
  253. package/src/orchestrator/plugins/figma/config.ts +24 -13
  254. package/src/orchestrator/plugins/linear/SKILL.md +6 -14
  255. package/src/orchestrator/plugins/linear/config.ts +27 -17
  256. package/src/orchestrator/plugins/netlify/config.ts +23 -9
  257. package/src/orchestrator/plugins/nextjs/config.ts +11 -1
  258. package/src/orchestrator/plugins/nx/config.ts +11 -1
  259. package/src/orchestrator/plugins/pins.test.ts +80 -0
  260. package/src/orchestrator/plugins/playwright/config.ts +11 -1
  261. package/src/orchestrator/plugins/prisma/config.ts +17 -2
  262. package/src/orchestrator/plugins/resend/config.ts +17 -1
  263. package/src/orchestrator/plugins/sentry/config.ts +13 -1
  264. package/src/orchestrator/plugins/slack/config.ts +20 -1
  265. package/src/orchestrator/plugins/strapi/config.ts +11 -1
  266. package/src/orchestrator/plugins/trello/config.ts +21 -1
  267. package/src/orchestrator/plugins/types.ts +24 -0
@@ -0,0 +1,1089 @@
1
+ import { createHash } from 'node:crypto'
2
+ import {
3
+ existsSync,
4
+ readFileSync,
5
+ readdirSync,
6
+ realpathSync,
7
+ statSync,
8
+ mkdtempSync,
9
+ mkdirSync,
10
+ rmSync,
11
+ writeFileSync,
12
+ } from 'node:fs'
13
+ import { join, resolve, relative, dirname, isAbsolute, sep } from 'node:path'
14
+ import { tmpdir } from 'node:os'
15
+ import { PLUGINS } from '../orchestrator/plugins/index.js'
16
+ import { getOrchestratorRoot, getPluginsRoot } from './copy.js'
17
+ import { getExcludedSkills, getExcludedAgents, getIncludedPluginIds, getIncludedMcpServers, getRequiredMcpEnvVars } from './stack-config.js'
18
+ import { splitFrontmatter, parseFrontmatterString } from './adapters/frontmatter.js'
19
+ import { packageLaunch, isPinned } from './mcp-audit.js'
20
+ import { disallowedBy, hostDisallowedBy, findInlineSecret, emptyPolicy, globMatch, hostOfUrl, hostAllowedBy, type EffectivePolicy } from './policy.js'
21
+ import { LOCAL_DIRS } from './gitignore.js'
22
+ import { satisfies, parseVersion, compareVersions } from './version-range.js'
23
+ import {
24
+ CONTENT_KINDS,
25
+ TEAM_CONFIG_REL,
26
+ LAYER_CONFIG_FILE,
27
+ parseTeamConfig,
28
+ checkServerShape,
29
+ serverTransport,
30
+ type ContentKind,
31
+ type TeamConfig,
32
+ type TeamIssue,
33
+ envNamesIn,
34
+ type TeamMcpServer,
35
+ } from './team-config.js'
36
+ import type { RepoInfo, StackConfig } from './types.js'
37
+
38
+ export type { EffectivePolicy } from './policy.js'
39
+
40
+ /**
41
+ * Layered sources: OpenCastle's own content at the bottom, the baselines a
42
+ * project extends above it, and the project's `.opencastle/` on top.
43
+ *
44
+ * Everything the adapters compile comes out of here as one directory in the
45
+ * shape they have always read, so seven targets gain team content without
46
+ * seven new code paths — and so what `sync`, `sync --check` and `review` see is
47
+ * one resolution, not three that agree by luck.
48
+ */
49
+
50
+ export type LayerKind = 'core' | 'baseline' | 'project'
51
+
52
+ export interface Layer {
53
+ /** How it is named in output and in the lock: `opencastle`, a package name, a path, `project`. */
54
+ id: string
55
+ kind: LayerKind
56
+ /** Absolute directory holding `skills/`, `agents/` and the rest. */
57
+ root: string
58
+ version?: string
59
+ config: TeamConfig
60
+ /** Where its config lives, as a person would find it. */
61
+ configFile?: string
62
+ /** A digest of the layer's content, so a baseline that changed without a version bump still shows. */
63
+ integrity?: string
64
+ }
65
+
66
+ export interface ContentItem {
67
+ kind: ContentKind
68
+ name: string
69
+ /** The id of the layer that provides it. */
70
+ layer: string
71
+ /** A file, or a skill's directory. */
72
+ path: string
73
+ /** The layer it replaced, when it replaced one. */
74
+ overrides?: string
75
+ /** The integration a plugin skill belongs to. */
76
+ plugin?: string
77
+ /** Where links inside a team item may point; anything else is skipped. */
78
+ within?: string[]
79
+ }
80
+
81
+ export interface TeamServer {
82
+ key: string
83
+ /** The layer that defines it. */
84
+ from: string
85
+ server: TeamMcpServer
86
+ /** Its config file, for messages. */
87
+ where: string
88
+ }
89
+
90
+ export interface ResolvedSources {
91
+ layers: Layer[]
92
+ /** Keyed `kind/name`, e.g. `skills/testing-workflow`. */
93
+ items: Map<string, ContentItem>
94
+ excluded: Array<{ ref: string; by: string; from: string }>
95
+ servers: Map<string, TeamServer>
96
+ /** Plugin servers the stack includes but the team's policy does not allow, with why. */
97
+ blocked: Map<string, string>
98
+ policy: EffectivePolicy
99
+ issues: TeamIssue[]
100
+ cliVersion: string
101
+ }
102
+
103
+ /** Where a kind lives inside a layer, and inside the directory the adapters read. */
104
+ const LAYER_DIR: Record<ContentKind, string> = {
105
+ instructions: 'instructions',
106
+ agents: 'agents',
107
+ skills: 'skills',
108
+ prompts: 'prompts',
109
+ workflows: 'workflows',
110
+ }
111
+ const CORE_DIR: Record<ContentKind, string> = { ...LAYER_DIR, workflows: 'agent-workflows' }
112
+
113
+ const NAME = /^[A-Za-z0-9][A-Za-z0-9._-]*$/
114
+ const PACKAGE_NAME = /^(@[a-z0-9-~][a-z0-9-._~]*\/)?[a-z0-9-~][a-z0-9-._~]*$/
115
+
116
+ export function cliVersionOf(pkgRoot: string): string {
117
+ try {
118
+ return (JSON.parse(readFileSync(join(pkgRoot, 'package.json'), 'utf8')) as { version: string }).version
119
+ } catch {
120
+ return '0.0.0'
121
+ }
122
+ }
123
+
124
+ function posix(p: string): string {
125
+ return p.split(sep).join('/')
126
+ }
127
+
128
+ /** A path as a person in the project would type it. */
129
+ function display(projectRoot: string | null, abs: string): string {
130
+ if (!projectRoot) return abs
131
+ const rel = posix(relative(projectRoot, abs))
132
+ return rel === '' ? '.' : rel
133
+ }
134
+
135
+ /** The name an item goes by, from its file name. */
136
+ function itemName(kind: ContentKind, file: string): string | null {
137
+ switch (kind) {
138
+ case 'instructions':
139
+ return file.endsWith('.md') ? file.replace(/(\.instructions)?\.md$/, '') : null
140
+ case 'agents':
141
+ return file.endsWith('.agent.md') ? file.slice(0, -'.agent.md'.length) : null
142
+ case 'prompts':
143
+ return file.endsWith('.md') ? file.replace(/(\.prompt)?\.md$/, '') : null
144
+ case 'workflows':
145
+ return file.endsWith('.md') && file !== 'README.md' ? file.slice(0, -3) : null
146
+ case 'skills':
147
+ return file
148
+ }
149
+ }
150
+
151
+ /** Where an item is written in the directory the adapters compile from. */
152
+ export function compiledPath(kind: ContentKind, name: string): string {
153
+ switch (kind) {
154
+ case 'instructions':
155
+ return `instructions/${name}.instructions.md`
156
+ case 'agents':
157
+ return `agents/${name}.agent.md`
158
+ case 'prompts':
159
+ return `prompts/${name}.prompt.md`
160
+ case 'workflows':
161
+ return `agent-workflows/${name}.md`
162
+ case 'skills':
163
+ return `skills/${name}`
164
+ }
165
+ }
166
+
167
+ /**
168
+ * Files an OS or a tool drops beside real content. Compiling them made the lock
169
+ * differ between a Mac and CI — `.DS_Store` in a team skill changed its digest
170
+ * and appeared as generated output on one machine only. Only these: a skill's
171
+ * own `.env.example` or `.github/` template is content, and dropping every
172
+ * dotfile lost them without a word.
173
+ */
174
+ function isJunk(name: string): boolean {
175
+ return name === '.DS_Store' || name.startsWith('._') || name === 'Thumbs.db' || name === 'desktop.ini' || name === '.git'
176
+ }
177
+
178
+ /**
179
+ * Bytes as they mean the same on every machine: text with LF line endings.
180
+ * Git on Windows checks text out with CRLF, and a digest over raw bytes then
181
+ * called an unchanged baseline changed.
182
+ */
183
+ export function canonicalBytes(buf: Buffer): Buffer {
184
+ const head = buf.subarray(0, 8000)
185
+ if (head.includes(0)) return buf
186
+ const text = buf.toString('utf8')
187
+ return text.includes('\r\n') ? Buffer.from(text.replace(/\r\n/g, '\n'), 'utf8') : buf
188
+ }
189
+
190
+ function isInside(root: string, abs: string): boolean {
191
+ const rel = relative(root, abs)
192
+ return rel === '' || (!rel.startsWith('..') && !isAbsolute(rel))
193
+ }
194
+
195
+ function listDir(dir: string, within?: string[], onSkip?: (abs: string) => void): Array<{ name: string; isDir: boolean }> {
196
+ if (!existsSync(dir)) return []
197
+ try {
198
+ return readdirSync(dir, { withFileTypes: true })
199
+ .filter((e) => !isJunk(e.name))
200
+ .filter((e) => {
201
+ // A link out of the layer would copy whatever it points at — a system
202
+ // file, another project — into every assistant's config.
203
+ if (!within || !e.isSymbolicLink()) return true
204
+ let inside = false
205
+ try {
206
+ const real = realpathSync(join(dir, e.name))
207
+ inside = within.some((root) => isInside(root, real))
208
+ } catch {
209
+ inside = false
210
+ }
211
+ if (!inside) onSkip?.(join(dir, e.name))
212
+ return inside
213
+ })
214
+ .map((e) => {
215
+ let isDir = e.isDirectory()
216
+ if (!isDir && e.isSymbolicLink()) {
217
+ try {
218
+ isDir = statSync(join(dir, e.name)).isDirectory()
219
+ } catch {
220
+ isDir = false
221
+ }
222
+ }
223
+ return { name: e.name, isDir }
224
+ })
225
+ .sort((a, b) => (a.name < b.name ? -1 : a.name > b.name ? 1 : 0))
226
+ } catch {
227
+ return []
228
+ }
229
+ }
230
+
231
+ /** The directories a layer's links may point into: itself, and the project. */
232
+ function allowedRoots(layer: Layer, projectRoot: string | null): string[] {
233
+ const roots: string[] = []
234
+ for (const r of [layer.root, projectRoot]) {
235
+ if (!r) continue
236
+ try {
237
+ roots.push(realpathSync(r))
238
+ } catch {
239
+ roots.push(r)
240
+ }
241
+ }
242
+ return roots
243
+ }
244
+
245
+ function scanLayer(layer: Layer, projectRoot: string | null): { items: ContentItem[]; issues: TeamIssue[] } {
246
+ const items: ContentItem[] = []
247
+ const issues: TeamIssue[] = []
248
+ const dirs = layer.kind === 'core' ? CORE_DIR : LAYER_DIR
249
+ const within = layer.kind === 'core' ? undefined : allowedRoots(layer, projectRoot)
250
+ // Said, not silent: a skill linked in from elsewhere in a monorepo is a
251
+ // reasonable thing to do, and vanishing from every assistant without a word
252
+ // is the worst way to find out it is not followed.
253
+ const skipped = (abs: string): void => {
254
+ issues.push({
255
+ level: 'warning',
256
+ where: display(projectRoot, abs),
257
+ message: 'is a link to somewhere outside this layer and the project, so it is not compiled',
258
+ fix: 'copy it in, or publish it as a baseline and extend that',
259
+ })
260
+ }
261
+ for (const kind of CONTENT_KINDS) {
262
+ const dir = join(layer.root, dirs[kind])
263
+ for (const entry of listDir(dir, within, skipped)) {
264
+ if (kind === 'skills') {
265
+ if (!entry.isDir) continue
266
+ if (!existsSync(join(dir, entry.name, 'SKILL.md'))) {
267
+ if (layer.kind !== 'core') {
268
+ issues.push({
269
+ level: 'warning',
270
+ where: display(projectRoot, join(dir, entry.name)),
271
+ message: 'has no SKILL.md, so it is not compiled',
272
+ })
273
+ }
274
+ continue
275
+ }
276
+ } else if (entry.isDir) {
277
+ continue
278
+ }
279
+ const name = itemName(kind, entry.name)
280
+ if (name === null) continue
281
+ if (!NAME.test(name)) {
282
+ issues.push({
283
+ level: 'warning',
284
+ where: display(projectRoot, join(dir, entry.name)),
285
+ message: 'is skipped: names are letters, digits, ".", "_" and "-"',
286
+ })
287
+ continue
288
+ }
289
+ if (kind === 'skills' && within) filesUnder(join(dir, entry.name), within, skipped)
290
+ items.push({ kind, name, layer: layer.id, path: join(dir, entry.name), ...(within && { within }) })
291
+ }
292
+ }
293
+ return { items, issues }
294
+ }
295
+
296
+ /**
297
+ * Every file under a directory, relative, sorted. A directory reached twice
298
+ * through links is walked once, so a link loop ends instead of recursing.
299
+ */
300
+ export function filesUnder(root: string, within?: string[], onSkip?: (abs: string) => void): string[] {
301
+ const out: string[] = []
302
+ const seen = new Set<string>()
303
+ const walk = (dir: string, prefix: string): void => {
304
+ let real = dir
305
+ try {
306
+ real = realpathSync(dir)
307
+ } catch {
308
+ return
309
+ }
310
+ if (seen.has(real)) return
311
+ seen.add(real)
312
+ for (const e of listDir(dir, within, onSkip)) {
313
+ if (e.isDir) walk(join(dir, e.name), `${prefix}${e.name}/`)
314
+ else out.push(`${prefix}${e.name}`)
315
+ }
316
+ }
317
+ if (existsSync(root)) walk(root, '')
318
+ return out
319
+ }
320
+
321
+ /** A digest of what a layer contributes: its config and its content directories. */
322
+ function layerIntegrity(root: string): string {
323
+ const hash = createHash('sha256')
324
+ const parts = [LAYER_CONFIG_FILE, ...CONTENT_KINDS.map((k) => LAYER_DIR[k])]
325
+ for (const part of parts) {
326
+ const abs = join(root, part)
327
+ if (!existsSync(abs)) continue
328
+ const files = statSync(abs).isDirectory() ? filesUnder(abs, [root]).map((f) => `${part}/${f}`) : [part]
329
+ for (const f of files) {
330
+ hash.update(f).update('\0').update(canonicalBytes(readFileSync(join(root, f)))).update('\0')
331
+ }
332
+ }
333
+ return `sha256-${hash.digest('base64')}`
334
+ }
335
+
336
+ /** `node_modules/<name>` from `fromDir` upwards, the way Node resolves a package. */
337
+ function findPackageDir(name: string, fromDir: string): string | null {
338
+ let dir = fromDir
339
+ for (;;) {
340
+ const candidate = join(dir, 'node_modules', ...name.split('/'))
341
+ if (existsSync(join(candidate, 'package.json'))) {
342
+ try {
343
+ return realpathSync(candidate)
344
+ } catch {
345
+ return candidate
346
+ }
347
+ }
348
+ const parent = dirname(dir)
349
+ if (parent === dir) return null
350
+ dir = parent
351
+ }
352
+ }
353
+
354
+ function readLayerConfig(root: string, where: string): { config: TeamConfig; issues: TeamIssue[] } {
355
+ const file = join(root, LAYER_CONFIG_FILE)
356
+ if (!existsSync(file)) return { config: {}, issues: [] }
357
+ let text: string
358
+ try {
359
+ text = readFileSync(file, 'utf8')
360
+ } catch (err) {
361
+ return { config: {}, issues: [{ level: 'error', where, message: `cannot be read — ${(err as Error).message}` }] }
362
+ }
363
+ const { config, issues } = parseTeamConfig(text, where)
364
+ return { config: config ?? {}, issues }
365
+ }
366
+
367
+ interface ExtendsContext {
368
+ projectRoot: string
369
+ layers: Layer[]
370
+ seen: Set<string>
371
+ issues: TeamIssue[]
372
+ }
373
+
374
+ /**
375
+ * Load one `extends` entry and, before it, everything it extends.
376
+ *
377
+ * A package is found the way Node finds one — `node_modules` from the
378
+ * declaring layer upwards — so npm, pnpm, Yarn and workspaces all work, a git
379
+ * dependency works, and the version is whatever the project's lockfile pinned.
380
+ * OpenCastle fetches nothing itself: the package manager already does that
381
+ * with integrity checks, private registries and upgrade bots, and a second
382
+ * fetcher here would be a second supply chain.
383
+ */
384
+ function loadExtends(
385
+ spec: string,
386
+ fromDir: string,
387
+ declaredIn: string,
388
+ chain: string[],
389
+ ctx: ExtendsContext,
390
+ ): void {
391
+ const fail = (message: string, fix?: string): void => {
392
+ ctx.issues.push({ level: 'error', where: declaredIn, message, ...(fix && { fix }) })
393
+ }
394
+
395
+ let root: string
396
+ let id: string
397
+ let version: string | undefined
398
+ let configWhere: string
399
+
400
+ if (spec.startsWith('./') || spec.startsWith('../')) {
401
+ root = resolve(fromDir, spec)
402
+ if (!existsSync(root) || !statSync(root).isDirectory()) {
403
+ fail(`extends "${spec}", which is not a directory (looked in ${display(ctx.projectRoot, root)})`)
404
+ return
405
+ }
406
+ id = display(ctx.projectRoot, root)
407
+ configWhere = `${id}/${LAYER_CONFIG_FILE}`
408
+ // These directories are gitignored as local run output, so a baseline kept
409
+ // there works on one laptop and is missing from every clone and from CI.
410
+ const ignored = LOCAL_DIRS.find((d) => isInside(join(ctx.projectRoot, d), root))
411
+ if (ignored) {
412
+ ctx.issues.push({
413
+ level: 'warning',
414
+ where: declaredIn,
415
+ message: `extends "${spec}", inside ${ignored}/, which git ignores — no clone or CI run will have it`,
416
+ fix: 'keep a shared baseline somewhere committed, e.g. a top-level directory or a package',
417
+ })
418
+ }
419
+ try {
420
+ version = (JSON.parse(readFileSync(join(root, 'package.json'), 'utf8')) as { version?: string }).version
421
+ } catch {
422
+ version = undefined
423
+ }
424
+ } else if (isAbsolute(spec) || /^[A-Za-z]:[\\/]/.test(spec)) {
425
+ fail(
426
+ `extends "${spec}", an absolute path — it is different on every machine and in CI`,
427
+ `use a path relative to ${declaredIn} (starting with ./ or ../), or a package name`,
428
+ )
429
+ return
430
+ } else {
431
+ const versioned = /^((?:@[^/@]+\/)?[^/@]+)@(.+)$/.exec(spec)
432
+ if (versioned) {
433
+ fail(
434
+ `extends "${spec}" — a package's version belongs in package.json, where your lockfile pins it`,
435
+ `write "extends": ["${versioned[1]}"] and add "${versioned[1]}": "${versioned[2]}" to devDependencies`,
436
+ )
437
+ return
438
+ }
439
+ if (!PACKAGE_NAME.test(spec)) {
440
+ fail(`extends "${spec}", which is neither a package name nor a path starting with ./ or ../`)
441
+ return
442
+ }
443
+ const pkgDir = findPackageDir(spec, fromDir)
444
+ if (!pkgDir) {
445
+ fail(
446
+ `extends "${spec}", which is not installed`,
447
+ `add it to devDependencies and install (in CI, install dependencies before running opencastle)`,
448
+ )
449
+ return
450
+ }
451
+ let pkg: { version?: string; opencastle?: unknown }
452
+ try {
453
+ pkg = JSON.parse(readFileSync(join(pkgDir, 'package.json'), 'utf8'))
454
+ } catch (err) {
455
+ fail(`extends "${spec}", whose package.json cannot be read — ${(err as Error).message}`)
456
+ return
457
+ }
458
+ const decl = pkg.opencastle as { baseline?: unknown } | undefined
459
+ if (!decl || typeof decl !== 'object' || !('baseline' in decl) || typeof decl.baseline !== 'string') {
460
+ fail(
461
+ `extends "${spec}", which is not an OpenCastle baseline`,
462
+ `a baseline declares itself in its package.json: "opencastle": { "baseline": "." } (opencastle baseline init creates one)`,
463
+ )
464
+ return
465
+ }
466
+ root = resolve(pkgDir, decl.baseline)
467
+ if (relative(pkgDir, root).startsWith('..') || !existsSync(root)) {
468
+ fail(`extends "${spec}", whose "opencastle.baseline" points outside the package or at nothing`)
469
+ return
470
+ }
471
+ id = spec
472
+ version = pkg.version
473
+ configWhere = `${spec}/${posix(relative(pkgDir, join(root, LAYER_CONFIG_FILE)))}`
474
+ }
475
+
476
+ let real: string
477
+ try {
478
+ real = realpathSync(root)
479
+ } catch {
480
+ real = root
481
+ }
482
+ if (chain.includes(real)) {
483
+ const names = [...chain.map((c) => display(ctx.projectRoot, c)), display(ctx.projectRoot, real)]
484
+ fail(`extends itself in a cycle: ${names.join(' → ')}`)
485
+ return
486
+ }
487
+ // A baseline reached twice — two others both extend it — is loaded once, at
488
+ // the first place it appears, which is below everything that needs it.
489
+ if (ctx.seen.has(real)) return
490
+ ctx.seen.add(real)
491
+
492
+ const { config, issues } = readLayerConfig(root, configWhere)
493
+ ctx.issues.push(...issues)
494
+ for (const inner of config.extends ?? []) {
495
+ loadExtends(inner, root, configWhere, [...chain, real], ctx)
496
+ }
497
+ ctx.layers.push({ id, kind: 'baseline', root, version, config, configFile: configWhere, integrity: layerIntegrity(root) })
498
+ }
499
+
500
+ /** `${VAR}`, `${env:VAR}` and `{env:VAR}` all mean the same variable. */
501
+ export function normaliseRefs(value: string): string {
502
+ return value.replace(/\$\{env:([A-Za-z_][A-Za-z0-9_]*)\}/g, '${$1}').replace(/(?<!\$)\{env:([A-Za-z_][A-Za-z0-9_]*)\}/g, '${$1}')
503
+ }
504
+
505
+ export interface ResolveOptions {
506
+ pkgRoot: string
507
+ /** Null resolves OpenCastle's own content only — what an adapter compiles when called directly. */
508
+ projectRoot: string | null
509
+ stack?: StackConfig
510
+ repoInfo?: RepoInfo
511
+ }
512
+
513
+ /**
514
+ * Resolve every layer and merge them into one set of items, one MCP server
515
+ * list and one policy. Never throws on bad input: problems come back as issues,
516
+ * errors among them meaning "do not compile".
517
+ */
518
+ export function resolveSources(opts: ResolveOptions): ResolvedSources {
519
+ const { pkgRoot, projectRoot, stack, repoInfo } = opts
520
+ const cliVersion = cliVersionOf(pkgRoot)
521
+ const issues: TeamIssue[] = []
522
+
523
+ const core: Layer = { id: 'opencastle', kind: 'core', root: getOrchestratorRoot(pkgRoot), version: cliVersion, config: {} }
524
+ const layers: Layer[] = [core]
525
+
526
+ let project: Layer | null = null
527
+ if (projectRoot) {
528
+ const root = join(projectRoot, '.opencastle')
529
+ const { config, issues: configIssues } = readLayerConfig(root, TEAM_CONFIG_REL)
530
+ issues.push(...configIssues)
531
+ const ctx: ExtendsContext = { projectRoot, layers, seen: new Set(), issues }
532
+ for (const spec of config.extends ?? []) loadExtends(spec, root, TEAM_CONFIG_REL, [], ctx)
533
+ project = { id: 'project', kind: 'project', root, config, configFile: TEAM_CONFIG_REL }
534
+ layers.push(project)
535
+ }
536
+
537
+ // ── Content ──────────────────────────────────────────────────
538
+ const items = new Map<string, ContentItem>()
539
+ const key = (i: { kind: ContentKind; name: string }): string => `${i.kind}/${i.name}`
540
+ // Every layer's version of every item, in layer order: what `require` needs
541
+ // to tell "replaced what the baseline shipped" from "provided it, as asked".
542
+ const history = new Map<string, ContentItem[]>()
543
+ const remember = (k: string, item: ContentItem): void => {
544
+ const list = history.get(k) ?? []
545
+ list.push(item)
546
+ history.set(k, list)
547
+ }
548
+
549
+ // OpenCastle's own content, less what the stack leaves out. Those are not
550
+ // exclusions anyone wrote, so a team layer naming one is not a mistake.
551
+ const stackOut = new Set<string>()
552
+ const excludedSkills = stack ? getExcludedSkills(stack) : new Set<string>()
553
+ const excludedAgents = stack ? getExcludedAgents(stack) : new Set<string>()
554
+ for (const item of scanLayer(core, projectRoot).items) {
555
+ if (item.kind === 'skills' && excludedSkills.has(item.name)) {
556
+ stackOut.add(key(item))
557
+ continue
558
+ }
559
+ if (item.kind === 'agents' && excludedAgents.has(`${item.name}.agent.md`)) {
560
+ stackOut.add(key(item))
561
+ continue
562
+ }
563
+ items.set(key(item), item)
564
+ remember(key(item), item)
565
+ }
566
+ // Integration skills: one SKILL.md per included plugin.
567
+ const pluginsRoot = getPluginsRoot(pkgRoot)
568
+ const includedPlugins = stack ? getIncludedPluginIds(stack) : null
569
+ for (const entry of listDir(pluginsRoot)) {
570
+ if (!entry.isDir) continue
571
+ const skill = join(pluginsRoot, entry.name, 'SKILL.md')
572
+ if (!existsSync(skill)) continue
573
+ if (includedPlugins && !includedPlugins.has(entry.name)) {
574
+ stackOut.add(`skills/${entry.name}`)
575
+ continue
576
+ }
577
+ const k = `skills/${entry.name}`
578
+ const prev = items.get(k)
579
+ const item: ContentItem = { kind: 'skills', name: entry.name, layer: 'opencastle', path: skill, plugin: entry.name, ...(prev && { overrides: prev.layer }) }
580
+ items.set(k, item)
581
+ remember(k, item)
582
+ }
583
+
584
+ const excluded: ResolvedSources['excluded'] = []
585
+ for (const layer of layers) {
586
+ if (layer.kind === 'core') continue
587
+ const where = layer.configFile ?? layer.id
588
+ for (const ref of layer.config.exclude ?? []) {
589
+ // Servers are excluded where servers are merged, below.
590
+ if (ref.startsWith('mcpServers/')) continue
591
+ const prev = items.get(ref)
592
+ if (prev) {
593
+ items.delete(ref)
594
+ excluded.push({ ref, by: layer.id, from: prev.layer })
595
+ } else if (!stackOut.has(ref) && !excluded.some((e) => e.ref === ref)) {
596
+ issues.push({
597
+ level: 'warning',
598
+ where,
599
+ message: `excludes ${ref}, which no layer below provides`,
600
+ fix: 'check the spelling — opencastle explain lists everything that is compiled',
601
+ })
602
+ }
603
+ }
604
+ const scanned = scanLayer(layer, projectRoot)
605
+ issues.push(...scanned.issues)
606
+ for (const item of scanned.items) {
607
+ const prev = items.get(key(item))
608
+ const placed = prev ? { ...item, overrides: prev.layer } : item
609
+ items.set(key(item), placed)
610
+ remember(key(item), placed)
611
+ }
612
+ }
613
+
614
+ // ── Policy ───────────────────────────────────────────────────
615
+ const policy: EffectivePolicy = emptyPolicy()
616
+ for (const layer of layers) {
617
+ const where = layer.configFile ?? layer.id
618
+ const p = layer.config.policy
619
+ if (layer.config.opencastle) policy.versionRanges.push({ range: layer.config.opencastle, by: layer.id, where })
620
+ if (!p) continue
621
+ if (p.mcp?.allow) {
622
+ // Allowing what a lower layer refuses has no effect, and saying nothing
623
+ // would let someone believe they had allowed it.
624
+ for (const pattern of p.mcp.allow) {
625
+ if (pattern.includes('*')) continue
626
+ const by = disallowedBy(policy, pattern)
627
+ if (by) {
628
+ issues.push({
629
+ level: 'warning',
630
+ where,
631
+ message: `allows MCP server "${pattern}", but ${by} does not — the stricter list applies`,
632
+ fix: `ask the owners of ${by} to allow it`,
633
+ })
634
+ }
635
+ }
636
+ policy.allowLists.push({ by: layer.id, where, patterns: p.mcp.allow })
637
+ }
638
+ if (p.mcp?.remoteHosts) policy.hostLists.push({ by: layer.id, where, patterns: p.mcp.remoteHosts })
639
+ if (p.mcp?.requirePinned === true) policy.requirePinned ??= layer.id
640
+ if (p.mcp?.requirePinned === false && policy.requirePinned) {
641
+ issues.push({
642
+ level: 'warning',
643
+ where,
644
+ message: `sets requirePinned to false, but ${policy.requirePinned} requires it — a layer can tighten policy, not relax it`,
645
+ })
646
+ }
647
+ for (const ref of p.require ?? []) policy.require.push({ ref, by: layer.id })
648
+ if (p.contextBudget && (!policy.contextBudget || p.contextBudget < policy.contextBudget.tokens)) {
649
+ policy.contextBudget = { tokens: p.contextBudget, by: layer.id }
650
+ }
651
+ }
652
+
653
+ const layerIndex = new Map(layers.map((l, i) => [l.id, i]))
654
+ for (const { ref, by } of policy.require) {
655
+ const byLayer = layers[layerIndex.get(by) ?? 0]
656
+ const where = byLayer.configFile ?? by
657
+ const item = items.get(ref)
658
+ if (!item) {
659
+ const ex = excluded.find((e) => e.ref === ref)
660
+ issues.push(
661
+ ex
662
+ ? {
663
+ level: 'error',
664
+ where: layers[layerIndex.get(ex.by) ?? 0].configFile ?? ex.by,
665
+ message: `excludes ${ref}, which ${by} requires`,
666
+ fix: `remove it from "exclude", or ask the owners of ${by}`,
667
+ }
668
+ : { level: 'error', where, message: `requires ${ref}, which no layer provides` },
669
+ )
670
+ continue
671
+ }
672
+ // What the requiring layer saw: the last version at or below it. If there
673
+ // was one, nothing above may replace it; if there was none, the layer is
674
+ // asking for it to be provided, and whoever provides it satisfies that.
675
+ const at = layerIndex.get(by) ?? 0
676
+ const asShipped = [...(history.get(ref) ?? [])].reverse().find((i) => (layerIndex.get(i.layer) ?? 0) <= at)
677
+ if (asShipped && asShipped !== item && (layerIndex.get(item.layer) ?? 0) > at) {
678
+ const from = asShipped.layer === 'opencastle' ? 'OpenCastle' : asShipped.layer
679
+ issues.push({
680
+ level: 'error',
681
+ where: layers[layerIndex.get(item.layer) ?? 0].configFile ?? item.layer,
682
+ message: `${item.layer} replaces ${ref} (from ${from}), which ${by} requires unchanged`,
683
+ fix: `give yours another name and keep ${from}'s, or ask the owners of ${by}`,
684
+ })
685
+ }
686
+ }
687
+
688
+ // ── What team content must carry ─────────────────────────────
689
+ for (const item of items.values()) {
690
+ if (item.layer === 'opencastle') continue
691
+ if (item.kind !== 'skills' && item.kind !== 'agents') continue
692
+ const file = item.kind === 'skills' ? join(item.path, 'SKILL.md') : item.path
693
+ let meta: Record<string, string> = {}
694
+ try {
695
+ meta = parseFrontmatterString(splitFrontmatter(readFileSync(file, 'utf8').replace(/\r\n/g, '\n')).frontmatter)
696
+ } catch {
697
+ meta = {}
698
+ }
699
+ if (!meta.description) {
700
+ issues.push({
701
+ level: 'warning',
702
+ where: display(projectRoot, file),
703
+ message:
704
+ item.kind === 'skills'
705
+ ? 'has no description in its frontmatter, so no assistant can tell when to load it'
706
+ : 'has no description in its frontmatter, so the agent index has nothing to say about it',
707
+ fix: 'add ---\\ndescription: "…"\\n--- at the top',
708
+ })
709
+ }
710
+ }
711
+
712
+ // ── Team MCP servers ─────────────────────────────────────────
713
+ const servers = new Map<string, TeamServer>()
714
+ const blocked = new Map<string, string>()
715
+ const excludedServers = new Map<string, string>()
716
+ for (const layer of layers) {
717
+ if (layer.kind === 'core') continue
718
+ const where = layer.configFile ?? layer.id
719
+ // A layer opts out of a server a layer below defines — or an integration
720
+ // brings — by excluding it, as it excludes a skill.
721
+ for (const ref of layer.config.exclude ?? []) {
722
+ if (!ref.startsWith('mcpServers/')) continue
723
+ const k = ref.slice('mcpServers/'.length)
724
+ const known = servers.has(k) || Object.values(PLUGINS).some((p) => p.mcpServerKey === k)
725
+ if (!known) {
726
+ issues.push({
727
+ level: 'warning',
728
+ where,
729
+ message: `excludes ${ref}, which no layer below defines and no integration brings`,
730
+ fix: 'check the spelling — opencastle explain lists every MCP server',
731
+ })
732
+ }
733
+ if (servers.has(k)) servers.delete(k)
734
+ excludedServers.set(k, layer.id)
735
+ excluded.push({ ref, by: layer.id, from: 'mcp' })
736
+ }
737
+ for (const [k, raw] of Object.entries(layer.config.mcpServers ?? {})) {
738
+ const shape = checkServerShape(k, raw, where)
739
+ if (shape.length > 0) {
740
+ issues.push(...shape)
741
+ continue
742
+ }
743
+ const server: TeamMcpServer = {
744
+ ...raw,
745
+ ...(raw.args && { args: raw.args.map(normaliseRefs) }),
746
+ ...(raw.url && { url: normaliseRefs(raw.url) }),
747
+ ...(raw.env && { env: Object.fromEntries(Object.entries(raw.env).map(([n, val]) => [n, normaliseRefs(val)])) }),
748
+ ...(raw.headers && {
749
+ headers: Object.fromEntries(Object.entries(raw.headers).map(([n, val]) => [n, normaliseRefs(val)])),
750
+ }),
751
+ }
752
+ servers.set(k, { key: k, from: layer.id, server, where })
753
+ excludedServers.delete(k)
754
+ }
755
+ }
756
+ for (const ts of [...servers.values()]) {
757
+ const { key: k, server, where } = ts
758
+ // Refused by a layer above the one that defines it: that layer is opting
759
+ // out, and the server is left out like a refused integration. Refused by
760
+ // the defining layer's own policy or one below it: the layer is breaking a
761
+ // rule it is held to, and that is an error.
762
+ const defining = layerIndex.get(ts.from) ?? 0
763
+ const refusing = policy.allowLists.filter((l) => !l.patterns.some((p) => globMatch(p, k)))
764
+ const url = serverTransport(server) === 'http' ? server.url : undefined
765
+ const hostRefusing = url ? policy.hostLists.filter((l) => !hostAllowedBy(l.patterns, url)) : []
766
+ const all = [...refusing, ...hostRefusing]
767
+ if (all.length > 0 && all.every((l) => (layerIndex.get(l.by) ?? 0) > defining)) {
768
+ servers.delete(k)
769
+ blocked.set(k, refusing.length > 0 ? `not on the MCP allowlist of ${refusing.map((l) => l.by).join(', ')}` : `${hostOfUrl(url ?? '')} is not an allowed host for ${hostRefusing.map((l) => l.by).join(', ')}`)
770
+ continue
771
+ }
772
+ if (refusing.length > 0) {
773
+ const by = refusing.map((l) => l.by).join(', ')
774
+ issues.push({
775
+ level: 'error',
776
+ where,
777
+ message: `defines MCP server "${k}", which ${by} does not allow`,
778
+ fix: `add it to policy.mcp.allow in ${by}, or remove it`,
779
+ })
780
+ }
781
+ if (hostRefusing.length > 0) {
782
+ const by = hostRefusing.map((l) => l.by).join(', ')
783
+ issues.push({
784
+ level: 'error',
785
+ where,
786
+ message: `MCP server "${k}" connects to ${hostOfUrl(url ?? '')}, a host ${by} does not allow`,
787
+ fix: `add the host to policy.mcp.remoteHosts in ${by}, or remove the server`,
788
+ })
789
+ }
790
+ if (server.command) {
791
+ const launch = packageLaunch(server.command, server.args ?? [])
792
+ if (launch && !isPinned(launch)) {
793
+ issues.push({
794
+ level: policy.requirePinned ? 'error' : 'warning',
795
+ where,
796
+ message: `MCP server "${k}" runs ${launch.spec} without an exact version — every machine runs whatever was published last`,
797
+ fix: `pin it as ${launch.name}@x.y.z${policy.requirePinned ? ` (${policy.requirePinned} requires pinned servers)` : ''}`,
798
+ })
799
+ }
800
+ }
801
+ const secret = findInlineSecret(server as unknown as Record<string, unknown>)
802
+ if (secret) {
803
+ issues.push({
804
+ level: 'error',
805
+ where,
806
+ message: `MCP server "${k}" has a credential written into ${secret} — it would be committed to every assistant's config`,
807
+ fix: 'put it in an environment variable and write "${NAME}" here',
808
+ })
809
+ }
810
+ }
811
+
812
+ // Integration servers the stack brings in that the policy refuses. Not an
813
+ // error: the team chose the policy, and the integration's skill is still
814
+ // useful without its server. They are left out and the lock says why.
815
+ for (const [k, by] of excludedServers) blocked.set(k, `excluded by ${by}`)
816
+ const includedServers = stack
817
+ ? getIncludedMcpServers(stack, repoInfo)
818
+ : new Set(Object.values(PLUGINS).map((p) => p.mcpServerKey).filter((k): k is string => Boolean(k)))
819
+ for (const plugin of Object.values(PLUGINS)) {
820
+ const k = plugin.mcpServerKey
821
+ if (!k || !plugin.mcpConfig || !includedServers.has(k) || servers.has(k) || blocked.has(k)) continue
822
+ const refused = disallowedBy(policy, k)
823
+ if (refused) {
824
+ blocked.set(k, `not on the MCP allowlist of ${refused}`)
825
+ continue
826
+ }
827
+ if (plugin.mcpConfig.type === 'http' && plugin.mcpConfig.url) {
828
+ const hostRefused = hostDisallowedBy(policy, plugin.mcpConfig.url)
829
+ if (hostRefused) blocked.set(k, `${hostOfUrl(plugin.mcpConfig.url)} is not an allowed host for ${hostRefused}`)
830
+ }
831
+ }
832
+
833
+ // ── The OpenCastle version the project asked for ─────────────
834
+ for (const { range, by, where } of policy.versionRanges) {
835
+ const ok = satisfies(cliVersion, range)
836
+ if (ok === null) {
837
+ issues.push({ level: 'error', where, message: `"opencastle": "${range}" is not a version range this release can read` })
838
+ } else if (!ok) {
839
+ issues.push({
840
+ level: 'error',
841
+ where,
842
+ message: `${by === 'project' ? 'this project' : by} needs OpenCastle ${range}; this is ${cliVersion}`,
843
+ fix: `run the version the project pins — add opencastle to devDependencies and use npx opencastle, or run npx opencastle@"${range}"`,
844
+ })
845
+ }
846
+ }
847
+
848
+ return { layers, items, excluded, servers, blocked, policy, issues, cliVersion }
849
+ }
850
+
851
+ /**
852
+ * Throws when the running OpenCastle is older than the one that compiled the
853
+ * project: what it would compile is not what the project has, so any answer it
854
+ * gave — a review, an explanation — would describe the wrong thing.
855
+ */
856
+ export function refuseOlderCli(pkgRoot: string, projectVersion: string): void {
857
+ const running = cliVersionOf(pkgRoot)
858
+ const mine = parseVersion(running)
859
+ const theirs = parseVersion(projectVersion)
860
+ if (mine && theirs && compareVersions(mine, theirs) < 0) {
861
+ throw new Error(
862
+ `this project was compiled by OpenCastle ${projectVersion}; this is ${running} — run npx opencastle@${projectVersion}, or add it to devDependencies`,
863
+ )
864
+ }
865
+ }
866
+
867
+ export function hasErrors(resolved: ResolvedSources): boolean {
868
+ return resolved.issues.some((i) => i.level === 'error')
869
+ }
870
+
871
+ /** True when anything beyond OpenCastle's own content is in play. */
872
+ export function usesTeamSources(resolved: ResolvedSources): boolean {
873
+ return (
874
+ resolved.layers.some((l) => l.kind === 'baseline') ||
875
+ [...resolved.items.values()].some((i) => i.layer !== 'opencastle') ||
876
+ resolved.excluded.length > 0 ||
877
+ resolved.servers.size > 0 ||
878
+ resolved.layers.some((l) => Object.keys(l.config).some((k) => k !== '$schema'))
879
+ )
880
+ }
881
+
882
+ // ── Materialising the merged source ────────────────────────────
883
+
884
+ /** What the MCP writers need beyond the plugin servers. */
885
+ export interface TeamMcpPlan {
886
+ /** Servers the team's layers define, written into every target. */
887
+ servers: Record<string, TeamMcpServer>
888
+ /** Servers a previous sync wrote for the team that no layer defines any more. */
889
+ retired: string[]
890
+ /** Integration servers the policy refuses; never written, removed if present. */
891
+ blocked: string[]
892
+ /** VS Code inputs only the retired servers asked for. */
893
+ retiredInputs?: string[]
894
+ }
895
+
896
+ export interface CompileSource {
897
+ /** A directory shaped like `src/orchestrator/`, holding the merged content. */
898
+ root: string
899
+ resolved: ResolvedSources
900
+ mcp: TeamMcpPlan
901
+ dispose(): void
902
+ }
903
+
904
+ /** Team files as the adapters expect them: LF line endings, and frontmatter where a target needs it. */
905
+ function normaliseTeamText(kind: ContentKind, name: string, text: string): string {
906
+ const lf = text.replace(/^\uFEFF/, '').replace(/\r\n/g, '\n')
907
+ const fm = /^---\n([\s\S]*?)\n---\n/.exec(lf)
908
+ if (fm) {
909
+ // An instruction with a description and no `applyTo` is still an
910
+ // instruction: every other target loads it always, so Copilot must too.
911
+ if (kind === 'instructions' && !/^applyTo\s*:/m.test(fm[1])) {
912
+ return `---\n${fm[1]}\napplyTo: '**'\n---\n${lf.slice(fm[0].length)}`
913
+ }
914
+ return lf
915
+ }
916
+ if (kind === 'instructions') {
917
+ // Copilot loads `.github/instructions/*.instructions.md` only where
918
+ // `applyTo` matches; the other targets load every instruction always.
919
+ // Without this a team instruction reached six assistants and not the seventh.
920
+ return `---\napplyTo: '**'\n---\n\n${lf}`
921
+ }
922
+ if (kind === 'agents') return `---\nname: '${name}'\n---\n\n${lf}`
923
+ return lf
924
+ }
925
+
926
+ function copyTree(
927
+ from: string,
928
+ to: string,
929
+ opts: { team: boolean; within?: string[]; transform?: (rel: string, text: string) => string } = { team: false },
930
+ ): void {
931
+ mkdirSync(to, { recursive: true })
932
+ for (const rel of filesUnder(from, opts.within)) {
933
+ const dest = join(to, rel)
934
+ mkdirSync(dirname(dest), { recursive: true })
935
+ const buf = readFileSync(join(from, rel))
936
+ if (opts.transform && rel.endsWith('.md')) writeFileSync(dest, opts.transform(rel, buf.toString('utf8')))
937
+ else writeFileSync(dest, opts.team ? canonicalBytes(buf) : buf)
938
+ }
939
+ }
940
+
941
+ /**
942
+ * Write the merged content to a scratch directory in the layout the adapters
943
+ * read. The caller disposes it.
944
+ */
945
+ export function materialize(
946
+ resolved: ResolvedSources,
947
+ pkgRoot: string,
948
+ previousTeamServers: string[] = [],
949
+ previousTeamVariables: string[] = [],
950
+ ): CompileSource {
951
+ const root = mkdtempSync(join(tmpdir(), 'opencastle-src-'))
952
+ try {
953
+ const coreRoot = getOrchestratorRoot(pkgRoot)
954
+ const copilot = join(coreRoot, 'copilot-instructions.md')
955
+ if (existsSync(copilot)) writeFileSync(join(root, 'copilot-instructions.md'), readFileSync(copilot))
956
+ for (const kind of CONTENT_KINDS) mkdirSync(join(root, CORE_DIR[kind]), { recursive: true })
957
+
958
+ for (const item of resolved.items.values()) {
959
+ const dest = join(root, compiledPath(item.kind, item.name))
960
+ const team = item.layer !== 'opencastle'
961
+ if (item.kind === 'skills') {
962
+ if (item.plugin) {
963
+ mkdirSync(dest, { recursive: true })
964
+ writeFileSync(join(dest, 'SKILL.md'), readFileSync(item.path))
965
+ } else {
966
+ copyTree(item.path, dest, {
967
+ team,
968
+ within: item.within,
969
+ transform: team
970
+ ? (rel, text) => (rel === 'SKILL.md' ? normaliseTeamText('skills', item.name, text) : text.replace(/\r\n/g, '\n'))
971
+ : undefined,
972
+ })
973
+ }
974
+ continue
975
+ }
976
+ const buf = readFileSync(item.path)
977
+ writeFileSync(dest, team ? normaliseTeamText(item.kind, item.name, buf.toString('utf8')) : buf)
978
+ }
979
+ } catch (err) {
980
+ rmSync(root, { recursive: true, force: true })
981
+ throw err
982
+ }
983
+
984
+ return {
985
+ root,
986
+ resolved,
987
+ mcp: mcpPlan(resolved, previousTeamServers, previousTeamVariables),
988
+ dispose: () => rmSync(root, { recursive: true, force: true }),
989
+ }
990
+ }
991
+
992
+ /**
993
+ * What the MCP writers do for the team: its servers, the ones a previous sync
994
+ * wrote that no layer defines now (named by the committed lock), and the
995
+ * integrations its policy refuses.
996
+ */
997
+ export function mcpPlan(
998
+ resolved: ResolvedSources,
999
+ previousTeamServers: string[] = [],
1000
+ previousTeamVariables: string[] = [],
1001
+ ): TeamMcpPlan {
1002
+ const servers: Record<string, TeamMcpServer> = {}
1003
+ const used = new Set<string>()
1004
+ for (const [k, ts] of [...resolved.servers.entries()].sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0))) {
1005
+ servers[k] = ts.server
1006
+ for (const v of [...Object.values(ts.server.env ?? {}), ...Object.values(ts.server.headers ?? {}), ...(ts.server.args ?? []), ts.server.url ?? '']) {
1007
+ for (const name of envNamesIn(v)) used.add(name)
1008
+ }
1009
+ }
1010
+ return {
1011
+ servers,
1012
+ retired: previousTeamServers.filter((k) => !(k in servers)).sort(),
1013
+ blocked: [...resolved.blocked.keys()].sort(),
1014
+ retiredInputs: previousTeamVariables.filter((v) => !used.has(v)).sort(),
1015
+ }
1016
+ }
1017
+
1018
+ /**
1019
+ * OpenCastle's own content for a stack, with nothing from any project. What an
1020
+ * adapter compiles when it is called without a source — the tests, mostly.
1021
+ */
1022
+ export function defaultSource(pkgRoot: string, stack?: StackConfig): CompileSource {
1023
+ return materialize(resolveSources({ pkgRoot, projectRoot: null, stack }), pkgRoot)
1024
+ }
1025
+
1026
+ /** Run `fn` with the caller's source, or a default one that is cleaned up after. */
1027
+ export async function withSource<T>(
1028
+ pkgRoot: string,
1029
+ stack: StackConfig | undefined,
1030
+ source: CompileSource | undefined,
1031
+ fn: (src: CompileSource) => Promise<T>,
1032
+ ): Promise<T> {
1033
+ if (source) return fn(source)
1034
+ const own = defaultSource(pkgRoot, stack)
1035
+ try {
1036
+ return await fn(own)
1037
+ } finally {
1038
+ own.dispose()
1039
+ }
1040
+ }
1041
+
1042
+ /** Issues rendered for a terminal, one per line pair. */
1043
+ export function formatIssues(issues: TeamIssue[]): string[] {
1044
+ const out: string[] = []
1045
+ for (const i of issues) {
1046
+ out.push(`${i.level === 'error' ? '✗' : '!'} ${i.where}: ${i.message}`)
1047
+ if (i.fix) out.push(` → ${i.fix}`)
1048
+ }
1049
+ return out
1050
+ }
1051
+
1052
+ /**
1053
+ * The environment variables the servers this project will actually write need:
1054
+ * the integrations' (less any the team's policy refused or its layers
1055
+ * replaced), and every `${NAME}` a team server refers to.
1056
+ */
1057
+ export function requiredEnvVars(
1058
+ resolved: ResolvedSources | undefined,
1059
+ stack: StackConfig,
1060
+ repoInfo?: RepoInfo,
1061
+ ): Array<{ server: string; envVar: string; hint: string }> {
1062
+ const out = getRequiredMcpEnvVars(stack, repoInfo).filter(
1063
+ (r) => !resolved || (!resolved.blocked.has(r.server) && !resolved.servers.has(r.server)),
1064
+ )
1065
+ for (const ts of resolved?.servers.values() ?? []) {
1066
+ const names = new Set<string>()
1067
+ for (const value of [
1068
+ ...Object.values(ts.server.env ?? {}),
1069
+ ...Object.values(ts.server.headers ?? {}),
1070
+ ...(ts.server.args ?? []),
1071
+ ts.server.url ?? '',
1072
+ ts.server.command ?? '',
1073
+ ]) {
1074
+ for (const name of envNamesIn(value)) names.add(name)
1075
+ }
1076
+ for (const name of [...names].sort()) {
1077
+ // One entry per variable. Two servers reading the same token listed it
1078
+ // twice, and `init` wrote two `NAME=` lines to .env — where the empty
1079
+ // second one is what a dotenv loader keeps.
1080
+ const have = out.find((o) => o.envVar === name)
1081
+ if (have) {
1082
+ have.hint = `${have.hint}; also the ${ts.key} MCP server`
1083
+ continue
1084
+ }
1085
+ out.push({ server: ts.key, envVar: name, hint: `used by the ${ts.key} MCP server (${ts.where})` })
1086
+ }
1087
+ }
1088
+ return out
1089
+ }