@reqvire-org/ads 0.3.33 → 0.3.35

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 (67) hide show
  1. package/dist/behavior-libraries.mjs +93 -0
  2. package/dist/behaviors.mjs +0 -6
  3. package/dist/bootstrap-ds/ds.config.json +1 -0
  4. package/dist/capture.mjs +3 -3
  5. package/dist/check-runner.mjs +7 -0
  6. package/dist/check.mjs +2 -0
  7. package/dist/config.mjs +4 -0
  8. package/dist/lint-config.mjs +7 -0
  9. package/dist/mcp/build-status.mjs +1 -1
  10. package/dist/mcp/catalog.mjs +4 -2
  11. package/dist/mcp/draft-discovery.mjs +55 -0
  12. package/dist/mcp/drafts.mjs +135 -16
  13. package/dist/mcp/mutations.mjs +16 -8
  14. package/dist/mcp/preview-owner-guard.mjs +36 -1
  15. package/dist/mcp/preview-watch.mjs +100 -14
  16. package/dist/mcp/preview-widget.bundle.js +14 -14
  17. package/dist/mcp/preview-work.mjs +41 -0
  18. package/dist/mcp/server.mjs +131 -36
  19. package/dist/preview-builder.mjs +1 -0
  20. package/dist/scenario-inspector.mjs +16 -10
  21. package/dist/scenario-program.mjs +36 -0
  22. package/dist/scenario-registry.mjs +106 -0
  23. package/dist/scenarios-compiler.mjs +154 -43
  24. package/dist/scenarios.mjs +2 -1
  25. package/dist/showcase/client.bundle.js +39 -39
  26. package/dist/showcase/comparison.js +29 -5
  27. package/dist/showcase/draft-navigation.js +41 -0
  28. package/dist/showcase/index.html +1 -2
  29. package/dist/showcase/preview-state.js +19 -0
  30. package/dist/showcase/style.css +2 -2
  31. package/dist/skills/ads-break-ui/references/behaviors.md +10 -0
  32. package/dist/skills/ads-break-ui/references/drafts.md +43 -4
  33. package/dist/skills/ads-break-ui/references/runtimes.md +9 -0
  34. package/dist/skills/ads-break-ui/references/validation.md +6 -0
  35. package/dist/skills/ads-designer/SKILL.md +7 -0
  36. package/dist/skills/ads-designer/assets/bootstrap-ds/ds.config.json +1 -0
  37. package/dist/skills/ads-designer/references/behaviors.md +10 -0
  38. package/dist/skills/ads-designer/references/drafts.md +43 -4
  39. package/dist/skills/ads-designer/references/runtimes.md +9 -0
  40. package/dist/skills/ads-designer/references/validation.md +6 -0
  41. package/dist/skills/ads-import/SKILL.md +4 -0
  42. package/dist/skills/ads-import/references/behaviors.md +10 -0
  43. package/dist/skills/ads-import/references/drafts.md +43 -4
  44. package/dist/skills/ads-import/references/runtimes.md +9 -0
  45. package/dist/skills/ads-import/references/validation.md +6 -0
  46. package/dist/skills/ads-motion/references/behaviors.md +10 -0
  47. package/dist/skills/ads-motion/references/drafts.md +43 -4
  48. package/dist/skills/ads-motion/references/runtimes.md +9 -0
  49. package/dist/skills/ads-motion/references/validation.md +6 -0
  50. package/dist/skills/ads-port/SKILL.md +8 -1
  51. package/dist/skills/ads-port/references/behaviors.md +10 -0
  52. package/dist/skills/ads-port/references/drafts.md +43 -4
  53. package/dist/skills/ads-port/references/native-implementation.md +14 -1
  54. package/dist/skills/ads-port/references/runtimes.md +9 -0
  55. package/dist/skills/ads-port/references/validation.md +6 -0
  56. package/dist/unit-contracts.mjs +2 -2
  57. package/dist/units.mjs +6 -0
  58. package/dist/validation-checks.mjs +23 -3
  59. package/dist/validation.mjs +19 -10
  60. package/dist/verification/browser.d.mts +27 -0
  61. package/dist/verification.mjs +8 -4
  62. package/docs/ARCHITECTURE.md +110 -0
  63. package/docs/CHANGELOG.md +114 -0
  64. package/docs/GUIDE.md +34 -5
  65. package/docs/MCP.md +54 -9
  66. package/docs/benchmarks/gidi-preview-memory.md +141 -0
  67. package/package.json +6 -4
@@ -103,6 +103,15 @@ compiler. Existing custom adapters still work; they must adopt the helper to gai
103
103
  incremental transforms. Upgrade the project dependency and restart the builder.
104
104
  Keep the full validation callback and production build behavior.
105
105
 
106
+ Managed acceptance builds every scenario in production mode and shares the
107
+ candidate compiler/checked output with browser verification. Remove
108
+ `build:mcp-previews` from `mcp.mutationChecks` after upgrading ADS; keep that script
109
+ in normal builds. Explicit project commands still run as configured. During
110
+ acceptance ADS parks accepted/draft compilers but retains their publications;
111
+ an old view remains visible while verified preview requests wait. Do not launch
112
+ a second compiler to work around that wait. Semantic workers retire after five
113
+ idle seconds and rediscover from revision-fenced metadata when needed.
114
+
106
115
  The shared watched builder reuses completed self-contained IIFE worker bundles
107
116
  for constructor URLs and standard `?worker`/`?worker&url` imports. It uses Vite's
108
117
  configured worker plugins, deduplicates pending requests, tracks real worker and
