@reqvire-org/ads 0.3.34 → 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.
@@ -3,16 +3,19 @@ import { existsSync, mkdirSync, readFileSync, readdirSync, realpathSync, renameS
3
3
  import path from "node:path";
4
4
  import { isDraftPreviewWorkspace } from "./draft-workspace.mjs";
5
5
  import { loadConfig, isInside } from "./config.mjs";
6
- import { discoverScenarioRegistry } from "./scenario-registry.mjs";
6
+ import { discoverScenarioRegistry, prepareScenarioRegistryTransfer, releaseScenarioRegistry } from "./scenario-registry.mjs";
7
7
  import { artifactDigest, createBuildReporter } from "./mcp/build-status.mjs";
8
8
  import { cachedPreviewPublication, previewArtifactHtml, readPreviewManifest } from "./preview-resources.mjs";
9
9
  import { previewArtifactPath, withPreviewSession } from "./preview-scope.mjs";
10
10
  import { previewSourceRevision } from "./preview-inputs.mjs";
11
11
  import { previewFileIgnored, previewWatchDirectories } from "./preview-files.mjs";
12
12
  import { createScenarioInspector } from "./scenario-inspector.mjs";
13
+ import { configurationFiles } from "./units.mjs";
14
+ import { validationInputFiles } from "./validation-inputs.mjs";
13
15
 
14
16
  const digest = value => createHash("sha256").update(value).digest("hex");
15
17
  const fileDigest = file => { try { return digest(readFileSync(file)); } catch { return null; } };
18
+ const cacheVersion = 3, maxCacheBytes = 8 * 1024 * 1024;
16
19
 
17
20
  /** Cache only successful validation + matching source/dependency/output content.
18
21
  * Cache state is development output, never proof that a failed build is current. */
@@ -24,12 +27,12 @@ export function createPreviewCache(options, compilerFiles = []) {
24
27
  const adapterDigest = () => digest(JSON.stringify(adapterFiles.map(file => [key(file), fileDigest(file)])));
25
28
  const loadedAdapter = adapterDigest();
26
29
  const target = path.join(root, ".ds/preview-cache.json");
27
- let value = { schemaVersion: 2, validation: null, entries: {} };
30
+ let value = { schemaVersion: cacheVersion, validation: null, entries: {}, dependencySets: {} };
28
31
  function reload() {
29
32
  try {
30
- if (realpathSync(target) === target && statSync(target).size < 8*1024*1024) {
33
+ if (realpathSync(target) === target && statSync(target).size < maxCacheBytes) {
31
34
  const stored = JSON.parse(readFileSync(target, "utf8"));
32
- if (stored.schemaVersion === 2 && stored.entries && typeof stored.entries === "object") value = stored;
35
+ if (stored.schemaVersion === cacheVersion && stored.entries && typeof stored.entries === "object" && stored.dependencySets && typeof stored.dependencySets === "object") value = stored;
33
36
  }
34
37
  } catch { /* Missing or corrupt cache means validate and rebuild. */ }
35
38
  }
@@ -45,38 +48,72 @@ export function createPreviewCache(options, compilerFiles = []) {
45
48
  return digest(JSON.stringify(rows.sort((a, b) => a[0].localeCompare(b[0]))));
46
49
  }
47
50
  function save() {
48
- value.compilerFiles = compilerFiles.map(file => isInside(root,file) ? path.relative(root,file) : null);
49
51
  mkdirSync(path.dirname(target), { recursive: true });
50
52
  if (realpathSync(path.dirname(target)) !== path.dirname(target)) throw new Error("Preview cache cannot resolve through a symlink.");
53
+ value.compilerFiles = compilerFiles.map(file => isInside(root,file) ? path.relative(root,file) : null);
54
+ const used = new Set(Object.values(value.entries).map(entry => entry.dependencySet));
55
+ value.dependencySets = Object.fromEntries([...used].filter(id=>value.dependencySets[id]).map(id=>[id,value.dependencySets[id]]));
56
+ const content = JSON.stringify(value);
57
+ if (Buffer.byteLength(content) >= maxCacheBytes) {
58
+ rmSync(target, {force:true});
59
+ console.warn("ADS preview cache exceeds 8 MiB after deduplication; this build remains current, but a new compiler will rebuild it.");
60
+ return;
61
+ }
51
62
  const temporary = `${target}.${randomUUID()}.tmp`;
52
- try { writeFileSync(temporary, JSON.stringify(value)); renameSync(temporary, target); }
63
+ try { writeFileSync(temporary, content); renameSync(temporary, target); }
53
64
  finally { rmSync(temporary, { force: true }); }
54
65
  }
66
+ function compilerInputs() {
67
+ const configured = new Set([...configurationFiles(options)].filter(file=>!/^(?:biome|oxlint|\.oxlint)/.test(file)));
68
+ const packages = new Set(["package-lock.json","npm-shrinkwrap.json","yarn.lock","pnpm-lock.yaml","bun.lock","bun.lockb","bunfig.toml",".npmrc",".yarnrc.yml","installed-dependencies"]);
69
+ const opaque = (options.config.validation?.inputs ?? []).map(file=>path.resolve(root,file));
70
+ // Use the same declared configuration/input boundary as guarded copies.
71
+ // Unrelated local launcher JSON must not make a candidate unportable.
72
+ return Object.entries(validationInputFiles(options)).filter(([file])=>configured.has(file)||packages.has(file)||opaque.some(directory=>isInside(directory,path.resolve(root,file))))
73
+ .sort(([a],[b])=>a.localeCompare(b));
74
+ }
55
75
  const compilerDigest = () => digest(JSON.stringify([
56
76
  ["adapter", adapterDigest()],
57
77
  ...compilerFiles.map(file => [key(file), fileDigest(file)]),
58
- ...readdirSync(root).filter(name => !/^(?:biome|oxlint|\.oxlint)/.test(name) && (/\.(?:json|lock|lockb)$/.test(name) || /^(?:vite|babel)\.config\./.test(name))).map(name => [name, fileDigest(path.join(root, name))]),
78
+ ...compilerInputs(),
59
79
  ["installed-packages", fileDigest(path.join(root, "node_modules/.package-lock.json"))],
60
80
  ["scheduler", fileDigest(import.meta.filename)],
61
81
  ["node-runtime", `${process.version}/${process.platform}/${process.arch}`],
62
82
  ]));
63
- function reusable(entry, expectedHtml) {
83
+ function reusable(entry, expectedHtml, inspection) {
64
84
  const cached = value.entries[entry.id];
65
- if (!cached || cached.metadata !== JSON.stringify(entry) || cached.compiler !== compilerDigest()) return false;
66
- if (!cached.dependencies || !Object.keys(cached.dependencies).length) return false;
67
- if (Object.entries(cached.dependencies).some(([file, hash]) => fileDigest(path.resolve(root, file)) !== hash)) return false;
85
+ if (!cached || cached.metadata !== JSON.stringify(entry) || cached.compiler !== (inspection?.compiler ?? compilerDigest())) return false;
86
+ const dependencies = value.dependencySets[cached.dependencySet];
87
+ if (!dependencies || !Object.keys(dependencies).length) return false;
88
+ let valid = inspection?.sets.get(cached.dependencySet);
89
+ if (valid === undefined) valid = !Object.entries(dependencies).some(([file, hash]) => {
90
+ const absolute = path.resolve(root, file);
91
+ if (!inspection) return fileDigest(absolute) !== hash;
92
+ if (!inspection.files.has(absolute)) inspection.files.set(absolute, fileDigest(absolute));
93
+ return inspection.files.get(absolute) !== hash;
94
+ });
95
+ inspection?.sets.set(cached.dependencySet, valid);
96
+ if (!valid) return false;
68
97
  if (expectedHtml !== undefined) return cached.artifact === `sha256:${digest(expectedHtml)}`;
69
98
  const file = path.join(root, previewArtifactPath(options, entry.artifact));
70
99
  try { return cached.artifact === artifactDigest(file); } catch { return false; }
71
100
  }
101
+ function reusableEntries(entries, revision) {
102
+ // Scope memoization to this one operation; the caller still fences source
103
+ // before publication. Never retain hashes across edits or requests.
104
+ const inspection = { compiler: compilerDigest(), files: new Map(), sets: new Map() };
105
+ return entries.every(entry => reusable(entry, previewArtifactHtml(entry.id, revision), inspection));
106
+ }
72
107
  function recordEntries(entries, dependencies) {
73
108
  const compiler = compilerDigest(), hashes = new Map();
74
109
  for (const entry of entries) {
75
110
  const files = [...new Set([path.join(root, entry.file), ...dependencies])]
76
111
  .filter(file => isInside(root, file) && !file.includes(`${path.sep}node_modules${path.sep}`));
77
112
  for (const file of files) if (!hashes.has(file)) hashes.set(file, fileDigest(file));
78
- value.entries[entry.id] = { metadata: JSON.stringify(entry), compiler,
79
- dependencies: Object.fromEntries(files.map(file => [path.relative(root, file), hashes.get(file)])),
113
+ const dependencyHashes = Object.fromEntries(files.map(file => [path.relative(root,file),hashes.get(file)]).sort(([a],[b])=>a.localeCompare(b)));
114
+ const dependencySet = digest(JSON.stringify(dependencyHashes));
115
+ value.dependencySets[dependencySet] = dependencyHashes;
116
+ value.entries[entry.id] = { metadata: JSON.stringify(entry), compiler, dependencySet,
80
117
  artifact: artifactDigest(path.join(root, previewArtifactPath(options, entry.artifact))) };
81
118
  }
82
119
  }
@@ -85,7 +122,7 @@ export function createPreviewCache(options, compilerFiles = []) {
85
122
  // Never attach the previous output to bytes newer than its compiled stamp.
86
123
  if (inputs() !== stamp) return false;
87
124
  const previous = value;
88
- value = { ...value, entries: { ...value.entries } };
125
+ value = { ...value, entries: { ...value.entries }, dependencySets: { ...value.dependencySets } };
89
126
  try {
90
127
  update();
91
128
  if (inputs() !== stamp) { value = previous; return false; }
@@ -95,13 +132,15 @@ export function createPreviewCache(options, compilerFiles = []) {
95
132
  }
96
133
  function graph(revision, entries, stamp) { value.graphRevision=revision;value.graphInputs=stamp;value.registry=entries; }
97
134
  function recordGraph(revision, entries, stamp = inputs()) { return recordCurrent(stamp, () => graph(revision, entries, stamp)); }
98
- return { inputs, reusable, reload, snapshot: () => structuredClone(value), seed(state) { value=structuredClone(state);save(); }, graphRevision: () => value.graphRevision, recordGraph, validated: stamp => value.validation === stamp,
135
+ return { inputs, reusable, reusableEntries, reload, snapshot: () => structuredClone(value), seed(state) { value=structuredClone(state);save(); }, graphRevision: () => value.graphRevision, recordGraph, validated: stamp => value.validation === stamp,
136
+ production(stamp) { return value.production?.stamp === stamp && value.production.revision === value.graphRevision; },
137
+ recordProduction(stamp) { return recordCurrent(stamp, () => { value.production = { stamp, revision: value.graphRevision }; }); },
99
138
  registry(stamp) {
100
139
  if(value.validation!==stamp || value.graphInputs!==stamp || !Array.isArray(value.registry) || !value.registry.length || value.registry.length>1000)return null;
101
140
  const valid=value.registry.every(entry=>typeof entry?.id==="string" && /^(?:tokens|components|patterns|composition)\/[\w./-]+$/.test(entry.id) && path.posix.normalize(entry.id)===entry.id
102
141
  && typeof entry.file==="string" && isInside(options.dsRoot,path.resolve(root,entry.file))
103
- && entry.artifact===`.ds/scenarios/${entry.id}/index.html` && reusable(entry,previewArtifactHtml(entry.id,value.graphRevision)));
104
- return valid?structuredClone(value.registry):null;
142
+ && entry.artifact===`.ds/scenarios/${entry.id}/index.html`);
143
+ return valid && reusableEntries(value.registry,value.graphRevision)?structuredClone(value.registry):null;
105
144
  },
106
145
  assertCompiler() {
107
146
  if (adapterDigest() !== loadedAdapter) throw Object.assign(new Error("Preview compiler code or dependencies changed. Invoke the preview again to restart the builder and load current code."), { code: "ADS_PREVIEW_RESTART" });
@@ -119,9 +158,9 @@ export function createPreviewCache(options, compilerFiles = []) {
119
158
  export function preparePreviewCache(candidate, target) {
120
159
  if (!candidate.config.mcp.previewManifest || candidate.config.framework !== target.config.framework || !target.config.mcp.previewManifest) return false;
121
160
  const file=path.join(candidate.root,".ds/preview-cache.json");
122
- if (!existsSync(file) || realpathSync(file)!==file || statSync(file).size>8*1024*1024) return false;
161
+ if (!existsSync(file) || realpathSync(file)!==file || statSync(file).size>=maxCacheBytes) return false;
123
162
  const state=JSON.parse(readFileSync(file,"utf8"));
124
- if(state.schemaVersion!==2 || !Array.isArray(state.compilerFiles) || state.compilerFiles.some(file=>typeof file!=="string"||!isInside(candidate.root,path.resolve(candidate.root,file))))return false;
163
+ if(state.schemaVersion!==cacheVersion || !Array.isArray(state.compilerFiles) || state.compilerFiles.some(file=>typeof file!=="string"||!isInside(candidate.root,path.resolve(candidate.root,file))))return false;
125
164
  const source=createPreviewCache(candidate,state.compilerFiles.map(file=>path.resolve(candidate.root,file)));
126
165
  const destination=createPreviewCache(target,state.compilerFiles.map(file=>path.resolve(target.root,file)));
127
166
  const stamp=source.inputs();
@@ -130,10 +169,12 @@ export function preparePreviewCache(candidate, target) {
130
169
  const publication=cachedPreviewPublication(candidate,entries,state.graphRevision,target);
131
170
  if(!publication || source.inputs()!==stamp)return false;
132
171
  const snapshot=source.snapshot();
172
+ const transferRegistry=prepareScenarioRegistryTransfer(candidate,target);
133
173
  return () => {
134
174
  if(destination.inputs()!==stamp)return false;
135
175
  publication.publish("accepted-mutation");
136
176
  destination.seed(snapshot);
177
+ transferRegistry?.();
137
178
  return {revision:publication.revision,scenarios:entries.map(entry=>entry.id)};
138
179
  };
139
180
  }
@@ -160,6 +201,7 @@ export async function runScenarioCompiler(directory, { watched = false, validate
160
201
  if (!watched) throw error;
161
202
  registryFailure = error; entries = error.scenarios ?? [];
162
203
  }
204
+ finally { if (watched && buildGraph) releaseScenarioRegistry(root); }
163
205
  const buildApps = () => entries.map(entry => ({ id: entry.id, file: previewArtifactPath(options, entry.artifact) }));
164
206
  const reporter = createBuildReporter(root, { apps: buildApps() });
165
207
  const requested = new Set();
@@ -173,6 +215,7 @@ export async function runScenarioCompiler(directory, { watched = false, validate
173
215
  let validation;
174
216
  let observedSourceRevision = previewSourceRevision(options);
175
217
  let invalidation;
218
+ let fullRequest, completedFull;
176
219
  const inspector = watched && buildGraph ? createScenarioInspector(root) : null;
177
220
  let discovering, unknownRevision;
178
221
  let liveCandidate, verifying = false;
@@ -269,12 +312,12 @@ export async function runScenarioCompiler(directory, { watched = false, validate
269
312
  } };
270
313
  cache.assertCompiler();
271
314
  const cached = cachedPreviewPublication(options, entries, cache.graphRevision());
272
- let reusable = cached && entries.every(entry => cache.reusable(entry, previewArtifactHtml(entry.id, cached.revision)));
315
+ let reusable = cache.production(stamp) && cached && cache.reusableEntries(entries,cached.revision);
273
316
  if (reusable) {
274
317
  try { readPreviewManifest(options, { verify: true }); }
275
318
  catch { reusable = false; }
276
319
  }
277
- const outcomes = await checkedBuild(stamp, () => reusable ? null : buildGraph(entries, options, track, { watched }));
320
+ const outcomes = await checkedBuild(stamp, () => reusable ? null : buildGraph(entries, options, track, { watched: false }));
278
321
  const failure = outcomes.find(outcome => outcome.status === "rejected");
279
322
  if (failure) throw failure.reason;
280
323
  cache.assertCompiler();
@@ -289,13 +332,17 @@ export async function runScenarioCompiler(directory, { watched = false, validate
289
332
  }
290
333
  for (const entry of entries) { pending.delete(entry.id); reporter.ready(entry.id, revisions.get(entry.id)); }
291
334
  publishedStamp = stamp;
335
+ publishedEntries = new Set(entries.map(entry => entry.id));
336
+ cache.recordProduction(stamp);
292
337
  reporter.progress("idle");
338
+ return true;
293
339
  } catch (error) {
294
340
  if (started !== generation) return;
295
341
  for (const entry of entries) { pending.delete(entry.id); reporter.error(entry.id, revisions.get(entry.id), error); }
296
342
  reporter.progress("idle");
297
343
  console.error(error);
298
344
  if (!watched) process.exitCode = 1;
345
+ return false;
299
346
  }
300
347
  }
301
348
  // Visual feedback and verified publication have separate lifecycles. Edits
@@ -339,7 +386,7 @@ export async function runScenarioCompiler(directory, { watched = false, validate
339
386
  candidate.build = Promise.resolve().then(() => {
340
387
  cache.assertCompiler();
341
388
  const cached = cachedPreviewPublication(options, candidate.entries, cache.graphRevision());
342
- if (cached && candidate.entries.every(entry => cache.reusable(entry, previewArtifactHtml(entry.id, cached.revision)))) { candidate.reused = true; return cached; }
389
+ if (cached && cache.reusableEntries(candidate.entries,cached.revision)) { candidate.reused = true; return cached; }
343
390
  return buildGraph(candidate.entries, options, track, { watched: true });
344
391
  });
345
392
  liveCandidate = candidate;
@@ -431,7 +478,26 @@ export async function runScenarioCompiler(directory, { watched = false, validate
431
478
  if (compiling) return;
432
479
  compiling = true;
433
480
  try {
434
- while (pending.size && !registryFailure && !stopped) {
481
+ while ((pending.size || fullRequest && fullRequest !== completedFull) && !stopped) {
482
+ if (fullRequest && fullRequest !== completedFull) {
483
+ const token = fullRequest, sourceRevision = previewSourceRevision(options);
484
+ // Production compilation and incremental compilation never overlap.
485
+ // The same process then serves this checked graph to verification.
486
+ if (verifying) { await new Promise(resolve => setTimeout(resolve, 20)); continue; }
487
+ let ok = false;
488
+ try {
489
+ entries = registry(); registryFailure = undefined;
490
+ reporter.setApps(buildApps()); reporter.clearFailure();
491
+ ok = await compileGraph();
492
+ } catch (error) {
493
+ registryFailure = error; failure(error);
494
+ } finally { releaseScenarioRegistry(root); }
495
+ completedFull = token;
496
+ const file = path.join(root, ".ds", `full-build-${reporter.session}.json`), temporary = `${file}.tmp`;
497
+ writeFileSync(temporary, JSON.stringify({ token, ok: !!ok, sourceRevision })); renameSync(temporary, file);
498
+ continue;
499
+ }
500
+ if (registryFailure) break;
435
501
  const id = pending.has(active) ? active : pending.values().next().value;
436
502
  pending.delete(id);
437
503
  const entry = entries.find(entry => entry.id === id);
@@ -463,6 +529,7 @@ export async function runScenarioCompiler(directory, { watched = false, validate
463
529
  try {
464
530
  const value = JSON.parse(readFileSync(file, "utf8"));
465
531
  if (value.session !== process.env.ADS_MCP_BUILD_SESSION) return;
532
+ if (typeof value.full === "string" && /^[\w-]{1,100}$/.test(value.full)) fullRequest = value.full;
466
533
  if (value.invalidation !== invalidation) {
467
534
  invalidation = value.invalidation;
468
535
  if (requested.size) sourceChanged("invalidate",options.config.dsDir,true);
@@ -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
@@ -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
@@ -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
@@ -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
@@ -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
@@ -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
  };
@@ -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,7 @@ 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 });
261
262
  // Queue all selected roots before parallel browser workers open. A
262
263
  // single graph avoids repeated compilation and startup handovers.
263
264
  await host.warmScenarios([...new Set(group.map(check => check.scenario).filter(Boolean))], signal);
@@ -354,7 +355,7 @@ export function createVerificationController(root, { reportRoot = root, onProgre
354
355
  }
355
356
  return verificationResult(diagnostics,results);
356
357
  } catch (error) { return verificationResult([{ rule: "behavior-verification", message: error.message }],results); }
357
- 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(); } }
358
359
  },
359
360
  };
360
361
  }
@@ -564,6 +564,34 @@ dependencies. An edit racing publication cannot associate previous output with
564
564
  newer inputs; it leaves the previous cache intact and requires the next build.
565
565
  A transferred checked graph can refresh older watcher metadata without recompiling
566
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.
567
595
 
568
596
  After the selected view paints, a connected showcase can prefetch changed peers'
569
597
  static resources into the App's existing byte cache. This bounded, opportunistic