@reqvire-org/ads 0.3.52 → 0.4.0
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 -9
- package/dist/assets.mjs +16 -2
- package/dist/behaviors.mjs +6 -5
- package/dist/boundaries.mjs +5 -5
- package/dist/browser-audit/first-render.mjs +22 -0
- package/dist/browser-audit/image-shape.mjs +36 -0
- package/dist/browser-audit/render-states.mjs +61 -35
- package/dist/browser-audit/worker.mjs +47 -12
- package/dist/browser-audit.mjs +75 -12
- package/dist/bun-compiler.mjs +14 -7
- package/dist/check-service.mjs +83 -0
- package/dist/check.mjs +20 -18
- package/dist/cli.mjs +5 -3
- package/dist/config.mjs +20 -41
- package/dist/contracts.d.mts +9 -0
- package/dist/finding-rules.mjs +8 -1
- package/dist/font-rules.mjs +103 -0
- package/dist/fonts-generated.mjs +32 -12
- package/dist/generated-entries.mjs +131 -0
- package/dist/icons.mjs +1 -1
- package/dist/init.mjs +11 -32
- package/dist/layers.mjs +7 -3
- package/dist/lint-config.mjs +4 -2
- package/dist/mcp/catalog.mjs +2 -1
- package/dist/mcp/context.mjs +3 -3
- package/dist/mcp/drafts.mjs +136 -121
- package/dist/mcp/mutations.mjs +65 -19
- package/dist/mcp/preview-watch.mjs +31 -5
- package/dist/mcp/preview-widget.bundle.js +50 -47
- package/dist/mcp/project-widget.bundle.js +45 -42
- package/dist/mcp/prompts.mjs +1 -1
- package/dist/mcp/server.mjs +81 -40
- package/dist/mcp/showcase-host.mjs +20 -7
- package/dist/mcp/widget.bundle.js +49 -46
- package/dist/oxlint.mjs +3 -2
- package/dist/program-cache.mjs +36 -0
- package/dist/public-api.mjs +2 -1
- package/dist/scenarios-compiler.mjs +82 -14
- package/dist/scenarios-vite.mjs +1 -1
- package/dist/scenarios.mjs +4 -3
- package/dist/showcase/client.bundle.js +27 -27
- package/dist/showcase/index.html +2 -2
- package/dist/skills/ads-break-ui/SKILL.md +25 -28
- package/dist/skills/ads-break-ui/references/behaviors.md +7 -6
- package/dist/skills/ads-break-ui/references/captures.md +7 -32
- package/dist/skills/ads-break-ui/references/contracts.md +58 -25
- package/dist/skills/ads-break-ui/references/drafts.md +59 -43
- package/dist/skills/ads-break-ui/references/evidence.md +1 -1
- package/dist/skills/ads-break-ui/references/guarded-editing.md +58 -47
- package/dist/skills/ads-break-ui/references/review.md +9 -8
- package/dist/skills/ads-break-ui/references/scenarios.md +1 -1
- package/dist/skills/ads-break-ui/references/validation.md +8 -4
- package/dist/skills/ads-break-ui/references/workflows.md +15 -8
- package/dist/skills/ads-designer/SKILL.md +30 -31
- package/dist/skills/ads-designer/references/accessibility.md +9 -5
- package/dist/skills/ads-designer/references/behaviors.md +7 -6
- package/dist/skills/ads-designer/references/branding.md +2 -2
- package/dist/skills/ads-designer/references/captures.md +7 -32
- package/dist/skills/ads-designer/references/cli.md +5 -1
- package/dist/skills/ads-designer/references/contracts.md +58 -25
- package/dist/skills/ads-designer/references/drafts.md +59 -43
- package/dist/skills/ads-designer/references/evidence.md +1 -1
- package/dist/skills/ads-designer/references/guarded-editing.md +58 -47
- package/dist/skills/ads-designer/references/performance.md +57 -6
- package/dist/skills/ads-designer/references/review.md +9 -8
- package/dist/skills/ads-designer/references/scenarios.md +1 -1
- package/dist/skills/ads-designer/references/validation.md +8 -4
- package/dist/skills/ads-designer/references/workflows.md +15 -8
- package/dist/skills/ads-import/SKILL.md +25 -28
- package/dist/skills/ads-import/references/behaviors.md +7 -6
- package/dist/skills/ads-import/references/captures.md +7 -32
- package/dist/skills/ads-import/references/cli.md +5 -1
- package/dist/skills/ads-import/references/contracts.md +58 -25
- package/dist/skills/ads-import/references/drafts.md +59 -43
- package/dist/skills/ads-import/references/evidence.md +1 -1
- package/dist/skills/ads-import/references/guarded-editing.md +58 -47
- package/dist/skills/ads-import/references/review.md +9 -8
- package/dist/skills/ads-import/references/scenarios.md +1 -1
- package/dist/skills/ads-import/references/validation.md +8 -4
- package/dist/skills/ads-import/references/workflows.md +15 -8
- package/dist/skills/ads-motion/SKILL.md +25 -28
- package/dist/skills/ads-motion/references/behaviors.md +7 -6
- package/dist/skills/ads-motion/references/captures.md +7 -32
- package/dist/skills/ads-motion/references/contracts.md +58 -25
- package/dist/skills/ads-motion/references/drafts.md +59 -43
- package/dist/skills/ads-motion/references/evidence.md +1 -1
- package/dist/skills/ads-motion/references/guarded-editing.md +58 -47
- package/dist/skills/ads-motion/references/review.md +9 -8
- package/dist/skills/ads-motion/references/scenarios.md +1 -1
- package/dist/skills/ads-motion/references/validation.md +8 -4
- package/dist/skills/ads-motion/references/workflows.md +15 -8
- package/dist/skills/ads-port/SKILL.md +25 -28
- package/dist/skills/ads-port/references/behaviors.md +7 -6
- package/dist/skills/ads-port/references/captures.md +7 -32
- package/dist/skills/ads-port/references/cli.md +5 -1
- package/dist/skills/ads-port/references/contracts.md +58 -25
- package/dist/skills/ads-port/references/drafts.md +59 -43
- package/dist/skills/ads-port/references/evidence.md +1 -1
- package/dist/skills/ads-port/references/guarded-editing.md +58 -47
- package/dist/skills/ads-port/references/native-implementation.md +6 -6
- package/dist/skills/ads-port/references/review.md +9 -8
- package/dist/skills/ads-port/references/scenarios.md +1 -1
- package/dist/skills/ads-port/references/validation.md +8 -4
- package/dist/skills/ads-port/references/workflows.md +15 -8
- package/dist/starters/preact/design-system/components/Layout/Grid/Grid.ads.contract.ts +6 -0
- package/dist/starters/preact/design-system/review/token-preview/TokenPreview.ads.contract.ts +6 -0
- package/dist/starters/preact/ds.config.json +0 -14
- package/dist/starters/react/README.md +9 -5
- package/dist/starters/react/design-system/brand/Icons/AppIcon/AppIcon.ads.fixture.ts +1 -1
- package/dist/starters/react/design-system/brand/Identity/Logo/Logo.ads.fixture.ts +2 -2
- package/dist/starters/react/design-system/components/Actions/Button/Button.ads.exports.ts +1 -0
- package/dist/starters/react/design-system/components/Actions/IconButton/IconButton.ads.exports.ts +1 -0
- package/dist/starters/react/design-system/components/Content/Icon/Icon.ads.exports.ts +1 -0
- package/dist/starters/react/design-system/components/Content/Image/Image.ads.exports.ts +1 -0
- package/dist/starters/react/design-system/components/Content/Logo/Logo.ads.exports.ts +1 -0
- package/dist/starters/react/design-system/components/Content/Logo/Logo.tsx +2 -2
- package/dist/starters/react/design-system/components/Forms/TextField/TextField.ads.exports.ts +1 -0
- package/dist/starters/react/design-system/components/Layout/Grid/Grid.ads.contract.ts +6 -0
- package/dist/starters/react/design-system/components/Layout/Grid/Grid.ads.exports.ts +1 -0
- package/dist/starters/react/design-system/controllers/Palette/Palette.ads.exports.ts +1 -0
- package/dist/starters/react/design-system/index.ts +3 -7
- package/dist/starters/react/design-system/patterns/Search/SearchBar/SearchBar.ads.exports.ts +1 -0
- package/dist/starters/react/design-system/review/brand-preview/BrandPreview.ads.exports.ts +1 -0
- package/dist/starters/react/design-system/review/demo-frame/DemoFrame.ads.exports.ts +1 -0
- package/dist/starters/react/design-system/review/grid-cell/GridCell.ads.exports.ts +1 -0
- package/dist/starters/react/design-system/review/index.ts +4 -3
- package/dist/starters/react/design-system/review/screen-frame/ScreenFrame.ads.exports.ts +1 -0
- package/dist/starters/react/design-system/review/token-preview/TokenPreview.ads.contract.ts +6 -0
- package/dist/starters/react/design-system/review/token-preview/TokenPreview.ads.exports.ts +1 -0
- package/dist/starters/react/design-system/styles.css +1 -0
- package/dist/starters/react/ds.config.json +0 -14
- package/dist/style-boundaries.mjs +7 -6
- package/dist/test-boundaries.mjs +2 -2
- package/dist/themes-watch.mjs +9 -3
- package/dist/token-fixtures.mjs +1 -1
- package/dist/unit-contracts.mjs +38 -4
- package/dist/units.mjs +16 -91
- package/dist/validation-checks.mjs +7 -1
- package/docs/ADS.md +10 -10
- package/docs/ARCHITECTURE.md +104 -44
- package/docs/BEHAVIORS.md +8 -7
- package/docs/CACHING.md +15 -6
- package/docs/CHANGELOG.md +107 -12
- package/docs/COMPARISON.md +1 -1
- package/docs/CONTRACTS.md +10 -25
- package/docs/GUIDE.md +98 -57
- package/docs/MCP.md +116 -151
- package/package.json +7 -7
- package/dist/contract-migration.mjs +0 -110
- package/dist/mcp/draft-exports.mjs +0 -40
- package/dist/mcp/edit-preparation.mjs +0 -115
package/dist/mcp/prompts.mjs
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
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 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
|
|
4
|
+
For MCP-only low-level repairs/migrations when ads_status.mutations.enabled, discover one owner with ads_units, create its draft with ads_create_draft, read relevant ranges with ads_read_file and send a Git unified diff through ads_update_draft({id,revision,patch}). Only a draft can be accepted: check it with ads_accept({id,revision,dryRun:true}), then accept it. A unit includes its own scenarios/fixtures; imported peers remain separate. tokens is the token foundation unit. An owner declares its public names in its own <Owner>.ads.exports.ts and its style permissions in its contract; ADS generates the public barrel, review entry and styles entry, so never edit them. A failed acceptance leaves 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 diffs, pass patchFile pointing to .ds/patches/<name>.patch rather than loading bytes into context; binary files go through ads_update_draft changes with encoding:base64. 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.
|
package/dist/mcp/server.mjs
CHANGED
|
@@ -2,7 +2,7 @@ import { watchThemesCss } from "../themes-watch.mjs";
|
|
|
2
2
|
import { randomUUID } from "node:crypto";
|
|
3
3
|
import { executionContext } from "./execution-context.mjs";
|
|
4
4
|
import { createExecutionCoordinator } from "./execution-coordinator.mjs";
|
|
5
|
-
import { existsSync, readFileSync, statSync, watch } from "node:fs";
|
|
5
|
+
import { existsSync, mkdirSync, readFileSync, statSync, watch } from "node:fs";
|
|
6
6
|
import path from "node:path";
|
|
7
7
|
import { Server, ProtocolError, INVALID_PARAMS, ResourceNotFoundError } from "@modelcontextprotocol/server";
|
|
8
8
|
import { serveStdio, StdioServerTransport } from "@modelcontextprotocol/server/stdio";
|
|
@@ -33,10 +33,9 @@ import { resourceLimitsStatus } from "../resource-limits.mjs";
|
|
|
33
33
|
import { assertBunRuntime } from "../runtime-requirements.mjs";
|
|
34
34
|
import { createMutationController, mutationLimits } from "./mutations.mjs";
|
|
35
35
|
import { createPreviewWork } from "./preview-work.mjs";
|
|
36
|
-
import { prepareUnitPatch, storePreparedPatch } from "./edit-preparation.mjs";
|
|
37
36
|
import { reconcileTokenSamples } from "../token-fixtures.mjs";
|
|
38
37
|
import { createCaptureController } from "../capture.mjs";
|
|
39
|
-
import { CAPTURES_URI, captureSpec
|
|
38
|
+
import { CAPTURES_URI, captureSpec } from "../capture-store.mjs";
|
|
40
39
|
import { previewSourceRevision } from "../preview-inputs.mjs";
|
|
41
40
|
import { createExecutionResults, RESULTS_URI, resultSections } from "./execution-results.mjs";
|
|
42
41
|
import { behaviorPage, behaviorSections } from "./behavior-pages.mjs";
|
|
@@ -48,6 +47,7 @@ import { createDraftController, DRAFTS_URI, draftIdSchema, draftRevisionSchema }
|
|
|
48
47
|
import { isDraftPreviewWorkspace } from "../draft-workspace.mjs";
|
|
49
48
|
import { isDraftFile } from "../draft-boundary.mjs";
|
|
50
49
|
import { findingCounts } from "../finding-rules.mjs";
|
|
50
|
+
import { releaseWarmChecks, useWarmChecks } from "../check-service.mjs";
|
|
51
51
|
|
|
52
52
|
const pkg = JSON.parse(readFileSync(new URL("../../package.json", import.meta.url), "utf8"));
|
|
53
53
|
class InvalidParamsError extends ProtocolError {
|
|
@@ -66,7 +66,6 @@ const recordRange = { recordIndex: z.number().int().min(0).optional(), offset: z
|
|
|
66
66
|
const paged = { cursor: z.string().max(300).optional(), limit: z.number().int().min(1).max(resultBudgets.maxLimit).optional() };
|
|
67
67
|
const annotations = { readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: false };
|
|
68
68
|
const schemas = { params: z.object({ cursor: z.string().optional() }).passthrough(), result: z.object({ resultType: z.literal("complete") }).passthrough() };
|
|
69
|
-
const ownerPatch = z.object({ unit: z.string().min(1).max(256), patch: z.string().min(1).max(mutationLimits.patchBytes).optional(), patchFile: z.string().min(1).max(500).optional() }).strict().refine(args => (args.patch !== undefined) !== (args.patchFile !== undefined), "Provide exactly one of patch or patchFile.");
|
|
70
69
|
|
|
71
70
|
function resourceQuery(uri, allowed) {
|
|
72
71
|
const url=new URL(uri);
|
|
@@ -74,7 +73,7 @@ function resourceQuery(uri, allowed) {
|
|
|
74
73
|
return Object.fromEntries([...url.searchParams].map(([key,value])=>[key,["limit","recordIndex","offset","chars"].includes(key)?Number(value):value]));
|
|
75
74
|
}
|
|
76
75
|
|
|
77
|
-
export function createAdsMcp(directory, { era = "legacy", skillDirectory, pollInterval = 1000, observeChanges = true, previewWatch, showcaseUrl, notifications, inspection, mutations = false, onBuildChange } = {}) {
|
|
76
|
+
export function createAdsMcp(directory, { era = "legacy", skillDirectory, pollInterval = 1000, observeChanges = true, previewWatch, showcaseUrl, mountPreview, notifications, inspection, mutations = false, onBuildChange } = {}) {
|
|
78
77
|
if (process.versions.bun) assertBunRuntime();
|
|
79
78
|
const root = path.resolve(directory);
|
|
80
79
|
let observationClosed = false;
|
|
@@ -85,7 +84,12 @@ export function createAdsMcp(directory, { era = "legacy", skillDirectory, pollIn
|
|
|
85
84
|
const draftObservers = cache.draftObservers ??= new Set();
|
|
86
85
|
const drafts = cache.drafts ??= createDraftController(root, { edits, prewarm: true,
|
|
87
86
|
onChange: () => { for (const observer of draftObservers) void observer().catch(error => { process.stderr.write(`ads mcp: ${error.message}\n`); }); },
|
|
88
|
-
|
|
87
|
+
// A draft preview is a view of its workspace, compiled by this project's compiler: no
|
|
88
|
+
// server, port, watcher set or compiler process of its own.
|
|
89
|
+
startPreview: (workspace, id) => {
|
|
90
|
+
if (!previewWatch?.attachDraft) throw new Error("Draft previews need the project's preview compiler; start ADS with its showcase.");
|
|
91
|
+
return createDraftPreview(workspace, { id, host: previewWatch, showcaseUrl: getShowcaseUrl, mountPreview, previewWork: cache.previewWork });
|
|
92
|
+
} });
|
|
89
93
|
const verification = cache.verification ??= createVerificationController(root, { previewWork: cache.previewWork });
|
|
90
94
|
const validation = cache.validation ??= createValidationController(root, { previewWork: cache.previewWork });
|
|
91
95
|
const executionResults = cache.executionResults ??= createExecutionResults(root,{retention:()=>{try{cache.resultRetention=loadConfig(root).config.mcp.resultRetention;}catch{/* Keep the last valid policy during config edits. */}return cache.resultRetention;}});
|
|
@@ -120,7 +124,7 @@ export function createAdsMcp(directory, { era = "legacy", skillDirectory, pollIn
|
|
|
120
124
|
const project = () => { const context = projectContext(options); context.showcase.url = getShowcaseUrl(); return context; };
|
|
121
125
|
const subscribed = new Set();
|
|
122
126
|
const server = new Server({ name: "reqvire-ads", version: pkg.version }, {
|
|
123
|
-
instructions: `${serverInstructions} ${mutations ? "MCP source mutation tools are enabled for MCP-only editing or deliberately selected guarded proposals. Read ads://guides/workflows first; availability does not require direct editors to use drafts. For tracked proposals, read ads://guides/drafts and accept the exact rendered/reviewed revision.
|
|
127
|
+
instructions: `${serverInstructions} ${mutations ? "MCP source mutation tools are enabled for MCP-only editing or deliberately selected guarded proposals. Read ads://guides/workflows first; availability does not require direct editors to use drafts. For tracked proposals, read ads://guides/drafts and accept the exact rendered/reviewed revision. Every MCP source change goes through a draft: only ads_accept of an exact draft revision writes accepted source. Focused repairs patch a draft with ads_update_draft; coupled owners share one draft. Keep mandatory ADS gates." : "MCP source mutation tools are disabled. Direct editors can still edit owned files normally and use MCP for previews/checks. MCP-only clients without another source channel cannot edit."}`,
|
|
124
128
|
capabilities: { tools: { listChanged: true }, resources: { listChanged: true, subscribe: true }, prompts: {},
|
|
125
129
|
extensions: { "io.modelcontextprotocol/ui": { mimeTypes: [APP_MIME] }, ...(era === "modern" ? { [SKILLS_EXTENSION]: { directoryRead: true } } : {}) } },
|
|
126
130
|
});
|
|
@@ -260,7 +264,7 @@ export function createAdsMcp(directory, { era = "legacy", skillDirectory, pollIn
|
|
|
260
264
|
{ uri: "ads://guides/atomic-styles", name: "Atomic styles: composition conflicts and custom-property extraction", mimeType: "text/markdown" },
|
|
261
265
|
{ uri: "ads://guides/scenarios", name: "Scenario coverage and public class-helper contracts", mimeType: "text/markdown" },
|
|
262
266
|
{ uri: "ads://guides/layers", name: "Component capabilities, pattern composition and dependency ownership", mimeType: "text/markdown" },
|
|
263
|
-
{ uri: "ads://guides/contracts", name: "Static owner contracts
|
|
267
|
+
{ uri: "ads://guides/contracts", name: "Static owner contracts and typed paints", mimeType: "text/markdown" },
|
|
264
268
|
{ uri: "ads://guides/review", name: "Development-only review UI, token renderers and migration", mimeType: "text/markdown" },
|
|
265
269
|
{ uri: "ads://guides/captures", name: "On-demand captures and candidate visual review", mimeType: "text/markdown" },
|
|
266
270
|
{ uri: `${PROJECT_URI}/status`, name: "ADS project status", mimeType: "application/json" },
|
|
@@ -416,9 +420,8 @@ export function createAdsMcp(directory, { era = "legacy", skillDirectory, pollIn
|
|
|
416
420
|
try { await refresh(); } catch (error) { process.stderr.write(`ads mcp: result saved; notification failed: ${error.message}\n`); }
|
|
417
421
|
return { ...json(summary), ...(!result.ok ? { isError: true } : {}) };
|
|
418
422
|
}
|
|
419
|
-
|
|
420
|
-
|
|
421
|
-
if (result.screenshots) await refresh();
|
|
423
|
+
/** After accepted source changes: reconfigure, rebuild and re-warm previews. */
|
|
424
|
+
async function afterApply(result) {
|
|
422
425
|
if (result.applied) {
|
|
423
426
|
try {
|
|
424
427
|
if (result.changes.some(change => change.path === "ds.config.json") || result.unit === "configuration" || result.units?.includes("configuration")) await previewWatch?.reconfigure?.(loadConfig(root).config.mcp,true);
|
|
@@ -427,8 +430,8 @@ export function createAdsMcp(directory, { era = "legacy", skillDirectory, pollIn
|
|
|
427
430
|
previewWatch?.setApps(allApps());
|
|
428
431
|
if ((result.units??[result.unit]).some(unit=>unit!=="documentation")) await previewWatch?.warm?.((options.config.mcp.previewManifest?scenarioApps():allApps()).map(app=>path.resolve(root,app.file)));
|
|
429
432
|
} catch (error) {result.warnings=[...(result.warnings ?? []),{rule:"mutation-notification",message:`Changes were applied, but preview refresh failed: ${error.message.slice(0,2000)}. Recheck ads_status and reopen the scenario.`}];}
|
|
430
|
-
}
|
|
431
|
-
return
|
|
433
|
+
} else await refresh();
|
|
434
|
+
return result;
|
|
432
435
|
}
|
|
433
436
|
function tools() {
|
|
434
437
|
return [
|
|
@@ -441,12 +444,11 @@ export function createAdsMcp(directory, { era = "legacy", skillDirectory, pollIn
|
|
|
441
444
|
return value.ok===false?{...response,isError:true}:response;
|
|
442
445
|
} },
|
|
443
446
|
...(mutations ? [
|
|
444
|
-
{ name:"ads_create_draft", description:"Create a Git-committable proposal under ads-drafts/ for 1–64 coupled ADS owners, copying only their
|
|
445
|
-
{ name:"ads_update_draft", description:"Update marked draft source or register new/deleted canonical target paths. Pass the current revision from ads_drafts. Source is UTF-8 unless encoding:base64; content:null proposes deletion.
|
|
447
|
+
{ name:"ads_create_draft", description:"Create a Git-committable proposal under ads-drafts/ for 1–64 coupled ADS owners, copying only their own files into non-importable .ads files. An owner can be in only one open draft at a time: another client's open draft holds its owners until it is accepted or dropped, so concurrent clients edit different owners; depend on an open draft instead of including its owners. New owners are allowed. Optional dependencies name separate unaccepted drafts used by pattern/composition previews. Creation does not change accepted source. Every ADS source change starts here: only a draft can be accepted. Edit the returned files normally, or patch them with ads_update_draft.", schema:z.object({units:z.array(z.string().min(1).max(256)).min(1).max(mutationLimits.units),title:z.string().min(1).max(160).optional(),id:draftIdSchema.optional(),dependencies:z.array(draftIdSchema).max(8).default([]),tokenGroups:z.array(z.string().min(1).max(160)).max(32).default([])}).strict(),_meta:{ui:{visibility:["model"]}},annotations:{...annotations,readOnlyHint:false,idempotentHint:false},call:async args=>{const result=drafts.create(args);if(observeChanges)await refresh();return json(result);} },
|
|
448
|
+
{ name:"ads_update_draft", description:"Update marked draft source or register new/deleted canonical target paths. Pass the current revision from ads_drafts. Source is UTF-8 unless encoding:base64; content:null proposes deletion. Optional dependencies replaces the draft dependency list. patch (inline) or patchFile (.ds/patches/*.patch) applies one Git unified diff to the draft instead: headers name canonical paths (--- a/path, +++ b/path, /dev/null creates/deletes), hunks must match the draft's current proposal exactly, and new paths join their declared owner; send binary files through changes with encoding:base64. Normal local file edits need no iteration tool. Accepted source remains unchanged; ownership and all required checks run at acceptance.",schema:z.object({id:draftIdSchema,revision:draftRevisionSchema,dependencies:z.array(draftIdSchema).max(8).optional(),changes:z.array(z.object({unit:z.string().max(256),path:z.string().min(1).max(500),content:z.string().max(256*1024).nullable(),encoding:z.enum(["utf8","base64"]).optional()}).strict()).max(32).default([]),patch:z.string().min(1).max(mutationLimits.patchBytes).optional(),patchFile:z.string().min(1).max(500).optional()}).strict().refine(args=>args.patch===undefined||args.patchFile===undefined,"Provide at most one of patch or patchFile."),_meta:{ui:{visibility:["model"]}},annotations:{...annotations,readOnlyHint:false,idempotentHint:false},call:async args=>{const result=drafts.update(args);if(observeChanges)await refresh();return json(result);} },
|
|
446
449
|
{ name:"ads_drop_draft",description:"Delete an exact tracked draft and its generated preview. This is Drop, not a separate refusal workflow. Accepted source is unchanged. Dependents report a missing dependency until corrected.",schema:z.object({id:draftIdSchema,revision:draftRevisionSchema}).strict(),_meta:{ui:{visibility:["model"]}},annotations:{...annotations,readOnlyHint:false,destructiveHint:true,idempotentHint:false},call:async args=>{const result=await drafts.drop(args);if(observeChanges)await refresh();return json(result);} },
|
|
447
|
-
{ name:"ads_accept",title:"Accept a reviewed draft",description:"Auto-mode acceptance: validate and apply the exact rendered/reviewed draft revision in one operation. Accept dependency drafts first; dependent drafts automatically switch to their final @ds implementations. Mandatory ADS guards and acceptance.checks run once on the candidate; affected registered tests gate acceptance when acceptance.behaviorChecks is true.
|
|
448
|
-
const result=await drafts.accept(args,signal,progress);
|
|
449
|
-
if(result.applied){await previewWatch?.invalidate?.();await refresh(true);}else await refresh();
|
|
450
|
+
{ name:"ads_accept",title:"Accept a reviewed draft",description:"Auto-mode acceptance: validate and apply the exact rendered/reviewed draft revision in one operation. Accept dependency drafts first; dependent drafts automatically switch to their final @ds implementations. Mandatory ADS guards and acceptance.checks run once on the candidate; affected registered tests gate acceptance when acceptance.behaviorChecks is true. acceptance.browserAudit owners (default) has axe-core audit the draft owners' own UI scenarios in every declared brand and theme, affected every scenario the change reaches, false none; any a11y-axe error (or an audit that cannot run) rejects acceptance. The full audit of everything affected runs as a stage with ads_validate (validation policy, scope changed) after a series of accepted drafts. Draft/source changes invalidate acceptance. This is the only way ADS writes accepted source. dryRun:true runs every acceptance check on the candidate and writes nothing; the draft stays. On failure retain the draft and inspect ads_results; on success apply normal source, remove the draft and publish an event. No additional human approval or manual Apply step.",schema:z.object({fresh:z.boolean().default(false),id:draftIdSchema,revision:draftRevisionSchema,dryRun:z.boolean().default(false)}).strict(),_meta:{ui:{visibility:["model"]}},annotations:{...annotations,readOnlyHint:false,destructiveHint:true,idempotentHint:false},call:async(args,signal,progress)=>{
|
|
451
|
+
const result=await afterApply(await drafts.accept(args,signal,progress));
|
|
450
452
|
return finishExecution("mutation",result);
|
|
451
453
|
} },
|
|
452
454
|
] : []),
|
|
@@ -524,32 +526,31 @@ export function createAdsMcp(directory, { era = "legacy", skillDirectory, pollIn
|
|
|
524
526
|
return json({ widget: { resourceUri: TOKENS_APP_URI }, category: null, tokenCount: inspectTokens(root).tokens.length, dataUri: `${PROJECT_URI}/tokens`, showcaseUrl: getShowcaseUrl() });
|
|
525
527
|
} },
|
|
526
528
|
{ name: "ads_behaviors", description: "Discover behavior owners, then page an exact unit's checks, guarantees, subjects, demonstrations or profiles. Summary listings never embed runner logs. Default 10/max 20 entries and 8 KiB JSON per page; continue with nextCursor and identical filters. Cursors expire when discovery/evidence changes. Read sourceFile with ads_read_file for a complete contract. Metadata and reachable calls do not prove execution; use ads_verify for registered checks.", schema: z.object({ query: z.string().max(200).optional(), unit: z.string().min(1).max(256).optional(), api: z.string().max(200).optional(), section: z.enum(behaviorSections).optional(), ...paged }).strict(), call: args => json(behaviorPage(options,args)) },
|
|
527
|
-
{ name: "ads_results", title: "Read execution outcomes", description: "Read saved ads_validate/ads_verify/
|
|
529
|
+
{ name: "ads_results", title: "Read execution outcomes", description: "Read saved ads_validate/ads_verify/ads_accept outcomes without rerunning anything. Pass the returned resultId; select outcomes, checks, diagnostics, advisories, warnings, changes, captures, acceptance, investigation or selection. Default 10/max 20 rows, at most 8 KiB JSON per page. Follow nextCursor with identical section/status. Rows marked detailTruncated can be read in full using recordIndex and offset/chars (max 2000); follow nextOffset. Results are retained by immutable run ID with bounded age/count/disk retention, including after reconnect or other clients finish. Expired IDs fail with ADS_RESULT_EXPIRED. For one outcome's browser evidence use ads_investigate with its exact unit/check/runId.", schema: z.object({ resultId: z.string().uuid(), section: z.enum(resultSections).optional(), status: z.enum(["all","passed","not_passed"]).optional(), ...paged, ...recordRange }).strict(), call: args => json(executionResults.page(args)) },
|
|
528
530
|
{ name:"ads_report_bug",title:"Report a suspected ADS defect",description:"Record an unexpected ADS guard, preview, build, transport or runner behavior after targeted investigation. Provide expected/observed behavior, minimal steps and frequency; keep suspectedCause separate. Evidence optionally selects a returned resultId or exact unit/check/runId. ADS snapshots compact evidence, version, configured framework and revisions. A report is an untriaged agent claim, not proof of an ADS cause. Returns a small receipt with the report ID and local file path; submitted reports cannot be read through MCP. Stored locally under .ds/reports/ with deduplication, no automatic expiry and no upload. Read ads://guides/reporting; ordinary valid guard rejections should be fixed in their owner.",schema:bugReportSchema,annotations:{readOnlyHint:false,destructiveHint:false,idempotentHint:false,openWorldHint:false},call:args=>submitReport("bug",args) },
|
|
529
531
|
{ name:"ads_request_feature",title:"Request an ADS capability",description:"Record a legitimate workflow that needs a missing ADS capability. Provide workflow, capability and impact; proposal is optional. Preserve valid design/API rather than weakening guards or inventing workaround props. Optional evidence references an existing execution/check, not pasted files/logs. ADS attaches compact context and returns a receipt with the report ID and local file path. Intake is submission-only; no report-reading tools or resources. Shared local report store: deduplicated, untriaged, no automatic expiry or upload. Read ads://guides/reporting; use ads_report_bug for suspected broken existing behavior.",schema:featureRequestSchema,annotations:{readOnlyHint:false,destructiveHint:false,idempotentHint:false,openWorldHint:false},call:args=>submitReport("feature",args) },
|
|
530
532
|
{ name: "ads_investigate", title: "Inspect check evidence", description: "Read a summary for an exact unit/check, or list latest investigations when no check is selected. Pass the outcome's runId to reject superseded evidence. Summary is at most 4 KiB JSON; details, requests, browserErrors and artifacts are separate paged sections (default 10/max 20 entries, 8 KiB). Read truncated rows with recordIndex/offset/chars and the exact runId. Artifact URIs are read separately. Does not rerun checks or infer root cause. Lists latest checks; an exact runId reads retained historical evidence, including candidate runs.", schema: z.object({unit:z.string().min(1).max(256).optional(),check:z.string().min(1).max(100).optional(),runId:z.string().min(1).max(100).optional(),section:z.enum(investigationSections).optional(),...paged,...recordRange}).strict(), call: args => json(investigationPage(root,args)) },
|
|
531
|
-
{ name: "ads_validate", description: "Run mandatory ADS architecture/freshness guards and the selected project policy. policy defaults to validation: its configured scripts, preview freshness, optional registered behavior checks and, unless <policy>.browserAudit is false, an axe-core audit of every rendered UI scenario in every declared brand and theme (a11y-axe findings are blocking errors in the diagnostics section). policy acceptance runs acceptance.checks, acceptance.behaviorChecks and acceptance.browserAudit without applying source, for direct editing; draft acceptance
|
|
533
|
+
{ name: "ads_validate", description: "Run mandatory ADS architecture/freshness guards and the selected project policy. policy defaults to validation: its configured scripts, preview freshness, optional registered behavior checks and, unless <policy>.browserAudit is false, an axe-core audit of every rendered UI scenario in every declared brand and theme (a11y-axe findings are blocking errors in the diagnostics section). policy acceptance runs acceptance.checks, acceptance.behaviorChecks and acceptance.browserAudit without applying source, for direct editing; draft acceptance runs the same acceptance policy, auditing per acceptance.browserAudit (owners by default). policy validation with scope changed is the stage check after a series of accepted drafts. No script names are inferred. scope changed selects affected registered checks from this policy's own successful full baseline; broad changes expand to all. Project scripts keep full scope. Draft edit/show never triggers policies. Reports skipped stages honestly and a bounded resultId; use ads_results for details. Read ads://guides/validation. Trusted configured commands run; nothing is installed.", schema: z.object({scope:z.enum(["all","changed"]).default("all"),policy:z.enum(["acceptance","validation"]).default("validation"),fresh:z.boolean().default(false)}).strict(), annotations: {readOnlyHint:false,destructiveHint:false,idempotentHint:false,openWorldHint:false}, call: async (args,signal,progress) => {
|
|
532
534
|
return finishExecution("validation",await validation.run(args,signal,progress));
|
|
533
535
|
} },
|
|
534
536
|
{ name: "ads_verify", description: "Run one owner's registered development behavior checks using its configured runner/profile. Executes trusted project commands with bounded output, cancellation and process-tree cleanup; installs nothing. Progress and per-check timings are available through ads_status; a profile timeout bounds the whole run. Browser profiles use an isolated managed showcase/MCP App. React StrictMode requires a project development harness, not a production widget. Missing/skipped cases, stale inputs and process exit alone cannot produce passing evidence. Replies contain counts, acceptance, at most three failure summaries and a resultId (4 KiB JSON maximum). Page outcomes with ads_results; inspect one exact unit/check/runId with ads_investigate. Discover exact unit/check IDs with ads_behaviors first.", schema: z.object({ unit: z.string().min(1).max(256), checks: z.array(z.string().min(1).max(100)).min(1).max(100).optional() }).strict(), annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: false, openWorldHint: false }, call: async (args, signal, progress) => {
|
|
535
537
|
const result = await verification.run(args, signal, progress);
|
|
536
538
|
return finishExecution("verification", {unit:args.unit,...result});
|
|
537
539
|
} },
|
|
538
|
-
{ name: "ads_units", description: "Discover editable ADS units and their files: components/patterns with colocated previews; shared controllers; development review/ helpers with a separate export entry; composition; tokens; foundation shared files; documentation including shared credits/license notices; assets/brand, assets/fonts and asset groups; configuration with ds.config.json, package/build/lint configuration and registered project guard/compiler sources. List summaries with query, or pass an exact unit ID for its manifest. Manifests include filePolicy for supported new documentation paths
|
|
540
|
+
{ name: "ads_units", description: "Discover editable ADS units and their files: components/patterns with colocated previews; shared controllers; development review/ helpers with a separate export entry; composition; tokens; foundation shared files; documentation including shared credits/license notices; assets/brand, assets/fonts and asset groups; configuration with ds.config.json, package/build/lint configuration and registered project guard/compiler sources. List summaries with query, or pass an exact unit ID for its manifest. Manifests include filePolicy for supported new documentation paths; every authored file has one owner and shared entries are generated; preserve peer permissions and unrelated configuration. Imported peers stay separate. New owners follow the existing colocation convention.", schema: query.extend({ unit: z.string().min(1).max(256).optional() }), call: ({ unit, query: search = "", limit }) => {
|
|
539
541
|
const matches = edits.units().filter(item => unit ? item.id === unit : item.id.toLowerCase().includes(search.toLowerCase()));
|
|
540
|
-
return json({ total: matches.length, units: matches.slice(0, limit).map(item => ({ id: item.id, kind: item.kind, fileCount: item.files.length, ...(unit ? { files: item.files.slice(0, 200), filesTruncated: item.files.length > 200, ...(item.
|
|
542
|
+
return json({ total: matches.length, units: matches.slice(0, limit).map(item => ({ id: item.id, kind: item.kind, fileCount: item.files.length, ...(unit ? { files: item.files.slice(0, 200), filesTruncated: item.files.length > 200, ...(item.filePolicy ? { filePolicy: item.filePolicy } : {}) } : {}) })) });
|
|
541
543
|
} },
|
|
542
544
|
{ name: "ads_read_file", description: "Read a bounded range of ADS or registered configuration/extension source. Returns unit, full-file digest, startLine and nextOffset; default/max is 12000 UTF-16 characters. Binary assets return byte count/digest and no encoded content. Paths come from ads_units or discovery. Missing new paths return digest null. Read only relevant context before preparing a Git patch.", schema: z.object({ path: z.string().min(1).max(500), offset: z.number().int().min(0).default(0), limit: z.number().int().min(1).max(mutationLimits.readChars).default(mutationLimits.readChars) }).strict(), call: ({ path: file, ...range }) => json(isDraftFile(file)?drafts.readFile(file,range):edits.read(file, range)) },
|
|
543
|
-
...(mutations ? [{
|
|
544
|
-
|
|
545
|
-
const {
|
|
546
|
-
return json({...
|
|
547
|
-
|
|
548
|
-
|
|
549
|
-
|
|
550
|
-
|
|
551
|
-
|
|
552
|
-
}, {name:"ads_apply_transaction",description:"Apply genuinely coupled ADS changes as 2–64 distinct owner Git patches. Each patch must obey its unit and narrow companion rules. Patches run in order; later patches use the earlier candidate's shared-entry content. Core guards, configured project checks, affected behavior checks and, unless acceptance.browserAudit is false, the axe-core audit of affected UI scenarios validate the complete final candidate before any live source is written. Maximum 256 distinct files/16 MiB combined. Dry runs, failures and cancellation publish nothing; publication rolls back on write failure. Optional screenshot:true with dryRun:true and explicit captures selects current/candidate images. Prefer ads_apply_patch for independent edits. Reply is a bounded summary; page diagnostics, outcomes and captures with ads_results using the returned resultId.",schema:z.object({patches:z.array(ownerPatch).min(2).max(mutationLimits.units),dryRun:z.boolean(),...screenshotFields}).strict(),annotations:{readOnlyHint:false,destructiveHint:true,idempotentHint:false,openWorldHint:false},_meta:{ui:{visibility:["model"]}},call:applyEdits}] : []),
|
|
545
|
+
...(mutations ? [{name:"ads_prepare_token_samples",description:"Reconcile a token scenario's consumed literal fixture samples into a draft. Removes undeclared tokens, preserves existing project bindings, and accepts explicit real-token/property/probe bindings. Reports unresolved token names; never guesses CSS meaning from token names. Writes into the given draft (id + revision, which must declare the scenario's owner) or creates a new one; accepted source is unchanged. Review it with ads_show_draft, then ads_accept.",schema:z.object({id:z.string().min(1).max(256),bindings:z.array(z.object({token:z.string().max(256),property:z.string().max(100),probe:z.string().max(1000)}).passthrough()).max(1000).optional(),draft:z.object({id:draftIdSchema,revision:draftRevisionSchema}).strict().optional()}).strict(),_meta:{ui:{visibility:["model"]}},annotations:{...annotations,readOnlyHint:false,idempotentHint:false},call:async args=>{
|
|
546
|
+
const {patch,guidance:_guidance,...result}=reconcileTokenSamples(options,args);
|
|
547
|
+
const summary={...result,removed:result.removed.slice(0,50),unresolved:result.unresolved.slice(0,50),unresolvedCount:result.unresolved.length};
|
|
548
|
+
if(!patch)return json({...summary,draft:null,next:"The samples already match; no draft was needed."});
|
|
549
|
+
const target=args.draft??(({id,revision})=>({id,revision}))(drafts.create({units:[result.unit],title:`Token samples: ${args.id}`.slice(0,160)}));
|
|
550
|
+
const draft=drafts.update({...target,patch});
|
|
551
|
+
if(observeChanges)await refresh();
|
|
552
|
+
return json({...summary,draft,next:"Review the draft with ads_show_draft, then ads_accept with its exact revision."});
|
|
553
|
+
}}] : []),
|
|
553
554
|
...options.config.mcp.apps.map((app) => ({ name: `ads_show_${app.id.replaceAll("-", "_")}`, title: app.title, description: `${app.description ?? app.title}. Renders the project's built ${app.kind} examples through MCP Apps; text fallback provides the showcase URL.`, schema: empty, _meta: { ui: { resourceUri: appUri(app.id) } }, call: async (_args, signal) => {
|
|
554
555
|
// Validate readiness without embedding executable HTML in model results.
|
|
555
556
|
const build = await previewBuild(app, signal);
|
|
@@ -576,7 +577,7 @@ export function createAdsMcp(directory, { era = "legacy", skillDirectory, pollIn
|
|
|
576
577
|
void context.mcpReq.notify({ method: "notifications/progress", params: { progressToken: token, progress: ++progress, message: value.message ?? (value.stage?`${value.stage}: ${value.elapsedMs??0} ms elapsed`:`${value.profile}: ${value.completed}/${value.total} completed; ${(value.active ?? []).slice(0,3).map(item => `${item.unit}#${item.check}`).join(", ") || "no active check reported"}; ${value.elapsedMs} ms elapsed`) } }).catch(() => {});
|
|
577
578
|
};
|
|
578
579
|
try {
|
|
579
|
-
const kinds={ads_validate:"validation",ads_verify:"verification",
|
|
580
|
+
const kinds={ads_validate:"validation",ads_verify:"verification",ads_accept:"mutation"};
|
|
580
581
|
const kind=kinds[name];
|
|
581
582
|
if(!kind)return await tool.call(input.data,context.mcpReq.signal,notify);
|
|
582
583
|
const client=server.getClientVersion?.();
|
|
@@ -629,7 +630,7 @@ export function createAdsMcp(directory, { era = "legacy", skillDirectory, pollIn
|
|
|
629
630
|
});
|
|
630
631
|
if (era === "modern") {
|
|
631
632
|
server.setRequestHandler("skills/list", schemas, ({ cursor }) => {
|
|
632
|
-
const listing = page(skills.skills, cursor, "skills"
|
|
633
|
+
const listing = page(skills.skills, cursor, "skills");
|
|
633
634
|
return { resultType: "complete", ttlMs: 300000, cacheScope: "public", skills: listing.items, ...(listing.nextCursor ? { nextCursor: listing.nextCursor } : {}) };
|
|
634
635
|
});
|
|
635
636
|
server.setRequestHandler("skills/get", { ...schemas, params: z.object({ uri: z.string() }).passthrough() }, ({ uri }) => {
|
|
@@ -639,7 +640,7 @@ export function createAdsMcp(directory, { era = "legacy", skillDirectory, pollIn
|
|
|
639
640
|
const children = skills.directories.get(uri);
|
|
640
641
|
if (!children) throw new ResourceNotFoundError(uri, "Unknown skill directory (no trailing slash).");
|
|
641
642
|
const listing = page(children, cursor, "directory");
|
|
642
|
-
return { resultType: "complete", resources: listing.items, ...(listing.nextCursor ? { nextCursor: listing.nextCursor } : {}) };
|
|
643
|
+
return { resultType: "complete", ttlMs: 300000, cacheScope: "public", resources: listing.items, ...(listing.nextCursor ? { nextCursor: listing.nextCursor } : {}) };
|
|
643
644
|
});
|
|
644
645
|
}
|
|
645
646
|
|
|
@@ -786,26 +787,65 @@ export function createAdsMcp(directory, { era = "legacy", skillDirectory, pollIn
|
|
|
786
787
|
return { server, refresh, warmScenarios, buildAll(signal, options) { previewWatch.setApps(allApps()); return previewWatch.buildAll(signal, options); }, readResource:read, async callTool(name,args,signal){const tool=tools().find(tool=>tool.name===name);if(!tool)throw new Error("Unknown preview tool.");return tool.call(tool.schema.parse(args),signal);}, async close() { executionObservers.delete(executionChanged);stopObservation(); if (!inspection) { await coordinator.close(); await cache.registryInspector?.close(); await drafts.close(); await validation.close(); await verification.close(); await captures.close(); } await server.close(); } };
|
|
787
788
|
}
|
|
788
789
|
|
|
789
|
-
|
|
790
|
+
/** A draft workspace's preview, served by the project's runtime and compiled by its compiler. */
|
|
791
|
+
export function createDraftPreview(workspace, { id, host, showcaseUrl, mountPreview, previewWork }) {
|
|
792
|
+
const { root, config } = loadConfig(workspace);
|
|
793
|
+
const previewWatch = createReconfigurablePreviewWatch(root, config.mcp, { delegate: host, prewarm: false });
|
|
794
|
+
const inspection = { skills: createSkillStore(), previewWork };
|
|
795
|
+
const listeners = new Set();
|
|
796
|
+
let timer, api;
|
|
797
|
+
const preview = () => api ??= createAdsMcp(root, { era: "modern", inspection, previewWatch, showcaseUrl: () => url, mutations: false, pollInterval: 0, observeChanges: false });
|
|
798
|
+
let watcher;
|
|
799
|
+
try {
|
|
800
|
+
mkdirSync(path.join(root, ".ds"), { recursive: true });
|
|
801
|
+
watcher = watch(path.join(root, ".ds"), (_event, file) => {
|
|
802
|
+
const selected = previewWatch.resourceSession();
|
|
803
|
+
if (String(file) !== (selected ? `build-status-${selected}.json` : "build-status.json")) return;
|
|
804
|
+
clearTimeout(timer);
|
|
805
|
+
timer = setTimeout(() => { try { const report = previewWatch.buildStatus(); for (const listener of listeners) listener(report); } catch { /* Retried on the next report. */ } }, 16); timer.unref();
|
|
806
|
+
});
|
|
807
|
+
watcher.unref(); watcher.on("error", () => watcher.close());
|
|
808
|
+
} catch { /* Build changes still arrive through explicit status reads. */ }
|
|
809
|
+
// The draft's own showcase, mounted on the project's host: the real standalone scenario page that
|
|
810
|
+
// audits, captures and behavior checks open.
|
|
811
|
+
const base = showcaseUrl?.(), prefix = `/draft/${id}/`;
|
|
812
|
+
const url = base ? new URL(prefix, base).href : undefined;
|
|
813
|
+
const ownUrl = () => url;
|
|
814
|
+
const unmount = mountPreview?.(prefix, () => createAdsMcp(root, { era: "modern", inspection, previewWatch, showcaseUrl: ownUrl, mutations: false, pollInterval: 0, observeChanges: false }).server);
|
|
815
|
+
return { url, prewarm: () => previewWatch.initialize(), buildStatus: () => previewWatch.buildStatus(),
|
|
816
|
+
warmScenarios: (ids, signal) => preview().warmScenarios(ids, signal), buildAll: async (signal, options) => { await previewWatch.initialize(); return preview().buildAll(signal, options); },
|
|
817
|
+
onBuildChange(listener) { listeners.add(listener); return () => listeners.delete(listener); },
|
|
818
|
+
primeRegistry(registry) { if (inspection.registry === registry || inspection.lastRegistry === registry) return; inspection.registry = inspection.lastRegistry = registry; inspection.registryRevision = undefined; inspection.catalog = undefined; },
|
|
819
|
+
callTool: (name, args, signal) => preview().callTool(name, args, signal), readResource: (uri, signal) => preview().readResource(uri, signal),
|
|
820
|
+
// The draft's verified preview revision, as the project host reports its own: captures and
|
|
821
|
+
// behavior evidence record which build they observed.
|
|
822
|
+
previewRevision: () => readPreviewManifest(withPreviewSession(loadConfig(root), previewWatch.resourceSession()))?.revision ?? null,
|
|
823
|
+
async close() { clearTimeout(timer); watcher?.close(); listeners.clear(); await Promise.allSettled([Promise.resolve().then(() => unmount?.()), previewWatch.stop(), api?.close()]); } };
|
|
824
|
+
}
|
|
825
|
+
|
|
826
|
+
export async function startAdsMcp(directory = process.cwd(), { stdio = true, despitePolicy = false, showcase = true, port = 0, mutations = false, previewWork = createPreviewWork(), previewBuildTimeoutMs, prewarm = stdio } = {}) {
|
|
790
827
|
if (process.versions.bun) assertBunRuntime();
|
|
791
828
|
// Fail before opening the transport for configuration/distribution errors.
|
|
792
829
|
const { root, config } = loadConfig(directory);
|
|
830
|
+
// The server and its preview compiler run this project's ads check in a warm worker (check-service.mjs).
|
|
831
|
+
useWarmChecks(root);
|
|
793
832
|
// The generated theme sheet follows the token sheets and ds.config.json from startup on.
|
|
794
833
|
const themesWatch = watchThemesCss(root, { log: message => process.stderr.write(`${message}\n`) });
|
|
795
834
|
const inspection = { skills: createSkillStore(), previewWork };
|
|
796
|
-
const previewWatch = createReconfigurablePreviewWatch(root, config.mcp, {buildTimeout:previewBuildTimeoutMs,prewarm,despitePolicy});
|
|
835
|
+
const previewWatch = createReconfigurablePreviewWatch(root, config.mcp, {...(previewBuildTimeoutMs === undefined ? {} : {buildTimeout:previewBuildTimeoutMs}),prewarm,despitePolicy});
|
|
797
836
|
let host, api;
|
|
798
837
|
let buildWatcher, buildChangeTimer;
|
|
799
838
|
const buildListeners = new Set();
|
|
800
839
|
const onBuildChange = report => { for (const listener of buildListeners) listener(report); };
|
|
801
840
|
const showcaseUrl = () => host?.url;
|
|
841
|
+
const mountPreview = (prefix, factory) => host?.mount(prefix, factory);
|
|
802
842
|
if (showcase) {
|
|
803
|
-
host = await startShowcaseHost(({ era }) => createAdsMcp(directory, { era, previewWatch, showcaseUrl, inspection, mutations, pollInterval: 0, observeChanges:false }).server,
|
|
804
|
-
{ port, observe: notifications => createAdsMcp(directory, { era: "modern", previewWatch, showcaseUrl, inspection, mutations, notifications, onBuildChange }) });
|
|
843
|
+
host = await startShowcaseHost(({ era }) => createAdsMcp(directory, { era, previewWatch, showcaseUrl, mountPreview, inspection, mutations, pollInterval: 0, observeChanges:false }).server,
|
|
844
|
+
{ port, observe: notifications => createAdsMcp(directory, { era: "modern", previewWatch, showcaseUrl, mountPreview, inspection, mutations, notifications, onBuildChange }) });
|
|
805
845
|
process.stderr.write(`ADS showcase: ${host.url}\n`);
|
|
806
846
|
}
|
|
807
847
|
const transport = stdio ? new StdioServerTransport() : null;
|
|
808
|
-
const handle = stdio ? serveStdio(({ era }) => createAdsMcp(directory, { era, previewWatch, showcaseUrl, inspection, mutations, onBuildChange }).server, { transport, legacy: "serve", onerror: (error) => process.stderr.write(`ads mcp: ${error.message}\n`) }) : null;
|
|
848
|
+
const handle = stdio ? serveStdio(({ era }) => createAdsMcp(directory, { era, previewWatch, showcaseUrl, mountPreview, inspection, mutations, onBuildChange }).server, { transport, legacy: "serve", onerror: (error) => process.stderr.write(`ads mcp: ${error.message}\n`) }) : null;
|
|
809
849
|
try {
|
|
810
850
|
buildWatcher = watch(path.join(root, ".ds"), (_event, file) => {
|
|
811
851
|
const selected = previewWatch.resourceSession();
|
|
@@ -844,6 +884,7 @@ export async function startAdsMcp(directory = process.cwd(), { stdio = true, des
|
|
|
844
884
|
Promise.resolve().then(() => inspection.registryInspector?.close()),
|
|
845
885
|
Promise.resolve().then(() => api?.close()),
|
|
846
886
|
Promise.resolve().then(() => handle?.close()),
|
|
887
|
+
Promise.resolve().then(() => releaseWarmChecks(root)),
|
|
847
888
|
]);
|
|
848
889
|
for (const event of ["end", "close", "error"]) process.stdin.removeListener(event, disconnect);
|
|
849
890
|
for (const signal of ["SIGINT", "SIGTERM"]) process.removeListener(signal, disconnect);
|
|
@@ -10,6 +10,9 @@ export async function startShowcaseHost(factory, { port = 0, observe } = {}) {
|
|
|
10
10
|
["/", "index.html", "text/html"], ["/client.js", "client.bundle.js", "text/javascript"], ["/style.css", "style.css", "text/css"],
|
|
11
11
|
].map(async ([route, file, type]) => [route, { type, bytes: await readFile(new URL(`../showcase/${file}`, import.meta.url)) }])));
|
|
12
12
|
const handler = createMcpHandler(factory, { legacy: "reject", maxRequestBodySize: 2 * 1024 * 1024 });
|
|
13
|
+
// Draft previews are served from this same host under /draft/<id>/: the same client, with that
|
|
14
|
+
// draft's own MCP endpoint. No other port or process.
|
|
15
|
+
const mounts = new Map();
|
|
13
16
|
const observer = observe?.(handler.notify);
|
|
14
17
|
const requests = new Set();
|
|
15
18
|
let sandbox;
|
|
@@ -19,23 +22,26 @@ export async function startShowcaseHost(factory, { port = 0, observe } = {}) {
|
|
|
19
22
|
res.writeHead(403); res.end("Only the local showcase may access this host."); return;
|
|
20
23
|
}
|
|
21
24
|
const url = new URL(req.url, origin);
|
|
22
|
-
|
|
25
|
+
const mount = [...mounts].find(([prefix]) => url.pathname.startsWith(prefix));
|
|
26
|
+
const route = mount ? `/${url.pathname.slice(mount[0].length)}` : url.pathname, target = mount ? mount[1] : handler;
|
|
27
|
+
if (mount && url.pathname === mount[0].slice(0, -1)) { res.writeHead(308, { Location: mount[0] + url.search }); res.end(); return; }
|
|
28
|
+
if (route === "/host.json" && req.method === "GET") {
|
|
23
29
|
res.writeHead(200, { "Content-Type": "application/json", "Cache-Control": "no-store" });
|
|
24
30
|
res.end(JSON.stringify({ sandboxUrl: sandbox?.url })); return;
|
|
25
31
|
}
|
|
26
|
-
const asset = assets.get(
|
|
27
|
-
if (req.method === "GET" && (asset ||
|
|
32
|
+
const asset = assets.get(route);
|
|
33
|
+
if (req.method === "GET" && (asset || route === "/favicon.ico")) {
|
|
28
34
|
res.writeHead(asset ? 200 : 204, { "Content-Type": asset?.type ?? "image/x-icon", "Cache-Control": "no-store", "X-Content-Type-Options": "nosniff", "Content-Security-Policy": `default-src 'self'; script-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self' data:; font-src 'self'; frame-src ${sandbox ? new URL(sandbox.url).origin : "'none'"};connect-src 'self';object-src 'none'` });
|
|
29
35
|
res.end(asset?.bytes); return;
|
|
30
36
|
}
|
|
31
|
-
if (
|
|
37
|
+
if (route !== "/mcp") { res.writeHead(404); res.end("Not found"); return; }
|
|
32
38
|
const abort = new AbortController();
|
|
33
39
|
requests.add(abort);
|
|
34
40
|
res.once("close", () => { requests.delete(abort); abort.abort(); });
|
|
35
41
|
try {
|
|
36
42
|
const request = new Request(url, { method: req.method, headers: req.headers, signal: abort.signal,
|
|
37
43
|
...(req.method === "POST" ? { body: Readable.toWeb(req), duplex: "half" } : {}) });
|
|
38
|
-
const response = await
|
|
44
|
+
const response = await target.fetch(request);
|
|
39
45
|
res.writeHead(response.status, Object.fromEntries(response.headers));
|
|
40
46
|
if (response.body) {
|
|
41
47
|
const stream = Readable.fromWeb(response.body);
|
|
@@ -58,7 +64,14 @@ export async function startShowcaseHost(factory, { port = 0, observe } = {}) {
|
|
|
58
64
|
}
|
|
59
65
|
catch (error) { web.close(); await observer?.close(); await handler.close(); throw error; }
|
|
60
66
|
let closing;
|
|
61
|
-
return { url: `http://127.0.0.1:${web.address().port}/`,
|
|
67
|
+
return { url: `http://127.0.0.1:${web.address().port}/`,
|
|
68
|
+
/** Serve another MCP server's showcase under a path prefix such as /draft/<id>/. */
|
|
69
|
+
mount(prefix, mountFactory) {
|
|
70
|
+
const mounted = createMcpHandler(mountFactory, { legacy: "reject", maxRequestBodySize: 2 * 1024 * 1024 });
|
|
71
|
+
mounts.set(prefix, mounted);
|
|
72
|
+
return async () => { if (mounts.get(prefix) === mounted) mounts.delete(prefix); await mounted.close(); };
|
|
73
|
+
},
|
|
74
|
+
close() {
|
|
62
75
|
return closing ??= (async () => {
|
|
63
76
|
// Close sockets first: live subscriptions and preview requests must not
|
|
64
77
|
// hold shutdown open while protocol instances wait for cancellation.
|
|
@@ -67,7 +80,7 @@ export async function startShowcaseHost(factory, { port = 0, observe } = {}) {
|
|
|
67
80
|
web.closeAllConnections();
|
|
68
81
|
const results = await Promise.allSettled([stopped,
|
|
69
82
|
Promise.resolve().then(() => observer?.close()),
|
|
70
|
-
handler.close(), sandbox?.close(),
|
|
83
|
+
handler.close(), sandbox?.close(), ...[...mounts.values()].map(mounted => mounted.close()),
|
|
71
84
|
]);
|
|
72
85
|
const errors = results.filter(result => result.status === "rejected").map(result => result.reason);
|
|
73
86
|
if (errors.length) throw new AggregateError(errors, "Showcase shutdown failed");
|