@reqvire-org/ads 0.3.34 → 0.3.36

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 (37) hide show
  1. package/dist/check-runner.mjs +7 -0
  2. package/dist/mcp/drafts.mjs +5 -2
  3. package/dist/mcp/mutation-limits.mjs +2 -0
  4. package/dist/mcp/mutations.mjs +20 -11
  5. package/dist/mcp/patch.mjs +5 -3
  6. package/dist/mcp/preview-owner-guard.mjs +36 -1
  7. package/dist/mcp/preview-watch.mjs +88 -13
  8. package/dist/mcp/preview-work.mjs +41 -0
  9. package/dist/mcp/server.mjs +29 -16
  10. package/dist/preview-builder.mjs +1 -0
  11. package/dist/scenario-inspector.mjs +11 -5
  12. package/dist/scenario-registry.mjs +16 -0
  13. package/dist/scenarios-compiler.mjs +90 -23
  14. package/dist/skills/ads-break-ui/references/drafts.md +6 -0
  15. package/dist/skills/ads-break-ui/references/guarded-editing.md +2 -2
  16. package/dist/skills/ads-break-ui/references/runtimes.md +9 -0
  17. package/dist/skills/ads-designer/references/drafts.md +6 -0
  18. package/dist/skills/ads-designer/references/guarded-editing.md +2 -2
  19. package/dist/skills/ads-designer/references/runtimes.md +9 -0
  20. package/dist/skills/ads-import/references/drafts.md +6 -0
  21. package/dist/skills/ads-import/references/guarded-editing.md +2 -2
  22. package/dist/skills/ads-import/references/runtimes.md +9 -0
  23. package/dist/skills/ads-motion/references/drafts.md +6 -0
  24. package/dist/skills/ads-motion/references/guarded-editing.md +2 -2
  25. package/dist/skills/ads-motion/references/runtimes.md +9 -0
  26. package/dist/skills/ads-port/references/drafts.md +6 -0
  27. package/dist/skills/ads-port/references/guarded-editing.md +2 -2
  28. package/dist/skills/ads-port/references/runtimes.md +9 -0
  29. package/dist/validation-checks.mjs +23 -3
  30. package/dist/validation.mjs +19 -10
  31. package/dist/verification.mjs +5 -4
  32. package/docs/ARCHITECTURE.md +28 -0
  33. package/docs/CHANGELOG.md +41 -12
  34. package/docs/GUIDE.md +5 -1
  35. package/docs/MCP.md +12 -7
  36. package/docs/benchmarks/gidi-preview-memory.md +141 -0
  37. package/package.json +1 -1
@@ -0,0 +1,7 @@
1
+ import { writeFileSync } from "node:fs";
2
+ import { checkProject } from "./check.mjs";
3
+
4
+ // Candidate architecture analysis can retain a large TypeScript heap. Give it
5
+ // a process lifetime instead of growing the long-running MCP process's heap.
6
+ const [root, report, trackingRoot] = process.argv.slice(2);
7
+ writeFileSync(report, JSON.stringify(checkProject(root, { trackingRoot })));
@@ -12,13 +12,15 @@ import { mergeDraftExports, isDraftExportEntry } from "./draft-exports.mjs";
12
12
  import { inspectTokens } from "../tokens.mjs";
13
13
  import { previewFileIgnored, previewWatchDirectories } from "../preview-files.mjs";
14
14
  import { createDraftDiscovery } from "./draft-discovery.mjs";
15
+ import { mutationLimits } from "./mutation-limits.mjs";
15
16
 
16
17
  export const DRAFTS_URI = "ads://project/drafts";
17
18
  const hash = bytes => createHash("sha256").update(bytes).digest("hex");
18
19
  const idSchema = z.string().regex(/^[a-z0-9][a-z0-9-]{0,79}$/);
19
20
  const relative = z.string().min(1).max(500).refine(value => !path.isAbsolute(value) && !value.includes("\\") && !value.includes("\0") && !value.split("/").some(part => !part || part === "." || part === ".."), "Use a canonical project-relative path.");
20
21
  const fileSchema = z.object({ target: relative, source: relative.nullable(), baseline: z.string().regex(/^[a-f0-9]{64}$/).nullable(), unit: z.string().max(256) }).strict();
21
- const manifestSchema = z.object({ schemaVersion: z.literal(1), id: idSchema, title: z.string().min(1).max(160), units: z.array(z.string().min(1).max(256)).min(1).max(8).refine(values=>new Set(values).size===values.length,"Draft owners must be unique."), dependencies: z.array(idSchema).max(8).refine(values=>new Set(values).size===values.length,"Draft dependencies must be unique.").default([]), tokenGroups:z.array(z.string().min(1).max(160)).max(32).default([]), files: z.array(fileSchema).max(256) }).strict();
22
+ const draftUnits = z.array(z.string().min(1).max(256)).min(1).max(mutationLimits.units).refine(values=>new Set(values).size===values.length,"Draft owners must be unique.");
23
+ const manifestSchema = z.object({ schemaVersion: z.literal(1), id: idSchema, title: z.string().min(1).max(160), units: draftUnits, dependencies: z.array(idSchema).max(8).refine(values=>new Set(values).size===values.length,"Draft dependencies must be unique.").default([]), tokenGroups:z.array(z.string().min(1).max(160)).max(32).default([]), files: z.array(fileSchema).max(mutationLimits.files) }).strict();
22
24
  export const draftIdSchema = idSchema;
