@reqvire-org/ads 0.3.28 → 0.3.31

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 (68) hide show
  1. package/dist/atomic-composition.mjs +2 -1
  2. package/dist/behaviors.mjs +2 -2
  3. package/dist/boundaries.mjs +6 -3
  4. package/dist/check.mjs +3 -0
  5. package/dist/cli.mjs +13 -0
  6. package/dist/config.mjs +11 -4
  7. package/dist/mcp/build-status.mjs +18 -5
  8. package/dist/mcp/context.mjs +2 -1
  9. package/dist/mcp/execution-results.mjs +4 -3
  10. package/dist/mcp/mutations.mjs +53 -51
  11. package/dist/mcp/preview-watch.mjs +23 -3
  12. package/dist/mcp/preview-widget.bundle.js +16 -15
  13. package/dist/mcp/resource-loader.js +40 -12
  14. package/dist/mcp/server.mjs +88 -46
  15. package/dist/oxlint.mjs +6 -1
  16. package/dist/preview-builder.mjs +10 -4
  17. package/dist/preview-files.mjs +19 -12
  18. package/dist/preview-inputs.mjs +6 -17
  19. package/dist/preview-resources.mjs +36 -7
  20. package/dist/preview-scope.mjs +6 -0
  21. package/dist/preview-workers.mjs +184 -0
  22. package/dist/project-documents.mjs +4 -0
  23. package/dist/scenario-inspector.mjs +34 -0
  24. package/dist/scenario-trace.mjs +5 -3
  25. package/dist/scenarios-compiler.mjs +200 -25
  26. package/dist/showcase/client.bundle.js +23 -22
  27. package/dist/showcase/index.html +2 -2
  28. package/dist/showcase/style.css +5 -1
  29. package/dist/skills/ads-break-ui/SKILL.md +3 -0
  30. package/dist/skills/ads-break-ui/references/behaviors.md +2 -0
  31. package/dist/skills/ads-break-ui/references/layers.md +6 -0
  32. package/dist/skills/ads-break-ui/references/runtimes.md +31 -0
  33. package/dist/skills/ads-break-ui/references/validation.md +69 -0
  34. package/dist/skills/ads-designer/SKILL.md +3 -0
  35. package/dist/skills/ads-designer/references/behaviors.md +2 -0
  36. package/dist/skills/ads-designer/references/layers.md +6 -0
  37. package/dist/skills/ads-designer/references/runtimes.md +31 -0
  38. package/dist/skills/ads-designer/references/validation.md +69 -0
  39. package/dist/skills/ads-import/SKILL.md +3 -0
  40. package/dist/skills/ads-import/references/behaviors.md +2 -0
  41. package/dist/skills/ads-import/references/layers.md +6 -0
  42. package/dist/skills/ads-import/references/runtimes.md +31 -0
  43. package/dist/skills/ads-import/references/validation.md +69 -0
  44. package/dist/skills/ads-motion/SKILL.md +3 -0
  45. package/dist/skills/ads-motion/references/behaviors.md +2 -0
  46. package/dist/skills/ads-motion/references/layers.md +6 -0
  47. package/dist/skills/ads-motion/references/runtimes.md +31 -0
  48. package/dist/skills/ads-motion/references/validation.md +69 -0
  49. package/dist/skills/ads-port/SKILL.md +3 -0
  50. package/dist/skills/ads-port/references/behaviors.md +2 -0
  51. package/dist/skills/ads-port/references/layers.md +6 -0
  52. package/dist/skills/ads-port/references/runtimes.md +31 -0
  53. package/dist/skills/ads-port/references/validation.md +69 -0
  54. package/dist/source-symbols.mjs +11 -0
  55. package/dist/source-values.mjs +10 -3
  56. package/dist/test-boundaries.mjs +96 -0
  57. package/dist/ui-framework.mjs +2 -1
  58. package/dist/units.mjs +12 -1
  59. package/dist/validation-checks.mjs +50 -0
  60. package/dist/validation-inputs.mjs +132 -0
  61. package/dist/validation.mjs +158 -0
  62. package/dist/verification/browser.mjs +3 -1
  63. package/dist/verification.mjs +1 -0
  64. package/docs/ARCHITECTURE.md +96 -20
  65. package/docs/BEHAVIORS.md +2 -0
  66. package/docs/CHANGELOG.md +74 -0
  67. package/docs/MCP.md +105 -12
  68. package/package.json +1 -1
@@ -4,6 +4,7 @@ import postcss from "postcss";
4
4
  import valueParser from "postcss-value-parser";
5
5
  import { isInside } from "./config.mjs";
6
6
  import { createAtomicTrace } from "./atomic-trace.mjs";
7
+ import { sourceSymbol } from "./source-symbols.mjs";
7
8
 
8
9
  export const atomicStyleGuide = "ads://guides/atomic-styles";
9
10
 
