@reqvire-org/ads 0.3.53 → 0.4.2

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 (401) hide show
  1. package/README.md +114 -94
  2. package/dist/a11y.mjs +108 -29
  3. package/dist/analysis/compiler-options.mjs +13 -0
  4. package/dist/analysis/context.mjs +46 -0
  5. package/dist/analysis/file-tree.mjs +52 -0
  6. package/dist/analysis/helpers.mjs +140 -0
  7. package/dist/analysis/impact.mjs +20 -0
  8. package/dist/analysis/inputs.mjs +15 -0
  9. package/dist/analysis/native-adapter.mjs +180 -0
  10. package/dist/analysis/native-project.mjs +323 -0
  11. package/dist/analysis/queries.mjs +133 -0
  12. package/dist/analysis/service.mjs +146 -0
  13. package/dist/analysis/standalone.mjs +57 -0
  14. package/dist/analysis/syntax.mjs +164 -0
  15. package/dist/analysis/worker.mjs +182 -0
  16. package/dist/assets.mjs +6 -6
  17. package/dist/atomic-composition.mjs +191 -70
  18. package/dist/atomic-trace.mjs +120 -50
  19. package/dist/behavior-libraries.mjs +106 -37
  20. package/dist/behaviors.mjs +222 -79
  21. package/dist/boundaries.mjs +137 -40
  22. package/dist/brand-assets.mjs +219 -47
  23. package/dist/brands.mjs +86 -27
  24. package/dist/bun-compiler.mjs +34 -13
  25. package/dist/bun-worker.mjs +7 -5
  26. package/dist/capture/worker.mjs +15 -4
  27. package/dist/capture-store.mjs +4 -2
  28. package/dist/capture.mjs +17 -14
  29. package/dist/check-service.mjs +66 -0
  30. package/dist/check.mjs +756 -196
  31. package/dist/cli.mjs +203 -100
  32. package/dist/color-values.mjs +21 -21
  33. package/dist/component-contrast.mjs +2 -2
  34. package/dist/config.mjs +308 -163
  35. package/dist/construction-styles.cjs +10 -0
  36. package/dist/contracts.d.mts +9 -0
  37. package/dist/control-padding.mjs +45 -25
  38. package/dist/css-values.mjs +3 -2
  39. package/dist/declarative-flow.mjs +209 -109
  40. package/dist/design-values.mjs +136 -51
  41. package/dist/development-runtime.mjs +4 -6
  42. package/dist/draft-boundary.mjs +11 -6
  43. package/dist/evidence.mjs +1 -1
  44. package/dist/finding-rules.mjs +7 -5
  45. package/dist/font-rules.mjs +2 -2
  46. package/dist/fonts-generated.mjs +4 -2
  47. package/dist/foundation-views.mjs +238 -0
  48. package/dist/foundation.mjs +63 -39
  49. package/dist/generated-entries.mjs +198 -0
  50. package/dist/icons.mjs +80 -33
  51. package/dist/image-attributes.mjs +109 -36
  52. package/dist/image-size.mjs +1 -1
  53. package/dist/index.mjs +0 -2
  54. package/dist/init.mjs +128 -68
  55. package/dist/investigations.mjs +2 -2
  56. package/dist/layers.mjs +300 -127
  57. package/dist/layout-widths.mjs +180 -85
  58. package/dist/linaria/preserve-values.cjs +7 -0
  59. package/dist/linaria/spatial-inputs.cjs +56 -0
  60. package/dist/lockup-composition.mjs +44 -0
  61. package/dist/lockup-model.cjs +64 -0
  62. package/dist/mcp/THIRD_PARTY_NOTICES.md +51 -1
  63. package/dist/mcp/apps.mjs +4 -30
  64. package/dist/mcp/behavior-pages.mjs +72 -24
  65. package/dist/mcp/build-status.mjs +257 -64
  66. package/dist/mcp/catalog.mjs +91 -26
  67. package/dist/mcp/context.mjs +17 -18
  68. package/dist/mcp/draft-discovery.mjs +44 -21
  69. package/dist/mcp/drafts.mjs +978 -343
  70. package/dist/mcp/execution-coordinator.mjs +417 -167
  71. package/dist/mcp/execution-results.mjs +7 -7
  72. package/dist/mcp/mutations.mjs +701 -219
  73. package/dist/mcp/preview-watch.mjs +465 -161
  74. package/dist/mcp/preview-widget.bundle.js +44 -50
  75. package/dist/mcp/prompts.mjs +6 -6
  76. package/dist/mcp/result-pages.mjs +1 -1
  77. package/dist/mcp/sandbox-host.mjs +1 -1
  78. package/dist/mcp/server.mjs +2436 -570
  79. package/dist/mcp/showcase-host.mjs +176 -39
  80. package/dist/mcp/skills.mjs +1 -1
  81. package/dist/mcp/text-diff.mjs +29 -10
  82. package/dist/paint-contracts.mjs +174 -81
  83. package/dist/palette-generated.mjs +2 -2
  84. package/dist/preview-bun.mjs +493 -187
  85. package/dist/preview-failure.mjs +1 -1
  86. package/dist/preview-files.mjs +13 -13
  87. package/dist/preview-imports.mjs +104 -55
  88. package/dist/preview-inputs.mjs +2 -2
  89. package/dist/preview-requests.mjs +24 -0
  90. package/dist/preview-resources.mjs +288 -147
  91. package/dist/preview-scope.mjs +5 -4
  92. package/dist/program-cache.mjs +10 -0
  93. package/dist/project-documents.mjs +1 -1
  94. package/dist/public-api.mjs +70 -31
  95. package/dist/public-props.mjs +39 -22
  96. package/dist/{browser-audit → render-audit}/axe-run.mjs +3 -3
  97. package/dist/{browser-audit → render-audit}/image-shape.mjs +2 -2
  98. package/dist/{browser-audit → render-audit}/layout-overflow.mjs +86 -23
  99. package/dist/{browser-audit → render-audit}/non-text-contrast.mjs +86 -27
  100. package/dist/{browser-audit → render-audit}/render-states.mjs +208 -52
  101. package/dist/{browser-audit → render-audit}/worker.mjs +86 -30
  102. package/dist/render-audit.mjs +828 -0
  103. package/dist/render-color-probe.mjs +96 -42
  104. package/dist/resource-limits.mjs +229 -97
  105. package/dist/runtime-contracts.mjs +467 -185
  106. package/dist/scenario-groups.mjs +22 -10
  107. package/dist/scenario-inspector.mjs +6 -43
  108. package/dist/scenario-program.mjs +8 -25
  109. package/dist/scenario-registry.mjs +72 -30
  110. package/dist/scenario-selectors.mjs +161 -64
  111. package/dist/scenario-slots.mjs +149 -56
  112. package/dist/scenario-trace.mjs +215 -109
  113. package/dist/scenarios-compiler.mjs +768 -359
  114. package/dist/scenarios-vite.d.mts +1 -3
  115. package/dist/scenarios-vite.mjs +2 -81
  116. package/dist/scenarios.mjs +424 -159
  117. package/dist/selector-match.mjs +2 -2
  118. package/dist/showcase/client.bundle.js +57 -56
  119. package/dist/showcase/draft-navigation.js +18 -0
  120. package/dist/showcase/favicon.ico +0 -0
  121. package/dist/showcase/favicon.svg +1 -0
  122. package/dist/showcase/foundation-view.css +55 -0
  123. package/dist/showcase/foundation-view.mjs +252 -0
  124. package/dist/showcase/guide-controls.ads.review.mjs +32 -0
  125. package/dist/showcase/icons.js +1 -145
  126. package/dist/showcase/index.html +3 -31
  127. package/dist/showcase/preview-frame.ads.review.css +46 -0
  128. package/dist/showcase/preview-frame.ads.review.d.mts +11 -0
  129. package/dist/showcase/preview-frame.ads.review.mjs +22 -0
  130. package/dist/showcase/preview-state.js +0 -9
  131. package/dist/showcase/refresh-scheduler.js +23 -0
  132. package/dist/showcase/style.css +5 -47
  133. package/dist/showcase/ui/ui.css +1353 -0
  134. package/dist/showcase/ui/ui.js +1062 -0
  135. package/dist/showcase-coverage.mjs +58 -37
  136. package/dist/skills/README.md +24 -23
  137. package/dist/skills/ads-designer/README.md +8 -2
  138. package/dist/skills/ads-designer/SKILL.md +152 -144
  139. package/dist/skills/ads-designer/references/accessibility.md +14 -11
  140. package/dist/skills/ads-designer/references/atomic-styles.md +4 -4
  141. package/dist/skills/ads-designer/references/behaviors.md +34 -30
  142. package/dist/skills/ads-designer/references/branding.md +98 -10
  143. package/dist/skills/ads-designer/references/captures.md +31 -31
  144. package/dist/skills/ads-designer/references/cli.md +21 -20
  145. package/dist/skills/ads-designer/references/contracts.md +63 -29
  146. package/dist/skills/ads-designer/references/design-data.md +49 -52
  147. package/dist/skills/ads-designer/references/drafts.md +71 -52
  148. package/dist/skills/ads-designer/references/evidence.md +1 -5
  149. package/dist/skills/ads-designer/references/guarded-editing.md +58 -51
  150. package/dist/skills/ads-designer/references/layers.md +1 -1
  151. package/dist/skills/ads-designer/references/layout.md +347 -0
  152. package/dist/skills/ads-designer/references/mobile.md +2 -1
  153. package/dist/skills/{ads-motion/references/performance.md → ads-designer/references/motion-performance.md} +5 -1
  154. package/dist/skills/{ads-motion/references/build.md → ads-designer/references/motion.md} +73 -5
  155. package/dist/skills/ads-designer/references/performance.md +3 -2
  156. package/dist/skills/ads-designer/references/review.md +42 -38
  157. package/dist/skills/ads-designer/references/runtimes.md +33 -30
  158. package/dist/skills/ads-designer/references/scenarios.md +17 -19
  159. package/dist/skills/{ads-break-ui/references/catalog.md → ads-designer/references/stress-catalog.md} +3 -1
  160. package/dist/skills/ads-designer/references/stress-test.md +68 -0
  161. package/dist/skills/ads-designer/references/validation.md +83 -71
  162. package/dist/skills/ads-designer/references/workflows.md +19 -37
  163. package/dist/skills/ads-import/SKILL.md +43 -328
  164. package/dist/skills/ads-import/references/atomic-styles.md +4 -4
  165. package/dist/skills/ads-import/references/behaviors.md +34 -30
  166. package/dist/skills/ads-import/references/branding.md +5 -5
  167. package/dist/skills/ads-import/references/captures.md +31 -31
  168. package/dist/skills/ads-import/references/cli.md +21 -20
  169. package/dist/skills/ads-import/references/compatibility.md +1 -1
  170. package/dist/skills/ads-import/references/contracts.md +63 -29
  171. package/dist/skills/ads-import/references/design-data.md +49 -52
  172. package/dist/skills/ads-import/references/drafts.md +71 -52
  173. package/dist/skills/ads-import/references/evidence.md +1 -5
  174. package/dist/skills/ads-import/references/guarded-editing.md +58 -51
  175. package/dist/skills/ads-import/references/implementation.md +2 -1
  176. package/dist/skills/ads-import/references/layers.md +1 -1
  177. package/dist/skills/ads-import/references/layout.md +347 -0
  178. package/dist/skills/ads-import/references/review.md +42 -38
  179. package/dist/skills/ads-import/references/runtimes.md +33 -30
  180. package/dist/skills/ads-import/references/scenarios.md +17 -19
  181. package/dist/skills/ads-import/references/tokens.md +3 -3
  182. package/dist/skills/ads-import/references/validation.md +83 -71
  183. package/dist/skills/ads-import/references/workflows.md +19 -37
  184. package/dist/skills/ads-migrate/SKILL.md +56 -0
  185. package/dist/skills/ads-migrate/references/0.4.1-to-0.4.2.md +602 -0
  186. package/dist/skills/ads-port/SKILL.md +54 -346
  187. package/dist/skills/ads-port/references/atomic-styles.md +4 -4
  188. package/dist/skills/ads-port/references/behaviors.md +34 -30
  189. package/dist/skills/ads-port/references/captures.md +31 -31
  190. package/dist/skills/ads-port/references/cli.md +21 -20
  191. package/dist/skills/ads-port/references/contracts.md +63 -29
  192. package/dist/skills/ads-port/references/design-data.md +49 -52
  193. package/dist/skills/ads-port/references/drafts.md +71 -52
  194. package/dist/skills/ads-port/references/evidence.md +1 -5
  195. package/dist/skills/ads-port/references/guarded-editing.md +58 -51
  196. package/dist/skills/ads-port/references/layers.md +1 -1
  197. package/dist/skills/ads-port/references/layout.md +347 -0
  198. package/dist/skills/ads-port/references/lint-and-docs.md +8 -11
  199. package/dist/skills/ads-port/references/native-implementation.md +8 -7
  200. package/dist/skills/ads-port/references/review.md +42 -38
  201. package/dist/skills/ads-port/references/runtimes.md +33 -30
  202. package/dist/skills/ads-port/references/scenarios.md +17 -19
  203. package/dist/skills/ads-port/references/validation.md +83 -71
  204. package/dist/skills/ads-port/references/workflows.md +19 -37
  205. package/dist/source-symbols.mjs +1 -8
  206. package/dist/source-values.mjs +266 -128
  207. package/dist/spatial-composition.mjs +322 -0
  208. package/dist/spatial-contexts.cjs +56 -0
  209. package/dist/spatial-css.cjs +351 -0
  210. package/dist/spatial-inputs.cjs +80 -0
  211. package/dist/spatial-metadata.mjs +18 -0
  212. package/dist/spatial-model.cjs +322 -0
  213. package/dist/spatial.mjs +21 -0
  214. package/dist/stage-timing.cjs +20 -0
  215. package/dist/starters/preact/design-system/patterns/Conversation/Conversation.tsx +105 -0
  216. package/dist/starters/preact/design-system/patterns/Shell/Shell.tsx +275 -0
  217. package/dist/starters/preact/design-system/review/demo-frame/DemoFrame.ads.review.tsx +7 -0
  218. package/dist/starters/preact/design-system/review/screen-frame/ScreenFrame.ads.review.tsx +10 -0
  219. package/dist/starters/preact/design-system/showcase/mcp/main.ads.mount.tsx +8 -0
  220. package/dist/starters/preact/ds.config.json +24 -19
  221. package/dist/starters/preact/package.json +4 -8
  222. package/dist/starters/preact/tsconfig.json +4 -5
  223. package/dist/starters/preact/vite.config.ts +3 -3
  224. package/dist/starters/react/ADS.md +42 -47
  225. package/dist/starters/react/README.md +54 -52
  226. package/dist/starters/react/design-system/components/Actions/Button/Button.ads.exports.ts +1 -0
  227. package/dist/starters/react/design-system/components/Actions/IconButton/IconButton.ads.exports.ts +1 -0
  228. package/dist/starters/react/design-system/components/Actions/IconButton/IconButton.tsx +18 -2
  229. package/dist/starters/react/design-system/components/Actions/IconButton/README.md +3 -0
  230. package/dist/starters/react/design-system/components/Content/Icon/Icon.ads.exports.ts +1 -0
  231. package/dist/starters/react/design-system/components/Content/Image/Image.ads.exports.ts +1 -0
  232. package/dist/starters/react/design-system/components/Content/Logo/Logo.ads.exports.ts +1 -0
  233. package/dist/starters/react/design-system/components/Forms/TextField/TextField.ads.exports.ts +1 -0
  234. package/dist/starters/react/design-system/composition/Workspace/WorkspacePage/README.md +5 -0
  235. package/dist/starters/react/design-system/composition/Workspace/WorkspacePage/WorkspacePage.ads.fixture.ts +13 -0
  236. package/dist/starters/react/design-system/composition/Workspace/WorkspacePage/WorkspacePage.ads.scenario.tsx +22 -0
  237. package/dist/starters/react/design-system/controllers/Palette/Palette.ads.exports.ts +1 -0
  238. package/dist/starters/react/design-system/index.ts +5 -8
  239. package/dist/starters/react/design-system/patterns/Conversation/Conversation.ads.exports.ts +1 -0
  240. package/dist/starters/react/design-system/patterns/Conversation/Conversation.ads.fixture.ts +7 -0
  241. package/dist/starters/react/design-system/patterns/Conversation/Conversation.ads.scenario.tsx +15 -0
  242. package/dist/starters/react/design-system/patterns/Conversation/Conversation.tsx +105 -0
  243. package/dist/starters/react/design-system/patterns/Conversation/README.md +9 -0
  244. package/dist/starters/react/design-system/patterns/Search/SearchBar/SearchBar.ads.exports.ts +1 -0
  245. package/dist/starters/react/design-system/patterns/Shell/Floating.ads.fixture.ts +5 -0
  246. package/dist/starters/react/design-system/patterns/Shell/Floating.ads.scenario.tsx +21 -0
  247. package/dist/starters/react/design-system/patterns/Shell/README.md +43 -0
  248. package/dist/starters/react/design-system/patterns/Shell/Shell.ads.exports.ts +1 -0
  249. package/dist/starters/react/design-system/patterns/Shell/Shell.ads.fixture.ts +5 -0
  250. package/dist/starters/react/design-system/patterns/Shell/Shell.ads.scenario.tsx +21 -0
  251. package/dist/starters/react/design-system/patterns/Shell/Shell.tsx +274 -0
  252. package/dist/starters/react/design-system/review/demo-frame/DemoFrame.ads.exports.ts +1 -0
  253. package/dist/starters/react/design-system/review/demo-frame/DemoFrame.ads.review.tsx +7 -0
  254. package/dist/starters/react/design-system/review/index.ads.review.ts +4 -0
  255. package/dist/starters/react/design-system/review/region-block/RegionBlock.ads.exports.ts +1 -0
  256. package/dist/starters/react/design-system/review/region-block/RegionBlock.ads.review.tsx +6 -0
  257. package/dist/starters/react/design-system/review/screen-frame/ScreenFrame.ads.exports.ts +1 -0
  258. package/dist/starters/react/design-system/review/screen-frame/ScreenFrame.ads.review.tsx +10 -0
  259. package/dist/starters/react/design-system/showcase/mcp/{main.tsx → main.ads.mount.tsx} +4 -2
  260. package/dist/starters/react/design-system/styles.css +1 -0
  261. package/dist/starters/react/design-system/tokens/catalog.ads.json +1221 -0
  262. package/dist/starters/react/design-system/tokens/colors.css +1 -1
  263. package/dist/starters/react/design-system/tokens/spacing.css +22 -32
  264. package/dist/starters/react/design-system/tokens/spatial.ads.json +70 -0
  265. package/dist/starters/react/design-system/tokens/themes.generated.ts +1 -1
  266. package/dist/starters/react/ds.config.json +24 -19
  267. package/dist/starters/react/package.json +2 -6
  268. package/dist/starters/react/tsconfig.json +2 -3
  269. package/dist/starters/react/vite.config.ts +3 -3
  270. package/dist/style-boundaries.mjs +73 -27
  271. package/dist/task-cache.mjs +173 -72
  272. package/dist/task-worker.mjs +22 -11
  273. package/dist/test-boundaries.mjs +133 -60
  274. package/dist/themes-generated.mjs +1 -1
  275. package/dist/themes-watch.mjs +60 -19
  276. package/dist/themes.mjs +176 -73
  277. package/dist/token-export.mjs +39 -14
  278. package/dist/token-policy.mjs +6 -3
  279. package/dist/token-quality.mjs +6 -6
  280. package/dist/token-samples.mjs +16 -5
  281. package/dist/tokens.mjs +71 -26
  282. package/dist/ui-framework.mjs +16 -14
  283. package/dist/unit-contracts.mjs +270 -89
  284. package/dist/units.mjs +215 -180
  285. package/dist/usage.mjs +138 -38
  286. package/dist/validation-checks.mjs +121 -38
  287. package/dist/validation-inputs.mjs +187 -78
  288. package/dist/validation.mjs +268 -102
  289. package/dist/verification/browser.mjs +27 -5
  290. package/dist/verification.mjs +711 -187
  291. package/docs/ADS.md +100 -89
  292. package/docs/ARCHITECTURE.md +353 -159
  293. package/docs/BEHAVIORS.md +33 -28
  294. package/docs/CACHING.md +55 -11
  295. package/docs/CHANGELOG.md +358 -17
  296. package/docs/COMPARISON.md +1 -1
  297. package/docs/CONTRACTS.md +22 -29
  298. package/docs/DESIGN-REFERENCES.md +40 -0
  299. package/docs/GUIDE.md +313 -292
  300. package/docs/MCP.md +261 -439
  301. package/docs/SPATIAL-CHECKS.md +69 -0
  302. package/docs/benchmarks/README.md +39 -0
  303. package/package.json +42 -34
  304. package/dist/browser-audit.mjs +0 -424
  305. package/dist/contract-migration.mjs +0 -110
  306. package/dist/create.mjs +0 -48
  307. package/dist/lint-config.mjs +0 -48
  308. package/dist/mcp/draft-exports.mjs +0 -40
  309. package/dist/mcp/edit-preparation.mjs +0 -115
  310. package/dist/mcp/project-widget.bundle.js +0 -114
  311. package/dist/mcp/reports.mjs +0 -101
  312. package/dist/mcp/widget.bundle.js +0 -147
  313. package/dist/oxlint.mjs +0 -88
  314. package/dist/preview-builder.mjs +0 -133
  315. package/dist/preview-workers.mjs +0 -184
  316. package/dist/showcase.mjs +0 -77
  317. package/dist/skills/ads-break-ui/LICENSE.upstream +0 -21
  318. package/dist/skills/ads-break-ui/README.md +0 -16
  319. package/dist/skills/ads-break-ui/SKILL.md +0 -415
  320. package/dist/skills/ads-break-ui/agents/openai.yaml +0 -4
  321. package/dist/skills/ads-break-ui/references/atomic-styles.md +0 -293
  322. package/dist/skills/ads-break-ui/references/behaviors.md +0 -411
  323. package/dist/skills/ads-break-ui/references/captures.md +0 -160
  324. package/dist/skills/ads-break-ui/references/contracts.md +0 -284
  325. package/dist/skills/ads-break-ui/references/design-data.md +0 -354
  326. package/dist/skills/ads-break-ui/references/drafts.md +0 -178
  327. package/dist/skills/ads-break-ui/references/evidence.md +0 -128
  328. package/dist/skills/ads-break-ui/references/guarded-editing.md +0 -154
  329. package/dist/skills/ads-break-ui/references/layers.md +0 -145
  330. package/dist/skills/ads-break-ui/references/reporting.md +0 -101
  331. package/dist/skills/ads-break-ui/references/review.md +0 -96
  332. package/dist/skills/ads-break-ui/references/runtimes.md +0 -203
  333. package/dist/skills/ads-break-ui/references/scenarios.md +0 -246
  334. package/dist/skills/ads-break-ui/references/validation.md +0 -162
  335. package/dist/skills/ads-break-ui/references/verification.md +0 -58
  336. package/dist/skills/ads-break-ui/references/workflows.md +0 -83
  337. package/dist/skills/ads-designer/references/reporting.md +0 -101
  338. package/dist/skills/ads-import/references/reporting.md +0 -101
  339. package/dist/skills/ads-motion/LICENSE.upstream +0 -21
  340. package/dist/skills/ads-motion/README.md +0 -22
  341. package/dist/skills/ads-motion/SKILL.md +0 -388
  342. package/dist/skills/ads-motion/agents/openai.yaml +0 -4
  343. package/dist/skills/ads-motion/references/atomic-styles.md +0 -293
  344. package/dist/skills/ads-motion/references/audit.md +0 -44
  345. package/dist/skills/ads-motion/references/behaviors.md +0 -411
  346. package/dist/skills/ads-motion/references/captures.md +0 -160
  347. package/dist/skills/ads-motion/references/contracts.md +0 -284
  348. package/dist/skills/ads-motion/references/design-data.md +0 -354
  349. package/dist/skills/ads-motion/references/drafts.md +0 -178
  350. package/dist/skills/ads-motion/references/evidence.md +0 -128
  351. package/dist/skills/ads-motion/references/guarded-editing.md +0 -154
  352. package/dist/skills/ads-motion/references/layers.md +0 -145
  353. package/dist/skills/ads-motion/references/motion-review.md +0 -35
  354. package/dist/skills/ads-motion/references/reporting.md +0 -101
  355. package/dist/skills/ads-motion/references/review.md +0 -96
  356. package/dist/skills/ads-motion/references/runtimes.md +0 -203
  357. package/dist/skills/ads-motion/references/scenarios.md +0 -246
  358. package/dist/skills/ads-motion/references/validation.md +0 -162
  359. package/dist/skills/ads-motion/references/verification.md +0 -39
  360. package/dist/skills/ads-motion/references/workflows.md +0 -83
  361. package/dist/skills/ads-port/references/reporting.md +0 -101
  362. package/dist/starters/preact/design-system/components/Layout/Grid/Grid.tsx +0 -76
  363. package/dist/starters/preact/design-system/review/demo-frame/DemoFrame.tsx +0 -29
  364. package/dist/starters/preact/design-system/review/screen-frame/ScreenFrame.tsx +0 -34
  365. package/dist/starters/preact/design-system/review/token-preview/TokenPreview.tsx +0 -137
  366. package/dist/starters/preact/design-system/showcase/mcp/main.tsx +0 -6
  367. package/dist/starters/react/design-system/brand/Icons/AppIcon/AppIcon.ads.fixture.ts +0 -7
  368. package/dist/starters/react/design-system/brand/Icons/AppIcon/AppIcon.ads.scenario.tsx +0 -4
  369. package/dist/starters/react/design-system/brand/Identity/Logo/Logo.ads.fixture.ts +0 -7
  370. package/dist/starters/react/design-system/brand/Identity/Logo/Logo.ads.scenario.tsx +0 -4
  371. package/dist/starters/react/design-system/components/Layout/Grid/Grid.ads.fixture.ts +0 -12
  372. package/dist/starters/react/design-system/components/Layout/Grid/Grid.ads.scenario.tsx +0 -17
  373. package/dist/starters/react/design-system/components/Layout/Grid/Grid.tsx +0 -75
  374. package/dist/starters/react/design-system/components/Layout/Grid/README.md +0 -21
  375. package/dist/starters/react/design-system/review/brand-preview/BrandPreview.tsx +0 -112
  376. package/dist/starters/react/design-system/review/demo-frame/DemoFrame.tsx +0 -29
  377. package/dist/starters/react/design-system/review/grid-cell/GridCell.tsx +0 -18
  378. package/dist/starters/react/design-system/review/index.ts +0 -5
  379. package/dist/starters/react/design-system/review/screen-frame/ScreenFrame.tsx +0 -34
  380. package/dist/starters/react/design-system/review/token-preview/TokenPreview.tsx +0 -137
  381. package/dist/starters/react/design-system/showcase/mcp/index.html +0 -1
  382. package/dist/starters/react/design-system/tokens/Color.ads.fixture.ts +0 -124
  383. package/dist/starters/react/design-system/tokens/Color.ads.scenario.tsx +0 -4
  384. package/dist/starters/react/design-system/tokens/Layout.ads.fixture.ts +0 -39
  385. package/dist/starters/react/design-system/tokens/Layout.ads.scenario.tsx +0 -4
  386. package/dist/starters/react/design-system/tokens/Motion.ads.fixture.ts +0 -18
  387. package/dist/starters/react/design-system/tokens/Motion.ads.scenario.tsx +0 -4
  388. package/dist/starters/react/design-system/tokens/Shape.ads.fixture.ts +0 -30
  389. package/dist/starters/react/design-system/tokens/Shape.ads.scenario.tsx +0 -4
  390. package/dist/starters/react/design-system/tokens/Space.ads.fixture.ts +0 -37
  391. package/dist/starters/react/design-system/tokens/Space.ads.scenario.tsx +0 -4
  392. package/dist/starters/react/design-system/tokens/Type.ads.fixture.ts +0 -29
  393. package/dist/starters/react/design-system/tokens/Type.ads.scenario.tsx +0 -4
  394. package/dist/starters/react/package-lock.json +0 -4707
  395. package/dist/token-fixtures.mjs +0 -30
  396. package/docs/benchmarks/bun-previews.md +0 -91
  397. package/docs/benchmarks/preview-memory.md +0 -147
  398. package/docs/benchmarks/turbo-poc.md +0 -284
  399. package/docs/plans/execution-coordination.md +0 -57
  400. /package/dist/{browser-audit → render-audit}/first-render.mjs +0 -0
  401. /package/dist/{browser-audit → render-audit}/layout-shift.mjs +0 -0
@@ -2,7 +2,7 @@ import { watchThemesCss } from "../themes-watch.mjs";
2
2
  import { randomUUID } from "node:crypto";
3
3
  import { executionContext } from "./execution-context.mjs";
4
4
  import { createExecutionCoordinator } from "./execution-coordinator.mjs";
5
- import { existsSync, readFileSync, statSync, watch } from "node:fs";
5
+ import { mkdirSync, readFileSync, statSync, watch } from "node:fs";
6
6
  import path from "node:path";
7
7
  import { Server, ProtocolError, INVALID_PARAMS, ResourceNotFoundError } from "@modelcontextprotocol/server";
8
8
  import { serveStdio, StdioServerTransport } from "@modelcontextprotocol/server/stdio";