@@ -67,3 +67,9 @@ separate latest validation result, alongside verification and mutation results.
67
67
  Source changes during execution reject success and leave the previous full
68
68
  baseline intact. Skipped registered behavior cases never pass; a project with no
69
69
  registered behavior contracts reports that stage as skipped with a reason.
70
+
71
+ Registered browser verification queues the selected scenario roots together
72
+ before browser workers open their pages. They share one candidate graph and
73
+ keep independent App state. This avoids compiling a growing graph per page.
74
+ A graph revision changing during startup keeps the preview pending until a
75
+ coherent current build mounts; it does not establish passing case evidence.
@@ -1,6 +1,6 @@
1
1
  ---
2
2
  name: ads-port
3
- description: "Port existing library components into a coherent project-owned ADS, reusing shared tokens and primitives while preserving required behavior. Use for native adaptation from a library URL, with reference comparison and provenance; not dependency installation or wrapping."
3
+ description: "Port existing library components into a coherent project-owned ADS, reusing shared tokens and primitives while preserving required behavior. Use for native adaptation from a library URL, with reference comparison and provenance; reuse explicitly declared behavior libraries as installed."
4
4
  ---
5
5
 
6
6
  ## Auto-mode tracked drafts
@@ -125,6 +125,13 @@ matching-property fixes, plus the build resolver for preserving opaque custom
125
125
  properties through extraction. Review warnings in the real `cx` composition and verify
126
126
  computed styles across affected sizes/states; retain intentional product behavior.
127
127
 
128
+ For positioning, menu/listbox keyboard handling, focus trapping and virtual lists,
129
+ prefer an installed library already listed in `ds.config.json` behaviorLibraries.
130
+ Use the installed API with minimal lifecycle/event integration and project-owned
131
+ styling; preserve the existing measured-geometry boundaries. If none fits, suggest
132
+ a framework-free package for approval or port natively. Add dependencies and
133
+ allowlist entries only with authorization; existing approval need not be repeated.
134
+
128
135
  Controllers are UI behavior owners: private helpers stay with their component or
129
136
  pattern; reusable controllers use discovered `controllers/<Name>` units. Use the
130
137
  project's configured framework and declared dependencies, or plain TypeScript,
@@ -21,6 +21,16 @@ UI references are allowed, but shared controllers cannot import component/patter
21
21
  runtime implementations. Keep business data in application adapters. Measured
22
22
  style writes retain exact `boundaries.styleWrites` properties; they do not allow
23
23
  shared-token overrides or an extra styling layer.
24
+ Projects explicitly approve installed runtime packages through
25
+ `behaviorLibraries` in `ds.config.json`; each must also be a `package.json`
26
+ dependency. Components, patterns and controllers may use them directly, including
27
+ package subpaths. Extract a shared controller when behavior is shared. Type-only
28
+ and development-role imports retain their existing rules. An empty/missing list
29
+ allows no additional runtime packages beyond the configured framework and Linaria.
30
+ ADS checks declarations and installed versions, not third-party source or
31
+ transitive dependency trees. The preview build bundles used code normally inside
32
+ the MCP App sandbox. Existing project styling and measured-geometry guards keep
33
+ their scope; declaration creates no broad style-write permissions.
24
34
  These gates inspect supported direct imports, markup and style boundaries.
25
35
  External package internals and delegated DOM behavior still require source,
26
36
  build and browser review; declaring a dependency does not prove it is headless.
@@ -49,6 +49,20 @@ Call `ads_show_draft({id,scenario?})`, then inspect its actual `showcaseUrl` in
49
49
  browser. The preview reuses an isolated compiler workspace across edits and does
50
50
  not run acceptance checks. Up to four draft compiler sessions stay warm; opening
51
51
  more reclaims an older generated workspace without deleting its tracked proposal.
52
+ Creation queues compiler prewarming without delaying its response. Bursts of
53
+ creations coalesce, and only one queued compiler initializes at a time. A newer
54
+ speculative prewarm reclaims the older unused one; explicitly opened sessions
55
+ remain warm within the four-session bound. MCP edits
56
+ and direct draft-file edits notify warm previews through file events; periodic
57
+ reconciliation recovers missed events. Watched builds compile requested scenarios
58
+ and their dependencies, retaining roots used by other open previews. Full builds
59
+ and validation still cover the complete configured scope. Incremental semantic
60
+ analysis reuses unchanged TypeScript source trees without caching passing checks.
61
+ Reopening a known scenario renders through the existing compiler while a worker
62
+ refreshes catalogue metadata. Read `discovery.state` (`current`, `pending`,
63
+ `error`) and its metadata revision separately from the exact proposal revision.
64
+ New/missing scenario identities wait for fresh discovery. A previous preview may
65
+ stay visible until compilation finishes; pending/stale output is not evidence.
52
66
  Reopen after edits to obtain the current revision.
53
67
  Compilation is feedback, not passing behavior/visual evidence.
54
68
 
@@ -73,10 +87,35 @@ Independent shared-barrel exports are merged; overlapping source changes remain
73
87
  explicit conflicts. Review the dependent's new revision before accepting it.
74
88
  If a dependency is dropped, correct the remaining draft's dependency list.
75
89
 