@@ -138,7 +139,7 @@ export function createAtomicCompositionReview(program, options) {
138
139
  if (!node || seen.has(node)) return false;
139
140
  seen = new Set([...seen, node]);
140
141
  const base = ts.isPropertyAccessExpression(node) ? node.expression : node;
141
- const symbol = checker.getSymbolAtLocation(base);
142
+ const symbol = sourceSymbol(checker, base);
142
143
  for (const item of symbol?.declarations ?? []) {
143
144
  if (ts.isImportSpecifier(item) && names.includes((item.propertyName ?? item.name).text) && modules.includes(item.parent.parent.parent.moduleSpecifier.text)) return true;
144
145
  if (ts.isNamespaceImport(item) && ts.isPropertyAccessExpression(node) && names.includes(node.name.text) && modules.includes(item.parent.parent.moduleSpecifier.text)) return true;
@@ -3,7 +3,7 @@ import path from "node:path";
3
3
  import { isBuiltin } from "node:module";
4
4
  import ts from "typescript";
5
5
  import { z } from "zod";
6
- import { isBehaviorFile, isDevelopmentFile, isInside, sourceFiles, isReviewFile } from "./config.mjs";
6
+ import { isBehaviorFile, isDevelopmentFile, isInside, sourceFiles, isReviewFile, isTestFile } from "./config.mjs";
7
7
  import { importResolver, projectCompilerOptions } from "./boundaries.mjs";
8
8
  import { inspectUnits } from "./units.mjs";
9
9
  import { scenarioApi } from "./public-api.mjs";
@@ -81,7 +81,7 @@ export function inspectBehaviors(options, suppliedProgram, suppliedRegistry) {
81
81
  const cases = new Set();
82
82
  for (const [name, check] of Object.entries(value.checks)) {
83
83
  const target = owned(check.file, `Check ${name}`);
84
- if (target && !isDevelopmentFile(target, options)) report(`Check ${name} must use a development-only test/spec file.`);
84
+ if (target && !isTestFile(target)) report(`Check ${name} must use a development-only test/spec file, not a scenario, fixture or helper.`);
85
85
  if (!Object.hasOwn(config.mcp.behaviorProfiles, check.profile)) report(`Check ${name} references unregistered profile ${check.profile}. Register its literal runner command in ds.config.json; checks cannot install packages or assume host globals.`);
86
86
  if (check.scenario && !scenarios.some(scenario => scenario.id === check.scenario)) report(`Check ${name} references unknown scenario ${check.scenario}.`);
87
87
  const identity = JSON.stringify([check.file, check.case, check.profile]);
@@ -10,7 +10,10 @@ export function projectCompilerOptions({ root, config, dsRoot }) {
10
10
  let compiler = {};
11
11
  if (file && isInside(root, file)) {
12
12
  const parsed = ts.readConfigFile(file, ts.sys.readFile);
13
- if (!parsed.error) compiler = ts.parseJsonConfigFileContent(parsed.config, ts.sys, path.dirname(file)).options;
13
+ // Only compiler options are consumed here. Expanding include/exclude globs
14
+ // for every lint rule/file needlessly walks the complete project tree.
15
+ // TypeScript still resolves extends (including package configs) normally.
16
+ if (!parsed.error) compiler = ts.parseJsonConfigFileContent(parsed.config, { ...ts.sys, readDirectory: () => [] }, path.dirname(file)).options;
14
17
  }
15
18
  return config && dsRoot ? { ...compiler, paths: { ...compiler.paths,
16
19
  [config.publicAlias]: [path.join(dsRoot, config.publicEntry)],
@@ -114,9 +117,9 @@ export function styleAccessProperty(node) {
114
117
 
115
118
  // Aliases, computed keys, cssText and bulk writes cannot widen an exception.
116
119
  export function styleWriteViolation(node, filename, { root, config }) {
117
- const allowed = config.boundaries.styleWrites.find((boundary) => path.resolve(root, boundary.file) === filename)?.properties ?? [];
118
120
  const property = styleAccessProperty(node);
119
- if (property !== undefined && property !== false && !(property && property !== "css-text" && allowed.includes(property))) {
121
+ if (property !== undefined && property !== false && !(property && property !== "css-text"
122
+ && config.boundaries.styleWrites.find((boundary) => path.resolve(root, boundary.file) === filename)?.properties?.includes(property))) {
120
123
  return "Imperative styles require a file boundary and an explicit property. Bulk writes, computed property names, and style-object escapes are forbidden.";
121
124
  }
122
125
  if (ts.isCallExpression(node) && isMember(node.expression) && ["setAttribute", "setAttributeNS"].includes(memberName(node.expression))) {
package/dist/check.mjs CHANGED
@@ -31,6 +31,7 @@ import { architectureEvidence, failure } from "./evidence.mjs";
31
31
  import { propertyRegistration } from "./property-registrations.mjs";
32
32
  import { createLayerBoundaries, layerSourceFiles } from "./layers.mjs";
33
33
  import { createDesignValues, inspectDesignAliases, isColorKeyword } from "./design-values.mjs";
34
+ import { inspectTestBoundaries } from "./test-boundaries.mjs";
34
35
 
35
36
  const scenarioLayoutGuidance = "Put demo-only sizing and framing in the development-only review/ layer, imported through the separate review entry. Patterns are production UI. Keep required behavior in the runtime owner; add component props for deliberate product API needs.";
36
37
  const inlineStyleGuidance = `Own visual styles in component/pattern Linaria. ${scenarioLayoutGuidance} Reserve inlineStyleFiles for documented measured geometry, not demo layout.`;
@@ -54,6 +55,7 @@ export function checkProject(directory, { trackingRoot } = {}) {
54
55
  diagnostics.push(...inspectAssets(options));
55
56
  const resolveImport = importResolver(options);
56
57
  const units = inspectUnits(options);
58
+ options.testOwner = file => units.owner(units.relative(path.relative(root,file)));
57
59
  const rootHtml = path.join(root, "index.html");
58
60
  const files = [...new Set([...sourceFiles(sourceRoot), ...sourceFiles(dsRoot), ...(existsSync(rootHtml) ? [rootHtml] : [])])];
59
61
  const boundaryFiles = [...config.inlineStyleFiles, ...config.boundaries.styleWrites.map(entry => entry.file)].map(file => path.resolve(root, file)).filter(file => existsSync(file) && statSync(file).isFile());
@@ -82,6 +84,7 @@ export function checkProject(directory, { trackingRoot } = {}) {
82
84
  inspectScenarioCoverage(options, program, report, (file, rule, message) => advisories.push({ file: path.relative(root, file).replaceAll("\\", "/"), rule, message, line: 1, column: 1 }), scenarioTrace);
83
85
  const behaviors = inspectBehaviors(options, program);
84
86
  diagnostics.push(...behaviors.diagnostics);
87
+ diagnostics.push(...inspectTestBoundaries(options,units,behaviors.contracts,program));
85
88
  inspectControllers(options, program, report, behaviors.contracts);
86
89
  // The foundation remains a fixed import-only entry, not an extra styling layer.
87
90
  const foundationEntry = path.join(dsRoot, config.stylesEntry);
package/dist/cli.mjs CHANGED
@@ -11,6 +11,7 @@ Usage: ads init [options] Run inside your project
11
11
 
12
12
  init Set up ADS in the current project (requires package.json)
13
13
  check [directory] Check tokens, ownership, imports, and showcase coverage
14
+ validate [dir] Audit architecture, lint, project scripts and behavior checks
14
15
  behaviors [dir] Inspect behavior contracts and current verification evidence
15
16
  verify [directory] Run registered behavior checks (--unit and --check select)
16
17
  tokens [directory] Inspect local token values and theme definitions
@@ -29,6 +30,7 @@ Usage: ads init [options] Run inside your project
29
30
  --mutations MCP only: enable guarded ADS source editing
30
31
  --unit id Verify only: select one discovered behavior contract owner
31
32
  --check id Verify only: select a registered check (repeatable)
33
+ --changed Validate only: select affected checks since the last full audit
32
34
 
33
35
  External components and examples are imported using the ADS skills.
34
36
  No component library or example catalogue is bundled.
@@ -46,10 +48,12 @@ async function main(args) {
46
48
  const selectedChecks = [];
47
49
  let showcase = true;
48
50
  let mutations = false;
51
+ let changed = false;
49
52
  const positional = [];
50
53
  for (let index = 0; index < args.length; index++) {
51
54
  const argument = args[index];
52
55
  if (argument === "--json") json = true;
56
+ else if (argument === "--changed") changed = true;
53
57
  else if (argument === "--no-showcase") showcase = false;
54
58
  else if (argument === "--mutations") mutations = true;
55
59
  else if (argument === "--unit" || argument === "--check") {
@@ -77,6 +81,7 @@ async function main(args) {
77
81
  }
78
82
  if (positional.length > 2) throw new Error("Extra argument. Run ads --help.");
79
83
  const [command, directory] = positional;
84
+ if (changed && command !== "validate") throw new Error("--changed is supported only by validate.");
80
85
  if ((port !== undefined || !showcase) && !["mcp", "showcase"].includes(command)) throw new Error("Website options are supported only by mcp/showcase.");
81
86
  if (!showcase && command !== "mcp") throw new Error("--no-showcase is supported only by mcp.");
82
87
  if (mutations && command !== "mcp") throw new Error("--mutations is supported only by mcp.");
@@ -95,6 +100,13 @@ async function main(args) {
95
100
  let result;
96
101
  if (command === "init") result = initProject(target, { toolPackage, packageManager, framework });
97
102
  else if (command === "check") result = checkProject(target);
103
+ else if (command === "validate") {
104
+ const {createValidationController}=await import("./validation.mjs");
105
+ const validation=createValidationController(target);
106
+ const abort=()=>{void validation.close();};process.once("SIGINT",abort);process.once("SIGTERM",abort);
107
+ try {result=await validation.run({scope:changed?"changed":"all"});}
108
+ finally {process.removeListener("SIGINT",abort);process.removeListener("SIGTERM",abort);await validation.close();}
109
+ }
98
110
  else if (command === "behaviors") { const {behaviorStatus}=await import("./verification.mjs"); const {loadConfig}=await import("./config.mjs"); result=behaviorStatus(loadConfig(target)); }
99
111
  else if (command === "verify") { const {createVerificationController}=await import("./verification.mjs"); const verification=createVerificationController(target); try {result=await verification.run({...(unit?{unit}:{}),...(selectedChecks.length?{checks:selectedChecks}:{})});} finally {await verification.close();} }
100
112
  else if (command === "tokens") result = inspectTokens(target);
@@ -107,6 +119,7 @@ async function main(args) {
107
119
  else if (command === "lint-config") console.log(`Generated ${result.file}\nProjects initialized with ads init refresh this automatically during lint:ds/build.`);
108
120
  else if (command === "behaviors") console.log(JSON.stringify(result, null, 2));
109
121
  else if (command === "verify") { for (const item of result.results) console.log(`${item.unit}#${item.check}: ${item.status} (${item.profile})`); }
122
+ 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})`:""}`);}
110
123
  else if (command === "tokens") {
111
124
  for (const token of result.tokens) console.log(`${token.name}${token.type ? ` (${token.type})` : ""}: ${token.definitions.map((entry) => `${entry.scope}: ${entry.value}`).join("; ")}`);
112
125
  } else if (result.ok) console.log(`ADS check passed: ${target}`);
package/dist/config.mjs CHANGED
@@ -18,6 +18,7 @@ export const defaultConfig = {
18
18
  boundaries: { styleWrites: [], componentVariables: [] },
19
19
  assets: { publicDirs: ["public/assets"], generatedPaths: ["dist", "dist-showcase", ".vite", ".ds"], generatedFiles: [], iconSource: null },
20
20
  oxlint: { plugins: [], rules: {}, overrides: [] },
21
+ validation: { checks: null, inputs: [] },
21
22
  mcp: { showcaseUrl: null, showcaseTitle: null, apps: [], previewWatch: null, previewManifest: null, mutationChecks: null, mutationCheckTimeoutMs: 60000, behaviorProfiles: {}, capture: {} },
22
23
  };
23
24
 
@@ -44,11 +45,17 @@ export function loadConfig(directory = process.cwd()) {
44
45
  if (!(field in defaultConfig)) throw new Error(`Unknown ADS configuration field: ${field}`);
45
46
  }
46
47
  if (user.oxlint !== undefined && (!user.oxlint || typeof user.oxlint !== "object" || Array.isArray(user.oxlint))) throw new Error("oxlint must be an object.");
47
- for (const field of ["boundaries", "assets", "oxlint", "mcp"]) {
48
+ for (const field of ["boundaries", "assets", "oxlint", "mcp", "validation"]) {
48
49
  if (user[field] !== undefined && (!user[field] || typeof user[field] !== "object" || Array.isArray(user[field]))) throw new Error(`${field} must be an object.`);
49
50
  for (const key of Object.keys(user[field] ?? {})) if (!(key in defaultConfig[field])) throw new Error(`Unknown ${field} configuration field: ${key}`);
50
51
  }
51
- const config = { ...defaultConfig, ...user, boundaries: { ...defaultConfig.boundaries, ...user.boundaries }, assets: { ...defaultConfig.assets, ...user.assets }, oxlint: { ...defaultConfig.oxlint, ...user.oxlint }, mcp: { ...defaultConfig.mcp, ...user.mcp } };
52
+ 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 } };
53
+ 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.");
54
+ 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.");
55
+ for (const file of config.validation.inputs) {
56
+ const absolute = projectPath(root,file,"validation.inputs");
57
+ if (absolute === root || path.relative(root,absolute).replaceAll("\\","/") !== file || file.split("/").some(part=>["node_modules",".git",".ds"].includes(part))) throw new Error("validation.inputs must name canonical source paths below the project root, excluding dependency and metadata directories.");
58
+ }
52
59
  if (config.schemaVersion !== 1) throw new Error(`Unsupported ADS config version: ${config.schemaVersion}`);
53
60
  if (user.framework !== undefined && !supportedFrameworks.includes(user.framework)) throw new Error("framework must be react or preact.");
54
61
  if (typeof config.publicAlias !== "string" || !config.publicAlias.trim()) throw new Error("publicAlias must be a non-empty string.");
@@ -116,7 +123,7 @@ export function loadConfig(directory = process.cwd()) {
116
123
  || !["protocol", "playwright"].includes(profile.runner ?? "protocol")
117
124
  || profile.framework !== undefined && profile.framework !== config.framework
118
125
  || profile.mode !== undefined && !["browser", "strict", "unit"].includes(profile.mode)
119
- || profile.timeoutMs !== undefined && (!Number.isInteger(profile.timeoutMs) || profile.timeoutMs < 100 || profile.timeoutMs > 300000)) throw new Error(`Invalid behavior profile ${name}. Use literal executable/args, a protocol or Playwright runner, a matching framework and a bounded timeout. Profiles do not install dependencies or receive APIs from an MCP host.`);
126
+ || 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.`);
120
127
  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.`);
121
128
  }
122
129
  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.");
@@ -222,7 +229,7 @@ export function importViolation(specifier, filename, options, resolve) {
222
229
  if (isReviewFile(filename, options)) return false;
223
230
  // Owner-local white-box tests may exercise private helpers without making
224
231
  // those helpers public API. Scenarios remain public-API consumers.
225
- if (isTestFile(filename) && isInside(dsRoot, filename) && isInside(path.dirname(filename), file)) return false;
232
+ if (isTestFile(filename) && isInside(dsRoot, filename) && options.testOwner?.(filename) && options.testOwner(filename) === options.testOwner(file)) return false;
226
233
  if (isDevelopmentFile(filename, options) && isDevelopmentFile(file, options)) return false;
227
234
  if (isTestFile(filename) && (isInside(path.join(dsRoot, "showcase"), file) || isTestFile(file))) return false;
228
235
  if (isInside(path.join(dsRoot, "showcase"), filename) && isInside(path.join(dsRoot, "showcase"), file)) return false;
@@ -5,7 +5,7 @@ import { z } from "zod";
5
5
  import { isInside, projectPath, loadConfig } from "../config.mjs";
6
6
  import { previewSourceRevision } from "../preview-inputs.mjs";
7
7
  import { readPreviewManifest } from "../preview-resources.mjs";
8
- import { previewArtifactPath, withPreviewSession } from "../preview-scope.mjs";
8
+ import { livePreviewOptions, previewArtifactPath, withPreviewSession } from "../preview-scope.mjs";
9
9
 
10
10
  export const BUILD_URI = "ads://project/build";
11
11
  export const buildStatusFile = (root) => path.join(root, ".ds/build-status.json");
@@ -13,7 +13,8 @@ const maxBytes = 256 * 1024;
13
13
  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
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();
15
15
  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
- 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(), 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.");
16
+ const liveSchema = z.object({ revision: z.string().regex(/^[a-f0-9]{64}$/), sourceRevision: z.string().regex(/^[a-f0-9]{64}$/) }).strict();
17
+ 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(), 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.");
17
18
  export const artifactDigest = (file) => {
18
19
  if (realpathSync(file) !== file) throw new Error("Preview output cannot resolve through a symlink.");
19
20
  if (statSync(file).size > 2 * 1024 * 1024) throw new Error("Preview exceeds 2 MiB.");
@@ -41,8 +42,10 @@ export function createBuildReporter(directory, { apps, session = process.env.ADS
41
42
  let sequence = 0;
42
43
  let diagnostics = [];
43
44
  let progress;
45
+ let live, batching = 0;
44
46
  function save() {
45
- const value = { schemaVersion: 1, session, sequence: ++sequence, updatedAt: new Date().toISOString(), previews: [...entries.values()], ...(progress ? { progress } : {}), ...(diagnostics.length ? { diagnostics } : {}) };
47
+ if (batching) return;
48
+ const value = { schemaVersion: 1, session, sequence: ++sequence, updatedAt: new Date().toISOString(), previews: [...entries.values()], ...(progress ? { progress } : {}), ...(live ? { live } : {}), ...(diagnostics.length ? { diagnostics } : {}) };
46
49
  let text = JSON.stringify(snapshot.parse(value));
47
50
  // A shared graph failure applies to every scenario. Store repeated details
48
51
  // once only when necessary; ordinary reports retain inline diagnostics.
@@ -71,6 +74,8 @@ export function createBuildReporter(directory, { apps, session = process.env.ADS
71
74
  save();
72
75
  return {
73
76
  session,
77
+ batch(run) { ++batching; try { return run(); } finally { --batching; save(); } },
78
+ live(value) { live = value; save(); },
74
79
  progress(phase) {
75
80
  const now = new Date().toISOString();
76
81
  progress = { phase, startedAt: !progress || progress.phase === "idle" ? now : progress.startedAt, updatedAt: now };
@@ -140,13 +145,20 @@ export function inspectBuildStatus(root, config, { session, previewSession, proc
140
145
  } catch (error) { reportError = `Invalid preview build status: ${error.message.slice(0, 500)}`; }
141
146
  let graphError;
142
147
  let sourceRevision, sourceError;
143
- if (report?.previews.some(entry=>entry.state==="ready")) {
148
+ if (report?.live || report?.previews.some(entry=>entry.state==="ready")) {
144
149
  try { sourceRevision = previewSourceRevision(loadConfig(root),config.apps); }
145
150
  catch (error) { sourceError = `Cannot verify preview inputs: ${error.message}`; }
146
151
  }
152
+ let live;
153
+ if (report?.live && !reportError && !sourceError && report.live.sourceRevision === sourceRevision && !report.diagnostics?.length) {
154
+ try {
155
+ const graph = readPreviewManifest(livePreviewOptions(options));
156
+ if (graph?.session === report.session && graph.revision === report.live.revision) live = { ...report.live, scenarios: new Set(graph.scenarios.map(entry => entry.id)) };
157
+ } catch { /* An incomplete/corrupt live graph grants no preview access. */ }
158
+ }
147
159
  if (config.previewManifest && report?.previews.some(entry => entry.state === "ready")) {
148
160
  try {
149
- if (!readPreviewManifest(options, { verify: true })) throw new Error("Preview resource manifest is missing.");
161
+ if (!readPreviewManifest(options, { verify: "cached" })) throw new Error("Preview resource manifest is missing.");
150
162
  } catch (error) { graphError = `Invalid preview resource graph: ${error.message}`; }
151
163
  }
152
164
  const previews = config.apps.map((app) => {
@@ -170,6 +182,7 @@ export function inspectBuildStatus(root, config, { session, previewSession, proc
170
182
  if (["stopped", "stopping", "idle"].includes(processState?.state)) state = "unreported";
171
183
  const current = state === "ready";
172
184
  return { id: app.id, state, session: report?.session ?? null, revision: value?.revision ?? null, lastSuccessfulRevision: value?.lastSuccessfulRevision ?? null,
185
+ ...(!current && state !== "error" && live?.scenarios.has(app.id) ? { live: { revision: live.revision, sourceRevision: live.sourceRevision, validated: false } } : {}),
173
186
  current, stale: state === "unreported" ? null : !current, available, ...(value?.sourceRevision ? {sourceRevision:value.sourceRevision} : {}), diagnostics };
174
187
  });
175
188
  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";
@@ -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. When ads_status.mutations.enabled, use ads_units and guarded ads_apply_patch for one owner; use ads_apply_transaction only for coupled owner patches. 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. 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. When ads_status.mutations.enabled, use ads_units and guarded ads_apply_patch for one owner; use ads_apply_transaction only for coupled owner patches. 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.";
10
10
 
11
11
  function manager(root, pkg) {
12
12
  if (typeof pkg.packageManager === "string") return pkg.packageManager.split("@")[0];
@@ -27,6 +27,7 @@ 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
31
  showcase: { client: "tool-owned-mcp", url: config.mcp.showcaseUrl, title: config.mcp.showcaseTitle ?? `${pkg.name ?? path.basename(root)} · Design System` },
31
32
  runtime: { ...developmentRuntime(),
32
33
  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." } };
@@ -5,7 +5,7 @@ import { compactAcceptance, compactRow, jsonBytes, resultBudgets, resultPage, re
5
5
 
6
6
  export const RESULTS_URI = "ads://project/results";
7
7
  export const resultSections = ["outcomes", "checks", "diagnostics", "advisories", "warnings", "changes", "captures", "acceptance", "investigation", "selection"];
8
- const kinds = ["verification", "mutation"];
8
+ const kinds = ["verification", "mutation", "validation"];
9
9
  const maxStoredBytes = 8 * 1024 * 1024;
10
10
  const uuid = value => typeof value === "string" && /^[a-f0-9]{8}(?:-[a-f0-9]{4}){3}-[a-f0-9]{12}$/.test(value);
11
11
  const resultUri = id => `ads://results/${id}`;
@@ -27,13 +27,14 @@ function snapshot(kind, raw) {
27
27
  outcomes: outcomes.map(outcome),
28
28
  checks: (raw.checks ?? []).map(({ results, ...check }) => ({ ...check, ...(results ? { outcomeCount: results.length } : {}) })),
29
29
  diagnostics: raw.diagnostics ?? [], advisories: raw.advisories ?? [], warnings: raw.warnings ?? [], changes: raw.changes ?? [],
30
- captures: raw.screenshots?.captures ?? [], selection: [{unit:raw.unit,units:raw.units,transaction:raw.transaction}],
30
+ captures: raw.screenshots?.captures ?? [], selection: [{unit:raw.unit,units:raw.units,transaction:raw.transaction,...raw.selection}],
31
31
  acceptance: raw.acceptance ? [raw.acceptance] : [], investigation: raw.investigation ? [raw.investigation] : [],
32
32
  };
33
33
  const resultId = randomUUID();
34
34
  return { schemaVersion: 1, resultId, kind, createdAt: new Date().toISOString(), ok: !!raw.ok,
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
+ ...(kind === "validation" ? {scope:raw.scope,requestedScope:raw.requestedScope,sourceRevision:raw.sourceRevision,current:raw.current,elapsedMs:raw.elapsedMs,...(raw.fallback?{fallback:raw.fallback}:{})} : {}),
37
38
  acceptance: raw.acceptance, investigation: raw.investigation,
38
39
  sections: Object.fromEntries(Object.entries(sections).map(([key, rows]) => [key, rows.map((row, recordIndex) => ({ recordIndex, ...(row && typeof row === "object" ? row : {message:row}) }))])),
39
40
  counts: { outcomes: count(outcomes), checks: count(sections.checks), diagnostics: sections.diagnostics.length,
@@ -46,7 +47,7 @@ function summary(value, storageWarning) {
46
47
  const failedOutcomes = value.sections.outcomes.filter(item => item.status !== "passed");
47
48
  const failureRows = failedOutcomes.length ? failedOutcomes : value.sections.diagnostics;
48
49
  const section = failedOutcomes.length ? "outcomes" : value.sections.diagnostics.length ? "diagnostics" : value.sections.captures.length ? "captures" : value.sections.outcomes.length ? "outcomes" : "checks";
49
- const result = { ok, resultId, kind, ...(applied !== undefined ? { applied } : {}), ...(unit ? { unit } : {}),
50
+ 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 } : {}),
50
51
  ...(units ? { units } : {}), ...(transaction ? { transaction } : {}), createdAt, counts, freshness:"recorded-at-completion",
51
52
  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)),
52
53
  failureCount: value.failureCount ?? failureRows.length, resourceUri,
@@ -1,5 +1,4 @@
1
1
  import { createHash, randomUUID } from "node:crypto";
2
- import { spawn } from "node:child_process";
3
2
  import { createRequire } from "node:module";
4
3
  import { cpSync, existsSync, lstatSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, realpathSync, renameSync, rmSync, symlinkSync, writeFileSync } from "node:fs";
5
4
  import path from "node:path";
@@ -9,16 +8,17 @@ import { affectedBehaviorUnits, createVerificationController } from "../verifica
9
8
  import { checkProject } from "../check.mjs";
10
9
  import { generateLintConfig } from "../lint-config.mjs";
11
10
  import { generateBrandAssets } from "../brand-assets.mjs";
12
- import { projectContext } from "./context.mjs";
13
11
  import { applyFilePatch, parseUnifiedPatch } from "./patch.mjs";
14
12
  import { createCaptureController, captureSelections } from "../capture.mjs";
15
13
  import { previewSourceRevision } from "../preview-inputs.mjs";
16
14
  import { inspectScenarios } from "../scenarios.mjs";
17
15
  import { checkUnitCandidate, checkUnitFiles, inspectUnits, validateUnitId } from "../units.mjs";
18
16
  import { acceptance, failure as evidenceFailure } from "../evidence.mjs";
19
- import { packageScriptCommand } from "../development-runtime.mjs";
17
+ import { checkCommand, projectChecks as checks } from "../validation-checks.mjs";
18
+ import { preparePreviewCache } from "../scenarios-compiler.mjs";
19
+ import { validationInputFiles } from "../validation-inputs.mjs";
20
20
 
21
- export const mutationLimits = { units: 8, files: 32, patchBytes: 256 * 1024, patchFileBytes: 16 * 1024 * 1024, fileBytes: 16 * 1024 * 1024, readChars: 12000, snapshotFiles: 20000, snapshotBytes: 128 * 1024 * 1024 };
21
+ export const mutationLimits = { units: 8, files: 32, patchBytes: 256 * 1024, patchFileBytes: 16 * 1024 * 1024, fileBytes: 16 * 1024 * 1024, readChars: 12000, snapshotFiles: 100000, snapshotBytes: 2 * 1024 * 1024 * 1024 };
22
22
  const digest = bytes => `sha256:${createHash("sha256").update(bytes).digest("hex")}`;
23
23
  const ignored = new Set([".git", ".ds", "node_modules", ".vite", "coverage", ".playwright-cli", "test-results", "output"]);
24
24
  const textFile = file => /\.(?:[cm]?[jt]sx?|css|html|jsonc?|md|txt|svg)$/.test(file);
@@ -80,7 +80,31 @@ function validateContent(change, unit) {
80
80
  if (unit !== "configuration" && /\b(?:oxlint|eslint)-(?:disable|enable)|\bbiome-ignore|@ts-(?:ignore|nocheck|expect-error)/.test(bytes.toString("utf8"))) throw fail("mutation-policy", "Configure reviewed lint/typecheck exceptions through the configuration unit instead of source suppression directives.", change.path);
81
81
  }
82
82
 
83
- function snapshot(options, destination) {
83
+ function candidateInputs(options,extraFiles=[]) {
84
+ try { return validationInputFiles(options,extraFiles,{maxFiles:mutationLimits.snapshotFiles,maxBytes:mutationLimits.snapshotBytes}); }
85
+ catch(error) { if(error.code==="ADS_INPUT_LIMIT")throw fail("mutation-snapshot",error.message);throw error; }
86
+ }
87
+ function copyInputs(options, destination, extraFiles, {baseline=new Map(),changed=new Set(),budget={bytes:0,files:0}}={}) {
88
+ for (const [relative,value] of Object.entries(candidateInputs(options,extraFiles))) {
89
+ if (baseline.has(relative)) continue;
90
+ if (relative==="installed-dependencies" || value===null) { baseline.set(relative,value);continue; }
91
+ const file=path.resolve(options.root,relative),stat=lstatSync(file);
92
+ if (budget.files+1>mutationLimits.snapshotFiles || budget.bytes+stat.size>mutationLimits.snapshotBytes) throw fail("mutation-snapshot","Relevant inputs exceed the bounded validation snapshot limit.");
93
+ const content=readFileSync(file);budget.bytes+=content.length;budget.files++;
94
+ if (budget.bytes>mutationLimits.snapshotBytes) throw fail("mutation-snapshot","Relevant inputs exceed the bounded validation snapshot limit.");
95
+ baseline.set(relative,digest(content));
96
+ if (!changed.has(relative)) {
97
+ const target=path.join(destination,relative);mkdirSync(path.dirname(target),{recursive:true});
98
+ writeFileSync(target,content,{mode:stat.mode});
99
+ }
100
+ }
101
+ return baseline;
102
+ }
103
+
104
+ function snapshot(options) {
105
+ // Scan the entire *candidate* to detect checking commands that rewrite source,
106
+ // including files outside the input graph. Live projects are never copied here.
107
+ candidateInputs(options);
84
108
  const entries = [];
85
109
  let bytes = 0;
86
110
  const generated = options.config.assets.generatedPaths.map(file => path.resolve(options.root, file));
@@ -90,16 +114,14 @@ function snapshot(options, destination) {
90
114
  const file = path.join(folder, entry.name);
91
115
  const relative = path.relative(options.root, file);
92
116
  if (generated.some(base => isInside(base, file))) continue;
93
- const target = destination && path.join(destination, relative);
94
- if (entry.isSymbolicLink()) throw fail("mutation-snapshot", "Project source symlinks require an ordinary project copy for guarded validation.", relative);
95
- if (entry.isDirectory()) { if (target) mkdirSync(target, { recursive: true }); walk(file); }
117
+ if (entry.isSymbolicLink()) continue;
118
+ if (entry.isDirectory()) walk(file);
96
119
  else if (entry.isFile()) {
97
120
  if (bytes + lstatSync(file).size > mutationLimits.snapshotBytes || entries.length >= mutationLimits.snapshotFiles) throw fail("mutation-snapshot", "Project source exceeds the bounded validation snapshot limit.");
98
121
  const content = readFileSync(file);
99
122
  bytes += content.length;
100
123
  if (bytes > mutationLimits.snapshotBytes || entries.length >= mutationLimits.snapshotFiles) throw fail("mutation-snapshot", "Project source exceeds the bounded validation snapshot limit.");
101
124
  entries.push([relative, digest(content)]);
102
- if (target) writeFileSync(target, content, { mode: lstatSync(file).mode });
103
125
  }
104
126
  }
105
127
  }
@@ -110,38 +132,6 @@ function snapshot(options, destination) {
110
132
  return JSON.stringify(entries);
111
133
  }
112
134
 
113
- function checkCommand(command, args, cwd, signal, input, gate = {category:"architecture",phase:"patch-preparation"}, timeoutMs = 60000) {
114
- return new Promise((resolve, reject) => {
115
- if (signal?.aborted) { reject(fail("mutation-cancelled", "Mutation cancelled before validation.",undefined,evidenceFailure("runner","mutation-execution","ADS_CANCELLED"))); return; }
116
- const child = spawn(command, args, { cwd, shell: false, detached: process.platform !== "win32", windowsHide: true, stdio: [input === undefined ? "ignore" : "pipe", "pipe", "pipe"],
117
- env: { ...process.env, PATH: [path.join(cwd, "node_modules/.bin"), path.dirname(process.execPath), process.env.PATH ?? ""].join(path.delimiter) } });
118
- let output = "", failure;
119
- const startedAt=Date.now();
120
- if (input !== undefined) { child.stdin.on("error", () => {}); child.stdin.end(input); }
121
- function kill() {
122
- if (!child.pid) return;
123
- if (process.platform === "win32") {
124
- const stop = spawn("taskkill", ["/pid", String(child.pid), "/T", "/F"], { stdio: "ignore", windowsHide: true });
125
- stop.on("error", () => child.kill("SIGKILL"));
126
- } else { try { process.kill(-child.pid, "SIGKILL"); } catch (error) { if (error.code !== "ESRCH") failure ??= error; } }
127
- }
128
- const abort = () => { failure = fail("mutation-cancelled", "Mutation cancelled during validation."); kill(); };
129
- signal?.addEventListener("abort", abort, { once: true });
130
- const timer = setTimeout(() => { failure = fail("mutation-check", `${path.basename(command)} ${args.join(" ")} exceeded its ${timeoutMs} ms command budget.`); failure.code="ADS_COMMAND_TIMEOUT"; kill(); }, timeoutMs);
131
- for (const stream of [child.stdout, child.stderr]) stream.on("data", chunk => { output = (output + chunk.toString()).slice(-12000); });
132
- child.once("error", error => { failure = error; });
133
- child.once("exit", kill); // Also clean up descendants of a finished launcher.
134
- child.once("close", code => {
135
- clearTimeout(timer); signal?.removeEventListener("abort", abort);
136
- const detail={command:path.basename(command),args,timeoutMs,elapsedMs:Date.now()-startedAt,exitCode:code};
137
- if (failure || code !== 0) {
138
- const error=failure??fail("mutation-check", `${path.basename(command)} ${args.join(" ")} failed (${code}).\n${output}`);
139
- error.diagnostic={...(error.diagnostic??{rule:"mutation-check",message:error.message}),...detail,output:output.slice(-4000),failure:evidenceFailure(failure?"runner":gate.category,gate.phase,failure?.code??(failure?"ADS_COMMAND_INTERRUPTED":"ADS_COMMAND_EXIT"),{certainty:"observed-boundary"})};
140
- reject(error);
141
- } else resolve({ ...detail,phase:gate.phase, passed: true });
142
- });
143
- });
144
- }
145
135
 
146
136
  function mutationEvidence(result, candidateRevision) {
147
137
  const diagnostics=(result.diagnostics??[]).map(diagnostic=>({...diagnostic,failure:diagnostic.failure??evidenceFailure("architecture","mutation-policy",diagnostic.rule)}));
@@ -150,14 +140,6 @@ function mutationEvidence(result, candidateRevision) {
150
140
  return {...result,...(result.diagnostics?{diagnostics}:{}),acceptance:accepted,investigation:{target:"candidate",candidateRevision:candidateRevision??null,...(failed?{failure:failed.failure,failingStep:failed.failure.phase,source:failed.file?{file:failed.file,line:failed.line,column:failed.column}:null,...(failed.command?{command:failed.command,args:failed.args,exitCode:failed.exitCode,output:failed.output}:{}),message:failed.message}:{}),acceptance:accepted}};
151
141
  }
152
142
 
153
- function checks(options) {
154
- const context = projectContext(options);
155
- const pkg = JSON.parse(readFileSync(path.join(options.root, "package.json"), "utf8"));
156
- const scripts = options.config.mcp.mutationChecks ?? [pkg.scripts?.["lint:project"] ? "lint:project" : "lint", "typecheck", "build:mcp-previews"].filter(name => typeof pkg.scripts?.[name] === "string");
157
- if (scripts.some(name => typeof pkg.scripts?.[name] !== "string")) throw fail("mutation-check", "Every configured mcp.mutationChecks script must exist in package.json.");
158
- if (scripts.length && !["npm", "bun"].includes(context.packageManager)) throw fail("mutation-check", "Declare packageManager as npm or bun to run mutation checks.");
159
- return scripts.map(script => packageScriptCommand(context.packageManager, script));
160
- }
161
143
 
162
144
  export function createMutationController(directory, { captures = createCaptureController(directory) } = {}) {
163
145
  const root = path.resolve(directory);
@@ -221,7 +203,9 @@ export function createMutationController(directory, { captures = createCaptureCo
221
203
  temporary = mkdtempSync(path.join(cache, "mutation-"));
222
204
  const candidate = path.join(temporary, "project");
223
205
  mkdirSync(candidate);
224
- const before = snapshot(options, candidate);
206
+ const patchPaths=plans.flatMap(plan=>plan.entries.map(entry=>entry.path));
207
+ const copyBudget={bytes:0,files:0};
208
+ const copiedInputs=copyInputs(options,candidate,patchPaths,{budget:copyBudget});
225
209
  const dependencies = path.join(root, "node_modules");
226
210
  if (!existsSync(dependencies)) throw fail("mutation-check", "Install project dependencies before using guarded mutations.");
227
211
  symlinkSync(realpathSync(dependencies), path.join(candidate, "node_modules"), process.platform === "win32" ? "junction" : "dir");
@@ -276,6 +260,21 @@ export function createMutationController(directory, { captures = createCaptureCo
276
260
  checkUnitCandidate(loadConfig(candidate),plan.unit,selected,inventory);
277
261
  }
278
262
  const candidateOptions = loadConfig(candidate);
263
+ // A proposed configuration may add roots or explicit inputs. Preserve
264
+ // already patched files while bringing those additional live inputs in.
265
+ copyInputs({root,config:candidateOptions.config,dsRoot:path.resolve(root,candidateOptions.config.dsDir),sourceRoot:path.resolve(root,candidateOptions.config.sourceDir)},candidate,patchPaths,{baseline:copiedInputs,changed:new Set(changes.map(change=>change.path)),budget:copyBudget});
266
+ const inputPaths = [...new Set([...changes.map(change=>change.path),...Object.keys(validationInputFiles(candidateOptions))])];
267
+ const scopedInputs = () => {
268
+ const files = {};
269
+ for (const original of [options,candidateOptions]) {
270
+ const rebased = { root, config: original.config, dsRoot: path.resolve(root,original.config.dsDir), sourceRoot: path.resolve(root,original.config.sourceDir) };
271
+ Object.assign(files,validationInputFiles(rebased,inputPaths));
272
+ }
273
+ return Object.fromEntries(Object.entries(files).sort(([a],[b])=>a.localeCompare(b)));
274
+ };
275
+ const currentInputs = scopedInputs();
276
+ const before = JSON.stringify(Object.fromEntries(Object.keys(currentInputs).map(file=>[file,copiedInputs.get(file)??null])));
277
+ if (JSON.stringify(currentInputs) !== before) throw fail("mutation-conflict","Relevant inputs changed while preparing validation; regenerate the patch.");
279
278
  const extraChecks = checks(candidateOptions);
280
279
  const expected = snapshot(candidateOptions);
281
280
  candidateRevision=digest(Buffer.from(expected));
@@ -317,9 +316,11 @@ export function createMutationController(directory, { captures = createCaptureCo
317
316
  const proposal = digest(Buffer.from(JSON.stringify(changes.map(change => [change.path, change.content === null ? null : digest(Buffer.from(change.content))]))));
318
317
  screenshots = await captures.run({ captures: selections, candidateRoot: candidate, proposal, publish: false }, signal, value => { progress = value; notifyProgress?.(value); });
319
318
  }
319
+ let preparedPreview;
320
+ if(!dryRun){try{preparedPreview=preparePreviewCache(candidateOptions,loadConfig(root));}catch{/* A missing cache falls back to background compilation. */}}
320
321
  if (signal?.aborted) throw fail("mutation-cancelled", "Mutation cancelled before application.",undefined,evidenceFailure("runner","mutation-execution","ADS_CANCELLED"));
321
322
  if (snapshot(candidateOptions) !== expected) throw fail("mutation-check", "A validation command changed source files. Use checks without source-writing side effects.");
322
- if (snapshot(loadConfig(root)) !== before) throw fail("mutation-conflict", "Project inputs changed during validation; no changes were applied. Read current source and retry.");
323
+ if (JSON.stringify(scopedInputs()) !== before) throw fail("mutation-conflict", "ADS, consuming UI or declared validation inputs changed during validation; no changes were applied. Read current source and retry.");
323
324
  for (const change of changes) address(options, change.path);
324
325
  if (screenshots) {
325
326
  captures.store.commit(screenshots.records);
@@ -354,6 +355,7 @@ export function createMutationController(directory, { captures = createCaptureCo
354
355
  const warnings = [];
355
356
  if (!dryRun && (assets || configuration)) { try { await generateBrandAssets(root); } catch (error) { warnings.push({ rule: "mutation-assets", message: `Source was applied; generated brand output needs recovery: ${error.message}` }); } }
356
357
  if (!dryRun && captures.store.fingerprint()) { try { captures.store.promote(previewSourceRevision(loadConfig(root)), inspectScenarios(loadConfig(root)).scenarios); } catch (error) { warnings.push({ rule: "mutation-capture", message: `Source was applied; capture promotion needs recovery: ${error.message}` }); } }
358
+ if (!dryRun && preparedPreview) { try { preparedPreview(); } catch (error) { warnings.push({rule:"mutation-preview-cache",message:`Source was applied; preview warming will rebuild instead: ${error.message}`}); } }
357
359
  return lastResult = mutationEvidence({ ok: true, ...(patches ? {units,transaction:true} : {unit}), applied: !dryRun, changes: changes.map(change => ({ path: change.path, operation: change.content === null ? "delete" : change.expectedDigest === null ? "create" : "update", digest: change.content === null ? null : digest(Buffer.from(change.content)) })), checks: verified, ...(result.advisories?.length ? { advisories: result.advisories, advisoryCount: result.advisories.length } : {}), ...(warnings.length ? { warnings } : {}),
358
360
  ...(screenshots ? { screenshots } : {}),
359
361
  preview: "Source validation passed. Inspect the managed preview build and rendered scenario after applying; validation is not visual verification." },candidateRevision);
@@ -6,6 +6,7 @@ import { fileURLToPath } from "node:url";
6
6
  import { buildFailure, inspectBuildStatus } from "./build-status.mjs";
7
7
  import { previewSessionDirectories, withPreviewSession } from "../preview-scope.mjs";
8
8
  import { developmentExecutable } from "../development-runtime.mjs";
9
+ import { readPreviewManifest } from "../preview-resources.mjs";
9
10
 
10
11
  function stamp(file) {
11
12
  try { const stat = statSync(file); return `${stat.mtimeMs}:${stat.ctimeMs}:${stat.size}`; }
@@ -132,7 +133,7 @@ export function createPreviewWatch(root, config, { log = process.stderr, buildTi
132
133
  })().finally(() => { restarting = undefined; });
133
134
  }
134
135
 
135
- async function ensure(file, signal) {
136
+ async function ensure(file, signal, { waitFor = "verified" } = {}) {
136
137
  if (signal?.aborted) throw new Error("Preview request cancelled.");
137
138
  if (state === "failed" || restarting || stalled) await restart();
138
139
  if (disposed) throw new Error("Preview watcher is stopped.");
@@ -149,6 +150,15 @@ export function createPreviewWatch(root, config, { log = process.stderr, buildTi
149
150
  if (!restarted && build?.diagnostics.some(item => item.code === "ADS_PREVIEW_RESTART")) {
150
151
  restarted = true; await restart(); request(file); baseline = baselines.get(file) ?? null; continue;
151
152
  }
153
+ // Interactive browsing may use compiled feedback or an earlier accepted
154
+ // view. It returns the actual non-current build status, never evidence.
155
+ if (waitFor === "compiled" && config.previewManifest) {
156
+ if (build?.live) return build;
157
+ try {
158
+ const manifest = readPreviewManifest(withPreviewSession({ root, config: { mcp: config } }, resourceSession()));
159
+ if (manifest && (!command || manifest.session === session) && manifest.scenarios.some(entry => entry.id === app?.id)) return build;
160
+ } catch { /* No retained graph: wait for compilation or its error. */ }
161
+ }
152
162
  if (build?.state === "error") throw buildFailure(build);
153
163
  if (command && state !== "running") throw new Error(error ?? "Preview watcher is stopped.");
154
164
  if (build?.current) return build;
@@ -183,7 +193,16 @@ export function createPreviewWatch(root, config, { log = process.stderr, buildTi
183
193
  })();
184
194
  return stopping;
185
195
  }
186
- return { start, ensure, invalidate() { invalidation = randomUUID(); if (active) request(active,true); }, async stop() { disposed = true; await restarting; return stopChild(); }, kill: () => kill("SIGKILL"), status, resourceSession, buildStatus, setApps(apps) {
196
+ return { start, ensure, invalidate() { invalidation = randomUUID(); if (active) request(active,true); }, async warm(files) {
197
+ if (disposed || !command || !files.length) return;
198
+ const selected=active;
199
+ if (state === "failed" || restarting || stalled) await restart();
200
+ if (disposed) return;
201
+ start();
202
+ for (const file of files) requests.add(file);
203
+ // Preparing a graph must not replace the user's active selection.
204
+ request(active ?? selected ?? files[0],true);
205
+ }, async stop() { disposed = true; await restarting; return stopChild(); }, kill: () => kill("SIGKILL"), status, resourceSession, buildStatus, setApps(apps) {
187
206
  for (const app of apps) {
188
207
  const file = path.resolve(root, app.file);
189
208
  if (!baselines.has(file)) baselines.set(file, stamp(file));
@@ -200,11 +219,12 @@ export function createReconfigurablePreviewWatch(root, config, options) {
200
219
  let pending = Promise.resolve(), replacing = false, stopped = false;
201
220
  return {
202
221
  start() { if (!stopped && !replacing) current.start(); },
203
- async ensure(file, signal) { await pending; if (stopped) throw new Error("Preview watcher is stopped."); return current.ensure(file, signal); },
222
+ async ensure(file, signal, options) { await pending; if (stopped) throw new Error("Preview watcher is stopped."); return current.ensure(file, signal, options); },
204
223
  status() { return replacing ? { state: "reconfiguring" } : current.status(); },
205
224
  resourceSession() { return current.resourceSession(); },
206
225
  buildStatus() { return current.buildStatus(); },
207
226
  async invalidate() { await pending; if (!stopped) current.invalidate(); },
227
+ async warm(files) { await pending; if (!stopped) return current.warm(files); },
208
228
  setApps(next) { apps = next; current.setApps(next); },
209
229
  kill() { current.kill(); },
210
230
  reconfigure(next, force = false) {