@reqvire-org/ads 0.3.38 → 0.3.40

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (64) hide show
  1. package/README.md +2 -0
  2. package/dist/bootstrap-ds/ds.config.json +2 -0
  3. package/dist/bun-compiler.mjs +1 -1
  4. package/dist/cli.mjs +7 -4
  5. package/dist/config.mjs +11 -6
  6. package/dist/mcp/build-status.mjs +27 -16
  7. package/dist/mcp/context.mjs +4 -3
  8. package/dist/mcp/drafts.mjs +127 -11
  9. package/dist/mcp/execution-results.mjs +2 -2
  10. package/dist/mcp/mutations.mjs +3 -2
  11. package/dist/mcp/preview-widget.bundle.js +2 -2
  12. package/dist/mcp/resource-loader.js +3 -2
  13. package/dist/mcp/server.mjs +15 -7
  14. package/dist/preview-failure.mjs +20 -0
  15. package/dist/preview-resources.mjs +69 -21
  16. package/dist/scenarios-compiler.mjs +7 -6
  17. package/dist/showcase/client.bundle.js +43 -41
  18. package/dist/showcase/index.html +15 -1
  19. package/dist/showcase/preview-state.js +2 -1
  20. package/dist/showcase/style.css +4 -1
  21. package/dist/skills/ads-break-ui/references/behaviors.md +8 -4
  22. package/dist/skills/ads-break-ui/references/drafts.md +26 -5
  23. package/dist/skills/ads-break-ui/references/guarded-editing.md +4 -2
  24. package/dist/skills/ads-break-ui/references/runtimes.md +4 -3
  25. package/dist/skills/ads-break-ui/references/validation.md +43 -25
  26. package/dist/skills/ads-break-ui/references/workflows.md +4 -3
  27. package/dist/skills/ads-designer/SKILL.md +7 -3
  28. package/dist/skills/ads-designer/assets/bootstrap-ds/ds.config.json +2 -0
  29. package/dist/skills/ads-designer/references/behaviors.md +8 -4
  30. package/dist/skills/ads-designer/references/cli.md +1 -1
  31. package/dist/skills/ads-designer/references/drafts.md +26 -5
  32. package/dist/skills/ads-designer/references/guarded-editing.md +4 -2
  33. package/dist/skills/ads-designer/references/runtimes.md +4 -3
  34. package/dist/skills/ads-designer/references/validation.md +43 -25
  35. package/dist/skills/ads-designer/references/workflows.md +4 -3
  36. package/dist/skills/ads-import/references/behaviors.md +8 -4
  37. package/dist/skills/ads-import/references/cli.md +1 -1
  38. package/dist/skills/ads-import/references/drafts.md +26 -5
  39. package/dist/skills/ads-import/references/guarded-editing.md +4 -2
  40. package/dist/skills/ads-import/references/runtimes.md +4 -3
  41. package/dist/skills/ads-import/references/validation.md +43 -25
  42. package/dist/skills/ads-import/references/workflows.md +4 -3
  43. package/dist/skills/ads-motion/references/behaviors.md +8 -4
  44. package/dist/skills/ads-motion/references/drafts.md +26 -5
  45. package/dist/skills/ads-motion/references/guarded-editing.md +4 -2
  46. package/dist/skills/ads-motion/references/runtimes.md +4 -3
  47. package/dist/skills/ads-motion/references/validation.md +43 -25
  48. package/dist/skills/ads-motion/references/workflows.md +4 -3
  49. package/dist/skills/ads-port/references/behaviors.md +8 -4
  50. package/dist/skills/ads-port/references/cli.md +1 -1
  51. package/dist/skills/ads-port/references/drafts.md +26 -5
  52. package/dist/skills/ads-port/references/guarded-editing.md +4 -2
  53. package/dist/skills/ads-port/references/runtimes.md +4 -3
  54. package/dist/skills/ads-port/references/validation.md +43 -25
  55. package/dist/skills/ads-port/references/workflows.md +4 -3
  56. package/dist/units.mjs +1 -1
  57. package/dist/validation-checks.mjs +10 -5
  58. package/dist/validation.mjs +16 -31
  59. package/docs/ARCHITECTURE.md +15 -4
  60. package/docs/BEHAVIORS.md +6 -3
  61. package/docs/CHANGELOG.md +48 -12
  62. package/docs/GUIDE.md +12 -6
  63. package/docs/MCP.md +39 -18
  64. 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 |
