@reqvire-org/ads 0.3.28 → 0.3.31

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 (68) hide show
  1. package/dist/atomic-composition.mjs +2 -1
  2. package/dist/behaviors.mjs +2 -2
  3. package/dist/boundaries.mjs +6 -3
  4. package/dist/check.mjs +3 -0
  5. package/dist/cli.mjs +13 -0
  6. package/dist/config.mjs +11 -4
  7. package/dist/mcp/build-status.mjs +18 -5
  8. package/dist/mcp/context.mjs +2 -1
  9. package/dist/mcp/execution-results.mjs +4 -3
  10. package/dist/mcp/mutations.mjs +53 -51
  11. package/dist/mcp/preview-watch.mjs +23 -3
  12. package/dist/mcp/preview-widget.bundle.js +16 -15
  13. package/dist/mcp/resource-loader.js +40 -12
  14. package/dist/mcp/server.mjs +88 -46
  15. package/dist/oxlint.mjs +6 -1
  16. package/dist/preview-builder.mjs +10 -4
  17. package/dist/preview-files.mjs +19 -12
  18. package/dist/preview-inputs.mjs +6 -17
  19. package/dist/preview-resources.mjs +36 -7
  20. package/dist/preview-scope.mjs +6 -0
  21. package/dist/preview-workers.mjs +184 -0
  22. package/dist/project-documents.mjs +4 -0
  23. package/dist/scenario-inspector.mjs +34 -0
  24. package/dist/scenario-trace.mjs +5 -3
  25. package/dist/scenarios-compiler.mjs +200 -25
  26. package/dist/showcase/client.bundle.js +23 -22
  27. package/dist/showcase/index.html +2 -2
  28. package/dist/showcase/style.css +5 -1
  29. package/dist/skills/ads-break-ui/SKILL.md +3 -0
  30. package/dist/skills/ads-break-ui/references/behaviors.md +2 -0
  31. package/dist/skills/ads-break-ui/references/layers.md +6 -0
  32. package/dist/skills/ads-break-ui/references/runtimes.md +31 -0
  33. package/dist/skills/ads-break-ui/references/validation.md +69 -0
  34. package/dist/skills/ads-designer/SKILL.md +3 -0
  35. package/dist/skills/ads-designer/references/behaviors.md +2 -0
  36. package/dist/skills/ads-designer/references/layers.md +6 -0
  37. package/dist/skills/ads-designer/references/runtimes.md +31 -0
  38. package/dist/skills/ads-designer/references/validation.md +69 -0
  39. package/dist/skills/ads-import/SKILL.md +3 -0
  40. package/dist/skills/ads-import/references/behaviors.md +2 -0
  41. package/dist/skills/ads-import/references/layers.md +6 -0
  42. package/dist/skills/ads-import/references/runtimes.md +31 -0
  43. package/dist/skills/ads-import/references/validation.md +69 -0
  44. package/dist/skills/ads-motion/SKILL.md +3 -0
  45. package/dist/skills/ads-motion/references/behaviors.md +2 -0
  46. package/dist/skills/ads-motion/references/layers.md +6 -0
  47. package/dist/skills/ads-motion/references/runtimes.md +31 -0
  48. package/dist/skills/ads-motion/references/validation.md +69 -0
  49. package/dist/skills/ads-port/SKILL.md +3 -0
  50. package/dist/skills/ads-port/references/behaviors.md +2 -0
  51. package/dist/skills/ads-port/references/layers.md +6 -0
  52. package/dist/skills/ads-port/references/runtimes.md +31 -0
  53. package/dist/skills/ads-port/references/validation.md +69 -0
  54. package/dist/source-symbols.mjs +11 -0
  55. package/dist/source-values.mjs +10 -3
  56. package/dist/test-boundaries.mjs +96 -0
  57. package/dist/ui-framework.mjs +2 -1
  58. package/dist/units.mjs +12 -1
  59. package/dist/validation-checks.mjs +50 -0
  60. package/dist/validation-inputs.mjs +132 -0
  61. package/dist/validation.mjs +158 -0
  62. package/dist/verification/browser.mjs +3 -1
  63. package/dist/verification.mjs +1 -0
  64. package/docs/ARCHITECTURE.md +96 -20
  65. package/docs/BEHAVIORS.md +2 -0
  66. package/docs/CHANGELOG.md +74 -0
  67. package/docs/MCP.md +105 -12
  68. package/package.json +1 -1
@@ -1,3 +1,22 @@
1
+ function closure(records, uri) {
2
+ const ordered = [], seen = new Set();
3
+ function visit(id) {
4
+ if (seen.has(id)) return;
5
+ seen.add(id);
6
+ const record=records.get(id);
7
+ if (!record) throw new Error(`Missing preview dependency metadata: ${id}`);
8
+ for (const dependency of [...record.imports,...record.styles,...record.references]) visit(dependency);
9
+ ordered.push(id);
10
+ }
11
+ visit(uri);return ordered;
12
+ }
13
+
14
+ export function changedPreviewScenarios(previous, next) {
15
+ if (!previous || previous.revision===next.revision) return [];
16
+ const signature=(graph,entry)=>{const records=new Map(Object.entries(graph.assets));return JSON.stringify(closure(records,entry.module).map(uri=>[uri,records.get(uri)]));};
17
+ return next.scenarios.filter(entry=>{const before=previous.scenarios.find(item=>item.id===entry.id);return !before || signature(previous,before)!==signature(next,entry);}).map(entry=>entry.id);
18
+ }
19
+
1
20
  /** Native ES modules keep framework semantics, cycles, and live bindings intact. */
