@reqvire-org/ads 0.3.40 → 0.3.42

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (43) hide show
  1. package/README.md +1 -0
  2. package/dist/bun-compiler.mjs +8 -4
  3. package/dist/cli.mjs +7 -4
  4. package/dist/config.mjs +4 -1
  5. package/dist/investigations.mjs +27 -8
  6. package/dist/mcp/context.mjs +1 -1
  7. package/dist/mcp/execution-context.mjs +38 -0
  8. package/dist/mcp/execution-coordinator.mjs +220 -0
  9. package/dist/mcp/execution-results.mjs +108 -48
  10. package/dist/mcp/mutations.mjs +3 -1
  11. package/dist/mcp/server.mjs +52 -21
  12. package/dist/scenarios-compiler.mjs +28 -1
  13. package/dist/skills/ads-break-ui/references/behaviors.md +4 -5
  14. package/dist/skills/ads-break-ui/references/evidence.md +12 -8
  15. package/dist/skills/ads-break-ui/references/validation.md +46 -0
  16. package/dist/skills/ads-designer/references/behaviors.md +4 -5
  17. package/dist/skills/ads-designer/references/cli.md +6 -1
  18. package/dist/skills/ads-designer/references/evidence.md +12 -8
  19. package/dist/skills/ads-designer/references/validation.md +46 -0
  20. package/dist/skills/ads-import/references/behaviors.md +4 -5
  21. package/dist/skills/ads-import/references/cli.md +6 -1
  22. package/dist/skills/ads-import/references/evidence.md +12 -8
  23. package/dist/skills/ads-import/references/validation.md +46 -0
  24. package/dist/skills/ads-motion/references/behaviors.md +4 -5
  25. package/dist/skills/ads-motion/references/evidence.md +12 -8
  26. package/dist/skills/ads-motion/references/validation.md +46 -0
  27. package/dist/skills/ads-port/references/behaviors.md +4 -5
  28. package/dist/skills/ads-port/references/cli.md +6 -1
  29. package/dist/skills/ads-port/references/evidence.md +12 -8
  30. package/dist/skills/ads-port/references/validation.md +46 -0
  31. package/dist/task-cache.mjs +122 -0
  32. package/dist/task-worker.mjs +19 -0
  33. package/dist/validation-checks.mjs +12 -10
  34. package/dist/validation.mjs +11 -5
  35. package/dist/verification.mjs +7 -3
  36. package/docs/ARCHITECTURE.md +23 -3
  37. package/docs/CACHING.md +99 -0
  38. package/docs/CHANGELOG.md +38 -12
  39. package/docs/MCP.md +54 -9
  40. package/docs/benchmarks/turbo-poc.md +266 -0
  41. package/docs/plans/execution-coordination.md +57 -0
  42. package/package.json +4 -3
  43. package/dist/check-runner.mjs +0 -7
