@reqvire-org/ads 0.3.32 → 0.3.34

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 (84) hide show
  1. package/README.md +9 -0
  2. package/dist/behavior-libraries.mjs +93 -0
  3. package/dist/behaviors.mjs +0 -6
  4. package/dist/bootstrap-ds/ds.config.json +1 -0
  5. package/dist/bootstrap-ds/vite.config.ts +2 -1
  6. package/dist/boundaries.mjs +2 -0
  7. package/dist/capture.mjs +8 -6
  8. package/dist/check.mjs +2 -0
  9. package/dist/config.mjs +9 -2
  10. package/dist/draft-boundary.mjs +27 -0
  11. package/dist/draft-workspace.mjs +10 -0
  12. package/dist/lint-config.mjs +8 -0
  13. package/dist/mcp/build-status.mjs +1 -1
  14. package/dist/mcp/catalog.mjs +4 -2
  15. package/dist/mcp/context.mjs +2 -2
  16. package/dist/mcp/draft-discovery.mjs +55 -0
  17. package/dist/mcp/draft-exports.mjs +40 -0
  18. package/dist/mcp/drafts.mjs +460 -0
  19. package/dist/mcp/edit-preparation.mjs +8 -7
  20. package/dist/mcp/execution-results.mjs +2 -0
  21. package/dist/mcp/mutations.mjs +6 -2
  22. package/dist/mcp/preview-watch.mjs +24 -5
  23. package/dist/mcp/preview-widget.bundle.js +14 -14
  24. package/dist/mcp/prompts.mjs +3 -2
  25. package/dist/mcp/server.mjs +178 -39
  26. package/dist/mcp/widget.bundle.js +1 -1
  27. package/dist/preview-files.mjs +2 -0
  28. package/dist/scenario-inspector.mjs +5 -5
  29. package/dist/scenario-program.mjs +36 -0
  30. package/dist/scenario-registry.mjs +90 -0
  31. package/dist/scenarios-compiler.mjs +68 -22
  32. package/dist/scenarios-vite.d.mts +1 -0
  33. package/dist/scenarios-vite.mjs +1 -0
  34. package/dist/scenarios.mjs +2 -1
  35. package/dist/showcase/client.bundle.js +28 -28
  36. package/dist/showcase/comparison.js +45 -0
  37. package/dist/showcase/draft-navigation.js +41 -0
  38. package/dist/showcase/preview-state.js +19 -0
  39. package/dist/showcase/style.css +5 -0
  40. package/dist/skills/README.md +5 -0
  41. package/dist/skills/ads-break-ui/SKILL.md +26 -0
  42. package/dist/skills/ads-break-ui/references/behaviors.md +10 -0
  43. package/dist/skills/ads-break-ui/references/captures.md +7 -0
  44. package/dist/skills/ads-break-ui/references/drafts.md +146 -0
  45. package/dist/skills/ads-break-ui/references/guarded-editing.md +6 -0
  46. package/dist/skills/ads-break-ui/references/validation.md +6 -0
  47. package/dist/skills/ads-designer/SKILL.md +33 -0
  48. package/dist/skills/ads-designer/assets/bootstrap-ds/ds.config.json +1 -0
  49. package/dist/skills/ads-designer/assets/bootstrap-ds/vite.config.ts +2 -1
  50. package/dist/skills/ads-designer/references/behaviors.md +10 -0
  51. package/dist/skills/ads-designer/references/captures.md +7 -0
  52. package/dist/skills/ads-designer/references/drafts.md +146 -0
  53. package/dist/skills/ads-designer/references/guarded-editing.md +6 -0
  54. package/dist/skills/ads-designer/references/validation.md +6 -0
  55. package/dist/skills/ads-import/SKILL.md +30 -0
  56. package/dist/skills/ads-import/references/behaviors.md +10 -0
  57. package/dist/skills/ads-import/references/captures.md +7 -0
  58. package/dist/skills/ads-import/references/drafts.md +146 -0
  59. package/dist/skills/ads-import/references/guarded-editing.md +6 -0
  60. package/dist/skills/ads-import/references/validation.md +6 -0
  61. package/dist/skills/ads-motion/SKILL.md +26 -0
  62. package/dist/skills/ads-motion/references/behaviors.md +10 -0
  63. package/dist/skills/ads-motion/references/captures.md +7 -0
  64. package/dist/skills/ads-motion/references/drafts.md +146 -0
  65. package/dist/skills/ads-motion/references/guarded-editing.md +6 -0
  66. package/dist/skills/ads-motion/references/validation.md +6 -0
  67. package/dist/skills/ads-port/SKILL.md +34 -1
  68. package/dist/skills/ads-port/references/behaviors.md +10 -0
  69. package/dist/skills/ads-port/references/captures.md +7 -0
  70. package/dist/skills/ads-port/references/drafts.md +146 -0
  71. package/dist/skills/ads-port/references/guarded-editing.md +6 -0
  72. package/dist/skills/ads-port/references/native-implementation.md +14 -1
  73. package/dist/skills/ads-port/references/validation.md +6 -0
  74. package/dist/unit-contracts.mjs +2 -2
  75. package/dist/units.mjs +6 -0
  76. package/dist/verification/browser.d.mts +27 -0
  77. package/dist/verification.mjs +3 -0
  78. package/docs/ADS.md +13 -0
  79. package/docs/ARCHITECTURE.md +94 -0
  80. package/docs/CHANGELOG.md +111 -0
  81. package/docs/CONTRACTS.md +8 -0
  82. package/docs/GUIDE.md +46 -9
  83. package/docs/MCP.md +90 -0
  84. package/package.json +6 -4
