@reqvire-org/ads 0.3.28 → 0.3.29

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 (53) 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 +5 -3
  7. package/dist/mcp/build-status.mjs +17 -4
  8. package/dist/mcp/context.mjs +2 -1
  9. package/dist/mcp/execution-results.mjs +4 -3
  10. package/dist/mcp/mutations.mjs +5 -43
  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 +74 -36
  15. package/dist/oxlint.mjs +6 -1
  16. package/dist/preview-builder.mjs +10 -4
  17. package/dist/preview-resources.mjs +11 -4
  18. package/dist/preview-scope.mjs +6 -0
  19. package/dist/preview-workers.mjs +184 -0
  20. package/dist/scenario-inspector.mjs +34 -0
  21. package/dist/scenario-trace.mjs +3 -2
  22. package/dist/scenarios-compiler.mjs +200 -25
  23. package/dist/showcase/client.bundle.js +22 -21
  24. package/dist/showcase/index.html +2 -2
  25. package/dist/showcase/style.css +2 -1
  26. package/dist/skills/ads-break-ui/SKILL.md +3 -0
  27. package/dist/skills/ads-break-ui/references/runtimes.md +31 -0
  28. package/dist/skills/ads-break-ui/references/validation.md +53 -0
  29. package/dist/skills/ads-designer/SKILL.md +3 -0
  30. package/dist/skills/ads-designer/references/runtimes.md +31 -0
  31. package/dist/skills/ads-designer/references/validation.md +53 -0
  32. package/dist/skills/ads-import/SKILL.md +3 -0
  33. package/dist/skills/ads-import/references/runtimes.md +31 -0
  34. package/dist/skills/ads-import/references/validation.md +53 -0
  35. package/dist/skills/ads-motion/SKILL.md +3 -0
  36. package/dist/skills/ads-motion/references/runtimes.md +31 -0
  37. package/dist/skills/ads-motion/references/validation.md +53 -0
  38. package/dist/skills/ads-port/SKILL.md +3 -0
  39. package/dist/skills/ads-port/references/runtimes.md +31 -0
  40. package/dist/skills/ads-port/references/validation.md +53 -0
  41. package/dist/source-symbols.mjs +11 -0
  42. package/dist/source-values.mjs +10 -3
  43. package/dist/test-boundaries.mjs +95 -0
  44. package/dist/ui-framework.mjs +2 -1
  45. package/dist/units.mjs +12 -1
  46. package/dist/validation-checks.mjs +50 -0
  47. package/dist/validation.mjs +172 -0
  48. package/dist/verification/browser.mjs +3 -1
  49. package/dist/verification.mjs +1 -0
  50. package/docs/ARCHITECTURE.md +72 -17
  51. package/docs/CHANGELOG.md +37 -0
  52. package/docs/MCP.md +68 -9
  53. package/package.json +1 -1
