@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,41 @@
1
+ /** A validation candidate owns the compiler budget until its checks finish.
2
+ * Published resources remain readable while idle preview compilers are parked. */
3
+ export function createPreviewWork() {
4
+ const watchers = new Set();
5
+ let active;
6
+ return {
7
+ register(watcher) {
8
+ watchers.add(watcher);
9
+ const lease = active;
10
+ if (lease) void watcher.suspend().then(() => { if (active !== lease) watcher.resume(); }).catch(error => {
11
+ if (active !== lease) watcher.resume();
12
+ process.stderr.write(`ads mcp: preview parking failed: ${error.message}\n`);
13
+ });
14
+ return () => watchers.delete(watcher);
15
+ },
16
+ async acquire(signal) {
17
+ while (active) {
18
+ if (signal?.aborted) throw new Error("Preview validation cancelled.");
19
+ await new Promise((resolve, reject) => {
20
+ const abort = () => { signal?.removeEventListener("abort", abort); reject(new Error("Preview validation cancelled.")); };
21
+ signal?.addEventListener("abort", abort, {once:true});
22
+ active.done.then(() => { signal?.removeEventListener("abort", abort); resolve(); });
23
+ });
24
+ }
25
+ if (signal?.aborted) throw new Error("Preview validation cancelled.");
26
+ let finish;
27
+ const lease = { done: new Promise(resolve => { finish = resolve; }) };
28
+ active = lease;
29
+ try { await Promise.all([...watchers].map(watcher => watcher.suspend())); }
30
+ catch (error) { for (const watcher of watchers) watcher.resume(); active = undefined; finish(); throw error; }
31
+ let released = false;
32
+ return () => {
33
+ if (released) return;
34
+ released = true;
35
+ for (const watcher of watchers) watcher.resume();
36
+ if (active === lease) active = undefined;
37
+ finish();
38
+ };
39
+ },
40
+ };
41
+ }
@@ -1,16 +1,16 @@
1
- import { existsSync, readFileSync, statSync } from "node:fs";
1
+ import { existsSync, readFileSync, statSync, watch } from "node:fs";
2
2
  import path from "node:path";
3
3
  import { Server, ProtocolError, INVALID_PARAMS, ResourceNotFoundError } from "@modelcontextprotocol/server";
4
4
  import { serveStdio, StdioServerTransport } from "@modelcontextprotocol/server/stdio";
5
5
  import { z } from "zod";
6
- import { checkProject } from "../check.mjs";
6
+ import { checkCandidate } from "../validation-checks.mjs";
7
7
  import { createValidationController } from "../validation.mjs";
8
8
  import { loadConfig, sourceFiles } from "../config.mjs";
9
9
  import { createVerificationController, BEHAVIOR_URI } from "../verification.mjs";
10
10
  import { INVESTIGATIONS_URI, investigationIndex, investigationPage, investigationSections, readInvestigation, readInvestigationResource } from "../investigations.mjs";
11
11
  import { failure } from "../evidence.mjs";
12
12
  import { inspectTokens } from "../tokens.mjs";
13
- import { inspectScenarios } from "../scenarios.mjs";
13
+ import { discoverScenarioRegistry, releaseScenarioRegistry } from "../scenario-registry.mjs";
14
14
  import { scenarioGroupFingerprint } from "../scenario-groups.mjs";
15
15
  import { startShowcaseHost } from "./showcase-host.mjs";
16
16
  import { createSkillStore, page, SKILLS_EXTENSION } from "./skills.mjs";
@@ -23,11 +23,13 @@ import { createReconfigurablePreviewWatch } from "./preview-watch.mjs";
23
23
  import { BUILD_URI, buildFailure, inspectBuildStatus, summarizeBuild } from "./build-status.mjs";
24
24
  import { GUIDE_URI, projectContext, projectGuide, serverInstructions, workflow } from "./context.mjs";
25
25
  import { createMutationController, mutationLimits } from "./mutations.mjs";
26
+ import { createPreviewWork } from "./preview-work.mjs";
26
27
  import { prepareUnitPatch, storePreparedPatch } from "./edit-preparation.mjs";
27
28
  import { reconcileTokenSamples } from "../token-fixtures.mjs";
28
29
  import { createCaptureController } from "../capture.mjs";
29
30
  import { CAPTURES_URI, captureSpec, screenshotFields } from "../capture-store.mjs";
30
31
  import { previewSourceRevision } from "../preview-inputs.mjs";
32
+ import { inspectBehaviorLibraries } from "../behavior-libraries.mjs";
31
33
  import { createExecutionResults, RESULTS_URI, resultSections } from "./execution-results.mjs";
32
34
  import { behaviorPage, behaviorSections } from "./behavior-pages.mjs";
33
35
  import { compactProgress, resultBudgets } from "./result-pages.mjs";
@@ -63,24 +65,36 @@ function resourceQuery(uri, allowed) {
63
65
  return Object.fromEntries([...url.searchParams].map(([key,value])=>[key,["limit","recordIndex","offset","chars"].includes(key)?Number(value):value]));
64
66
  }
65
67
 
