@reqvire-org/ads 0.3.33 → 0.3.34

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 (54) 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.mjs +2 -0
  6. package/dist/config.mjs +4 -0
  7. package/dist/lint-config.mjs +7 -0
  8. package/dist/mcp/build-status.mjs +1 -1
  9. package/dist/mcp/catalog.mjs +4 -2
  10. package/dist/mcp/draft-discovery.mjs +55 -0
  11. package/dist/mcp/drafts.mjs +135 -16
  12. package/dist/mcp/preview-watch.mjs +13 -2
  13. package/dist/mcp/preview-widget.bundle.js +14 -14
  14. package/dist/mcp/server.mjs +109 -27
  15. package/dist/scenario-inspector.mjs +5 -5
  16. package/dist/scenario-program.mjs +36 -0
  17. package/dist/scenario-registry.mjs +90 -0
  18. package/dist/scenarios-compiler.mjs +66 -22
  19. package/dist/scenarios.mjs +2 -1
  20. package/dist/showcase/client.bundle.js +39 -39
  21. package/dist/showcase/comparison.js +29 -5
  22. package/dist/showcase/draft-navigation.js +41 -0
  23. package/dist/showcase/index.html +1 -2
  24. package/dist/showcase/preview-state.js +19 -0
  25. package/dist/showcase/style.css +2 -2
  26. package/dist/skills/ads-break-ui/references/behaviors.md +10 -0
  27. package/dist/skills/ads-break-ui/references/drafts.md +43 -4
  28. package/dist/skills/ads-break-ui/references/validation.md +6 -0
  29. package/dist/skills/ads-designer/SKILL.md +7 -0
  30. package/dist/skills/ads-designer/assets/bootstrap-ds/ds.config.json +1 -0
  31. package/dist/skills/ads-designer/references/behaviors.md +10 -0
  32. package/dist/skills/ads-designer/references/drafts.md +43 -4
  33. package/dist/skills/ads-designer/references/validation.md +6 -0
  34. package/dist/skills/ads-import/SKILL.md +4 -0
  35. package/dist/skills/ads-import/references/behaviors.md +10 -0
  36. package/dist/skills/ads-import/references/drafts.md +43 -4
  37. package/dist/skills/ads-import/references/validation.md +6 -0
  38. package/dist/skills/ads-motion/references/behaviors.md +10 -0
  39. package/dist/skills/ads-motion/references/drafts.md +43 -4
  40. package/dist/skills/ads-motion/references/validation.md +6 -0
  41. package/dist/skills/ads-port/SKILL.md +8 -1
  42. package/dist/skills/ads-port/references/behaviors.md +10 -0
  43. package/dist/skills/ads-port/references/drafts.md +43 -4
  44. package/dist/skills/ads-port/references/native-implementation.md +14 -1
  45. package/dist/skills/ads-port/references/validation.md +6 -0
  46. package/dist/unit-contracts.mjs +2 -2
  47. package/dist/units.mjs +6 -0
  48. package/dist/verification/browser.d.mts +27 -0
  49. package/dist/verification.mjs +3 -0
  50. package/docs/ARCHITECTURE.md +82 -0
  51. package/docs/CHANGELOG.md +92 -0
  52. package/docs/GUIDE.md +29 -4
  53. package/docs/MCP.md +44 -4
  54. package/package.json +6 -4
@@ -1,4 +1,4 @@
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";
@@ -10,7 +10,7 @@ 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 } 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";
@@ -28,6 +28,7 @@ import { reconcileTokenSamples } from "../token-fixtures.mjs";
28
28
  import { createCaptureController } from "../capture.mjs";
29
29
  import { CAPTURES_URI, captureSpec, screenshotFields } from "../capture-store.mjs";
30
30
  import { previewSourceRevision } from "../preview-inputs.mjs";
31
+ import { inspectBehaviorLibraries } from "../behavior-libraries.mjs";
31
32
  import { createExecutionResults, RESULTS_URI, resultSections } from "./execution-results.mjs";
32
33
  import { behaviorPage, behaviorSections } from "./behavior-pages.mjs";
33
34
  import { compactProgress, resultBudgets } from "./result-pages.mjs";