23
25
  export const draftRevisionSchema = z.string().regex(/^[a-f0-9]{64}$/);
24
26
 
@@ -154,6 +156,7 @@ export function createDraftController(directory, { edits, startPreview, prewarm
154
156
  }
155
157
  function create({ units, title, id = randomUUID(), dependencies = [], tokenGroups: selectedGroups = [] }) {
156
158
  if (closed) throw new Error("Draft controller is closed.");
159
+ units = draftUnits.parse(units);
157
160
  idSchema.parse(id);
158
161
  if (existsSync(manifestFile(id))) throw new Error("Draft already exists.");
159
162
  const options = loadConfig(root), inventory = inspectUnits(options), files = new Map();
@@ -174,7 +177,7 @@ export function createDraftController(directory, { edits, startPreview, prewarm
174
177
  files.set(target, { target, source, baseline: hash(content), unit });
175
178
  }
176
179
  }
177
- const manifest = manifestSchema.parse({ schemaVersion: 1, id, title: title ?? units.join(", "), units, dependencies, tokenGroups:selectedGroups, files: [...files.values()] });
180
+ const manifest = manifestSchema.parse({ schemaVersion: 1, id, title: title ?? units.join(", ").slice(0,160), units, dependencies, tokenGroups:selectedGroups, files: [...files.values()] });
178
181
  for (const dependency of dependencies) {const value=inspect(dependency,[id]);if(value.dependencyErrors.length)throw new Error(value.dependencyErrors[0].message);}
179
182
  for (const file of manifest.files) atomic(safe(path.dirname(manifestFile(id)), file.source), bytes(safe(root, file.target)));
180
183
  save(manifest);
@@ -0,0 +1,2 @@
1
+ /** Shared budgets for tracked drafts and guarded publication. */
2
+ export const mutationLimits = Object.freeze({ units: 64, files: 256, patchBytes: 256 * 1024, patchFileBytes: 16 * 1024 * 1024, fileBytes: 16 * 1024 * 1024, readChars: 12000, snapshotFiles: 100000, snapshotBytes: 2 * 1024 * 1024 * 1024 });
@@ -5,7 +5,6 @@ import path from "node:path";
5
5
  import ts from "typescript";
6
6
  import { isInside, loadConfig } from "../config.mjs";
7
7
  import { affectedBehaviorUnits, createVerificationController } from "../verification.mjs";
8
- import { checkProject } from "../check.mjs";
9
8
  import { generateLintConfig } from "../lint-config.mjs";
10
9
  import { generateBrandAssets } from "../brand-assets.mjs";
11
10
  import { applyFilePatch, parseUnifiedPatch } from "./patch.mjs";
@@ -14,11 +13,12 @@ import { previewSourceRevision } from "../preview-inputs.mjs";
14
13
  import { inspectScenarios } from "../scenarios.mjs";
15
14
  import { checkUnitCandidate, checkUnitFiles, inspectUnits, validateUnitId } from "../units.mjs";
16
15
  import { acceptance, failure as evidenceFailure } from "../evidence.mjs";
17
- import { checkCommand, projectChecks as checks } from "../validation-checks.mjs";
16
+ import { checkCandidate, checkCommand, projectChecks as checks } from "../validation-checks.mjs";
18
17
  import { preparePreviewCache } from "../scenarios-compiler.mjs";
19
18
  import { validationInputFiles } from "../validation-inputs.mjs";
19
+ import { mutationLimits } from "./mutation-limits.mjs";
20
20
 
21
- export const mutationLimits = { units: 8, files: 32, patchBytes: 256 * 1024, patchFileBytes: 16 * 1024 * 1024, fileBytes: 16 * 1024 * 1024, readChars: 12000, snapshotFiles: 100000, snapshotBytes: 2 * 1024 * 1024 * 1024 };
21
+ export { mutationLimits } from "./mutation-limits.mjs";
22
22
  const digest = bytes => `sha256:${createHash("sha256").update(bytes).digest("hex")}`;
23
23
  const ignored = new Set([".git", ".ds", "node_modules", ".vite", "coverage", ".playwright-cli", "test-results", "output"]);
24
24
  const textFile = file => /\.(?:[cm]?[jt]sx?|css|html|jsonc?|md|txt|svg)$/.test(file);
@@ -141,7 +141,7 @@ function mutationEvidence(result, candidateRevision) {
141
141
  }
142
142
 
143
143
 
144
- export function createMutationController(directory, { captures = createCaptureController(directory) } = {}) {
144
+ export function createMutationController(directory, { captures = createCaptureController(directory), previewWork } = {}) {
145
145
  const root = path.resolve(directory);
146
146
  let busy = false;
147
147
  let lastResult = null;
@@ -153,7 +153,7 @@ export function createMutationController(directory, { captures = createCaptureCo
153
153
  let commands = [], diagnostics = [];
154
154
  try { commands = checks(options).map(check => [check.command, ...check.args].join(" ")); }
155
155
  catch (error) { diagnostics = [error.diagnostic ?? { rule: "mutation-check", message: error.message }]; }
156
- return { enabled: true, scope: "one-ds-unit", format: "git-unified-diff", transactions:{tool:"ads_apply_transaction",maxUnits:mutationLimits.units,finalCandidateChecks:true}, preparation:{owner:"ads_prepare_patch",tokenSamples:"ads_prepare_token_samples"}, dsDir: options.config.dsDir, limits: mutationLimits, checks: ["ads check", "registered Oxlint rules", ...commands], diagnostics, busy, ...(progress ? { progress } : {}), lastResult };
156
+ return { enabled: true, scope: "one-ds-unit", format: "git-unified-diff", transactions:{tool:"ads_apply_transaction",maxUnits:mutationLimits.units,finalCandidateChecks:true}, preparation:{owner:"ads_prepare_patch",tokenSamples:"ads_prepare_token_samples"}, dsDir: options.config.dsDir, limits: mutationLimits, checks: ["ads check", "registered Oxlint rules", ...commands, ...options.config.mcp.previewManifest && options.config.mcp.previewWatch ? ["managed production previews"] : []], diagnostics, busy, ...(progress ? { progress } : {}), lastResult };
157
157
  },
158
158
  cancel() { active?.abort(); },
159
159
  units() { return inspectUnits(loadConfig(root)).units; },
@@ -174,14 +174,14 @@ export function createMutationController(directory, { captures = createCaptureCo
174
174
  busy = true;
175
175
  active = new AbortController();
176
176
  signal = signal ? AbortSignal.any([signal, active.signal]) : active.signal;
177
- let temporary, candidateRevision;
177
+ let temporary, candidateRevision, releasePreview, previewHost;
178
178
  let boundary=evidenceFailure("runner","mutation-execution","ADS_MUTATION_EXCEPTION",{certainty:"unclassified"});
179
179
  const verified = [];
180
180
  try {
181
181
  const options = loadConfig(root);
182
182
  if (screenshot && !dryRun || selections !== undefined && !screenshot) throw fail("mutation-capture", "Use screenshot:true only with dryRun:true and an explicit captures:[{scenario,target?,theme?,viewport?}] selection. Ordinary patches create no screenshots.");
183
183
  if (screenshot) selections = captureSelections(selections);
184
- if (patches !== undefined && (unit !== undefined || patch !== undefined || patchFile !== undefined || !Array.isArray(patches) || patches.length < 2 || patches.length > mutationLimits.units)) throw fail("mutation-batch", "A transaction requires 2–8 distinct owner patches, without a top-level unit/patch.");
184
+ if (patches !== undefined && (unit !== undefined || patch !== undefined || patchFile !== undefined || !Array.isArray(patches) || patches.length < 2 || patches.length > mutationLimits.units)) throw fail("mutation-batch", `A transaction requires 2–${mutationLimits.units} distinct owner patches, without a top-level unit/patch.`);
185
185
  const groups = patches ?? [{unit,patch,patchFile}];
186
186
  if (new Set(groups.map(group => group.unit)).size !== groups.length) throw fail("mutation-batch", "Use one patch per distinct unit in a transaction.");
187
187
  let patchBytes = 0;
@@ -241,7 +241,7 @@ export function createMutationController(directory, { captures = createCaptureCo
241
241
  originals.push({...original,mode:original.exists ? lstatSync(address(options,entry.path)).mode : undefined});
242
242
  byPath.set(entry.path,changes.length);
243
243
  changes.push({...change,expectedDigest:original.digest});
244
- if (changes.length > mutationLimits.files) throw fail("mutation-batch", "A transaction may change at most 32 distinct files.");
244
+ if (changes.length > mutationLimits.files) throw fail("mutation-batch", `A transaction may change at most ${mutationLimits.files} distinct files.`);
245
245
  }
246
246
  return change;
247
247
  });
@@ -279,7 +279,8 @@ export function createMutationController(directory, { captures = createCaptureCo
279
279
  const extraChecks = checks(candidateOptions);
280
280
  const expected = snapshot(candidateOptions);
281
281
  candidateRevision=digest(Buffer.from(expected));
282
- const result = checkProject(candidate, { trackingRoot: root });
282
+ if (previewWork) releasePreview = await previewWork.acquire(signal);
283
+ const result = await checkCandidate(candidate, signal, root);
283
284
  if (!result.ok) return lastResult = mutationEvidence({ ok: false, applied: false, diagnostics: result.diagnostics, total: result.diagnostics.length, checks: verified },candidateRevision);
284
285
  verified.push({ name: "ads check", passed: true });
285
286
  const lintConfig = generateLintConfig(candidate).file;
@@ -302,10 +303,18 @@ export function createMutationController(directory, { captures = createCaptureCo
302
303
  progress={stage:"project-checks",completed:index,total:extraChecks.length,message:`Checking ${check.command} ${check.args.join(" ")}`};notifyProgress?.(progress);
303
304
  verified.push(await checkCommand(check.command, check.args, candidate, signal, undefined, {category:"build",phase:`project-check:${check.args.at(-1)}`}, candidateOptions.config.mcp.mutationCheckTimeoutMs));
304
305
  }
306
+ if (candidateOptions.config.mcp.previewManifest && candidateOptions.config.mcp.previewWatch) {
307
+ boundary=evidenceFailure("build","preview-build","ADS_PREVIEW_BUILD");
308
+ progress={stage:"preview-build",message:"Building all candidate previews"};notifyProgress?.(progress);
309
+ const { startAdsMcp } = await import("./server.mjs");
310
+ previewHost = await startAdsMcp(candidate, { stdio:false });
311
+ await previewHost.buildAll(signal, {timeoutMs:candidateOptions.config.mcp.mutationCheckTimeoutMs});
312
+ verified.push({ name:"managed production previews", passed:true });
313
+ }
305
314
  boundary=evidenceFailure("runner","behavior-verification","ADS_BEHAVIOR_SETUP");
306
315
  const behaviorUnits = affectedBehaviorUnits(candidateOptions, changes.map(change => change.path));
307
316
  if (behaviorUnits.length) {
308
- const verification = createVerificationController(candidate, { reportRoot: root, onProgress: value => { progress = { stage: "behavior", ...value }; notifyProgress?.(progress); } });
317
+ const verification = createVerificationController(candidate, { reportRoot: root, previewHost, onProgress: value => { progress = { stage: "behavior", ...value }; notifyProgress?.(progress); } });
309
318
  let evidence;
310
319
  try { evidence = await verification.run({ units: behaviorUnits, persist: false }, signal); }
311
320
  finally { await verification.close(); }
@@ -366,7 +375,7 @@ export function createMutationController(directory, { captures = createCaptureCo
366
375
  preview: "Source validation passed. Inspect the managed preview build and rendered scenario after applying; validation is not visual verification." },candidateRevision);
367
376
  } catch (error) {
368
377
  return lastResult = mutationEvidence({ ok: false, applied: false, diagnostics: [error.diagnostic ?? { rule: "mutation-error", message: error.message,failure:error.failure??boundary }], checks: verified },candidateRevision);
369
- } finally { try { if (temporary) rmSync(temporary, { recursive: true, force: true }); } finally { busy = false; active = undefined; progress = undefined; } }
378
+ } finally { try { await previewHost?.close(); } finally { try { if (temporary) rmSync(temporary, { recursive: true, force: true }); } finally { releasePreview?.(); busy = false; active = undefined; progress = undefined; } } }
370
379
  },
371
380
  };
372
381
  }
@@ -1,3 +1,5 @@
1
+ import { mutationLimits } from "./mutation-limits.mjs";
2
+
1
3
  function error(message, file, rule = "mutation-patch") {
2
4
  return Object.assign(new Error(message), { diagnostic: { rule, message, ...(file ? { file } : {}) } });
3
5
  }
@@ -10,7 +12,7 @@ function fileName(header, prefix) {
10
12
  }
11
13
 
12
14
  /** Text hunks are exact; Git binary blocks are applied by Git in the candidate. */
13
- export function parseUnifiedPatch(patch, maxFiles = 32) {
15
+ export function parseUnifiedPatch(patch, maxFiles = mutationLimits.files) {
14
16
  const lines = patch.split("\n");
15
17
  if (lines.at(-1) === "") lines.pop();
16
18
  const files = [], paths = new Set();
@@ -32,7 +34,7 @@ export function parseUnifiedPatch(patch, maxFiles = 32) {
32
34
  if (lines[index] === "GIT binary patch") {
33
35
  if (!gitPath || !binaryIndex) throw error("Binary patches need a Git file header and full blob hashes. Generate with git diff --binary.");
34
36
  const file = gitPath;
35
- if (paths.has(file) || files.length >= maxFiles) throw error("Provide 1–32 distinct file patches.", file, "mutation-batch");
37
+ if (paths.has(file) || files.length >= maxFiles) throw error(`Provide 1–${maxFiles} distinct file patches.`, file, "mutation-batch");
36
38
  paths.add(file);
37
39
  while (index < lines.length && !lines[index].startsWith("diff --git ")) index++;
38
40
  const block = lines.slice(start, index).join("\n") + "\n";
@@ -44,7 +46,7 @@ export function parseUnifiedPatch(patch, maxFiles = 32) {
44
46
  const file = after ?? before;
45
47
  if (gitPath && gitPath !== file) throw error("Git metadata and file headers must identify the same path.", file);
46
48
  if (!file || before && after && before !== after) throw error("Use separate delete and create entries to rename a file.", file);
47
- if (paths.has(file) || files.length >= maxFiles) throw error("Provide 1–32 distinct file patches.", file, "mutation-batch");
49
+ if (paths.has(file) || files.length >= maxFiles) throw error(`Provide 1–${maxFiles} distinct file patches.`, file, "mutation-batch");
48
50
  paths.add(file);
49
51
  const entry = { path: file, operation: before === null ? "create" : after === null ? "delete" : "update", hunks: [] };
50
52
  while (lines[index]?.startsWith("@@")) {
@@ -1,13 +1,48 @@
1
1
  import { spawn } from "node:child_process";
2
+ import { readFileSync, readdirSync } from "node:fs";
2
3
 
3
4
  // The only stdin writer is the MCP owner. EOF also arrives after SIGKILL or a
4
5
  // client launcher crash, when the owner's JavaScript cleanup cannot execute.
5
6
  const pid = Number(process.argv[2]);
6
7
  if (!Number.isSafeInteger(pid) || pid <= 1 || pid === process.pid) throw new Error("Invalid owned preview process group");
7
8
  let released = false, stopping = false, timer, input = "";
9
+ // Browser runners can put their web server in another process group. Linux
10
+ // command guards retain descendant identities before a launcher exits/reparents
11
+ // them; start times prevent a recycled PID from becoming a cleanup target.
12
+ const tree = process.platform === "linux" && process.argv[3] === "--tree";
13
+ const owned = new Map();
14
+ function identity(id) {
15
+ try { const text=readFileSync(`/proc/${id}/stat`,"utf8"),fields=text.slice(text.lastIndexOf(")")+2).split(" "); return {parent:Number(fields[1]),start:fields[19],state:fields[0]}; } catch { return null; }
16
+ }
17
+ const initial = tree ? identity(pid) : null;
18
+ if (initial) owned.set(pid,initial.start);
19
+ function collect() {
20
+ if (!tree) return;
21
+ const processes=new Map();
22
+ for (const name of readdirSync("/proc")) if (/^\d+$/.test(name)) { const value=identity(Number(name)); if(value)processes.set(Number(name),value); }
23
+ for (const [id,start] of owned) if (processes.get(id)?.start!==start) owned.delete(id);
24
+ for (let pass=0;pass<20;pass++) {
25
+ const size=owned.size;
26
+ for (const [id,value] of processes) if (owned.has(value.parent)) owned.set(id,value.start);
27
+ if (size===owned.size) break;
28
+ }
29
+ }
30
+ const observe = tree ? setInterval(collect,250) : null;
31
+ observe?.unref();
32
+ function signalTree(signal) {
33
+ for (const [id,start] of owned) if (identity(id)?.start===start) {
34
+ try { process.kill(id,signal); } catch (error) { if(error.code!=="ESRCH")process.exitCode=1; }
35
+ }
36
+ }
8
37
  function stop() {
9
38
  if (released || stopping) return;
10
39
  stopping = true;
40
+ clearInterval(observe);
41
+ if (tree) {
42
+ collect();signalTree("SIGTERM");
43
+ if (owned.size) timer=setTimeout(()=>signalTree("SIGKILL"),1500);
44
+ return;
45
+ }
11
46
  if (process.platform === "win32") {
12
47
  const terminator = spawn("taskkill", ["/pid", String(pid), "/T", "/F"], { stdio: "ignore", windowsHide: true });
13
48
  terminator.on("error", () => { process.exitCode = 1; });
@@ -22,7 +57,7 @@ function stop() {
22
57
  }
23
58
  process.stdin.on("data", bytes => {
24
59
  input = (input + bytes).slice(-32);
25
- if (input === "disarm\n") { released = true; clearTimeout(timer); }
60
+ if (input === "disarm\n") { released = true; clearTimeout(timer); clearInterval(observe); }
26
61
  });
27
62
  for (const event of ["end", "close", "error"]) process.stdin.once(event, stop);
28
63
  for (const signal of ["SIGINT", "SIGTERM"]) process.once(signal, stop);
@@ -30,6 +30,7 @@ export function createPreviewWatch(root, config, { log = process.stderr, buildTi
30
30
  let restarting;
31
31
  let disposed = false;
32
32
  let stalled = false;
33
+ let suspended = false, resuming, suspending;
33
34
  const baselines = new Map();
34
35
  const ready = new Set();
35
36
  const requests = new Set();
@@ -41,17 +42,17 @@ export function createPreviewWatch(root, config, { log = process.stderr, buildTi
41
42
  stream.pipe(output);
42
43
  }
43
44
  let active;
45
+ let full;
44
46
  let invalidation;
45
47
  let requestFile = path.join(root, ".ds", `preview-requests-${session}.json`);
46
48
  let reportFile = path.join(root, ".ds", `build-status-${session}.json`);
47
49
  function request(file,force = false) {
48
50
  if (!command || !force && requests.has(file) && active === file) return;
49
- requests.add(file);
50
- active = file;
51
+ if (file) { requests.add(file); active = file; }
51
52
  mkdirSync(path.dirname(requestFile), { recursive: true });
52
53
  if (realpathSync(path.dirname(requestFile)) !== path.dirname(requestFile)) throw new Error("Preview requests cannot resolve through a symlink.");
53
54
  const temporary = `${requestFile}.tmp`;
54
- writeFileSync(temporary, JSON.stringify({ session, active: path.relative(root, active).replaceAll("\\", "/"), files: [...requests].map((file) => path.relative(root, file).replaceAll("\\", "/")), ...(invalidation ? {invalidation} : {}) }));
55
+ writeFileSync(temporary, JSON.stringify({ session, active: active ? path.relative(root, active).replaceAll("\\", "/") : null, files: [...requests].map((file) => path.relative(root, file).replaceAll("\\", "/")), ...(invalidation ? {invalidation} : {}), ...(full ? {full} : {}) }));
55
56
  renameSync(temporary, requestFile);
56
57
  }
57
58
 
@@ -66,7 +67,7 @@ export function createPreviewWatch(root, config, { log = process.stderr, buildTi
66
67
  } catch (failure) { if (failure.code !== "ESRCH") throw failure; }
67
68
  }
68
69
  function start() {
69
- if (disposed || state !== "idle") return;
70
+ if (disposed || suspended || state !== "idle") return;
70
71
  for (const app of config.apps) {
71
72
  const file = path.resolve(root, app.file);
72
73
  baselines.set(file, stamp(file));
@@ -126,6 +127,7 @@ export function createPreviewWatch(root, config, { log = process.stderr, buildTi
126
127
  }
127
128
  });
128
129
  child.once("error", (failure) => { error = `Cannot start preview watcher: ${failure.message}`; });
130
+ if (active) request(active, true);
129
131
  }
130
132
 
131
133
  function restart() {
@@ -143,6 +145,18 @@ export function createPreviewWatch(root, config, { log = process.stderr, buildTi
143
145
 
144
146
  async function ensure(file, signal, { waitFor = "verified" } = {}) {
145
147
  if (signal?.aborted) throw new Error("Preview request cancelled.");
148
+ if (suspended) {
149
+ const current = buildStatus().previews.find(entry=>config.apps.some(app=>path.resolve(root,app.file)===file && app.id===entry.id));
150
+ if (current?.current) return current;
151
+ if (waitFor === "compiled" && config.previewManifest) {
152
+ try {
153
+ const manifest = readPreviewManifest(withPreviewSession({ root, config: { mcp: config } }, resourceSession()));
154
+ const app = config.apps.find(entry => path.resolve(root, entry.file) === file);
155
+ if (manifest?.scenarios.some(entry => entry.id === app?.id)) return buildStatus().previews.find(entry => entry.id === app.id);
156
+ } catch { /* No retained preview: queue this request until validation ends. */ }
157
+ }
158
+ await waitForResume(signal);
159
+ }
146
160
  if (state === "failed" || restarting || stalled) await restart();
147
161
  if (disposed) throw new Error("Preview watcher is stopped.");
148
162
  start();
@@ -150,10 +164,16 @@ export function createPreviewWatch(root, config, { log = process.stderr, buildTi
150
164
  if (signal?.aborted) throw new Error("Preview request cancelled.");
151
165
  const app = config.apps.find((entry) => path.resolve(root, entry.file) === file);
152
166
  let baseline = baselines.get(file) ?? null;
153
- const deadline = Date.now() + buildTimeout;
167
+ let deadline = Date.now() + buildTimeout;
154
168
  let restarted = false;
155
169
  while (Date.now() < deadline) {
156
170
  if (signal?.aborted) throw new Error("Preview request cancelled.");
171
+ if (suspended) {
172
+ const pausedAt = Date.now();
173
+ await waitForResume(signal); deadline += Date.now() - pausedAt;
174
+ if (disposed) throw new Error("Preview watcher is stopped.");
175
+ start(); request(file, true); baseline = baselines.get(file) ?? null;
176
+ }
157
177
  const build = buildStatus().previews.find((entry) => entry.id === app?.id);
158
178
  if (!restarted && build?.diagnostics.some(item => item.code === "ADS_PREVIEW_RESTART")) {
159
179
  restarted = true; await restart(); request(file); baseline = baselines.get(file) ?? null; continue;
@@ -187,22 +207,66 @@ export function createPreviewWatch(root, config, { log = process.stderr, buildTi
187
207
  for (const directory of previewSessionDirectories(withPreviewSession({ root, config: { mcp: config } }, resourceSession()))) rmSync(directory, { recursive: true, force: true });
188
208
  }
189
209
 
190
- async function stopChild() {
210
+ async function stopChild({ preserve = false } = {}) {
191
211
  rmSync(requestFile, { force: true });
192
212
  if (stopping) return stopping;
193
- if (!child || childClosed) { if (command) state = "stopped"; rmSync(reportFile, { force: true }); clearOutput(); return; }
213
+ const cleanup = () => { if (!preserve) { rmSync(reportFile, { force: true }); rmSync(path.join(root, ".ds", `full-build-${session}.json`), {force:true}); clearOutput(); } };
214
+ if (!child || childClosed) { if (command) state = "stopped"; cleanup(); return; }
194
215
  if (state === "stopped") return;
195
216
  state = "stopping";
196
217
  stopping = (async () => {
197
218
  kill("SIGTERM");
198
219
  clearTimeout(killTimer);
199
220
  const timer = setTimeout(() => kill("SIGKILL"), 1500);
200
- try { await closed; } finally { clearTimeout(timer); rmSync(reportFile, { force: true }); clearOutput(); }
221
+ try { await closed; } finally { clearTimeout(timer); cleanup(); }
201
222
  })();
202
223
  return stopping;
203
224
  }
204
- return { start, ensure, async initialize() {
225
+ function waitForResume(signal) {
226
+ if (!suspended || disposed) return Promise.resolve();
227
+ if (signal?.aborted) return Promise.reject(new Error("Preview request cancelled."));
228
+ return new Promise((resolve, reject) => {
229
+ const abort = () => { signal?.removeEventListener("abort", abort); reject(new Error("Preview request cancelled.")); };
230
+ signal?.addEventListener("abort", abort, { once: true });
231
+ resuming.promise.then(() => { signal?.removeEventListener("abort", abort); resolve(); });
232
+ });
233
+ }
234
+ function resume() {
235
+ if (suspending) { void suspending.then(resume); return; }
236
+ if (!suspended) return;
237
+ suspended = false;
238
+ state = command ? "idle" : "disabled";
239
+ error = undefined; child = closed = stopping = undefined; childClosed = false;
240
+ ready.clear(); baselines.clear();
241
+ // Requests are replayed on demand; publication keeps its existing session.
242
+ const previous = resuming; resuming = undefined; previous.finish();
243
+ }
244
+ return { start, ensure, async buildAll(signal, { timeoutMs = 300000 } = {}) {
245
+ await waitForResume(signal);
246
+ if (!command || disposed) throw new Error("A full managed preview build requires mcp.previewWatch.");
247
+ if (state === "failed" || restarting || stalled) await restart();
248
+ start(); full = randomUUID(); request(active, true);
249
+ const token = full, deadline = Date.now() + timeoutMs;
250
+ while (Date.now() < deadline) {
251
+ if (signal?.aborted) throw new Error("Preview build cancelled.");
252
+ if (state !== "running") throw new Error(error ?? "Preview compiler stopped during full build.");
253
+ let result;
254
+ try { result = JSON.parse(readFileSync(path.join(root, ".ds", `full-build-${session}.json`), "utf8")); } catch { /* Waiting for this request. */ }
255
+ if (result?.token === token) {
256
+ const report = buildStatus();
257
+ if (!result.ok) throw buildFailure({ ...report, diagnostics: [...(report.diagnostics??[]),...report.previews.flatMap(entry => entry.diagnostics)] });
258
+ const scenarios = report.previews.filter(entry => entry.id.includes("/"));
259
+ if (!scenarios.length || scenarios.some(entry => !entry.current)) throw new Error("Full preview build is stale or incomplete; retry against current source.");
260
+ return report;
261
+ }
262
+ await new Promise(resolve => setTimeout(resolve, 50));
263
+ }
264
+ stalled = true;
265
+ throw new Error("Full preview build exceeded its command budget.");
266
+ }, async initialize() {
205
267
  if (disposed || !command) return;
268
+ await waitForResume();
269
+ if (disposed) return;
206
270
  if (state === "failed" || restarting || stalled) await restart();
207
271
  start();
208
272
  const deadline = Date.now() + buildTimeout;
@@ -213,6 +277,7 @@ export function createPreviewWatch(root, config, { log = process.stderr, buildTi
213
277
  if (!disposed) throw new Error(error ?? "Preview compiler initialization timed out.");
214
278
  }, invalidate() { invalidation = randomUUID(); if (active) request(active,true); }, async warm(files) {
215
279
  if (disposed || !command || !files.length) return;
280
+ await waitForResume();
216
281
  const selected=active;
217
282
  if (state === "failed" || restarting || stalled) await restart();
218
283
  if (disposed) return;
@@ -220,7 +285,14 @@ export function createPreviewWatch(root, config, { log = process.stderr, buildTi
220
285
  for (const file of files) requests.add(file);
221
286
  // Preparing a graph must not replace the user's active selection.
222
287
  request(active ?? selected ?? files[0],true);
223
- }, async stop() { disposed = true; await restarting; return stopChild(); }, kill: () => kill("SIGKILL"), status, resourceSession, buildStatus, setApps(apps) {
288
+ }, async suspend() {
289
+ if (disposed || !command) return;
290
+ if (suspended) return suspending;
291
+ suspended = true;
292
+ let finish; resuming = { promise: new Promise(resolve => { finish = resolve; }), finish: () => finish() };
293
+ suspending = (async () => { await restarting; await stopChild({ preserve: true }); if (!disposed) state = "suspended"; })();
294
+ try { await suspending; } finally { suspending = undefined; }
295
+ }, resume, async stop() { disposed = true; await restarting; await suspending; resume(); return stopChild(); }, kill: () => kill("SIGKILL"), status, resourceSession, buildStatus, setApps(apps) {
224
296
  for (const app of apps) {
225
297
  const file = path.resolve(root, app.file);
226
298
  if (!baselines.has(file)) baselines.set(file, stamp(file));
@@ -234,9 +306,9 @@ export function createReconfigurablePreviewWatch(root, config, options) {
234
306
  let current = createPreviewWatch(root, config, options);
235
307
  let signature = JSON.stringify(config);
236
308
  let apps = config.apps;
237
- let pending = Promise.resolve(), replacing = false, stopped = false;
309
+ let pending = Promise.resolve(), replacing = false, stopped = false, parked = false;
238
310
  return {
239
- start() { if (!stopped && !replacing) current.start(); },
311
+ start() { if (!stopped && !replacing && !parked) current.start(); },
240
312
  async initialize() { await pending; if (!stopped) return current.initialize(); },
241
313
  async ensure(file, signal, options) { await pending; if (stopped) throw new Error("Preview watcher is stopped."); return current.ensure(file, signal, options); },
242
314
  status() { return replacing ? { state: "reconfiguring" } : current.status(); },
@@ -244,6 +316,9 @@ export function createReconfigurablePreviewWatch(root, config, options) {
244
316
  buildStatus() { return current.buildStatus(); },
245
317
  async invalidate() { await pending; if (!stopped) current.invalidate(); },
246
318
  async warm(files) { await pending; if (!stopped) return current.warm(files); },
319
+ async buildAll(signal, options) { await pending; if (stopped) throw new Error("Preview watcher is stopped."); return current.buildAll(signal, options); },
320
+ async suspend() { parked = true; await pending; if (!stopped && parked) return current.suspend(); },
321
+ resume() { parked = false; current.resume(); },
247
322
  setApps(next) { apps = next; current.setApps(next); },
248
323
  kill() { current.kill(); },
249
324
  reconfigure(next, force = false) {
@@ -255,7 +330,7 @@ export function createReconfigurablePreviewWatch(root, config, options) {
255
330
  await current.stop();
256
331
  if (stopped) return;
257
332
  current = createPreviewWatch(root, { ...next, apps }, options);
258
- current.start();
333
+ if (parked) await current.suspend(); else current.start();
259
334
  }).finally(() => { replacing = false; });
260
335
  return pending;
261
336
  },
@@ -0,0 +1,41 @@
1
+ /** A validation candidate owns the compiler budget until its checks finish.
2
+ * Published resources remain readable while idle preview compilers are parked. */
3
+ export function createPreviewWork() {
4
+ const watchers = new Set();
5
+ let active;
6
+ return {
7
+ register(watcher) {
8
+ watchers.add(watcher);
9
+ const lease = active;
10
+ if (lease) void watcher.suspend().then(() => { if (active !== lease) watcher.resume(); }).catch(error => {
11
+ if (active !== lease) watcher.resume();
12
+ process.stderr.write(`ads mcp: preview parking failed: ${error.message}\n`);
13
+ });
14
+ return () => watchers.delete(watcher);
15
+ },
16
+ async acquire(signal) {
17
+ while (active) {
18
+ if (signal?.aborted) throw new Error("Preview validation cancelled.");
19
+ await new Promise((resolve, reject) => {
20
+ const abort = () => { signal?.removeEventListener("abort", abort); reject(new Error("Preview validation cancelled.")); };
21
+ signal?.addEventListener("abort", abort, {once:true});
22
+ active.done.then(() => { signal?.removeEventListener("abort", abort); resolve(); });
23
+ });
24
+ }
25
+ if (signal?.aborted) throw new Error("Preview validation cancelled.");
26
+ let finish;
27
+ const lease = { done: new Promise(resolve => { finish = resolve; }) };
28
+ active = lease;
29
+ try { await Promise.all([...watchers].map(watcher => watcher.suspend())); }
30
+ catch (error) { for (const watcher of watchers) watcher.resume(); active = undefined; finish(); throw error; }
31
+ let released = false;
32
+ return () => {
33
+ if (released) return;
34
+ released = true;
35
+ for (const watcher of watchers) watcher.resume();
36
+ if (active === lease) active = undefined;
37
+ finish();
38
+ };
39
+ },
40
+ };
41
+ }