@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
@@ -0,0 +1,106 @@
1
+ import { createHash, randomUUID } from "node:crypto";
2
+ import { existsSync, lstatSync, mkdirSync, readFileSync, readdirSync, realpathSync, renameSync, rmSync, writeFileSync } from "node:fs";
3
+ import path from "node:path";
4
+ import { loadConfig, isInside } from "./config.mjs";
5
+ import { inspectScenarios } from "./scenarios.mjs";
6
+ import { previewSourceRevision } from "./preview-inputs.mjs";
7
+ import { createScenarioProgram } from "./scenario-program.mjs";
8
+
9
+ const hash = value => createHash("sha256").update(value).digest("hex");
10
+ const filename = "scenario-registry.json";
11
+ const maxBytes = 8 * 1024 * 1024;
12
+ const programs = new Map();
13
+ export function releaseScenarioRegistry(root) {
14
+ programs.get(root)?.clear();
15
+ programs.delete(root);
16
+ }
17
+ function programFor(root) {
18
+ const program = programs.get(root) ?? createScenarioProgram();
19
+ programs.delete(root); programs.set(root, program);
20
+ while (programs.size > 2) { const oldest = programs.keys().next().value; programs.get(oldest).clear(); programs.delete(oldest); }
21
+ return program;
22
+ }
23
+ // A source checkout and a published build have different code even when their
24
+ // package versions match. Cache identities follow the actual discovery code.
25
+ const toolRevision = (() => {
26
+ const root = import.meta.dirname, rows = [];
27
+ function visit(directory) {
28
+ for (const entry of readdirSync(directory, { withFileTypes: true }).sort((a, b) => a.name.localeCompare(b.name))) {
29
+ const file = path.join(directory, entry.name);
30
+ if (entry.isDirectory() && !["skills", "bootstrap-ds", "showcase"].includes(entry.name)) visit(file);
31
+ else if (entry.isFile() && /\.(?:mjs|js|cjs|json)$/.test(entry.name)) rows.push([path.relative(root, file), hash(readFileSync(file))]);
32
+ }
33
+ }
34
+ visit(root);
35
+ return hash(JSON.stringify([rows, process.versions.bun ?? process.version, process.platform, process.arch]));
36
+ })();
37
+
38
+ function validRegistry(value, options) {
39
+ return value && Array.isArray(value.scenarios) && value.scenarios.length <= 10000
40
+ && value.scenarios.every(item => typeof item?.id === "string" && /^(?:tokens|components|patterns|composition)\/[\w./-]+$/.test(item.id)
41
+ && path.posix.normalize(item.id) === item.id && typeof item.title === "string"
42
+ && ["tokens", "components", "patterns", "composition"].includes(item.kind)
43
+ && typeof item.file === "string" && isInside(options.dsRoot, path.resolve(options.root, item.file))
44
+ && item.artifact === `.ds/scenarios/${item.id}/index.html` && Array.isArray(item.covers) && Array.isArray(item.tokens))
45
+ && Array.isArray(value.diagnostics) && value.diagnostics.every(item => typeof item?.message === "string" && typeof item.rule === "string");
46
+ }
47
+
48
+ function read(options, revision) {
49
+ const file = path.join(options.root, ".ds", filename);
50
+ try {
51
+ const stat = lstatSync(file);
52
+ if (!stat.isFile() || stat.nlink !== 1 || stat.size > maxBytes || realpathSync(file) !== file) return;
53
+ const snapshot = JSON.parse(readFileSync(file, "utf8"));
54
+ if (snapshot.schemaVersion === 1 && snapshot.root === options.root && snapshot.toolRevision === toolRevision
55
+ && snapshot.revision === revision && snapshot.digest === hash(JSON.stringify(snapshot.registry)) && validRegistry(snapshot.registry, options)) return snapshot.registry;
56
+ } catch { /* Missing/corrupt/generated data is a cache miss, never evidence. */ }
57
+ }
58
+
59
+ /** Read a current discovery snapshot without starting semantic analysis. */
60
+ export function readScenarioRegistry(options) {
61
+ return read(options, previewSourceRevision(options));
62
+ }
63
+
64
+ function write(options, revision, registry) {
65
+ const directory = path.join(options.root, ".ds"), file = path.join(directory, filename), temporary = `${file}.${randomUUID()}.tmp`;
66
+ try {
67
+ if (existsSync(directory) && realpathSync(directory) !== directory) return;
68
+ mkdirSync(directory, { recursive: true });
69
+ if (realpathSync(directory) !== directory) return;
70
+ const content = JSON.stringify({ schemaVersion: 1, root: options.root, toolRevision, revision, digest: hash(JSON.stringify(registry)), registry });
71
+ if (Buffer.byteLength(content) > maxBytes) return;
72
+ writeFileSync(temporary, content);
73
+ renameSync(temporary, file);
74
+ } catch { /* Read-only projects can still discover scenarios without caching. */ }
75
+ finally { try { rmSync(temporary, { force: true }); } catch { /* Optional cache cleanup must not prevent discovery. */ } }
76
+ }
77
+
78
+ /** Relocate metadata only after identical accepted source is in place. This
79
+ * never supplies passing checks; validation continues to inspect source. */
80
+ export function prepareScenarioRegistryTransfer(candidate, target) {
81
+ const revision = previewSourceRevision(candidate), registry = read(candidate, revision);
82
+ if (!registry) return null;
83
+ return () => {
84
+ if (previewSourceRevision(target) !== revision || !validRegistry(registry, target)) return false;
85
+ write(target, revision, registry);
86
+ return true;
87
+ };
88
+ }
89
+
90
+ /** Share semantic discovery between preview hosts and compiler processes.
91
+ * This snapshot contains metadata/diagnostics only, never validated outputs or
92
+ * passing check results. Validation continues to inspect source independently. */
93
+ export function discoverScenarioRegistry(options) {
94
+ for (let attempt = 0; attempt < 2; ++attempt) {
95
+ // Contract inspectors memoize TypeScript programs on options. A new source
96
+ // revision needs fresh options as well as a fresh registry.
97
+ const current = loadConfig(options.root), revision = previewSourceRevision(current);
98
+ const cached = read(current, revision);
99
+ if (cached) return cached;
100
+ const registry = inspectScenarios(current, programFor(current.root).build(current));
101
+ if (revision !== previewSourceRevision(loadConfig(current.root))) continue;
102
+ write(current, revision, registry);
103
+ return registry;
104
+ }
105
+ throw Object.assign(new Error("Sources changed during scenario discovery. Retry against the current source."), { code: "ADS_SCENARIO_SOURCE_CHANGED" });
106
+ }
@@ -3,33 +3,36 @@ 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 { inspectScenarios } from "./scenarios.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. */
19
22
  export function createPreviewCache(options, compilerFiles = []) {
20
23
  const { root } = options;
21
24
  const key = file => isInside(import.meta.dirname,file) ? `ads-tool/${path.relative(import.meta.dirname,file)}` : isInside(root,file) ? `project/${path.relative(root,file)}` : file;
22
- const adapterFiles = [import.meta.filename, ...["preview-builder.mjs", "preview-workers.mjs", "preview-files.mjs", "preview-inputs.mjs", "preview-resources.mjs", "preview-scope.mjs", "scenario-groups.mjs", "scenario-inspector.mjs", "scenarios-vite.mjs", "linaria.mjs", "linaria/atomic-css.cjs", "linaria/atomic-styled.cjs", "linaria/preserve-values.cjs"].map(file => path.join(import.meta.dirname, file)), ...compilerFiles,
25
+ const adapterFiles = [import.meta.filename, ...["preview-builder.mjs", "preview-workers.mjs", "preview-files.mjs", "preview-inputs.mjs", "preview-resources.mjs", "preview-scope.mjs", "scenario-groups.mjs", "scenario-inspector.mjs", "scenario-registry.mjs", "scenarios-vite.mjs", "linaria.mjs", "linaria/atomic-css.cjs", "linaria/atomic-styled.cjs", "linaria/preserve-values.cjs"].map(file => path.join(import.meta.dirname, file)), ...compilerFiles,
23
26
  ...["package.json", "package-lock.json", "bun.lock", "bun.lockb", "node_modules/.package-lock.json"].map(file => path.join(root, file))];
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,59 +48,108 @@ 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
  }
83
- function recordGraph(revision, entries) { value.graphRevision=revision;value.graphInputs=inputs();value.registry=entries;save(); }
84
- return { inputs, reusable, reload, snapshot: () => structuredClone(value), seed(state) { value=structuredClone(state);save(); }, graphRevision: () => value.graphRevision, recordGraph, validated: stamp => value.validation === stamp,
120
+ function recordCurrent(stamp, update) {
121
+ // Publication and dependency hashing can overlap the next external edit.
122
+ // Never attach the previous output to bytes newer than its compiled stamp.
123
+ if (inputs() !== stamp) return false;
124
+ const previous = value;
125
+ value = { ...value, entries: { ...value.entries }, dependencySets: { ...value.dependencySets } };
126
+ try {
127
+ update();
128
+ if (inputs() !== stamp) { value = previous; return false; }
129
+ save();
130
+ return true;
131
+ } catch (error) { value = previous; throw error; }
132
+ }
133
+ function graph(revision, entries, stamp) { value.graphRevision=revision;value.graphInputs=stamp;value.registry=entries; }
134
+ function recordGraph(revision, entries, stamp = inputs()) { return recordCurrent(stamp, () => graph(revision, entries, 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 }; }); },
85
138
  registry(stamp) {
86
139
  if(value.validation!==stamp || value.graphInputs!==stamp || !Array.isArray(value.registry) || !value.registry.length || value.registry.length>1000)return null;
87
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
88
141
  && typeof entry.file==="string" && isInside(options.dsRoot,path.resolve(root,entry.file))
89
- && entry.artifact===`.ds/scenarios/${entry.id}/index.html` && reusable(entry,previewArtifactHtml(entry.id,value.graphRevision)));
90
- 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;
91
144
  },
