@reqvire-org/ads 0.3.35 → 0.3.37
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.
- package/README.md +10 -8
- package/dist/bootstrap-ds/README.md +8 -9
- package/dist/bootstrap-ds/ds.config.json +1 -8
- package/dist/bootstrap-ds/package.json +4 -3
- package/dist/bootstrap-ds/scripts/build-mcp-previews.mjs +2 -32
- package/dist/bun-compiler.mjs +13 -0
- package/dist/bun-worker.mjs +9 -0
- package/dist/check.mjs +7 -4
- package/dist/cli.mjs +11 -7
- package/dist/config.mjs +22 -4
- package/dist/development-runtime.mjs +3 -1
- package/dist/init.mjs +16 -18
- package/dist/mcp/build-status.mjs +6 -4
- package/dist/mcp/context.mjs +9 -4
- package/dist/mcp/drafts.mjs +9 -4
- package/dist/mcp/mutation-limits.mjs +2 -0
- package/dist/mcp/mutations.mjs +8 -17
- package/dist/mcp/patch.mjs +5 -3
- package/dist/mcp/preview-watch.mjs +21 -9
- package/dist/mcp/preview-widget.bundle.js +58 -63
- package/dist/mcp/preview-work.mjs +1 -15
- package/dist/mcp/project-widget.bundle.js +57 -62
- package/dist/mcp/prompts.mjs +2 -2
- package/dist/mcp/resource-loader.js +32 -10
- package/dist/mcp/server.mjs +90 -35
- package/dist/mcp/widget.bundle.js +59 -64
- package/dist/preview-builder.mjs +17 -5
- package/dist/preview-bun.mjs +266 -0
- package/dist/preview-imports.mjs +73 -0
- package/dist/preview-resources.mjs +26 -14
- package/dist/scenario-inspector.mjs +11 -4
- package/dist/scenarios-compiler.mjs +47 -6
- package/dist/showcase/client.bundle.js +68 -72
- package/dist/showcase/index.html +2 -2
- package/dist/showcase/sandbox.bundle.js +1 -1
- package/dist/showcase/style.css +4 -0
- package/dist/skills/ads-break-ui/SKILL.md +39 -40
- package/dist/skills/ads-break-ui/references/drafts.md +12 -3
- package/dist/skills/ads-break-ui/references/guarded-editing.md +6 -5
- package/dist/skills/ads-break-ui/references/runtimes.md +91 -140
- package/dist/skills/ads-break-ui/references/validation.md +13 -3
- package/dist/skills/ads-break-ui/references/workflows.md +82 -0
- package/dist/skills/ads-designer/SKILL.md +38 -39
- package/dist/skills/ads-designer/assets/bootstrap-ds/README.md +8 -9
- package/dist/skills/ads-designer/assets/bootstrap-ds/ds.config.json +1 -8
- package/dist/skills/ads-designer/assets/bootstrap-ds/package.json +4 -3
- package/dist/skills/ads-designer/assets/bootstrap-ds/scripts/build-mcp-previews.mjs +2 -32
- package/dist/skills/ads-designer/references/cli.md +24 -20
- package/dist/skills/ads-designer/references/drafts.md +12 -3
- package/dist/skills/ads-designer/references/guarded-editing.md +6 -5
- package/dist/skills/ads-designer/references/runtimes.md +91 -140
- package/dist/skills/ads-designer/references/validation.md +13 -3
- package/dist/skills/ads-designer/references/workflows.md +82 -0
- package/dist/skills/ads-import/SKILL.md +40 -42
- package/dist/skills/ads-import/references/cli.md +24 -20
- package/dist/skills/ads-import/references/drafts.md +12 -3
- package/dist/skills/ads-import/references/guarded-editing.md +6 -5
- package/dist/skills/ads-import/references/runtimes.md +91 -140
- package/dist/skills/ads-import/references/validation.md +13 -3
- package/dist/skills/ads-import/references/workflows.md +82 -0
- package/dist/skills/ads-motion/SKILL.md +37 -38
- package/dist/skills/ads-motion/references/drafts.md +12 -3
- package/dist/skills/ads-motion/references/guarded-editing.md +6 -5
- package/dist/skills/ads-motion/references/runtimes.md +91 -140
- package/dist/skills/ads-motion/references/validation.md +13 -3
- package/dist/skills/ads-motion/references/workflows.md +82 -0
- package/dist/skills/ads-port/SKILL.md +37 -38
- package/dist/skills/ads-port/references/cli.md +24 -20
- package/dist/skills/ads-port/references/drafts.md +12 -3
- package/dist/skills/ads-port/references/guarded-editing.md +6 -5
- package/dist/skills/ads-port/references/runtimes.md +91 -140
- package/dist/skills/ads-port/references/validation.md +13 -3
- package/dist/skills/ads-port/references/workflows.md +82 -0
- package/dist/usage.mjs +84 -0
- package/dist/validation.mjs +0 -12
- package/dist/verification/browser.mjs +77 -48
- package/docs/ADS.md +17 -11
- package/docs/ARCHITECTURE.md +43 -29
- package/docs/BEHAVIORS.md +3 -3
- package/docs/CHANGELOG.md +67 -12
- package/docs/GUIDE.md +96 -53
- package/docs/MCP.md +97 -123
- package/docs/benchmarks/bun-previews.md +91 -0
- package/docs/benchmarks/gidi-preview-memory.md +4 -0
- package/package.json +15 -13
package/dist/mcp/prompts.mjs
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
export const reasoning = `
|
|
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.
|
|
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
|
-
|
|
138
|
-
|
|
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
|
|
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
|
-
|
|
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
|
}
|
package/dist/mcp/server.mjs
CHANGED
|
@@ -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 {
|
|
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";
|
|
@@ -29,7 +30,6 @@ import { reconcileTokenSamples } from "../token-fixtures.mjs";
|
|
|
29
30
|
import { createCaptureController } from "../capture.mjs";
|
|
30
31
|
import { CAPTURES_URI, captureSpec, screenshotFields } from "../capture-store.mjs";
|
|
31
32
|
import { previewSourceRevision } from "../preview-inputs.mjs";
|
|
32
|
-
import { inspectBehaviorLibraries } from "../behavior-libraries.mjs";
|
|
33
33
|
import { createExecutionResults, RESULTS_URI, resultSections } from "./execution-results.mjs";
|
|
34
34
|
import { behaviorPage, behaviorSections } from "./behavior-pages.mjs";
|
|
35
35
|
import { compactProgress, resultBudgets } from "./result-pages.mjs";
|
|
@@ -106,7 +106,7 @@ export function createAdsMcp(directory, { era = "legacy", skillDirectory, pollIn
|
|
|
106
106
|
const project = () => { const context = projectContext(options); context.showcase.url = getShowcaseUrl(); return context; };
|
|
107
107
|
const subscribed = new Set();
|
|
108
108
|
const server = new Server({ name: "reqvire-ads", version: pkg.version }, {
|
|
109
|
-
instructions: `${serverInstructions} ${mutations ? "
|
|
109
|
+
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
110
|
capabilities: { tools: { listChanged: true }, resources: { listChanged: true, subscribe: true }, prompts: {},
|
|
111
111
|
extensions: { "io.modelcontextprotocol/ui": { mimeTypes: [APP_MIME] }, ...(era === "modern" ? { [SKILLS_EXTENSION]: { directoryRead: true } } : {}) } },
|
|
112
112
|
});
|
|
@@ -119,13 +119,37 @@ export function createAdsMcp(directory, { era = "legacy", skillDirectory, pollIn
|
|
|
119
119
|
}
|
|
120
120
|
cache.lastRegistry = cache.registry; return cache.registry;
|
|
121
121
|
};
|
|
122
|
-
|
|
122
|
+
async function getRegistryAsync() {
|
|
123
|
+
for(let attempt=0;attempt<2;attempt++){
|
|
124
|
+
const current=loadConfig(root),revision=previewSourceRevision(current);
|
|
125
|
+
if(cache.registry&&cache.registryRevision===revision)return cache.registry;
|
|
126
|
+
const stored=readScenarioRegistry(current);
|
|
127
|
+
if(stored){cache.registry=cache.lastRegistry=stored;cache.registryRevision=revision;return stored;}
|
|
128
|
+
if(cache.registryTask?.revision!==revision){
|
|
129
|
+
const inspector=cache.registryInspector??=createScenarioInspector(root);
|
|
130
|
+
const task={revision,promise:inspector.inspect()};cache.registryTask=task;
|
|
131
|
+
void task.promise.finally(()=>{if(cache.registryTask===task)cache.registryTask=undefined;}).catch(()=>{});
|
|
132
|
+
}
|
|
133
|
+
const registry=await cache.registryTask.promise;
|
|
134
|
+
if(previewSourceRevision(loadConfig(root))!==revision)continue;
|
|
135
|
+
cache.registry=cache.lastRegistry=registry;cache.registryRevision=revision;cache.catalog=undefined;
|
|
136
|
+
return registry;
|
|
137
|
+
}
|
|
138
|
+
throw new Error("Sources changed during scenario discovery. Retry against the current source.");
|
|
139
|
+
}
|
|
140
|
+
const quickRegistry = () => {
|
|
141
|
+
if(cache.registry??cache.lastRegistry)return cache.registry??cache.lastRegistry;
|
|
142
|
+
const stored=readScenarioRegistry(loadConfig(root));
|
|
143
|
+
if(stored)cache.lastRegistry=stored;
|
|
144
|
+
return stored??{scenarios:[],diagnostics:[]};
|
|
145
|
+
};
|
|
146
|
+
const previewRegistry = waitFor => waitFor === "compiled" && (cache.registry??cache.lastRegistry) ? cache.registry??cache.lastRegistry : getRegistryAsync();
|
|
123
147
|
function captureInventory() {
|
|
124
148
|
const current = loadConfig(root), registry = getRegistry();
|
|
125
149
|
return { ...registry, revision: previewSourceRevision(current) };
|
|
126
150
|
}
|
|
127
151
|
function captureIndex() { const inventory = captureInventory(); return captures.store.list(inventory.scenarios, inventory.revision, { prune: !inventory.diagnostics.length }); }
|
|
128
|
-
const scenarioApps = (quick = false) => (quick ?
|
|
152
|
+
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
153
|
const tokenScenarios = () => {
|
|
130
154
|
const references=drafts.list({unit:"tokens",limit:100000}).drafts.map(({id,title,revision,state,preview})=>({id,title,revision,state,preview}));
|
|
131
155
|
return getRegistry().scenarios.filter(item => item.kind === "tokens").map(item => ({ id:item.id,title:item.title,count:item.tokens.length,drafts:references }));
|
|
@@ -144,16 +168,37 @@ export function createAdsMcp(directory, { era = "legacy", skillDirectory, pollIn
|
|
|
144
168
|
if (!manifest?.scenarios.some(entry => entry.id === id)) throw new Error("The preview resource graph is not ready for this scenario. Rebuild previews.");
|
|
145
169
|
return { manifestUri: live ? LIVE_PREVIEW_MANIFEST_URI : PREVIEW_MANIFEST_URI, manifestRevision: manifest.revision };
|
|
146
170
|
}
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
171
|
+
async function getCatalog() {
|
|
172
|
+
for(let attempt=0;attempt<2;attempt++){
|
|
173
|
+
await getRegistryAsync();const revision=cache.registryRevision;
|
|
174
|
+
if(cache.catalog&&cache.catalogRevision===revision)return cache.catalog;
|
|
175
|
+
if(cache.catalogTask?.revision!==revision){
|
|
176
|
+
const inspector=cache.registryInspector??=createScenarioInspector(root);
|
|
177
|
+
const task={revision,promise:inspector.inspect(root,"catalog")};cache.catalogTask=task;
|
|
178
|
+
void task.promise.finally(()=>{if(cache.catalogTask===task)cache.catalogTask=undefined;}).catch(()=>{});
|
|
179
|
+
}
|
|
180
|
+
const value=await cache.catalogTask.promise;
|
|
181
|
+
if(previewSourceRevision(loadConfig(root))!==revision)continue;
|
|
182
|
+
cache.catalog=value.catalog;cache.catalogRevision=revision;cache.behaviorLibraries={libraries:value.libraries};return cache.catalog;
|
|
183
|
+
}
|
|
184
|
+
throw new Error("Sources changed during catalogue discovery. Retry against the current source.");
|
|
185
|
+
}
|
|
186
|
+
const getBehaviorLibraries = () => cache.behaviorLibraries;
|
|
187
|
+
function annotateDrafts(items, found = drafts.list({limit:100000}).drafts) {
|
|
188
|
+
const units = edits.units();
|
|
151
189
|
return items.map(item => {
|
|
152
190
|
const unit = units.find(unit => unit.files.includes(item.file))?.id ?? null;
|
|
153
191
|
return { ...item, unit, drafts: found.filter(draft => draft.units.includes(unit)).map(({id,title,revision,state,preview}) => ({id,title,revision,state,preview})) };
|
|
154
192
|
});
|
|
155
193
|
}
|
|
156
194
|
const getDocuments = () => cache.documents ??= projectDocuments(options);
|
|
195
|
+
async function explorer() {
|
|
196
|
+
const registry=await getRegistryAsync(), proposals=drafts.list({limit:100000}).drafts;
|
|
197
|
+
const scenarios=annotateDrafts(registry.scenarios,proposals).map(({id,title,kind,group,unit,drafts})=>({id,title,kind,...(group?{group}:{}),unit,drafts}));
|
|
198
|
+
return {status:{projectRoot:root,project:{showcase:project().showcase},drafts:{previewOnly:isDraftPreviewWorkspace(root)},previewWatch:previewWatch?.status(),build:summarizeBuild(builds())},
|
|
199
|
+
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,
|
|
200
|
+
tools:tools().map(({name,_meta,schema})=>{const waitFor=z.toJSONSchema(schema).properties?.waitFor;return{name,...(_meta?{_meta}:{}),inputSchema:{properties:waitFor?{waitFor}:{}}};}),diagnostics:registry.diagnostics};
|
|
201
|
+
}
|
|
157
202
|
const builds = () => {
|
|
158
203
|
previewWatch?.setApps(allApps(true));
|
|
159
204
|
const report = previewWatch?.buildStatus() ?? inspectBuildStatus(root, { ...options.config.mcp, apps: allApps(true) });
|
|
@@ -194,6 +239,7 @@ export function createAdsMcp(directory, { era = "legacy", skillDirectory, pollIn
|
|
|
194
239
|
return [
|
|
195
240
|
{ 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
241
|
{ uri: "ads://guides/behaviors", name: "Controller and behavioral verification guide", mimeType: "text/markdown" },
|
|
242
|
+
{ uri: "ads://guides/workflows", name: "Direct code editing and MCP-only editing workflows", mimeType: "text/markdown" },
|
|
197
243
|
{ uri: "ads://guides/validation", name: "Full and affected validation; test boundaries", mimeType: "text/markdown" },
|
|
198
244
|
{ uri: "ads://guides/runtimes", name: "Node and Bun setup, compiler and verification runtime", mimeType: "text/markdown" },
|
|
199
245
|
{ uri: "ads://guides/evidence", name: "Failure boundaries and compact investigations", mimeType: "text/markdown" },
|
|
@@ -204,6 +250,7 @@ export function createAdsMcp(directory, { era = "legacy", skillDirectory, pollIn
|
|
|
204
250
|
{ uri: "ads://guides/review", name: "Development-only review UI, token renderers and migration", mimeType: "text/markdown" },
|
|
205
251
|
{ uri: "ads://guides/captures", name: "On-demand captures and candidate visual review", mimeType: "text/markdown" },
|
|
206
252
|
{ uri: `${PROJECT_URI}/status`, name: "ADS project status", mimeType: "application/json" },
|
|
253
|
+
{ uri: `${PROJECT_URI}/explorer`, name: "Explorer navigation and preview bootstrap", mimeType: "application/json" },
|
|
207
254
|
{ uri: BUILD_URI, name: "Preview build status and diagnostics", mimeType: "application/json" },
|
|
208
255
|
{ uri: `${PROJECT_URI}/tokens`, name: "Project token values and themes", mimeType: "application/json" },
|
|
209
256
|
{ uri: `${PROJECT_URI}/catalog`, name: "Public components and patterns", mimeType: "application/json" },
|
|
@@ -230,9 +277,9 @@ export function createAdsMcp(directory, { era = "legacy", skillDirectory, pollIn
|
|
|
230
277
|
...[...skills.files.values()].filter((file) => !skillEntries.has(file.uri)).map(({ uri, name, mimeType }) => ({ uri, name, mimeType })),
|
|
231
278
|
];
|
|
232
279
|
}
|
|
233
|
-
function status() {
|
|
280
|
+
async function status() {
|
|
234
281
|
const context = project(), mutationState = mutations ? edits.status() : null, behaviorState = verification.status();
|
|
235
|
-
const catalog = getCatalog(), registry = cache.registry;
|
|
282
|
+
const catalog = await getCatalog(), registry = cache.registry;
|
|
236
283
|
return { projectRoot: root, workflow: workflow([...previews(), ...scenarioApps(true)]), project: context,
|
|
237
284
|
package: pkg.name, version: pkg.version, dsDir: options.config.dsDir, publicAlias: options.config.publicAlias, behaviorLibraries: getBehaviorLibraries().libraries,
|
|
238
285
|
components: catalog.filter((item) => item.kind === "components" && item.apiKind === "ui").length,
|
|
@@ -251,11 +298,13 @@ export function createAdsMcp(directory, { era = "legacy", skillDirectory, pollIn
|
|
|
251
298
|
experimental: { apps: true, nativeSkills: era === "modern", nativeSkillActivation: "host-controlled" } };
|
|
252
299
|
}
|
|
253
300
|
async function read(uri, signal) {
|
|
301
|
+
if(uri===`${PROJECT_URI}/explorer`)return{contents:[{uri,mimeType:"application/json",text:JSON.stringify(await explorer())}]};
|
|
254
302
|
if(uri.startsWith("ads://drafts/")){
|
|
255
303
|
const url=new URL(uri),match=url.pathname.match(/^\/([a-z0-9][a-z0-9-]{0,79})\/resource$/);
|
|
256
304
|
if(!match||[...url.searchParams.keys()].some(key=>key!=="uri")||!url.searchParams.get("uri"))throw new Error("Invalid draft resource address.");
|
|
257
305
|
return drafts.readResource(match[1],url.searchParams.get("uri"),signal);
|
|
258
306
|
}
|
|
307
|
+
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
308
|
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
309
|
if (uri === GUIDE_URI) return { contents: [{ uri, mimeType: "text/markdown", text: projectGuide(project(), [...previews(), ...scenarioApps()]) }] };
|
|
261
310
|
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 +321,10 @@ export function createAdsMcp(directory, { era = "legacy", skillDirectory, pollIn
|
|
|
272
321
|
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
322
|
if (skills.files.has(uri)) return { contents: [skills.read(uri)] };
|
|
274
323
|
let value;
|
|
275
|
-
if (uri === `${PROJECT_URI}/status`) value = status();
|
|
324
|
+
if (uri === `${PROJECT_URI}/status`) value = await status();
|
|
276
325
|
else if (uri === BUILD_URI) value = builds();
|
|
277
326
|
else if (uri === `${PROJECT_URI}/tokens`) value = tokenWidgetData(inspectTokens(root));
|
|
278
|
-
else if (uri === `${PROJECT_URI}/catalog`) value = { items: annotateDrafts(getCatalog()) };
|
|
327
|
+
else if (uri === `${PROJECT_URI}/catalog`) value = { items: annotateDrafts(await getCatalog()) };
|
|
279
328
|
else if (uri === DRAFTS_URI) value = drafts.list();
|
|
280
329
|
else if (uri === `${PROJECT_URI}/scenarios`) value = getRegistry();
|
|
281
330
|
else if (uri === `${PROJECT_URI}/checks`) value = await architecture(signal);
|
|
@@ -359,24 +408,24 @@ export function createAdsMcp(directory, { era = "legacy", skillDirectory, pollIn
|
|
|
359
408
|
function tools() {
|
|
360
409
|
return [
|
|
361
410
|
{ 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();
|
|
411
|
+
{ 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)=>{
|
|
412
|
+
const value=await drafts.show(args,signal),base=getShowcaseUrl();
|
|
364
413
|
let comparisonUrl=null;
|
|
365
414
|
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
415
|
return json({...value,isolatedShowcaseUrl:value.showcaseUrl,showcaseUrl:comparisonUrl??value.showcaseUrl,comparisonUrl});
|
|
367
416
|
} },
|
|
368
417
|
...(mutations ? [
|
|
369
|
-
{ name:"ads_create_draft", description:"Create a Git-committable proposal under ads-drafts/ for 1–
|
|
418
|
+
{ 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
419
|
{ 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
420
|
{ 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,
|
|
421
|
+
{ 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
422
|
if(validation.status().busy||verification.status().running)throw new Error("Wait for validation/verification before acceptance.");
|
|
374
423
|
const result=await drafts.accept(args,signal,progress);
|
|
375
424
|
if(result.applied){await previewWatch?.invalidate?.();await refresh(true);}else await refresh();
|
|
376
425
|
return finishExecution("mutation",result);
|
|
377
426
|
} },
|
|
378
427
|
] : []),
|
|
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.
|
|
428
|
+
{ 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
429
|
{ 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
430
|
let result;
|
|
382
431
|
if(draft){
|
|
@@ -392,8 +441,8 @@ export function createAdsMcp(directory, { era = "legacy", skillDirectory, pollIn
|
|
|
392
441
|
await refresh(); return captureResponse(result, era === "modern");
|
|
393
442
|
} },
|
|
394
443
|
{ 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()));
|
|
444
|
+
{ 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 }) => {
|
|
445
|
+
const matches = (await getCatalog()).filter((item) => (!kind || item.kind === kind) && item.name.toLowerCase().includes(search.toLowerCase()));
|
|
397
446
|
return json({ total: matches.length, items: annotateDrafts(matches.slice(0, limit)), resourceUri: `${PROJECT_URI}/catalog` });
|
|
398
447
|
} },
|
|
399
448
|
{ 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 +452,7 @@ export function createAdsMcp(directory, { era = "legacy", skillDirectory, pollIn
|
|
|
403
452
|
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
453
|
} },
|
|
405
454
|
{ 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);
|
|
455
|
+
const registry = await previewRegistry(waitFor);
|
|
407
456
|
const entry = registry.scenarios.find(item => item.id === id);
|
|
408
457
|
if (!entry) throw new Error("Unknown scenario id. Read ads_scenarios; IDs must match discovered source entries.");
|
|
409
458
|
if (registry.diagnostics.length) throw new Error("Scenario registry has errors. Read ads://project/scenarios and fix its diagnostics.");
|
|
@@ -434,7 +483,7 @@ export function createAdsMcp(directory, { era = "legacy", skillDirectory, pollIn
|
|
|
434
483
|
return json({ ...manifest, text: content.text.slice(offset, offset + limit), offset, ...(offset + limit < content.text.length ? { nextOffset: offset + limit } : {}) });
|
|
435
484
|
} },
|
|
436
485
|
{ 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);
|
|
486
|
+
const registry = await previewRegistry(waitFor);
|
|
438
487
|
if (!category && options.config.mcp.previewManifest) category = registry.scenarios.find(item => item.kind === "tokens")?.id;
|
|
439
488
|
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
489
|
if (category) {
|
|
@@ -454,7 +503,7 @@ export function createAdsMcp(directory, { era = "legacy", skillDirectory, pollIn
|
|
|
454
503
|
{ 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
504
|
{ 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
505
|
{ 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,
|
|
506
|
+
{ 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
507
|
if (verification.status().running || edits.status().busy) throw new Error("Wait for the active verification or guarded edit before validating.");
|
|
459
508
|
return finishExecution("validation",await validation.run(args,signal,progress));
|
|
460
509
|
} },
|
|
@@ -473,11 +522,11 @@ export function createAdsMcp(directory, { era = "legacy", skillDirectory, pollIn
|
|
|
473
522
|
const {patch,...result}=reconcileTokenSamples(options,args);
|
|
474
523
|
return json({...result,removed:result.removed.slice(0,50),unresolved:result.unresolved.slice(0,50),unresolvedCount:result.unresolved.length,...storePreparedPatch(options,patch)});
|
|
475
524
|
}},
|
|
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
|
|
525
|
+
{ 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
526
|
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
527
|
annotations: { readOnlyHint: false, destructiveHint: true, idempotentHint: false, openWorldHint: false }, _meta: { ui: { visibility: ["model"] } },
|
|
479
528
|
call: applyEdits,
|
|
480
|
-
}, {name:"ads_apply_transaction",description:"Apply genuinely coupled ADS changes as 2–
|
|
529
|
+
}, {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
530
|
...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
531
|
// Validate readiness without embedding executable HTML in model results.
|
|
483
532
|
const build = await previewBuild(app, signal);
|
|
@@ -638,13 +687,14 @@ export function createAdsMcp(directory, { era = "legacy", skillDirectory, pollIn
|
|
|
638
687
|
|| entry.diagnostics.some(item => item.code === "ADS_PREVIEW_STALE_SOURCE"));
|
|
639
688
|
deferredDiscovery ||= filesChanged;
|
|
640
689
|
const discoveryChanged = deferredDiscovery && !checking;
|
|
641
|
-
if (discoveryChanged) deferredDiscovery = false;
|
|
690
|
+
if (discoveryChanged) { await getRegistryAsync(); if(observationClosed)return false; deferredDiscovery = false; }
|
|
642
691
|
if (discoveryChanged || assetsChanged || draftResourcesChanged) { if (notifications) notifications.resourcesChanged(); else await server.sendResourceListChanged(); }
|
|
643
692
|
previousArtifacts = artifactFingerprint();
|
|
644
693
|
previousAssets = assetFingerprint();
|
|
645
694
|
previousBuild = JSON.stringify(builds());
|
|
646
695
|
const targets = discoveryChanged ? (era === "modern" ? resources().map((entry) => entry.uri).filter((uri) => !skills.files.has(uri)) : [...subscribed]).filter(uri => !uri.startsWith("ads://drafts/"))
|
|
647
696
|
: [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));
|
|
697
|
+
if((discoveryChanged||draftsChanged)&&(era==="modern"||subscribed.has(`${PROJECT_URI}/explorer`)))targets.push(`${PROJECT_URI}/explorer`);
|
|
648
698
|
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
699
|
targets.push(...changedDraftBuilds.filter(uri=>era==="modern"||subscribed.has(uri)));
|
|
650
700
|
previousDraftBuilds=currentDraftBuilds;
|
|
@@ -671,21 +721,23 @@ export function createAdsMcp(directory, { era = "legacy", skillDirectory, pollIn
|
|
|
671
721
|
async function warmScenarios(ids, signal) {
|
|
672
722
|
if (!previewWatch) return;
|
|
673
723
|
const apps = allApps(), selected = new Set(ids);
|
|
674
|
-
const
|
|
675
|
-
if (
|
|
724
|
+
const selectedApps = apps.filter(app => selected.has(app.id));
|
|
725
|
+
if (selectedApps.length !== selected.size) throw new Error("Cannot warm an unknown verification scenario.");
|
|
676
726
|
previewWatch.setApps(apps);
|
|
727
|
+
const ready = new Set(previewWatch.buildStatus().previews.filter(entry=>entry.current).map(entry=>entry.id));
|
|
728
|
+
const files = selectedApps.filter(app=>!ready.has(app.id)).map(app => path.resolve(root, app.file));
|
|
729
|
+
if (!files.length) return;
|
|
677
730
|
await previewWatch.warm(files);
|
|
678
731
|
for (const file of files) await previewWatch.ensure(file, signal);
|
|
679
732
|
}
|
|
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(); } };
|
|
733
|
+
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
734
|
}
|
|
682
735
|
|
|
683
|
-
export async function startAdsMcp(directory = process.cwd(), { stdio = true, showcase = true, port = 0, mutations = false, previewWork = createPreviewWork() } = {}) {
|
|
736
|
+
export async function startAdsMcp(directory = process.cwd(), { stdio = true, showcase = true, port = 0, mutations = false, previewWork = createPreviewWork(), previewBuildTimeoutMs = 30000, prewarm = stdio } = {}) {
|
|
684
737
|
// Fail before opening the transport for configuration/distribution errors.
|
|
685
738
|
const { root, config } = loadConfig(directory);
|
|
686
739
|
const inspection = { skills: createSkillStore(), previewWork };
|
|
687
|
-
const previewWatch = createReconfigurablePreviewWatch(root, config.mcp);
|
|
688
|
-
const unregisterPreview = previewWork.register(previewWatch);
|
|
740
|
+
const previewWatch = createReconfigurablePreviewWatch(root, config.mcp, {buildTimeout:previewBuildTimeoutMs,prewarm});
|
|
689
741
|
let host, api;
|
|
690
742
|
let buildWatcher, buildChangeTimer;
|
|
691
743
|
const buildListeners = new Set();
|
|
@@ -710,13 +762,15 @@ export async function startAdsMcp(directory = process.cwd(), { stdio = true, sho
|
|
|
710
762
|
});
|
|
711
763
|
buildWatcher.unref(); buildWatcher.on("error", () => { buildWatcher.close(); });
|
|
712
764
|
} catch { /* Periodic observation also covers replaced/missing report directories. */ }
|
|
765
|
+
const warmStart=prewarm?setTimeout(()=>previewWatch.start(),0):undefined;
|
|
766
|
+
warmStart?.unref();
|
|
713
767
|
let closing;
|
|
714
768
|
function close() {
|
|
715
769
|
return closing ??= (async () => {
|
|
770
|
+
clearTimeout(warmStart);
|
|
716
771
|
buildListeners.clear();
|
|
717
772
|
clearTimeout(buildChangeTimer); buildWatcher?.close();
|
|
718
773
|
inspection.edits?.cancel();
|
|
719
|
-
unregisterPreview();
|
|
720
774
|
// Stop every owned resource even if another close fails or has in-flight RPCs.
|
|
721
775
|
const results = await Promise.allSettled([
|
|
722
776
|
Promise.resolve().then(() => host?.close()),
|
|
@@ -725,6 +779,7 @@ export async function startAdsMcp(directory = process.cwd(), { stdio = true, sho
|
|
|
725
779
|
Promise.resolve().then(() => inspection.verification?.close()),
|
|
726
780
|
Promise.resolve().then(() => inspection.captures?.close()),
|
|
727
781
|
Promise.resolve().then(() => inspection.drafts?.close()),
|
|
782
|
+
Promise.resolve().then(() => inspection.registryInspector?.close()),
|
|
728
783
|
Promise.resolve().then(() => api?.close()),
|
|
729
784
|
Promise.resolve().then(() => handle?.close()),
|
|
730
785
|
]);
|
|
@@ -750,7 +805,7 @@ export async function startAdsMcp(directory = process.cwd(), { stdio = true, sho
|
|
|
750
805
|
for (const signal of ["SIGINT", "SIGTERM"]) process.once(signal, disconnect);
|
|
751
806
|
process.once("exit", forceCleanup);
|
|
752
807
|
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) {
|
|
808
|
+
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
809
|
if (inspection.registry === registry || inspection.lastRegistry === registry) return;
|
|
755
810
|
inspection.registry = inspection.lastRegistry = registry; inspection.registryRevision = undefined; inspection.catalog = undefined;
|
|
756
811
|
}, 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 };
|