@reqvire-org/ads 0.4.5 → 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";
@@ -37,6 +37,8 @@ import { createPreviewWork } from "./preview-work.mjs";
37
37
  import { createCaptureController } from "../capture.mjs";
38
38
  import { CAPTURES_URI, captureSpec } from "../capture-store.mjs";
39
39
  import { previewSourceRevision } from "../preview-inputs.mjs";
40
+ import { outsideInputRequestScope, withInputRequestScope } from "../input-scope.mjs";
41
+ import { ownedInputSet, registerInputDigests } from "../validation-inputs.mjs";
40
42
  import { createExecutionResults, RESULTS_URI, resultSections } from "./execution-results.mjs";
41
43
  import { behaviorSections } from "./behavior-pages.mjs";
42
44
  import { compactProgress, resultBudgets } from "./result-pages.mjs";
@@ -270,10 +272,11 @@ export async function createAdsMcp(
270
272
  return stored;
271
273
  }
272
274
  if (cache.registryTask?.revision !== revision) {
273
- const inspector = (cache.registryInspector ??= createScenarioInspector(root));
275
+ // Shared by later requests: start it outside this request's revision.
276
+ const inspector = (cache.registryInspector ??= outsideInputRequestScope(() => createScenarioInspector(root)));
274
277
  const task = {
275
278
  revision,
276
- promise: inspector.inspect(),
279
+ promise: outsideInputRequestScope(() => inspector.inspect()),
277
280
  };
278
281
  cache.registryTask = task;
279
282
  void task.promise
@@ -283,7 +286,7 @@ export async function createAdsMcp(
283
286
  .catch(() => {});
284
287
  }
285
288
  const registry = await cache.registryTask.promise;
286
- if ((await previewSourceRevision(loadConfig(root))) !== revision) continue;
289
+ if ((await previewSourceRevision(loadConfig(root), [], { fresh: true })) !== revision) continue;
287
290
  cache.registry = cache.lastRegistry = registry;
288
291
  cache.registryRevision = revision;
289
292
  cache.catalog = undefined;
@@ -371,10 +374,10 @@ export async function createAdsMcp(
371
374
  const revision = cache.registryRevision;
372
375
  if (cache.catalog && cache.catalogRevision === revision) return cache.catalog;
373
376
  if (cache.catalogTask?.revision !== revision) {
374
- const inspector = (cache.registryInspector ??= createScenarioInspector(root));
377
+ const inspector = (cache.registryInspector ??= outsideInputRequestScope(() => createScenarioInspector(root)));
375
378
  const task = {
376
379
  revision,
377
- promise: inspector.inspect(root, "catalog"),
380
+ promise: outsideInputRequestScope(() => inspector.inspect(root, "catalog")),
378
381
  };
379
382
  cache.catalogTask = task;
380
383
  void task.promise
@@ -384,7 +387,7 @@ export async function createAdsMcp(
384
387
  .catch(() => {});
385
388
  }
386
389
  const value = await cache.catalogTask.promise;
387
- if ((await previewSourceRevision(loadConfig(root))) !== revision) continue;
390
+ if ((await previewSourceRevision(loadConfig(root), [], { fresh: true })) !== revision) continue;
388
391
  cache.catalog = value.catalog;
389
392
  cache.catalogRevision = revision;
390
393
  cache.behaviorLibraries = {
@@ -828,7 +831,12 @@ export async function createAdsMcp(
828
831
  signal?.throwIfAborted();
829
832
  return { graph, readAsset: id => { signal?.throwIfAborted(); return readPreviewAsset(options, id, graph); } };
830
833
  }
831
- async function read(uri, signal) {
834
+ // Accepted-project reads share one input revision per request. Draft reads
835
+ // keep their own lifecycle (they may refresh the draft workspace first).
836
+ function read(uri, signal) {
837
+ return uri.startsWith("ads://drafts/") ? readResource(uri, signal) : withInputRequestScope(() => readResource(uri, signal), { label: `resource:${uri}` });
838
+ }
839
+ async function readResource(uri, signal) {
832
840
  if (uri === `${PROJECT_URI}/explorer`)
833
841
  return {
834
842
  contents: [
@@ -1237,7 +1245,15 @@ export async function createAdsMcp(
1237
1245
  } else await refresh();
1238
1246
  return result;
1239
1247
  }
1248
+ // Read-only accepted-project tools; mutations, validation, captures and
1249
+ // drafts keep fresh reads at every fence.
1250
+ const requestScopedTools = new Set(["ads_status", "ads_catalog", "ads_scenarios", "ads_show_scenario"]);
1240
1251
  function tools() {
1252
+ return toolDefinitions().map((tool) =>
1253
+ requestScopedTools.has(tool.name) ? { ...tool, call: (...args) => withInputRequestScope(() => tool.call(...args), { label: `tool:${tool.name}` }) } : tool,
1254
+ );
1255
+ }
1256
+ function toolDefinitions() {
1241
1257
  return [
1242
1258
  {
1243
1259
  name: "ads_drafts",
@@ -2193,6 +2209,31 @@ export async function createAdsMcp(
2193
2209
  }
2194
2210
  // Modern HTTP serves a fresh protocol instance per request. Its shared observer
2195
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;
2196
2237
  if (observeChanges) await initializeObservation();
2197
2238
  let deferredDiscovery = false;
2198
2239
  let refreshing,
@@ -2213,7 +2254,8 @@ export async function createAdsMcp(
2213
2254
  refreshAgain = false;
2214
2255
  const forced = refreshForced;
2215
2256
  refreshForced = false;
2216
- changed = (await refreshOnce(forced)) || changed;
2257
+ // One input revision per observation pass (each status read used to walk again).
2258
+ changed = (await withInputRequestScope(() => refreshOnce(forced), { own: true, label: "observe" })) || changed;
2217
2259
  }
2218
2260
  return changed;
2219
2261
  })
@@ -2380,6 +2422,7 @@ export async function createAdsMcp(
2380
2422
  observationClosed = true;
2381
2423
  draftObservers.delete(refresh);
2382
2424
  if (timer) clearInterval(timer);
2425
+ unregisterDigests?.();
2383
2426
  };
2384
2427
  server.oninitialized = () => previewWatch?.start();
2385
2428
  server.onclose = async () => {
@@ -2454,30 +2497,21 @@ export function createDraftPreview(workspace, { id, host, showcaseUrl, mountPrev
2454
2497
  pollInterval: 0,
2455
2498
  observeChanges: false,
2456
2499
  }));
2457
- let watcher;
2458
- try {
2459
- mkdirSync(path.join(root, ".ds"), {
2460
- recursive: true,
2461
- });
2462
- watcher = watch(path.join(root, ".ds"), (_event, file) => {
2463
- const selected = previewWatch.resourceSession();
2464
- if (String(file) !== (selected ? `build-status-${selected}.json` : "build-status.json")) return;
2465
- clearTimeout(timer);
2466
- timer = setTimeout(async () => {
2467
- try {
2468
- const report = await previewWatch.buildStatus();
2469
- for (const listener of listeners) listener(report);
2470
- } catch {
2471
- /* Retried on the next report. */
2472
- }
2473
- }, 16);
2474
- timer.unref();
2475
- });
2476
- watcher.unref();
2477
- watcher.on("error", () => watcher.close());
2478
- } catch {
2479
- /* Build changes still arrive through explicit status reads. */
2480
- }
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 };
2481
2515
  // The draft's own showcase, mounted on the project's host: the real standalone scenario page that
2482
2516
  // audits, captures and behavior checks open.
2483
2517
  const base = showcaseUrl?.(),
@@ -2532,6 +2566,8 @@ export function createDraftPreview(workspace, { id, host, showcaseUrl, mountPrev
2532
2566
  callTool: async (name, args, signal) => (await preview()).callTool(name, args, signal),
2533
2567
  readResource: async (uri, signal) => (await preview()).readResource(uri, signal),
2534
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),
2535
2571
  // The draft's verified preview revision, as the project host reports its own: captures and
2536
2572
  // behavior evidence record which build they observed.
2537
2573
  previewRevision: () => readPreviewManifest(withPreviewSession(loadConfig(root), previewWatch.resourceSession()))?.revision ?? null,
@@ -2584,7 +2620,7 @@ export async function startAdsMcp(
2584
2620
  compiler,
2585
2621
  });
2586
2622
  let host, api;
2587
- let buildWatcher, buildChangeTimer;
2623
+ let buildWatcher, buildChangeTimer, reportChanged;
2588
2624
  const buildListeners = new Set();
2589
2625
  const onBuildChange = (report) => {
2590
2626
  host?.buildChanged(report);
@@ -2654,24 +2690,21 @@ export async function startAdsMcp(
2654
2690
  )
2655
2691
  : null;
2656
2692
  try {
2657
- buildWatcher = watch(path.join(root, ".ds"), (_event, file) => {
2658
- const selected = previewWatch.resourceSession();
2659
- 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 = () => {
2660
2695
  clearTimeout(buildChangeTimer);
2661
2696
  buildChangeTimer = setTimeout(async () => {
2662
2697
  try {
2663
- 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" }));
2664
2700
  } catch {
2665
2701
  /* The polling observer retries transient writes. */
2666
2702
  }
2667
2703
  for (const refresh of inspection.draftObservers ?? []) void refresh().catch(() => {});
2668
2704
  }, 16);
2669
2705
  buildChangeTimer.unref();
2670
- });
2671
- buildWatcher.unref();
2672
- buildWatcher.on("error", () => {
2673
- buildWatcher.close();
2674
- });
2706
+ };
2707
+ buildWatcher = { close: (previewWatch.onReport ?? (() => () => {}))(reportChanged) };
2675
2708
  } catch {
2676
2709
  /* Periodic observation also covers replaced/missing report directories. */
2677
2710
  }
@@ -2765,6 +2798,8 @@ export async function startAdsMcp(
2765
2798
  return () => buildListeners.delete(listener);
2766
2799
  },
2767
2800
  buildStatus: async () => previewWatch.buildStatus(),
2801
+ /** Re-read build status and notify clients, exactly as when a compiler report arrives. */
2802
+ refreshBuildStatus: () => reportChanged?.(),
2768
2803
  primeRegistry(registry) {
2769
2804
  if (inspection.registry === registry || inspection.lastRegistry === registry) return;
2770
2805
  inspection.registry = inspection.lastRegistry = registry;
@@ -6,6 +6,7 @@ import { Readable } from "node:stream";
6
6
  import { createMcpHandler, isLegacyRequest, WebStandardStreamableHTTPServerTransport } from "@modelcontextprotocol/server";
7
7
  import { serveShowcaseHttp, showcaseHttpEvents } from "./showcase-http.mjs";
8
8
  import { startSandboxHost } from "./sandbox-host.mjs";
9
+ import timing from "../stage-timing.cjs";
9
10
 
10
11
  const maxRequestBodySize = 2 * 1024 * 1024,
11
12
  maxLegacySessions = 64;
@@ -147,7 +148,7 @@ export async function startShowcaseHost(factory, { port = 0, observe } = {}) {
147
148
  if (!service) { res.writeHead(503); res.end("Showcase service unavailable."); return; }
148
149
  const abort = new AbortController(); requests.add(abort);
149
150
  res.once("close", () => { requests.delete(abort); abort.abort(); });
150
- await serveShowcaseHttp(req, res, route.slice(5) + url.search, service, abort.signal);
151
+ await timing.timeStage(`showcase-api:${req.method} ${route.slice(5).replace(/^drafts\/[^/]+\//, "drafts/*/")}`, () => serveShowcaseHttp(req, res, route.slice(5) + url.search, service, abort.signal));
151
152
  return;
152
153
  }
153
154
  const asset = assets.get(route);
@@ -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,15 +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
+ import timing from "./stage-timing.cjs";
6
7
 
7
- /** Shared source evidence for compilation, watch recovery and status reads. */
8
- export async function previewSourceRevision(options,apps=[]){
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. */
12
+ export function previewSourceRevision(options,apps=[],fence={}){
13
+ return timing.timeStage("preview-source-revision", () => revision(options,apps,ownedInputFiles(options,fence)));
14
+ }
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){
9
23
  const {root} = options;
10
24
  const rows = [];
11
25
  const scenarios = [];
12
26
  const outputs = new Set(apps.map(app => path.resolve(root,app.file)));
13
- for (const [relative,digest] of Object.entries(await validationInputFiles(options))){
27
+ for (const [relative,digest] of Object.entries(await inputs)){
14
28
  const file=path.resolve(root,relative);
15
29
  if (outputs.has(file)) continue;
16
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
 
@@ -121,7 +121,7 @@ export async function prepareScenarioRegistryTransfer(candidate, target) {
121
121
  registry = read(candidate, revision);
122
122
  if (!registry) return null;
123
123
  return async () => {
124
- if ((await previewSourceRevision(target)) !== revision || !validRegistry(registry, target)) return false;
124
+ if ((await previewSourceRevision(target, [], { fresh: true })) !== revision || !validRegistry(registry, target)) return false;
125
125
  write(target, revision, registry);
126
126
  return true;
127
127
  };
@@ -140,7 +140,7 @@ export async function discoverScenarioRegistry(options) {
140
140
  const cached = read(current, revision);
141
141
  if (cached) return cached;
142
142
  const registry = await inspectScenarios(current, await programFor(current.root).build(current));
143
- if (revision !== (await previewSourceRevision(loadConfig(current.root)))) continue;
143
+ if (revision !== (await previewSourceRevision(loadConfig(current.root), [], { fresh: true }))) continue;
144
144
  write(current, revision, registry);
145
145
  return registry;
146
146
  }