@reqvire-org/ads 0.3.37 → 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 +5 -1
- package/dist/bootstrap-ds/README.md +2 -2
- package/dist/bootstrap-ds/ds.config.json +2 -0
- package/dist/bootstrap-ds/package.json +1 -1
- package/dist/cli.mjs +16 -5
- package/dist/config.mjs +13 -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/preview-owner-guard.mjs +7 -4
- package/dist/mcp/preview-widget.bundle.js +46 -47
- package/dist/mcp/project-widget.bundle.js +45 -46
- package/dist/mcp/server.mjs +20 -7
- package/dist/mcp/widget.bundle.js +47 -48
- package/dist/preview-bun.mjs +5 -2
- package/dist/resource-limits.mjs +146 -0
- package/dist/runtime-requirements.mjs +21 -0
- package/dist/scenarios-compiler.mjs +4 -3
- package/dist/showcase/client.bundle.js +56 -57
- package/dist/showcase/sandbox.bundle.js +1 -1
- package/dist/skills/ads-break-ui/SKILL.md +3 -2
- 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 +89 -4
- 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 +10 -5
- package/dist/skills/ads-designer/assets/bootstrap-ds/README.md +2 -2
- package/dist/skills/ads-designer/assets/bootstrap-ds/ds.config.json +2 -0
- package/dist/skills/ads-designer/assets/bootstrap-ds/package.json +1 -1
- package/dist/skills/ads-designer/references/behaviors.md +8 -4
- package/dist/skills/ads-designer/references/cli.md +3 -3
- 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 +89 -4
- 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/SKILL.md +3 -2
- package/dist/skills/ads-import/references/behaviors.md +8 -4
- package/dist/skills/ads-import/references/cli.md +3 -3
- 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 +89 -4
- 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/SKILL.md +3 -2
- 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 +89 -4
- 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/SKILL.md +3 -2
- package/dist/skills/ads-port/references/behaviors.md +8 -4
- package/dist/skills/ads-port/references/cli.md +3 -3
- 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 +89 -4
- 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/dist/verification/browser.mjs +8 -8
- package/docs/ARCHITECTURE.md +8 -4
- package/docs/BEHAVIORS.md +6 -3
- package/docs/CHANGELOG.md +70 -13
- package/docs/GUIDE.md +13 -7
- package/docs/MCP.md +49 -17
- package/package.json +2 -2
package/README.md
CHANGED
|
@@ -42,6 +42,8 @@ uses Preact. See [implementation support](docs/GUIDE.md#implementation-support).
|
|
|
42
42
|
- **Iterate in tracked drafts** without rerunning acceptance checks after every
|
|
43
43
|
edit. Commit proposals for PR review, compare Accepted/Draft in Explorer, and
|
|
44
44
|
let the agent accept an exact reviewed revision after required checks pass.
|
|
45
|
+
- **Bound command memory** with project process-tree budgets and reported kernel
|
|
46
|
+
or watchdog enforcement. See [resource budgets](skills/ads-designer/references/runtimes.md#ads-command-memory-limits-ads-0338).
|
|
45
47
|
- **Verify behavior** through project-owned guarantees and registered tests,
|
|
46
48
|
with progress, timings and evidence tied to current source.
|
|
47
49
|
- **Keep contracts explicit** for typed paint inputs, scoped data bindings and
|
|
@@ -63,7 +65,7 @@ Drafts survive restart and Git clone, but cannot enter production imports.
|
|
|
63
65
|
|
|
64
66
|
## Set up your project
|
|
65
67
|
|
|
66
|
-
Run **inside your project**, where `package.json` lives. Install Bun 1.
|
|
68
|
+
Run **inside your project**, where `package.json` lives. Install Bun 1.4.1+ for
|
|
67
69
|
ADS tooling and previews. Your application can continue using Node/npm or Bun.
|
|
68
70
|
|
|
69
71
|
```sh
|
|
@@ -100,6 +102,8 @@ Linaria; integrate its extraction with your build as described in the
|
|
|
100
102
|
|---------|-----|
|
|
101
103
|
| `ads init --framework react` | Set up ADS in the current project; also accepts `preact`; saved choices can omit the flag |
|
|
102
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 |
|
|
103
107
|
| `ads compile` | Compile all previews with Bun; `--watch` rebuilds on edits |
|
|
104
108
|
| `ads tokens` | Inspect token values and themes |
|
|
105
109
|
| `ads behaviors` | Inspect registered behavior guarantees and current evidence |
|
|
@@ -12,7 +12,7 @@ Read the local [contract](ADS.md) and the
|
|
|
12
12
|
|
|
13
13
|
Copy the contents of `bootstrap-ds/`, including dotfiles, into a new project.
|
|
14
14
|
The installed `ads-designer` skill contains the same files in
|
|
15
|
-
`assets/bootstrap-ds/`. Set the project name in `package.json`. Install Bun 1.
|
|
15
|
+
`assets/bootstrap-ds/`. Set the project name in `package.json`. Install Bun 1.4.1+ for ADS tooling and previews. The application can keep its
|
|
16
16
|
Node/npm build pipeline. Use a current ADS release.
|
|
17
17
|
|
|
18
18
|
```sh
|
|
@@ -36,7 +36,7 @@ lockfile and translate nested npm scripts to `bun --bun run`. Initialize with
|
|
|
36
36
|
`bunx @reqvire-org/ads init`. Init detects existing
|
|
37
37
|
Bun projects and preserves their scripts/lockfiles. Use `bun install` and
|
|
38
38
|
`bun --bun run build`/`bun --bun run dev:showcase`. Node is unnecessary with Bun
|
|
39
|
-
1.
|
|
39
|
+
1.4.1+. ADS supplies its Bun preview compiler independently of the project build.
|
|
40
40
|
|
|
41
41
|
For an existing application, merge only the ADS source and required extraction,
|
|
42
42
|
aliases and preview adapter. Preserve its framework, entry points and build.
|
package/dist/cli.mjs
CHANGED
|
@@ -1,7 +1,9 @@
|
|
|
1
1
|
#!/usr/bin/env bun
|
|
2
2
|
import { readFileSync } from "node:fs";
|
|
3
3
|
import path from "node:path";
|
|
4
|
-
import {
|
|
4
|
+
import { loadConfig } from "./config.mjs";
|
|
5
|
+
import { enterMemoryBudget } from "./resource-limits.mjs";
|
|
6
|
+
import { assertBunRuntime } from "./runtime-requirements.mjs";
|
|
5
7
|
|
|
6
8
|
const pkg = JSON.parse(readFileSync(new URL("../package.json", import.meta.url), "utf8"));
|
|
7
9
|
const help = `ADS ${pkg.version} — tooling for a project's local design system
|
|
@@ -12,7 +14,8 @@ Usage: ads init [options] Run inside your project
|
|
|
12
14
|
init Set up ADS in the current project (requires package.json)
|
|
13
15
|
check [directory] Check tokens, ownership, imports, and showcase coverage
|
|
14
16
|
compile [directory] Build ADS previews with Bun (--watch for incremental previews)
|
|
15
|
-
validate [dir] Audit ADS gates
|
|
17
|
+
validate [dir] Audit ADS gates and the chosen project policy
|
|
18
|
+
--policy acceptance|validation (default validation)
|
|
16
19
|
behaviors [dir] Inspect behavior contracts and current verification evidence
|
|
17
20
|
verify [directory] Run registered behavior checks (--unit and --check select)
|
|
18
21
|
tokens [directory] Inspect local token values and theme definitions
|
|
@@ -40,6 +43,7 @@ No component library or example catalogue is bundled.
|
|
|
40
43
|
async function main(args) {
|
|
41
44
|
if (!args.length || args.includes("--help")) { process.stdout.write(help); return; }
|
|
42
45
|
if (args.length === 1 && args[0] === "--version") { console.log(pkg.version); return; }
|
|
46
|
+
if (process.versions.bun) assertBunRuntime();
|
|
43
47
|
let json = false;
|
|
44
48
|
let toolPackage;
|
|
45
49
|
let packageManager;
|
|
@@ -49,13 +53,14 @@ async function main(args) {
|
|
|
49
53
|
const selectedChecks = [];
|
|
50
54
|
let showcase = true;
|
|
51
55
|
let mutations = false;
|
|
52
|
-
let changed = false, watched = false;
|
|
56
|
+
let changed = false, watched = false, policy;
|
|
53
57
|
const positional = [];
|
|
54
58
|
for (let index = 0; index < args.length; index++) {
|
|
55
59
|
const argument = args[index];
|
|
56
60
|
if (argument === "--json") json = true;
|
|
57
61
|
else if(argument === "--watch") watched = true;
|
|
58
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];}
|
|
59
64
|
else if (argument === "--no-showcase") showcase = false;
|
|
60
65
|
else if (argument === "--mutations") mutations = true;
|
|
61
66
|
else if (argument === "--unit" || argument === "--check") {
|
|
@@ -83,8 +88,14 @@ async function main(args) {
|
|
|
83
88
|
}
|
|
84
89
|
if (positional.length > 2) throw new Error("Extra argument. Run ads --help.");
|
|
85
90
|
const [command, directory] = positional;
|
|
91
|
+
if(command!=="init"){
|
|
92
|
+
const exitCode=await enterMemoryBudget(loadConfig(path.resolve(directory??process.cwd())).config,args);
|
|
93
|
+
if(exitCode!==null){process.exitCode=exitCode;return;}
|
|
94
|
+
}
|
|
95
|
+
const { checkProject, generateBrandAssets, generateLintConfig, initProject, inspectTokens } = await import("./index.mjs");
|
|
86
96
|
if(watched&&command!=="compile")throw new Error("--watch is supported only by compile.");
|
|
87
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.");
|
|
88
99
|
if (changed && command !== "validate") throw new Error("--changed is supported only by validate.");
|
|
89
100
|
if ((port !== undefined || !showcase) && !["mcp", "showcase"].includes(command)) throw new Error("Website options are supported only by mcp/showcase.");
|
|
90
101
|
if (!showcase && command !== "mcp") throw new Error("--no-showcase is supported only by mcp.");
|
|
@@ -108,7 +119,7 @@ async function main(args) {
|
|
|
108
119
|
const {createValidationController}=await import("./validation.mjs");
|
|
109
120
|
const validation=createValidationController(target);
|
|
110
121
|
const abort=()=>{void validation.close();};process.once("SIGINT",abort);process.once("SIGTERM",abort);
|
|
111
|
-
try {result=await validation.run({scope:changed?"changed":"all"});}
|
|
122
|
+
try {result=await validation.run({scope:changed?"changed":"all",policy});}
|
|
112
123
|
finally {process.removeListener("SIGINT",abort);process.removeListener("SIGTERM",abort);await validation.close();}
|
|
113
124
|
}
|
|
114
125
|
else if (command === "behaviors") { const {behaviorStatus}=await import("./verification.mjs"); const {loadConfig}=await import("./config.mjs"); result=behaviorStatus(loadConfig(target)); }
|
|
@@ -123,7 +134,7 @@ async function main(args) {
|
|
|
123
134
|
else if (command === "lint-config") console.log(`Generated ${result.file}\nUse this optional configuration only in the project linter you choose to run.`);
|
|
124
135
|
else if (command === "behaviors") console.log(JSON.stringify(result, null, 2));
|
|
125
136
|
else if (command === "verify") { for (const item of result.results) console.log(`${item.unit}#${item.check}: ${item.status} (${item.profile})`); }
|
|
126
|
-
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})`:""}`);}
|
|
127
138
|
else if (command === "tokens") {
|
|
128
139
|
for (const token of result.tokens) console.log(`${token.name}${token.type ? ` (${token.type})` : ""}: ${token.definitions.map((entry) => `${entry.scope}: ${entry.value}`).join("; ")}`);
|
|
129
140
|
} else if (result.ok) console.log(`ADS check passed: ${target}`);
|
package/dist/config.mjs
CHANGED
|
@@ -22,8 +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
|
-
|
|
26
|
-
|
|
25
|
+
acceptance: { checks: [], behaviorChecks: false },
|
|
26
|
+
validation: { checks: [], behaviorChecks: true, inputs: [] },
|
|
27
|
+
resources: { memoryLimitMb: null },
|
|
28
|
+
mcp: { showcaseUrl: null, showcaseTitle: null, apps: [], previewWatch: null, previewManifest: null, mutationCheckTimeoutMs: 60000, behaviorProfiles: {}, capture: {} },
|
|
27
29
|
};
|
|
28
30
|
|
|
29
31
|
export function isInside(parent, file) {
|
|
@@ -49,11 +51,13 @@ export function loadConfig(directory = process.cwd()) {
|
|
|
49
51
|
if (!(field in defaultConfig)) throw new Error(`Unknown ADS configuration field: ${field}`);
|
|
50
52
|
}
|
|
51
53
|
if (user.oxlint !== undefined && (!user.oxlint || typeof user.oxlint !== "object" || Array.isArray(user.oxlint))) throw new Error("oxlint must be an object.");
|
|
52
|
-
|
|
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"]) {
|
|
53
56
|
if (user[field] !== undefined && (!user[field] || typeof user[field] !== "object" || Array.isArray(user[field]))) throw new Error(`${field} must be an object.`);
|
|
54
57
|
for (const key of Object.keys(user[field] ?? {})) if (!(key in defaultConfig[field])) throw new Error(`Unknown ${field} configuration field: ${key}`);
|
|
55
58
|
}
|
|
56
|
-
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 } };
|
|
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 } };
|
|
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.");
|
|
57
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.");
|
|
58
62
|
const notificationNames = new Set();
|
|
59
63
|
for (const entry of config.usage.notifications) {
|
|
@@ -67,7 +71,11 @@ export function loadConfig(directory = process.cwd()) {
|
|
|
67
71
|
}
|
|
68
72
|
}
|
|
69
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.");
|
|
70
|
-
|
|
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
|
+
}
|
|
71
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.");
|
|
72
80
|
for (const file of config.validation.inputs) {
|
|
73
81
|
const absolute = projectPath(root,file,"validation.inputs");
|
|
@@ -146,7 +154,6 @@ export function loadConfig(directory = process.cwd()) {
|
|
|
146
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.`);
|
|
147
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.`);
|
|
148
156
|
}
|
|
149
|
-
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.");
|
|
150
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.");
|
|
151
158
|
if (config.mcp.previewManifest !== null) {
|
|
152
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");
|
|
@@ -34,13 +34,14 @@ function signalTree(signal) {
|
|
|
34
34
|
try { process.kill(id,signal); } catch (error) { if(error.code!=="ESRCH")process.exitCode=1; }
|
|
35
35
|
}
|
|
36
36
|
}
|
|
37
|
-
function stop() {
|
|
37
|
+
function stop(immediate = false) {
|
|
38
|
+
immediate = immediate === true;
|
|
38
39
|
if (released || stopping) return;
|
|
39
40
|
stopping = true;
|
|
40
41
|
clearInterval(observe);
|
|
41
42
|
if (tree) {
|
|
42
|
-
collect();signalTree("SIGTERM");
|
|
43
|
-
if (owned.size) timer=setTimeout(()=>signalTree("SIGKILL"),1500);
|
|
43
|
+
collect();signalTree(immediate ? "SIGKILL" : "SIGTERM");
|
|
44
|
+
if (owned.size && !immediate) timer=setTimeout(()=>signalTree("SIGKILL"),1500);
|
|
44
45
|
return;
|
|
45
46
|
}
|
|
46
47
|
if (process.platform === "win32") {
|
|
@@ -48,8 +49,9 @@ function stop() {
|
|
|
48
49
|
terminator.on("error", () => { process.exitCode = 1; });
|
|
49
50
|
return;
|
|
50
51
|
}
|
|
51
|
-
try { process.kill(-pid, "SIGTERM"); }
|
|
52
|
+
try { process.kill(-pid, immediate ? "SIGKILL" : "SIGTERM"); }
|
|
52
53
|
catch (error) { if (error.code !== "ESRCH") process.exitCode = 1; return; }
|
|
54
|
+
if (immediate) return;
|
|
53
55
|
timer = setTimeout(() => {
|
|
54
56
|
try { process.kill(-pid, "SIGKILL"); }
|
|
55
57
|
catch (error) { if (error.code !== "ESRCH") process.exitCode = 1; }
|
|
@@ -57,6 +59,7 @@ function stop() {
|
|
|
57
59
|
}
|
|
58
60
|
process.stdin.on("data", bytes => {
|
|
59
61
|
input = (input + bytes).slice(-32);
|
|
62
|
+
if (input === "kill\n") stop(true);
|
|
60
63
|
if (input === "disarm\n") { released = true; clearTimeout(timer); clearInterval(observe); }
|
|
61
64
|
});
|
|
62
65
|
for (const event of ["end", "close", "error"]) process.stdin.once(event, stop);
|