@@ -1,6 +1,8 @@
1
1
  {
2
2
  "framework": "react",
3
3
  "behaviorLibraries": [],
4
+ "acceptance": { "checks": [], "behaviorChecks": false },
5
+ "validation": { "checks": [], "behaviorChecks": true, "inputs": [] },
4
6
  "mcp": {
5
7
  "previewManifest": ".ds/preview/manifest.json"
6
8
  },
@@ -8,6 +8,6 @@ import { checkCandidate } from "./validation-checks.mjs";
8
8
  export function compilePreviews(directory=process.cwd(),{watched=false}={}) {
9
9
  const root=path.resolve(directory);
10
10
  return runScenarioCompiler(root,{watched,compilerFiles:[import.meta.filename,...["preview-bun.mjs","preview-imports.mjs","bun-worker.mjs"].map(file=>fileURLToPath(new URL(file,import.meta.url)))],
11
- async validate(){const result=await checkCandidate(root);if(!result.ok)throw new Error(result.diagnostics.map(item=>`${item.file}:${item.line??1}: ${item.rule}: ${item.message}`).join("\n"));},buildGraph:createBunPreviewBuilder()});
11
+ async validate(){const result=await checkCandidate(root);if(!result.ok)throw Object.assign(new Error("ADS project validation failed."),{diagnostics:result.diagnostics});},buildGraph:createBunPreviewBuilder()});
12
12
  }