@@ -0,0 +1,95 @@
1
+ import { existsSync, readFileSync, readdirSync } from "node:fs";
2
+ import path from "node:path";
3
+ import ts from "typescript";
4
+ import { adsFileRole, isInside, isDevelopmentFile, isTestFile } from "./config.mjs";
5
+ import { importResolver } from "./boundaries.mjs";
6
+ import { previewFileIgnored } from "./preview-files.mjs";
7
+
8
+ /** Test ownership is structural; arbitrary assertion intent remains the runner's concern. */
9
+ export function inspectTestBoundaries(options, inventory, contracts, program) {
10
+ const diagnostics = [], resolve = importResolver(options), parsed = new Map(), tests = [];
11
+ const owner = file => inventory.owner(inventory.relative(path.relative(options.root,file)));
12
+ function source(file) {
13
+ if (!parsed.has(file)) parsed.set(file,program?.getSourceFile(file) ?? ts.createSourceFile(file,readFileSync(file,"utf8"),ts.ScriptTarget.Latest,true));
14
+ return parsed.get(file);
15
+ }
16
+ function walk(directory) {
17
+ for (const entry of readdirSync(directory,{withFileTypes:true})) {
18
+ const file = path.join(directory,entry.name);
19
+ if (entry.isSymbolicLink() || previewFileIgnored(options,file) || ["output","test-results","playwright-report",".playwright-cli"].includes(entry.name)) continue;
20
+ if (entry.isDirectory()) walk(file);
21
+ else if (entry.isFile() && /\.[cm]?[jt]sx?$/.test(file) && isTestFile(file)) {
22
+ let executable=/\.(?:test|spec)\.[cm]?[jt]sx?$/.test(file);
23
+ const names=new Set(["test","it","describe"]);
24
+ const ast=source(file);
25
+ for(const statement of ast.statements) if(ts.isImportDeclaration(statement)&&ts.isStringLiteralLike(statement.moduleSpecifier)&&/^(?:vitest|@playwright\/test|node:test|bun:test|@jest\/globals)$/.test(statement.moduleSpecifier.text)) {
26
+ const bindings=statement.importClause?.namedBindings;
27
+ if(statement.importClause?.name)names.add(statement.importClause.name.text);
28
+ if(bindings&&ts.isNamespaceImport(bindings))names.add(bindings.name.text);
29
+ if(bindings&&ts.isNamedImports(bindings))for(const item of bindings.elements)if(["test","it","describe"].includes((item.propertyName??item.name).text))names.add(item.name.text);
30
+ }
31
+ function visit(node){if(ts.isCallExpression(node)){let base=node.expression;while(ts.isPropertyAccessExpression(base)||ts.isCallExpression(base))base=base.expression;if(ts.isIdentifier(base)&&names.has(base.text))executable=true;}if(!executable)ts.forEachChild(node,visit);}
32
+ if(!executable)visit(ast);
33
+ if(executable)tests.push(file);
34
+ }
35
+ }
36
+ }
37
+ walk(options.root);
38
+ const registered = new Set(contracts.flatMap(contract=>Object.values(contract.checks).map(check=>path.resolve(options.root,path.dirname(contract.file),check.file))));
39
+ function imports(file) {
40
+ const edges = [];
41
+ function visit(node) {
42
+ let specifier;
43
+ if ((ts.isImportDeclaration(node)||ts.isExportDeclaration(node)) && node.moduleSpecifier && ts.isStringLiteralLike(node.moduleSpecifier)) specifier=node.moduleSpecifier.text;
44
+ if (ts.isCallExpression(node) && (node.expression.kind === ts.SyntaxKind.ImportKeyword || ts.isIdentifier(node.expression)&&node.expression.text === "require") && node.arguments[0] && ts.isStringLiteralLike(node.arguments[0])) specifier=node.arguments[0].text;
45
+ const typeOnly=ts.isImportDeclaration(node)&&(node.importClause?.isTypeOnly||node.importClause?.namedBindings&&ts.isNamedImports(node.importClause.namedBindings)&&!node.importClause.name&&node.importClause.namedBindings.elements.length&&node.importClause.namedBindings.elements.every(item=>item.isTypeOnly))||ts.isExportDeclaration(node)&&node.isTypeOnly;
46
+ if (specifier&&!typeOnly) for (const target of resolve(specifier,file)) if (existsSync(target) && isInside(options.root,target) && !target.split(path.sep).includes("node_modules") && /\.[cm]?[jt]sx?$/.test(target)) edges.push({specifier,target,node});
47
+ ts.forEachChild(node,visit);
48
+ }
49
+ visit(source(file));return edges;
50
+ }
51
+ function report(file,rule,message) { diagnostics.push({file:path.relative(options.root,file).replaceAll("\\","/"),rule,line:1,column:1,message}); }
52
+ for (const file of tests) {
53
+ const own = owner(file), inside = isInside(options.dsRoot,file);
54
+ const edges = imports(file);
55
+ const marked = adsFileRole(file) === "behavior.spec" || /@ads:[\w.-]+/.test(source(file).text);
56
+ if (marked && !registered.has(file)) report(file,"test-registration","ADS behavior specs must be registered by their owning contract. Register this file or remove the obsolete spec.");
57
+ if (inside) {
58
+ const unit = inventory.units.find(unit=>unit.id===own);
59
+ const real = ["configuration","foundation","tokens"].includes(own) || unit?.files.some(relative=>{const target=path.resolve(options.root,relative);return !isDevelopmentFile(target,options) || own?.startsWith("composition/") && /\.scenario\.[cm]?[jt]sx?$/.test(target);});
60
+ if (!real) report(file,"test-ownership","ADS tests belong beside a real runtime or composition owner. A test/helper file alone cannot create an owner.");
61
+ }
62
+ if (!inside) {
63
+ // Application tests may integrate public UI alongside application runtime.
64
+ // Helpers under test/ do not masquerade as the application subject.
65
+ let hasAppSubject = edges.some(edge=>isInside(options.sourceRoot,edge.target)&&!isInside(options.dsRoot,edge.target)&&!isDevelopmentFile(edge.target,options));
66
+ const seen = new Set(); let usesAds = marked;
67
+ function trace(target) {
68
+ if (seen.has(target)) return;seen.add(target);
69
+ for (const edge of imports(target)) {
70
+ if (isInside(options.dsRoot,edge.target)) usesAds=true;
71
+ else if (isDevelopmentFile(edge.target,options)) trace(edge.target);
72
+ else if (isInside(options.sourceRoot,edge.target)) hasAppSubject=true;
73
+ }
74
+ }
75
+ trace(file);
76
+ if (usesAds && !hasAppSubject) report(file,"test-ownership","This test exercises ADS without an application runtime subject. Move it beside its owning component/pattern or composition; application integration tests stay beside their application subject.");
77
+ }
78
+ // Development helpers cannot hide a private import across owners. Public
79
+ // barrel imports are permitted and stop at the declared API boundary.
80
+ if (inside) {
81
+ const seen = new Set();
82
+ function trace(target) {
83
+ if (seen.has(target)) return;seen.add(target);
84
+ for (const edge of imports(target)) {
85
+ if (edge.specifier === options.config.publicAlias || edge.specifier === `${options.config.publicAlias}/review`) continue;
86
+ if (!isInside(options.dsRoot,edge.target)) continue;
87
+ if (isDevelopmentFile(edge.target,options)) { trace(edge.target);continue; }
88
+ if (owner(edge.target) !== own && edge.target !== path.join(options.dsRoot,options.config.stylesEntry)) report(file,"test-private-import",`Test ${own} reaches private source owned by ${owner(edge.target)} through ${path.relative(options.root,target)}. Use the public ADS API for peers; private helpers stay with their owner.`);
89
+ }
90
+ }
91
+ trace(file);
92
+ }
93
+ }
94
+ return diagnostics;
95
+ }
@@ -1,6 +1,7 @@
1
1
  import { existsSync } from "node:fs";
2
2
  import path from "node:path";
3
3
  import ts from "typescript";
4
+ import { sourceSymbol } from "./source-symbols.mjs";
4
5
 