@@ -1,6 +1,7 @@
1
- export const reasoning = `ADS is development tooling. The project owns its components, patterns, token values and branding.
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.
2
+ ADS is development tooling. The project owns its components, patterns, token values and branding.
2
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.
3
- 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 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
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.
5
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.
6
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.
@@ -1,4 +1,4 @@
1
- import { existsSync, readFileSync, statSync } from "node:fs";
1
+ import { existsSync, readFileSync, statSync, watch } from "node:fs";
2
2
  import path from "node:path";
3
3
  import { Server, ProtocolError, INVALID_PARAMS, ResourceNotFoundError } from "@modelcontextprotocol/server";
4
4
  import { serveStdio, StdioServerTransport } from "@modelcontextprotocol/server/stdio";
@@ -10,7 +10,7 @@ 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 { inspectScenarios } from "../scenarios.mjs";
13
+ import { discoverScenarioRegistry } from "../scenario-registry.mjs";
14
14
  import { scenarioGroupFingerprint } from "../scenario-groups.mjs";
15
15
  import { startShowcaseHost } from "./showcase-host.mjs";
16
16
  import { createSkillStore, page, SKILLS_EXTENSION } from "./skills.mjs";
@@ -28,12 +28,16 @@ import { reconcileTokenSamples } from "../token-fixtures.mjs";
28
28
  import { createCaptureController } from "../capture.mjs";
29
29
  import { CAPTURES_URI, captureSpec, screenshotFields } from "../capture-store.mjs";
30
30
  import { previewSourceRevision } from "../preview-inputs.mjs";
31
+ import { inspectBehaviorLibraries } from "../behavior-libraries.mjs";
31
32
  import { createExecutionResults, RESULTS_URI, resultSections } from "./execution-results.mjs";
32
33
  import { behaviorPage, behaviorSections } from "./behavior-pages.mjs";
33
34
  import { compactProgress, resultBudgets } from "./result-pages.mjs";
34
35
  import { createReportStore, bugReportSchema, featureRequestSchema } from "./reports.mjs";
35
36
  import { createHash } from "node:crypto";
36
37
  import { developmentRuntime } from "../development-runtime.mjs";
38
+ import { createDraftController, DRAFTS_URI, draftIdSchema, draftRevisionSchema } from "./drafts.mjs";
39
+ import { isDraftPreviewWorkspace } from "../draft-workspace.mjs";
40
+ import { isDraftFile } from "../draft-boundary.mjs";
37
41
 
38
42
  const pkg = JSON.parse(readFileSync(new URL("../../package.json", import.meta.url), "utf8"));
39
43
  class InvalidParamsError extends ProtocolError {
@@ -60,12 +64,17 @@ function resourceQuery(uri, allowed) {
60
64
  return Object.fromEntries([...url.searchParams].map(([key,value])=>[key,["limit","recordIndex","offset","chars"].includes(key)?Number(value):value]));
61
65
  }
62
66
 
63
- export function createAdsMcp(directory, { era = "legacy", skillDirectory, pollInterval = 1000, observeChanges = true, previewWatch, showcaseUrl, notifications, inspection, mutations = false } = {}) {
67
+ export function createAdsMcp(directory, { era = "legacy", skillDirectory, pollInterval = 1000, observeChanges = true, previewWatch, showcaseUrl, notifications, inspection, mutations = false, onBuildChange } = {}) {
64
68
  const root = path.resolve(directory);
69
+ let observationClosed = false;
65
70
  const cache = inspection ?? {};
66
71
  const skills = cache.skills ??= createSkillStore(skillDirectory);
67
72
  const captures = cache.captures ??= createCaptureController(root);
68
73
  const edits = cache.edits ??= createMutationController(root, { captures });
74
+ const draftObservers = cache.draftObservers ??= new Set();
75
+ const drafts = cache.drafts ??= createDraftController(root, { edits, prewarm: true,
76
+ onChange: () => { for (const observer of draftObservers) void observer().catch(error => { process.stderr.write(`ads mcp: ${error.message}\n`); }); },
77
+ startPreview: workspace => startAdsMcp(workspace, { stdio: false, mutations: false }) });
69
78
  const verification = cache.verification ??= createVerificationController(root);
70
79
  const validation = cache.validation ??= createValidationController(root);
71
80
  const executionResults = cache.executionResults ??= createExecutionResults(root);
@@ -74,6 +83,7 @@ export function createAdsMcp(directory, { era = "legacy", skillDirectory, pollIn
74
83
  const signature = `${root}:${JSON.stringify(options.config)}`;
75
84
  if (cache.signature !== signature) {
76
85
  cache.signature = signature;
86
+ cache.behaviorLibraries = undefined;
77
87
  cache.registry = cache.catalog = cache.documents = undefined;
78
88
  }
79
89
  const getShowcaseUrl = () => showcaseUrl?.() ?? options.config.mcp.showcaseUrl;
@@ -88,19 +98,28 @@ export function createAdsMcp(directory, { era = "legacy", skillDirectory, pollIn
88
98
  const project = () => { const context = projectContext(options); context.showcase.url = getShowcaseUrl(); return context; };
89
99
  const subscribed = new Set();
90
100
  const server = new Server({ name: "reqvire-ads", version: pkg.version }, {
91
- instructions: `${serverInstructions} ${mutations ? "Guarded editing is 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."}`,
101
+ 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."}`,
92
102
  capabilities: { tools: { listChanged: true }, resources: { listChanged: true, subscribe: true }, prompts: {},
93
103
  extensions: { "io.modelcontextprotocol/ui": { mimeTypes: [APP_MIME] }, ...(era === "modern" ? { [SKILLS_EXTENSION]: { directoryRead: true } } : {}) } },
