@lesliechan721/aw 0.1.0-beta.10

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 (508) hide show
  1. package/dist/authoring/assets/aw-config.d.mts +51 -0
  2. package/dist/authoring/assets/aw-config.mjs +1025 -0
  3. package/dist/authoring/assets/aw-config.mjs.map +1 -0
  4. package/dist/authoring/scripts/add-skill.d.mts +2 -0
  5. package/dist/authoring/scripts/add-skill.mjs +355 -0
  6. package/dist/authoring/scripts/add-skill.mjs.map +1 -0
  7. package/dist/authoring/scripts/init-plugin.d.mts +2 -0
  8. package/dist/authoring/scripts/init-plugin.mjs +487 -0
  9. package/dist/authoring/scripts/init-plugin.mjs.map +1 -0
  10. package/dist/authoring/scripts/lib/javascript-import-scanner.d.mts +4 -0
  11. package/dist/authoring/scripts/lib/javascript-import-scanner.mjs +261 -0
  12. package/dist/authoring/scripts/lib/javascript-import-scanner.mjs.map +1 -0
  13. package/dist/authoring/scripts/lib/plugin-root.d.mts +26 -0
  14. package/dist/authoring/scripts/lib/plugin-root.mjs +125 -0
  15. package/dist/authoring/scripts/lib/plugin-root.mjs.map +1 -0
  16. package/dist/authoring/scripts/lib/plugin-version-check.d.mts +69 -0
  17. package/dist/authoring/scripts/lib/plugin-version-check.mjs +563 -0
  18. package/dist/authoring/scripts/lib/plugin-version-check.mjs.map +1 -0
  19. package/dist/authoring/scripts/lib/semver.d.mts +9 -0
  20. package/dist/authoring/scripts/lib/semver.mjs +63 -0
  21. package/dist/authoring/scripts/lib/semver.mjs.map +1 -0
  22. package/dist/authoring/scripts/lib/skill-scaffold.d.mts +111 -0
  23. package/dist/authoring/scripts/lib/skill-scaffold.mjs +353 -0
  24. package/dist/authoring/scripts/lib/skill-scaffold.mjs.map +1 -0
  25. package/dist/authoring/scripts/plugin-status.d.mts +2 -0
  26. package/dist/authoring/scripts/plugin-status.mjs +93 -0
  27. package/dist/authoring/scripts/plugin-status.mjs.map +1 -0
  28. package/dist/authoring/scripts/remove-plugin.d.mts +2 -0
  29. package/dist/authoring/scripts/remove-plugin.mjs +367 -0
  30. package/dist/authoring/scripts/remove-plugin.mjs.map +1 -0
  31. package/dist/authoring/scripts/validate-plugin.d.mts +2 -0
  32. package/dist/authoring/scripts/validate-plugin.mjs +3465 -0
  33. package/dist/authoring/scripts/validate-plugin.mjs.map +1 -0
  34. package/dist/authoring/scripts/validate-skill.d.mts +2 -0
  35. package/dist/authoring/scripts/validate-skill.mjs +126 -0
  36. package/dist/authoring/scripts/validate-skill.mjs.map +1 -0
  37. package/dist/authoring/templates/aw-config-runtime.d.mts +2 -0
  38. package/dist/authoring/templates/aw-config-runtime.mjs +407 -0
  39. package/dist/authoring/templates/aw-config-runtime.mjs.map +1 -0
  40. package/dist/index.d.ts +2 -0
  41. package/dist/index.js +8 -0
  42. package/dist/index.js.map +1 -0
  43. package/dist/scripts/aw-skill-eval-materializer.d.ts +24 -0
  44. package/dist/scripts/aw-skill-eval-materializer.js +309 -0
  45. package/dist/scripts/aw-skill-eval-materializer.js.map +1 -0
  46. package/dist/scripts/bundle-plugins.d.ts +17 -0
  47. package/dist/scripts/bundle-plugins.js +126 -0
  48. package/dist/scripts/bundle-plugins.js.map +1 -0
  49. package/dist/scripts/plugin-staging.d.ts +26 -0
  50. package/dist/scripts/plugin-staging.js +76 -0
  51. package/dist/scripts/plugin-staging.js.map +1 -0
  52. package/dist/scripts/test-plugin-scripts.d.ts +7 -0
  53. package/dist/scripts/test-plugin-scripts.js +610 -0
  54. package/dist/scripts/test-plugin-scripts.js.map +1 -0
  55. package/dist/src/adapters/helpers.d.ts +44 -0
  56. package/dist/src/adapters/helpers.js +95 -0
  57. package/dist/src/adapters/helpers.js.map +1 -0
  58. package/dist/src/authoring/workspace-commands.d.ts +70 -0
  59. package/dist/src/authoring/workspace-commands.js +158 -0
  60. package/dist/src/authoring/workspace-commands.js.map +1 -0
  61. package/dist/src/commands/aw-capabilities.d.ts +78 -0
  62. package/dist/src/commands/aw-capabilities.js +254 -0
  63. package/dist/src/commands/aw-capabilities.js.map +1 -0
  64. package/dist/src/commands/catalog-dev-source.d.ts +120 -0
  65. package/dist/src/commands/catalog-dev-source.js +434 -0
  66. package/dist/src/commands/catalog-dev-source.js.map +1 -0
  67. package/dist/src/commands/catalog-generation.d.ts +16 -0
  68. package/dist/src/commands/catalog-generation.js +9 -0
  69. package/dist/src/commands/catalog-generation.js.map +1 -0
  70. package/dist/src/commands/catalog-publication-inspection.d.ts +138 -0
  71. package/dist/src/commands/catalog-publication-inspection.js +711 -0
  72. package/dist/src/commands/catalog-publication-inspection.js.map +1 -0
  73. package/dist/src/commands/catalog-publication-journal.d.ts +56 -0
  74. package/dist/src/commands/catalog-publication-journal.js +215 -0
  75. package/dist/src/commands/catalog-publication-journal.js.map +1 -0
  76. package/dist/src/commands/catalog-publication-target.d.ts +18 -0
  77. package/dist/src/commands/catalog-publication-target.js +95 -0
  78. package/dist/src/commands/catalog-publication-target.js.map +1 -0
  79. package/dist/src/commands/catalog-publish.d.ts +103 -0
  80. package/dist/src/commands/catalog-publish.js +804 -0
  81. package/dist/src/commands/catalog-publish.js.map +1 -0
  82. package/dist/src/commands/catalog-source.d.ts +134 -0
  83. package/dist/src/commands/catalog-source.js +377 -0
  84. package/dist/src/commands/catalog-source.js.map +1 -0
  85. package/dist/src/commands/catalog-status.d.ts +56 -0
  86. package/dist/src/commands/catalog-status.js +217 -0
  87. package/dist/src/commands/catalog-status.js.map +1 -0
  88. package/dist/src/commands/catalog-store.d.ts +80 -0
  89. package/dist/src/commands/catalog-store.js +348 -0
  90. package/dist/src/commands/catalog-store.js.map +1 -0
  91. package/dist/src/commands/catalog-workspace-resolution.d.ts +13 -0
  92. package/dist/src/commands/catalog-workspace-resolution.js +42 -0
  93. package/dist/src/commands/catalog-workspace-resolution.js.map +1 -0
  94. package/dist/src/commands/console.d.ts +3 -0
  95. package/dist/src/commands/console.js +44 -0
  96. package/dist/src/commands/console.js.map +1 -0
  97. package/dist/src/commands/dependency-operation-plan.d.ts +58 -0
  98. package/dist/src/commands/dependency-operation-plan.js +261 -0
  99. package/dist/src/commands/dependency-operation-plan.js.map +1 -0
  100. package/dist/src/commands/init.d.ts +25 -0
  101. package/dist/src/commands/init.js +42 -0
  102. package/dist/src/commands/init.js.map +1 -0
  103. package/dist/src/commands/offline-cleanup-evidence.d.ts +59 -0
  104. package/dist/src/commands/offline-cleanup-evidence.js +163 -0
  105. package/dist/src/commands/offline-cleanup-evidence.js.map +1 -0
  106. package/dist/src/commands/operation-plan.d.ts +126 -0
  107. package/dist/src/commands/operation-plan.js +47 -0
  108. package/dist/src/commands/operation-plan.js.map +1 -0
  109. package/dist/src/commands/operation-planner.d.ts +46 -0
  110. package/dist/src/commands/operation-planner.js +139 -0
  111. package/dist/src/commands/operation-planner.js.map +1 -0
  112. package/dist/src/commands/options.d.ts +70 -0
  113. package/dist/src/commands/options.js +194 -0
  114. package/dist/src/commands/options.js.map +1 -0
  115. package/dist/src/commands/plugin-capabilities.d.ts +22 -0
  116. package/dist/src/commands/plugin-capabilities.js +159 -0
  117. package/dist/src/commands/plugin-capabilities.js.map +1 -0
  118. package/dist/src/commands/rebuild-command.d.ts +88 -0
  119. package/dist/src/commands/rebuild-command.js +3626 -0
  120. package/dist/src/commands/rebuild-command.js.map +1 -0
  121. package/dist/src/commands/rebuild-integration.d.ts +190 -0
  122. package/dist/src/commands/rebuild-integration.js +4439 -0
  123. package/dist/src/commands/rebuild-integration.js.map +1 -0
  124. package/dist/src/commands/rebuild-operations.d.ts +100 -0
  125. package/dist/src/commands/rebuild-operations.js +625 -0
  126. package/dist/src/commands/rebuild-operations.js.map +1 -0
  127. package/dist/src/commands/reconcile-operation-plan.d.ts +26 -0
  128. package/dist/src/commands/reconcile-operation-plan.js +28 -0
  129. package/dist/src/commands/reconcile-operation-plan.js.map +1 -0
  130. package/dist/src/commands/review-publication.d.ts +99 -0
  131. package/dist/src/commands/review-publication.js +904 -0
  132. package/dist/src/commands/review-publication.js.map +1 -0
  133. package/dist/src/commands/runtime.d.ts +172 -0
  134. package/dist/src/commands/runtime.js +720 -0
  135. package/dist/src/commands/runtime.js.map +1 -0
  136. package/dist/src/commands/skill-eval.d.ts +33 -0
  137. package/dist/src/commands/skill-eval.js +363 -0
  138. package/dist/src/commands/skill-eval.js.map +1 -0
  139. package/dist/src/commands/status-v6.d.ts +206 -0
  140. package/dist/src/commands/status-v6.js +2175 -0
  141. package/dist/src/commands/status-v6.js.map +1 -0
  142. package/dist/src/commands/sync-command.d.ts +23 -0
  143. package/dist/src/commands/sync-command.js +242 -0
  144. package/dist/src/commands/sync-command.js.map +1 -0
  145. package/dist/src/commands/wizard.d.ts +56 -0
  146. package/dist/src/commands/wizard.js +58 -0
  147. package/dist/src/commands/wizard.js.map +1 -0
  148. package/dist/src/commands/write-commands.d.ts +7 -0
  149. package/dist/src/commands/write-commands.js +190 -0
  150. package/dist/src/commands/write-commands.js.map +1 -0
  151. package/dist/src/constants.d.ts +31 -0
  152. package/dist/src/constants.js +32 -0
  153. package/dist/src/constants.js.map +1 -0
  154. package/dist/src/eval/manifest-v1.d.ts +67 -0
  155. package/dist/src/eval/manifest-v1.js +347 -0
  156. package/dist/src/eval/manifest-v1.js.map +1 -0
  157. package/dist/src/generators/agents.d.ts +3 -0
  158. package/dist/src/generators/agents.js +46 -0
  159. package/dist/src/generators/agents.js.map +1 -0
  160. package/dist/src/generators/hooks.d.ts +15 -0
  161. package/dist/src/generators/hooks.js +76 -0
  162. package/dist/src/generators/hooks.js.map +1 -0
  163. package/dist/src/generators/instructions.d.ts +13 -0
  164. package/dist/src/generators/instructions.js +66 -0
  165. package/dist/src/generators/instructions.js.map +1 -0
  166. package/dist/src/generators/local-plugin.d.ts +56 -0
  167. package/dist/src/generators/local-plugin.js +1373 -0
  168. package/dist/src/generators/local-plugin.js.map +1 -0
  169. package/dist/src/generators/permissions.d.ts +10 -0
  170. package/dist/src/generators/permissions.js +37 -0
  171. package/dist/src/generators/permissions.js.map +1 -0
  172. package/dist/src/generators/shared.d.ts +2 -0
  173. package/dist/src/generators/shared.js +15 -0
  174. package/dist/src/generators/shared.js.map +1 -0
  175. package/dist/src/index.d.ts +41 -0
  176. package/dist/src/index.js +3327 -0
  177. package/dist/src/index.js.map +1 -0
  178. package/dist/src/output/command-receipt.d.ts +87 -0
  179. package/dist/src/output/command-receipt.js +302 -0
  180. package/dist/src/output/command-receipt.js.map +1 -0
  181. package/dist/src/output/debug-log.d.ts +4 -0
  182. package/dist/src/output/debug-log.js +97 -0
  183. package/dist/src/output/debug-log.js.map +1 -0
  184. package/dist/src/output/equivalent-command.d.ts +9 -0
  185. package/dist/src/output/equivalent-command.js +39 -0
  186. package/dist/src/output/equivalent-command.js.map +1 -0
  187. package/dist/src/output/model.d.ts +76 -0
  188. package/dist/src/output/model.js +2 -0
  189. package/dist/src/output/model.js.map +1 -0
  190. package/dist/src/output/rebuild-progress.d.ts +21 -0
  191. package/dist/src/output/rebuild-progress.js +128 -0
  192. package/dist/src/output/rebuild-progress.js.map +1 -0
  193. package/dist/src/output/redact.d.ts +3 -0
  194. package/dist/src/output/redact.js +39 -0
  195. package/dist/src/output/redact.js.map +1 -0
  196. package/dist/src/output/reporter.d.ts +9 -0
  197. package/dist/src/output/reporter.js +133 -0
  198. package/dist/src/output/reporter.js.map +1 -0
  199. package/dist/src/portable/commands.d.ts +124 -0
  200. package/dist/src/portable/commands.js +557 -0
  201. package/dist/src/portable/commands.js.map +1 -0
  202. package/dist/src/portable/materializer.d.ts +50 -0
  203. package/dist/src/portable/materializer.js +462 -0
  204. package/dist/src/portable/materializer.js.map +1 -0
  205. package/dist/src/portable/skills-cli.d.ts +43 -0
  206. package/dist/src/portable/skills-cli.js +148 -0
  207. package/dist/src/portable/skills-cli.js.map +1 -0
  208. package/dist/src/tui/catalog-freshness.d.ts +1 -0
  209. package/dist/src/tui/catalog-freshness.js +2 -0
  210. package/dist/src/tui/catalog-freshness.js.map +1 -0
  211. package/dist/src/tui/catalog-generation.d.ts +21 -0
  212. package/dist/src/tui/catalog-generation.js +116 -0
  213. package/dist/src/tui/catalog-generation.js.map +1 -0
  214. package/dist/src/tui/catalog-sources/projection.d.ts +4 -0
  215. package/dist/src/tui/catalog-sources/projection.js +17 -0
  216. package/dist/src/tui/catalog-sources/projection.js.map +1 -0
  217. package/dist/src/tui/catalog-sources/review.d.ts +3 -0
  218. package/dist/src/tui/catalog-sources/review.js +13 -0
  219. package/dist/src/tui/catalog-sources/review.js.map +1 -0
  220. package/dist/src/tui/catalog-sources/screens.d.ts +12 -0
  221. package/dist/src/tui/catalog-sources/screens.js +33 -0
  222. package/dist/src/tui/catalog-sources/screens.js.map +1 -0
  223. package/dist/src/tui/catalog-sources/session.d.ts +22 -0
  224. package/dist/src/tui/catalog-sources/session.js +225 -0
  225. package/dist/src/tui/catalog-sources/session.js.map +1 -0
  226. package/dist/src/tui/catalog-sources/types.d.ts +41 -0
  227. package/dist/src/tui/catalog-sources/types.js +2 -0
  228. package/dist/src/tui/catalog-sources/types.js.map +1 -0
  229. package/dist/src/tui/components.d.ts +102 -0
  230. package/dist/src/tui/components.js +184 -0
  231. package/dist/src/tui/components.js.map +1 -0
  232. package/dist/src/tui/console-app-v4.d.ts +20 -0
  233. package/dist/src/tui/console-app-v4.js +5066 -0
  234. package/dist/src/tui/console-app-v4.js.map +1 -0
  235. package/dist/src/tui/controller-runtime.d.ts +23 -0
  236. package/dist/src/tui/controller-runtime.js +2011 -0
  237. package/dist/src/tui/controller-runtime.js.map +1 -0
  238. package/dist/src/tui/controller.d.ts +557 -0
  239. package/dist/src/tui/controller.js +2120 -0
  240. package/dist/src/tui/controller.js.map +1 -0
  241. package/dist/src/tui/diagnostics.d.ts +30 -0
  242. package/dist/src/tui/diagnostics.js +71 -0
  243. package/dist/src/tui/diagnostics.js.map +1 -0
  244. package/dist/src/tui/index.d.ts +17 -0
  245. package/dist/src/tui/index.js +17 -0
  246. package/dist/src/tui/index.js.map +1 -0
  247. package/dist/src/tui/input-display.d.ts +8 -0
  248. package/dist/src/tui/input-display.js +36 -0
  249. package/dist/src/tui/input-display.js.map +1 -0
  250. package/dist/src/tui/keys.d.ts +12 -0
  251. package/dist/src/tui/keys.js +22 -0
  252. package/dist/src/tui/keys.js.map +1 -0
  253. package/dist/src/tui/layout.d.ts +12 -0
  254. package/dist/src/tui/layout.js +19 -0
  255. package/dist/src/tui/layout.js.map +1 -0
  256. package/dist/src/tui/model.d.ts +424 -0
  257. package/dist/src/tui/model.js +1493 -0
  258. package/dist/src/tui/model.js.map +1 -0
  259. package/dist/src/tui/operation-review-planner.d.ts +21 -0
  260. package/dist/src/tui/operation-review-planner.js +622 -0
  261. package/dist/src/tui/operation-review-planner.js.map +1 -0
  262. package/dist/src/tui/prompt.d.ts +8 -0
  263. package/dist/src/tui/prompt.js +231 -0
  264. package/dist/src/tui/prompt.js.map +1 -0
  265. package/dist/src/tui/router.d.ts +206 -0
  266. package/dist/src/tui/router.js +137 -0
  267. package/dist/src/tui/router.js.map +1 -0
  268. package/dist/src/tui/runner.d.ts +11 -0
  269. package/dist/src/tui/runner.js +71 -0
  270. package/dist/src/tui/runner.js.map +1 -0
  271. package/dist/src/tui/source-ref-presets.d.ts +3 -0
  272. package/dist/src/tui/source-ref-presets.js +11 -0
  273. package/dist/src/tui/source-ref-presets.js.map +1 -0
  274. package/dist/src/tui/theme.d.ts +26 -0
  275. package/dist/src/tui/theme.js +28 -0
  276. package/dist/src/tui/theme.js.map +1 -0
  277. package/dist/src/tui/viewport.d.ts +20 -0
  278. package/dist/src/tui/viewport.js +29 -0
  279. package/dist/src/tui/viewport.js.map +1 -0
  280. package/dist/src/tui/views.d.ts +57 -0
  281. package/dist/src/tui/views.js +201 -0
  282. package/dist/src/tui/views.js.map +1 -0
  283. package/dist/src/tui/wizard.d.ts +11 -0
  284. package/dist/src/tui/wizard.js +323 -0
  285. package/dist/src/tui/wizard.js.map +1 -0
  286. package/dist/src/types.d.ts +474 -0
  287. package/dist/src/types.js +34 -0
  288. package/dist/src/types.js.map +1 -0
  289. package/dist/src/utils/agent-version.d.ts +19 -0
  290. package/dist/src/utils/agent-version.js +205 -0
  291. package/dist/src/utils/agent-version.js.map +1 -0
  292. package/dist/src/utils/artifact-plan.d.ts +27 -0
  293. package/dist/src/utils/artifact-plan.js +453 -0
  294. package/dist/src/utils/artifact-plan.js.map +1 -0
  295. package/dist/src/utils/artifact-renderer.d.ts +129 -0
  296. package/dist/src/utils/artifact-renderer.js +400 -0
  297. package/dist/src/utils/artifact-renderer.js.map +1 -0
  298. package/dist/src/utils/artifact-request.d.ts +16 -0
  299. package/dist/src/utils/artifact-request.js +42 -0
  300. package/dist/src/utils/artifact-request.js.map +1 -0
  301. package/dist/src/utils/artifact-sources.d.ts +8 -0
  302. package/dist/src/utils/artifact-sources.js +10 -0
  303. package/dist/src/utils/artifact-sources.js.map +1 -0
  304. package/dist/src/utils/aw-home-mutation-lock.d.ts +11 -0
  305. package/dist/src/utils/aw-home-mutation-lock.js +83 -0
  306. package/dist/src/utils/aw-home-mutation-lock.js.map +1 -0
  307. package/dist/src/utils/bundle-integrity.d.ts +2 -0
  308. package/dist/src/utils/bundle-integrity.js +63 -0
  309. package/dist/src/utils/bundle-integrity.js.map +1 -0
  310. package/dist/src/utils/bundle-layout.d.ts +4 -0
  311. package/dist/src/utils/bundle-layout.js +531 -0
  312. package/dist/src/utils/bundle-layout.js.map +1 -0
  313. package/dist/src/utils/catalog-digests.d.ts +18 -0
  314. package/dist/src/utils/catalog-digests.js +156 -0
  315. package/dist/src/utils/catalog-digests.js.map +1 -0
  316. package/dist/src/utils/catalog-generation-control-snapshot.d.ts +11 -0
  317. package/dist/src/utils/catalog-generation-control-snapshot.js +45 -0
  318. package/dist/src/utils/catalog-generation-control-snapshot.js.map +1 -0
  319. package/dist/src/utils/catalog-generation-error.d.ts +16 -0
  320. package/dist/src/utils/catalog-generation-error.js +30 -0
  321. package/dist/src/utils/catalog-generation-error.js.map +1 -0
  322. package/dist/src/utils/catalog-generation-resolver.d.ts +32 -0
  323. package/dist/src/utils/catalog-generation-resolver.js +251 -0
  324. package/dist/src/utils/catalog-generation-resolver.js.map +1 -0
  325. package/dist/src/utils/catalog-generation-service.d.ts +161 -0
  326. package/dist/src/utils/catalog-generation-service.js +1237 -0
  327. package/dist/src/utils/catalog-generation-service.js.map +1 -0
  328. package/dist/src/utils/catalog-generation-state.d.ts +22 -0
  329. package/dist/src/utils/catalog-generation-state.js +192 -0
  330. package/dist/src/utils/catalog-generation-state.js.map +1 -0
  331. package/dist/src/utils/catalog-generation-store.d.ts +57 -0
  332. package/dist/src/utils/catalog-generation-store.js +397 -0
  333. package/dist/src/utils/catalog-generation-store.js.map +1 -0
  334. package/dist/src/utils/catalog-manifest-v7.d.ts +5 -0
  335. package/dist/src/utils/catalog-manifest-v7.js +98 -0
  336. package/dist/src/utils/catalog-manifest-v7.js.map +1 -0
  337. package/dist/src/utils/catalog-operation-context.d.ts +20 -0
  338. package/dist/src/utils/catalog-operation-context.js +141 -0
  339. package/dist/src/utils/catalog-operation-context.js.map +1 -0
  340. package/dist/src/utils/catalog-public-error.d.ts +19 -0
  341. package/dist/src/utils/catalog-public-error.js +100 -0
  342. package/dist/src/utils/catalog-public-error.js.map +1 -0
  343. package/dist/src/utils/catalog-runtime-projection.d.ts +33 -0
  344. package/dist/src/utils/catalog-runtime-projection.js +77 -0
  345. package/dist/src/utils/catalog-runtime-projection.js.map +1 -0
  346. package/dist/src/utils/catalog-snapshot.d.ts +10 -0
  347. package/dist/src/utils/catalog-snapshot.js +20 -0
  348. package/dist/src/utils/catalog-snapshot.js.map +1 -0
  349. package/dist/src/utils/catalog-source-identity.d.ts +5 -0
  350. package/dist/src/utils/catalog-source-identity.js +137 -0
  351. package/dist/src/utils/catalog-source-identity.js.map +1 -0
  352. package/dist/src/utils/catalog-source-impact.d.ts +20 -0
  353. package/dist/src/utils/catalog-source-impact.js +222 -0
  354. package/dist/src/utils/catalog-source-impact.js.map +1 -0
  355. package/dist/src/utils/catalog-source-presentation.d.ts +1 -0
  356. package/dist/src/utils/catalog-source-presentation.js +32 -0
  357. package/dist/src/utils/catalog-source-presentation.js.map +1 -0
  358. package/dist/src/utils/catalog-source-references.d.ts +66 -0
  359. package/dist/src/utils/catalog-source-references.js +1180 -0
  360. package/dist/src/utils/catalog-source-references.js.map +1 -0
  361. package/dist/src/utils/catalog-sources.d.ts +53 -0
  362. package/dist/src/utils/catalog-sources.js +456 -0
  363. package/dist/src/utils/catalog-sources.js.map +1 -0
  364. package/dist/src/utils/codex-config.d.ts +126 -0
  365. package/dist/src/utils/codex-config.js +1032 -0
  366. package/dist/src/utils/codex-config.js.map +1 -0
  367. package/dist/src/utils/codex-manager.d.ts +81 -0
  368. package/dist/src/utils/codex-manager.js +810 -0
  369. package/dist/src/utils/codex-manager.js.map +1 -0
  370. package/dist/src/utils/codex-marketplace-path.d.ts +5 -0
  371. package/dist/src/utils/codex-marketplace-path.js +45 -0
  372. package/dist/src/utils/codex-marketplace-path.js.map +1 -0
  373. package/dist/src/utils/codex-native-observation.d.ts +16 -0
  374. package/dist/src/utils/codex-native-observation.js +22 -0
  375. package/dist/src/utils/codex-native-observation.js.map +1 -0
  376. package/dist/src/utils/codex-native-render-receipt.d.ts +40 -0
  377. package/dist/src/utils/codex-native-render-receipt.js +205 -0
  378. package/dist/src/utils/codex-native-render-receipt.js.map +1 -0
  379. package/dist/src/utils/codex-reconciler.d.ts +128 -0
  380. package/dist/src/utils/codex-reconciler.js +294 -0
  381. package/dist/src/utils/codex-reconciler.js.map +1 -0
  382. package/dist/src/utils/codex-roles.d.ts +71 -0
  383. package/dist/src/utils/codex-roles.js +257 -0
  384. package/dist/src/utils/codex-roles.js.map +1 -0
  385. package/dist/src/utils/codex-shared-native.d.ts +63 -0
  386. package/dist/src/utils/codex-shared-native.js +142 -0
  387. package/dist/src/utils/codex-shared-native.js.map +1 -0
  388. package/dist/src/utils/codex-skill-staging.d.ts +11 -0
  389. package/dist/src/utils/codex-skill-staging.js +8 -0
  390. package/dist/src/utils/codex-skill-staging.js.map +1 -0
  391. package/dist/src/utils/codex-surface-analysis.d.ts +45 -0
  392. package/dist/src/utils/codex-surface-analysis.js +245 -0
  393. package/dist/src/utils/codex-surface-analysis.js.map +1 -0
  394. package/dist/src/utils/config-value.d.ts +3 -0
  395. package/dist/src/utils/config-value.js +23 -0
  396. package/dist/src/utils/config-value.js.map +1 -0
  397. package/dist/src/utils/dynamic-skill-tree.d.ts +36 -0
  398. package/dist/src/utils/dynamic-skill-tree.js +466 -0
  399. package/dist/src/utils/dynamic-skill-tree.js.map +1 -0
  400. package/dist/src/utils/file-rules.d.ts +1 -0
  401. package/dist/src/utils/file-rules.js +2 -0
  402. package/dist/src/utils/file-rules.js.map +1 -0
  403. package/dist/src/utils/git-catalog-provider.d.ts +22 -0
  404. package/dist/src/utils/git-catalog-provider.js +497 -0
  405. package/dist/src/utils/git-catalog-provider.js.map +1 -0
  406. package/dist/src/utils/hooks-contract.d.ts +1 -0
  407. package/dist/src/utils/hooks-contract.js +2 -0
  408. package/dist/src/utils/hooks-contract.js.map +1 -0
  409. package/dist/src/utils/json.d.ts +4 -0
  410. package/dist/src/utils/json.js +29 -0
  411. package/dist/src/utils/json.js.map +1 -0
  412. package/dist/src/utils/local-marketplace.d.ts +41 -0
  413. package/dist/src/utils/local-marketplace.js +316 -0
  414. package/dist/src/utils/local-marketplace.js.map +1 -0
  415. package/dist/src/utils/manifest.d.ts +11 -0
  416. package/dist/src/utils/manifest.js +33 -0
  417. package/dist/src/utils/manifest.js.map +1 -0
  418. package/dist/src/utils/marketplace.d.ts +3 -0
  419. package/dist/src/utils/marketplace.js +76 -0
  420. package/dist/src/utils/marketplace.js.map +1 -0
  421. package/dist/src/utils/multi-source-catalog.d.ts +66 -0
  422. package/dist/src/utils/multi-source-catalog.js +345 -0
  423. package/dist/src/utils/multi-source-catalog.js.map +1 -0
  424. package/dist/src/utils/native-cli.d.ts +118 -0
  425. package/dist/src/utils/native-cli.js +518 -0
  426. package/dist/src/utils/native-cli.js.map +1 -0
  427. package/dist/src/utils/orphan-marketplace-cleanup.d.ts +18 -0
  428. package/dist/src/utils/orphan-marketplace-cleanup.js +198 -0
  429. package/dist/src/utils/orphan-marketplace-cleanup.js.map +1 -0
  430. package/dist/src/utils/ownership.d.ts +194 -0
  431. package/dist/src/utils/ownership.js +723 -0
  432. package/dist/src/utils/ownership.js.map +1 -0
  433. package/dist/src/utils/path-catalog-provider.d.ts +7 -0
  434. package/dist/src/utils/path-catalog-provider.js +74 -0
  435. package/dist/src/utils/path-catalog-provider.js.map +1 -0
  436. package/dist/src/utils/paths.d.ts +40 -0
  437. package/dist/src/utils/paths.js +137 -0
  438. package/dist/src/utils/paths.js.map +1 -0
  439. package/dist/src/utils/platform-entries.d.ts +1 -0
  440. package/dist/src/utils/platform-entries.js +2 -0
  441. package/dist/src/utils/platform-entries.js.map +1 -0
  442. package/dist/src/utils/platform-support.d.ts +1 -0
  443. package/dist/src/utils/platform-support.js +2 -0
  444. package/dist/src/utils/platform-support.js.map +1 -0
  445. package/dist/src/utils/plugin-config-write.d.ts +110 -0
  446. package/dist/src/utils/plugin-config-write.js +773 -0
  447. package/dist/src/utils/plugin-config-write.js.map +1 -0
  448. package/dist/src/utils/plugin-config.d.ts +389 -0
  449. package/dist/src/utils/plugin-config.js +1642 -0
  450. package/dist/src/utils/plugin-config.js.map +1 -0
  451. package/dist/src/utils/plugin-dependencies.d.ts +12 -0
  452. package/dist/src/utils/plugin-dependencies.js +162 -0
  453. package/dist/src/utils/plugin-dependencies.js.map +1 -0
  454. package/dist/src/utils/plugin-intent-state.d.ts +34 -0
  455. package/dist/src/utils/plugin-intent-state.js +289 -0
  456. package/dist/src/utils/plugin-intent-state.js.map +1 -0
  457. package/dist/src/utils/plugin-script-contract.d.ts +1 -0
  458. package/dist/src/utils/plugin-script-contract.js +2 -0
  459. package/dist/src/utils/plugin-script-contract.js.map +1 -0
  460. package/dist/src/utils/plugin-scripts.d.ts +101 -0
  461. package/dist/src/utils/plugin-scripts.js +253 -0
  462. package/dist/src/utils/plugin-scripts.js.map +1 -0
  463. package/dist/src/utils/process-lock.d.ts +47 -0
  464. package/dist/src/utils/process-lock.js +532 -0
  465. package/dist/src/utils/process-lock.js.map +1 -0
  466. package/dist/src/utils/process-tree.d.ts +2 -0
  467. package/dist/src/utils/process-tree.js +2 -0
  468. package/dist/src/utils/process-tree.js.map +1 -0
  469. package/dist/src/utils/project-boundary.d.ts +9 -0
  470. package/dist/src/utils/project-boundary.js +67 -0
  471. package/dist/src/utils/project-boundary.js.map +1 -0
  472. package/dist/src/utils/rendered-contract.d.ts +8 -0
  473. package/dist/src/utils/rendered-contract.js +134 -0
  474. package/dist/src/utils/rendered-contract.js.map +1 -0
  475. package/dist/src/utils/runtime-skill-closure.d.ts +13 -0
  476. package/dist/src/utils/runtime-skill-closure.js +863 -0
  477. package/dist/src/utils/runtime-skill-closure.js.map +1 -0
  478. package/dist/src/utils/safe-fs.d.ts +21 -0
  479. package/dist/src/utils/safe-fs.js +111 -0
  480. package/dist/src/utils/safe-fs.js.map +1 -0
  481. package/dist/src/utils/skill-authoring.d.ts +1 -0
  482. package/dist/src/utils/skill-authoring.js +2 -0
  483. package/dist/src/utils/skill-authoring.js.map +1 -0
  484. package/dist/src/utils/skill-validation.d.ts +37 -0
  485. package/dist/src/utils/skill-validation.js +326 -0
  486. package/dist/src/utils/skill-validation.js.map +1 -0
  487. package/dist/src/utils/slash-commands.d.ts +1 -0
  488. package/dist/src/utils/slash-commands.js +2 -0
  489. package/dist/src/utils/slash-commands.js.map +1 -0
  490. package/dist/src/utils/state-paths.d.ts +14 -0
  491. package/dist/src/utils/state-paths.js +139 -0
  492. package/dist/src/utils/state-paths.js.map +1 -0
  493. package/dist/src/utils/target-eligibility.d.ts +13 -0
  494. package/dist/src/utils/target-eligibility.js +35 -0
  495. package/dist/src/utils/target-eligibility.js.map +1 -0
  496. package/dist/src/utils/target-order.d.ts +7 -0
  497. package/dist/src/utils/target-order.js +10 -0
  498. package/dist/src/utils/target-order.js.map +1 -0
  499. package/dist/src/utils/template-engine.d.ts +1 -0
  500. package/dist/src/utils/template-engine.js +2 -0
  501. package/dist/src/utils/template-engine.js.map +1 -0
  502. package/dist/src/utils/test-path-fence.d.ts +12 -0
  503. package/dist/src/utils/test-path-fence.js +31 -0
  504. package/dist/src/utils/test-path-fence.js.map +1 -0
  505. package/dist/vitest.config.d.ts +2 -0
  506. package/dist/vitest.config.js +16 -0
  507. package/dist/vitest.config.js.map +1 -0
  508. package/package.json +64 -0