@@ -63,13 +64,17 @@ function resourceQuery(uri, allowed) {
63
64
  return Object.fromEntries([...url.searchParams].map(([key,value])=>[key,["limit","recordIndex","offset","chars"].includes(key)?Number(value):value]));
64
65
  }
65
66
 
66
- export function createAdsMcp(directory, { era = "legacy", skillDirectory, pollInterval = 1000, observeChanges = true, previewWatch, showcaseUrl, notifications, inspection, mutations = false } = {}) {
67
+ export function createAdsMcp(directory, { era = "legacy", skillDirectory, pollInterval = 1000, observeChanges = true, previewWatch, showcaseUrl, notifications, inspection, mutations = false, onBuildChange } = {}) {
67
68
  const root = path.resolve(directory);
69
+ let observationClosed = false;
68
70
  const cache = inspection ?? {};
69
71
  const skills = cache.skills ??= createSkillStore(skillDirectory);
70
72
  const captures = cache.captures ??= createCaptureController(root);
71
73
  const edits = cache.edits ??= createMutationController(root, { captures });
72
- const drafts = cache.drafts ??= createDraftController(root, { edits, startPreview: workspace => startAdsMcp(workspace, { stdio: false, mutations: false }) });
74
+ const draftObservers = cache.draftObservers ??= new Set();
75
+ const drafts = cache.drafts ??= createDraftController(root, { edits, prewarm: true,
76
+ onChange: () => { for (const observer of draftObservers) void observer().catch(error => { process.stderr.write(`ads mcp: ${error.message}\n`); }); },
77
+ startPreview: workspace => startAdsMcp(workspace, { stdio: false, mutations: false }) });
73
78
  const verification = cache.verification ??= createVerificationController(root);
74
79
  const validation = cache.validation ??= createValidationController(root);
75
80
  const executionResults = cache.executionResults ??= createExecutionResults(root);
@@ -78,6 +83,7 @@ export function createAdsMcp(directory, { era = "legacy", skillDirectory, pollIn
78
83
  const signature = `${root}:${JSON.stringify(options.config)}`;
79
84
  if (cache.signature !== signature) {
80
85
  cache.signature = signature;
86
+ cache.behaviorLibraries = undefined;
81
87
  cache.registry = cache.catalog = cache.documents = undefined;
82
88
  }
83
89
  const getShowcaseUrl = () => showcaseUrl?.() ?? options.config.mcp.showcaseUrl;
@@ -96,16 +102,22 @@ export function createAdsMcp(directory, { era = "legacy", skillDirectory, pollIn
96
102
  capabilities: { tools: { listChanged: true }, resources: { listChanged: true, subscribe: true }, prompts: {},
97
103
  extensions: { "io.modelcontextprotocol/ui": { mimeTypes: [APP_MIME] }, ...(era === "modern" ? { [SKILLS_EXTENSION]: { directoryRead: true } } : {}) } },
98
104
  });
99
- const getRegistry = () => { cache.registry ??= inspectScenarios(options); cache.lastRegistry = cache.registry; return cache.registry; };
105
+ const getRegistry = () => {
106
+ const current = loadConfig(root), revision = previewSourceRevision(current);
107
+ if (!cache.registry || cache.registryRevision !== revision) {
108
+ cache.registry = discoverScenarioRegistry(current); cache.registryRevision = revision; cache.catalog = undefined; cache.behaviorLibraries = undefined;
109
+ }
110
+ cache.lastRegistry = cache.registry; return cache.registry;
111
+ };
100
112
  const previewRegistry = waitFor => waitFor === "compiled" ? cache.registry ?? cache.lastRegistry ?? getRegistry() : getRegistry();
101
113
  function captureInventory() {
102
- const current = loadConfig(root), registry = inspectScenarios(current);
114
+ const current = loadConfig(root), registry = getRegistry();
103
115
  return { ...registry, revision: previewSourceRevision(current) };
104
116
  }
105
117
  function captureIndex() { const inventory = captureInventory(); return captures.store.list(inventory.scenarios, inventory.revision, { prune: !inventory.diagnostics.length }); }
106
118
  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
119
  const tokenScenarios = () => {
108
- const references=drafts.list({unit:"tokens",limit:100000}).drafts.map(({id,title,revision,state})=>({id,title,revision,state}));
120
+ const references=drafts.list({unit:"tokens",limit:100000}).drafts.map(({id,title,revision,state,preview})=>({id,title,revision,state,preview}));
109
121
  return getRegistry().scenarios.filter(item => item.kind === "tokens").map(item => ({ id:item.id,title:item.title,count:item.tokens.length,drafts:references }));
110
122
  };
111
123
  const allApps = (quick = false) => [...options.config.mcp.apps, ...scenarioApps(quick)];
@@ -122,18 +134,20 @@ export function createAdsMcp(directory, { era = "legacy", skillDirectory, pollIn
122
134
  if (!manifest?.scenarios.some(entry => entry.id === id)) throw new Error("The preview resource graph is not ready for this scenario. Rebuild previews.");
123
135
  return { manifestUri: live ? LIVE_PREVIEW_MANIFEST_URI : PREVIEW_MANIFEST_URI, manifestRevision: manifest.revision };
124
136
  }
125
- const getCatalog = () => cache.catalog ??= inspectCatalog(options, getRegistry().scenarios);
137
+ const getCatalog = () => { const registry = getRegistry(); return cache.catalog ??= inspectCatalog(loadConfig(root), registry.scenarios, getBehaviorLibraries()); };
138
+ const getBehaviorLibraries = () => cache.behaviorLibraries ??= inspectBehaviorLibraries(loadConfig(root));
126
139
  function annotateDrafts(items) {
127
140
  const found = drafts.list({limit:100000}).drafts, units = edits.units();
128
141
  return items.map(item => {
129
142
  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})) };
143
+ return { ...item, unit, drafts: found.filter(draft => draft.units.includes(unit)).map(({id,title,revision,state,preview}) => ({id,title,revision,state,preview})) };
131
144
  });
132
145
  }
133
146
  const getDocuments = () => cache.documents ??= projectDocuments(options);
134
147
  const builds = () => {
135
148
  previewWatch?.setApps(allApps(true));
136
- return previewWatch?.buildStatus() ?? inspectBuildStatus(root, { ...options.config.mcp, apps: allApps(true) });
149
+ const report = previewWatch?.buildStatus() ?? inspectBuildStatus(root, { ...options.config.mcp, apps: allApps(true) });
150
+ return { ...report, drafts: drafts.previewStatuses() };
137
151
  };
138
152
  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
153
 
@@ -184,6 +198,7 @@ export function createAdsMcp(directory, { era = "legacy", skillDirectory, pollIn
184
198
  { uri: `${PROJECT_URI}/tokens`, name: "Project token values and themes", mimeType: "application/json" },
185
199
  { uri: `${PROJECT_URI}/catalog`, name: "Public components and patterns", mimeType: "application/json" },
186
200
  { uri: DRAFTS_URI, name: "Tracked ADS drafts and acceptance events", mimeType: "application/json" },
201
+ ...drafts.previewStatuses().map(({ id, resourceUri }) => ({ uri: resourceUri, name: `Draft ${id}: preview build status and diagnostics`, mimeType: "application/json" })),
187
202
  { uri: "ads://guides/drafts", name: "Auto-mode tracked draft workflow", mimeType: "text/markdown" },
188
203
  { uri: `${PROJECT_URI}/scenarios`, name: "Independently mountable scenarios", mimeType: "application/json" },
189
204
  { uri: BEHAVIOR_URI, name: "Behavior contracts, demonstrations and current verification evidence", mimeType: "application/json" },
@@ -207,17 +222,18 @@ export function createAdsMcp(directory, { era = "legacy", skillDirectory, pollIn
207
222
  }
208
223
  function status() {
209
224
  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,
225
+ const catalog = getCatalog(), registry = cache.registry;
226
+ return { projectRoot: root, workflow: workflow([...previews(), ...scenarioApps(true)]), project: context,
227
+ package: pkg.name, version: pkg.version, dsDir: options.config.dsDir, publicAlias: options.config.publicAlias, behaviorLibraries: getBehaviorLibraries().libraries,
228
+ components: catalog.filter((item) => item.kind === "components" && item.apiKind === "ui").length,
229
+ patterns: catalog.filter((item) => item.kind === "patterns" && item.apiKind === "ui").length,
214
230
  tokenCount: inspectTokens(root).tokens.length, showcaseUrl: getShowcaseUrl(),
215
231
  previewWatch: previewWatch?.status() ?? { state: "disabled" },
216
232
  mutations: mutations ? { ...mutationState, progress: compactProgress(mutationState.progress), lastResult: executionResults.latest("mutation") } : { enabled: false },
217
233
  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
234
  build: summarizeBuild(builds()),
219
235
  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" },
236
+ scenarios: { count: registry.scenarios.length, diagnostics: registry.diagnostics, resourceUri: `${PROJECT_URI}/scenarios`, tool: "ads_show_scenario" },
221
237
  validation: { ...validation.status(), tool: "ads_validate", lastResult: executionResults.latest("validation") },
222
238
  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
239
  captures: { resourceUri: CAPTURES_URI, tool: "ads_capture", clearTool: "ads_capture_clear", ...captures.status() },
@@ -371,8 +387,10 @@ export function createAdsMcp(directory, { era = "legacy", skillDirectory, pollIn
371
387
  return json({ total: matches.length, items: annotateDrafts(matches.slice(0, limit)), resourceUri: `${PROJECT_URI}/catalog` });
372
388
  } },
373
389
  { 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` });
390
+ const registry = getRegistry();
391
+ 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()));
392
+ const report = builds(), states = new Map(report.previews.map(item => [item.id, item]));
393
+ 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
394
  } },
377
395
  { 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
396
  const registry = previewRegistry(waitFor);
@@ -485,6 +503,7 @@ export function createAdsMcp(directory, { era = "legacy", skillDirectory, pollIn
485
503
  return { resources: listing.items, ...(listing.nextCursor ? { nextCursor: listing.nextCursor } : {}) };
486
504
  });
487
505
  server.setRequestHandler("resources/templates/list", () => ({ resourceTemplates: [
506
+ { 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
507
  { 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
508
  { 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
509
  { 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 +555,8 @@ export function createAdsMcp(directory, { era = "legacy", skillDirectory, pollIn
536
555
  const artifactFingerprint = () => fileFingerprint(allApps(true).map(app => path.resolve(root, previewArtifactPath(previewOptions(), app.file))));
537
556
  const assetFingerprint = () => resourceAssets().map(asset => asset.uri).sort().join("\n");
538
557
  let previous, previousArtifacts, previousAssets, previousBuild, previousCaptures, previousCaptureUris, previousDrafts;
558
+ let previousDraftBuilds = new Map();
559
+ const draftBuilds = () => new Map(drafts.previewStatuses().map(build => [build.resourceUri, JSON.stringify(build)]));
539
560
  const investigationFingerprint=()=>fileFingerprint([path.join(root,".ds/investigations.json")]);
540
561
  let previousInvestigations, previousResults, observing=false;
541
562
  function initializeObservation() {
@@ -544,12 +565,31 @@ export function createAdsMcp(directory, { era = "legacy", skillDirectory, pollIn
544
565
  previousCaptures=captures.store.fingerprint();previousCaptureUris=captures.store.resourceUris();
545
566
  previousInvestigations=investigationFingerprint();previousResults=executionResults.fingerprint();observing=true;
546
567
  previousDrafts=drafts.fingerprint();
568
+ previousDraftBuilds=draftBuilds();
547
569
  }
548
570
  // Modern HTTP serves a fresh protocol instance per request. Its shared observer
549
571
  // already tracks changes; immutable byte reads need no source/build scan.
550
572
  if (observeChanges) initializeObservation();
551
573
  let deferredDiscovery = false;
552
- async function refresh(force = false) {
574
+ let refreshing, refreshAgain = false, refreshForced = false;
575
+ function refresh(force = false) {
576
+ if (observationClosed) return Promise.resolve(false);
577
+ // Stateless HTTP handlers share the persistent observer. Starting their own
578
+ // observation after every mutation would force a false source change and
579
+ // throw away accepted discovery/capture caches on each draft edit.
580
+ if (!observeChanges) return Promise.all([...draftObservers].map(observer => observer(force))).then(values => values.some(Boolean));
581
+ refreshAgain = true; refreshForced ||= force;
582
+ return refreshing ??= Promise.resolve().then(async () => {
583
+ let changed = false;
584
+ while (refreshAgain && !observationClosed) {
585
+ refreshAgain = false;
586
+ const forced = refreshForced; refreshForced = false;
587
+ changed = await refreshOnce(forced) || changed;
588
+ }
589
+ return changed;
590
+ }).finally(() => { refreshing = undefined; });
591
+ }
592
+ async function refreshOnce(force) {
553
593
  if (!observing) { initializeObservation();force=true; }
554
594
  // Polling covers replaced files and new directories consistently across OSes.
555
595
  cache.documents = undefined;
@@ -559,20 +599,26 @@ export function createAdsMcp(directory, { era = "legacy", skillDirectory, pollIn
559
599
  const build = JSON.stringify(builds());
560
600
  const filesChanged = force || next !== previous;
561
601
  const buildChanged = build !== previousBuild;
602
+ if (buildChanged) onBuildChange?.(JSON.parse(build));
562
603
  const artifactsChanged = artifacts !== previousArtifacts;
563
604
  const assetsChanged = assets !== previousAssets;
564
605
  const capturesChanged = captures.store.fingerprint() !== previousCaptures;
565
606
  const investigationsChanged=investigationFingerprint()!==previousInvestigations;
566
607
  const resultsChanged=executionResults.fingerprint()!==previousResults;
567
608
  const draftFingerprint=drafts.fingerprint(),draftsChanged=draftFingerprint!==previousDrafts;
609
+ const currentDraftBuilds=draftBuilds();
610
+ const changedDraftBuilds=[...new Set([...previousDraftBuilds.keys(),...currentDraftBuilds.keys()])].filter(uri=>previousDraftBuilds.get(uri)!==currentDraftBuilds.get(uri));
611
+ const draftResourcesChanged=[...previousDraftBuilds.keys()].some(uri=>!currentDraftBuilds.has(uri)) || [...currentDraftBuilds.keys()].some(uri=>!previousDraftBuilds.has(uri));
568
612
  if (!filesChanged && !buildChanged && !artifactsChanged && !assetsChanged && !capturesChanged && !investigationsChanged && !resultsChanged && !draftsChanged && !deferredDiscovery) return false;
569
613
  if (filesChanged) {
570
614
  const updated = loadConfig(root);
571
615
  await previewWatch?.reconfigure?.(updated.config.mcp);
616
+ if (observationClosed) return false;
572
617
  const appsChanged = JSON.stringify(updated.config.mcp.apps) !== JSON.stringify(options.config.mcp.apps) || updated.config.mcp.previewManifest !== options.config.mcp.previewManifest;
573
618
  options = updated;
574
619
  cache.signature = `${root}:${JSON.stringify(options.config)}`;
575
620
  cache.catalog = undefined;
621
+ cache.behaviorLibraries = undefined;
576
622
  cache.registry = undefined;
577
623
  previous = fingerprint();
578
624
  if (appsChanged) { if (notifications) notifications.toolsChanged(); else await server.sendToolListChanged(); }
@@ -583,13 +629,15 @@ export function createAdsMcp(directory, { era = "legacy", skillDirectory, pollIn
583
629
  deferredDiscovery ||= filesChanged;
584
630
  const discoveryChanged = deferredDiscovery && !checking;
585
631
  if (discoveryChanged) deferredDiscovery = false;
586
- if (discoveryChanged || assetsChanged) { if (notifications) notifications.resourcesChanged(); else await server.sendResourceListChanged(); }
632
+ if (discoveryChanged || assetsChanged || draftResourcesChanged) { if (notifications) notifications.resourcesChanged(); else await server.sendResourceListChanged(); }
587
633
  previousArtifacts = artifactFingerprint();
588
634
  previousAssets = assetFingerprint();
589
635
  previousBuild = JSON.stringify(builds());
590
- const targets = discoveryChanged ? era === "modern" ? resources().map((entry) => entry.uri).filter((uri) => !skills.files.has(uri)) : [...subscribed]
636
+ const targets = discoveryChanged ? (era === "modern" ? resources().map((entry) => entry.uri).filter((uri) => !skills.files.has(uri)) : [...subscribed]).filter(uri => !uri.startsWith("ads://drafts/"))
591
637
  : [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
638
  if(draftsChanged){targets.push(...[DRAFTS_URI,`${PROJECT_URI}/catalog`,`${PROJECT_URI}/scenarios`,`${PROJECT_URI}/status`].filter(uri=>era==="modern"||subscribed.has(uri)));previousDrafts=draftFingerprint;}
639
+ targets.push(...changedDraftBuilds.filter(uri=>era==="modern"||subscribed.has(uri)));
640
+ previousDraftBuilds=currentDraftBuilds;
593
641
  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
642
  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
643
  if (capturesChanged || discoveryChanged) {
@@ -598,14 +646,28 @@ export function createAdsMcp(directory, { era = "legacy", skillDirectory, pollIn
598
646
  previousCaptureUris = current;
599
647
  previousCaptures = captures.store.fingerprint();
600
648
  }
601
- for (const uri of new Set(targets)) { if (notifications) notifications.resourceUpdated(uri); else await server.sendResourceUpdated({ uri }); }
649
+ for (const uri of new Set(targets)) {
650
+ if (observationClosed) return false;
651
+ if (notifications) notifications.resourceUpdated(uri); else await server.sendResourceUpdated({ uri });
652
+ }
602
653
  return true;
603
654
  }
604
- const timer = pollInterval > 0 ? setInterval(() => { refresh().catch((error) => process.stderr.write(`ads mcp: ${error.message}\n`)); }, pollInterval) : null;
655
+ const timer = pollInterval > 0 ? setInterval(() => { if (!observationClosed) refresh().catch(error => { if (!observationClosed) process.stderr.write(`ads mcp: ${error.message}\n`); }); }, pollInterval) : null;
605
656
  timer?.unref();
657
+ if (observeChanges) draftObservers.add(refresh);
658
+ const stopObservation = () => { observationClosed = true; draftObservers.delete(refresh); if (timer) clearInterval(timer); };
606
659
  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(); } };
660
+ server.onclose = stopObservation;
661
+ async function warmScenarios(ids, signal) {
662
+ if (!previewWatch) return;
663
+ const apps = allApps(), selected = new Set(ids);
664
+ const files = apps.filter(app => selected.has(app.id)).map(app => path.resolve(root, app.file));
665
+ if (files.length !== selected.size) throw new Error("Cannot warm an unknown verification scenario.");
666
+ previewWatch.setApps(apps);
667
+ await previewWatch.warm(files);
668
+ for (const file of files) await previewWatch.ensure(file, signal);
669
+ }
670
+ return { server, refresh, warmScenarios, 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
671
  }
610
672
 
611
673
  export async function startAdsMcp(directory = process.cwd(), { stdio = true, showcase = true, port = 0, mutations = false } = {}) {
@@ -614,17 +676,34 @@ export async function startAdsMcp(directory = process.cwd(), { stdio = true, sho
614
676
  const inspection = { skills: createSkillStore() };
615
677
  const previewWatch = createReconfigurablePreviewWatch(root, config.mcp);
616
678
  let host, api;
679
+ let buildWatcher, buildChangeTimer;
680
+ const buildListeners = new Set();
681
+ const onBuildChange = report => { for (const listener of buildListeners) listener(report); };
617
682
  const showcaseUrl = () => host?.url;
618
683
  if (showcase) {
619
684
  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 }) });
685
+ { port, observe: notifications => createAdsMcp(directory, { era: "modern", previewWatch, showcaseUrl, inspection, mutations, notifications, onBuildChange }) });
621
686
  process.stderr.write(`ADS showcase: ${host.url}\n`);
622
687
  }
623
688
  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;
689
+ 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;
690
+ try {
691
+ buildWatcher = watch(path.join(root, ".ds"), (_event, file) => {
692
+ const selected = previewWatch.resourceSession();
693
+ if (String(file) !== (selected ? `build-status-${selected}.json` : "build-status.json")) return;
694
+ clearTimeout(buildChangeTimer);
695
+ buildChangeTimer = setTimeout(() => {
696
+ try { onBuildChange(previewWatch.buildStatus()); } catch { /* The polling observer retries transient writes. */ }
697
+ for (const refresh of inspection.draftObservers ?? []) void refresh().catch(() => {});
698
+ }, 16); buildChangeTimer.unref();
699
+ });
700
+ buildWatcher.unref(); buildWatcher.on("error", () => { buildWatcher.close(); });
701
+ } catch { /* Periodic observation also covers replaced/missing report directories. */ }
625
702
  let closing;
626
703
  function close() {
627
704
  return closing ??= (async () => {
705
+ buildListeners.clear();
706
+ clearTimeout(buildChangeTimer); buildWatcher?.close();
628
707
  inspection.edits?.cancel();
629
708
  // Stop every owned resource even if another close fails or has in-flight RPCs.
630
709
  const results = await Promise.allSettled([
@@ -658,5 +737,8 @@ export async function startAdsMcp(directory = process.cwd(), { stdio = true, sho
658
737
  for (const signal of ["SIGINT", "SIGTERM"]) process.once(signal, disconnect);
659
738
  process.once("exit", forceCleanup);
660
739
  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 };
740
+ return { close, url: host?.url, warmScenarios: (ids, signal) => previewApi().warmScenarios(ids, signal), prewarm: () => previewWatch.initialize(), onBuildChange(listener) { buildListeners.add(listener); return () => buildListeners.delete(listener); }, buildStatus: () => previewWatch.buildStatus(), primeRegistry(registry) {
741
+ if (inspection.registry === registry || inspection.lastRegistry === registry) return;
742
+ inspection.registry = inspection.lastRegistry = registry; inspection.registryRevision = undefined; inspection.catalog = undefined;
743
+ }, 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
744
  }
@@ -1,12 +1,12 @@
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
  }
@@ -16,7 +16,7 @@ export function createScenarioInspector(root) {
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
20
  if (!worker) {
21
21
  worker = new Worker(new URL(import.meta.url), { workerData: { adsScenarioInspector: true, root } });
22
22
  worker.on("message", ({ id, result, error }) => {
@@ -27,7 +27,7 @@ export function createScenarioInspector(root) {
27
27
  worker.on("exit", () => { fail(new Error("Scenario inspector closed.")); worker = undefined; });
28
28
  }
29
29
  const id = ++sequence;
30
- return new Promise((resolve, reject) => { pending.set(id, { resolve, reject }); worker.postMessage({ id }); });
30
+ return new Promise((resolve, reject) => { pending.set(id, { resolve, reject }); worker.postMessage({ id, root: directory }); });
31
31
  },
32
32
  async close() { const previous = worker; worker = undefined; fail(new Error("Scenario inspector closed.")); await previous?.terminate(); },
33
33
  };
@@ -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
+ }
@@ -0,0 +1,90 @@
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
+ function programFor(root) {
14
+ const program = programs.get(root) ?? createScenarioProgram();
15
+ programs.delete(root); programs.set(root, program);
16
+ while (programs.size > 2) { const oldest = programs.keys().next().value; programs.get(oldest).clear(); programs.delete(oldest); }
17
+ return program;
18
+ }
19
+ // A source checkout and a published build have different code even when their
20
+ // package versions match. Cache identities follow the actual discovery code.
21
+ const toolRevision = (() => {
22
+ const root = import.meta.dirname, rows = [];
23
+ function visit(directory) {
24
+ for (const entry of readdirSync(directory, { withFileTypes: true }).sort((a, b) => a.name.localeCompare(b.name))) {
25
+ const file = path.join(directory, entry.name);
26
+ if (entry.isDirectory() && !["skills", "bootstrap-ds", "showcase"].includes(entry.name)) visit(file);
27
+ else if (entry.isFile() && /\.(?:mjs|js|cjs|json)$/.test(entry.name)) rows.push([path.relative(root, file), hash(readFileSync(file))]);
28
+ }
29
+ }
30
+ visit(root);
31
+ return hash(JSON.stringify([rows, process.versions.bun ?? process.version, process.platform, process.arch]));
32
+ })();
33
+
34
+ function validRegistry(value, options) {
35
+ return value && Array.isArray(value.scenarios) && value.scenarios.length <= 10000
36
+ && value.scenarios.every(item => typeof item?.id === "string" && /^(?:tokens|components|patterns|composition)\/[\w./-]+$/.test(item.id)
37
+ && path.posix.normalize(item.id) === item.id && typeof item.title === "string"
38
+ && ["tokens", "components", "patterns", "composition"].includes(item.kind)
39
+ && typeof item.file === "string" && isInside(options.dsRoot, path.resolve(options.root, item.file))
40
+ && item.artifact === `.ds/scenarios/${item.id}/index.html` && Array.isArray(item.covers) && Array.isArray(item.tokens))
41
+ && Array.isArray(value.diagnostics) && value.diagnostics.every(item => typeof item?.message === "string" && typeof item.rule === "string");
42
+ }
43
+
44
+ function read(options, revision) {
45
+ const file = path.join(options.root, ".ds", filename);
46
+ try {
47
+ const stat = lstatSync(file);
48
+ if (!stat.isFile() || stat.nlink !== 1 || stat.size > maxBytes || realpathSync(file) !== file) return;
49
+ const snapshot = JSON.parse(readFileSync(file, "utf8"));
50
+ if (snapshot.schemaVersion === 1 && snapshot.root === options.root && snapshot.toolRevision === toolRevision
51
+ && snapshot.revision === revision && snapshot.digest === hash(JSON.stringify(snapshot.registry)) && validRegistry(snapshot.registry, options)) return snapshot.registry;
52
+ } catch { /* Missing/corrupt/generated data is a cache miss, never evidence. */ }
53
+ }
54
+
55
+ /** Read a current discovery snapshot without starting semantic analysis. */
56
+ export function readScenarioRegistry(options) {
57
+ return read(options, previewSourceRevision(options));
58
+ }
59
+
60
+ function write(options, revision, registry) {
61
+ const directory = path.join(options.root, ".ds"), file = path.join(directory, filename), temporary = `${file}.${randomUUID()}.tmp`;
62
+ try {
63
+ if (existsSync(directory) && realpathSync(directory) !== directory) return;
64
+ mkdirSync(directory, { recursive: true });
65
+ if (realpathSync(directory) !== directory) return;
66
+ const content = JSON.stringify({ schemaVersion: 1, root: options.root, toolRevision, revision, digest: hash(JSON.stringify(registry)), registry });
67
+ if (Buffer.byteLength(content) > maxBytes) return;
68
+ writeFileSync(temporary, content);
69
+ renameSync(temporary, file);
70
+ } catch { /* Read-only projects can still discover scenarios without caching. */ }
71
+ finally { try { rmSync(temporary, { force: true }); } catch { /* Optional cache cleanup must not prevent discovery. */ } }
72
+ }
73
+
74
+ /** Share semantic discovery between preview hosts and compiler processes.
75
+ * This snapshot contains metadata/diagnostics only, never validated outputs or
76
+ * passing check results. Validation continues to inspect source independently. */
77
+ export function discoverScenarioRegistry(options) {
78
+ for (let attempt = 0; attempt < 2; ++attempt) {
79
+ // Contract inspectors memoize TypeScript programs on options. A new source
80
+ // revision needs fresh options as well as a fresh registry.
81
+ const current = loadConfig(options.root), revision = previewSourceRevision(current);
82
+ const cached = read(current, revision);
83
+ if (cached) return cached;
84
+ const registry = inspectScenarios(current, programFor(current.root).build(current));
85
+ if (revision !== previewSourceRevision(loadConfig(current.root))) continue;
86
+ write(current, revision, registry);
87
+ return registry;
88
+ }
89
+ throw Object.assign(new Error("Sources changed during scenario discovery. Retry against the current source."), { code: "ADS_SCENARIO_SOURCE_CHANGED" });
90
+ }