@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
@@ -1,5 +1,5 @@
1
1
  import { randomUUID } from "node:crypto";
2
- import { lstatSync, mkdirSync, readFileSync, realpathSync, renameSync, rmSync, writeFileSync } from "node:fs";
2
+ import { existsSync, lstatSync, mkdirSync, readFileSync, readdirSync, realpathSync, renameSync, rmSync, writeFileSync } from "node:fs";
3
3
  import path from "node:path";
4
4
  import { compactAcceptance, compactRow, jsonBytes, resultBudgets, resultPage, resultRecord } from "./result-pages.mjs";
5
5
 
@@ -21,7 +21,7 @@ function outcome(item) {
21
21
  investigation: { unit:item.unit, check:item.check, runId:item.runId, resourceUri:investigation?.resourceUri } };
22
22
  }
23
23
 
24
- function snapshot(kind, raw) {
24
+ function snapshot(kind, raw, resultId = randomUUID()) {
25
25
  const outcomes = raw.results ?? raw.behavior?.results ?? (raw.checks ?? []).flatMap(check => check.results ?? []);
26
26
  const sections = {
27
27
  outcomes: outcomes.map(outcome),
@@ -30,13 +30,12 @@ function snapshot(kind, raw) {
30
30
  captures: raw.screenshots?.captures ?? [], selection: [{unit:raw.unit,units:raw.units,transaction:raw.transaction,...raw.selection}],
31
31
  acceptance: raw.acceptance ? [raw.acceptance] : [], investigation: raw.investigation ? [raw.investigation] : [],
32
32
  };
33
- const resultId = randomUUID();
34
33
  return { schemaVersion: 1, resultId, kind, createdAt: new Date().toISOString(), ok: !!raw.ok,
35
34
  ...(raw.applied !== undefined ? { applied: raw.applied } : {}), ...(raw.unit ? { unit: raw.unit } : {}),
36
35
  ...(raw.units ? { units: raw.units } : {}), ...(raw.transaction ? { transaction: true } : {}),
37
36
  ...(raw.draft ? {draft:raw.draft,draftRevision:raw.revision,draftEvent:raw.event?{id:raw.event.id,state:raw.event.state}:null,updatedDependents:raw.updatedDependents??[]} : {}),
38
37
  ...(kind === "validation" ? {policy:raw.policy,scope:raw.scope,requestedScope:raw.requestedScope,sourceRevision:raw.sourceRevision,current:raw.current,elapsedMs:raw.elapsedMs,...(raw.fallback?{fallback:raw.fallback}:{})} : {}),
39
- acceptance: raw.acceptance, investigation: raw.investigation,
38
+ acceptance: raw.acceptance, investigation: raw.investigation, execution:raw.execution,
40
39
  sections: Object.fromEntries(Object.entries(sections).map(([key, rows]) => [key, rows.map((row, recordIndex) => ({ recordIndex, ...(row && typeof row === "object" ? row : {message:row}) }))])),
41
40
  counts: { outcomes: count(outcomes), checks: count(sections.checks), diagnostics: sections.diagnostics.length,
42
41
  advisories: sections.advisories.length, warnings: sections.warnings.length, changes: sections.changes.length, captures: sections.captures.length },
@@ -52,7 +51,9 @@ function summary(value, storageWarning) {
52
51
  ...(units ? { units } : {}), ...(transaction ? { transaction } : {}), createdAt, counts, freshness:"recorded-at-completion",
53
52
  ...(value.draft?{draft:value.draft,draftRevision:value.draftRevision,draftEvent:value.draftEvent,updatedDependentCount:value.updatedDependents.length}:{}),
54
53
  acceptance: compactAcceptance(value.acceptance), failures: value.failurePreview ?? failureRows.slice(0, 3).map(item => compactRow({recordIndex:item.recordIndex,unit:item.unit,check:item.check,status:item.status,rule:item.rule,file:item.file,failure:item.failure,message:item.message},640)),
54
+ ...(value.sections.checks.some(item=>item.cache)?{taskCache:value.sections.checks.filter(item=>item.cache).map(item=>({task:item.cache.task,status:item.cache.status}))}:{}),
55
55
  failureCount: value.failureCount ?? failureRows.length, resourceUri,
56
+ ...(value.execution?{execution:compactRow(value.execution,1100)}:{}),
56
57
  next: value.detailsUnavailable ? null : { tool: "ads_results", arguments: { resultId, section, ...(section === "outcomes" && failedOutcomes.length ? { status: "not_passed" } : {}) } },
57
58
  ...((storageWarning ?? value.storageWarning) ? { storageWarning: storageWarning ?? value.storageWarning } : {}), byteLimit: resultBudgets.summary };
58
59
  if (jsonBytes(result) > resultBudgets.summary) {
@@ -70,60 +71,119 @@ function summary(value, storageWarning) {
70
71
  return result;
71
72
  }
72
73
 
73
- /** One immutable, replaceable snapshot per execution kind. No result history. */
74
- export function createExecutionResults(root) {
74
+ export const defaultResultRetention = {maxRuns:50,maxAgeDays:7,maxBytesMb:256};
75
+ /** Immutable run snapshots plus bounded latest indexes; no history lives in heap. */
76
+ export function createExecutionResults(root,{retention=()=>defaultResultRetention}={}) {
75
77
  root = path.resolve(root);
76
- const folder = path.join(root, ".ds/tool-results"), memory = new Map();
77
- function file(kind) { return path.join(folder, `${kind}.json`); }
78
+ const folder = path.join(root, ".ds/tool-results"), history=path.join(folder,"runs"),memory=new Map();
79
+ let collection={overBudget:false};
80
+ const settings=()=>({...defaultResultRetention,...(typeof retention==="function"?retention():retention)});
81
+ const file=kind=>path.join(folder,`${kind}.json`);
82
+ function readJson(target,limit=maxStoredBytes) {
83
+ try {const stat=lstatSync(target);if(realpathSync(target)!==target||!stat.isFile()||stat.nlink!==1||stat.size>limit)return undefined;return JSON.parse(readFileSync(target,"utf8"));}catch{return undefined;}
84
+ }
85
+ function atomic(target,value) {
86
+ let ancestor=path.dirname(target);
87
+ while(!existsSync(ancestor))ancestor=path.dirname(ancestor);
88
+ if(realpathSync(ancestor)!==ancestor)throw new Error("Result output cannot resolve through a symlink.");
89
+ mkdirSync(path.dirname(target),{recursive:true});
90
+ if(realpathSync(path.dirname(target))!==path.dirname(target))throw new Error("Result output cannot resolve through a symlink.");
91
+ const staged=`${target}.${randomUUID()}.tmp`;
92
+ try {writeFileSync(staged,JSON.stringify(value));renameSync(staged,target);}finally{rmSync(staged,{force:true});}
93
+ }
94
+ function entries(){
95
+ const rows=readJson(path.join(folder,"index.json"),4*1024*1024)?.entries;
96
+ return Array.isArray(rows)?rows.filter(row=>row&&uuid(row.resultId)&&kinds.includes(row.kind)&&Number.isFinite(Date.parse(row.createdAt))&&Number.isSafeInteger(row.bytes)&&row.bytes>=0).map(row=>({...row,owned:Array.isArray(row.owned)?row.owned.filter(file=>typeof file==="string"&&/^\.ds\/(?:verification|investigation-runs)\/[a-f0-9-]{36}(?:\.json)?$/.test(file)):[]})):[];
97
+ }
98
+ function valid(value){return value?.schemaVersion===1&&kinds.includes(value.kind)&&uuid(value.resultId)&&resultSections.every(section=>Array.isArray(value.sections?.[section]));}
78
99
  function read(kind) {
79
- const temporary = memory.get(kind);
80
- if (temporary?.memoryOnly) return temporary.value;
81
- const target = file(kind);
82
- try {
83
- if (realpathSync(target) !== target || !lstatSync(target).isFile() || lstatSync(target).nlink !== 1 || lstatSync(target).size > maxStoredBytes) return undefined;
84
- const value = JSON.parse(readFileSync(target, "utf8"));
85
- return value.schemaVersion === 1 && value.kind === kind && uuid(value.resultId) && resultSections.every(section => Array.isArray(value.sections?.[section])) ? value : undefined;
86
- } catch { return undefined; }
100
+ const pending=memory.get(kind);if(pending?.memoryOnly)return pending.value;
101
+ const value=readJson(file(kind));return valid(value)?value:undefined;
87
102
  }
88
103
  function find(resultId) {
89
- if (!uuid(resultId)) throw new Error("Use an exact resultId returned by an execution summary.");
90
- const value = kinds.map(read).find(value => value?.resultId === resultId);
91
- if (!value) throw new Error("Result is unavailable or superseded. Only the latest completed result of each kind is retained; discover its ID with ads_status.");
92
- return value;
104
+ if(!uuid(resultId))throw new Error("Use an exact resultId returned by an execution summary.");
105
+ const value=readJson(path.join(history,`${resultId}.json`))??kinds.map(read).find(value=>value?.resultId===resultId);
106
+ if(valid(value))return value;
107
+ if((readJson(path.join(folder,"expired.json"))?.ids??[]).includes(resultId))throw Object.assign(new Error("Execution result expired under this project's retention policy."),{code:"ADS_RESULT_EXPIRED"});
108
+ throw Object.assign(new Error("Execution result is unavailable. Use an exact retained run/result ID."),{code:"ADS_RESULT_UNAVAILABLE"});
109
+ }
110
+ function bytes(directory) {
111
+ try {const stat=lstatSync(directory);if(stat.isSymbolicLink())return 0;if(stat.isFile())return stat.size;if(!stat.isDirectory())return 0;return readdirSync(directory).reduce((n,name)=>n+bytes(path.join(directory,name)),0);}catch{return 0;}
112
+ }
113
+ function removeOwned(relative) {
114
+ if(typeof relative!=="string"||!/^\.ds\/(?:verification|investigation-runs)\/[a-f0-9-]{36}(?:\.json)?$/.test(relative))return;
115
+ const target=path.join(root,relative);
116
+ try {if(realpathSync(target)===target)rmSync(target,{recursive:true,force:true});}catch{/* Already collected. */}
93
117
  }
94
118
  return {
95
- save(kind, raw) {
96
- if (!kinds.includes(kind)) throw new Error("Unknown execution kind.");
97
- const value = snapshot(kind, raw);
98
- let content = JSON.stringify(value);
99
- if (Buffer.byteLength(content) > maxStoredBytes) {
100
- const preview=summary(value);
101
- value.failurePreview=preview.failures;value.failureCount=preview.failureCount;
102
- value.sections=Object.fromEntries(resultSections.map(section=>[section,[]]));
103
- value.acceptance=preview.acceptance;delete value.investigation;
104
- value.detailsUnavailable=true;
105
- value.storageWarning="Result details exceeded the 8 MiB retention limit. Only this summary is retained; execution and applied state above are unchanged.";
106
- content=JSON.stringify(value);
119
+ has(id){try{find(id);return true;}catch{return false;}},
120
+ save(kind,raw,{resultId=randomUUID()}={}) {
121
+ if(!kinds.includes(kind)||!uuid(resultId))throw new Error("Unknown execution kind or invalid result ID.");
122
+ if(this.has(resultId))throw new Error("Execution result IDs are immutable.");
123
+ const value=snapshot(kind,raw,resultId);
124
+ if(Buffer.byteLength(JSON.stringify(value))>maxStoredBytes){
125
+ const preview=summary(value);value.failurePreview=preview.failures;value.failureCount=preview.failureCount;
126
+ value.sections=Object.fromEntries(resultSections.map(section=>[section,[]]));value.acceptance=preview.acceptance;delete value.investigation;
127
+ value.detailsUnavailable=true;value.storageWarning="Result details exceeded the 8 MiB retention limit. Only this summary is retained; execution and applied state above are unchanged.";
107
128
  }
129
+ const outcomes=raw.results??raw.behavior?.results??(raw.checks??[]).flatMap(check=>check.results??[]);
130
+ const owned=[...new Set([...(raw.execution?.artifacts??[]).filter(file=>/^\.ds\/verification\/[a-f0-9-]{36}$/.test(file)),...outcomes.flatMap(row=>[...(uuid(row.runId)?[`.ds/investigation-runs/${row.runId}.json`]:[]),...(typeof row.report==="string"&&/^\.ds\/verification\/[a-f0-9-]{36}\//.test(row.report)?[row.report.split("/").slice(0,3).join("/")]:[])])])];
108
131
  let storageWarning;
109
- try {
110
- let ancestor=folder;
111
- while(true){try{lstatSync(ancestor);break;}catch(error){if(error.code!=="ENOENT")throw error;ancestor=path.dirname(ancestor);}}
112
- if(realpathSync(ancestor)!==ancestor)throw new Error("Result output cannot resolve through a symlink.");
113
- mkdirSync(folder, { recursive: true });
114
- if (realpathSync(folder) !== folder) throw new Error("Result output cannot resolve through a symlink.");
115
- const staged = `${file(kind)}.${randomUUID()}.tmp`;
116
- try { writeFileSync(staged, content); renameSync(staged, file(kind)); } finally { rmSync(staged, { force: true }); }
117
- memory.set(kind, { value, memoryOnly: false });
118
- } catch {
119
- memory.set(kind, { value: JSON.parse(content), memoryOnly: true });
120
- storageWarning = "Result details are available in this server's memory only; storage failed. Execution and applied state above are unchanged.";
132
+ try{
133
+ atomic(path.join(history,`${resultId}.json`),value);atomic(file(kind),value);
134
+ atomic(path.join(folder,"index.json"),{schemaVersion:1,entries:[...entries(),{resultId,kind,createdAt:value.createdAt,owned,bytes:Buffer.byteLength(JSON.stringify(value))}]});
135
+ memory.set(kind,{memoryOnly:false});
136
+ }catch{
137
+ memory.set(kind,{value,memoryOnly:true});storageWarning="Result details are available in this server's memory only; storage failed. Execution and applied state above are unchanged.";
138
+ }
139
+ return summary(value,storageWarning);
140
+ },
141
+ latest(kind){const value=read(kind);return value?summary(value,memory.get(kind)?.memoryOnly?"Result details are in server memory only.":undefined):null;},
142
+ retentionStatus(){return {...settings(),...collection};},
143
+ collect({protectedIds=[]}={}) {
144
+ if(existsSync(history)&&realpathSync(history)!==history)throw new Error("Result archive cannot resolve through a symlink.");
145
+ const policy=settings(),protectedSet=new Set(protectedIds),all=entries().reverse().sort((a,b)=>Number(protectedSet.has(b.resultId))-Number(protectedSet.has(a.resultId))||b.createdAt.localeCompare(a.createdAt));
146
+ const kept=[],removed=[];let used=0;
147
+ for(const entry of all){
148
+ const size=entry.bytes+(entry.owned??[]).reduce((n,item)=>n+bytes(path.join(root,item)),0);
149
+ const expired=Date.now()-Date.parse(entry.createdAt)>policy.maxAgeDays*86400000;
150
+ if(!protectedSet.has(entry.resultId)&&(expired||kept.length>=policy.maxRuns||used+size>policy.maxBytesMb*1024*1024)){removed.push(entry);continue;}
151
+ kept.push(entry);used+=size;
152
+ }
153
+ const retainedOwned=new Set(kept.flatMap(entry=>entry.owned??[]));
154
+ if(removed.length){
155
+ const expired=readJson(path.join(folder,"expired.json"))?.ids??[];
156
+ atomic(path.join(folder,"expired.json"),{ids:[...new Set([...expired,...removed.map(entry=>entry.resultId)])].slice(-4096)});
157
+ for(const entry of removed){
158
+ rmSync(path.join(history,`${entry.resultId}.json`),{force:true});
159
+ const journal=path.join(root,".ds/execution-runs",`${entry.resultId}.json`);
160
+ if(!protectedSet.has(entry.resultId)&&(!existsSync(journal)||realpathSync(journal)===journal))rmSync(journal,{force:true});
161
+ rmSync(path.join(root,".ds/execution-runs",`${entry.resultId}.baseline.json`),{force:true});
162
+ for(const owned of entry.owned??[])if(!retainedOwned.has(owned))removeOwned(owned);
163
+ if(read(entry.kind)?.resultId===entry.resultId){const next=kept.find(item=>item.kind===entry.kind);const value=next&&readJson(path.join(history,`${next.resultId}.json`));if(value)atomic(file(entry.kind),value);else rmSync(file(entry.kind),{force:true});}
164
+ }
165
+ const index=path.join(root,".ds/investigations.json"),investigations=readJson(index,2*1024*1024);
166
+ if(investigations?.bundles){
167
+ const expiredRuns=new Set(removed.flatMap(entry=>entry.owned??[]).filter(item=>item.startsWith(".ds/investigation-runs/")&&!retainedOwned.has(item)).map(item=>path.basename(item,".json")));
168
+ investigations.bundles=Object.fromEntries(Object.entries(investigations.bundles).filter(([,value])=>!expiredRuns.has(value.runId)));
169
+ atomic(index,investigations);
170
+ }
171
+ atomic(path.join(folder,"index.json"),{schemaVersion:1,entries:kept});
172
+ }
173
+ // Orphan reports from abandoned executions are collected only after the age
174
+ // window and while no run is active. Never inspect arbitrary temp folders.
175
+ if(!protectedIds.length){
176
+ const reports=path.join(root,".ds/verification");
177
+ if(existsSync(reports)&&realpathSync(reports)===reports)for(const name of readdirSync(reports)){
178
+ const rel=`.ds/verification/${name}`,target=path.join(root,rel);
179
+ if(uuid(name)&&!retainedOwned.has(rel)&&Date.now()-lstatSync(target).mtimeMs>policy.maxAgeDays*86400000)removeOwned(rel);
180
+ }
121
181
  }
122
- return summary(value, storageWarning);
182
+ collection={retainedRuns:kept.length,retainedBytes:used,overBudget:used>policy.maxBytesMb*1024*1024||kept.length>policy.maxRuns};
183
+ return collection;
123
184
  },
124
- latest(kind) { const value = read(kind); return value ? summary(value, memory.get(kind)?.memoryOnly ? "Result details are in server memory only." : undefined) : null; },
125
- index() { return { retention: "latest-per-kind", results: kinds.map(kind => this.latest(kind)).filter(Boolean).map(({resultId,kind,ok,applied,createdAt,counts,resourceUri})=>({resultId,kind,ok,applied,createdAt,counts,resourceUri})) }; },
126
- fingerprint() { return kinds.map(kind=>{if(memory.get(kind)?.memoryOnly)return memory.get(kind).value.resultId;try{const stat=lstatSync(file(kind));return `${kind}:${stat.mtimeMs}:${stat.size}`;}catch{return `${kind}:missing`;}}).join("\n"); },
185
+ index(){return {retention:"bounded-runs",...this.retentionStatus(),results:kinds.map(kind=>this.latest(kind)).filter(Boolean).map(({resultId,kind,ok,applied,createdAt,counts,resourceUri})=>({resultId,kind,ok,applied,createdAt,counts,resourceUri}))};},
186
+ fingerprint(){return [...kinds.map(kind=>read(kind)?.resultId??`${kind}:missing`),...entries().map(entry=>entry.resultId)].join("\n");},
127
187
  page({ resultId, section = "outcomes", status = "all", cursor, limit, recordIndex, offset, chars } = {}) {
128
188
  const value = find(resultId);
129
189
  if(value.detailsUnavailable)throw new Error("This result exceeded the 8 MiB retention limit; only its summary is available.");
@@ -1,3 +1,4 @@
1
+ import { trackExecutionWorkspace } from "./execution-context.mjs";
1
2
  import { createHash, randomUUID } from "node:crypto";
2
3
  import { cpSync, existsSync, lstatSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, realpathSync, renameSync, rmSync, symlinkSync, writeFileSync } from "node:fs";
3
4
  import path from "node:path";
@@ -199,6 +200,7 @@ export function createMutationController(directory, { captures = createCaptureCo
199
200
  mkdirSync(cache, { recursive: true });
200
201
  if (realpathSync(cache) !== path.join(realpathSync(root), ".ds")) throw fail("mutation-path", "The .ds directory cannot resolve through a symlink.");
201
202
  temporary = mkdtempSync(path.join(cache, "mutation-"));
203
+ trackExecutionWorkspace(temporary);
202
204
  const candidate = path.join(temporary, "project");
203
205
  mkdirSync(candidate);
204
206
  const patchPaths=plans.flatMap(plan=>plan.entries.map(entry=>entry.path));
@@ -279,8 +281,8 @@ export function createMutationController(directory, { captures = createCaptureCo
279
281
  candidateRevision=digest(Buffer.from(expected));
280
282
  if (previewWork) releasePreview = await previewWork.acquire(signal);
281
283
  const result = await checkCandidate(candidate, signal, root);
284
+ verified.push({name:"ads check",passed:result.ok,cache:result.cache});
282
285
  if (!result.ok) return lastResult = mutationEvidence({ ok: false, applied: false, diagnostics: result.diagnostics, total: result.diagnostics.length, checks: verified },candidateRevision);
283
- verified.push({ name: "ads check", passed: true });
284
286
  if (assets || configuration) {
285
287
  boundary=evidenceFailure("build","brand-assets","ADS_ASSET_BUILD");
286
288
  const brand = await generateBrandAssets(candidate);
@@ -1,9 +1,13 @@
1
+ import { randomUUID } from "node:crypto";
2
+ import { executionContext } from "./execution-context.mjs";
3
+ import { createExecutionCoordinator } from "./execution-coordinator.mjs";
1
4
  import { existsSync, readFileSync, statSync, watch } from "node:fs";
2
5
  import path from "node:path";
3
6
  import { Server, ProtocolError, INVALID_PARAMS, ResourceNotFoundError } from "@modelcontextprotocol/server";
4
7
  import { serveStdio, StdioServerTransport } from "@modelcontextprotocol/server/stdio";
5
8
  import { z } from "zod";
6
9
  import { checkCandidate } from "../validation-checks.mjs";
10
+ import { taskCacheSettings } from "../task-cache.mjs";
7
11
  import { createValidationController } from "../validation.mjs";
8
12
  import { loadConfig, sourceFiles } from "../config.mjs";
9
13
  import { createVerificationController, BEHAVIOR_URI } from "../verification.mjs";
@@ -81,7 +85,11 @@ export function createAdsMcp(directory, { era = "legacy", skillDirectory, pollIn
81
85
  startPreview: workspace => startAdsMcp(workspace, { stdio: false, mutations: false, previewWork: cache.previewWork }) });
82
86
  const verification = cache.verification ??= createVerificationController(root, { previewWork: cache.previewWork });
83
87
  const validation = cache.validation ??= createValidationController(root, { previewWork: cache.previewWork });
84
- const executionResults = cache.executionResults ??= createExecutionResults(root);
88
+ const executionResults = cache.executionResults ??= createExecutionResults(root,{retention:()=>{try{cache.resultRetention=loadConfig(root).config.mcp.resultRetention;}catch{/* Keep the last valid policy during config edits. */}return cache.resultRetention;}});
89
+ const executionObservers=cache.executionObservers??=new Set();
90
+ const coordinator=cache.coordinator??=createExecutionCoordinator(root,{results:executionResults,onChange:()=>{for(const observer of executionObservers)observer();}});
91
+ const connectionId=randomUUID();
92
+ void coordinator.ready().catch(error=>process.stderr.write(`ads mcp: execution recovery: ${error.message}\n`));
85
93
  const reports = cache.reports ??= createReportStore(root, { context: reportContext, resolveEvidence: reportEvidence });
86
94
  let options = loadConfig(root);
87
95
  const signature = `${root}:${JSON.stringify(options.config)}`;
@@ -91,11 +99,11 @@ export function createAdsMcp(directory, { era = "legacy", skillDirectory, pollIn
91
99
  cache.registry = cache.catalog = cache.documents = undefined;
92
100
  }
93
101
  const getShowcaseUrl = () => showcaseUrl?.() ?? options.config.mcp.showcaseUrl;
94
- async function architecture(signal) {
102
+ async function architecture(signal, fresh=false) {
95
103
  let release;
96
104
  try {
97
105
  if (cache.previewWork) release = await cache.previewWork.acquire(signal);
98
- return await checkCandidate(root, signal);
106
+ return await checkCandidate(root, signal, root, {fresh});
99
107
  } finally { release?.(); }
100
108
  }
101
109
  function scenarioUrl(id) {
@@ -283,7 +291,7 @@ export function createAdsMcp(directory, { era = "legacy", skillDirectory, pollIn
283
291
  async function status() {
284
292
  const context = project(), mutationState = mutations ? edits.status() : null, behaviorState = verification.status();
285
293
  const catalog = await getCatalog(), registry = cache.registry;
286
- return { projectRoot: root, workflow: workflow([...previews(), ...scenarioApps(true)]), project: context,
294
+ return { projectRoot: root, taskCache:taskCacheSettings(root), workflow: workflow([...previews(), ...scenarioApps(true)]), project: context,
287
295
  package: pkg.name, version: pkg.version, dsDir: options.config.dsDir, publicAlias: options.config.publicAlias, behaviorLibraries: getBehaviorLibraries().libraries,
288
296
  components: catalog.filter((item) => item.kind === "components" && item.apiKind === "ui").length,
289
297
  patterns: catalog.filter((item) => item.kind === "patterns" && item.apiKind === "ui").length,
@@ -296,6 +304,7 @@ export function createAdsMcp(directory, { era = "legacy", skillDirectory, pollIn
296
304
  build: summarizeBuild(builds()),
297
305
  previews: previews(), skills: skills.skills.map(({ uri, frontmatter }) => ({ uri, name: frontmatter.name, description: frontmatter.description })),
298
306
  scenarios: { count: registry.scenarios.length, diagnostics: registry.diagnostics, resourceUri: `${PROJECT_URI}/scenarios`, tool: "ads_show_scenario" },
307
+ execution: coordinator.status(),
299
308
  validation: { ...validation.status(), tool: "ads_validate", lastResult: executionResults.latest("validation") },
300
309
  behaviors: { resourceUri: BEHAVIOR_URI, discoveryTool: "ads_behaviors", verificationTool: "ads_verify", investigationTool: "ads_investigate", investigationResourceUri: INVESTIGATIONS_URI, ...behaviorState, progress: compactProgress(behaviorState.progress), lastResult: executionResults.latest("verification"), resultsTool: "ads_results", resultsResourceUri: RESULTS_URI },
301
310
  captures: { resourceUri: CAPTURES_URI, tool: "ads_capture", clearTool: "ads_capture_clear", ...captures.status() },
@@ -391,12 +400,12 @@ export function createAdsMcp(directory, { era = "legacy", skillDirectory, pollIn
391
400
  }
392
401
 
393
402
  async function finishExecution(kind, result) {
403
+ if(executionContext.getStore()?.record.instanceId===coordinator.status().instanceId)return result;
394
404
  const summary = executionResults.save(kind, result);
395
405
  try { await refresh(); } catch (error) { process.stderr.write(`ads mcp: result saved; notification failed: ${error.message}\n`); }
396
406
  return { ...json(summary), ...(!result.ok ? { isError: true } : {}) };
397
407
  }
398
408
  async function applyEdits(args,signal,progress) {
399
- if (validation.status().busy) throw new Error("Wait for the active validation run before editing source.");
400
409
  const result = await edits.apply(args,signal,progress);
401
410
  if (result.screenshots) await refresh();
402
411
  if (result.applied) {
@@ -424,8 +433,7 @@ export function createAdsMcp(directory, { era = "legacy", skillDirectory, pollIn
424
433
  { name:"ads_create_draft", description:"Create a Git-committable proposal under ads-drafts/ for 1–64 coupled ADS owners, copying only their source/companions into non-importable .ads files. New owners are allowed. Optional dependencies name separate unaccepted drafts used by pattern/composition previews. Creation does not change accepted source. Edit the returned files normally; use ads_update_draft to register additions/deletions.", schema:z.object({units:z.array(z.string().min(1).max(256)).min(1).max(mutationLimits.units),title:z.string().min(1).max(160).optional(),id:draftIdSchema.optional(),dependencies:z.array(draftIdSchema).max(8).default([]),tokenGroups:z.array(z.string().min(1).max(160)).max(32).default([])}).strict(),_meta:{ui:{visibility:["model"]}},annotations:{...annotations,readOnlyHint:false,idempotentHint:false},call:async args=>{const result=drafts.create(args);if(observeChanges)await refresh();return json(result);} },
425
434
  { name:"ads_update_draft", description:"Update marked draft source or register new/deleted canonical target paths. Pass the current revision from ads_drafts. Source is UTF-8 unless encoding:base64; content:null proposes deletion. refresh:true rebases onto current accepted source using stored baselines; non-overlapping edits merge and overlapping edits leave the draft unchanged with diagnostics. Use changes with refresh only for explicit resolved contents of existing draft files; refresh separately from dependency changes. Optional dependencies replaces the draft dependency list. Normal local file edits need no iteration tool. Accepted source remains unchanged; ownership and all required checks run at acceptance.",schema:z.object({id:draftIdSchema,revision:draftRevisionSchema,refresh:z.boolean().default(false),dependencies:z.array(draftIdSchema).max(8).optional(),changes:z.array(z.object({unit:z.string().max(256),path:z.string().min(1).max(500),content:z.string().max(256*1024).nullable(),encoding:z.enum(["utf8","base64"]).optional()}).strict()).max(32).default([])}).strict(),_meta:{ui:{visibility:["model"]}},annotations:{...annotations,readOnlyHint:false,idempotentHint:false},call:async args=>{const result=drafts.update(args);if(observeChanges)await refresh();return json(result);} },
426
435
  { name:"ads_drop_draft",description:"Delete an exact tracked draft and its generated preview. This is Drop, not a separate refusal workflow. Accepted source is unchanged. Dependents report a missing dependency until corrected.",schema:z.object({id:draftIdSchema,revision:draftRevisionSchema}).strict(),_meta:{ui:{visibility:["model"]}},annotations:{...annotations,readOnlyHint:false,destructiveHint:true,idempotentHint:false},call:async args=>{const result=await drafts.drop(args);if(observeChanges)await refresh();return json(result);} },
427
- { name:"ads_accept",title:"Accept a reviewed draft",description:"Auto-mode acceptance: validate and apply the exact rendered/reviewed draft revision in one operation. Accept dependency drafts first; dependent drafts automatically switch to their final @ds implementations. Mandatory ADS guards and acceptance.checks run once on the candidate; affected registered tests gate acceptance when acceptance.behaviorChecks is true. Draft/source changes invalidate acceptance. On failure retain the draft and inspect ads_results; on success apply normal source, remove the draft and publish an event. No additional human approval or manual Apply step.",schema:z.object({id:draftIdSchema,revision:draftRevisionSchema}).strict(),_meta:{ui:{visibility:["model"]}},annotations:{...annotations,readOnlyHint:false,destructiveHint:true,idempotentHint:false},call:async(args,signal,progress)=>{
428
- if(validation.status().busy||verification.status().running)throw new Error("Wait for validation/verification before acceptance.");
436
+ { name:"ads_accept",title:"Accept a reviewed draft",description:"Auto-mode acceptance: validate and apply the exact rendered/reviewed draft revision in one operation. Accept dependency drafts first; dependent drafts automatically switch to their final @ds implementations. Mandatory ADS guards and acceptance.checks run once on the candidate; affected registered tests gate acceptance when acceptance.behaviorChecks is true. Draft/source changes invalidate acceptance. On failure retain the draft and inspect ads_results; on success apply normal source, remove the draft and publish an event. No additional human approval or manual Apply step.",schema:z.object({fresh:z.boolean().default(false),id:draftIdSchema,revision:draftRevisionSchema}).strict(),_meta:{ui:{visibility:["model"]}},annotations:{...annotations,readOnlyHint:false,destructiveHint:true,idempotentHint:false},call:async(args,signal,progress)=>{
429
437
  const result=await drafts.accept(args,signal,progress);
430
438
  if(result.applied){await previewWatch?.invalidate?.();await refresh(true);}else await refresh();
431
439
  return finishExecution("mutation",result);
@@ -473,9 +481,9 @@ export function createAdsMcp(directory, { era = "legacy", skillDirectory, pollIn
473
481
  const matches = inventory.tokens.filter((token) => token.name.toLowerCase().includes(search.toLowerCase()));
474
482
  return json({ total: matches.length, tokens: matches.slice(0, limit), categories: tokenScenarios(), tokenGroups:drafts.tokenGroups(), diagnosticCount: inventory.diagnostics.length, resourceUri: `${PROJECT_URI}/tokens` });
475
483
  } },
476
- { 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) => {
477
- const result = await architecture(signal);
478
- 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` });
484
+ { 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), fresh:z.boolean().default(false) }).strict(), call: async ({ limit, fresh }, signal) => {
485
+ const result = await architecture(signal,fresh);
486
+ return json({ ok: result.ok, acceptance:result.acceptance, cache:result.cache, 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` });
479
487
  } },
480
488
  { 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 })) }) },
481
489
  { name: "ads_read_skill", description: "Read a selected skill or relative supporting text file in bounded chunks. This is explicit instruction access, not automatic native skill activation/install.", schema: z.object({ name: z.string().max(64), file: z.string().max(300).default("SKILL.md"), offset: z.number().int().min(0).default(0), limit: z.number().int().min(1).max(8000).default(6000) }).strict(), call: ({ name, file, offset, limit }) => {
@@ -505,16 +513,14 @@ export function createAdsMcp(directory, { era = "legacy", skillDirectory, pollIn
505
513
  return json({ widget: { resourceUri: TOKENS_APP_URI }, category: null, tokenCount: inspectTokens(root).tokens.length, dataUri: `${PROJECT_URI}/tokens`, showcaseUrl: getShowcaseUrl() });
506
514
  } },
507
515
  { name: "ads_behaviors", description: "Discover behavior owners, then page an exact unit's checks, guarantees, subjects, demonstrations or profiles. Summary listings never embed runner logs. Default 10/max 20 entries and 8 KiB JSON per page; continue with nextCursor and identical filters. Cursors expire when discovery/evidence changes. Read sourceFile with ads_read_file for a complete contract. Metadata and reachable calls do not prove execution; use ads_verify for registered checks.", schema: z.object({ query: z.string().max(200).optional(), unit: z.string().min(1).max(256).optional(), api: z.string().max(200).optional(), section: z.enum(behaviorSections).optional(), ...paged }).strict(), call: args => json(behaviorPage(options,args)) },
508
- { name: "ads_results", title: "Read execution outcomes", description: "Read saved ads_validate/ads_verify/ads_apply_patch/ads_apply_transaction outcomes without rerunning anything. Pass the returned resultId; select outcomes, checks, diagnostics, advisories, warnings, changes, captures, acceptance, investigation or selection. Default 10/max 20 rows, at most 8 KiB JSON per page. Follow nextCursor with identical section/status. Rows marked detailTruncated can be read in full using recordIndex and offset/chars (max 2000); follow nextOffset. Only the latest validation, verification and mutation snapshots are retained; replaced IDs fail explicitly. For one outcome's browser evidence use ads_investigate with its exact unit/check/runId.", schema: z.object({ resultId: z.string().uuid(), section: z.enum(resultSections).optional(), status: z.enum(["all","passed","not_passed"]).optional(), ...paged, ...recordRange }).strict(), call: args => json(executionResults.page(args)) },
516
+ { name: "ads_results", title: "Read execution outcomes", description: "Read saved ads_validate/ads_verify/ads_apply_patch/ads_apply_transaction outcomes without rerunning anything. Pass the returned resultId; select outcomes, checks, diagnostics, advisories, warnings, changes, captures, acceptance, investigation or selection. Default 10/max 20 rows, at most 8 KiB JSON per page. Follow nextCursor with identical section/status. Rows marked detailTruncated can be read in full using recordIndex and offset/chars (max 2000); follow nextOffset. Results are retained by immutable run ID with bounded age/count/disk retention, including after reconnect or other clients finish. Expired IDs fail with ADS_RESULT_EXPIRED. For one outcome's browser evidence use ads_investigate with its exact unit/check/runId.", schema: z.object({ resultId: z.string().uuid(), section: z.enum(resultSections).optional(), status: z.enum(["all","passed","not_passed"]).optional(), ...paged, ...recordRange }).strict(), call: args => json(executionResults.page(args)) },
509
517
  { name:"ads_report_bug",title:"Report a suspected ADS defect",description:"Record an unexpected ADS guard, preview, build, transport or runner behavior after targeted investigation. Provide expected/observed behavior, minimal steps and frequency; keep suspectedCause separate. Evidence optionally selects a returned resultId or exact unit/check/runId. ADS snapshots compact evidence, version, configured framework and revisions. A report is an untriaged agent claim, not proof of an ADS cause. Returns a small receipt with the report ID and local file path; submitted reports cannot be read through MCP. Stored locally under .ds/reports/ with deduplication, no automatic expiry and no upload. Read ads://guides/reporting; ordinary valid guard rejections should be fixed in their owner.",schema:bugReportSchema,annotations:{readOnlyHint:false,destructiveHint:false,idempotentHint:false,openWorldHint:false},call:args=>submitReport("bug",args) },
510
518
  { name:"ads_request_feature",title:"Request an ADS capability",description:"Record a legitimate workflow that needs a missing ADS capability. Provide workflow, capability and impact; proposal is optional. Preserve valid design/API rather than weakening guards or inventing workaround props. Optional evidence references an existing execution/check, not pasted files/logs. ADS attaches compact context and returns a receipt with the report ID and local file path. Intake is submission-only; no report-reading tools or resources. Shared local report store: deduplicated, untriaged, no automatic expiry or upload. Read ads://guides/reporting; use ads_report_bug for suspected broken existing behavior.",schema:featureRequestSchema,annotations:{readOnlyHint:false,destructiveHint:false,idempotentHint:false,openWorldHint:false},call:args=>submitReport("feature",args) },
511
- { name: "ads_investigate", title: "Inspect check evidence", description: "Read a summary for an exact unit/check, or list latest investigations when no check is selected. Pass the outcome's runId to reject superseded evidence. Summary is at most 4 KiB JSON; details, requests, browserErrors and artifacts are separate paged sections (default 10/max 20 entries, 8 KiB). Read truncated rows with recordIndex/offset/chars and the exact runId. Artifact URIs are read separately. Does not rerun checks or infer root cause. Only the latest bundle per check is retained, including candidate runs.", schema: z.object({unit:z.string().min(1).max(256).optional(),check:z.string().min(1).max(100).optional(),runId:z.string().min(1).max(100).optional(),section:z.enum(investigationSections).optional(),...paged,...recordRange}).strict(), call: args => json(investigationPage(root,args)) },
512
- { name: "ads_validate", description: "Run mandatory ADS architecture/freshness guards and the selected project policy. policy defaults to validation: its configured scripts, preview freshness and optional registered behavior checks. policy acceptance runs acceptance.checks and acceptance.behaviorChecks without applying source, for direct editing. No script names are inferred. scope changed selects affected registered checks from this policy's own successful full baseline; broad changes expand to all. Project scripts keep full scope. Draft edit/show never triggers policies. Reports skipped stages honestly and a bounded resultId; use ads_results for details. Read ads://guides/validation. Trusted configured commands run; nothing is installed.", schema: z.object({scope:z.enum(["all","changed"]).default("all"),policy:z.enum(["acceptance","validation"]).default("validation")}).strict(), annotations: {readOnlyHint:false,destructiveHint:false,idempotentHint:false,openWorldHint:false}, call: async (args,signal,progress) => {
513
- if (verification.status().running || edits.status().busy) throw new Error("Wait for the active verification or guarded edit before validating.");
519
+ { name: "ads_investigate", title: "Inspect check evidence", description: "Read a summary for an exact unit/check, or list latest investigations when no check is selected. Pass the outcome's runId to reject superseded evidence. Summary is at most 4 KiB JSON; details, requests, browserErrors and artifacts are separate paged sections (default 10/max 20 entries, 8 KiB). Read truncated rows with recordIndex/offset/chars and the exact runId. Artifact URIs are read separately. Does not rerun checks or infer root cause. Lists latest checks; an exact runId reads retained historical evidence, including candidate runs.", schema: z.object({unit:z.string().min(1).max(256).optional(),check:z.string().min(1).max(100).optional(),runId:z.string().min(1).max(100).optional(),section:z.enum(investigationSections).optional(),...paged,...recordRange}).strict(), call: args => json(investigationPage(root,args)) },
520
+ { name: "ads_validate", description: "Run mandatory ADS architecture/freshness guards and the selected project policy. policy defaults to validation: its configured scripts, preview freshness and optional registered behavior checks. policy acceptance runs acceptance.checks and acceptance.behaviorChecks without applying source, for direct editing. No script names are inferred. scope changed selects affected registered checks from this policy's own successful full baseline; broad changes expand to all. Project scripts keep full scope. Draft edit/show never triggers policies. Reports skipped stages honestly and a bounded resultId; use ads_results for details. Read ads://guides/validation. Trusted configured commands run; nothing is installed.", schema: z.object({scope:z.enum(["all","changed"]).default("all"),policy:z.enum(["acceptance","validation"]).default("validation"),fresh:z.boolean().default(false)}).strict(), annotations: {readOnlyHint:false,destructiveHint:false,idempotentHint:false,openWorldHint:false}, call: async (args,signal,progress) => {
514
521
  return finishExecution("validation",await validation.run(args,signal,progress));
515
522
  } },
516
523
  { name: "ads_verify", description: "Run one owner's registered development behavior checks using its configured runner/profile. Executes trusted project commands with bounded output, cancellation and process-tree cleanup; installs nothing. Progress and per-check timings are available through ads_status; a profile timeout bounds the whole run. Browser profiles use an isolated managed showcase/MCP App. React StrictMode requires a project development harness, not a production widget. Missing/skipped cases, stale inputs and process exit alone cannot produce passing evidence. Replies contain counts, acceptance, at most three failure summaries and a resultId (4 KiB JSON maximum). Page outcomes with ads_results; inspect one exact unit/check/runId with ads_investigate. Discover exact unit/check IDs with ads_behaviors first.", schema: z.object({ unit: z.string().min(1).max(256), checks: z.array(z.string().min(1).max(100)).min(1).max(100).optional() }).strict(), annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: false, openWorldHint: false }, call: async (args, signal, progress) => {
517
- if (validation.status().busy) throw new Error("Wait for the active validation run before verifying separately.");
518
524
  const result = await verification.run(args, signal, progress);
519
525
  return finishExecution("verification", {unit:args.unit,...result});
520
526
  } },
@@ -556,10 +562,27 @@ export function createAdsMcp(directory, { era = "legacy", skillDirectory, pollIn
556
562
  let progress = 0;
557
563
  const token = context.mcpReq._meta?.progressToken;
558
564
  const notify = token === undefined ? undefined : value => {
559
- void context.mcpReq.notify({ method: "notifications/progress", params: { progressToken: token, progress: ++progress, message: value.message ?? `${value.profile}: ${value.completed}/${value.total} completed; ${(value.active ?? []).slice(0,3).map(item => `${item.unit}#${item.check}`).join(", ") || "no active check reported"}; ${value.elapsedMs} ms elapsed` } }).catch(() => {});
565
+ void context.mcpReq.notify({ method: "notifications/progress", params: { progressToken: token, progress: ++progress, message: value.message ?? (value.stage?`${value.stage}: ${value.elapsedMs??0} ms elapsed`:`${value.profile}: ${value.completed}/${value.total} completed; ${(value.active ?? []).slice(0,3).map(item => `${item.unit}#${item.check}`).join(", ") || "no active check reported"}; ${value.elapsedMs} ms elapsed`) } }).catch(() => {});
560
566
  };
561
- try { return await tool.call(input.data, context.mcpReq.signal, notify); }
562
- catch (error) { return { isError: true, content: [{ type: "text", text: error.message }], structuredContent: {ok:false,message:error.message,failure:failure(error.build?"build":"runner",error.build?"preview-build":"tool-execution",error.build?.code??"ADS_TOOL_ERROR",{certainty:"observed-boundary"}),...(error.build?{build:error.build}:{})} }; }
567
+ try {
568
+ const kinds={ads_validate:"validation",ads_verify:"verification",ads_apply_patch:"mutation",ads_apply_transaction:"mutation",ads_accept:"mutation"};
569
+ const kind=kinds[name];
570
+ if(!kind)return await tool.call(input.data,context.mcpReq.signal,notify);
571
+ const client=server.getClientVersion?.();
572
+ const label=context.mcpReq._meta?.["ads/clientId"];
573
+ const owner={clientId:typeof label==="string"?label.slice(0,100):null,clientName:client?.name?.slice(0,100)??null,connectionId};
574
+ const args=input.data;
575
+ const selection={...(args.policy?{policy:args.policy}:{}),...(args.scope?{requestedScope:args.scope,scope:args.scope}:{}),units:args.units??args.patches?.map(row=>row.unit)??(args.unit?[args.unit]:[]),...(args.id?{draft:args.id}:{}),...(args.checks?{checks:args.checks}:{})};
576
+ const summary=await coordinator.execute({operation:name,kind,owner,selection,watchSource:kind!=="mutation"},context.mcpReq.signal,notify,(signal,progress)=>{
577
+ executionContext.getStore().fresh=args.fresh??false;
578
+ if(name==="ads_accept")progress({stage:"selection",policy:"acceptance",scope:"changed",units:drafts.inspect(args.id).manifest.units});
579
+ return tool.call(args,signal,progress);
580
+ });
581
+ const {isError,...value}=summary;
582
+ await refresh();
583
+ return {...json(value),...(isError?{isError:true}:{})};
584
+ }
585
+ catch (error) { return { isError: true, content: [{ type: "text", text: error.message }], structuredContent: {ok:false,message:error.message,...(error.code?{code:error.code}:{}),...(error.lock?{lock:error.lock}:{}),failure:failure(error.build?"build":"runner",error.build?"preview-build":"tool-execution",error.build?.code??error.code??"ADS_TOOL_ERROR",{certainty:"observed-boundary"}),...(error.build?{build:error.build}:{})} }; }
563
586
  });
564
587
  server.setRequestHandler("resources/list", ({ params = {} }) => {
565
588
  previewWatch?.start();
@@ -625,6 +648,12 @@ export function createAdsMcp(directory, { era = "legacy", skillDirectory, pollIn
625
648
  const draftBuilds = () => new Map(drafts.previewStatuses().map(build => [build.resourceUri, JSON.stringify(build)]));
626
649
  const investigationFingerprint=()=>fileFingerprint([path.join(root,".ds/investigations.json")]);
627
650
  let previousInvestigations, previousResults, observing=false;
651
+ const executionChanged=()=>{
652
+ const uri=`${PROJECT_URI}/status`;
653
+ if(notifications)notifications.resourceUpdated(uri);
654
+ else if(subscribed.has(uri))void server.sendResourceUpdated({uri}).catch(()=>{});
655
+ };
656
+ executionObservers.add(executionChanged);
628
657
  function initializeObservation() {
629
658
  if (observing) return;
630
659
  previous=fingerprint();previousArtifacts=artifactFingerprint();previousAssets=assetFingerprint();previousBuild=JSON.stringify(builds());
@@ -724,9 +753,9 @@ export function createAdsMcp(directory, { era = "legacy", skillDirectory, pollIn
724
753
  const timer = pollInterval > 0 ? setInterval(() => { if (!observationClosed) refresh().catch(error => { if (!observationClosed) process.stderr.write(`ads mcp: ${error.message}\n`); }); }, pollInterval) : null;
725
754
  timer?.unref();
726
755
  if (observeChanges) draftObservers.add(refresh);
727
- const stopObservation = () => { observationClosed = true; draftObservers.delete(refresh); if (timer) clearInterval(timer); };
756
+ const stopObservation = () => { executionObservers.delete(executionChanged);observationClosed = true; draftObservers.delete(refresh); if (timer) clearInterval(timer); };
728
757
  server.oninitialized = () => previewWatch?.start();
729
- server.onclose = stopObservation;
758
+ server.onclose = () => {stopObservation();if(!inspection)void coordinator.close().catch(()=>{});};
730
759
  async function warmScenarios(ids, signal) {
731
760
  if (!previewWatch) return;
732
761
  const apps = allApps(), selected = new Set(ids);
@@ -739,7 +768,7 @@ export function createAdsMcp(directory, { era = "legacy", skillDirectory, pollIn
739
768
  await previewWatch.warm(files);
740
769
  for (const file of files) await previewWatch.ensure(file, signal);
741
770
  }
742
- 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 cache.registryInspector?.close(); await drafts.close(); await validation.close(); await verification.close(); await captures.close(); } await server.close(); } };
771
+ 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() { executionObservers.delete(executionChanged);stopObservation(); if (!inspection) { await coordinator.close(); await cache.registryInspector?.close(); await drafts.close(); await validation.close(); await verification.close(); await captures.close(); } await server.close(); } };
743
772
  }
744
773
 
745
774
  export async function startAdsMcp(directory = process.cwd(), { stdio = true, showcase = true, port = 0, mutations = false, previewWork = createPreviewWork(), previewBuildTimeoutMs = 30000, prewarm = stdio } = {}) {
@@ -784,8 +813,10 @@ export async function startAdsMcp(directory = process.cwd(), { stdio = true, sho
784
813
  buildListeners.clear();
785
814
  clearTimeout(buildChangeTimer); buildWatcher?.close();
786
815
  inspection.edits?.cancel();
816
+ const executionClosing=inspection.coordinator?.close();
787
817
  // Stop every owned resource even if another close fails or has in-flight RPCs.
788
818
  const results = await Promise.allSettled([
819
+ executionClosing,
789
820
  Promise.resolve().then(() => host?.close()),
790
821
  previewWatch.stop(),
791
822
  Promise.resolve().then(() => inspection.validation?.close()),
@@ -14,6 +14,7 @@ import { createScenarioInspector } from "./scenario-inspector.mjs";
14
14
  import { configurationFiles } from "./units.mjs";
15
15
  import { validationInputFiles } from "./validation-inputs.mjs";
16
16
  import { previewRuntimeFingerprint } from "./runtime-requirements.mjs";
17
+ import { architectureExternalInputs } from "./task-cache.mjs";
17
18
 
18
19
  const digest = value => createHash("sha256").update(value).digest("hex");
19
20
  const fileDigest = file => { try { return digest(readFileSync(file)); } catch { return null; } };
@@ -23,6 +24,9 @@ const cacheVersion = 3, maxCacheBytes = 8 * 1024 * 1024;
23
24
  * Cache state is development output, never proof that a failed build is current. */
24
25
  export function createPreviewCache(options, compilerFiles = []) {
25
26
  const { root } = options;
27
+ // Build adapters such as Vite set NODE_ENV while configuring a build. Capture
28
+ // the launch environment once; internal compiler setup is not an external edit.
29
+ const launchEnvironment=architectureExternalInputs(root).environment;
26
30
  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;
27
31
  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,
28
32
  ...["package.json", "package-lock.json", "bun.lock", "bun.lockb", "node_modules/.package-lock.json"].map(file => path.join(root, file))];
@@ -40,7 +44,7 @@ export function createPreviewCache(options, compilerFiles = []) {
40
44
  }
41
45
  reload();
42
46
  function inputs() {
43
- const rows = [["project-inputs",previewSourceRevision(options)],["runtime",previewRuntimeFingerprint()]];
47
+ const rows = [["project-inputs",previewSourceRevision(options)],["runtime",previewRuntimeFingerprint()],["architecture-environment",{...architectureExternalInputs(root),environment:launchEnvironment}]];
44
48
  for (const file of compilerFiles) rows.push([key(file), fileDigest(file)]);
45
49
  // Tool upgrades invalidate validation even when the project's lockfile is unchanged.
46
50
  for (const name of readdirSync(import.meta.dirname).filter(name => name.endsWith(".mjs"))) {
@@ -183,6 +187,29 @@ export function preparePreviewCache(candidate, target) {
183
187
 
184
188
  export function promotePreviewCache(candidate,target) { const publish=preparePreviewCache(candidate,target);return publish?publish():false; }
185
189
 
190
+ /** Restore a complete verified graph without rediscovering semantic scenarios or
191
+ * starting a compiler. Live build evidence always belongs to this new session. */
192
+ export async function restoreCompiledPreviews(options, compilerFiles) {
193
+ const cache=createPreviewCache(options,compilerFiles),stamp=cache.inputs();
194
+ if(!cache.production(stamp))return false;
195
+ const entries=cache.registry(stamp);
196
+ if(!entries?.length)return false;
197
+ const publication=cachedPreviewPublication(options,entries,cache.graphRevision());
198
+ if(!publication)return false;
199
+ // The native graph stamp includes the successful gate's source, tool, runtime,
200
+ // Git tracking and installed-package environment. Do not invoke a second batch
201
+ // runner to revalidate identical evidence already attached to this graph.
202
+ const sourceRevision=previewSourceRevision(options);
203
+ if(cache.inputs()!==stamp)return false;
204
+ const reporter=createBuildReporter(options.root,{apps:entries.map(entry=>({id:entry.id,file:previewArtifactPath(options,entry.artifact)}))});
205
+ publication.publish(reporter.session);
206
+ mkdirSync(path.join(options.root,".ds/scenarios"),{recursive:true});
207
+ writeFileSync(path.join(options.root,".ds/scenarios/manifest.json"),JSON.stringify({schemaVersion:1,scenarios:entries}));
208
+ if(cache.inputs()!==stamp)return false;
209
+ reporter.batch(()=>{for(const entry of entries){const revision=reporter.begin(entry.id,{sourceRevision});reporter.ready(entry.id,revision);}reporter.progress("idle");});
210
+ return {restored:true,revision:publication.revision,scenarios:entries.length};
211
+ }
212
+
186
213
  /** Shared scheduling and cache; the project supplies its own React/Preact build. */
187
214
  export async function runScenarioCompiler(directory, { watched = false, validate, build, buildGraph, compilerFiles = [] }) {
188
215
  const root = path.resolve(directory);
@@ -346,9 +346,8 @@ previews and a `resultId` (4 KiB UTF-8 JSON maximum). Use `ads_results` to read
346
346
  selected `outcomes`, `checks`, `diagnostics` or other sections without execution.
347
347
  Pages default to 10 rows, allow at most 20 and stay within 8 KiB; follow
348
348
  `nextCursor` with identical selection/status. Truncated records provide
349
- `recordIndex` for exact `offset`/`chars` ranges. Only the latest verification and
350
- mutation snapshots are retained, independently, at most 8 MiB each. Replaced IDs
351
- fail explicitly. Validation still uses complete internal outcomes.
349
+ `recordIndex` for exact `offset`/`chars` ranges. Immutable run snapshots remain readable across other executions and reconnects,
350
+ within configurable retention, at most 8 MiB each. Expired IDs fail explicitly. Validation still uses complete internal outcomes.
352
351
 
353
352
  Use `ads_investigate({unit,check,runId})` with an outcome's exact IDs for its compact
354
353
  summary (4 KiB maximum); details, requests, browser errors and artifact metadata are separate
@@ -358,8 +357,8 @@ the recorded run ID. Saved outcomes describe completion time; compare current
358
357
  input and observed preview revisions, failing step/source, startup viewport,
359
358
  failed startup requests and available project-recorded artifacts keep diagnosis
360
359
  separate from an inferred component defect. No artifact is invented or test
361
- retried. Each check retains one latest bundle; old artifact resource access is
362
- superseded. Candidate bundles remain distinct from passing live-source evidence.
360
+ retried. Latest-check listings are indexes; exact run IDs retain their historical bundles
361
+ and artifacts until collection. Candidate bundles remain distinct from passing live-source evidence.
363
362
  Read the portable [evidence reference](evidence.md)
364
363
  for category meanings, collection limits and artifact policy.
365
364
 
@@ -45,10 +45,13 @@ characters); follow `nextOffset`. Do not combine ranges with a cursor/status fil
45
45
  Read only the relevant log range. Reading pages or ranges never executes checks.
46
46
 
47
47
  `ads://project/results` lists the latest IDs. `ads://results/<resultId>` reads a
48
- summary; matching query parameters read pages/ranges. Only the latest verification
49
- and latest mutation snapshots are retained, independently, up to 8 MiB each.
50
- A superseded ID fails explicitly. An oversized report retains only its summary
51
- with a warning; disk failure retains details in server memory until shutdown.
48
+ summary; matching query parameters read pages/ranges. Immutable snapshots remain
49
+ readable across subsequent runs and reconnects, within `mcp.resultRetention`.
50
+ Defaults are 50 runs, seven days and 256 MiB including owned browser evidence;
51
+ individual snapshots remain limited to 8 MiB. `ADS_RESULT_EXPIRED` identifies a
52
+ recently collected ID; older/unknown IDs are unavailable. An oversized report
53
+ retains only its summary with a warning; disk failure retains latest details in
54
+ server memory until shutdown.
52
55
  Neither changes actual acceptance or applied state. These are logical JSON byte
53
56
  budgets, not token estimates; compatibility text can duplicate structured JSON.
54
57
  Saved outcomes describe completion-time evidence, not current source freshness;
@@ -68,7 +71,7 @@ Take an outcome's exact owner/check/run IDs from `ads_results`, then:
68
71
  ```
69
72
 
70
73
  Send this to `ads_investigate`. It reads a summary within 4096 JSON bytes, without
71
- running code. The run ID rejects evidence superseded by another execution.
74
+ running code. The exact run ID selects retained historical evidence from that execution.
72
75
  `section: "details"`, `"requests"`, `"browserErrors"` or `"artifacts"` reads separate pages
73
76
  (default 10/max 20 rows, at most 8192 JSON bytes); artifacts themselves require
74
77
  explicit resource reads. Truncated investigation records also support
@@ -93,9 +96,10 @@ artifacts exist; ADS does not turn on expensive recording or rerun a failed case
93
96
  Protocol runners may provide structured failure/step/location/artifact fields;
94
97
  older reports remain valid and their unclassified errors stay explicit.
95
98
 
96
- Only the latest bundle per registered check is exposed, including dry runs.
97
- Another verification replaces it and removes old artifacts from resource access;
98
- old runner output directories follow project cleanup policy. Artifact resources
99
+ Listings show the latest bundle per registered check, including dry runs.
100
+ An exact `runId` reads the retained historical bundle and artifacts. Collection
101
+ expires a result and its owned evidence together; another verification alone does
102
+ not revoke earlier evidence. Artifact resources
99
103
  are restricted to registered ordinary files under that run's output directory,
100
104
  bounded to 20 MiB each and checked against their recorded digest on read.
101
105
  Metadata is bounded to 2 MiB. Removed registrations are pruned on verification.