@reqvire-org/ads 0.3.36 → 0.3.38

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 (86) hide show
  1. package/README.md +12 -8
  2. package/dist/bootstrap-ds/README.md +8 -9
  3. package/dist/bootstrap-ds/ds.config.json +1 -8
  4. package/dist/bootstrap-ds/package.json +4 -3
  5. package/dist/bootstrap-ds/scripts/build-mcp-previews.mjs +2 -32
  6. package/dist/bun-compiler.mjs +13 -0
  7. package/dist/bun-worker.mjs +9 -0
  8. package/dist/check.mjs +7 -4
  9. package/dist/cli.mjs +20 -8
  10. package/dist/config.mjs +24 -4
  11. package/dist/development-runtime.mjs +3 -1
  12. package/dist/init.mjs +16 -18
  13. package/dist/mcp/build-status.mjs +6 -4
  14. package/dist/mcp/context.mjs +9 -4
  15. package/dist/mcp/drafts.mjs +4 -2
  16. package/dist/mcp/mutations.mjs +4 -14
  17. package/dist/mcp/preview-owner-guard.mjs +7 -4
  18. package/dist/mcp/preview-watch.mjs +21 -9
  19. package/dist/mcp/preview-widget.bundle.js +57 -63
  20. package/dist/mcp/preview-work.mjs +1 -15
  21. package/dist/mcp/project-widget.bundle.js +55 -61
  22. package/dist/mcp/prompts.mjs +2 -2
  23. package/dist/mcp/resource-loader.js +32 -10
  24. package/dist/mcp/server.mjs +94 -34
  25. package/dist/mcp/widget.bundle.js +58 -64
  26. package/dist/preview-builder.mjs +17 -5
  27. package/dist/preview-bun.mjs +269 -0
  28. package/dist/preview-imports.mjs +73 -0
  29. package/dist/preview-resources.mjs +26 -14
  30. package/dist/resource-limits.mjs +146 -0
  31. package/dist/runtime-requirements.mjs +21 -0
  32. package/dist/scenario-inspector.mjs +11 -4
  33. package/dist/scenarios-compiler.mjs +51 -9
  34. package/dist/showcase/client.bundle.js +66 -71
  35. package/dist/showcase/index.html +2 -2
  36. package/dist/showcase/sandbox.bundle.js +1 -1
  37. package/dist/showcase/style.css +4 -0
  38. package/dist/skills/ads-break-ui/SKILL.md +42 -42
  39. package/dist/skills/ads-break-ui/references/drafts.md +6 -3
  40. package/dist/skills/ads-break-ui/references/guarded-editing.md +4 -3
  41. package/dist/skills/ads-break-ui/references/runtimes.md +175 -140
  42. package/dist/skills/ads-break-ui/references/validation.md +13 -3
  43. package/dist/skills/ads-break-ui/references/workflows.md +82 -0
  44. package/dist/skills/ads-designer/SKILL.md +41 -41
  45. package/dist/skills/ads-designer/assets/bootstrap-ds/README.md +8 -9
  46. package/dist/skills/ads-designer/assets/bootstrap-ds/ds.config.json +1 -8
  47. package/dist/skills/ads-designer/assets/bootstrap-ds/package.json +4 -3
  48. package/dist/skills/ads-designer/assets/bootstrap-ds/scripts/build-mcp-previews.mjs +2 -32
  49. package/dist/skills/ads-designer/references/cli.md +25 -21
  50. package/dist/skills/ads-designer/references/drafts.md +6 -3
  51. package/dist/skills/ads-designer/references/guarded-editing.md +4 -3
  52. package/dist/skills/ads-designer/references/runtimes.md +175 -140
  53. package/dist/skills/ads-designer/references/validation.md +13 -3
  54. package/dist/skills/ads-designer/references/workflows.md +82 -0
  55. package/dist/skills/ads-import/SKILL.md +43 -44
  56. package/dist/skills/ads-import/references/cli.md +25 -21
  57. package/dist/skills/ads-import/references/drafts.md +6 -3
  58. package/dist/skills/ads-import/references/guarded-editing.md +4 -3
  59. package/dist/skills/ads-import/references/runtimes.md +175 -140
  60. package/dist/skills/ads-import/references/validation.md +13 -3
  61. package/dist/skills/ads-import/references/workflows.md +82 -0
  62. package/dist/skills/ads-motion/SKILL.md +40 -40
  63. package/dist/skills/ads-motion/references/drafts.md +6 -3
  64. package/dist/skills/ads-motion/references/guarded-editing.md +4 -3
  65. package/dist/skills/ads-motion/references/runtimes.md +175 -140
  66. package/dist/skills/ads-motion/references/validation.md +13 -3
  67. package/dist/skills/ads-motion/references/workflows.md +82 -0
  68. package/dist/skills/ads-port/SKILL.md +40 -40
  69. package/dist/skills/ads-port/references/cli.md +25 -21
  70. package/dist/skills/ads-port/references/drafts.md +6 -3
  71. package/dist/skills/ads-port/references/guarded-editing.md +4 -3
  72. package/dist/skills/ads-port/references/runtimes.md +175 -140
  73. package/dist/skills/ads-port/references/validation.md +13 -3
  74. package/dist/skills/ads-port/references/workflows.md +82 -0
  75. package/dist/usage.mjs +84 -0
  76. package/dist/validation.mjs +0 -12
  77. package/dist/verification/browser.mjs +77 -48
  78. package/docs/ADS.md +17 -11
  79. package/docs/ARCHITECTURE.md +43 -29
  80. package/docs/BEHAVIORS.md +3 -3
  81. package/docs/CHANGELOG.md +81 -13
  82. package/docs/GUIDE.md +96 -53
  83. package/docs/MCP.md +117 -123
  84. package/docs/benchmarks/bun-previews.md +91 -0
  85. package/docs/benchmarks/gidi-preview-memory.md +4 -0
  86. package/package.json +16 -14
@@ -1,7 +1,7 @@
1
- export const reasoning = `For iterative design, read ads://guides/drafts and use tracked auto-mode drafts. Create a coherent proposal, edit normally, review the real ads_show_draft preview and accept its exact revision with ads_accept. Do not report requested design work complete while it remains only in drafts; fix acceptance failures or report the unfinished blocker. Pattern and composition drafts may depend on component/pattern/token drafts via normal @ds imports in an isolated overlay. Accept dependencies first, then review dependent revisions again. No separate iterate/refuse action or human approval gate is required. Low-level guarded patches remain available for focused repairs/migrations.
1
+ export const reasoning = `Choose direct code editing or MCP-only editing using ads://guides/workflows, based on actual source access and user instructions. Direct editors change owned files normally and use MCP for previews/checks; ordinary direct edits do not require tracked drafts or ads_accept. MCP-only iterative design uses enabled draft tools: create a coherent proposal, edit it, inspect ads_show_draft and accept its exact reviewed revision. Direct editors may choose that isolated workflow too. Complete required tracked proposals by acceptance; fix failing checks or report unfinished work, and retain proposals only when requested. Accept dependency drafts first, then review dependents again. Auto mode implies agent review, not an extra human approval gate. Compiler ownership is independent: mcp.previewWatch:false is the direct-editing/external-builder variant; MCP serves published graph/evidence without starting a compiler. Source changes stale existing evidence until verified updated output is published.
2
2
  ADS is development tooling. The project owns its components, patterns, token values and branding.