13
13
  if(process.argv[1]&&path.resolve(process.argv[1])===fileURLToPath(import.meta.url))await compilePreviews(process.cwd(),{watched:process.argv.includes("--watch")});
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, project scripts and behavior checks
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 validation ${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})`:""}`);}
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
- validation: { checks: null, inputs: [] },
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, mutationChecks: null, mutationCheckTimeoutMs: 60000, behaviorProfiles: {}, capture: {} },
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
- for (const field of ["boundaries", "assets", "oxlint", "mcp", "validation", "usage", "resources"]) {
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
- if (config.validation.checks !== null && (!Array.isArray(config.validation.checks) || config.validation.checks.length > 20 || new Set(config.validation.checks).size !== config.validation.checks.length || config.validation.checks.some(name=>typeof name !== "string" || !/^[\w:.-]+$/.test(name)))) throw new Error("validation.checks must be null or up to 20 unique package script names.");
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");
@@ -7,15 +7,18 @@ import { previewSourceRevision } from "../preview-inputs.mjs";
7
7
  import { readPreviewManifest } from "../preview-resources.mjs";
8
8
  import { livePreviewOptions, previewArtifactPath, withPreviewSession } from "../preview-scope.mjs";
9
9
 
10
+ import { previewFailureTitle, previewDiagnosticText } from "../preview-failure.mjs";
11
+
10
12
  export const BUILD_URI = "ads://project/build";
11
13
  export const buildStatusFile = (root) => path.join(root, ".ds/build-status.json");
12
14
  const maxBytes = 256 * 1024;
13
15
  const diagnostic = z.object({ message: z.string().max(4000), file: z.string().max(1000).optional(), line: z.number().int().positive().optional(), column: z.number().int().positive().optional(), plugin: z.string().max(200).optional(), code: z.string().max(100).optional() }).strict();
14
- const preview = z.object({ id: z.string().max(256), state: z.enum(["idle", "building", "ready", "error"]), revision: z.number().int().nonnegative(), lastSuccessfulRevision: z.number().int().positive().nullable(), artifactDigest: z.string().regex(/^sha256:[a-f0-9]{64}$/).nullable(), sourceRevision:z.string().regex(/^[a-f0-9]{64}$/).optional(), diagnostics: z.array(diagnostic).max(20), diagnosticSet: z.number().int().nonnegative().optional() }).strict();
16
+ const failureSchema=z.object({scope:z.enum(["project","graph","scenario"]),phase:z.enum(["validation","discovery","build"])}).strict();
17
+ const preview = z.object({ id: z.string().max(256), state: z.enum(["idle", "building", "ready", "error"]), revision: z.number().int().nonnegative(), lastSuccessfulRevision: z.number().int().positive().nullable(), artifactDigest: z.string().regex(/^sha256:[a-f0-9]{64}$/).nullable(), sourceRevision:z.string().regex(/^[a-f0-9]{64}$/).optional(), diagnostics: z.array(diagnostic).max(20), diagnosticSet: z.number().int().nonnegative().optional(), failure:failureSchema.optional() }).strict();
15
18
  const progressSchema = z.object({ phase: z.enum(["queued", "validation", "compilation", "validation-and-compilation", "publication", "idle"]), startedAt: z.string().datetime(), updatedAt: z.string().datetime() }).strict();
16
19
  const liveSchema = z.object({ revision: z.string().regex(/^[a-f0-9]{64}$/), sourceRevision: z.string().regex(/^[a-f0-9]{64}$/) }).strict();
17
20
  const warmupSchema=z.object({state:z.enum(["warming","ready","error"]),completed:z.number().int().nonnegative(),total:z.number().int().nonnegative(),failed:z.number().int().nonnegative(),active:z.string().max(256).optional()}).strict();
18
- const snapshot = z.object({ schemaVersion: z.literal(1), session: z.string().regex(/^[\w-]{1,100}$/), sequence: z.number().int().nonnegative(), updatedAt: z.string().datetime(), progress: progressSchema.optional(), warmup:warmupSchema.optional(), live: liveSchema.optional(), previews: z.array(preview), diagnostics: z.array(diagnostic).max(20).optional(), diagnosticSets: z.array(z.array(diagnostic).max(20)).optional() }).strict().refine(value => value.previews.every(entry => entry.diagnosticSet === undefined || value.diagnosticSets?.[entry.diagnosticSet]), "Invalid shared diagnostic reference.");
21
+ const snapshot = z.object({ failure:failureSchema.optional(), schemaVersion: z.literal(1), session: z.string().regex(/^[\w-]{1,100}$/), sequence: z.number().int().nonnegative(), updatedAt: z.string().datetime(), progress: progressSchema.optional(), warmup:warmupSchema.optional(), live: liveSchema.optional(), previews: z.array(preview), diagnostics: z.array(diagnostic).max(20).optional(), diagnosticSets: z.array(z.array(diagnostic).max(20)).optional() }).strict().refine(value => value.previews.every(entry => entry.diagnosticSet === undefined || value.diagnosticSets?.[entry.diagnosticSet]), "Invalid shared diagnostic reference.");
19
22
  export const artifactDigest = (file) => {
20
23
  if (realpathSync(file) !== file) throw new Error("Preview output cannot resolve through a symlink.");
21
24
  if (statSync(file).size > 2 * 1024 * 1024) throw new Error("Preview exceeds 2 MiB.");
@@ -28,10 +31,15 @@ function normalizeDiagnostic(root, error) {
28
31
  const file = typeof source === "string" ? source.split("?")[0] : null;
29
32
  const line = location?.line ?? error?.line;
30
33
  const column = location?.column !== undefined ? location.column + 1 : error?.column;
31
- return { message: String(error?.message ?? error).slice(0, 4000),
34
+ return { message: ((typeof error?.rule === "string" ? `${error.rule}: ` : "")+String(error?.message ?? error)).slice(0, 4000),
32
35
  ...(file ? { file: (path.isAbsolute(file) ? path.relative(root, file) : file).replaceAll("\\", "/").slice(0, 1000) } : {}),
33
36
  ...(Number.isInteger(line) && line > 0 ? { line } : {}), ...(Number.isInteger(column) && column > 0 ? { column } : {}),
34
- ...(typeof error?.plugin === "string" ? { plugin: error.plugin.slice(0, 200) } : {}), ...(typeof error?.code === "string" ? { code: error.code.slice(0, 100) } : {}) };
37
+ ...(typeof error?.plugin === "string" ? { plugin: error.plugin.slice(0, 200) } : {}), ...(typeof (error?.code??error?.rule) === "string" ? { code: (error.code??error.rule).slice(0, 100) } : {}) };
38
+ }
39
+
40
+ function normalizedDiagnostics(root, value) {
41
+ const errors=Array.isArray(value)?value:Array.isArray(value?.diagnostics)?value.diagnostics:[value];
42
+ return errors.slice(0,20).map(error=>normalizeDiagnostic(root,error));
35
43
  }
36
44
 
37
45
  /** One publisher per project compiler; no dependency on a UI framework. */
@@ -42,11 +50,11 @@ export function createBuildReporter(directory, { apps, session = process.env.ADS
42
50
  const entries = new Map(apps.map((app) => [app.id, { id: app.id, state: "idle", revision: 0, lastSuccessfulRevision: null, artifactDigest: null, diagnostics: [] }]));
43
51
  let sequence = 0;
44
52
  let diagnostics = [];
45
- let progress, warmup;
53
+ let progress, warmup, failureContext;
46
54
  let live, batching = 0;
47
55
  function save() {
48
56
  if (batching) return;
49
- const value = { schemaVersion: 1, session, sequence: ++sequence, updatedAt: new Date().toISOString(), previews: [...entries.values()], ...(progress ? { progress } : {}), ...(warmup?{warmup}:{}), ...(live ? { live } : {}), ...(diagnostics.length ? { diagnostics } : {}) };
57
+ const value = { ...(failureContext?{failure:failureContext}:{}), schemaVersion: 1, session, sequence: ++sequence, updatedAt: new Date().toISOString(), previews: [...entries.values()], ...(progress ? { progress } : {}), ...(warmup?{warmup}:{}), ...(live ? { live } : {}), ...(diagnostics.length ? { diagnostics } : {}) };
50
58
  let text = JSON.stringify(snapshot.parse(value));
51
59
  // A shared graph failure applies to every scenario. Store repeated details
52
60
  // once only when necessary; ordinary reports retain inline diagnostics.
@@ -84,13 +92,14 @@ export function createBuildReporter(directory, { apps, session = process.env.ADS
84
92
  save();
85
93
  },
86
94
  failure(error) {
87
- diagnostics = (Array.isArray(error) ? error : [error]).slice(0, 20).map(error => normalizeDiagnostic(root, error));
95
+ diagnostics = normalizedDiagnostics(root,error);
96
+ failureContext=error?.previewFailure??{scope:"project",phase:"discovery"};
88
97
  for (const value of entries.values()) { value.state = "error"; ++value.revision; value.diagnostics = []; }
89
98
  save();
90
99
  },
91
100
  clearFailure() {
92
101
  if (!diagnostics.length) return;
93
- diagnostics = [];
102
+ diagnostics = [];failureContext=undefined;
94
103
  for (const value of entries.values()) if (value.state === "error" && !value.diagnostics.length) value.state = "idle";
95
104
  save();
96
105
  },
@@ -106,7 +115,7 @@ export function createBuildReporter(directory, { apps, session = process.env.ADS
106
115
  value.sourceRevision = sourceRevision;
107
116
  value.state = "building";
108
117
  value.revision++;
109
- value.diagnostics = [];
118
+ value.diagnostics = [];value.failure=undefined;
110
119
  save();
111
120
  return value.revision;
112
121
  },
@@ -117,7 +126,7 @@ export function createBuildReporter(directory, { apps, session = process.env.ADS
117
126
  value.artifactDigest = artifactDigest(projectPath(root, app.file, "mcp.apps.file"));
118
127
  value.state = "ready";
119
128
  value.lastSuccessfulRevision = revision;
120
- value.diagnostics = [];
129
+ value.diagnostics = [];value.failure=undefined;
121
130
  save();
122
131
  return true;
123
132
  },
@@ -125,7 +134,8 @@ export function createBuildReporter(directory, { apps, session = process.env.ADS
125
134
  const value = entry(id, revision);
126
135
  if (!value) return false;
127
136
  value.state = "error";
128
- value.diagnostics = (Array.isArray(failure) ? failure : [failure]).slice(0, 20).map((error) => normalizeDiagnostic(root, error));
137
+ value.diagnostics = normalizedDiagnostics(root,failure);
138
+ value.failure=failure?.previewFailure??{scope:"scenario",phase:"build"};
129
139
  save();
130
140
  return true;
131
141
  },
@@ -166,8 +176,9 @@ export function inspectBuildStatus(root, config, { session, previewSession, proc
166
176
  const previews = config.apps.map((app) => {
167
177
  const value = report?.previews.find((entry) => entry.id === app.id);
168
178
  let state = value?.state ?? "unreported";
179
+ let failure=value?.failure;
169
180
  let diagnostics = value?.diagnosticSet !== undefined ? report.diagnosticSets[value.diagnosticSet] : value?.diagnostics ?? [];
170
- if (report?.diagnostics?.length) { state = "error"; diagnostics = [...report.diagnostics, ...diagnostics].slice(0, 20); }
181
+ if (report?.diagnostics?.length) { failure=report.failure??{scope:"project",phase:"discovery"}; state = "error"; diagnostics = [...report.diagnostics, ...diagnostics].slice(0, 20); }
171
182
  const artifact = path.resolve(root, previewArtifactPath(options, app.file));
172
183
  const available = existsSync(artifact);
173
184
  if (reportError) { state = "error"; diagnostics = [{ message: reportError }]; }
@@ -185,10 +196,10 @@ export function inspectBuildStatus(root, config, { session, previewSession, proc
185
196
  const current = state === "ready";
186
197
  return { id: app.id, state, session: report?.session ?? null, revision: value?.revision ?? null, lastSuccessfulRevision: value?.lastSuccessfulRevision ?? null,
187
198
  ...(!current && state !== "error" && live?.scenarios.has(app.id) ? { live: { revision: live.revision, sourceRevision: live.sourceRevision, validated: false } } : {}),
188
- current, stale: state === "unreported" ? null : !current, available, ...(value?.sourceRevision ? {sourceRevision:value.sourceRevision} : {}), diagnostics };
199
+ ...(state==="error"&&failure?{failure}:{}), current, stale: state === "unreported" ? null : !current, available, ...(value?.sourceRevision ? {sourceRevision:value.sourceRevision} : {}), diagnostics };
189
200
  });
190
201
  const state = reportError || report?.diagnostics?.length || previews.some((entry) => entry.state === "error") ? "error" : previews.some((entry) => entry.state === "building") ? "building" : previews.some((entry) => entry.state === "unreported") ? "unreported" : previews.some(entry => entry.current) ? "ready" : previews.length ? "idle" : "disabled";
191
- return { state, reported: Boolean(report), session: report?.session ?? null, sequence: report?.sequence ?? null, updatedAt: report?.updatedAt ?? null, ...(report?.progress ? { progress: report.progress } : {}), ...(report?.warmup?{warmup:report.warmup}:{}), previews, ...(report?.diagnostics?.length ? { diagnostics: report.diagnostics } : {}), resourceUri: BUILD_URI };
202
+ return { ...(report?.failure?{failure:report.failure}:{}), state, reported: Boolean(report), session: report?.session ?? null, sequence: report?.sequence ?? null, updatedAt: report?.updatedAt ?? null, ...(report?.progress ? { progress: report.progress } : {}), ...(report?.warmup?{warmup:report.warmup}:{}), previews, ...(report?.diagnostics?.length ? { diagnostics: report.diagnostics } : {}), resourceUri: BUILD_URI };
192
203
  }
193
204
 
194
205
  export class PreviewBuildError extends Error {
@@ -207,6 +218,6 @@ export function summarizeBuild(build) {
207
218
 
208
219
  export function buildFailure(build) {
209
220
  const summary = summarizeBuild(build);
210
- const details = summary.diagnostics.map((entry) => `${entry.file ?? ""}${entry.line ? `:${entry.line}` : ""}${entry.file ? ": " : ""}${entry.message}`).join("\n");
211
- return new PreviewBuildError(`Preview build failed. ${details}${summary.diagnosticsTruncated ? `\nMore diagnostic detail: ${BUILD_URI}` : ""}`, summary);
221
+ const details = previewDiagnosticText(summary.diagnostics);
222
+ return new PreviewBuildError(`${previewFailureTitle(summary)}. ${details}${summary.diagnosticsTruncated ? `\nMore diagnostic detail: ${BUILD_URI}` : ""}`, summary);
212
223
  }
@@ -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
- validation: { tool: "ads_validate", cli: ["ads", "validate"], defaultScope: "all", scopes: ["all","changed"], guideUri: "ads://guides/validation" },
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: "Use ads_check for core architecture diagnostics, then run the project's registered lint/typecheck/build and relevant tests from projectRoot. Core checks do not replace those commands. Review real UI in both themes; HTML delivery and compilation do not prove visual/behavioral correctness." };
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) {
@@ -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
  }
@@ -127,7 +166,7 @@ export function createDraftController(directory, { edits, startPreview, prewarm
127
166
  if (closed || previews.get(id) !== session) return;
128
167
  const scenarios = report.previews.filter(item => item.revision > 0 || item.live || item.state === "error").map(item => ({ id: item.id, state: item.live ? "checking" : item.state,
129
168
  building: ["idle", "building"].includes(item.state), current: item.current, stale: item.stale, revision: item.revision,
130
- ...(item.live ? { live: item.live } : {}), diagnosticCount: item.diagnostics.length }));
169
+ ...(item.live ? { live: item.live } : {}), ...(item.failure ? {failure:item.failure} : {}), diagnosticCount: item.diagnostics.length }));
131
170
  const building = scenarios.some(item => item.building);
132
171
  const state = scenarios.some(item => item.state === "error") ? "error" : building ? scenarios.some(item => item.live) ? "checking" : "building" : scenarios.some(item => item.current) ? "ready" : report.state;
133
172
  const build = { state, building, current: state === "ready", stale: state === "ready" ? false : scenarios.length ? true : null,
@@ -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) atomic(safe(path.dirname(manifestFile(id)), file.source), bytes(safe(root, file.target)));
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(bytes(safe(root, change.path))), unit: change.unit }; manifest.files.push(file); }
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(root, ".ds/draft-previews", id, "project");
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
- return { ...summary(value), scenario: selected, scenarios, diagnostics: registry.diagnostics, 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." };
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) { const session = previews.get(id); previews.delete(id); if (session) { discovery.remove(session.workspace); try { await session.starting; } catch { /* Failed prewarming remains retryable. */ } session.unsubscribeBuild?.(); await session.runtime?.close(); if (!previews.has(id)) rmSync(path.dirname(session.workspace), { recursive: true, force: true }); } }
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){const session=previews.get(id);if(!session?.starting)throw new Error("Draft preview is not active. Reopen ads_show_draft.");if(session.error)throw new Error(`Draft preview is stale: ${session.error}`);await session.starting;return session.runtime.readResource(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
  };