5
6
  const modules = new Set(["react", "preact", "preact/compat", "preact/jsx-runtime"]);
6
7
 
@@ -37,7 +38,7 @@ export function importedUiApi(expression, checker) {
37
38
  base = base.left ?? base.expression;
38
39
  }
39
40
  if (!ts.isIdentifier(base)) return null;
40
- for (const declaration of checker.getSymbolAtLocation(base)?.declarations ?? []) {
41
+ for (const declaration of sourceSymbol(checker, base)?.declarations ?? []) {
41
42
  if (ts.isImportSpecifier(declaration) && modules.has(declaration.parent.parent.parent.moduleSpecifier.text)) {
42
43
  return { name: [(declaration.propertyName ?? declaration.name).text, ...parts].join("."), module: declaration.parent.parent.parent.moduleSpecifier.text };
43
44
  }
package/dist/units.mjs CHANGED
@@ -66,7 +66,7 @@ export function configurationFiles(options) {
66
66
  for (const match of command.matchAll(/\b(?:npm|bun)\s+run\s+([\w:.-]+)/g)) script(match[1]);
67
67
  for (const match of command.matchAll(/\b(?:node|bun|tsx|ts-node)\s+([^\s;&|]+\.[cm]?[jt]sx?)(?=\s|$)/g)) visit(path.resolve(root, match[1]), true);
68
68
  }
69
- for (const name of ["lint:ds", "lint:style", "lint:project", "typecheck", "build:mcp-previews", "generate:icons", ...(config.mcp.mutationChecks ?? [])]) script(name);
69
+ for (const name of ["lint:ds", "lint:style", "lint:project", "typecheck", "build:mcp-previews", "generate:icons", "build:lib", "build:app", ...(config.validation?.checks ?? []), ...(config.mcp.mutationChecks ?? [])]) script(name);
70
70
  const watch = config.mcp.previewWatch;
71
71
  if (watch) {
72
72
  if (["npm", "bun"].includes(watch.command) && watch.args[0] === "run") script(watch.args[1]);
@@ -76,6 +76,17 @@ export function configurationFiles(options) {
76
76
  if (["npm", "bun"].includes(profile.command) && profile.args[0] === "run") script(profile.args[1]);
77
77
  else for (const argument of [profile.command, ...profile.args]) if (/\.[cm]?[jt]sx?$/.test(argument)) visit(path.resolve(root, argument), true);
78
78
  }
79
+ // Build/configuration tests follow their actual setup source, without
80
+ // capturing component tests invoked by a registered runner.
81
+ const setupSources = [...files];
82
+ for (const file of setupSources) {
83
+ if (!source.test(file)) continue;
84
+ const stem=file.replace(/\.[cm]?[jt]sx?$/,"");
85
+ for (const role of ["test","spec"]) for (const extension of ["ts","tsx","js","mjs","mts"]) {
86
+ const sidecar=`${stem}.ads.${role}.${extension}`;
87
+ if (existsSync(path.join(root,sidecar))) files.add(sidecar);
88
+ }
89
+ }
79
90
  return files;
80
91
  }
81
92
 
@@ -0,0 +1,50 @@
1
+ import { spawn } from "node:child_process";
2
+ import { readFileSync } from "node:fs";
3
+ import path from "node:path";
4
+ import { projectContext } from "./mcp/context.mjs";
5
+ import { packageScriptCommand } from "./development-runtime.mjs";
6
+ import { failure as evidenceFailure } from "./evidence.mjs";
7
+ const fail = (rule, message, file, failure) => Object.assign(new Error(message), { diagnostic: {rule, message, ...(file ? {file} : {}), ...(failure ? {failure} : {})} });
8
+
9
+ export function checkCommand(command, args, cwd, signal, input, gate = {category:"architecture",phase:"patch-preparation"}, timeoutMs = 60000) {
10
+ return new Promise((resolve, reject) => {
11
+ if (signal?.aborted) { reject(fail("mutation-cancelled", "Mutation cancelled before validation.",undefined,evidenceFailure("runner","mutation-execution","ADS_CANCELLED"))); return; }
12
+ const child = spawn(command, args, { cwd, shell: false, detached: process.platform !== "win32", windowsHide: true, stdio: [input === undefined ? "ignore" : "pipe", "pipe", "pipe"],
13
+ env: { ...process.env, PATH: [path.join(cwd, "node_modules/.bin"), path.dirname(process.execPath), process.env.PATH ?? ""].join(path.delimiter) } });
14
+ let output = "", failure;
15
+ const startedAt=Date.now();
16
+ if (input !== undefined) { child.stdin.on("error", () => {}); child.stdin.end(input); }
17
+ function kill() {
18
+ if (!child.pid) return;
19
+ if (process.platform === "win32") {
20
+ const stop = spawn("taskkill", ["/pid", String(child.pid), "/T", "/F"], { stdio: "ignore", windowsHide: true });
21
+ stop.on("error", () => child.kill("SIGKILL"));
22
+ } else { try { process.kill(-child.pid, "SIGKILL"); } catch (error) { if (error.code !== "ESRCH") failure ??= error; } }
23
+ }
24
+ const abort = () => { failure = fail("mutation-cancelled", "Mutation cancelled during validation."); kill(); };
25
+ signal?.addEventListener("abort", abort, { once: true });
26
+ 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);
27
+ for (const stream of [child.stdout, child.stderr]) stream.on("data", chunk => { output = (output + chunk.toString()).slice(-12000); });
28
+ child.once("error", error => { failure = error; });
29
+ child.once("exit", kill); // Also clean up descendants of a finished launcher.
30
+ child.once("close", code => {
31
+ clearTimeout(timer); signal?.removeEventListener("abort", abort);
32
+ const detail={command:path.basename(command),args,timeoutMs,elapsedMs:Date.now()-startedAt,exitCode:code};
33
+ if (failure || code !== 0) {
34
+ const error=failure??fail("mutation-check", `${path.basename(command)} ${args.join(" ")} failed (${code}).\n${output}`);
35
+ 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"})};
36
+ reject(error);
37
+ } else resolve({ ...detail,phase:gate.phase, passed: true });
38
+ });
39
+ });
40
+ }
41
+
42
+
43
+ export function projectChecks(options) {
44
+ const context = projectContext(options);
45
+ const pkg = JSON.parse(readFileSync(path.join(options.root, "package.json"), "utf8"));
46
+ const scripts = options.config.mcp.mutationChecks ?? [pkg.scripts?.["lint:project"] ? "lint:project" : "lint", "typecheck", "build:mcp-previews"].filter(name => typeof pkg.scripts?.[name] === "string");
47
+ if (scripts.some(name => typeof pkg.scripts?.[name] !== "string")) throw fail("mutation-check", "Every configured mcp.mutationChecks script must exist in package.json.");
48
+ if (scripts.length && !["npm", "bun"].includes(context.packageManager)) throw fail("mutation-check", "Declare packageManager as npm or bun to run mutation checks.");
49
+ return scripts.map(script => packageScriptCommand(context.packageManager, script));
50
+ }
@@ -0,0 +1,172 @@
1
+ import { createHash, randomUUID } from "node:crypto";
2
+ import { existsSync, lstatSync, mkdirSync, readFileSync, readdirSync, realpathSync, renameSync, rmSync, writeFileSync } from "node:fs";
3
+ import { createRequire } from "node:module";
4
+ import path from "node:path";
5
+ import { fileURLToPath } from "node:url";
6
+ import { checkProject } from "./check.mjs";
7
+ import { loadConfig, isInside } from "./config.mjs";
8
+ import { createLintConfig } from "./lint-config.mjs";
9
+ import { inspectUnits } from "./units.mjs";
10
+ import { inspectBehaviors } from "./behaviors.mjs";
11
+ import { affectedBehaviorUnits, createVerificationController } from "./verification.mjs";
12
+ import { previewFileIgnored } from "./preview-files.mjs";
13
+ import { checkCommand, projectChecks } from "./validation-checks.mjs";
14
+ import { projectContext } from "./mcp/context.mjs";
15
+ import { packageScriptCommand } from "./development-runtime.mjs";
16
+ import { acceptance } from "./evidence.mjs";
17
+ import { inspectScenarios } from "./scenarios.mjs";
18
+ import { inspectBuildStatus } from "./mcp/build-status.mjs";
19
+
20
+ const hash = value => createHash("sha256").update(value).digest("hex");
21
+ function toolInputs() {
22
+ const root=path.dirname(fileURLToPath(import.meta.url)),rows=[];
23
+ function visit(directory){for(const entry of readdirSync(directory,{withFileTypes:true}).sort((a,b)=>a.name.localeCompare(b.name))){const file=path.join(directory,entry.name);if(entry.isDirectory()&&!["skills","bootstrap-ds","showcase"].includes(entry.name))visit(file);else if(entry.isFile()&&/\.(?:mjs|js|cjs|json)$/.test(file))rows.push([path.relative(root,file),hash(readFileSync(file))]);}}
24
+ visit(root);return rows;
25
+ }
26
+ const toolRevision = hash(JSON.stringify([toolInputs(),process.versions.bun??process.version,process.platform,process.arch]));
27
+ const ignored = new Set(["test-results", "playwright-report", ".playwright-cli", "output"]);
28
+
29
+ /** One content inventory includes new/deleted tests and source outside ADS roots. */
30
+ export function validationInputs(options) {
31
+ const files = {};
32
+ function walk(directory) {
33
+ for (const entry of readdirSync(directory, { withFileTypes: true }).sort((a,b) => a.name.localeCompare(b.name))) {
34
+ const file = path.join(directory, entry.name);
35
+ if (ignored.has(entry.name) || previewFileIgnored(options, file) || entry.name.endsWith(".tsbuildinfo")) continue;
36
+ if (entry.isSymbolicLink()) throw new Error(`Validation source cannot be a symlink: ${path.relative(options.root,file)}`);
37
+ if (entry.isDirectory()) walk(file);
38
+ else if (entry.isFile()) files[path.relative(options.root,file).replaceAll("\\", "/")] = hash(readFileSync(file));
39
+ }
40
+ }
41
+ walk(options.root);
42
+ const installed = path.join(options.root,"node_modules/.package-lock.json");
43
+ files["node_modules/.package-lock.json"] = existsSync(installed) ? hash(readFileSync(installed)) : null;
44
+ return { files, revision: hash(JSON.stringify([toolRevision,files])) };
45
+ }
46
+
47
+ function outputFile(root, name) {
48
+ const folder = path.join(root,".ds");
49
+ if (existsSync(folder) && realpathSync(folder) !== folder) throw new Error("Validation output cannot resolve through a symlink.");
50
+ mkdirSync(folder,{recursive:true});
51
+ return path.join(folder,name);
52
+ }
53
+
54
+ export function createValidationController(directory) {
55
+ const root = path.resolve(directory);
56
+ let active, progress;
57
+ return {
58
+ status() { return { busy: !!active, ...(progress ? {progress} : {}) }; },
59
+ async close() { const pending = active; pending?.abort(); await pending?.completion; },
60
+ async run({scope = "all"} = {}, signal, onProgress) {
61
+ if (!["all","changed"].includes(scope)) throw new Error("Validation scope must be all or changed.");
62
+ if (active) throw new Error("Validation is already running.");
63
+ active = new AbortController();
64
+ const controller = active;
65
+ signal = signal ? AbortSignal.any([signal,controller.signal]) : controller.signal;
66
+ let finish; controller.completion = new Promise(resolve => { finish = resolve; });
67
+ const startedAt = Date.now(), checks = [], diagnostics = [], advisories = [], results = [];
68
+ const requestedScope = scope;
69
+ let inputs, changed = [], units = [], fallback;
70
+ function stage(name) { signal.throwIfAborted(); progress = {stage:name,elapsedMs:Date.now()-startedAt,completed:checks.length}; onProgress?.(progress); }
71
+ async function command(name, launch, options) {
72
+ stage(name);
73
+ try { const result = await checkCommand(launch.command, launch.args, root, signal, undefined, {category:"build",phase:name}, options.config.mcp.mutationCheckTimeoutMs); checks.push({name,...result}); }
74
+ catch (error) { checks.push({name,passed:false}); throw error; }
75
+ }
76
+ try {
77
+ const options = loadConfig(root);
78
+ inputs = validationInputs(options);
79
+ const baselineFile = outputFile(root,"validation-baseline.json");
80
+ if (scope === "changed") {
81
+ let baseline;
82
+ try { if (realpathSync(baselineFile) === baselineFile && lstatSync(baselineFile).size < 8*1024*1024) baseline = JSON.parse(readFileSync(baselineFile,"utf8")); } catch { /* No trusted baseline: perform the complete audit. */ }
83
+ if (baseline?.schemaVersion !== 1 || baseline.root !== root || baseline.toolRevision !== toolRevision || !baseline.files || hash(JSON.stringify([toolRevision,baseline.files])) !== baseline.revision) fallback = "No compatible successful full-validation baseline.";
84
+ else {
85
+ changed = [...new Set([...Object.keys(inputs.files),...Object.keys(baseline.files)])].filter(file => inputs.files[file] !== baseline.files[file]);
86
+ const inventory = inspectUnits(options);
87
+ if (changed.some(file => {
88
+ const owner=inventory.owner(inventory.relative(file));
89
+ return !isInside(options.dsRoot,path.join(root,file)) && !isInside(options.sourceRoot,path.join(root,file)) || [null,"configuration","foundation","tokens"].includes(owner) || !inventory.units.some(unit=>unit.id===owner);
90
+ })) fallback = "Configuration, foundation, deleted ownership or unclassified inputs changed.";
91
+ }
92
+ if (fallback) scope = "all";
93
+ }
94
+ stage("architecture");
95
+ const core = checkProject(root);
96
+ diagnostics.push(...core.diagnostics); advisories.push(...(core.advisories ?? []));
97
+ checks.push({name:"architecture",passed:core.ok});
98
+ if (!core.ok) return complete();
99
+ const pkg = JSON.parse(readFileSync(path.join(root,"package.json"),"utf8"));
100
+ const scripts = projectChecks(options);
101
+ if (scope === "all") {
102
+ const configured = options.config.validation.checks;
103
+ if (configured) scripts.splice(0,scripts.length,...configured.map(script => {
104
+ if (typeof pkg.scripts?.[script] !== "string") throw new Error(`Configured validation script does not exist: ${script}`);
105
+ return packageScriptCommand(projectContext(options).packageManager,script);
106
+ }));
107
+ else for (const script of ["test", pkg.scripts?.["build:lib"] ? "build:lib" : pkg.scripts?.["build:app"] ? "build:app" : "build"]) if (typeof pkg.scripts?.[script] === "string" && !scripts.some(item => item.args.at(-1) === script)) scripts.splice(Math.max(0,scripts.length-1),0,packageScriptCommand(projectContext(options).packageManager,script));
108
+ }
109
+ function recursive(script, seen = new Set()) {
110
+ if (seen.has(script)) return false;seen.add(script);
111
+ const text=pkg.scripts?.[script] ?? "";
112
+ return /\bads\s+validate\b|\bcli\.mjs["']?\s+validate\b/.test(text) || [...text.matchAll(/\b(?:npm|bun)\s+(?:--bun\s+)?run\s+([\w:.-]+)/g)].some(match=>recursive(match[1],seen));
113
+ }
114
+ if (scripts.some(launch=>recursive(launch.args.at(-1)))) throw new Error("A selected project script calls ads validate recursively. Use leaf check/build scripts in validation.checks.");
115
+ stage("registered-oxlint");
116
+ const require = createRequire(path.join(root,"package.json"));
117
+ const oxlintPackage = require.resolve("oxlint/package.json");
118
+ const bin = JSON.parse(readFileSync(oxlintPackage,"utf8")).bin;
119
+ const lintConfig = outputFile(root,`validation-lint-${randomUUID()}.json`);
120
+ try {
121
+ writeFileSync(lintConfig,JSON.stringify(createLintConfig(options)));
122
+ const paths = [...new Set([options.config.dsDir,options.config.sourceDir,...inspectUnits(options).units.find(unit=>unit.id==="configuration").files.filter(file=>/\.[cm]?[jt]sx?$/.test(file))])].filter(file=>existsSync(path.join(root,file)));
123
+ await command("registered-oxlint",{command:process.execPath,args:[path.resolve(path.dirname(oxlintPackage),typeof bin === "string" ? bin : bin.oxlint),"--deny-warnings","--config",lintConfig,...paths]},options);
124
+ } finally { rmSync(lintConfig,{force:true}); }
125
+ for (const launch of scripts) await command(`project:${launch.args.at(-1)}`,launch,options);
126
+ if (options.config.mcp.previewManifest || options.config.mcp.apps.length) {
127
+ stage("verified-previews");
128
+ const apps=[...options.config.mcp.apps,...inspectScenarios(options).scenarios.map(entry=>({id:entry.id,file:entry.artifact}))];
129
+ const build=inspectBuildStatus(root,{...options.config.mcp,apps});
130
+ const pending=build.previews.filter(entry=>!entry.current);
131
+ checks.push({name:"verified-previews",passed:!pending.length,previewCount:apps.length});
132
+ if (pending.length) {
133
+ diagnostics.push(...pending.map(entry=>({rule:"validation-previews",message:`${entry.id}: ${entry.state}. A current verified preview is required; successful command exit alone is insufficient.`,details:entry.diagnostics})));
134
+ return complete();
135
+ }
136
+ } else checks.push({name:"verified-previews",passed:true,skipped:true,reason:"No managed preview output configured."});
137
+ const behaviors = inspectBehaviors(options);
138
+ units = scope === "all" ? behaviors.contracts.map(contract=>contract.unit) : affectedBehaviorUnits(options,changed);
139
+ if (units.length) {
140
+ stage("behavior");
141
+ const verification = createVerificationController(root);
142
+ let result;
143
+ try { result = await verification.run({units},signal,value=>{ progress={stage:"behavior",...value}; onProgress?.(progress); }); }
144
+ finally { await verification.close(); }
145
+ results.push(...result.results); diagnostics.push(...result.diagnostics);
146
+ checks.push({name:"registered-behavior",passed:result.ok});
147
+ if (!result.ok && !result.diagnostics.length) diagnostics.push({rule:"validation-behavior",message:"Registered behavior checks did not all pass. Inspect the recorded outcomes."});
148
+ } else checks.push({name:"registered-behavior",passed:true,skipped:true,reason:scope === "all" ? "No registered behavior contracts." : "No affected behavior contracts."});
149
+ } catch (error) { diagnostics.push(error.diagnostic ?? {rule:signal.aborted ? "validation-cancelled" : "validation-execution",message:error.message}); }
150
+ finally { /* Completion also runs for early architecture failures. */ }
151
+ return complete();
152
+
153
+ function complete() {
154
+ try {
155
+ let current = false;
156
+ try { current = !!inputs && validationInputs(loadConfig(root)).revision === inputs.revision; } catch (error) { diagnostics.push({rule:"validation-inputs",message:error.message}); }
157
+ if (inputs && !current) diagnostics.push({rule:"validation-stale",message:"Project inputs changed during validation. Rerun against current source."});
158
+ if (signal.aborted && !diagnostics.some(item=>item.rule==="validation-cancelled")) diagnostics.push({rule:"validation-cancelled",message:"Validation was cancelled."});
159
+ let ok = current && !signal.aborted && !diagnostics.length && checks.every(check=>check.passed);
160
+ if (ok && scope === "all") {
161
+ const file = outputFile(root,"validation-baseline.json"), temporary = `${file}.${randomUUID()}.tmp`;
162
+ try { writeFileSync(temporary,JSON.stringify({schemaVersion:1,root,toolRevision,...inputs})); renameSync(temporary,file); }
163
+ catch (error) { ok=false;diagnostics.push({rule:"validation-baseline",message:error.message}); }
164
+ finally { rmSync(temporary,{force:true}); }
165
+ }
166
+ return {ok,scope,requestedScope,...(fallback?{fallback}:{}),sourceRevision:inputs?.revision,current,elapsedMs:Date.now()-startedAt,selection:{files:changed,units},checks,diagnostics,advisories,results,
167
+ acceptance:acceptance(scope === "all" ? "full-project-validation" : "affected-project-validation",ok,checks.filter(check=>check.passed&&!check.skipped).map(check=>check.name),["unconfigured-project-checks","unasserted-behavior","visual-parity","accessibility-audit"])};
168
+ } finally { active=undefined;progress=undefined;finish(); }
169
+ }
170
+ },
171
+ };
172
+ }
@@ -142,7 +142,9 @@ async function openPreviewScenario(page, url, scenario, { timeout = 3e4 } = {})
142
142
  page.on("response", response);
143
143
  page.on("pageerror", pageError);
144
144
  try {
145
- await page.goto(url, { waitUntil: "load", timeout });
145
+ const verified = new URL(url);
146
+ verified.searchParams.set("waitFor", "verified");
147
+ await page.goto(verified.href, { waitUntil: "load", timeout });
146
148
  const end = Date.now() + timeout;
147
149
  while (Date.now() < end) {
148
150
  for (const frame of page.frames().filter((frame2) => frame2 !== page.mainFrame())) {
@@ -261,6 +261,7 @@ export function createVerificationController(root, { reportRoot = root, onProgre
261
261
  for (const check of group.filter(check => check.scenario)) {
262
262
  const url = new URL(host.url);
263
263
  url.searchParams.set("scenario", check.scenario);
264
+ url.searchParams.set("waitFor", "verified");
264
265
  scenarios[check.scenario] = url.href;
265
266
  }
266
267
  }
@@ -435,22 +435,46 @@ one-shot production/library builds keep their own compiler and optimization.
435
435
 
436
436
  ```mermaid
437
437
  flowchart LR
438
- Edit[Source edit] --> Registry[Refresh scenario registry]
439
- Registry --> Validate[Validate project]
440
- Registry --> Compile[Update persistent Vite graph]
438
+ Edit[Source edit] --> Compile[Update persistent Vite graph]
439
+ Compile --> Validate[Validate project and inspect registry in background]
440
+ Compile --> Live[Unverified live resources]
441
+ Live --> App[Compare selected dependency closure]
441
442
  Validate --> Publish[Check source revision and publish atomically]
442
443
  Compile --> Publish
443
- Publish --> App[Compare selected dependency closure]
444
+ Publish --> App
445
+ Validate -->|Failure| Revert[Restore last verified view]
444
446
  App --> Keep[Unchanged: keep mounted view]
445
447
  App --> Mount[Changed: remount selected view]
446
448
  ```
447
449
 
448
- Watch output is private scratch data under `.ds/incremental/`, not a successful
449
- published build. Both validation and compilation must succeed against unchanged
450
- source before the scheduler publishes immutable resources. Failed/superseded work
451
- retains the previous preview with stale diagnostics. Files outside Rollup's module
452
- graph still cause validation and build reconciliation. Normal compiler shutdown
453
- closes its Vite watcher and removes its scratch directory.
450
+ Watched compilation provides immediate visual feedback while validation and
451
+ scenario inspection run in the background. Inspection uses a persistent worker
452
+ to keep the compiler responsive. Rapid edits replace pending work, with one
453
+ verification run in flight. Production builds retain their own optimization.
454
+
455
+ Live resources are fenced to the current source digest and managed session.
456
+ They never update accepted artifacts, the successful graph cache or `current`.
457
+ Only validation and compilation passing against unchanged source can publish the
458
+ verified graph. Failure restores the last verified view; compilation errors are
459
+ reported without waiting for a slow validation command. Files outside Rollup's
460
+ module graph still cause validation and build reconciliation. Normal compiler
461
+ shutdown closes its Vite watcher and removes its scratch directory.
462
+
463
+ The shared builder also reuses unchanged worker bundles through the project's
464
+ Vite pipeline. Worker code, transitive dependencies and configuration determine
465
+ reuse; changed inputs rebuild the affected bundle. This is generic build caching,
466
+ independent of any design system and separate from source-validation evidence.
467
+
468
+ Accepted MCP edits prepare previews even when no viewer has opened them. A
469
+ matching checked candidate graph and scenario registry carry into the project's existing cache;
470
+ otherwise the normal watcher builds it in the background. Builds tied to a
471
+ temporary candidate location are rebuilt. Source, dependencies, compiler and
472
+ output content determine reuse, with no expiry based on elapsed time.
473
+
474
+ After the selected view paints, a connected showcase can prefetch changed peers'
475
+ static resources into the App's existing byte cache. This bounded, opportunistic
476
+ work neither evaluates modules nor mounts hidden examples. Navigation remains
477
+ independent of background preparation, and resource integrity checks still apply.
454
478
 
455
479
  A successful global revision does not require remounting an unchanged selected
456
480
  view. The App compares its static module/style/asset closure, retains DOM/form/
@@ -466,15 +490,27 @@ foundation change can select every owner. Configured project checks still run as
466
490
  authored; releases run the full test suite. ADS does not claim per-test-case
467
491
  selection or skip validation because a module transform was cached.
468
492
 
493
+ Architecture inspection shares analysis within one immutable TypeScript checker
494
+ and avoids redundant source discovery. A new inspection still observes current
495
+ source and configuration; successful diagnostics are not cached across edits.
496
+
469
497
  After source changes, validation and compilation must both succeed before a new
470
498
  graph becomes current. MCP announces build/resource updates.
471
499
  Build success records the project input digest captured before compilation;
472
500
  status reads independently verify that digest and the output bytes. Guarded
473
501
  publication invalidates the compiler explicitly. Content reconciliation recovers
474
502
  missed atomic file replacements, so OS watch delivery cannot establish freshness.
475
- The built-in client refreshes discovery and sends the current selection to the
476
- existing App. Its loader retains or remounts that view according to its dependency
477
- closure. Failed builds retain the previous view with visible stale diagnostics. Invalid scenario metadata at startup and later source
503
+ The built-in client uses `waitFor: compiled` for interactive selections, so it
504
+ can browse compiled feedback or a retained verified graph while checks run.
505
+ Default MCP preview calls, captures and verification still wait for verified
506
+ output. Pending selections never report App readiness as verified. Discovery
507
+ notifications are reconciled after validation rather than repeating synchronous
508
+ semantic inspection on the live update path. The App retains or remounts its view
509
+ according to its dependency closure. A quiet monochrome indicator in the
510
+ showcase's upper-right header exposes compilation, checking, reload and fallback
511
+ status through its accessible label, tooltip and details popover. No status or
512
+ loading overlay covers the widget area; external Apps hosts retain an in-App
513
+ fallback. Invalid scenario metadata at startup and later source
478
514
  failures stay in the watcher's recoverable diagnostic path. Fixing source triggers validation again.
479
515
  If the compiler process exits, the next preview request starts one fresh child;
480
516
  MCP inspection remains available. Each child generation has its own status report,
@@ -489,9 +525,10 @@ reachable from the scenario entry; browser tests still verify mounting, states,
489
525
  accessibility and visual parity.
490
526
 
491
527
  The working example and starter build one shared multi-entry graph on first
492
- preview demand, then reuse it across selections and unchanged restarts. Only the
493
- selected scenario's static dependency closure loads in the App; dynamic imports
494
- remain lazy. Production bundles, workers and cancellation stay project-owned.
528
+ preview demand or accepted-edit preparation, then reuse it across selections and
529
+ unchanged restarts. The App loads the selected scenario's static dependency
530
+ closure and may prefetch changed peers; dynamic imports remain lazy. Production
531
+ bundles, workers and cancellation stay project-owned.
495
532
  The MCP server serves compiled bytes without evaluating project TSX. Compiler
496
533
  adapters normalize each entry to mount/unmount, retaining native React or Preact
497
534
  semantics; choosing a framework does not install one into the tooling host.
@@ -540,6 +577,24 @@ Static checks establish the policies and source formats they cover. Behavior
540
577
  tests and browser review verify the resulting accessibility, layout, themes,
541
578
  states, and motion. Both forms of verification support agent-driven iteration.
542
579
 
580
+ The CLI `ads validate` and MCP `ads_validate` share one audit engine, combining
581
+ architecture and test-boundary guards, registered lint rules, project commands
582
+ and behavior contracts. Full audits establish a content baseline. Changed audits
583
+ select affected behavior owners from that baseline; broad or unclassified changes
584
+ expand to full. Opaque project commands retain their declared scope.
585
+
586
+ Only a successful full audit against unchanged source advances the baseline.
587
+ This works without Git history and does not cache individual test results. Skills
588
+ guide agents toward affected checks during editing and full audits after ownership
589
+ or runner migrations, before releases and for explicit complete validation.
590
+
591
+ Tests follow the same ownership boundaries as implementation: pure ADS tests stay
592
+ with their owners, marked behavior specs require registration, and private imports
593
+ cannot cross owners through helpers. Application integration tests stay with their
594
+ application subject. Static guards enforce these boundaries without claiming to
595
+ infer arbitrary assertion intent. Operational details live in the
596
+ [validation guide](../skills/ads-designer/references/validation.md).
597
+
543
598
  ## MCP makes the project ADS available to agents
544
599
 
545
600
  The stdio server exposes the same token inspection and core architecture checks
@@ -599,7 +654,7 @@ sections without rerunning checks. Pages have at most 20 rows and 8 KiB of JSON;
599
654
  truncated records support bounded text ranges. Discovery and investigation
600
655
  sections use the same paging budget. Cursors bind the query and result/revision;
601
656
  superseded IDs fail explicitly instead of silently returning another run.
602
- Only the latest verification and mutation snapshots are retained, each at most
657
+ Only the latest validation, verification and mutation snapshots are retained, each at most
603
658
  8 MiB under `.ds/tool-results/`. Oversized reports retain a summary with an
604
659
  explicit unavailable-details warning. Storage/notification failure cannot change
605
660
  an accepted edit's applied state. These are payload byte budgets, not tokenizer
package/docs/CHANGELOG.md CHANGED
@@ -1,5 +1,42 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.3.29
4
+
5
+ - Prepare managed previews after accepted MCP edits, including unopened viewers.
6
+ Reuse matching portable candidate graphs through the existing verified cache;
7
+ otherwise warm the normal compiler in the background. Prefetch changed peers'
8
+ static resources into the connected showcase's existing byte cache without
9
+ evaluating or mounting them. Content changes invalidate reuse; elapsed time does not.
10
+
11
+ - Add shared `ads validate` / `ads_validate` full and changed audits, source-fenced
12
+ full baselines, independent paged validation results and skill trigger guidance.
13
+ Reuse configured project commands and registered behaviors with explicit scope
14
+ expansion, skipped-stage reporting and cancellation.
15
+ - Enforce actual test-owner private imports, including development-helper chains;
16
+ reject unregistered marked behavior specs and pure ADS tests outside an owner.
17
+
18
+ - Reuse self-contained IIFE worker bundles generically in the shared watched
19
+ preview builder. Keep the project's Vite worker compiler/plugins, deduplicate
20
+ requests across constructor/query imports, fingerprint transitive inputs and
21
+ resolution directories, re-emit assets and include worker inputs in successful
22
+ graph caching. Preserve importer transforms and failure/source fences.
23
+
24
+ - Separate live visual feedback from verified preview publication. Compile edits
25
+ while full checks and worker-based registry inspection run in the background;
26
+ coalesce rapid edits, preserve unchanged mounted views and restore the last
27
+ verified graph on failure. Fence live resources to source/session and keep
28
+ captures, guarded edits and default MCP preview calls on verified output.
29
+ - Keep showcase navigation usable during checks with an explicit compiled-preview
30
+ mode. Replace blocking preview overlays with a quiet monochrome header
31
+ indicator and on-demand status details. Disable watched-preview minification
32
+ and batch shared graph cache/report writes.
33
+
34
+ - Reduce validation overhead without skipping checks: read TypeScript compiler
35
+ options without repeatedly enumerating source trees, share symbol identities
36
+ within immutable checkers, and look up style permissions only for candidate
37
+ writes. Keep fresh source/configuration inspection and full global validation;
38
+ no persistent diagnostic cache or per-owner validation shortcut is introduced.
39
+
3
40
  ## 0.3.28
4
41
 
5
42
  - Group component, pattern and composition showcase navigation using folder