@reqvire-org/ads 0.3.34 → 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/check-runner.mjs +7 -0
- package/dist/mcp/mutations.mjs +16 -8
- package/dist/mcp/preview-owner-guard.mjs +36 -1
- package/dist/mcp/preview-watch.mjs +88 -13
- package/dist/mcp/preview-work.mjs +41 -0
- package/dist/mcp/server.mjs +27 -14
- package/dist/preview-builder.mjs +1 -0
- package/dist/scenario-inspector.mjs +11 -5
- package/dist/scenario-registry.mjs +16 -0
- package/dist/scenarios-compiler.mjs +90 -23
- package/dist/skills/ads-break-ui/references/runtimes.md +9 -0
- package/dist/skills/ads-designer/references/runtimes.md +9 -0
- package/dist/skills/ads-import/references/runtimes.md +9 -0
- package/dist/skills/ads-motion/references/runtimes.md +9 -0
- package/dist/skills/ads-port/references/runtimes.md +9 -0
- package/dist/validation-checks.mjs +23 -3
- package/dist/validation.mjs +19 -10
- package/dist/verification.mjs +5 -4
- package/docs/ARCHITECTURE.md +28 -0
- package/docs/CHANGELOG.md +34 -12
- package/docs/GUIDE.md +5 -1
- package/docs/MCP.md +10 -5
- package/docs/benchmarks/gidi-preview-memory.md +141 -0
- 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 })));
|
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);
|
|
@@ -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,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
|
-
|
|
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() {
|
|
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
|
|
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
|
+
}
|
package/dist/mcp/server.mjs
CHANGED
|
@@ -3,14 +3,14 @@ import path from "node:path";
|
|
|
3
3
|
import { Server, ProtocolError, INVALID_PARAMS, ResourceNotFoundError } from "@modelcontextprotocol/server";
|
|
4
4
|
import { serveStdio, StdioServerTransport } from "@modelcontextprotocol/server/stdio";
|
|
5
5
|
import { z } from "zod";
|
|
6
|
-
import {
|
|
6
|
+
import { checkCandidate } from "../validation-checks.mjs";
|
|
7
7
|
import { createValidationController } from "../validation.mjs";
|
|
8
8
|
import { loadConfig, sourceFiles } from "../config.mjs";
|
|
9
9
|
import { createVerificationController, BEHAVIOR_URI } from "../verification.mjs";
|
|
10
10
|
import { INVESTIGATIONS_URI, investigationIndex, investigationPage, investigationSections, readInvestigation, readInvestigationResource } from "../investigations.mjs";
|
|
11
11
|
import { failure } from "../evidence.mjs";
|
|
12
12
|
import { inspectTokens } from "../tokens.mjs";
|
|
13
|
-
import { discoverScenarioRegistry } from "../scenario-registry.mjs";
|
|
13
|
+
import { discoverScenarioRegistry, releaseScenarioRegistry } from "../scenario-registry.mjs";
|
|
14
14
|
import { scenarioGroupFingerprint } from "../scenario-groups.mjs";
|
|
15
15
|
import { startShowcaseHost } from "./showcase-host.mjs";
|
|
16
16
|
import { createSkillStore, page, SKILLS_EXTENSION } from "./skills.mjs";
|
|
@@ -23,6 +23,7 @@ import { createReconfigurablePreviewWatch } from "./preview-watch.mjs";
|
|
|
23
23
|
import { BUILD_URI, buildFailure, inspectBuildStatus, summarizeBuild } from "./build-status.mjs";
|
|
24
24
|
import { GUIDE_URI, projectContext, projectGuide, serverInstructions, workflow } from "./context.mjs";
|
|
25
25
|
import { createMutationController, mutationLimits } from "./mutations.mjs";
|
|
26
|
+
import { createPreviewWork } from "./preview-work.mjs";
|
|
26
27
|
import { prepareUnitPatch, storePreparedPatch } from "./edit-preparation.mjs";
|
|
27
28
|
import { reconcileTokenSamples } from "../token-fixtures.mjs";
|
|
28
29
|
import { createCaptureController } from "../capture.mjs";
|
|
@@ -70,13 +71,13 @@ export function createAdsMcp(directory, { era = "legacy", skillDirectory, pollIn
|
|
|
70
71
|
const cache = inspection ?? {};
|
|
71
72
|
const skills = cache.skills ??= createSkillStore(skillDirectory);
|
|
72
73
|
const captures = cache.captures ??= createCaptureController(root);
|
|
73
|
-
const edits = cache.edits ??= createMutationController(root, { captures });
|
|
74
|
+
const edits = cache.edits ??= createMutationController(root, { captures, previewWork: cache.previewWork });
|
|
74
75
|
const draftObservers = cache.draftObservers ??= new Set();
|
|
75
76
|
const drafts = cache.drafts ??= createDraftController(root, { edits, prewarm: true,
|
|
76
77
|
onChange: () => { for (const observer of draftObservers) void observer().catch(error => { process.stderr.write(`ads mcp: ${error.message}\n`); }); },
|
|
77
|
-
startPreview: workspace => startAdsMcp(workspace, { stdio: false, mutations: false }) });
|
|
78
|
-
const verification = cache.verification ??= createVerificationController(root);
|
|
79
|
-
const validation = cache.validation ??= createValidationController(root);
|
|
78
|
+
startPreview: workspace => startAdsMcp(workspace, { stdio: false, mutations: false, previewWork: cache.previewWork }) });
|
|
79
|
+
const verification = cache.verification ??= createVerificationController(root, { previewWork: cache.previewWork });
|
|
80
|
+
const validation = cache.validation ??= createValidationController(root, { previewWork: cache.previewWork });
|
|
80
81
|
const executionResults = cache.executionResults ??= createExecutionResults(root);
|
|
81
82
|
const reports = cache.reports ??= createReportStore(root, { context: reportContext, resolveEvidence: reportEvidence });
|
|
82
83
|
let options = loadConfig(root);
|
|
@@ -87,6 +88,13 @@ export function createAdsMcp(directory, { era = "legacy", skillDirectory, pollIn
|
|
|
87
88
|
cache.registry = cache.catalog = cache.documents = undefined;
|
|
88
89
|
}
|
|
89
90
|
const getShowcaseUrl = () => showcaseUrl?.() ?? options.config.mcp.showcaseUrl;
|
|
91
|
+
async function architecture(signal) {
|
|
92
|
+
let release;
|
|
93
|
+
try {
|
|
94
|
+
if (cache.previewWork) release = await cache.previewWork.acquire(signal);
|
|
95
|
+
return await checkCandidate(root, signal);
|
|
96
|
+
} finally { release?.(); }
|
|
97
|
+
}
|
|
90
98
|
function scenarioUrl(id) {
|
|
91
99
|
const base = getShowcaseUrl();
|
|
92
100
|
if (!base) return null;
|
|
@@ -105,7 +113,9 @@ export function createAdsMcp(directory, { era = "legacy", skillDirectory, pollIn
|
|
|
105
113
|
const getRegistry = () => {
|
|
106
114
|
const current = loadConfig(root), revision = previewSourceRevision(current);
|
|
107
115
|
if (!cache.registry || cache.registryRevision !== revision) {
|
|
108
|
-
cache.registry = discoverScenarioRegistry(current);
|
|
116
|
+
try { cache.registry = discoverScenarioRegistry(current); }
|
|
117
|
+
finally { releaseScenarioRegistry(root); }
|
|
118
|
+
cache.registryRevision = revision; cache.catalog = undefined; cache.behaviorLibraries = undefined;
|
|
109
119
|
}
|
|
110
120
|
cache.lastRegistry = cache.registry; return cache.registry;
|
|
111
121
|
};
|
|
@@ -268,7 +278,7 @@ export function createAdsMcp(directory, { era = "legacy", skillDirectory, pollIn
|
|
|
268
278
|
else if (uri === `${PROJECT_URI}/catalog`) value = { items: annotateDrafts(getCatalog()) };
|
|
269
279
|
else if (uri === DRAFTS_URI) value = drafts.list();
|
|
270
280
|
else if (uri === `${PROJECT_URI}/scenarios`) value = getRegistry();
|
|
271
|
-
else if (uri === `${PROJECT_URI}/checks`) value =
|
|
281
|
+
else if (uri === `${PROJECT_URI}/checks`) value = await architecture(signal);
|
|
272
282
|
else if (uri === BEHAVIOR_URI || uri.startsWith(`${BEHAVIOR_URI}?`)) value = behaviorPage(options, resourceQuery(uri, ["unit", "api", "query", "section", "cursor", "limit"]));
|
|
273
283
|
else if (uri === INVESTIGATIONS_URI || uri.startsWith(`${INVESTIGATIONS_URI}?`)) value = investigationPage(root, resourceQuery(uri, ["unit", "check", "runId", "section", "cursor", "limit", "recordIndex", "offset", "chars"]));
|
|
274
284
|
else if (uri === RESULTS_URI || uri.startsWith("ads://results/")) return { contents: [executionResults.readResource(uri)] };
|
|
@@ -408,8 +418,8 @@ export function createAdsMcp(directory, { era = "legacy", skillDirectory, pollIn
|
|
|
408
418
|
const matches = inventory.tokens.filter((token) => token.name.toLowerCase().includes(search.toLowerCase()));
|
|
409
419
|
return json({ total: matches.length, tokens: matches.slice(0, limit), categories: tokenScenarios(), tokenGroups:drafts.tokenGroups(), diagnosticCount: inventory.diagnostics.length, resourceUri: `${PROJECT_URI}/tokens` });
|
|
410
420
|
} },
|
|
411
|
-
{ name: "ads_check", description: "Run read-only core ADS architecture checks; returns blocking diagnostics separately from nonblocking advisories, with warnings before informational limits. Atomic warnings include helper/forwarded-class paths and ads://guides/atomic-styles guidance; unresolved paths do not establish safe composition. Project Oxlint, typecheck, build and browser tests remain separate.", schema: z.object({ limit: z.number().int().min(1).max(50).default(20) }).strict(), call: ({ limit }) => {
|
|
412
|
-
const result =
|
|
421
|
+
{ name: "ads_check", description: "Run read-only core ADS architecture checks; returns blocking diagnostics separately from nonblocking advisories, with warnings before informational limits. Atomic warnings include helper/forwarded-class paths and ads://guides/atomic-styles guidance; unresolved paths do not establish safe composition. Project Oxlint, typecheck, build and browser tests remain separate.", schema: z.object({ limit: z.number().int().min(1).max(50).default(20) }).strict(), call: async ({ limit }, signal) => {
|
|
422
|
+
const result = await architecture(signal);
|
|
413
423
|
return json({ ok: result.ok, acceptance:result.acceptance, total: result.diagnostics.length, diagnostics: result.diagnostics.slice(0, limit), advisoryCount: result.advisories?.length ?? 0, advisories: (result.advisories ?? []).slice(0, limit), resourceUri: `${PROJECT_URI}/checks` });
|
|
414
424
|
} },
|
|
415
425
|
{ name: "ads_skills", description: "Select one ADS workflow after ads_status: ads-designer for building/refining/debugging UI; ads-port for a library reference; ads-import for another project's ADS; ads-motion for animation; ads-break-ui for stress testing. Then read that workflow with ads_read_skill. Listing does not activate a native skill.", schema: empty, call: () => json({ skills: skills.skills.map(({ uri, frontmatter }) => ({ uri, ...frontmatter })) }) },
|
|
@@ -667,14 +677,15 @@ export function createAdsMcp(directory, { era = "legacy", skillDirectory, pollIn
|
|
|
667
677
|
await previewWatch.warm(files);
|
|
668
678
|
for (const file of files) await previewWatch.ensure(file, signal);
|
|
669
679
|
}
|
|
670
|
-
return { server, refresh, warmScenarios, readResource:read, async callTool(name,args,signal){const tool=tools().find(tool=>tool.name===name);if(!tool)throw new Error("Unknown preview tool.");return tool.call(tool.schema.parse(args),signal);}, async close() { stopObservation(); if (!inspection) { await drafts.close(); await validation.close(); await verification.close(); await captures.close(); } await server.close(); } };
|
|
680
|
+
return { server, refresh, warmScenarios, buildAll(signal, options) { previewWatch.setApps(allApps()); return previewWatch.buildAll(signal, options); }, readResource:read, async callTool(name,args,signal){const tool=tools().find(tool=>tool.name===name);if(!tool)throw new Error("Unknown preview tool.");return tool.call(tool.schema.parse(args),signal);}, async close() { stopObservation(); if (!inspection) { await drafts.close(); await validation.close(); await verification.close(); await captures.close(); } await server.close(); } };
|
|
671
681
|
}
|
|
672
682
|
|
|
673
|
-
export async function startAdsMcp(directory = process.cwd(), { stdio = true, showcase = true, port = 0, mutations = false } = {}) {
|
|
683
|
+
export async function startAdsMcp(directory = process.cwd(), { stdio = true, showcase = true, port = 0, mutations = false, previewWork = createPreviewWork() } = {}) {
|
|
674
684
|
// Fail before opening the transport for configuration/distribution errors.
|
|
675
685
|
const { root, config } = loadConfig(directory);
|
|
676
|
-
const inspection = { skills: createSkillStore() };
|
|
686
|
+
const inspection = { skills: createSkillStore(), previewWork };
|
|
677
687
|
const previewWatch = createReconfigurablePreviewWatch(root, config.mcp);
|
|
688
|
+
const unregisterPreview = previewWork.register(previewWatch);
|
|
678
689
|
let host, api;
|
|
679
690
|
let buildWatcher, buildChangeTimer;
|
|
680
691
|
const buildListeners = new Set();
|
|
@@ -705,6 +716,7 @@ export async function startAdsMcp(directory = process.cwd(), { stdio = true, sho
|
|
|
705
716
|
buildListeners.clear();
|
|
706
717
|
clearTimeout(buildChangeTimer); buildWatcher?.close();
|
|
707
718
|
inspection.edits?.cancel();
|
|
719
|
+
unregisterPreview();
|
|
708
720
|
// Stop every owned resource even if another close fails or has in-flight RPCs.
|
|
709
721
|
const results = await Promise.allSettled([
|
|
710
722
|
Promise.resolve().then(() => host?.close()),
|
|
@@ -720,6 +732,7 @@ export async function startAdsMcp(directory = process.cwd(), { stdio = true, sho
|
|
|
720
732
|
for (const signal of ["SIGINT", "SIGTERM"]) process.removeListener(signal, disconnect);
|
|
721
733
|
process.removeListener("exit", forceCleanup);
|
|
722
734
|
const errors = results.filter(result => result.status === "rejected").map(result => result.reason);
|
|
735
|
+
releaseScenarioRegistry(root);
|
|
723
736
|
if (errors.length) throw new AggregateError(errors, "ADS shutdown failed");
|
|
724
737
|
})();
|
|
725
738
|
}
|
|
@@ -737,7 +750,7 @@ export async function startAdsMcp(directory = process.cwd(), { stdio = true, sho
|
|
|
737
750
|
for (const signal of ["SIGINT", "SIGTERM"]) process.once(signal, disconnect);
|
|
738
751
|
process.once("exit", forceCleanup);
|
|
739
752
|
const previewApi=()=>api??=createAdsMcp(root,{era:"modern",inspection,previewWatch,showcaseUrl,mutations:false,pollInterval:0,observeChanges:false});
|
|
740
|
-
return { close, url: host?.url, warmScenarios: (ids, signal) => previewApi().warmScenarios(ids, signal), prewarm: () => previewWatch.initialize(), onBuildChange(listener) { buildListeners.add(listener); return () => buildListeners.delete(listener); }, buildStatus: () => previewWatch.buildStatus(), primeRegistry(registry) {
|
|
753
|
+
return { close, url: host?.url, async buildAll(signal, options) { await previewWatch.initialize(); return previewApi().buildAll(signal, options); }, warmScenarios: (ids, signal) => previewApi().warmScenarios(ids, signal), prewarm: () => previewWatch.initialize(), onBuildChange(listener) { buildListeners.add(listener); return () => buildListeners.delete(listener); }, buildStatus: () => previewWatch.buildStatus(), primeRegistry(registry) {
|
|
741
754
|
if (inspection.registry === registry || inspection.lastRegistry === registry) return;
|
|
742
755
|
inspection.registry = inspection.lastRegistry = registry; inspection.registryRevision = undefined; inspection.catalog = undefined;
|
|
743
756
|
}, callTool:(name,args,signal)=>previewApi().callTool(name,args,signal),readResource:(uri,signal)=>previewApi().readResource(uri,signal),previewRevision: () => readPreviewManifest(withPreviewSession(loadConfig(root), previewWatch.resourceSession()))?.revision ?? null };
|
package/dist/preview-builder.mjs
CHANGED
|
@@ -23,6 +23,7 @@ export function createVitePreviewBuilder({ build, configure }) {
|
|
|
23
23
|
}
|
|
24
24
|
const builder = async (entries, options, track, { watched = false } = {}) => {
|
|
25
25
|
if (!watched) {
|
|
26
|
+
await close();
|
|
26
27
|
const config = await configure(entries, options);
|
|
27
28
|
const output = await build({ ...config, plugins: [...config.plugins ?? [], track], build: { ...config.build, write: false, watch: null } });
|
|
28
29
|
return createPreviewResources(output, options, entries);
|
|
@@ -11,24 +11,30 @@ if (!isMainThread && workerData?.adsScenarioInspector) {
|
|
|
11
11
|
});
|
|
12
12
|
}
|
|
13
13
|
|
|
14
|
-
export function createScenarioInspector(root) {
|
|
15
|
-
let worker, sequence = 0;
|
|
14
|
+
export function createScenarioInspector(root, { idleMs = 5000 } = {}) {
|
|
15
|
+
let worker, sequence = 0, idle;
|
|
16
16
|
const pending = new Map();
|
|
17
17
|
function fail(error) { for (const task of pending.values()) task.reject(error); pending.clear(); }
|
|
18
18
|
return {
|
|
19
19
|
inspect(directory = root) {
|
|
20
|
+
clearTimeout(idle);
|
|
20
21
|
if (!worker) {
|
|
21
22
|
worker = new Worker(new URL(import.meta.url), { workerData: { adsScenarioInspector: true, root } });
|
|
23
|
+
const current = worker;
|
|
22
24
|
worker.on("message", ({ id, result, error }) => {
|
|
23
25
|
const task = pending.get(id); pending.delete(id);
|
|
24
26
|
if (task) { if (error) task.reject(new Error(error)); else task.resolve(result); }
|
|
27
|
+
if (!pending.size && worker === current) {
|
|
28
|
+
idle = setTimeout(() => { if (worker === current && !pending.size) { worker = undefined; void current.terminate(); } }, idleMs);
|
|
29
|
+
idle.unref();
|
|
30
|
+
}
|
|
25
31
|
});
|
|
26
|
-
worker.on("error", fail);
|
|
27
|
-
worker.on("exit", () => { fail(new Error("Scenario inspector closed.")); worker = undefined; });
|
|
32
|
+
worker.on("error", error => { if (worker === current) fail(error); });
|
|
33
|
+
worker.on("exit", () => { if (worker === current) { fail(new Error("Scenario inspector closed.")); worker = undefined; } });
|
|
28
34
|
}
|
|
29
35
|
const id = ++sequence;
|
|
30
36
|
return new Promise((resolve, reject) => { pending.set(id, { resolve, reject }); worker.postMessage({ id, root: directory }); });
|
|
31
37
|
},
|
|
32
|
-
async close() { const previous = worker; worker = undefined; fail(new Error("Scenario inspector closed.")); await previous?.terminate(); },
|
|
38
|
+
async close() { clearTimeout(idle); const previous = worker; worker = undefined; fail(new Error("Scenario inspector closed.")); await previous?.terminate(); },
|
|
33
39
|
};
|
|
34
40
|
}
|
|
@@ -10,6 +10,10 @@ const hash = value => createHash("sha256").update(value).digest("hex");
|
|
|
10
10
|
const filename = "scenario-registry.json";
|
|
11
11
|
const maxBytes = 8 * 1024 * 1024;
|
|
12
12
|
const programs = new Map();
|
|
13
|
+
export function releaseScenarioRegistry(root) {
|
|
14
|
+
programs.get(root)?.clear();
|
|
15
|
+
programs.delete(root);
|
|
16
|
+
}
|
|
13
17
|
function programFor(root) {
|
|
14
18
|
const program = programs.get(root) ?? createScenarioProgram();
|
|
15
19
|
programs.delete(root); programs.set(root, program);
|
|
@@ -71,6 +75,18 @@ function write(options, revision, registry) {
|
|
|
71
75
|
finally { try { rmSync(temporary, { force: true }); } catch { /* Optional cache cleanup must not prevent discovery. */ } }
|
|
72
76
|
}
|
|
73
77
|
|
|
78
|
+
/** Relocate metadata only after identical accepted source is in place. This
|
|
79
|
+
* never supplies passing checks; validation continues to inspect source. */
|
|
80
|
+
export function prepareScenarioRegistryTransfer(candidate, target) {
|
|
81
|
+
const revision = previewSourceRevision(candidate), registry = read(candidate, revision);
|
|
82
|
+
if (!registry) return null;
|
|
83
|
+
return () => {
|
|
84
|
+
if (previewSourceRevision(target) !== revision || !validRegistry(registry, target)) return false;
|
|
85
|
+
write(target, revision, registry);
|
|
86
|
+
return true;
|
|
87
|
+
};
|
|
88
|
+
}
|
|
89
|
+
|
|
74
90
|
/** Share semantic discovery between preview hosts and compiler processes.
|
|
75
91
|
* This snapshot contains metadata/diagnostics only, never validated outputs or
|
|
76
92
|
* passing check results. Validation continues to inspect source independently. */
|