76
- DS Explorer has a Drafts section and draft badges. Its header Split view toggle
77
- compares Accepted and Draft in the right pane, preserving navigation. Both use
78
- the same scenario/theme and available or phone viewport width. New scenarios
79
- without an accepted counterpart show only the draft and disable comparison.
90
+ DS Explorer keeps drafts in the ordinary Tokens, Components, Patterns and
91
+ Composition navigation. A Draft badge marks an owner with a pending proposal,
92
+ whether or not it has an accepted version. Select that entry and use the header
93
+ Split view toggle to compare Accepted and Draft in the right pane. Both use the
94
+ same scenario/theme and available or phone viewport width. New owners appear
95
+ in their normal section; without an accepted counterpart they show only the
96
+ draft and disable comparison. There is no separate Drafts tab or scenario picker.
97
+ An isolated overlay can also render an unchanged scenario as an explicit review
98
+ context; that alone does not give its owner a Draft badge. Use `ads_drafts` for
99
+ draft-only MCP listing.
100
+
101
+ After 20 retained module revisions, Explorer restarts the affected App to release
102
+ its module cache, then restores the selected scenario/theme/viewport. Comparison
103
+ keeps the other version mounted; no manual reload or draft acceptance is needed.
104
+
105
+ Explorer entry glyphs separately show preview build states in monochrome: not
106
+ built, building, compiled/checking, ready, stale and failed. MCP draft summaries
107
+ include `preview` and preview calls include `build`; inspect `building`,
108
+ `current`, `stale`, scenario revisions and `preview.resourceUri` for detail.
109
+ Subscribe to `ads://project/build` and `ads://project/drafts` for standard
110
+ resource-update notifications on completion, failure and metadata refresh, or
111
+ subscribe only to an active draft's `preview.resourceUri` for its isolated report.
112
+ Modern clients use `subscriptions/listen` resource filters; older clients use
113
+ `resources/subscribe`. Re-read notified resources to update the existing view;
114
+ unsubscribe on teardown and resubscribe/read after reconnect. Removal invalidates
115
+ the scoped resource. Poll when the host does not forward notifications.
116
+ Build completion and mounted-App rendering readiness are separate. Ready draft
117
+ output remains unaccepted. Review the
118
+ current rendered revision and complete acceptance before finishing the change.
80
119
 
81
120
  ## Accept or drop
82
121
 
@@ -62,7 +62,20 @@ Dependency installation does not establish styling ownership. Keep only needed,
62
62
  declared runtime dependencies; inspect any stylesheet, reset, theme provider or
63
63
  visual default they require. Do not introduce a dependency's styling system or
64
64
  global reset to make its pixels match. Adapt owned styles through Linaria and
65
- shared Data; preserve any supported headless dependency's behavior contract.
65
+ shared Data; preserve installed behavior libraries explicitly approved through
66
+ `behaviorLibraries` in `ds.config.json` and listed in `package.json` dependencies.
67
+ Use their installed APIs with minimal lifecycle/event integration; do not vendor
68
+ or rewrite their source. For hard behavior, prefer the project's declared library.
69
+ If none fits, suggest a framework-free package for approval or implement natively.
70
+ Do not add a package or allowlist entry without authorization already covering it.
71
+ ADS checks the declaration and installation, not third-party dependency internals.
72
+
73
+ Floating UI's `computePosition` can feed `x`/`y` through exact allowlisted writes
74
+ such as `element.style.setProperty("--ds-popover-x", x + "px")` and the equivalent
75
+ `--ds-popover-y`. Register only these measured properties in
76
+ `boundaries.styleWrites`; keep placement CSS and visual treatment in project
77
+ Linaria and clean up `autoUpdate` observers on unmount. Library approval creates
78
+ no additional inline-style or CSSProperties exception.
66
79
 
67
80
  Preserve required capabilities, accessibility and interactions while applying
68
81
  the project's visual language. Source pixels are a reference, not an automatic
@@ -103,6 +103,15 @@ compiler. Existing custom adapters still work; they must adopt the helper to gai
103
103
  incremental transforms. Upgrade the project dependency and restart the builder.
104
104
  Keep the full validation callback and production build behavior.
105
105
 
106
+ Managed acceptance builds every scenario in production mode and shares the
107
+ candidate compiler/checked output with browser verification. Remove
108
+ `build:mcp-previews` from `mcp.mutationChecks` after upgrading ADS; keep that script
109
+ in normal builds. Explicit project commands still run as configured. During
110
+ acceptance ADS parks accepted/draft compilers but retains their publications;
111
+ an old view remains visible while verified preview requests wait. Do not launch
112
+ a second compiler to work around that wait. Semantic workers retire after five
113
+ idle seconds and rediscover from revision-fenced metadata when needed.
114
+
106
115
  The shared watched builder reuses completed self-contained IIFE worker bundles
107
116
  for constructor URLs and standard `?worker`/`?worker&url` imports. It uses Vite's
108
117
  configured worker plugins, deduplicates pending requests, tracks real worker and
@@ -67,3 +67,9 @@ separate latest validation result, alongside verification and mutation results.
67
67
  Source changes during execution reject success and leave the previous full
68
68
  baseline intact. Skipped registered behavior cases never pass; a project with no
69
69
  registered behavior contracts reports that stage as skipped with a reason.
70
+
71
+ Registered browser verification queues the selected scenario roots together
72
+ before browser workers open their pages. They share one candidate graph and
73
+ keep independent App state. This avoids compiling a growing graph per page.
74
+ A graph revision changing during startup keeps the preview pending until a
75
+ coherent current build mounts; it does not establish passing case evidence.
@@ -96,14 +96,14 @@ export function staticContractValue(expression, checker, options, locations = ne
96
96
  return read(expression);
97
97
  }
98
98
 