@@ -0,0 +1,3465 @@
1
+ #!/usr/bin/env node
2
+ import { spawnSync } from 'node:child_process';
3
+ import { createHash } from 'node:crypto';
4
+ import * as fs from 'node:fs';
5
+ import { createRequire } from 'node:module';
6
+ import * as os from 'node:os';
7
+ import * as path from 'node:path';
8
+ import { fileURLToPath, pathToFileURL } from 'node:url';
9
+ import { getPluginAuthoringAcceptedValues as getCorePluginAuthoringAcceptedValues, getSkillFrontmatterCapabilityRegistry, normalizePluginConfigDefinition, } from '@lesliechan721/aw-plugin-core/manifest';
10
+ import { checkPluginVersions } from './lib/plugin-version-check.mjs';
11
+ import { scanJavaScriptImportSpecifiers } from './lib/javascript-import-scanner.mjs';
12
+ import { assertAuthoringPluginPathFence, assertCanonicalAuthoringPluginRoot, } from './lib/plugin-root.mjs';
13
+ const require = createRequire(import.meta.url);
14
+ const __dirname = path.dirname(fileURLToPath(import.meta.url));
15
+ const authoringRuntimeRoot = path.resolve(__dirname, '..', '..');
16
+ const CLI_PACKAGE_ROOT = path.basename(authoringRuntimeRoot) === 'dist'
17
+ ? path.dirname(authoringRuntimeRoot)
18
+ : authoringRuntimeRoot;
19
+ const errors = [];
20
+ const warnings = [];
21
+ const SOURCE_PLUGIN_MANIFEST_CONTRACT_VERSION = 11;
22
+ let capabilityDiagnostic = null;
23
+ const MAX_SKILL_NAME_LEN = 64;
24
+ const MAX_SKILL_DESCRIPTION_LEN = 1024;
25
+ const MAX_SKILL_COMPATIBILITY_LEN = 500;
26
+ const MAX_SKILL_SHORT_DESCRIPTION_LEN = 1024;
27
+ const MAX_SKILL_LINES = 500;
28
+ const MAX_OPENAI_INTERFACE_NAME_LEN = 64;
29
+ const MIN_OPENAI_INTERFACE_DESCRIPTION_LEN = 25;
30
+ const MAX_OPENAI_INTERFACE_DESCRIPTION_LEN = 64;
31
+ const MAX_OPENAI_DEFAULT_PROMPT_LEN = 1024;
32
+ const MAX_OPENAI_DEPENDENCY_TYPE_LEN = 64;
33
+ const MAX_OPENAI_DEPENDENCY_TRANSPORT_LEN = 64;
34
+ const MAX_OPENAI_DEPENDENCY_VALUE_LEN = 1024;
35
+ const MAX_OPENAI_DEPENDENCY_DESCRIPTION_LEN = 1024;
36
+ const MAX_OPENAI_DEPENDENCY_COMMAND_LEN = 1024;
37
+ const MAX_OPENAI_DEPENDENCY_URL_LEN = 1024;
38
+ const CLAUDE_FRONTMATTER_SHELLS = new Set(['bash', 'powershell']);
39
+ const CLAUDE_SLASH_COMMAND_ONLY_FIELDS = new Set([
40
+ 'allowed-tools',
41
+ 'model',
42
+ 'argument-hint',
43
+ 'disable-model-invocation',
44
+ 'shell',
45
+ ]);
46
+ const CODEX_POLICY_PRODUCTS = new Set([
47
+ 'atlas',
48
+ 'ATLAS',
49
+ 'chatgpt',
50
+ 'CHATGPT',
51
+ 'codex',
52
+ 'CODEX',
53
+ ]);
54
+ const MANIFEST_POLICY_PRODUCTS = new Set(getPluginAuthoringAcceptedValues('manifest', 'marketplace.policy.products'));
55
+ const MARKETPLACE_AUTHENTICATION_POLICIES = new Set(getPluginAuthoringAcceptedValues('manifest', 'marketplace.policy.authentication'));
56
+ const MARKETPLACE_INSTALLATION_POLICIES = new Set(getPluginAuthoringAcceptedValues('manifest', 'marketplace.policy.installation'));
57
+ const PUBLIC_HOOK_EVENTS = new Set(['before_tool', 'after_tool', 'session_start']);
58
+ const PUBLIC_SESSION_START_SOURCES = new Set(['startup', 'resume', 'clear']);
59
+ const PUBLIC_SESSION_START_DEFAULT_MATCHER = 'startup|resume|clear';
60
+ const PUBLIC_HOOK_RENDER_MAP = {
61
+ claude: {
62
+ before_tool: 'PreToolUse',
63
+ after_tool: 'PostToolUse',
64
+ session_start: 'SessionStart',
65
+ },
66
+ codex: {
67
+ before_tool: 'PreToolUse',
68
+ after_tool: 'PostToolUse',
69
+ session_start: 'SessionStart',
70
+ },
71
+ };
72
+ const NATIVE_HOOK_EVENTS = {
73
+ claude: new Set([
74
+ 'PreToolUse',
75
+ 'PostToolUse',
76
+ 'PostToolUseFailure',
77
+ 'Notification',
78
+ 'UserPromptSubmit',
79
+ 'SessionStart',
80
+ 'SessionEnd',
81
+ 'Stop',
82
+ 'StopFailure',
83
+ 'SubagentStart',
84
+ 'SubagentStop',
85
+ 'PreCompact',
86
+ 'PostCompact',
87
+ 'PermissionRequest',
88
+ 'PermissionDenied',
89
+ 'Setup',
90
+ 'TeammateIdle',
91
+ 'TaskCreated',
92
+ 'TaskCompleted',
93
+ 'Elicitation',
94
+ 'ElicitationResult',
95
+ 'ConfigChange',
96
+ 'WorktreeCreate',
97
+ 'WorktreeRemove',
98
+ 'InstructionsLoaded',
99
+ 'CwdChanged',
100
+ 'FileChanged',
101
+ ]),
102
+ codex: new Set([
103
+ 'PreToolUse',
104
+ 'PermissionRequest',
105
+ 'PostToolUse',
106
+ 'SessionStart',
107
+ 'UserPromptSubmit',
108
+ 'Stop',
109
+ ]),
110
+ };
111
+ const MATCHERLESS_NATIVE_HOOK_EVENTS = {
112
+ claude: new Set([
113
+ 'UserPromptSubmit',
114
+ 'Stop',
115
+ 'TeammateIdle',
116
+ 'TaskCreated',
117
+ 'TaskCompleted',
118
+ 'WorktreeCreate',
119
+ 'WorktreeRemove',
120
+ 'CwdChanged',
121
+ ]),
122
+ codex: new Set(['UserPromptSubmit', 'Stop']),
123
+ };
124
+ const TEMPLATE_TEXT_FILE_EXTENSIONS = /\.(md|markdown|txt|json|yaml|yml|toml|rules)$/i;
125
+ const SLASH_COMMAND_NAME_PATTERN = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;
126
+ const DEFAULT_SLASH_COMMANDS_DIR = 'slash-commands';
127
+ const SCRIPT_NODE_EXTENSIONS = new Set(['.js', '.mjs', '.cjs']);
128
+ const SCRIPT_TIMEOUT_MIN_MS = 1000;
129
+ const SCRIPT_TIMEOUT_MAX_MS = 300000;
130
+ const ARTIFACT_TARGETS = new Set(getPluginAuthoringAcceptedValues('artifacts', 'artifacts.targets[].target'));
131
+ const ARTIFACT_STATES = new Set(getPluginAuthoringAcceptedValues('artifacts', 'artifacts.targets[].states'));
132
+ const ARTIFACT_SCOPES = new Set(['user', 'project']);
133
+ const ARTIFACT_KINDS = new Set(['instruction', 'codexRole', 'skill']);
134
+ const ARTIFACT_PROJECT_MANAGED_KINDS = new Set(['instruction', 'agent', 'skill']);
135
+ const ARTIFACT_KIND_BY_TARGET = {
136
+ 'codex.developerInstructionsBlock': 'instruction',
137
+ 'codex.agentRole': 'codexRole',
138
+ 'codex.skill': 'skill',
139
+ 'claude.skill': 'skill',
140
+ 'agent-skills.skill': 'skill',
141
+ };
142
+ const ARTIFACT_PROJECT_MANAGED_KIND_BY_TARGET = {
143
+ 'codex.developerInstructionsBlock': 'instruction',
144
+ 'codex.agentRole': 'agent',
145
+ 'codex.skill': 'skill',
146
+ };
147
+ const PLUGIN_NAME_PATTERN = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;
148
+ let yamlParser = null;
149
+ let pluginVersionCheckResult = null;
150
+ let skillEvalManifestTools = null;
151
+ function error(msg) {
152
+ errors.push(msg);
153
+ }
154
+ function warn(msg) {
155
+ warnings.push(msg);
156
+ }
157
+ function loadYamlParser(sourceName) {
158
+ if (yamlParser)
159
+ return yamlParser;
160
+ try {
161
+ yamlParser = require('yaml');
162
+ return yamlParser;
163
+ }
164
+ catch (e) {
165
+ throw new Error(`${sourceName}: YAML parser dependency "yaml" is not installed; run pnpm install in the agent-workflows repo`);
166
+ }
167
+ }
168
+ function stripStandaloneTemplateControlLines(content) {
169
+ return content
170
+ .replace(/\r\n/g, '\n')
171
+ .split('\n')
172
+ .map((line) => {
173
+ const trimmed = line.trim();
174
+ if (/^{{[#/^]/.test(trimmed) || /^{{else\b/.test(trimmed)) {
175
+ return '';
176
+ }
177
+ return line;
178
+ })
179
+ .join('\n');
180
+ }
181
+ function stripDotSlash(value) {
182
+ return value.startsWith('./') ? value.slice(2) : value;
183
+ }
184
+ function escapeRegexSegment(value) {
185
+ return value.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
186
+ }
187
+ function compileGlob(pattern) {
188
+ const normalized = pattern.split(path.sep).join('/');
189
+ let source = '^';
190
+ for (let index = 0; index < normalized.length; index += 1) {
191
+ const char = normalized[index];
192
+ const next = normalized[index + 1];
193
+ if (char === '*' && next === '*') {
194
+ source += '.*';
195
+ index += 1;
196
+ continue;
197
+ }
198
+ if (char === '*') {
199
+ source += '[^/]*';
200
+ continue;
201
+ }
202
+ if (char === '?') {
203
+ source += '.';
204
+ continue;
205
+ }
206
+ source += escapeRegexSegment(char);
207
+ }
208
+ source += '$';
209
+ return new RegExp(source);
210
+ }
211
+ function normalizeRelativePath(filePath) {
212
+ return path.posix.normalize(stripDotSlash(filePath).split(path.sep).join('/'));
213
+ }
214
+ function matchesGlob(filePath, pattern) {
215
+ return compileGlob(pattern).test(normalizeRelativePath(filePath));
216
+ }
217
+ function isTemplateTextFile(relativePath) {
218
+ return TEMPLATE_TEXT_FILE_EXTENSIONS.test(relativePath);
219
+ }
220
+ function templateIncludesPath(manifest, relativePath) {
221
+ const normalized = normalizeRelativePath(relativePath);
222
+ const include = manifest.buildConfig?.templates?.include;
223
+ if (!Array.isArray(include) || !isTemplateTextFile(normalized))
224
+ return false;
225
+ return include.some((pattern) => matchesGlob(normalized, pattern));
226
+ }
227
+ function resolveTemplateValue(vars, platform) {
228
+ const resolved = {};
229
+ for (const [key, entry] of Object.entries(vars)) {
230
+ if (entry && typeof entry === 'object' && !Array.isArray(entry)) {
231
+ resolved[key] = entry[platform];
232
+ }
233
+ }
234
+ return resolved;
235
+ }
236
+ function replaceConditionalBlocks(input, resolvedVars, tagName) {
237
+ const pattern = new RegExp(`{{#${tagName}\\s+([a-zA-Z0-9_]+)}}([\\s\\S]*?){{\\/${tagName}}}`, 'g');
238
+ return input.replace(pattern, (_match, rawKey, blockContent) => {
239
+ const truthy = resolvedVars[rawKey] === true;
240
+ if (tagName === 'if') {
241
+ return truthy ? blockContent : '';
242
+ }
243
+ return truthy ? '' : blockContent;
244
+ });
245
+ }
246
+ function renderTemplate(content, vars, platform) {
247
+ const resolvedVars = resolveTemplateValue(vars, platform);
248
+ const withConditionals = replaceConditionalBlocks(replaceConditionalBlocks(content, resolvedVars, 'if'), resolvedVars, 'unless');
249
+ return withConditionals.replace(/{{([a-zA-Z0-9_]+)}}/g, (_match, rawKey) => {
250
+ const value = resolvedVars[rawKey];
251
+ if (value === undefined)
252
+ return '';
253
+ return String(value);
254
+ });
255
+ }
256
+ function renderTemplateForPlatform(manifest, relativePath, content, platform) {
257
+ if (!templateIncludesPath(manifest, relativePath))
258
+ return content;
259
+ const vars = manifest.buildConfig?.templates?.vars ?? {};
260
+ return renderTemplate(content, vars, platform);
261
+ }
262
+ function renderedContentVariants(manifest, relativePath, content, platforms) {
263
+ if (!templateIncludesPath(manifest, relativePath)) {
264
+ return [{ content, platform: null }];
265
+ }
266
+ const seen = new Set();
267
+ const variants = [];
268
+ for (const platform of platforms) {
269
+ const rendered = renderTemplateForPlatform(manifest, relativePath, content, platform);
270
+ if (seen.has(rendered))
271
+ continue;
272
+ seen.add(rendered);
273
+ variants.push({ content: rendered, platform });
274
+ }
275
+ return variants;
276
+ }
277
+ function formatYamlError(parseError, lineCounter, sourceName) {
278
+ let location = '';
279
+ if (Array.isArray(parseError.pos) && Number.isInteger(parseError.pos[0])) {
280
+ const linePos = lineCounter.linePos(parseError.pos[0]);
281
+ location = `:${linePos.line}:${linePos.col}`;
282
+ }
283
+ let message = parseError.message || String(parseError);
284
+ if (parseError.code === 'BLOCK_AS_IMPLICIT_KEY') {
285
+ message = `${message}; plain scalar values containing ": " must be quoted`;
286
+ }
287
+ return `${sourceName}${location}: ${message}`;
288
+ }
289
+ function parseYaml(content, sourceName) {
290
+ const yaml = loadYamlParser(sourceName);
291
+ const lineCounter = new yaml.LineCounter();
292
+ const document = yaml.parseDocument(stripStandaloneTemplateControlLines(content), {
293
+ lineCounter,
294
+ prettyErrors: false,
295
+ });
296
+ if (document.errors.length > 0) {
297
+ throw new Error(formatYamlError(document.errors[0], lineCounter, sourceName));
298
+ }
299
+ const value = document.toJSON();
300
+ return value ?? {};
301
+ }
302
+ function parseFrontmatter(content, sourceName) {
303
+ const match = content.match(/^---\r?\n([\s\S]*?)\r?\n---/);
304
+ if (!match)
305
+ return null;
306
+ return parseYaml(match[1], sourceName);
307
+ }
308
+ function getPluginAuthoringAcceptedValues(surface, field) {
309
+ return getCorePluginAuthoringAcceptedValues(surface, field);
310
+ }
311
+ function loadSkillFrontmatterCapabilityRegistry() {
312
+ return getSkillFrontmatterCapabilityRegistry();
313
+ }
314
+ async function tryLoadCliManifestTools() {
315
+ const manifestModulePath = path.join(CLI_PACKAGE_ROOT, 'dist', 'src', 'utils', 'manifest.js');
316
+ const runtimeProjectionModulePath = path.join(CLI_PACKAGE_ROOT, 'dist', 'src', 'utils', 'catalog-runtime-projection.js');
317
+ const capabilityModulePath = path.join(CLI_PACKAGE_ROOT, 'dist', 'src', 'commands', 'aw-capabilities.js');
318
+ if (!fs.existsSync(manifestModulePath)
319
+ || !fs.existsSync(runtimeProjectionModulePath)
320
+ || !fs.existsSync(capabilityModulePath))
321
+ return null;
322
+ try {
323
+ const [manifestModule, runtimeProjectionModule, capabilityModule] = await Promise.all([
324
+ import(pathToFileURL(manifestModulePath).href),
325
+ import(pathToFileURL(runtimeProjectionModulePath).href),
326
+ import(pathToFileURL(capabilityModulePath).href),
327
+ ]);
328
+ if (manifestModule.SOURCE_PLUGIN_MANIFEST_CONTRACT_VERSION
329
+ !== SOURCE_PLUGIN_MANIFEST_CONTRACT_VERSION) {
330
+ return null;
331
+ }
332
+ return {
333
+ assertPluginInputTree: manifestModule.assertPluginInputTree ?? null,
334
+ validateSourcePluginManifest: manifestModule.validateSourcePluginManifest ?? null,
335
+ readPluginManifest: manifestModule.readPluginManifest ?? null,
336
+ discoverPlugins: manifestModule.discoverPlugins ?? null,
337
+ resolvePluginRequirements: manifestModule.resolvePluginRequirements ?? null,
338
+ implementedCapabilities: capabilityModule.IMPLEMENTED_AW_CAPABILITIES ?? null,
339
+ createRuntimeResolver: runtimeProjectionModule.createCatalogRuntimeImportResolver ?? null,
340
+ };
341
+ }
342
+ catch {
343
+ return null;
344
+ }
345
+ }
346
+ async function tryLoadCliSkillValidationTools() {
347
+ const modulePath = path.join(CLI_PACKAGE_ROOT, 'dist', 'src', 'utils', 'skill-validation.js');
348
+ if (!fs.existsSync(modulePath))
349
+ return null;
350
+ try {
351
+ const mod = await import(pathToFileURL(modulePath).href);
352
+ if (typeof mod.parseSkillFrontmatter !== 'function'
353
+ || typeof mod.validateSkillFrontmatter !== 'function'
354
+ || typeof mod.validateCodexMetadata !== 'function') {
355
+ return null;
356
+ }
357
+ return {
358
+ parseSkillFrontmatter: mod.parseSkillFrontmatter,
359
+ validateSkillFrontmatter: mod.validateSkillFrontmatter,
360
+ validateCodexMetadata: mod.validateCodexMetadata,
361
+ };
362
+ }
363
+ catch {
364
+ return null;
365
+ }
366
+ }
367
+ function findRepoRootCandidate(pluginDir) {
368
+ let currentPath = path.dirname(pluginDir);
369
+ while (true) {
370
+ if (fs.lstatSync(path.join(currentPath, '.git'), { throwIfNoEntry: false })) {
371
+ return currentPath;
372
+ }
373
+ const parentPath = path.dirname(currentPath);
374
+ if (parentPath === currentPath)
375
+ return null;
376
+ currentPath = parentPath;
377
+ }
378
+ }
379
+ function discoverCanonicalRepoRoot(repoRootCandidate) {
380
+ if (!repoRootCandidate)
381
+ return null;
382
+ const result = spawnSync('git', ['rev-parse', '--show-toplevel'], {
383
+ cwd: repoRootCandidate,
384
+ encoding: 'utf8',
385
+ });
386
+ if (result.status !== 0 || !result.stdout.trim())
387
+ return null;
388
+ const repoRoot = path.resolve(result.stdout.trim());
389
+ return fs.realpathSync(repoRoot) === fs.realpathSync(repoRootCandidate)
390
+ ? repoRoot
391
+ : null;
392
+ }
393
+ function resolveCanonicalRepoRoot(pluginDir, pluginName, repoRoot) {
394
+ if (!repoRoot)
395
+ return null;
396
+ return fs.realpathSync(pluginDir) === path.join(fs.realpathSync(repoRoot), 'plugins', pluginName)
397
+ ? repoRoot
398
+ : null;
399
+ }
400
+ // ---------------------------------------------------------------------------
401
+ // Lightweight manifest checks (fallback when CLI not built)
402
+ // ---------------------------------------------------------------------------
403
+ const STRICT_SEMVER_PATTERN = /^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-((?:0|[1-9]\d*|(?:[0-9A-Za-z-]*[A-Za-z-][0-9A-Za-z-]*))(?:\.(?:0|[1-9]\d*|(?:[0-9A-Za-z-]*[A-Za-z-][0-9A-Za-z-]*)))*))?(?:\+([0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*))?$/;
404
+ function parseStrictSemVer(value) {
405
+ const stringValue = String(value);
406
+ const match = stringValue.match(STRICT_SEMVER_PATTERN);
407
+ if (!match)
408
+ return null;
409
+ return {
410
+ raw: stringValue,
411
+ major: Number(match[1]),
412
+ minor: Number(match[2]),
413
+ patch: Number(match[3]),
414
+ prerelease: match[4] ? match[4].split('.') : [],
415
+ build: match[5] ? match[5].split('.') : [],
416
+ };
417
+ }
418
+ function comparePrereleaseIdentifier(left, right) {
419
+ const leftNumeric = /^\d+$/.test(left);
420
+ const rightNumeric = /^\d+$/.test(right);
421
+ if (leftNumeric && rightNumeric) {
422
+ return Number(left) - Number(right);
423
+ }
424
+ if (leftNumeric)
425
+ return -1;
426
+ if (rightNumeric)
427
+ return 1;
428
+ if (left < right)
429
+ return -1;
430
+ if (left > right)
431
+ return 1;
432
+ return 0;
433
+ }
434
+ function compareStrictSemVer(left, right) {
435
+ const leftVersion = parseStrictSemVer(left);
436
+ const rightVersion = parseStrictSemVer(right);
437
+ if (!leftVersion || !rightVersion) {
438
+ throw new Error('compareStrictSemVer requires strict SemVer inputs.');
439
+ }
440
+ for (const key of ['major', 'minor', 'patch']) {
441
+ if (leftVersion[key] !== rightVersion[key]) {
442
+ return leftVersion[key] - rightVersion[key];
443
+ }
444
+ }
445
+ const leftPrerelease = leftVersion.prerelease;
446
+ const rightPrerelease = rightVersion.prerelease;
447
+ if (leftPrerelease.length === 0 && rightPrerelease.length === 0) {
448
+ return 0;
449
+ }
450
+ if (leftPrerelease.length === 0) {
451
+ return 1;
452
+ }
453
+ if (rightPrerelease.length === 0) {
454
+ return -1;
455
+ }
456
+ const maxLength = Math.max(leftPrerelease.length, rightPrerelease.length);
457
+ for (let index = 0; index < maxLength; index += 1) {
458
+ const leftIdentifier = leftPrerelease[index];
459
+ const rightIdentifier = rightPrerelease[index];
460
+ if (leftIdentifier === undefined)
461
+ return -1;
462
+ if (rightIdentifier === undefined)
463
+ return 1;
464
+ const result = comparePrereleaseIdentifier(leftIdentifier, rightIdentifier);
465
+ if (result !== 0) {
466
+ return result;
467
+ }
468
+ }
469
+ return 0;
470
+ }
471
+ function validateStrictSemVerString(value, fieldName) {
472
+ if (value === undefined) {
473
+ error(`Invalid ${fieldName}: expected a strict SemVer 2.0.0 string. Received undefined.`);
474
+ return null;
475
+ }
476
+ if (typeof value !== 'string' || !STRICT_SEMVER_PATTERN.test(value)) {
477
+ error(`Invalid ${fieldName}: expected a strict SemVer 2.0.0 string. Received ${JSON.stringify(value)}.`);
478
+ return null;
479
+ }
480
+ return value;
481
+ }
482
+ function validateManifestLightweight(manifest) {
483
+ const input = expectRecord(manifest, 'plugin manifest');
484
+ if (!input)
485
+ return;
486
+ if (Object.prototype.hasOwnProperty.call(input, 'commands')) {
487
+ error('top-level "commands" has been removed; use "slashCommands" instead');
488
+ }
489
+ validateAllowedKeys(input, 'plugin manifest', [
490
+ 'schemaVersion',
491
+ 'name',
492
+ 'version',
493
+ 'description',
494
+ 'dependencies',
495
+ 'requires',
496
+ 'skills',
497
+ 'slashCommands',
498
+ 'mcpServers',
499
+ 'apps',
500
+ 'distributions',
501
+ 'marketplace',
502
+ 'interface',
503
+ 'extensions',
504
+ 'buildConfig',
505
+ 'scripts',
506
+ 'config',
507
+ 'artifacts',
508
+ ]);
509
+ if (manifest.dependencies !== undefined) {
510
+ if (!Array.isArray(manifest.dependencies)) {
511
+ error('dependencies must be an array');
512
+ }
513
+ else if (manifest.dependencies.length > 64) {
514
+ error('dependencies must contain at most 64 direct plugin dependencies');
515
+ }
516
+ else {
517
+ const seen = new Set();
518
+ for (const [index, dependency] of manifest.dependencies.entries()) {
519
+ if (typeof dependency !== 'string' || !PLUGIN_NAME_PATTERN.test(dependency)) {
520
+ error(`dependencies[${index}] must be an ASCII lowercase hyphen-case plugin name`);
521
+ continue;
522
+ }
523
+ if (dependency === manifest.name) {
524
+ error(`plugin "${manifest.name}" cannot depend on itself`);
525
+ }
526
+ if (seen.has(dependency)) {
527
+ error(`dependencies contains duplicate plugin "${dependency}"`);
528
+ }
529
+ seen.add(dependency);
530
+ }
531
+ }
532
+ }
533
+ for (const field of ['name', 'version', 'description', 'marketplace']) {
534
+ if (!manifest[field]) {
535
+ error(`Missing required field: ${field}`);
536
+ }
537
+ }
538
+ if (manifest.name && !/^[a-z0-9]+(?:-[a-z0-9]+)*$/.test(manifest.name)) {
539
+ error(`manifest name "${manifest.name}" is not lowercase-hyphen-case`);
540
+ }
541
+ if (manifest.version) {
542
+ const pluginVersion = parseStrictSemVer(manifest.version);
543
+ if (!pluginVersion) {
544
+ error(`manifest.version must be a strict SemVer 2.0.0 string, got "${manifest.version}"`);
545
+ }
546
+ else if (pluginVersion.prerelease.length > 0 || pluginVersion.build.length > 0) {
547
+ error('manifest.version must be a stable SemVer without prerelease or build metadata');
548
+ }
549
+ }
550
+ if (manifest.marketplace) {
551
+ const mp = manifest.marketplace;
552
+ if (!mp.category)
553
+ error('marketplace.category is required');
554
+ if (typeof mp.strict !== 'boolean')
555
+ error('marketplace.strict must be a boolean');
556
+ if (!mp.policy || !mp.policy.installation)
557
+ error('marketplace.policy.installation is required');
558
+ else if (!MARKETPLACE_INSTALLATION_POLICIES.has(mp.policy.installation))
559
+ error(`marketplace.policy.installation must be one of ${[...MARKETPLACE_INSTALLATION_POLICIES].map((value) => JSON.stringify(value)).join(', ')}`);
560
+ if (!mp.policy || !mp.policy.authentication)
561
+ error('marketplace.policy.authentication is required');
562
+ else if (!MARKETPLACE_AUTHENTICATION_POLICIES.has(mp.policy.authentication))
563
+ error('marketplace.policy.authentication must be "ON_INSTALL" or "ON_USE"');
564
+ validateManifestPolicyProducts(mp.policy?.products);
565
+ }
566
+ for (const field of ['skills', 'slashCommands', 'mcpServers', 'apps']) {
567
+ if (manifest[field] && !manifest[field].startsWith('./')) {
568
+ error(`${field} path must start with "./", got "${manifest[field]}"`);
569
+ }
570
+ }
571
+ const claudeCommands = manifest.buildConfig?.manifestOverrides?.claude?.commands;
572
+ if (claudeCommands !== undefined) {
573
+ error('buildConfig.manifestOverrides.claude.commands has been removed; use "slashCommands" instead');
574
+ }
575
+ for (const platform of ['claude', 'codex']) {
576
+ const rules = manifest.buildConfig?.fileRules?.[platform];
577
+ if (!rules)
578
+ continue;
579
+ for (const pattern of [...(rules.include ?? []), ...(rules.exclude ?? [])]) {
580
+ const normalized = String(pattern).replace(/\\/g, '/').replace(/^\.\//, '');
581
+ if (normalized === 'commands' || normalized.startsWith('commands/')) {
582
+ error(`buildConfig.fileRules.${platform} no longer accepts legacy "commands/**" source rules; use "slashCommands" instead`);
583
+ }
584
+ }
585
+ }
586
+ validateExtensionsLightweight(manifest.extensions);
587
+ validatePlatformFieldSupport(manifest);
588
+ }
589
+ function validatePortableNativeArtifactCapabilityLightweight(manifest) {
590
+ if (manifest.distributions?.agentSkills === undefined)
591
+ return;
592
+ const hasOtherNativeDeclaration = Boolean(manifest.skills
593
+ || manifest.slashCommands
594
+ || manifest.mcpServers
595
+ || manifest.apps
596
+ || (manifest.extensions?.instructions?.length ?? 0) > 0
597
+ || (manifest.extensions?.permissions?.length ?? 0) > 0
598
+ || (manifest.extensions?.hooks?.length ?? 0) > 0
599
+ || (manifest.extensions?.nativeHooks?.claude?.length ?? 0) > 0
600
+ || (manifest.extensions?.nativeHooks?.codex?.length ?? 0) > 0
601
+ || (manifest.extensions?.agents?.length ?? 0) > 0);
602
+ const hasPresentNativeArtifact = (manifest.artifacts?.targets ?? []).some((target) => (target?.platform === 'claude' || target?.platform === 'codex')
603
+ && Array.isArray(target.states)
604
+ && target.states.includes('present'));
605
+ if (!hasOtherNativeDeclaration && !hasPresentNativeArtifact) {
606
+ const message = 'Invalid plugin manifest: portable-only plugins are not supported. Declare at least one non-empty native capability.';
607
+ if (!errors.includes(message))
608
+ error(message);
609
+ }
610
+ }
611
+ function normalizeManifestProductToken(value) {
612
+ return String(value).trim().toUpperCase().replace(/[\s-]+/g, '_');
613
+ }
614
+ function resolveSupportedPlatforms(manifest) {
615
+ const products = manifest.marketplace?.policy?.products;
616
+ if (!Array.isArray(products) || products.length === 0) {
617
+ return new Set(['claude', 'codex']);
618
+ }
619
+ const supported = new Set();
620
+ for (const product of products) {
621
+ const normalized = normalizeManifestProductToken(product);
622
+ if (normalized === 'CLAUDE')
623
+ supported.add('claude');
624
+ if (normalized === 'CODEX')
625
+ supported.add('codex');
626
+ }
627
+ return supported;
628
+ }
629
+ function supportsManifestPlatform(manifest, platform) {
630
+ return resolveSupportedPlatforms(manifest).has(platform);
631
+ }
632
+ function formatManifestProductsForError(manifest) {
633
+ const products = manifest.marketplace?.policy?.products;
634
+ if (!Array.isArray(products) || products.length === 0) {
635
+ return 'marketplace.policy.products=[]';
636
+ }
637
+ const normalized = [...new Set(products.map(normalizeManifestProductToken))];
638
+ return `marketplace.policy.products=[${normalized.join(', ')}]`;
639
+ }
640
+ function platformProductName(platform) {
641
+ return platform === 'claude' ? 'CLAUDE' : 'CODEX';
642
+ }
643
+ function pluginNameForError(manifest) {
644
+ return typeof manifest.name === 'string' && manifest.name.trim()
645
+ ? manifest.name.trim()
646
+ : '<unknown>';
647
+ }
648
+ function assertPlatformFieldSupported(manifest, fieldPath, requiredPlatform) {
649
+ if (supportsManifestPlatform(manifest, requiredPlatform))
650
+ return;
651
+ error(`Invalid plugin "${pluginNameForError(manifest)}": ${fieldPath} requires ${platformProductName(requiredPlatform)} support, but ${formatManifestProductsForError(manifest)}.`);
652
+ }
653
+ function hasNonEmptyOverride(value) {
654
+ return isRecord(value) && Object.keys(value).length > 0;
655
+ }
656
+ function validateManifestPolicyProducts(products) {
657
+ if (products === undefined)
658
+ return;
659
+ if (!Array.isArray(products)) {
660
+ error('marketplace.policy.products must be an array');
661
+ return;
662
+ }
663
+ for (const [index, product] of products.entries()) {
664
+ const fieldName = `marketplace.policy.products[${index}]`;
665
+ if (typeof product !== 'string' || product.trim() === '') {
666
+ error(`${fieldName} must be a non-empty string`);
667
+ continue;
668
+ }
669
+ const normalized = normalizeManifestProductToken(product);
670
+ if (!MANIFEST_POLICY_PRODUCTS.has(normalized)) {
671
+ error(`${fieldName} must be one of "CODEX" or "CLAUDE"`);
672
+ }
673
+ }
674
+ }
675
+ function validatePlatformFieldSupport(manifest) {
676
+ if (manifest.buildConfig?.fileRules?.claude !== undefined) {
677
+ assertPlatformFieldSupported(manifest, 'buildConfig.fileRules.claude', 'claude');
678
+ }
679
+ if (manifest.buildConfig?.fileRules?.codex !== undefined) {
680
+ assertPlatformFieldSupported(manifest, 'buildConfig.fileRules.codex', 'codex');
681
+ }
682
+ if (manifest.buildConfig?.manifestOverrides?.claude !== undefined) {
683
+ assertPlatformFieldSupported(manifest, 'buildConfig.manifestOverrides.claude', 'claude');
684
+ }
685
+ if (manifest.buildConfig?.manifestOverrides?.codex !== undefined) {
686
+ assertPlatformFieldSupported(manifest, 'buildConfig.manifestOverrides.codex', 'codex');
687
+ }
688
+ if (manifest.apps) {
689
+ assertPlatformFieldSupported(manifest, 'apps', 'codex');
690
+ }
691
+ if (Array.isArray(manifest.extensions?.nativeHooks?.claude) && manifest.extensions.nativeHooks.claude.length > 0) {
692
+ assertPlatformFieldSupported(manifest, 'extensions.nativeHooks.claude', 'claude');
693
+ }
694
+ if (Array.isArray(manifest.extensions?.nativeHooks?.codex) && manifest.extensions.nativeHooks.codex.length > 0) {
695
+ assertPlatformFieldSupported(manifest, 'extensions.nativeHooks.codex', 'codex');
696
+ }
697
+ for (const [fieldName, entries] of [
698
+ ['extensions.instructions', manifest.extensions?.instructions],
699
+ ['extensions.permissions', manifest.extensions?.permissions],
700
+ ['extensions.hooks', manifest.extensions?.hooks],
701
+ ['extensions.agents', manifest.extensions?.agents],
702
+ ]) {
703
+ if (!Array.isArray(entries))
704
+ continue;
705
+ entries.forEach((entry, index) => {
706
+ if (!isRecord(entry.agentOverrides))
707
+ return;
708
+ for (const platform of ['claude', 'codex']) {
709
+ if (hasNonEmptyOverride(entry.agentOverrides[platform])) {
710
+ assertPlatformFieldSupported(manifest, `${fieldName}[${index}].agentOverrides.${platform}`, platform);
711
+ }
712
+ }
713
+ });
714
+ }
715
+ if (!Array.isArray(manifest.artifacts?.targets))
716
+ return;
717
+ manifest.artifacts.targets.forEach((target, index) => {
718
+ if (target?.platform === 'claude' || target?.platform === 'codex') {
719
+ assertPlatformFieldSupported(manifest, `artifacts.targets[${index}].platform`, target.platform);
720
+ }
721
+ });
722
+ }
723
+ function isTemplateAsset(manifest, relativePath) {
724
+ return templateIncludesPath(manifest, relativePath);
725
+ }
726
+ function isRecord(value) {
727
+ return value !== null && typeof value === 'object' && !Array.isArray(value);
728
+ }
729
+ function validateAllowedKeys(record, fieldName, allowedKeys) {
730
+ for (const key of Object.keys(record)) {
731
+ if (!allowedKeys.includes(key)) {
732
+ error(`${fieldName} has unknown field "${key}"`);
733
+ }
734
+ }
735
+ }
736
+ function validateManifestString(value, fieldName) {
737
+ if (typeof value !== 'string' || value.trim() === '') {
738
+ error(`${fieldName} must be a non-empty string`);
739
+ return null;
740
+ }
741
+ return value;
742
+ }
743
+ function validatePublicHookEvent(value, fieldName) {
744
+ const event = validateManifestString(value, fieldName);
745
+ if (!event)
746
+ return null;
747
+ if (event === 'session_stop') {
748
+ error(`${fieldName}: public event "session_stop" has been removed; use extensions.nativeHooks.claude[].event = "Stop" or "SessionEnd", or extensions.nativeHooks.codex[].event = "Stop"`);
749
+ return null;
750
+ }
751
+ if (!PUBLIC_HOOK_EVENTS.has(event)) {
752
+ error(`${fieldName}: unsupported public hook event "${event}"`);
753
+ return null;
754
+ }
755
+ return event;
756
+ }
757
+ function normalizePublicSessionStartMatcher(matcher, fieldName) {
758
+ if (matcher === undefined)
759
+ return PUBLIC_SESSION_START_DEFAULT_MATCHER;
760
+ if (typeof matcher !== 'string' || matcher.trim() === '') {
761
+ error(`${fieldName} must be a non-empty string`);
762
+ return null;
763
+ }
764
+ const selected = new Set();
765
+ for (const part of matcher.split('|')) {
766
+ if (!PUBLIC_SESSION_START_SOURCES.has(part)) {
767
+ error(`${fieldName}: public session_start only allows startup, resume, clear, or their "|" union`);
768
+ return null;
769
+ }
770
+ selected.add(part);
771
+ }
772
+ return ['startup', 'resume', 'clear'].filter((part) => selected.has(part)).join('|');
773
+ }
774
+ function validatePublicHookMatcher(event, matcher, fieldName) {
775
+ if (matcher === undefined)
776
+ return event === 'session_start' ? PUBLIC_SESSION_START_DEFAULT_MATCHER : undefined;
777
+ if (typeof matcher !== 'string' || matcher.trim() === '') {
778
+ error(`${fieldName} must be a non-empty string`);
779
+ return null;
780
+ }
781
+ if (event === 'session_start') {
782
+ return normalizePublicSessionStartMatcher(matcher, fieldName);
783
+ }
784
+ return matcher;
785
+ }
786
+ function validateNativeHookEvent(value, platform, fieldName) {
787
+ const event = validateManifestString(value, fieldName);
788
+ if (!event)
789
+ return null;
790
+ if (!NATIVE_HOOK_EVENTS[platform].has(event)) {
791
+ error(`${fieldName}: unsupported ${platform} hook event "${event}"`);
792
+ return null;
793
+ }
794
+ return event;
795
+ }
796
+ function validateNativeHookMatcher(event, platform, matcher, fieldName) {
797
+ if (matcher === undefined)
798
+ return undefined;
799
+ if (typeof matcher !== 'string' || matcher.trim() === '') {
800
+ error(`${fieldName} must be a non-empty string`);
801
+ return null;
802
+ }
803
+ if (MATCHERLESS_NATIVE_HOOK_EVENTS[platform].has(event)) {
804
+ error(`${fieldName}: ${platform} event "${event}" does not allow matcher`);
805
+ return null;
806
+ }
807
+ return matcher;
808
+ }
809
+ function validateHookAgentOverrides(value, baseHook, fieldName, duplicateCollector) {
810
+ if (value === undefined) {
811
+ for (const platform of ['claude', 'codex']) {
812
+ duplicateCollector(platform, baseHook);
813
+ }
814
+ return;
815
+ }
816
+ const overrides = expectRecord(value, fieldName);
817
+ if (!overrides)
818
+ return;
819
+ validateAllowedKeys(overrides, fieldName, ['claude', 'codex']);
820
+ for (const platform of ['claude', 'codex']) {
821
+ const override = overrides[platform];
822
+ if (override === null)
823
+ continue;
824
+ if (override === undefined) {
825
+ duplicateCollector(platform, baseHook);
826
+ continue;
827
+ }
828
+ const overrideRecord = expectRecord(override, `${fieldName}.${platform}`);
829
+ if (!overrideRecord)
830
+ continue;
831
+ validateAllowedKeys(overrideRecord, `${fieldName}.${platform}`, ['event', 'matcher', 'command']);
832
+ const event = overrideRecord.event === undefined
833
+ ? baseHook.event
834
+ : validatePublicHookEvent(overrideRecord.event, `${fieldName}.${platform}.event`);
835
+ const matcherValue = overrideRecord.matcher === undefined
836
+ ? baseHook.matcher
837
+ : overrideRecord.matcher;
838
+ const matcher = event
839
+ ? validatePublicHookMatcher(event, matcherValue, `${fieldName}.${platform}.matcher`)
840
+ : null;
841
+ const command = overrideRecord.command === undefined
842
+ ? baseHook.command
843
+ : validateManifestString(overrideRecord.command, `${fieldName}.${platform}.command`);
844
+ if (event && matcher !== null && command) {
845
+ duplicateCollector(platform, { event, matcher, command });
846
+ }
847
+ }
848
+ }
849
+ function validateHookEntryLightweight(entry, fieldName, duplicateCollector) {
850
+ const input = expectRecord(entry, fieldName);
851
+ if (!input)
852
+ return;
853
+ validateAllowedKeys(input, fieldName, ['event', 'matcher', 'command', 'agentOverrides']);
854
+ const event = validatePublicHookEvent(input.event, `${fieldName}.event`);
855
+ const matcher = event
856
+ ? validatePublicHookMatcher(event, input.matcher, `${fieldName}.matcher`)
857
+ : null;
858
+ const command = validateManifestString(input.command, `${fieldName}.command`);
859
+ if (!event || matcher === null || !command)
860
+ return;
861
+ validateHookAgentOverrides(input.agentOverrides, { event, matcher, command }, `${fieldName}.agentOverrides`, duplicateCollector);
862
+ }
863
+ function validateNativeHookEntryLightweight(entry, platform, fieldName, duplicateCollector) {
864
+ const input = expectRecord(entry, fieldName);
865
+ if (!input)
866
+ return;
867
+ validateAllowedKeys(input, fieldName, ['event', 'matcher', 'command']);
868
+ const event = validateNativeHookEvent(input.event, platform, `${fieldName}.event`);
869
+ const matcher = event
870
+ ? validateNativeHookMatcher(event, platform, input.matcher, `${fieldName}.matcher`)
871
+ : null;
872
+ const command = validateManifestString(input.command, `${fieldName}.command`);
873
+ if (!event || matcher === null || !command)
874
+ return;
875
+ duplicateCollector(platform, { event, matcher, command, native: true });
876
+ }
877
+ function validateExtensionsLightweight(extensions) {
878
+ if (extensions === undefined)
879
+ return;
880
+ const input = expectRecord(extensions, 'extensions');
881
+ if (!input)
882
+ return;
883
+ validateAllowedKeys(input, 'extensions', ['instructions', 'permissions', 'hooks', 'nativeHooks', 'agents']);
884
+ const seenHooks = {
885
+ claude: new Set(),
886
+ codex: new Set(),
887
+ };
888
+ const collectHook = (platform, hook) => {
889
+ const event = hook.native ? hook.event : PUBLIC_HOOK_RENDER_MAP[platform][hook.event];
890
+ const matcher = hook.matcher === '*' ? undefined : hook.matcher;
891
+ const key = JSON.stringify([event, matcher ?? null, hook.command]);
892
+ if (seenHooks[platform].has(key)) {
893
+ error(`extensions has duplicate ${platform} hook for event "${event}" and command "${hook.command}"`);
894
+ }
895
+ seenHooks[platform].add(key);
896
+ };
897
+ if (input.hooks !== undefined) {
898
+ if (!Array.isArray(input.hooks)) {
899
+ error('extensions.hooks must be an array');
900
+ }
901
+ else {
902
+ input.hooks.forEach((entry, index) => validateHookEntryLightweight(entry, `extensions.hooks[${index}]`, collectHook));
903
+ }
904
+ }
905
+ if (input.nativeHooks !== undefined) {
906
+ const nativeHooks = expectRecord(input.nativeHooks, 'extensions.nativeHooks');
907
+ if (nativeHooks) {
908
+ validateAllowedKeys(nativeHooks, 'extensions.nativeHooks', ['claude', 'codex']);
909
+ for (const platform of ['claude', 'codex']) {
910
+ if (nativeHooks[platform] === undefined)
911
+ continue;
912
+ if (!Array.isArray(nativeHooks[platform])) {
913
+ error(`extensions.nativeHooks.${platform} must be an array`);
914
+ continue;
915
+ }
916
+ nativeHooks[platform].forEach((entry, index) => validateNativeHookEntryLightweight(entry, platform, `extensions.nativeHooks.${platform}[${index}]`, collectHook));
917
+ }
918
+ }
919
+ }
920
+ }
921
+ function expectRecord(value, fieldName) {
922
+ if (!isRecord(value)) {
923
+ error(`${fieldName} must be an object`);
924
+ return null;
925
+ }
926
+ return value;
927
+ }
928
+ function validateNonEmptyString(value, fieldName, maxLength) {
929
+ if (typeof value !== 'string') {
930
+ error(`${fieldName} must be a string`);
931
+ return null;
932
+ }
933
+ const trimmed = value.trim();
934
+ if (trimmed.length === 0) {
935
+ error(`${fieldName} must not be empty`);
936
+ return null;
937
+ }
938
+ if (maxLength !== undefined && countCharacters(trimmed) > maxLength) {
939
+ error(`${fieldName} must be <= ${maxLength} characters`);
940
+ }
941
+ return trimmed;
942
+ }
943
+ async function loadSkillEvalManifestTools() {
944
+ if (skillEvalManifestTools)
945
+ return skillEvalManifestTools;
946
+ const modulePath = path.join(CLI_PACKAGE_ROOT, 'dist', 'src', 'eval', 'manifest-v1.js');
947
+ try {
948
+ skillEvalManifestTools = await import(pathToFileURL(modulePath).href);
949
+ return skillEvalManifestTools;
950
+ }
951
+ catch {
952
+ return null;
953
+ }
954
+ }
955
+ async function validatePluginEvalManifest(pluginDir, pluginManifest) {
956
+ const legacyRoot = path.join(pluginDir, 'evals');
957
+ if (fs.existsSync(legacyRoot)) {
958
+ error('Plugin-root evals/ is legacy; put evals/ inside its owning static or dynamic Skill directory.');
959
+ }
960
+ const skillRoots = [...collectDeclaredSkillNames(pluginDir, pluginManifest).all]
961
+ .sort()
962
+ .map((skill) => ({ skill, root: path.join(pluginDir, 'skills', skill) }));
963
+ const seenSkills = new Set();
964
+ let manifestTools = null;
965
+ for (const owner of skillRoots) {
966
+ const evalDir = path.join(owner.root, 'evals');
967
+ const manifestPath = path.join(evalDir, 'manifest.json');
968
+ if (!fs.existsSync(manifestPath))
969
+ continue;
970
+ const manifestField = path.relative(pluginDir, manifestPath).split(path.sep).join('/');
971
+ if (seenSkills.has(owner.skill)) {
972
+ error(`Skill ${JSON.stringify(owner.skill)} has more than one evals/manifest.json owner`);
973
+ continue;
974
+ }
975
+ seenSkills.add(owner.skill);
976
+ manifestTools ??= await loadSkillEvalManifestTools();
977
+ if (typeof manifestTools?.validateAwSkillEvalManifest !== 'function') {
978
+ error('Canonical AwSkillEvalManifest v1 validator is unavailable; run the current built aw CLI.');
979
+ continue;
980
+ }
981
+ const validation = await manifestTools.validateAwSkillEvalManifest({
982
+ plugin: {
983
+ rootDir: pluginDir,
984
+ manifestPath: path.join(pluginDir, '.agents-plugin', 'plugin.json'),
985
+ manifest: pluginManifest,
986
+ },
987
+ skill: owner.skill,
988
+ });
989
+ for (const message of validation.errors)
990
+ error(`${manifestField}: ${message}`);
991
+ }
992
+ }
993
+ function countCharacters(value) {
994
+ return Array.from(value).length;
995
+ }
996
+ function countLines(value) {
997
+ if (value.length === 0)
998
+ return 0;
999
+ const normalized = value.replace(/\r\n?/g, '\n');
1000
+ const withoutFinalNewline = normalized.endsWith('\n')
1001
+ ? normalized.slice(0, -1)
1002
+ : normalized;
1003
+ return withoutFinalNewline.split('\n').length;
1004
+ }
1005
+ function sanitizeSingleLine(value) {
1006
+ return value.trim().split(/\s+/).filter(Boolean).join(' ');
1007
+ }
1008
+ function validateCodexMetadataString(record, key, fieldName, maxLength, required = false) {
1009
+ if (record[key] === undefined) {
1010
+ if (required) {
1011
+ error(`${fieldName}.${key} is required`);
1012
+ }
1013
+ return null;
1014
+ }
1015
+ if (typeof record[key] !== 'string') {
1016
+ error(`${fieldName}.${key} must be a string`);
1017
+ return null;
1018
+ }
1019
+ const sanitized = sanitizeSingleLine(record[key]);
1020
+ if (sanitized.length === 0) {
1021
+ error(`${fieldName}.${key} must not be empty`);
1022
+ return null;
1023
+ }
1024
+ if (countCharacters(sanitized) > maxLength) {
1025
+ error(`${fieldName}.${key} must be <= ${maxLength} characters`);
1026
+ }
1027
+ return sanitized;
1028
+ }
1029
+ function validateCodexShortDescription(record, fieldName) {
1030
+ const sanitized = validateCodexMetadataString(record, 'short_description', fieldName, MAX_OPENAI_INTERFACE_DESCRIPTION_LEN);
1031
+ if (sanitized !== null &&
1032
+ countCharacters(sanitized) < MIN_OPENAI_INTERFACE_DESCRIPTION_LEN) {
1033
+ error(`${fieldName}.short_description must be >= ${MIN_OPENAI_INTERFACE_DESCRIPTION_LEN} characters`);
1034
+ }
1035
+ return sanitized;
1036
+ }
1037
+ function validateCodexDefaultPrompt(record, key, fieldName, maxLength, skillReference, required = false) {
1038
+ const sanitized = validateCodexMetadataString(record, key, fieldName, maxLength, required);
1039
+ if (sanitized === null)
1040
+ return null;
1041
+ const mention = `$${skillReference}`;
1042
+ if (!sanitized.includes(mention)) {
1043
+ error(`${fieldName}.${key} must explicitly mention "${mention}"`);
1044
+ }
1045
+ return sanitized;
1046
+ }
1047
+ function validateCodexBrandColor(record, key, fieldName) {
1048
+ if (record[key] === undefined)
1049
+ return;
1050
+ if (typeof record[key] !== 'string') {
1051
+ error(`${fieldName}.${key} must be a string`);
1052
+ return;
1053
+ }
1054
+ const value = record[key].trim();
1055
+ if (value.length === 0) {
1056
+ error(`${fieldName}.${key} must not be empty`);
1057
+ return;
1058
+ }
1059
+ if (!/^#[0-9a-fA-F]{6}$/.test(value)) {
1060
+ error(`${fieldName}.${key} must match #RRGGBB`);
1061
+ }
1062
+ }
1063
+ function validateCodexIconPath(record, key, fieldName) {
1064
+ if (record[key] === undefined)
1065
+ return;
1066
+ if (typeof record[key] !== 'string') {
1067
+ error(`${fieldName}.${key} must be a string`);
1068
+ return;
1069
+ }
1070
+ const value = record[key].trim();
1071
+ if (value.length === 0) {
1072
+ error(`${fieldName}.${key} must not be empty`);
1073
+ return;
1074
+ }
1075
+ if (path.isAbsolute(value) || path.win32.isAbsolute(value)) {
1076
+ error(`${fieldName}.${key} must be a relative path under assets/`);
1077
+ return;
1078
+ }
1079
+ const components = value.split('/');
1080
+ if (components.some((component) => component === '..')) {
1081
+ error(`${fieldName}.${key} must be a relative path under assets/`);
1082
+ return;
1083
+ }
1084
+ const normalized = path.posix.normalize(stripDotSlash(value));
1085
+ if (normalized !== 'assets' && !normalized.startsWith('assets/')) {
1086
+ error(`${fieldName}.${key} must be a relative path under assets/`);
1087
+ }
1088
+ }
1089
+ function validateAllowedTools(value, fieldName, options) {
1090
+ if (typeof value === 'string') {
1091
+ if (value.trim().length === 0) {
1092
+ error(`${fieldName} must not be an empty string`);
1093
+ }
1094
+ return;
1095
+ }
1096
+ if (!options.allowArray) {
1097
+ error(`${fieldName} must be a space-separated string in the Agent Skills portable core profile`);
1098
+ return;
1099
+ }
1100
+ if (!Array.isArray(value)) {
1101
+ error(`${fieldName} must be a string or an array of strings`);
1102
+ return;
1103
+ }
1104
+ for (const [index, item] of value.entries()) {
1105
+ if (typeof item !== 'string') {
1106
+ error(`${fieldName}[${index}] must be a string`);
1107
+ }
1108
+ else if (item.trim().length === 0) {
1109
+ error(`${fieldName}[${index}] must not be empty`);
1110
+ }
1111
+ }
1112
+ }
1113
+ function isNonEmptyFrontmatterString(value) {
1114
+ return typeof value === 'string' && value.trim().length > 0;
1115
+ }
1116
+ function isFrontmatterStringArray(value) {
1117
+ return Array.isArray(value) && value.every(isNonEmptyFrontmatterString);
1118
+ }
1119
+ function frontmatterValueMatchesType(value, type) {
1120
+ switch (type) {
1121
+ case 'boolean':
1122
+ return typeof value === 'boolean';
1123
+ case 'boolean-or-string':
1124
+ return typeof value === 'boolean' || isNonEmptyFrontmatterString(value);
1125
+ case 'boolean-or-string-or-binary-number':
1126
+ return typeof value === 'boolean'
1127
+ || isNonEmptyFrontmatterString(value)
1128
+ || value === 0
1129
+ || value === 1;
1130
+ case 'object':
1131
+ return value !== null && typeof value === 'object' && !Array.isArray(value);
1132
+ case 'string':
1133
+ return isNonEmptyFrontmatterString(value);
1134
+ case 'string-map':
1135
+ return value !== null && typeof value === 'object' && !Array.isArray(value)
1136
+ && Object.values(value).every((entry) => typeof entry === 'string');
1137
+ case 'string-or-integer':
1138
+ return isNonEmptyFrontmatterString(value)
1139
+ || (typeof value === 'number' && Number.isInteger(value));
1140
+ case 'string-or-string-array':
1141
+ return isNonEmptyFrontmatterString(value) || isFrontmatterStringArray(value);
1142
+ default:
1143
+ return false;
1144
+ }
1145
+ }
1146
+ function skillFrontmatterProfile(options) {
1147
+ if (options.strictAgentSkills || !options.targetsClaude) {
1148
+ return 'portable-agent-skills';
1149
+ }
1150
+ return options.claudeSkillProfile === 'current'
1151
+ ? 'claude-current'
1152
+ : 'claude-2.1.88';
1153
+ }
1154
+ function validateSkillFrontmatterCapabilityFields(fm, fieldName, profile) {
1155
+ let registry;
1156
+ try {
1157
+ registry = loadSkillFrontmatterCapabilityRegistry();
1158
+ }
1159
+ catch (registryError) {
1160
+ error(`${fieldName} capability registry error: ${registryError.message}`);
1161
+ return;
1162
+ }
1163
+ for (const [key, value] of Object.entries(fm)) {
1164
+ const capability = registry.fields[key];
1165
+ if (!capability) {
1166
+ error(`${fieldName} [unknown-field] field ${JSON.stringify(key)} is not registered for any supported profile`);
1167
+ continue;
1168
+ }
1169
+ if (!capability.profiles.includes(profile)) {
1170
+ if (profile === 'portable-agent-skills' && capability.owner !== 'agent-skills') {
1171
+ error(`${fieldName} [portable-profile-platform-extension] field ${JSON.stringify(key)} is a Claude Code extension`);
1172
+ }
1173
+ else {
1174
+ const version = capability.introducedVersion
1175
+ ? `; documented minimum is Claude Code ${capability.introducedVersion}`
1176
+ : '';
1177
+ error(`${fieldName} [known-field-not-supported-by-target-version] field ${JSON.stringify(key)} is not supported by profile ${JSON.stringify(profile)}${version}`);
1178
+ }
1179
+ continue;
1180
+ }
1181
+ const expectedType = capability.typeByProfile?.[profile] ?? capability.type;
1182
+ if (!frontmatterValueMatchesType(value, expectedType)) {
1183
+ error(`${fieldName} [known-field-invalid-type-value] field ${JSON.stringify(key)} must have type ${JSON.stringify(expectedType)} in profile ${JSON.stringify(profile)}`);
1184
+ continue;
1185
+ }
1186
+ const acceptedValues = capability.acceptedValuesByProfile?.[profile]
1187
+ ?? capability.acceptedValues;
1188
+ const acceptedValuesCaseInsensitive = capability.acceptedValuesCaseInsensitiveByProfile?.[profile]
1189
+ ?? capability.acceptedValuesCaseInsensitive
1190
+ ?? false;
1191
+ if (typeof value === 'string' &&
1192
+ acceptedValues &&
1193
+ !acceptedValues.includes(acceptedValuesCaseInsensitive ? value.trim().toLowerCase() : value.trim())) {
1194
+ error(`${fieldName} [known-field-invalid-type-value] field ${JSON.stringify(key)} must be one of ${acceptedValues.map((entry) => JSON.stringify(entry)).join(', ')}`);
1195
+ }
1196
+ for (const [requiredKey, requiredValue] of Object.entries(capability.requires ?? {})) {
1197
+ if (fm[requiredKey] !== requiredValue) {
1198
+ error(`${fieldName} [known-field-requires-related-field] field ${JSON.stringify(key)} requires ${JSON.stringify(requiredKey)}=${JSON.stringify(requiredValue)}`);
1199
+ }
1200
+ }
1201
+ }
1202
+ for (const [key, capability] of Object.entries(registry.fields)) {
1203
+ if (capability.required && capability.profiles.includes(profile) && fm[key] === undefined) {
1204
+ error(`${fieldName} [known-field-invalid-type-value] required field ${JSON.stringify(key)} is missing for profile ${JSON.stringify(profile)}`);
1205
+ }
1206
+ }
1207
+ }
1208
+ function validateSkillFrontmatter(fm, skillName, options) {
1209
+ const fieldName = `skills/${skillName}/SKILL.md frontmatter`;
1210
+ const profile = skillFrontmatterProfile(options);
1211
+ validateSkillFrontmatterCapabilityFields(fm, fieldName, profile);
1212
+ if (fm.name === undefined) {
1213
+ error(`${fieldName} missing "name"`);
1214
+ }
1215
+ else {
1216
+ const name = validateNonEmptyString(fm.name, `${fieldName}.name`, MAX_SKILL_NAME_LEN);
1217
+ if (name) {
1218
+ if (!/^[a-z0-9]+(?:-[a-z0-9]+)*$/.test(name)) {
1219
+ error(`${fieldName}.name must use ASCII lowercase hyphen-case`);
1220
+ }
1221
+ if (name !== skillName) {
1222
+ error(`${fieldName}.name "${name}" must match skill directory "${skillName}"`);
1223
+ }
1224
+ }
1225
+ }
1226
+ if (fm.description === undefined) {
1227
+ error(`${fieldName} missing "description"`);
1228
+ }
1229
+ else {
1230
+ validateNonEmptyString(fm.description, `${fieldName}.description`, MAX_SKILL_DESCRIPTION_LEN);
1231
+ }
1232
+ if (fm.license !== undefined) {
1233
+ validateNonEmptyString(fm.license, `${fieldName}.license`);
1234
+ }
1235
+ if (fm.compatibility !== undefined) {
1236
+ validateNonEmptyString(fm.compatibility, `${fieldName}.compatibility`, MAX_SKILL_COMPATIBILITY_LEN);
1237
+ }
1238
+ if (fm.metadata !== undefined) {
1239
+ const metadata = expectRecord(fm.metadata, `${fieldName}.metadata`);
1240
+ if (metadata) {
1241
+ if (profile !== 'claude-current') {
1242
+ for (const [key, value] of Object.entries(metadata)) {
1243
+ if (typeof value !== 'string') {
1244
+ error(`${fieldName}.metadata.${key} must be a string`);
1245
+ }
1246
+ }
1247
+ }
1248
+ if (metadata['short-description'] !== undefined) {
1249
+ validateNonEmptyString(metadata['short-description'], `${fieldName}.metadata.short-description`, MAX_SKILL_SHORT_DESCRIPTION_LEN);
1250
+ }
1251
+ }
1252
+ }
1253
+ }
1254
+ function isCodexTargeted(manifest) {
1255
+ return supportsManifestPlatform(manifest, 'codex');
1256
+ }
1257
+ function isClaudeTargeted(manifest) {
1258
+ return supportsManifestPlatform(manifest, 'claude');
1259
+ }
1260
+ function targetedPlatforms(manifest) {
1261
+ const platforms = [];
1262
+ if (isClaudeTargeted(manifest))
1263
+ platforms.push('claude');
1264
+ if (isCodexTargeted(manifest))
1265
+ platforms.push('codex');
1266
+ return platforms.length > 0 ? platforms : ['claude', 'codex'];
1267
+ }
1268
+ // ---------------------------------------------------------------------------
1269
+ // Supplemental checks (always run — not covered by CLI validator)
1270
+ // ---------------------------------------------------------------------------
1271
+ function validateNameMatchesDirectory(pluginDir, manifest) {
1272
+ const pluginName = path.basename(pluginDir);
1273
+ if (manifest.name && manifest.name !== pluginName) {
1274
+ error(`manifest name "${manifest.name}" does not match directory name "${pluginName}"`);
1275
+ }
1276
+ }
1277
+ function validateNoBuildOutputDirs(pluginDir) {
1278
+ if (fs.existsSync(path.join(pluginDir, '.claude-plugin'))) {
1279
+ error('.claude-plugin/ directory must not exist in plugin source (it is a build output)');
1280
+ }
1281
+ if (fs.existsSync(path.join(pluginDir, '.codex-plugin'))) {
1282
+ error('.codex-plugin/ directory must not exist in plugin source (it is a build output)');
1283
+ }
1284
+ }
1285
+ function validateDeclaredPathsExist(pluginDir, manifest) {
1286
+ for (const field of ['skills', 'slashCommands', 'mcpServers', 'apps']) {
1287
+ if (!manifest[field])
1288
+ continue;
1289
+ const resolved = path.join(pluginDir, manifest[field]);
1290
+ if (!fs.existsSync(resolved)) {
1291
+ error(`${field} points to "${manifest[field]}" but path does not exist: ${resolved}`);
1292
+ }
1293
+ }
1294
+ }
1295
+ function validateCanonicalSkillLayout(pluginDir, manifest) {
1296
+ if (manifest.skills && normalizeRelativePath(manifest.skills) !== 'skills') {
1297
+ error('skills must be "./skills"');
1298
+ }
1299
+ const pluginReadme = path.join(pluginDir, 'README.md');
1300
+ if (!fs.statSync(pluginReadme, { throwIfNoEntry: false })?.isFile()) {
1301
+ error('Plugin root README.md is required');
1302
+ }
1303
+ else {
1304
+ const content = fs.readFileSync(pluginReadme, 'utf8');
1305
+ if (content.trim() === '')
1306
+ error('Plugin root README.md must not be empty');
1307
+ }
1308
+ const declared = collectDeclaredSkillNames(pluginDir, manifest);
1309
+ const sourceBackedDynamicSkills = (Array.isArray(manifest.artifacts?.targets)
1310
+ ? manifest.artifacts.targets
1311
+ : [])
1312
+ .filter((target) => target &&
1313
+ typeof target === 'object' &&
1314
+ (target.target === 'codex.skill' || target.target === 'claude.skill') &&
1315
+ typeof target.skillKey === 'string' &&
1316
+ Array.isArray(target.sourceDirs) &&
1317
+ target.sourceDirs.length > 0)
1318
+ .map((target) => target.skillKey.trim());
1319
+ for (const skill of new Set([...declared.static, ...sourceBackedDynamicSkills])) {
1320
+ const skillRoot = path.join(pluginDir, 'skills', skill);
1321
+ if (!fs.statSync(skillRoot, { throwIfNoEntry: false })?.isDirectory()) {
1322
+ error(`Skill ${JSON.stringify(skill)} must use source root "./skills/${skill}"`);
1323
+ continue;
1324
+ }
1325
+ const skillReadme = path.join(skillRoot, 'README.md');
1326
+ if (!fs.statSync(skillReadme, { throwIfNoEntry: false })?.isFile()) {
1327
+ error(`skills/${skill}/README.md is required`);
1328
+ continue;
1329
+ }
1330
+ const content = fs.readFileSync(skillReadme, 'utf8');
1331
+ if (content.trim() === '') {
1332
+ error(`skills/${skill}/README.md must not be empty`);
1333
+ }
1334
+ }
1335
+ const portableRoot = manifest.distributions?.agentSkills?.skills;
1336
+ for (const skill of declared.portable) {
1337
+ const skillRoot = path.join(pluginDir, portableRoot, skill);
1338
+ const skillReadme = path.join(skillRoot, 'README.md');
1339
+ if (!fs.statSync(skillReadme, { throwIfNoEntry: false })?.isFile()) {
1340
+ error(`${normalizeRelativePath(path.join(portableRoot, skill, 'README.md'))} is required`);
1341
+ continue;
1342
+ }
1343
+ if (fs.readFileSync(skillReadme, 'utf8').trim() === '') {
1344
+ error(`${normalizeRelativePath(path.join(portableRoot, skill, 'README.md'))} must not be empty`);
1345
+ }
1346
+ }
1347
+ }
1348
+ function validateDeclaredNativeAssets(pluginDir, manifest) {
1349
+ const defaults = [
1350
+ ['skills', 'skills'],
1351
+ [DEFAULT_SLASH_COMMANDS_DIR, 'slashCommands'],
1352
+ ['.mcp.json', 'mcpServers'],
1353
+ ['.app.json', 'apps'],
1354
+ ];
1355
+ for (const [filename, field] of defaults) {
1356
+ const fullPath = path.join(pluginDir, filename);
1357
+ if (fs.existsSync(fullPath) && !manifest[field]) {
1358
+ if (field === 'skills') {
1359
+ const dynamicSkills = new Set((Array.isArray(manifest.artifacts?.targets) ? manifest.artifacts.targets : [])
1360
+ .filter((target) => {
1361
+ if (!target ||
1362
+ typeof target !== 'object' ||
1363
+ (target.target !== 'codex.skill' && target.target !== 'claude.skill') ||
1364
+ typeof target.skillKey !== 'string' ||
1365
+ !Array.isArray(target.sourceDirs) ||
1366
+ target.sourceDirs.length === 0)
1367
+ return false;
1368
+ return target.sourceDirs.every((sourceDir) => typeof sourceDir === 'string' &&
1369
+ (normalizeRelativePath(sourceDir) === `skills/${target.skillKey}` ||
1370
+ normalizeRelativePath(sourceDir).startsWith(`skills/${target.skillKey}/`)));
1371
+ })
1372
+ .map((target) => target.skillKey));
1373
+ const entries = fs.readdirSync(fullPath, { withFileTypes: true });
1374
+ if (entries.length > 0 &&
1375
+ entries.every((entry) => entry.isDirectory() && dynamicSkills.has(entry.name))) {
1376
+ continue;
1377
+ }
1378
+ }
1379
+ error(`"${filename}" exists but manifest does not declare "${field}" — declare it or remove the file`);
1380
+ }
1381
+ }
1382
+ }
1383
+ function collectDeclaredSkillNames(pluginDir, manifest) {
1384
+ const skillsRoot = typeof manifest.skills === 'string'
1385
+ ? path.join(pluginDir, manifest.skills)
1386
+ : null;
1387
+ const staticSkillNames = skillsRoot && fs.existsSync(skillsRoot)
1388
+ ? fs.readdirSync(skillsRoot, { withFileTypes: true })
1389
+ .filter((entry) => entry.isDirectory())
1390
+ .map((entry) => entry.name)
1391
+ .sort()
1392
+ : [];
1393
+ const staticSkillNameSet = new Set(staticSkillNames);
1394
+ const artifactTargets = Array.isArray(manifest.artifacts?.targets)
1395
+ ? manifest.artifacts.targets
1396
+ : [];
1397
+ const dynamicSkillNames = artifactTargets
1398
+ .filter((target) => target
1399
+ && typeof target === 'object'
1400
+ && (target.target === 'codex.skill' || target.target === 'claude.skill')
1401
+ && typeof target.skillKey === 'string'
1402
+ && target.skillKey.trim() !== '')
1403
+ .map((target) => target.skillKey.trim())
1404
+ .sort();
1405
+ const dynamicSkillNameSet = new Set(dynamicSkillNames);
1406
+ const portableRoot = typeof manifest.distributions?.agentSkills?.skills === 'string'
1407
+ ? path.join(pluginDir, manifest.distributions.agentSkills.skills)
1408
+ : null;
1409
+ const portableRootStats = portableRoot
1410
+ ? fs.lstatSync(portableRoot, { throwIfNoEntry: false })
1411
+ : null;
1412
+ const portableSkillNameSet = new Set(portableRootStats?.isDirectory() && !portableRootStats.isSymbolicLink()
1413
+ ? fs.readdirSync(portableRoot, { withFileTypes: true })
1414
+ .filter((entry) => entry.isDirectory())
1415
+ .map((entry) => entry.name)
1416
+ : []);
1417
+ return {
1418
+ static: staticSkillNameSet,
1419
+ dynamic: dynamicSkillNameSet,
1420
+ portable: portableSkillNameSet,
1421
+ all: new Set([...staticSkillNames, ...dynamicSkillNames]),
1422
+ };
1423
+ }
1424
+ function isNodeRunnablePath(relativePath) {
1425
+ return SCRIPT_NODE_EXTENSIONS.has(path.posix.extname(normalizeRelativePath(relativePath)));
1426
+ }
1427
+ function normalizePluginScriptPath(pluginDir, value, fieldName) {
1428
+ if (typeof value !== 'string' || value.trim() === '') {
1429
+ error(`${fieldName} must be a non-empty string`);
1430
+ return null;
1431
+ }
1432
+ if (/\s|[;&|<>`]/.test(value) || value.includes('$(')) {
1433
+ error(`${fieldName} must be a file path, not an inline command`);
1434
+ return null;
1435
+ }
1436
+ if (!value.startsWith('./')) {
1437
+ error(`${fieldName} must start with "./"`);
1438
+ return null;
1439
+ }
1440
+ if (path.isAbsolute(value) || path.win32.isAbsolute(value)) {
1441
+ error(`${fieldName} must be relative to the plugin root`);
1442
+ return null;
1443
+ }
1444
+ const relativePath = normalizeRelativePath(value);
1445
+ if (relativePath === '.' || relativePath === '..' || relativePath.startsWith('../')) {
1446
+ error(`${fieldName} must stay inside the plugin root`);
1447
+ return null;
1448
+ }
1449
+ const absolutePath = path.resolve(pluginDir, relativePath);
1450
+ const relativeFromRoot = path.relative(pluginDir, absolutePath);
1451
+ if (relativeFromRoot.startsWith('..') || path.isAbsolute(relativeFromRoot)) {
1452
+ error(`${fieldName} must stay inside the plugin root`);
1453
+ return null;
1454
+ }
1455
+ return relativePath;
1456
+ }
1457
+ function validateDeclaredScriptFile(pluginDir, relativePath, fieldName) {
1458
+ if (!relativePath)
1459
+ return;
1460
+ const absolutePath = path.join(pluginDir, relativePath);
1461
+ const stats = fs.statSync(absolutePath, { throwIfNoEntry: false });
1462
+ if (!stats?.isFile()) {
1463
+ error(`${fieldName} points to "${relativePath}" but the file does not exist`);
1464
+ }
1465
+ }
1466
+ function validateScriptEntry(pluginDir, value, fieldName, options = {}) {
1467
+ const entry = expectRecord(value, fieldName);
1468
+ if (!entry)
1469
+ return null;
1470
+ if ('command' in entry) {
1471
+ error(`${fieldName}.command is not supported; declare runner/path instead`);
1472
+ }
1473
+ validateAllowedKeys(entry, fieldName, ['runner', 'path', 'args']);
1474
+ const runner = validateManifestString(entry.runner, `${fieldName}.runner`);
1475
+ if (runner !== 'node') {
1476
+ error(`${fieldName}.runner must be "node"`);
1477
+ }
1478
+ const relativePath = normalizePluginScriptPath(pluginDir, entry.path, `${fieldName}.path`);
1479
+ validateDeclaredScriptFile(pluginDir, relativePath, `${fieldName}.path`);
1480
+ if (options.requireNodePath && relativePath && !isNodeRunnablePath(relativePath)) {
1481
+ error(`${fieldName}.path must use a Node runnable extension (.js, .mjs, or .cjs)`);
1482
+ }
1483
+ if (entry.args !== undefined) {
1484
+ if (!Array.isArray(entry.args)) {
1485
+ error(`${fieldName}.args must be an array of strings`);
1486
+ }
1487
+ else {
1488
+ entry.args.forEach((arg, index) => {
1489
+ if (typeof arg !== 'string') {
1490
+ error(`${fieldName}.args[${index}] must be a string`);
1491
+ }
1492
+ });
1493
+ }
1494
+ }
1495
+ return runner && relativePath ? { runner, path: relativePath } : null;
1496
+ }
1497
+ function isNonRegistryDependencySpecifier(specifier) {
1498
+ const trimmed = String(specifier).trim();
1499
+ return (/^(?:workspace|file|link|portal):/i.test(trimmed) ||
1500
+ /^(?:git\+|git:|ssh:)/i.test(trimmed) ||
1501
+ /^https?:\/\//i.test(trimmed) ||
1502
+ /(?:\.tgz|\.tar\.gz)(?:[#?].*)?$/i.test(trimmed) ||
1503
+ trimmed.startsWith('./') ||
1504
+ trimmed.startsWith('../') ||
1505
+ trimmed.startsWith('/') ||
1506
+ trimmed.startsWith('~') ||
1507
+ /^[\w.-]+\/[\w.-]+(?:#.*)?$/.test(trimmed));
1508
+ }
1509
+ function readPackageDependencyNames(packageJson, fieldName, dependencyField) {
1510
+ const rawDependencies = packageJson[dependencyField];
1511
+ if (rawDependencies === undefined)
1512
+ return [];
1513
+ const dependencies = expectRecord(rawDependencies, `${fieldName}.${dependencyField}`);
1514
+ if (!dependencies)
1515
+ return [];
1516
+ const names = [];
1517
+ for (const [name, specifier] of Object.entries(dependencies)) {
1518
+ if (typeof specifier !== 'string') {
1519
+ error(`${fieldName}.${dependencyField}.${name} must be a string specifier`);
1520
+ continue;
1521
+ }
1522
+ if (isNonRegistryDependencySpecifier(specifier)) {
1523
+ error(`${fieldName}.${dependencyField}.${name} uses non registry-backed specifier "${specifier}"`);
1524
+ }
1525
+ names.push(name);
1526
+ }
1527
+ return names;
1528
+ }
1529
+ function validatePackageRoot(pluginDir, packageRootValue, fieldName) {
1530
+ const packageRoot = normalizePluginScriptPath(pluginDir, packageRootValue, fieldName);
1531
+ if (!packageRoot)
1532
+ return null;
1533
+ const absolutePackageRoot = path.join(pluginDir, packageRoot);
1534
+ const stats = fs.statSync(absolutePackageRoot, { throwIfNoEntry: false });
1535
+ if (!stats?.isDirectory()) {
1536
+ error(`${fieldName} must point to a package directory`);
1537
+ return { packageRoot, dependencies: [], devDependencies: [] };
1538
+ }
1539
+ for (const lockfile of ['package-lock.json', 'yarn.lock', 'bun.lock', 'bun.lockb']) {
1540
+ if (fs.existsSync(path.join(absolutePackageRoot, lockfile))) {
1541
+ error(`${fieldName} only supports pnpm-lock.yaml, found ${lockfile}`);
1542
+ }
1543
+ }
1544
+ const packageJsonPath = path.join(absolutePackageRoot, 'package.json');
1545
+ const lockfilePath = path.join(absolutePackageRoot, 'pnpm-lock.yaml');
1546
+ if (!fs.existsSync(packageJsonPath)) {
1547
+ error(`${fieldName} is missing package.json`);
1548
+ }
1549
+ if (!fs.existsSync(lockfilePath)) {
1550
+ error(`${fieldName} is missing pnpm-lock.yaml`);
1551
+ }
1552
+ let packageJson = {};
1553
+ if (fs.existsSync(packageJsonPath)) {
1554
+ try {
1555
+ packageJson = JSON.parse(fs.readFileSync(packageJsonPath, 'utf8'));
1556
+ }
1557
+ catch (e) {
1558
+ error(`${fieldName}/package.json is not valid JSON: ${e.message}`);
1559
+ packageJson = {};
1560
+ }
1561
+ }
1562
+ if (packageJson.optionalDependencies !== undefined) {
1563
+ error(`${fieldName}/package.json optionalDependencies are not supported`);
1564
+ }
1565
+ if (packageJson.bundledDependencies !== undefined || packageJson.bundleDependencies !== undefined) {
1566
+ error(`${fieldName}/package.json bundledDependencies are not supported`);
1567
+ }
1568
+ return {
1569
+ packageRoot,
1570
+ dependencies: readPackageDependencyNames(packageJson, fieldName, 'dependencies'),
1571
+ devDependencies: readPackageDependencyNames(packageJson, fieldName, 'devDependencies'),
1572
+ };
1573
+ }
1574
+ function isRelativeSpecifier(specifier) {
1575
+ return specifier === '.' || specifier === '..' || specifier.startsWith('./') || specifier.startsWith('../');
1576
+ }
1577
+ function packageNameFromSpecifier(specifier) {
1578
+ if (specifier.startsWith('@')) {
1579
+ const [scope, name] = specifier.split('/');
1580
+ return `${scope}/${name ?? ''}`;
1581
+ }
1582
+ return specifier.split('/')[0];
1583
+ }
1584
+ function resolveRelativeJavaScriptImport(importer, specifier, pluginDir) {
1585
+ const importerDir = path.posix.dirname(importer);
1586
+ const normalized = path.posix.normalize(path.posix.join(importerDir, specifier));
1587
+ if (normalized === '..' || normalized.startsWith('../') || path.posix.isAbsolute(normalized)) {
1588
+ return { escaped: true, path: normalized };
1589
+ }
1590
+ const candidates = [
1591
+ normalized,
1592
+ `${normalized}.js`,
1593
+ `${normalized}.mjs`,
1594
+ `${normalized}.cjs`,
1595
+ path.posix.join(normalized, 'index.js'),
1596
+ path.posix.join(normalized, 'index.mjs'),
1597
+ path.posix.join(normalized, 'index.cjs'),
1598
+ ];
1599
+ const found = candidates.find((candidate) => fs.existsSync(path.join(pluginDir, candidate)));
1600
+ return found ? { escaped: false, path: found } : { escaped: false, path: null };
1601
+ }
1602
+ function pathIsUnderPackageRoot(relativePath, packageRoot) {
1603
+ if (!packageRoot)
1604
+ return false;
1605
+ return relativePath === packageRoot || relativePath.startsWith(`${packageRoot}/`);
1606
+ }
1607
+ function scanNodeImportContract(pluginDir, entryPaths, options) {
1608
+ const queue = [...new Set(entryPaths.filter(Boolean).map(normalizeRelativePath))];
1609
+ const visited = new Set();
1610
+ const dependencies = new Set(options.packageMeta?.dependencies ?? []);
1611
+ const devDependencies = new Set(options.packageMeta?.devDependencies ?? []);
1612
+ const packageRoot = options.packageMeta?.packageRoot;
1613
+ while (queue.length > 0) {
1614
+ const relativePath = queue.shift();
1615
+ if (!relativePath || visited.has(relativePath))
1616
+ continue;
1617
+ visited.add(relativePath);
1618
+ const absolutePath = path.join(pluginDir, relativePath);
1619
+ if (!fs.existsSync(absolutePath)) {
1620
+ error(`${options.label}: missing Node import file "${relativePath}"`);
1621
+ continue;
1622
+ }
1623
+ const source = fs.readFileSync(absolutePath, 'utf8');
1624
+ for (const { specifier } of scanJavaScriptImportSpecifiers(source)) {
1625
+ if (specifier.startsWith('node:'))
1626
+ continue;
1627
+ if (isRelativeSpecifier(specifier)) {
1628
+ const resolved = resolveRelativeJavaScriptImport(relativePath, specifier, pluginDir);
1629
+ if (resolved.escaped) {
1630
+ error(`${options.label}: relative import "${specifier}" from "${relativePath}" escapes the plugin root`);
1631
+ continue;
1632
+ }
1633
+ if (!resolved.path) {
1634
+ error(`${options.label}: unable to resolve relative import "${specifier}" from "${relativePath}"`);
1635
+ continue;
1636
+ }
1637
+ queue.push(resolved.path);
1638
+ continue;
1639
+ }
1640
+ if (specifier.startsWith('/') || specifier.includes(':')) {
1641
+ error(`${options.label}: unsupported import specifier "${specifier}" from "${relativePath}"`);
1642
+ continue;
1643
+ }
1644
+ const packageName = packageNameFromSpecifier(specifier);
1645
+ if (!packageRoot) {
1646
+ error(`${options.label}: bare import "${specifier}" from "${relativePath}" requires scripts.node.packageRoot`);
1647
+ continue;
1648
+ }
1649
+ if (!pathIsUnderPackageRoot(relativePath, packageRoot)) {
1650
+ error(`${options.label}: bare import "${specifier}" from "${relativePath}" is outside scripts.node.packageRoot`);
1651
+ continue;
1652
+ }
1653
+ if (dependencies.has(packageName))
1654
+ continue;
1655
+ if (devDependencies.has(packageName)) {
1656
+ if (!options.allowDevDependencies) {
1657
+ error(`${options.label}: runtime import "${specifier}" from "${relativePath}" uses dev dependency "${packageName}"`);
1658
+ }
1659
+ continue;
1660
+ }
1661
+ error(`${options.label}: import "${specifier}" from "${relativePath}" is not declared in dependencies`);
1662
+ }
1663
+ }
1664
+ }
1665
+ function listFilesRecursive(rootDir) {
1666
+ const output = [];
1667
+ if (!fs.existsSync(rootDir))
1668
+ return output;
1669
+ const walk = (dir) => {
1670
+ for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
1671
+ const absolutePath = path.join(dir, entry.name);
1672
+ if (entry.isDirectory()) {
1673
+ walk(absolutePath);
1674
+ }
1675
+ else if (entry.isFile()) {
1676
+ output.push(normalizeRelativePath(path.relative(rootDir, absolutePath)));
1677
+ }
1678
+ }
1679
+ };
1680
+ walk(rootDir);
1681
+ return output;
1682
+ }
1683
+ function validateConfigSchemaLightweight(config) {
1684
+ if (config === undefined)
1685
+ return;
1686
+ try {
1687
+ normalizePluginConfigDefinition(config);
1688
+ }
1689
+ catch (validationError) {
1690
+ error(validationError instanceof Error ? validationError.message : String(validationError));
1691
+ }
1692
+ }
1693
+ function configSchemaKeys(manifest) {
1694
+ const schema = manifest.config?.fields;
1695
+ return isRecord(schema) ? new Set(Object.keys(schema)) : new Set();
1696
+ }
1697
+ function defaultConfigValues(manifest) {
1698
+ const schema = manifest.config?.fields;
1699
+ const values = {};
1700
+ if (!isRecord(schema))
1701
+ return values;
1702
+ for (const [key, field] of Object.entries(schema)) {
1703
+ if (isRecord(field) && Object.prototype.hasOwnProperty.call(field, 'default')) {
1704
+ values[key] = field.default;
1705
+ }
1706
+ }
1707
+ return values;
1708
+ }
1709
+ function validateArtifactId(value, fieldName) {
1710
+ const id = validateManifestString(value, fieldName);
1711
+ if (!id)
1712
+ return null;
1713
+ if (!/^[A-Za-z][A-Za-z0-9_.-]*$/.test(id)) {
1714
+ error(`${fieldName}: expected a stable id using letters, numbers, ".", "_" or "-"`);
1715
+ }
1716
+ return id;
1717
+ }
1718
+ function validateCodexRoleKey(value, fieldName) {
1719
+ const roleKey = validateManifestString(value, fieldName);
1720
+ if (!roleKey)
1721
+ return null;
1722
+ if (!/^[A-Za-z][A-Za-z0-9_-]*$/.test(roleKey)) {
1723
+ error(`${fieldName}: expected a valid Codex role key`);
1724
+ }
1725
+ return roleKey;
1726
+ }
1727
+ function validateCodexSkillKey(value, fieldName) {
1728
+ const skillKey = validateManifestString(value, fieldName);
1729
+ if (!skillKey)
1730
+ return null;
1731
+ if (!/^[A-Za-z][A-Za-z0-9_-]*$/.test(skillKey)) {
1732
+ error(`${fieldName}: expected a valid Codex skill key`);
1733
+ }
1734
+ return skillKey;
1735
+ }
1736
+ function validatePortableSkillKey(value, fieldName) {
1737
+ const skillKey = validateManifestString(value, fieldName);
1738
+ if (!skillKey)
1739
+ return null;
1740
+ if (skillKey.length > MAX_SKILL_NAME_LEN || !/^[a-z0-9]+(?:-[a-z0-9]+)*$/.test(skillKey)) {
1741
+ error(`${fieldName}: expected at most 64 ASCII lowercase hyphen-case characters`);
1742
+ }
1743
+ return skillKey;
1744
+ }
1745
+ function validateStringArray(value, fieldName, options = {}) {
1746
+ if (!Array.isArray(value)) {
1747
+ error(`${fieldName} must be an array`);
1748
+ return [];
1749
+ }
1750
+ const output = [];
1751
+ for (const [index, entry] of value.entries()) {
1752
+ const itemFieldName = `${fieldName}[${index}]`;
1753
+ if (typeof entry !== 'string' || entry.trim() === '') {
1754
+ error(`${itemFieldName} must be a non-empty string`);
1755
+ continue;
1756
+ }
1757
+ if (options.allowed && !options.allowed.has(entry)) {
1758
+ error(`${itemFieldName}: unsupported ${options.label ?? 'value'} "${entry}"`);
1759
+ continue;
1760
+ }
1761
+ if (!output.includes(entry))
1762
+ output.push(entry);
1763
+ }
1764
+ if (options.requireNonEmpty && output.length === 0) {
1765
+ error(`${fieldName} must contain at least one value`);
1766
+ }
1767
+ return output;
1768
+ }
1769
+ function validateArtifactTargetEntry(entry, index, manifest, pluginDir) {
1770
+ const fieldName = `artifacts.targets[${index}]`;
1771
+ const target = expectRecord(entry, fieldName);
1772
+ if (!target)
1773
+ return null;
1774
+ validateAllowedKeys(target, fieldName, [
1775
+ 'id',
1776
+ 'platform',
1777
+ 'distribution',
1778
+ 'scopes',
1779
+ 'target',
1780
+ 'kind',
1781
+ 'projectManagedKind',
1782
+ 'states',
1783
+ 'refreshKeys',
1784
+ 'delivery',
1785
+ 'requiresCodexProjectConfig',
1786
+ 'roleKey',
1787
+ 'skillKey',
1788
+ 'sourceDirs',
1789
+ 'runtimeImports',
1790
+ ]);
1791
+ const id = validateArtifactId(target.id, `${fieldName}.id`);
1792
+ const artifactTarget = validateManifestString(target.target, `${fieldName}.target`);
1793
+ if (artifactTarget && !ARTIFACT_TARGETS.has(artifactTarget)) {
1794
+ error(`${fieldName}.target: unsupported artifact target "${artifactTarget}"`);
1795
+ }
1796
+ const portable = artifactTarget === 'agent-skills.skill';
1797
+ let delivery;
1798
+ if (artifactTarget === 'codex.skill') {
1799
+ delivery = expectRecord(target.delivery, `${fieldName}.delivery`);
1800
+ if (delivery) {
1801
+ if (delivery.mode === 'aw-extension') {
1802
+ validateAllowedKeys(delivery, `${fieldName}.delivery`, ['mode']);
1803
+ }
1804
+ else if (delivery.mode === 'codex-native') {
1805
+ validateAllowedKeys(delivery, `${fieldName}.delivery`, ['mode', 'identity', 'renderProfile']);
1806
+ if (delivery.identity !== 'shared') {
1807
+ error(`${fieldName}.delivery.identity: expected "shared"`);
1808
+ }
1809
+ if (delivery.renderProfile !== 'user') {
1810
+ error(`${fieldName}.delivery.renderProfile: expected "user"`);
1811
+ }
1812
+ }
1813
+ else {
1814
+ error(`${fieldName}.delivery.mode: expected "codex-native" or "aw-extension"`);
1815
+ }
1816
+ }
1817
+ }
1818
+ else if (target.delivery !== undefined) {
1819
+ error(`${fieldName}.delivery: delivery is only supported for codex.skill targets`);
1820
+ }
1821
+ const platform = portable || target.platform === undefined
1822
+ ? undefined
1823
+ : validateManifestString(target.platform, `${fieldName}.platform`);
1824
+ const distribution = portable || target.distribution !== undefined
1825
+ ? validateManifestString(target.distribution, `${fieldName}.distribution`)
1826
+ : undefined;
1827
+ if (portable) {
1828
+ if (distribution !== 'agent-skills') {
1829
+ error(`${fieldName}.distribution: expected "agent-skills"`);
1830
+ }
1831
+ if (target.platform !== undefined) {
1832
+ error(`${fieldName}.platform: distribution targets do not support platform`);
1833
+ }
1834
+ }
1835
+ else {
1836
+ const expectedPlatform = artifactTarget === 'claude.skill' ? 'claude' : 'codex';
1837
+ if (platform && artifactTarget && platform !== expectedPlatform) {
1838
+ error(`${fieldName}.platform: target "${artifactTarget}" must use "${expectedPlatform}"`);
1839
+ }
1840
+ if (target.distribution !== undefined) {
1841
+ error(`${fieldName}.distribution: platform targets do not support distribution`);
1842
+ }
1843
+ }
1844
+ const expectedKind = ARTIFACT_KIND_BY_TARGET[artifactTarget];
1845
+ const kind = target.kind === undefined
1846
+ ? expectedKind
1847
+ : validateManifestString(target.kind, `${fieldName}.kind`);
1848
+ if (kind && !ARTIFACT_KINDS.has(kind)) {
1849
+ error(`${fieldName}.kind: unsupported artifact kind "${kind}"`);
1850
+ }
1851
+ if (expectedKind && kind && kind !== expectedKind) {
1852
+ error(`${fieldName}.kind: target "${artifactTarget}" requires kind "${expectedKind}"`);
1853
+ }
1854
+ const expectedProjectManagedKind = ARTIFACT_PROJECT_MANAGED_KIND_BY_TARGET[artifactTarget];
1855
+ const projectManagedKind = target.projectManagedKind === undefined
1856
+ ? expectedProjectManagedKind
1857
+ : validateManifestString(target.projectManagedKind, `${fieldName}.projectManagedKind`);
1858
+ if (projectManagedKind && !ARTIFACT_PROJECT_MANAGED_KINDS.has(projectManagedKind)) {
1859
+ error(`${fieldName}.projectManagedKind: unsupported Codex project managed kind "${projectManagedKind}"`);
1860
+ }
1861
+ if (expectedProjectManagedKind &&
1862
+ projectManagedKind &&
1863
+ projectManagedKind !== expectedProjectManagedKind) {
1864
+ error(`${fieldName}.projectManagedKind: target "${artifactTarget}" must map to "${expectedProjectManagedKind}"`);
1865
+ }
1866
+ if (!expectedProjectManagedKind && projectManagedKind) {
1867
+ error(`${fieldName}.projectManagedKind: target "${artifactTarget}" does not support projectManagedKind`);
1868
+ }
1869
+ const scopes = validateStringArray(target.scopes, `${fieldName}.scopes`, {
1870
+ allowed: ARTIFACT_SCOPES,
1871
+ label: 'artifact scope',
1872
+ requireNonEmpty: true,
1873
+ });
1874
+ const states = validateStringArray(target.states, `${fieldName}.states`, {
1875
+ allowed: ARTIFACT_STATES,
1876
+ label: 'artifact state',
1877
+ requireNonEmpty: true,
1878
+ });
1879
+ const refreshKeys = validateStringArray(target.refreshKeys, `${fieldName}.refreshKeys`);
1880
+ const schemaKeys = configSchemaKeys(manifest);
1881
+ for (const [refreshIndex, refreshKey] of refreshKeys.entries()) {
1882
+ if (!schemaKeys.has(refreshKey)) {
1883
+ error(`${fieldName}.refreshKeys[${refreshIndex}]: unknown config key "${refreshKey}"`);
1884
+ continue;
1885
+ }
1886
+ }
1887
+ if (target.requiresCodexProjectConfig !== undefined &&
1888
+ typeof target.requiresCodexProjectConfig !== 'boolean') {
1889
+ error(`${fieldName}.requiresCodexProjectConfig must be a boolean`);
1890
+ }
1891
+ if (artifactTarget === 'codex.skill' && target.requiresCodexProjectConfig === true) {
1892
+ error(`${fieldName}.requiresCodexProjectConfig: codex.skill writes the skill runtime and must not require Codex project config preflight`);
1893
+ }
1894
+ if ((platform === 'claude' || portable) && target.requiresCodexProjectConfig !== undefined) {
1895
+ error(`${fieldName}.requiresCodexProjectConfig: this target does not support the field`);
1896
+ }
1897
+ let roleKey;
1898
+ let skillKey;
1899
+ if (artifactTarget === 'codex.agentRole') {
1900
+ roleKey = validateCodexRoleKey(target.roleKey, `${fieldName}.roleKey`);
1901
+ if (!roleKey) {
1902
+ error(`${fieldName}.roleKey: codex.agentRole targets must declare a static roleKey`);
1903
+ }
1904
+ }
1905
+ else if (target.roleKey !== undefined) {
1906
+ error(`${fieldName}.roleKey: roleKey is only supported for codex.agentRole targets`);
1907
+ }
1908
+ if (artifactTarget === 'codex.skill' || artifactTarget === 'claude.skill' || portable) {
1909
+ skillKey = portable
1910
+ ? validatePortableSkillKey(target.skillKey, `${fieldName}.skillKey`)
1911
+ : validateCodexSkillKey(target.skillKey, `${fieldName}.skillKey`);
1912
+ if (!skillKey) {
1913
+ error(`${fieldName}.skillKey: ${artifactTarget} targets must declare a static skillKey`);
1914
+ }
1915
+ }
1916
+ else if (target.skillKey !== undefined) {
1917
+ error(`${fieldName}.skillKey: skillKey is only supported for skill targets`);
1918
+ }
1919
+ const normalizedSourceDirs = Array.isArray(target.sourceDirs)
1920
+ ? target.sourceDirs
1921
+ .filter((sourceDir) => typeof sourceDir === 'string' && sourceDir.trim() !== '')
1922
+ .map((sourceDir) => path.posix.normalize(sourceDir))
1923
+ : [];
1924
+ if (new Set(normalizedSourceDirs).size !== normalizedSourceDirs.length) {
1925
+ error(`${fieldName}.sourceDirs must not contain duplicate directories`);
1926
+ }
1927
+ const sourceDirs = target.sourceDirs === undefined
1928
+ ? []
1929
+ : validateStringArray(target.sourceDirs, `${fieldName}.sourceDirs`);
1930
+ if (sourceDirs.length > 0 && artifactTarget !== 'codex.skill' && artifactTarget !== 'claude.skill' && !portable) {
1931
+ error(`${fieldName}.sourceDirs: sourceDirs are only supported for skill targets`);
1932
+ }
1933
+ for (const [sourceIndex, sourceDir] of sourceDirs.entries()) {
1934
+ const sourceField = `${fieldName}.sourceDirs[${sourceIndex}]`;
1935
+ if (!sourceDir.startsWith('./') || path.posix.isAbsolute(sourceDir)) {
1936
+ error(`${sourceField} must start with "./" and stay inside the plugin root`);
1937
+ continue;
1938
+ }
1939
+ const normalized = path.posix.normalize(sourceDir);
1940
+ if (normalized === '.' || normalized === '..' || normalized.startsWith('../')) {
1941
+ error(`${sourceField} must stay inside the plugin root`);
1942
+ continue;
1943
+ }
1944
+ const stats = fs.lstatSync(path.join(pluginDir, normalized), { throwIfNoEntry: false });
1945
+ if (!stats?.isDirectory() || stats.isSymbolicLink()) {
1946
+ error(`${sourceField} must point to an existing directory`);
1947
+ }
1948
+ if (skillKey && !portable &&
1949
+ normalized !== `skills/${skillKey}` &&
1950
+ !normalized.startsWith(`skills/${skillKey}/`)) {
1951
+ error(`${sourceField} must stay inside "./skills/${skillKey}"`);
1952
+ }
1953
+ if (skillKey && !portable &&
1954
+ isSkillAuthorOnlyPath(path.posix.relative(`skills/${skillKey}`, normalized))) {
1955
+ error(`${sourceField} must not point inside an author-only Skill directory`);
1956
+ }
1957
+ }
1958
+ if (skillKey && !portable &&
1959
+ sourceDirs.length > 0 &&
1960
+ !normalizedSourceDirs.includes(`skills/${skillKey}`)) {
1961
+ error(`${fieldName}.sourceDirs must include "./skills/${skillKey}" so README.md is published`);
1962
+ }
1963
+ return {
1964
+ id,
1965
+ platform,
1966
+ distribution,
1967
+ scopes,
1968
+ target: artifactTarget,
1969
+ kind,
1970
+ projectManagedKind,
1971
+ states,
1972
+ refreshKeys,
1973
+ delivery,
1974
+ roleKey,
1975
+ skillKey,
1976
+ sourceDirs,
1977
+ runtimeImports: Array.isArray(target.runtimeImports) ? target.runtimeImports : [],
1978
+ };
1979
+ }
1980
+ function validateArtifactsConfigLightweight(pluginDir, manifest) {
1981
+ if (manifest.artifacts === undefined)
1982
+ return [];
1983
+ const artifacts = expectRecord(manifest.artifacts, 'artifacts');
1984
+ if (!artifacts)
1985
+ return [];
1986
+ validateAllowedKeys(artifacts, 'artifacts', ['targets']);
1987
+ if (artifacts.targets === undefined)
1988
+ return [];
1989
+ if (!Array.isArray(artifacts.targets)) {
1990
+ error('artifacts.targets must be an array');
1991
+ return [];
1992
+ }
1993
+ const declarations = artifacts.targets
1994
+ .map((entry, index) => validateArtifactTargetEntry(entry, index, manifest, pluginDir))
1995
+ .filter(Boolean);
1996
+ const idsBySurfaceScope = new Map();
1997
+ const nativeIds = new Map();
1998
+ const nativeSkillKeys = new Map();
1999
+ for (const [declarationIndex, declaration] of declarations.entries()) {
2000
+ for (const scope of declaration.scopes) {
2001
+ const surface = declaration.platform ?? declaration.distribution;
2002
+ const key = `${surface}:${scope}:${declaration.id}`;
2003
+ const existing = idsBySurfaceScope.get(key);
2004
+ if (existing !== undefined) {
2005
+ error(`artifacts.targets has duplicate artifact id "${declaration.id}" for surface/scope "${surface}:${scope}" in targets[${existing}] and targets[${declarationIndex}]`);
2006
+ }
2007
+ else {
2008
+ idsBySurfaceScope.set(key, declarationIndex);
2009
+ }
2010
+ }
2011
+ if (declaration.delivery?.mode === 'codex-native') {
2012
+ const existingId = nativeIds.get(declaration.id);
2013
+ if (existingId !== undefined) {
2014
+ error(`artifacts.targets has duplicate codex-native artifact id "${declaration.id}" in the shared projection at targets[${existingId}] and targets[${declarationIndex}]`);
2015
+ }
2016
+ else {
2017
+ nativeIds.set(declaration.id, declarationIndex);
2018
+ }
2019
+ const existingSkillKey = nativeSkillKeys.get(declaration.skillKey);
2020
+ if (existingSkillKey !== undefined) {
2021
+ error(`artifacts.targets has duplicate codex-native skillKey "${declaration.skillKey}" in the shared projection at targets[${existingSkillKey}] and targets[${declarationIndex}]`);
2022
+ }
2023
+ else {
2024
+ nativeSkillKeys.set(declaration.skillKey, declarationIndex);
2025
+ }
2026
+ }
2027
+ }
2028
+ const staticSkillNames = new Set(collectDeclaredSkillNames(pluginDir, manifest).static);
2029
+ for (const [index, declaration] of declarations.entries()) {
2030
+ if (declaration.target === 'codex.skill'
2031
+ && declaration.delivery?.mode === 'codex-native'
2032
+ && staticSkillNames.has(declaration.skillKey)) {
2033
+ error(`artifacts.targets[${index}].skillKey: native dynamic Skill "${declaration.skillKey}" conflicts with a static Skill of the same name`);
2034
+ }
2035
+ }
2036
+ const owners = new Map();
2037
+ for (const declaration of declarations) {
2038
+ if ((declaration.target !== 'codex.skill' && declaration.target !== 'claude.skill' && declaration.target !== 'agent-skills.skill') ||
2039
+ !declaration.skillKey) {
2040
+ continue;
2041
+ }
2042
+ for (const scope of declaration.scopes) {
2043
+ const ownerKey = `${declaration.platform ?? declaration.distribution}:${scope}:${declaration.skillKey}`;
2044
+ const existing = owners.get(ownerKey);
2045
+ if (existing) {
2046
+ error(`artifacts.targets has duplicate skill ownership "${ownerKey}" in artifacts "${existing}" and "${declaration.id}"`);
2047
+ }
2048
+ else {
2049
+ owners.set(ownerKey, declaration.id);
2050
+ }
2051
+ }
2052
+ }
2053
+ return declarations;
2054
+ }
2055
+ function validateArtifactPlanRefreshKeys(refreshKeys, declaration, fieldName) {
2056
+ const keys = validateStringArray(refreshKeys, `${fieldName}.refreshKeys`);
2057
+ for (const [index, key] of keys.entries()) {
2058
+ if (!declaration.refreshKeys.includes(key)) {
2059
+ error(`${fieldName}.refreshKeys[${index}]: "${key}" is not declared for artifact "${declaration.id}"`);
2060
+ }
2061
+ }
2062
+ for (const declaredKey of declaration.refreshKeys) {
2063
+ if (!keys.includes(declaredKey)) {
2064
+ error(`${fieldName}: artifact "${declaration.id}" must preserve declared refresh key "${declaredKey}"`);
2065
+ }
2066
+ }
2067
+ }
2068
+ function isValidArtifactFilePath(relativePath) {
2069
+ return (relativePath.trim() !== '' &&
2070
+ !relativePath.includes('\\') &&
2071
+ !relativePath.startsWith('/') &&
2072
+ path.posix.normalize(relativePath) === relativePath &&
2073
+ !relativePath.split('/').some((segment) => segment === '' || segment === '.' || segment === '..'));
2074
+ }
2075
+ function isSkillAuthorOnlyPath(relativePath) {
2076
+ const [topLevel] = relativePath.split('/').filter(Boolean);
2077
+ return topLevel === 'evals' || topLevel === 'reports';
2078
+ }
2079
+ function collectArtifactSourceFiles(rootDir, fieldName, files) {
2080
+ const rootStats = fs.lstatSync(rootDir, { throwIfNoEntry: false });
2081
+ if (!rootStats?.isDirectory() || rootStats.isSymbolicLink())
2082
+ return;
2083
+ const visit = (currentDir, parentPath) => {
2084
+ const entries = fs.readdirSync(currentDir, { withFileTypes: true })
2085
+ .sort((left, right) => left.name.localeCompare(right.name));
2086
+ for (const entry of entries) {
2087
+ const relativePath = parentPath ? `${parentPath}/${entry.name}` : entry.name;
2088
+ if (isSkillAuthorOnlyPath(relativePath))
2089
+ continue;
2090
+ const absolutePath = path.join(currentDir, entry.name);
2091
+ if (entry.isSymbolicLink()) {
2092
+ error(`${fieldName} contains unsupported symbolic link "${relativePath}"`);
2093
+ continue;
2094
+ }
2095
+ if (entry.isDirectory()) {
2096
+ visit(absolutePath, relativePath);
2097
+ continue;
2098
+ }
2099
+ if (!entry.isFile()) {
2100
+ error(`${fieldName} contains unsupported non-regular file "${relativePath}"`);
2101
+ continue;
2102
+ }
2103
+ files.set(relativePath, fs.readFileSync(absolutePath));
2104
+ }
2105
+ };
2106
+ visit(rootDir, '');
2107
+ }
2108
+ function findArtifactFilePrefixConflict(files) {
2109
+ const paths = [...files.keys()].sort();
2110
+ for (const [index, relativePath] of paths.entries()) {
2111
+ const prefix = paths.slice(0, index).find((candidate) => relativePath.startsWith(`${candidate}/`));
2112
+ if (prefix)
2113
+ return [prefix, relativePath];
2114
+ }
2115
+ return null;
2116
+ }
2117
+ function authorRuntimeImportKey(artifactId, importIndex) {
2118
+ return `${artifactId}\0${importIndex}`;
2119
+ }
2120
+ async function resolveAuthorRuntimeImports(options) {
2121
+ const artifactImports = (options.manifest.artifacts?.targets ?? []).flatMap((target) => (target.runtimeImports ?? []).map((reference, importIndex) => ({
2122
+ key: authorRuntimeImportKey(target.id, importIndex),
2123
+ label: `artifacts target ${JSON.stringify(target.id)} runtime import ${JSON.stringify(reference.name)}`,
2124
+ purpose: 'artifact-runtime',
2125
+ reference,
2126
+ })));
2127
+ const skillRuntimeImports = (options.manifest.buildConfig?.skillRuntimeFiles ?? []).flatMap((entry, importIndex) => {
2128
+ if (!isRecord(entry.import))
2129
+ return [];
2130
+ const platforms = [
2131
+ ...(entry.platforms !== undefined || entry.distributions === undefined
2132
+ ? (entry.platforms ?? [...resolveSupportedPlatforms(options.manifest)])
2133
+ : []),
2134
+ ...(entry.distributions?.includes('agent-skills') ? [undefined] : []),
2135
+ ];
2136
+ return platforms.length > 0 ? [{
2137
+ key: importIndex,
2138
+ label: `buildConfig.skillRuntimeFiles[${importIndex}].import`,
2139
+ purpose: 'skill-runtime-file',
2140
+ reference: entry.import,
2141
+ platforms,
2142
+ }] : [];
2143
+ });
2144
+ const requested = [...artifactImports, ...skillRuntimeImports];
2145
+ if (requested.length === 0) {
2146
+ return { artifactImports: new Map(), skillRuntimeImports: new Map() };
2147
+ }
2148
+ if (!options.repoRoot
2149
+ || typeof options.cliManifestTools?.readPluginManifest !== 'function'
2150
+ || typeof options.cliManifestTools?.discoverPlugins !== 'function'
2151
+ || typeof options.cliManifestTools?.createRuntimeResolver !== 'function') {
2152
+ error('Portable runtime imports require a complete built CLI and canonical same-source Git workspace.');
2153
+ return null;
2154
+ }
2155
+ let consumer;
2156
+ let resolver;
2157
+ try {
2158
+ const sourceSet = await options.cliManifestTools.discoverPlugins(options.repoRoot);
2159
+ consumer = await options.cliManifestTools.readPluginManifest(options.pluginDir);
2160
+ if (!sourceSet.some((candidate) => candidate.manifest.name === consumer.manifest.name)) {
2161
+ sourceSet.push(consumer);
2162
+ }
2163
+ resolver = options.cliManifestTools.createRuntimeResolver(sourceSet);
2164
+ }
2165
+ catch {
2166
+ error('Portable runtime imports could not load the canonical same-source plugin set.');
2167
+ return null;
2168
+ }
2169
+ const resolvedArtifacts = new Map();
2170
+ const resolvedSkillRuntimeFiles = new Map();
2171
+ for (const request of requested) {
2172
+ let value;
2173
+ try {
2174
+ for (const platform of request.platforms ?? [undefined]) {
2175
+ const resolution = await resolver.resolve({
2176
+ consumer,
2177
+ reference: request.reference,
2178
+ purpose: request.purpose,
2179
+ platform,
2180
+ });
2181
+ const bytes = fs.readFileSync(resolution.sourcePath);
2182
+ const digest = `sha256:${createHash('sha256').update(bytes).digest('hex')}`;
2183
+ if (digest !== resolution.sourceDigest)
2184
+ throw new Error('runtime export changed during resolution');
2185
+ const current = {
2186
+ bytes,
2187
+ digest: resolution.sourceDigest,
2188
+ providerPluginId: resolution.provider,
2189
+ providerVersion: resolution.providerVersion,
2190
+ exportName: resolution.name,
2191
+ source: resolution.source,
2192
+ };
2193
+ if (value && (value.digest !== current.digest
2194
+ || value.providerPluginId !== current.providerPluginId
2195
+ || value.providerVersion !== current.providerVersion
2196
+ || value.exportName !== current.exportName
2197
+ || value.source !== current.source)) {
2198
+ throw new Error('runtime export changed between projection surfaces');
2199
+ }
2200
+ value = current;
2201
+ }
2202
+ }
2203
+ catch {
2204
+ const provider = typeof request.reference.plugin === 'string'
2205
+ ? JSON.stringify(request.reference.plugin)
2206
+ : '<invalid-provider>';
2207
+ const exportName = typeof request.reference.export === 'string'
2208
+ ? JSON.stringify(request.reference.export)
2209
+ : '<invalid-export>';
2210
+ error(`Cannot resolve ${request.label} from provider ${provider} export ${exportName}.`);
2211
+ continue;
2212
+ }
2213
+ if (request.purpose === 'artifact-runtime')
2214
+ resolvedArtifacts.set(request.key, value);
2215
+ else
2216
+ resolvedSkillRuntimeFiles.set(request.key, value);
2217
+ }
2218
+ return {
2219
+ artifactImports: resolvedArtifacts,
2220
+ skillRuntimeImports: resolvedSkillRuntimeFiles,
2221
+ };
2222
+ }
2223
+ function overlayPortableRuntimeFiles(files, manifest, pluginDir, skillKey, runtimeImports) {
2224
+ for (const [runtimeIndex, runtimeFile] of (manifest.buildConfig?.skillRuntimeFiles ?? []).entries()) {
2225
+ if (runtimeFile.skill !== skillKey
2226
+ || !runtimeFile.distributions?.includes('agent-skills'))
2227
+ continue;
2228
+ if (typeof runtimeFile.source === 'string') {
2229
+ const sourcePath = path.join(pluginDir, normalizeRelativePath(runtimeFile.source));
2230
+ const stats = fs.lstatSync(sourcePath, { throwIfNoEntry: false });
2231
+ if (!stats?.isFile() || stats.isSymbolicLink()) {
2232
+ error(`buildConfig.skillRuntimeFiles[${runtimeIndex}].source must point to a regular file`);
2233
+ continue;
2234
+ }
2235
+ files.set(runtimeFile.target, fs.readFileSync(sourcePath));
2236
+ continue;
2237
+ }
2238
+ if (isRecord(runtimeFile.import)) {
2239
+ const resolved = runtimeImports?.skillRuntimeImports.get(runtimeIndex);
2240
+ if (!resolved) {
2241
+ error(`buildConfig.skillRuntimeFiles[${runtimeIndex}].import could not be resolved`);
2242
+ continue;
2243
+ }
2244
+ files.set(runtimeFile.target, resolved.bytes);
2245
+ }
2246
+ }
2247
+ }
2248
+ function validateRenderedSkillTree(options) {
2249
+ const { entry, declaration, fieldName, pluginDir, manifest, materializedRoot, skillValidationTools, } = options;
2250
+ if (entry.state !== 'present' || !isRecord(entry.content) || !isRecord(entry.content.files)) {
2251
+ return;
2252
+ }
2253
+ const files = new Map();
2254
+ declaration.sourceDirs.forEach((sourceDir, index) => {
2255
+ collectArtifactSourceFiles(path.join(pluginDir, normalizeRelativePath(sourceDir)), `artifacts.targets sourceDirs[${index}] for artifact "${declaration.id}"`, files);
2256
+ });
2257
+ if (declaration.target === 'agent-skills.skill') {
2258
+ overlayPortableRuntimeFiles(files, manifest, pluginDir, declaration.skillKey, options.runtimeImports);
2259
+ }
2260
+ for (const [relativePath, content] of Object.entries(entry.content.files)) {
2261
+ if (isSkillAuthorOnlyPath(relativePath)) {
2262
+ error(`${fieldName}.content.files path "${relativePath}" uses an author-only Skill directory`);
2263
+ continue;
2264
+ }
2265
+ if (isValidArtifactFilePath(relativePath) && typeof content === 'string') {
2266
+ files.set(relativePath, Buffer.from(content, 'utf8'));
2267
+ }
2268
+ }
2269
+ const conflict = findArtifactFilePrefixConflict(files);
2270
+ if (conflict) {
2271
+ error(`${fieldName} final file tree path "${conflict[0]}" conflicts with "${conflict[1]}"`);
2272
+ return;
2273
+ }
2274
+ const skillFile = files.get('SKILL.md');
2275
+ if (!skillFile || skillFile.toString('utf8').trim() === '') {
2276
+ error(`${fieldName} final file tree must contain a non-empty SKILL.md`);
2277
+ }
2278
+ else if (!skillValidationTools) {
2279
+ error(`${fieldName} final SKILL.md cannot be validated because the shared CLI Skill validator is unavailable`);
2280
+ }
2281
+ else {
2282
+ const sourcePath = `${fieldName} final SKILL.md`;
2283
+ const parsed = skillValidationTools.parseSkillFrontmatter(skillFile.toString('utf8'), sourcePath);
2284
+ for (const diagnostic of parsed.errors) {
2285
+ error(`${diagnostic.path} [${diagnostic.code}] ${diagnostic.message}`);
2286
+ }
2287
+ if (parsed.frontmatter) {
2288
+ const diagnostics = skillValidationTools.validateSkillFrontmatter(parsed.frontmatter, {
2289
+ profile: declaration.platform === 'claude' ? 'claude-2.1.88' : 'portable-agent-skills',
2290
+ expectedName: declaration.skillKey,
2291
+ sourcePath,
2292
+ });
2293
+ for (const diagnostic of diagnostics) {
2294
+ error(`${diagnostic.path} [${diagnostic.code}] ${diagnostic.message}`);
2295
+ }
2296
+ }
2297
+ }
2298
+ const readme = files.get('README.md');
2299
+ if (!readme || readme.toString('utf8').trim() === '') {
2300
+ error(`${fieldName} final file tree must contain a non-empty README.md`);
2301
+ }
2302
+ const sensitiveValues = Object.entries(manifest.config?.fields ?? {})
2303
+ .filter(([, field]) => isRecord(field) && field.sensitive === true)
2304
+ .map(([key, field]) => Object.prototype.hasOwnProperty.call(field, 'default')
2305
+ ? String(field.default)
2306
+ : String(defaultConfigValues(manifest)[key] ?? ''))
2307
+ .filter(Boolean);
2308
+ for (const [relativePath, content] of files) {
2309
+ const text = content.toString('utf8');
2310
+ if (/\{\{[^{}]+\}\}/u.test(text)) {
2311
+ error(`${fieldName} final file tree contains an unresolved template in "${relativePath}"`);
2312
+ }
2313
+ if (sensitiveValues.some((value) => text.includes(value))) {
2314
+ error(`${fieldName} final file tree exposes sensitive config in "${relativePath}"`);
2315
+ }
2316
+ }
2317
+ if (declaration.target === 'codex.skill') {
2318
+ const openAiYaml = files.get('agents/openai.yaml');
2319
+ if (!openAiYaml || openAiYaml.toString('utf8').trim() === '') {
2320
+ error(`${fieldName} final file tree must contain a non-empty agents/openai.yaml`);
2321
+ }
2322
+ }
2323
+ fs.rmSync(materializedRoot, { recursive: true, force: true });
2324
+ for (const [relativePath, content] of files) {
2325
+ const targetPath = path.join(materializedRoot, ...relativePath.split('/'));
2326
+ fs.mkdirSync(path.dirname(targetPath), { recursive: true });
2327
+ fs.writeFileSync(targetPath, content);
2328
+ }
2329
+ if (declaration.target === 'codex.skill' && files.has('agents/openai.yaml')) {
2330
+ validateOpenAiYaml(path.join(materializedRoot, 'agents', 'openai.yaml'), declaration.skillKey, true, manifest, materializedRoot, skillValidationTools);
2331
+ }
2332
+ }
2333
+ function validateStaticPortableFinalTrees(pluginDir, manifest, runtimeImports, skillValidationTools) {
2334
+ const portableRoot = manifest.distributions?.agentSkills?.skills;
2335
+ if (typeof portableRoot !== 'string')
2336
+ return;
2337
+ const rootDir = path.join(pluginDir, normalizeRelativePath(portableRoot));
2338
+ const rootStats = fs.lstatSync(rootDir, { throwIfNoEntry: false });
2339
+ if (!rootStats?.isDirectory() || rootStats.isSymbolicLink())
2340
+ return;
2341
+ const dynamicKeys = new Set((manifest.artifacts?.targets ?? [])
2342
+ .filter((target) => target.target === 'agent-skills.skill' && typeof target.skillKey === 'string')
2343
+ .map((target) => target.skillKey));
2344
+ const tempRoot = fs.mkdtempSync(path.join(os.tmpdir(), 'aw-static-portable-final-'));
2345
+ try {
2346
+ for (const entry of fs.readdirSync(rootDir, { withFileTypes: true })) {
2347
+ if (!entry.isDirectory() || dynamicKeys.has(entry.name))
2348
+ continue;
2349
+ validateRenderedSkillTree({
2350
+ entry: { state: 'present', content: { files: {} } },
2351
+ declaration: {
2352
+ id: `static:${entry.name}`,
2353
+ distribution: 'agent-skills',
2354
+ target: 'agent-skills.skill',
2355
+ skillKey: entry.name,
2356
+ sourceDirs: [`${portableRoot}/${entry.name}`],
2357
+ },
2358
+ fieldName: `static portable Skill "${entry.name}"`,
2359
+ pluginDir,
2360
+ manifest,
2361
+ runtimeImports,
2362
+ materializedRoot: path.join(tempRoot, entry.name),
2363
+ skillValidationTools,
2364
+ });
2365
+ }
2366
+ }
2367
+ finally {
2368
+ fs.rmSync(tempRoot, { recursive: true, force: true });
2369
+ }
2370
+ }
2371
+ function validateRenderedArtifactPlan(plan, declarations, scopeLabel, options) {
2372
+ const planField = `scripts.artifacts.render fixture (${scopeLabel})`;
2373
+ const root = expectRecord(plan, planField);
2374
+ if (!root)
2375
+ return;
2376
+ validateAllowedKeys(root, planField, ['version', 'artifacts']);
2377
+ if (root.version !== 2) {
2378
+ error(`${planField}.version must be 2`);
2379
+ }
2380
+ if (!Array.isArray(root.artifacts)) {
2381
+ error(`${planField}.artifacts must be an array`);
2382
+ return;
2383
+ }
2384
+ const byKey = new Map(declarations.map((target) => [`${target.id}:${target.target}`, target]));
2385
+ const returned = new Set();
2386
+ root.artifacts.forEach((artifact, index) => {
2387
+ const fieldName = `${planField}.artifacts[${index}]`;
2388
+ const entry = expectRecord(artifact, fieldName);
2389
+ if (!entry)
2390
+ return;
2391
+ validateAllowedKeys(entry, fieldName, [
2392
+ 'id',
2393
+ 'platform',
2394
+ 'distribution',
2395
+ 'target',
2396
+ 'kind',
2397
+ 'state',
2398
+ 'refreshKeys',
2399
+ 'disabledReason',
2400
+ 'roleKey',
2401
+ 'skillKey',
2402
+ 'content',
2403
+ ]);
2404
+ const id = validateArtifactId(entry.id, `${fieldName}.id`);
2405
+ const target = validateManifestString(entry.target, `${fieldName}.target`);
2406
+ const key = id && target ? `${id}:${target}` : null;
2407
+ const declaration = key ? byKey.get(key) : null;
2408
+ if (!declaration) {
2409
+ error(`${fieldName}: artifact "${key ?? '<unknown>'}" is not declared for ${scopeLabel}`);
2410
+ return;
2411
+ }
2412
+ if (returned.has(key)) {
2413
+ error(`${fieldName}: duplicate artifact id + target "${key}"`);
2414
+ }
2415
+ returned.add(key);
2416
+ if (declaration.distribution) {
2417
+ if (entry.distribution !== declaration.distribution) {
2418
+ error(`${fieldName}.distribution: expected "${declaration.distribution}"`);
2419
+ }
2420
+ if (entry.platform !== undefined) {
2421
+ error(`${fieldName}.platform: distribution artifacts do not support platform`);
2422
+ }
2423
+ }
2424
+ else if (entry.platform !== declaration.platform) {
2425
+ error(`${fieldName}.platform: expected "${declaration.platform}"`);
2426
+ }
2427
+ if (entry.kind !== declaration.kind) {
2428
+ error(`${fieldName}.kind: expected "${declaration.kind}"`);
2429
+ }
2430
+ if (!declaration.states.includes(entry.state)) {
2431
+ error(`${fieldName}.state: "${entry.state}" is not declared for artifact "${declaration.id}"`);
2432
+ }
2433
+ validateArtifactPlanRefreshKeys(entry.refreshKeys, declaration, fieldName);
2434
+ if (entry.state === 'present' && entry.content === undefined) {
2435
+ error(`${fieldName}.content is required when state is "present"`);
2436
+ }
2437
+ if (entry.disabledReason !== undefined &&
2438
+ (typeof entry.disabledReason !== 'string' || entry.disabledReason.trim() === '')) {
2439
+ error(`${fieldName}.disabledReason must be a non-empty string`);
2440
+ }
2441
+ if (declaration.target === 'codex.agentRole') {
2442
+ if (entry.roleKey !== declaration.roleKey) {
2443
+ error(`${fieldName}.roleKey: expected "${declaration.roleKey}" from static metadata`);
2444
+ }
2445
+ if (isRecord(entry.content)) {
2446
+ const registration = entry.content.registration;
2447
+ if (isRecord(registration) && registration.config_file !== undefined) {
2448
+ error(`${fieldName}.content.registration.config_file must be generated by AW, not renderer`);
2449
+ }
2450
+ const roleFile = entry.content.roleFile;
2451
+ if (isRecord(roleFile) && roleFile.name !== declaration.roleKey) {
2452
+ error(`${fieldName}.content.roleFile.name: expected "${declaration.roleKey}"`);
2453
+ }
2454
+ }
2455
+ }
2456
+ else if (entry.roleKey !== undefined) {
2457
+ error(`${fieldName}.roleKey is only supported for codex.agentRole artifacts`);
2458
+ }
2459
+ if (declaration.target === 'codex.skill' || declaration.target === 'claude.skill' || declaration.target === 'agent-skills.skill') {
2460
+ if (entry.skillKey !== declaration.skillKey) {
2461
+ error(`${fieldName}.skillKey: expected "${declaration.skillKey}" from static metadata`);
2462
+ }
2463
+ if (entry.state === 'present') {
2464
+ if (!isRecord(entry.content)) {
2465
+ error(`${fieldName}.content must be an object for dynamic skill artifacts`);
2466
+ }
2467
+ else {
2468
+ validateAllowedKeys(entry.content, `${fieldName}.content`, ['files']);
2469
+ const files = expectRecord(entry.content.files, `${fieldName}.content.files`);
2470
+ if (files) {
2471
+ const filePaths = Object.keys(files).sort();
2472
+ for (const [relativePath, content] of Object.entries(files)) {
2473
+ if (!isValidArtifactFilePath(relativePath)) {
2474
+ error(`${fieldName}.content.files path "${relativePath}" must be a normalized POSIX relative path`);
2475
+ }
2476
+ if (typeof content !== 'string') {
2477
+ error(`${fieldName}.content.files.${relativePath} must be a string`);
2478
+ }
2479
+ }
2480
+ for (const [pathIndex, relativePath] of filePaths.entries()) {
2481
+ const conflict = filePaths.slice(0, pathIndex).find((candidate) => relativePath.startsWith(`${candidate}/`));
2482
+ if (conflict) {
2483
+ error(`${fieldName}.content.files path "${conflict}" conflicts with "${relativePath}"`);
2484
+ }
2485
+ }
2486
+ }
2487
+ }
2488
+ validateRenderedSkillTree({
2489
+ entry,
2490
+ declaration,
2491
+ fieldName,
2492
+ pluginDir: options.pluginDir,
2493
+ manifest: options.manifest,
2494
+ runtimeImports: options.runtimeImports,
2495
+ materializedRoot: path.join(options.tempRoot, `${declaration.platform ?? declaration.distribution}-${scopeLabel.split('/')[1]}-${index}`),
2496
+ skillValidationTools: options.skillValidationTools,
2497
+ });
2498
+ }
2499
+ }
2500
+ else if (entry.skillKey !== undefined) {
2501
+ error(`${fieldName}.skillKey is only supported for dynamic skill artifacts`);
2502
+ }
2503
+ });
2504
+ for (const declaration of declarations) {
2505
+ const key = `${declaration.id}:${declaration.target}`;
2506
+ if (!returned.has(key)) {
2507
+ error(`${planField}: renderer must return artifact "${declaration.id}" target "${declaration.target}"`);
2508
+ }
2509
+ }
2510
+ }
2511
+ function runArtifactRendererFixture(pluginDir, manifest, renderEntry, declarations, resolvedRuntimeImports, skillValidationTools) {
2512
+ if (!renderEntry || declarations.length === 0)
2513
+ return;
2514
+ const surfaceScopes = [...new Set(declarations.flatMap((target) => target.scopes.map((scope) => `${target.platform ?? target.distribution}:${scope}`)))];
2515
+ const values = defaultConfigValues(manifest);
2516
+ const tempRoot = fs.mkdtempSync(path.join(os.tmpdir(), 'aw-artifact-render-'));
2517
+ try {
2518
+ for (const surfaceScope of surfaceScopes) {
2519
+ const [surface, scope] = surfaceScope.split(':');
2520
+ const distribution = surface === 'agent-skills' ? surface : undefined;
2521
+ const platform = distribution ? undefined : surface;
2522
+ const event = distribution ? 'materialize' : 'install';
2523
+ const scopedDeclarations = declarations.filter((target) => (distribution ? target.distribution === distribution : target.platform === platform)
2524
+ && target.scopes.includes(scope));
2525
+ const contextPath = path.join(tempRoot, `context-${surface}-${scope}.json`);
2526
+ const runtimeImports = scopedDeclarations.flatMap((target) => target.runtimeImports.map((runtimeImport, importIndex) => {
2527
+ const resolved = resolvedRuntimeImports?.artifactImports.get(authorRuntimeImportKey(target.id, importIndex));
2528
+ if (!resolved)
2529
+ return null;
2530
+ const importPath = path.join(tempRoot, `runtime-${target.id}-${importIndex}`);
2531
+ fs.writeFileSync(importPath, resolved.bytes);
2532
+ return {
2533
+ artifactId: target.id,
2534
+ name: runtimeImport.name,
2535
+ providerPluginId: resolved.providerPluginId,
2536
+ exportName: resolved.exportName,
2537
+ path: importPath,
2538
+ digest: resolved.digest,
2539
+ };
2540
+ }).filter(Boolean));
2541
+ fs.writeFileSync(contextPath, JSON.stringify({
2542
+ event,
2543
+ surface: distribution
2544
+ ? { kind: 'distribution', name: distribution }
2545
+ : { kind: 'platform', name: platform },
2546
+ ...(platform ? { platform } : {}),
2547
+ ...(distribution ? { distribution } : {}),
2548
+ scope,
2549
+ plugin: {
2550
+ name: manifest.name,
2551
+ version: manifest.version,
2552
+ rootDir: pluginDir,
2553
+ },
2554
+ config: {
2555
+ mode: 'artifact-render',
2556
+ targetScope: scope,
2557
+ schema: manifest.config?.fields ?? {},
2558
+ values,
2559
+ sources: Object.fromEntries(Object.keys(values).map((key) => [key, 'default'])),
2560
+ issues: [],
2561
+ },
2562
+ changedConfigKeys: [],
2563
+ requestedArtifactIds: scopedDeclarations.map((target) => target.id),
2564
+ previousArtifacts: [],
2565
+ artifactSources: scopedDeclarations.map((target) => ({
2566
+ id: target.id,
2567
+ target: target.target,
2568
+ sourceDirs: target.sourceDirs.map((sourceDir) => path.join(pluginDir, normalizeRelativePath(sourceDir))),
2569
+ })),
2570
+ runtimeImports,
2571
+ paths: {
2572
+ awHome: path.join(tempRoot, 'aw-home'),
2573
+ codexHome: path.join(tempRoot, 'codex-home'),
2574
+ claudeHome: path.join(tempRoot, 'claude-home'),
2575
+ manifestPath: path.join(pluginDir, '.agents-plugin', 'plugin.json'),
2576
+ configStores: {
2577
+ user: path.join(tempRoot, 'config-user.json'),
2578
+ project: path.join(tempRoot, 'config-project.json'),
2579
+ },
2580
+ },
2581
+ renderer: {
2582
+ runner: renderEntry.runner,
2583
+ path: renderEntry.path,
2584
+ args: renderEntry.args ?? [],
2585
+ manifestDigest: 'author-validator-fixture',
2586
+ rendererDigest: 'author-validator-fixture',
2587
+ },
2588
+ }), 'utf8');
2589
+ const rendererHome = path.join(tempRoot, 'home');
2590
+ const rendererTemp = path.join(tempRoot, 'tmp');
2591
+ fs.mkdirSync(rendererHome, { recursive: true });
2592
+ fs.mkdirSync(rendererTemp, { recursive: true });
2593
+ const rendererEnv = {
2594
+ AW_HOME: path.join(tempRoot, 'aw-home'),
2595
+ AW_CODEX_HOME: path.join(tempRoot, 'codex-home'),
2596
+ AW_CLAUDE_HOME: path.join(tempRoot, 'claude-home'),
2597
+ PATH: process.env.PATH ?? process.env.Path ?? '',
2598
+ AW_PLUGIN_CONTEXT: contextPath,
2599
+ AW_PLUGIN_ROOT: pluginDir,
2600
+ AW_PLUGIN_NAME: typeof manifest.name === 'string' ? manifest.name : '',
2601
+ AW_PLUGIN_VERSION: typeof manifest.version === 'string' ? manifest.version : '',
2602
+ AW_PLUGIN_EVENT: event,
2603
+ ...(platform ? { AW_PLUGIN_PLATFORM: platform } : {}),
2604
+ ...(distribution ? { AW_PLUGIN_DISTRIBUTION: distribution } : {}),
2605
+ AW_PLUGIN_SCOPE: scope,
2606
+ };
2607
+ if (process.platform === 'win32') {
2608
+ rendererEnv.USERPROFILE = rendererHome;
2609
+ rendererEnv.TEMP = rendererTemp;
2610
+ rendererEnv.TMP = rendererTemp;
2611
+ if (process.env.SystemRoot)
2612
+ rendererEnv.SystemRoot = process.env.SystemRoot;
2613
+ if (process.env.ComSpec)
2614
+ rendererEnv.ComSpec = process.env.ComSpec;
2615
+ }
2616
+ else {
2617
+ rendererEnv.HOME = rendererHome;
2618
+ rendererEnv.TMPDIR = rendererTemp;
2619
+ }
2620
+ const result = spawnSync(process.execPath, [path.join(pluginDir, renderEntry.path), ...(renderEntry.args ?? [])], {
2621
+ cwd: pluginDir,
2622
+ env: rendererEnv,
2623
+ encoding: 'utf8',
2624
+ timeout: 5000,
2625
+ maxBuffer: 1024 * 1024,
2626
+ });
2627
+ const fieldName = `scripts.artifacts.render fixture (${surface}/${scope})`;
2628
+ if (result.error) {
2629
+ error(`${fieldName} failed: ${result.error.message}`);
2630
+ continue;
2631
+ }
2632
+ if (result.status !== 0) {
2633
+ const stderr = String(result.stderr ?? '').trim().split('\n')[0] ?? '';
2634
+ error(`${fieldName} exited with code ${result.status}${stderr ? `: ${stderr}` : ''}`);
2635
+ continue;
2636
+ }
2637
+ let plan;
2638
+ try {
2639
+ plan = JSON.parse(result.stdout);
2640
+ }
2641
+ catch (e) {
2642
+ error(`${fieldName} stdout must be JSON ArtifactPlan: ${e.message}`);
2643
+ continue;
2644
+ }
2645
+ validateRenderedArtifactPlan(plan, scopedDeclarations, `${surface}/${scope}`, {
2646
+ pluginDir,
2647
+ manifest,
2648
+ runtimeImports: resolvedRuntimeImports,
2649
+ tempRoot,
2650
+ skillValidationTools,
2651
+ });
2652
+ }
2653
+ }
2654
+ finally {
2655
+ fs.rmSync(tempRoot, { recursive: true, force: true });
2656
+ }
2657
+ }
2658
+ function validateDynamicArtifactsLightweight(pluginDir, manifest, renderEntry, runtimeImports, skillValidationTools) {
2659
+ const declarations = validateArtifactsConfigLightweight(pluginDir, manifest);
2660
+ const hasTargets = declarations.length > 0;
2661
+ const hasRenderer = Boolean(manifest.scripts?.artifacts?.render);
2662
+ if (hasTargets && !hasRenderer) {
2663
+ error('artifacts.targets requires scripts.artifacts.render');
2664
+ }
2665
+ if (hasRenderer && !hasTargets) {
2666
+ error('scripts.artifacts.render requires artifacts.targets');
2667
+ }
2668
+ runArtifactRendererFixture(pluginDir, manifest, renderEntry, declarations, runtimeImports, skillValidationTools);
2669
+ }
2670
+ function validateScriptsLightweight(pluginDir, manifest) {
2671
+ validateConfigSchemaLightweight(manifest.config);
2672
+ if (manifest.scripts === undefined)
2673
+ return null;
2674
+ const scripts = expectRecord(manifest.scripts, 'scripts');
2675
+ if (!scripts)
2676
+ return null;
2677
+ validateAllowedKeys(scripts, 'scripts', ['postApply', 'helpers', 'node', 'artifacts', 'tests']);
2678
+ const runtimeNodeEntries = [];
2679
+ let artifactRenderEntry = null;
2680
+ let packageMeta = null;
2681
+ if (scripts.helpers !== undefined) {
2682
+ const helpers = expectRecord(scripts.helpers, 'scripts.helpers');
2683
+ if (helpers) {
2684
+ validateAllowedKeys(helpers, 'scripts.helpers', ['config']);
2685
+ const helperPath = normalizePluginScriptPath(pluginDir, helpers.config, 'scripts.helpers.config');
2686
+ validateDeclaredScriptFile(pluginDir, helperPath, 'scripts.helpers.config');
2687
+ if (helperPath && !isNodeRunnablePath(helperPath)) {
2688
+ error('scripts.helpers.config must use a Node runnable extension (.js, .mjs, or .cjs)');
2689
+ }
2690
+ if (helperPath)
2691
+ runtimeNodeEntries.push({ path: helperPath, fieldName: 'scripts.helpers.config' });
2692
+ }
2693
+ }
2694
+ if (scripts.postApply !== undefined) {
2695
+ const postApply = expectRecord(scripts.postApply, 'scripts.postApply');
2696
+ if (postApply) {
2697
+ validateAllowedKeys(postApply, 'scripts.postApply', ['path', 'timeoutMs']);
2698
+ const postApplyPath = normalizePluginScriptPath(pluginDir, postApply.path, 'scripts.postApply.path');
2699
+ validateDeclaredScriptFile(pluginDir, postApplyPath, 'scripts.postApply.path');
2700
+ if (postApplyPath && !isNodeRunnablePath(postApplyPath)) {
2701
+ error('scripts.postApply.path must use a Node runnable extension (.js, .mjs, or .cjs)');
2702
+ }
2703
+ if (postApply.timeoutMs !== undefined && (!Number.isInteger(postApply.timeoutMs)
2704
+ || postApply.timeoutMs < SCRIPT_TIMEOUT_MIN_MS || postApply.timeoutMs > SCRIPT_TIMEOUT_MAX_MS)) {
2705
+ error(`scripts.postApply.timeoutMs must be an integer between ${SCRIPT_TIMEOUT_MIN_MS} and ${SCRIPT_TIMEOUT_MAX_MS}`);
2706
+ }
2707
+ if (postApplyPath)
2708
+ runtimeNodeEntries.push({ path: postApplyPath, fieldName: 'scripts.postApply.path' });
2709
+ }
2710
+ }
2711
+ if (scripts.node !== undefined) {
2712
+ const node = expectRecord(scripts.node, 'scripts.node');
2713
+ if (node) {
2714
+ validateAllowedKeys(node, 'scripts.node', ['packageRoot', 'build']);
2715
+ if (node.packageRoot !== undefined) {
2716
+ packageMeta = validatePackageRoot(pluginDir, node.packageRoot, 'scripts.node.packageRoot');
2717
+ }
2718
+ if (node.build !== undefined) {
2719
+ const buildEntry = validateScriptEntry(pluginDir, node.build, 'scripts.node.build', {
2720
+ requireNodeRunner: true,
2721
+ requireNodePath: true,
2722
+ });
2723
+ if (buildEntry) {
2724
+ scanNodeImportContract(pluginDir, [buildEntry.path], {
2725
+ label: 'scripts.node.build import contract',
2726
+ packageMeta,
2727
+ allowDevDependencies: true,
2728
+ });
2729
+ }
2730
+ }
2731
+ }
2732
+ }
2733
+ if (scripts.artifacts !== undefined) {
2734
+ const artifacts = expectRecord(scripts.artifacts, 'scripts.artifacts');
2735
+ if (artifacts) {
2736
+ validateAllowedKeys(artifacts, 'scripts.artifacts', ['render']);
2737
+ if (artifacts.render !== undefined) {
2738
+ artifactRenderEntry = validateScriptEntry(pluginDir, artifacts.render, 'scripts.artifacts.render', {
2739
+ requireNodeRunner: true,
2740
+ requireNodePath: true,
2741
+ });
2742
+ if (artifactRenderEntry) {
2743
+ runtimeNodeEntries.push({
2744
+ path: artifactRenderEntry.path,
2745
+ fieldName: 'scripts.artifacts.render.path',
2746
+ });
2747
+ }
2748
+ }
2749
+ }
2750
+ }
2751
+ if (scripts.tests !== undefined) {
2752
+ const tests = expectRecord(scripts.tests, 'scripts.tests');
2753
+ if (tests) {
2754
+ validateAllowedKeys(tests, 'scripts.tests', ['node']);
2755
+ if (tests.node !== undefined) {
2756
+ if (!Array.isArray(tests.node)) {
2757
+ error('scripts.tests.node must be an array of glob strings');
2758
+ }
2759
+ else {
2760
+ const allFiles = listFilesRecursive(pluginDir);
2761
+ const testEntries = [];
2762
+ tests.node.forEach((pattern, index) => {
2763
+ if (typeof pattern !== 'string' || pattern.trim() === '') {
2764
+ error(`scripts.tests.node[${index}] must be a non-empty string`);
2765
+ return;
2766
+ }
2767
+ for (const filePath of allFiles) {
2768
+ if (matchesGlob(filePath, pattern)) {
2769
+ testEntries.push(filePath);
2770
+ }
2771
+ }
2772
+ });
2773
+ scanNodeImportContract(pluginDir, testEntries, {
2774
+ label: 'scripts.tests.node import contract',
2775
+ packageMeta,
2776
+ allowDevDependencies: true,
2777
+ });
2778
+ }
2779
+ }
2780
+ }
2781
+ }
2782
+ scanNodeImportContract(pluginDir, runtimeNodeEntries.map((entry) => entry.path), {
2783
+ label: 'runtime Node import contract',
2784
+ packageMeta,
2785
+ allowDevDependencies: false,
2786
+ });
2787
+ return artifactRenderEntry;
2788
+ }
2789
+ function validateMcpContent(pluginDir, manifest) {
2790
+ if (!manifest.mcpServers)
2791
+ return;
2792
+ if (isTemplateAsset(manifest, manifest.mcpServers))
2793
+ return;
2794
+ const mcpPath = path.join(pluginDir, manifest.mcpServers);
2795
+ if (!fs.existsSync(mcpPath))
2796
+ return;
2797
+ try {
2798
+ const content = JSON.parse(fs.readFileSync(mcpPath, 'utf8'));
2799
+ if (!content.mcpServers || typeof content.mcpServers !== 'object') {
2800
+ error(`${manifest.mcpServers} must have a "mcpServers" top-level key`);
2801
+ }
2802
+ }
2803
+ catch (e) {
2804
+ error(`${manifest.mcpServers} is not valid JSON: ${e.message}`);
2805
+ }
2806
+ }
2807
+ function validateAppsContent(pluginDir, manifest) {
2808
+ if (!manifest.apps)
2809
+ return;
2810
+ if (isTemplateAsset(manifest, manifest.apps))
2811
+ return;
2812
+ const appsPath = path.join(pluginDir, manifest.apps);
2813
+ if (!fs.existsSync(appsPath))
2814
+ return;
2815
+ try {
2816
+ const content = JSON.parse(fs.readFileSync(appsPath, 'utf8'));
2817
+ if (!content.apps || typeof content.apps !== 'object') {
2818
+ error(`${manifest.apps} must have an "apps" top-level key`);
2819
+ }
2820
+ }
2821
+ catch (e) {
2822
+ error(`${manifest.apps} is not valid JSON: ${e.message}`);
2823
+ }
2824
+ }
2825
+ function hasCodexRepoManagedSurface(manifest) {
2826
+ if (manifest.skills || manifest.slashCommands || manifest.mcpServers) {
2827
+ return true;
2828
+ }
2829
+ if ((manifest.artifacts?.targets ?? []).some((target) => target?.platform === 'codex' &&
2830
+ Array.isArray(target.scopes) &&
2831
+ target.scopes.includes('project') &&
2832
+ typeof target.projectManagedKind === 'string')) {
2833
+ return true;
2834
+ }
2835
+ const extensions = manifest.extensions;
2836
+ if (!extensions || typeof extensions !== 'object' || Array.isArray(extensions)) {
2837
+ return false;
2838
+ }
2839
+ return ['instructions', 'permissions', 'hooks', 'agents'].some((key) => Array.isArray(extensions[key]) && extensions[key].length > 0) || (extensions.nativeHooks &&
2840
+ typeof extensions.nativeHooks === 'object' &&
2841
+ !Array.isArray(extensions.nativeHooks) &&
2842
+ Array.isArray(extensions.nativeHooks.codex) &&
2843
+ extensions.nativeHooks.codex.length > 0);
2844
+ }
2845
+ function warnCodexProjectScopeLimitations(manifest) {
2846
+ if (!isCodexTargeted(manifest)) {
2847
+ return;
2848
+ }
2849
+ if (manifest.apps) {
2850
+ warn('Codex project scope does not support apps; users must install this app surface with `aw install <plugin> -p codex -s user` or split the plugin.');
2851
+ }
2852
+ if (!hasCodexRepoManagedSurface(manifest)) {
2853
+ warn('This Codex-targeted plugin has no repo-managed project surface; Codex project scope will fail fast and only Codex user native install is applicable.');
2854
+ }
2855
+ }
2856
+ function validateExtensionNameUniqueness(manifest) {
2857
+ if (!manifest.extensions)
2858
+ return;
2859
+ for (const extType of ['instructions', 'permissions', 'hooks', 'agents']) {
2860
+ const items = manifest.extensions[extType];
2861
+ if (!Array.isArray(items))
2862
+ continue;
2863
+ const names = new Set();
2864
+ for (const item of items) {
2865
+ if (item.name) {
2866
+ if (names.has(item.name)) {
2867
+ error(`extensions.${extType} has duplicate name: "${item.name}"`);
2868
+ }
2869
+ names.add(item.name);
2870
+ }
2871
+ }
2872
+ }
2873
+ }
2874
+ function validateOpenAiYaml(openaiYamlPath, skillName, required, manifest, pluginDir, skillValidationTools) {
2875
+ const fieldName = `skills/${skillName}/agents/openai.yaml`;
2876
+ if (!fs.existsSync(openaiYamlPath)) {
2877
+ if (required) {
2878
+ error(`${fieldName} not found; Codex-targeted skills must declare Codex trigger policy`);
2879
+ }
2880
+ else {
2881
+ warn(`${fieldName} not found; this is acceptable only for non-Codex skills`);
2882
+ }
2883
+ return;
2884
+ }
2885
+ if (!skillValidationTools) {
2886
+ error(`${fieldName} cannot be validated because the shared CLI Skill validator is unavailable`);
2887
+ return;
2888
+ }
2889
+ try {
2890
+ const relativePath = path.relative(pluginDir, openaiYamlPath);
2891
+ const rawContent = fs.readFileSync(openaiYamlPath, 'utf8');
2892
+ const validation = skillValidationTools.validateCodexMetadata(renderTemplateForPlatform(manifest, relativePath, rawContent, 'codex'), skillName, fieldName);
2893
+ for (const entry of validation.errors) {
2894
+ error(`${entry.path} [${entry.code}] ${entry.message}`);
2895
+ }
2896
+ const skillRoot = path.dirname(path.dirname(openaiYamlPath));
2897
+ for (const assetPath of validation.assetPaths) {
2898
+ const absoluteAssetPath = path.join(skillRoot, ...assetPath.split('/'));
2899
+ const stats = fs.lstatSync(absoluteAssetPath, { throwIfNoEntry: false });
2900
+ if (!stats?.isFile() || stats.isSymbolicLink()) {
2901
+ error(`${fieldName} references missing regular file "${assetPath}"`);
2902
+ }
2903
+ }
2904
+ }
2905
+ catch (e) {
2906
+ error(`${fieldName} shared validation failed: ${e.message}`);
2907
+ }
2908
+ }
2909
+ function validateSkills(pluginDir, manifest, options, skillValidationTools) {
2910
+ if (!manifest.skills)
2911
+ return;
2912
+ const skillsDir = path.join(pluginDir, manifest.skills);
2913
+ if (!fs.existsSync(skillsDir))
2914
+ return;
2915
+ const requiresCodexMetadata = isCodexTargeted(manifest);
2916
+ const targetsClaude = isClaudeTargeted(manifest);
2917
+ const skillDirs = fs
2918
+ .readdirSync(skillsDir, { withFileTypes: true })
2919
+ .filter((d) => d.isDirectory());
2920
+ if (skillDirs.length === 0) {
2921
+ error('skills directory exists but contains no skill subdirectories');
2922
+ }
2923
+ for (const dir of skillDirs) {
2924
+ const skillPath = path.join(skillsDir, dir.name);
2925
+ const skillMdPath = path.join(skillPath, 'SKILL.md');
2926
+ const openaiYamlPath = path.join(skillPath, 'agents', 'openai.yaml');
2927
+ const skillMdRelativePath = path.relative(pluginDir, skillMdPath);
2928
+ if (!fs.existsSync(skillMdPath)) {
2929
+ error(`skills/${dir.name}/SKILL.md not found`);
2930
+ continue;
2931
+ }
2932
+ const content = fs.readFileSync(skillMdPath, 'utf8');
2933
+ const lineCount = countLines(content);
2934
+ if (lineCount >= MAX_SKILL_LINES) {
2935
+ warn(`skills/${dir.name}/SKILL.md has ${lineCount} lines; Agent Skills recommends keeping SKILL.md under ${MAX_SKILL_LINES} lines`);
2936
+ }
2937
+ const variants = renderedContentVariants(manifest, skillMdRelativePath, content, targetedPlatforms(manifest));
2938
+ for (const variant of variants) {
2939
+ const sourceName = variant.platform
2940
+ ? `skills/${dir.name}/SKILL.md (${variant.platform} render)`
2941
+ : `skills/${dir.name}/SKILL.md`;
2942
+ if (!skillValidationTools) {
2943
+ error(`${sourceName} cannot be validated because the shared CLI Skill validator is unavailable`);
2944
+ }
2945
+ else {
2946
+ const parsed = skillValidationTools.parseSkillFrontmatter(variant.content, sourceName);
2947
+ for (const entry of parsed.errors) {
2948
+ error(`${entry.path} [${entry.code}] ${entry.message}`);
2949
+ }
2950
+ if (parsed.frontmatter) {
2951
+ const profile = options.strictAgentSkills || !targetsClaude
2952
+ ? 'portable-agent-skills'
2953
+ : options.claudeSkillProfile === 'current'
2954
+ ? 'claude-current'
2955
+ : 'claude-2.1.88';
2956
+ const diagnostics = skillValidationTools.validateSkillFrontmatter(parsed.frontmatter, {
2957
+ profile,
2958
+ expectedName: dir.name,
2959
+ sourcePath: sourceName,
2960
+ });
2961
+ for (const entry of diagnostics) {
2962
+ error(`${entry.path} [${entry.code}] ${entry.message}`);
2963
+ }
2964
+ }
2965
+ }
2966
+ }
2967
+ validateOpenAiYaml(openaiYamlPath, dir.name, requiresCodexMetadata, manifest, pluginDir, skillValidationTools);
2968
+ if (/\[TODO[:\]]/i.test(content)) {
2969
+ error(`skills/${dir.name}/SKILL.md still contains TODO placeholders`);
2970
+ }
2971
+ }
2972
+ }
2973
+ function detectCodexSlashCommandForbiddenSyntax(content) {
2974
+ const checks = [
2975
+ [/\$ARGUMENTS\b/, '$ARGUMENTS'],
2976
+ [/\$\d+\b/, '$1'],
2977
+ [/```!/, '```!'],
2978
+ [/!`[^`\r\n]+`/, '!`command`'],
2979
+ ];
2980
+ for (const [pattern, label] of checks) {
2981
+ if (pattern.test(content)) {
2982
+ return label;
2983
+ }
2984
+ }
2985
+ return null;
2986
+ }
2987
+ function validateSlashCommandAssetReference(commandRoot, commandRelativePath, value, fieldName) {
2988
+ if (value === undefined)
2989
+ return;
2990
+ validateCodexIconPath({ [fieldName]: value }, fieldName, `${commandRelativePath}.codex.interface`);
2991
+ if (typeof value !== 'string' || value.trim().length === 0)
2992
+ return;
2993
+ const normalized = normalizeRelativePath(stripDotSlash(value));
2994
+ const absolutePath = path.join(commandRoot, normalized);
2995
+ const stats = fs.statSync(absolutePath, { throwIfNoEntry: false });
2996
+ if (!stats) {
2997
+ error(`${commandRelativePath}.codex.interface.${fieldName} references missing asset "${value}"`);
2998
+ return;
2999
+ }
3000
+ if (!stats.isFile()) {
3001
+ error(`${commandRelativePath}.codex.interface.${fieldName} must reference a file, got "${value}"`);
3002
+ }
3003
+ }
3004
+ function validateSlashCommandFrontmatter(commandRoot, commandRelativePath, frontmatter, platform) {
3005
+ const fieldName = `${commandRelativePath} frontmatter`;
3006
+ const fm = expectRecord(frontmatter, fieldName);
3007
+ if (!fm)
3008
+ return;
3009
+ for (const key of Object.keys(fm)) {
3010
+ if (CLAUDE_SLASH_COMMAND_ONLY_FIELDS.has(key)) {
3011
+ error(`${fieldName}: "${key}" must be nested under "claude"`);
3012
+ }
3013
+ }
3014
+ validateAllowedKeys(fm, fieldName, ['description', 'claude', 'codex']);
3015
+ validateNonEmptyString(fm.description, `${fieldName}.description`, MAX_SKILL_DESCRIPTION_LEN);
3016
+ if (platform === 'claude' && fm.claude !== undefined) {
3017
+ const claudeBlock = expectRecord(fm.claude, `${fieldName}.claude`);
3018
+ if (claudeBlock) {
3019
+ validateAllowedKeys(claudeBlock, `${fieldName}.claude`, [
3020
+ 'description',
3021
+ 'allowed-tools',
3022
+ 'model',
3023
+ 'argument-hint',
3024
+ 'shell',
3025
+ ]);
3026
+ if (claudeBlock.description !== undefined) {
3027
+ validateNonEmptyString(claudeBlock.description, `${fieldName}.claude.description`, MAX_SKILL_DESCRIPTION_LEN);
3028
+ }
3029
+ if (claudeBlock['allowed-tools'] !== undefined) {
3030
+ validateAllowedTools(claudeBlock['allowed-tools'], `${fieldName}.claude.allowed-tools`, { allowArray: true });
3031
+ }
3032
+ if (claudeBlock.model !== undefined) {
3033
+ validateNonEmptyString(claudeBlock.model, `${fieldName}.claude.model`);
3034
+ }
3035
+ if (claudeBlock['argument-hint'] !== undefined) {
3036
+ validateNonEmptyString(claudeBlock['argument-hint'], `${fieldName}.claude.argument-hint`);
3037
+ }
3038
+ if (claudeBlock.shell !== undefined) {
3039
+ if (typeof claudeBlock.shell !== 'string') {
3040
+ error(`${fieldName}.claude.shell must be a string`);
3041
+ }
3042
+ else if (!CLAUDE_FRONTMATTER_SHELLS.has(claudeBlock.shell.trim().toLowerCase())) {
3043
+ error(`${fieldName}.claude.shell must be "bash" or "powershell"`);
3044
+ }
3045
+ }
3046
+ }
3047
+ }
3048
+ if (platform === 'codex' && fm.codex !== undefined) {
3049
+ const codexBlock = expectRecord(fm.codex, `${fieldName}.codex`);
3050
+ if (codexBlock) {
3051
+ if (codexBlock.policy !== undefined) {
3052
+ error(`${fieldName}.codex.policy is not supported; generated slashCommands skills are always manual-only`);
3053
+ }
3054
+ validateAllowedKeys(codexBlock, `${fieldName}.codex`, ['description', 'interface']);
3055
+ if (codexBlock.description !== undefined) {
3056
+ validateNonEmptyString(codexBlock.description, `${fieldName}.codex.description`, MAX_SKILL_DESCRIPTION_LEN);
3057
+ }
3058
+ if (codexBlock.interface !== undefined) {
3059
+ const interfaceBlock = expectRecord(codexBlock.interface, `${fieldName}.codex.interface`);
3060
+ if (interfaceBlock) {
3061
+ validateAllowedKeys(interfaceBlock, `${fieldName}.codex.interface`, [
3062
+ 'display_name',
3063
+ 'short_description',
3064
+ 'icon_small',
3065
+ 'icon_large',
3066
+ 'brand_color',
3067
+ 'default_prompt',
3068
+ ]);
3069
+ validateCodexMetadataString(interfaceBlock, 'display_name', `${fieldName}.codex.interface`, MAX_OPENAI_INTERFACE_NAME_LEN);
3070
+ validateCodexShortDescription(interfaceBlock, `${fieldName}.codex.interface`);
3071
+ validateCodexDefaultPrompt(interfaceBlock, 'default_prompt', `${fieldName}.codex.interface`, MAX_OPENAI_DEFAULT_PROMPT_LEN, path.basename(commandRelativePath, path.extname(commandRelativePath)));
3072
+ validateCodexBrandColor(interfaceBlock, 'brand_color', `${fieldName}.codex.interface`);
3073
+ validateSlashCommandAssetReference(commandRoot, commandRelativePath, interfaceBlock.icon_small, 'icon_small');
3074
+ validateSlashCommandAssetReference(commandRoot, commandRelativePath, interfaceBlock.icon_large, 'icon_large');
3075
+ }
3076
+ }
3077
+ }
3078
+ }
3079
+ }
3080
+ function validateSlashCommands(pluginDir, manifest) {
3081
+ const defaultSlashCommandsDir = path.join(pluginDir, DEFAULT_SLASH_COMMANDS_DIR);
3082
+ if (fs.existsSync(defaultSlashCommandsDir) && !manifest.slashCommands) {
3083
+ error(`"${DEFAULT_SLASH_COMMANDS_DIR}" exists but manifest does not declare "slashCommands"`);
3084
+ }
3085
+ if (!manifest.slashCommands)
3086
+ return;
3087
+ const targetPlatforms = resolveSupportedPlatforms(manifest);
3088
+ const slashCommandsRoot = path.join(pluginDir, manifest.slashCommands);
3089
+ const stats = fs.statSync(slashCommandsRoot, { throwIfNoEntry: false });
3090
+ if (!stats) {
3091
+ error(`slashCommands points to "${manifest.slashCommands}" but path does not exist`);
3092
+ return;
3093
+ }
3094
+ if (!stats.isDirectory()) {
3095
+ error(`slashCommands must point to a directory, got "${manifest.slashCommands}"`);
3096
+ return;
3097
+ }
3098
+ const skillNames = new Set();
3099
+ if (manifest.skills) {
3100
+ const skillsRoot = path.join(pluginDir, manifest.skills);
3101
+ if (fs.existsSync(skillsRoot)) {
3102
+ for (const entry of fs.readdirSync(skillsRoot, { withFileTypes: true })) {
3103
+ if (entry.isDirectory()) {
3104
+ skillNames.add(entry.name);
3105
+ }
3106
+ }
3107
+ }
3108
+ }
3109
+ const seenCommands = new Set();
3110
+ const commandFiles = [];
3111
+ for (const entry of fs.readdirSync(slashCommandsRoot, { withFileTypes: true })) {
3112
+ const relativePath = normalizeRelativePath(path.join(stripDotSlash(manifest.slashCommands), entry.name));
3113
+ if (entry.isDirectory()) {
3114
+ if (entry.name !== 'assets') {
3115
+ error(`slashCommands does not support nested directory "${relativePath}"; only root *.md files and assets/ are allowed`);
3116
+ }
3117
+ continue;
3118
+ }
3119
+ if (!entry.isFile()) {
3120
+ error(`slashCommands has unsupported entry "${relativePath}"`);
3121
+ continue;
3122
+ }
3123
+ if (path.posix.extname(entry.name) !== '.md') {
3124
+ error(`slashCommands only accepts root *.md files; found "${relativePath}"`);
3125
+ continue;
3126
+ }
3127
+ commandFiles.push(entry.name);
3128
+ }
3129
+ if (commandFiles.length === 0) {
3130
+ error(`slashCommands "${manifest.slashCommands}" must contain at least one root *.md command file`);
3131
+ return;
3132
+ }
3133
+ for (const fileName of commandFiles.sort()) {
3134
+ const commandName = path.posix.basename(fileName, '.md');
3135
+ const commandRelativePath = normalizeRelativePath(path.join(stripDotSlash(manifest.slashCommands), fileName));
3136
+ if (commandName.length === 0 ||
3137
+ commandName.length > 64 ||
3138
+ !SLASH_COMMAND_NAME_PATTERN.test(commandName)) {
3139
+ error(`${commandRelativePath} command name must use lowercase hyphen-case and be <= 64 characters`);
3140
+ continue;
3141
+ }
3142
+ if (seenCommands.has(commandName)) {
3143
+ error(`slashCommands has duplicate command name "${commandName}"`);
3144
+ continue;
3145
+ }
3146
+ if (skillNames.has(commandName)) {
3147
+ error(`slashCommands command "${commandName}" conflicts with source skill "${commandName}"`);
3148
+ continue;
3149
+ }
3150
+ seenCommands.add(commandName);
3151
+ const absolutePath = path.join(slashCommandsRoot, fileName);
3152
+ const rawContent = fs.readFileSync(absolutePath, 'utf8');
3153
+ for (const platform of ['claude', 'codex']) {
3154
+ if (!targetPlatforms.has(platform))
3155
+ continue;
3156
+ const rendered = renderTemplateForPlatform(manifest, commandRelativePath, rawContent, platform);
3157
+ if (platform === 'codex') {
3158
+ const codexForbiddenSyntax = detectCodexSlashCommandForbiddenSyntax(rendered);
3159
+ if (codexForbiddenSyntax) {
3160
+ error(`${commandRelativePath} Codex render still contains Claude-only syntax "${codexForbiddenSyntax}"`);
3161
+ }
3162
+ }
3163
+ let frontmatter;
3164
+ try {
3165
+ frontmatter = parseFrontmatter(rendered, `${commandRelativePath} (${platform} render)`);
3166
+ }
3167
+ catch (parseError) {
3168
+ error(`${commandRelativePath} (${platform} render) has invalid YAML frontmatter: ${parseError.message}`);
3169
+ continue;
3170
+ }
3171
+ if (!frontmatter) {
3172
+ error(`${commandRelativePath} (${platform} render) is missing YAML frontmatter`);
3173
+ continue;
3174
+ }
3175
+ validateSlashCommandFrontmatter(slashCommandsRoot, commandRelativePath, frontmatter, platform);
3176
+ }
3177
+ }
3178
+ }
3179
+ // ---------------------------------------------------------------------------
3180
+ // Main
3181
+ // ---------------------------------------------------------------------------
3182
+ function printUsage() {
3183
+ console.log(`Usage:
3184
+ aw plugin validate <plugin-directory> [options]
3185
+
3186
+ Options:
3187
+ --strict-agent-skills Allow only Agent Skills portable core frontmatter.
3188
+ --claude-skill-profile <minimum|current>
3189
+ Validate Claude fields at AW minimum 2.1.88 (default) or current docs.
3190
+ --version-base <git-ref> Compare the production bundle against this Git base. Default: HEAD.
3191
+ --workspace-root <path> Workspace root. Default: current directory.
3192
+ --json Emit one machine-readable JSON result to stdout.
3193
+ -h, --help Show this help message.
3194
+ `);
3195
+ }
3196
+ function exitCliError(message, json) {
3197
+ if (json) {
3198
+ console.log(JSON.stringify({
3199
+ ok: false,
3200
+ profile: 'unknown',
3201
+ warnings: [],
3202
+ errors: [message],
3203
+ }, null, 2));
3204
+ }
3205
+ else {
3206
+ console.error(message);
3207
+ }
3208
+ process.exit(1);
3209
+ }
3210
+ async function validatePluginDir(pluginDir, options) {
3211
+ const manifestPath = path.join(pluginDir, '.agents-plugin', 'plugin.json');
3212
+ const cliManifestTools = await tryLoadCliManifestTools();
3213
+ if (!cliManifestTools
3214
+ || typeof cliManifestTools.assertPluginInputTree !== 'function'
3215
+ || typeof cliManifestTools.validateSourcePluginManifest !== 'function') {
3216
+ error(`Plugin manifest contract v${SOURCE_PLUGIN_MANIFEST_CONTRACT_VERSION} is unavailable; install a complete current aw CLI and retry.`);
3217
+ return;
3218
+ }
3219
+ try {
3220
+ await cliManifestTools.assertPluginInputTree(pluginDir);
3221
+ }
3222
+ catch (e) {
3223
+ error(e.message);
3224
+ return;
3225
+ }
3226
+ if (!fs.existsSync(manifestPath)) {
3227
+ error('.agents-plugin/plugin.json not found');
3228
+ return;
3229
+ }
3230
+ let manifest;
3231
+ try {
3232
+ manifest = JSON.parse(fs.readFileSync(manifestPath, 'utf8'));
3233
+ }
3234
+ catch (e) {
3235
+ error(`.agents-plugin/plugin.json is not valid JSON: ${e.message}`);
3236
+ return;
3237
+ }
3238
+ if (options.enforceCanonicalRoot
3239
+ && typeof manifest?.name === 'string'
3240
+ && manifest.name !== '') {
3241
+ try {
3242
+ assertCanonicalAuthoringPluginRoot({
3243
+ workspaceRoot: options.repoRoot,
3244
+ pluginRoot: pluginDir,
3245
+ pluginName: manifest.name,
3246
+ requireManifest: true,
3247
+ });
3248
+ }
3249
+ catch (cause) {
3250
+ error(cause.message);
3251
+ return;
3252
+ }
3253
+ }
3254
+ const skillValidationTools = await tryLoadCliSkillValidationTools();
3255
+ try {
3256
+ const normalizedManifest = await cliManifestTools.validateSourcePluginManifest(pluginDir, manifest);
3257
+ const requirements = await cliManifestTools.resolvePluginRequirements({
3258
+ pluginRoot: pluginDir,
3259
+ manifest: normalizedManifest,
3260
+ implementedCapabilities: cliManifestTools.implementedCapabilities,
3261
+ });
3262
+ if (requirements.unsupportedByCurrentAw.length > 0) {
3263
+ capabilityDiagnostic = {
3264
+ errorCode: 'awCapabilityUnsupported',
3265
+ missingCapabilities: requirements.unsupportedByCurrentAw,
3266
+ availableCapabilities: [...cliManifestTools.implementedCapabilities].sort(),
3267
+ };
3268
+ error(`[awCapabilityUnsupported] missingCapabilities=${JSON.stringify(requirements.unsupportedByCurrentAw)}`);
3269
+ }
3270
+ const satisfiedCapabilities = new Set([...requirements.declared, ...requirements.derived]);
3271
+ const advisoryObservations = requirements.observations.filter((observation) => (observation.code !== 'aw-command-detected'
3272
+ || observation.capability === undefined
3273
+ || !satisfiedCapabilities.has(observation.capability)));
3274
+ for (const observation of advisoryObservations) {
3275
+ warn(`[awCapabilityObservation] ${observation.path}: ${observation.message}`);
3276
+ }
3277
+ }
3278
+ catch (e) {
3279
+ error(e.message);
3280
+ }
3281
+ validatePlatformFieldSupport(manifest);
3282
+ validatePortableNativeArtifactCapabilityLightweight(manifest);
3283
+ validateNameMatchesDirectory(pluginDir, manifest);
3284
+ validateNoBuildOutputDirs(pluginDir);
3285
+ validateDeclaredNativeAssets(pluginDir, manifest);
3286
+ validateCanonicalSkillLayout(pluginDir, manifest);
3287
+ await validatePluginEvalManifest(pluginDir, manifest);
3288
+ const artifactRenderEntry = validateScriptsLightweight(pluginDir, manifest);
3289
+ const runtimeImports = await resolveAuthorRuntimeImports({
3290
+ pluginDir,
3291
+ manifest,
3292
+ repoRoot: options.repoRoot,
3293
+ cliManifestTools,
3294
+ });
3295
+ validateStaticPortableFinalTrees(pluginDir, manifest, runtimeImports, skillValidationTools);
3296
+ validateDynamicArtifactsLightweight(pluginDir, manifest, artifactRenderEntry, runtimeImports, skillValidationTools);
3297
+ validateMcpContent(pluginDir, manifest);
3298
+ validateAppsContent(pluginDir, manifest);
3299
+ warnCodexProjectScopeLimitations(manifest);
3300
+ validateExtensionNameUniqueness(manifest);
3301
+ validateSkills(pluginDir, manifest, options, skillValidationTools);
3302
+ validateSlashCommands(pluginDir, manifest);
3303
+ if (errors.length === 0) {
3304
+ const repoRoot = resolveCanonicalRepoRoot(pluginDir, manifest.name ?? '', options.gitRoot);
3305
+ if (repoRoot) {
3306
+ try {
3307
+ pluginVersionCheckResult = await checkPluginVersions({
3308
+ repoRoot,
3309
+ cliPackageRoot: CLI_PACKAGE_ROOT,
3310
+ base: options.versionBase,
3311
+ pluginNames: [manifest.name],
3312
+ });
3313
+ const check = pluginVersionCheckResult.checks[0];
3314
+ for (const message of check?.warnings ?? []) {
3315
+ warn(`plugin version check: ${message}`);
3316
+ }
3317
+ for (const message of check?.errors ?? []) {
3318
+ error(`plugin version check: ${message}`);
3319
+ }
3320
+ }
3321
+ catch (versionError) {
3322
+ if (versionError?.code === 'bundlerUnavailable'
3323
+ || versionError?.code === 'gitUnavailable') {
3324
+ warn(`plugin version check skipped: ${versionError.message}`);
3325
+ }
3326
+ else {
3327
+ error(`plugin version check failed: ${versionError.message}`);
3328
+ }
3329
+ }
3330
+ }
3331
+ }
3332
+ }
3333
+ function parseArgs(argv) {
3334
+ const args = argv.slice(2);
3335
+ const options = {
3336
+ pluginDir: null,
3337
+ strictAgentSkills: false,
3338
+ claudeSkillProfile: 'minimum',
3339
+ versionBase: 'HEAD',
3340
+ workspaceRoot: null,
3341
+ json: args.includes('--json'),
3342
+ };
3343
+ for (let index = 0; index < args.length; index += 1) {
3344
+ const arg = args[index];
3345
+ if (arg === '-h' || arg === '--help') {
3346
+ printUsage();
3347
+ process.exit(0);
3348
+ }
3349
+ if (arg === '--json') {
3350
+ continue;
3351
+ }
3352
+ if (arg === '--strict-agent-skills') {
3353
+ options.strictAgentSkills = true;
3354
+ continue;
3355
+ }
3356
+ if (arg === '--claude-skill-profile') {
3357
+ const value = args[index + 1];
3358
+ if (!value || value.startsWith('--')) {
3359
+ exitCliError('--claude-skill-profile requires a value.', options.json);
3360
+ }
3361
+ index += 1;
3362
+ if (value !== 'minimum' && value !== 'current') {
3363
+ exitCliError(`Invalid --claude-skill-profile: expected "minimum" or "current". Received ${JSON.stringify(value)}.`, options.json);
3364
+ }
3365
+ options.claudeSkillProfile = value;
3366
+ continue;
3367
+ }
3368
+ if (arg === '--version-base') {
3369
+ const value = args[index + 1];
3370
+ if (!value || value.startsWith('--')) {
3371
+ exitCliError('--version-base requires a value.', options.json);
3372
+ }
3373
+ index += 1;
3374
+ options.versionBase = value;
3375
+ continue;
3376
+ }
3377
+ if (arg === '--workspace-root') {
3378
+ const value = args[index + 1];
3379
+ if (!value || value.startsWith('--')) {
3380
+ exitCliError('--workspace-root requires a value.', options.json);
3381
+ }
3382
+ index += 1;
3383
+ options.workspaceRoot = value;
3384
+ continue;
3385
+ }
3386
+ if (!arg.startsWith('--')) {
3387
+ if (!options.pluginDir) {
3388
+ options.pluginDir = arg;
3389
+ continue;
3390
+ }
3391
+ exitCliError(`Unknown argument: ${arg}`, options.json);
3392
+ }
3393
+ exitCliError(`Unknown option: ${arg}`, options.json);
3394
+ }
3395
+ return options;
3396
+ }
3397
+ async function main() {
3398
+ const args = parseArgs(process.argv);
3399
+ if (!args.pluginDir) {
3400
+ exitCliError('plugin-directory is required; run with --help for usage.', args.json);
3401
+ }
3402
+ const requestedWorkspaceRoot = args.workspaceRoot === null
3403
+ ? null
3404
+ : path.resolve(args.workspaceRoot);
3405
+ const resolved = path.resolve(requestedWorkspaceRoot ?? '.', args.pluginDir);
3406
+ if (!fs.existsSync(resolved)) {
3407
+ exitCliError(`[ERROR] Directory not found: ${resolved}`, args.json);
3408
+ }
3409
+ const repoRootCandidate = requestedWorkspaceRoot ?? findRepoRootCandidate(resolved);
3410
+ try {
3411
+ assertAuthoringPluginPathFence({
3412
+ repoRoot: repoRootCandidate ?? undefined,
3413
+ pluginRoot: resolved,
3414
+ requirePluginRoot: true,
3415
+ requireManifest: true,
3416
+ });
3417
+ }
3418
+ catch (pathError) {
3419
+ exitCliError(`[ERROR] ${pathError.message}`, args.json);
3420
+ }
3421
+ const repoRoot = requestedWorkspaceRoot ?? discoverCanonicalRepoRoot(repoRootCandidate);
3422
+ const gitRoot = discoverCanonicalRepoRoot(findRepoRootCandidate(resolved));
3423
+ await validatePluginDir(resolved, {
3424
+ strictAgentSkills: args.strictAgentSkills,
3425
+ claudeSkillProfile: args.claudeSkillProfile,
3426
+ versionBase: args.versionBase,
3427
+ repoRoot,
3428
+ gitRoot,
3429
+ enforceCanonicalRoot: requestedWorkspaceRoot !== null,
3430
+ });
3431
+ if (args.json) {
3432
+ console.log(JSON.stringify({
3433
+ ok: errors.length === 0,
3434
+ profile: args.strictAgentSkills ? 'agent-skills-portable-core' : 'aw-source',
3435
+ claudeSkillProfile: args.claudeSkillProfile,
3436
+ pluginDirectory: resolved,
3437
+ workspaceRoot: process.env.AW_AUTHORING_WORKSPACE_ROOT ?? repoRoot,
3438
+ workspaceRootResolvedFrom: process.env.AW_AUTHORING_WORKSPACE_ROOT_RESOLVED_FROM ?? 'explicit',
3439
+ versionCheck: pluginVersionCheckResult,
3440
+ warnings,
3441
+ errors,
3442
+ ...(capabilityDiagnostic ?? {}),
3443
+ }, null, 2));
3444
+ if (errors.length > 0) {
3445
+ process.exit(1);
3446
+ }
3447
+ return;
3448
+ }
3449
+ if (warnings.length > 0) {
3450
+ console.log(`\n[WARN] ${warnings.length} warning(s):`);
3451
+ for (const w of warnings) {
3452
+ console.log(` - ${w}`);
3453
+ }
3454
+ }
3455
+ if (errors.length > 0) {
3456
+ console.log(`\n[FAIL] ${errors.length} error(s):`);
3457
+ for (const e of errors) {
3458
+ console.log(` - ${e}`);
3459
+ }
3460
+ process.exit(1);
3461
+ }
3462
+ console.log('[PASS] All checks passed.');
3463
+ }
3464
+ main();
3465
+ //# sourceMappingURL=validate-plugin.mjs.map