@reqvire-org/ads 0.3.38 → 0.3.39
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 +2 -0
- package/dist/bootstrap-ds/ds.config.json +2 -0
- package/dist/cli.mjs +7 -4
- package/dist/config.mjs +11 -6
- package/dist/mcp/context.mjs +4 -3
- package/dist/mcp/drafts.mjs +126 -10
- package/dist/mcp/execution-results.mjs +2 -2
- package/dist/mcp/mutations.mjs +3 -2
- package/dist/mcp/server.mjs +15 -7
- package/dist/skills/ads-break-ui/references/behaviors.md +8 -4
- package/dist/skills/ads-break-ui/references/drafts.md +26 -5
- package/dist/skills/ads-break-ui/references/guarded-editing.md +4 -2
- package/dist/skills/ads-break-ui/references/runtimes.md +4 -3
- package/dist/skills/ads-break-ui/references/validation.md +43 -25
- package/dist/skills/ads-break-ui/references/workflows.md +4 -3
- package/dist/skills/ads-designer/SKILL.md +7 -3
- package/dist/skills/ads-designer/assets/bootstrap-ds/ds.config.json +2 -0
- package/dist/skills/ads-designer/references/behaviors.md +8 -4
- package/dist/skills/ads-designer/references/cli.md +1 -1
- package/dist/skills/ads-designer/references/drafts.md +26 -5
- package/dist/skills/ads-designer/references/guarded-editing.md +4 -2
- package/dist/skills/ads-designer/references/runtimes.md +4 -3
- package/dist/skills/ads-designer/references/validation.md +43 -25
- package/dist/skills/ads-designer/references/workflows.md +4 -3
- package/dist/skills/ads-import/references/behaviors.md +8 -4
- package/dist/skills/ads-import/references/cli.md +1 -1
- package/dist/skills/ads-import/references/drafts.md +26 -5
- package/dist/skills/ads-import/references/guarded-editing.md +4 -2
- package/dist/skills/ads-import/references/runtimes.md +4 -3
- package/dist/skills/ads-import/references/validation.md +43 -25
- package/dist/skills/ads-import/references/workflows.md +4 -3
- package/dist/skills/ads-motion/references/behaviors.md +8 -4
- package/dist/skills/ads-motion/references/drafts.md +26 -5
- package/dist/skills/ads-motion/references/guarded-editing.md +4 -2
- package/dist/skills/ads-motion/references/runtimes.md +4 -3
- package/dist/skills/ads-motion/references/validation.md +43 -25
- package/dist/skills/ads-motion/references/workflows.md +4 -3
- package/dist/skills/ads-port/references/behaviors.md +8 -4
- package/dist/skills/ads-port/references/cli.md +1 -1
- package/dist/skills/ads-port/references/drafts.md +26 -5
- package/dist/skills/ads-port/references/guarded-editing.md +4 -2
- package/dist/skills/ads-port/references/runtimes.md +4 -3
- package/dist/skills/ads-port/references/validation.md +43 -25
- package/dist/skills/ads-port/references/workflows.md +4 -3
- package/dist/units.mjs +1 -1
- package/dist/validation-checks.mjs +10 -5
- package/dist/validation.mjs +16 -31
- package/docs/ARCHITECTURE.md +8 -4
- package/docs/BEHAVIORS.md +6 -3
- package/docs/CHANGELOG.md +49 -12
- package/docs/GUIDE.md +12 -6
- package/docs/MCP.md +27 -15
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -102,6 +102,8 @@ Linaria; integrate its extraction with your build as described in the
|
|
|
102
102
|
|---------|-----|
|
|
103
103
|
| `ads init --framework react` | Set up ADS in the current project; also accepts `preact`; saved choices can omit the flag |
|
|
104
104
|
| `ads check` | Check tokens, styles, imports, and ADS ownership |
|
|
105
|
+
| `ads validate` | Run the configured validation policy and current-preview audit |
|
|
106
|
+
| `ads validate --policy acceptance` | Check the acceptance policy against direct source edits without applying changes |
|
|
105
107
|
| `ads compile` | Compile all previews with Bun; `--watch` rebuilds on edits |
|
|
106
108
|
| `ads tokens` | Inspect token values and themes |
|
|
107
109
|
| `ads behaviors` | Inspect registered behavior guarantees and current evidence |
|
package/dist/cli.mjs
CHANGED
|
@@ -14,7 +14,8 @@ Usage: ads init [options] Run inside your project
|
|
|
14
14
|
init Set up ADS in the current project (requires package.json)
|
|
15
15
|
check [directory] Check tokens, ownership, imports, and showcase coverage
|
|
16
16
|
compile [directory] Build ADS previews with Bun (--watch for incremental previews)
|
|
17
|
-
validate [dir] Audit ADS gates
|
|
17
|
+
validate [dir] Audit ADS gates and the chosen project policy
|
|
18
|
+
--policy acceptance|validation (default validation)
|
|
18
19
|
behaviors [dir] Inspect behavior contracts and current verification evidence
|
|
19
20
|
verify [directory] Run registered behavior checks (--unit and --check select)
|
|
20
21
|
tokens [directory] Inspect local token values and theme definitions
|
|
@@ -52,13 +53,14 @@ async function main(args) {
|
|
|
52
53
|
const selectedChecks = [];
|
|
53
54
|
let showcase = true;
|
|
54
55
|
let mutations = false;
|
|
55
|
-
let changed = false, watched = false;
|
|
56
|
+
let changed = false, watched = false, policy;
|
|
56
57
|
const positional = [];
|
|
57
58
|
for (let index = 0; index < args.length; index++) {
|
|
58
59
|
const argument = args[index];
|
|
59
60
|
if (argument === "--json") json = true;
|
|
60
61
|
else if(argument === "--watch") watched = true;
|
|
61
62
|
else if (argument === "--changed") changed = true;
|
|
63
|
+
else if (argument === "--policy") {if(policy!==undefined || !["acceptance","validation"].includes(args[index+1]))throw new Error("--policy requires acceptance or validation.");policy=args[++index];}
|
|
62
64
|
else if (argument === "--no-showcase") showcase = false;
|
|
63
65
|
else if (argument === "--mutations") mutations = true;
|
|
64
66
|
else if (argument === "--unit" || argument === "--check") {
|
|
@@ -93,6 +95,7 @@ async function main(args) {
|
|
|
93
95
|
const { checkProject, generateBrandAssets, generateLintConfig, initProject, inspectTokens } = await import("./index.mjs");
|
|
94
96
|
if(watched&&command!=="compile")throw new Error("--watch is supported only by compile.");
|
|
95
97
|
if(command==="compile"){const {compilePreviews}=await import("./bun-compiler.mjs");await compilePreviews(path.resolve(directory??process.cwd()),{watched});return;}
|
|
98
|
+
if (policy!==undefined && command!=="validate")throw new Error("--policy is supported only by validate.");
|
|
96
99
|
if (changed && command !== "validate") throw new Error("--changed is supported only by validate.");
|
|
97
100
|
if ((port !== undefined || !showcase) && !["mcp", "showcase"].includes(command)) throw new Error("Website options are supported only by mcp/showcase.");
|
|
98
101
|
if (!showcase && command !== "mcp") throw new Error("--no-showcase is supported only by mcp.");
|
|
@@ -116,7 +119,7 @@ async function main(args) {
|
|
|
116
119
|
const {createValidationController}=await import("./validation.mjs");
|
|
117
120
|
const validation=createValidationController(target);
|
|
118
121
|
const abort=()=>{void validation.close();};process.once("SIGINT",abort);process.once("SIGTERM",abort);
|
|
119
|
-
try {result=await validation.run({scope:changed?"changed":"all"});}
|
|
122
|
+
try {result=await validation.run({scope:changed?"changed":"all",policy});}
|
|
120
123
|
finally {process.removeListener("SIGINT",abort);process.removeListener("SIGTERM",abort);await validation.close();}
|
|
121
124
|
}
|
|
122
125
|
else if (command === "behaviors") { const {behaviorStatus}=await import("./verification.mjs"); const {loadConfig}=await import("./config.mjs"); result=behaviorStatus(loadConfig(target)); }
|
|
@@ -131,7 +134,7 @@ async function main(args) {
|
|
|
131
134
|
else if (command === "lint-config") console.log(`Generated ${result.file}\nUse this optional configuration only in the project linter you choose to run.`);
|
|
132
135
|
else if (command === "behaviors") console.log(JSON.stringify(result, null, 2));
|
|
133
136
|
else if (command === "verify") { for (const item of result.results) console.log(`${item.unit}#${item.check}: ${item.status} (${item.profile})`); }
|
|
134
|
-
else if (command === "validate") {console.log(`ADS
|
|
137
|
+
else if (command === "validate") {console.log(`ADS ${result.policy} ${result.ok?"passed":"failed"}: ${result.scope}${result.fallback?` (${result.fallback})`:""}`);for(const check of result.checks)console.log(`${check.name}: ${check.skipped?"skipped":check.passed?"passed":"failed"}${check.reason?` (${check.reason})`:""}`);}
|
|
135
138
|
else if (command === "tokens") {
|
|
136
139
|
for (const token of result.tokens) console.log(`${token.name}${token.type ? ` (${token.type})` : ""}: ${token.definitions.map((entry) => `${entry.scope}: ${entry.value}`).join("; ")}`);
|
|
137
140
|
} else if (result.ok) console.log(`ADS check passed: ${target}`);
|
package/dist/config.mjs
CHANGED
|
@@ -22,9 +22,10 @@ export const defaultConfig = {
|
|
|
22
22
|
boundaries: { styleWrites: [], componentVariables: [] },
|
|
23
23
|
assets: { publicDirs: ["public/assets"], generatedPaths: ["dist", "dist-showcase", ".vite", ".ds"], generatedFiles: [], iconSource: null },
|
|
24
24
|
oxlint: { plugins: [], rules: {}, overrides: [] },
|
|
25
|
-
|
|
25
|
+
acceptance: { checks: [], behaviorChecks: false },
|
|
26
|
+
validation: { checks: [], behaviorChecks: true, inputs: [] },
|
|
26
27
|
resources: { memoryLimitMb: null },
|
|
27
|
-
mcp: { showcaseUrl: null, showcaseTitle: null, apps: [], previewWatch: null, previewManifest: null,
|
|
28
|
+
mcp: { showcaseUrl: null, showcaseTitle: null, apps: [], previewWatch: null, previewManifest: null, mutationCheckTimeoutMs: 60000, behaviorProfiles: {}, capture: {} },
|
|
28
29
|
};
|
|
29
30
|
|
|
30
31
|
export function isInside(parent, file) {
|
|
@@ -50,11 +51,12 @@ export function loadConfig(directory = process.cwd()) {
|
|
|
50
51
|
if (!(field in defaultConfig)) throw new Error(`Unknown ADS configuration field: ${field}`);
|
|
51
52
|
}
|
|
52
53
|
if (user.oxlint !== undefined && (!user.oxlint || typeof user.oxlint !== "object" || Array.isArray(user.oxlint))) throw new Error("oxlint must be an object.");
|
|
53
|
-
|
|
54
|
+
if (user.mcp && Object.hasOwn(user.mcp,"mutationChecks")) throw new Error("Move mcp.mutationChecks to acceptance.checks; choose acceptance.behaviorChecks explicitly. ADS no longer infers project scripts.");
|
|
55
|
+
for (const field of ["boundaries", "assets", "oxlint", "mcp", "acceptance", "validation", "usage", "resources"]) {
|
|
54
56
|
if (user[field] !== undefined && (!user[field] || typeof user[field] !== "object" || Array.isArray(user[field]))) throw new Error(`${field} must be an object.`);
|
|
55
57
|
for (const key of Object.keys(user[field] ?? {})) if (!(key in defaultConfig[field])) throw new Error(`Unknown ${field} configuration field: ${key}`);
|
|
56
58
|
}
|
|
57
|
-
const config = { ...defaultConfig, ...user, boundaries: { ...defaultConfig.boundaries, ...user.boundaries }, assets: { ...defaultConfig.assets, ...user.assets }, oxlint: { ...defaultConfig.oxlint, ...user.oxlint }, validation: { ...defaultConfig.validation, ...user.validation }, mcp: { ...defaultConfig.mcp, ...user.mcp }, usage: { ...defaultConfig.usage, ...user.usage }, resources: { ...defaultConfig.resources, ...user.resources } };
|
|
59
|
+
const config = { ...defaultConfig, ...user, boundaries: { ...defaultConfig.boundaries, ...user.boundaries }, assets: { ...defaultConfig.assets, ...user.assets }, oxlint: { ...defaultConfig.oxlint, ...user.oxlint }, acceptance: { ...defaultConfig.acceptance, ...user.acceptance }, validation: { ...defaultConfig.validation, ...user.validation }, mcp: { ...defaultConfig.mcp, ...user.mcp }, usage: { ...defaultConfig.usage, ...user.usage }, resources: { ...defaultConfig.resources, ...user.resources } };
|
|
58
60
|
if(config.resources.memoryLimitMb!==null&&(!Number.isInteger(config.resources.memoryLimitMb)||config.resources.memoryLimitMb<64||config.resources.memoryLimitMb>1048576))throw new Error("resources.memoryLimitMb must be null (automatic) or an integer from 64 to 1048576 MiB.");
|
|
59
61
|
if (!Array.isArray(config.usage.notifications) || config.usage.notifications.length > 100) throw new Error("usage.notifications must be an array of notification API registrations.");
|
|
60
62
|
const notificationNames = new Set();
|
|
@@ -69,7 +71,11 @@ export function loadConfig(directory = process.cwd()) {
|
|
|
69
71
|
}
|
|
70
72
|
}
|
|
71
73
|
if (!Array.isArray(config.usage.restrictedImports) || config.usage.restrictedImports.length > 100 || new Set(config.usage.restrictedImports).size !== config.usage.restrictedImports.length || config.usage.restrictedImports.some(name => typeof name !== "string" || !/^(?:@[a-z0-9][a-z0-9._~-]*\/)?[a-z0-9][a-z0-9._~-]*$/.test(name))) throw new Error("usage.restrictedImports must contain distinct npm package names.");
|
|
72
|
-
|
|
74
|
+
for (const name of ["acceptance","validation"]) {
|
|
75
|
+
const policy=config[name];
|
|
76
|
+
if (!Array.isArray(policy.checks) || policy.checks.length>20 || new Set(policy.checks).size!==policy.checks.length || policy.checks.some(script=>typeof script!=="string" || !/^[a-zA-Z0-9][\w:.-]*$/.test(script))) throw new Error(`${name}.checks must contain up to 20 unique package script names.`);
|
|
77
|
+
if(typeof policy.behaviorChecks!=="boolean")throw new Error(`${name}.behaviorChecks must be a boolean.`);
|
|
78
|
+
}
|
|
73
79
|
if (!Array.isArray(config.validation.inputs) || config.validation.inputs.length > 200 || new Set(config.validation.inputs).size !== config.validation.inputs.length) throw new Error("validation.inputs must contain at most 200 unique project-relative files or directories.");
|
|
74
80
|
for (const file of config.validation.inputs) {
|
|
75
81
|
const absolute = projectPath(root,file,"validation.inputs");
|
|
@@ -148,7 +154,6 @@ export function loadConfig(directory = process.cwd()) {
|
|
|
148
154
|
|| profile.timeoutMs !== undefined && (!Number.isInteger(profile.timeoutMs) || profile.timeoutMs < 100 || profile.timeoutMs > 900000)) throw new Error(`Invalid behavior profile ${name}. Use literal executable/args, a protocol or Playwright runner, a matching framework and a timeout from 100 to 900000 ms. Profiles do not install dependencies or receive APIs from an MCP host.`);
|
|
149
155
|
if (profile.mode === "strict" && config.framework !== "react") throw new Error(`Behavior profile ${name}: React StrictMode requires framework react; use the configured framework's lifecycle tests instead.`);
|
|
150
156
|
}
|
|
151
|
-
if (config.mcp.mutationChecks !== null && (!Array.isArray(config.mcp.mutationChecks) || config.mcp.mutationChecks.length > 12 || new Set(config.mcp.mutationChecks).size !== config.mcp.mutationChecks.length || config.mcp.mutationChecks.some(name => typeof name !== "string" || !/^[a-zA-Z0-9][\w:.-]*$/.test(name)))) throw new Error("mcp.mutationChecks must be null or up to 12 unique package script names.");
|
|
152
157
|
if (!Number.isInteger(config.mcp.mutationCheckTimeoutMs) || config.mcp.mutationCheckTimeoutMs < 100 || config.mcp.mutationCheckTimeoutMs > 300000) throw new Error("mcp.mutationCheckTimeoutMs must be an integer from 100 to 300000. This budget applies to each registered project script, separately from behavior profiles.");
|
|
153
158
|
if (config.mcp.previewManifest !== null) {
|
|
154
159
|
const manifest = projectPath(root, config.mcp.previewManifest, "mcp.previewManifest");
|
package/dist/mcp/context.mjs
CHANGED
|
@@ -6,7 +6,7 @@ import { developmentRuntime, packageScriptCommand } from "../development-runtime
|
|
|
6
6
|
|
|
7
7
|
export const GUIDE_URI = "ads://project/guide";
|
|
8
8
|
// Put the task triggers and entry path first: some hosts shorten server guidance.
|
|
9
|
-
export const serverInstructions = "Use ADS for UI work: components, patterns, controllers, hooks, tokens, themes, branding, layout, interaction, accessibility, motion and showcase review. Start with ads_status; if tools are not exposed, read ads://project/guide then ads://project/status. Use the returned projectRoot and commands. Choose direct source editing or MCP-only editing using ads://guides/workflows, based on actual editor access and user preference, not mutations.enabled. With direct code access, edit owned files normally and use MCP for preview/checks; ordinary direct edits do not require drafts or ads_accept. MCP-only iterative design uses enabled draft tools, rendered review and exact-revision ads_accept; read ads://guides/drafts. Complete tracked proposals by accepting required drafts; accept dependencies first and review dependents again. Without a source editor or enabled mutation tools, inspection is available but editing is not. Low-level MCP repairs can use ads_units and guarded ads_apply_patch for one owner or ads_apply_transaction for coupled owners. Find existing public UI with ads_catalog; discover its previews with ads_scenarios and open ads_show_scenario. Starting ADS also serves its built-in showcase: use ads_status.showcaseUrl for browser review instead of starting another runtime/compiler or project browser app. Read one relevant ADS skill before editing. Inspect the real preview, edit its owned source, check the build and review again. Scope source/guides to the project, its instruction ancestry and user-selected import/reference sources; broad searches of /mnt or home are not ADS discovery. Domain-model/requirements work is a separate project workflow. For requested visual evidence, use ads_capture or screenshot-enabled patch dry runs; read ads://guides/captures for named targets, image resources and the current/candidate lifecycle. For behavior work, read ads://guides/behaviors and use ads_behaviors/ads_verify: scenario exercises are demonstrations, and registered guarantees need current passing execution evidence. Use ads_validate with scope changed during editing, and the default full scope after test/ownership/config migrations, before releases, or for explicit complete audits. Read ads://guides/validation; report actual scope/revision and inspect failures through ads_results. Execution replies are bounded summaries. Read only needed sections with ads_results(resultId, section, status, cursor); follow nextCursor without rerunning. For a failure, inspect its boundary and acceptance, then ads_investigate with the outcome's exact unit/check/runId; detail sections and artifacts load separately (ads://guides/evidence). Preserve valid APIs when source tracing is inconclusive. After targeted investigation, record suspected ADS defects with ads_report_bug or missing capabilities with ads_request_feature; read ads://guides/reporting. These are local untriaged reports, not established causes or upstream issues. Use the configured project framework and declared dependencies; MCP hosts supply no ad hoc APIs. MCP source checks do not replace browser tests; direct edits still need project checks. Reading HTML is not rendering, and reading a skill is not native activation. A running watcher is not proof of current source: inspect ads_status.build or ads://project/build after edits. Notifications may not reach the agent. Only explicitly enabled mutation tools edit project-owned ADS units after validation. Checks and compiler commands come from validated project configuration, never an ad hoc command argument.";
|
|
9
|
+
export const serverInstructions = "Use ADS for UI work: components, patterns, controllers, hooks, tokens, themes, branding, layout, interaction, accessibility, motion and showcase review. Start with ads_status; if tools are not exposed, read ads://project/guide then ads://project/status. Use the returned projectRoot and commands. Choose direct source editing or MCP-only editing using ads://guides/workflows, based on actual editor access and user preference, not mutations.enabled. With direct code access, edit owned files normally and use MCP for preview/checks; ordinary direct edits do not require drafts or ads_accept. MCP-only iterative design uses enabled draft tools, rendered review and exact-revision ads_accept; read ads://guides/drafts. Complete tracked proposals by accepting required drafts; accept dependencies first and review dependents again. Without a source editor or enabled mutation tools, inspection is available but editing is not. Low-level MCP repairs can use ads_units and guarded ads_apply_patch for one owner or ads_apply_transaction for coupled owners. Find existing public UI with ads_catalog; discover its previews with ads_scenarios and open ads_show_scenario. Starting ADS also serves its built-in showcase: use ads_status.showcaseUrl for browser review instead of starting another runtime/compiler or project browser app. Read one relevant ADS skill before editing. Inspect the real preview, edit its owned source, check the build and review again. Scope source/guides to the project, its instruction ancestry and user-selected import/reference sources; broad searches of /mnt or home are not ADS discovery. Domain-model/requirements work is a separate project workflow. For requested visual evidence, use ads_capture or screenshot-enabled patch dry runs; read ads://guides/captures for named targets, image resources and the current/candidate lifecycle. For behavior work, read ads://guides/behaviors and use ads_behaviors/ads_verify: scenario exercises are demonstrations, and registered guarantees need current passing execution evidence. For direct edits, use ads_validate with policy acceptance to enforce the project acceptance policy without applying source. Draft acceptance uses the same configured policy on its candidate; draft edit/show runs neither policy. Test registration alone does not gate acceptance. Use ads_validate with scope changed during editing, and the default full validation policy/scope after test/ownership/config migrations, before releases, or for explicit complete audits. Read ads://guides/validation; report actual scope/revision and inspect failures through ads_results. Execution replies are bounded summaries. Read only needed sections with ads_results(resultId, section, status, cursor); follow nextCursor without rerunning. For a failure, inspect its boundary and acceptance, then ads_investigate with the outcome's exact unit/check/runId; detail sections and artifacts load separately (ads://guides/evidence). Preserve valid APIs when source tracing is inconclusive. After targeted investigation, record suspected ADS defects with ads_report_bug or missing capabilities with ads_request_feature; read ads://guides/reporting. These are local untriaged reports, not established causes or upstream issues. Use the configured project framework and declared dependencies; MCP hosts supply no ad hoc APIs. MCP source checks do not replace browser tests; direct edits still need project checks. Reading HTML is not rendering, and reading a skill is not native activation. A running watcher is not proof of current source: inspect ads_status.build or ads://project/build after edits. Notifications may not reach the agent. Only explicitly enabled mutation tools edit project-owned ADS units after validation. Checks and compiler commands come from validated project configuration, never an ad hoc command argument.";
|
|
10
10
|
|
|
11
11
|
function manager(root, pkg) {
|
|
12
12
|
if (typeof pkg.packageManager === "string") return pkg.packageManager.split("@")[0];
|
|
@@ -27,7 +27,8 @@ export function projectContext(options) {
|
|
|
27
27
|
publicEntry: path.join(dsRoot, config.publicEntry), publicEntryUri: existsSync(path.join(dsRoot, config.publicEntry)) ? sourceUri(path.relative(root, path.join(dsRoot, config.publicEntry)).replaceAll("\\", "/")) : null,
|
|
28
28
|
review: { importFrom: `${config.publicAlias}/review`, entry: path.join(dsRoot, config.reviewEntry), sourceUri: existsSync(path.join(dsRoot, config.reviewEntry)) ? sourceUri(path.relative(root, path.join(dsRoot, config.reviewEntry)).replaceAll("\\", "/")) : null, developmentOnly: true },
|
|
29
29
|
stylesEntry: path.join(dsRoot, config.stylesEntry), packageManager, commands, guides,
|
|
30
|
-
|
|
30
|
+
policies: {acceptance:config.acceptance,validation:config.validation},
|
|
31
|
+
validation: { tool: "ads_validate", policies:["acceptance","validation"], defaultPolicy:"validation", cli: ["ads", "validate"], defaultScope: "all", scopes: ["all","changed"], guideUri: "ads://guides/validation" },
|
|
31
32
|
showcase: { client: "tool-owned-mcp", url: config.mcp.showcaseUrl, title: config.mcp.showcaseTitle ?? `${pkg.name ?? path.basename(root)} · Design System` },
|
|
32
33
|
runtime: { ...developmentRuntime(),
|
|
33
34
|
shellHint: "The agent shell may have a different PATH from MCP. Use this runtime executable/bin directory and the returned project commands; do not search the whole machine or assume another runtime must be installed." } };
|
|
@@ -48,7 +49,7 @@ export function workflow(previews) {
|
|
|
48
49
|
],
|
|
49
50
|
preview: previews.length ? "Use ads_scenarios to select an exact path-derived id, then ads_show_scenario. Public UI and related parts share addressable scenarios; composition/ holds larger scenarios. Showcase and MCP mount the same source with colocated fixtures. The showcase is the tool's minimal MCP client and Apps host; it discovers these entries and invokes the same preview tools. Both transports share the published preview graph and the managed compiler when enabled. A reusable sandboxed App loads selected modules and shared runtime/CSS/fonts through MCP resources; no project code or styling belongs in the outer host. Check build freshness after changes."
|
|
50
51
|
: "No component scenarios or legacy Apps are registered. Token inspection is available in the built-in showcase. Existing components need colocated independently mountable scenarios/fixtures and a project compiler before MCP can render them. Do not create a replica or separate browser app to get a preview.",
|
|
51
|
-
validation: "
|
|
52
|
+
validation: "Run ads_validate with policy acceptance for direct source edits; guarded writes enforce that policy on isolated candidates. The project explicitly selects scripts and behavior gating through acceptance/validation configuration; no script names are inferred. Use the default validation policy for complete audits, and ads_verify for explicit behavior checks. Core checks do not replace required project commands. Review real UI in both themes; HTML delivery and compilation do not prove visual/behavioral correctness." };
|
|
52
53
|
}
|
|
53
54
|
|
|
54
55
|
export function projectGuide(context, previews) {
|
package/dist/mcp/drafts.mjs
CHANGED
|
@@ -1,3 +1,6 @@
|
|
|
1
|
+
import { spawnSync } from "node:child_process";
|
|
2
|
+
import { mkdtempSync } from "node:fs";
|
|
3
|
+
import { tmpdir } from "node:os";
|
|
1
4
|
import { createHash, randomUUID } from "node:crypto";
|
|
2
5
|
import { cpSync, existsSync, lstatSync, mkdirSync, readFileSync, readdirSync, realpathSync, renameSync, rmSync, symlinkSync, watch, writeFileSync } from "node:fs";
|
|
3
6
|
import path from "node:path";
|
|
@@ -18,7 +21,7 @@ export const DRAFTS_URI = "ads://project/drafts";
|
|
|
18
21
|
const hash = bytes => createHash("sha256").update(bytes).digest("hex");
|
|
19
22
|
const idSchema = z.string().regex(/^[a-z0-9][a-z0-9-]{0,79}$/);
|
|
20
23
|
const relative = z.string().min(1).max(500).refine(value => !path.isAbsolute(value) && !value.includes("\\") && !value.includes("\0") && !value.split("/").some(part => !part || part === "." || part === ".."), "Use a canonical project-relative path.");
|
|
21
|
-
const fileSchema = z.object({ target: relative, source: relative.nullable(), baseline: z.string().regex(/^[a-f0-9]{64}$/).nullable(), unit: z.string().max(256) }).strict();
|
|
24
|
+
const fileSchema = z.object({ target: relative, source: relative.nullable(), baseline: z.string().regex(/^[a-f0-9]{64}$/).nullable(), base: relative.optional(), unit: z.string().max(256) }).strict();
|
|
22
25
|
const draftUnits = z.array(z.string().min(1).max(256)).min(1).max(mutationLimits.units).refine(values=>new Set(values).size===values.length,"Draft owners must be unique.");
|
|
23
26
|
const manifestSchema = z.object({ schemaVersion: z.literal(1), id: idSchema, title: z.string().min(1).max(160), units: draftUnits, dependencies: z.array(idSchema).max(8).refine(values=>new Set(values).size===values.length,"Draft dependencies must be unique.").default([]), tokenGroups:z.array(z.string().min(1).max(160)).max(32).default([]), files: z.array(fileSchema).max(mutationLimits.files) }).strict();
|
|
24
27
|
export const draftIdSchema = idSchema;
|
|
@@ -51,11 +54,45 @@ function atomic(file, content) {
|
|
|
51
54
|
finally { rmSync(staging, { force: true }); }
|
|
52
55
|
}
|
|
53
56
|
const storedName = target => `files/${target}.ads`;
|
|
57
|
+
const baseName = target => `bases/${target}.ads`;
|
|
58
|
+
function mergeJson(current,baseline,proposed) {
|
|
59
|
+
const equal=(a,b)=>JSON.stringify(a)===JSON.stringify(b);
|
|
60
|
+
if(equal(current,baseline)||equal(current,proposed))return proposed;
|
|
61
|
+
if(equal(proposed,baseline))return current;
|
|
62
|
+
const object=value=>value!==null&&typeof value==="object"&&!Array.isArray(value);
|
|
63
|
+
if(![current,baseline,proposed].every(object))throw new Error("Overlapping JSON value edits.");
|
|
64
|
+
return Object.fromEntries([...new Set([...Object.keys(current),...Object.keys(baseline),...Object.keys(proposed)])]
|
|
65
|
+
.map(key=>[key,mergeJson(current[key],baseline[key],proposed[key])]).filter(([,value])=>value!==undefined));
|
|
66
|
+
}
|
|
67
|
+
function mergeSource(current, baseline, proposed, target) {
|
|
68
|
+
if (current === baseline || current === proposed) return proposed;
|
|
69
|
+
if (proposed === baseline) return current;
|
|
70
|
+
if ([current, baseline, proposed].some(value => value === null || value.includes("\0"))) throw new Error("Overlapping deletion, addition or binary edit.");
|
|
71
|
+
if(target.endsWith(".json")) {
|
|
72
|
+
const content=mergeJson(JSON.parse(current),JSON.parse(baseline),JSON.parse(proposed));
|
|
73
|
+
return JSON.stringify(content,null,current.match(/\n([ \t]+)"/)?.[1]??2)+(current.endsWith("\n")?"\n":"");
|
|
74
|
+
}
|
|
75
|
+
const folder = mkdtempSync(path.join(tmpdir(), "ads-draft-merge-"));
|
|
76
|
+
try {
|
|
77
|
+
const files = [current, baseline, proposed].map((content, index) => { const file=path.join(folder,String(index)); writeFileSync(file,content); return file; });
|
|
78
|
+
const result=spawnSync("git",["merge-file","-p","--",...files],{encoding:"utf8",timeout:5000,maxBuffer:32*1024**2});
|
|
79
|
+
if (result.error || result.status !== 0) throw new Error("Overlapping edits; resolve the draft source against the current project and retry.");
|
|
80
|
+
return result.stdout;
|
|
81
|
+
} finally { rmSync(folder,{recursive:true,force:true}); }
|
|
82
|
+
}
|
|
54
83
|
|
|
55
84
|
/** Tracked proposal source is separate from disposable compiler state. No Git checkout is required. */
|
|
56
85
|
export function createDraftController(directory, { edits, startPreview, prewarm = false, onChange, scenarioInspector } = {}) {
|
|
57
86
|
const root = path.resolve(directory), storage = path.join(root, DRAFT_DIRECTORY);
|
|
58
87
|
const previews = new Map();
|
|
88
|
+
function previewDirectory(id) {
|
|
89
|
+
const folder=path.join(root,".ds/draft-previews",idSchema.parse(id));
|
|
90
|
+
for(let current=folder;isInside(root,current);current=path.dirname(current)) {
|
|
91
|
+
if(lstatSync(current,{throwIfNoEntry:false})?.isSymbolicLink())throw new Error("Draft preview storage cannot resolve through a symlink.");
|
|
92
|
+
if(current===root)break;
|
|
93
|
+
}
|
|
94
|
+
return folder;
|
|
95
|
+
}
|
|
59
96
|
let active, closed = false;
|
|
60
97
|
let changeTimer, prewarmTimer, prewarming, pendingPrewarm;
|
|
61
98
|
const watchers = new Map();
|
|
@@ -74,6 +111,8 @@ export function createDraftController(directory, { edits, startPreview, prewarm
|
|
|
74
111
|
if (!manifest.units.includes(file.unit) || file.target.split("/").some(part => [DRAFT_DIRECTORY, ".ds", "node_modules", ".git"].includes(part))) throw new Error("Draft targets must be normal source owned by a declared unit.");
|
|
75
112
|
if (file.source && (!file.source.startsWith("files/") || !file.source.endsWith(".ads"))) throw new Error("Draft sources must use the non-importable .ads extension under files/.");
|
|
76
113
|
if (file.source) safe(path.dirname(manifestFile(id)), file.source);
|
|
114
|
+
if (file.base && (file.base !== baseName(file.target) || !file.baseline)) throw new Error("Invalid draft baseline source.");
|
|
115
|
+
if (file.base) safe(path.dirname(manifestFile(id)),file.base);
|
|
77
116
|
}
|
|
78
117
|
return manifest;
|
|
79
118
|
}
|
|
@@ -174,26 +213,64 @@ export function createDraftController(directory, { edits, startPreview, prewarm
|
|
|
174
213
|
const content = bytes(safe(root, target));
|
|
175
214
|
if (content === null) continue;
|
|
176
215
|
const source = storedName(target);
|
|
177
|
-
files.set(target, { target, source, baseline: hash(content), unit });
|
|
216
|
+
files.set(target, { target, source, baseline: hash(content), base: baseName(target), unit });
|
|
178
217
|
}
|
|
179
218
|
}
|
|
180
219
|
const manifest = manifestSchema.parse({ schemaVersion: 1, id, title: title ?? units.join(", ").slice(0,160), units, dependencies, tokenGroups:selectedGroups, files: [...files.values()] });
|
|
181
220
|
for (const dependency of dependencies) {const value=inspect(dependency,[id]);if(value.dependencyErrors.length)throw new Error(value.dependencyErrors[0].message);}
|
|
182
|
-
for (const file of manifest.files)
|
|
221
|
+
for (const file of manifest.files) {
|
|
222
|
+
const content=bytes(safe(root,file.target)),folder=path.dirname(manifestFile(id));
|
|
223
|
+
atomic(safe(folder,file.source),content); atomic(safe(folder,file.base),content);
|
|
224
|
+
}
|
|
183
225
|
save(manifest);
|
|
184
226
|
const value = inspect(id); event(id, value.revision, "created");
|
|
185
227
|
reconcileWatches(); queuePrewarm(id);
|
|
186
228
|
return { ...summary(value), directory: `${DRAFT_DIRECTORY}/${id}`, next: "Edit the marked source files, or register new/deleted files with ads_update_draft. Use ads_show_draft, review the rendered result, then ads_accept with its exact revision. Do not finish a design change with unaccepted drafts." };
|
|
187
229
|
}
|
|
188
|
-
function update({ id, revision, changes = [], dependencies }) {
|
|
230
|
+
function update({ id, revision, changes = [], dependencies, refresh = false }) {
|
|
189
231
|
const value = inspect(id);
|
|
190
232
|
if (value.revision !== revision) throw new Error("Draft revision changed. Read ads_drafts again before editing.");
|
|
191
233
|
const manifest = value.manifest;
|
|
234
|
+
if (refresh) {
|
|
235
|
+
if (dependencies) throw new Error("Refresh separately from dependency edits, then review the new revision.");
|
|
236
|
+
const resolved=new Map();
|
|
237
|
+
for(const change of changes){if(resolved.has(change.path)||!manifest.files.some(file=>file.target===change.path&&file.unit===change.unit))throw new Error("Refresh resolutions must name unique existing draft files and their owners.");resolved.set(change.path,change.content===null?null:Buffer.from(change.content,change.encoding==="base64"?"base64":"utf8"));}
|
|
238
|
+
const merged=[],conflicts=[];
|
|
239
|
+
for (const file of value.files) {
|
|
240
|
+
const current=bytes(safe(root,file.target)),digest=fileHash(current);
|
|
241
|
+
if (digest===file.baseline && !resolved.has(file.target)) continue;
|
|
242
|
+
const original=file.base?bytes(safe(path.dirname(manifestFile(id)),file.base)):null;
|
|
243
|
+
try {
|
|
244
|
+
let content;
|
|
245
|
+
if(resolved.has(file.target))content=resolved.get(file.target);
|
|
246
|
+
else if (fileHash(file.content)===file.baseline || fileHash(file.content)===digest) content=current;
|
|
247
|
+
else {
|
|
248
|
+
if (fileHash(original)!==file.baseline) throw new Error("Original baseline unavailable for this older draft; resolve this file explicitly.");
|
|
249
|
+
if(current&&original&&file.content&&isDraftExportEntry(file.target,loadConfig(root))&&mergeDraftExports(original.toString(),current.toString(),current.toString(),file.target,loadConfig(root),manifest.units).content===original.toString())
|
|
250
|
+
content=Buffer.from(mergeDraftExports(current.toString(),file.content.toString(),original.toString(),file.target,loadConfig(root),manifest.units).content);
|
|
251
|
+
else {
|
|
252
|
+
if([current,original,file.content].some(content=>content!==null&&!Buffer.from(content.toString()).equals(content)))throw new Error("Overlapping binary edits require explicit resolution.");
|
|
253
|
+
content=Buffer.from(mergeSource(current?.toString()??null,original?.toString()??null,file.content?.toString()??null,file.target));
|
|
254
|
+
}
|
|
255
|
+
}
|
|
256
|
+
merged.push({file,current,content});
|
|
257
|
+
} catch(error) { conflicts.push({path:file.target,message:error.message}); }
|
|
258
|
+
}
|
|
259
|
+
if (conflicts.length) return {...summary(value),refreshed:false,diagnostics:conflicts};
|
|
260
|
+
for (const {file,current,content} of merged) {
|
|
261
|
+
const record=manifest.files.find(item=>item.target===file.target),folder=path.dirname(manifestFile(id));
|
|
262
|
+
record.baseline=fileHash(current);record.base=current===null?undefined:baseName(file.target);
|
|
263
|
+
if(current!==null)atomic(safe(folder,record.base),current);
|
|
264
|
+
record.source=content===null?null:storedName(file.target);
|
|
265
|
+
if(content!==null)atomic(safe(folder,record.source),content);
|
|
266
|
+
}
|
|
267
|
+
save(manifest);changed();return {...summary(inspect(id)),refreshed:true};
|
|
268
|
+
}
|
|
192
269
|
if (dependencies) { for (const dependency of dependencies) {const value=inspect(dependency,[id]);if(value.dependencyErrors.length)throw new Error(value.dependencyErrors[0].message);} manifest.dependencies = dependencies; }
|
|
193
270
|
for (const change of changes) {
|
|
194
271
|
if (!manifest.units.includes(change.unit)) throw new Error("Changes must belong to a declared draft unit.");
|
|
195
272
|
let file = manifest.files.find(file => file.target === change.path);
|
|
196
|
-
if (!file) { file = { target: change.path, source: null, baseline: fileHash(
|
|
273
|
+
if (!file) { const original=bytes(safe(root,change.path)); file = { target: change.path, source: null, baseline: fileHash(original), ...(original===null?{}:{base:baseName(change.path)}), unit: change.unit }; if(original!==null)atomic(safe(path.dirname(manifestFile(id)),file.base),original); manifest.files.push(file); }
|
|
197
274
|
file.unit = change.unit;
|
|
198
275
|
if (change.content === null) file.source = null;
|
|
199
276
|
else {
|
|
@@ -212,11 +289,17 @@ export function createDraftController(directory, { edits, startPreview, prewarm
|
|
|
212
289
|
if (value.conflicts.length) throw new Error(`Draft baseline conflict: ${value.conflicts.join(", ")}`);
|
|
213
290
|
let session = previews.get(id);
|
|
214
291
|
if (!session) {
|
|
215
|
-
const workspace = path.join(
|
|
292
|
+
const workspace = path.join(previewDirectory(id), "project");
|
|
293
|
+
const directory=path.dirname(workspace);
|
|
294
|
+
if(existsSync(directory)&&realpathSync(directory)!==directory)throw new Error("Draft preview storage cannot be a symlink.");
|
|
295
|
+
rmSync(directory,{recursive:true,force:true});
|
|
216
296
|
mkdirSync(workspace, { recursive: true });
|
|
217
297
|
if (realpathSync(workspace) !== workspace) throw new Error("Draft preview workspace cannot be a symlink.");
|
|
218
298
|
session = { workspace, inputs: new Map() }; previews.set(id, session); reconcileWatches();
|
|
219
299
|
}
|
|
300
|
+
if(session.revision&&!existsSync(path.join(session.workspace,".ds/draft-preview.json")))session.recovering=true;
|
|
301
|
+
mkdirSync(session.workspace,{recursive:true});
|
|
302
|
+
if(realpathSync(session.workspace)!==session.workspace)throw new Error("Draft preview workspace cannot be a symlink.");
|
|
220
303
|
const inputs = validationInputFiles(loadConfig(root)), desired = new Map();
|
|
221
304
|
let size = 0;
|
|
222
305
|
for (const [target, digest] of Object.entries(inputs)) if (digest && target !== "installed-dependencies") {
|
|
@@ -242,7 +325,7 @@ export function createDraftController(directory, { edits, startPreview, prewarm
|
|
|
242
325
|
}
|
|
243
326
|
overlay(value);
|
|
244
327
|
for (const target of session.inputs.keys()) if (!desired.has(target)) rmSync(safe(session.workspace, target), { force: true });
|
|
245
|
-
for (const [target, content] of desired) if (session.inputs.get(target) !== hash(content)) atomic(safe(session.workspace, target), content);
|
|
328
|
+
for (const [target, content] of desired) if (session.inputs.get(target) !== hash(content) || !existsSync(safe(session.workspace,target))) atomic(safe(session.workspace, target), content);
|
|
246
329
|
session.inputs = new Map([...desired].map(([target, content]) => [target, hash(content)]));
|
|
247
330
|
const modules = path.join(session.workspace, "node_modules");
|
|
248
331
|
if (!existsSync(modules) && existsSync(path.join(root, "node_modules"))) symlinkSync(realpathSync(path.join(root, "node_modules")), modules, process.platform === "win32" ? "junction" : "dir");
|
|
@@ -270,6 +353,8 @@ export function createDraftController(directory, { edits, startPreview, prewarm
|
|
|
270
353
|
async function show({ id, scenario }, signal) {
|
|
271
354
|
if (signal?.aborted) throw new Error("Draft preview request cancelled.");
|
|
272
355
|
if (closed) throw new Error("Draft controller is closed.");
|
|
356
|
+
const existing=previews.get(id);
|
|
357
|
+
if(existing&&(existing.recovering||!existsSync(path.join(existing.workspace,".ds/draft-preview.json"))))await retire(id);
|
|
273
358
|
if(!previews.has(id)&&[...previews.values()].filter(session=>session.starting).length>=4){const oldest=[...previews].find(([,session])=>session.starting);if(oldest)await retire(oldest[0]);}
|
|
274
359
|
const value = prepare(id), { session } = value;
|
|
275
360
|
session.opened = true;
|
|
@@ -280,6 +365,11 @@ export function createDraftController(directory, { edits, startPreview, prewarm
|
|
|
280
365
|
: registry?.scenarios.find(item => value.manifest.units.includes(units.owner(units.relative(item.file))));
|
|
281
366
|
if (!registry || !known || !existsSync(path.join(session.workspace, known.file)) || registry.diagnostics.length) registry = await discovery.current(session.workspace, value.revision);
|
|
282
367
|
const metadataRevision = metadata.revision;
|
|
368
|
+
const diagnosticsUri=`ads://drafts/${id}/resource?uri=${encodeURIComponent("ads://project/scenarios")}`;
|
|
369
|
+
session.registry=registry;
|
|
370
|
+
if(registry.diagnostics.length) {session.build={state:"error",building:false,current:false,stale:true,scenarios:[],diagnosticCount:registry.diagnostics.length,resourceUri:scopedBuild(id)};++discoveryVersion;onChange?.();
|
|
371
|
+
return {...summary(value),ok:false,diagnostics:registry.diagnostics,diagnosticsUri,previewOnly:true,
|
|
372
|
+
next:"Fix these diagnostics in this draft's source. The accepted project registry is separate. Reopen ads_show_draft after editing."};}
|
|
283
373
|
const scenarios = registry.scenarios.map(({ id, title, kind, group, file }) => ({ id, title, kind, ...(group ? { group } : {}), unit: units.owner(units.relative(file)) }));
|
|
284
374
|
const owned = scenarios.find(item => value.manifest.units.includes(item.unit))?.id;
|
|
285
375
|
if(!scenario&&!owned&&value.manifest.units.some(unit=>/^(?:components|patterns|composition)\//.test(unit)))throw new Error("Draft has no independently mountable owner scenario yet. Add its scenario/fixture or select an explicit existing context scenario.");
|
|
@@ -294,7 +384,13 @@ export function createDraftController(directory, { edits, startPreview, prewarm
|
|
|
294
384
|
const acceptedExists = accepted.scenarios.some(item => item.id === selected);
|
|
295
385
|
const previewResult=selected&&session.runtime.callTool?await session.runtime.callTool("ads_show_scenario",{id:selected,waitFor:"compiled"},signal):undefined;
|
|
296
386
|
if (session.runtime.buildStatus) recordBuild(id, session, session.runtime.buildStatus());
|
|
297
|
-
|
|
387
|
+
if(previewResult?.isError){
|
|
388
|
+
registry=await discovery.current(session.workspace,value.revision);session.registry=registry;
|
|
389
|
+
const diagnostics=registry.diagnostics.length?registry.diagnostics:[{rule:"draft-preview",message:previewResult.content?.find(item=>item.type==="text")?.text??"Draft preview compilation failed."}];
|
|
390
|
+
return {...summary(value),ok:false,scenario:selected,diagnostics,diagnosticsUri,previewOnly:true,previewResult,
|
|
391
|
+
next:"Fix the draft-private preview errors, then reopen this draft. Accepted source has not changed."};
|
|
392
|
+
}
|
|
393
|
+
return { ...summary(value), scenario: selected, scenarios, diagnostics: registry.diagnostics, diagnosticsUri, discovery: discovery.status(metadata, metadataRevision), build: previewResult?.structuredContent?.build ?? previewStatus(id), showcaseUrl: url.href, acceptedExists, previewOnly: true, previewResult,draftScope:`ads://drafts/${id}/resource?uri=`, next: "Inspect the actual rendered draft and its build freshness. Catalogue metadata may refresh in the background. Subscribe to ads://project/build and ads://project/drafts for updates. Reopen after edits; accept only the revision you reviewed. Full acceptance checks have not run." };
|
|
298
394
|
}
|
|
299
395
|
async function startSession(id, session) {
|
|
300
396
|
session.starting ??= (async () => {
|
|
@@ -310,7 +406,12 @@ export function createDraftController(directory, { edits, startPreview, prewarm
|
|
|
310
406
|
})().catch(error => { session.starting = undefined; throw error; });
|
|
311
407
|
return session.starting;
|
|
312
408
|
}
|
|
313
|
-
async function retire(id) {
|
|
409
|
+
async function retire(id) {
|
|
410
|
+
const session=previews.get(id),workspace=path.join(previewDirectory(id),"project");
|
|
411
|
+
previews.delete(id);discovery.remove(workspace);
|
|
412
|
+
if(session){try{await session.starting;}catch{/* Failed startup remains disposable. */}session.unsubscribeBuild?.();await session.runtime?.close();}
|
|
413
|
+
if(!previews.has(id))rmSync(path.dirname(workspace),{recursive:true,force:true});
|
|
414
|
+
}
|
|
314
415
|
function queuePrewarm(id) {
|
|
315
416
|
if (!prewarm || !startPreview || !loadConfig(root).config.mcp.previewWatch) return;
|
|
316
417
|
pendingPrewarm = id;
|
|
@@ -380,6 +481,7 @@ export function createDraftController(directory, { edits, startPreview, prewarm
|
|
|
380
481
|
try{const merged=mergeDraftExports(accepted.toString(),source.toString(),originals.get(file.target)?.toString()??"",file.target,loadConfig(root),manifest.units);atomic(safe(path.dirname(manifestFile(dependent)),file.source),merged.content);file.baseline=fileHash(accepted);}catch{/* An overlapping edit remains an explicit baseline conflict. */}
|
|
381
482
|
}
|
|
382
483
|
}
|
|
484
|
+
for(const file of manifest.files)if(file.base){const accepted=bytes(safe(root,file.target));if(accepted!==null&&fileHash(accepted)===file.baseline)atomic(safe(path.dirname(manifestFile(dependent)),file.base),accepted);}
|
|
383
485
|
manifest.dependencies = manifest.dependencies.filter(dependency => dependency !== id); save(manifest); updated.push(dependent);
|
|
384
486
|
}
|
|
385
487
|
}catch(error){result.warnings=[...(result.warnings??[]),{rule:"draft-dependency",message:`Source applied; dependent ${dependent} needs recovery: ${error.message}`}];}
|
|
@@ -443,6 +545,10 @@ export function createDraftController(directory, { edits, startPreview, prewarm
|
|
|
443
545
|
}
|
|
444
546
|
const timer = setInterval(() => { if (!closed) { reconcileWatches(); syncPreviews(); } }, 5000);
|
|
445
547
|
timer.unref();
|
|
548
|
+
const generated=path.join(root,".ds/draft-previews");
|
|
549
|
+
if(existsSync(generated)&&realpathSync(generated)===generated)for(const entry of readdirSync(generated,{withFileTypes:true})){
|
|
550
|
+
if(entry.isDirectory()&&!entry.isSymbolicLink()&&idSchema.safeParse(entry.name).success&&!existsSync(manifestFile(entry.name)))rmSync(previewDirectory(entry.name),{recursive:true,force:true});
|
|
551
|
+
}
|
|
446
552
|
reconcileWatches();
|
|
447
553
|
return { list, create, update, show, drop, accept, prepare, events, inspect, tokenGroups,
|
|
448
554
|
previewStatuses: () => [...previews].map(([id, session]) => ({ id, revision: session.revision, ...previewStatus(id) })),
|
|
@@ -458,7 +564,17 @@ export function createDraftController(directory, { edits, startPreview, prewarm
|
|
|
458
564
|
if(!Number.isSafeInteger(offset)||offset<0||offset>text.length||!Number.isSafeInteger(limit)||limit<1||limit>12000)throw new Error("Invalid draft read range.");
|
|
459
565
|
return{path:file,draft:parts[1],unit:mapping?.unit??null,digest:`sha256:${hash(content)}`,bytes:content.length,binary,content:binary?null:text.slice(offset,end),offset,nextOffset:!binary&&end<text.length?end:null,totalChars:binary?null:text.length,startLine:text.slice(0,offset).split("\n").length};
|
|
460
566
|
},
|
|
461
|
-
async readResource(id,uri,signal){
|
|
567
|
+
async readResource(id,uri,signal){
|
|
568
|
+
const session=previews.get(id);
|
|
569
|
+
if(session?.error)throw new Error(`Draft preview is stale: ${session.error}`);
|
|
570
|
+
if(uri==="ads://project/scenarios"&&session?.registry){
|
|
571
|
+
prepare(id);
|
|
572
|
+
session.registry=await discovery.current(session.workspace,session.revision);
|
|
573
|
+
return{contents:[{uri,mimeType:"application/json",text:JSON.stringify(session.registry)}]};
|
|
574
|
+
}
|
|
575
|
+
if(!session?.starting)throw new Error("Draft preview is not active. Reopen ads_show_draft.");
|
|
576
|
+
await session.starting;return session.runtime.readResource(uri,signal);
|
|
577
|
+
},
|
|
462
578
|
fingerprint:()=>`${draftStamp()}:${discoveryVersion}`,
|
|
463
579
|
async close() { closed = true; clearInterval(timer); clearTimeout(changeTimer); clearTimeout(prewarmTimer); pendingPrewarm = undefined; for (const { watcher } of watchers.values()) watcher.close(); watchers.clear(); active?.abort.abort(); await Promise.allSettled([discovery.close(), ...[...previews.keys()].map(retire)]); await prewarming; },
|
|
464
580
|
};
|
|
@@ -35,7 +35,7 @@ function snapshot(kind, raw) {
|
|
|
35
35
|
...(raw.applied !== undefined ? { applied: raw.applied } : {}), ...(raw.unit ? { unit: raw.unit } : {}),
|
|
36
36
|
...(raw.units ? { units: raw.units } : {}), ...(raw.transaction ? { transaction: true } : {}),
|
|
37
37
|
...(raw.draft ? {draft:raw.draft,draftRevision:raw.revision,draftEvent:raw.event?{id:raw.event.id,state:raw.event.state}:null,updatedDependents:raw.updatedDependents??[]} : {}),
|
|
38
|
-
...(kind === "validation" ? {scope:raw.scope,requestedScope:raw.requestedScope,sourceRevision:raw.sourceRevision,current:raw.current,elapsedMs:raw.elapsedMs,...(raw.fallback?{fallback:raw.fallback}:{})} : {}),
|
|
38
|
+
...(kind === "validation" ? {policy:raw.policy,scope:raw.scope,requestedScope:raw.requestedScope,sourceRevision:raw.sourceRevision,current:raw.current,elapsedMs:raw.elapsedMs,...(raw.fallback?{fallback:raw.fallback}:{})} : {}),
|
|
39
39
|
acceptance: raw.acceptance, investigation: raw.investigation,
|
|
40
40
|
sections: Object.fromEntries(Object.entries(sections).map(([key, rows]) => [key, rows.map((row, recordIndex) => ({ recordIndex, ...(row && typeof row === "object" ? row : {message:row}) }))])),
|
|
41
41
|
counts: { outcomes: count(outcomes), checks: count(sections.checks), diagnostics: sections.diagnostics.length,
|
|
@@ -48,7 +48,7 @@ function summary(value, storageWarning) {
|
|
|
48
48
|
const failedOutcomes = value.sections.outcomes.filter(item => item.status !== "passed");
|
|
49
49
|
const failureRows = failedOutcomes.length ? failedOutcomes : value.sections.diagnostics;
|
|
50
50
|
const section = failedOutcomes.length ? "outcomes" : value.sections.diagnostics.length ? "diagnostics" : value.sections.captures.length ? "captures" : value.sections.outcomes.length ? "outcomes" : "checks";
|
|
51
|
-
const result = { ok, resultId, kind, ...(kind === "validation" ? {scope:value.scope,requestedScope:value.requestedScope,sourceRevision:value.sourceRevision,current:value.current,elapsedMs:value.elapsedMs,...(value.fallback?{fallback:value.fallback}:{})} : {}), ...(applied !== undefined ? { applied } : {}), ...(unit ? { unit } : {}),
|
|
51
|
+
const result = { ok, resultId, kind, ...(kind === "validation" ? {policy:value.policy,scope:value.scope,requestedScope:value.requestedScope,sourceRevision:value.sourceRevision,current:value.current,elapsedMs:value.elapsedMs,...(value.fallback?{fallback:value.fallback}:{})} : {}), ...(applied !== undefined ? { applied } : {}), ...(unit ? { unit } : {}),
|
|
52
52
|
...(units ? { units } : {}), ...(transaction ? { transaction } : {}), createdAt, counts, freshness:"recorded-at-completion",
|
|
53
53
|
...(value.draft?{draft:value.draft,draftRevision:value.draftRevision,draftEvent:value.draftEvent,updatedDependentCount:value.updatedDependents.length}:{}),
|
|
54
54
|
acceptance: compactAcceptance(value.acceptance), failures: value.failurePreview ?? failureRows.slice(0, 3).map(item => compactRow({recordIndex:item.recordIndex,unit:item.unit,check:item.check,status:item.status,rule:item.rule,file:item.file,failure:item.failure,message:item.message},640)),
|
package/dist/mcp/mutations.mjs
CHANGED
|
@@ -290,7 +290,8 @@ export function createMutationController(directory, { captures = createCaptureCo
|
|
|
290
290
|
progress={stage:"project-checks",completed:index,total:extraChecks.length,message:`Checking ${check.command} ${check.args.join(" ")}`};notifyProgress?.(progress);
|
|
291
291
|
verified.push(await checkCommand(check.command, check.args, candidate, signal, undefined, {category:"build",phase:`project-check:${check.args.at(-1)}`}, candidateOptions.config.mcp.mutationCheckTimeoutMs));
|
|
292
292
|
}
|
|
293
|
-
|
|
293
|
+
const behaviorUnits = candidateOptions.config.acceptance.behaviorChecks ? affectedBehaviorUnits(candidateOptions, changes.map(change => change.path)) : [];
|
|
294
|
+
if ((behaviorUnits.length || screenshot) && candidateOptions.config.mcp.previewManifest && candidateOptions.config.mcp.previewWatch) {
|
|
294
295
|
boundary=evidenceFailure("build","preview-build","ADS_PREVIEW_BUILD");
|
|
295
296
|
progress={stage:"preview-build",message:"Building all candidate previews"};notifyProgress?.(progress);
|
|
296
297
|
const { startAdsMcp } = await import("./server.mjs");
|
|
@@ -302,7 +303,6 @@ export function createMutationController(directory, { captures = createCaptureCo
|
|
|
302
303
|
verified.push({ name:"managed production previews", passed:true });
|
|
303
304
|
}
|
|
304
305
|
boundary=evidenceFailure("runner","behavior-verification","ADS_BEHAVIOR_SETUP");
|
|
305
|
-
const behaviorUnits = affectedBehaviorUnits(candidateOptions, changes.map(change => change.path));
|
|
306
306
|
if (behaviorUnits.length) {
|
|
307
307
|
const verification = createVerificationController(candidate, { reportRoot: root, previewHost, onProgress: value => { progress = { stage: "behavior", ...value }; notifyProgress?.(progress); } });
|
|
308
308
|
let evidence;
|
|
@@ -311,6 +311,7 @@ export function createMutationController(directory, { captures = createCaptureCo
|
|
|
311
311
|
if (!evidence.ok) return lastResult = mutationEvidence({ ok: false, applied: false, diagnostics: [...evidence.results.filter(item => item.status !== "passed").map(item => ({ rule: "behavior-check", failure:item.failure, message: `${item.unit}#${item.check}: ${item.status}. ${item.message}` })),...evidence.diagnostics], checks: verified, behavior: evidence },candidateRevision);
|
|
312
312
|
verified.push({ name: "registered behavior checks", passed: true, results: evidence.results });
|
|
313
313
|
}
|
|
314
|
+
else verified.push({name:"registered behavior checks",skipped:true,reason:candidateOptions.config.acceptance.behaviorChecks ? "No affected behavior contracts." : "Not required by acceptance policy."});
|
|
314
315
|
let screenshots;
|
|
315
316
|
if (screenshot) {
|
|
316
317
|
boundary=evidenceFailure("runner","capture","ADS_CAPTURE_FAILED");
|
package/dist/mcp/server.mjs
CHANGED
|
@@ -289,6 +289,7 @@ export function createAdsMcp(directory, { era = "legacy", skillDirectory, pollIn
|
|
|
289
289
|
patterns: catalog.filter((item) => item.kind === "patterns" && item.apiKind === "ui").length,
|
|
290
290
|
tokenCount: inspectTokens(root).tokens.length, showcaseUrl: getShowcaseUrl(),
|
|
291
291
|
resourceLimits: resourceLimitsStatus(options.config.resources),
|
|
292
|
+
policies:{acceptance:options.config.acceptance,validation:options.config.validation},
|
|
292
293
|
previewWatch: previewWatch?.status() ?? { state: "disabled" },
|
|
293
294
|
mutations: mutations ? { ...mutationState, progress: compactProgress(mutationState.progress), lastResult: executionResults.latest("mutation") } : { enabled: false },
|
|
294
295
|
drafts: { mode:"auto", enabled:mutations, resourceUri:DRAFTS_URI, listTool:"ads_drafts", previewTool:"ads_show_draft", acceptTool:"ads_accept", previewOnly:isDraftPreviewWorkspace(root), events:drafts.events().slice(-3) },
|
|
@@ -412,17 +413,18 @@ export function createAdsMcp(directory, { era = "legacy", skillDirectory, pollIn
|
|
|
412
413
|
function tools() {
|
|
413
414
|
return [
|
|
414
415
|
{ 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)) },
|
|
415
|
-
{ name:"ads_show_draft", title:"Draft preview", description:"Prepare/reuse an isolated compiler workspace for a tracked draft and its dependency drafts. Returns a browser showcase URL and available scenarios without running acceptance checks. Existing @ds imports resolve the proposed overlay only here. Inspect the actual rendered result; then accept the exact returned revision. For comparison, open comparisonUrl in DS Explorer and use Split view. New owners have no accepted comparison.", schema:z.object({id:draftIdSchema,scenario:z.string().max(256).optional()}).strict(), _meta:{ui:{resourceUri:scenarioWidget()}}, annotations:{...annotations,readOnlyHint:false,idempotentHint:false}, call:async (args,signal)=>{
|
|
416
|
+
{ name:"ads_show_draft", title:"Draft preview", description:"Prepare/reuse an isolated compiler workspace for a tracked draft and its dependency drafts. Returns a browser showcase URL and available scenarios without running acceptance checks. Registry failures return the draft-private diagnostics and diagnosticsUri, never the accepted registry. Existing @ds imports resolve the proposed overlay only here. Inspect the actual rendered result; then accept the exact returned revision. For comparison, open comparisonUrl in DS Explorer and use Split view. New owners have no accepted comparison.", schema:z.object({id:draftIdSchema,scenario:z.string().max(256).optional()}).strict(), _meta:{ui:{resourceUri:scenarioWidget()}}, annotations:{...annotations,readOnlyHint:false,idempotentHint:false}, call:async (args,signal)=>{
|
|
416
417
|
const value=await drafts.show(args,signal),base=getShowcaseUrl();
|
|
417
418
|
let comparisonUrl=null;
|
|
418
419
|
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;}
|
|
419
|
-
|
|
420
|
+
const response=json({...value,isolatedShowcaseUrl:value.showcaseUrl,showcaseUrl:comparisonUrl??value.showcaseUrl,comparisonUrl});
|
|
421
|
+
return value.ok===false?{...response,isError:true}:response;
|
|
420
422
|
} },
|
|
421
423
|
...(mutations ? [
|
|
422
424
|
{ 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);} },
|
|
423
|
-
{ name:"ads_update_draft", description:"Update marked draft source or register new/deleted canonical target paths. Pass the current revision from ads_drafts. Source is UTF-8 unless encoding:base64; content:null proposes deletion. Optional dependencies replaces the draft dependency list. Normal local file edits need no iteration tool. Accepted source remains unchanged; ownership and all required checks run at acceptance.",schema:z.object({id:draftIdSchema,revision:draftRevisionSchema,dependencies:z.array(draftIdSchema).max(8).optional(),changes:z.array(z.object({unit:z.string().max(256),path:z.string().min(1).max(500),content:z.string().max(256*1024).nullable(),encoding:z.enum(["utf8","base64"]).optional()}).strict()).max(32).default([])}).strict(),_meta:{ui:{visibility:["model"]}},annotations:{...annotations,readOnlyHint:false,idempotentHint:false},call:async args=>{const result=drafts.update(args);if(observeChanges)await refresh();return json(result);} },
|
|
425
|
+
{ 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. refresh:true rebases onto current accepted source using stored baselines; non-overlapping edits merge and overlapping edits leave the draft unchanged with diagnostics. Use changes with refresh only for explicit resolved contents of existing draft files; refresh separately from dependency changes. 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,refresh:z.boolean().default(false),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);} },
|
|
424
426
|
{ 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);} },
|
|
425
|
-
{ name:"ads_accept",title:"Accept a reviewed draft",description:"Auto-mode acceptance: validate and apply the exact rendered/reviewed draft revision in one operation. Accept dependency drafts first; dependent drafts automatically switch to their final @ds implementations. Mandatory
|
|
427
|
+
{ 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. 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)=>{
|
|
426
428
|
if(validation.status().busy||verification.status().running)throw new Error("Wait for validation/verification before acceptance.");
|
|
427
429
|
const result=await drafts.accept(args,signal,progress);
|
|
428
430
|
if(result.applied){await previewWatch?.invalidate?.();await refresh(true);}else await refresh();
|
|
@@ -507,7 +509,7 @@ export function createAdsMcp(directory, { era = "legacy", skillDirectory, pollIn
|
|
|
507
509
|
{ 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) },
|
|
508
510
|
{ 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) },
|
|
509
511
|
{ 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)) },
|
|
510
|
-
{ name: "ads_validate", description: "Run
|
|
512
|
+
{ name: "ads_validate", description: "Run mandatory ADS architecture/freshness guards and the selected project policy. policy defaults to validation: its configured scripts, preview freshness and optional registered behavior checks. policy acceptance runs acceptance.checks and acceptance.behaviorChecks without applying source, for direct editing. 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")}).strict(), annotations: {readOnlyHint:false,destructiveHint:false,idempotentHint:false,openWorldHint:false}, call: async (args,signal,progress) => {
|
|
511
513
|
if (verification.status().running || edits.status().busy) throw new Error("Wait for the active verification or guarded edit before validating.");
|
|
512
514
|
return finishExecution("validation",await validation.run(args,signal,progress));
|
|
513
515
|
} },
|
|
@@ -566,6 +568,7 @@ export function createAdsMcp(directory, { era = "legacy", skillDirectory, pollIn
|
|
|
566
568
|
return { resources: listing.items, ...(listing.nextCursor ? { nextCursor: listing.nextCursor } : {}) };
|
|
567
569
|
});
|
|
568
570
|
server.setRequestHandler("resources/templates/list", () => ({ resourceTemplates: [
|
|
571
|
+
{ uriTemplate: "ads://drafts/{id}/resource?uri=ads%3A%2F%2Fproject%2Fscenarios", name:"Draft scenario diagnostics",description:"Draft-private registry and diagnostics; accepted ads://project/scenarios is a separate registry.",mimeType:"application/json" },
|
|
569
572
|
{ uriTemplate: "ads://drafts/{id}/resource?uri=ads%3A%2F%2Fproject%2Fbuild", name: "Draft preview build status", description: "Use preview.resourceUri from ads_drafts or ads://project/build. Available while the draft preview session is active; updates on build completion and failure.", mimeType: "application/json" },
|
|
570
573
|
{ uriTemplate: "ads://captures/{key}/{slot}", name: "Current/candidate screenshot", description: "Exact keys and available slots come from ads://project/captures. Slots are replaced in place, not revision history.", mimeType: "image/png" },
|
|
571
574
|
{ uriTemplate: "ads://results/{resultId}", name: "Saved execution summary", description: "Use resultId from execution or ads://project/results. Query section/status/cursor/limit for pages, or section/recordIndex/offset/chars for exact record ranges. Only the latest result of each kind remains available.", mimeType: "application/json" },
|
|
@@ -699,7 +702,9 @@ export function createAdsMcp(directory, { era = "legacy", skillDirectory, pollIn
|
|
|
699
702
|
const targets = discoveryChanged ? (era === "modern" ? resources().map((entry) => entry.uri).filter((uri) => !skills.files.has(uri)) : [...subscribed]).filter(uri => !uri.startsWith("ads://drafts/"))
|
|
700
703
|
: [BUILD_URI, BEHAVIOR_URI, INVESTIGATIONS_URI, DRAFTS_URI, `${PROJECT_URI}/status`, ...(filesChanged ? [`${PROJECT_URI}/tokens`] : []), ...(options.config.mcp.previewManifest ? [PREVIEW_MANIFEST_URI, LIVE_PREVIEW_MANIFEST_URI] : []), ...(artifactsChanged ? allApps(true).map(app => appUri(app.id)) : [])].filter((uri) => era === "modern" || subscribed.has(uri));
|
|
701
704
|
if((discoveryChanged||draftsChanged)&&(era==="modern"||subscribed.has(`${PROJECT_URI}/explorer`)))targets.push(`${PROJECT_URI}/explorer`);
|
|
702
|
-
if(draftsChanged){
|
|
705
|
+
if(draftsChanged){
|
|
706
|
+
targets.push(...[...new Set([...previousDraftBuilds.keys(),...currentDraftBuilds.keys()])].map(uri=>uri.replace(encodeURIComponent(BUILD_URI),encodeURIComponent(`${PROJECT_URI}/scenarios`))).filter(uri=>era==="modern"||subscribed.has(uri)));
|
|
707
|
+
targets.push(...[DRAFTS_URI,`${PROJECT_URI}/catalog`,`${PROJECT_URI}/scenarios`,`${PROJECT_URI}/status`].filter(uri=>era==="modern"||subscribed.has(uri)));previousDrafts=draftFingerprint;}
|
|
703
708
|
targets.push(...changedDraftBuilds.filter(uri=>era==="modern"||subscribed.has(uri)));
|
|
704
709
|
previousDraftBuilds=currentDraftBuilds;
|
|
705
710
|
if(resultsChanged){targets.push(...[RESULTS_URI,...executionResults.index().results.map(entry=>entry.resourceUri),...[...subscribed].filter(uri=>uri.startsWith("ads://results/"))].filter(uri=>era==="modern"||subscribed.has(uri)));previousResults=executionResults.fingerprint();}
|
|
@@ -767,7 +772,10 @@ export async function startAdsMcp(directory = process.cwd(), { stdio = true, sho
|
|
|
767
772
|
});
|
|
768
773
|
buildWatcher.unref(); buildWatcher.on("error", () => { buildWatcher.close(); });
|
|
769
774
|
} catch { /* Periodic observation also covers replaced/missing report directories. */ }
|
|
770
|
-
|
|
775
|
+
// Modern stdio negotiation can spawn a disposable probe process. Its
|
|
776
|
+
// metadata requests must not start a compiler; oninitialized starts the real
|
|
777
|
+
// connection's shared compiler. HTTP-only hosts can warm immediately.
|
|
778
|
+
const warmStart=prewarm&&!stdio?setTimeout(()=>previewWatch.start(),0):undefined;
|
|
771
779
|
warmStart?.unref();
|
|
772
780
|
let closing;
|
|
773
781
|
function close() {
|