@@ -0,0 +1,122 @@
1
+ import { createHash } from "node:crypto";
2
+ import { createRequire } from "node:module";
3
+ import { spawnSync } from "node:child_process";
4
+ import { accessSync, constants, existsSync, mkdirSync, readFileSync, readdirSync, realpathSync, rmSync, statSync, writeFileSync } from "node:fs";
5
+ import path from "node:path";
6
+ import { fileURLToPath } from "node:url";
7
+ import { isInside, loadConfig } from "./config.mjs";
8
+ import { validationInputFiles } from "./validation-inputs.mjs";
9
+ import { previewRuntimeFingerprint } from "./runtime-requirements.mjs";
10
+ import { checkCommand } from "./validation-checks.mjs";
11
+
12
+ const hash = value => createHash("sha256").update(value).digest("hex");
13
+ const toolRoot = path.dirname(fileURLToPath(import.meta.url));
14
+ const semanticEnv = ["NODE_ENV", "NODE_OPTIONS", "BUN_OPTIONS", "TZ", "LANG", "LC_ALL"];
15
+ function turboBinary() {
16
+ const platform=process.platform==="win32"?"windows":process.platform==="android"?"linux":process.platform,arch=process.arch==="x64"?"64":process.arch;
17
+ try {
18
+ const resolve=createRequire(createRequire(import.meta.url).resolve("turbo/package.json"));
19
+ return resolve.resolve(`@turbo/${platform}-${arch}/bin/turbo${platform==="windows"?".exe":""}`);
20
+ } catch(cause) {
21
+ // Turbo's convenience JS launcher repairs missing binaries with npm install.
22
+ // Managed ADS operations must only run already-installed project dependencies.
23
+ throw Object.assign(new Error(`ADS needs its installed Turbo binary for ${platform}-${arch}. Reinstall ADS dependencies with platform optional dependencies enabled.`,{cause}),{code:"ADS_TASK_RUNTIME_MISSING"});
24
+ }
25
+ }
26
+ function toolInputs() {
27
+ const rows=[];
28
+ function visit(directory) {
29
+ for (const entry of readdirSync(directory,{withFileTypes:true}).sort((a,b)=>a.name.localeCompare(b.name))) {
30
+ const file=path.join(directory,entry.name);
31
+ if (entry.isDirectory() && !["skills","bootstrap-ds","showcase"].includes(entry.name)) visit(file);
32
+ else if(entry.isFile() && /\.(?:mjs|js|cjs|json)$/.test(entry.name)) rows.push([path.relative(toolRoot,file),hash(readFileSync(file))]);
33
+ }
34
+ }
35
+ visit(toolRoot);
36
+ // Include the tool's dependency lock when running from a source checkout.
37
+ const lock=path.join(toolRoot,"../package-lock.json");
38
+ if(existsSync(lock))rows.push(["tool-lock",hash(readFileSync(lock))]);
39
+ return rows;
40
+ }
41
+ // Recompute source digests per request: editing a running checkout must invalidate.
42
+ export function architectureExternalInputs(root, trackingRoot=root) {
43
+ const options=loadConfig(root),manifest=path.join(root,"package.json"),pkg=existsSync(manifest)?JSON.parse(readFileSync(manifest,"utf8")):{};
44
+ const dependencies=Object.keys({...pkg.dependencies,...pkg.devDependencies,...pkg.peerDependencies}).sort().map(name=>{
45
+ for(let directory=root;;directory=path.dirname(directory)) {
46
+ const file=path.join(directory,"node_modules",name,"package.json");
47
+ if(existsSync(file))return [name,hash(readFileSync(file))];
48
+ if(path.dirname(directory)===directory)return [name,null];
49
+ }
50
+ });
51
+ const tracked=spawnSync("git",["ls-files","-z","--","."],{cwd:trackingRoot,encoding:"utf8",maxBuffer:16*1024*1024});
52
+ const generated=[...options.config.assets.generatedPaths.map(file=>path.resolve(root,file)),path.join(root,".ds"),path.join(options.dsRoot,"dist-kit"),path.join(options.dsRoot,"dist-showcase")];
53
+ const noRepository=tracked.status===128 && /not a git repository/i.test(tracked.stderr??"");
54
+ const git={status:noRepository?0:tracked.status,error:tracked.error?.code??null,stderr:noRepository?"":tracked.stderr??"",files:(tracked.stdout??"").split("\0").filter(file=>file && generated.some(directory=>isInside(directory,path.resolve(root,file)))).sort().map(file=>[file,existsSync(path.resolve(root,file))||existsSync(path.resolve(trackingRoot,file))])};
55
+ return {dependencies,git,
56
+ environment:Object.fromEntries(semanticEnv.map(name=>[name,process.env[name]??null]))};
57
+ }
58
+ export function architectureTaskInputs(root, trackingRoot=root) {
59
+ return {schemaVersion:1,kind:"architecture",runtime:previewRuntimeFingerprint(),tool:toolInputs(),files:validationInputFiles(loadConfig(root)),...architectureExternalInputs(root,trackingRoot)};
60
+ }
61
+
62
+ export function taskCacheSettings(root) {
63
+ const directory=path.resolve(root,process.env.ADS_CACHE_DIR??".ds/task-cache");
64
+ return {backend:"turbo",enabled:process.env.ADS_CACHE!=="off",remote:process.env.ADS_REMOTE_CACHE==="1",directory};
65
+ }
66
+ function cacheDirectory(root, workspace) {
67
+ const settings=taskCacheSettings(root);
68
+ if(!settings.enabled)return {...settings,directory:path.join(workspace,"cache")};
69
+ try {
70
+ mkdirSync(settings.directory,{recursive:true});
71
+ if(realpathSync(settings.directory)!==settings.directory)throw new Error("ADS cache directory cannot resolve through a symlink.");
72
+ accessSync(settings.directory,constants.W_OK);
73
+ } catch(error) {
74
+ if(!["EACCES","EPERM","EROFS","ENOSPC","EDQUOT"].includes(error.code))throw error;
75
+ return {...settings,enabled:false,remote:false,directory:path.join(workspace,"cache"),reason:"cache-directory-unwritable"};
76
+ }
77
+ return settings;
78
+ }
79
+ function collect(directory) {
80
+ // Turbo owns serialization and atomic publication. Only prune finished, old
81
+ // artifacts, never current workspaces or live ADS evidence.
82
+ const entries=readdirSync(directory).filter(name=>/^[a-f0-9]+\.tar\.zst$/.test(name)).map(name=>{
83
+ const file=path.join(directory,name),stat=statSync(file),companions=["-meta.json","-manifest.json"].map(suffix=>file.replace(/\.tar\.zst$/,suffix));
84
+ return {file,companions,size:stat.size+companions.reduce((sum,file)=>sum+(existsSync(file)?statSync(file).size:0),0),mtime:stat.mtimeMs};
85
+ }).sort((a,b)=>b.mtime-a.mtime);
86
+ let bytes=0;
87
+ for(const entry of entries){bytes+=entry.size;if((bytes>256*1024*1024 || Date.now()-entry.mtime>7*86400000) && Date.now()-entry.mtime>60000){rmSync(entry.file,{force:true});for(const file of entry.companions)rmSync(file,{force:true});}}
88
+ }
89
+
90
+ /** One backend for deterministic ADS batch checks. Cache hits are still fenced
91
+ * against current source; they never restore locks, policy results or baselines. */
92
+ export async function runArchitectureTask(root, trackingRoot, directory, signal, {fresh=false}={}) {
93
+ // A nonexistent target is a structural diagnostic, not a task workspace to
94
+ // create as a side effect. The analysis primitive exits before source work.
95
+ if(!existsSync(root)){const {checkProject}=await import("./check.mjs");return checkProject(root);}
96
+ const settings=cacheDirectory(trackingRoot,directory),inputs=architectureTaskInputs(root,trackingRoot),key=hash(JSON.stringify(inputs));
97
+ writeFileSync(path.join(directory,"inputs.json"),JSON.stringify(inputs));
98
+ writeFileSync(path.join(directory,"worker.mjs"),readFileSync(new URL("./task-worker.mjs",import.meta.url)));
99
+ writeFileSync(path.join(directory,"package.json"),JSON.stringify({name:"ads-internal-task",version:"1.0.0",private:true,packageManager:"bun@1.4.1",scripts:{architecture:`${process.versions.bun?"bun":"node"} worker.mjs`}}));
100
+ const passThrough=["ADS_TASK_ROOT","ADS_TASK_TRACKING_ROOT","ADS_TASK_TOOL","ADS_TASK_KEY"];
101
+ writeFileSync(path.join(directory,"turbo.json"),JSON.stringify({tasks:{architecture:{inputs:["inputs.json","worker.mjs"],outputs:["out/report.json"],passThroughEnv:passThrough}},globalPassThroughEnv:semanticEnv}));
102
+ const modes=settings.enabled?`local:${fresh?"w":"rw"}${settings.remote?`,remote:${fresh?"w":"rw"}`:""}`:"local:";
103
+ const args=["run","architecture","--single-package",`--cache=${modes}`,`--cache-dir=${settings.directory}`,"--concurrency=1","--summarize","--output-logs=errors-only","--ui=stream"];
104
+ const started=Date.now();let failure;
105
+ try { await checkCommand(turboBinary(),args,directory,signal,undefined,{category:"architecture",phase:"ads-check"},60000,
106
+ {ADS_TASK_ROOT:root,ADS_TASK_TRACKING_ROOT:trackingRoot,ADS_TASK_TOOL:toolRoot,ADS_TASK_KEY:key,TURBO_TELEMETRY_DISABLED:"1"}); }
107
+ catch(error){failure=error;}
108
+ if(signal?.aborted)throw failure??Object.assign(new Error("Mutation cancelled during validation."),{diagnostic:{rule:"mutation-cancelled",message:"Mutation cancelled during validation."}});
109
+ if(hash(JSON.stringify(architectureTaskInputs(root,trackingRoot)))!==key)throw Object.assign(new Error("Source, dependencies or Git tracking changed during the ADS task; retry against the current inputs."),{code:"ADS_SOURCE_CHANGED"});
110
+ const report=path.join(directory,"out/report.json");
111
+ if(!existsSync(report))throw failure??new Error("ADS task did not produce an architecture report.");
112
+ if(statSync(report).size>16*1024*1024)throw new Error("Architecture report exceeds 16 MiB.");
113
+ const result=JSON.parse(readFileSync(report,"utf8"));
114
+ // Failing source guards return actionable diagnostics but never a cacheable
115
+ // successful task. Infrastructure failures cannot masquerade as source errors.
116
+ if(failure && result.ok!==false)throw failure;
117
+ let hit=false;
118
+ const summaries=path.join(directory,".turbo/runs");
119
+ if(existsSync(summaries))for(const file of readdirSync(summaries).filter(name=>name.endsWith(".json"))){const summary=JSON.parse(readFileSync(path.join(summaries,file),"utf8"));hit=summary.tasks?.some(task=>task.cache?.status==="HIT")??false;}
120
+ try{collect(settings.directory);}catch{/* Cache maintenance never changes gate results. */}
121
+ return {...result,cache:{backend:"turbo",task:"architecture",key,status:!settings.enabled?"disabled":fresh?"fresh":hit?"hit":"miss",...(settings.reason?{reason:settings.reason}:{}),elapsedMs:Date.now()-started}};
122
+ }
@@ -0,0 +1,19 @@
1
+ import { mkdirSync, readFileSync, writeFileSync } from "node:fs";
2
+ import { createHash } from "node:crypto";
3
+ import path from "node:path";
4
+ import { pathToFileURL } from "node:url";
5
+
6
+ // Copied to an isolated Turbo task workspace. Physical source/tool locations are
7
+ // passed at execution time, not embedded into portable cached task inputs.
8
+ const {ADS_TASK_ROOT:root,ADS_TASK_TRACKING_ROOT:trackingRoot,ADS_TASK_TOOL:tool,ADS_TASK_KEY:key}=process.env;
9
+ if(!root || !trackingRoot || !tool || !key)throw new Error("Missing ADS task execution context.");
10
+ const {architectureTaskInputs}=await import(pathToFileURL(path.join(tool,"task-cache.mjs")));
11
+ const current=()=>createHash("sha256").update(JSON.stringify(architectureTaskInputs(root,trackingRoot))).digest("hex");
12
+ if(current()!==key)throw new Error("ADS task inputs changed before execution.");
13
+ const {checkProject}=await import(pathToFileURL(path.join(tool,"check.mjs")));
14
+ const result=checkProject(root,{trackingRoot});
15
+ if(current()!==key)throw new Error("ADS task inputs changed during execution.");
16
+ // The descriptor is part of Turbo's key; also reject an inconsistent caller.
17
+ if(createHash("sha256").update(readFileSync("inputs.json")).digest("hex")!==key)throw new Error("ADS task input descriptor mismatch.");
18
+ mkdirSync("out",{recursive:true});writeFileSync("out/report.json",JSON.stringify(result));
19
+ if(!result.ok)process.exitCode=1;
@@ -1,5 +1,6 @@
1
+ import { executionContext, finishExecutionGuard, trackExecutionChild, trackExecutionWorkspace } from "./mcp/execution-context.mjs";
1
2
  import { spawn } from "node:child_process";
