@reqvire-org/ads 0.4.0 → 0.4.3

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