@reqvire-org/ads 0.4.6 → 0.4.7

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.
@@ -2,7 +2,7 @@ import { watchThemesCss } from "../themes-watch.mjs";
2
2
  import { randomUUID } from "node:crypto";
3
3
  import { executionContext } from "./execution-context.mjs";
4
4
  import { createExecutionCoordinator } from "./execution-coordinator.mjs";
5
- import { mkdirSync, readFileSync, statSync, watch } from "node:fs";
5
+ import { readFileSync, statSync } from "node:fs";
6
6
  import path from "node:path";
7
7
  import { Server, ProtocolError, INVALID_PARAMS, ResourceNotFoundError } from "@modelcontextprotocol/server";
8
8
  import { serveStdio, StdioServerTransport } from "@modelcontextprotocol/server/stdio";
@@ -38,6 +38,7 @@ import { createCaptureController } from "../capture.mjs";
38
38
  import { CAPTURES_URI, captureSpec } from "../capture-store.mjs";
39
39
  import { previewSourceRevision } from "../preview-inputs.mjs";
40
40
  import { outsideInputRequestScope, withInputRequestScope } from "../input-scope.mjs";
41
+ import { ownedInputSet, registerInputDigests } from "../validation-inputs.mjs";
41
42
  import { createExecutionResults, RESULTS_URI, resultSections } from "./execution-results.mjs";
42
43
  import { behaviorSections } from "./behavior-pages.mjs";
43
44
  import { compactProgress, resultBudgets } from "./result-pages.mjs";
@@ -2208,6 +2209,31 @@ export async function createAdsMcp(
2208
2209
  }
2209
2210
  // Modern HTTP serves a fresh protocol instance per request. Its shared observer
2210
2211
  // already tracks changes; immutable byte reads need no source/build scan.
2212
+ // One process watches: the managed compiler keeps the digest map of ADS-owned
2213
+ // inputs and publishes it per session. Request scopes and observation passes
2214
+ // read that map, so build reports and status checks come from the same events.
2215
+ // Without a running managed compiler, reads walk the owned inputs instead.
2216
+ const unregisterDigests =
2217
+ observeChanges && previewWatch
2218
+ ? registerInputDigests(
2219
+ {
2220
+ root,
2221
+ key: (candidate) => ownedInputSet(root).key(candidate),
2222
+ // The running compiler's latest map for this session, or null (then readers walk).
2223
+ async current() {
2224
+ const session = previewWatch.resourceSession?.();
2225
+ // Ask the compiler for its map as of now (events it already received are
2226
+ // re-read first); without an answer, readers walk the owned inputs.
2227
+ const published = session && previewWatch.status?.().state === "running" ? ((await previewWatch.flushDigests?.(session)) ?? null) : null;
2228
+ if (!published || published.key !== ownedInputSet(root).key(loadConfig(root))) return null;
2229
+ // Provisional (an event the compiler has not re-read yet): this revision can
2230
+ // match no build, so status waits instead of calling the old build current.
2231
+ return published.pending ? { ...published.digests, "ads:inputs-changing": "pending" } : published.digests;
2232
+ },
2233
+ },
2234
+ { set: "owned" },
2235
+ )
2236
+ : undefined;
2211
2237
  if (observeChanges) await initializeObservation();
2212
2238
  let deferredDiscovery = false;
2213
2239
  let refreshing,
@@ -2396,6 +2422,7 @@ export async function createAdsMcp(
2396
2422
  observationClosed = true;
2397
2423
  draftObservers.delete(refresh);
2398
2424
  if (timer) clearInterval(timer);
2425
+ unregisterDigests?.();
2399
2426
  };
2400
2427
  server.oninitialized = () => previewWatch?.start();
2401
2428
  server.onclose = async () => {
@@ -2470,30 +2497,21 @@ export function createDraftPreview(workspace, { id, host, showcaseUrl, mountPrev
2470
2497
  pollInterval: 0,
2471
2498
  observeChanges: false,
2472
2499
  }));
2473
- let watcher;
2474
- try {
2475
- mkdirSync(path.join(root, ".ds"), {
2476
- recursive: true,
2477
- });
2478
- watcher = watch(path.join(root, ".ds"), (_event, file) => {
2479
- const selected = previewWatch.resourceSession();
2480
- if (String(file) !== (selected ? `build-status-${selected}.json` : "build-status.json")) return;
2481
- clearTimeout(timer);
2482
- timer = setTimeout(async () => {
2483
- try {
2484
- const report = await previewWatch.buildStatus();
2485
- for (const listener of listeners) listener(report);
2486
- } catch {
2487
- /* Retried on the next report. */
2488
- }
2489
- }, 16);
2490
- timer.unref();
2491
- });
2492
- watcher.unref();
2493
- watcher.on("error", () => watcher.close());
2494
- } catch {
2495
- /* Build changes still arrive through explicit status reads. */
2496
- }
2500
+ // This draft's reports arrive over the host compiler's channel.
2501
+ const offReport = previewWatch.onReport((target) => {
2502
+ if (target !== previewWatch.resourceSession()) return;
2503
+ clearTimeout(timer);
2504
+ timer = setTimeout(async () => {
2505
+ try {
2506
+ const report = await previewWatch.buildStatus();
2507
+ for (const listener of listeners) listener(report);
2508
+ } catch {
2509
+ /* Retried on the next report. */
2510
+ }
2511
+ }, 16);
2512
+ timer.unref();
2513
+ });
2514
+ const watcher = { close: offReport };
2497
2515
  // The draft's own showcase, mounted on the project's host: the real standalone scenario page that