@@ -11,18 +11,19 @@ import { checkCandidate } from "../validation-checks.mjs";
11
11
  import { taskCacheSettings } from "../task-cache.mjs";
12
12
  import { createValidationController } from "../validation.mjs";
13
13
  import { loadConfig, sourceFiles } from "../config.mjs";
14
- import { createVerificationController, BEHAVIOR_URI } from "../verification.mjs";
15
- import { INVESTIGATIONS_URI, investigationIndex, investigationPage, investigationSections, readInvestigation, readInvestigationResource } from "../investigations.mjs";
14
+ import { BEHAVIOR_URI } from "../verification.mjs";
15
+ import { INVESTIGATIONS_URI, investigationIndex, investigationPage, investigationSections, readInvestigationResource } from "../investigations.mjs";
16
16
  import { failure } from "../evidence.mjs";
17
- import { inspectTokens } from "../tokens.mjs";
17
+ import { analyze } from "../analysis/service.mjs";
18
+ import { exportTokensDtcg } from "../token-export.mjs";
18
19
  import { ICONS_URI, iconInputs, iconSet } from "../icons.mjs";
19
- import { discoverScenarioRegistry, readScenarioRegistry, releaseScenarioRegistry } from "../scenario-registry.mjs";
20
+ import { readScenarioRegistry, releaseScenarioRegistry } from "../scenario-registry.mjs";
20
21
  import { createScenarioInspector } from "../scenario-inspector.mjs";
21
22
  import { scenarioGroupFingerprint } from "../scenario-groups.mjs";
22
23
  import { startShowcaseHost } from "./showcase-host.mjs";
23
24
  import { createSkillStore, page, SKILLS_EXTENSION } from "./skills.mjs";
24
25
  import { projectDocuments, PROJECT_URI, readProjectDocument } from "./catalog.mjs";
25
- import { APP_MIME, appMetadata, appUri, projectApp, TOKENS_APP_URI, tokensApp, tokenWidgetData, SCENARIO_APP_URI, scenarioApp, previewApp, PREVIEW_APP_URI } from "./apps.mjs";
26
+ import { APP_MIME, appMetadata, appUri, tokenWidgetData, previewApp, PREVIEW_APP_URI } from "./apps.mjs";
26
27
  import { LIVE_PREVIEW_MANIFEST_URI, PREVIEW_MANIFEST_URI, readPreviewManifest, readPreviewAsset } from "../preview-resources.mjs";
27
28
  import { livePreviewOptions, previewArtifactPath, withPreviewSession } from "../preview-scope.mjs";
28
29
  import { getWorkflowPrompt, promptDefinitions } from "./prompts.mjs";
@@ -33,67 +34,149 @@ import { resourceLimitsStatus } from "../resource-limits.mjs";
33
34
  import { assertBunRuntime } from "../runtime-requirements.mjs";
34
35
  import { createMutationController, mutationLimits } from "./mutations.mjs";
35
36
  import { createPreviewWork } from "./preview-work.mjs";
36
- import { prepareUnitPatch, storePreparedPatch } from "./edit-preparation.mjs";
37
- import { reconcileTokenSamples } from "../token-fixtures.mjs";
38
37
  import { createCaptureController } from "../capture.mjs";
39
- import { CAPTURES_URI, captureSpec, screenshotFields } from "../capture-store.mjs";
38
+ import { CAPTURES_URI, captureSpec } from "../capture-store.mjs";
40
39
  import { previewSourceRevision } from "../preview-inputs.mjs";
41
40
  import { createExecutionResults, RESULTS_URI, resultSections } from "./execution-results.mjs";
42
- import { behaviorPage, behaviorSections } from "./behavior-pages.mjs";
41
+ import { behaviorSections } from "./behavior-pages.mjs";
43
42
  import { compactProgress, resultBudgets } from "./result-pages.mjs";
44
- import { createReportStore, bugReportSchema, featureRequestSchema } from "./reports.mjs";
45
- import { createHash } from "node:crypto";
46
- import { developmentRuntime } from "../development-runtime.mjs";
47
43
  import { createDraftController, DRAFTS_URI, draftIdSchema, draftRevisionSchema } from "./drafts.mjs";
48
44
  import { isDraftPreviewWorkspace } from "../draft-workspace.mjs";
49
45
  import { isDraftFile } from "../draft-boundary.mjs";
50
- import { findingCounts } from "../finding-rules.mjs";
51
-
46
+ import { releaseWarmChecks, useWarmChecks } from "../check-service.mjs";
52
47
  const pkg = JSON.parse(readFileSync(new URL("../../package.json", import.meta.url), "utf8"));
53
48
  class InvalidParamsError extends ProtocolError {
54
- constructor(message) { super(INVALID_PARAMS, message); }
49
+ constructor(message) {
50
+ super(INVALID_PARAMS, message);
51
+ }
55
52
  }
56
53
  const json = (value) => ({ content: [{ type: "text", text: JSON.stringify(value) }], structuredContent: value });
57
54
  function captureResponse(value, resourceLinks = false) {
58
55
  const result = json(value);
59
56
  if (!resourceLinks) return result; // Older protocol clients retain text/structured URI discovery.
60
- for (const capture of value.captures ?? value.screenshots?.captures ?? []) for (const slot of ["current", "candidate"]) if (capture[slot]) result.content.push({ type: "resource_link", uri: capture[slot].resourceUri, mimeType: "image/png", name: `${slot === "current" ? "Current" : "Candidate"}: ${capture.scenario}${capture.target ? ` / ${capture.target}` : ""}` });
57
+ for (const capture of value.captures ?? value.screenshots?.captures ?? [])
58
+ for (const slot of ["current", "candidate"])
59
+ if (capture[slot])
60
+ result.content.push({
61
+ type: "resource_link",
62
+ uri: capture[slot].resourceUri,
63
+ mimeType: "image/png",
64
+ name: `${slot === "current" ? "Current" : "Candidate"}: ${capture.scenario}${capture.target ? ` / ${capture.target}` : ""}`,
65
+ });
61
66
  return result;
62
67
  }
63
68
  const empty = z.object({}).strict();
64
- const query = z.object({ query: z.string().max(200).optional(), limit: z.number().int().min(1).max(50).default(20) }).strict();
65
- const recordRange = { recordIndex: z.number().int().min(0).optional(), offset: z.number().int().min(0).optional(), chars: z.number().int().min(1).max(2000).optional() };
66
- const paged = { cursor: z.string().max(300).optional(), limit: z.number().int().min(1).max(resultBudgets.maxLimit).optional() };
67
- const annotations = { readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: false };
68
- const schemas = { params: z.object({ cursor: z.string().optional() }).passthrough(), result: z.object({ resultType: z.literal("complete") }).passthrough() };
69
- const ownerPatch = z.object({ unit: z.string().min(1).max(256), patch: z.string().min(1).max(mutationLimits.patchBytes).optional(), patchFile: z.string().min(1).max(500).optional() }).strict().refine(args => (args.patch !== undefined) !== (args.patchFile !== undefined), "Provide exactly one of patch or patchFile.");
70
-
69
+ const query = z
70
+ .object({
71
+ query: z.string().max(200).optional(),
72
+ limit: z.number().int().min(1).max(50).default(20),
73
+ })
74
+ .strict();
75
+ const recordRange = {
76
+ recordIndex: z.number().int().min(0).optional(),
77
+ offset: z.number().int().min(0).optional(),
78
+ chars: z.number().int().min(1).max(2000).optional(),
79
+ };
80
+ const paged = {
81
+ cursor: z.string().max(300).optional(),
82
+ limit: z.number().int().min(1).max(resultBudgets.maxLimit).optional(),
83
+ };
84
+ const annotations = {
85
+ readOnlyHint: true,
86
+ destructiveHint: false,
87
+ idempotentHint: true,
88
+ openWorldHint: false,
89
+ };
90
+ const schemas = {
91
+ params: z
92
+ .object({
93
+ cursor: z.string().optional(),
94
+ })
95
+ .passthrough(),
96
+ result: z
97
+ .object({
98
+ resultType: z.literal("complete"),
99
+ })
100
+ .passthrough(),
101
+ };
71
102
  function resourceQuery(uri, allowed) {
72
- const url=new URL(uri);
73
- if([...url.searchParams.keys()].some(key=>!allowed.includes(key)))throw new Error("Unknown paged resource query.");
74
- return Object.fromEntries([...url.searchParams].map(([key,value])=>[key,["limit","recordIndex","offset","chars"].includes(key)?Number(value):value]));
103
+ const url = new URL(uri);
104
+ if ([...url.searchParams.keys()].some((key) => !allowed.includes(key))) throw new Error("Unknown paged resource query.");
105
+ return Object.fromEntries(
106
+ [...url.searchParams].map(([key, value]) => [key, ["limit", "recordIndex", "offset", "chars"].includes(key) ? Number(value) : value]),
107
+ );
75
108
  }