3
3
  Start with ads_status and use its projectRoot, workflow and project commands; the MCP workspace may be nested inside the client repository. If ADS tools are not exposed, read ads://project/guide then ads://project/status. Find existing public UI with ads_catalog and load one relevant ADS workflow via ads_skills/ads_read_skill. UI implementation/refinement uses ads-designer; library adaptation ads-port; ADS transfer ads-import; motion ads-motion; stress testing ads-break-ui. Domain-model workflows are separate. Inspect the relevant public API, local guide, token definitions and real showcase fixture before proposing changes. Keep source/instruction discovery scoped to the target project, ancestry and selected external sources; broad scans of /mnt or home are not needed to discover this ADS.
4
- For low-level repairs/migrations when ads_status.mutations.enabled, discover one owner with ads_units, read relevant ranges with ads_read_file and send only a Git unified diff through ads_apply_patch({unit,patch,dryRun}). A unit includes its own scenarios/fixtures; imported peers remain separate. tokens is the token foundation unit. Only that owner's public re-exports may change in the shared entry; preserve unrelated statements. A real re-export may replace a redundant export {}; placeholder; do not add empty exports. Token manifests list companionFiles: include required foundation import changes only for canonical token files created/deleted in the same patch, preserving other imports/comments and canonical order. Use dryRun to review validation. Rejected patches leave source unchanged; fix diagnostics rather than bypassing checks with direct writes. Shared globals use foundation; guides use documentation; assets use discovered assets/* units. Intentional configuration, registered project guards/builders and rule exceptions use configuration, which validates the proposed settings and refreshes its compiler. Keep mandatory ADS gates. For large/binary diffs, pass patchFile pointing to .ds/patches/<name>.patch rather than loading bytes into context; Git binary patches require installed Git. When editing is disabled, use local editing tools.
4
+ For MCP-only low-level repairs/migrations when ads_status.mutations.enabled, discover one owner with ads_units, read relevant ranges with ads_read_file and send only a Git unified diff through ads_apply_patch({unit,patch,dryRun}). A unit includes its own scenarios/fixtures; imported peers remain separate. tokens is the token foundation unit. Only that owner's public re-exports may change in the shared entry; preserve unrelated statements. A real re-export may replace a redundant export {}; placeholder; do not add empty exports. Token manifests list companionFiles: include required foundation import changes only for canonical token files created/deleted in the same patch, preserving other imports/comments and canonical order. Use dryRun to review validation. Rejected patches leave source unchanged; fix diagnostics rather than bypassing checks with direct writes. Shared globals use foundation; guides use documentation; assets use discovered assets/* units. Intentional configuration, registered project guards/builders and rule exceptions use configuration, which validates the proposed settings and refreshes its compiler. Keep mandatory ADS gates. For large/binary diffs, pass patchFile pointing to .ds/patches/<name>.patch rather than loading bytes into context; Git binary patches require installed Git. Direct editors use their authorized editor instead; MCP-only clients without mutation tools cannot edit.
5
5
  Reason through Data (design-token values, semantic roles and relationships), UX (structure, behavior, accessibility, states and layout), and Skin (token-backed identity and visual states). Business data is a separate application-owned input, supplied through typed props or injected callbacks/services. Shared foundation Data is the only design-value catalogue. Components map it with --ds-* and patterns/review with --ux-*; there are no independent owner token namespaces or value sheets. Reuse project font, text and spacing roles when upstream constants differ. Read ads://guides/tokens for source boundaries and duplication review. The project uses Linaria extraction for owned styles; MCP adds no production runtime.
6
6
  Choose an existing public component or pattern first. Keep application data/routing/effects in the application and fixture data/state beside its scenario. Change presentation in its owning ADS implementation, then demonstrate the same public API in the showcase. Put demo-only sizing and framing in a development-only review/ helper, exported through the separate review entry rather than the production barrel; add component props for deliberate runtime API needs and preserve required behavior. Do not create a widget-only replica or override component internals.
7
7
  For token source inspection, call ads_tokens with a focused query. For token samples, components, patterns and composition, use ads_scenarios to select a path-derived id and invoke ads_show_scenario. Showcase and MCP mount that exact entry and its colocated fixture; no page initialization is required. The showcase is a minimal tool-owned shell plus an MCP client and Apps host. Its menus come from tools; it invokes the same entry tools and refreshes the active scenario through notifications. The reusable App loads framework runtime, foundation CSS, fonts and selected modules via MCP resources inside its sandbox. Keep project execution and styles out of the outer host; preserve mount/unmount cleanup and lazy dependencies. Use the existing ads_status showcase URL, or ads showcase when no MCP runtime is connected. Projects supply scenarios/fixtures and the compiler, not browser page files or another shell. Tool metadata selects an MCP App; a resources/read of HTML alone is not proof of rendered UI. If the host has no Apps view, give the configured showcase URL and use text/resources.