94
104
  });
95
- const getRegistry = () => { cache.registry ??= inspectScenarios(options); cache.lastRegistry = cache.registry; return cache.registry; };
105
+ const getRegistry = () => {
106
+ const current = loadConfig(root), revision = previewSourceRevision(current);
107
+ if (!cache.registry || cache.registryRevision !== revision) {
108
+ cache.registry = discoverScenarioRegistry(current); cache.registryRevision = revision; cache.catalog = undefined; cache.behaviorLibraries = undefined;
109
+ }
110
+ cache.lastRegistry = cache.registry; return cache.registry;
111
+ };
96
112
  const previewRegistry = waitFor => waitFor === "compiled" ? cache.registry ?? cache.lastRegistry ?? getRegistry() : getRegistry();
97
113
  function captureInventory() {
98
- const current = loadConfig(root), registry = inspectScenarios(current);
114
+ const current = loadConfig(root), registry = getRegistry();
99
115
  return { ...registry, revision: previewSourceRevision(current) };
100
116
  }
101
117
  function captureIndex() { const inventory = captureInventory(); return captures.store.list(inventory.scenarios, inventory.revision, { prune: !inventory.diagnostics.length }); }
102
118
  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 }));
103
- const tokenScenarios = () => getRegistry().scenarios.filter(item => item.kind === "tokens").map(item => ({ id: item.id, title: item.title, count: item.tokens.length }));
119
+ const tokenScenarios = () => {
120
+ const references=drafts.list({unit:"tokens",limit:100000}).drafts.map(({id,title,revision,state,preview})=>({id,title,revision,state,preview}));
121
+ return getRegistry().scenarios.filter(item => item.kind === "tokens").map(item => ({ id:item.id,title:item.title,count:item.tokens.length,drafts:references }));
122
+ };
104
123
  const allApps = (quick = false) => [...options.config.mcp.apps, ...scenarioApps(quick)];
105
124
  const scenarioWidget = () => options.config.mcp.previewManifest ? PREVIEW_APP_URI : SCENARIO_APP_URI;
106
125
  const previewOptions = () => withPreviewSession(options, previewWatch?.resourceSession?.());
@@ -115,11 +134,20 @@ export function createAdsMcp(directory, { era = "legacy", skillDirectory, pollIn
115
134
  if (!manifest?.scenarios.some(entry => entry.id === id)) throw new Error("The preview resource graph is not ready for this scenario. Rebuild previews.");
116
135
  return { manifestUri: live ? LIVE_PREVIEW_MANIFEST_URI : PREVIEW_MANIFEST_URI, manifestRevision: manifest.revision };
117
136
  }
118
- const getCatalog = () => cache.catalog ??= inspectCatalog(options, getRegistry().scenarios);
137
+ const getCatalog = () => { const registry = getRegistry(); return cache.catalog ??= inspectCatalog(loadConfig(root), registry.scenarios, getBehaviorLibraries()); };
138
+ const getBehaviorLibraries = () => cache.behaviorLibraries ??= inspectBehaviorLibraries(loadConfig(root));
139
+ function annotateDrafts(items) {
140
+ const found = drafts.list({limit:100000}).drafts, units = edits.units();
141
+ return items.map(item => {
142
+ const unit = units.find(unit => unit.files.includes(item.file))?.id ?? null;
143
+ return { ...item, unit, drafts: found.filter(draft => draft.units.includes(unit)).map(({id,title,revision,state,preview}) => ({id,title,revision,state,preview})) };
144
+ });
145
+ }
119
146
  const getDocuments = () => cache.documents ??= projectDocuments(options);
120
147
  const builds = () => {
121
148
  previewWatch?.setApps(allApps(true));
122
- return previewWatch?.buildStatus() ?? inspectBuildStatus(root, { ...options.config.mcp, apps: allApps(true) });
149
+ const report = previewWatch?.buildStatus() ?? inspectBuildStatus(root, { ...options.config.mcp, apps: allApps(true) });
150
+ return { ...report, drafts: drafts.previewStatuses() };
123
151
  };
124
152
  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 }));
125
153
 