2
21
  export class PreviewResourceLoader {
3
22
  constructor(read) {
@@ -10,6 +29,7 @@ export class PreviewResourceLoader {
10
29
  this.revisions = new Set();
11
30
  this.importing = Promise.resolve();
12
31
  this.generation = 0;
32
+ this.prefetchGeneration = 0;
13
33
  this.closed = false;
14
34
  globalThis.__dsPreviewImport = uri => this.importModule(uri);
15
35
  }
@@ -47,18 +67,25 @@ export class PreviewResourceLoader {
47
67
  return this.bytes.get(uri);
48
68
  }
49
69
  closure(uri) {
50
- const ordered = [];
51
- const seen = new Set();
52
- const visit = id => {
53
- if (seen.has(id)) return;
54
- seen.add(id);
55
- const record = this.records.get(id);
56
- if (!record) throw new Error(`Missing preview dependency metadata: ${id}`);
57
- for (const dependency of [...record.imports, ...record.styles, ...record.references]) visit(dependency);
58
- ordered.push(id);
59
- };
60
- visit(uri);
61
- return ordered;
70
+ return closure(this.records,uri);
71
+ }
72
+ async prefetch(manifest, ids) {
73
+ if (this.closed) return;
74
+ this.register(manifest);
75
+ const generation=++this.prefetchGeneration, pending=new Set(), scenarios=[];
76
+ let bytes=0;
77
+ for (const id of ids) {
78
+ const entry=manifest.scenarios.find(entry=>entry.id===id);
79
+ if (!entry) continue;
80
+ const missing=this.closure(entry.module).filter(uri=>!this.bytes.has(uri)&&!pending.has(uri));
81
+ const size=missing.reduce((sum,uri)=>sum+this.records.get(uri).size,0);
82
+ if (bytes+size>16*1024*1024 || pending.size+missing.length>256) continue;
83
+ bytes+=size;scenarios.push(id);for(const uri of missing)pending.add(uri);
84
+ }
85
+ const queue=[...pending];let index=0;
86
+ const next=async()=>{while(!this.closed&&generation===this.prefetchGeneration&&index<queue.length)await this.resource(queue[index++]);};
87
+ await Promise.all(Array.from({length:Math.min(3,queue.length)},next));
88
+ return {scenarios,resources:queue.length};
62
89
  }
63
90
  async materialize(uri) {
64
91
  const ordered = this.closure(uri);
@@ -140,6 +167,7 @@ export class PreviewResourceLoader {
140
167
  if (this.closed) return;
141
168
  this.closed = true;
142
169
  ++this.generation;
170
+ ++this.prefetchGeneration;
143
171
  await this.unmount?.();
144
172
  this.mounted = undefined;
145
173
  for (const style of this.styles.values()) style.remove();
@@ -4,6 +4,7 @@ import { Server, ProtocolError, INVALID_PARAMS, ResourceNotFoundError } from "@m
4
4
  import { serveStdio, StdioServerTransport } from "@modelcontextprotocol/server/stdio";
5
5
  import { z } from "zod";
6
6
  import { checkProject } from "../check.mjs";
7
+ import { createValidationController } from "../validation.mjs";
7
8
  import { loadConfig, sourceFiles } from "../config.mjs";
8
9
  import { createVerificationController, BEHAVIOR_URI } from "../verification.mjs";
9
10
  import { INVESTIGATIONS_URI, investigationIndex, investigationPage, investigationSections, readInvestigation, readInvestigationResource } from "../investigations.mjs";
@@ -15,8 +16,8 @@ import { startShowcaseHost } from "./showcase-host.mjs";
15
16
  import { createSkillStore, page, SKILLS_EXTENSION } from "./skills.mjs";
16
17
  import { inspectCatalog, projectDocuments, PROJECT_URI, readProjectDocument } from "./catalog.mjs";
17
18
  import { APP_MIME, appMetadata, appUri, projectApp, TOKENS_APP_URI, tokensApp, tokenWidgetData, SCENARIO_APP_URI, scenarioApp, previewApp, PREVIEW_APP_URI } from "./apps.mjs";
18
- import { PREVIEW_MANIFEST_URI, readPreviewManifest, readPreviewAsset } from "../preview-resources.mjs";
19
- import { previewArtifactPath, withPreviewSession } from "../preview-scope.mjs";
19
+ import { LIVE_PREVIEW_MANIFEST_URI, PREVIEW_MANIFEST_URI, readPreviewManifest, readPreviewAsset } from "../preview-resources.mjs";
20
+ import { livePreviewOptions, previewArtifactPath, withPreviewSession } from "../preview-scope.mjs";
20
21
  import { getWorkflowPrompt, promptDefinitions } from "./prompts.mjs";
21
22
  import { createReconfigurablePreviewWatch } from "./preview-watch.mjs";
22
23
  import { BUILD_URI, buildFailure, inspectBuildStatus, summarizeBuild } from "./build-status.mjs";
@@ -59,13 +60,14 @@ function resourceQuery(uri, allowed) {
59
60
  return Object.fromEntries([...url.searchParams].map(([key,value])=>[key,["limit","recordIndex","offset","chars"].includes(key)?Number(value):value]));
60
61
  }
61
62
 
62
- export function createAdsMcp(directory, { era = "legacy", skillDirectory, pollInterval = 1000, previewWatch, showcaseUrl, notifications, inspection, mutations = false } = {}) {
63
+ export function createAdsMcp(directory, { era = "legacy", skillDirectory, pollInterval = 1000, observeChanges = true, previewWatch, showcaseUrl, notifications, inspection, mutations = false } = {}) {
63
64
  const root = path.resolve(directory);
64
65
  const cache = inspection ?? {};
65
66
  const skills = cache.skills ??= createSkillStore(skillDirectory);
66
67
  const captures = cache.captures ??= createCaptureController(root);
67
68
  const edits = cache.edits ??= createMutationController(root, { captures });
68
69
  const verification = cache.verification ??= createVerificationController(root);
70
+ const validation = cache.validation ??= createValidationController(root);
69
71
  const executionResults = cache.executionResults ??= createExecutionResults(root);
70
72
  const reports = cache.reports ??= createReportStore(root, { context: reportContext, resolveEvidence: reportEvidence });
71
73
  let options = loadConfig(root);
@@ -90,32 +92,34 @@ export function createAdsMcp(directory, { era = "legacy", skillDirectory, pollIn
90
92
  capabilities: { tools: { listChanged: true }, resources: { listChanged: true, subscribe: true }, prompts: {},
91
93
  extensions: { "io.modelcontextprotocol/ui": { mimeTypes: [APP_MIME] }, ...(era === "modern" ? { [SKILLS_EXTENSION]: { directoryRead: true } } : {}) } },
92
94
  });
93
- const getRegistry = () => cache.registry ??= inspectScenarios(options);
95
+ const getRegistry = () => { cache.registry ??= inspectScenarios(options); cache.lastRegistry = cache.registry; return cache.registry; };
96
+ const previewRegistry = waitFor => waitFor === "compiled" ? cache.registry ?? cache.lastRegistry ?? getRegistry() : getRegistry();
94
97
  function captureInventory() {
95
98
  const current = loadConfig(root), registry = inspectScenarios(current);
96
99
  return { ...registry, revision: previewSourceRevision(current) };
97
100
  }
98
101
  function captureIndex() { const inventory = captureInventory(); return captures.store.list(inventory.scenarios, inventory.revision, { prune: !inventory.diagnostics.length }); }
99
- const scenarioApps = () => getRegistry().scenarios.map(item => ({ id: item.id, title: item.title, kind: item.kind, ...(item.samples ? { samples: item.samples } : {}), file: item.artifact }));
102
+ 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 }));
100
103
  const tokenScenarios = () => getRegistry().scenarios.filter(item => item.kind === "tokens").map(item => ({ id: item.id, title: item.title, count: item.tokens.length }));
101
- const allApps = () => [...options.config.mcp.apps, ...scenarioApps()];
104
+ const allApps = (quick = false) => [...options.config.mcp.apps, ...scenarioApps(quick)];
102
105
  const scenarioWidget = () => options.config.mcp.previewManifest ? PREVIEW_APP_URI : SCENARIO_APP_URI;
103
106
  const previewOptions = () => withPreviewSession(options, previewWatch?.resourceSession?.());
104
107
  const resourceAssets = () => {
105
108
  try { return Object.entries(readPreviewManifest(previewOptions())?.assets ?? {}).map(([uri, record]) => ({ uri, name: `Preview asset ${uri.slice("ads://assets/".length)}`, mimeType: record.mimeType, size: record.size })); }
106
109
  catch { return []; } // Discovery and diagnostics remain usable after a failed graph.
107
110
  };
108
- function graphSelection(id) {
111
+ function graphSelection(id, build) {
109
112
  if (!options.config.mcp.previewManifest) return {};
110
- const manifest = readPreviewManifest(previewOptions());
113
+ const live = build?.live && !build.current;
114
+ const manifest = readPreviewManifest(live ? livePreviewOptions(previewOptions()) : previewOptions());
111
115
  if (!manifest?.scenarios.some(entry => entry.id === id)) throw new Error("The preview resource graph is not ready for this scenario. Rebuild previews.");
112
- return { manifestUri: PREVIEW_MANIFEST_URI, manifestRevision: manifest.revision };
116
+ return { manifestUri: live ? LIVE_PREVIEW_MANIFEST_URI : PREVIEW_MANIFEST_URI, manifestRevision: manifest.revision };
113
117
  }
114
118
  const getCatalog = () => cache.catalog ??= inspectCatalog(options, getRegistry().scenarios);
115
119
  const getDocuments = () => cache.documents ??= projectDocuments(options);
116
120
  const builds = () => {
117
- previewWatch?.setApps(allApps());
118
- return previewWatch?.buildStatus() ?? inspectBuildStatus(root, { ...options.config.mcp, apps: allApps() });
121
+ previewWatch?.setApps(allApps(true));
122
+ return previewWatch?.buildStatus() ?? inspectBuildStatus(root, { ...options.config.mcp, apps: allApps(true) });
119
123
  };
120
124
  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 }));
121
125
 
@@ -152,6 +156,7 @@ export function createAdsMcp(directory, { era = "legacy", skillDirectory, pollIn
152
156
  return [
153
157
  { uri: GUIDE_URI, name: "Start here: design-system workflow", description: "Read first for UI/ADS tasks, especially when only resource access is exposed. Explains the exact workspace, tool sequence, skill selection, previews, project commands and fallback.", mimeType: "text/markdown" },
154
158
  { uri: "ads://guides/behaviors", name: "Controller and behavioral verification guide", mimeType: "text/markdown" },
159
+ { uri: "ads://guides/validation", name: "Full and affected validation; test boundaries", mimeType: "text/markdown" },
155
160
  { uri: "ads://guides/runtimes", name: "Node and Bun setup, compiler and verification runtime", mimeType: "text/markdown" },
156
161
  { uri: "ads://guides/evidence", name: "Failure boundaries and compact investigations", mimeType: "text/markdown" },
157
162
  { uri: "ads://guides/atomic-styles", name: "Atomic styles: composition conflicts and custom-property extraction", mimeType: "text/markdown" },
@@ -177,7 +182,7 @@ export function createAdsMcp(directory, { era = "legacy", skillDirectory, pollIn
177
182
  { uri: "ads://guides/reporting", name: "Report suspected ADS bugs and feature requests", mimeType: "text/markdown" },
178
183
  { uri: TOKENS_APP_URI, name: "Experimental token widget", mimeType: APP_MIME },
179
184
  { uri: SCENARIO_APP_URI, name: "Experimental scenario widget", mimeType: APP_MIME },
180
- ...(options.config.mcp.previewManifest ? [{ uri: PREVIEW_APP_URI, name: "Shared-resource preview App", mimeType: APP_MIME }, { uri: PREVIEW_MANIFEST_URI, name: "Preview dependency graph", mimeType: "application/json" }] : []),
185
+ ...(options.config.mcp.previewManifest ? [{ uri: PREVIEW_APP_URI, name: "Shared-resource preview App", mimeType: APP_MIME }, { uri: PREVIEW_MANIFEST_URI, name: "Verified preview dependency graph", mimeType: "application/json" }, { uri: LIVE_PREVIEW_MANIFEST_URI, name: "Unverified live feedback; background checks pending", mimeType: "application/json" }] : []),
181
186
  ...(options.config.mcp.previewManifest ? resourceAssets() : []),
182
187
  ...allApps().map((app) => ({ uri: appUri(app.id), name: app.title, description: app.description, mimeType: APP_MIME })),
183
188
  ...documents.filter((document) => !promoted.has(document.uri)).map(({ file: _file, ...document }) => document),
@@ -196,6 +201,7 @@ export function createAdsMcp(directory, { era = "legacy", skillDirectory, pollIn
196
201
  build: summarizeBuild(builds()),
197
202
  previews: previews(), skills: skills.skills.map(({ uri, frontmatter }) => ({ uri, name: frontmatter.name, description: frontmatter.description })),
198
203
  scenarios: { count: getRegistry().scenarios.length, diagnostics: getRegistry().diagnostics, resourceUri: `${PROJECT_URI}/scenarios`, tool: "ads_show_scenario" },
204
+ validation: { ...validation.status(), tool: "ads_validate", lastResult: executionResults.latest("validation") },
199
205
  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 },
200
206
  captures: { resourceUri: CAPTURES_URI, tool: "ads_capture", clearTool: "ads_capture_clear", ...captures.status() },
201
207
  reports: { access:"submission-only", storageDirectory:".ds/reports", bugTool:"ads_report_bug", featureTool:"ads_request_feature", guidanceUri:"ads://guides/reporting", delivery:"local-only", retention:"until-explicit-removal" },
@@ -204,6 +210,7 @@ export function createAdsMcp(directory, { era = "legacy", skillDirectory, pollIn
204
210
  async function read(uri, signal) {
205
211
  if (uri === GUIDE_URI) return { contents: [{ uri, mimeType: "text/markdown", text: projectGuide(project(), [...previews(), ...scenarioApps()]) }] };
206
212
  if (uri === "ads://guides/behaviors") return { contents: [{ uri, mimeType: "text/markdown", text: readFileSync(new URL("../skills/ads-designer/references/behaviors.md", import.meta.url), "utf8") }] };
213
+ if (uri === "ads://guides/validation") return { contents: [{ uri, mimeType: "text/markdown", text: readFileSync(new URL("../skills/ads-designer/references/validation.md", import.meta.url), "utf8") }] };
207
214
  if (uri === "ads://guides/runtimes") return { contents: [{ uri, mimeType: "text/markdown", text: readFileSync(new URL("../skills/ads-designer/references/runtimes.md", import.meta.url), "utf8") }] };
208
215
  if (uri === "ads://guides/evidence") return { contents: [{ uri, mimeType: "text/markdown", text: readFileSync(new URL("../skills/ads-designer/references/evidence.md", import.meta.url), "utf8") }] };
209
216
  if (uri === "ads://guides/tokens") return { contents: [{ uri, mimeType: "text/markdown", text: readFileSync(new URL("../skills/ads-designer/references/design-data.md", import.meta.url), "utf8") }] };
@@ -230,6 +237,11 @@ export function createAdsMcp(directory, { era = "legacy", skillDirectory, pollIn
230
237
  value = readPreviewManifest(previewOptions());
231
238
  if (!value) throw new Error("Preview resources are not built yet. Invoke ads_show_scenario to start the managed compiler.");
232
239
  }
240
+ else if (uri === LIVE_PREVIEW_MANIFEST_URI && options.config.mcp.previewManifest) {
241
+ const report = builds(), live = report.previews.find(entry => entry.live)?.live;
242
+ value = readPreviewManifest(livePreviewOptions(previewOptions()));
243
+ if (!live || value?.revision !== live.revision || value.session !== report.session) throw new Error("No live feedback for the current source. Use the verified preview after checks pass.");
244
+ }
233
245
  if (value !== undefined) return { contents: [{ uri, mimeType: "application/json", text: JSON.stringify(value) }] };
234
246
  if (uri.startsWith("ads://investigations/") || uri.startsWith("ads://verification-artifacts/")) {
235
247
  try { return {contents:[readInvestigationResource(root,uri)]}; }
@@ -244,7 +256,11 @@ export function createAdsMcp(directory, { era = "legacy", skillDirectory, pollIn
244
256
  if (uri === PREVIEW_APP_URI && options.config.mcp.previewManifest) return { contents: [{ uri, mimeType: APP_MIME, text: previewApp(), _meta: appMetadata() }] };
245
257
  if (uri.startsWith("ads://assets/") && options.config.mcp.previewManifest) {
246
258
  try { return { contents: [readPreviewAsset(previewOptions(), uri)] }; }
247
- catch (error) { if (error.code === "ADS_PREVIEW_NOT_FOUND") throw new ResourceNotFoundError(uri, error.message); throw error; }
259
+ catch (error) {
260
+ if (error.code !== "ADS_PREVIEW_NOT_FOUND") throw error;
261
+ try { return { contents: [readPreviewAsset(livePreviewOptions(previewOptions()), uri)] }; }
262
+ catch (error) { if (error.code === "ADS_PREVIEW_NOT_FOUND") throw new ResourceNotFoundError(uri, error.message); throw error; }
263
+ }
248
264
  }
249
265
  const app = allApps().find((entry) => appUri(entry.id) === uri);
250
266
  if (app) {
@@ -257,10 +273,14 @@ export function createAdsMcp(directory, { era = "legacy", skillDirectory, pollIn
257
273
  if (document) return { contents: [{ uri, mimeType: document.mimeType, text: readProjectDocument(document) }] };
258
274
  throw new ResourceNotFoundError(uri, `Unknown ADS resource: ${uri}`);
259
275
  }
260
- async function previewBuild(app, signal) {
261
- previewWatch?.setApps(allApps());
262
- if (previewWatch) return previewWatch.ensure(path.resolve(root, app.file), signal);
276
+ async function previewBuild(app, signal, waitFor = "verified") {
277
+ previewWatch?.setApps(allApps(waitFor === "compiled"));
278
+ if (previewWatch) return previewWatch.ensure(path.resolve(root, app.file), signal, { waitFor });
263
279
  const build = builds().previews.find((entry) => entry.id === app.id);
280
+ if (waitFor === "compiled" && options.config.mcp.previewManifest) {
281
+ try { graphSelection(app.id, build); return build; }
282
+ catch { /* No usable graph yet: keep the normal diagnostics/wait path. */ }
283
+ }
264
284
  if (build?.state === "error") throw buildFailure(build);
265
285
  if (["building", "idle"].includes(build?.state)) throw Object.assign(new Error("Preview build is still pending. Invoke the preview again after rebuilding."), { build: { ...build, resourceUri: BUILD_URI } });
266
286
  return build;
@@ -272,6 +292,7 @@ export function createAdsMcp(directory, { era = "legacy", skillDirectory, pollIn
272
292
  return { ...json(summary), ...(!result.ok ? { isError: true } : {}) };
273
293
  }
274
294
  async function applyEdits(args,signal,progress) {
295
+ if (validation.status().busy) throw new Error("Wait for the active validation run before editing source.");
275
296
  const result = await edits.apply(args,signal,progress);
276
297
  if (result.screenshots) await refresh();
277
298
  if (result.applied) {
@@ -279,6 +300,8 @@ export function createAdsMcp(directory, { era = "legacy", skillDirectory, pollIn
279
300
  if (result.changes.some(change => change.path === "ds.config.json") || result.unit === "configuration" || result.units?.includes("configuration")) await previewWatch?.reconfigure?.(loadConfig(root).config.mcp,true);
280
301
  await previewWatch?.invalidate?.();
281
302
  await refresh(true);
303
+ previewWatch?.setApps(allApps());
304
+ if ((result.units??[result.unit]).some(unit=>unit!=="documentation")) await previewWatch?.warm?.((options.config.mcp.previewManifest?scenarioApps():allApps()).map(app=>path.resolve(root,app.file)));
282
305
  } catch (error) {result.warnings=[...(result.warnings ?? []),{rule:"mutation-notification",message:`Changes were applied, but preview refresh failed: ${error.message.slice(0,2000)}. Recheck ads_status and reopen the scenario.`}];}
283
306
  }
284
307
  return finishExecution("mutation", { ...(args.patches ? {units:args.patches.map(item=>item.unit),transaction:true} : {unit:args.unit}), ...result });
@@ -300,13 +323,14 @@ export function createAdsMcp(directory, { era = "legacy", skillDirectory, pollIn
300
323
  const units = edits.units();
301
324
  return json({ total: matches.length, scenarios: matches.slice(offset, offset + limit).map(item => ({ ...item, unit: units.find(unit => unit.files.includes(item.file))?.id ?? null })), ...(offset + limit < matches.length ? { nextOffset: offset + limit } : {}), diagnostics: getRegistry().diagnostics, resourceUri: `${PROJECT_URI}/scenarios` });
302
325
  } },
303
- { name: "ads_show_scenario", title: "Scenario preview", description: "Render one real token, component, pattern or composition scenario with its colocated fixtures and state adapter. First get an exact id from ads_scenarios or ads_catalog.previews. The managed compiler builds it on demand; errors return diagnostics instead of falsely current output. Requires MCP Apps plus host resource forwarding; fallback links to the same scenario in the project showcase.", schema: z.object({ id: z.string().min(1).max(256) }).strict(), _meta: { ui: { resourceUri: scenarioWidget() } }, call: async ({ id }, signal) => {
304
- const entry = getRegistry().scenarios.find(item => item.id === id);
326
+ { 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) => {
327
+ const registry = previewRegistry(waitFor);
328
+ const entry = registry.scenarios.find(item => item.id === id);
305
329
  if (!entry) throw new Error("Unknown scenario id. Read ads_scenarios; IDs must match discovered source entries.");
306
- if (getRegistry().diagnostics.length) throw new Error("Scenario registry has errors. Read ads://project/scenarios and fix its diagnostics.");
307
- const app = scenarioApps().find(item => item.id === id);
308
- const build = await previewBuild(app, signal);
309
- const graph = graphSelection(id);
330
+ if (registry.diagnostics.length) throw new Error("Scenario registry has errors. Read ads://project/scenarios and fix its diagnostics.");
331
+ const app = scenarioApps(waitFor === "compiled").find(item => item.id === id);
332
+ const build = await previewBuild(app, signal, waitFor);
333
+ const graph = graphSelection(id, build);
310
334
  if (!options.config.mcp.previewManifest) projectApp(options, app, build);
311
335
  return json({ widget: { resourceUri: scenarioWidget() }, scenario: { ...entry, resourceUri: appUri(id) }, ...graph, build, showcaseUrl: scenarioUrl(id) });
312
336
  } },
@@ -330,27 +354,33 @@ export function createAdsMcp(directory, { era = "legacy", skillDirectory, pollIn
330
354
  if (!("text" in content)) return json({ ...manifest, mimeType: content.mimeType, binary: true, note: "Read binary bytes via resources/read; this tool does not embed them." });
331
355
  return json({ ...manifest, text: content.text.slice(offset, offset + limit), offset, ...(offset + limit < content.text.length ? { nextOffset: offset + limit } : {}) });
332
356
  } },
333
- { name: "ads_show_tokens", title: "Token previews", description: "Render an exact discovered token scenario with its project-owned templates and fixtures. Pass its id as category, discovered through ads_tokens.categories or ads_scenarios(kind: tokens). Omit category for the first project token scenario, or a generic definition inspector for older compilers.", schema: z.object({ category: z.string().max(256).optional() }).strict(), _meta: { ui: { resourceUri: options.config.mcp.previewManifest ? PREVIEW_APP_URI : TOKENS_APP_URI } }, call: async ({ category }, signal) => {
334
- if (!category && options.config.mcp.previewManifest) category = tokenScenarios()[0]?.id;
357
+ { name: "ads_show_tokens", title: "Token previews", description: "Render a discovered token scenario with project-owned templates and fixtures. Pass its id as category, or omit for the first token scenario. Default waitFor: verified requires current checks. Interactive browsers may use waitFor: compiled for explicitly unverified feedback or a retained view. Older compilers provide a generic definition inspector.", schema: z.object({ category: z.string().max(256).optional(), waitFor: z.enum(["verified", "compiled"]).default("verified") }).strict(), _meta: { ui: { resourceUri: options.config.mcp.previewManifest ? PREVIEW_APP_URI : TOKENS_APP_URI } }, call: async ({ category, waitFor }, signal) => {
358
+ const registry = previewRegistry(waitFor);
359
+ if (!category && options.config.mcp.previewManifest) category = registry.scenarios.find(item => item.kind === "tokens")?.id;
335
360
  if (!category && options.config.mcp.previewManifest) throw new Error("No token scenario is registered. Colocate a token scenario and fixture before opening the preview; ads_tokens still inspects definitions.");
336
361
  if (category) {
337
- const entry = getRegistry().scenarios.find(item => item.kind === "tokens" && item.id === category);
362
+ const entry = registry.scenarios.find(item => item.kind === "tokens" && item.id === category);
338
363
  if (!entry) throw new Error("Unknown token scenario. Discover categories with ads_tokens or ads_scenarios(kind: tokens) first.");
339
- if (getRegistry().diagnostics.length) throw new Error("Scenario registry has errors. Fix its diagnostics before reviewing.");
340
- const app = scenarioApps().find(item => item.id === category);
341
- const build = await previewBuild(app, signal);
342
- const graph = graphSelection(category);
364
+ if (registry.diagnostics.length) throw new Error("Scenario registry has errors. Fix its diagnostics before reviewing.");
365
+ const app = scenarioApps(waitFor === "compiled").find(item => item.id === category);
366
+ const build = await previewBuild(app, signal, waitFor);
367
+ const graph = graphSelection(category, build);
343
368
  if (!options.config.mcp.previewManifest) projectApp(options, app, build);
344
369
  return json({ widget: { resourceUri: options.config.mcp.previewManifest ? PREVIEW_APP_URI : TOKENS_APP_URI }, category, scenario: { ...entry, resourceUri: appUri(category) }, ...graph, build, showcaseUrl: scenarioUrl(category) });
345
370
  }
346
371
  return json({ widget: { resourceUri: TOKENS_APP_URI }, category: null, tokenCount: inspectTokens(root).tokens.length, dataUri: `${PROJECT_URI}/tokens`, showcaseUrl: getShowcaseUrl() });
347
372
  } },
348
373
  { name: "ads_behaviors", description: "Discover behavior owners, then page an exact unit's checks, guarantees, subjects, demonstrations or profiles. Summary listings never embed runner logs. Default 10/max 20 entries and 8 KiB JSON per page; continue with nextCursor and identical filters. Cursors expire when discovery/evidence changes. Read sourceFile with ads_read_file for a complete contract. Metadata and reachable calls do not prove execution; use ads_verify for registered checks.", schema: z.object({ query: z.string().max(200).optional(), unit: z.string().min(1).max(256).optional(), api: z.string().max(200).optional(), section: z.enum(behaviorSections).optional(), ...paged }).strict(), call: args => json(behaviorPage(options,args)) },
349
- { name: "ads_results", title: "Read execution outcomes", description: "Read saved ads_verify/ads_apply_patch/ads_apply_transaction outcomes without rerunning anything. Pass the returned resultId; select outcomes, checks, diagnostics, advisories, warnings, changes, captures, acceptance, investigation or selection. Default 10/max 20 rows, at most 8 KiB JSON per page. Follow nextCursor with identical section/status. Rows marked detailTruncated can be read in full using recordIndex and offset/chars (max 2000); follow nextOffset. Only the latest verification and mutation snapshots are retained; replaced IDs fail explicitly. For one outcome's browser evidence use ads_investigate with its exact unit/check/runId.", schema: z.object({ resultId: z.string().uuid(), section: z.enum(resultSections).optional(), status: z.enum(["all","passed","not_passed"]).optional(), ...paged, ...recordRange }).strict(), call: args => json(executionResults.page(args)) },
374
+ { name: "ads_results", title: "Read execution outcomes", description: "Read saved ads_validate/ads_verify/ads_apply_patch/ads_apply_transaction outcomes without rerunning anything. Pass the returned resultId; select outcomes, checks, diagnostics, advisories, warnings, changes, captures, acceptance, investigation or selection. Default 10/max 20 rows, at most 8 KiB JSON per page. Follow nextCursor with identical section/status. Rows marked detailTruncated can be read in full using recordIndex and offset/chars (max 2000); follow nextOffset. Only the latest validation, verification and mutation snapshots are retained; replaced IDs fail explicitly. For one outcome's browser evidence use ads_investigate with its exact unit/check/runId.", schema: z.object({ resultId: z.string().uuid(), section: z.enum(resultSections).optional(), status: z.enum(["all","passed","not_passed"]).optional(), ...paged, ...recordRange }).strict(), call: args => json(executionResults.page(args)) },
350
375
  { name:"ads_report_bug",title:"Report a suspected ADS defect",description:"Record an unexpected ADS guard, preview, build, transport or runner behavior after targeted investigation. Provide expected/observed behavior, minimal steps and frequency; keep suspectedCause separate. Evidence optionally selects a returned resultId or exact unit/check/runId. ADS snapshots compact evidence, version, configured framework and revisions. A report is an untriaged agent claim, not proof of an ADS cause. Returns a small receipt with the report ID and local file path; submitted reports cannot be read through MCP. Stored locally under .ds/reports/ with deduplication, no automatic expiry and no upload. Read ads://guides/reporting; ordinary valid guard rejections should be fixed in their owner.",schema:bugReportSchema,annotations:{readOnlyHint:false,destructiveHint:false,idempotentHint:false,openWorldHint:false},call:args=>submitReport("bug",args) },
351
376
  { name:"ads_request_feature",title:"Request an ADS capability",description:"Record a legitimate workflow that needs a missing ADS capability. Provide workflow, capability and impact; proposal is optional. Preserve valid design/API rather than weakening guards or inventing workaround props. Optional evidence references an existing execution/check, not pasted files/logs. ADS attaches compact context and returns a receipt with the report ID and local file path. Intake is submission-only; no report-reading tools or resources. Shared local report store: deduplicated, untriaged, no automatic expiry or upload. Read ads://guides/reporting; use ads_report_bug for suspected broken existing behavior.",schema:featureRequestSchema,annotations:{readOnlyHint:false,destructiveHint:false,idempotentHint:false,openWorldHint:false},call:args=>submitReport("feature",args) },
352
377
  { name: "ads_investigate", title: "Inspect check evidence", description: "Read a summary for an exact unit/check, or list latest investigations when no check is selected. Pass the outcome's runId to reject superseded evidence. Summary is at most 4 KiB JSON; details, requests, browserErrors and artifacts are separate paged sections (default 10/max 20 entries, 8 KiB). Read truncated rows with recordIndex/offset/chars and the exact runId. Artifact URIs are read separately. Does not rerun checks or infer root cause. Only the latest bundle per check is retained, including candidate runs.", schema: z.object({unit:z.string().min(1).max(256).optional(),check:z.string().min(1).max(100).optional(),runId:z.string().min(1).max(100).optional(),section:z.enum(investigationSections).optional(),...paged,...recordRange}).strict(), call: args => json(investigationPage(root,args)) },
378
+ { name: "ads_validate", description: "Run the shared ads validate audit. Default scope all: core architecture and test ownership, registered Oxlint, configured project scripts and all registered behavior checks. scope changed uses affected behavior checks since the last successful full audit; missing/incompatible baselines or broad changes expand to all and report why. Core and opaque project scripts retain their full scope. Use changed during editing, all after test/ownership/config migrations and before releases or explicit complete audits. Reports scope, source revision, skipped stages, progress and a bounded resultId; page diagnostics/checks/outcomes with ads_results. Changed inputs, cancellation and failed/skipped registered cases cannot pass. Read ads://guides/validation. Runs trusted configured commands; installs nothing.", schema: z.object({scope:z.enum(["all","changed"]).default("all")}).strict(), annotations: {readOnlyHint:false,destructiveHint:false,idempotentHint:false,openWorldHint:false}, call: async (args,signal,progress) => {
379
+ if (verification.status().running || edits.status().busy) throw new Error("Wait for the active verification or guarded edit before validating.");
380
+ return finishExecution("validation",await validation.run(args,signal,progress));
381
+ } },
353
382
  { name: "ads_verify", description: "Run one owner's registered development behavior checks using its configured runner/profile. Executes trusted project commands with bounded output, cancellation and process-tree cleanup; installs nothing. Progress and per-check timings are available through ads_status; a profile timeout bounds the whole run. Browser profiles use an isolated managed showcase/MCP App. React StrictMode requires a project development harness, not a production widget. Missing/skipped cases, stale inputs and process exit alone cannot produce passing evidence. Replies contain counts, acceptance, at most three failure summaries and a resultId (4 KiB JSON maximum). Page outcomes with ads_results; inspect one exact unit/check/runId with ads_investigate. Discover exact unit/check IDs with ads_behaviors first.", schema: z.object({ unit: z.string().min(1).max(256), checks: z.array(z.string().min(1).max(100)).min(1).max(100).optional() }).strict(), annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: false, openWorldHint: false }, call: async (args, signal, progress) => {
383
+ if (validation.status().busy) throw new Error("Wait for the active validation run before verifying separately.");
354
384
  const result = await verification.run(args, signal, progress);
355
385
  return finishExecution("verification", {unit:args.unit,...result});
356
386
  } },
@@ -452,18 +482,23 @@ export function createAdsMcp(directory, { era = "legacy", skillDirectory, pollIn
452
482
  const sources = sourceFiles(options.dsRoot);
453
483
  return `${fileFingerprint([...sources, ...getDocuments().map(doc => doc.file), path.join(root, "ds.config.json"), path.join(root, "package.json"), path.join(root, ".ds/behavior-results.json")])}\n${scenarioGroupFingerprint(options, sources)}`;
454
484
  };
455
- const artifactFingerprint = () => fileFingerprint(allApps().map(app => path.resolve(root, previewArtifactPath(previewOptions(), app.file))));
485
+ const artifactFingerprint = () => fileFingerprint(allApps(true).map(app => path.resolve(root, previewArtifactPath(previewOptions(), app.file))));
456
486
  const assetFingerprint = () => resourceAssets().map(asset => asset.uri).sort().join("\n");
457
- let previous = fingerprint();
458
- let previousArtifacts = artifactFingerprint();
459
- let previousAssets = assetFingerprint();
460
- let previousBuild = JSON.stringify(builds());
461
- let previousCaptures = captures.store.fingerprint();
462
- let previousCaptureUris = captures.store.resourceUris();
487
+ let previous, previousArtifacts, previousAssets, previousBuild, previousCaptures, previousCaptureUris;
463
488
  const investigationFingerprint=()=>fileFingerprint([path.join(root,".ds/investigations.json")]);
464
- let previousInvestigations=investigationFingerprint();
465
- let previousResults=executionResults.fingerprint();
489
+ let previousInvestigations, previousResults, observing=false;
490
+ function initializeObservation() {
491
+ if (observing) return;
492
+ previous=fingerprint();previousArtifacts=artifactFingerprint();previousAssets=assetFingerprint();previousBuild=JSON.stringify(builds());
493
+ previousCaptures=captures.store.fingerprint();previousCaptureUris=captures.store.resourceUris();
494
+ previousInvestigations=investigationFingerprint();previousResults=executionResults.fingerprint();observing=true;
495
+ }
496
+ // Modern HTTP serves a fresh protocol instance per request. Its shared observer
497
+ // already tracks changes; immutable byte reads need no source/build scan.
498
+ if (observeChanges) initializeObservation();
499
+ let deferredDiscovery = false;
466
500
  async function refresh(force = false) {
501
+ if (!observing) { initializeObservation();force=true; }
467
502
  // Polling covers replaced files and new directories consistently across OSes.
468
503
  cache.documents = undefined;
469
504
  const next = fingerprint();
@@ -477,7 +512,7 @@ export function createAdsMcp(directory, { era = "legacy", skillDirectory, pollIn
477
512
  const capturesChanged = captures.store.fingerprint() !== previousCaptures;
478
513
  const investigationsChanged=investigationFingerprint()!==previousInvestigations;
479
514
  const resultsChanged=executionResults.fingerprint()!==previousResults;
480
- if (!filesChanged && !buildChanged && !artifactsChanged && !assetsChanged && !capturesChanged && !investigationsChanged && !resultsChanged) return false;
515
+ if (!filesChanged && !buildChanged && !artifactsChanged && !assetsChanged && !capturesChanged && !investigationsChanged && !resultsChanged && !deferredDiscovery) return false;
481
516
  if (filesChanged) {
482
517
  const updated = loadConfig(root);
483
518
  await previewWatch?.reconfigure?.(updated.config.mcp);
@@ -489,15 +524,21 @@ export function createAdsMcp(directory, { era = "legacy", skillDirectory, pollIn
489
524
  previous = fingerprint();
490
525
  if (appsChanged) { if (notifications) notifications.toolsChanged(); else await server.sendToolListChanged(); }
491
526
  }
492
- if (filesChanged || assetsChanged) { if (notifications) notifications.resourcesChanged(); else await server.sendResourceListChanged(); }
527
+ const checking = options.config.mcp.previewManifest && previewWatch?.status().state === "running"
528
+ && builds().previews.some(entry => ["idle", "building"].includes(entry.state)
529
+ || entry.diagnostics.some(item => item.code === "ADS_PREVIEW_STALE_SOURCE"));
530
+ deferredDiscovery ||= filesChanged;
531
+ const discoveryChanged = deferredDiscovery && !checking;
532
+ if (discoveryChanged) deferredDiscovery = false;
533
+ if (discoveryChanged || assetsChanged) { if (notifications) notifications.resourcesChanged(); else await server.sendResourceListChanged(); }
493
534
  previousArtifacts = artifactFingerprint();
494
535
  previousAssets = assetFingerprint();
495
536
  previousBuild = JSON.stringify(builds());
496
- const targets = filesChanged ? era === "modern" ? resources().map((entry) => entry.uri).filter((uri) => !skills.files.has(uri)) : [...subscribed]
497
- : [BUILD_URI, BEHAVIOR_URI, INVESTIGATIONS_URI, `${PROJECT_URI}/status`, ...(options.config.mcp.previewManifest ? [PREVIEW_MANIFEST_URI] : []), ...(artifactsChanged ? allApps().map(app => appUri(app.id)) : [])].filter((uri) => era === "modern" || subscribed.has(uri));
537
+ const targets = discoveryChanged ? era === "modern" ? resources().map((entry) => entry.uri).filter((uri) => !skills.files.has(uri)) : [...subscribed]
538
+ : [BUILD_URI, BEHAVIOR_URI, INVESTIGATIONS_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));
498
539
  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();}
499
540
  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();}
500
- if (capturesChanged || filesChanged) {
541
+ if (capturesChanged || discoveryChanged) {
501
542
  const current = (captures.store.fingerprint() ? captureIndex().captures : []).flatMap(record => [record.current?.resourceUri, record.candidate?.resourceUri].filter(Boolean));
502
543
  targets.push(...[CAPTURES_URI, ...previousCaptureUris, ...current].filter(uri => era === "modern" || subscribed.has(uri)));
503
544
  previousCaptureUris = current;
@@ -510,7 +551,7 @@ export function createAdsMcp(directory, { era = "legacy", skillDirectory, pollIn
510
551
  timer?.unref();
511
552
  server.oninitialized = () => previewWatch?.start();
512
553
  server.onclose = () => { if (timer) clearInterval(timer); };
513
- return { server, refresh, async close() { if (timer) clearInterval(timer); if (!inspection) { await verification.close(); await captures.close(); } await server.close(); } };
554
+ return { server, refresh, async close() { if (timer) clearInterval(timer); if (!inspection) { await validation.close(); await verification.close(); await captures.close(); } await server.close(); } };
514
555
  }
515
556
 
516
557
  export async function startAdsMcp(directory = process.cwd(), { stdio = true, showcase = true, port = 0, mutations = false } = {}) {
@@ -521,7 +562,7 @@ export async function startAdsMcp(directory = process.cwd(), { stdio = true, sho
521
562
  let host;
522
563
  const showcaseUrl = () => host?.url;
523
564
  if (showcase) {
524
- host = await startShowcaseHost(({ era }) => createAdsMcp(directory, { era, previewWatch, showcaseUrl, inspection, mutations, pollInterval: 0 }).server,
565
+ host = await startShowcaseHost(({ era }) => createAdsMcp(directory, { era, previewWatch, showcaseUrl, inspection, mutations, pollInterval: 0, observeChanges:false }).server,
525
566
  { port, observe: notifications => createAdsMcp(directory, { era: "modern", previewWatch, showcaseUrl, inspection, mutations, notifications }) });
526
567
  process.stderr.write(`ADS showcase: ${host.url}\n`);
527
568
  }
@@ -535,6 +576,7 @@ export async function startAdsMcp(directory = process.cwd(), { stdio = true, sho
535
576
  const results = await Promise.allSettled([
536
577
  Promise.resolve().then(() => host?.close()),
537
578
  previewWatch.stop(),
579
+ Promise.resolve().then(() => inspection.validation?.close()),
538
580
  Promise.resolve().then(() => inspection.verification?.close()),
539
581
  Promise.resolve().then(() => inspection.captures?.close()),
540
582
  Promise.resolve().then(() => handle?.close()),
package/dist/oxlint.mjs CHANGED
@@ -1,5 +1,6 @@
1
1
  import path from "node:path";
2
- import { defaultConfig, importViolation } from "./config.mjs";
2
+ import { defaultConfig, importViolation, isTestFile } from "./config.mjs";
3
+ import { inspectUnits } from "./units.mjs";
3
4
  import { appImportViolation, showcaseImportViolation, importResolver } from "./boundaries.mjs";
4
5
 
5
6
  const schema = [{
@@ -59,6 +60,10 @@ export default {
59
60
  const resolve = importResolver(settings);
60
61
  const filename = path.resolve(context.getFilename());
61
62
  const buildFiles = new Set((settings.config.configurationFiles ?? []).map(file => path.resolve(settings.root,file)));
63
+ if (isTestFile(filename)) {
64
+ const inventory = inspectUnits({...settings,sourceRoot:path.resolve(settings.root,settings.config.sourceDir)});
65
+ settings.testOwner = file => inventory.owner(inventory.relative(path.relative(settings.root,file)));
66
+ }
62
67
  function inspect(node) {
63
68
  if (typeof node.source?.value !== "string") return;
64
69
  if (buildFiles.has(filename) && resolve(node.source.value,filename).every(file=>buildFiles.has(file))) return;
@@ -3,10 +3,12 @@ import { mkdirSync, rmSync, writeFileSync } from "node:fs";
3
3
  import path from "node:path";
4
4
  import { previewSourceRevision } from "./preview-inputs.mjs";
5
5
  import { createPreviewResources } from "./preview-resources.mjs";
6
+ import { createPreviewWorkerCache } from "./preview-workers.mjs";
6
7
 
7
8
  /** Project-owned Vite plugins/configuration, with a persistent development graph.
8
9
  * Watch output is private scratch data; only the compiler may publish it after
9
- * validation and its source/generation checks. Existing buildGraph adapters work
10
+ * the relevant source/generation checks; verified output also requires validation.
11
+ * Existing buildGraph adapters work
10
12
  * unchanged; opt in by passing this function as buildGraph. */
11
13
  export function createVitePreviewBuilder({ build, configure }) {
12
14
  let graph;
@@ -51,15 +53,19 @@ export function createVitePreviewBuilder({ build, configure }) {
51
53
  const capture = { name: "ads-incremental-preview", enforce: "post",
52
54
  buildStart() { started = previewSourceRevision(options); this.addWatchFile(trigger); },
53
55
  writeBundle(_output, bundle) {
54
- candidate = { source: started, output: { output: Object.values(bundle) }, modules: [...this.getModuleIds()] };
56
+ const inputs = [...this.getModuleIds(), ...this.getWatchFiles()].filter(id => !id.startsWith("\0"))
57
+ .map(id => path.isAbsolute(id) ? id : path.resolve(options.root, id));
58
+ candidate = { source: started, output: { output: Object.values(bundle) }, modules: [...new Set(inputs)]
59
+ .filter(file => !file.startsWith(directory + path.sep)) };
55
60
  },
56
61
  };
57
62
  try {
58
63
  const config = await configure(entries, options);
59
64
  const output = config.build?.rollupOptions?.output;
60
65
  if (Array.isArray(output) || output?.file) throw new Error("Incremental preview builds require one module output without output.file.");
61
- current.watcher = await build({ ...config, plugins: [...config.plugins ?? [], capture],
62
- build: { ...config.build, write: true, outDir: path.join(directory, "output"), emptyOutDir: true,
66
+ const workers = createPreviewWorkerCache(options, () => started === previewSourceRevision(options));
67
+ current.watcher = await build({ ...config, plugins: [...config.plugins ?? [], workers, capture],
68
+ build: { ...config.build, minify: false, cssMinify: false, reportCompressedSize: false, write: true, outDir: path.join(directory, "output"), emptyOutDir: true,
63
69
  rollupOptions: { ...config.build?.rollupOptions, output: { ...output, dir: path.join(directory, "output") } },
64
70
  watch: { ...config.build?.watch, skipWrite: false,
65
71
  // Bun's native fs-watch reattachment can miss rapid subsequent
@@ -1,31 +1,38 @@
1
1
  import { readdirSync } from "node:fs";
2
2
  import path from "node:path";
3
- import { isInside } from "./config.mjs";
4
3
 
5
4
  const metadata = new Set(["node_modules", ".git", ".ds", ".vite", "coverage"]);
6
5
  const generated = new Set(["dist", "build", "target", "out", ".next", ".nuxt", ".svelte-kit", ".turbo"]);
7
6
 
8
7
  /** Shared watch/fingerprint policy. Explicit source roots take priority over default outputs. */
9
- export function previewFileIgnored({root, config}, file) {
10
- const absolute = path.resolve(file), relative = path.relative(root, absolute);
11
- if (relative.split(path.sep).some(name => metadata.has(name))) return true;
12
- if (config.assets.generatedPaths.some(base => isInside(path.resolve(root, base), absolute))) return true;
13
- const sources = [config.dsDir, config.sourceDir].map(base => path.resolve(root, base));
14
- for (const name of relative.split(path.sep)) {
15
- if (!generated.has(name)) continue;
16
- if (!sources.some(source => isInside(source, absolute) || isInside(absolute, source))) return true;
17
- }
18
- return false;
8
+ export function createPreviewFileFilter({root, config}) {
9
+ const canonical = value => process.platform === "win32" ? value.toLowerCase() : value;
10
+ const relativePath = file => canonical(path.relative(root, path.resolve(root, file)));
11
+ const outputs = config.assets.generatedPaths.map(relativePath);
12
+ const sources = [config.dsDir, config.sourceDir].map(relativePath);
13
+ const within = (parent, file) => parent === ""
14
+ ? file !== ".." && !file.startsWith(`..${path.sep}`) && !path.isAbsolute(file)
15
+ : file === parent || file.startsWith(parent + path.sep);
16
+ return file => {
17
+ const relative = path.relative(root, path.resolve(file)), parts = relative.split(path.sep);
18
+ if (parts.some(name => metadata.has(name))) return true;
19
+ const key = canonical(relative);
20
+ if (outputs.some(base => within(base, key))) return true;
21
+ return parts.some(name => generated.has(name)) && !sources.some(source => within(source, key) || within(key, source));
22
+ };
19
23
  }
20
24
 
25
+ export const previewFileIgnored = (options, file) => createPreviewFileFilter(options)(file);
26
+
21
27
  /** Allocate individual watches so excluded descendants never consume OS watches. */
22
28
  export function previewWatchDirectories(options) {
23
29
  const directories = [];
30
+ const ignored = createPreviewFileFilter(options);
24
31
  function visit(directory) {
25
32
  directories.push(directory);
26
33
  for (const entry of readdirSync(directory, {withFileTypes:true})) {
27
34
  const child = path.join(directory, entry.name);
28
- if (entry.isDirectory() && !entry.isSymbolicLink() && !previewFileIgnored(options, child)) visit(child);
35
+ if (entry.isDirectory() && !entry.isSymbolicLink() && !ignored(child)) visit(child);
29
36
  }
30
37
  }
31
38
  visit(options.root);
@@ -1,9 +1,8 @@
1
1
  import { createHash } from "node:crypto";
2
- import { existsSync, readFileSync, readdirSync } from "node:fs";
3
2
  import path from "node:path";
4
- import { previewFileIgnored } from "./preview-files.mjs";
5
3
  import { isScenarioFile } from "./config.mjs";
6
4
  import { scenarioGroupFingerprint } from "./scenario-groups.mjs";
5
+ import { validationInputFiles } from "./validation-inputs.mjs";
7
6
 
8
7
  /** Shared source evidence for compilation, watch recovery and status reads. */
9
8
  export function previewSourceRevision(options, apps = options.config.mcp.apps ?? []) {
@@ -11,22 +10,12 @@ export function previewSourceRevision(options, apps = options.config.mcp.apps ??
11
10
  const rows = [];
12
11
  const scenarios = [];
13
12
  const outputs = new Set(apps.map(app => path.resolve(root,app.file)));
14
- function digest(file) { return createHash("sha256").update(readFileSync(file)).digest("hex"); }
15
- function visit(directory) {
16
- for (const entry of readdirSync(directory,{withFileTypes:true})) {
17
- if (entry.isSymbolicLink()) continue;
18
- const file = path.join(directory,entry.name);
19
- if (outputs.has(file) || previewFileIgnored(options,file)) continue;
20
- if (entry.isDirectory()) visit(file);
21
- else if (entry.isFile() && /\.(?:[cm]?[jt]sx?|css|html|json|md|svg|png|jpe?g|webp|gif|woff2?|ttf|otf|lock|lockb)$/.test(file)) {
22
- rows.push([path.relative(root,file),digest(file)]);
23
- if (isScenarioFile(file)) scenarios.push(file);
24
- }
25
- }
13
+ for (const [relative,digest] of Object.entries(validationInputFiles(options))) {
14
+ const file=path.resolve(root,relative);
15
+ if (outputs.has(file)) continue;
16
+ rows.push([relative,digest]);
17
+ if (digest && isScenarioFile(file)) scenarios.push(file);
26
18
  }
27
- visit(root);
28
19
  rows.push(["scenario-group-structure",scenarioGroupFingerprint(options,scenarios)]);
29
- const installed = path.join(root,"node_modules/.package-lock.json");
30
- rows.push(["installed-packages",existsSync(installed) ? digest(installed) : null]);
31
20
  return createHash("sha256").update(JSON.stringify(rows.sort((a,b)=>a[0].localeCompare(b[0])))).digest("hex");
32
21
  }