@reqvire-org/ads 0.3.33 → 0.3.35
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.
- package/dist/behavior-libraries.mjs +93 -0
- package/dist/behaviors.mjs +0 -6
- package/dist/bootstrap-ds/ds.config.json +1 -0
- package/dist/capture.mjs +3 -3
- package/dist/check-runner.mjs +7 -0
- package/dist/check.mjs +2 -0
- package/dist/config.mjs +4 -0
- package/dist/lint-config.mjs +7 -0
- package/dist/mcp/build-status.mjs +1 -1
- package/dist/mcp/catalog.mjs +4 -2
- package/dist/mcp/draft-discovery.mjs +55 -0
- package/dist/mcp/drafts.mjs +135 -16
- package/dist/mcp/mutations.mjs +16 -8
- package/dist/mcp/preview-owner-guard.mjs +36 -1
- package/dist/mcp/preview-watch.mjs +100 -14
- package/dist/mcp/preview-widget.bundle.js +14 -14
- package/dist/mcp/preview-work.mjs +41 -0
- package/dist/mcp/server.mjs +131 -36
- package/dist/preview-builder.mjs +1 -0
- package/dist/scenario-inspector.mjs +16 -10
- package/dist/scenario-program.mjs +36 -0
- package/dist/scenario-registry.mjs +106 -0
- package/dist/scenarios-compiler.mjs +154 -43
- package/dist/scenarios.mjs +2 -1
- package/dist/showcase/client.bundle.js +39 -39
- package/dist/showcase/comparison.js +29 -5
- package/dist/showcase/draft-navigation.js +41 -0
- package/dist/showcase/index.html +1 -2
- package/dist/showcase/preview-state.js +19 -0
- package/dist/showcase/style.css +2 -2
- package/dist/skills/ads-break-ui/references/behaviors.md +10 -0
- package/dist/skills/ads-break-ui/references/drafts.md +43 -4
- package/dist/skills/ads-break-ui/references/runtimes.md +9 -0
- package/dist/skills/ads-break-ui/references/validation.md +6 -0
- package/dist/skills/ads-designer/SKILL.md +7 -0
- package/dist/skills/ads-designer/assets/bootstrap-ds/ds.config.json +1 -0
- package/dist/skills/ads-designer/references/behaviors.md +10 -0
- package/dist/skills/ads-designer/references/drafts.md +43 -4
- package/dist/skills/ads-designer/references/runtimes.md +9 -0
- package/dist/skills/ads-designer/references/validation.md +6 -0
- package/dist/skills/ads-import/SKILL.md +4 -0
- package/dist/skills/ads-import/references/behaviors.md +10 -0
- package/dist/skills/ads-import/references/drafts.md +43 -4
- package/dist/skills/ads-import/references/runtimes.md +9 -0
- package/dist/skills/ads-import/references/validation.md +6 -0
- package/dist/skills/ads-motion/references/behaviors.md +10 -0
- package/dist/skills/ads-motion/references/drafts.md +43 -4
- package/dist/skills/ads-motion/references/runtimes.md +9 -0
- package/dist/skills/ads-motion/references/validation.md +6 -0
- package/dist/skills/ads-port/SKILL.md +8 -1
- package/dist/skills/ads-port/references/behaviors.md +10 -0
- package/dist/skills/ads-port/references/drafts.md +43 -4
- package/dist/skills/ads-port/references/native-implementation.md +14 -1
- package/dist/skills/ads-port/references/runtimes.md +9 -0
- package/dist/skills/ads-port/references/validation.md +6 -0
- package/dist/unit-contracts.mjs +2 -2
- package/dist/units.mjs +6 -0
- package/dist/validation-checks.mjs +23 -3
- package/dist/validation.mjs +19 -10
- package/dist/verification/browser.d.mts +27 -0
- package/dist/verification.mjs +8 -4
- package/docs/ARCHITECTURE.md +110 -0
- package/docs/CHANGELOG.md +114 -0
- package/docs/GUIDE.md +34 -5
- package/docs/MCP.md +54 -9
- package/docs/benchmarks/gidi-preview-memory.md +141 -0
- package/package.json +6 -4
package/dist/mcp/mutations.mjs
CHANGED
|
@@ -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,7 +13,7 @@ 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";
|
|
20
19
|
|
|
@@ -141,7 +140,7 @@ function mutationEvidence(result, candidateRevision) {
|
|
|
141
140
|
}
|
|
142
141
|
|
|
143
142
|
|
|
144
|
-
export function createMutationController(directory, { captures = createCaptureController(directory) } = {}) {
|
|
143
|
+
export function createMutationController(directory, { captures = createCaptureController(directory), previewWork } = {}) {
|
|
145
144
|
const root = path.resolve(directory);
|
|
146
145
|
let busy = false;
|
|
147
146
|
let lastResult = null;
|
|
@@ -153,7 +152,7 @@ export function createMutationController(directory, { captures = createCaptureCo
|
|
|
153
152
|
let commands = [], diagnostics = [];
|
|
154
153
|
try { commands = checks(options).map(check => [check.command, ...check.args].join(" ")); }
|
|
155
154
|
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 };
|
|
155
|
+
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
156
|
},
|
|
158
157
|
cancel() { active?.abort(); },
|
|
159
158
|
units() { return inspectUnits(loadConfig(root)).units; },
|
|
@@ -174,7 +173,7 @@ export function createMutationController(directory, { captures = createCaptureCo
|
|
|
174
173
|
busy = true;
|
|
175
174
|
active = new AbortController();
|
|
176
175
|
signal = signal ? AbortSignal.any([signal, active.signal]) : active.signal;
|
|
177
|
-
let temporary, candidateRevision;
|
|
176
|
+
let temporary, candidateRevision, releasePreview, previewHost;
|
|
178
177
|
let boundary=evidenceFailure("runner","mutation-execution","ADS_MUTATION_EXCEPTION",{certainty:"unclassified"});
|
|
179
178
|
const verified = [];
|
|
180
179
|
try {
|
|
@@ -279,7 +278,8 @@ export function createMutationController(directory, { captures = createCaptureCo
|
|
|
279
278
|
const extraChecks = checks(candidateOptions);
|
|
280
279
|
const expected = snapshot(candidateOptions);
|
|
281
280
|
candidateRevision=digest(Buffer.from(expected));
|
|
282
|
-
|
|
281
|
+
if (previewWork) releasePreview = await previewWork.acquire(signal);
|
|
282
|
+
const result = await checkCandidate(candidate, signal, root);
|
|
283
283
|
if (!result.ok) return lastResult = mutationEvidence({ ok: false, applied: false, diagnostics: result.diagnostics, total: result.diagnostics.length, checks: verified },candidateRevision);
|
|
284
284
|
verified.push({ name: "ads check", passed: true });
|
|
285
285
|
const lintConfig = generateLintConfig(candidate).file;
|
|
@@ -302,10 +302,18 @@ export function createMutationController(directory, { captures = createCaptureCo
|
|
|
302
302
|
progress={stage:"project-checks",completed:index,total:extraChecks.length,message:`Checking ${check.command} ${check.args.join(" ")}`};notifyProgress?.(progress);
|
|
303
303
|
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
304
|
}
|
|
305
|
+
if (candidateOptions.config.mcp.previewManifest && candidateOptions.config.mcp.previewWatch) {
|
|
306
|
+
boundary=evidenceFailure("build","preview-build","ADS_PREVIEW_BUILD");
|
|
307
|
+
progress={stage:"preview-build",message:"Building all candidate previews"};notifyProgress?.(progress);
|
|
308
|
+
const { startAdsMcp } = await import("./server.mjs");
|
|
309
|
+
previewHost = await startAdsMcp(candidate, { stdio:false });
|
|
310
|
+
await previewHost.buildAll(signal, {timeoutMs:candidateOptions.config.mcp.mutationCheckTimeoutMs});
|
|
311
|
+
verified.push({ name:"managed production previews", passed:true });
|
|
312
|
+
}
|
|
305
313
|
boundary=evidenceFailure("runner","behavior-verification","ADS_BEHAVIOR_SETUP");
|
|
306
314
|
const behaviorUnits = affectedBehaviorUnits(candidateOptions, changes.map(change => change.path));
|
|
307
315
|
if (behaviorUnits.length) {
|
|
308
|
-
const verification = createVerificationController(candidate, { reportRoot: root, onProgress: value => { progress = { stage: "behavior", ...value }; notifyProgress?.(progress); } });
|
|
316
|
+
const verification = createVerificationController(candidate, { reportRoot: root, previewHost, onProgress: value => { progress = { stage: "behavior", ...value }; notifyProgress?.(progress); } });
|
|
309
317
|
let evidence;
|
|
310
318
|
try { evidence = await verification.run({ units: behaviorUnits, persist: false }, signal); }
|
|
311
319
|
finally { await verification.close(); }
|
|
@@ -366,7 +374,7 @@ export function createMutationController(directory, { captures = createCaptureCo
|
|
|
366
374
|
preview: "Source validation passed. Inspect the managed preview build and rendered scenario after applying; validation is not visual verification." },candidateRevision);
|
|
367
375
|
} catch (error) {
|
|
368
376
|
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; } }
|
|
377
|
+
} finally { try { await previewHost?.close(); } finally { try { if (temporary) rmSync(temporary, { recursive: true, force: true }); } finally { releasePreview?.(); busy = false; active = undefined; progress = undefined; } } }
|
|
370
378
|
},
|
|
371
379
|
};
|
|
372
380
|
}
|
|
@@ -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);
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { spawn } from "node:child_process";
|
|
2
2
|
import { randomUUID } from "node:crypto";
|
|
3
|
-
import { statSync, mkdirSync, writeFileSync, renameSync, rmSync, realpathSync } from "node:fs";
|
|
3
|
+
import { statSync, mkdirSync, readFileSync, writeFileSync, renameSync, rmSync, realpathSync } from "node:fs";
|
|
4
4
|
import path from "node:path";
|
|
5
5
|
import { fileURLToPath } from "node:url";
|
|
6
6
|
import { Writable } from "node:stream";
|
|
@@ -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
|
-
|
|
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,77 @@ 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
|
-
|
|
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);
|
|
221
|
+
try { await closed; } finally { clearTimeout(timer); cleanup(); }
|
|
201
222
|
})();
|
|
202
223
|
return stopping;
|
|
203
224
|
}
|
|
204
|
-
|
|
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() {
|
|
267
|
+
if (disposed || !command) return;
|
|
268
|
+
await waitForResume();
|
|
269
|
+
if (disposed) return;
|
|
270
|
+
if (state === "failed" || restarting || stalled) await restart();
|
|
271
|
+
start();
|
|
272
|
+
const deadline = Date.now() + buildTimeout;
|
|
273
|
+
while (!disposed && state === "running" && Date.now() < deadline) {
|
|
274
|
+
try { if (JSON.parse(readFileSync(reportFile, "utf8")).session === session) return; } catch { /* Waiting for compiler initialization, without requesting a graph. */ }
|
|
275
|
+
await new Promise(resolve => setTimeout(resolve, 20));
|
|
276
|
+
}
|
|
277
|
+
if (!disposed) throw new Error(error ?? "Preview compiler initialization timed out.");
|
|
278
|
+
}, invalidate() { invalidation = randomUUID(); if (active) request(active,true); }, async warm(files) {
|
|
205
279
|
if (disposed || !command || !files.length) return;
|
|
280
|
+
await waitForResume();
|
|
206
281
|
const selected=active;
|
|
207
282
|
if (state === "failed" || restarting || stalled) await restart();
|
|
208
283
|
if (disposed) return;
|
|
@@ -210,7 +285,14 @@ export function createPreviewWatch(root, config, { log = process.stderr, buildTi
|
|
|
210
285
|
for (const file of files) requests.add(file);
|
|
211
286
|
// Preparing a graph must not replace the user's active selection.
|
|
212
287
|
request(active ?? selected ?? files[0],true);
|
|
213
|
-
}, async
|
|
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) {
|
|
214
296
|
for (const app of apps) {
|
|
215
297
|
const file = path.resolve(root, app.file);
|
|
216
298
|
if (!baselines.has(file)) baselines.set(file, stamp(file));
|
|
@@ -224,15 +306,19 @@ export function createReconfigurablePreviewWatch(root, config, options) {
|
|
|
224
306
|
let current = createPreviewWatch(root, config, options);
|
|
225
307
|
let signature = JSON.stringify(config);
|
|
226
308
|
let apps = config.apps;
|
|
227
|
-
let pending = Promise.resolve(), replacing = false, stopped = false;
|
|
309
|
+
let pending = Promise.resolve(), replacing = false, stopped = false, parked = false;
|
|
228
310
|
return {
|
|
229
|
-
start() { if (!stopped && !replacing) current.start(); },
|
|
311
|
+
start() { if (!stopped && !replacing && !parked) current.start(); },
|
|
312
|
+
async initialize() { await pending; if (!stopped) return current.initialize(); },
|
|
230
313
|
async ensure(file, signal, options) { await pending; if (stopped) throw new Error("Preview watcher is stopped."); return current.ensure(file, signal, options); },
|
|
231
314
|
status() { return replacing ? { state: "reconfiguring" } : current.status(); },
|
|
232
315
|
resourceSession() { return current.resourceSession(); },
|
|
233
316
|
buildStatus() { return current.buildStatus(); },
|
|
234
317
|
async invalidate() { await pending; if (!stopped) current.invalidate(); },
|
|
235
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(); },
|
|
236
322
|
setApps(next) { apps = next; current.setApps(next); },
|
|
237
323
|
kill() { current.kill(); },
|
|
238
324
|
reconfigure(next, force = false) {
|
|
@@ -244,7 +330,7 @@ export function createReconfigurablePreviewWatch(root, config, options) {
|
|
|
244
330
|
await current.stop();
|
|
245
331
|
if (stopped) return;
|
|
246
332
|
current = createPreviewWatch(root, { ...next, apps }, options);
|
|
247
|
-
current.start();
|
|
333
|
+
if (parked) await current.suspend(); else current.start();
|
|
248
334
|
}).finally(() => { replacing = false; });
|
|
249
335
|
return pending;
|
|
250
336
|
},
|