2
- import { mkdtempSync, readFileSync, rmSync, statSync } from "node:fs";
3
+ import { mkdtempSync, readFileSync, rmSync } from "node:fs";
3
4
  import { tmpdir } from "node:os";
4
5
  import { fileURLToPath } from "node:url";
5
6
  import path from "node:path";
@@ -8,21 +9,20 @@ import { packageScriptCommand } from "./development-runtime.mjs";
8
9
  import { failure as evidenceFailure } from "./evidence.mjs";
9
10
  const fail = (rule, message, file, failure) => Object.assign(new Error(message), { diagnostic: {rule, message, ...(file ? {file} : {}), ...(failure ? {failure} : {})} });
10
11
 
11
- export async function checkCandidate(root, signal, trackingRoot = root) {
12
+ export async function checkCandidate(root, signal, trackingRoot = root, options = {}) {
12
13
  const directory = mkdtempSync(path.join(tmpdir(), "ads-architecture-"));
13
- const report = path.join(directory, "report.json");
14
+ trackExecutionWorkspace(directory);
14
15
  try {
15
- await checkCommand(process.execPath, [fileURLToPath(new URL("./check-runner.mjs", import.meta.url)), root, report, trackingRoot], root, signal, undefined, {category:"architecture",phase:"ads-check"});
16
- if (statSync(report).size > 16 * 1024 * 1024) throw new Error("Architecture report exceeds 16 MiB.");
17
- return JSON.parse(readFileSync(report, "utf8"));
16
+ const {runArchitectureTask}=await import("./task-cache.mjs");
17
+ return await runArchitectureTask(root,trackingRoot,directory,signal,{fresh:executionContext.getStore()?.fresh,...options});
18
18
  } finally { rmSync(directory, { recursive:true, force:true }); }
19
19
  }
20
20
 
21
- export function checkCommand(command, args, cwd, signal, input, gate = {category:"architecture",phase:"patch-preparation"}, timeoutMs = 60000) {
21
+ export function checkCommand(command, args, cwd, signal, input, gate = {category:"architecture",phase:"patch-preparation"}, timeoutMs = 60000, environment = {}) {
22
22
  return new Promise((resolve, reject) => {
23
23
  if (signal?.aborted) { reject(fail("mutation-cancelled", "Mutation cancelled before validation.",undefined,evidenceFailure("runner","mutation-execution","ADS_CANCELLED"))); return; }
24
24
  const child = spawn(command, args, { cwd, shell: false, detached: process.platform !== "win32", windowsHide: true, stdio: [input === undefined ? "ignore" : "pipe", "pipe", "pipe"],
25
- env: { ...process.env, PATH: [path.join(cwd, "node_modules/.bin"), path.dirname(process.execPath), process.env.PATH ?? ""].join(path.delimiter) } });
25
+ env: { ...process.env, ...environment, PATH: [path.join(cwd, "node_modules/.bin"), path.dirname(process.execPath), process.env.PATH ?? ""].join(path.delimiter) } });
26
26
  let output = "", failure, guard, done = false;
27
27
  const startedAt=Date.now();
28
28
  if (input !== undefined) { child.stdin.on("error", () => {}); child.stdin.end(input); }
@@ -33,6 +33,7 @@ export function checkCommand(command, args, cwd, signal, input, gate = {category
33
33
  stop.on("error", () => child.kill("SIGKILL"));
34
34
  } else { try { process.kill(-child.pid, "SIGKILL"); } catch (error) { if (error.code !== "ESRCH") failure ??= error; } }
35
35
  }
36
+ trackExecutionChild(child);
36
37
  if (child.pid) {
37
38
  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});
38
39
  guard.stdin.on("error",()=>{});
@@ -45,9 +46,10 @@ export function checkCommand(command, args, cwd, signal, input, gate = {category
45
46
  for (const stream of [child.stdout, child.stderr]) stream.on("data", chunk => { output = (output + chunk.toString()).slice(-12000); });
46
47
  child.once("error", error => { failure = error; });
47
48
  child.once("exit", kill); // Also clean up descendants of a finished launcher.
48
- child.once("close", code => {
49
- done = true; guard?.stdin.end("cleanup\n");
49
+ child.once("close", async code => {
50
+ done = true;
50
51
  clearTimeout(timer); signal?.removeEventListener("abort", abort);
52
+ try{await finishExecutionGuard(guard);}catch(error){failure??=error;}
51
53
  const detail={command:path.basename(command),args,timeoutMs,elapsedMs:Date.now()-startedAt,exitCode:code};
52
54
  if (failure || code !== 0) {
53
55
  const error=failure??fail("mutation-check", `${path.basename(command)} ${args.join(" ")} failed (${code}).\n${output}`);
@@ -1,3 +1,4 @@
1
+ import { executionContext } from "./mcp/execution-context.mjs";
1
2
  import { createHash, randomUUID } from "node:crypto";
2
3
  import { existsSync, lstatSync, mkdirSync, readFileSync, readdirSync, realpathSync, renameSync, rmSync, writeFileSync } from "node:fs";
3
4
  import path from "node:path";
@@ -38,7 +39,7 @@ export function createValidationController(directory, { previewWork } = {}) {
38
39
  return {
39
40
  status() { return { busy: !!active, ...(progress ? {progress} : {}) }; },
40
41
  async close() { const pending = active; pending?.abort(); await pending?.completion; },
41
- async run({scope = "all", policy = "validation"} = {}, signal, onProgress) {
42
+ async run({scope = "all", policy = "validation", fresh = false} = {}, signal, onProgress) {
42
43
  if (!["all","changed"].includes(scope)) throw new Error("Validation scope must be all or changed.");
43
44
  if (!["acceptance","validation"].includes(policy)) throw new Error("Policy must be acceptance or validation.");
44
45
  if (active) throw new Error("Validation is already running.");
@@ -74,15 +75,17 @@ export function createValidationController(directory, { previewWork } = {}) {
74
75
  }
75
76
  if (fallback) scope = "all";
76
77
  }
78
+ onProgress?.({stage:"selection",scope,requestedScope,units,elapsedMs:Date.now()-startedAt});
77
79
  stage("architecture");
78
- const core = await checkCandidate(root, signal);
80
+ const core = await checkCandidate(root, signal, root, {fresh});
79
81
  diagnostics.push(...core.diagnostics); advisories.push(...(core.advisories ?? []));
80
- checks.push({name:"architecture",passed:core.ok});
82
+ checks.push({name:"architecture",passed:core.ok,cache:core.cache});
81
83
  if (!core.ok) return complete();
82
84
  const scripts = projectChecks(options,policy);
83
85
  for (const launch of scripts) await command(`project:${launch.args.at(-1)}`,launch,options);
84
86
  const behaviors = inspectBehaviors(options);
85
87
  units = options.config[policy].behaviorChecks ? (scope === "all" ? behaviors.contracts.map(contract=>contract.unit) : affectedBehaviorUnits(options,changed)) : [];
88
+ onProgress?.({stage:"selection",scope,requestedScope,units,elapsedMs:Date.now()-startedAt});
86
89
  const requirePreviews=policy === "validation" || units.length>0;
87
90
  if (requirePreviews && options.config.mcp.previewManifest && options.config.mcp.previewWatch) {
88
91
  stage("preview-build");
@@ -128,9 +131,12 @@ export function createValidationController(directory, { previewWork } = {}) {
128
131
  let ok = current && !signal.aborted && !diagnostics.length && checks.every(check=>check.skipped || check.passed);
129
132
  if (ok && scope === "all") {
130
133
  const file = outputFile(root,`${policy}-baseline.json`), temporary = `${file}.${randomUUID()}.tmp`;
131
- try { writeFileSync(temporary,JSON.stringify({schemaVersion:1,root,toolRevision,...inputs})); renameSync(temporary,file); }
134
+ const publish=()=>{
135
+ try { writeFileSync(temporary,JSON.stringify({schemaVersion:1,root,toolRevision,...inputs})); renameSync(temporary,file); }
136
+ finally { rmSync(temporary,{force:true}); }
137
+ };
138
+ try { const execution=executionContext.getStore();if(execution)execution.commits.push({file,value:{schemaVersion:1,root,toolRevision,...inputs}});else publish(); }
132
139
  catch (error) { ok=false;diagnostics.push({rule:"validation-baseline",message:error.message}); }
133
- finally { rmSync(temporary,{force:true}); }
134
140
  }
135
141
  return {ok,policy,scope,requestedScope,...(fallback?{fallback}:{}),sourceRevision:inputs?.revision,current,elapsedMs:Date.now()-startedAt,selection:{files:changed,units},checks,diagnostics,advisories,results,
136
142
  acceptance:acceptance(policy === "acceptance" ? "project-acceptance-policy" : scope === "all" ? "full-project-validation" : "affected-project-validation",ok,checks.filter(check=>check.passed&&!check.skipped).map(check=>check.name),["unconfigured-project-checks","unasserted-behavior","visual-parity","accessibility-audit"])};
@@ -1,3 +1,4 @@
1
+ import { finishExecutionGuard, trackExecutionArtifact, trackExecutionChild } from "./mcp/execution-context.mjs";
1
2
  import { createHash, randomUUID } from "node:crypto";
2
3
  import { spawn } from "node:child_process";
3
4
  import { existsSync, lstatSync, mkdirSync, readFileSync, realpathSync, renameSync, rmSync, writeFileSync } from "node:fs";
@@ -184,8 +185,9 @@ export function executeDevelopmentCommand(profile, args, root, env, signal) {
184
185
  };
185
186
  child = spawn(developmentExecutable(profile.command), args, { cwd: root, detached: process.platform !== "win32", shell: false, stdio: ["ignore", "pipe", "pipe"], windowsHide: true,
186
187
  env: { ...process.env, ...env, PATH: [path.join(root, "node_modules/.bin"), path.dirname(process.execPath), process.env.PATH ?? ""].join(path.delimiter) } });
188
+ trackExecutionChild(child);
187
189
  if (child.pid) {
188
- guard = spawn(process.execPath, [fileURLToPath(new URL("./mcp/preview-owner-guard.mjs", import.meta.url)), String(child.pid)], { detached: process.platform !== "win32", stdio: ["pipe", "ignore", "ignore"], windowsHide: true });
190
+ guard = spawn(process.execPath, [fileURLToPath(new URL("./mcp/preview-owner-guard.mjs", import.meta.url)), String(child.pid), "--tree"], { detached: process.platform !== "win32", stdio: ["pipe", "ignore", "ignore"], windowsHide: true });
189
191
  guard.stdin.on("error", () => {});
190
192
  guard.once("error", error => { failure = error; kill(); });
191
193
  guard.once("exit", () => { if (!done) { failure ??= new Error("Verification ownership guard exited unexpectedly."); kill(); } });
@@ -196,8 +198,9 @@ export function executeDevelopmentCommand(profile, args, root, env, signal) {
196
198
  for (const stream of [child.stdout, child.stderr]) stream.on("data", chunk => { output = (output + chunk.toString()).slice(-12000); });
197
199
  child.once("error", error => { failure = error; });
198
200
  child.once("exit", kill);
199
- child.once("close", code => {
200
- done = true; kill(); guard?.stdin.end("disarm\n"); clearTimeout(timeout); signal.removeEventListener("abort", abort);
201
+ child.once("close", async code => {
202
+ done = true; kill(); clearTimeout(timeout); signal.removeEventListener("abort", abort);
203
+ try{await finishExecutionGuard(guard);}catch(error){failure??=error;}
201
204
  const elapsedMs = Date.now() - startedAt;
202
205
  if (failure) reject(Object.assign(failure, { output, elapsedMs }));
203
206
  else resolve({ code, output, elapsedMs });
@@ -253,6 +256,7 @@ export function createVerificationController(root, { reportRoot = root, onProgre
253
256
  const group = selection.filter(check => check.profile === profileName);
254
257
  const directory = path.join(reportRoot, ".ds/verification", randomUUID());
255
258
  mkdirSync(directory, { recursive: true });
259
+ trackExecutionArtifact(reportRoot,directory);
256
260
  if (realpathSync(directory) !== directory) throw new Error("Verification output cannot resolve through a symlink.");
257
261
  const runId = randomUUID(), report = path.join(directory, "report.json"), request = path.join(directory, "request.json");
258
262
  const scenarios = {};
@@ -729,6 +729,17 @@ and behavior contracts. Full audits establish a content baseline. Changed audits
729
729
  select affected behavior owners from that baseline; broad or unclassified changes
730
730
  expand to full. Opaque project commands retain their declared scope.
731
731
 
732
+ MCP executions share a process-wide exclusive lease spanning checks, guarded
733
+ mutations, child cleanup and durable result publication. Conflicting requests get
734
+ a structured `ADS_VALIDATION_LOCKED` response; Explorer and preview serving keep
735
+ their independent lane. Relevant source edits abort working-tree runs early,
736
+ recording changed paths and known/unknown attribution. Source-change interruption
737
+ cannot publish a successful baseline. A small run journal supports crash recovery;
738
+ immutable run results and exact-run investigations survive reconnects and subsequent
739
+ runs under bounded age/count/disk retention. Collection protects active work and
740
+ expires owned evidence with its result. See [execution coordination](MCP.md#shared-process-execution-coordination)
741
+ and the [implementation plan](plans/execution-coordination.md).
742
+
732
743
  Only a successful full audit against unchanged source advances the baseline.
733
744
  This works without Git history and does not cache individual test results. Skills
734
745
  guide agents toward affected checks during editing and full audits after ownership
@@ -789,6 +800,15 @@ for 100,000 files / 2 GiB. Unrelated native artifacts are not copied. Declared e
789
800
  inputs support project commands that read data outside the UI graph. When
790
801
  `acceptance.behaviorChecks` is true, affected registered behavior checks, including
791
802
  consumers of a changed shared controller, run in the isolated candidate project.
803
+ Architecture batch checks use the internal pinned Turbo runner and its installed
804
+ platform binary; no global Turbo or runtime dependency installer is invoked. Local artifact
805
+ reuse is enabled by default and fenced by current input/tool/runtime/Git state;
806
+ policy results, browser evidence, locks and baselines are never task outputs.
807
+ Project scripts remain uncached without a known deterministic contract. The warm
808
+ Bun preview compiler retains its module cache; complete verified graph restoration
809
+ publishes fresh build-session evidence without semantic rediscovery. See
810
+ [cache controls and CI wiring](CACHING.md).
811
+
792
812
  `acceptance.checks` and `validation.checks` explicitly select project scripts; no
793
813
  names are inferred. Validation selects its own `behaviorChecks` flag. Direct
794
814
  edits can invoke `ads validate --policy acceptance`; separate baselines prevent
@@ -817,9 +837,9 @@ bounded acceptance, at most three failure previews and a result ID in at most
817
837
  sections without rerunning checks. Pages have at most 20 rows and 8 KiB of JSON;
818
838
  truncated records support bounded text ranges. Discovery and investigation
819
839
  sections use the same paging budget. Cursors bind the query and result/revision;
820
- superseded IDs fail explicitly instead of silently returning another run.
821
- Only the latest validation, verification and mutation snapshots are retained, each at most
822
- 8 MiB under `.ds/tool-results/`. Oversized reports retain a summary with an
840
+ expired IDs fail explicitly instead of silently returning another run.
841
+ Immutable run snapshots persist under `.ds/tool-results/`, each at most 8 MiB,
842
+ with configurable age/count/disk retention and associated evidence collection. Oversized reports retain a summary with an
823
843
  explicit unavailable-details warning. Storage/notification failure cannot change
824
844
  an accepted edit's applied state. These are payload byte budgets, not tokenizer
825
845
  estimates; MCP compatibility text may duplicate structured JSON on the wire.
@@ -0,0 +1,99 @@
1
+ # Batch task caching
2
+
3
+ ADS uses its pinned Turborepo dependency internally for architecture batch tasks.
4
+ Projects do not install Turbo, create `turbo.json`, or choose between backends.
5
+ Local caching is enabled out of the box for `ads check` and the source-check
6
+ stages of validation, acceptance, guarded mutations and preview compilation.
7
+ The synchronous exported `checkProject` function remains the analysis primitive;
8
+ the CLI and managed execution paths use the internal task runner. ADS invokes
9
+ the already-installed platform binary directly. It never runs Turbo's automatic
10
+ repair installer; a missing binary reports `ADS_TASK_RUNTIME_MISSING` and asks
11
+ for dependency reinstallation with optional platform packages enabled.
12
+
13
+ Keys include relevant ADS/application source, local dependency inputs,
14
+ configuration, lockfiles, declared installed package manifests, Git tracking,
15
+ ADS implementation and runtime/platform, and the check's semantic environment.
16
+ Inputs are fenced around execution and when a hit is consumed. Install from the
17
+ lockfile; request a fresh check after manually modifying installed package
18
+ contents without changing a lockfile.
19
+
20
+ Only successful deterministic source reports are cached. Project policy scripts
21
+ and registered browser/behavior checks still execute according to their policy;
22
+ ADS cannot infer cache contracts for arbitrary scripts. A hit never restores a
23
+ successful acceptance, baseline, run ID, lock or live build status. Each policy
24
+ invocation establishes its own freshness and result. The existing coordinator
25
+ retains execution ownership, cancellation and cleanup.
26
+
27
+ ## Controls
28
+
29
+ | Control | Behavior |
30
+ | --- | --- |
31
+ | Default | Local `.ds/task-cache`; remote cache disabled |
32
+ | `ads check --fresh`, `ads validate --fresh` | Bypass task-cache reads; refresh successful cached outputs |
33
+ | MCP `ads_check`, `ads_validate`, `ads_accept`: `fresh:true` | Same override for the operation's source checks |
34
+ | `ADS_CACHE=off` | Disable task-cache reads/writes; keep the same runner |
35
+ | `ADS_CACHE_DIR=/absolute/path` | Relocate or share the local artifact store |
36
+ | `ADS_REMOTE_CACHE=1` | Opt into remote caching with standard Turbo provider settings |
37
+
38
+ Read-only projects and unwritable/full cache stores run through the same Turbo
39
+ runner uncached in an isolated temporary workspace, reporting the fallback reason.
40
+ `ADS_CACHE=off` also avoids creating a project cache directory.
41
+
42
+ Fresh concerns batch task reuse; it does not force unchanged Bun modules to
43
+ recompile or change the selected test policy. `ads_status.taskCache` reports
44
+ settings. Source reports include key, hit/miss/fresh/disabled status and elapsed
45
+ time. Execution replies include compact cache status; `ads_results` check records
46
+ retain details.
47
+
48
+ Collection targets 256 MiB and seven days, pruning old archives while protecting
49
+ files written within the last minute. Concurrent activity can temporarily exceed
50
+ the target. Isolated temporary workspaces are removed on completion or recovery.
51
+ Only immutable archives share storage; live outputs and evidence stay isolated.
52
+
53
+ ## Preview restoration
54
+
55
+ The interactive Bun compiler keeps its incremental module/graph cache. Turbo is
56
+ not launched on every edit. ADS reopens a matching complete graph without semantic
57
+ scenario discovery or compiler startup: check cached registry/dependencies, verify
58
+ immutable assets, match the successful guard evidence already attached to the
59
+ graph against current source/tool/runtime/Git/dependency state, fence inputs, and
60
+ publish new session metadata. This native handoff does not invoke Turbo again. Missing, changed or corrupt artifacts fall back to compiling.
61
+ Guard failures remain failures. Old live build evidence is never restored.
62
+
63
+ ## CI wiring
64
+
65
+ Use the existing CLI and persist the artifact directory. No additional ADS cache
66
+ server, network API or MCP endpoint is needed. For example, after installing the
67
+ project's dependencies and supported Bun:
68
+
69
+ ```yaml
70
+ - uses: actions/cache@v4
71
+ with:
72
+ path: explorer/.ds/task-cache
73
+ key: ads-${{ runner.os }}-${{ runner.arch }}-${{ github.sha }}
74
+ restore-keys: |
75
+ ads-${{ runner.os }}-${{ runner.arch }}-
76
+ - run: bunx --no-install ads validate . --json
77
+ working-directory: explorer
78
+ ```
79
+
80
+ Change `explorer/` to the project directory. ADS task keys determine input matches;
81
+ the outer archive key only finds candidate artifacts. Cache this directory,
82
+ not the entire `.ds` directory and its run-specific state. Alternatively set
83
+ `ADS_REMOTE_CACHE=1` with the provider's `TURBO_TOKEN`, `TURBO_TEAM` and optionally
84
+ `TURBO_API`. Managed or self-hosted storage is a project choice. Tasks execute on
85
+ the caller's machine or CI runner on a miss.
86
+
87
+ See [measurements and proofs](benchmarks/turbo-poc.md), Turbo's
88
+ [GitHub Actions guide](https://turborepo.dev/docs/guides/ci-vendors/github-actions)
89
+ and [cache controls](https://turborepo.dev/docs/reference/run#--cache-options).
90
+
91
+ ## Hermit-managed projects
92
+
93
+ Turbo is a normal dependency of the ADS tool package, which a project installs as
94
+ `@reqvire-org/ads` in `devDependencies`. Hermit should pin Bun >=1.4.1 for ADS;
95
+ it should not install a second global Turbo executable or manage a project
96
+ `turbo.json`. Keep the project's other Rust/native/Node tools as its build requires.
97
+ This ADS repository and the local shadcn example have no Hermit environment.
98
+ Reqvire pins Bun 1.4.2. Neezler's native-client Hermit environment also supplies
99
+ Bun 1.4.2 for the root ADS/frontend commands invoked by its Makefile.
package/docs/CHANGELOG.md CHANGED
@@ -1,34 +1,60 @@
1
1
  # Changelog
2
2
 
3
- ## 0.3.40
3
+ ## 0.3.42
4
4
 
5
5
  <!-- ads-local-tests:start -->
6
- Local verification: **602/602 passed** with `ADS_TEST_BUN=1 npm test`.
7
- Tested commit: `eb5d277c1f5198d54318ca0a3fa836e1eb7ee2a3`; Node v24.13.0, Bun 1.4.1.
8
- Completed 2026-10-24T18:24:27.888Z (829 seconds).
6
+ Local verification: **624/624 passed** with `ADS_TEST_BUN=1 npm test`.
7
+ Tested commit: `b85bcac055ff420b612b94961b177377c5f0dd16`; Node v24.13.0, Bun 1.4.1.
8
+ Completed 2026-10-26T17:07:50.019Z (754 seconds).
9
9
 
10
10
  <!-- ads-local-test-proof
11
11
  {
12
12
  "schema": 1,
13
- "version": "0.3.40",
14
- "commit": "eb5d277c1f5198d54318ca0a3fa836e1eb7ee2a3",
15
- "sourceSha256": "597fe2f9983e64fac21e3d4584e5bae7068a24fde7f00bde9a57c89ea41fa597",
13
+ "version": "0.3.42",
14
+ "commit": "b85bcac055ff420b612b94961b177377c5f0dd16",
15
+ "sourceSha256": "a3ac8b5ef580cb6793968b91c6a68a33f286194e39ab7def682b4642a71cde74",
16
16
  "command": "ADS_TEST_BUN=1 npm test",
17
17
  "result": "pass",
18
- "tests": 602,
19
- "pass": 602,
18
+ "tests": 624,
19
+ "pass": 624,
20
20
  "fail": 0,
21
21
  "cancelled": 0,
22
22
  "skipped": 0,
23
23
  "node": "v24.13.0",
24
24
  "bun": "1.4.1",
25
- "completedAt": "2026-10-24T18:24:27.888Z",
26
- "durationMs": 829113,
27
- "logSha256": "810783acb0791a199a1e773d8da6779ed537f8a632971b851da40446ebe6fd97"
25
+ "completedAt": "2026-10-26T17:07:50.019Z",
26
+ "durationMs": 754350,
27
+ "logSha256": "18afde78bb91bacea61cc80ff8e15cd49b66f775a2f3998c91cf3b1522388600"
28
28
  }
29
29
  -->
30
30
  <!-- ads-local-tests:end -->
31
31
 
32
+ - Use pinned internal Turbo for deterministic architecture batch tasks, with
33
+ local caching enabled by default, fresh/off/shared-directory controls and
34
+ opt-in remote caching. Preserve policy script/test execution, source fences,
35
+ process ownership, cancellation and fresh run evidence. Report cache provenance.
36
+ - Keep read-only source inspection available: disabled or unavailable cache storage
37
+ runs uncached in a temporary workspace through the same runner. Invoke only the
38
+ installed Turbo platform binary; managed operations never run its repair installer.
39
+ - Restore complete verified preview graphs without repeating semantic scenario
40
+ discovery or starting a compiler; publish fresh live-session evidence. Document
41
+ CI cache wiring and keep the interactive Bun compiler's incremental graph.
42
+
43
+ ## 0.3.41
44
+
45
+ - Coordinate validation, verification, draft acceptance and guarded edits across all
46
+ clients of one ADS process. Return structured lock/holder/progress responses;
47
+ keep Explorer and preview serving available.
48
+ - Abort working-tree checks early on relevant source edits and report changed
49
+ paths and observed attribution without advancing acceptance baselines.
50
+ - Retain immutable run results and exact-run investigation evidence across other
51
+ executions, reconnects and restarts. Journal interrupted runs and finish runner
52
+ ownership cleanup before releasing the execution lease.
53
+ - Add configurable age/count/disk retention with protected active runs and explicit
54
+ expiry errors. Update portable skills and shared-server workflow guidance.
55
+
56
+ ## 0.3.40
57
+
32
58
  - Fix immutable preview resource collisions when a compiler keeps dependency
33
59
  filenames stable. Resource identities include transitive dependencies, with
34
60
  cycle-aware hashing; unrelated preview branches retain their cached identities.
package/docs/MCP.md CHANGED
@@ -495,16 +495,16 @@ the latest IDs. Status embeds summaries, not complete runner reports. Saved
495
495
  outcomes are completion-time evidence; compare revisions with `ads_behaviors`
496
496
  before claiming current source passed.
497
497
 
498
- Only the latest verification snapshot and latest mutation snapshot are retained,
499
- independently, each up to 8 MiB in `.ds/tool-results/`. Replacing a snapshot makes
500
- its old ID unavailable; do not mix pages across runs. An oversized report retains
501
- only its summary and an explicit unavailable-details warning. A failed disk write
502
- keeps details in server memory until shutdown. Neither condition changes guard
503
- acceptance or whether source was applied. These are logical payload byte limits;
504
- compatibility text can duplicate structured JSON in the MCP response.
498
+ Execution snapshots are immutable by run/result ID. They survive other clients'
499
+ runs, reconnects and ADS restarts within `mcp.resultRetention`: by default 50 runs,
500
+ seven days and 256 MiB of result/evidence data. Each snapshot is limited to 8 MiB;
501
+ oversized reports retain a summary with an explicit warning. Storage failure keeps
502
+ latest details in memory with a warning. `ADS_RESULT_EXPIRED` identifies recently
503
+ collected results; the expiry tombstone index is bounded to 4096 IDs. Older unknown
504
+ IDs are unavailable. These limits do not change actual acceptance/applied state.
505
505
 
506
506
  For diagnosis, take one outcome's exact `unit`, `check` and `runId` and call
507
- `ads_investigate`. The run ID rejects superseded evidence. Without a check, it
507
+ `ads_investigate`. The exact run ID selects retained evidence from that execution. Without a check, it
508
508
  lists available investigations with paging. An exact check returns a summary
509
509
  within 4096 JSON bytes; `section: "details"`, `"requests"`, `"browserErrors"` or `"artifacts"`
510
510
  returns detail pages with the same 10/20-row and 8192-byte limits. Truncated records support
@@ -515,7 +515,7 @@ artifacts. Exact input/observed preview revisions, source/failing step, startup
515
515
  viewport and failed requests separate evidence from a suspected cause.
516
516
  The summary's `details.failure.category` distinguishes architecture, build,
517
517
  transport, runner and assertion boundaries; `acceptance` names established and unverified scope.
518
- Only the latest bundle per check remains resource-accessible. Read the portable
518
+ Latest-check listings are convenience indexes; exact retained run IDs and their registered artifacts remain resource-accessible. Read the portable
519
519
  [evidence guide](../skills/ads-designer/references/evidence.md) for collection
520
520
  limits and project-controlled trace/screenshot recording.
521
521
 
@@ -1443,3 +1443,48 @@ so later creation invalidates evidence. Dependencies, metadata and generated out
1443
1443
  are not source inputs. The setting defaults to an empty list and accepts up to 200
1444
1444
  unique canonical paths below the project root. Declare data read dynamically by
1445
1445
  selected commands; ADS cannot infer arbitrary filesystem access inside a command.
1446
+
1447
+ ## Shared-process execution coordination
1448
+
1449
+ One ADS process has an exclusive execution lease shared by its HTTP and stdio
1450
+ clients. `ads_validate` (both policies/scopes), `ads_verify`, `ads_accept`,
1451
+ `ads_apply_patch` and `ads_apply_transaction` acquire it before work and retain it
1452
+ through child/ownership-guard cleanup and result publication. Changed scope still
1453
+ runs full project scripts. Parallel units and `wait: true` are not supported.
1454
+
1455
+ A conflicting call is a tool error with `code: "ADS_VALIDATION_LOCKED"` and `lock`:
1456
+ run ID, instance ID, operation, owner/client label where known, policy, requested
1457
+ and effective scope, units, start time, progress and nullable estimated remaining
1458
+ milliseconds. Client labels (including optional request `_meta["ads/clientId"]`)
1459
+ are advisory metadata, not authentication. Stateless HTTP requests do not define
1460
+ persistent client sessions. The run ID is the result ID; any connected project
1461
+ client can read retained evidence by ID after reconnecting.
1462
+
1463
+ `ads_status.execution` exposes the lock, server instance and retention state.
1464
+ Status resource subscriptions receive acquisition, progress, stopping and release
1465
+ updates. Read-only discovery, Explorer and preview delivery stay available.
1466
+ Accepted-source writes from every client, including the holder, contend for the
1467
+ same lease. Draft creation/editing affects separate proposals and remains usable.
1468
+
1469
+ Relevant source changes during working-tree validation/verification initiate early
1470
+ shutdown with `ADS_SOURCE_CHANGED_DURING_RUN`. Results name changed paths,
1471
+ added/modified/deleted classification and observed attribution; external editors
1472
+ have unknown authorship. While stopping, contention responses include these details.
1473
+ Generated outputs are excluded. Completed observations remain inspectable, and a
1474
+ stopped run cannot establish acceptance or publish a full-policy baseline. Guarded
1475
+ candidate edits retain their existing source-conflict checks before publication.
1476
+
1477
+ The durable journal under `.ds/execution-runs/` records work before it starts.
1478
+ Cancellation and request disconnect initiate cleanup and save a terminal result
1479
+ even when its response cannot be delivered. On restart, orphaned recorded process
1480
+ identities are checked before cleanup; PID reuse is not authority. Active work in
1481
+ another live process is not recovered. Unfinished abandoned runs become interrupted
1482
+ and never auto-resume. Existing EOF ownership guards also terminate child trees.
1483
+
1484
+ Collection runs at startup and after executions. Results, retained investigations
1485
+ and owned verification folders expire together; baselines are independent. Active
1486
+ runs and the just-returned result are protected (temporary over-budget state is
1487
+ reported). Abandoned known mutation workspaces are removed during recovery;
1488
+ unreferenced old verification folders are removed after the configured age.
1489
+ No cleanup is triggered solely by a client disconnect. Independent ADS processes
1490
+ on the same project are outside this process-local coordination guarantee.