99
- export function inspectUnitContracts(options) {
99
+ export function inspectUnitContracts(options, suppliedProgram) {
100
100
  if (options.unitContracts) return options.unitContracts;
101
101
  const files = sourceFiles(options.dsRoot).filter(isContractFile);
102
102
  const result = { contracts: [], diagnostics: [], program: null };
103
103
  options.unitContracts = result;
104
104
  if (!files.length) return result;
105
105
  const inventory = inspectUnits(options);
106
- const program = ts.createProgram(sourceFiles(options.dsRoot).filter(file => /\.[cm]?[jt]sx?$/.test(file)), { ...projectCompilerOptions(options), allowJs: true });
106
+ const program = suppliedProgram ?? ts.createProgram(sourceFiles(options.dsRoot).filter(file => /\.[cm]?[jt]sx?$/.test(file)), { ...projectCompilerOptions(options), allowJs: true });
107
107
  result.program = program;
108
108
  const checker = program.getTypeChecker();
109
109
  const publicItems = [...publicApi(program, options), ...reviewApi(program, options)];
package/dist/units.mjs CHANGED
@@ -64,6 +64,12 @@ export function configurationFiles(options) {
64
64
  for (const file of files) visit(path.resolve(root,file),true, /^(?:ts|js)config[^/]*\.jsonc?$/.test(file));
65
65
  for (const plugin of config.oxlint.plugins) visit(path.resolve(root, plugin.path), true);
66
66
  const pkg = existsSync(path.join(root, "package.json")) ? JSON.parse(readFileSync(path.join(root, "package.json"), "utf8")) : {};
67
+ // Explicit build-tool config flags identify setup files even inside the ADS
68
+ // directory. Their tooling imports are not production behavior dependencies.
69
+ for (const command of Object.values(pkg.scripts ?? {})) if (typeof command === "string") {
70
+ for (const match of command.matchAll(/\b(?:vite|vitest|playwright)\b[^;&|\n]*?\s(?:--config(?:=|\s+)|-c\s+)(?:"([^"]+)"|'([^']+)'|([^\s;&|]+))/g))
71
+ visit(path.resolve(root, match[1] ?? match[2] ?? match[3]), true);
72
+ }
67
73
  const scripts = new Set();
68
74
  function script(name) {
69
75
  if (scripts.has(name)) return;
@@ -1,17 +1,29 @@
1
1
  import { spawn } from "node:child_process";
2
- import { readFileSync } from "node:fs";
2
+ import { mkdtempSync, readFileSync, rmSync, statSync } from "node:fs";
3
+ import { tmpdir } from "node:os";
4
+ import { fileURLToPath } from "node:url";
3
5
  import path from "node:path";
4
6
  import { projectContext } from "./mcp/context.mjs";
5
7
  import { packageScriptCommand } from "./development-runtime.mjs";
6
8
  import { failure as evidenceFailure } from "./evidence.mjs";
7
9
  const fail = (rule, message, file, failure) => Object.assign(new Error(message), { diagnostic: {rule, message, ...(file ? {file} : {}), ...(failure ? {failure} : {})} });
8
10
 
11
+ export async function checkCandidate(root, signal, trackingRoot = root) {
12
+ const directory = mkdtempSync(path.join(tmpdir(), "ads-architecture-"));
13
+ const report = path.join(directory, "report.json");
14
+ try {
15
+ await checkCommand(process.execPath, [fileURLToPath(new URL("./check-runner.mjs", import.meta.url)), root, report, trackingRoot], root, signal, undefined, {category:"architecture",phase:"ads-check"});
16
+ if (statSync(report).size > 16 * 1024 * 1024) throw new Error("Architecture report exceeds 16 MiB.");
17
+ return JSON.parse(readFileSync(report, "utf8"));
18
+ } finally { rmSync(directory, { recursive:true, force:true }); }
19
+ }
20
+
9
21
  export function checkCommand(command, args, cwd, signal, input, gate = {category:"architecture",phase:"patch-preparation"}, timeoutMs = 60000) {
10
22
  return new Promise((resolve, reject) => {
11
23
  if (signal?.aborted) { reject(fail("mutation-cancelled", "Mutation cancelled before validation.",undefined,evidenceFailure("runner","mutation-execution","ADS_CANCELLED"))); return; }
12
24
  const child = spawn(command, args, { cwd, shell: false, detached: process.platform !== "win32", windowsHide: true, stdio: [input === undefined ? "ignore" : "pipe", "pipe", "pipe"],
13
25
  env: { ...process.env, PATH: [path.join(cwd, "node_modules/.bin"), path.dirname(process.execPath), process.env.PATH ?? ""].join(path.delimiter) } });
14
- let output = "", failure;
26
+ let output = "", failure, guard, done = false;
15
27
  const startedAt=Date.now();
16
28
  if (input !== undefined) { child.stdin.on("error", () => {}); child.stdin.end(input); }
17
29
  function kill() {
@@ -21,6 +33,12 @@ export function checkCommand(command, args, cwd, signal, input, gate = {category
21
33
  stop.on("error", () => child.kill("SIGKILL"));
22
34
  } else { try { process.kill(-child.pid, "SIGKILL"); } catch (error) { if (error.code !== "ESRCH") failure ??= error; } }
23
35
  }
36
+ if (child.pid) {
37
+ guard = spawn(process.execPath, [fileURLToPath(new URL("./mcp/preview-owner-guard.mjs", import.meta.url)), String(child.pid), "--tree"], {stdio:["pipe","ignore","ignore"],windowsHide:true});
38
+ guard.stdin.on("error",()=>{});
39
+ const guardFailed = () => { if (!done) { failure ??= new Error("Validation ownership guard exited."); kill(); } };
40
+ guard.once("error",guardFailed);guard.once("exit",guardFailed);
41
+ }
24
42
  const abort = () => { failure = fail("mutation-cancelled", "Mutation cancelled during validation."); kill(); };
25
43
  signal?.addEventListener("abort", abort, { once: true });
26
44
  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);
@@ -28,6 +46,7 @@ export function checkCommand(command, args, cwd, signal, input, gate = {category
28
46
  child.once("error", error => { failure = error; });
29
47
  child.once("exit", kill); // Also clean up descendants of a finished launcher.
30
48
  child.once("close", code => {
49
+ done = true; guard?.stdin.end("cleanup\n");
31
50
  clearTimeout(timer); signal?.removeEventListener("abort", abort);
32
51
  const detail={command:path.basename(command),args,timeoutMs,elapsedMs:Date.now()-startedAt,exitCode:code};
33
52
  if (failure || code !== 0) {
@@ -43,7 +62,8 @@ export function checkCommand(command, args, cwd, signal, input, gate = {category
43
62
  export function projectChecks(options) {
44
63
  const context = projectContext(options);
45
64
  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");
65
+ const managed = options.config.mcp.previewManifest && options.config.mcp.previewWatch;
66
+ const scripts = options.config.mcp.mutationChecks ?? [pkg.scripts?.["lint:project"] ? "lint:project" : "lint", "typecheck", ...(managed ? [] : ["build:mcp-previews"])].filter(name => typeof pkg.scripts?.[name] === "string");
47
67
  if (scripts.some(name => typeof pkg.scripts?.[name] !== "string")) throw fail("mutation-check", "Every configured mcp.mutationChecks script must exist in package.json.");
48
68
  if (scripts.length && !["npm", "bun"].includes(context.packageManager)) throw fail("mutation-check", "Declare packageManager as npm or bun to run mutation checks.");
49
69
  return scripts.map(script => packageScriptCommand(context.packageManager, script));
@@ -3,14 +3,13 @@ import { existsSync, lstatSync, mkdirSync, readFileSync, readdirSync, realpathSy
3
3
  import { createRequire } from "node:module";
4
4
  import path from "node:path";
5
5
  import { fileURLToPath } from "node:url";
6
- import { checkProject } from "./check.mjs";
7
6
  import { loadConfig, isInside } from "./config.mjs";
8
7
  import { createLintConfig } from "./lint-config.mjs";
9
8
  import { inspectUnits } from "./units.mjs";
10
9
  import { inspectBehaviors } from "./behaviors.mjs";
11
10
  import { affectedBehaviorUnits, createVerificationController } from "./verification.mjs";
12
11
  import { validationInputFiles } from "./validation-inputs.mjs";
13
- import { checkCommand, projectChecks } from "./validation-checks.mjs";
12
+ import { checkCandidate, checkCommand, projectChecks } from "./validation-checks.mjs";
14
13
  import { projectContext } from "./mcp/context.mjs";
15
14
  import { packageScriptCommand } from "./development-runtime.mjs";
16
15
  import { acceptance } from "./evidence.mjs";
@@ -37,7 +36,7 @@ function outputFile(root, name) {
37
36
  return path.join(folder,name);
38
37
  }
39
38
 
40
- export function createValidationController(directory) {
39
+ export function createValidationController(directory, { previewWork } = {}) {
41
40
  const root = path.resolve(directory);
42
41
  let active, progress;
43
42
  return {
@@ -52,7 +51,7 @@ export function createValidationController(directory) {
52
51
  let finish; controller.completion = new Promise(resolve => { finish = resolve; });
53
52
  const startedAt = Date.now(), checks = [], diagnostics = [], advisories = [], results = [];
54
53
  const requestedScope = scope;
55
- let inputs, changed = [], units = [], fallback;
54
+ let inputs, changed = [], units = [], fallback, releasePreview, previewHost;
56
55
  function stage(name) { signal.throwIfAborted(); progress = {stage:name,elapsedMs:Date.now()-startedAt,completed:checks.length}; onProgress?.(progress); }
57
56
  async function command(name, launch, options) {
58
57
  stage(name);
@@ -60,6 +59,7 @@ export function createValidationController(directory) {
60
59
  catch (error) { checks.push({name,passed:false}); throw error; }
61
60
  }
62
61
  try {
62
+ if (previewWork) releasePreview = await previewWork.acquire(signal);
63
63
  const options = loadConfig(root);
64
64
  inputs = validationInputs(options);
65
65
  const baselineFile = outputFile(root,"validation-baseline.json");
@@ -78,7 +78,7 @@ export function createValidationController(directory) {
78
78
  if (fallback) scope = "all";
79
79
  }
80
80
  stage("architecture");
81
- const core = checkProject(root);
81
+ const core = await checkCandidate(root, signal);
82
82
  diagnostics.push(...core.diagnostics); advisories.push(...(core.advisories ?? []));
83
83
  checks.push({name:"architecture",passed:core.ok});
84
84
  if (!core.ok) return complete();
@@ -109,10 +109,21 @@ export function createValidationController(directory) {
109
109
  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);
110
110
  } finally { rmSync(lintConfig,{force:true}); }
111
111
  for (const launch of scripts) await command(`project:${launch.args.at(-1)}`,launch,options);
112
+ if (options.config.mcp.previewManifest && options.config.mcp.previewWatch) {
113
+ stage("preview-build");
114
+ const { startAdsMcp } = await import("./mcp/server.mjs");
115
+ previewHost = await startAdsMcp(root, { stdio:false });
116
+ await previewHost.buildAll(signal, {timeoutMs:options.config.mcp.mutationCheckTimeoutMs});
117
+ checks.push({name:"managed production previews",passed:true});
118
+ }
112
119
  if (options.config.mcp.previewManifest || options.config.mcp.apps.length) {
113
120
  stage("verified-previews");
114
121
  const apps=[...options.config.mcp.apps,...inspectScenarios(options).scenarios.map(entry=>({id:entry.id,file:entry.artifact}))];
115
- const build=inspectBuildStatus(root,{...options.config.mcp,apps});
122
+ const build=previewHost ? previewHost.buildStatus() : inspectBuildStatus(root,{...options.config.mcp,apps});
123
+ if (previewHost && options.config.mcp.apps.length) build.previews = [
124
+ ...build.previews.filter(entry=>entry.id.includes("/")),
125
+ ...inspectBuildStatus(root,{...options.config.mcp,apps:options.config.mcp.apps}).previews,
126
+ ];
116
127
  const pending=build.previews.filter(entry=>!entry.current);
117
128
  checks.push({name:"verified-previews",passed:!pending.length,previewCount:apps.length});
118
129
  if (pending.length) {
@@ -124,7 +135,7 @@ export function createValidationController(directory) {
124
135
  units = scope === "all" ? behaviors.contracts.map(contract=>contract.unit) : affectedBehaviorUnits(options,changed);
125
136
  if (units.length) {
126
137
  stage("behavior");
127
- const verification = createVerificationController(root);
138
+ const verification = createVerificationController(root, {previewHost});
128
139
  let result;
129
140
  try { result = await verification.run({units},signal,value=>{ progress={stage:"behavior",...value}; onProgress?.(progress); }); }
130
141
  finally { await verification.close(); }
@@ -133,11 +144,10 @@ export function createValidationController(directory) {
133
144
  if (!result.ok && !result.diagnostics.length) diagnostics.push({rule:"validation-behavior",message:"Registered behavior checks did not all pass. Inspect the recorded outcomes."});
134
145
  } else checks.push({name:"registered-behavior",passed:true,skipped:true,reason:scope === "all" ? "No registered behavior contracts." : "No affected behavior contracts."});
135
146
  } catch (error) { diagnostics.push(error.diagnostic ?? {rule:signal.aborted ? "validation-cancelled" : "validation-execution",message:error.message}); }
136
- finally { /* Completion also runs for early architecture failures. */ }
147
+ finally { try { await previewHost?.close(); } finally { releasePreview?.();active=undefined;progress=undefined;finish(); } }
137
148
  return complete();
138
149
 
139
150
  function complete() {
140
- try {
141
151
  let current = false;
142
152
  try { current = !!inputs && validationInputs(loadConfig(root)).revision === inputs.revision; } catch (error) { diagnostics.push({rule:"validation-inputs",message:error.message}); }
143
153
  if (inputs && !current) diagnostics.push({rule:"validation-stale",message:"Project inputs changed during validation. Rerun against current source."});
@@ -151,7 +161,6 @@ export function createValidationController(directory) {
151
161
  }
152
162
  return {ok,scope,requestedScope,...(fallback?{fallback}:{}),sourceRevision:inputs?.revision,current,elapsedMs:Date.now()-startedAt,selection:{files:changed,units},checks,diagnostics,advisories,results,
153
163
  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"])};
154
- } finally { active=undefined;progress=undefined;finish(); }
155
164
  }
156
165
  },
157
166
  };
@@ -0,0 +1,27 @@
1
+ import type { Frame, Page } from "@playwright/test";
2
+
3
+ /** Development-only helpers; Playwright is provided by the project's runner. */
4
+ export interface VerificationRequest {
5
+ schemaVersion: 1;
6
+ runId: string;
7
+ projectRoot: string;
8
+ framework: string;
9
+ profile: string;
10
+ mode: string;
11
+ checks: { id: string; scenario?: string; [key: string]: unknown }[];
12
+ scenarios: Record<string, string>;
13
+ }
14
+
15
+ export interface PaintAuditResult {
16
+ ok: boolean;
17
+ complete?: boolean;
18
+ verified: { owner: string; binding: string; variable: string }[];
19
+ diagnostics: string[];
20
+ limits?: string[];
21
+ scope?: string;
22
+ }
23
+
24
+ export function verificationRequest(): VerificationRequest;
25
+ export function auditBehaviorPaints(frame: Frame): Promise<PaintAuditResult>;
26
+ export function openBehaviorScenario(page: Page, checkId: string, options?: { timeout?: number }): Promise<Frame>;
27
+ export function openPreviewScenario(page: Page, url: string, scenario: string, options?: { timeout?: number }): Promise<Frame>;
@@ -223,7 +223,7 @@ function runProgress(group, report, startedAt, profile, timeoutMs) {
223
223
  }
224
224
 
225
225
  /** Registered development commands are trusted project code, never model-supplied commands. */
226
- export function createVerificationController(root, { reportRoot = root, onProgress } = {}) {
226
+ export function createVerificationController(root, { reportRoot = root, onProgress, previewWork, previewHost } = {}) {
227
227
  root = path.resolve(root);
228
228
  reportRoot = path.resolve(reportRoot);
229
229
  let active, progress;
@@ -236,9 +236,10 @@ export function createVerificationController(root, { reportRoot = root, onProgre
236
236
  const controller = active;
237
237
  signal = signal ? AbortSignal.any([signal, active.signal]) : active.signal;
238
238
  let finish; controller.completion = new Promise(resolve => { finish = resolve; });
239
- let host;
239
+ let host, releasePreview;
240
240
  const results = [], diagnostics = [];
241
241
  try {
242
+ if (previewWork) releasePreview = await previewWork.acquire(signal);
242
243
  const options = loadConfig(root), inventory = inspectBehaviors(options);
243
244
  if (inventory.diagnostics.length) return verificationResult(inventory.diagnostics.map(diagnostic=>({...diagnostic,failure:failure("architecture","behavior-contract",diagnostic.rule)})),results);
244
245
  const selectedUnits = new Set(units ?? (unit ? [unit] : inventory.contracts.map(item => item.unit)));
@@ -257,7 +258,10 @@ export function createVerificationController(root, { reportRoot = root, onProgre
257
258
  const scenarios = {};
258
259
  if (profile.mode === "browser" && group.some(check => check.scenario)) {
259
260
  const { startAdsMcp } = await import("./mcp/server.mjs");
260
- host ??= await startAdsMcp(root, { stdio: false, showcase: true });
261
+ host ??= previewHost ?? await startAdsMcp(root, { stdio: false, showcase: true });
262
+ // Queue all selected roots before parallel browser workers open. A
263
+ // single graph avoids repeated compilation and startup handovers.
264
+ await host.warmScenarios([...new Set(group.map(check => check.scenario).filter(Boolean))], signal);
261
265
  for (const check of group.filter(check => check.scenario)) {
262
266
  const url = new URL(host.url);
263
267
  url.searchParams.set("scenario", check.scenario);
@@ -351,7 +355,7 @@ export function createVerificationController(root, { reportRoot = root, onProgre
351
355
  }
352
356
  return verificationResult(diagnostics,results);
353
357
  } catch (error) { return verificationResult([{ rule: "behavior-verification", message: error.message }],results); }
354
- finally { try { await host?.close(); } finally { if (active === controller) { active = undefined; progress = undefined; } finish(); } }
358
+ finally { try { if (host !== previewHost) await host?.close(); } finally { releasePreview?.(); if (active === controller) { active = undefined; progress = undefined; } finish(); } }
355
359
  },
356
360
  };
357
361
  }
@@ -241,6 +241,29 @@ dependencies, with no runtime supplied by the MCP host. Shared controllers do no
241
241
  import styled consumers or introduce another skin layer. Existing measurement and
242
242
  style-write boundaries still apply.
243
243
 
244
+ Projects can explicitly allow installed runtime packages with
245
+ `"behaviorLibraries": ["@floating-ui/dom", "tabbable"]` in `ds.config.json`.
246
+ Each name must also appear in `package.json` dependencies and be installed.
247
+ Production ADS code may import those packages and their subpaths directly from
248
+ components, patterns or controllers; extract a shared controller only when the
249
+ behavior is shared. Other external runtime imports fail
250
+ `behavior-library-undeclared`. Type-only imports and development roles retain
251
+ their existing rules, as do the configured framework and Linaria exceptions.
252
+ `ads lint-config` reports import locations and the exact list to declare.
253
+
254
+ This is project approval, not a recursive dependency audit or a guarantee about
255
+ third-party internals. ADS reads installed versions without executing packages
256
+ or scanning their dependency source or stylesheets. The declaration authorizes
257
+ package imports and subpaths. Existing source styling and measured-geometry
258
+ checks retain their scope; it introduces no new package-CSS certification gate. Use libraries as installed, with minimal lifecycle/event integration.
259
+ For example, Floating UI's `computePosition` can supply `x` and `y` to an
260
+ allowlisted producer's `style.setProperty("--ds-popover-x", ...)` and
261
+ `style.setProperty("--ds-popover-y", ...)`; project Linaria owns positioning
262
+ rules and visual treatment. Register those exact properties using the existing
263
+ `boundaries.styleWrites` mechanism. Clean up positioning observers on unmount.
264
+ The project preview compiler bundles used library code into the normal MCP App
265
+ resource graph; declarations alone do not load packages or change its sandbox.
266
+
244
267
  Optional `<Owner>.ads.contract.ts` modules identify public APIs or private
245
268
  implementation symbols, named guarantees and registered execution checks. Scenario
246
269
  `exercises` links public behavior APIs to reachable demonstrations; `covers`
@@ -464,6 +487,60 @@ scenario inspection run in the background. Inspection uses a persistent worker
464
487
  to keep the compiler responsive. Rapid edits replace pending work, with one
465
488
  verification run in flight. Production builds retain their own optimization.
466
489
 
490
+ Preview discovery shares `.ds/scenario-registry.json` between the MCP host,
491
+ draft selector and compiler processes. The snapshot contains scenario metadata
492
+ and diagnostics, keyed to the full relevant source/dependency/directory revision
493
+ and the loaded ADS code/runtime. Accepted and draft roots retain separate
494
+ snapshots. A matching snapshot avoids repeating TypeScript analysis during
495
+ startup; changed inputs or missing/corrupt snapshots trigger fresh discovery.
496
+ Explicit catalogue reads fence their in-memory registry against current source,
497
+ so edits and removals are visible before the next observation/reconciliation tick.
498
+ Reopening an already known draft scenario retains its last discovered metadata
499
+ while a persistent worker refreshes the catalogue. It does not run synchronous
500
+ semantic discovery on the preview request. New/missing scenario identities await
501
+ worker discovery; accepted comparison metadata is independently revision-fenced.
502
+ The response's `discovery` distinguishes current, pending and failed metadata
503
+ from the exact proposal revision and the actual preview build. Superseded worker
504
+ results cannot replace newer requests; drop/shutdown retires their state/worker.
505
+ Preview analysis retains a bounded set of TypeScript programs and unchanged
506
+ source trees across edits; module lookups are refreshed so added/deleted files
507
+ cannot inherit old resolution results. Full validation uses fresh independent
508
+ analysis. Watched graphs include requested scenario roots and their dependencies,
509
+ preserving roots used by other mounted Apps; untouched catalogue entries are not
510
+ compiled until requested. Unwatched full builds retain complete entry coverage.
511
+ Snapshot publication fences source edits during inspection. This cache supplies
512
+ no passing validation or behavior evidence: architecture and acceptance checks
513
+ continue to inspect and validate source independently.
514
+
515
+ Draft creation queues background compiler initialization. One prewarm runs at a
516
+ time, newer pending drafts supersede unused queued work and reclaim an older
517
+ unused speculative session, and explicit preview requests share the same startup.
518
+ Explicitly opened sessions remain subject to the four-session bound.
519
+ File events and MCP writes synchronize warm
520
+ overlays after a short debounce; a slower periodic reconciliation recovers lost
521
+ events and replaced directories. Closing ADS stops queued jobs, source watchers
522
+ and every owned compiler.
523
+
524
+ Draft build reports flow from their preview hosts into the parent build resource
525
+ and proposal summaries. `ads://project/build.drafts` identifies active proposal
526
+ builds, their scenario states, session/revision, freshness and scoped resource
527
+ addresses; `ads_drafts` and relevant discovery/preview results carry compact
528
+ status. Draft source edits immediately mark an existing preview queued/stale.
529
+ Build transitions change the parent resource fingerprint and emit standard
530
+ resource-update notifications for build/draft subscribers, including completion
531
+ and failure without another edit. Active scoped build resources are listed and
532
+ subscribable; removal emits a final invalidation and a resource-list change.
533
+ Observers share draft events across connections, detach when closed and serialize
534
+ refreshes so overlapping file events cannot replay older state. Native report-file
535
+ events notify promptly; periodic observation also covers missed/replaced files.
536
+ Stateless HTTP mutation handlers forward refreshes to those observers; they do
537
+ not initialize fresh observation and misclassify each request as a source edit.
538
+ Draft-only edits preserve accepted registry/catalogue snapshots. Capture updates
539
+ reuse source-fenced discovery rather than allocating another semantic program.
540
+ Explorer uses these reports for monochrome
541
+ entry glyphs and refreshes its mounted Apps. A ready draft preview remains
542
+ unaccepted; catalogue metadata or compiled feedback cannot establish acceptance.
543
+
467
544
  Live resources are fenced to the current source digest and managed session.
468
545
  They never update accepted artifacts, the successful graph cache or `current`.
469
546
  Only validation and compilation passing against unchanged source can publish the
@@ -482,6 +559,39 @@ matching checked candidate graph and scenario registry carry into the project's
482
559
  otherwise the normal watcher builds it in the background. Builds tied to a
483
560
  temporary candidate location are rebuilt. Source, dependencies, compiler and
484
561
  output content determine reuse, with no expiry based on elapsed time.
562
+ Cache recording checks the compiled source stamp before and after hashing
563
+ dependencies. An edit racing publication cannot associate previous output with
564
+ newer inputs; it leaves the previous cache intact and requires the next build.
565
+ A transferred checked graph can refresh older watcher metadata without recompiling
566
+ it, while a partial watched graph cannot replace the complete catalogue.
567
+ Its full semantic registry snapshot transfers only when source revisions match,
568
+ so restarting a parked compiler need not repeat discovery of accepted source.
569
+ Shared dependency maps are stored once, with a fresh validation memo for each
570
+ reuse operation. No file hash is retained across operations. Configuration input
571
+ ordering is canonical across Node and Bun; complete caches stay within the
572
+ existing 8 MiB budget rather than silently writing an unreadable large file.
573
+
574
+ Guarded acceptance and MCP validation park the project's accepted and draft
575
+ compiler processes while the isolated candidate runs. Parking retains the same
576
+ publication session and immutable assets, so mounted Apps keep their view and
577
+ resource reads continue. Requests requiring a verified build queue until validation releases the
578
+ compiler budget; cancellation removes the waiter. Resumption starts a compiler
579
+ only when requested, reusing checked artifacts for unchanged inputs.
580
+
581
+ For managed resource previews, ADS requests all scenarios in production mode
582
+ through that candidate's compiler. It closes an incremental Rollup graph before
583
+ starting production compilation. The same candidate host then serves registered
584
+ browser verification; warm selections reuse the checked production graph.
585
+ Production reuse requires a successful production build of the exact inputs,
586
+ not merely a previously compiled development graph. Project-owned additional
587
+ commands still run as configured. Remove the standalone preview-build command
588
+ from `mcp.mutationChecks`; keep it in the ordinary project build.
589
+
590
+ Candidate architecture inspection runs in a short-lived owned process, releasing
591
+ its TypeScript heap after completion or cancellation. Semantic preview workers
592
+ retire after five idle seconds, while revision-fenced metadata remains on disk.
593
+ Closing a temporary host releases its semantic program cache. These lifecycle
594
+ bounds do not change source checks, behavior selection or publication fences.
485
595
 
486
596
  After the selected view paints, a connected showcase can prefetch changed peers'
487
597
  static resources into the App's existing byte cache. This bounded, opportunistic