76
-
77
- export function createAdsMcp(directory, { era = "legacy", skillDirectory, pollInterval = 1000, observeChanges = true, previewWatch, showcaseUrl, notifications, inspection, mutations = false, onBuildChange } = {}) {
78
- if (process.versions.bun) assertBunRuntime();
109
+ export async function createAdsMcp(
110
+ directory,
111
+ {
112
+ era = "legacy",
113
+ skillDirectory,
114
+ pollInterval = 1000,
115
+ observeChanges = true,
116
+ previewWatch,
117
+ showcaseUrl,
118
+ mountPreview,
119
+ notifications,
120
+ inspection,
121
+ mutations = false,
122
+ onBuildChange,
123
+ } = {},
124
+ ) {
125
+ assertBunRuntime();
79
126
  const root = path.resolve(directory);
80
127
  let observationClosed = false;
81
128
  const cache = inspection ?? {};
82
- const skills = cache.skills ??= createSkillStore(skillDirectory);
83
- const captures = cache.captures ??= createCaptureController(root);
84
- const edits = cache.edits ??= createMutationController(root, { captures, previewWork: cache.previewWork });
85
- const draftObservers = cache.draftObservers ??= new Set();
86
- const drafts = cache.drafts ??= createDraftController(root, { edits, prewarm: true,
87
- onChange: () => { for (const observer of draftObservers) void observer().catch(error => { process.stderr.write(`ads mcp: ${error.message}\n`); }); },
88
- startPreview: workspace => startAdsMcp(workspace, { stdio: false, mutations: false, previewWork: cache.previewWork }) });
89
- const verification = cache.verification ??= createVerificationController(root, { previewWork: cache.previewWork });
90
- const validation = cache.validation ??= createValidationController(root, { previewWork: cache.previewWork });
91
- const executionResults = cache.executionResults ??= createExecutionResults(root,{retention:()=>{try{cache.resultRetention=loadConfig(root).config.mcp.resultRetention;}catch{/* Keep the last valid policy during config edits. */}return cache.resultRetention;}});
92
- const executionObservers=cache.executionObservers??=new Set();
93
- const coordinator=cache.coordinator??=createExecutionCoordinator(root,{results:executionResults,onChange:()=>{for(const observer of executionObservers)observer();}});
94
- const connectionId=randomUUID();
95
- void coordinator.ready().catch(error=>process.stderr.write(`ads mcp: execution recovery: ${error.message}\n`));
96
- const reports = cache.reports ??= createReportStore(root, { context: reportContext, resolveEvidence: reportEvidence });
129
+ const skills = (cache.skills ??= createSkillStore(skillDirectory));
130
+ const captures = (cache.captures ??= createCaptureController(root));
131
+ const edits = (cache.edits ??= createMutationController(root, {
132
+ captures,
133
+ previewWork: cache.previewWork,
134
+ }));
135
+ const draftObservers = (cache.draftObservers ??= new Set());
136
+ const drafts = (cache.drafts ??= createDraftController(root, {
137
+ edits,
138
+ prewarm: true,
139
+ onChange: () => {
140
+ for (const observer of draftObservers)
141
+ void observer().catch((error) => {
142
+ process.stderr.write(`ads mcp: ${error.message}\n`);
143
+ });
144
+ },
145
+ // A draft preview is a view of its workspace, compiled by this project's compiler: no
146
+ // server, port, watcher set or compiler process of its own.
147
+ startPreview: (workspace, id) => {
148
+ if (!previewWatch?.attachDraft) throw new Error("Draft previews need the project's preview compiler; start ADS with its showcase.");
149
+ return createDraftPreview(workspace, {
150
+ id,
151
+ host: previewWatch,
152
+ showcaseUrl: getShowcaseUrl,
153
+ mountPreview,
154
+ previewWork: cache.previewWork,
155
+ });
156
+ },
157
+ }));
158
+ const validation = (cache.validation ??= createValidationController(root, {
159
+ previewWork: cache.previewWork,
160
+ }));
161
+ const executionResults = (cache.executionResults ??= createExecutionResults(root, {
162
+ retention: () => {
163
+ try {
164
+ cache.resultRetention = loadConfig(root).config.mcp.resultRetention;
165
+ } catch {
166
+ /* Keep the last valid policy during config edits. */
167
+ }
168
+ return cache.resultRetention;
169
+ },
170
+ }));
171
+ const executionObservers = (cache.executionObservers ??= new Set());
172
+ const coordinator = (cache.coordinator ??= createExecutionCoordinator(root, {
173
+ results: executionResults,
174
+ onChange: () => {
175
+ for (const observer of executionObservers) observer();
176
+ },
177
+ }));
178
+ const connectionId = randomUUID();
179
+ void coordinator.ready().catch((error) => process.stderr.write(`ads mcp: execution recovery: ${error.message}\n`));
97
180
  let options = loadConfig(root);
98
181
  const signature = `${root}:${JSON.stringify(options.config)}`;
99
182
  if (cache.signature !== signature) {
@@ -101,468 +184,1615 @@ export function createAdsMcp(directory, { era = "legacy", skillDirectory, pollIn
101
184
  cache.behaviorLibraries = undefined;
102
185
  cache.registry = cache.catalog = cache.documents = undefined;
103
186
  }
104
- const getShowcaseUrl = () => showcaseUrl?.() ?? options.config.mcp.showcaseUrl;
105
- async function architecture(signal, fresh=false) {
187
+ // The URL and port of the showcase this MCP server is running; none with --no-showcase.
188
+ const getShowcaseUrl = () => showcaseUrl?.() ?? null;
189
+ async function architecture(signal, fresh = false) {
106
190
  let release;
107
191
  try {
108
192
  if (cache.previewWork) release = await cache.previewWork.acquire(signal);
109
- return await checkCandidate(root, signal, root, {fresh});
110
- } finally { release?.(); }
193
+ return await checkCandidate(root, signal, root, {
194
+ fresh,
195
+ });
196
+ } finally {
197
+ release?.();
198
+ }
111
199
  }
112
200
  function scenarioUrl(id) {
113
201
  const base = getShowcaseUrl();
114
202
  if (!base) return null;
115
203
  const url = new URL(base);
116
- url.searchParams.delete("category");
117
204
  url.searchParams.set("scenario", id);
118
205
  return url.href;
119
206
  }
120
- const project = () => { const context = projectContext(options); context.showcase.url = getShowcaseUrl(); return context; };
207
+ const project = () => {
208
+ const context = projectContext(options);
209
+ context.showcase.url = getShowcaseUrl();
210
+ return context;
211
+ };
121
212
  const subscribed = new Set();
122
- const server = new Server({ name: "reqvire-ads", version: pkg.version }, {
123
- instructions: `${serverInstructions} ${mutations ? "MCP source mutation tools are enabled for MCP-only editing or deliberately selected guarded proposals. Read ads://guides/workflows first; availability does not require direct editors to use drafts. For tracked proposals, read ads://guides/drafts and accept the exact rendered/reviewed revision. Focused repairs use ads_units, ads_read_file and guarded ads_apply_patch for one owner, or ads_apply_transaction for coupled owners. Preserve companionFiles scope and mandatory ADS gates." : "MCP source mutation tools are disabled. Direct editors can still edit owned files normally and use MCP for previews/checks. MCP-only clients without another source channel cannot edit."}`,
124
- capabilities: { tools: { listChanged: true }, resources: { listChanged: true, subscribe: true }, prompts: {},
125
- extensions: { "io.modelcontextprotocol/ui": { mimeTypes: [APP_MIME] }, ...(era === "modern" ? { [SKILLS_EXTENSION]: { directoryRead: true } } : {}) } },
126
- });
127
- const getRegistry = () => {
128
- const current = loadConfig(root), revision = previewSourceRevision(current);
213
+ const server = new Server(
214
+ {
215
+ name: "reqvire-ads",
216
+ version: pkg.version,
217
+ },
218
+ {
219
+ instructions: `${serverInstructions} ${mutations ? "MCP source mutation tools are enabled for MCP-only editing or deliberately selected guarded proposals. Read ads://guides/workflows first; availability does not require direct editors to use drafts. For tracked proposals, read ads://guides/drafts and accept the exact rendered/reviewed revision. Every MCP source change goes through a draft: only ads_accept of an exact draft revision writes accepted source. Focused repairs patch a draft with ads_update_draft; coupled owners share one draft. Keep mandatory ADS gates." : "MCP source mutation tools are disabled. Direct editors can still edit owned files normally and use MCP for previews/checks. MCP-only clients without another source channel cannot edit."}`,
220
+ capabilities: {
221
+ tools: {
222
+ listChanged: true,
223
+ },
224
+ resources: {
225
+ listChanged: true,
226
+ subscribe: true,
227
+ },
228
+ prompts: {},
229
+ extensions: {
230
+ "io.modelcontextprotocol/ui": {
231
+ mimeTypes: [APP_MIME],
232
+ },
233
+ ...(era === "modern"
234
+ ? {
235
+ [SKILLS_EXTENSION]: {
236
+ directoryRead: true,
237
+ },
238
+ }
239
+ : {}),
240
+ },
241
+ },
242
+ },
243
+ );
244
+ const getRegistry = async () => {
245
+ const current = loadConfig(root),
246
+ revision = await previewSourceRevision(current);
129
247
  if (!cache.registry || cache.registryRevision !== revision) {
130
- try { cache.registry = discoverScenarioRegistry(current); }
131
- finally { releaseScenarioRegistry(root); }
132
- cache.registryRevision = revision; cache.catalog = undefined; cache.behaviorLibraries = undefined;
248
+ try {
249
+ cache.registry = await readScenarioRegistry(current);
250
+ if (!cache.registry) cache.registry = await analyze(root, "registry");
251
+ } finally {
252
+ releaseScenarioRegistry(root);
253
+ }
254
+ cache.registryRevision = revision;
255
+ cache.catalog = undefined;
256
+ cache.behaviorLibraries = undefined;
133
257
  }
134
- cache.lastRegistry = cache.registry; return cache.registry;
258
+ cache.lastRegistry = cache.registry;
259
+ return cache.registry;
135
260
  };
136
261
  async function getRegistryAsync() {
137
- for(let attempt=0;attempt<2;attempt++){
138
- const current=loadConfig(root),revision=previewSourceRevision(current);
139
- if(cache.registry&&cache.registryRevision===revision)return cache.registry;
140
- const stored=readScenarioRegistry(current);
141
- if(stored){cache.registry=cache.lastRegistry=stored;cache.registryRevision=revision;return stored;}
142
- if(cache.registryTask?.revision!==revision){
143
- const inspector=cache.registryInspector??=createScenarioInspector(root);
144
- const task={revision,promise:inspector.inspect()};cache.registryTask=task;
145
- void task.promise.finally(()=>{if(cache.registryTask===task)cache.registryTask=undefined;}).catch(()=>{});
262
+ for (let attempt = 0; attempt < 2; attempt++) {
263
+ const current = loadConfig(root),
264
+ revision = await previewSourceRevision(current);
265
+ if (cache.registry && cache.registryRevision === revision) return cache.registry;
266
+ const stored = await readScenarioRegistry(current);
267
+ if (stored) {
268
+ cache.registry = cache.lastRegistry = stored;
269
+ cache.registryRevision = revision;
270
+ return stored;
271
+ }
272
+ if (cache.registryTask?.revision !== revision) {
273
+ const inspector = (cache.registryInspector ??= createScenarioInspector(root));
274
+ const task = {
275
+ revision,
276
+ promise: inspector.inspect(),
277
+ };
278
+ cache.registryTask = task;
279
+ void task.promise
280
+ .finally(() => {
281
+ if (cache.registryTask === task) cache.registryTask = undefined;
282
+ })
283
+ .catch(() => {});
146
284
  }
147
- const registry=await cache.registryTask.promise;
148
- if(previewSourceRevision(loadConfig(root))!==revision)continue;
149
- cache.registry=cache.lastRegistry=registry;cache.registryRevision=revision;cache.catalog=undefined;
285
+ const registry = await cache.registryTask.promise;
286
+ if ((await previewSourceRevision(loadConfig(root))) !== revision) continue;
287
+ cache.registry = cache.lastRegistry = registry;
288
+ cache.registryRevision = revision;
289
+ cache.catalog = undefined;
150
290
  return registry;
151
291
  }
152
292
  throw new Error("Sources changed during scenario discovery. Retry against the current source.");
153
293
  }
154
- const quickRegistry = () => {
155
- if(cache.registry??cache.lastRegistry)return cache.registry??cache.lastRegistry;
156
- const stored=readScenarioRegistry(loadConfig(root));
157
- if(stored)cache.lastRegistry=stored;
158
- return stored??{scenarios:[],diagnostics:[]};
294
+ const quickRegistry = async () => {
295
+ if (cache.registry ?? cache.lastRegistry) return cache.registry ?? cache.lastRegistry;
296
+ const stored = await readScenarioRegistry(loadConfig(root));
297
+ if (stored) cache.lastRegistry = stored;
298
+ return (
299
+ stored ?? {
300
+ scenarios: [],
301
+ diagnostics: [],
302
+ }
303
+ );
159
304
  };
160
- const previewRegistry = waitFor => waitFor === "compiled" && (cache.registry??cache.lastRegistry) ? cache.registry??cache.lastRegistry : getRegistryAsync();
161
- function captureInventory() {
162
- const current = loadConfig(root), registry = getRegistry();
163
- return { ...registry, revision: previewSourceRevision(current) };
305
+ const previewRegistry = async (waitFor) =>
306
+ waitFor === "compiled" && (cache.registry ?? cache.lastRegistry) ? (cache.registry ?? cache.lastRegistry) : await getRegistryAsync();
307
+ async function captureInventory() {
308
+ const current = loadConfig(root),
309
+ registry = await getRegistryAsync();
310
+ return {
311
+ ...registry,
312
+ revision: await previewSourceRevision(current),
313
+ };
314
+ }
315
+ async function captureIndex() {
316
+ const inventory = await captureInventory();
317
+ return captures.store.list(inventory.scenarios, inventory.revision, {
318
+ prune: !inventory.diagnostics.length,
319
+ });
164
320
  }
165
- function captureIndex() { const inventory = captureInventory(); return captures.store.list(inventory.scenarios, inventory.revision, { prune: !inventory.diagnostics.length }); }
166
- const scenarioApps = (quick = false) => (quick ? quickRegistry() : getRegistry()).scenarios.map(item => ({ id: item.id, title: item.title, kind: item.kind, ...(item.samples ? { samples: item.samples } : {}), file: item.artifact }));
167
- const tokenScenarios = () => {
168
- const references=drafts.list({unit:"tokens",limit:100000}).drafts.map(({id,title,revision,state,preview})=>({id,title,revision,state,preview}));
169
- return getRegistry().scenarios.filter(item => item.kind === "tokens").map(item => ({ id:item.id,title:item.title,count:item.tokens.length,drafts:references }));
321
+ const scenarioApps = async (quick = false) =>
322
+ (quick ? await quickRegistry() : await getRegistry()).scenarios.map((item) => ({
323
+ id: item.id,
324
+ title: item.title,
325
+ kind: item.kind,
326
+ ...(item.samples ? { samples: item.samples } : {}),
327
+ file: item.artifact,
328
+ }));
329
+ const tokenScenarios = async () => {
330
+ const references = (
331
+ await drafts.list({
332
+ unit: "tokens",
333
+ limit: 100000,
334
+ })
335
+ ).drafts.map(({ id, title, revision, state, preview }) => ({
336
+ id,
337
+ title,
338
+ revision,
339
+ state,
340
+ preview,
341
+ }));
342
+ return (await getRegistry()).scenarios
343
+ .filter((item) => item.kind === "tokens")
344
+ .map((item) => ({ id: item.id, title: item.title, count: item.tokens.length, drafts: references }));
170
345
  };
171
- const allApps = (quick = false) => [...options.config.mcp.apps, ...scenarioApps(quick)];
172
- const scenarioWidget = () => options.config.mcp.previewManifest ? PREVIEW_APP_URI : SCENARIO_APP_URI;
173
346
  const previewOptions = () => withPreviewSession(options, previewWatch?.resourceSession?.());
174
347
  const resourceAssets = () => {
175
- try { return Object.entries(readPreviewManifest(previewOptions())?.assets ?? {}).map(([uri, record]) => ({ uri, name: `Preview asset ${uri.slice("ads://assets/".length)}`, mimeType: record.mimeType, size: record.size })); }
176
- catch { return []; } // Discovery and diagnostics remain usable after a failed graph.
348
+ try {
349
+ return Object.entries(readPreviewManifest(previewOptions())?.assets ?? {}).map(([uri, record]) => ({
350
+ uri,
351
+ name: `Preview asset ${uri.slice("ads://assets/".length)}`,
352
+ mimeType: record.mimeType,
353
+ size: record.size,
354
+ }));
355
+ } catch {
356
+ return [];
357
+ } // Discovery and diagnostics remain usable after a failed graph.
177
358
  };
178
359
  function graphSelection(id, build) {
179
- if (!options.config.mcp.previewManifest) return {};
180
360
  const live = build?.live && !build.current;
181
361
  const manifest = readPreviewManifest(live ? livePreviewOptions(previewOptions()) : previewOptions());
182
- if (!manifest?.scenarios.some(entry => entry.id === id)) throw new Error("The preview resource graph is not ready for this scenario. Rebuild previews.");
183
- return { manifestUri: live ? LIVE_PREVIEW_MANIFEST_URI : PREVIEW_MANIFEST_URI, manifestRevision: manifest.revision };
362
+ if (!manifest?.scenarios.some((entry) => entry.id === id)) throw new Error("The preview resource graph is not ready for this scenario. Rebuild previews.");
363
+ return {
364
+ manifestUri: live ? LIVE_PREVIEW_MANIFEST_URI : PREVIEW_MANIFEST_URI,
365
+ manifestRevision: manifest.revision,
366
+ };
184
367
  }
185
368
  async function getCatalog() {
186
- for(let attempt=0;attempt<2;attempt++){
187
- await getRegistryAsync();const revision=cache.registryRevision;
188
- if(cache.catalog&&cache.catalogRevision===revision)return cache.catalog;
189
- if(cache.catalogTask?.revision!==revision){
190
- const inspector=cache.registryInspector??=createScenarioInspector(root);
191
- const task={revision,promise:inspector.inspect(root,"catalog")};cache.catalogTask=task;
192
- void task.promise.finally(()=>{if(cache.catalogTask===task)cache.catalogTask=undefined;}).catch(()=>{});
369
+ for (let attempt = 0; attempt < 2; attempt++) {
370
+ await getRegistryAsync();
371
+ const revision = cache.registryRevision;
372
+ if (cache.catalog && cache.catalogRevision === revision) return cache.catalog;
373
+ if (cache.catalogTask?.revision !== revision) {
374
+ const inspector = (cache.registryInspector ??= createScenarioInspector(root));
375
+ const task = {
376
+ revision,
377
+ promise: inspector.inspect(root, "catalog"),
378
+ };
379
+ cache.catalogTask = task;
380
+ void task.promise
381
+ .finally(() => {
382
+ if (cache.catalogTask === task) cache.catalogTask = undefined;
383
+ })
384
+ .catch(() => {});
193
385
  }
194
- const value=await cache.catalogTask.promise;
195
- if(previewSourceRevision(loadConfig(root))!==revision)continue;
196
- cache.catalog=value.catalog;cache.catalogRevision=revision;cache.behaviorLibraries={libraries:value.libraries};return cache.catalog;
386
+ const value = await cache.catalogTask.promise;
387
+ if ((await previewSourceRevision(loadConfig(root))) !== revision) continue;
388
+ cache.catalog = value.catalog;
389
+ cache.catalogRevision = revision;
390
+ cache.behaviorLibraries = {
391
+ libraries: value.libraries,
392
+ };
393
+ return cache.catalog;
197
394
  }
198
395
  throw new Error("Sources changed during catalogue discovery. Retry against the current source.");
199
396
  }
200
397
  const getBehaviorLibraries = () => cache.behaviorLibraries;
201
- function annotateDrafts(items, found = drafts.list({limit:100000}).drafts) {
202
- const units = edits.units();
203
- return items.map(item => {
204
- const unit = units.find(unit => unit.files.includes(item.file))?.id ?? null;
205
- return { ...item, unit, drafts: found.filter(draft => draft.units.includes(unit)).map(({id,title,revision,state,preview}) => ({id,title,revision,state,preview})) };
398
+ async function annotateDrafts(items, found) {
399
+ if (found === undefined)
400
+ found = (
401
+ await drafts.list({
402
+ limit: 100000,
403
+ })
404
+ ).drafts;
405
+ const units = await edits.units();
406
+ return items.map((item) => {
407
+ const unit = units.find((unit) => unit.files.includes(item.file))?.id ?? null;
408
+ return {
409
+ ...item,
410
+ unit,
411
+ drafts: found
412
+ .filter((draft) => draft.units.includes(unit))
413
+ .map(({ id, title, revision, state, preview }) => ({
414
+ id,
415
+ title,
416
+ revision,
417
+ state,
418
+ preview,
419
+ })),
420
+ };
206
421
  });
207
422
  }
208
- const getDocuments = () => cache.documents ??= projectDocuments(options);
423
+ const getDocuments = () => (cache.documents ??= projectDocuments(options));
209
424
  async function explorer() {
210
- const registry=await getRegistryAsync(), proposals=drafts.list({limit:100000}).drafts;
211
- const scenarios=annotateDrafts(registry.scenarios,proposals).map(({id,title,kind,group,unit,drafts})=>({id,title,kind,...(group?{group}:{}),unit,drafts}));
212
- return {status:{projectRoot:root,project:{showcase:project().showcase},themes:options.config.themes,...(options.config.brands.length?{brands:options.config.brands}:{}),icons:Boolean(options.config.assets.glyphs),drafts:{previewOnly:isDraftPreviewWorkspace(root)},previewWatch:previewWatch?.status(),build:summarizeBuild(builds())},
213
- scenarios,categories:scenarios.filter(item=>item.kind==="tokens").map(item=>({...item,count:registry.scenarios.find(value=>value.id===item.id)?.tokens?.length??0})),drafts:proposals,
214
- tools:tools().map(({name,_meta,schema})=>{const waitFor=z.toJSONSchema(schema).properties?.waitFor;return{name,...(_meta?{_meta}:{}),inputSchema:{properties:waitFor?{waitFor}:{}}};}),diagnostics:registry.diagnostics};
425
+ const registry = await getRegistryAsync(),
426
+ proposals = (
427
+ await drafts.list({
428
+ limit: 100000,
429
+ })
430
+ ).drafts;
431
+ const scenarios = (await annotateDrafts(registry.scenarios, proposals)).map(({ id, title, kind, group, unit, drafts }) => ({
432
+ id,
433
+ title,
434
+ kind,
435
+ ...(group
436
+ ? {
437
+ group,
438
+ }
439
+ : {}),
440
+ unit,
441
+ drafts,
442
+ }));
443
+ return {
444
+ status: {
445
+ projectRoot: root,
446
+ project: {
447
+ showcase: project().showcase,
448
+ },
449
+ themes: options.config.themes,
450
+ ...(options.config.brands.length
451
+ ? {
452
+ brands: options.config.brands,
453
+ }
454
+ : {}),
455
+ icons: Boolean(options.config.assets.glyphs),
456
+ drafts: {
457
+ previewOnly: isDraftPreviewWorkspace(root),
458
+ },
459
+ compiler: previewWatch?.status(),
460
+ build: summarizeBuild(await builds()),
461
+ },
462
+ scenarios,
463
+ categories: scenarios
464
+ .filter((item) => item.kind === "tokens")
465
+ .map((item) => ({ ...item, count: registry.scenarios.find((value) => value.id === item.id)?.tokens?.length ?? 0 })),
466
+ drafts: proposals,
467
+ tools: tools().map(({ name, _meta, schema }) => {
468
+ const waitFor = z.toJSONSchema(schema).properties?.waitFor;
469
+ return {
470
+ name,
471
+ ...(_meta
472
+ ? {
473
+ _meta,
474
+ }
475
+ : {}),
476
+ inputSchema: {
477
+ properties: waitFor
478
+ ? {
479
+ waitFor,
480
+ }
481
+ : {},
482
+ },
483
+ };
484
+ }),
485
+ diagnostics: registry.diagnostics,
486
+ };
215
487
  }
216
- const builds = () => {
217
- previewWatch?.setApps(allApps(true));
218
- const report = previewWatch?.buildStatus() ?? inspectBuildStatus(root, { ...options.config.mcp, apps: allApps(true) });
219
- return { ...report, drafts: drafts.previewStatuses() };
488
+ const builds = async () => {
489
+ previewWatch?.setApps(await scenarioApps(true));
490
+ const report =
491
+ (await previewWatch?.buildStatus()) ??
492
+ (await inspectBuildStatus(root, {
493
+ ...options.config.mcp,
494
+ apps: await scenarioApps(true),
495
+ }));
496
+ return {
497
+ ...report,
498
+ drafts: drafts.previewStatuses(),
499
+ };
220
500
  };
221
- const previews = () => options.config.mcp.apps.map((app) => ({ id: app.id, title: app.title, kind: app.kind, tool: `ads_show_${app.id.replaceAll("-", "_")}`, resourceUri: appUri(app.id), available: existsSync(path.resolve(root, app.file)), file: app.file }));
222
-
223
- function reportContext(submission) {
224
- const captured = { ads: { package: pkg.name, version: pkg.version }, capturedAt: new Date().toISOString(), framework: null,
225
- runtime: { ...developmentRuntime(), platform: process.platform, arch: process.arch }, warnings: [] };
226
- try { const current=loadConfig(root);captured.framework=current.config.framework;captured.configurationRevision=createHash("sha256").update(JSON.stringify(current.config)).digest("hex");captured.sourceRevision=previewSourceRevision(current); }
227
- catch { captured.warnings.push("Current configuration/source revision could not be captured."); }
228
- try{const projectPackage=JSON.parse(readFileSync(path.join(root,"package.json"),"utf8"));if(typeof projectPackage.name==="string")captured.project={name:projectPackage.name.slice(0,160)};}catch{captured.warnings.push("Project package name could not be captured.");}
229
- try { const build=builds(),preview=build.previews?.find(item=>item.id===submission.scenario);captured.build={state:build.state,updatedAt:build.updatedAt,session:build.session,sequence:build.sequence,...(preview?{preview:{id:preview.id,state:preview.state,revision:preview.revision,current:preview.current,stale:preview.stale}}:{})}; }
230
- catch { captured.warnings.push("Current build metadata could not be captured."); }
231
- // Target names can describe an unaccepted draft; they are agent claims, not registrations.
232
- if(submission.scenario)try{captured.scenarioRegistered=getRegistry().scenarios.some(item=>item.id===submission.scenario);}catch{captured.scenarioRegistered=null;}
233
- if(submission.unit)try{captured.unitRegistered=edits.units().some(item=>item.id===submission.unit);}catch{captured.unitRegistered=null;}
234
- return captured;
235
- }
236
- function reportEvidence(reference) {
237
- if(reference.resultId)return JSON.parse(executionResults.readResource(`ads://results/${reference.resultId}`).text);
238
- const bundle=readInvestigation(root,reference);
239
- if(bundle.runId!==reference.runId)throw new Error("Investigation was superseded. Reference the exact current unit/check/runId or describe earlier observations without attaching unrelated evidence.");
240
- const {unit,check,runId,status,target,inputRevision,observedPreviewRevision,framework,profile,completedAt,failure,source,failingStep,viewport,acceptance}=bundle;
241
- return {unit,check,runId,status,target,inputRevision,observedPreviewRevision,framework,profile,completedAt,failure,source,failingStep,viewport,acceptance,
242
- artifacts:(bundle.artifacts??[]).slice(0,3).map(({resourceUri,digest,mimeType,available})=>({resourceUri,digest,mimeType,available})),artifactsAreReferences:true};
243
- }
244
- function submitReport(kind,args) {
245
- return json(reports.submit(kind,args));
246
- }
247
-
248
- function resources() {
501
+ async function resources() {
249
502
  const context = project();
250
503
  const documents = getDocuments();
251
504
  const promoted = new Set([context.publicEntryUri, context.review.sourceUri, ...context.guides.map((guide) => guide.uri)]);
252
505
  const skillEntries = new Set(skills.skills.map((skill) => skill.uri));
253
506
  return [
254
- { uri: GUIDE_URI, name: "Start here: design-system workflow", description: "Read first for UI/ADS tasks, especially when only resource access is exposed. Explains the exact workspace, tool sequence, skill selection, previews, project commands and fallback.", mimeType: "text/markdown" },
255
- { uri: "ads://guides/behaviors", name: "Controller and behavioral verification guide", mimeType: "text/markdown" },
256
- { uri: "ads://guides/workflows", name: "Direct code editing and MCP-only editing workflows", mimeType: "text/markdown" },
257
- { uri: "ads://guides/validation", name: "Full and affected validation; test boundaries", mimeType: "text/markdown" },
258
- { uri: "ads://guides/runtimes", name: "Node and Bun setup, compiler and verification runtime", mimeType: "text/markdown" },
259
- { uri: "ads://guides/evidence", name: "Failure boundaries and compact investigations", mimeType: "text/markdown" },
260
- { uri: "ads://guides/atomic-styles", name: "Atomic styles: composition conflicts and custom-property extraction", mimeType: "text/markdown" },
261
- { uri: "ads://guides/scenarios", name: "Scenario coverage and public class-helper contracts", mimeType: "text/markdown" },
262
- { uri: "ads://guides/layers", name: "Component capabilities, pattern composition and dependency ownership", mimeType: "text/markdown" },
263
- { uri: "ads://guides/contracts", name: "Static owner contracts, typed paints and guarded migration", mimeType: "text/markdown" },
264
- { uri: "ads://guides/review", name: "Development-only review UI, token renderers and migration", mimeType: "text/markdown" },
265
- { uri: "ads://guides/captures", name: "On-demand captures and candidate visual review", mimeType: "text/markdown" },
266
- { uri: `${PROJECT_URI}/status`, name: "ADS project status", mimeType: "application/json" },
267
- { uri: `${PROJECT_URI}/explorer`, name: "Explorer navigation and preview bootstrap", mimeType: "application/json" },
268
- { uri: BUILD_URI, name: "Preview build status and diagnostics", mimeType: "application/json" },
269
- { uri: `${PROJECT_URI}/tokens`, name: "Project token values and themes", mimeType: "application/json" },
270
- { uri: ICONS_URI, name: "Glyph set, aliases, icon sizes, glyph findings and other products' logos", mimeType: "application/json" },
271
- { uri: `${PROJECT_URI}/catalog`, name: "Public components and patterns", mimeType: "application/json" },
272
- { uri: DRAFTS_URI, name: "Tracked ADS drafts and acceptance events", mimeType: "application/json" },
273
- ...drafts.previewStatuses().map(({ id, resourceUri }) => ({ uri: resourceUri, name: `Draft ${id}: preview build status and diagnostics`, mimeType: "application/json" })),
274
- { uri: "ads://guides/drafts", name: "Auto-mode tracked draft workflow", mimeType: "text/markdown" },
275
- { uri: `${PROJECT_URI}/scenarios`, name: "Independently mountable scenarios", mimeType: "application/json" },
276
- { uri: BEHAVIOR_URI, name: "Behavior contracts, demonstrations and current verification evidence", mimeType: "application/json" },
277
- { uri: RESULTS_URI, name: "Latest execution summaries and paged outcomes", mimeType: "application/json" },
278
- { uri: INVESTIGATIONS_URI, name: "Latest per-check investigation evidence", mimeType: "application/json" },
279
- { uri: CAPTURES_URI, name: "On-demand current and candidate screenshots", mimeType: "application/json" },
280
- { uri: `${PROJECT_URI}/checks`, name: "Current ADS architecture diagnostics", mimeType: "application/json" },
507
+ {
508
+ uri: GUIDE_URI,
509
+ name: "Start here: design-system workflow",
510
+ description:
511
+ "Read first for UI/ADS tasks, especially when only resource access is exposed. Explains the exact workspace, tool sequence, skill selection, previews, project commands and fallback.",
512
+ mimeType: "text/markdown",
513
+ },
514
+ {
515
+ uri: "ads://guides/behaviors",
516
+ name: "Controller and behavioral verification guide",
517
+ mimeType: "text/markdown",
518
+ },
519
+ {
520
+ uri: "ads://guides/workflows",
521
+ name: "Direct code editing and MCP-only editing workflows",
522
+ mimeType: "text/markdown",
523
+ },
524
+ {
525
+ uri: "ads://guides/validation",
526
+ name: "Full and affected validation; test boundaries",
527
+ mimeType: "text/markdown",
528
+ },
529
+ {
530
+ uri: "ads://guides/runtimes",
531
+ name: "Node and Bun setup, compiler and verification runtime",
532
+ mimeType: "text/markdown",
533
+ },
534
+ {
535
+ uri: "ads://guides/evidence",
536
+ name: "Failure boundaries and compact investigations",
537
+ mimeType: "text/markdown",
538
+ },
539
+ {
540
+ uri: "ads://guides/atomic-styles",
541
+ name: "Atomic styles: composition conflicts and custom-property extraction",
542
+ mimeType: "text/markdown",
543
+ },
544
+ {
545
+ uri: "ads://guides/scenarios",
546
+ name: "Scenario coverage and public class-helper contracts",
547
+ mimeType: "text/markdown",
548
+ },
549
+ {
550
+ uri: "ads://guides/layers",
551
+ name: "Component capabilities, pattern composition and dependency ownership",
552
+ mimeType: "text/markdown",
553
+ },
554
+ {
555
+ uri: "ads://guides/contracts",
556
+ name: "Static owner contracts and typed paints",
557
+ mimeType: "text/markdown",
558
+ },
559
+ {
560
+ uri: "ads://guides/review",
561
+ name: "Development-only review UI and migration",
562
+ mimeType: "text/markdown",
563
+ },
564
+ {
565
+ uri: "ads://guides/captures",
566
+ name: "On-demand captures and candidate visual review",
567
+ mimeType: "text/markdown",
568
+ },
569
+ {
570
+ uri: `${PROJECT_URI}/status`,
571
+ name: "ADS project status",
572
+ mimeType: "application/json",
573
+ },
574
+ {
575
+ uri: `${PROJECT_URI}/explorer`,
576
+ name: "Explorer navigation and preview bootstrap",
577
+ mimeType: "application/json",
578
+ },
579
+ {
580
+ uri: BUILD_URI,
581
+ name: "Preview build status and diagnostics",
582
+ mimeType: "application/json",
583
+ },
584
+ {
585
+ uri: `${PROJECT_URI}/tokens`,
586
+ name: "Project token values and themes",
587
+ mimeType: "application/json",
588
+ },
589
+ {
590
+ uri: `${PROJECT_URI}/tokens/dtcg`,
591
+ name: "Project tokens as W3C Design Tokens (DTCG) JSON",
592
+ description: "The same export as `ads tokens --format dtcg`: the first theme and brand; other themes and brands in $extensions.",
593
+ mimeType: "application/json",
594
+ },
595
+ {
596
+ uri: ICONS_URI,
597
+ name: "Glyph set, aliases, icon sizes, glyph findings and other products' logos",
598
+ mimeType: "application/json",
599
+ },
600
+ {
601
+ uri: `${PROJECT_URI}/catalog`,
602
+ name: "Public components and patterns",
603
+ mimeType: "application/json",
604
+ },
605
+ {
606
+ uri: DRAFTS_URI,
607
+ name: "Tracked ADS drafts and acceptance events",
608
+ mimeType: "application/json",
609
+ },
610
+ ...drafts.previewStatuses().map(({ id, resourceUri }) => ({
611
+ uri: resourceUri,
612
+ name: `Draft ${id}: preview build status and diagnostics`,
613
+ mimeType: "application/json",
614
+ })),
615
+ {
616
+ uri: "ads://guides/drafts",
617
+ name: "Auto-mode tracked draft workflow",
618
+ mimeType: "text/markdown",
619
+ },
620
+ {
621
+ uri: `${PROJECT_URI}/scenarios`,
622
+ name: "Independently mountable scenarios",
623
+ mimeType: "application/json",
624
+ },
625
+ {
626
+ uri: BEHAVIOR_URI,
627
+ name: "Behavior contracts, demonstrations and current verification evidence",
628
+ mimeType: "application/json",
629
+ },
630
+ {
631
+ uri: RESULTS_URI,
632
+ name: "Latest execution summaries and paged outcomes",
633
+ mimeType: "application/json",
634
+ },
635
+ {
636
+ uri: INVESTIGATIONS_URI,
637
+ name: "Latest per-check investigation evidence",
638
+ mimeType: "application/json",
639
+ },
640
+ {
641
+ uri: CAPTURES_URI,
642
+ name: "On-demand current and candidate screenshots",
643
+ mimeType: "application/json",
644
+ },
645
+ {
646
+ uri: `${PROJECT_URI}/checks`,
647
+ name: "Current ADS architecture diagnostics",
648
+ mimeType: "application/json",
649
+ },
281
650
  // Keep fallback workflow metadata discoverable in the bounded first page.
282
- ...skills.skills.map(({ uri, frontmatter }) => ({ uri, name: frontmatter.name, description: frontmatter.description, mimeType: "text/markdown" })),
283
- ...documents.filter(document => promoted.has(document.uri)).sort((a, b) => Number(b.uri === context.publicEntryUri) - Number(a.uri === context.publicEntryUri)).map(({ file: _file, ...document }) => document),
284
- { uri: "ads://guides/tokens", name: "Shared Data and component variable boundaries", mimeType: "text/markdown" },
285
- { uri: "ads://guides/branding", name: "Brand artwork, icons, committed targets and glyph sets", mimeType: "text/markdown" },
286
- { uri: "ads://guides/accessibility", name: "WCAG 2.2 AA guards and accessibility practice", mimeType: "text/markdown" },
287
- { uri: "ads://guides/performance", name: "Images, fonts, layout shift and what ADS leaves to Lighthouse", mimeType: "text/markdown" },
288
- { uri: "ads://guides/reporting", name: "Report suspected ADS bugs and feature requests", mimeType: "text/markdown" },
289
- { uri: TOKENS_APP_URI, name: "Experimental token widget", mimeType: APP_MIME },
290
- { uri: SCENARIO_APP_URI, name: "Experimental scenario widget", mimeType: APP_MIME },
291
- ...(options.config.mcp.previewManifest ? [{ uri: PREVIEW_APP_URI, name: "Shared-resource preview App", mimeType: APP_MIME }, { uri: PREVIEW_MANIFEST_URI, name: "Verified preview dependency graph", mimeType: "application/json" }, { uri: LIVE_PREVIEW_MANIFEST_URI, name: "Unverified live feedback; background checks pending", mimeType: "application/json" }] : []),
292
- ...(options.config.mcp.previewManifest ? resourceAssets() : []),
293
- ...allApps().map((app) => ({ uri: appUri(app.id), name: app.title, description: app.description, mimeType: APP_MIME })),
651
+ ...skills.skills.map(({ uri, frontmatter }) => ({
652
+ uri,
653
+ name: frontmatter.name,
654
+ description: frontmatter.description,
655
+ mimeType: "text/markdown",
656
+ })),
657
+ ...documents
658
+ .filter((document) => promoted.has(document.uri))
659
+ .sort((a, b) => Number(b.uri === context.publicEntryUri) - Number(a.uri === context.publicEntryUri))
660
+ .map(({ file: _file, ...document }) => document),
661
+ {
662
+ uri: "ads://guides/tokens",
663
+ name: "Shared Data and component variable boundaries",
664
+ mimeType: "text/markdown",
665
+ },
666
+ {
667
+ uri: "ads://guides/branding",
668
+ name: "Brand artwork, icons, committed targets and glyph sets",
669
+ mimeType: "text/markdown",
670
+ },
671
+ {
672
+ uri: "ads://guides/accessibility",
673
+ name: "WCAG 2.2 AA guards and accessibility practice",
674
+ mimeType: "text/markdown",
675
+ },
676
+ {
677
+ uri: "ads://guides/layout",
678
+ name: "Spatial layouts: @ads-layout constructions, regions, panels and worked examples",
679
+ mimeType: "text/markdown",
680
+ },
681
+ {
682
+ uri: "ads://guides/performance",
683
+ name: "Images, fonts, layout shift and what ADS leaves to Lighthouse",
684
+ mimeType: "text/markdown",
685
+ },
686
+ {
687
+ uri: PREVIEW_APP_URI,
688
+ name: "Shared-resource preview App",
689
+ mimeType: APP_MIME,
690
+ },
691
+ {
692
+ uri: PREVIEW_MANIFEST_URI,
693
+ name: "Verified preview dependency graph",
694
+ mimeType: "application/json",
695
+ },
696
+ {
697
+ uri: LIVE_PREVIEW_MANIFEST_URI,
698
+ name: "Unverified live feedback; background checks pending",
699
+ mimeType: "application/json",
700
+ },
701
+ ...resourceAssets(),
702
+ ...(await scenarioApps()).map((app) => ({ uri: appUri(app.id), name: app.title, description: app.description, mimeType: APP_MIME })),
294
703
  ...documents.filter((document) => !promoted.has(document.uri)).map(({ file: _file, ...document }) => document),
295
- ...[...skills.files.values()].filter((file) => !skillEntries.has(file.uri)).map(({ uri, name, mimeType }) => ({ uri, name, mimeType })),
704
+ ...[...skills.files.values()]
705
+ .filter((file) => !skillEntries.has(file.uri))
706
+ .map(({ uri, name, mimeType }) => ({
707
+ uri,
708
+ name,
709
+ mimeType,
710
+ })),
296
711
  ];
297
712
  }
298
713
  async function status() {
299
- const context = project(), mutationState = mutations ? edits.status() : null, behaviorState = verification.status();
300
- const catalog = await getCatalog(), registry = cache.registry;
301
- return { projectRoot: root, taskCache:taskCacheSettings(root), workflow: workflow([...previews(), ...scenarioApps(true)]), project: context,
302
- package: pkg.name, version: pkg.version, dsDir: options.config.dsDir, publicAlias: options.config.publicAlias, behaviorLibraries: getBehaviorLibraries().libraries,
714
+ const context = project(),
715
+ mutationState = mutations ? edits.status() : null;
716
+ const catalog = await getCatalog(),
717
+ registry = cache.registry;
718
+ return {
719
+ projectRoot: root,
720
+ taskCache: taskCacheSettings(root),
721
+ workflow: workflow(await scenarioApps(true)),
722
+ project: context,
723
+ package: pkg.name,
724
+ version: pkg.version,
725
+ dsDir: options.config.dsDir,
726
+ publicAlias: options.config.publicAlias,
727
+ behaviorLibraries: getBehaviorLibraries().libraries,
303
728
  components: catalog.filter((item) => item.kind === "components" && item.apiKind === "ui").length,
304
729
  patterns: catalog.filter((item) => item.kind === "patterns" && item.apiKind === "ui").length,
305
- tokenCount: inspectTokens(root).tokens.length, themes: options.config.themes, ...(options.config.brands.length ? { brands: options.config.brands } : {}), showcaseUrl: getShowcaseUrl(),
730
+ tokenCount: (await tokenInventory()).tokens.length,
731
+ themes: options.config.themes,
732
+ ...(options.config.brands.length
733
+ ? {
734
+ brands: options.config.brands,
735
+ }
736
+ : {}),
737
+ showcaseUrl: getShowcaseUrl(),
306
738
  resourceLimits: resourceLimitsStatus(options.config.resources),
307
- policies:{acceptance:options.config.acceptance,validation:options.config.validation},
308
- previewWatch: previewWatch?.status() ?? { state: "disabled" },
309
- mutations: mutations ? { ...mutationState, progress: compactProgress(mutationState.progress), lastResult: executionResults.latest("mutation") } : { enabled: false },
310
- drafts: { mode:"auto", enabled:mutations, resourceUri:DRAFTS_URI, listTool:"ads_drafts", previewTool:"ads_show_draft", acceptTool:"ads_accept", previewOnly:isDraftPreviewWorkspace(root), events:drafts.events().slice(-3) },
311
- build: summarizeBuild(builds()),
312
- previews: previews(), skills: skills.skills.map(({ uri, frontmatter }) => ({ uri, name: frontmatter.name, description: frontmatter.description })),
313
- scenarios: { count: registry.scenarios.length, diagnostics: registry.diagnostics, resourceUri: `${PROJECT_URI}/scenarios`, tool: "ads_show_scenario" },
739
+ gates: {
740
+ acceptance: options.config.acceptance,
741
+ validation: options.config.validation,
742
+ },
743
+ compiler: previewWatch?.status() ?? {
744
+ state: "disabled",
745
+ },
746
+ mutations: mutations
747
+ ? {
748
+ ...mutationState,
749
+ progress: compactProgress(mutationState.progress),
750
+ lastResult: executionResults.latest("mutation"),
751
+ }
752
+ : {
753
+ enabled: false,
754
+ },
755
+ drafts: {
756
+ mode: "auto",
757
+ enabled: mutations,
758
+ resourceUri: DRAFTS_URI,
759
+ listTool: "ads_drafts",
760
+ previewTool: "ads_show_draft",
761
+ acceptTool: "ads_accept",
762
+ previewOnly: isDraftPreviewWorkspace(root),
763
+ events: drafts.events().slice(-3),
764
+ },
765
+ build: summarizeBuild(await builds()),
766
+ skills: skills.skills.map(({ uri, frontmatter }) => ({
767
+ uri,
768
+ name: frontmatter.name,
769
+ description: frontmatter.description,
770
+ })),
771
+ scenarios: {
772
+ count: registry.scenarios.length,
773
+ diagnostics: registry.diagnostics,
774
+ resourceUri: `${PROJECT_URI}/scenarios`,
775
+ tool: "ads_show_scenario",
776
+ },
314
777
  execution: coordinator.status(),
315
- validation: { ...validation.status(), tool: "ads_validate", lastResult: executionResults.latest("validation") },
316
- behaviors: { resourceUri: BEHAVIOR_URI, discoveryTool: "ads_behaviors", verificationTool: "ads_verify", investigationTool: "ads_investigate", investigationResourceUri: INVESTIGATIONS_URI, ...behaviorState, progress: compactProgress(behaviorState.progress), lastResult: executionResults.latest("verification"), resultsTool: "ads_results", resultsResourceUri: RESULTS_URI },
317
- captures: { resourceUri: CAPTURES_URI, tool: "ads_capture", clearTool: "ads_capture_clear", ...captures.status() },
318
- reports: { access:"submission-only", storageDirectory:".ds/reports", bugTool:"ads_report_bug", featureTool:"ads_request_feature", guidanceUri:"ads://guides/reporting", delivery:"local-only", retention:"until-explicit-removal" },
319
- experimental: { apps: true, nativeSkills: era === "modern", nativeSkillActivation: "host-controlled" } };
778
+ validation: (({ progress, ...state }) => ({
779
+ ...state,
780
+ ...(progress
781
+ ? {
782
+ progress: compactProgress(progress),
783
+ }
784
+ : {}),
785
+ tool: "ads_validate",
786
+ lastResult: executionResults.latest("validation"),
787
+ }))(validation.status()),
788
+ behaviors: {
789
+ resourceUri: BEHAVIOR_URI,
790
+ discoveryTool: "ads_behaviors",
791
+ investigationTool: "ads_investigate",
792
+ investigationResourceUri: INVESTIGATIONS_URI,
793
+ resultsTool: "ads_results",
794
+ resultsResourceUri: RESULTS_URI,
795
+ },
796
+ captures: {
797
+ resourceUri: CAPTURES_URI,
798
+ tool: "ads_capture",
799
+ clearTool: "ads_capture_clear",
800
+ ...captures.status(),
801
+ },
802
+ experimental: {
803
+ apps: true,
804
+ nativeSkills: era === "modern",
805
+ nativeSkillActivation: "host-controlled",
806
+ },
807
+ };
320
808
  }
809
+ const tokenInventory = () => analyze(root, "tokens");
810
+ const behaviorInventory = (args) => analyze(root, "behavior-page", [args]);
321
811
  async function read(uri, signal) {
322
- if(uri===`${PROJECT_URI}/explorer`)return{contents:[{uri,mimeType:"application/json",text:JSON.stringify(await explorer())}]};
323
- if(uri.startsWith("ads://drafts/")){
324
- const url=new URL(uri),match=url.pathname.match(/^\/([a-z0-9][a-z0-9-]{0,79})\/resource$/);
325
- if(!match||[...url.searchParams.keys()].some(key=>key!=="uri")||!url.searchParams.get("uri"))throw new Error("Invalid draft resource address.");
326
- return drafts.readResource(match[1],url.searchParams.get("uri"),signal);
812
+ if (uri === `${PROJECT_URI}/explorer`)
813
+ return {
814
+ contents: [
815
+ {
816
+ uri,
817
+ mimeType: "application/json",
818
+ text: JSON.stringify(await explorer()),
819
+ },
820
+ ],
821
+ };
822
+ if (uri.startsWith("ads://drafts/")) {
823
+ const url = new URL(uri),
824
+ match = url.pathname.match(/^\/([a-z0-9][a-z0-9-]{0,79})\/resource$/);
825
+ if (!match || [...url.searchParams.keys()].some((key) => key !== "uri") || !url.searchParams.get("uri"))
826
+ throw new Error("Invalid draft resource address.");
827
+ return drafts.readResource(match[1], url.searchParams.get("uri"), signal);
828
+ }
829
+ if (uri === "ads://guides/workflows")
830
+ return {
831
+ contents: [
832
+ {
833
+ uri,
834
+ mimeType: "text/markdown",
835
+ text: readFileSync(new URL("../skills/ads-designer/references/workflows.md", import.meta.url), "utf8"),
836
+ },
837
+ ],
838
+ };
839
+ if (uri === "ads://guides/drafts")
840
+ return {
841
+ contents: [
842
+ {
843
+ uri,
844
+ mimeType: "text/markdown",
845
+ text: readFileSync(new URL("../skills/ads-designer/references/drafts.md", import.meta.url), "utf8"),
846
+ },
847
+ ],
848
+ };
849
+ if (uri === GUIDE_URI) {
850
+ await getRegistryAsync();
851
+ return {
852
+ contents: [
853
+ {
854
+ uri,
855
+ mimeType: "text/markdown",
856
+ text: projectGuide(project(), await scenarioApps()),
857
+ },
858
+ ],
859
+ };
327
860
  }
328
- if (uri === "ads://guides/workflows") return {contents:[{uri,mimeType:"text/markdown",text:readFileSync(new URL("../skills/ads-designer/references/workflows.md",import.meta.url),"utf8")}]};
329
- if (uri === "ads://guides/drafts") return { contents: [{uri,mimeType:"text/markdown",text:readFileSync(new URL("../skills/ads-designer/references/drafts.md",import.meta.url),"utf8")}] };
330
- if (uri === GUIDE_URI) return { contents: [{ uri, mimeType: "text/markdown", text: projectGuide(project(), [...previews(), ...scenarioApps()]) }] };
331
- if (uri === "ads://guides/behaviors") return { contents: [{ uri, mimeType: "text/markdown", text: readFileSync(new URL("../skills/ads-designer/references/behaviors.md", import.meta.url), "utf8") }] };
332
- if (uri === "ads://guides/validation") return { contents: [{ uri, mimeType: "text/markdown", text: readFileSync(new URL("../skills/ads-designer/references/validation.md", import.meta.url), "utf8") }] };
333
- if (uri === "ads://guides/runtimes") return { contents: [{ uri, mimeType: "text/markdown", text: readFileSync(new URL("../skills/ads-designer/references/runtimes.md", import.meta.url), "utf8") }] };
334
- if (uri === "ads://guides/evidence") return { contents: [{ uri, mimeType: "text/markdown", text: readFileSync(new URL("../skills/ads-designer/references/evidence.md", import.meta.url), "utf8") }] };
335
- if (uri === "ads://guides/performance") return { contents: [{ uri, mimeType: "text/markdown", text: readFileSync(new URL("../skills/ads-designer/references/performance.md", import.meta.url), "utf8") }] };
336
- if (uri === "ads://guides/accessibility") return { contents: [{ uri, mimeType: "text/markdown", text: readFileSync(new URL("../skills/ads-designer/references/accessibility.md", import.meta.url), "utf8") }] };
337
- if (uri === "ads://guides/branding") return { contents: [{ uri, mimeType: "text/markdown", text: readFileSync(new URL("../skills/ads-designer/references/branding.md", import.meta.url), "utf8") }] };
338
- if (uri === "ads://guides/tokens") return { contents: [{ uri, mimeType: "text/markdown", text: readFileSync(new URL("../skills/ads-designer/references/design-data.md", import.meta.url), "utf8") }] };
339
- if (uri === "ads://guides/reporting") return { contents: [{ uri, mimeType: "text/markdown", text: readFileSync(new URL("../skills/ads-designer/references/reporting.md", import.meta.url), "utf8") }] };
340
- if (uri === "ads://guides/atomic-styles") return { contents: [{ uri, mimeType: "text/markdown", text: readFileSync(new URL("../skills/ads-designer/references/atomic-styles.md", import.meta.url), "utf8") }] };
341
- if (uri === "ads://guides/scenarios") return { contents: [{ uri, mimeType: "text/markdown", text: readFileSync(new URL("../skills/ads-designer/references/scenarios.md", import.meta.url), "utf8") }] };
342
- if (uri === "ads://guides/layers") return { contents: [{ uri, mimeType: "text/markdown", text: readFileSync(new URL("../skills/ads-designer/references/layers.md", import.meta.url), "utf8") }] };
343
- if (uri === "ads://guides/contracts") return { contents: [{ uri, mimeType: "text/markdown", text: readFileSync(new URL("../skills/ads-designer/references/contracts.md", import.meta.url), "utf8") }] };
344
- if (uri === "ads://guides/review") return { contents: [{ uri, mimeType: "text/markdown", text: readFileSync(new URL("../skills/ads-designer/references/review.md", import.meta.url), "utf8") }] };
345
- if (uri === "ads://guides/captures") return { contents: [{ uri, mimeType: "text/markdown", text: readFileSync(new URL("../skills/ads-designer/references/captures.md", import.meta.url), "utf8") }] };
346
- if (skills.files.has(uri)) return { contents: [skills.read(uri)] };
861
+ if (uri === "ads://guides/behaviors")
862
+ return {
863
+ contents: [
864
+ {
865
+ uri,
866
+ mimeType: "text/markdown",
867
+ text: readFileSync(new URL("../skills/ads-designer/references/behaviors.md", import.meta.url), "utf8"),
868
+ },
869
+ ],
870
+ };
871
+ if (uri === "ads://guides/validation")
872
+ return {
873
+ contents: [
874
+ {
875
+ uri,
876
+ mimeType: "text/markdown",
877
+ text: readFileSync(new URL("../skills/ads-designer/references/validation.md", import.meta.url), "utf8"),
878
+ },
879
+ ],
880
+ };
881
+ if (uri === "ads://guides/runtimes")
882
+ return {
883
+ contents: [
884
+ {
885
+ uri,
886
+ mimeType: "text/markdown",
887
+ text: readFileSync(new URL("../skills/ads-designer/references/runtimes.md", import.meta.url), "utf8"),
888
+ },
889
+ ],
890
+ };
891
+ if (uri === "ads://guides/evidence")
892
+ return {
893
+ contents: [
894
+ {
895
+ uri,
896
+ mimeType: "text/markdown",
897
+ text: readFileSync(new URL("../skills/ads-designer/references/evidence.md", import.meta.url), "utf8"),
898
+ },
899
+ ],
900
+ };
901
+ if (uri === "ads://guides/performance")
902
+ return {
903
+ contents: [
904
+ {
905
+ uri,
906
+ mimeType: "text/markdown",
907
+ text: readFileSync(new URL("../skills/ads-designer/references/performance.md", import.meta.url), "utf8"),
908
+ },
909
+ ],
910
+ };
911
+ if (uri === "ads://guides/accessibility")
912
+ return {
913
+ contents: [
914
+ {
915
+ uri,
916
+ mimeType: "text/markdown",
917
+ text: readFileSync(new URL("../skills/ads-designer/references/accessibility.md", import.meta.url), "utf8"),
918
+ },
919
+ ],
920
+ };
921
+ if (uri === "ads://guides/layout")
922
+ return {
923
+ contents: [
924
+ {
925
+ uri,
926
+ mimeType: "text/markdown",
927
+ text: readFileSync(new URL("../skills/ads-designer/references/layout.md", import.meta.url), "utf8"),
928
+ },
929
+ ],
930
+ };
931
+ if (uri === "ads://guides/branding")
932
+ return {
933
+ contents: [
934
+ {
935
+ uri,
936
+ mimeType: "text/markdown",
937
+ text: readFileSync(new URL("../skills/ads-designer/references/branding.md", import.meta.url), "utf8"),
938
+ },
939
+ ],
940
+ };
941
+ if (uri === "ads://guides/tokens")
942
+ return {
943
+ contents: [
944
+ {
945
+ uri,
946
+ mimeType: "text/markdown",
947
+ text: readFileSync(new URL("../skills/ads-designer/references/design-data.md", import.meta.url), "utf8"),
948
+ },
949
+ ],
950
+ };
951
+ if (uri === "ads://guides/atomic-styles")
952
+ return {
953
+ contents: [
954
+ {
955
+ uri,
956
+ mimeType: "text/markdown",
957
+ text: readFileSync(new URL("../skills/ads-designer/references/atomic-styles.md", import.meta.url), "utf8"),
958
+ },
959
+ ],
960
+ };
961
+ if (uri === "ads://guides/scenarios")
962
+ return {
963
+ contents: [
964
+ {
965
+ uri,
966
+ mimeType: "text/markdown",
967
+ text: readFileSync(new URL("../skills/ads-designer/references/scenarios.md", import.meta.url), "utf8"),
968
+ },
969
+ ],
970
+ };
971
+ if (uri === "ads://guides/layers")
972
+ return {
973
+ contents: [
974
+ {
975
+ uri,
976
+ mimeType: "text/markdown",
977
+ text: readFileSync(new URL("../skills/ads-designer/references/layers.md", import.meta.url), "utf8"),
978
+ },
979
+ ],
980
+ };
981
+ if (uri === "ads://guides/contracts")
982
+ return {
983
+ contents: [
984
+ {
985
+ uri,
986
+ mimeType: "text/markdown",
987
+ text: readFileSync(new URL("../skills/ads-designer/references/contracts.md", import.meta.url), "utf8"),
988
+ },
989
+ ],
990
+ };
991
+ if (uri === "ads://guides/review")
992
+ return {
993
+ contents: [
994
+ {
995
+ uri,
996
+ mimeType: "text/markdown",
997
+ text: readFileSync(new URL("../skills/ads-designer/references/review.md", import.meta.url), "utf8"),
998
+ },
999
+ ],
1000
+ };
1001
+ if (uri === "ads://guides/captures")
1002
+ return {
1003
+ contents: [
1004
+ {
1005
+ uri,
1006
+ mimeType: "text/markdown",
1007
+ text: readFileSync(new URL("../skills/ads-designer/references/captures.md", import.meta.url), "utf8"),
1008
+ },
1009
+ ],
1010
+ };
1011
+ if (skills.files.has(uri))
1012
+ return {
1013
+ contents: [skills.read(uri)],
1014
+ };
347
1015
  let value;
348
1016
  if (uri === `${PROJECT_URI}/status`) value = await status();
349
- else if (uri === BUILD_URI) value = builds();
350
- else if (uri === `${PROJECT_URI}/tokens`) value = tokenWidgetData(inspectTokens(root));
351
- else if (uri === ICONS_URI) value = iconSet(loadConfig(root));
352
- else if (uri === `${PROJECT_URI}/catalog`) value = { items: annotateDrafts(await getCatalog()) };
353
- else if (uri === DRAFTS_URI) value = drafts.list();
354
- else if (uri === `${PROJECT_URI}/scenarios`) value = getRegistry();
1017
+ else if (uri === BUILD_URI) value = await builds();
1018
+ else if (uri === `${PROJECT_URI}/tokens`) value = tokenWidgetData(await tokenInventory());
1019
+ else if (uri === `${PROJECT_URI}/tokens/dtcg` || uri.startsWith(`${PROJECT_URI}/tokens/dtcg?`)) {
1020
+ // One export implementation for the CLI and MCP, over the same revision-aware token inventory.
1021
+ const { theme, brand } = resourceQuery(uri, ["theme", "brand"]);
1022
+ value = await exportTokensDtcg(root, { theme, brand }, await tokenInventory());
1023
+ }
1024
+ else if (uri === ICONS_URI) {
1025
+ const iconOptions = loadConfig(root);
1026
+ // Reuse the revision-aware analysis path used by the Tokens view. A
1027
+ // standalone inspection here repeatedly rediscovers the same ownership.
1028
+ value = await iconSet(iconOptions, iconOptions.config.assets.glyphs ? await tokenInventory() : undefined);
1029
+ }
1030
+ else if (uri === `${PROJECT_URI}/catalog`)
1031
+ value = {
1032
+ items: await annotateDrafts(await getCatalog()),
1033
+ };
1034
+ else if (uri === DRAFTS_URI) value = await drafts.list();
1035
+ else if (uri === `${PROJECT_URI}/scenarios`) value = await getRegistryAsync();
355
1036
  else if (uri === `${PROJECT_URI}/checks`) value = await architecture(signal);
356
- else if (uri === BEHAVIOR_URI || uri.startsWith(`${BEHAVIOR_URI}?`)) value = behaviorPage(options, resourceQuery(uri, ["unit", "api", "query", "section", "cursor", "limit"]));
357
- else if (uri === INVESTIGATIONS_URI || uri.startsWith(`${INVESTIGATIONS_URI}?`)) value = investigationPage(root, resourceQuery(uri, ["unit", "check", "runId", "section", "cursor", "limit", "recordIndex", "offset", "chars"]));
358
- else if (uri === RESULTS_URI || uri.startsWith("ads://results/")) return { contents: [executionResults.readResource(uri)] };
359
- else if (uri === CAPTURES_URI) value = captureIndex();
360
- else if (uri === PREVIEW_MANIFEST_URI && options.config.mcp.previewManifest) {
1037
+ else if (uri === BEHAVIOR_URI || uri.startsWith(`${BEHAVIOR_URI}?`))
1038
+ value = await behaviorInventory(resourceQuery(uri, ["unit", "api", "query", "section", "cursor", "limit"]));
1039
+ else if (uri === INVESTIGATIONS_URI || uri.startsWith(`${INVESTIGATIONS_URI}?`))
1040
+ value = investigationPage(root, resourceQuery(uri, ["unit", "check", "runId", "section", "cursor", "limit", "recordIndex", "offset", "chars"]));
1041
+ else if (uri === RESULTS_URI || uri.startsWith("ads://results/"))
1042
+ return {
1043
+ contents: [executionResults.readResource(uri)],
1044
+ };
1045
+ else if (uri === CAPTURES_URI) value = await captureIndex();
1046
+ else if (uri === PREVIEW_MANIFEST_URI) {
361
1047
  value = readPreviewManifest(previewOptions());
362
1048
  if (!value) throw new Error("Preview resources are not built yet. Invoke ads_show_scenario to start the managed compiler.");
363
- }
364
- else if (uri === LIVE_PREVIEW_MANIFEST_URI && options.config.mcp.previewManifest) {
365
- const report = builds(), live = report.previews.find(entry => entry.live)?.live;
1049
+ } else if (uri === LIVE_PREVIEW_MANIFEST_URI) {
1050
+ const report = await builds(),
1051
+ live = report.previews.find((entry) => entry.live)?.live;
366
1052
  value = readPreviewManifest(livePreviewOptions(previewOptions()));
367
- if (!live || value?.revision !== live.revision || value.session !== report.session) throw new Error("No live feedback for the current source. Use the verified preview after checks pass.");
1053
+ if (!live || value?.revision !== live.revision || value.session !== report.session)
1054
+ throw new Error("No live feedback for the current source. Use the verified preview after checks pass.");
368
1055
  }
369
- if (value !== undefined) return { contents: [{ uri, mimeType: "application/json", text: JSON.stringify(value) }] };
1056
+ if (value !== undefined)
1057
+ return {
1058
+ contents: [
1059
+ {
1060
+ uri,
1061
+ mimeType: "application/json",
1062
+ text: JSON.stringify(value),
1063
+ },
1064
+ ],
1065
+ };
370
1066
  if (uri.startsWith("ads://investigations/") || uri.startsWith("ads://verification-artifacts/")) {
371
- try { return {contents:[readInvestigationResource(root,uri)]}; }
372
- catch(error){throw new ResourceNotFoundError(uri,error.message);}
1067
+ try {
1068
+ return {
1069
+ contents: [readInvestigationResource(root, uri)],
1070
+ };
1071
+ } catch (error) {
1072
+ throw new ResourceNotFoundError(uri, error.message);
1073
+ }
373
1074
  }
374
1075
  if (uri.startsWith("ads://captures/")) {
375
- try { const inventory = captureInventory(); return { contents: [captures.store.readResource(uri, inventory.scenarios, inventory.revision, { allowUnknownTargets: !!inventory.diagnostics.length })] }; }
376
- catch (error) { if (error.code === "ADS_CAPTURE_NOT_FOUND") throw new ResourceNotFoundError(uri, error.message); throw error; }
1076
+ try {
1077
+ const inventory = await captureInventory();
1078
+ return {
1079
+ contents: [
1080
+ captures.store.readResource(uri, inventory.scenarios, inventory.revision, {
1081
+ allowUnknownTargets: !!inventory.diagnostics.length,
1082
+ }),
1083
+ ],
1084
+ };
1085
+ } catch (error) {
1086
+ if (error.code === "ADS_CAPTURE_NOT_FOUND") throw new ResourceNotFoundError(uri, error.message);
1087
+ throw error;
1088
+ }
377
1089
  }
378
- if (uri === TOKENS_APP_URI) return { contents: [{ uri, mimeType: APP_MIME, text: tokensApp(tokenWidgetData(inspectTokens(root))), _meta: appMetadata({ nested: true }) }] };
379
- if (uri === SCENARIO_APP_URI) return { contents: [{ uri, mimeType: APP_MIME, text: scenarioApp(), _meta: appMetadata({ nested: true }) }] };
380
- if (uri === PREVIEW_APP_URI && options.config.mcp.previewManifest) return { contents: [{ uri, mimeType: APP_MIME, text: previewApp(), _meta: appMetadata() }] };
381
- if (uri.startsWith("ads://assets/") && options.config.mcp.previewManifest) {
382
- try { return { contents: [readPreviewAsset(previewOptions(), uri)] }; }
383
- catch (error) {
1090
+ if (uri === PREVIEW_APP_URI)
1091
+ return {
1092
+ contents: [
1093
+ {
1094
+ uri,
1095
+ mimeType: APP_MIME,
1096
+ text: previewApp(),
1097
+ _meta: appMetadata(),
1098
+ },
1099
+ ],
1100
+ };
1101
+ if (uri.startsWith("ads://assets/")) {
1102
+ try {
1103
+ return {
1104
+ contents: [readPreviewAsset(previewOptions(), uri)],
1105
+ };
1106
+ } catch (error) {
384
1107
  if (error.code !== "ADS_PREVIEW_NOT_FOUND") throw error;
385
- try { return { contents: [readPreviewAsset(livePreviewOptions(previewOptions()), uri)] }; }
386
- catch (error) { if (error.code === "ADS_PREVIEW_NOT_FOUND") throw new ResourceNotFoundError(uri, error.message); throw error; }
1108
+ try {
1109
+ return {
1110
+ contents: [readPreviewAsset(livePreviewOptions(previewOptions()), uri)],
1111
+ };
1112
+ } catch (error) {
1113
+ if (error.code === "ADS_PREVIEW_NOT_FOUND") throw new ResourceNotFoundError(uri, error.message);
1114
+ throw error;
1115
+ }
387
1116
  }
388
1117
  }
389
- const app = allApps().find((entry) => appUri(entry.id) === uri);
1118
+ await getRegistryAsync();
1119
+ const app = (await scenarioApps()).find((entry) => appUri(entry.id) === uri);
390
1120
  if (app) {
391
- if (scenarioApps().some(entry => entry.id === app.id) && getRegistry().diagnostics.length) throw new Error("Scenario registry has errors. Read ads://project/scenarios before opening a preview.");
392
- const build = await previewBuild(app, signal);
393
- const graph = options.config.mcp.previewManifest && scenarioApps().some(entry => entry.id === app.id);
394
- return { contents: [{ uri, mimeType: APP_MIME, text: graph ? previewApp({ id: app.id }) : projectApp(options, app, build), _meta: appMetadata() }] };
1121
+ if ((await getRegistry()).diagnostics.length) throw new Error("Scenario registry has errors. Read ads://project/scenarios before opening a preview.");
1122
+ await previewBuild(app, signal);
1123
+ return {
1124
+ contents: [
1125
+ {
1126
+ uri,
1127
+ mimeType: APP_MIME,
1128
+ text: previewApp({
1129
+ id: app.id,
1130
+ }),
1131
+ _meta: appMetadata(),
1132
+ },
1133
+ ],
1134
+ };
395
1135
  }
396
1136
  const document = getDocuments().find((entry) => entry.uri === uri);
397
- if (document) return { contents: [{ uri, mimeType: document.mimeType, text: readProjectDocument(document) }] };
1137
+ if (document)
1138
+ return {
1139
+ contents: [
1140
+ {
1141
+ uri,
1142
+ mimeType: document.mimeType,
1143
+ text: readProjectDocument(document),
1144
+ },
1145
+ ],
1146
+ };
398
1147
  throw new ResourceNotFoundError(uri, `Unknown ADS resource: ${uri}`);
399
1148
  }
400
1149
  async function previewBuild(app, signal, waitFor = "verified") {
401
- previewWatch?.setApps(allApps(waitFor === "compiled"));
402
- if (previewWatch) return previewWatch.ensure(path.resolve(root, app.file), signal, { waitFor });
403
- const build = builds().previews.find((entry) => entry.id === app.id);
404
- if (waitFor === "compiled" && options.config.mcp.previewManifest) {
405
- try { graphSelection(app.id, build); return build; }
406
- catch { /* No usable graph yet: keep the normal diagnostics/wait path. */ }
1150
+ if (waitFor !== "compiled") await getRegistryAsync();
1151
+ previewWatch?.setApps(await scenarioApps(waitFor === "compiled"));
1152
+ if (previewWatch)
1153
+ return previewWatch.ensure(path.resolve(root, app.file), signal, {
1154
+ waitFor,
1155
+ });
1156
+ const build = (await builds()).previews.find((entry) => entry.id === app.id);
1157
+ if (waitFor === "compiled") {
1158
+ try {
1159
+ graphSelection(app.id, build);
1160
+ return build;
1161
+ } catch {
1162
+ /* No usable graph yet: keep the normal diagnostics/wait path. */
1163
+ }
407
1164
  }
408
1165
  if (build?.state === "error") throw buildFailure(build);
409
- if (["building", "idle"].includes(build?.state)) throw Object.assign(new Error("Preview build is still pending. Invoke the preview again after rebuilding."), { build: { ...build, resourceUri: BUILD_URI } });
1166
+ if (["building", "idle"].includes(build?.state))
1167
+ throw Object.assign(new Error("Preview build is still pending. Invoke the preview again after rebuilding."), {
1168
+ build: {
1169
+ ...build,
1170
+ resourceUri: BUILD_URI,
1171
+ },
1172
+ });
410
1173
  return build;
411
1174
  }
412
-
413
1175
  async function finishExecution(kind, result) {
414
- if(executionContext.getStore()?.record.instanceId===coordinator.status().instanceId)return result;
1176
+ if (executionContext.getStore()?.record.instanceId === coordinator.status().instanceId) return result;
415
1177
  const summary = executionResults.save(kind, result);
416
- try { await refresh(); } catch (error) { process.stderr.write(`ads mcp: result saved; notification failed: ${error.message}\n`); }
417
- return { ...json(summary), ...(!result.ok ? { isError: true } : {}) };
1178
+ try {
1179
+ await refresh();
1180
+ } catch (error) {
1181
+ process.stderr.write(`ads mcp: result saved; notification failed: ${error.message}\n`);
1182
+ }
1183
+ return {
1184
+ ...json(summary),
1185
+ ...(!result.ok
1186
+ ? {
1187
+ isError: true,
1188
+ }
1189
+ : {}),
1190
+ };
418
1191
  }
419
- async function applyEdits(args,signal,progress) {
420
- const result = await edits.apply(args,signal,progress);
421
- if (result.screenshots) await refresh();
1192
+ /** After accepted source changes: reconfigure, rebuild and re-warm previews. */
1193
+ async function afterApply(result) {
422
1194
  if (result.applied) {
423
1195
  try {
424
- if (result.changes.some(change => change.path === "ds.config.json") || result.unit === "configuration" || result.units?.includes("configuration")) await previewWatch?.reconfigure?.(loadConfig(root).config.mcp,true);
1196
+ if (result.changes.some((change) => change.path === "ds.config.json") || result.unit === "configuration" || result.units?.includes("configuration"))
1197
+ await previewWatch?.reconfigure?.(loadConfig(root).config.mcp, true);
425
1198
  await previewWatch?.invalidate?.();
426
1199
  await refresh(true);
427
- previewWatch?.setApps(allApps());
428
- if ((result.units??[result.unit]).some(unit=>unit!=="documentation")) await previewWatch?.warm?.((options.config.mcp.previewManifest?scenarioApps():allApps()).map(app=>path.resolve(root,app.file)));
429
- } catch (error) {result.warnings=[...(result.warnings ?? []),{rule:"mutation-notification",message:`Changes were applied, but preview refresh failed: ${error.message.slice(0,2000)}. Recheck ads_status and reopen the scenario.`}];}
430
- }
431
- return finishExecution("mutation", { ...(args.patches ? {units:args.patches.map(item=>item.unit),transaction:true} : {unit:args.unit}), ...result });
1200
+ await getRegistryAsync();
1201
+ previewWatch?.setApps(await scenarioApps());
1202
+ if ((result.units ?? [result.unit]).some((unit) => unit !== "documentation"))
1203
+ await previewWatch?.warm?.((await scenarioApps()).map((app) => path.resolve(root, app.file)));
1204
+ } catch (error) {
1205
+ result.warnings = [
1206
+ ...(result.warnings ?? []),
1207
+ {
1208
+ rule: "mutation-notification",
1209
+ message: `Changes were applied, but preview refresh failed: ${error.message.slice(0, 2000)}. Recheck ads_status and reopen the scenario.`,
1210
+ },
1211
+ ];
1212
+ }
1213
+ } else await refresh();
1214
+ return result;
432
1215
  }
433
1216
  function tools() {
434
1217
  return [
435
- { name:"ads_drafts", description:"List only tracked ADS drafts, including owner units, exact revisions, conflicts, dependencies and recent acceptance/drop events. Use id for paged file mappings. Drafts survive restart/Git clone; generated previews and execution evidence do not. Read ads://guides/drafts. Finish a coherent design change by accepting its drafts after rendered review; never report a draft-only preview as completed work.", schema:query.extend({id:draftIdSchema.optional(),unit:z.string().max(256).optional(),offset:z.number().int().min(0).default(0)}), call:args=>json(drafts.list(args)) },
436
- { name:"ads_show_draft", title:"Draft preview", description:"Prepare/reuse an isolated compiler workspace for a tracked draft and its dependency drafts. Returns a browser showcase URL and available scenarios without running acceptance checks. Registry failures return the draft-private diagnostics and diagnosticsUri, never the accepted registry. Existing @ds imports resolve the proposed overlay only here. Inspect the actual rendered result; then accept the exact returned revision. For comparison, open comparisonUrl in DS Explorer and use Split view. New owners have no accepted comparison.", schema:z.object({id:draftIdSchema,scenario:z.string().max(256).optional()}).strict(), _meta:{ui:{resourceUri:scenarioWidget()}}, annotations:{...annotations,readOnlyHint:false,idempotentHint:false}, call:async (args,signal)=>{
437
- const value=await drafts.show(args,signal),base=getShowcaseUrl();
438
- let comparisonUrl=null;
439
- if(base){const url=new URL(base);url.searchParams.set("draft",args.id);if(value.scenario)url.searchParams.set("scenario",value.scenario);if(value.acceptedExists)url.searchParams.set("split","1");comparisonUrl=url.href;}
440
- const response=json({...value,isolatedShowcaseUrl:value.showcaseUrl,showcaseUrl:comparisonUrl??value.showcaseUrl,comparisonUrl});
441
- return value.ok===false?{...response,isError:true}:response;
442
- } },
443
- ...(mutations ? [
444
- { name:"ads_create_draft", description:"Create a Git-committable proposal under ads-drafts/ for 1–64 coupled ADS owners, copying only their source/companions into non-importable .ads files. New owners are allowed. Optional dependencies name separate unaccepted drafts used by pattern/composition previews. Creation does not change accepted source. Edit the returned files normally; use ads_update_draft to register additions/deletions.", schema:z.object({units:z.array(z.string().min(1).max(256)).min(1).max(mutationLimits.units),title:z.string().min(1).max(160).optional(),id:draftIdSchema.optional(),dependencies:z.array(draftIdSchema).max(8).default([]),tokenGroups:z.array(z.string().min(1).max(160)).max(32).default([])}).strict(),_meta:{ui:{visibility:["model"]}},annotations:{...annotations,readOnlyHint:false,idempotentHint:false},call:async args=>{const result=drafts.create(args);if(observeChanges)await refresh();return json(result);} },
445
- { name:"ads_update_draft", description:"Update marked draft source or register new/deleted canonical target paths. Pass the current revision from ads_drafts. Source is UTF-8 unless encoding:base64; content:null proposes deletion. refresh:true rebases onto current accepted source using stored baselines; non-overlapping edits merge and overlapping edits leave the draft unchanged with diagnostics. Use changes with refresh only for explicit resolved contents of existing draft files; refresh separately from dependency changes. Optional dependencies replaces the draft dependency list. Normal local file edits need no iteration tool. Accepted source remains unchanged; ownership and all required checks run at acceptance.",schema:z.object({id:draftIdSchema,revision:draftRevisionSchema,refresh:z.boolean().default(false),dependencies:z.array(draftIdSchema).max(8).optional(),changes:z.array(z.object({unit:z.string().max(256),path:z.string().min(1).max(500),content:z.string().max(256*1024).nullable(),encoding:z.enum(["utf8","base64"]).optional()}).strict()).max(32).default([])}).strict(),_meta:{ui:{visibility:["model"]}},annotations:{...annotations,readOnlyHint:false,idempotentHint:false},call:async args=>{const result=drafts.update(args);if(observeChanges)await refresh();return json(result);} },
446
- { name:"ads_drop_draft",description:"Delete an exact tracked draft and its generated preview. This is Drop, not a separate refusal workflow. Accepted source is unchanged. Dependents report a missing dependency until corrected.",schema:z.object({id:draftIdSchema,revision:draftRevisionSchema}).strict(),_meta:{ui:{visibility:["model"]}},annotations:{...annotations,readOnlyHint:false,destructiveHint:true,idempotentHint:false},call:async args=>{const result=await drafts.drop(args);if(observeChanges)await refresh();return json(result);} },
447
- { name:"ads_accept",title:"Accept a reviewed draft",description:"Auto-mode acceptance: validate and apply the exact rendered/reviewed draft revision in one operation. Accept dependency drafts first; dependent drafts automatically switch to their final @ds implementations. Mandatory ADS guards and acceptance.checks run once on the candidate; affected registered tests gate acceptance when acceptance.behaviorChecks is true. Unless acceptance.browserAudit is false, axe-core audits the candidate's affected UI scenarios in every declared brand and theme; any a11y-axe error (or an audit that cannot run) rejects acceptance. Draft/source changes invalidate acceptance. On failure retain the draft and inspect ads_results; on success apply normal source, remove the draft and publish an event. No additional human approval or manual Apply step.",schema:z.object({fresh:z.boolean().default(false),id:draftIdSchema,revision:draftRevisionSchema}).strict(),_meta:{ui:{visibility:["model"]}},annotations:{...annotations,readOnlyHint:false,destructiveHint:true,idempotentHint:false},call:async(args,signal,progress)=>{
448
- const result=await drafts.accept(args,signal,progress);
449
- if(result.applied){await previewWatch?.invalidate?.();await refresh(true);}else await refresh();
450
- return finishExecution("mutation",result);
451
- } },
452
- ] : []),
453
- { name: "ads_status", description: "Start here for UI/ADS work: components, patterns, tokens/themes/branding, layout, behavior, motion and showcase review. Returns the exact project root/public API, workflow, project commands, editing mode and build diagnostics. Choose direct editing or MCP-only editing through ads://guides/workflows. Ordinary direct edits use MCP for previews/checks without draft acceptance; MCP-only edits require enabled mutation tools.", schema: empty, call: async () => json(await status()) },
454
- { name: "ads_capture", title: "Capture a design-system scenario", description: "Capture a real scenario/target inside the MCP App iframe. Optional draft + revision captures Accepted/current and that exact unaccepted Draft/candidate without acceptance checks; new scenarios have no baseline. Uses project-local Playwright/browser; installs nothing. Returns PNG resource URIs, never image bytes in text. Ordinary capture replaces current/clears candidate. Inspect ads://project/captures and read the image resources for visual review. Appearance is not behavior or acceptance verification.", schema: captureSpec.safeExtend({draft:draftIdSchema.optional(),revision:draftRevisionSchema.optional()}).refine(args=>(args.draft===undefined)===(args.revision===undefined),"Provide draft and revision together."), annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: false, openWorldHint: false }, call: async ({draft,revision,...selection}, signal, progress) => {
455
- let result;
456
- if(draft){
457
- const proposal=drafts.prepare(draft);
458
- if(proposal.revision!==revision)throw new Error("Draft revision changed. Reopen its preview before capturing.");
459
- const acceptedHost=getShowcaseUrl()?{url:getShowcaseUrl(),previewRevision:()=>readPreviewManifest(previewOptions())?.revision??null}:null;
460
- const captured=await captures.run({captures:[selection],candidateRoot:proposal.session.workspace,proposal:revision,publish:false,previewHosts:[acceptedHost,proposal.session.runtime]},signal,progress);
461
- if(drafts.inspect(draft).revision!==revision)throw new Error("Draft changed during capture; no image slots were replaced.");
462
- captures.store.commit(captured.records);
463
- const inventory=captureInventory(),keys=new Set(captured.records.map(record=>record.key));
464
- result={ok:true,draft,draftRevision:revision,previewOnly:true,captures:captures.store.list(inventory.scenarios,inventory.revision).captures.filter(record=>keys.has(record.key))};
465
- }else result=await captures.run({captures:[selection]},signal,progress);
466
- await refresh(); return captureResponse(result, era === "modern");
467
- } },
468
- { name: "ads_capture_clear", description: "Delete generated screenshot slots for one scenario/target. candidateOnly discards a proposal while retaining current. Source is unchanged. No TTL/history is kept; each target has at most current and candidate.", schema: z.object({ scenario: z.string().min(1).max(256), target: z.string().regex(/^[a-zA-Z0-9][\w.-]{0,79}$/).optional(), candidateOnly: z.boolean().default(false) }).strict(), annotations: { readOnlyHint: false, destructiveHint: true, idempotentHint: true, openWorldHint: false }, call: async args => { const result = captures.store.clear(args); await refresh(); return json(result); } },
469
- { name: "ads_catalog", description: "Before creating/changing UI or behavior, find existing public components/patterns/controllers and hooks with a small query/limit. Returns import alias and exact source/guide URIs so you can reuse or edit the owner. Read ads_status first for workspace/workflow. Metadata only; does not render UI.", schema: query.extend({ kind: z.enum(["components", "patterns", "controllers"]).optional() }), call: async ({ query: search = "", limit, kind }) => {
470
- const matches = (await getCatalog()).filter((item) => (!kind || item.kind === kind) && item.name.toLowerCase().includes(search.toLowerCase()));
471
- return json({ total: matches.length, items: annotateDrafts(matches.slice(0, limit)), resourceUri: `${PROJECT_URI}/catalog` });
472
- } },
473
- { name: "ads_scenarios", description: "Find an independently mountable brand, token, component, pattern or composition preview. IDs derive from source filenames. Optional group labels are derived from folder names and searchable; group is discovery output, never scenario metadata. covers lists rendered public UI, exercises lists behavioral APIs and tokens lists the real token inputs. Use ads_show_scenario with an exact returned id. Showcase and MCP use this same registry.", schema: query.extend({ kind: z.enum(["brand", "tokens", "components", "patterns", "composition"]).optional(), offset: z.number().int().min(0).default(0) }), call: ({ query: search = "", limit, kind, offset }) => {
474
- const registry = getRegistry();
475
- const matches = registry.scenarios.filter(item => (!kind || item.kind === kind) && `${item.id} ${item.title} ${item.group ?? ""} ${item.covers.join(" ")} ${(item.exercises ?? []).join(" ")} ${item.tokens.join(" ")}`.toLowerCase().includes(search.toLowerCase()));
476
- const report = builds(), states = new Map(report.previews.map(item => [item.id, item]));
477
- return json({ total: matches.length, scenarios: annotateDrafts(matches.slice(offset, offset + limit)).map(item => ({ ...item, build: summarizeBuild(states.get(item.id)) })), ...(offset + limit < matches.length ? { nextOffset: offset + limit } : {}), diagnostics: registry.diagnostics, resourceUri: `${PROJECT_URI}/scenarios` });
478
- } },
479
- { name: "ads_show_scenario", title: "Scenario preview", description: "Render one real scenario with its fixtures. Discover its exact id first. Default waitFor: verified waits for successful current checks. Interactive browsers may request waitFor: compiled for unverified live feedback or a retained earlier view; inspect build.current and never use pending output as verification evidence. Requires MCP Apps and resource forwarding; fallback links to the same showcase scenario.", schema: z.object({ id: z.string().min(1).max(256), waitFor: z.enum(["verified", "compiled"]).default("verified") }).strict(), _meta: { ui: { resourceUri: scenarioWidget() } }, call: async ({ id, waitFor }, signal) => {
480
- const registry = await previewRegistry(waitFor);
481
- const entry = registry.scenarios.find(item => item.id === id);
482
- if (!entry) throw new Error("Unknown scenario id. Read ads_scenarios; IDs must match discovered source entries.");
483
- if (registry.diagnostics.length) throw new Error("Scenario registry has errors. Read ads://project/scenarios and fix its diagnostics.");
484
- const app = scenarioApps(waitFor === "compiled").find(item => item.id === id);
485
- const build = await previewBuild(app, signal, waitFor);
486
- const graph = graphSelection(id, build);
487
- if (!options.config.mcp.previewManifest) projectApp(options, app, build);
488
- return json({ widget: { resourceUri: scenarioWidget() }, scenario: { ...entry, resourceUri: appUri(id) }, ...graph, build, showcaseUrl: scenarioUrl(id) });
489
- } },
490
- { name: "ads_tokens", description: "Use before styling, theme, brand or motion-token changes to inspect existing semantic definitions/values. Query specific token names with a small limit. ads_show_tokens renders project token scenarios; definition inspection does not validate component layout.", schema: query, call: ({ query: search = "", limit }) => {
491
- const inventory = inspectTokens(root);
492
- const matches = inventory.tokens.filter((token) => token.name.toLowerCase().includes(search.toLowerCase()));
493
- return json({ total: matches.length, tokens: matches.slice(0, limit), categories: tokenScenarios(), tokenGroups:drafts.tokenGroups(), diagnosticCount: inventory.diagnostics.length, resourceUri: `${PROJECT_URI}/tokens` });
494
- } },
495
- { name: "ads_check", description: "Run read-only core ADS architecture checks; returns blocking errors (diagnostics) separately from nonblocking review items (the advisories section, severity review), with review items before informational limits; summary counts both. Atomic review items include helper/forwarded-class paths and ads://guides/atomic-styles guidance; unresolved paths do not establish safe composition. Project Oxlint, typecheck, build and browser tests remain separate.", schema: z.object({ limit: z.number().int().min(1).max(50).default(20), fresh:z.boolean().default(false) }).strict(), call: async ({ limit, fresh }, signal) => {
496
- const result = await architecture(signal,fresh);
497
- return json({ ok: result.ok, acceptance:result.acceptance, cache:result.cache, summary: findingCounts(result.diagnostics.length, (result.advisories ?? []).filter(item => item.severity === "review").length), total: result.diagnostics.length, diagnostics: result.diagnostics.slice(0, limit), advisoryCount: result.advisories?.length ?? 0, advisories: (result.advisories ?? []).slice(0, limit), resourceUri: `${PROJECT_URI}/checks` });
498
- } },
499
- { name: "ads_skills", description: "Select one ADS workflow after ads_status: ads-designer for building/refining/debugging UI; ads-port for a library reference; ads-import for another project's ADS; ads-motion for animation; ads-break-ui for stress testing. Then read that workflow with ads_read_skill. Listing does not activate a native skill.", schema: empty, call: () => json({ skills: skills.skills.map(({ uri, frontmatter }) => ({ uri, ...frontmatter })) }) },
500
- { name: "ads_read_skill", description: "Read a selected skill or relative supporting text file in bounded chunks. This is explicit instruction access, not automatic native skill activation/install.", schema: z.object({ name: z.string().max(64), file: z.string().max(300).default("SKILL.md"), offset: z.number().int().min(0).default(0), limit: z.number().int().min(1).max(8000).default(6000) }).strict(), call: ({ name, file, offset, limit }) => {
501
- const skill = skills.skills.find((entry) => entry.frontmatter.name === name);
502
- if (!skill) throw new Error("Unknown ADS skill name.");
503
- const uri = `${skill.uri.slice(0, -"SKILL.md".length)}${file.split("/").map(encodeURIComponent).join("/")}`;
504
- const manifest = skill.resources.find((resource) => resource.uri === uri);
505
- if (!manifest) throw new Error("Unknown relative skill file. Consult its manifest with native skills/get or the resources catalog.");
506
- const content = skills.read(uri);
507
- if (!("text" in content)) return json({ ...manifest, mimeType: content.mimeType, binary: true, note: "Read binary bytes via resources/read; this tool does not embed them." });
508
- return json({ ...manifest, text: content.text.slice(offset, offset + limit), offset, ...(offset + limit < content.text.length ? { nextOffset: offset + limit } : {}) });
509
- } },
510
- { name: "ads_show_tokens", title: "Token previews", description: "Render a discovered token scenario with project-owned templates and fixtures. Pass its id as category, or omit for the first token scenario. Default waitFor: verified requires current checks. Interactive browsers may use waitFor: compiled for explicitly unverified feedback or a retained view. Older compilers provide a generic definition inspector.", schema: z.object({ category: z.string().max(256).optional(), waitFor: z.enum(["verified", "compiled"]).default("verified") }).strict(), _meta: { ui: { resourceUri: options.config.mcp.previewManifest ? PREVIEW_APP_URI : TOKENS_APP_URI } }, call: async ({ category, waitFor }, signal) => {
511
- const registry = await previewRegistry(waitFor);
512
- if (!category && options.config.mcp.previewManifest) category = registry.scenarios.find(item => item.kind === "tokens")?.id;
513
- if (!category && options.config.mcp.previewManifest) throw new Error("No token scenario is registered. Colocate a token scenario and fixture before opening the preview; ads_tokens still inspects definitions.");
514
- if (category) {
515
- const entry = registry.scenarios.find(item => item.kind === "tokens" && item.id === category);
516
- if (!entry) throw new Error("Unknown token scenario. Discover categories with ads_tokens or ads_scenarios(kind: tokens) first.");
517
- if (registry.diagnostics.length) throw new Error("Scenario registry has errors. Fix its diagnostics before reviewing.");
518
- const app = scenarioApps(waitFor === "compiled").find(item => item.id === category);
1218
+ {
1219
+ name: "ads_drafts",
1220
+ description:
1221
+ "List only tracked ADS drafts, including owner units, exact revisions, conflicts, dependencies and recent acceptance/drop events. Use id for paged file mappings. Drafts survive restart/Git clone; generated previews and execution evidence do not. Read ads://guides/drafts. Finish a coherent design change by accepting its drafts after rendered review; never report a draft-only preview as completed work.",
1222
+ schema: query.extend({
1223
+ id: draftIdSchema.optional(),
1224
+ unit: z.string().max(256).optional(),
1225
+ offset: z.number().int().min(0).default(0),
1226
+ }),
1227
+ call: async (args) => json(await drafts.list(args)),
1228
+ },
1229
+ {
1230
+ name: "ads_show_draft",
1231
+ title: "Draft preview",
1232
+ description:
1233
+ "Prepare/reuse an isolated compiler workspace for a tracked draft and its dependency drafts. Returns a browser showcase URL and available scenarios without running acceptance checks. Registry failures return the draft-private diagnostics and diagnosticsUri, never the accepted registry. Existing @ds imports resolve the proposed overlay only here. Inspect the actual rendered result; then accept the exact returned revision. For comparison, open comparisonUrl in DS Explorer and use Split view. New owners have no accepted comparison.",
1234
+ schema: z
1235
+ .object({
1236
+ id: draftIdSchema,
1237
+ scenario: z.string().max(256).optional(),
1238
+ })
1239
+ .strict(),
1240
+ _meta: {
1241
+ ui: {
1242
+ resourceUri: PREVIEW_APP_URI,
1243
+ },
1244
+ },
1245
+ annotations: {
1246
+ ...annotations,
1247
+ readOnlyHint: false,
1248
+ idempotentHint: false,
1249
+ },
1250
+ call: async (args, signal) => {
1251
+ const value = await drafts.show(args, signal),
1252
+ base = getShowcaseUrl();
1253
+ let comparisonUrl = null;
1254
+ if (base) {
1255
+ const url = new URL(base);
1256
+ url.searchParams.set("draft", args.id);
1257
+ if (value.scenario) url.searchParams.set("scenario", value.scenario);
1258
+ if (value.acceptedExists) url.searchParams.set("split", "1");
1259
+ comparisonUrl = url.href;
1260
+ }
1261
+ const response = json({
1262
+ ...value,
1263
+ isolatedShowcaseUrl: value.showcaseUrl,
1264
+ showcaseUrl: comparisonUrl ?? value.showcaseUrl,
1265
+ comparisonUrl,
1266
+ });
1267
+ return value.ok === false
1268
+ ? {
1269
+ ...response,
1270
+ isError: true,
1271
+ }
1272
+ : response;
1273
+ },
1274
+ },
1275
+ ...(mutations
1276
+ ? [
1277
+ {
1278
+ name: "ads_create_draft",
1279
+ description:
1280
+ "Create a Git-committable proposal under ads-drafts/ for 1–64 coupled ADS owners, copying only their own files into non-importable .ads files. An owner can be in only one open draft at a time: another client's open draft holds its owners until it is accepted or dropped, so concurrent clients edit different owners; depend on an open draft instead of including its owners. New owners are allowed. Optional dependencies name separate unaccepted drafts used by pattern/composition previews. Creation does not change accepted source. Every ADS source change starts here: only a draft can be accepted. Edit the returned files normally, or patch them with ads_update_draft.",
1281
+ schema: z
1282
+ .object({
1283
+ units: z.array(z.string().min(1).max(256)).min(1).max(mutationLimits.units),
1284
+ title: z.string().min(1).max(160).optional(),
1285
+ id: draftIdSchema.optional(),
1286
+ dependencies: z.array(draftIdSchema).max(8).default([]),
1287
+ tokenGroups: z.array(z.string().min(1).max(160)).max(32).default([]),
1288
+ })
1289
+ .strict(),
1290
+ _meta: {
1291
+ ui: {
1292
+ visibility: ["model"],
1293
+ },
1294
+ },
1295
+ annotations: {
1296
+ ...annotations,
1297
+ readOnlyHint: false,
1298
+ idempotentHint: false,
1299
+ },
1300
+ call: async (args) => {
1301
+ const result = await drafts.create(args);
1302
+ if (observeChanges) await refresh().catch(error => process.stderr.write(`ads mcp: draft saved; notification failed: ${error.message}\n`));
1303
+ return json(result);
1304
+ },
1305
+ },
1306
+ {
1307
+ name: "ads_update_draft",
1308
+ description:
1309
+ "Update marked draft source or register new/deleted canonical target paths. Pass the current revision from ads_drafts. Source is UTF-8 unless encoding:base64; content:null proposes deletion. Optional dependencies replaces the draft dependency list. patch (inline) or patchFile (.ds/patches/*.patch) applies one Git unified diff to the draft instead: headers name canonical paths (--- a/path, +++ b/path, /dev/null creates/deletes), hunks must match the draft's current proposal exactly, and new paths join their declared owner; send binary files through changes with encoding:base64. Normal local file edits need no iteration tool. Accepted source remains unchanged; ownership and all required checks run at acceptance.",
1310
+ schema: z
1311
+ .object({
1312
+ id: draftIdSchema,
1313
+ revision: draftRevisionSchema,
1314
+ dependencies: z.array(draftIdSchema).max(8).optional(),
1315
+ changes: z
1316
+ .array(
1317
+ z
1318
+ .object({
1319
+ unit: z.string().max(256),
1320
+ path: z.string().min(1).max(500),
1321
+ content: z
1322
+ .string()
1323
+ .max(256 * 1024)
1324
+ .nullable(),
1325
+ encoding: z.enum(["utf8", "base64"]).optional(),
1326
+ })
1327
+ .strict(),
1328
+ )
1329
+ .max(32)
1330
+ .default([]),
1331
+ patch: z.string().min(1).max(mutationLimits.patchBytes).optional(),
1332
+ patchFile: z.string().min(1).max(500).optional(),
1333
+ })
1334
+ .strict()
1335
+ .refine((args) => args.patch === undefined || args.patchFile === undefined, "Provide at most one of patch or patchFile."),
1336
+ _meta: {
1337
+ ui: {
1338
+ visibility: ["model"],
1339
+ },
1340
+ },
1341
+ annotations: {
1342
+ ...annotations,
1343
+ readOnlyHint: false,
1344
+ idempotentHint: false,
1345
+ },
1346
+ call: async (args) => {
1347
+ const result = await drafts.update(args);
1348
+ if (observeChanges) await refresh().catch(error => process.stderr.write(`ads mcp: draft saved; notification failed: ${error.message}\n`));
1349
+ return json(result);
1350
+ },
1351
+ },
1352
+ {
1353
+ name: "ads_drop_draft",
1354
+ description:
1355
+ "Delete an exact tracked draft and its generated preview. This is Drop, not a separate refusal workflow. Accepted source is unchanged. Dependents report a missing dependency until corrected.",
1356
+ schema: z
1357
+ .object({
1358
+ id: draftIdSchema,
1359
+ revision: draftRevisionSchema,
1360
+ })
1361
+ .strict(),
1362
+ _meta: {
1363
+ ui: {
1364
+ visibility: ["model"],
1365
+ },
1366
+ },
1367
+ annotations: {
1368
+ ...annotations,
1369
+ readOnlyHint: false,
1370
+ destructiveHint: true,
1371
+ idempotentHint: false,
1372
+ },
1373
+ call: async (args) => {
1374
+ const result = await drafts.drop(args);
1375
+ if (observeChanges) await refresh().catch(error => process.stderr.write(`ads mcp: draft saved; notification failed: ${error.message}\n`));
1376
+ return json(result);
1377
+ },
1378
+ },
1379
+ {
1380
+ name: "ads_accept",
1381
+ title: "Accept a reviewed draft",
1382
+ description:
1383
+ "Auto-mode acceptance: validate and apply the exact rendered/reviewed draft revision in one operation. Accept dependency drafts first; dependent drafts automatically switch to their final @ds implementations. The gate runs once on the candidate: ads check, then acceptance.scripts, then the draft owners' own registered behavior tests (unless acceptance.behavior is false) and the render audit of the draft owners' own scenarios in every declared brand and theme (unless acceptance.audit is false). Any failure, render-audit error or audit that cannot run rejects acceptance. What the draft reaches beyond its owners is ads_validate's to check after a series of accepted drafts. Draft/source changes invalidate acceptance. This is the only way ADS writes accepted source. dryRun:true runs every acceptance check on the candidate and writes nothing; the draft stays. On failure retain the draft and inspect ads_results; on success apply normal source, remove the draft and publish an event. No additional human approval or manual Apply step.",
1384
+ schema: z
1385
+ .object({
1386
+ fresh: z.boolean().default(false),
1387
+ id: draftIdSchema,
1388
+ revision: draftRevisionSchema,
1389
+ dryRun: z.boolean().default(false),
1390
+ })
1391
+ .strict(),
1392
+ _meta: {
1393
+ ui: {
1394
+ visibility: ["model"],
1395
+ },
1396
+ },
1397
+ annotations: {
1398
+ ...annotations,
1399
+ readOnlyHint: false,
1400
+ destructiveHint: true,
1401
+ idempotentHint: false,
1402
+ },
1403
+ call: async (args, signal, progress) => {
1404
+ const result = await afterApply(await drafts.accept(args, signal, progress));
1405
+ return finishExecution("mutation", result);
1406
+ },
1407
+ },
1408
+ ]
1409
+ : []),
1410
+ {
1411
+ name: "ads_status",
1412
+ description:
1413
+ "Start here for UI/ADS work: components, patterns, tokens/themes/branding, layout, behavior, motion and showcase review. Returns the exact project root/public API, workflow, project commands, editing mode and build diagnostics. Choose direct editing or MCP-only editing through ads://guides/workflows. Ordinary direct edits use MCP for previews/checks without draft acceptance; MCP-only edits require enabled mutation tools.",
1414
+ schema: empty,
1415
+ call: async () => json(await status()),
1416
+ },
1417
+ {
1418
+ name: "ads_capture",
1419
+ title: "Capture a design-system scenario",
1420
+ description:
1421
+ "Capture a real scenario/target inside the MCP App iframe. Optional guides selects layout overlay layers: bounds, tracks, gaps, padding, margins, mini; omitted means no guides. Available for components, patterns, compositions and tokens/Layout. Optional draft + revision captures Accepted/current and that exact unaccepted Draft/candidate without acceptance checks; new scenarios have no baseline. Uses project-local Playwright/browser; installs nothing. Returns PNG resource URIs, never image bytes in text. Ordinary capture replaces current/clears candidate. Inspect ads://project/captures and read the image resources for visual review. Appearance is not behavior or acceptance verification.",
1422
+ schema: captureSpec
1423
+ .safeExtend({
1424
+ draft: draftIdSchema.optional(),
1425
+ revision: draftRevisionSchema.optional(),
1426
+ })
1427
+ .refine((args) => (args.draft === undefined) === (args.revision === undefined), "Provide draft and revision together."),
1428
+ annotations: {
1429
+ readOnlyHint: false,
1430
+ destructiveHint: false,
1431
+ idempotentHint: false,
1432
+ openWorldHint: false,
1433
+ },
1434
+ call: async ({ draft, revision, ...selection }, signal, progress) => {
1435
+ let result;
1436
+ // Captures of accepted source use the showcase this server runs; without one, capture starts its own host.
1437
+ const acceptedHost = getShowcaseUrl()
1438
+ ? {
1439
+ url: getShowcaseUrl(),
1440
+ previewRevision: () => readPreviewManifest(previewOptions())?.revision ?? null,
1441
+ }
1442
+ : null;
1443
+ if (draft) {
1444
+ const proposal = await drafts.prepare(draft);
1445
+ if (proposal.revision !== revision) throw new Error("Draft revision changed. Reopen its preview before capturing.");
1446
+ const captured = await captures.run(
1447
+ {
1448
+ captures: [selection],
1449
+ candidateRoot: proposal.session.workspace,
1450
+ proposal: revision,
1451
+ publish: false,
1452
+ previewHosts: [acceptedHost, proposal.session.runtime],
1453
+ },
1454
+ signal,
1455
+ progress,
1456
+ );
1457
+ if ((await drafts.inspect(draft)).revision !== revision) throw new Error("Draft changed during capture; no image slots were replaced.");
1458
+ captures.store.commit(captured.records);
1459
+ const inventory = await captureInventory(),
1460
+ keys = new Set(captured.records.map((record) => record.key));
1461
+ result = {
1462
+ ok: true,
1463
+ draft,
1464
+ draftRevision: revision,
1465
+ previewOnly: true,
1466
+ captures: captures.store.list(inventory.scenarios, inventory.revision).captures.filter((record) => keys.has(record.key)),
1467
+ };
1468
+ } else
1469
+ result = await captures.run(
1470
+ {
1471
+ captures: [selection],
1472
+ previewHosts: [acceptedHost],
1473
+ },
1474
+ signal,
1475
+ progress,
1476
+ );
1477
+ await refresh();
1478
+ return captureResponse(result, era === "modern");
1479
+ },
1480
+ },
1481
+ {
1482
+ name: "ads_capture_clear",
1483
+ description:
1484
+ "Delete generated screenshot slots for one scenario/target. candidateOnly discards a proposal while retaining current. Source is unchanged. No TTL/history is kept; each target has at most current and candidate.",
1485
+ schema: z
1486
+ .object({
1487
+ scenario: z.string().min(1).max(256),
1488
+ target: z
1489
+ .string()
1490
+ .regex(/^[a-zA-Z0-9][\w.-]{0,79}$/)
1491
+ .optional(),
1492
+ candidateOnly: z.boolean().default(false),
1493
+ })
1494
+ .strict(),
1495
+ annotations: {
1496
+ readOnlyHint: false,
1497
+ destructiveHint: true,
1498
+ idempotentHint: true,
1499
+ openWorldHint: false,
1500
+ },
1501
+ call: async (args) => {
1502
+ const result = captures.store.clear(args);
1503
+ await refresh();
1504
+ return json(result);
1505
+ },
1506
+ },
1507
+ {
1508
+ name: "ads_catalog",
1509
+ description:
1510
+ "Before creating/changing UI or behavior, find existing public components/patterns/controllers and hooks with a small query/limit. Returns import alias and exact source/guide URIs so you can reuse or edit the owner. Read ads_status first for workspace/workflow. Metadata only; does not render UI.",
1511
+ schema: query.extend({
1512
+ kind: z.enum(["components", "patterns", "controllers"]).optional(),
1513
+ }),
1514
+ call: async ({ query: search = "", limit, kind }) => {
1515
+ const matches = (await getCatalog()).filter((item) => (!kind || item.kind === kind) && item.name.toLowerCase().includes(search.toLowerCase()));
1516
+ return json({
1517
+ total: matches.length,
1518
+ items: await annotateDrafts(matches.slice(0, limit)),
1519
+ resourceUri: `${PROJECT_URI}/catalog`,
1520
+ });
1521
+ },
1522
+ },
1523
+ {
1524
+ name: "ads_scenarios",
1525
+ description:
1526
+ "Find an independently mountable brand, token, component, pattern or composition preview. IDs derive from source filenames. Optional group labels are derived from folder names and searchable; group is discovery output, never scenario metadata. covers lists rendered public UI, exercises lists behavioral APIs and tokens lists the real token inputs. Use ads_show_scenario with an exact returned id. Showcase and MCP use this same registry.",
1527
+ schema: query.extend({
1528
+ kind: z.enum(["brand", "tokens", "components", "patterns", "composition"]).optional(),
1529
+ offset: z.number().int().min(0).default(0),
1530
+ }),
1531
+ call: async ({ query: search = "", limit, kind, offset }) => {
1532
+ const registry = await getRegistryAsync();
1533
+ const matches = registry.scenarios.filter(
1534
+ (item) =>
1535
+ (!kind || item.kind === kind) &&
1536
+ `${item.id} ${item.title} ${item.group ?? ""} ${item.covers.join(" ")} ${(item.exercises ?? []).join(" ")} ${item.tokens.join(" ")}`
1537
+ .toLowerCase()
1538
+ .includes(search.toLowerCase()),
1539
+ );
1540
+ const report = await builds(),
1541
+ states = new Map(report.previews.map((item) => [item.id, item]));
1542
+ return json({
1543
+ total: matches.length,
1544
+ scenarios: (await annotateDrafts(matches.slice(offset, offset + limit))).map((item) => ({ ...item, build: summarizeBuild(states.get(item.id)) })),
1545
+ ...(offset + limit < matches.length
1546
+ ? {
1547
+ nextOffset: offset + limit,
1548
+ }
1549
+ : {}),
1550
+ diagnostics: registry.diagnostics,
1551
+ resourceUri: `${PROJECT_URI}/scenarios`,
1552
+ });
1553
+ },
1554
+ },
1555
+ {
1556
+ name: "ads_show_scenario",
1557
+ title: "Scenario preview",
1558
+ description:
1559
+ "Render one real scenario with its fixtures. Discover its exact id first. Default waitFor: verified waits for successful current checks. Interactive browsers may request waitFor: compiled for unverified live feedback or a retained earlier view; inspect build.current and never use pending output as verification evidence. Requires MCP Apps and resource forwarding; fallback links to the same showcase scenario.",
1560
+ schema: z
1561
+ .object({
1562
+ id: z.string().min(1).max(256),
1563
+ waitFor: z.enum(["verified", "compiled"]).default("verified"),
1564
+ })
1565
+ .strict(),
1566
+ _meta: {
1567
+ ui: {
1568
+ resourceUri: PREVIEW_APP_URI,
1569
+ },
1570
+ },
1571
+ call: async ({ id, waitFor }, signal) => {
1572
+ const registry = await previewRegistry(waitFor);
1573
+ const entry = registry.scenarios.find((item) => item.id === id);
1574
+ if (!entry) throw new Error("Unknown scenario id. Read ads_scenarios; IDs must match discovered source entries.");
1575
+ if (registry.diagnostics.length) throw new Error("Scenario registry has errors. Read ads://project/scenarios and fix its diagnostics.");
1576
+ const app = (await scenarioApps(waitFor === "compiled")).find((item) => item.id === id);
519
1577
  const build = await previewBuild(app, signal, waitFor);
520
- const graph = graphSelection(category, build);
521
- if (!options.config.mcp.previewManifest) projectApp(options, app, build);
522
- return json({ widget: { resourceUri: options.config.mcp.previewManifest ? PREVIEW_APP_URI : TOKENS_APP_URI }, category, scenario: { ...entry, resourceUri: appUri(category) }, ...graph, build, showcaseUrl: scenarioUrl(category) });
523
- }
524
- return json({ widget: { resourceUri: TOKENS_APP_URI }, category: null, tokenCount: inspectTokens(root).tokens.length, dataUri: `${PROJECT_URI}/tokens`, showcaseUrl: getShowcaseUrl() });
525
- } },
526
- { name: "ads_behaviors", description: "Discover behavior owners, then page an exact unit's checks, guarantees, subjects, demonstrations or profiles. Summary listings never embed runner logs. Default 10/max 20 entries and 8 KiB JSON per page; continue with nextCursor and identical filters. Cursors expire when discovery/evidence changes. Read sourceFile with ads_read_file for a complete contract. Metadata and reachable calls do not prove execution; use ads_verify for registered checks.", schema: z.object({ query: z.string().max(200).optional(), unit: z.string().min(1).max(256).optional(), api: z.string().max(200).optional(), section: z.enum(behaviorSections).optional(), ...paged }).strict(), call: args => json(behaviorPage(options,args)) },
527
- { name: "ads_results", title: "Read execution outcomes", description: "Read saved ads_validate/ads_verify/ads_apply_patch/ads_apply_transaction outcomes without rerunning anything. Pass the returned resultId; select outcomes, checks, diagnostics, advisories, warnings, changes, captures, acceptance, investigation or selection. Default 10/max 20 rows, at most 8 KiB JSON per page. Follow nextCursor with identical section/status. Rows marked detailTruncated can be read in full using recordIndex and offset/chars (max 2000); follow nextOffset. Results are retained by immutable run ID with bounded age/count/disk retention, including after reconnect or other clients finish. Expired IDs fail with ADS_RESULT_EXPIRED. For one outcome's browser evidence use ads_investigate with its exact unit/check/runId.", schema: z.object({ resultId: z.string().uuid(), section: z.enum(resultSections).optional(), status: z.enum(["all","passed","not_passed"]).optional(), ...paged, ...recordRange }).strict(), call: args => json(executionResults.page(args)) },
528
- { name:"ads_report_bug",title:"Report a suspected ADS defect",description:"Record an unexpected ADS guard, preview, build, transport or runner behavior after targeted investigation. Provide expected/observed behavior, minimal steps and frequency; keep suspectedCause separate. Evidence optionally selects a returned resultId or exact unit/check/runId. ADS snapshots compact evidence, version, configured framework and revisions. A report is an untriaged agent claim, not proof of an ADS cause. Returns a small receipt with the report ID and local file path; submitted reports cannot be read through MCP. Stored locally under .ds/reports/ with deduplication, no automatic expiry and no upload. Read ads://guides/reporting; ordinary valid guard rejections should be fixed in their owner.",schema:bugReportSchema,annotations:{readOnlyHint:false,destructiveHint:false,idempotentHint:false,openWorldHint:false},call:args=>submitReport("bug",args) },
529
- { name:"ads_request_feature",title:"Request an ADS capability",description:"Record a legitimate workflow that needs a missing ADS capability. Provide workflow, capability and impact; proposal is optional. Preserve valid design/API rather than weakening guards or inventing workaround props. Optional evidence references an existing execution/check, not pasted files/logs. ADS attaches compact context and returns a receipt with the report ID and local file path. Intake is submission-only; no report-reading tools or resources. Shared local report store: deduplicated, untriaged, no automatic expiry or upload. Read ads://guides/reporting; use ads_report_bug for suspected broken existing behavior.",schema:featureRequestSchema,annotations:{readOnlyHint:false,destructiveHint:false,idempotentHint:false,openWorldHint:false},call:args=>submitReport("feature",args) },
530
- { name: "ads_investigate", title: "Inspect check evidence", description: "Read a summary for an exact unit/check, or list latest investigations when no check is selected. Pass the outcome's runId to reject superseded evidence. Summary is at most 4 KiB JSON; details, requests, browserErrors and artifacts are separate paged sections (default 10/max 20 entries, 8 KiB). Read truncated rows with recordIndex/offset/chars and the exact runId. Artifact URIs are read separately. Does not rerun checks or infer root cause. Lists latest checks; an exact runId reads retained historical evidence, including candidate runs.", schema: z.object({unit:z.string().min(1).max(256).optional(),check:z.string().min(1).max(100).optional(),runId:z.string().min(1).max(100).optional(),section:z.enum(investigationSections).optional(),...paged,...recordRange}).strict(), call: args => json(investigationPage(root,args)) },
531
- { name: "ads_validate", description: "Run mandatory ADS architecture/freshness guards and the selected project policy. policy defaults to validation: its configured scripts, preview freshness, optional registered behavior checks and, unless <policy>.browserAudit is false, an axe-core audit of every rendered UI scenario in every declared brand and theme (a11y-axe findings are blocking errors in the diagnostics section). policy acceptance runs acceptance.checks, acceptance.behaviorChecks and acceptance.browserAudit without applying source, for direct editing; draft acceptance and guarded patches run the same acceptance policy, auditing only the candidate's affected UI scenarios. No script names are inferred. scope changed selects affected registered checks from this policy's own successful full baseline; broad changes expand to all. Project scripts keep full scope. Draft edit/show never triggers policies. Reports skipped stages honestly and a bounded resultId; use ads_results for details. Read ads://guides/validation. Trusted configured commands run; nothing is installed.", schema: z.object({scope:z.enum(["all","changed"]).default("all"),policy:z.enum(["acceptance","validation"]).default("validation"),fresh:z.boolean().default(false)}).strict(), annotations: {readOnlyHint:false,destructiveHint:false,idempotentHint:false,openWorldHint:false}, call: async (args,signal,progress) => {
532
- return finishExecution("validation",await validation.run(args,signal,progress));
533
- } },
534
- { name: "ads_verify", description: "Run one owner's registered development behavior checks using its configured runner/profile. Executes trusted project commands with bounded output, cancellation and process-tree cleanup; installs nothing. Progress and per-check timings are available through ads_status; a profile timeout bounds the whole run. Browser profiles use an isolated managed showcase/MCP App. React StrictMode requires a project development harness, not a production widget. Missing/skipped cases, stale inputs and process exit alone cannot produce passing evidence. Replies contain counts, acceptance, at most three failure summaries and a resultId (4 KiB JSON maximum). Page outcomes with ads_results; inspect one exact unit/check/runId with ads_investigate. Discover exact unit/check IDs with ads_behaviors first.", schema: z.object({ unit: z.string().min(1).max(256), checks: z.array(z.string().min(1).max(100)).min(1).max(100).optional() }).strict(), annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: false, openWorldHint: false }, call: async (args, signal, progress) => {
535
- const result = await verification.run(args, signal, progress);
536
- return finishExecution("verification", {unit:args.unit,...result});
537
- } },
538
- { name: "ads_units", description: "Discover editable ADS units and their files: components/patterns with colocated previews; shared controllers; development review/ helpers with a separate export entry; composition; tokens; foundation shared files; documentation including shared credits/license notices; assets/brand, assets/fonts and asset groups; configuration with ds.config.json, package/build/lint configuration and registered project guard/compiler sources. List summaries with query, or pass an exact unit ID for its manifest. Manifests include filePolicy for supported new documentation paths and companionFiles with permitted shared-entry or owner-only style-boundary bookkeeping; preserve peer permissions and unrelated configuration. Imported peers stay separate. New owners follow the existing colocation convention.", schema: query.extend({ unit: z.string().min(1).max(256).optional() }), call: ({ unit, query: search = "", limit }) => {
539
- const matches = edits.units().filter(item => unit ? item.id === unit : item.id.toLowerCase().includes(search.toLowerCase()));
540
- return json({ total: matches.length, units: matches.slice(0, limit).map(item => ({ id: item.id, kind: item.kind, fileCount: item.files.length, ...(unit ? { files: item.files.slice(0, 200), filesTruncated: item.files.length > 200, ...(item.companionFiles ? { companionFiles: item.companionFiles } : {}), ...(item.filePolicy ? { filePolicy: item.filePolicy } : {}) } : {}) })) });
541
- } },
542
- { name: "ads_read_file", description: "Read a bounded range of ADS or registered configuration/extension source. Returns unit, full-file digest, startLine and nextOffset; default/max is 12000 UTF-16 characters. Binary assets return byte count/digest and no encoded content. Paths come from ads_units or discovery. Missing new paths return digest null. Read only relevant context before preparing a Git patch.", schema: z.object({ path: z.string().min(1).max(500), offset: z.number().int().min(0).default(0), limit: z.number().int().min(1).max(mutationLimits.readChars).default(mutationLimits.readChars) }).strict(), call: ({ path: file, ...range }) => json(isDraftFile(file)?drafts.readFile(file,range):edits.read(file, range)) },
543
- ...(mutations ? [{ name: "ads_prepare_patch", description: "Prepare a Git patch without a separate project mirror. Create copies only one owner plus its declared companions into a local draft; edit that directory with local file tools. Diff checks baseline/source freshness and owner paths, then writes a patchFile under .ds/patches. Migrate prepares mechanical .ads. role names and legacy contracts in that draft, retaining unresolved sections for review. Discard removes the draft. Live source is never changed; ads_apply_patch still validates all gates. Remote clients can continue sending inline Git diffs instead.", schema:z.object({unit:z.string().min(1).max(256),action:z.enum(["create","migrate","diff","discard"]).default("create"),draft:z.string().max(100).optional()}).strict(), call:args=>json(prepareUnitPatch(options,args)) },
544
- {name:"ads_prepare_token_samples",description:"Reconcile a token scenario's consumed literal fixture samples. Removes undeclared tokens, preserves existing project bindings, and accepts explicit real-token/property/probe bindings. Reports unresolved token names; never guesses CSS meaning from token names. Returns an owner patchFile without changing source. Apply it through ads_apply_patch and review the real preview.",schema:z.object({id:z.string().min(1).max(256),bindings:z.array(z.object({token:z.string().max(256),property:z.string().max(100),probe:z.string().max(1000)}).passthrough()).max(1000).optional()}).strict(),call:args=>{
545
- const {patch,...result}=reconcileTokenSamples(options,args);
546
- return json({...result,removed:result.removed.slice(0,50),unresolved:result.unresolved.slice(0,50),unresolvedCount:result.unresolved.length,...storePreparedPatch(options,patch)});
547
- }},
548
- { name: "ads_apply_patch", description: "Apply one Git diff to one ADS unit from ads_units. Pass exactly one of patch (inline) or patchFile (a regular .patch/.diff under .ds/patches/, for large/binary diffs without model-context bytes). Text uses --- a/path, +++ b/path and exact @@ hunks; /dev/null creates/deletes. Git binary patches require git diff --binary --full-index and installed Git. A unit owns its implementation, previews and fixtures; imported peers are separate. Foundation, documentation, assets and configuration are editable too. Configuration changes may register/edit project guards and builders; the proposed schema, mandatory ADS and candidate project checks must pass. Only selected-unit public re-exports may change; preserve unrelated statements. A real selected-unit re-export may remove a redundant export {}; placeholder. A tokens patch may include its companionFiles foundation entry only to add/remove canonical imports required by token files created/deleted in this patch, preserving other imports/comments and canonical order. A runtime owner patch may also include its ds.config.json companion solely for that owner's inlineStyleFiles/styleWrites entries alongside its source. Unused permissions fail validation. Unless acceptance.browserAudit is false, axe-core audits the candidate's affected UI scenarios in every brand and theme; a11y-axe errors reject the patch. Set dryRun true to validate without writing. Optional screenshot:true plus captures:[{scenario,target?,theme?,brand?,viewport?}] captures current/candidate only after gates pass. For genuinely coupled owner changes use ads_apply_transaction with one patch per owner. Fix rejected patches and inspect current previews after acceptance. Reply is a 4 KiB summary; read diagnostics, outcomes and requested captures through ads_results using its resultId.",
549
- schema: z.object({ unit: z.string().min(1).max(256), dryRun: z.boolean(), patch: z.string().min(1).max(mutationLimits.patchBytes).optional(), patchFile: z.string().min(1).max(500).optional(), ...screenshotFields }).strict().refine(args => (args.patch !== undefined) !== (args.patchFile !== undefined), "Provide exactly one of patch or patchFile."),
550
- annotations: { readOnlyHint: false, destructiveHint: true, idempotentHint: false, openWorldHint: false }, _meta: { ui: { visibility: ["model"] } },
551
- call: applyEdits,
552
- }, {name:"ads_apply_transaction",description:"Apply genuinely coupled ADS changes as 2–64 distinct owner Git patches. Each patch must obey its unit and narrow companion rules. Patches run in order; later patches use the earlier candidate's shared-entry content. Core guards, configured project checks, affected behavior checks and, unless acceptance.browserAudit is false, the axe-core audit of affected UI scenarios validate the complete final candidate before any live source is written. Maximum 256 distinct files/16 MiB combined. Dry runs, failures and cancellation publish nothing; publication rolls back on write failure. Optional screenshot:true with dryRun:true and explicit captures selects current/candidate images. Prefer ads_apply_patch for independent edits. Reply is a bounded summary; page diagnostics, outcomes and captures with ads_results using the returned resultId.",schema:z.object({patches:z.array(ownerPatch).min(2).max(mutationLimits.units),dryRun:z.boolean(),...screenshotFields}).strict(),annotations:{readOnlyHint:false,destructiveHint:true,idempotentHint:false,openWorldHint:false},_meta:{ui:{visibility:["model"]}},call:applyEdits}] : []),
553
- ...options.config.mcp.apps.map((app) => ({ name: `ads_show_${app.id.replaceAll("-", "_")}`, title: app.title, description: `${app.description ?? app.title}. Renders the project's built ${app.kind} examples through MCP Apps; text fallback provides the showcase URL.`, schema: empty, _meta: { ui: { resourceUri: appUri(app.id) } }, call: async (_args, signal) => {
554
- // Validate readiness without embedding executable HTML in model results.
555
- const build = await previewBuild(app, signal);
556
- projectApp(options, app);
557
- return json({ widget: { resourceUri: appUri(app.id) }, title: app.title, kind: app.kind, build, showcaseUrl: getShowcaseUrl() });
558
- } })),
1578
+ const graph = graphSelection(id, build);
1579
+ return json({
1580
+ widget: {
1581
+ resourceUri: PREVIEW_APP_URI,
1582
+ },
1583
+ scenario: {
1584
+ ...entry,
1585
+ resourceUri: appUri(id),
1586
+ },
1587
+ ...graph,
1588
+ build,
1589
+ showcaseUrl: scenarioUrl(id),
1590
+ });
1591
+ },
1592
+ },
1593
+ {
1594
+ name: "ads_tokens",
1595
+ description:
1596
+ "Use before styling, theme, brand or motion-token changes to inspect existing semantic definitions/values. Query specific token names with a small limit. ads_show_scenario renders a token scenario (ids from ads_scenarios kind: tokens); definition inspection does not validate component layout.",
1597
+ schema: query,
1598
+ call: async ({ query: search = "", limit }) => {
1599
+ const inventory = await tokenInventory();
1600
+ await getRegistryAsync();
1601
+ const matches = inventory.tokens.filter((token) => token.name.toLowerCase().includes(search.toLowerCase()));
1602
+ return json({
1603
+ total: matches.length,
1604
+ tokens: matches.slice(0, limit),
1605
+ categories: await tokenScenarios(),
1606
+ tokenGroups: await drafts.tokenGroups(inventory.tokens),
1607
+ diagnosticCount: inventory.diagnostics.length,
1608
+ resourceUri: `${PROJECT_URI}/tokens`,
1609
+ dtcgUri: `${PROJECT_URI}/tokens/dtcg`,
1610
+ });
1611
+ },
1612
+ },
1613
+ // Skills tools only for 2025-era clients; 2026-07-28 clients read skills natively through the skills extension.
1614
+ ...(era === "modern"
1615
+ ? []
1616
+ : [
1617
+ {
1618
+ name: "ads_skills",
1619
+ description:
1620
+ "Select one ADS workflow after ads_status: ads-designer for building, refining, animating, stress-testing or debugging UI; ads-port for a library reference; ads-import for another project's ADS; ads-migrate for version upgrades. Then read that workflow with ads_read_skill. Listing does not activate a native skill.",
1621
+ schema: empty,
1622
+ call: () =>
1623
+ json({
1624
+ skills: skills.skills.map(({ uri, frontmatter }) => ({
1625
+ uri,
1626
+ ...frontmatter,
1627
+ })),
1628
+ }),
1629
+ },
1630
+ {
1631
+ name: "ads_read_skill",
1632
+ description:
1633
+ "Read a selected skill or relative supporting text file in bounded chunks. This is explicit instruction access, not automatic native skill activation/install.",
1634
+ schema: z
1635
+ .object({
1636
+ name: z.string().max(64),
1637
+ file: z.string().max(300).default("SKILL.md"),
1638
+ offset: z.number().int().min(0).default(0),
1639
+ limit: z.number().int().min(1).max(8000).default(6000),
1640
+ })
1641
+ .strict(),
1642
+ call: ({ name, file, offset, limit }) => {
1643
+ const skill = skills.skills.find((entry) => entry.frontmatter.name === name);
1644
+ if (!skill) throw new Error("Unknown ADS skill name.");
1645
+ const uri = `${skill.uri.slice(0, -"SKILL.md".length)}${file.split("/").map(encodeURIComponent).join("/")}`;
1646
+ const manifest = skill.resources.find((resource) => resource.uri === uri);
1647
+ if (!manifest) throw new Error("Unknown relative skill file. Consult its manifest with native skills/get or the resources catalog.");
1648
+ const content = skills.read(uri);
1649
+ if (!("text" in content))
1650
+ return json({
1651
+ ...manifest,
1652
+ mimeType: content.mimeType,
1653
+ binary: true,
1654
+ note: "Read binary bytes via resources/read; this tool does not embed them.",
1655
+ });
1656
+ return json({
1657
+ ...manifest,
1658
+ text: content.text.slice(offset, offset + limit),
1659
+ offset,
1660
+ ...(offset + limit < content.text.length
1661
+ ? {
1662
+ nextOffset: offset + limit,
1663
+ }
1664
+ : {}),
1665
+ });
1666
+ },
1667
+ },
1668
+ ]),
1669
+ {
1670
+ name: "ads_behaviors",
1671
+ description:
1672
+ "Discover behavior owners, then page an exact unit's checks, guarantees, subjects, demonstrations or profiles. Summary listings never embed runner logs. Default 10/max 20 entries and 8 KiB JSON per page; continue with nextCursor and identical filters. Cursors expire when discovery/evidence changes. Read sourceFile with ads_read_file for a complete contract. Metadata and reachable calls do not prove execution; registered checks run at ads_accept (the draft owners' own) and ads_validate (everything the change set reaches).",
1673
+ schema: z
1674
+ .object({
1675
+ query: z.string().max(200).optional(),
1676
+ unit: z.string().min(1).max(256).optional(),
1677
+ api: z.string().max(200).optional(),
1678
+ section: z.enum(behaviorSections).optional(),
1679
+ ...paged,
1680
+ })
1681
+ .strict(),
1682
+ call: async (args) => json(await behaviorInventory(args)),
1683
+ },
1684
+ {
1685
+ name: "ads_results",
1686
+ title: "Read execution outcomes",
1687
+ description:
1688
+ "Read saved ads_validate/ads_accept outcomes without rerunning anything. Pass the returned resultId; select outcomes, checks, diagnostics, advisories, warnings, changes, captures, acceptance, investigation or selection. Default 10/max 20 rows, at most 8 KiB JSON per page. Follow nextCursor with identical section/status. Rows marked detailTruncated can be read in full using recordIndex and offset/chars (max 2000); follow nextOffset. Results are retained by immutable run ID with bounded age/count/disk retention, including after reconnect or other clients finish. Expired IDs fail with ADS_RESULT_EXPIRED. For one outcome's browser evidence use ads_investigate with its exact unit/check/runId.",
1689
+ schema: z
1690
+ .object({
1691
+ resultId: z.string().uuid(),
1692
+ section: z.enum(resultSections).optional(),
1693
+ status: z.enum(["all", "passed", "not_passed"]).optional(),
1694
+ ...paged,
1695
+ ...recordRange,
1696
+ })
1697
+ .strict(),
1698
+ call: (args) => json(executionResults.page(args)),
1699
+ },
1700
+ {
1701
+ name: "ads_investigate",
1702
+ title: "Inspect check evidence",
1703
+ description:
1704
+ "Read a summary for an exact unit/check, or list latest investigations when no check is selected. Pass the outcome's runId to reject superseded evidence. Summary is at most 4 KiB JSON; details, requests, browserErrors and artifacts are separate paged sections (default 10/max 20 entries, 8 KiB). Read truncated rows with recordIndex/offset/chars and the exact runId. Artifact URIs are read separately. Does not rerun checks or infer root cause. Lists latest checks; an exact runId reads retained historical evidence, including candidate runs.",
1705
+ schema: z
1706
+ .object({
1707
+ unit: z.string().min(1).max(256).optional(),
1708
+ check: z.string().min(1).max(100).optional(),
1709
+ runId: z.string().min(1).max(100).optional(),
1710
+ section: z.enum(investigationSections).optional(),
1711
+ ...paged,
1712
+ ...recordRange,
1713
+ })
1714
+ .strict(),
1715
+ call: (args) => json(investigationPage(root, args)),
1716
+ },
1717
+ {
1718
+ name: "ads_validate",
1719
+ description:
1720
+ "The project gate: ads check, acceptance.scripts then validation.scripts, and every registered behavior test and render audit (axe-core, non-text contrast, overflow, layout shift, image shape in every brand and theme) its change set reaches; any failure or render-audit error fails it. scope changed is what changed since the last successful full validation (shared configuration, foundation or token changes widen it to everything); scope all is everything. Run it after a series of accepted drafts and before merging or releasing. Draft edit/show never runs it. Reports skipped stages honestly and a bounded resultId; use ads_results for details and ads_investigate for one failed behavior check. Read ads://guides/validation. Trusted configured commands run; nothing is installed.",
1721
+ schema: z
1722
+ .object({
1723
+ scope: z.enum(["all", "changed"]).default("all"),
1724
+ fresh: z.boolean().default(false),
1725
+ })
1726
+ .strict(),
1727
+ annotations: {
1728
+ readOnlyHint: false,
1729
+ destructiveHint: false,
1730
+ idempotentHint: false,
1731
+ openWorldHint: false,
1732
+ },
1733
+ call: async (args, signal, progress) => {
1734
+ return finishExecution("validation", await validation.run(args, signal, progress));
1735
+ },
1736
+ },
1737
+ {
1738
+ name: "ads_units",
1739
+ description:
1740
+ "Discover editable ADS units and their files: components/patterns with colocated previews; shared controllers; development review/ helpers with a separate export entry; composition; tokens; foundation shared files; documentation including shared credits/license notices; assets/brand, assets/fonts and asset groups; configuration with ds.config.json, package/build/lint configuration and registered project guard/compiler sources. List summaries with query, or pass an exact unit ID for its manifest. Manifests include filePolicy for supported new documentation paths; every authored file has one owner and shared entries are generated; preserve peer permissions and unrelated configuration. Imported peers stay separate. New owners follow the existing colocation convention.",
1741
+ schema: query.extend({
1742
+ unit: z.string().min(1).max(256).optional(),
1743
+ }),
1744
+ call: async ({ unit, query: search = "", limit }) => {
1745
+ const matches = (await edits.units()).filter((item) => (unit ? item.id === unit : item.id.toLowerCase().includes(search.toLowerCase())));
1746
+ return json({
1747
+ total: matches.length,
1748
+ units: matches
1749
+ .slice(0, limit)
1750
+ .map((item) => ({
1751
+ id: item.id,
1752
+ kind: item.kind,
1753
+ fileCount: item.files.length,
1754
+ ...(unit
1755
+ ? { files: item.files.slice(0, 200), filesTruncated: item.files.length > 200, ...(item.filePolicy ? { filePolicy: item.filePolicy } : {}) }
1756
+ : {}),
1757
+ })),
1758
+ });
1759
+ },
1760
+ },
1761
+ {
1762
+ name: "ads_read_file",
1763
+ description:
1764
+ "Read a bounded range of ADS or registered configuration/extension source. Returns unit, full-file digest, startLine and nextOffset; default/max is 12000 UTF-16 characters. Binary assets return byte count/digest and no encoded content. Paths come from ads_units or discovery. Missing new paths return digest null. Read only relevant context before preparing a Git patch.",
1765
+ schema: z
1766
+ .object({
1767
+ path: z.string().min(1).max(500),
1768
+ offset: z.number().int().min(0).default(0),
1769
+ limit: z.number().int().min(1).max(mutationLimits.readChars).default(mutationLimits.readChars),
1770
+ })
1771
+ .strict(),
1772
+ call: async ({ path: file, ...range }) => json(isDraftFile(file) ? drafts.readFile(file, range) : await edits.read(file, range)),
1773
+ },
559
1774
  ];
560
1775
  }
561
1776
  server.setRequestHandler("tools/list", ({ params = {} }) => {
562
1777
  previewWatch?.start();
563
1778
  const { cursor } = params;
564
- const listing = page(tools().map(({ schema, call: _call, ...tool }) => ({ ...tool, inputSchema: z.toJSONSchema(schema), annotations: tool.annotations ?? annotations })), cursor, "tools");
565
- return { tools: listing.items, ...(listing.nextCursor ? { nextCursor: listing.nextCursor } : {}) };
1779
+ const listing = page(
1780
+ tools().map(({ schema, call: _call, ...tool }) => ({
1781
+ ...tool,
1782
+ inputSchema: z.toJSONSchema(schema),
1783
+ annotations: tool.annotations ?? annotations,
1784
+ })),
1785
+ cursor,
1786
+ "tools",
1787
+ );
1788
+ return {
1789
+ tools: listing.items,
1790
+ ...(listing.nextCursor
1791
+ ? {
1792
+ nextCursor: listing.nextCursor,
1793
+ }
1794
+ : {}),
1795
+ };
566
1796
  });
567
1797
  server.setRequestHandler("tools/call", async ({ params: { name, arguments: args } }, context) => {
568
1798
  const tool = tools().find((entry) => entry.name === name);
@@ -572,139 +1802,407 @@ export function createAdsMcp(directory, { era = "legacy", skillDirectory, pollIn
572
1802
  previewWatch?.start();
573
1803
  let progress = 0;
574
1804
  const token = context.mcpReq._meta?.progressToken;
575
- const notify = token === undefined ? undefined : value => {
576
- void context.mcpReq.notify({ method: "notifications/progress", params: { progressToken: token, progress: ++progress, message: value.message ?? (value.stage?`${value.stage}: ${value.elapsedMs??0} ms elapsed`:`${value.profile}: ${value.completed}/${value.total} completed; ${(value.active ?? []).slice(0,3).map(item => `${item.unit}#${item.check}`).join(", ") || "no active check reported"}; ${value.elapsedMs} ms elapsed`) } }).catch(() => {});
577
- };
1805
+ const notify =
1806
+ token === undefined
1807
+ ? undefined
1808
+ : (value) => {
1809
+ void context.mcpReq
1810
+ .notify({
1811
+ method: "notifications/progress",
1812
+ params: {
1813
+ progressToken: token,
1814
+ progress: ++progress,
1815
+ message:
1816
+ value.message ??
1817
+ (value.stage
1818
+ ? `${value.stage}: ${value.elapsedMs ?? 0} ms elapsed`
1819
+ : `${value.profile}: ${value.completed}/${value.total} completed; ${
1820
+ (value.active ?? [])
1821
+ .slice(0, 3)
1822
+ .map((item) => `${item.unit}#${item.check}`)
1823
+ .join(", ") || "no active check reported"
1824
+ }; ${value.elapsedMs} ms elapsed`),
1825
+ },
1826
+ })
1827
+ .catch(() => {});
1828
+ };
578
1829
  try {
579
- const kinds={ads_validate:"validation",ads_verify:"verification",ads_apply_patch:"mutation",ads_apply_transaction:"mutation",ads_accept:"mutation"};
580
- const kind=kinds[name];
581
- if(!kind)return await tool.call(input.data,context.mcpReq.signal,notify);
582
- const client=server.getClientVersion?.();
583
- const label=context.mcpReq._meta?.["ads/clientId"];
584
- const owner={clientId:typeof label==="string"?label.slice(0,100):null,clientName:client?.name?.slice(0,100)??null,connectionId};
585
- const args=input.data;
586
- const selection={...(args.policy?{policy:args.policy}:{}),...(args.scope?{requestedScope:args.scope,scope:args.scope}:{}),units:args.units??args.patches?.map(row=>row.unit)??(args.unit?[args.unit]:[]),...(args.id?{draft:args.id}:{}),...(args.checks?{checks:args.checks}:{})};
587
- const summary=await coordinator.execute({operation:name,kind,owner,selection,watchSource:kind!=="mutation"},context.mcpReq.signal,notify,(signal,progress)=>{
588
- executionContext.getStore().fresh=args.fresh??false;
589
- if(name==="ads_accept")progress({stage:"selection",policy:"acceptance",scope:"changed",units:drafts.inspect(args.id).manifest.units});
590
- return tool.call(args,signal,progress);
591
- });
592
- const {isError,...value}=summary;
1830
+ const kinds = {
1831
+ ads_validate: "validation",
1832
+ ads_accept: "mutation",
1833
+ };
1834
+ const kind = kinds[name];
1835
+ if (!kind) return await tool.call(input.data, context.mcpReq.signal, notify);
1836
+ const client = server.getClientVersion?.();
1837
+ const label = context.mcpReq._meta?.["ads/clientId"];
1838
+ const owner = {
1839
+ clientId: typeof label === "string" ? label.slice(0, 100) : null,
1840
+ clientName: client?.name?.slice(0, 100) ?? null,
1841
+ connectionId,
1842
+ };
1843
+ const args = input.data;
1844
+ const selection = {
1845
+ ...(args.scope
1846
+ ? {
1847
+ requestedScope: args.scope,
1848
+ scope: args.scope,
1849
+ }
1850
+ : {}),
1851
+ units: args.units ?? args.patches?.map((row) => row.unit) ?? (args.unit ? [args.unit] : []),
1852
+ ...(args.id
1853
+ ? {
1854
+ draft: args.id,
1855
+ }
1856
+ : {}),
1857
+ ...(args.checks
1858
+ ? {
1859
+ checks: args.checks,
1860
+ }
1861
+ : {}),
1862
+ };
1863
+ const summary = await coordinator.execute(
1864
+ {
1865
+ operation: name,
1866
+ kind,
1867
+ owner,
1868
+ selection,
1869
+ watchSource: kind !== "mutation",
1870
+ },
1871
+ context.mcpReq.signal,
1872
+ notify,
1873
+ async (signal, progress) => {
1874
+ executionContext.getStore().fresh = args.fresh ?? false;
1875
+ if (name === "ads_accept")
1876
+ progress({
1877
+ stage: "selection",
1878
+ scope: "draft",
1879
+ units: (await drafts.inspect(args.id)).manifest.units,
1880
+ });
1881
+ return tool.call(args, signal, progress);
1882
+ },
1883
+ );
1884
+ const { isError, ...value } = summary;
593
1885
  await refresh();
594
- return {...json(value),...(isError?{isError:true}:{})};
1886
+ return {
1887
+ ...json(value),
1888
+ ...(isError
1889
+ ? {
1890
+ isError: true,
1891
+ }
1892
+ : {}),
1893
+ };
1894
+ } catch (error) {
1895
+ return {
1896
+ isError: true,
1897
+ content: [
1898
+ {
1899
+ type: "text",
1900
+ text: error.message,
1901
+ },
1902
+ ],
1903
+ structuredContent: {
1904
+ ok: false,
1905
+ message: error.message,
1906
+ ...(error.code
1907
+ ? {
1908
+ code: error.code,
1909
+ }
1910
+ : {}),
1911
+ ...(error.lock
1912
+ ? {
1913
+ lock: error.lock,
1914
+ }
1915
+ : {}),
1916
+ failure: failure(
1917
+ error.build ? "build" : "runner",
1918
+ error.build ? "preview-build" : "tool-execution",
1919
+ error.build?.code ?? error.code ?? "ADS_TOOL_ERROR",
1920
+ {
1921
+ certainty: "observed-boundary",
1922
+ },
1923
+ ),
1924
+ ...(error.build
1925
+ ? {
1926
+ build: error.build,
1927
+ }
1928
+ : {}),
1929
+ },
1930
+ };
595
1931
  }
596
- catch (error) { return { isError: true, content: [{ type: "text", text: error.message }], structuredContent: {ok:false,message:error.message,...(error.code?{code:error.code}:{}),...(error.lock?{lock:error.lock}:{}),failure:failure(error.build?"build":"runner",error.build?"preview-build":"tool-execution",error.build?.code??error.code??"ADS_TOOL_ERROR",{certainty:"observed-boundary"}),...(error.build?{build:error.build}:{})} }; }
597
1932
  });
598
- server.setRequestHandler("resources/list", ({ params = {} }) => {
1933
+ server.setRequestHandler("resources/list", async ({ params = {} }) => {
1934
+ await getRegistryAsync();
599
1935
  previewWatch?.start();
600
1936
  const { cursor } = params;
601
- const listing = page(resources(), cursor, "resources");
602
- return { resources: listing.items, ...(listing.nextCursor ? { nextCursor: listing.nextCursor } : {}) };
1937
+ const listing = page(await resources(), cursor, "resources");
1938
+ return {
1939
+ resources: listing.items,
1940
+ ...(listing.nextCursor
1941
+ ? {
1942
+ nextCursor: listing.nextCursor,
1943
+ }
1944
+ : {}),
1945
+ };
603
1946
  });
604
- server.setRequestHandler("resources/templates/list", () => ({ resourceTemplates: [
605
- { uriTemplate: "ads://drafts/{id}/resource?uri=ads%3A%2F%2Fproject%2Fscenarios", name:"Draft scenario diagnostics",description:"Draft-private registry and diagnostics; accepted ads://project/scenarios is a separate registry.",mimeType:"application/json" },
606
- { uriTemplate: "ads://drafts/{id}/resource?uri=ads%3A%2F%2Fproject%2Fbuild", name: "Draft preview build status", description: "Use preview.resourceUri from ads_drafts or ads://project/build. Available while the draft preview session is active; updates on build completion and failure.", mimeType: "application/json" },
607
- { uriTemplate: "ads://captures/{key}/{slot}", name: "Current/candidate screenshot", description: "Exact keys and available slots come from ads://project/captures. Slots are replaced in place, not revision history.", mimeType: "image/png" },
608
- { uriTemplate: "ads://results/{resultId}", name: "Saved execution summary", description: "Use resultId from execution or ads://project/results. Query section/status/cursor/limit for pages, or section/recordIndex/offset/chars for exact record ranges. Only the latest result of each kind remains available.", mimeType: "application/json" },
609
- { uriTemplate: "ads://investigations/{unit}/{check}", name: "Latest check investigation", description: "Use encoded unit/check segments from ads://project/investigations. One latest bundle per check, including candidate verification.", mimeType: "application/json" },
610
- ] }));
611
- server.setRequestHandler("resources/read", ({ params: { uri } }, context) => read(uri, context.mcpReq.signal));
612
- server.setRequestHandler("resources/subscribe", ({ params: { uri } }) => {
613
- if (!resources().some((entry) => entry.uri === uri)) {
614
- if(uri.startsWith("ads://results/")) {
615
- try {executionResults.readResource(uri);subscribed.add(uri);return {};}catch{throw new ResourceNotFoundError(uri,"Unknown or superseded execution result.");}
1947
+ server.setRequestHandler("resources/templates/list", () => ({
1948
+ resourceTemplates: [
1949
+ {
1950
+ uriTemplate: "ads://drafts/{id}/resource?uri=ads%3A%2F%2Fproject%2Fscenarios",
1951
+ name: "Draft scenario diagnostics",
1952
+ description: "Draft-private registry and diagnostics; accepted ads://project/scenarios is a separate registry.",
1953
+ mimeType: "application/json",
1954
+ },
1955
+ {
1956
+ uriTemplate: "ads://drafts/{id}/resource?uri=ads%3A%2F%2Fproject%2Fbuild",
1957
+ name: "Draft preview build status",
1958
+ description:
1959
+ "Use preview.resourceUri from ads_drafts or ads://project/build. Available while the draft preview session is active; updates on build completion and failure.",
1960
+ mimeType: "application/json",
1961
+ },
1962
+ {
1963
+ uriTemplate: "ads://project/tokens/dtcg{?theme,brand}",
1964
+ name: "Project tokens as W3C Design Tokens (DTCG) JSON",
1965
+ description:
1966
+ "Same as `ads tokens --format dtcg [--theme <name>] [--brand <name>]`: one theme's and brand's values, the others in $extensions. Names come from ads://project/tokens.",
1967
+ mimeType: "application/json",
1968
+ },
1969
+ {
1970
+ uriTemplate: "ads://captures/{key}/{slot}",
1971
+ name: "Current/candidate screenshot",
1972
+ description: "Exact keys and available slots come from ads://project/captures. Slots are replaced in place, not revision history.",
1973
+ mimeType: "image/png",
1974
+ },
1975
+ {
1976
+ uriTemplate: "ads://results/{resultId}",
1977
+ name: "Saved execution summary",
1978
+ description:
1979
+ "Use resultId from execution or ads://project/results. Query section/status/cursor/limit for pages, or section/recordIndex/offset/chars for exact record ranges. Only the latest result of each kind remains available.",
1980
+ mimeType: "application/json",
1981
+ },
1982
+ {
1983
+ uriTemplate: "ads://investigations/{unit}/{check}",
1984
+ name: "Latest check investigation",
1985
+ description: "Use encoded unit/check segments from ads://project/investigations. One latest bundle per check, including candidate verification.",
1986
+ mimeType: "application/json",
1987
+ },
1988
+ ],
1989
+ }));
1990
+ server.setRequestHandler("resources/read", async ({ params: { uri } }, context) => read(uri, context.mcpReq.signal));
1991
+ server.setRequestHandler("resources/subscribe", async ({ params: { uri } }) => {
1992
+ await getRegistryAsync();
1993
+ if (!(await resources()).some((entry) => entry.uri === uri)) {
1994
+ if (uri.startsWith("ads://results/")) {
1995
+ try {
1996
+ executionResults.readResource(uri);
1997
+ subscribed.add(uri);
1998
+ return {};
1999
+ } catch {
2000
+ throw new ResourceNotFoundError(uri, "Unknown or superseded execution result.");
2001
+ }
616
2002
  }
617
- if(uri.startsWith("ads://investigations/")) {
618
- try {readInvestigationResource(root,uri);subscribed.add(uri);return {};}catch{throw new ResourceNotFoundError(uri,"Unknown check investigation.");}
2003
+ if (uri.startsWith("ads://investigations/")) {
2004
+ try {
2005
+ readInvestigationResource(root, uri);
2006
+ subscribed.add(uri);
2007
+ return {};
2008
+ } catch {
2009
+ throw new ResourceNotFoundError(uri, "Unknown check investigation.");
2010
+ }
619
2011
  }
620
2012
  if (!uri.startsWith("ads://captures/")) throw new ResourceNotFoundError(uri, "Unknown ADS resource subscription.");
621
- try { const inventory = captureInventory(); captures.store.readResource(uri, inventory.scenarios, inventory.revision, { allowUnknownTargets: !!inventory.diagnostics.length }); } catch { throw new ResourceNotFoundError(uri, "Unknown or absent screenshot slot."); }
2013
+ try {
2014
+ const inventory = await captureInventory();
2015
+ captures.store.readResource(uri, inventory.scenarios, inventory.revision, {
2016
+ allowUnknownTargets: !!inventory.diagnostics.length,
2017
+ });
2018
+ } catch {
2019
+ throw new ResourceNotFoundError(uri, "Unknown or absent screenshot slot.");
2020
+ }
622
2021
  }
623
- subscribed.add(uri); return {};
2022
+ subscribed.add(uri);
2023
+ return {};
2024
+ });
2025
+ server.setRequestHandler("resources/unsubscribe", ({ params: { uri } }) => {
2026
+ subscribed.delete(uri);
2027
+ return {};
624
2028
  });
625
- server.setRequestHandler("resources/unsubscribe", ({ params: { uri } }) => { subscribed.delete(uri); return {}; });
626
- server.setRequestHandler("prompts/list", () => ({ prompts: promptDefinitions(skills.skills) }));
2029
+ server.setRequestHandler("prompts/list", () => ({
2030
+ prompts: promptDefinitions(skills.skills),
2031
+ }));
627
2032
  server.setRequestHandler("prompts/get", ({ params: { name, arguments: args } }) => {
628
- try { return getWorkflowPrompt(name, args, skills.skills); } catch (error) { throw new InvalidParamsError(error.message); }
2033
+ try {
2034
+ return getWorkflowPrompt(name, args, skills.skills);
2035
+ } catch (error) {
2036
+ throw new InvalidParamsError(error.message);
2037
+ }
629
2038
  });
630
2039
  if (era === "modern") {
631
2040
  server.setRequestHandler("skills/list", schemas, ({ cursor }) => {
632
2041
  const listing = page(skills.skills, cursor, "skills");
633
- return { resultType: "complete", ttlMs: 300000, cacheScope: "public", skills: listing.items, ...(listing.nextCursor ? { nextCursor: listing.nextCursor } : {}) };
634
- });
635
- server.setRequestHandler("skills/get", { ...schemas, params: z.object({ uri: z.string() }).passthrough() }, ({ uri }) => {
636
- try { return { resultType: "complete", ttlMs: 300000, cacheScope: "public", skill: skills.get(uri) }; } catch (error) { throw new InvalidParamsError(error.message); }
637
- });
638
- server.setRequestHandler("resources/directory/read", { ...schemas, params: z.object({ uri: z.string(), cursor: z.string().optional() }).passthrough() }, ({ uri, cursor }) => {
639
- const children = skills.directories.get(uri);
640
- if (!children) throw new ResourceNotFoundError(uri, "Unknown skill directory (no trailing slash).");
641
- const listing = page(children, cursor, "directory");
642
- return { resultType: "complete", ttlMs: 300000, cacheScope: "public", resources: listing.items, ...(listing.nextCursor ? { nextCursor: listing.nextCursor } : {}) };
2042
+ return {
2043
+ resultType: "complete",
2044
+ ttlMs: 300000,
2045
+ cacheScope: "public",
2046
+ skills: listing.items,
2047
+ ...(listing.nextCursor
2048
+ ? {
2049
+ nextCursor: listing.nextCursor,
2050
+ }
2051
+ : {}),
2052
+ };
643
2053
  });
2054
+ server.setRequestHandler(
2055
+ "skills/get",
2056
+ {
2057
+ ...schemas,
2058
+ params: z
2059
+ .object({
2060
+ uri: z.string(),
2061
+ })
2062
+ .passthrough(),
2063
+ },
2064
+ ({ uri }) => {
2065
+ try {
2066
+ return {
2067
+ resultType: "complete",
2068
+ ttlMs: 300000,
2069
+ cacheScope: "public",
2070
+ skill: skills.get(uri),
2071
+ };
2072
+ } catch (error) {
2073
+ throw new InvalidParamsError(error.message);
2074
+ }
2075
+ },
2076
+ );
2077
+ server.setRequestHandler(
2078
+ "resources/directory/read",
2079
+ {
2080
+ ...schemas,
2081
+ params: z
2082
+ .object({
2083
+ uri: z.string(),
2084
+ cursor: z.string().optional(),
2085
+ })
2086
+ .passthrough(),
2087
+ },
2088
+ ({ uri, cursor }) => {
2089
+ const children = skills.directories.get(uri);
2090
+ if (!children) throw new ResourceNotFoundError(uri, "Unknown skill directory (no trailing slash).");
2091
+ const listing = page(children, cursor, "directory");
2092
+ return {
2093
+ resultType: "complete",
2094
+ ttlMs: 300000,
2095
+ cacheScope: "public",
2096
+ resources: listing.items,
2097
+ ...(listing.nextCursor
2098
+ ? {
2099
+ nextCursor: listing.nextCursor,
2100
+ }
2101
+ : {}),
2102
+ };
2103
+ },
2104
+ );
644
2105
  }
645
-
646
2106
  function fileFingerprint(files) {
647
- return files.sort().map((file) => {
648
- try { const stat = statSync(file); return `${file}:${stat.mtimeMs}:${stat.size}`; } catch { return `${file}:missing`; }
649
- }).join("\n");
2107
+ return files
2108
+ .sort()
2109
+ .map((file) => {
2110
+ try {
2111
+ const stat = statSync(file);
2112
+ return `${file}:${stat.mtimeMs}:${stat.size}`;
2113
+ } catch {
2114
+ return `${file}:missing`;
2115
+ }
2116
+ })
2117
+ .join("\n");
650
2118
  }
651
2119
  const fingerprint = () => {
652
2120
  const sources = sourceFiles(options.dsRoot);
653
- return `${fileFingerprint([...sources, ...getDocuments().map(doc => doc.file), path.join(root, "ds.config.json"), path.join(root, "package.json"), path.join(root, ".ds/behavior-results.json")])}\n${scenarioGroupFingerprint(options, sources)}`;
2121
+ return `${fileFingerprint([...sources, ...getDocuments().map((doc) => doc.file), path.join(root, "ds.config.json"), path.join(root, "package.json"), path.join(root, ".ds/behavior-results.json")])}\n${scenarioGroupFingerprint(options, sources)}`;
654
2122
  };
655
- const artifactFingerprint = () => fileFingerprint(allApps(true).map(app => path.resolve(root, previewArtifactPath(previewOptions(), app.file))));
656
- const assetFingerprint = () => resourceAssets().map(asset => asset.uri).sort().join("\n");
2123
+ const artifactFingerprint = async () =>
2124
+ fileFingerprint((await scenarioApps(true)).map((app) => path.resolve(root, previewArtifactPath(previewOptions(), app.file))));
2125
+ const assetFingerprint = () =>
2126
+ resourceAssets()
2127
+ .map((asset) => asset.uri)
2128
+ .sort()
2129
+ .join("\n");
657
2130
  const iconFingerprint = () => fileFingerprint(iconInputs(options));
658
2131
  let previousIcons;
659
2132
  let previous, previousArtifacts, previousAssets, previousBuild, previousCaptures, previousCaptureUris, previousDrafts;
660
2133
  let previousDraftBuilds = new Map();
661
- const draftBuilds = () => new Map(drafts.previewStatuses().map(build => [build.resourceUri, JSON.stringify(build)]));
662
- const investigationFingerprint=()=>fileFingerprint([path.join(root,".ds/investigations.json")]);
663
- let previousInvestigations, previousResults, observing=false;
664
- const executionChanged=()=>{
665
- const uri=`${PROJECT_URI}/status`;
666
- if(notifications)notifications.resourceUpdated(uri);
667
- else if(subscribed.has(uri))void server.sendResourceUpdated({uri}).catch(()=>{});
2134
+ const draftBuilds = () => new Map(drafts.previewStatuses().map((build) => [build.resourceUri, JSON.stringify(build)]));
2135
+ const investigationFingerprint = () => fileFingerprint([path.join(root, ".ds/investigations.json")]);
2136
+ let previousInvestigations,
2137
+ previousResults,
2138
+ observing = false;
2139
+ const executionChanged = () => {
2140
+ const uri = `${PROJECT_URI}/status`;
2141
+ if (notifications) notifications.resourceUpdated(uri);
2142
+ else if (subscribed.has(uri))
2143
+ void server
2144
+ .sendResourceUpdated({
2145
+ uri,
2146
+ })
2147
+ .catch(() => {});
668
2148
  };
669
2149
  executionObservers.add(executionChanged);
670
- function initializeObservation() {
2150
+ async function initializeObservation() {
671
2151
  if (observing) return;
672
- previous=fingerprint();previousArtifacts=artifactFingerprint();previousAssets=assetFingerprint();previousIcons=iconFingerprint();previousBuild=JSON.stringify(builds());
673
- previousCaptures=captures.store.fingerprint();previousCaptureUris=captures.store.resourceUris();
674
- previousInvestigations=investigationFingerprint();previousResults=executionResults.fingerprint();observing=true;
675
- previousDrafts=drafts.fingerprint();
676
- previousDraftBuilds=draftBuilds();
2152
+ previous = fingerprint();
2153
+ previousArtifacts = await artifactFingerprint();
2154
+ previousAssets = assetFingerprint();
2155
+ previousIcons = iconFingerprint();
2156
+ previousBuild = JSON.stringify(await builds());
2157
+ previousCaptures = captures.store.fingerprint();
2158
+ previousCaptureUris = captures.store.resourceUris();
2159
+ previousInvestigations = investigationFingerprint();
2160
+ previousResults = executionResults.fingerprint();
2161
+ observing = true;
2162
+ previousDrafts = drafts.fingerprint();
2163
+ previousDraftBuilds = draftBuilds();
677
2164
  }
678
2165
  // Modern HTTP serves a fresh protocol instance per request. Its shared observer
679
2166
  // already tracks changes; immutable byte reads need no source/build scan.
680
- if (observeChanges) initializeObservation();
2167
+ if (observeChanges) await initializeObservation();
681
2168
  let deferredDiscovery = false;
682
- let refreshing, refreshAgain = false, refreshForced = false;
2169
+ let refreshing,
2170
+ refreshAgain = false,
2171
+ refreshForced = false;
683
2172
  function refresh(force = false) {
684
2173
  if (observationClosed) return Promise.resolve(false);
685
2174
  // Stateless HTTP handlers share the persistent observer. Starting their own
686
2175
  // observation after every mutation would force a false source change and
687
2176
  // throw away accepted discovery/capture caches on each draft edit.
688
- if (!observeChanges) return Promise.all([...draftObservers].map(observer => observer(force))).then(values => values.some(Boolean));
689
- refreshAgain = true; refreshForced ||= force;
690
- return refreshing ??= Promise.resolve().then(async () => {
691
- let changed = false;
692
- while (refreshAgain && !observationClosed) {
693
- refreshAgain = false;
694
- const forced = refreshForced; refreshForced = false;
695
- changed = await refreshOnce(forced) || changed;
696
- }
697
- return changed;
698
- }).finally(() => { refreshing = undefined; });
2177
+ if (!observeChanges) return Promise.all([...draftObservers].map((observer) => observer(force))).then((values) => values.some(Boolean));
2178
+ refreshAgain = true;
2179
+ refreshForced ||= force;
2180
+ return (refreshing ??= Promise.resolve()
2181
+ .then(async () => {
2182
+ let changed = false;
2183
+ while (refreshAgain && !observationClosed) {
2184
+ refreshAgain = false;
2185
+ const forced = refreshForced;
2186
+ refreshForced = false;
2187
+ changed = (await refreshOnce(forced)) || changed;
2188
+ }
2189
+ return changed;
2190
+ })
2191
+ .finally(() => {
2192
+ refreshing = undefined;
2193
+ }));
699
2194
  }
700
2195
  async function refreshOnce(force) {
701
- if (!observing) { initializeObservation();force=true; }
2196
+ if (!observing) {
2197
+ await initializeObservation();
2198
+ force = true;
2199
+ }
702
2200
  // Polling covers replaced files and new directories consistently across OSes.
703
2201
  cache.documents = undefined;
704
2202
  const next = fingerprint();
705
- const artifacts = artifactFingerprint();
2203
+ const artifacts = await artifactFingerprint();
706
2204
  const assets = assetFingerprint();
707
- const build = JSON.stringify(builds());
2205
+ const build = JSON.stringify(await builds());
708
2206
  const filesChanged = force || next !== previous;
709
2207
  const buildChanged = build !== previousBuild;
710
2208
  if (buildChanged) onBuildChange?.(JSON.parse(build));
@@ -712,163 +2210,531 @@ export function createAdsMcp(directory, { era = "legacy", skillDirectory, pollIn
712
2210
  const assetsChanged = assets !== previousAssets;
713
2211
  const iconsChanged = iconFingerprint() !== previousIcons;
714
2212
  const capturesChanged = captures.store.fingerprint() !== previousCaptures;
715
- const investigationsChanged=investigationFingerprint()!==previousInvestigations;
716
- const resultsChanged=executionResults.fingerprint()!==previousResults;
717
- const draftFingerprint=drafts.fingerprint(),draftsChanged=draftFingerprint!==previousDrafts;
718
- const currentDraftBuilds=draftBuilds();
719
- const changedDraftBuilds=[...new Set([...previousDraftBuilds.keys(),...currentDraftBuilds.keys()])].filter(uri=>previousDraftBuilds.get(uri)!==currentDraftBuilds.get(uri));
720
- const draftResourcesChanged=[...previousDraftBuilds.keys()].some(uri=>!currentDraftBuilds.has(uri)) || [...currentDraftBuilds.keys()].some(uri=>!previousDraftBuilds.has(uri));
721
- if (!filesChanged && !buildChanged && !artifactsChanged && !assetsChanged && !iconsChanged && !capturesChanged && !investigationsChanged && !resultsChanged && !draftsChanged && !deferredDiscovery) return false;
2213
+ const investigationsChanged = investigationFingerprint() !== previousInvestigations;
2214
+ const resultsChanged = executionResults.fingerprint() !== previousResults;
2215
+ const draftFingerprint = drafts.fingerprint(),
2216
+ draftsChanged = draftFingerprint !== previousDrafts;
2217
+ const currentDraftBuilds = draftBuilds();
2218
+ const changedDraftBuilds = [...new Set([...previousDraftBuilds.keys(), ...currentDraftBuilds.keys()])].filter(
2219
+ (uri) => previousDraftBuilds.get(uri) !== currentDraftBuilds.get(uri),
2220
+ );
2221
+ const draftResourcesChanged =
2222
+ [...previousDraftBuilds.keys()].some((uri) => !currentDraftBuilds.has(uri)) ||
2223
+ [...currentDraftBuilds.keys()].some((uri) => !previousDraftBuilds.has(uri));
2224
+ if (
2225
+ !filesChanged &&
2226
+ !buildChanged &&
2227
+ !artifactsChanged &&
2228
+ !assetsChanged &&
2229
+ !iconsChanged &&
2230
+ !capturesChanged &&
2231
+ !investigationsChanged &&
2232
+ !resultsChanged &&
2233
+ !draftsChanged &&
2234
+ !deferredDiscovery
2235
+ )
2236
+ return false;
722
2237
  if (filesChanged) {
723
2238
  const updated = loadConfig(root);
724
2239
  await previewWatch?.reconfigure?.(updated.config.mcp);
725
2240
  if (observationClosed) return false;
726
- const appsChanged = JSON.stringify(updated.config.mcp.apps) !== JSON.stringify(options.config.mcp.apps) || updated.config.mcp.previewManifest !== options.config.mcp.previewManifest;
727
2241
  options = updated;
728
2242
  cache.signature = `${root}:${JSON.stringify(options.config)}`;
729
2243
  cache.catalog = undefined;
730
2244
  cache.behaviorLibraries = undefined;
731
2245
  cache.registry = undefined;
732
2246
  previous = fingerprint();
733
- if (appsChanged) { if (notifications) notifications.toolsChanged(); else await server.sendToolListChanged(); }
734
2247
  }
735
- const checking = options.config.mcp.previewManifest && previewWatch?.status().state === "running"
736
- && builds().previews.some(entry => ["idle", "building"].includes(entry.state)
737
- || entry.diagnostics.some(item => item.code === "ADS_PREVIEW_STALE_SOURCE"));
2248
+ // Hold changed discovery only while the compiler is building, so clients do not refetch
2249
+ // mid-check. Previews nobody has requested, or stale ones not being rebuilt, are not a
2250
+ // build in progress: nothing would ever release the hold.
2251
+ const report = await builds();
2252
+ const checking =
2253
+ previewWatch?.status().state === "running" &&
2254
+ ((report.progress && report.progress.phase !== "idle") || report.previews.some((entry) => entry.state === "building"));
738
2255
  deferredDiscovery ||= filesChanged;
739
2256
  const discoveryChanged = deferredDiscovery && !checking;
740
- if (discoveryChanged) { await getRegistryAsync(); if(observationClosed)return false; deferredDiscovery = false; }
741
- if (discoveryChanged || assetsChanged || draftResourcesChanged) { if (notifications) notifications.resourcesChanged(); else await server.sendResourceListChanged(); }
742
- previousArtifacts = artifactFingerprint();
2257
+ if (discoveryChanged) {
2258
+ await getRegistryAsync();
2259
+ if (observationClosed) return false;
2260
+ deferredDiscovery = false;
2261
+ }
2262
+ if (discoveryChanged || assetsChanged || draftResourcesChanged) {
2263
+ if (notifications) notifications.resourcesChanged();
2264
+ else await server.sendResourceListChanged();
2265
+ }
2266
+ previousArtifacts = await artifactFingerprint();
743
2267
  previousAssets = assetFingerprint();
744
2268
  previousIcons = iconFingerprint();
745
- previousBuild = JSON.stringify(builds());
746
- const targets = discoveryChanged ? (era === "modern" ? resources().map((entry) => entry.uri).filter((uri) => !skills.files.has(uri)) : [...subscribed]).filter(uri => !uri.startsWith("ads://drafts/"))
747
- : [BUILD_URI, BEHAVIOR_URI, INVESTIGATIONS_URI, DRAFTS_URI, `${PROJECT_URI}/status`, ...(filesChanged ? [`${PROJECT_URI}/tokens`] : []), ...(filesChanged || iconsChanged ? [ICONS_URI] : []), ...(options.config.mcp.previewManifest ? [PREVIEW_MANIFEST_URI, LIVE_PREVIEW_MANIFEST_URI] : []), ...(artifactsChanged ? allApps(true).map(app => appUri(app.id)) : [])].filter((uri) => era === "modern" || subscribed.has(uri));
748
- if((discoveryChanged||draftsChanged)&&(era==="modern"||subscribed.has(`${PROJECT_URI}/explorer`)))targets.push(`${PROJECT_URI}/explorer`);
749
- if(draftsChanged){
750
- targets.push(...[...new Set([...previousDraftBuilds.keys(),...currentDraftBuilds.keys()])].map(uri=>uri.replace(encodeURIComponent(BUILD_URI),encodeURIComponent(`${PROJECT_URI}/scenarios`))).filter(uri=>era==="modern"||subscribed.has(uri)));
751
- targets.push(...[DRAFTS_URI,`${PROJECT_URI}/catalog`,`${PROJECT_URI}/scenarios`,`${PROJECT_URI}/status`].filter(uri=>era==="modern"||subscribed.has(uri)));previousDrafts=draftFingerprint;}
752
- targets.push(...changedDraftBuilds.filter(uri=>era==="modern"||subscribed.has(uri)));
753
- previousDraftBuilds=currentDraftBuilds;
754
- if(resultsChanged){targets.push(...[RESULTS_URI,...executionResults.index().results.map(entry=>entry.resourceUri),...[...subscribed].filter(uri=>uri.startsWith("ads://results/"))].filter(uri=>era==="modern"||subscribed.has(uri)));previousResults=executionResults.fingerprint();}
755
- if(investigationsChanged){targets.push(...[INVESTIGATIONS_URI,...investigationIndex(root).entries.map(entry=>entry.resourceUri),...[...subscribed].filter(uri=>uri.startsWith("ads://investigations/"))].filter(uri=>era==="modern"||subscribed.has(uri)));previousInvestigations=investigationFingerprint();}
2269
+ previousBuild = JSON.stringify(await builds());
2270
+ const targets = discoveryChanged
2271
+ ? (era === "modern" ? (await resources()).map((entry) => entry.uri).filter((uri) => !skills.files.has(uri)) : [...subscribed]).filter(
2272
+ (uri) => !uri.startsWith("ads://drafts/"),
2273
+ )
2274
+ : [
2275
+ BUILD_URI,
2276
+ BEHAVIOR_URI,
2277
+ INVESTIGATIONS_URI,
2278
+ DRAFTS_URI,
2279
+ `${PROJECT_URI}/status`,
2280
+ ...(filesChanged ? [`${PROJECT_URI}/tokens`, `${PROJECT_URI}/tokens/dtcg`] : []),
2281
+ ...(filesChanged || iconsChanged ? [ICONS_URI] : []),
2282
+ PREVIEW_MANIFEST_URI,
2283
+ LIVE_PREVIEW_MANIFEST_URI,
2284
+ ...(artifactsChanged ? (await scenarioApps(true)).map((app) => appUri(app.id)) : []),
2285
+ ].filter((uri) => era === "modern" || subscribed.has(uri));
2286
+ if ((discoveryChanged || draftsChanged) && (era === "modern" || subscribed.has(`${PROJECT_URI}/explorer`))) targets.push(`${PROJECT_URI}/explorer`);
2287
+ if (draftsChanged) {
2288
+ targets.push(
2289
+ ...[...new Set([...previousDraftBuilds.keys(), ...currentDraftBuilds.keys()])]
2290
+ .map((uri) => uri.replace(encodeURIComponent(BUILD_URI), encodeURIComponent(`${PROJECT_URI}/scenarios`)))
2291
+ .filter((uri) => era === "modern" || subscribed.has(uri)),
2292
+ );
2293
+ targets.push(
2294
+ ...[DRAFTS_URI, `${PROJECT_URI}/catalog`, `${PROJECT_URI}/scenarios`, `${PROJECT_URI}/status`].filter((uri) => era === "modern" || subscribed.has(uri)),
2295
+ );
2296
+ previousDrafts = draftFingerprint;
2297
+ }
2298
+ targets.push(...changedDraftBuilds.filter((uri) => era === "modern" || subscribed.has(uri)));
2299
+ previousDraftBuilds = currentDraftBuilds;
2300
+ if (resultsChanged) {
2301
+ targets.push(
2302
+ ...[
2303
+ RESULTS_URI,
2304
+ ...executionResults.index().results.map((entry) => entry.resourceUri),
2305
+ ...[...subscribed].filter((uri) => uri.startsWith("ads://results/")),
2306
+ ].filter((uri) => era === "modern" || subscribed.has(uri)),
2307
+ );
2308
+ previousResults = executionResults.fingerprint();
2309
+ }
2310
+ if (investigationsChanged) {
2311
+ targets.push(
2312
+ ...[
2313
+ INVESTIGATIONS_URI,
2314
+ ...investigationIndex(root).entries.map((entry) => entry.resourceUri),
2315
+ ...[...subscribed].filter((uri) => uri.startsWith("ads://investigations/")),
2316
+ ].filter((uri) => era === "modern" || subscribed.has(uri)),
2317
+ );
2318
+ previousInvestigations = investigationFingerprint();
2319
+ }
756
2320
  if (capturesChanged || discoveryChanged) {
757
- const current = (captures.store.fingerprint() ? captureIndex().captures : []).flatMap(record => [record.current?.resourceUri, record.candidate?.resourceUri].filter(Boolean));
758
- targets.push(...[CAPTURES_URI, ...previousCaptureUris, ...current].filter(uri => era === "modern" || subscribed.has(uri)));
2321
+ const current = (captures.store.fingerprint() ? (await captureIndex()).captures : []).flatMap((record) =>
2322
+ [record.current?.resourceUri, record.candidate?.resourceUri].filter(Boolean),
2323
+ );
2324
+ targets.push(...[CAPTURES_URI, ...previousCaptureUris, ...current].filter((uri) => era === "modern" || subscribed.has(uri)));
759
2325
  previousCaptureUris = current;
760
2326
  previousCaptures = captures.store.fingerprint();
761
2327
  }
762
2328
  for (const uri of new Set(targets)) {
763
2329
  if (observationClosed) return false;
764
- if (notifications) notifications.resourceUpdated(uri); else await server.sendResourceUpdated({ uri });
2330
+ if (notifications) notifications.resourceUpdated(uri);
2331
+ else
2332
+ await server.sendResourceUpdated({
2333
+ uri,
2334
+ });
765
2335
  }
766
2336
  return true;
767
2337
  }
768
- const timer = pollInterval > 0 ? setInterval(() => { if (!observationClosed) refresh().catch(error => { if (!observationClosed) process.stderr.write(`ads mcp: ${error.message}\n`); }); }, pollInterval) : null;
2338
+ const timer =
2339
+ pollInterval > 0
2340
+ ? setInterval(() => {
2341
+ if (!observationClosed)
2342
+ refresh().catch((error) => {
2343
+ if (!observationClosed) process.stderr.write(`ads mcp: ${error.message}\n`);
2344
+ });
2345
+ }, pollInterval)
2346
+ : null;
769
2347
  timer?.unref();
770
2348
  if (observeChanges) draftObservers.add(refresh);
771
- const stopObservation = () => { executionObservers.delete(executionChanged);observationClosed = true; draftObservers.delete(refresh); if (timer) clearInterval(timer); };
2349
+ const stopObservation = () => {
2350
+ executionObservers.delete(executionChanged);
2351
+ observationClosed = true;
2352
+ draftObservers.delete(refresh);
2353
+ if (timer) clearInterval(timer);
2354
+ };
772
2355
  server.oninitialized = () => previewWatch?.start();
773
- server.onclose = () => {stopObservation();if(!inspection)void coordinator.close().catch(()=>{});};
2356
+ server.onclose = async () => {
2357
+ stopObservation();
2358
+ if (!inspection) void coordinator.close().catch(() => {});
2359
+ };
774
2360
  async function warmScenarios(ids, signal) {
775
2361
  if (!previewWatch) return;
776
- const apps = allApps(), selected = new Set(ids);
777
- const selectedApps = apps.filter(app => selected.has(app.id));
2362
+ await getRegistryAsync();
2363
+ const apps = await scenarioApps(),
2364
+ selected = new Set(ids);
2365
+ const selectedApps = apps.filter((app) => selected.has(app.id));
778
2366
  if (selectedApps.length !== selected.size) throw new Error("Cannot warm an unknown verification scenario.");
779
2367
  previewWatch.setApps(apps);
780
- const ready = new Set(previewWatch.buildStatus().previews.filter(entry=>entry.current).map(entry=>entry.id));
781
- const files = selectedApps.filter(app=>!ready.has(app.id)).map(app => path.resolve(root, app.file));
2368
+ const ready = new Set((await previewWatch.buildStatus()).previews.filter((entry) => entry.current).map((entry) => entry.id));
2369
+ const files = selectedApps.filter((app) => !ready.has(app.id)).map((app) => path.resolve(root, app.file));
782
2370
  if (!files.length) return;
783
2371
  await previewWatch.warm(files);
784
2372
  for (const file of files) await previewWatch.ensure(file, signal);
785
2373
  }
786
- return { server, refresh, warmScenarios, buildAll(signal, options) { previewWatch.setApps(allApps()); return previewWatch.buildAll(signal, options); }, readResource:read, async callTool(name,args,signal){const tool=tools().find(tool=>tool.name===name);if(!tool)throw new Error("Unknown preview tool.");return tool.call(tool.schema.parse(args),signal);}, async close() { executionObservers.delete(executionChanged);stopObservation(); if (!inspection) { await coordinator.close(); await cache.registryInspector?.close(); await drafts.close(); await validation.close(); await verification.close(); await captures.close(); } await server.close(); } };
2374
+ return {
2375
+ server,
2376
+ refresh,
2377
+ warmScenarios,
2378
+ async buildAll(signal, options) {
2379
+ await getRegistryAsync();
2380
+ previewWatch.setApps(await scenarioApps());
2381
+ return previewWatch.buildAll(signal, options);
2382
+ },
2383
+ readResource: read,
2384
+ async callTool(name, args, signal) {
2385
+ const tool = tools().find((tool) => tool.name === name);
2386
+ if (!tool) throw new Error("Unknown preview tool.");
2387
+ return tool.call(tool.schema.parse(args), signal);
2388
+ },
2389
+ async close() {
2390
+ executionObservers.delete(executionChanged);
2391
+ stopObservation();
2392
+ if (!inspection) {
2393
+ await coordinator.close();
2394
+ await cache.registryInspector?.close();
2395
+ await drafts.close();
2396
+ await validation.close();
2397
+ await captures.close();
2398
+ }
2399
+ await server.close();
2400
+ },
2401
+ };
787
2402
  }
788
2403
 
789
- export async function startAdsMcp(directory = process.cwd(), { stdio = true, despitePolicy = false, showcase = true, port = 0, mutations = false, previewWork = createPreviewWork(), previewBuildTimeoutMs = 30000, prewarm = stdio } = {}) {
790
- if (process.versions.bun) assertBunRuntime();
2404
+ /** A draft workspace's preview, served by the project's runtime and compiled by its compiler. */
2405
+ export function createDraftPreview(workspace, { id, host, showcaseUrl, mountPreview, previewWork }) {
2406
+ const { root, config } = loadConfig(workspace);
2407
+ const previewWatch = createReconfigurablePreviewWatch(root, config.mcp, {
2408
+ delegate: host,
2409
+ prewarm: false,
2410
+ });
2411
+ const inspection = {
2412
+ skills: createSkillStore(),
2413
+ previewWork,
2414
+ };
2415
+ const listeners = new Set();
2416
+ let timer, api;
2417
+ const preview = async () =>
2418
+ (api ??= await createAdsMcp(root, {
2419
+ era: "modern",
2420
+ inspection,
2421
+ previewWatch,
2422
+ showcaseUrl: () => url,
2423
+ mutations: false,
2424
+ pollInterval: 0,
2425
+ observeChanges: false,
2426
+ }));
2427
+ let watcher;
2428
+ try {
2429
+ mkdirSync(path.join(root, ".ds"), {
2430
+ recursive: true,
2431
+ });
2432
+ watcher = watch(path.join(root, ".ds"), (_event, file) => {
2433
+ const selected = previewWatch.resourceSession();
2434
+ if (String(file) !== (selected ? `build-status-${selected}.json` : "build-status.json")) return;
2435
+ clearTimeout(timer);
2436
+ timer = setTimeout(async () => {
2437
+ try {
2438
+ const report = await previewWatch.buildStatus();
2439
+ for (const listener of listeners) listener(report);
2440
+ } catch {
2441
+ /* Retried on the next report. */
2442
+ }
2443
+ }, 16);
2444
+ timer.unref();
2445
+ });
2446
+ watcher.unref();
2447
+ watcher.on("error", () => watcher.close());
2448
+ } catch {
2449
+ /* Build changes still arrive through explicit status reads. */
2450
+ }
2451
+ // The draft's own showcase, mounted on the project's host: the real standalone scenario page that
2452
+ // audits, captures and behavior checks open.
2453
+ const base = showcaseUrl?.(),
2454
+ prefix = `/draft/${id}/`;
2455
+ const url = base ? new URL(prefix, base).href : undefined;
2456
+ const ownUrl = () => url;
2457
+ // A 2025-era HTTP session observes the draft like a stdio connection; per-request modern instances do not.
2458
+ const unmount = mountPreview?.(
2459
+ prefix,
2460
+ async ({ era, session }) =>
2461
+ (
2462
+ await createAdsMcp(root, {
2463
+ era,
2464
+ inspection,
2465
+ previewWatch,
2466
+ showcaseUrl: ownUrl,
2467
+ mutations: false,
2468
+ ...(session
2469
+ ? {}
2470
+ : {
2471
+ pollInterval: 0,
2472
+ observeChanges: false,
2473
+ }),
2474
+ })
2475
+ ).server,
2476
+ );
2477
+ return {
2478
+ url,
2479
+ prewarm: async () => previewWatch.initialize(),
2480
+ buildStatus: async () => previewWatch.buildStatus(),
2481
+ warmScenarios: async (ids, signal) => (await preview()).warmScenarios(ids, signal),
2482
+ buildAll: async (signal, options) => {
2483
+ await previewWatch.initialize();
2484
+ return (await preview()).buildAll(signal, options);
2485
+ },
2486
+ onBuildChange(listener) {
2487
+ listeners.add(listener);
2488
+ return () => listeners.delete(listener);
2489
+ },
2490
+ primeRegistry(registry) {
2491
+ if (inspection.registry === registry || inspection.lastRegistry === registry) return;
2492
+ inspection.registry = inspection.lastRegistry = registry;
2493
+ inspection.registryRevision = undefined;
2494
+ inspection.catalog = undefined;
2495
+ },
2496
+ callTool: async (name, args, signal) => (await preview()).callTool(name, args, signal),
2497
+ readResource: async (uri, signal) => (await preview()).readResource(uri, signal),
2498
+ // The draft's verified preview revision, as the project host reports its own: captures and
2499
+ // behavior evidence record which build they observed.
2500
+ previewRevision: () => readPreviewManifest(withPreviewSession(loadConfig(root), previewWatch.resourceSession()))?.revision ?? null,
2501
+ async close() {
2502
+ clearTimeout(timer);
2503
+ watcher?.close();
2504
+ listeners.clear();
2505
+ await Promise.allSettled([Promise.resolve().then(async () => unmount?.()), previewWatch.stop(), api?.close()]);
2506
+ },
2507
+ };
2508
+ }
2509
+
2510
+ /** `compiler` replaces ADS's preview compiler process for ADS's own tests; projects never set it. */
2511
+ export async function startAdsMcp(
2512
+ directory = process.cwd(),
2513
+ {
2514
+ stdio = true,
2515
+ despitePolicy = false,
2516
+ showcase = true,
2517
+ port = 0,
2518
+ mutations = false,
2519
+ previewWork = createPreviewWork(),
2520
+ previewBuildTimeoutMs,
2521
+ prewarm = stdio,
2522
+ compiler,
2523
+ } = {},
2524
+ ) {
2525
+ assertBunRuntime();
791
2526
  // Fail before opening the transport for configuration/distribution errors.
792
2527
  const { root, config } = loadConfig(directory);
2528
+ // The server and its preview compiler run this project's ads check in a warm worker (check-service.mjs).
2529
+ useWarmChecks(root);
793
2530
  // The generated theme sheet follows the token sheets and ds.config.json from startup on.
794
- const themesWatch = watchThemesCss(root, { log: message => process.stderr.write(`${message}\n`) });
795
- const inspection = { skills: createSkillStore(), previewWork };
796
- const previewWatch = createReconfigurablePreviewWatch(root, config.mcp, {buildTimeout:previewBuildTimeoutMs,prewarm,despitePolicy});
2531
+ const themesWatch = watchThemesCss(root, {
2532
+ log: (message) => process.stderr.write(`${message}\n`),
2533
+ });
2534
+ await themesWatch.ready;
2535
+ const inspection = {
2536
+ skills: createSkillStore(),
2537
+ previewWork,
2538
+ };
2539
+ const previewWatch = createReconfigurablePreviewWatch(root, config.mcp, {
2540
+ ...(previewBuildTimeoutMs === undefined
2541
+ ? {}
2542
+ : {
2543
+ buildTimeout: previewBuildTimeoutMs,
2544
+ }),
2545
+ prewarm,
2546
+ despitePolicy,
2547
+ compiler,
2548
+ });
797
2549
  let host, api;
798
2550
  let buildWatcher, buildChangeTimer;
799
2551
  const buildListeners = new Set();
800
- const onBuildChange = report => { for (const listener of buildListeners) listener(report); };
2552
+ const onBuildChange = (report) => {
2553
+ for (const listener of buildListeners) listener(report);
2554
+ };
801
2555
  const showcaseUrl = () => host?.url;
2556
+ const mountPreview = (prefix, factory) => host?.mount(prefix, factory);
802
2557
  if (showcase) {
803
- host = await startShowcaseHost(({ era }) => createAdsMcp(directory, { era, previewWatch, showcaseUrl, inspection, mutations, pollInterval: 0, observeChanges:false }).server,
804
- { port, observe: notifications => createAdsMcp(directory, { era: "modern", previewWatch, showcaseUrl, inspection, mutations, notifications, onBuildChange }) });
2558
+ // A 2025-era HTTP session observes the project like a stdio connection; per-request modern instances do not.
2559
+ host = await startShowcaseHost(
2560
+ async ({ era, session }) =>
2561
+ (
2562
+ await createAdsMcp(directory, {
2563
+ era,
2564
+ previewWatch,
2565
+ showcaseUrl,
2566
+ mountPreview,
2567
+ inspection,
2568
+ mutations,
2569
+ ...(session
2570
+ ? {
2571
+ onBuildChange,
2572
+ }
2573
+ : {
2574
+ pollInterval: 0,
2575
+ observeChanges: false,
2576
+ }),
2577
+ })
2578
+ ).server,
2579
+ {
2580
+ port,
2581
+ observe: async (notifications) =>
2582
+ createAdsMcp(directory, {
2583
+ era: "modern",
2584
+ previewWatch,
2585
+ showcaseUrl,
2586
+ mountPreview,
2587
+ inspection,
2588
+ mutations,
2589
+ notifications,
2590
+ onBuildChange,
2591
+ }),
2592
+ },
2593
+ );
805
2594
  process.stderr.write(`ADS showcase: ${host.url}\n`);
806
2595
  }
807
2596
  const transport = stdio ? new StdioServerTransport() : null;
808
- const handle = stdio ? serveStdio(({ era }) => createAdsMcp(directory, { era, previewWatch, showcaseUrl, inspection, mutations, onBuildChange }).server, { transport, legacy: "serve", onerror: (error) => process.stderr.write(`ads mcp: ${error.message}\n`) }) : null;
2597
+ const handle = stdio
2598
+ ? serveStdio(
2599
+ async ({ era }) =>
2600
+ (
2601
+ await createAdsMcp(directory, {
2602
+ era,
2603
+ previewWatch,
2604
+ showcaseUrl,
2605
+ mountPreview,
2606
+ inspection,
2607
+ mutations,
2608
+ onBuildChange,
2609
+ })
2610
+ ).server,
2611
+ {
2612
+ transport,
2613
+ legacy: "serve",
2614
+ onerror: (error) => process.stderr.write(`ads mcp: ${error.message}\n`),
2615
+ },
2616
+ )
2617
+ : null;
809
2618
  try {
810
2619
  buildWatcher = watch(path.join(root, ".ds"), (_event, file) => {
811
2620
  const selected = previewWatch.resourceSession();
812
2621
  if (String(file) !== (selected ? `build-status-${selected}.json` : "build-status.json")) return;
813
2622
  clearTimeout(buildChangeTimer);
814
- buildChangeTimer = setTimeout(() => {
815
- try { onBuildChange(previewWatch.buildStatus()); } catch { /* The polling observer retries transient writes. */ }
2623
+ buildChangeTimer = setTimeout(async () => {
2624
+ try {
2625
+ onBuildChange(await previewWatch.buildStatus());
2626
+ } catch {
2627
+ /* The polling observer retries transient writes. */
2628
+ }
816
2629
  for (const refresh of inspection.draftObservers ?? []) void refresh().catch(() => {});
817
- }, 16); buildChangeTimer.unref();
2630
+ }, 16);
2631
+ buildChangeTimer.unref();
2632
+ });
2633
+ buildWatcher.unref();
2634
+ buildWatcher.on("error", () => {
2635
+ buildWatcher.close();
818
2636
  });
819
- buildWatcher.unref(); buildWatcher.on("error", () => { buildWatcher.close(); });
820
- } catch { /* Periodic observation also covers replaced/missing report directories. */ }
2637
+ } catch {
2638
+ /* Periodic observation also covers replaced/missing report directories. */
2639
+ }
821
2640
  // Modern stdio negotiation can spawn a disposable probe process. Its
822
2641
  // metadata requests must not start a compiler; oninitialized starts the real
823
2642
  // connection's shared compiler. HTTP-only hosts can warm immediately.
824
- const warmStart=prewarm&&!stdio?setTimeout(()=>previewWatch.start(),0):undefined;
2643
+ const warmStart = prewarm && !stdio ? setTimeout(() => previewWatch.start(), 0) : undefined;
825
2644
  warmStart?.unref();
826
2645
  let closing;
827
- function close() {
828
- return closing ??= (async () => {
2646
+ async function close() {
2647
+ return (closing ??= await (async () => {
829
2648
  clearTimeout(warmStart);
830
- themesWatch.close();
2649
+ await themesWatch.close();
831
2650
  buildListeners.clear();
832
- clearTimeout(buildChangeTimer); buildWatcher?.close();
2651
+ clearTimeout(buildChangeTimer);
2652
+ buildWatcher?.close();
833
2653
  inspection.edits?.cancel();
834
- const executionClosing=inspection.coordinator?.close();
2654
+ const executionClosing = await inspection.coordinator?.close();
835
2655
  // Stop every owned resource even if another close fails or has in-flight RPCs.
836
2656
  const results = await Promise.allSettled([
837
2657
  executionClosing,
838
- Promise.resolve().then(() => host?.close()),
2658
+ Promise.resolve().then(async () => host?.close()),
839
2659
  previewWatch.stop(),
840
- Promise.resolve().then(() => inspection.validation?.close()),
841
- Promise.resolve().then(() => inspection.verification?.close()),
842
- Promise.resolve().then(() => inspection.captures?.close()),
843
- Promise.resolve().then(() => inspection.drafts?.close()),
844
- Promise.resolve().then(() => inspection.registryInspector?.close()),
845
- Promise.resolve().then(() => api?.close()),
2660
+ Promise.resolve().then(async () => inspection.validation?.close()),
2661
+ Promise.resolve().then(async () => inspection.captures?.close()),
2662
+ Promise.resolve().then(async () => inspection.drafts?.close()),
2663
+ Promise.resolve().then(async () => inspection.registryInspector?.close()),
2664
+ Promise.resolve().then(async () => api?.close()),
846
2665
  Promise.resolve().then(() => handle?.close()),
2666
+ Promise.resolve().then(async () => releaseWarmChecks(root)),
847
2667
  ]);
848
2668
  for (const event of ["end", "close", "error"]) process.stdin.removeListener(event, disconnect);
849
2669
  for (const signal of ["SIGINT", "SIGTERM"]) process.removeListener(signal, disconnect);
850
2670
  process.removeListener("exit", forceCleanup);
851
- const errors = results.filter(result => result.status === "rejected").map(result => result.reason);
2671
+ const errors = results.filter((result) => result.status === "rejected").map((result) => result.reason);
852
2672
  releaseScenarioRegistry(root);
853
2673
  if (errors.length) throw new AggregateError(errors, "ADS shutdown failed");
854
- })();
2674
+ })());
2675
+ }
2676
+ async function disconnect() {
2677
+ void close().catch((error) => {
2678
+ process.stderr.write(`ads mcp: ${error.message}\n`);
2679
+ process.exitCode = 1;
2680
+ });
2681
+ }
2682
+ function forceCleanup() {
2683
+ previewWatch.kill();
855
2684
  }
856
- function disconnect() { void close().catch(error => { process.stderr.write(`ads mcp: ${error.message}\n`); process.exitCode = 1; }); }
857
- function forceCleanup() { previewWatch.kill(); }
858
2685
  // Probe instances have no managed child; a real connection activates it.
859
2686
  // The SDK also closes its wire on stdout failure. Closing a probe instance
860
2687
  // must not shut the runtime down, so observe the wire, not server.onclose.
861
2688
  if (transport) {
862
2689
  const wireClosed = transport.onclose;
863
- transport.onclose = () => { try { wireClosed?.(); } finally { disconnect(); } };
2690
+ transport.onclose = async () => {
2691
+ try {
2692
+ wireClosed?.();
2693
+ } finally {
2694
+ await disconnect();
2695
+ }
2696
+ };
864
2697
  for (const event of ["end", "close", "error"]) process.stdin.once(event, disconnect);
865
- if (process.stdin.readableEnded || process.stdin.destroyed) disconnect();
2698
+ if (process.stdin.readableEnded || process.stdin.destroyed) await disconnect();
866
2699
  }
867
2700
  for (const signal of ["SIGINT", "SIGTERM"]) process.once(signal, disconnect);
868
2701
  process.once("exit", forceCleanup);
869
- const previewApi=()=>api??=createAdsMcp(root,{era:"modern",inspection,previewWatch,showcaseUrl,mutations:false,pollInterval:0,observeChanges:false});
870
- return { close, url: host?.url, async buildAll(signal, options) { await previewWatch.initialize(); return previewApi().buildAll(signal, options); }, parkCompiler: () => previewWatch.suspend({immutable:true}), warmScenarios: (ids, signal) => previewApi().warmScenarios(ids, signal), prewarm: () => previewWatch.initialize(), onBuildChange(listener) { buildListeners.add(listener); return () => buildListeners.delete(listener); }, buildStatus: () => previewWatch.buildStatus(), primeRegistry(registry) {
871
- if (inspection.registry === registry || inspection.lastRegistry === registry) return;
872
- inspection.registry = inspection.lastRegistry = registry; inspection.registryRevision = undefined; inspection.catalog = undefined;
873
- }, callTool:(name,args,signal)=>previewApi().callTool(name,args,signal),readResource:(uri,signal)=>previewApi().readResource(uri,signal),previewRevision: () => readPreviewManifest(withPreviewSession(loadConfig(root), previewWatch.resourceSession()))?.revision ?? null };
2702
+ const previewApi = async () =>
2703
+ (api ??= await createAdsMcp(root, {
2704
+ era: "modern",
2705
+ inspection,
2706
+ previewWatch,
2707
+ showcaseUrl,
2708
+ mutations: false,
2709
+ pollInterval: 0,
2710
+ observeChanges: false,
2711
+ }));
2712
+ return {
2713
+ close,
2714
+ url: host?.url,
2715
+ async buildAll(signal, options) {
2716
+ await previewWatch.initialize();
2717
+ return (await previewApi()).buildAll(signal, options);
2718
+ },
2719
+ parkCompiler: async () =>
2720
+ previewWatch.suspend({
2721
+ immutable: true,
2722
+ }),
2723
+ warmScenarios: async (ids, signal) => (await previewApi()).warmScenarios(ids, signal),
2724
+ prewarm: async () => previewWatch.initialize(),
2725
+ onBuildChange(listener) {
2726
+ buildListeners.add(listener);
2727
+ return () => buildListeners.delete(listener);
2728
+ },
2729
+ buildStatus: async () => previewWatch.buildStatus(),
2730
+ primeRegistry(registry) {
2731
+ if (inspection.registry === registry || inspection.lastRegistry === registry) return;
2732
+ inspection.registry = inspection.lastRegistry = registry;
2733
+ inspection.registryRevision = undefined;
2734
+ inspection.catalog = undefined;
2735
+ },
2736
+ callTool: async (name, args, signal) => (await previewApi()).callTool(name, args, signal),
2737
+ readResource: async (uri, signal) => (await previewApi()).readResource(uri, signal),
2738
+ previewRevision: () => readPreviewManifest(withPreviewSession(loadConfig(root), previewWatch.resourceSession()))?.revision ?? null,
2739
+ };
874
2740
  }