@@ -27,6 +27,7 @@ export class PreviewResourceLoader {
27
27
  this.styles = new Map();
28
28
  this.styleReady = new Map();
29
29
  this.revisions = new Set();
30
+ this.loadedModules = new Set();
30
31
  this.importing = Promise.resolve();
31
32
  this.generation = 0;
32
33
  this.prefetchGeneration = 0;
@@ -35,8 +36,6 @@ export class PreviewResourceLoader {
35
36
  }
36
37
  register(manifest) {
37
38
  if (manifest.schemaVersion !== 1 || !Array.isArray(manifest.scenarios) || !manifest.assets || typeof manifest.revision !== "string") throw new Error("Unsupported preview manifest. Rebuild previews with the installed ADS version.");
38
- this.revisions.add(manifest.revision);
39
- if (this.revisions.size > 20) throw Object.assign(new Error("Reopen the preview to release modules retained across 20 build revisions."), { code: "ADS_PREVIEW_REOPEN" });
40
39
  for (const [uri, record] of Object.entries(manifest.assets)) {
41
40
  if (!/^ads:\/\/assets\/[a-f0-9]{64}\.[a-z0-9]+$/.test(uri) || !/^sha256:[a-f0-9]{64}$/.test(record.digest)
42
41
  || !["imports", "dynamicImports", "styles", "references"].every(key => Array.isArray(record[key]) && record[key].every(ref => Object.hasOwn(manifest.assets, ref)))) throw new Error("Invalid preview dependency graph.");
@@ -96,7 +95,7 @@ export class PreviewResourceLoader {
96
95
  if (this.urls.has(id)) continue;
97
96
  const record = this.records.get(id);
98
97
  let bytes = await this.resource(id);
99
- if (record.kind === "module" || record.mimeType === "text/css") {
98
+ if (record.kind === "module" || record.mimeType === "text/css" || record.mimeType === "text/javascript") {
100
99
  let text = new TextDecoder().decode(bytes);
101
100
  for (const reference of record.references) {
102
101
  const url = this.urls.get(reference);
@@ -121,6 +120,11 @@ export class PreviewResourceLoader {
121
120
  const prepare = this.importing.then(() => this.materialize(uri));
122
121
  this.importing = prepare.catch(() => {});
123
122
  const dependencies = await prepare;
123
+ await this.attachStyles(dependencies);
124
+ try { const module = await import(/* @vite-ignore */ uri); this.loadedModules.add(uri); return module; }
125
+ catch (error) { throw new Error(`Preview module import failed for ${uri}: ${error.message}. Inspect the App resource bridge, browser network/CSP diagnostics and current build.`, { cause: error }); }
126
+ }
127
+ async attachStyles(dependencies) {
124
128
  for (const id of dependencies) {
125
129
  const record = this.records.get(id);
126
130
  if (record.mimeType !== "text/css") continue;
@@ -134,8 +138,24 @@ export class PreviewResourceLoader {
134
138
  document.head.append(style);
135
139
  try { await ready; } catch (error) { style.remove(); this.styles.delete(id); this.styleReady.delete(id); throw error; }
136
140
  }
137
- try { return await import(/* @vite-ignore */ uri); }
138
- catch (error) { throw new Error(`Preview module import failed for ${uri}: ${error.message}. Inspect the App resource bridge, browser network/CSP diagnostics and current build.`, { cause: error }); }
141
+ }
142
+ async refreshStyles(uri, generation) {
143
+ const roots = [uri], seen = new Set(), keep = new Set();
144
+ // A lazy module can keep identical JS bytes while its CSS metadata changes.
145
+ // Refresh only lazy branches already opened by this App, leaving unopened
146
+ // pages unfetched and retaining the currently mounted component state.
147
+ for (let index = 0; index < roots.length; index++) {
148
+ const root = roots[index]; if (seen.has(root)) continue; seen.add(root);
149
+ for (const id of await this.materialize(root)) {
150
+ keep.add(id);
151
+ for (const dynamic of this.records.get(id).dynamicImports) if (this.loadedModules.has(dynamic)) roots.push(dynamic);
152
+ }
153
+ }
154
+ await this.attachStyles([...keep]);
155
+ if (generation !== this.generation || this.closed) return false;
156
+ for (const [id, style] of this.styles) if (!keep.has(id)) { style.remove(); this.styles.delete(id); this.styleReady.delete(id); }
157
+ for (const id of keep) if (this.styles.has(id)) document.head.append(this.styles.get(id));
158
+ return true;
139
159
  }
140
160
  async mount(manifest, id, container) {
141
161
  const generation = ++this.generation;
@@ -145,7 +165,11 @@ export class PreviewResourceLoader {
145
165
  const signature = JSON.stringify(this.closure(scenario.module).map(uri => [uri, this.records.get(uri)]));
146
166
  // A successful global graph revision may only affect another scenario.
147
167
  // Retain this view's form/scroll state, then let the caller rerun its audits.
148
- if (this.mounted?.id === id && this.mounted.container === container && this.mounted.signature === signature) return true;
168
+ if (this.mounted?.id === id && this.mounted.container === container && this.mounted.signature === signature) return this.refreshStyles(scenario.module, generation);
169
+ // Background warming changes the global manifest without loading another
170
+ // module into this App. Only actual selected module revisions need a reset.
171
+ this.revisions.add(scenario.module);
172
+ if (this.revisions.size > 20) throw Object.assign(new Error("Reopen the preview to release modules retained across 20 build revisions."), { code: "ADS_PREVIEW_REOPEN" });
149
173
  const module = await this.importModule(scenario.module);
150
174
  if (generation !== this.generation) return false;
151
175
  const unmount = this.unmount;
@@ -154,9 +178,7 @@ export class PreviewResourceLoader {
154
178
  await unmount?.();
155
179
  if (generation !== this.generation || this.closed) return false;
156
180
  container.replaceChildren();
157
- const keep = new Set(this.closure(scenario.module));
158
- for (const [uri, style] of this.styles) if (!keep.has(uri)) { style.remove(); this.styles.delete(uri); this.styleReady.delete(uri); }
159
- for (const uri of this.closure(scenario.module)) if (this.styles.has(uri)) document.head.append(this.styles.get(uri));
181
+ if (!await this.refreshStyles(scenario.module, generation)) return false;
160
182
  if (typeof module.mount !== "function") throw new Error("The compiled scenario has no mount adapter.");
161
183
  this.unmount = module.mount(container);
162
184
  if (typeof this.unmount !== "function") throw new Error("The scenario mount adapter must return an unmount callback.");
@@ -172,7 +194,7 @@ export class PreviewResourceLoader {
172
194
  this.mounted = undefined;
173
195
  for (const style of this.styles.values()) style.remove();
174
196
  for (const url of this.urls.values()) URL.revokeObjectURL(url);
175
- this.styles.clear(); this.styleReady.clear(); this.urls.clear(); this.bytes.clear(); this.records.clear();
197
+ this.styles.clear(); this.styleReady.clear(); this.urls.clear(); this.bytes.clear(); this.records.clear();this.revisions.clear();this.loadedModules.clear();
176
198
  delete globalThis.__dsPreviewImport;
177
199
  }
178
200
  }
@@ -10,11 +10,12 @@ import { createVerificationController, BEHAVIOR_URI } from "../verification.mjs"
10
10
  import { INVESTIGATIONS_URI, investigationIndex, investigationPage, investigationSections, readInvestigation, readInvestigationResource } from "../investigations.mjs";
11
11
  import { failure } from "../evidence.mjs";
12
12
  import { inspectTokens } from "../tokens.mjs";
13
- import { discoverScenarioRegistry, releaseScenarioRegistry } from "../scenario-registry.mjs";
13
+ import { discoverScenarioRegistry, readScenarioRegistry, releaseScenarioRegistry } from "../scenario-registry.mjs";
14
+ import { createScenarioInspector } from "../scenario-inspector.mjs";
14
15
  import { scenarioGroupFingerprint } from "../scenario-groups.mjs";
15
16
  import { startShowcaseHost } from "./showcase-host.mjs";
16
17
  import { createSkillStore, page, SKILLS_EXTENSION } from "./skills.mjs";
17
- import { inspectCatalog, projectDocuments, PROJECT_URI, readProjectDocument } from "./catalog.mjs";
18
+ import { projectDocuments, PROJECT_URI, readProjectDocument } from "./catalog.mjs";
18
19
  import { APP_MIME, appMetadata, appUri, projectApp, TOKENS_APP_URI, tokensApp, tokenWidgetData, SCENARIO_APP_URI, scenarioApp, previewApp, PREVIEW_APP_URI } from "./apps.mjs";
19
20
  import { LIVE_PREVIEW_MANIFEST_URI, PREVIEW_MANIFEST_URI, readPreviewManifest, readPreviewAsset } from "../preview-resources.mjs";
20
21
  import { livePreviewOptions, previewArtifactPath, withPreviewSession } from "../preview-scope.mjs";
@@ -22,6 +23,8 @@ import { getWorkflowPrompt, promptDefinitions } from "./prompts.mjs";
22
23
  import { createReconfigurablePreviewWatch } from "./preview-watch.mjs";
23
24
  import { BUILD_URI, buildFailure, inspectBuildStatus, summarizeBuild } from "./build-status.mjs";
24
25
  import { GUIDE_URI, projectContext, projectGuide, serverInstructions, workflow } from "./context.mjs";
26
+ import { resourceLimitsStatus } from "../resource-limits.mjs";
27
+ import { assertBunRuntime } from "../runtime-requirements.mjs";
25
28
  import { createMutationController, mutationLimits } from "./mutations.mjs";
26
29
  import { createPreviewWork } from "./preview-work.mjs";
27
30
  import { prepareUnitPatch, storePreparedPatch } from "./edit-preparation.mjs";
@@ -29,7 +32,6 @@ import { reconcileTokenSamples } from "../token-fixtures.mjs";
29
32
  import { createCaptureController } from "../capture.mjs";
30
33
  import { CAPTURES_URI, captureSpec, screenshotFields } from "../capture-store.mjs";
31
34
  import { previewSourceRevision } from "../preview-inputs.mjs";
32
- import { inspectBehaviorLibraries } from "../behavior-libraries.mjs";
33
35
  import { createExecutionResults, RESULTS_URI, resultSections } from "./execution-results.mjs";
34
36
  import { behaviorPage, behaviorSections } from "./behavior-pages.mjs";
35
37
  import { compactProgress, resultBudgets } from "./result-pages.mjs";
@@ -66,6 +68,7 @@ function resourceQuery(uri, allowed) {
66
68
  }
67
69
 
68
70
  export function createAdsMcp(directory, { era = "legacy", skillDirectory, pollInterval = 1000, observeChanges = true, previewWatch, showcaseUrl, notifications, inspection, mutations = false, onBuildChange } = {}) {
71
+ if (process.versions.bun) assertBunRuntime();
69
72
  const root = path.resolve(directory);
70
73
  let observationClosed = false;
71
74
  const cache = inspection ?? {};
@@ -106,7 +109,7 @@ export function createAdsMcp(directory, { era = "legacy", skillDirectory, pollIn
106
109
  const project = () => { const context = projectContext(options); context.showcase.url = getShowcaseUrl(); return context; };
107
110
  const subscribed = new Set();
108
111
  const server = new Server({ name: "reqvire-ads", version: pkg.version }, {
109
- instructions: `${serverInstructions} ${mutations ? "Auto-mode tracked drafts are enabled. Read ads://guides/drafts. Create/edit a draft, inspect its real preview, then accept the exact reviewed revision with ads_accept. Complete coherent design changes by accepting their required drafts; failures are unfinished blockers. Accept dependency drafts first and review their dependents again. Low-level guarded editing is also enabled: discover one owner with ads_units, read relevant ranges with ads_read_file and send only a Git unified diff to ads_apply_patch with that unit ID. Include its own scenarios/fixtures and required re-exports together, never unrelated units. Manifests list companionFiles: required canonical token imports, or only the selected runtime owner's style-boundary entries in ds.config.json alongside its source. Unused style permissions fail validation. The server validates architecture, registered Oxlint and project checks before writing. Fix rejected patches in their owner. Intentional settings, project guards and builders use the configuration unit; mandatory ADS gates still run." : "Source mutation tools are disabled; source edits use the client's editor/filesystem tools."}`,
112
+ instructions: `${serverInstructions} ${mutations ? "MCP source mutation tools are enabled for MCP-only editing or deliberately selected guarded proposals. Read ads://guides/workflows first; availability does not require direct editors to use drafts. For tracked proposals, read ads://guides/drafts and accept the exact rendered/reviewed revision. Focused repairs use ads_units, ads_read_file and guarded ads_apply_patch for one owner, or ads_apply_transaction for coupled owners. Preserve companionFiles scope and mandatory ADS gates." : "MCP source mutation tools are disabled. Direct editors can still edit owned files normally and use MCP for previews/checks. MCP-only clients without another source channel cannot edit."}`,
110
113
  capabilities: { tools: { listChanged: true }, resources: { listChanged: true, subscribe: true }, prompts: {},
111
114
  extensions: { "io.modelcontextprotocol/ui": { mimeTypes: [APP_MIME] }, ...(era === "modern" ? { [SKILLS_EXTENSION]: { directoryRead: true } } : {}) } },
112
115
  });
@@ -119,13 +122,37 @@ export function createAdsMcp(directory, { era = "legacy", skillDirectory, pollIn
119
122
  }
120
123
  cache.lastRegistry = cache.registry; return cache.registry;
121
124
  };
122
- const previewRegistry = waitFor => waitFor === "compiled" ? cache.registry ?? cache.lastRegistry ?? getRegistry() : getRegistry();
125
+ async function getRegistryAsync() {
126
+ for(let attempt=0;attempt<2;attempt++){
127
+ const current=loadConfig(root),revision=previewSourceRevision(current);
128
+ if(cache.registry&&cache.registryRevision===revision)return cache.registry;
129
+ const stored=readScenarioRegistry(current);
130
+ if(stored){cache.registry=cache.lastRegistry=stored;cache.registryRevision=revision;return stored;}
131
+ if(cache.registryTask?.revision!==revision){
132
+ const inspector=cache.registryInspector??=createScenarioInspector(root);
133
+ const task={revision,promise:inspector.inspect()};cache.registryTask=task;
134
+ void task.promise.finally(()=>{if(cache.registryTask===task)cache.registryTask=undefined;}).catch(()=>{});
135
+ }
136
+ const registry=await cache.registryTask.promise;
137
+ if(previewSourceRevision(loadConfig(root))!==revision)continue;
138
+ cache.registry=cache.lastRegistry=registry;cache.registryRevision=revision;cache.catalog=undefined;
139
+ return registry;
140
+ }
141
+ throw new Error("Sources changed during scenario discovery. Retry against the current source.");
142
+ }
143
+ const quickRegistry = () => {
144
+ if(cache.registry??cache.lastRegistry)return cache.registry??cache.lastRegistry;
145
+ const stored=readScenarioRegistry(loadConfig(root));
146
+ if(stored)cache.lastRegistry=stored;
147
+ return stored??{scenarios:[],diagnostics:[]};
148
+ };
149
+ const previewRegistry = waitFor => waitFor === "compiled" && (cache.registry??cache.lastRegistry) ? cache.registry??cache.lastRegistry : getRegistryAsync();
123
150
  function captureInventory() {
124
151
  const current = loadConfig(root), registry = getRegistry();
125
152
  return { ...registry, revision: previewSourceRevision(current) };
126
153
  }
127
154
  function captureIndex() { const inventory = captureInventory(); return captures.store.list(inventory.scenarios, inventory.revision, { prune: !inventory.diagnostics.length }); }
128
- const scenarioApps = (quick = false) => (quick ? cache.registry ?? cache.lastRegistry ?? getRegistry() : getRegistry()).scenarios.map(item => ({ id: item.id, title: item.title, kind: item.kind, ...(item.samples ? { samples: item.samples } : {}), file: item.artifact }));
155
+ 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 }));
129
156
  const tokenScenarios = () => {
130
157
  const references=drafts.list({unit:"tokens",limit:100000}).drafts.map(({id,title,revision,state,preview})=>({id,title,revision,state,preview}));
131
158
  return getRegistry().scenarios.filter(item => item.kind === "tokens").map(item => ({ id:item.id,title:item.title,count:item.tokens.length,drafts:references }));
@@ -144,16 +171,37 @@ export function createAdsMcp(directory, { era = "legacy", skillDirectory, pollIn
144
171
  if (!manifest?.scenarios.some(entry => entry.id === id)) throw new Error("The preview resource graph is not ready for this scenario. Rebuild previews.");
145
172
  return { manifestUri: live ? LIVE_PREVIEW_MANIFEST_URI : PREVIEW_MANIFEST_URI, manifestRevision: manifest.revision };
146
173
  }
147
- const getCatalog = () => { const registry = getRegistry(); return cache.catalog ??= inspectCatalog(loadConfig(root), registry.scenarios, getBehaviorLibraries()); };
148
- const getBehaviorLibraries = () => cache.behaviorLibraries ??= inspectBehaviorLibraries(loadConfig(root));
149
- function annotateDrafts(items) {
150
- const found = drafts.list({limit:100000}).drafts, units = edits.units();
174
+ async function getCatalog() {
175
+ for(let attempt=0;attempt<2;attempt++){
176
+ await getRegistryAsync();const revision=cache.registryRevision;
177
+ if(cache.catalog&&cache.catalogRevision===revision)return cache.catalog;
178
+ if(cache.catalogTask?.revision!==revision){
179
+ const inspector=cache.registryInspector??=createScenarioInspector(root);
180
+ const task={revision,promise:inspector.inspect(root,"catalog")};cache.catalogTask=task;
181
+ void task.promise.finally(()=>{if(cache.catalogTask===task)cache.catalogTask=undefined;}).catch(()=>{});
182
+ }
183
+ const value=await cache.catalogTask.promise;
184
+ if(previewSourceRevision(loadConfig(root))!==revision)continue;
185
+ cache.catalog=value.catalog;cache.catalogRevision=revision;cache.behaviorLibraries={libraries:value.libraries};return cache.catalog;
186
+ }
187
+ throw new Error("Sources changed during catalogue discovery. Retry against the current source.");
188
+ }
189
+ const getBehaviorLibraries = () => cache.behaviorLibraries;
190
+ function annotateDrafts(items, found = drafts.list({limit:100000}).drafts) {
191
+ const units = edits.units();
151
192
  return items.map(item => {
152
193
  const unit = units.find(unit => unit.files.includes(item.file))?.id ?? null;
153
194
  return { ...item, unit, drafts: found.filter(draft => draft.units.includes(unit)).map(({id,title,revision,state,preview}) => ({id,title,revision,state,preview})) };
154
195
  });
155
196
  }
156
197
  const getDocuments = () => cache.documents ??= projectDocuments(options);
198
+ async function explorer() {
199
+ const registry=await getRegistryAsync(), proposals=drafts.list({limit:100000}).drafts;
200
+ const scenarios=annotateDrafts(registry.scenarios,proposals).map(({id,title,kind,group,unit,drafts})=>({id,title,kind,...(group?{group}:{}),unit,drafts}));
201
+ return {status:{projectRoot:root,project:{showcase:project().showcase},drafts:{previewOnly:isDraftPreviewWorkspace(root)},previewWatch:previewWatch?.status(),build:summarizeBuild(builds())},
202
+ 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,
203
+ tools:tools().map(({name,_meta,schema})=>{const waitFor=z.toJSONSchema(schema).properties?.waitFor;return{name,...(_meta?{_meta}:{}),inputSchema:{properties:waitFor?{waitFor}:{}}};}),diagnostics:registry.diagnostics};
204
+ }
157
205
  const builds = () => {
158
206
  previewWatch?.setApps(allApps(true));
159
207
  const report = previewWatch?.buildStatus() ?? inspectBuildStatus(root, { ...options.config.mcp, apps: allApps(true) });
@@ -194,6 +242,7 @@ export function createAdsMcp(directory, { era = "legacy", skillDirectory, pollIn
194
242
  return [
195
243
  { 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" },
196
244
  { uri: "ads://guides/behaviors", name: "Controller and behavioral verification guide", mimeType: "text/markdown" },
245
+ { uri: "ads://guides/workflows", name: "Direct code editing and MCP-only editing workflows", mimeType: "text/markdown" },
197
246
  { uri: "ads://guides/validation", name: "Full and affected validation; test boundaries", mimeType: "text/markdown" },
198
247
  { uri: "ads://guides/runtimes", name: "Node and Bun setup, compiler and verification runtime", mimeType: "text/markdown" },
199
248
  { uri: "ads://guides/evidence", name: "Failure boundaries and compact investigations", mimeType: "text/markdown" },
@@ -204,6 +253,7 @@ export function createAdsMcp(directory, { era = "legacy", skillDirectory, pollIn
204
253
  { uri: "ads://guides/review", name: "Development-only review UI, token renderers and migration", mimeType: "text/markdown" },
205
254
  { uri: "ads://guides/captures", name: "On-demand captures and candidate visual review", mimeType: "text/markdown" },
206
255
  { uri: `${PROJECT_URI}/status`, name: "ADS project status", mimeType: "application/json" },
256
+ { uri: `${PROJECT_URI}/explorer`, name: "Explorer navigation and preview bootstrap", mimeType: "application/json" },
207
257
  { uri: BUILD_URI, name: "Preview build status and diagnostics", mimeType: "application/json" },
208
258
  { uri: `${PROJECT_URI}/tokens`, name: "Project token values and themes", mimeType: "application/json" },
209
259
  { uri: `${PROJECT_URI}/catalog`, name: "Public components and patterns", mimeType: "application/json" },
@@ -230,14 +280,15 @@ export function createAdsMcp(directory, { era = "legacy", skillDirectory, pollIn
230
280
  ...[...skills.files.values()].filter((file) => !skillEntries.has(file.uri)).map(({ uri, name, mimeType }) => ({ uri, name, mimeType })),
231
281
  ];
232
282
  }
233
- function status() {
283
+ async function status() {
234
284
  const context = project(), mutationState = mutations ? edits.status() : null, behaviorState = verification.status();
235
- const catalog = getCatalog(), registry = cache.registry;
285
+ const catalog = await getCatalog(), registry = cache.registry;
236
286
  return { projectRoot: root, workflow: workflow([...previews(), ...scenarioApps(true)]), project: context,
237
287
  package: pkg.name, version: pkg.version, dsDir: options.config.dsDir, publicAlias: options.config.publicAlias, behaviorLibraries: getBehaviorLibraries().libraries,
238
288
  components: catalog.filter((item) => item.kind === "components" && item.apiKind === "ui").length,
239
289
  patterns: catalog.filter((item) => item.kind === "patterns" && item.apiKind === "ui").length,
240
290
  tokenCount: inspectTokens(root).tokens.length, showcaseUrl: getShowcaseUrl(),
291
+ resourceLimits: resourceLimitsStatus(options.config.resources),
241
292
  previewWatch: previewWatch?.status() ?? { state: "disabled" },
242
293
  mutations: mutations ? { ...mutationState, progress: compactProgress(mutationState.progress), lastResult: executionResults.latest("mutation") } : { enabled: false },
243
294
  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) },
@@ -251,11 +302,13 @@ export function createAdsMcp(directory, { era = "legacy", skillDirectory, pollIn
251
302
  experimental: { apps: true, nativeSkills: era === "modern", nativeSkillActivation: "host-controlled" } };
252
303
  }
253
304
  async function read(uri, signal) {
305
+ if(uri===`${PROJECT_URI}/explorer`)return{contents:[{uri,mimeType:"application/json",text:JSON.stringify(await explorer())}]};
254
306
  if(uri.startsWith("ads://drafts/")){
255
307
  const url=new URL(uri),match=url.pathname.match(/^\/([a-z0-9][a-z0-9-]{0,79})\/resource$/);
256
308
  if(!match||[...url.searchParams.keys()].some(key=>key!=="uri")||!url.searchParams.get("uri"))throw new Error("Invalid draft resource address.");
257
309
  return drafts.readResource(match[1],url.searchParams.get("uri"),signal);
258
310
  }
311
+ 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")}]};
259
312
  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")}] };
260
313
  if (uri === GUIDE_URI) return { contents: [{ uri, mimeType: "text/markdown", text: projectGuide(project(), [...previews(), ...scenarioApps()]) }] };
261
314
  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") }] };
@@ -272,10 +325,10 @@ export function createAdsMcp(directory, { era = "legacy", skillDirectory, pollIn
272
325
  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") }] };
273
326
  if (skills.files.has(uri)) return { contents: [skills.read(uri)] };
274
327
  let value;
275
- if (uri === `${PROJECT_URI}/status`) value = status();
328
+ if (uri === `${PROJECT_URI}/status`) value = await status();
276
329
  else if (uri === BUILD_URI) value = builds();
277
330
  else if (uri === `${PROJECT_URI}/tokens`) value = tokenWidgetData(inspectTokens(root));
278
- else if (uri === `${PROJECT_URI}/catalog`) value = { items: annotateDrafts(getCatalog()) };
331
+ else if (uri === `${PROJECT_URI}/catalog`) value = { items: annotateDrafts(await getCatalog()) };
279
332
  else if (uri === DRAFTS_URI) value = drafts.list();
280
333
  else if (uri === `${PROJECT_URI}/scenarios`) value = getRegistry();
281
334
  else if (uri === `${PROJECT_URI}/checks`) value = await architecture(signal);
@@ -359,8 +412,8 @@ export function createAdsMcp(directory, { era = "legacy", skillDirectory, pollIn
359
412
  function tools() {
360
413
  return [
361
414
  { 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)) },
362
- { 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. 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=>{
363
- const value=await drafts.show(args),base=getShowcaseUrl();
415
+ { 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. 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)=>{
416
+ const value=await drafts.show(args,signal),base=getShowcaseUrl();
364
417
  let comparisonUrl=null;
365
418
  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;}
366
419
  return json({...value,isolatedShowcaseUrl:value.showcaseUrl,showcaseUrl:comparisonUrl??value.showcaseUrl,comparisonUrl});
@@ -369,14 +422,14 @@ export function createAdsMcp(directory, { era = "legacy", skillDirectory, pollIn
369
422
  { name:"ads_create_draft", description:"Create a Git-committable proposal under ads-drafts/ for 1–64 coupled ADS owners, copying only their source/companions into non-importable .ads files. New owners are allowed. Optional dependencies name separate unaccepted drafts used by pattern/composition previews. Creation does not change accepted source. Edit the returned files normally; use ads_update_draft to register additions/deletions.", schema:z.object({units:z.array(z.string().min(1).max(256)).min(1).max(mutationLimits.units),title:z.string().min(1).max(160).optional(),id:draftIdSchema.optional(),dependencies:z.array(draftIdSchema).max(8).default([]),tokenGroups:z.array(z.string().min(1).max(160)).max(32).default([])}).strict(),_meta:{ui:{visibility:["model"]}},annotations:{...annotations,readOnlyHint:false,idempotentHint:false},call:async args=>{const result=drafts.create(args);if(observeChanges)await refresh();return json(result);} },
370
423
  { 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. 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([])}).strict(),_meta:{ui:{visibility:["model"]}},annotations:{...annotations,readOnlyHint:false,idempotentHint:false},call:async args=>{const result=drafts.update(args);if(observeChanges)await refresh();return json(result);} },
371
424
  { 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);} },
372
- { 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 architecture, registered Oxlint/project and affected behavior checks run once on the candidate. Draft/source changes invalidate acceptance. On failure retain the draft and inspect ads_results; on success apply normal source, remove the draft and publish an event. No additional human approval or manual Apply step.",schema:z.object({id:draftIdSchema,revision:draftRevisionSchema}).strict(),_meta:{ui:{visibility:["model"]}},annotations:{...annotations,readOnlyHint:false,destructiveHint:true,idempotentHint:false},call:async(args,signal,progress)=>{
425
+ { 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 architecture, configured project and affected behavior checks run once on the candidate. Draft/source changes invalidate acceptance. On failure retain the draft and inspect ads_results; on success apply normal source, remove the draft and publish an event. No additional human approval or manual Apply step.",schema:z.object({id:draftIdSchema,revision:draftRevisionSchema}).strict(),_meta:{ui:{visibility:["model"]}},annotations:{...annotations,readOnlyHint:false,destructiveHint:true,idempotentHint:false},call:async(args,signal,progress)=>{
373
426
  if(validation.status().busy||verification.status().running)throw new Error("Wait for validation/verification before acceptance.");
374
427
  const result=await drafts.accept(args,signal,progress);
375
428
  if(result.applied){await previewWatch?.invalidate?.();await refresh(true);}else await refresh();
376
429
  return finishExecution("mutation",result);
377
430
  } },
378
431
  ] : []),
379
- { 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. When mutations.enabled, use tracked drafts and ads_accept for iterative design (ads://guides/drafts); low-level guarded patches remain available; otherwise use local editing tools.", schema: empty, call: () => json(status()) },
432
+ { 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()) },
380
433
  { 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) => {
381
434
  let result;
382
435
  if(draft){
@@ -392,8 +445,8 @@ export function createAdsMcp(directory, { era = "legacy", skillDirectory, pollIn
392
445
  await refresh(); return captureResponse(result, era === "modern");
393
446
  } },
394
447
  { 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); } },
395
- { 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: ({ query: search = "", limit, kind }) => {
396
- const matches = getCatalog().filter((item) => (!kind || item.kind === kind) && item.name.toLowerCase().includes(search.toLowerCase()));
448
+ { 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 }) => {
449
+ const matches = (await getCatalog()).filter((item) => (!kind || item.kind === kind) && item.name.toLowerCase().includes(search.toLowerCase()));
397
450
  return json({ total: matches.length, items: annotateDrafts(matches.slice(0, limit)), resourceUri: `${PROJECT_URI}/catalog` });
398
451
  } },
399
452
  { name: "ads_scenarios", description: "Find an independently mountable 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(["tokens", "components", "patterns", "composition"]).optional(), offset: z.number().int().min(0).default(0) }), call: ({ query: search = "", limit, kind, offset }) => {
@@ -403,7 +456,7 @@ export function createAdsMcp(directory, { era = "legacy", skillDirectory, pollIn
403
456
  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` });
404
457
  } },
405
458
  { 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) => {
406
- const registry = previewRegistry(waitFor);
459
+ const registry = await previewRegistry(waitFor);
407
460
  const entry = registry.scenarios.find(item => item.id === id);
408
461
  if (!entry) throw new Error("Unknown scenario id. Read ads_scenarios; IDs must match discovered source entries.");
409
462
  if (registry.diagnostics.length) throw new Error("Scenario registry has errors. Read ads://project/scenarios and fix its diagnostics.");
@@ -434,7 +487,7 @@ export function createAdsMcp(directory, { era = "legacy", skillDirectory, pollIn
434
487
  return json({ ...manifest, text: content.text.slice(offset, offset + limit), offset, ...(offset + limit < content.text.length ? { nextOffset: offset + limit } : {}) });
435
488
  } },
436
489
  { 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) => {
437
- const registry = previewRegistry(waitFor);
490
+ const registry = await previewRegistry(waitFor);
438
491
  if (!category && options.config.mcp.previewManifest) category = registry.scenarios.find(item => item.kind === "tokens")?.id;
439
492
  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.");
440
493
  if (category) {
@@ -454,7 +507,7 @@ export function createAdsMcp(directory, { era = "legacy", skillDirectory, pollIn
454
507
  { 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) },
455
508
  { 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) },
456
509
  { 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. Only the latest bundle per check is retained, 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)) },
457
- { name: "ads_validate", description: "Run the shared ads validate audit. Default scope all: core architecture and test ownership, registered Oxlint, configured project scripts and all registered behavior checks. scope changed uses affected behavior checks since the last successful full audit; missing/incompatible baselines or broad changes expand to all and report why. Core and opaque project scripts retain their full scope. Use changed during editing, all after test/ownership/config migrations and before releases or explicit complete audits. Reports scope, source revision, skipped stages, progress and a bounded resultId; page diagnostics/checks/outcomes with ads_results. Changed inputs, cancellation and failed/skipped registered cases cannot pass. Read ads://guides/validation. Runs trusted configured commands; installs nothing.", schema: z.object({scope:z.enum(["all","changed"]).default("all")}).strict(), annotations: {readOnlyHint:false,destructiveHint:false,idempotentHint:false,openWorldHint:false}, call: async (args,signal,progress) => {
510
+ { name: "ads_validate", description: "Run the shared ads validate audit. Default scope all: core architecture and test ownership, configured project scripts and all registered behavior checks. scope changed uses affected behavior checks since the last successful full audit; missing/incompatible baselines or broad changes expand to all and report why. Core and opaque project scripts retain their full scope. Use changed during editing, all after test/ownership/config migrations and before releases or explicit complete audits. Reports scope, source revision, skipped stages, progress and a bounded resultId; page diagnostics/checks/outcomes with ads_results. Changed inputs, cancellation and failed/skipped registered cases cannot pass. Read ads://guides/validation. Runs trusted configured commands; installs nothing.", schema: z.object({scope:z.enum(["all","changed"]).default("all")}).strict(), annotations: {readOnlyHint:false,destructiveHint:false,idempotentHint:false,openWorldHint:false}, call: async (args,signal,progress) => {
458
511
  if (verification.status().running || edits.status().busy) throw new Error("Wait for the active verification or guarded edit before validating.");
459
512
  return finishExecution("validation",await validation.run(args,signal,progress));
460
513
  } },
@@ -473,11 +526,11 @@ export function createAdsMcp(directory, { era = "legacy", skillDirectory, pollIn
473
526
  const {patch,...result}=reconcileTokenSamples(options,args);
474
527
  return json({...result,removed:result.removed.slice(0,50),unresolved:result.unresolved.slice(0,50),unresolvedCount:result.unresolved.length,...storePreparedPatch(options,patch)});
475
528
  }},
476
- { name: "ads_apply_patch", description: "Apply one Git diff to one ADS unit from ads_units. Pass exactly one of patch (inline) or patchFile (a regular .patch/.diff under .ds/patches/, for large/binary diffs without model-context bytes). Text uses --- a/path, +++ b/path and exact @@ hunks; /dev/null creates/deletes. Git binary patches require git diff --binary --full-index and installed Git. A unit owns its implementation, previews and fixtures; imported peers are separate. Foundation, documentation, assets and configuration are editable too. Configuration changes may register/edit project guards and builders; the proposed schema, mandatory core/Oxlint and candidate project checks must pass. Only selected-unit public re-exports may change; preserve unrelated statements. A real selected-unit re-export may remove a redundant export {}; placeholder. A tokens patch may include its companionFiles foundation entry only to add/remove canonical imports required by token files created/deleted in this patch, preserving other imports/comments and canonical order. A runtime owner patch may also include its ds.config.json companion solely for that owner's inlineStyleFiles/styleWrites entries alongside its source. Unused permissions fail validation. Set dryRun true to validate without writing. Optional screenshot:true plus captures:[{scenario,target?,theme?,viewport?}] captures current/candidate only after gates pass. For genuinely coupled owner changes use ads_apply_transaction with one patch per owner. Fix rejected patches and inspect current previews after acceptance. Reply is a 4 KiB summary; read diagnostics, outcomes and requested captures through ads_results using its resultId.",
529
+ { name: "ads_apply_patch", description: "Apply one Git diff to one ADS unit from ads_units. Pass exactly one of patch (inline) or patchFile (a regular .patch/.diff under .ds/patches/, for large/binary diffs without model-context bytes). Text uses --- a/path, +++ b/path and exact @@ hunks; /dev/null creates/deletes. Git binary patches require git diff --binary --full-index and installed Git. A unit owns its implementation, previews and fixtures; imported peers are separate. Foundation, documentation, assets and configuration are editable too. Configuration changes may register/edit project guards and builders; the proposed schema, mandatory ADS and candidate project checks must pass. Only selected-unit public re-exports may change; preserve unrelated statements. A real selected-unit re-export may remove a redundant export {}; placeholder. A tokens patch may include its companionFiles foundation entry only to add/remove canonical imports required by token files created/deleted in this patch, preserving other imports/comments and canonical order. A runtime owner patch may also include its ds.config.json companion solely for that owner's inlineStyleFiles/styleWrites entries alongside its source. Unused permissions fail validation. Set dryRun true to validate without writing. Optional screenshot:true plus captures:[{scenario,target?,theme?,viewport?}] captures current/candidate only after gates pass. For genuinely coupled owner changes use ads_apply_transaction with one patch per owner. Fix rejected patches and inspect current previews after acceptance. Reply is a 4 KiB summary; read diagnostics, outcomes and requested captures through ads_results using its resultId.",
477
530
  schema: z.object({ unit: z.string().min(1).max(256), dryRun: z.boolean(), patch: z.string().min(1).max(mutationLimits.patchBytes).optional(), patchFile: z.string().min(1).max(500).optional(), ...screenshotFields }).strict().refine(args => (args.patch !== undefined) !== (args.patchFile !== undefined), "Provide exactly one of patch or patchFile."),
478
531
  annotations: { readOnlyHint: false, destructiveHint: true, idempotentHint: false, openWorldHint: false }, _meta: { ui: { visibility: ["model"] } },
479
532
  call: applyEdits,
480
- }, {name:"ads_apply_transaction",description:"Apply genuinely coupled ADS changes as 2–64 distinct owner Git patches. Each patch must obey its unit and narrow companion rules. Patches run in order; later patches use the earlier candidate's shared-entry content. Core guards, registered Oxlint/project checks and affected behavior checks validate the complete final candidate before any live source is written. Maximum 256 distinct files/16 MiB combined. Dry runs, failures and cancellation publish nothing; publication rolls back on write failure. Optional screenshot:true with dryRun:true and explicit captures selects current/candidate images. Prefer ads_apply_patch for independent edits. Reply is a bounded summary; page diagnostics, outcomes and captures with ads_results using the returned resultId.",schema:z.object({patches:z.array(ownerPatch).min(2).max(mutationLimits.units),dryRun:z.boolean(),...screenshotFields}).strict(),annotations:{readOnlyHint:false,destructiveHint:true,idempotentHint:false,openWorldHint:false},_meta:{ui:{visibility:["model"]}},call:applyEdits}] : []),
533
+ }, {name:"ads_apply_transaction",description:"Apply genuinely coupled ADS changes as 2–64 distinct owner Git patches. Each patch must obey its unit and narrow companion rules. Patches run in order; later patches use the earlier candidate's shared-entry content. Core guards, configured project checks and affected behavior checks validate the complete final candidate before any live source is written. Maximum 256 distinct files/16 MiB combined. Dry runs, failures and cancellation publish nothing; publication rolls back on write failure. Optional screenshot:true with dryRun:true and explicit captures selects current/candidate images. Prefer ads_apply_patch for independent edits. Reply is a bounded summary; page diagnostics, outcomes and captures with ads_results using the returned resultId.",schema:z.object({patches:z.array(ownerPatch).min(2).max(mutationLimits.units),dryRun:z.boolean(),...screenshotFields}).strict(),annotations:{readOnlyHint:false,destructiveHint:true,idempotentHint:false,openWorldHint:false},_meta:{ui:{visibility:["model"]}},call:applyEdits}] : []),
481
534
  ...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) => {
482
535
  // Validate readiness without embedding executable HTML in model results.
483
536
  const build = await previewBuild(app, signal);
@@ -638,13 +691,14 @@ export function createAdsMcp(directory, { era = "legacy", skillDirectory, pollIn
638
691
  || entry.diagnostics.some(item => item.code === "ADS_PREVIEW_STALE_SOURCE"));
639
692
  deferredDiscovery ||= filesChanged;
640
693
  const discoveryChanged = deferredDiscovery && !checking;
641
- if (discoveryChanged) deferredDiscovery = false;
694
+ if (discoveryChanged) { await getRegistryAsync(); if(observationClosed)return false; deferredDiscovery = false; }
642
695
  if (discoveryChanged || assetsChanged || draftResourcesChanged) { if (notifications) notifications.resourcesChanged(); else await server.sendResourceListChanged(); }
643
696
  previousArtifacts = artifactFingerprint();
644
697
  previousAssets = assetFingerprint();
645
698
  previousBuild = JSON.stringify(builds());
646
699
  const targets = discoveryChanged ? (era === "modern" ? resources().map((entry) => entry.uri).filter((uri) => !skills.files.has(uri)) : [...subscribed]).filter(uri => !uri.startsWith("ads://drafts/"))
647
700
  : [BUILD_URI, BEHAVIOR_URI, INVESTIGATIONS_URI, DRAFTS_URI, `${PROJECT_URI}/status`, ...(filesChanged ? [`${PROJECT_URI}/tokens`] : []), ...(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));
701
+ if((discoveryChanged||draftsChanged)&&(era==="modern"||subscribed.has(`${PROJECT_URI}/explorer`)))targets.push(`${PROJECT_URI}/explorer`);
648
702
  if(draftsChanged){targets.push(...[DRAFTS_URI,`${PROJECT_URI}/catalog`,`${PROJECT_URI}/scenarios`,`${PROJECT_URI}/status`].filter(uri=>era==="modern"||subscribed.has(uri)));previousDrafts=draftFingerprint;}
649
703
  targets.push(...changedDraftBuilds.filter(uri=>era==="modern"||subscribed.has(uri)));
650
704
  previousDraftBuilds=currentDraftBuilds;
@@ -671,21 +725,24 @@ export function createAdsMcp(directory, { era = "legacy", skillDirectory, pollIn
671
725
  async function warmScenarios(ids, signal) {
672
726
  if (!previewWatch) return;
673
727
  const apps = allApps(), selected = new Set(ids);
674
- const files = apps.filter(app => selected.has(app.id)).map(app => path.resolve(root, app.file));
675
- if (files.length !== selected.size) throw new Error("Cannot warm an unknown verification scenario.");
728
+ const selectedApps = apps.filter(app => selected.has(app.id));
729
+ if (selectedApps.length !== selected.size) throw new Error("Cannot warm an unknown verification scenario.");
676
730
  previewWatch.setApps(apps);
731
+ const ready = new Set(previewWatch.buildStatus().previews.filter(entry=>entry.current).map(entry=>entry.id));
732
+ const files = selectedApps.filter(app=>!ready.has(app.id)).map(app => path.resolve(root, app.file));
733
+ if (!files.length) return;
677
734
  await previewWatch.warm(files);
678
735
  for (const file of files) await previewWatch.ensure(file, signal);
679
736
  }
680
- 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() { stopObservation(); if (!inspection) { await drafts.close(); await validation.close(); await verification.close(); await captures.close(); } await server.close(); } };
737
+ 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() { stopObservation(); if (!inspection) { await cache.registryInspector?.close(); await drafts.close(); await validation.close(); await verification.close(); await captures.close(); } await server.close(); } };
681
738
  }
682
739
 
683
- export async function startAdsMcp(directory = process.cwd(), { stdio = true, showcase = true, port = 0, mutations = false, previewWork = createPreviewWork() } = {}) {
740
+ export async function startAdsMcp(directory = process.cwd(), { stdio = true, showcase = true, port = 0, mutations = false, previewWork = createPreviewWork(), previewBuildTimeoutMs = 30000, prewarm = stdio } = {}) {
741
+ if (process.versions.bun) assertBunRuntime();
684
742
  // Fail before opening the transport for configuration/distribution errors.
685
743
  const { root, config } = loadConfig(directory);
686
744
  const inspection = { skills: createSkillStore(), previewWork };
687
- const previewWatch = createReconfigurablePreviewWatch(root, config.mcp);
688
- const unregisterPreview = previewWork.register(previewWatch);
745
+ const previewWatch = createReconfigurablePreviewWatch(root, config.mcp, {buildTimeout:previewBuildTimeoutMs,prewarm});
689
746
  let host, api;
690
747
  let buildWatcher, buildChangeTimer;
691
748
  const buildListeners = new Set();
@@ -710,13 +767,15 @@ export async function startAdsMcp(directory = process.cwd(), { stdio = true, sho
710
767
  });
711
768
  buildWatcher.unref(); buildWatcher.on("error", () => { buildWatcher.close(); });
712
769
  } catch { /* Periodic observation also covers replaced/missing report directories. */ }
770
+ const warmStart=prewarm?setTimeout(()=>previewWatch.start(),0):undefined;
771
+ warmStart?.unref();
713
772
  let closing;
714
773
  function close() {
715
774
  return closing ??= (async () => {
775
+ clearTimeout(warmStart);
716
776
  buildListeners.clear();
717
777
  clearTimeout(buildChangeTimer); buildWatcher?.close();
718
778
  inspection.edits?.cancel();
719
- unregisterPreview();
720
779
  // Stop every owned resource even if another close fails or has in-flight RPCs.
721
780
  const results = await Promise.allSettled([
722
781
  Promise.resolve().then(() => host?.close()),
@@ -725,6 +784,7 @@ export async function startAdsMcp(directory = process.cwd(), { stdio = true, sho
725
784
  Promise.resolve().then(() => inspection.verification?.close()),
726
785
  Promise.resolve().then(() => inspection.captures?.close()),
727
786
  Promise.resolve().then(() => inspection.drafts?.close()),
787
+ Promise.resolve().then(() => inspection.registryInspector?.close()),
728
788
  Promise.resolve().then(() => api?.close()),
729
789
  Promise.resolve().then(() => handle?.close()),
730
790
  ]);
@@ -750,7 +810,7 @@ export async function startAdsMcp(directory = process.cwd(), { stdio = true, sho
750
810
  for (const signal of ["SIGINT", "SIGTERM"]) process.once(signal, disconnect);
751
811
  process.once("exit", forceCleanup);
752
812
  const previewApi=()=>api??=createAdsMcp(root,{era:"modern",inspection,previewWatch,showcaseUrl,mutations:false,pollInterval:0,observeChanges:false});
753
- return { close, url: host?.url, async buildAll(signal, options) { await previewWatch.initialize(); return previewApi().buildAll(signal, options); }, warmScenarios: (ids, signal) => previewApi().warmScenarios(ids, signal), prewarm: () => previewWatch.initialize(), onBuildChange(listener) { buildListeners.add(listener); return () => buildListeners.delete(listener); }, buildStatus: () => previewWatch.buildStatus(), primeRegistry(registry) {
813
+ 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) {
754
814
  if (inspection.registry === registry || inspection.lastRegistry === registry) return;
755
815
  inspection.registry = inspection.lastRegistry = registry; inspection.registryRevision = undefined; inspection.catalog = undefined;
756
816
  }, 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 };