@@ -169,6 +197,9 @@ export function createAdsMcp(directory, { era = "legacy", skillDirectory, pollIn
169
197
  { uri: BUILD_URI, name: "Preview build status and diagnostics", mimeType: "application/json" },
170
198
  { uri: `${PROJECT_URI}/tokens`, name: "Project token values and themes", mimeType: "application/json" },
171
199
  { uri: `${PROJECT_URI}/catalog`, name: "Public components and patterns", mimeType: "application/json" },
200
+ { uri: DRAFTS_URI, name: "Tracked ADS drafts and acceptance events", mimeType: "application/json" },
201
+ ...drafts.previewStatuses().map(({ id, resourceUri }) => ({ uri: resourceUri, name: `Draft ${id}: preview build status and diagnostics`, mimeType: "application/json" })),
202
+ { uri: "ads://guides/drafts", name: "Auto-mode tracked draft workflow", mimeType: "text/markdown" },
172
203
  { uri: `${PROJECT_URI}/scenarios`, name: "Independently mountable scenarios", mimeType: "application/json" },
173
204
  { uri: BEHAVIOR_URI, name: "Behavior contracts, demonstrations and current verification evidence", mimeType: "application/json" },
174
205
  { uri: RESULTS_URI, name: "Latest execution summaries and paged outcomes", mimeType: "application/json" },
@@ -191,16 +222,18 @@ export function createAdsMcp(directory, { era = "legacy", skillDirectory, pollIn
191
222
  }
192
223
  function status() {
193
224
  const context = project(), mutationState = mutations ? edits.status() : null, behaviorState = verification.status();
194
- return { projectRoot: root, workflow: workflow([...previews(), ...scenarioApps()]), project: context,
195
- package: pkg.name, version: pkg.version, dsDir: options.config.dsDir, publicAlias: options.config.publicAlias,
196
- components: getCatalog().filter((item) => item.kind === "components" && item.apiKind === "ui").length,
197
- patterns: getCatalog().filter((item) => item.kind === "patterns" && item.apiKind === "ui").length,
225
+ const catalog = getCatalog(), registry = cache.registry;
226
+ return { projectRoot: root, workflow: workflow([...previews(), ...scenarioApps(true)]), project: context,
227
+ package: pkg.name, version: pkg.version, dsDir: options.config.dsDir, publicAlias: options.config.publicAlias, behaviorLibraries: getBehaviorLibraries().libraries,
228
+ components: catalog.filter((item) => item.kind === "components" && item.apiKind === "ui").length,
229
+ patterns: catalog.filter((item) => item.kind === "patterns" && item.apiKind === "ui").length,
198
230
  tokenCount: inspectTokens(root).tokens.length, showcaseUrl: getShowcaseUrl(),
199
231
  previewWatch: previewWatch?.status() ?? { state: "disabled" },
200
232
  mutations: mutations ? { ...mutationState, progress: compactProgress(mutationState.progress), lastResult: executionResults.latest("mutation") } : { enabled: false },
233
+ 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) },
201
234
  build: summarizeBuild(builds()),
202
235
  previews: previews(), skills: skills.skills.map(({ uri, frontmatter }) => ({ uri, name: frontmatter.name, description: frontmatter.description })),
203
- scenarios: { count: getRegistry().scenarios.length, diagnostics: getRegistry().diagnostics, resourceUri: `${PROJECT_URI}/scenarios`, tool: "ads_show_scenario" },
236
+ scenarios: { count: registry.scenarios.length, diagnostics: registry.diagnostics, resourceUri: `${PROJECT_URI}/scenarios`, tool: "ads_show_scenario" },
204
237
  validation: { ...validation.status(), tool: "ads_validate", lastResult: executionResults.latest("validation") },
205
238
  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 },
206
239
  captures: { resourceUri: CAPTURES_URI, tool: "ads_capture", clearTool: "ads_capture_clear", ...captures.status() },
@@ -208,6 +241,12 @@ export function createAdsMcp(directory, { era = "legacy", skillDirectory, pollIn
208
241
  experimental: { apps: true, nativeSkills: era === "modern", nativeSkillActivation: "host-controlled" } };
209
242
  }
210
243
  async function read(uri, signal) {
244
+ if(uri.startsWith("ads://drafts/")){
245
+ const url=new URL(uri),match=url.pathname.match(/^\/([a-z0-9][a-z0-9-]{0,79})\/resource$/);
246
+ if(!match||[...url.searchParams.keys()].some(key=>key!=="uri")||!url.searchParams.get("uri"))throw new Error("Invalid draft resource address.");
247
+ return drafts.readResource(match[1],url.searchParams.get("uri"),signal);
248
+ }
249
+ 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")}] };
211
250
  if (uri === GUIDE_URI) return { contents: [{ uri, mimeType: "text/markdown", text: projectGuide(project(), [...previews(), ...scenarioApps()]) }] };
212
251
  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") }] };
213
252
  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") }] };
@@ -226,7 +265,8 @@ export function createAdsMcp(directory, { era = "legacy", skillDirectory, pollIn
226
265
  if (uri === `${PROJECT_URI}/status`) value = status();
227
266
  else if (uri === BUILD_URI) value = builds();
228
267
  else if (uri === `${PROJECT_URI}/tokens`) value = tokenWidgetData(inspectTokens(root));
229
- else if (uri === `${PROJECT_URI}/catalog`) value = { items: getCatalog() };
268
+ else if (uri === `${PROJECT_URI}/catalog`) value = { items: annotateDrafts(getCatalog()) };
269
+ else if (uri === DRAFTS_URI) value = drafts.list();
230
270
  else if (uri === `${PROJECT_URI}/scenarios`) value = getRegistry();
231
271
  else if (uri === `${PROJECT_URI}/checks`) value = checkProject(root);
232
272
  else if (uri === BEHAVIOR_URI || uri.startsWith(`${BEHAVIOR_URI}?`)) value = behaviorPage(options, resourceQuery(uri, ["unit", "api", "query", "section", "cursor", "limit"]));
@@ -308,20 +348,49 @@ export function createAdsMcp(directory, { era = "legacy", skillDirectory, pollIn
308
348
  }
309
349
  function tools() {
310
350
  return [
311
- { 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 guarded ads_apply_patch for ADS edits; otherwise use local editing tools.", schema: empty, call: () => json(status()) },
312
- { name: "ads_capture", title: "Capture a design-system scenario", description: "Capture one discovered scenario or its named captureTargets element inside the real MCP App iframe, excluding showcase navigation. Uses project-local Playwright/browser and an isolated host; installs nothing. Returns PNG resource URIs and source/build/settings metadata, never image bytes in text. Successful standalone capture replaces current and clears a prior candidate for that target. No screenshots are created until requested. Inspect ads://project/captures for stale/current evidence. Appearance is not behavior verification.", schema: captureSpec, annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: false, openWorldHint: false }, call: async (args, signal, progress) => {
313
- const result = await captures.run({ captures: [args] }, signal, progress); await refresh(); return captureResponse(result, era === "modern");
351
+ { 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)) },
352
+ { 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=>{
353
+ const value=await drafts.show(args),base=getShowcaseUrl();
354
+ let comparisonUrl=null;
355
+ 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;}
356
+ return json({...value,isolatedShowcaseUrl:value.showcaseUrl,showcaseUrl:comparisonUrl??value.showcaseUrl,comparisonUrl});
357
+ } },
358
+ ...(mutations ? [
359
+ { name:"ads_create_draft", description:"Create a Git-committable proposal under ads-drafts/ for 1–8 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(8),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);} },
360
+ { 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);} },
361
+ { 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);} },
362
+ { 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)=>{
363
+ if(validation.status().busy||verification.status().running)throw new Error("Wait for validation/verification before acceptance.");
364
+ const result=await drafts.accept(args,signal,progress);
365
+ if(result.applied){await previewWatch?.invalidate?.();await refresh(true);}else await refresh();
366
+ return finishExecution("mutation",result);
367
+ } },
368
+ ] : []),
369
+ { 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()) },
370
+ { 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) => {
371
+ let result;
372
+ if(draft){
373
+ const proposal=drafts.prepare(draft);
374
+ if(proposal.revision!==revision)throw new Error("Draft revision changed. Reopen its preview before capturing.");
375
+ const acceptedHost=getShowcaseUrl()?{url:getShowcaseUrl(),previewRevision:()=>readPreviewManifest(previewOptions())?.revision??null}:null;
376
+ const captured=await captures.run({captures:[selection],candidateRoot:proposal.session.workspace,proposal:revision,publish:false,previewHosts:[acceptedHost,proposal.session.runtime]},signal,progress);
377
+ if(drafts.inspect(draft).revision!==revision)throw new Error("Draft changed during capture; no image slots were replaced.");
378
+ captures.store.commit(captured.records);
379
+ const inventory=captureInventory(),keys=new Set(captured.records.map(record=>record.key));
380
+ result={ok:true,draft,draftRevision:revision,previewOnly:true,captures:captures.store.list(inventory.scenarios,inventory.revision).captures.filter(record=>keys.has(record.key))};
381
+ }else result=await captures.run({captures:[selection]},signal,progress);
382
+ await refresh(); return captureResponse(result, era === "modern");
314
383
  } },
315
384
  { 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); } },
