@reqvire-org/ads 0.3.36 → 0.3.38
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/README.md +12 -8
- package/dist/bootstrap-ds/README.md +8 -9
- package/dist/bootstrap-ds/ds.config.json +1 -8
- package/dist/bootstrap-ds/package.json +4 -3
- package/dist/bootstrap-ds/scripts/build-mcp-previews.mjs +2 -32
- package/dist/bun-compiler.mjs +13 -0
- package/dist/bun-worker.mjs +9 -0
- package/dist/check.mjs +7 -4
- package/dist/cli.mjs +20 -8
- package/dist/config.mjs +24 -4
- package/dist/development-runtime.mjs +3 -1
- package/dist/init.mjs +16 -18
- package/dist/mcp/build-status.mjs +6 -4
- package/dist/mcp/context.mjs +9 -4
- package/dist/mcp/drafts.mjs +4 -2
- package/dist/mcp/mutations.mjs +4 -14
- package/dist/mcp/preview-owner-guard.mjs +7 -4
- package/dist/mcp/preview-watch.mjs +21 -9
- package/dist/mcp/preview-widget.bundle.js +57 -63
- package/dist/mcp/preview-work.mjs +1 -15
- package/dist/mcp/project-widget.bundle.js +55 -61
- package/dist/mcp/prompts.mjs +2 -2
- package/dist/mcp/resource-loader.js +32 -10
- package/dist/mcp/server.mjs +94 -34
- package/dist/mcp/widget.bundle.js +58 -64
- package/dist/preview-builder.mjs +17 -5
- package/dist/preview-bun.mjs +269 -0
- package/dist/preview-imports.mjs +73 -0
- package/dist/preview-resources.mjs +26 -14
- package/dist/resource-limits.mjs +146 -0
- package/dist/runtime-requirements.mjs +21 -0
- package/dist/scenario-inspector.mjs +11 -4
- package/dist/scenarios-compiler.mjs +51 -9
- package/dist/showcase/client.bundle.js +66 -71
- package/dist/showcase/index.html +2 -2
- package/dist/showcase/sandbox.bundle.js +1 -1
- package/dist/showcase/style.css +4 -0
- package/dist/skills/ads-break-ui/SKILL.md +42 -42
- package/dist/skills/ads-break-ui/references/drafts.md +6 -3
- package/dist/skills/ads-break-ui/references/guarded-editing.md +4 -3
- package/dist/skills/ads-break-ui/references/runtimes.md +175 -140
- package/dist/skills/ads-break-ui/references/validation.md +13 -3
- package/dist/skills/ads-break-ui/references/workflows.md +82 -0
- package/dist/skills/ads-designer/SKILL.md +41 -41
- package/dist/skills/ads-designer/assets/bootstrap-ds/README.md +8 -9
- package/dist/skills/ads-designer/assets/bootstrap-ds/ds.config.json +1 -8
- package/dist/skills/ads-designer/assets/bootstrap-ds/package.json +4 -3
- package/dist/skills/ads-designer/assets/bootstrap-ds/scripts/build-mcp-previews.mjs +2 -32
- package/dist/skills/ads-designer/references/cli.md +25 -21
- package/dist/skills/ads-designer/references/drafts.md +6 -3
- package/dist/skills/ads-designer/references/guarded-editing.md +4 -3
- package/dist/skills/ads-designer/references/runtimes.md +175 -140
- package/dist/skills/ads-designer/references/validation.md +13 -3
- package/dist/skills/ads-designer/references/workflows.md +82 -0
- package/dist/skills/ads-import/SKILL.md +43 -44
- package/dist/skills/ads-import/references/cli.md +25 -21
- package/dist/skills/ads-import/references/drafts.md +6 -3
- package/dist/skills/ads-import/references/guarded-editing.md +4 -3
- package/dist/skills/ads-import/references/runtimes.md +175 -140
- package/dist/skills/ads-import/references/validation.md +13 -3
- package/dist/skills/ads-import/references/workflows.md +82 -0
- package/dist/skills/ads-motion/SKILL.md +40 -40
- package/dist/skills/ads-motion/references/drafts.md +6 -3
- package/dist/skills/ads-motion/references/guarded-editing.md +4 -3
- package/dist/skills/ads-motion/references/runtimes.md +175 -140
- package/dist/skills/ads-motion/references/validation.md +13 -3
- package/dist/skills/ads-motion/references/workflows.md +82 -0
- package/dist/skills/ads-port/SKILL.md +40 -40
- package/dist/skills/ads-port/references/cli.md +25 -21
- package/dist/skills/ads-port/references/drafts.md +6 -3
- package/dist/skills/ads-port/references/guarded-editing.md +4 -3
- package/dist/skills/ads-port/references/runtimes.md +175 -140
- package/dist/skills/ads-port/references/validation.md +13 -3
- package/dist/skills/ads-port/references/workflows.md +82 -0
- package/dist/usage.mjs +84 -0
- package/dist/validation.mjs +0 -12
- package/dist/verification/browser.mjs +77 -48
- package/docs/ADS.md +17 -11
- package/docs/ARCHITECTURE.md +43 -29
- package/docs/BEHAVIORS.md +3 -3
- package/docs/CHANGELOG.md +81 -13
- package/docs/GUIDE.md +96 -53
- package/docs/MCP.md +117 -123
- package/docs/benchmarks/bun-previews.md +91 -0
- package/docs/benchmarks/gidi-preview-memory.md +4 -0
- package/package.json +16 -14
|
@@ -0,0 +1,146 @@
|
|
|
1
|
+
import { spawn, execFile } from "node:child_process";
|
|
2
|
+
import { existsSync, mkdtempSync, readFileSync, readdirSync, rmSync, writeFileSync } from "node:fs";
|
|
3
|
+
import os from "node:os";
|
|
4
|
+
import path from "node:path";
|
|
5
|
+
import { fileURLToPath } from "node:url";
|
|
6
|
+
|
|
7
|
+
const MiB = 1024 * 1024;
|
|
8
|
+
const execute = (command, args) => new Promise(resolve => execFile(command, args, {timeout:5000,windowsHide:true,maxBuffer:8*MiB}, (error, stdout) => resolve(error ? null : stdout)));
|
|
9
|
+
|
|
10
|
+
function hostMemory() {
|
|
11
|
+
let available = os.freemem(), parentLimit = Infinity;
|
|
12
|
+
if (process.platform === "linux") {
|
|
13
|
+
try { available = Number(readFileSync("/proc/meminfo","utf8").match(/^MemAvailable:\s+(\d+)/m)[1])*1024; } catch { /* Use OS free memory. */ }
|
|
14
|
+
try {
|
|
15
|
+
const group = readFileSync("/proc/self/cgroup","utf8").match(/^0::(.*)$/m)[1];
|
|
16
|
+
let folder = path.join("/sys/fs/cgroup", group);
|
|
17
|
+
while(folder.startsWith("/sys/fs/cgroup")) {
|
|
18
|
+
try { const value=readFileSync(path.join(folder,"memory.max"),"utf8").trim(); if(value!=="max")parentLimit=Math.min(parentLimit,Number(value)); } catch { /* Not every ancestor has a memory controller. */ }
|
|
19
|
+
if(folder==="/sys/fs/cgroup")break;folder=path.dirname(folder);
|
|
20
|
+
}
|
|
21
|
+
} catch { /* A watchdog can still enforce the process budget. */ }
|
|
22
|
+
}
|
|
23
|
+
return {totalMb:os.totalmem()/MiB,availableMb:available/MiB,parentLimitMb:parentLimit/MiB};
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
export function resolveMemoryBudget(resources={}, host=hostMemory()) {
|
|
27
|
+
const automatic=Math.max(128,Math.floor(Math.min(6144,host.totalMb/4,Math.max(128,host.availableMb-1024))));
|
|
28
|
+
return Math.max(64,Math.floor(Math.min(resources.memoryLimitMb??automatic,host.parentLimitMb??Infinity)));
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
function inheritedScope() {
|
|
32
|
+
const folder=process.env.ADS_MEMORY_SCOPE;
|
|
33
|
+
const budget=Number(process.env.ADS_MEMORY_LIMIT_MB);
|
|
34
|
+
return folder&&Number.isInteger(budget)&&budget>=64&&["cgroup","inherited-cgroup","watchdog"].includes(process.env.ADS_MEMORY_ENFORCEMENT)&&path.basename(folder).startsWith("ads-memory-")&&existsSync(folder)?folder:null;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
export function resourceLimitsStatus(resources) {
|
|
38
|
+
const inherited=inheritedScope();
|
|
39
|
+
return {memoryLimitMb:inherited?Number(process.env.ADS_MEMORY_LIMIT_MB):resolveMemoryBudget(resources),
|
|
40
|
+
enforcement:inherited?process.env.ADS_MEMORY_ENFORCEMENT:"host-managed",
|
|
41
|
+
scope:inherited?"ADS command and descendants":"embedding host",hardLimit:!!inherited&&["cgroup","inherited-cgroup"].includes(process.env.ADS_MEMORY_ENFORCEMENT)};
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
async function processes() {
|
|
45
|
+
if(process.platform==="linux") {
|
|
46
|
+
const values=new Map();
|
|
47
|
+
for(const name of readdirSync("/proc"))if(/^\d+$/.test(name))try{
|
|
48
|
+
const text=readFileSync(`/proc/${name}/stat`,"utf8"),fields=text.slice(text.lastIndexOf(")")+2).split(" ");
|
|
49
|
+
values.set(Number(name),{parent:Number(fields[1]),start:fields[19]});
|
|
50
|
+
}catch{/* A process may exit during sampling. */}
|
|
51
|
+
return values;
|
|
52
|
+
}
|
|
53
|
+
const output=process.platform==="win32"
|
|
54
|
+
?await execute("powershell.exe",["-NoProfile","-Command","Get-CimInstance Win32_Process | Select-Object ProcessId,ParentProcessId,WorkingSetSize,CreationDate | ConvertTo-Json -Compress"])
|
|
55
|
+
:await execute("ps",["-axo","pid=,ppid=,rss=,lstart="]);
|
|
56
|
+
if(output===null)throw new Error("Cannot sample process-tree memory.");
|
|
57
|
+
if(process.platform==="win32")return new Map([JSON.parse(output)].flat().map(row=>[row.ProcessId,{parent:row.ParentProcessId,rss:Number(row.WorkingSetSize),start:String(row.CreationDate)}]));
|
|
58
|
+
return new Map(output.trim().split("\n").filter(Boolean).map(line=>{const [pid,parent,rss,...date]=line.trim().split(/\s+/);return[Number(pid),{parent:Number(parent),rss:Number(rss)*1024,start:date.join(" ")}];}));
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
export async function sampleMemoryTree(pid, owned=new Map()) {
|
|
62
|
+
const current=await processes();
|
|
63
|
+
for(const [id,start]of owned)if(current.get(id)?.start!==start)owned.delete(id);
|
|
64
|
+
if(current.has(pid))owned.set(pid,current.get(pid).start);
|
|
65
|
+
for(let pass=0;pass<100;pass++) {
|
|
66
|
+
const before=owned.size;for(const [id,value]of current)if(owned.has(value.parent))owned.set(id,value.start);
|
|
67
|
+
if(owned.size===before)break;
|
|
68
|
+
}
|
|
69
|
+
let bytes=0;
|
|
70
|
+
for(const id of owned.keys())try{
|
|
71
|
+
bytes+=current.get(id).rss??Number(readFileSync(`/proc/${id}/status`,"utf8").match(/^VmRSS:\s+(\d+)/m)?.[1]??0)*1024;
|
|
72
|
+
}catch{/* An exited process no longer consumes memory. */}
|
|
73
|
+
return {bytes,owned};
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
/** Dedicated CLI supervision; embedded APIs retain their host's resource policy. */
|
|
77
|
+
export async function runWithMemoryBudget(command,args,{cwd=process.cwd(),memoryLimitMb,kernel=true}={}) {
|
|
78
|
+
const budget=memoryLimitMb??resolveMemoryBudget();
|
|
79
|
+
if(!Number.isInteger(budget)||budget<64||budget>1048576)throw new Error("A process memory budget must be 64–1048576 MiB.");
|
|
80
|
+
const folder=mkdtempSync(path.join(os.tmpdir(),"ads-memory-")), marker=path.join(folder,"started.json");
|
|
81
|
+
const unit=`ads-memory-${process.pid}-${path.basename(folder).slice(-6)}.scope`;
|
|
82
|
+
let interrupted=false,exceeded=false,monitorError=false,child,guard,observing=false,timer,peak=0;
|
|
83
|
+
const stop=()=>{interrupted=true;guard?.stdin.end("cleanup\n");};
|
|
84
|
+
for(const signal of ["SIGINT","SIGTERM"])process.on(signal,stop);
|
|
85
|
+
async function launch(mode) {
|
|
86
|
+
const enforced=mode==="cgroup";
|
|
87
|
+
let pending="",started=false,done=false;
|
|
88
|
+
const env={...process.env,ADS_MEMORY_SCOPE:folder,ADS_MEMORY_LIMIT_MB:String(budget),ADS_MEMORY_ENFORCEMENT:mode};
|
|
89
|
+
child=spawn(enforced?"systemd-run":command,enforced?["--user","--scope","--quiet",`--unit=${unit}`,"-p",`MemoryMax=${budget}M`,"-p","MemorySwapMax=0","-p","OOMPolicy=kill","--",command,...args]:args,
|
|
90
|
+
{cwd,env,stdio:["inherit","inherit","pipe"],detached:process.platform!=="win32",windowsHide:true});
|
|
91
|
+
const active=child;
|
|
92
|
+
if(child.pid){
|
|
93
|
+
guard=spawn(process.execPath,[fileURLToPath(new URL("./mcp/preview-owner-guard.mjs",import.meta.url)),String(child.pid),"--tree"],{stdio:["pipe","ignore","ignore"],windowsHide:true});
|
|
94
|
+
guard.stdin.on("error",()=>{});
|
|
95
|
+
guard.on("error",()=>{monitorError=true;active.kill("SIGKILL");});
|
|
96
|
+
guard.once("exit",()=>{if(!done&&!interrupted&&!exceeded&&!monitorError){monitorError=true;active.kill("SIGKILL");}});
|
|
97
|
+
if(mode==="watchdog"){
|
|
98
|
+
const owned=new Map();
|
|
99
|
+
timer=setInterval(async()=>{
|
|
100
|
+
if(observing)return;observing=true;
|
|
101
|
+
try{
|
|
102
|
+
const {bytes}=await sampleMemoryTree(active.pid,owned);peak=Math.max(peak,bytes);
|
|
103
|
+
if(bytes>budget*MiB){exceeded=true;guard.stdin.end("kill\n");}
|
|
104
|
+
}catch{monitorError=true;guard.stdin.end("kill\n");}
|
|
105
|
+
finally{observing=false;}
|
|
106
|
+
},200);
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
function forward(bytes) {
|
|
110
|
+
if(!process.stderr.write(bytes)){active.stderr.pause();process.stderr.once("drain",()=>active.stderr.resume());}
|
|
111
|
+
}
|
|
112
|
+
child.stderr.on("data",bytes=>{
|
|
113
|
+
if(!enforced||started||existsSync(marker)){started=true;if(pending){forward(pending);pending="";}forward(bytes);}
|
|
114
|
+
else pending=(pending+bytes.toString()).slice(-8000);
|
|
115
|
+
});
|
|
116
|
+
const result=await new Promise(resolve=>{child.once("error",error=>resolve({code:1,error}));child.once("close",(code,signal)=>resolve({code:code??(signal?1:0),signal}));});
|
|
117
|
+
done=true;clearInterval(timer);guard?.stdin.end("cleanup\n");
|
|
118
|
+
if(enforced&&!existsSync(marker)&&!interrupted)return null;
|
|
119
|
+
if(pending)forward(pending);
|
|
120
|
+
if(enforced){
|
|
121
|
+
const status=await execute("systemctl",["--user","show",unit,"--property=Result","--value"]);
|
|
122
|
+
exceeded=status?.trim()==="oom-kill";
|
|
123
|
+
await execute("systemctl",["--user","reset-failed",unit]);
|
|
124
|
+
}
|
|
125
|
+
if(exceeded)process.stderr.write(`ADS_MEMORY_LIMIT: ADS command exceeded its ${budget} MiB process-tree memory budget${peak?` (sampled ${Math.ceil(peak/MiB)} MiB RSS)`:""}. This invocation failed; inspect retained results before retrying.\n`);
|
|
126
|
+
if(monitorError)process.stderr.write("ADS_MEMORY_MONITOR_FAILED: resource supervision failed; command stopped.\n");
|
|
127
|
+
return exceeded||monitorError?1:interrupted?0:result.code;
|
|
128
|
+
}
|
|
129
|
+
try {
|
|
130
|
+
const parentLimit=hostMemory().parentLimitMb;
|
|
131
|
+
// A new user scope would move the command out of a caller's existing budget.
|
|
132
|
+
// Preserve finite parent envelopes; add monitoring only for a lower local cap.
|
|
133
|
+
if(kernel&&process.platform==="linux"&&Number.isFinite(parentLimit))return await launch(parentLimit<=budget?"inherited-cgroup":"watchdog");
|
|
134
|
+
if(kernel&&process.platform==="linux") {const result=await launch("cgroup");if(result!==null)return result;}
|
|
135
|
+
return await launch("watchdog");
|
|
136
|
+
}finally{
|
|
137
|
+
clearInterval(timer);for(const signal of ["SIGINT","SIGTERM"])process.removeListener(signal,stop);
|
|
138
|
+
rmSync(folder,{recursive:true,force:true});
|
|
139
|
+
}
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
export async function enterMemoryBudget(config,args) {
|
|
143
|
+
const inherited=inheritedScope();
|
|
144
|
+
if(inherited){const file=path.join(inherited,"started.json");if(!existsSync(file))writeFileSync(file,JSON.stringify({pid:process.pid}));return null;}
|
|
145
|
+
return runWithMemoryBudget(process.execPath,[process.argv[1],...args],{memoryLimitMb:resolveMemoryBudget(config.resources)});
|
|
146
|
+
}
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
export const minimumBunVersion = "1.4.1";
|
|
2
|
+
|
|
3
|
+
export function supportsBunVersion(version) {
|
|
4
|
+
const match = /^(\d+)\.(\d+)\.(\d+)(?:\+[\w.-]+)?$/.exec(version ?? "");
|
|
5
|
+
if (!match) return false;
|
|
6
|
+
const actual = match.slice(1).map(Number), minimum = minimumBunVersion.split(".").map(Number);
|
|
7
|
+
for (let index = 0; index < minimum.length; index++) {
|
|
8
|
+
if (actual[index] !== minimum[index]) return actual[index] > minimum[index];
|
|
9
|
+
}
|
|
10
|
+
return true;
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
export function assertBunRuntime(version = process.versions.bun) {
|
|
14
|
+
if (!supportsBunVersion(version)) throw new Error(`ADS requires Bun >=${minimumBunVersion}; ${version ? `running Bun ${version}` : "this process is not running Bun"} (${process.execPath}). Upgrade the Bun executable used to launch ADS. The consuming application can keep its own runtime.`);
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
// Bun's emulated Node version can stay unchanged across compiler upgrades.
|
|
18
|
+
// Fingerprint both so an upgrade never reuses output from the old bundler.
|
|
19
|
+
export function previewRuntimeFingerprint() {
|
|
20
|
+
return `${process.version}/bun:${process.versions.bun ?? "none"}/${process.platform}/${process.arch}`;
|
|
21
|
+
}
|
|
@@ -1,12 +1,19 @@
|
|
|
1
1
|
import { Worker, isMainThread, parentPort, workerData } from "node:worker_threads";
|
|
2
2
|
import { loadConfig } from "./config.mjs";
|
|
3
|
+
import { inspectCatalog } from "./mcp/catalog.mjs";
|
|
4
|
+
import { inspectBehaviorLibraries } from "./behavior-libraries.mjs";
|
|
3
5
|
import { discoverScenarioRegistry } from "./scenario-registry.mjs";
|
|
4
6
|
|
|
5
7
|
// Discovery is semantic source analysis. Keep it off the live compiler's event
|
|
6
8
|
// loop; the caller fences each result against the exact project input digest.
|
|
7
9
|
if (!isMainThread && workerData?.adsScenarioInspector) {
|
|
8
|
-
parentPort.on("message", ({ id, root = workerData.root }) => {
|
|
9
|
-
try {
|
|
10
|
+
parentPort.on("message", ({ id, root = workerData.root, kind = "registry" }) => {
|
|
11
|
+
try {
|
|
12
|
+
const options=loadConfig(root),registry=discoverScenarioRegistry(options);
|
|
13
|
+
const libraries=kind==="catalog"?inspectBehaviorLibraries(options):null;
|
|
14
|
+
const result=kind==="catalog"?{catalog:inspectCatalog(options,registry.scenarios,libraries),libraries:libraries.libraries}:registry;
|
|
15
|
+
parentPort.postMessage({id,result});
|
|
16
|
+
}
|
|
10
17
|
catch (error) { parentPort.postMessage({ id, error: error.message }); }
|
|
11
18
|
});
|
|
12
19
|
}
|
|
@@ -16,7 +23,7 @@ export function createScenarioInspector(root, { idleMs = 5000 } = {}) {
|
|
|
16
23
|
const pending = new Map();
|
|
17
24
|
function fail(error) { for (const task of pending.values()) task.reject(error); pending.clear(); }
|
|
18
25
|
return {
|
|
19
|
-
inspect(directory = root) {
|
|
26
|
+
inspect(directory = root, kind = "registry") {
|
|
20
27
|
clearTimeout(idle);
|
|
21
28
|
if (!worker) {
|
|
22
29
|
worker = new Worker(new URL(import.meta.url), { workerData: { adsScenarioInspector: true, root } });
|
|
@@ -33,7 +40,7 @@ export function createScenarioInspector(root, { idleMs = 5000 } = {}) {
|
|
|
33
40
|
worker.on("exit", () => { if (worker === current) { fail(new Error("Scenario inspector closed.")); worker = undefined; } });
|
|
34
41
|
}
|
|
35
42
|
const id = ++sequence;
|
|
36
|
-
return new Promise((resolve, reject) => { pending.set(id, { resolve, reject }); worker.postMessage({ id, root: directory }); });
|
|
43
|
+
return new Promise((resolve, reject) => { pending.set(id, { resolve, reject }); worker.postMessage({ id, root: directory, kind }); });
|
|
37
44
|
},
|
|
38
45
|
async close() { clearTimeout(idle); const previous = worker; worker = undefined; fail(new Error("Scenario inspector closed.")); await previous?.terminate(); },
|
|
39
46
|
};
|
|
@@ -12,6 +12,7 @@ import { previewFileIgnored, previewWatchDirectories } from "./preview-files.mjs
|
|
|
12
12
|
import { createScenarioInspector } from "./scenario-inspector.mjs";
|
|
13
13
|
import { configurationFiles } from "./units.mjs";
|
|
14
14
|
import { validationInputFiles } from "./validation-inputs.mjs";
|
|
15
|
+
import { previewRuntimeFingerprint } from "./runtime-requirements.mjs";
|
|
15
16
|
|
|
16
17
|
const digest = value => createHash("sha256").update(value).digest("hex");
|
|
17
18
|
const fileDigest = file => { try { return digest(readFileSync(file)); } catch { return null; } };
|
|
@@ -22,7 +23,7 @@ const cacheVersion = 3, maxCacheBytes = 8 * 1024 * 1024;
|
|
|
22
23
|
export function createPreviewCache(options, compilerFiles = []) {
|
|
23
24
|
const { root } = options;
|
|
24
25
|
const key = file => isInside(import.meta.dirname,file) ? `ads-tool/${path.relative(import.meta.dirname,file)}` : isInside(root,file) ? `project/${path.relative(root,file)}` : file;
|
|
25
|
-
const adapterFiles = [import.meta.filename, ...["preview-builder.mjs", "preview-workers.mjs", "preview-files.mjs", "preview-inputs.mjs", "preview-resources.mjs", "preview-scope.mjs", "scenario-groups.mjs", "scenario-inspector.mjs", "scenario-registry.mjs", "scenarios-vite.mjs", "linaria.mjs", "linaria/atomic-css.cjs", "linaria/atomic-styled.cjs", "linaria/preserve-values.cjs"].map(file => path.join(import.meta.dirname, file)), ...compilerFiles,
|
|
26
|
+
const adapterFiles = [import.meta.filename, ...["runtime-requirements.mjs", "preview-builder.mjs", "preview-workers.mjs", "preview-files.mjs", "preview-inputs.mjs", "preview-resources.mjs", "preview-scope.mjs", "scenario-groups.mjs", "scenario-inspector.mjs", "scenario-registry.mjs", "scenarios-vite.mjs", "linaria.mjs", "linaria/atomic-css.cjs", "linaria/atomic-styled.cjs", "linaria/preserve-values.cjs"].map(file => path.join(import.meta.dirname, file)), ...compilerFiles,
|
|
26
27
|
...["package.json", "package-lock.json", "bun.lock", "bun.lockb", "node_modules/.package-lock.json"].map(file => path.join(root, file))];
|
|
27
28
|
const adapterDigest = () => digest(JSON.stringify(adapterFiles.map(file => [key(file), fileDigest(file)])));
|
|
28
29
|
const loadedAdapter = adapterDigest();
|
|
@@ -38,7 +39,7 @@ export function createPreviewCache(options, compilerFiles = []) {
|
|
|
38
39
|
}
|
|
39
40
|
reload();
|
|
40
41
|
function inputs() {
|
|
41
|
-
const rows = [["project-inputs",previewSourceRevision(options)],["
|
|
42
|
+
const rows = [["project-inputs",previewSourceRevision(options)],["runtime",previewRuntimeFingerprint()]];
|
|
42
43
|
for (const file of compilerFiles) rows.push([key(file), fileDigest(file)]);
|
|
43
44
|
// Tool upgrades invalidate validation even when the project's lockfile is unchanged.
|
|
44
45
|
for (const name of readdirSync(import.meta.dirname).filter(name => name.endsWith(".mjs"))) {
|
|
@@ -78,7 +79,7 @@ export function createPreviewCache(options, compilerFiles = []) {
|
|
|
78
79
|
...compilerInputs(),
|
|
79
80
|
["installed-packages", fileDigest(path.join(root, "node_modules/.package-lock.json"))],
|
|
80
81
|
["scheduler", fileDigest(import.meta.filename)],
|
|
81
|
-
["
|
|
82
|
+
["runtime", previewRuntimeFingerprint()],
|
|
82
83
|
]));
|
|
83
84
|
function reusable(entry, expectedHtml, inspection) {
|
|
84
85
|
const cached = value.entries[entry.id];
|
|
@@ -207,6 +208,20 @@ export async function runScenarioCompiler(directory, { watched = false, validate
|
|
|
207
208
|
const requested = new Set();
|
|
208
209
|
const pending = new Set();
|
|
209
210
|
let active;
|
|
211
|
+
const prewarm = watched && process.env.ADS_MCP_PREWARM_VIEWS === "1";
|
|
212
|
+
const warmed = new Set(), warmFailures = new Set();
|
|
213
|
+
let preferred, warming;
|
|
214
|
+
if(prewarm)try{preferred=JSON.parse(readFileSync(path.join(root,".ds/last-preview.json"),"utf8")).scenario;}catch{/* First startup warms the first view. */}
|
|
215
|
+
function warmProgress() {
|
|
216
|
+
if(!prewarm)return;
|
|
217
|
+
const completed=entries.filter(entry=>warmed.has(entry.id)).length,failed=entries.filter(entry=>warmFailures.has(entry.id)).length;
|
|
218
|
+
reporter.warmup({state:completed===entries.length?"ready":completed+failed===entries.length?"error":"warming",completed,total:entries.length,failed,...(warming?{active:warming}:{})});
|
|
219
|
+
}
|
|
220
|
+
function nextWarm() {
|
|
221
|
+
if(!prewarm||registryFailure)return;
|
|
222
|
+
return entries.find(entry=>entry.id===preferred&&!requested.has(entry.id)&&!warmed.has(entry.id))??entries.find(entry=>!requested.has(entry.id)&&!warmed.has(entry.id));
|
|
223
|
+
}
|
|
224
|
+
warmProgress();
|
|
210
225
|
let compiling = false;
|
|
211
226
|
let stopped = false;
|
|
212
227
|
let generation = 0;
|
|
@@ -317,7 +332,7 @@ export async function runScenarioCompiler(directory, { watched = false, validate
|
|
|
317
332
|
try { readPreviewManifest(options, { verify: true }); }
|
|
318
333
|
catch { reusable = false; }
|
|
319
334
|
}
|
|
320
|
-
const outcomes = await checkedBuild(stamp, () => reusable ? null : buildGraph(entries, options, track, { watched: false }));
|
|
335
|
+
const outcomes = await checkedBuild(stamp, () => reusable ? null : buildGraph(entries, options, track, { watched: false, sourceRevision }));
|
|
321
336
|
const failure = outcomes.find(outcome => outcome.status === "rejected");
|
|
322
337
|
if (failure) throw failure.reason;
|
|
323
338
|
cache.assertCompiler();
|
|
@@ -334,6 +349,8 @@ export async function runScenarioCompiler(directory, { watched = false, validate
|
|
|
334
349
|
publishedStamp = stamp;
|
|
335
350
|
publishedEntries = new Set(entries.map(entry => entry.id));
|
|
336
351
|
cache.recordProduction(stamp);
|
|
352
|
+
for(const entry of entries){warmed.add(entry.id);warmFailures.delete(entry.id);}
|
|
353
|
+
warmProgress();
|
|
337
354
|
reporter.progress("idle");
|
|
338
355
|
return true;
|
|
339
356
|
} catch (error) {
|
|
@@ -360,7 +377,10 @@ export async function runScenarioCompiler(directory, { watched = false, validate
|
|
|
360
377
|
reporter.setApps(buildApps());
|
|
361
378
|
}
|
|
362
379
|
const registryReused = !!prepared && JSON.stringify(prepared) === JSON.stringify(entries);
|
|
363
|
-
|
|
380
|
+
// Publication/cache identities follow discovery order, never navigation
|
|
381
|
+
// order. Otherwise warming a non-first view produces a full graph that
|
|
382
|
+
// cannot match the next process's canonical registry and rebuilds forever.
|
|
383
|
+
const selected = registryReused ? prepared : entries.filter(entry=>requested.has(entry.id));
|
|
364
384
|
const candidate = { generation, stamp, sourceRevision, registry: [...entries], entries: selected, dependencies: new Set(), registryReused };
|
|
365
385
|
// Retain roots requested by other mounted Apps, without compiling untouched
|
|
366
386
|
// catalogue entries. Production/unwatched builds still cover all entries.
|
|
@@ -387,7 +407,7 @@ export async function runScenarioCompiler(directory, { watched = false, validate
|
|
|
387
407
|
cache.assertCompiler();
|
|
388
408
|
const cached = cachedPreviewPublication(options, candidate.entries, cache.graphRevision());
|
|
389
409
|
if (cached && cache.reusableEntries(candidate.entries,cached.revision)) { candidate.reused = true; return cached; }
|
|
390
|
-
return buildGraph(candidate.entries, options, track, { watched: true });
|
|
410
|
+
return buildGraph(candidate.entries, options, track, { watched: true, sourceRevision });
|
|
391
411
|
});
|
|
392
412
|
liveCandidate = candidate;
|
|
393
413
|
try {
|
|
@@ -396,6 +416,8 @@ export async function runScenarioCompiler(directory, { watched = false, validate
|
|
|
396
416
|
if (publication.publishLive) {
|
|
397
417
|
publication.publishLive(reporter.session);
|
|
398
418
|
reporter.live({ revision: publication.revision, sourceRevision });
|
|
419
|
+
for(const entry of candidate.entries){warmed.add(entry.id);warmFailures.delete(entry.id);}
|
|
420
|
+
warmProgress();
|
|
399
421
|
}
|
|
400
422
|
reporter.progress("validation");
|
|
401
423
|
} catch (error) {
|
|
@@ -406,6 +428,8 @@ export async function runScenarioCompiler(directory, { watched = false, validate
|
|
|
406
428
|
}
|
|
407
429
|
function rejectLive(candidate, error) {
|
|
408
430
|
candidate.failed = true;
|
|
431
|
+
for(const entry of candidate.entries){warmed.delete(entry.id);warmFailures.add(entry.id);}
|
|
432
|
+
warmProgress();
|
|
409
433
|
reporter.batch(() => {
|
|
410
434
|
reporter.live(undefined);
|
|
411
435
|
for (const entry of candidate.entries) reporter.error(entry.id, candidate.revisions.get(entry.id), error);
|
|
@@ -478,7 +502,7 @@ export async function runScenarioCompiler(directory, { watched = false, validate
|
|
|
478
502
|
if (compiling) return;
|
|
479
503
|
compiling = true;
|
|
480
504
|
try {
|
|
481
|
-
while ((pending.size || fullRequest && fullRequest !== completedFull) && !stopped) {
|
|
505
|
+
while ((pending.size || fullRequest && fullRequest !== completedFull || nextWarm()) && !stopped) {
|
|
482
506
|
if (fullRequest && fullRequest !== completedFull) {
|
|
483
507
|
const token = fullRequest, sourceRevision = previewSourceRevision(options);
|
|
484
508
|
// Production compilation and incremental compilation never overlap.
|
|
@@ -498,10 +522,26 @@ export async function runScenarioCompiler(directory, { watched = false, validate
|
|
|
498
522
|
continue;
|
|
499
523
|
}
|
|
500
524
|
if (registryFailure) break;
|
|
525
|
+
if(!pending.size){
|
|
526
|
+
// Let incoming foreground selections enter the queue before the next
|
|
527
|
+
// background job in the shared compiler.
|
|
528
|
+
await new Promise(resolve=>setTimeout(resolve,50));
|
|
529
|
+
if(stopped)break;
|
|
530
|
+
if(!pending.size){
|
|
531
|
+
const entry=nextWarm();
|
|
532
|
+
if(entry){
|
|
533
|
+
// Bun can finish the remaining graph in one bounded build after
|
|
534
|
+
// the first view. Rebuilding 1, 2, ... N roots repeats bundling N
|
|
535
|
+
// times despite the persistent per-file transform cache.
|
|
536
|
+
const warm=buildGraph?.warmBatch&&warmed.size?entries.filter(item=>!requested.has(item.id)&&!warmed.has(item.id)):[entry];
|
|
537
|
+
for(const item of warm){requested.add(item.id);pending.add(item.id);}
|
|
538
|
+
}
|
|
539
|
+
}
|
|
540
|
+
}
|
|
501
541
|
const id = pending.has(active) ? active : pending.values().next().value;
|
|
502
542
|
pending.delete(id);
|
|
503
543
|
const entry = entries.find(entry => entry.id === id);
|
|
504
|
-
if (entry) await compile(entry);
|
|
544
|
+
if (entry) {warming=id;warmProgress();try{await compile(entry);}finally{warming=undefined;warmProgress();}}
|
|
505
545
|
}
|
|
506
546
|
} catch (error) { failure(error); }
|
|
507
547
|
finally { compiling = false; }
|
|
@@ -565,6 +605,7 @@ export async function runScenarioCompiler(directory, { watched = false, validate
|
|
|
565
605
|
++generation;
|
|
566
606
|
reporter.progress("queued");
|
|
567
607
|
validation = undefined;
|
|
608
|
+
warmed.clear();warmFailures.clear();warmProgress();
|
|
568
609
|
const changes = [...changed]; changed.clear();
|
|
569
610
|
try {
|
|
570
611
|
// Registry inspection for live graphs runs in the verification worker.
|
|
@@ -639,7 +680,8 @@ export async function runScenarioCompiler(directory, { watched = false, validate
|
|
|
639
680
|
} catch (error) { failure(error); }
|
|
640
681
|
}, 1000);
|
|
641
682
|
request();
|
|
642
|
-
|
|
683
|
+
if(prewarm)void drain();
|
|
684
|
+
console.log(`Scenario compiler ready: ${entries.length} entries; ${prewarm?"sequential background warming enabled":"builds are requested on demand"}.`);
|
|
643
685
|
for (const signal of ["SIGINT", "SIGTERM"]) process.once(signal, () => {
|
|
644
686
|
stopped = true; clearTimeout(timer); clearInterval(reconcileTimer); for (const { watcher } of watchers.values()) watcher.close();
|
|
645
687
|
void inspector?.close();
|