92
145
  assertCompiler() {
93
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" });
94
147
  },
95
148
  validate(stamp) { value.validation = stamp; save(); },
96
- recordAll(entries, dependencies, revision) { recordEntries(entries, dependencies); recordGraph(revision,entries); },
97
- record(entry, dependencies) {
98
- recordEntries([entry], dependencies);
99
- save();
149
+ recordAll(entries, dependencies, revision, stamp = inputs()) {
150
+ return recordCurrent(stamp, () => { recordEntries(entries, dependencies); graph(revision, entries, stamp); });
100
151
  },
152
+ record(entry, dependencies, stamp = inputs()) { return recordCurrent(stamp, () => recordEntries([entry], dependencies)); },
101
153
  };
102
154
  }
103
155
 
@@ -106,9 +158,9 @@ export function createPreviewCache(options, compilerFiles = []) {
106
158
  export function preparePreviewCache(candidate, target) {
107
159
  if (!candidate.config.mcp.previewManifest || candidate.config.framework !== target.config.framework || !target.config.mcp.previewManifest) return false;
108
160
  const file=path.join(candidate.root,".ds/preview-cache.json");
109
- 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;
110
162
  const state=JSON.parse(readFileSync(file,"utf8"));
111
- 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;
112
164
  const source=createPreviewCache(candidate,state.compilerFiles.map(file=>path.resolve(candidate.root,file)));
113
165
  const destination=createPreviewCache(target,state.compilerFiles.map(file=>path.resolve(target.root,file)));
114
166
  const stamp=source.inputs();
@@ -117,10 +169,12 @@ export function preparePreviewCache(candidate, target) {
117
169
  const publication=cachedPreviewPublication(candidate,entries,state.graphRevision,target);
118
170
  if(!publication || source.inputs()!==stamp)return false;
119
171
  const snapshot=source.snapshot();
172
+ const transferRegistry=prepareScenarioRegistryTransfer(candidate,target);
120
173
  return () => {
121
174
  if(destination.inputs()!==stamp)return false;
122
175
  publication.publish("accepted-mutation");
123
176
  destination.seed(snapshot);
177
+ transferRegistry?.();
124
178
  return {revision:publication.revision,scenarios:entries.map(entry=>entry.id)};
125
179
  };
126
180
  }
@@ -135,7 +189,7 @@ export async function runScenarioCompiler(directory, { watched = false, validate
135
189
  const cache = createPreviewCache(options, compilerFiles);
136
190
  function registry() {
137
191
  options = withPreviewSession(loadConfig(root), process.env.ADS_MCP_BUILD_SESSION);
138
- const result = inspectScenarios(options);
192
+ const result = discoverScenarioRegistry(options);
139
193
  if (result.diagnostics.length) throw Object.assign(new Error(result.diagnostics.map(item => `${item.file}: ${item.message}`).join("\n")), { scenarios: result.scenarios });
140
194
  mkdirSync(path.join(root, ".ds/scenarios"), { recursive: true });
141
195
  writeFileSync(path.join(root, ".ds/scenarios/manifest.json"), JSON.stringify({ schemaVersion: 1, scenarios: result.scenarios }, null, 2));
@@ -147,6 +201,7 @@ export async function runScenarioCompiler(directory, { watched = false, validate
147
201
  if (!watched) throw error;
148
202
  registryFailure = error; entries = error.scenarios ?? [];
149
203
  }
204
+ finally { if (watched && buildGraph) releaseScenarioRegistry(root); }
150
205
  const buildApps = () => entries.map(entry => ({ id: entry.id, file: previewArtifactPath(options, entry.artifact) }));
151
206
  const reporter = createBuildReporter(root, { apps: buildApps() });
152
207
  const requested = new Set();
@@ -156,10 +211,13 @@ export async function runScenarioCompiler(directory, { watched = false, validate
156
211
  let stopped = false;
157
212
  let generation = 0;
158
213
  let publishedStamp;
214
+ let publishedEntries = new Set();
159
215
  let validation;
160
216
  let observedSourceRevision = previewSourceRevision(options);
161
217
  let invalidation;
218
+ let fullRequest, completedFull;
162
219
  const inspector = watched && buildGraph ? createScenarioInspector(root) : null;
220
+ let discovering, unknownRevision;
163
221
  let liveCandidate, verifying = false;
164
222
  function failure(error) {
165
223
  try { reporter.failure(error); } catch (reportError) { console.error(reportError); }
@@ -218,7 +276,7 @@ export async function runScenarioCompiler(directory, { watched = false, validate
218
276
  if (failure) throw failure.reason;
219
277
  cache.assertCompiler();
220
278
  if (stopped || started !== generation || stamp !== cache.inputs()) return; // Watch queued a newer revision.
221
- if (!reuse) cache.record(entry, dependencies);
279
+ if (!reuse && !cache.record(entry, dependencies, stamp)) return;
222
280
  reporter.ready(entry.id, revision);
223
281
  reporter.progress("idle");
224
282
  } catch (error) {
@@ -254,12 +312,12 @@ export async function runScenarioCompiler(directory, { watched = false, validate
254
312
  } };
255
313
  cache.assertCompiler();
256
314
  const cached = cachedPreviewPublication(options, entries, cache.graphRevision());
257
- 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);
258
316
  if (reusable) {
259
317
  try { readPreviewManifest(options, { verify: true }); }
260
318
  catch { reusable = false; }
261
319
  }
262
- 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 }));
263
321
  const failure = outcomes.find(outcome => outcome.status === "rejected");
264
322
  if (failure) throw failure.reason;
265
323
  cache.assertCompiler();
@@ -267,20 +325,24 @@ export async function runScenarioCompiler(directory, { watched = false, validate
267
325
  const publication = outcomes[1].value;
268
326
  if (publication) {
269
327
  publication.publish(reporter.session);
270
- cache.recordAll(entries, dependencies, publication.revision);
328
+ if (!cache.recordAll(entries, dependencies, publication.revision, stamp)) return;
271
329
  } else {
272
330
  cached.publish(reporter.session);
273
- cache.recordGraph(cached.revision,entries);
331
+ if (!cache.recordGraph(cached.revision,entries,stamp)) return;
274
332
  }
275
333
  for (const entry of entries) { pending.delete(entry.id); reporter.ready(entry.id, revisions.get(entry.id)); }
276
334
  publishedStamp = stamp;
335
+ publishedEntries = new Set(entries.map(entry => entry.id));
336
+ cache.recordProduction(stamp);
277
337
  reporter.progress("idle");
338
+ return true;
278
339
  } catch (error) {
279
340
  if (started !== generation) return;
280
341
  for (const entry of entries) { pending.delete(entry.id); reporter.error(entry.id, revisions.get(entry.id), error); }
281
342
  reporter.progress("idle");
282
343
  console.error(error);
283
344
  if (!watched) process.exitCode = 1;
345
+ return false;
284
346
  }
285
347
  }
286
348
  // Visual feedback and verified publication have separate lifecycles. Edits
@@ -290,12 +352,20 @@ export async function runScenarioCompiler(directory, { watched = false, validate
290
352
  cache.reload();
291
353
  const sourceRevision = previewSourceRevision(options), stamp = cache.inputs();
292
354
  const prepared=cache.registry(stamp);
293
- if(prepared){entries=prepared;reporter.setApps(buildApps());}
294
- const candidate = { generation, stamp, sourceRevision, entries: [...entries], dependencies: new Set(), registryReused:!!prepared };
295
- // One multi-entry build covers every requested scenario in this revision.
296
- // Navigation must not enqueue the same shared graph once per visited entry.
355
+ // A guarded edit can publish a checked graph while this watcher's discovery
356
+ // still describes the previous revision. Adopt its current metadata before
357
+ // comparing registries. A partial watched graph cannot replace the catalogue.
358
+ if (prepared?.length === entries.length && prepared.every((entry, index) => entry.id === entries[index].id)) {
359
+ entries = prepared;
360
+ reporter.setApps(buildApps());
361
+ }
362
+ const registryReused = !!prepared && JSON.stringify(prepared) === JSON.stringify(entries);
363
+ const selected = registryReused ? prepared : entries.filter(entry => requested.has(entry.id));
364
+ const candidate = { generation, stamp, sourceRevision, registry: [...entries], entries: selected, dependencies: new Set(), registryReused };
365
+ // Retain roots requested by other mounted Apps, without compiling untouched
366
+ // catalogue entries. Production/unwatched builds still cover all entries.
297
367
  for (const entry of candidate.entries) pending.delete(entry.id);
298
- candidate.revisions = reporter.batch(() => new Map(entries.map(entry => [entry.id, reporter.begin(entry.id, { sourceRevision })])));
368
+ candidate.revisions = reporter.batch(() => new Map(candidate.entries.map(entry => [entry.id, reporter.begin(entry.id, { sourceRevision })])));
299
369
  reporter.progress("validation-and-compilation");
300
370
  const track = { name: "ads-live-preview-dependencies", generateBundle() {
301
371
  for (const id of this.getModuleIds()) {
@@ -316,7 +386,7 @@ export async function runScenarioCompiler(directory, { watched = false, validate
316
386
  candidate.build = Promise.resolve().then(() => {
317
387
  cache.assertCompiler();
318
388
  const cached = cachedPreviewPublication(options, candidate.entries, cache.graphRevision());
319
- 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; }
320
390
  return buildGraph(candidate.entries, options, track, { watched: true });
321
391
  });
322
392
  liveCandidate = candidate;
@@ -357,7 +427,7 @@ export async function runScenarioCompiler(directory, { watched = false, validate
357
427
  }
358
428
  // Give compiled feedback priority before starting CPU-heavy validation.
359
429
  // An already running check continues; later edits replace its candidate.
360
- const inspection=candidate.reused&&candidate.registryReused?Promise.resolve({scenarios:candidate.entries,diagnostics:[]}):inspector.inspect();
430
+ const inspection=candidate.reused&&candidate.registryReused?Promise.resolve({scenarios:candidate.registry,diagnostics:[]}):inspector.inspect();
361
431
  const outcomes = [compiled, ...await Promise.allSettled([gate(candidate.stamp), inspection])];
362
432
  if (stopped) return;
363
433
  if (candidate !== liveCandidate || candidate.generation !== generation || candidate.stamp !== cache.inputs()) {
@@ -368,7 +438,7 @@ export async function runScenarioCompiler(directory, { watched = false, validate
368
438
  if (outcomes[2].status === "rejected") throw outcomes[2].reason;
369
439
  const registry = outcomes[2].value;
370
440
  if (registry.diagnostics.length) throw new Error(registry.diagnostics.map(item => `${item.file}: ${item.message}`).join("\n"));
371
- if (JSON.stringify(registry.scenarios) !== JSON.stringify(candidate.entries)) {
441
+ if (JSON.stringify(registry.scenarios) !== JSON.stringify(candidate.registry)) {
372
442
  entries = registry.scenarios;
373
443
  writeFileSync(path.join(root, ".ds/scenarios/manifest.json"), JSON.stringify({ schemaVersion: 1, scenarios: entries }, null, 2));
374
444
  reporter.batch(() => { reporter.setApps(buildApps()); reporter.live(undefined); reporter.progress("idle"); });
@@ -386,14 +456,17 @@ export async function runScenarioCompiler(directory, { watched = false, validate
386
456
  const publication = outcomes[0].value;
387
457
  if (stopped || candidate !== liveCandidate || candidate.generation !== generation || candidate.stamp !== cache.inputs()) continue;
388
458
  publication.publish(reporter.session);
389
- if (!candidate.reused) cache.recordAll(candidate.entries, candidate.dependencies, publication.revision);
390
- else cache.recordGraph(publication.revision,candidate.entries);
459
+ const recorded = !candidate.reused
460
+ ? cache.recordAll(candidate.entries, candidate.dependencies, publication.revision, candidate.stamp)
461
+ : cache.recordGraph(publication.revision,candidate.entries,candidate.stamp);
462
+ if (!recorded) { if (candidate === liveCandidate) liveCandidate = undefined; continue; }
391
463
  reporter.batch(() => {
392
464
  for (const entry of candidate.entries) reporter.ready(entry.id, candidate.revisions.get(entry.id));
393
465
  reporter.live(undefined);
394
466
  reporter.progress("idle");
395
467
  });
396
468
  publishedStamp = candidate.stamp;
469
+ publishedEntries = new Set(candidate.entries.map(entry => entry.id));
397
470
  } catch (error) {
398
471
  if (!candidate.failed) rejectLive(candidate, error);
399
472
  }
@@ -405,7 +478,26 @@ export async function runScenarioCompiler(directory, { watched = false, validate
405
478
  if (compiling) return;
406
479
  compiling = true;
407
480
  try {
408
- 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;
409
501
  const id = pending.has(active) ? active : pending.values().next().value;
410
502
  pending.delete(id);
411
503
  const entry = entries.find(entry => entry.id === id);
@@ -414,24 +506,43 @@ export async function runScenarioCompiler(directory, { watched = false, validate
414
506
  } catch (error) { failure(error); }
415
507
  finally { compiling = false; }
416
508
  }
509
+ function discoverUnknownEntries() {
510
+ if (!inspector || discovering) return;
511
+ const revision = previewSourceRevision(options);
512
+ if (unknownRevision === revision) return;
513
+ unknownRevision = revision;
514
+ discovering = inspector.inspect().then(result => {
515
+ if (stopped) return;
516
+ if (previewSourceRevision(options) !== revision) { unknownRevision = undefined; return; }
517
+ if (result.diagnostics.length) throw new Error(result.diagnostics.map(item => `${item.file}: ${item.message}`).join("\n"));
518
+ if (JSON.stringify(result.scenarios) === JSON.stringify(entries)) return;
519
+ ++generation; entries = result.scenarios; registryFailure = undefined; liveCandidate = undefined;
520
+ reporter.setApps(buildApps());
521
+ writeFileSync(path.join(root, ".ds/scenarios/manifest.json"), JSON.stringify({ schemaVersion: 1, scenarios: entries }));
522
+ for (const id of requested) if (!entries.some(entry => entry.id === id)) requested.delete(id);
523
+ request();
524
+ }).catch(error => { if (!stopped) failure(error); }).finally(() => { discovering = undefined; });
525
+ }
417
526
  function request(startBuild = true) {
418
527
  const file = process.env.ADS_MCP_REQUEST_FILE;
419
528
  if (!file || !existsSync(file)) return;
420
529
  try {
421
530
  const value = JSON.parse(readFileSync(file, "utf8"));
422
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;
423
533
  if (value.invalidation !== invalidation) {
424
534
  invalidation = value.invalidation;
425
535
  if (requested.size) sourceChanged("invalidate",options.config.dsDir,true);
426
536
  }
427
537
  active = entries.find(entry => entry.artifact === value.active)?.id;
538
+ if (value.files.some(file => !entries.some(entry => entry.artifact === file))) discoverUnknownEntries();
428
539
  for (const file of value.files) {
429
540
  const entry = entries.find(entry => entry.artifact === file);
430
541
  if (entry && !requested.has(entry.id)) {
431
542
  requested.add(entry.id);
432
543
  const covered = liveCandidate && !liveCandidate.failed && liveCandidate.generation === generation
433
544
  && liveCandidate.stamp === cache.inputs() && liveCandidate.entries.some(item => item.id === entry.id);
434
- if (!buildGraph || publishedStamp !== cache.inputs() && !covered) pending.add(entry.id);
545
+ if (!buildGraph || (!publishedEntries.has(entry.id) || publishedStamp !== cache.inputs()) && !covered) pending.add(entry.id);
435
546
  }
436
547
  }
437
548
  if (startBuild) void drain();
@@ -476,7 +587,7 @@ export async function runScenarioCompiler(directory, { watched = false, validate
476
587
  } catch (error) {
477
588
  registryFailure = error; failure(error);
478
589
  }
479
- }, 100);
590
+ }, 16);
480
591
  }
481
592
  // Do not allocate recursive OS watches for node_modules or generated trees.
482
593
  const watchers = new Map();
@@ -41,7 +41,8 @@ export function publicUi(program, options) {
41
41
  export function inspectScenarios(options, suppliedProgram) {
42
42
  const { root, dsRoot } = options;
43
43
  const files = sourceFiles(dsRoot).filter(isScenarioFile);
44
- const program = suppliedProgram ?? inspectUnitContracts(options).program ?? ts.createProgram([path.join(dsRoot, options.config.publicEntry), path.join(dsRoot, options.config.reviewEntry), ...files], { ...projectCompilerOptions(options), allowJs: true });
44
+ const contracts = inspectUnitContracts(options, suppliedProgram);
45
+ const program = suppliedProgram ?? contracts.program ?? ts.createProgram([path.join(dsRoot, options.config.publicEntry), path.join(dsRoot, options.config.reviewEntry), ...files], { ...projectCompilerOptions(options), allowJs: true });
45
46
  const apis = scenarioApi(program, options);
46
47
  const duplicate = apis.find((item, index) => apis.some((other, otherIndex) => index !== otherIndex && item.name === other.name));
47
48
  const known = new Map(apis.filter(item => item.kind !== "controllers").map((item) => [item.name, item]));