316
385
  { 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 }) => {
317
386
  const matches = getCatalog().filter((item) => (!kind || item.kind === kind) && item.name.toLowerCase().includes(search.toLowerCase()));
318
- const units = edits.units();
319
- return json({ total: matches.length, items: matches.slice(0, limit).map(item => ({ ...item, unit: units.find(unit => unit.files.includes(item.file))?.id ?? null })), resourceUri: `${PROJECT_URI}/catalog` });
387
+ return json({ total: matches.length, items: annotateDrafts(matches.slice(0, limit)), resourceUri: `${PROJECT_URI}/catalog` });
320
388
  } },
321
389
  { 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 }) => {
322
- const matches = getRegistry().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()));
323
- const units = edits.units();
324
- return json({ total: matches.length, scenarios: matches.slice(offset, offset + limit).map(item => ({ ...item, unit: units.find(unit => unit.files.includes(item.file))?.id ?? null })), ...(offset + limit < matches.length ? { nextOffset: offset + limit } : {}), diagnostics: getRegistry().diagnostics, resourceUri: `${PROJECT_URI}/scenarios` });
390
+ const registry = getRegistry();
391
+ 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()));
392
+ const report = builds(), states = new Map(report.previews.map(item => [item.id, item]));
393
+ 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` });
325
394
  } },
326
395
  { 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) => {
327
396
  const registry = previewRegistry(waitFor);
@@ -337,7 +406,7 @@ export function createAdsMcp(directory, { era = "legacy", skillDirectory, pollIn
337
406
  { 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 }) => {
338
407
  const inventory = inspectTokens(root);
339
408
  const matches = inventory.tokens.filter((token) => token.name.toLowerCase().includes(search.toLowerCase()));
340
- return json({ total: matches.length, tokens: matches.slice(0, limit), categories: tokenScenarios(), diagnosticCount: inventory.diagnostics.length, resourceUri: `${PROJECT_URI}/tokens` });
409
+ return json({ total: matches.length, tokens: matches.slice(0, limit), categories: tokenScenarios(), tokenGroups:drafts.tokenGroups(), diagnosticCount: inventory.diagnostics.length, resourceUri: `${PROJECT_URI}/tokens` });
341
410
  } },
342
411
  { name: "ads_check", description: "Run read-only core ADS architecture checks; returns blocking diagnostics separately from nonblocking advisories, with warnings before informational limits. Atomic warnings 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) }).strict(), call: ({ limit }) => {
343
412
  const result = checkProject(root);
@@ -388,7 +457,7 @@ export function createAdsMcp(directory, { era = "legacy", skillDirectory, pollIn
388
457
  const matches = edits.units().filter(item => unit ? item.id === unit : item.id.toLowerCase().includes(search.toLowerCase()));
389
458
  return json({ total: matches.length, units: matches.slice(0, limit).map(item => ({ id: item.id, kind: item.kind, fileCount: item.files.length, ...(unit ? { files: item.files.slice(0, 200), filesTruncated: item.files.length > 200, ...(item.companionFiles ? { companionFiles: item.companionFiles } : {}), ...(item.filePolicy ? { filePolicy: item.filePolicy } : {}) } : {}) })) });
390
459
  } },
391
- { 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(edits.read(file, range)) },
460
+ { 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)) },
392
461
  ...(mutations ? [{ name: "ads_prepare_patch", description: "Prepare a Git patch without a separate project mirror. Create copies only one owner plus its declared companions into a local draft; edit that directory with local file tools. Diff checks baseline/source freshness and owner paths, then writes a patchFile under .ds/patches. Migrate prepares mechanical .ads. role names and legacy contracts in that draft, retaining unresolved sections for review. Discard removes the draft. Live source is never changed; ads_apply_patch still validates all gates. Remote clients can continue sending inline Git diffs instead.", schema:z.object({unit:z.string().min(1).max(256),action:z.enum(["create","migrate","diff","discard"]).default("create"),draft:z.string().max(100).optional()}).strict(), call:args=>json(prepareUnitPatch(options,args)) },
393
462
  {name:"ads_prepare_token_samples",description:"Reconcile a token scenario's consumed literal fixture samples. Removes undeclared tokens, preserves existing project bindings, and accepts explicit real-token/property/probe bindings. Reports unresolved token names; never guesses CSS meaning from token names. Returns an owner patchFile without changing source. Apply it through ads_apply_patch and review the real preview.",schema:z.object({id:z.string().min(1).max(256),bindings:z.array(z.object({token:z.string().max(256),property:z.string().max(100),probe:z.string().max(1000)}).passthrough()).max(1000).optional()}).strict(),call:args=>{
394
463
  const {patch,...result}=reconcileTokenSamples(options,args);
@@ -434,6 +503,7 @@ export function createAdsMcp(directory, { era = "legacy", skillDirectory, pollIn
434
503
  return { resources: listing.items, ...(listing.nextCursor ? { nextCursor: listing.nextCursor } : {}) };
435
504
  });
436
505
  server.setRequestHandler("resources/templates/list", () => ({ resourceTemplates: [
506
+ { 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" },
437
507
  { 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" },
438
508
  { 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" },
439
509
  { 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" },
@@ -484,7 +554,9 @@ export function createAdsMcp(directory, { era = "legacy", skillDirectory, pollIn
484
554
  };
485
555
  const artifactFingerprint = () => fileFingerprint(allApps(true).map(app => path.resolve(root, previewArtifactPath(previewOptions(), app.file))));
486
556
  const assetFingerprint = () => resourceAssets().map(asset => asset.uri).sort().join("\n");
487
- let previous, previousArtifacts, previousAssets, previousBuild, previousCaptures, previousCaptureUris;
557
+ let previous, previousArtifacts, previousAssets, previousBuild, previousCaptures, previousCaptureUris, previousDrafts;
558
+ let previousDraftBuilds = new Map();
559
+ const draftBuilds = () => new Map(drafts.previewStatuses().map(build => [build.resourceUri, JSON.stringify(build)]));
488
560
  const investigationFingerprint=()=>fileFingerprint([path.join(root,".ds/investigations.json")]);
489
561
  let previousInvestigations, previousResults, observing=false;
490
562
  function initializeObservation() {
@@ -492,12 +564,32 @@ export function createAdsMcp(directory, { era = "legacy", skillDirectory, pollIn
492
564
  previous=fingerprint();previousArtifacts=artifactFingerprint();previousAssets=assetFingerprint();previousBuild=JSON.stringify(builds());
493
565
  previousCaptures=captures.store.fingerprint();previousCaptureUris=captures.store.resourceUris();
494
566
  previousInvestigations=investigationFingerprint();previousResults=executionResults.fingerprint();observing=true;
567
+ previousDrafts=drafts.fingerprint();
568
+ previousDraftBuilds=draftBuilds();
495
569
  }
496
570
  // Modern HTTP serves a fresh protocol instance per request. Its shared observer
497
571
  // already tracks changes; immutable byte reads need no source/build scan.
498
572
  if (observeChanges) initializeObservation();
499
573
  let deferredDiscovery = false;
500
- async function refresh(force = false) {
574
+ let refreshing, refreshAgain = false, refreshForced = false;
575
+ function refresh(force = false) {
576
+ if (observationClosed) return Promise.resolve(false);
577
+ // Stateless HTTP handlers share the persistent observer. Starting their own
578
+ // observation after every mutation would force a false source change and
579
+ // throw away accepted discovery/capture caches on each draft edit.
580
+ if (!observeChanges) return Promise.all([...draftObservers].map(observer => observer(force))).then(values => values.some(Boolean));
581
+ refreshAgain = true; refreshForced ||= force;
582
+ return refreshing ??= Promise.resolve().then(async () => {
583
+ let changed = false;
584
+ while (refreshAgain && !observationClosed) {
585
+ refreshAgain = false;
586
+ const forced = refreshForced; refreshForced = false;
587
+ changed = await refreshOnce(forced) || changed;
588
+ }
589
+ return changed;
590
+ }).finally(() => { refreshing = undefined; });
591
+ }
592
+ async function refreshOnce(force) {
501
593
  if (!observing) { initializeObservation();force=true; }
502
594
  // Polling covers replaced files and new directories consistently across OSes.
503
595
  cache.documents = undefined;
@@ -507,19 +599,26 @@ export function createAdsMcp(directory, { era = "legacy", skillDirectory, pollIn
507
599
  const build = JSON.stringify(builds());
508
600
  const filesChanged = force || next !== previous;
509
601
  const buildChanged = build !== previousBuild;
602
+ if (buildChanged) onBuildChange?.(JSON.parse(build));
510
603
  const artifactsChanged = artifacts !== previousArtifacts;
511
604
  const assetsChanged = assets !== previousAssets;
512
605
  const capturesChanged = captures.store.fingerprint() !== previousCaptures;
513
606
  const investigationsChanged=investigationFingerprint()!==previousInvestigations;
514
607
  const resultsChanged=executionResults.fingerprint()!==previousResults;
515
- if (!filesChanged && !buildChanged && !artifactsChanged && !assetsChanged && !capturesChanged && !investigationsChanged && !resultsChanged && !deferredDiscovery) return false;
608
+ const draftFingerprint=drafts.fingerprint(),draftsChanged=draftFingerprint!==previousDrafts;
609
+ const currentDraftBuilds=draftBuilds();
610
+ const changedDraftBuilds=[...new Set([...previousDraftBuilds.keys(),...currentDraftBuilds.keys()])].filter(uri=>previousDraftBuilds.get(uri)!==currentDraftBuilds.get(uri));
611
+ const draftResourcesChanged=[...previousDraftBuilds.keys()].some(uri=>!currentDraftBuilds.has(uri)) || [...currentDraftBuilds.keys()].some(uri=>!previousDraftBuilds.has(uri));
612
+ if (!filesChanged && !buildChanged && !artifactsChanged && !assetsChanged && !capturesChanged && !investigationsChanged && !resultsChanged && !draftsChanged && !deferredDiscovery) return false;
516
613
  if (filesChanged) {
517
614
  const updated = loadConfig(root);
518
615
  await previewWatch?.reconfigure?.(updated.config.mcp);
616
+ if (observationClosed) return false;
519
617
  const appsChanged = JSON.stringify(updated.config.mcp.apps) !== JSON.stringify(options.config.mcp.apps) || updated.config.mcp.previewManifest !== options.config.mcp.previewManifest;
520
618
  options = updated;
521
619
  cache.signature = `${root}:${JSON.stringify(options.config)}`;
522
620
  cache.catalog = undefined;
621
+ cache.behaviorLibraries = undefined;
523
622
  cache.registry = undefined;
524
623
  previous = fingerprint();
525
624
  if (appsChanged) { if (notifications) notifications.toolsChanged(); else await server.sendToolListChanged(); }
@@ -530,12 +629,15 @@ export function createAdsMcp(directory, { era = "legacy", skillDirectory, pollIn
530
629
  deferredDiscovery ||= filesChanged;
531
630
  const discoveryChanged = deferredDiscovery && !checking;
532
631
  if (discoveryChanged) deferredDiscovery = false;
533
- if (discoveryChanged || assetsChanged) { if (notifications) notifications.resourcesChanged(); else await server.sendResourceListChanged(); }
632
+ if (discoveryChanged || assetsChanged || draftResourcesChanged) { if (notifications) notifications.resourcesChanged(); else await server.sendResourceListChanged(); }
534
633
  previousArtifacts = artifactFingerprint();
535
634
  previousAssets = assetFingerprint();
536
635
  previousBuild = JSON.stringify(builds());
537
- const targets = discoveryChanged ? era === "modern" ? resources().map((entry) => entry.uri).filter((uri) => !skills.files.has(uri)) : [...subscribed]
538
- : [BUILD_URI, BEHAVIOR_URI, INVESTIGATIONS_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));
636
+ const targets = discoveryChanged ? (era === "modern" ? resources().map((entry) => entry.uri).filter((uri) => !skills.files.has(uri)) : [...subscribed]).filter(uri => !uri.startsWith("ads://drafts/"))
637
+ : [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));
638
+ if(draftsChanged){targets.push(...[DRAFTS_URI,`${PROJECT_URI}/catalog`,`${PROJECT_URI}/scenarios`,`${PROJECT_URI}/status`].filter(uri=>era==="modern"||subscribed.has(uri)));previousDrafts=draftFingerprint;}
639
+ targets.push(...changedDraftBuilds.filter(uri=>era==="modern"||subscribed.has(uri)));
640
+ previousDraftBuilds=currentDraftBuilds;
539
641
  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();}
540
642
  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();}
541
643
  if (capturesChanged || discoveryChanged) {
@@ -544,14 +646,28 @@ export function createAdsMcp(directory, { era = "legacy", skillDirectory, pollIn
544
646
  previousCaptureUris = current;
545
647
  previousCaptures = captures.store.fingerprint();
546
648
  }
547
- for (const uri of new Set(targets)) { if (notifications) notifications.resourceUpdated(uri); else await server.sendResourceUpdated({ uri }); }
649
+ for (const uri of new Set(targets)) {
650
+ if (observationClosed) return false;
651
+ if (notifications) notifications.resourceUpdated(uri); else await server.sendResourceUpdated({ uri });
652
+ }
548
653
  return true;
549
654
  }
550
- const timer = pollInterval > 0 ? setInterval(() => { refresh().catch((error) => process.stderr.write(`ads mcp: ${error.message}\n`)); }, pollInterval) : null;
655
+ const timer = pollInterval > 0 ? setInterval(() => { if (!observationClosed) refresh().catch(error => { if (!observationClosed) process.stderr.write(`ads mcp: ${error.message}\n`); }); }, pollInterval) : null;
551
656
  timer?.unref();
657
+ if (observeChanges) draftObservers.add(refresh);
658
+ const stopObservation = () => { observationClosed = true; draftObservers.delete(refresh); if (timer) clearInterval(timer); };
552
659
  server.oninitialized = () => previewWatch?.start();
553
- server.onclose = () => { if (timer) clearInterval(timer); };
554
- return { server, refresh, async close() { if (timer) clearInterval(timer); if (!inspection) { await validation.close(); await verification.close(); await captures.close(); } await server.close(); } };
660
+ server.onclose = stopObservation;
661
+ async function warmScenarios(ids, signal) {
662
+ if (!previewWatch) return;
663
+ const apps = allApps(), selected = new Set(ids);
664
+ const files = apps.filter(app => selected.has(app.id)).map(app => path.resolve(root, app.file));
665
+ if (files.length !== selected.size) throw new Error("Cannot warm an unknown verification scenario.");
666
+ previewWatch.setApps(apps);
667
+ await previewWatch.warm(files);
668
+ for (const file of files) await previewWatch.ensure(file, signal);
669
+ }
670
+ return { server, refresh, warmScenarios, 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(); } };
555
671
  }
556
672
 
557
673
  export async function startAdsMcp(directory = process.cwd(), { stdio = true, showcase = true, port = 0, mutations = false } = {}) {
@@ -559,18 +675,35 @@ export async function startAdsMcp(directory = process.cwd(), { stdio = true, sho
559
675
  const { root, config } = loadConfig(directory);
560
676
  const inspection = { skills: createSkillStore() };
561
677
  const previewWatch = createReconfigurablePreviewWatch(root, config.mcp);
562
- let host;
678
+ let host, api;
679
+ let buildWatcher, buildChangeTimer;
680
+ const buildListeners = new Set();
681
+ const onBuildChange = report => { for (const listener of buildListeners) listener(report); };
563
682
  const showcaseUrl = () => host?.url;
564
683
  if (showcase) {
565
684
  host = await startShowcaseHost(({ era }) => createAdsMcp(directory, { era, previewWatch, showcaseUrl, inspection, mutations, pollInterval: 0, observeChanges:false }).server,
566
- { port, observe: notifications => createAdsMcp(directory, { era: "modern", previewWatch, showcaseUrl, inspection, mutations, notifications }) });
685
+ { port, observe: notifications => createAdsMcp(directory, { era: "modern", previewWatch, showcaseUrl, inspection, mutations, notifications, onBuildChange }) });
567
686
  process.stderr.write(`ADS showcase: ${host.url}\n`);
568
687
  }
569
688
  const transport = stdio ? new StdioServerTransport() : null;
570
- const handle = stdio ? serveStdio(({ era }) => createAdsMcp(directory, { era, previewWatch, showcaseUrl, inspection, mutations }).server, { transport, legacy: "serve", onerror: (error) => process.stderr.write(`ads mcp: ${error.message}\n`) }) : null;
689
+ const handle = stdio ? serveStdio(({ era }) => createAdsMcp(directory, { era, previewWatch, showcaseUrl, inspection, mutations, onBuildChange }).server, { transport, legacy: "serve", onerror: (error) => process.stderr.write(`ads mcp: ${error.message}\n`) }) : null;
690
+ try {
691
+ buildWatcher = watch(path.join(root, ".ds"), (_event, file) => {
692
+ const selected = previewWatch.resourceSession();
693
+ if (String(file) !== (selected ? `build-status-${selected}.json` : "build-status.json")) return;
694
+ clearTimeout(buildChangeTimer);
695
+ buildChangeTimer = setTimeout(() => {
696
+ try { onBuildChange(previewWatch.buildStatus()); } catch { /* The polling observer retries transient writes. */ }
697
+ for (const refresh of inspection.draftObservers ?? []) void refresh().catch(() => {});
698
+ }, 16); buildChangeTimer.unref();
699
+ });
700
+ buildWatcher.unref(); buildWatcher.on("error", () => { buildWatcher.close(); });
701
+ } catch { /* Periodic observation also covers replaced/missing report directories. */ }
571
702
  let closing;
572
703
  function close() {
573
704
  return closing ??= (async () => {
705
+ buildListeners.clear();
706
+ clearTimeout(buildChangeTimer); buildWatcher?.close();
574
707
  inspection.edits?.cancel();
575
708
  // Stop every owned resource even if another close fails or has in-flight RPCs.
576
709
  const results = await Promise.allSettled([
@@ -579,6 +712,8 @@ export async function startAdsMcp(directory = process.cwd(), { stdio = true, sho
579
712
  Promise.resolve().then(() => inspection.validation?.close()),
580
713
  Promise.resolve().then(() => inspection.verification?.close()),
581
714
  Promise.resolve().then(() => inspection.captures?.close()),
715
+ Promise.resolve().then(() => inspection.drafts?.close()),
716
+ Promise.resolve().then(() => api?.close()),
582
717
  Promise.resolve().then(() => handle?.close()),
583
718
  ]);
584
719
  for (const event of ["end", "close", "error"]) process.stdin.removeListener(event, disconnect);
@@ -601,5 +736,9 @@ export async function startAdsMcp(directory = process.cwd(), { stdio = true, sho
601
736
  }
602
737
  for (const signal of ["SIGINT", "SIGTERM"]) process.once(signal, disconnect);
603
738
  process.once("exit", forceCleanup);
604
- return { close, url: host?.url, previewRevision: () => readPreviewManifest(withPreviewSession(loadConfig(root), previewWatch.resourceSession()))?.revision ?? null };
739
+ const previewApi=()=>api??=createAdsMcp(root,{era:"modern",inspection,previewWatch,showcaseUrl,mutations:false,pollInterval:0,observeChanges:false});
740
+ return { close, url: host?.url, warmScenarios: (ids, signal) => previewApi().warmScenarios(ids, signal), prewarm: () => previewWatch.initialize(), onBuildChange(listener) { buildListeners.add(listener); return () => buildListeners.delete(listener); }, buildStatus: () => previewWatch.buildStatus(), primeRegistry(registry) {
741
+ if (inspection.registry === registry || inspection.lastRegistry === registry) return;
742
+ inspection.registry = inspection.lastRegistry = registry; inspection.registryRevision = undefined; inspection.catalog = undefined;
743
+ }, 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 };
605
744
  }