66
- export function createAdsMcp(directory, { era = "legacy", skillDirectory, pollInterval = 1000, observeChanges = true, previewWatch, showcaseUrl, notifications, inspection, mutations = false } = {}) {
68
+ export function createAdsMcp(directory, { era = "legacy", skillDirectory, pollInterval = 1000, observeChanges = true, previewWatch, showcaseUrl, notifications, inspection, mutations = false, onBuildChange } = {}) {
67
69
  const root = path.resolve(directory);
70
+ let observationClosed = false;
68
71
  const cache = inspection ?? {};
69
72
  const skills = cache.skills ??= createSkillStore(skillDirectory);
70
73
  const captures = cache.captures ??= createCaptureController(root);
71
- const edits = cache.edits ??= createMutationController(root, { captures });
72
- const drafts = cache.drafts ??= createDraftController(root, { edits, startPreview: workspace => startAdsMcp(workspace, { stdio: false, mutations: false }) });
73
- const verification = cache.verification ??= createVerificationController(root);
74
- const validation = cache.validation ??= createValidationController(root);
74
+ const edits = cache.edits ??= createMutationController(root, { captures, previewWork: cache.previewWork });
75
+ const draftObservers = cache.draftObservers ??= new Set();
76
+ const drafts = cache.drafts ??= createDraftController(root, { edits, prewarm: true,
77
+ onChange: () => { for (const observer of draftObservers) void observer().catch(error => { process.stderr.write(`ads mcp: ${error.message}\n`); }); },
78
+ startPreview: workspace => startAdsMcp(workspace, { stdio: false, mutations: false, previewWork: cache.previewWork }) });
79
+ const verification = cache.verification ??= createVerificationController(root, { previewWork: cache.previewWork });
80
+ const validation = cache.validation ??= createValidationController(root, { previewWork: cache.previewWork });
75
81
  const executionResults = cache.executionResults ??= createExecutionResults(root);
76
82
  const reports = cache.reports ??= createReportStore(root, { context: reportContext, resolveEvidence: reportEvidence });
77
83
  let options = loadConfig(root);
78
84
  const signature = `${root}:${JSON.stringify(options.config)}`;
79
85
  if (cache.signature !== signature) {
80
86
  cache.signature = signature;
87
+ cache.behaviorLibraries = undefined;
81
88
  cache.registry = cache.catalog = cache.documents = undefined;
82
89
  }
83
90
  const getShowcaseUrl = () => showcaseUrl?.() ?? options.config.mcp.showcaseUrl;
91
+ async function architecture(signal) {
92
+ let release;
93
+ try {
94
+ if (cache.previewWork) release = await cache.previewWork.acquire(signal);
95
+ return await checkCandidate(root, signal);
96
+ } finally { release?.(); }
97
+ }
84
98
  function scenarioUrl(id) {
85
99
  const base = getShowcaseUrl();
86
100
  if (!base) return null;
@@ -96,16 +110,24 @@ export function createAdsMcp(directory, { era = "legacy", skillDirectory, pollIn
96
110
  capabilities: { tools: { listChanged: true }, resources: { listChanged: true, subscribe: true }, prompts: {},
97
111
  extensions: { "io.modelcontextprotocol/ui": { mimeTypes: [APP_MIME] }, ...(era === "modern" ? { [SKILLS_EXTENSION]: { directoryRead: true } } : {}) } },
98
112
  });
99
- const getRegistry = () => { cache.registry ??= inspectScenarios(options); cache.lastRegistry = cache.registry; return cache.registry; };
113
+ const getRegistry = () => {
114
+ const current = loadConfig(root), revision = previewSourceRevision(current);
115
+ if (!cache.registry || cache.registryRevision !== revision) {
116
+ try { cache.registry = discoverScenarioRegistry(current); }
117
+ finally { releaseScenarioRegistry(root); }
118
+ cache.registryRevision = revision; cache.catalog = undefined; cache.behaviorLibraries = undefined;
119
+ }
120
+ cache.lastRegistry = cache.registry; return cache.registry;
121
+ };
100
122
  const previewRegistry = waitFor => waitFor === "compiled" ? cache.registry ?? cache.lastRegistry ?? getRegistry() : getRegistry();
101
123
  function captureInventory() {
102
- const current = loadConfig(root), registry = inspectScenarios(current);
124
+ const current = loadConfig(root), registry = getRegistry();
103
125
  return { ...registry, revision: previewSourceRevision(current) };
104
126
  }
105
127
  function captureIndex() { const inventory = captureInventory(); return captures.store.list(inventory.scenarios, inventory.revision, { prune: !inventory.diagnostics.length }); }
106
128
  const scenarioApps = (quick = false) => (quick ? cache.registry ?? cache.lastRegistry ?? getRegistry() : getRegistry()).scenarios.map(item => ({ id: item.id, title: item.title, kind: item.kind, ...(item.samples ? { samples: item.samples } : {}), file: item.artifact }));
107
129
  const tokenScenarios = () => {
108
- const references=drafts.list({unit:"tokens",limit:100000}).drafts.map(({id,title,revision,state})=>({id,title,revision,state}));
130
+ const references=drafts.list({unit:"tokens",limit:100000}).drafts.map(({id,title,revision,state,preview})=>({id,title,revision,state,preview}));
109
131
  return getRegistry().scenarios.filter(item => item.kind === "tokens").map(item => ({ id:item.id,title:item.title,count:item.tokens.length,drafts:references }));
110
132
  };
111
133
  const allApps = (quick = false) => [...options.config.mcp.apps, ...scenarioApps(quick)];
@@ -122,18 +144,20 @@ export function createAdsMcp(directory, { era = "legacy", skillDirectory, pollIn
122
144
  if (!manifest?.scenarios.some(entry => entry.id === id)) throw new Error("The preview resource graph is not ready for this scenario. Rebuild previews.");
123
145
  return { manifestUri: live ? LIVE_PREVIEW_MANIFEST_URI : PREVIEW_MANIFEST_URI, manifestRevision: manifest.revision };
124
146
  }
125
- const getCatalog = () => cache.catalog ??= inspectCatalog(options, getRegistry().scenarios);
147
+ const getCatalog = () => { const registry = getRegistry(); return cache.catalog ??= inspectCatalog(loadConfig(root), registry.scenarios, getBehaviorLibraries()); };
148
+ const getBehaviorLibraries = () => cache.behaviorLibraries ??= inspectBehaviorLibraries(loadConfig(root));
126
149
  function annotateDrafts(items) {
127
150
  const found = drafts.list({limit:100000}).drafts, units = edits.units();
128
151
  return items.map(item => {
129
152
  const unit = units.find(unit => unit.files.includes(item.file))?.id ?? null;
130
- return { ...item, unit, drafts: found.filter(draft => draft.units.includes(unit)).map(({id,title,revision,state}) => ({id,title,revision,state})) };
153
+ return { ...item, unit, drafts: found.filter(draft => draft.units.includes(unit)).map(({id,title,revision,state,preview}) => ({id,title,revision,state,preview})) };
131
154
  });
132
155
  }
133
156
  const getDocuments = () => cache.documents ??= projectDocuments(options);
134
157
  const builds = () => {
135
158
  previewWatch?.setApps(allApps(true));
136
- return previewWatch?.buildStatus() ?? inspectBuildStatus(root, { ...options.config.mcp, apps: allApps(true) });
159
+ const report = previewWatch?.buildStatus() ?? inspectBuildStatus(root, { ...options.config.mcp, apps: allApps(true) });
160
+ return { ...report, drafts: drafts.previewStatuses() };
137
161
  };
138
162
  const previews = () => options.config.mcp.apps.map((app) => ({ id: app.id, title: app.title, kind: app.kind, tool: `ads_show_${app.id.replaceAll("-", "_")}`, resourceUri: appUri(app.id), available: existsSync(path.resolve(root, app.file)), file: app.file }));
139
163
 
@@ -184,6 +208,7 @@ export function createAdsMcp(directory, { era = "legacy", skillDirectory, pollIn
184
208
  { uri: `${PROJECT_URI}/tokens`, name: "Project token values and themes", mimeType: "application/json" },
185
209
  { uri: `${PROJECT_URI}/catalog`, name: "Public components and patterns", mimeType: "application/json" },
186
210
  { uri: DRAFTS_URI, name: "Tracked ADS drafts and acceptance events", mimeType: "application/json" },
211
+ ...drafts.previewStatuses().map(({ id, resourceUri }) => ({ uri: resourceUri, name: `Draft ${id}: preview build status and diagnostics`, mimeType: "application/json" })),
187
212
  { uri: "ads://guides/drafts", name: "Auto-mode tracked draft workflow", mimeType: "text/markdown" },
188
213
  { uri: `${PROJECT_URI}/scenarios`, name: "Independently mountable scenarios", mimeType: "application/json" },
189
214
  { uri: BEHAVIOR_URI, name: "Behavior contracts, demonstrations and current verification evidence", mimeType: "application/json" },
@@ -207,17 +232,18 @@ export function createAdsMcp(directory, { era = "legacy", skillDirectory, pollIn
207
232
  }
208
233
  function status() {
209
234
  const context = project(), mutationState = mutations ? edits.status() : null, behaviorState = verification.status();
210
- return { projectRoot: root, workflow: workflow([...previews(), ...scenarioApps()]), project: context,
211
- package: pkg.name, version: pkg.version, dsDir: options.config.dsDir, publicAlias: options.config.publicAlias,
212
- components: getCatalog().filter((item) => item.kind === "components" && item.apiKind === "ui").length,
213
- patterns: getCatalog().filter((item) => item.kind === "patterns" && item.apiKind === "ui").length,
235
+ const catalog = getCatalog(), registry = cache.registry;
236
+ return { projectRoot: root, workflow: workflow([...previews(), ...scenarioApps(true)]), project: context,
237
+ package: pkg.name, version: pkg.version, dsDir: options.config.dsDir, publicAlias: options.config.publicAlias, behaviorLibraries: getBehaviorLibraries().libraries,
238
+ components: catalog.filter((item) => item.kind === "components" && item.apiKind === "ui").length,
239
+ patterns: catalog.filter((item) => item.kind === "patterns" && item.apiKind === "ui").length,
214
240
  tokenCount: inspectTokens(root).tokens.length, showcaseUrl: getShowcaseUrl(),
215
241
  previewWatch: previewWatch?.status() ?? { state: "disabled" },
216
242
  mutations: mutations ? { ...mutationState, progress: compactProgress(mutationState.progress), lastResult: executionResults.latest("mutation") } : { enabled: false },
217
243
  drafts: { mode:"auto", enabled:mutations, resourceUri:DRAFTS_URI, listTool:"ads_drafts", previewTool:"ads_show_draft", acceptTool:"ads_accept", previewOnly:isDraftPreviewWorkspace(root), events:drafts.events().slice(-3) },
218
244
  build: summarizeBuild(builds()),
219
245
  previews: previews(), skills: skills.skills.map(({ uri, frontmatter }) => ({ uri, name: frontmatter.name, description: frontmatter.description })),
220
- scenarios: { count: getRegistry().scenarios.length, diagnostics: getRegistry().diagnostics, resourceUri: `${PROJECT_URI}/scenarios`, tool: "ads_show_scenario" },
246
+ scenarios: { count: registry.scenarios.length, diagnostics: registry.diagnostics, resourceUri: `${PROJECT_URI}/scenarios`, tool: "ads_show_scenario" },
221
247
  validation: { ...validation.status(), tool: "ads_validate", lastResult: executionResults.latest("validation") },
222
248
  behaviors: { resourceUri: BEHAVIOR_URI, discoveryTool: "ads_behaviors", verificationTool: "ads_verify", investigationTool: "ads_investigate", investigationResourceUri: INVESTIGATIONS_URI, ...behaviorState, progress: compactProgress(behaviorState.progress), lastResult: executionResults.latest("verification"), resultsTool: "ads_results", resultsResourceUri: RESULTS_URI },
223
249
  captures: { resourceUri: CAPTURES_URI, tool: "ads_capture", clearTool: "ads_capture_clear", ...captures.status() },
@@ -252,7 +278,7 @@ export function createAdsMcp(directory, { era = "legacy", skillDirectory, pollIn
252
278
  else if (uri === `${PROJECT_URI}/catalog`) value = { items: annotateDrafts(getCatalog()) };
253
279
  else if (uri === DRAFTS_URI) value = drafts.list();
254
280
  else if (uri === `${PROJECT_URI}/scenarios`) value = getRegistry();
255
- else if (uri === `${PROJECT_URI}/checks`) value = checkProject(root);
281
+ else if (uri === `${PROJECT_URI}/checks`) value = await architecture(signal);
256
282
  else if (uri === BEHAVIOR_URI || uri.startsWith(`${BEHAVIOR_URI}?`)) value = behaviorPage(options, resourceQuery(uri, ["unit", "api", "query", "section", "cursor", "limit"]));
257
283
  else if (uri === INVESTIGATIONS_URI || uri.startsWith(`${INVESTIGATIONS_URI}?`)) value = investigationPage(root, resourceQuery(uri, ["unit", "check", "runId", "section", "cursor", "limit", "recordIndex", "offset", "chars"]));
258
284
  else if (uri === RESULTS_URI || uri.startsWith("ads://results/")) return { contents: [executionResults.readResource(uri)] };
@@ -371,8 +397,10 @@ export function createAdsMcp(directory, { era = "legacy", skillDirectory, pollIn
371
397
  return json({ total: matches.length, items: annotateDrafts(matches.slice(0, limit)), resourceUri: `${PROJECT_URI}/catalog` });
372
398
  } },
373
399
  { name: "ads_scenarios", description: "Find an independently mountable token, component, pattern or composition preview. IDs derive from source filenames. Optional group labels are derived from folder names and searchable; group is discovery output, never scenario metadata. covers lists rendered public UI, exercises lists behavioral APIs and tokens lists the real token inputs. Use ads_show_scenario with an exact returned id. Showcase and MCP use this same registry.", schema: query.extend({ kind: z.enum(["tokens", "components", "patterns", "composition"]).optional(), offset: z.number().int().min(0).default(0) }), call: ({ query: search = "", limit, kind, offset }) => {
374
- const matches = getRegistry().scenarios.filter(item => (!kind || item.kind === kind) && `${item.id} ${item.title} ${item.group ?? ""} ${item.covers.join(" ")} ${(item.exercises ?? []).join(" ")} ${item.tokens.join(" ")}`.toLowerCase().includes(search.toLowerCase()));
375
- return json({ total: matches.length, scenarios: annotateDrafts(matches.slice(offset, offset + limit)), ...(offset + limit < matches.length ? { nextOffset: offset + limit } : {}), diagnostics: getRegistry().diagnostics, resourceUri: `${PROJECT_URI}/scenarios` });
400
+ const registry = getRegistry();
401
+ const matches = registry.scenarios.filter(item => (!kind || item.kind === kind) && `${item.id} ${item.title} ${item.group ?? ""} ${item.covers.join(" ")} ${(item.exercises ?? []).join(" ")} ${item.tokens.join(" ")}`.toLowerCase().includes(search.toLowerCase()));
402
+ const report = builds(), states = new Map(report.previews.map(item => [item.id, item]));
403
+ return json({ total: matches.length, scenarios: annotateDrafts(matches.slice(offset, offset + limit)).map(item => ({ ...item, build: summarizeBuild(states.get(item.id)) })), ...(offset + limit < matches.length ? { nextOffset: offset + limit } : {}), diagnostics: registry.diagnostics, resourceUri: `${PROJECT_URI}/scenarios` });
376
404
  } },
377
405
  { name: "ads_show_scenario", title: "Scenario preview", description: "Render one real scenario with its fixtures. Discover its exact id first. Default waitFor: verified waits for successful current checks. Interactive browsers may request waitFor: compiled for unverified live feedback or a retained earlier view; inspect build.current and never use pending output as verification evidence. Requires MCP Apps and resource forwarding; fallback links to the same showcase scenario.", schema: z.object({ id: z.string().min(1).max(256), waitFor: z.enum(["verified", "compiled"]).default("verified") }).strict(), _meta: { ui: { resourceUri: scenarioWidget() } }, call: async ({ id, waitFor }, signal) => {
378
406
  const registry = previewRegistry(waitFor);
@@ -390,8 +418,8 @@ export function createAdsMcp(directory, { era = "legacy", skillDirectory, pollIn
390
418
  const matches = inventory.tokens.filter((token) => token.name.toLowerCase().includes(search.toLowerCase()));
391
419
  return json({ total: matches.length, tokens: matches.slice(0, limit), categories: tokenScenarios(), tokenGroups:drafts.tokenGroups(), diagnosticCount: inventory.diagnostics.length, resourceUri: `${PROJECT_URI}/tokens` });
392
420
  } },
393
- { name: "ads_check", description: "Run read-only core ADS architecture checks; returns blocking diagnostics separately from nonblocking advisories, with warnings before informational limits. Atomic warnings include helper/forwarded-class paths and ads://guides/atomic-styles guidance; unresolved paths do not establish safe composition. Project Oxlint, typecheck, build and browser tests remain separate.", schema: z.object({ limit: z.number().int().min(1).max(50).default(20) }).strict(), call: ({ limit }) => {
394
- const result = checkProject(root);
421
+ { name: "ads_check", description: "Run read-only core ADS architecture checks; returns blocking diagnostics separately from nonblocking advisories, with warnings before informational limits. Atomic warnings include helper/forwarded-class paths and ads://guides/atomic-styles guidance; unresolved paths do not establish safe composition. Project Oxlint, typecheck, build and browser tests remain separate.", schema: z.object({ limit: z.number().int().min(1).max(50).default(20) }).strict(), call: async ({ limit }, signal) => {
422
+ const result = await architecture(signal);
395
423
  return json({ ok: result.ok, acceptance:result.acceptance, total: result.diagnostics.length, diagnostics: result.diagnostics.slice(0, limit), advisoryCount: result.advisories?.length ?? 0, advisories: (result.advisories ?? []).slice(0, limit), resourceUri: `${PROJECT_URI}/checks` });
396
424
  } },
397
425
  { name: "ads_skills", description: "Select one ADS workflow after ads_status: ads-designer for building/refining/debugging UI; ads-port for a library reference; ads-import for another project's ADS; ads-motion for animation; ads-break-ui for stress testing. Then read that workflow with ads_read_skill. Listing does not activate a native skill.", schema: empty, call: () => json({ skills: skills.skills.map(({ uri, frontmatter }) => ({ uri, ...frontmatter })) }) },
@@ -485,6 +513,7 @@ export function createAdsMcp(directory, { era = "legacy", skillDirectory, pollIn
485
513
  return { resources: listing.items, ...(listing.nextCursor ? { nextCursor: listing.nextCursor } : {}) };
486
514
  });
487
515
  server.setRequestHandler("resources/templates/list", () => ({ resourceTemplates: [
516
+ { uriTemplate: "ads://drafts/{id}/resource?uri=ads%3A%2F%2Fproject%2Fbuild", name: "Draft preview build status", description: "Use preview.resourceUri from ads_drafts or ads://project/build. Available while the draft preview session is active; updates on build completion and failure.", mimeType: "application/json" },
488
517
  { uriTemplate: "ads://captures/{key}/{slot}", name: "Current/candidate screenshot", description: "Exact keys and available slots come from ads://project/captures. Slots are replaced in place, not revision history.", mimeType: "image/png" },
489
518
  { uriTemplate: "ads://results/{resultId}", name: "Saved execution summary", description: "Use resultId from execution or ads://project/results. Query section/status/cursor/limit for pages, or section/recordIndex/offset/chars for exact record ranges. Only the latest result of each kind remains available.", mimeType: "application/json" },
490
519
  { uriTemplate: "ads://investigations/{unit}/{check}", name: "Latest check investigation", description: "Use encoded unit/check segments from ads://project/investigations. One latest bundle per check, including candidate verification.", mimeType: "application/json" },
@@ -536,6 +565,8 @@ export function createAdsMcp(directory, { era = "legacy", skillDirectory, pollIn
536
565
  const artifactFingerprint = () => fileFingerprint(allApps(true).map(app => path.resolve(root, previewArtifactPath(previewOptions(), app.file))));
537
566
  const assetFingerprint = () => resourceAssets().map(asset => asset.uri).sort().join("\n");
538
567
  let previous, previousArtifacts, previousAssets, previousBuild, previousCaptures, previousCaptureUris, previousDrafts;
568
+ let previousDraftBuilds = new Map();
569
+ const draftBuilds = () => new Map(drafts.previewStatuses().map(build => [build.resourceUri, JSON.stringify(build)]));
539
570
  const investigationFingerprint=()=>fileFingerprint([path.join(root,".ds/investigations.json")]);
540
571
  let previousInvestigations, previousResults, observing=false;
541
572
  function initializeObservation() {
@@ -544,12 +575,31 @@ export function createAdsMcp(directory, { era = "legacy", skillDirectory, pollIn
544
575
  previousCaptures=captures.store.fingerprint();previousCaptureUris=captures.store.resourceUris();
545
576
  previousInvestigations=investigationFingerprint();previousResults=executionResults.fingerprint();observing=true;
546
577
  previousDrafts=drafts.fingerprint();
578
+ previousDraftBuilds=draftBuilds();
547
579
  }
548
580
  // Modern HTTP serves a fresh protocol instance per request. Its shared observer
549
581
  // already tracks changes; immutable byte reads need no source/build scan.
550
582
  if (observeChanges) initializeObservation();
551
583
  let deferredDiscovery = false;
552
- async function refresh(force = false) {
584
+ let refreshing, refreshAgain = false, refreshForced = false;
585
+ function refresh(force = false) {
586
+ if (observationClosed) return Promise.resolve(false);
587
+ // Stateless HTTP handlers share the persistent observer. Starting their own
588
+ // observation after every mutation would force a false source change and
589
+ // throw away accepted discovery/capture caches on each draft edit.
590
+ if (!observeChanges) return Promise.all([...draftObservers].map(observer => observer(force))).then(values => values.some(Boolean));
591
+ refreshAgain = true; refreshForced ||= force;
592
+ return refreshing ??= Promise.resolve().then(async () => {
593
+ let changed = false;
594
+ while (refreshAgain && !observationClosed) {
595
+ refreshAgain = false;
596
+ const forced = refreshForced; refreshForced = false;
597
+ changed = await refreshOnce(forced) || changed;
598
+ }
599
+ return changed;
600
+ }).finally(() => { refreshing = undefined; });
601
+ }
602
+ async function refreshOnce(force) {
553
603
  if (!observing) { initializeObservation();force=true; }
554
604
  // Polling covers replaced files and new directories consistently across OSes.
555
605
  cache.documents = undefined;
@@ -559,20 +609,26 @@ export function createAdsMcp(directory, { era = "legacy", skillDirectory, pollIn
559
609
  const build = JSON.stringify(builds());
560
610
  const filesChanged = force || next !== previous;
561
611
  const buildChanged = build !== previousBuild;
612
+ if (buildChanged) onBuildChange?.(JSON.parse(build));
562
613
  const artifactsChanged = artifacts !== previousArtifacts;
563
614
  const assetsChanged = assets !== previousAssets;
564
615
  const capturesChanged = captures.store.fingerprint() !== previousCaptures;
565
616
  const investigationsChanged=investigationFingerprint()!==previousInvestigations;
566
617
  const resultsChanged=executionResults.fingerprint()!==previousResults;
567
618
  const draftFingerprint=drafts.fingerprint(),draftsChanged=draftFingerprint!==previousDrafts;
619
+ const currentDraftBuilds=draftBuilds();
620
+ const changedDraftBuilds=[...new Set([...previousDraftBuilds.keys(),...currentDraftBuilds.keys()])].filter(uri=>previousDraftBuilds.get(uri)!==currentDraftBuilds.get(uri));
621
+ const draftResourcesChanged=[...previousDraftBuilds.keys()].some(uri=>!currentDraftBuilds.has(uri)) || [...currentDraftBuilds.keys()].some(uri=>!previousDraftBuilds.has(uri));
568
622
  if (!filesChanged && !buildChanged && !artifactsChanged && !assetsChanged && !capturesChanged && !investigationsChanged && !resultsChanged && !draftsChanged && !deferredDiscovery) return false;
569
623
  if (filesChanged) {
570
624
  const updated = loadConfig(root);
571
625
  await previewWatch?.reconfigure?.(updated.config.mcp);
626
+ if (observationClosed) return false;
572
627
  const appsChanged = JSON.stringify(updated.config.mcp.apps) !== JSON.stringify(options.config.mcp.apps) || updated.config.mcp.previewManifest !== options.config.mcp.previewManifest;
573
628
  options = updated;
574
629
  cache.signature = `${root}:${JSON.stringify(options.config)}`;
575
630
  cache.catalog = undefined;
631
+ cache.behaviorLibraries = undefined;
576
632
  cache.registry = undefined;
577
633
  previous = fingerprint();
578
634
  if (appsChanged) { if (notifications) notifications.toolsChanged(); else await server.sendToolListChanged(); }
@@ -583,13 +639,15 @@ export function createAdsMcp(directory, { era = "legacy", skillDirectory, pollIn
583
639
  deferredDiscovery ||= filesChanged;
584
640
  const discoveryChanged = deferredDiscovery && !checking;
585
641
  if (discoveryChanged) deferredDiscovery = false;
586
- if (discoveryChanged || assetsChanged) { if (notifications) notifications.resourcesChanged(); else await server.sendResourceListChanged(); }
642
+ if (discoveryChanged || assetsChanged || draftResourcesChanged) { if (notifications) notifications.resourcesChanged(); else await server.sendResourceListChanged(); }
587
643
  previousArtifacts = artifactFingerprint();
588
644
  previousAssets = assetFingerprint();
589
645
  previousBuild = JSON.stringify(builds());
590
- const targets = discoveryChanged ? era === "modern" ? resources().map((entry) => entry.uri).filter((uri) => !skills.files.has(uri)) : [...subscribed]
646
+ const targets = discoveryChanged ? (era === "modern" ? resources().map((entry) => entry.uri).filter((uri) => !skills.files.has(uri)) : [...subscribed]).filter(uri => !uri.startsWith("ads://drafts/"))
591
647
  : [BUILD_URI, BEHAVIOR_URI, INVESTIGATIONS_URI, DRAFTS_URI, `${PROJECT_URI}/status`, ...(filesChanged ? [`${PROJECT_URI}/tokens`] : []), ...(options.config.mcp.previewManifest ? [PREVIEW_MANIFEST_URI, LIVE_PREVIEW_MANIFEST_URI] : []), ...(artifactsChanged ? allApps(true).map(app => appUri(app.id)) : [])].filter((uri) => era === "modern" || subscribed.has(uri));
592
648
  if(draftsChanged){targets.push(...[DRAFTS_URI,`${PROJECT_URI}/catalog`,`${PROJECT_URI}/scenarios`,`${PROJECT_URI}/status`].filter(uri=>era==="modern"||subscribed.has(uri)));previousDrafts=draftFingerprint;}
649
+ targets.push(...changedDraftBuilds.filter(uri=>era==="modern"||subscribed.has(uri)));
650
+ previousDraftBuilds=currentDraftBuilds;
593
651
  if(resultsChanged){targets.push(...[RESULTS_URI,...executionResults.index().results.map(entry=>entry.resourceUri),...[...subscribed].filter(uri=>uri.startsWith("ads://results/"))].filter(uri=>era==="modern"||subscribed.has(uri)));previousResults=executionResults.fingerprint();}
594
652
  if(investigationsChanged){targets.push(...[INVESTIGATIONS_URI,...investigationIndex(root).entries.map(entry=>entry.resourceUri),...[...subscribed].filter(uri=>uri.startsWith("ads://investigations/"))].filter(uri=>era==="modern"||subscribed.has(uri)));previousInvestigations=investigationFingerprint();}
595
653
  if (capturesChanged || discoveryChanged) {
@@ -598,34 +656,67 @@ export function createAdsMcp(directory, { era = "legacy", skillDirectory, pollIn
598
656
  previousCaptureUris = current;
599
657
  previousCaptures = captures.store.fingerprint();
600
658
  }
601
- for (const uri of new Set(targets)) { if (notifications) notifications.resourceUpdated(uri); else await server.sendResourceUpdated({ uri }); }
659
+ for (const uri of new Set(targets)) {
660
+ if (observationClosed) return false;
661
+ if (notifications) notifications.resourceUpdated(uri); else await server.sendResourceUpdated({ uri });
662
+ }
602
663
  return true;
603
664
  }
604
- const timer = pollInterval > 0 ? setInterval(() => { refresh().catch((error) => process.stderr.write(`ads mcp: ${error.message}\n`)); }, pollInterval) : null;
665
+ const timer = pollInterval > 0 ? setInterval(() => { if (!observationClosed) refresh().catch(error => { if (!observationClosed) process.stderr.write(`ads mcp: ${error.message}\n`); }); }, pollInterval) : null;
605
666
  timer?.unref();
667
+ if (observeChanges) draftObservers.add(refresh);
668
+ const stopObservation = () => { observationClosed = true; draftObservers.delete(refresh); if (timer) clearInterval(timer); };
606
669
  server.oninitialized = () => previewWatch?.start();
607
- server.onclose = () => { if (timer) clearInterval(timer); };
608
- return { server, refresh, readResource:read, async callTool(name,args,signal){const tool=tools().find(tool=>tool.name===name);if(!tool)throw new Error("Unknown preview tool.");return tool.call(tool.schema.parse(args),signal);}, async close() { if (timer) clearInterval(timer); if (!inspection) { await drafts.close(); await validation.close(); await verification.close(); await captures.close(); } await server.close(); } };
670
+ server.onclose = stopObservation;
671
+ async function warmScenarios(ids, signal) {
672
+ if (!previewWatch) return;
673
+ const apps = allApps(), selected = new Set(ids);
674
+ const files = apps.filter(app => selected.has(app.id)).map(app => path.resolve(root, app.file));
675
+ if (files.length !== selected.size) throw new Error("Cannot warm an unknown verification scenario.");
676
+ previewWatch.setApps(apps);
677
+ await previewWatch.warm(files);
678
+ for (const file of files) await previewWatch.ensure(file, signal);
679
+ }
680
+ return { server, refresh, warmScenarios, buildAll(signal, options) { previewWatch.setApps(allApps()); return previewWatch.buildAll(signal, options); }, readResource:read, async callTool(name,args,signal){const tool=tools().find(tool=>tool.name===name);if(!tool)throw new Error("Unknown preview tool.");return tool.call(tool.schema.parse(args),signal);}, async close() { stopObservation(); if (!inspection) { await drafts.close(); await validation.close(); await verification.close(); await captures.close(); } await server.close(); } };
609
681
  }
610
682
 
611
- export async function startAdsMcp(directory = process.cwd(), { stdio = true, showcase = true, port = 0, mutations = false } = {}) {
683
+ export async function startAdsMcp(directory = process.cwd(), { stdio = true, showcase = true, port = 0, mutations = false, previewWork = createPreviewWork() } = {}) {
612
684
  // Fail before opening the transport for configuration/distribution errors.
613
685
  const { root, config } = loadConfig(directory);
614
- const inspection = { skills: createSkillStore() };
686
+ const inspection = { skills: createSkillStore(), previewWork };
615
687
  const previewWatch = createReconfigurablePreviewWatch(root, config.mcp);
688
+ const unregisterPreview = previewWork.register(previewWatch);
616
689
  let host, api;
690
+ let buildWatcher, buildChangeTimer;
691
+ const buildListeners = new Set();
692
+ const onBuildChange = report => { for (const listener of buildListeners) listener(report); };
617
693
  const showcaseUrl = () => host?.url;
618
694
  if (showcase) {
619
695
  host = await startShowcaseHost(({ era }) => createAdsMcp(directory, { era, previewWatch, showcaseUrl, inspection, mutations, pollInterval: 0, observeChanges:false }).server,
620
- { port, observe: notifications => createAdsMcp(directory, { era: "modern", previewWatch, showcaseUrl, inspection, mutations, notifications }) });
696
+ { port, observe: notifications => createAdsMcp(directory, { era: "modern", previewWatch, showcaseUrl, inspection, mutations, notifications, onBuildChange }) });
621
697
  process.stderr.write(`ADS showcase: ${host.url}\n`);
622
698
  }
623
699
  const transport = stdio ? new StdioServerTransport() : null;
624
- const handle = stdio ? serveStdio(({ era }) => createAdsMcp(directory, { era, previewWatch, showcaseUrl, inspection, mutations }).server, { transport, legacy: "serve", onerror: (error) => process.stderr.write(`ads mcp: ${error.message}\n`) }) : null;
700
+ const handle = stdio ? serveStdio(({ era }) => createAdsMcp(directory, { era, previewWatch, showcaseUrl, inspection, mutations, onBuildChange }).server, { transport, legacy: "serve", onerror: (error) => process.stderr.write(`ads mcp: ${error.message}\n`) }) : null;
701
+ try {
702
+ buildWatcher = watch(path.join(root, ".ds"), (_event, file) => {
703
+ const selected = previewWatch.resourceSession();
704
+ if (String(file) !== (selected ? `build-status-${selected}.json` : "build-status.json")) return;
705
+ clearTimeout(buildChangeTimer);
706
+ buildChangeTimer = setTimeout(() => {
707
+ try { onBuildChange(previewWatch.buildStatus()); } catch { /* The polling observer retries transient writes. */ }
708
+ for (const refresh of inspection.draftObservers ?? []) void refresh().catch(() => {});
709
+ }, 16); buildChangeTimer.unref();
710
+ });
711
+ buildWatcher.unref(); buildWatcher.on("error", () => { buildWatcher.close(); });
712
+ } catch { /* Periodic observation also covers replaced/missing report directories. */ }
625
713
  let closing;
626
714
  function close() {
627
715
  return closing ??= (async () => {
716
+ buildListeners.clear();
717
+ clearTimeout(buildChangeTimer); buildWatcher?.close();
628
718
  inspection.edits?.cancel();
719
+ unregisterPreview();
629
720
  // Stop every owned resource even if another close fails or has in-flight RPCs.
630
721
  const results = await Promise.allSettled([
631
722
  Promise.resolve().then(() => host?.close()),
@@ -641,6 +732,7 @@ export async function startAdsMcp(directory = process.cwd(), { stdio = true, sho
641
732
  for (const signal of ["SIGINT", "SIGTERM"]) process.removeListener(signal, disconnect);
642
733
  process.removeListener("exit", forceCleanup);
643
734
  const errors = results.filter(result => result.status === "rejected").map(result => result.reason);
735
+ releaseScenarioRegistry(root);
644
736
  if (errors.length) throw new AggregateError(errors, "ADS shutdown failed");
645
737
  })();
646
738
  }
@@ -658,5 +750,8 @@ export async function startAdsMcp(directory = process.cwd(), { stdio = true, sho
658
750
  for (const signal of ["SIGINT", "SIGTERM"]) process.once(signal, disconnect);
659
751
  process.once("exit", forceCleanup);
660
752
  const previewApi=()=>api??=createAdsMcp(root,{era:"modern",inspection,previewWatch,showcaseUrl,mutations:false,pollInterval:0,observeChanges:false});
661
- return { close, url: host?.url, callTool:(name,args,signal)=>previewApi().callTool(name,args,signal),readResource:(uri,signal)=>previewApi().readResource(uri,signal),previewRevision: () => readPreviewManifest(withPreviewSession(loadConfig(root), previewWatch.resourceSession()))?.revision ?? null };
753
+ return { close, url: host?.url, async buildAll(signal, options) { await previewWatch.initialize(); return previewApi().buildAll(signal, options); }, warmScenarios: (ids, signal) => previewApi().warmScenarios(ids, signal), prewarm: () => previewWatch.initialize(), onBuildChange(listener) { buildListeners.add(listener); return () => buildListeners.delete(listener); }, buildStatus: () => previewWatch.buildStatus(), primeRegistry(registry) {
754
+ if (inspection.registry === registry || inspection.lastRegistry === registry) return;
755
+ inspection.registry = inspection.lastRegistry = registry; inspection.registryRevision = undefined; inspection.catalog = undefined;
756
+ }, callTool:(name,args,signal)=>previewApi().callTool(name,args,signal),readResource:(uri,signal)=>previewApi().readResource(uri,signal),previewRevision: () => readPreviewManifest(withPreviewSession(loadConfig(root), previewWatch.resourceSession()))?.revision ?? null };
662
757
  }
@@ -23,6 +23,7 @@ export function createVitePreviewBuilder({ build, configure }) {
23
23
  }
24
24
  const builder = async (entries, options, track, { watched = false } = {}) => {
25
25
  if (!watched) {
26
+ await close();
26
27
  const config = await configure(entries, options);
27
28
  const output = await build({ ...config, plugins: [...config.plugins ?? [], track], build: { ...config.build, write: false, watch: null } });
28
29
  return createPreviewResources(output, options, entries);
@@ -1,34 +1,40 @@
1
1
  import { Worker, isMainThread, parentPort, workerData } from "node:worker_threads";
2
2
  import { loadConfig } from "./config.mjs";
3
- import { inspectScenarios } from "./scenarios.mjs";
3
+ import { discoverScenarioRegistry } from "./scenario-registry.mjs";
4
4
 
5
5
  // Discovery is semantic source analysis. Keep it off the live compiler's event
6
6
  // loop; the caller fences each result against the exact project input digest.
7
7
  if (!isMainThread && workerData?.adsScenarioInspector) {
8
- parentPort.on("message", ({ id }) => {
9
- try { parentPort.postMessage({ id, result: inspectScenarios(loadConfig(workerData.root)) }); }
8
+ parentPort.on("message", ({ id, root = workerData.root }) => {
9
+ try { parentPort.postMessage({ id, result: discoverScenarioRegistry(loadConfig(root)) }); }
10
10
  catch (error) { parentPort.postMessage({ id, error: error.message }); }
11
11
  });
12
12
  }
13
13
 
14
- export function createScenarioInspector(root) {
15
- let worker, sequence = 0;
14
+ export function createScenarioInspector(root, { idleMs = 5000 } = {}) {
15
+ let worker, sequence = 0, idle;
16
16
  const pending = new Map();
17
17
  function fail(error) { for (const task of pending.values()) task.reject(error); pending.clear(); }
18
18
  return {
19
- inspect() {
19
+ inspect(directory = root) {
20
+ clearTimeout(idle);
20
21
  if (!worker) {
21
22
  worker = new Worker(new URL(import.meta.url), { workerData: { adsScenarioInspector: true, root } });
23
+ const current = worker;
22
24
  worker.on("message", ({ id, result, error }) => {
23
25
  const task = pending.get(id); pending.delete(id);
24
26
  if (task) { if (error) task.reject(new Error(error)); else task.resolve(result); }
27
+ if (!pending.size && worker === current) {
28
+ idle = setTimeout(() => { if (worker === current && !pending.size) { worker = undefined; void current.terminate(); } }, idleMs);
29
+ idle.unref();
30
+ }
25
31
  });
26
- worker.on("error", fail);
27
- worker.on("exit", () => { fail(new Error("Scenario inspector closed.")); worker = undefined; });
32
+ worker.on("error", error => { if (worker === current) fail(error); });
33
+ worker.on("exit", () => { if (worker === current) { fail(new Error("Scenario inspector closed.")); worker = undefined; } });
28
34
  }
29
35
  const id = ++sequence;
30
- return new Promise((resolve, reject) => { pending.set(id, { resolve, reject }); worker.postMessage({ id }); });
36
+ return new Promise((resolve, reject) => { pending.set(id, { resolve, reject }); worker.postMessage({ id, root: directory }); });
31
37
  },
32
- async close() { const previous = worker; worker = undefined; fail(new Error("Scenario inspector closed.")); await previous?.terminate(); },
38
+ async close() { clearTimeout(idle); const previous = worker; worker = undefined; fail(new Error("Scenario inspector closed.")); await previous?.terminate(); },
33
39
  };
34
40
  }
@@ -0,0 +1,36 @@
1
+ import ts from "typescript";
2
+ import path from "node:path";
3
+ import { isContractFile, isScenarioFile, sourceFiles } from "./config.mjs";
4
+ import { projectCompilerOptions } from "./boundaries.mjs";
5
+
6
+ /** Preview-only checker reuse. Validation keeps its independent fresh program. */
7
+ export function createScenarioProgram() {
8
+ let previous, signature;
9
+ const sources = new Map();
10
+ return {
11
+ build(options) {
12
+ const compilerOptions = { ...projectCompilerOptions(options), allowJs: true };
13
+ const next = JSON.stringify([options.root, compilerOptions]);
14
+ if (signature !== next) { previous = undefined; sources.clear(); signature = next; }
15
+ const files = sourceFiles(options.dsRoot);
16
+ const roots = files.some(isContractFile) ? files.filter(file => /\.[cm]?[jt]sx?$/.test(file))
17
+ : [path.join(options.dsRoot, options.config.publicEntry), path.join(options.dsRoot, options.config.reviewEntry), ...files.filter(isScenarioFile)];
18
+ const host = ts.createCompilerHost(compilerOptions, true), load = host.getSourceFile.bind(host);
19
+ // New/deleted modules and changed dependency exports must resolve again;
20
+ // source-tree reuse does not grant reuse of old failed module lookups.
21
+ host.hasInvalidatedResolutions = () => true;
22
+ host.getSourceFile = (file, languageVersion, onError, force) => {
23
+ const text = host.readFile(file), cached = sources.get(file), mode = JSON.stringify(languageVersion);
24
+ if (!force && cached && cached.text === text && cached.mode === mode) return cached.source;
25
+ const source = load(file, languageVersion, onError, force);
26
+ if (source) sources.set(file, { text, mode, source }); else sources.delete(file);
27
+ return source;
28
+ };
29
+ previous = ts.createProgram({ rootNames: roots, options: compilerOptions, host, oldProgram: previous });
30
+ const retained = new Set(previous.getSourceFiles().map(file => file.fileName));
31
+ for (const file of sources.keys()) if (!retained.has(file)) sources.delete(file);
32
+ return previous;
33
+ },
34
+ clear() { previous = undefined; signature = undefined; sources.clear(); },
35
+ };
36
+ }