2498
2516
  // audits, captures and behavior checks open.
2499
2517
  const base = showcaseUrl?.(),
@@ -2548,6 +2566,8 @@ export function createDraftPreview(workspace, { id, host, showcaseUrl, mountPrev
2548
2566
  callTool: async (name, args, signal) => (await preview()).callTool(name, args, signal),
2549
2567
  readResource: async (uri, signal) => (await preview()).readResource(uri, signal),
2550
2568
  capturePreview: async (uri, signal) => (await preview()).capturePreview(uri, signal),
2569
+ /** Files the draft controller just wrote or removed in this workspace. */
2570
+ notifyChanges: (files) => previewWatch.notifyChanges(files),
2551
2571
  // The draft's verified preview revision, as the project host reports its own: captures and
2552
2572
  // behavior evidence record which build they observed.
2553
2573
  previewRevision: () => readPreviewManifest(withPreviewSession(loadConfig(root), previewWatch.resourceSession()))?.revision ?? null,
@@ -2600,7 +2620,7 @@ export async function startAdsMcp(
2600
2620
  compiler,
2601
2621
  });
2602
2622
  let host, api;
2603
- let buildWatcher, buildChangeTimer;
2623
+ let buildWatcher, buildChangeTimer, reportChanged;
2604
2624
  const buildListeners = new Set();
2605
2625
  const onBuildChange = (report) => {
2606
2626
  host?.buildChanged(report);
@@ -2670,24 +2690,21 @@ export async function startAdsMcp(
2670
2690
  )
2671
2691
  : null;
2672
2692
  try {
2673
- buildWatcher = watch(path.join(root, ".ds"), (_event, file) => {
2674
- const selected = previewWatch.resourceSession();
2675
- if (String(file) !== (selected ? `build-status-${selected}.json` : "build-status.json")) return;
2693
+ // Reports arrive over the compiler channel (project and hosted drafts).
2694
+ reportChanged = () => {
2676
2695
  clearTimeout(buildChangeTimer);
2677
2696
  buildChangeTimer = setTimeout(async () => {
2678
2697
  try {
2679
- onBuildChange(await previewWatch.buildStatus());
2698
+ // Each report change is one status read against the project's digest map.
2699
+ onBuildChange(await withInputRequestScope(() => previewWatch.buildStatus(), { own: true, label: "build-change" }));
2680
2700
  } catch {
2681
2701
  /* The polling observer retries transient writes. */
2682
2702
  }
2683
2703
  for (const refresh of inspection.draftObservers ?? []) void refresh().catch(() => {});
2684
2704
  }, 16);
2685
2705
  buildChangeTimer.unref();
2686
- });
2687
- buildWatcher.unref();
2688
- buildWatcher.on("error", () => {
2689
- buildWatcher.close();
2690
- });
2706
+ };
2707
+ buildWatcher = { close: (previewWatch.onReport ?? (() => () => {}))(reportChanged) };
2691
2708
  } catch {
2692
2709
  /* Periodic observation also covers replaced/missing report directories. */
2693
2710
  }
@@ -2781,6 +2798,8 @@ export async function startAdsMcp(
2781
2798
  return () => buildListeners.delete(listener);
2782
2799
  },
2783
2800
  buildStatus: async () => previewWatch.buildStatus(),
2801
+ /** Re-read build status and notify clients, exactly as when a compiler report arrives. */
2802
+ refreshBuildStatus: () => reportChanged?.(),
2784
2803
  primeRegistry(registry) {
2785
2804
  if (inspection.registry === registry || inspection.lastRegistry === registry) return;
2786
2805
  inspection.registry = inspection.lastRegistry = registry;
@@ -10,7 +10,7 @@ import selectorParser from "postcss-selector-parser";
10
10
  import valueParser from "postcss-value-parser";
11
11
  import { transform, TransformCacheCollection, disposeEvalBroker } from "@wyw-in-js/transform";
12
12
  import { createPreviewResources } from "./preview-resources.mjs";
13
- import { previewSourceRevision } from "./preview-inputs.mjs";
13
+ import { previewBuildRevision } from "./preview-inputs.mjs";
14
14
  import { linariaTagResolver } from "./linaria.mjs";
15
15
  import { createPreviewImportOptimizer } from "./preview-imports.mjs";
16
16
  import { assertBunRuntime } from "./runtime-requirements.mjs";
@@ -182,7 +182,7 @@ export function createBunPreviewBuilder() {
182
182
  closed = false,
183
183
  workerQueue = Promise.resolve();
184
184
  const builder = async (entries, options, track, { watched = false, workerEntry, workerAncestors = [], sourceRevision } = {}) => {
185
- sourceRevision ??= await previewSourceRevision(options);
185
+ sourceRevision ??= await previewBuildRevision(options);
186
186
  if (closed) throw new Error("Preview compiler is closed.");
187
187
  const signature = JSON.stringify([options.root, options.config, watched]);
188
188
  if (context !== signature) {
@@ -2,20 +2,29 @@ import { createHash } from "node:crypto";
2
2
  import path from "node:path";
3
3
  import { isScenarioFile } from "./config.mjs";
4
4
  import { scenarioGroupFingerprint } from "./scenario-groups.mjs";
5
- import { validationInputFiles } from "./validation-inputs.mjs";
5
+ import { ownedInputFiles } from "./validation-inputs.mjs";
6
6
  import timing from "./stage-timing.cjs";
7
7
 
8
- /** Shared source evidence for compilation, watch recovery and status reads. */
9
- /** `fence`: { fresh } re-walks after long work; { observed } pairs the walk with external evidence. */
8
+ /** Preview freshness: build status, discovery caches, captures and watch recovery.
9
+ * Derived from the ADS-owned inputs only (configuration, design system, declared
10
+ * public folders). `fence`: { fresh } re-walks after long work; { observed }
11
+ * pairs the walk with external evidence. */
10
12
  export function previewSourceRevision(options,apps=[],fence={}){
11
- return timing.timeStage("preview-source-revision", () => sourceRevision(options,apps,fence));
13
+ return timing.timeStage("preview-source-revision", () => revision(options,apps,ownedInputFiles(options,fence)));
12
14
  }
13
- async function sourceRevision(options,apps,fence){
15
+
16
+ /** Compiler cache keys: the ADS-owned inputs only. Package versions are pinned
17
+ * in ds.config.json; ADS reads no project-owned file to key compiled bytes. */
18
+ export function previewBuildRevision(options,apps=[],fence={}){
19
+ return timing.timeStage("preview-build-revision", () => revision(options,apps,ownedInputFiles(options,fence)));
20
+ }
21
+
22
+ async function revision(options,apps,inputs){
14
23
  const {root} = options;
15
24
  const rows = [];
16
25
  const scenarios = [];
17
26
  const outputs = new Set(apps.map(app => path.resolve(root,app.file)));
18
- for (const [relative,digest] of Object.entries(await validationInputFiles(options,[],fence))){
27
+ for (const [relative,digest] of Object.entries(await inputs)){
19
28
  const file=path.resolve(root,relative);
20
29
  if (outputs.has(file)) continue;
21
30
  rows.push([relative,digest]);
@@ -1,4 +1,4 @@
1
- import { spawn, execFile } from "node:child_process";
1
+ import { spawn, execFile, execFileSync } from "node:child_process";
2
2
  import { existsSync, mkdtempSync, readFileSync, readdirSync, rmSync, writeFileSync } from "node:fs";
3
3
  import os from "node:os";
4
4
  import path from "node:path";
@@ -35,13 +35,35 @@ function hostMemory() {
35
35
  } catch {
36
36
  /* A watchdog can still enforce the process budget. */
37
37
  }
38
- }
38
+ } else if (process.platform === "darwin") available = darwinAvailable() ?? available;
39
39
  return { totalMb: os.totalmem() / MiB, availableMb: available / MiB, parentLimitMb: parentLimit / MiB };
40
40
  }
41
41
 
42
+ // macOS's free memory excludes inactive, speculative and purgeable pages the
43
+ // kernel reclaims on demand, so os.freemem() alone understates what is available.
44
+ function darwinAvailable() {
45
+ try {
46
+ return parseDarwinAvailable(execFileSync("vm_stat", { timeout: 2000, encoding: "utf8" }));
47
+ } catch {
48
+ return null;
49
+ }
50
+ }
51
+
52
+ /** Parse vm_stat output (exported for tests). */
53
+ export function parseDarwinAvailable(text) {
54
+ const page = Number(text.match(/page size of (\d+) bytes/)?.[1]),
55
+ pages = (name) => Number(text.match(new RegExp(`^Pages ${name}:\\s+(\\d+)`, "m"))?.[1] ?? 0);
56
+ return page ? (pages("free") + pages("inactive") + pages("speculative") + pages("purgeable")) * page : null;
57
+ }
58
+
42
59
  export function resolveMemoryBudget(resources = {}, host) {
43
60
  if (host === undefined) host = hostMemory();
44
- const automatic = Math.max(128, Math.floor(Math.min(6144, host.totalMb / 4, Math.max(128, host.availableMb - 1024))));
61
+ // Momentary free memory varies minute to minute; a normal showcase (compiler,
62
+ // analysis workers, native TypeScript) needs about 2 GiB. Never go below
63
+ // min(3 GiB, half of RAM) automatically: the limit stops runaways, it should not
64
+ // fail ordinary sessions on a busy machine.
65
+ const floor = Math.min(3072, host.totalMb / 2);
66
+ const automatic = Math.max(128, Math.floor(Math.min(6144, Math.max(floor, Math.min(host.totalMb / 4, host.availableMb - 1024)))));
45
67
  return Math.max(64, Math.floor(Math.min(resources.memoryLimitMb ?? automatic, host.parentLimitMb ?? Infinity)));
46
68
  }
47
69
 
@@ -10,13 +10,14 @@ import { prepareScenarioRegistryTransfer, releaseScenarioRegistry } from "./scen
10
10
  import { artifactDigest, createBuildReporter } from "./mcp/build-status.mjs";
11
11
  import { cachedPreviewPublication, previewArtifactHtml, readPreviewManifest } from "./preview-resources.mjs";
12
12
  import { previewArtifactPath, withPreviewSession } from "./preview-scope.mjs";
13
- import { previewSourceRevision } from "./preview-inputs.mjs";
13
+ import { previewBuildRevision, previewSourceRevision } from "./preview-inputs.mjs";
14
14
  import { queuePreviewRequests } from "./preview-requests.mjs";
15
- import { previewFileIgnored, previewWatchDirectories } from "./preview-files.mjs";
15
+ import { previewFileIgnored } from "./preview-files.mjs";
16
16
  import { createScenarioInspector } from "./scenario-inspector.mjs";
17
17
  import { analyze } from "./analysis/service.mjs";
18
- import { configurationFiles } from "./units.mjs";
19
- import { validationInputFiles } from "./validation-inputs.mjs";
18
+ import { ownedInputSet, registerInputDigests } from "./validation-inputs.mjs";
19
+ import { createInputDigests } from "./input-digests.mjs";
20
+ import { compilerChannel } from "./mcp/compiler-channel.mjs";
20
21
  import { previewRuntimeFingerprint } from "./runtime-requirements.mjs";
21
22
  import { architectureExternalInputs } from "./task-cache.mjs";
22
23
 
@@ -89,7 +90,7 @@ export function createPreviewCache(options, compilerFiles = []) {
89
90
  reload();
90
91
  async function inputs() {
91
92
  const rows = [
92
- ["project-inputs", await previewSourceRevision(options)],
93
+ ["project-inputs", await previewBuildRevision(options)],
93
94
  ["runtime", previewRuntimeFingerprint()],
94
95
  ["architecture-environment", { ...architectureExternalInputs(root), environment: launchEnvironment }],
95
96
  ];
@@ -122,34 +123,11 @@ export function createPreviewCache(options, compilerFiles = []) {
122
123
  rmSync(temporary, { force: true });
123
124
  }
124
125
  }
125
- async function compilerInputs() {
126
- const configured = new Set([...(await configurationFiles(options))].filter((file) => !/^(?:biome|oxlint|\.oxlint)/.test(file)));
127
- const packages = new Set([
128
- "package-lock.json",
129
- "npm-shrinkwrap.json",
130
- "yarn.lock",
131
- "pnpm-lock.yaml",
132
- "bun.lock",
133
- "bun.lockb",
134
- "bunfig.toml",
135
- ".npmrc",
136
- ".yarnrc.yml",
137
- "installed-dependencies",
138
- ]);
139
- const opaque = (options.config.validation?.inputs ?? []).map((file) => path.resolve(root, file));
140
- // Use the same declared configuration/input boundary as guarded copies.
141
- // Unrelated local launcher JSON must not make a candidate unportable.
142
- return Object.entries(await validationInputFiles(options))
143
- .filter(([file]) => configured.has(file) || packages.has(file) || opaque.some((directory) => isInside(directory, path.resolve(root, file))))
144
- .sort(([a], [b]) => a.localeCompare(b));
145
- }
146
126
  const compilerDigest = async () =>
147
127
  digest(
148
128
  JSON.stringify([
149
129
  ["adapter", adapterDigest()],
150
130
  ...compilerFiles.map((file) => [key(file), fileDigest(file)]),
151
- ...(await compilerInputs()),
152
- ["installed-packages", fileDigest(path.join(root, "node_modules/.package-lock.json"))],
153
131
  ["scheduler", fileDigest(import.meta.filename)],
154
132
  ["runtime", previewRuntimeFingerprint()],
155
133
  ]),
@@ -407,15 +385,11 @@ function createScheduler() {
407
385
  * with the options setup(root) gives for its own root and a builder of its own. Compiler options
408
386
  * fixed to one root cannot build a draft; each draft then reports that instead of waiting.
409
387
  */
410
- async function hostDrafts(file, setup, schedule) {
388
+ async function hostDrafts(channel, setup, schedule) {
411
389
  const instances = new Map();
390
+ let wanted = [],
391
+ reconciling = Promise.resolve();
412
392
  async function reconcile() {
413
- let wanted = [];
414
- try {
415
- wanted = JSON.parse(readFileSync(file, "utf8")).drafts ?? [];
416
- } catch {
417
- /* No drafts yet. */
418
- }
419
393
  const sessions = new Set(wanted.map((entry) => entry.session));
420
394
  for (const [session, instance] of instances)
421
395
  if (!sessions.has(session)) {
@@ -424,10 +398,10 @@ async function hostDrafts(file, setup, schedule) {
424
398
  }
425
399
  for (const entry of wanted) {
426
400
  if (instances.has(entry.session) || !isDraftPreviewWorkspace(entry.root)) continue;
427
- const context = { session: entry.session, requestFile: entry.requestFile, statusFile: entry.statusFile, prewarm: false, schedule: schedule("draft") };
401
+ const context = { session: entry.session, prewarm: false, schedule: schedule("draft") };
428
402
  if (!setup) {
429
403
  instances.set(entry.session, Promise.resolve(null));
430
- createBuildReporter(entry.root, { apps: [], session: entry.session, file: entry.statusFile }).failure(
404
+ createBuildReporter(entry.root, { apps: [], session: entry.session }).failure(
431
405
  scopedPreviewFailure(
432
406
  new Error(
433
407
  "This project's preview compiler passes runScenarioCompiler options for one root, so it cannot build drafts. Pass a function of the root that returns the options instead.",
@@ -447,18 +421,15 @@ async function hostDrafts(file, setup, schedule) {
447
421
  );
448
422
  }
449
423
  }
450
- void (await reconcile());
451
- let timer;
452
- const watcher = watch(path.dirname(file), (_event, name) => {
453
- if (String(name) === path.basename(file)) {
454
- clearTimeout(timer);
455
- timer = setTimeout(async () => void (await reconcile()), 16);
456
- }
424
+ // The MCP watcher sends the current draft list (and replays it after a reconnect).
425
+ const off = channel.on("drafts", (message) => {
426
+ wanted = (Array.isArray(message.drafts) ? message.drafts : []).filter((entry) => typeof entry?.root === "string" && typeof entry?.session === "string");
427
+ reconciling = reconciling.then(reconcile, reconcile);
457
428
  });
458
429
  return {
459
430
  async stop() {
460
- watcher.close();
461
- clearTimeout(timer);
431
+ off();
432
+ await reconciling.catch(() => {});
462
433
  for (const instance of instances.values()) (await instance)?.stop();
463
434
  instances.clear();
464
435
  },
@@ -482,13 +453,13 @@ export async function runScenarioCompiler(directory, setup) {
482
453
  await buildGraph.close?.();
483
454
  return { async stop() {} };
484
455
  }
485
- const control = process.env.ADS_MCP_DRAFT_CONTROL,
486
- hosting = watched && !context.session && control && existsSync(path.dirname(control));
456
+ // An MCP-managed compiler talks to its watcher over one channel; the project
457
+ // instance also hosts that watcher's draft instances in this process.
458
+ const channel = watched ? compilerChannel() : null;
459
+ const hosting = !!channel && !context.session;
487
460
  const scheduler = hosting ? createScheduler() : null;
488
461
  const {
489
462
  session: buildSession = process.env.ADS_MCP_BUILD_SESSION,
490
- requestFile = process.env.ADS_MCP_REQUEST_FILE,
491
- statusFile = process.env.ADS_MCP_BUILD_STATUS,
492
463
  prewarm: prewarmViews = process.env.ADS_MCP_PREWARM_VIEWS === "1",
493
464
  schedule = scheduler ? scheduler("project") : (run) => run(),
494
465
  } = context;
@@ -522,7 +493,6 @@ export async function runScenarioCompiler(directory, setup) {
522
493
  const reporter = createBuildReporter(root, {
523
494
  apps: buildApps(),
524
495
  ...(buildSession ? { session: buildSession } : {}),
525
- ...(statusFile ? { file: statusFile } : {}),
526
496
  });
527
497
  const requested = new Set();
528
498
  const pending = new Set();
@@ -671,7 +641,7 @@ export async function runScenarioCompiler(directory, setup) {
671
641
  reusable = false;
672
642
  }
673
643
  }
674
- const outcomes = await checkedBuild(stamp, async () => (reusable ? null : await buildGraph(entries, options, track, { watched: false, sourceRevision })));
644
+ const outcomes = await checkedBuild(stamp, async () => (reusable ? null : await buildGraph(entries, options, track, { watched: false, sourceRevision: await previewBuildRevision(options) })));
675
645
  const failure = outcomes.find((outcome) => outcome.status === "rejected");
676
646
  if (failure) throw failure.reason;
677
647
  cache.assertCompiler();
@@ -778,7 +748,7 @@ export async function runScenarioCompiler(directory, setup) {
778
748
  candidate.reused = true;
779
749
  return cached;
780
750
  }
781
- return buildGraph(candidate.entries, options, track, { watched: true, sourceRevision });
751
+ return buildGraph(candidate.entries, options, track, { watched: true, sourceRevision: await previewBuildRevision(options) });
782
752
  });
783
753
  liveCandidate = candidate;
784
754
  try {
@@ -924,10 +894,7 @@ export async function runScenarioCompiler(directory, setup) {
924
894
  releaseScenarioRegistry(root);
925
895
  }
926
896
  completedFull = token;
927
- const file = path.join(root, ".ds", `full-build-${reporter.session}.json`),
928
- temporary = `${file}.tmp`;
929
- writeFileSync(temporary, JSON.stringify({ token, ok: !!ok, sourceRevision }));
930
- renameSync(temporary, file);
897
+ channel?.send({ type: "full-build", session: reporter.session, token, ok: !!ok, sourceRevision });
931
898
  continue;
932
899
  }
933
900
  if (registryFailure) break;
@@ -1002,12 +969,13 @@ export async function runScenarioCompiler(directory, setup) {
1002
969
  discovering = undefined;
1003
970
  });
1004
971
  }
972
+ // The watcher's latest preview request for this session (replayed on reconnect).
973
+ let latestRequest;
1005
974
  async function request(startBuild = true) {
1006
- const file = requestFile;
1007
- if (!file || !existsSync(file)) return;
975
+ const value = latestRequest;
976
+ if (!value) return;
1008
977
  try {
1009
- const value = JSON.parse(readFileSync(file, "utf8"));
1010
- if (value.session !== buildSession) return;
978
+ if (value.session !== buildSession || !Array.isArray(value.files)) return;
1011
979
  if (typeof value.full === "string" && /^[\w-]{1,100}$/.test(value.full)) fullRequest = value.full;
1012
980
  if (value.invalidation !== invalidation) {
1013
981
  invalidation = value.invalidation;
@@ -1034,7 +1002,39 @@ export async function runScenarioCompiler(directory, setup) {
1034
1002
  }
1035
1003
  let timer;
1036
1004
  const changed = new Set();
1037
- function sourceChanged(_event, file, topology = false) {
1005
+ // This process's watchers feed one digest map; every revision read here
1006
+ // (including the reconcile check) answers from it instead of walking again.
1007
+ // Build reports and compile cache keys both derive from the ADS-owned inputs,
1008
+ // exactly as the MCP server checks them.
1009
+ // This compiler owns the digest map of ADS-owned inputs. It sends each changed map
1010
+ // to its MCP watcher (same session), so reports and status checks share one view.
1011
+ const publishDigests = (digests) => {
1012
+ if (!stopped) channel?.send({ type: "digests", session: reporter.session, key: ownedInputSet(root).key(loadConfig(root)), digests });
1013
+ };
1014
+ // An event makes the map provisional at once; the watcher then reports no build as
1015
+ // current until this process has re-read the files and published the new map.
1016
+ let settleTimer;
1017
+ const pendingDigests = () => {
1018
+ if (stopped) return;
1019
+ channel?.send({ type: "digests-pending", session: reporter.session });
1020
+ clearTimeout(settleTimer);
1021
+ settleTimer = setTimeout(() => void digestMaps[0][0].current().catch((error) => failure(error)), 16);
1022
+ settleTimer.unref?.();
1023
+ };
1024
+ const digestMaps = [
1025
+ [
1026
+ createInputDigests(root, ownedInputSet(root), { watchFiles: false, onError: (error) => console.error(error), onUpdate: publishDigests, onPending: pendingDigests }),
1027
+ "owned",
1028
+ ],
1029
+ ];
1030
+ const unregisterDigests = digestMaps.map(([map, set]) => registerInputDigests(map, { set, unscoped: true }));
1031
+ const inputDigests = {
1032
+ notify: (...args) => digestMaps.forEach(([map]) => map.notify(...args)),
1033
+ invalidate: () => digestMaps.forEach(([map]) => map.invalidate()),
1034
+ close: () => digestMaps.forEach(([map]) => map.close()),
1035
+ };
1036
+ function sourceChanged(event, file, topology = false) {
1037
+ inputDigests.notify(file ?? null, event === "rename" || topology ? "rename" : "change");
1038
1038
  if (!file || (!topology && !/\.(?:[cm]?[jt]sx?|css|html|json|md|svg|png|jpe?g|webp|gif|woff2?|ttf|otf|lock|lockb)$/.test(file))) return;
1039
1039
  const absolute = path.join(root, file);
1040
1040
  if (previewFileIgnored(options, absolute)) return;
@@ -1093,6 +1093,7 @@ export async function runScenarioCompiler(directory, setup) {
1093
1093
  watcher.on("error", async (error) => {
1094
1094
  watcher.close();
1095
1095
  if (watchers.get(directory)?.watcher === watcher) watchers.delete(directory);
1096
+ inputDigests.invalidate(); // Events may have been missed: walk again.
1096
1097
  await failure(error);
1097
1098
  });
1098
1099
  return true;
@@ -1101,32 +1102,73 @@ export async function runScenarioCompiler(directory, setup) {
1101
1102
  }
1102
1103
  }
1103
1104
  async function reconcileWatches(initial = false) {
1104
- if (stopped) return;
1105
+ // Draft workspaces change only through MCP, which sends their changed files
1106
+ // over the channel; they need no watchers.
1107
+ if (stopped || draftWorkspace) return;
1105
1108
  try {
1106
- await addWatch(root, sourceChanged);
1107
- const wanted = new Set([root, path.join(root, ".ds")]);
1108
- for (const directory of previewWatchDirectories(options)) {
1109
- if (directory === root) continue;
1109
+ // Only ADS-owned inputs: ds.config.json and the folders it declares (plus
1110
+ // ADS's own .ds). A replaced config file gets a new identity and a new watch.
1111
+ const configFile = path.join(root, "ds.config.json");
1112
+ const wanted = new Set();
1113
+ if (existsSync(configFile)) {
1114
+ wanted.add(configFile);
1115
+ await addWatch(configFile, (event) => sourceChanged(event, "ds.config.json", event === "rename"));
1116
+ }
1117
+ // The compiler's own declared files (its command and adapters) restart it when they change.
1118
+ for (const file of compilerFiles.map((file) => path.resolve(file)))
1119
+ if (isInside(root, file) && existsSync(file) && !previewFileIgnored(options, file)) {
1120
+ wanted.add(file);
1121
+ await addWatch(file, (event) => sourceChanged(event, path.relative(root, file), true));
1122
+ }
1123
+ for (const directory of ownedInputSet(root).directories(options)) {
1124
+ if (directory === configFile) continue;
1110
1125
  wanted.add(directory);
1111
1126
  const relative = path.relative(root, directory);
1112
1127
  if ((await addWatch(directory, (event, file, topology) => sourceChanged(event, file && path.join(relative, file), topology))) && !initial)
1113
1128
  sourceChanged("rename", relative, true);
1114
1129
  }
1115
- mkdirSync(path.join(root, ".ds"), { recursive: true });
1116
- await addWatch(path.join(root, ".ds"), async (_event, file) => {
1117
- if (file === path.basename(requestFile ?? "")) await request();
1118
- });
1119
1130
  for (const [directory, { watcher }] of watchers)
1120
1131
  if (!wanted.has(directory) || !existsSync(directory)) {
1121
1132
  watcher.close();
1122
1133
  watchers.delete(directory);
1123
- if (!initial && directory !== root && directory !== path.join(root, ".ds")) sourceChanged("rename", path.relative(root, directory), true);
1134
+ if (!initial && directory !== configFile && !compilerFiles.some((file) => path.resolve(file) === directory))
1135
+ sourceChanged("rename", path.relative(root, directory), true);
1124
1136
  }
1125
1137
  } catch (error) {
1126
1138
  await failure(error);
1127
1139
  }
1128
1140
  }
1141
+ // Requests and (for drafts) MCP's change notices arrive over the channel.
1142
+ const channelHandlers = channel
1143
+ ? [
1144
+ channel.on("request", (message) => {
1145
+ if (message.session !== buildSession || !message.value || typeof message.value !== "object") return;
1146
+ latestRequest = message.value;
1147
+ void request();
1148
+ }),
1149
+ // A reader asks for the map as of now: process every event already delivered
1150
+ // (re-reading those files), then answer, even if nothing changed.
1151
+ channel.on("digests-flush", async (message) => {
1152
+ if (message.session !== buildSession || typeof message.id !== "string") return;
1153
+ try {
1154
+ await new Promise((resolve) => setImmediate(resolve));
1155
+ await new Promise((resolve) => setImmediate(resolve));
1156
+ const digests = await digestMaps[0][0].current();
1157
+ channel.send({ type: "digests", session: buildSession, key: ownedInputSet(root).key(loadConfig(root)), digests, flush: message.id });
1158
+ } catch (error) {
1159
+ channel.send({ type: "digests-flush-failed", session: buildSession, id: message.id, message: error.message });
1160
+ }
1161
+ }),
1162
+ channel.on("draft-changes", (message) => {
1163
+ if (message.session !== buildSession || !Array.isArray(message.files)) return;
1164
+ for (const change of message.files)
1165
+ if (typeof change?.path === "string") sourceChanged(change.kind === "rename" ? "rename" : "change", change.path, change.kind === "rename");
1166
+ }),
1167
+ ]
1168
+ : [];
1129
1169
  await reconcileWatches(true);
1170
+ // Publish the first map before any request reads it.
1171
+ await digestMaps[0][0].current().catch((error) => failure(error));
1130
1172
  const reconcileTimer = setInterval(async () => {
1131
1173
  // A retired draft workspace disappears before its host stops this instance.
1132
1174
  if (!existsSync(root)) {
@@ -1148,13 +1190,17 @@ export async function runScenarioCompiler(directory, setup) {
1148
1190
  await request();
1149
1191
  if (prewarm) void drain();
1150
1192
  console.log(`Scenario compiler ready: ${entries.length} entries; ${prewarm ? "sequential background warming enabled" : "builds are requested on demand"}.`);
1151
- const drafts = hosting ? await hostDrafts(control, typeof setup === "function" ? setup : null, scheduler) : null;
1193
+ const drafts = hosting ? await hostDrafts(channel, typeof setup === "function" ? setup : null, scheduler) : null;
1152
1194
  handle = {
1153
1195
  async stop() {
1154
1196
  if (stopped) return;
1155
1197
  stopped = true;
1156
1198
  clearTimeout(timer);
1157
1199
  clearInterval(reconcileTimer);
1200
+ for (const unregister of unregisterDigests) unregister();
1201
+ clearTimeout(settleTimer);
1202
+ inputDigests.close();
1203
+ for (const off of channelHandlers) off();
1158
1204
  for (const { watcher } of watchers.values()) watcher.close();
1159
1205
  void (await drafts?.stop());
1160
1206
  void (await inspector?.close());
@@ -23,8 +23,10 @@ style writes retain the exact properties declared in the owner contract's
23
23
  `styles.writes`; they do not allow
24
24
  shared-token overrides or an extra styling layer.
25
25
  Projects explicitly approve installed runtime packages through
26
- `behaviorLibraries` in `ds.config.json`; each must also be a `package.json`
27
- dependency. Components, patterns and controllers may use them directly, including
26
+ `behaviorLibraries` in `ds.config.json`, pinned to the exact installed version
27
+ (`"tabbable@6.2.0"`); each must also be a `package.json` dependency. Pin the
28
+ `framework` the same way (`"preact@10.27.2"`) and update a pin together with the
29
+ upgrade; `ads check` reports a pin that differs from the installed version. Components, patterns and controllers may use them directly, including
28
30
  package subpaths. Extract a shared controller when behavior is shared. Type-only
29
31
  and development-role imports retain their existing rules. An empty/missing list
30
32
  allows no additional runtime packages beyond the configured framework and Linaria.
@@ -23,8 +23,10 @@ style writes retain the exact properties declared in the owner contract's
23
23
  `styles.writes`; they do not allow
24
24
  shared-token overrides or an extra styling layer.
25
25
  Projects explicitly approve installed runtime packages through
26
- `behaviorLibraries` in `ds.config.json`; each must also be a `package.json`
27
- dependency. Components, patterns and controllers may use them directly, including
26
+ `behaviorLibraries` in `ds.config.json`, pinned to the exact installed version
27
+ (`"tabbable@6.2.0"`); each must also be a `package.json` dependency. Pin the
28
+ `framework` the same way (`"preact@10.27.2"`) and update a pin together with the
29
+ upgrade; `ads check` reports a pin that differs from the installed version. Components, patterns and controllers may use them directly, including
28
30
  package subpaths. Extract a shared controller when behavior is shared. Type-only
29
31
  and development-role imports retain their existing rules. An empty/missing list
30
32
  allows no additional runtime packages beyond the configured framework and Linaria.
@@ -56,3 +56,4 @@ Load only the guide(s) for the requested transition.
56
56
  | 0.4.1 | 0.4.2 | [Showcase, review boundaries and preview migration](references/0.4.1-to-0.4.2.md) |
57
57
  | 0.4.3 | 0.4.4 | [Incremental previews and manifest reuse](references/0.4.3-to-0.4.4.md) |
58
58
  | 0.4.4 | 0.4.5 | [HTTP showcase delivery and reconnect behavior](references/0.4.4-to-0.4.5.md) |
59
+ | 0.4.5 or 0.4.6 | 0.4.7 | [Pinned package versions and ADS-owned preview inputs](references/0.4.6-to-0.4.7.md) |