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