@reqvire-org/ads 0.3.40 → 0.3.41

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 (31) hide show
  1. package/dist/config.mjs +4 -1
  2. package/dist/investigations.mjs +27 -8
  3. package/dist/mcp/context.mjs +1 -1
  4. package/dist/mcp/execution-context.mjs +38 -0
  5. package/dist/mcp/execution-coordinator.mjs +220 -0
  6. package/dist/mcp/execution-results.mjs +107 -48
  7. package/dist/mcp/mutations.mjs +2 -0
  8. package/dist/mcp/server.mjs +42 -13
  9. package/dist/skills/ads-break-ui/references/behaviors.md +4 -5
  10. package/dist/skills/ads-break-ui/references/evidence.md +12 -8
  11. package/dist/skills/ads-break-ui/references/validation.md +33 -0
  12. package/dist/skills/ads-designer/references/behaviors.md +4 -5
  13. package/dist/skills/ads-designer/references/evidence.md +12 -8
  14. package/dist/skills/ads-designer/references/validation.md +33 -0
  15. package/dist/skills/ads-import/references/behaviors.md +4 -5
  16. package/dist/skills/ads-import/references/evidence.md +12 -8
  17. package/dist/skills/ads-import/references/validation.md +33 -0
  18. package/dist/skills/ads-motion/references/behaviors.md +4 -5
  19. package/dist/skills/ads-motion/references/evidence.md +12 -8
  20. package/dist/skills/ads-motion/references/validation.md +33 -0
  21. package/dist/skills/ads-port/references/behaviors.md +4 -5
  22. package/dist/skills/ads-port/references/evidence.md +12 -8
  23. package/dist/skills/ads-port/references/validation.md +33 -0
  24. package/dist/validation-checks.mjs +6 -2
  25. package/dist/validation.mjs +8 -2
  26. package/dist/verification.mjs +7 -3
  27. package/docs/ARCHITECTURE.md +14 -3
  28. package/docs/CHANGELOG.md +25 -12
  29. package/docs/MCP.md +54 -9
  30. package/docs/plans/execution-coordination.md +57 -0
  31. package/package.json +1 -1
package/dist/config.mjs CHANGED
@@ -25,7 +25,7 @@ export const defaultConfig = {
25
25
  acceptance: { checks: [], behaviorChecks: false },
26
26
  validation: { checks: [], behaviorChecks: true, inputs: [] },
27
27
  resources: { memoryLimitMb: null },
28
- mcp: { showcaseUrl: null, showcaseTitle: null, apps: [], previewWatch: null, previewManifest: null, mutationCheckTimeoutMs: 60000, behaviorProfiles: {}, capture: {} },
28
+ mcp: { showcaseUrl: null, showcaseTitle: null, apps: [], previewWatch: null, previewManifest: null, mutationCheckTimeoutMs: 60000, behaviorProfiles: {}, capture: {}, resultRetention: {maxRuns:50,maxAgeDays:7,maxBytesMb:256} },
29
29
  };
30
30
 
31
31
  export function isInside(parent, file) {
@@ -154,6 +154,9 @@ export function loadConfig(directory = process.cwd()) {
154
154
  || profile.timeoutMs !== undefined && (!Number.isInteger(profile.timeoutMs) || profile.timeoutMs < 100 || profile.timeoutMs > 900000)) throw new Error(`Invalid behavior profile ${name}. Use literal executable/args, a protocol or Playwright runner, a matching framework and a timeout from 100 to 900000 ms. Profiles do not install dependencies or receive APIs from an MCP host.`);
155
155
  if (profile.mode === "strict" && config.framework !== "react") throw new Error(`Behavior profile ${name}: React StrictMode requires framework react; use the configured framework's lifecycle tests instead.`);
156
156
  }
157
+ const retention={...defaultConfig.mcp.resultRetention,...config.mcp.resultRetention};
158
+ if(!config.mcp.resultRetention || typeof config.mcp.resultRetention!=="object" || Array.isArray(config.mcp.resultRetention) || Object.keys(config.mcp.resultRetention).some(key=>!["maxRuns","maxAgeDays","maxBytesMb"].includes(key)) || !Number.isInteger(retention.maxRuns) || retention.maxRuns<1 || retention.maxRuns>1000 || !Number.isInteger(retention.maxAgeDays) || retention.maxAgeDays<1 || retention.maxAgeDays>365 || !Number.isInteger(retention.maxBytesMb) || retention.maxBytesMb<8 || retention.maxBytesMb>16384)throw new Error("mcp.resultRetention requires maxRuns (1–1000), maxAgeDays (1–365), maxBytesMb (8–16384).");
159
+ config.mcp.resultRetention=retention;
157
160
  if (!Number.isInteger(config.mcp.mutationCheckTimeoutMs) || config.mcp.mutationCheckTimeoutMs < 100 || config.mcp.mutationCheckTimeoutMs > 300000) throw new Error("mcp.mutationCheckTimeoutMs must be an integer from 100 to 300000. This budget applies to each registered project script, separately from behavior profiles.");
158
161
  if (config.mcp.previewManifest !== null) {
159
162
  const manifest = projectPath(root, config.mcp.previewManifest, "mcp.previewManifest");
@@ -1,4 +1,4 @@
1
- import { existsSync, lstatSync, mkdirSync, readFileSync, realpathSync, renameSync, rmSync, writeFileSync } from "node:fs";
1
+ import { existsSync, lstatSync, mkdirSync, readFileSync, readdirSync, realpathSync, renameSync, rmSync, writeFileSync } from "node:fs";
2
2
  import path from "node:path";
3
3
  import { createHash, randomUUID } from "node:crypto";
4
4
  import { compactAcceptance, compactRow, jsonBytes, resultBudgets, resultPage, resultRecord } from "./mcp/result-pages.mjs";
@@ -9,8 +9,9 @@ const identity = entry => `${entry.unit}#${entry.check}`;
9
9
  export const investigationUri = entry => `ads://investigations/${encodeURIComponent(entry.unit)}/${encodeURIComponent(entry.check)}`;
10
10
  const ordinary = file => { try { return realpathSync(file)===path.resolve(file)&&lstatSync(file).isFile()&&lstatSync(file).nlink===1; } catch { return false; } };
11
11
  const digest = bytes => `sha256:${createHash("sha256").update(bytes).digest("hex")}`;
12
- function saved(root) {
13
- const file=indexFile(root);
12
+ function saved(root,runId) {
13
+ if(runId!==undefined && (typeof runId!=="string" || !/^[a-zA-Z0-9_-]{1,100}$/.test(runId)))throw new Error("Invalid investigation run ID.");
14
+ const file=runId===undefined?indexFile(root):path.join(root,".ds/investigation-runs",`${runId}.json`);
14
15
  if(!ordinary(file)||lstatSync(file).size>2*1024*1024)return {};
15
16
  try {const value=JSON.parse(readFileSync(file,"utf8"));return value.schemaVersion===1&&value.bundles&&typeof value.bundles==="object"&&!Array.isArray(value.bundles)?value.bundles:{};}catch{return {};}
16
17
  }
@@ -26,6 +27,17 @@ export function saveInvestigations(root, entries, registered) {
26
27
  for(const entry of entries)bundles[identity(entry)]={...entry,resourceUri:investigationUri(entry)};
27
28
  const content=JSON.stringify({schemaVersion:1,bundles});
28
29
  if(Buffer.byteLength(content)>2*1024*1024)throw new Error("Latest investigation metadata exceeds 2 MiB.");
30
+ const archive=path.join(root,".ds/investigation-runs");
31
+ mkdirSync(archive,{recursive:true});
32
+ if(realpathSync(archive)!==archive)throw new Error("Investigation archive cannot resolve through a symlink.");
33
+ for(const runId of new Set(entries.map(entry=>entry.runId))){
34
+ if(typeof runId!=="string"||!/^[a-zA-Z0-9_-]{1,100}$/.test(runId))continue;
35
+ const file=path.join(archive,`${runId}.json`),temporary=`${file}.${randomUUID()}.tmp`;
36
+ const rows={...saved(root,runId),...Object.fromEntries(entries.filter(entry=>entry.runId===runId).map(entry=>[identity(entry),{...entry,resourceUri:`${investigationUri(entry)}?runId=${encodeURIComponent(runId)}`}]))};
37
+ const data=JSON.stringify({schemaVersion:1,bundles:rows});
38
+ if(Buffer.byteLength(data)>2*1024*1024)throw new Error("Run investigation metadata exceeds 2 MiB.");
39
+ try{writeFileSync(temporary,data);renameSync(temporary,file);}finally{rmSync(temporary,{force:true});}
40
+ }
29
41
  const file=indexFile(root),temporary=`${file}.${randomUUID()}.tmp`;
30
42
  mkdirSync(path.dirname(file),{recursive:true});
31
43
  if(realpathSync(path.dirname(file))!==path.dirname(file))throw new Error("Investigation output cannot resolve through a symlink.");
@@ -36,9 +48,10 @@ export function investigationIndex(root) {
36
48
  return {retention:"latest-per-check",entries:Object.values(saved(root)).map(({unit,check,status,runId,target,completedAt,inputRevision,resourceUri,failure})=>({unit,check,status,runId,target,completedAt,inputRevision,resourceUri,...(failure?{failure}:{})}))};
37
49
  }
38
50
 
39
- export function readInvestigation(root,{unit,check}) {
40
- const bundle=saved(root)[identity({unit,check})];
41
- if(!bundle)throw new Error("No investigation exists for this check. Run ads_verify or a guarded candidate first.");
51
+ export function readInvestigation(root,{unit,check,runId}) {
52
+ const latest=saved(root)[identity({unit,check})];
53
+ const bundle=runId===undefined||latest?.runId===runId?latest:saved(root,runId)[identity({unit,check})];
54
+ if(!bundle)throw new Error("No retained investigation exists for this check/run. It may have expired; discover current evidence with ads_behaviors.");
42
55
  return {...bundle,artifacts:(bundle.artifacts??[]).map(artifact=>({...artifact,available:!!artifactPath(root,artifact.path)}))};
43
56
  }
44
57
 
@@ -50,7 +63,7 @@ export function investigationPage(root,{unit,check,runId,section="summary",curso
50
63
  return resultPage(entries,{cursor,limit,identity:["investigations",unit,entries],key:"entries",header:{retention:"latest-per-check"}});
51
64
  }
52
65
  if(!unit||!investigationSections.includes(section))throw new Error("Select an exact unit/check and a known investigation section.");
53
- const bundle=readInvestigation(root,{unit,check});
66
+ const bundle=readInvestigation(root,{unit,check,runId});
54
67
  if(runId!==undefined&&bundle.runId!==runId)throw new Error("Investigation was superseded by a different run. Do not mix it with the earlier result.");
55
68
  const details={source:bundle.source,failingStep:bundle.failingStep,viewport:bundle.viewport,viewportSource:bundle.viewportSource,failure:bundle.failure};
56
69
  if(section!=="summary"){
@@ -92,7 +105,13 @@ export function readInvestigationResource(root,uri) {
92
105
  if([...url.searchParams.keys()].some(key=>!["section","runId","cursor","limit","recordIndex","offset","chars"].includes(key)))throw new Error("Unknown investigation resource query.");
93
106
  return {uri,mimeType:"application/json",text:JSON.stringify(investigationPage(root,{unit:parts[0],check:parts[1],section:url.searchParams.get("section")??"summary",runId:url.searchParams.get("runId")??undefined,cursor:url.searchParams.get("cursor")??undefined,...Object.fromEntries(["limit","recordIndex","offset","chars"].filter(key=>url.searchParams.has(key)).map(key=>[key,Number(url.searchParams.get(key))]))}))};
94
107
  }
95
- const artifact=Object.values(saved(root)).flatMap(bundle=>bundle.artifacts??[]).find(artifact=>artifact.resourceUri===uri);
108
+ let artifact=Object.values(saved(root)).flatMap(bundle=>bundle.artifacts??[]).find(artifact=>artifact.resourceUri===uri);
109
+ const archive=path.join(root,".ds/investigation-runs");
110
+ if(!artifact&&existsSync(archive)&&realpathSync(archive)===archive)for(const name of readdirSync(archive)){
111
+ if(!/^[a-zA-Z0-9_-]{1,100}\.json$/.test(name))continue;
112
+ artifact=Object.values(saved(root,name.slice(0,-5))).flatMap(bundle=>bundle.artifacts??[]).find(artifact=>artifact.resourceUri===uri);
113
+ if(artifact)break;
114
+ }
96
115
  const file=artifact&&artifactPath(root,artifact.path);
97
116
  if(!file||!existsSync(file))throw new Error("Investigation artifact is unavailable or has been superseded.");
98
117
  const bytes=readFileSync(file);
@@ -67,7 +67,7 @@ Use this server for UI components/patterns, tokens/themes/branding, layout, inte
67
67
  With MCP-only access and enabled mutation tools, read ads://guides/drafts. Discover owners with ads_units, create a coherent proposal with ads_create_draft, read/edit marked source through ads_read_file/ads_update_draft, inspect ads_show_draft in the browser, then ads_accept with its exact reviewed revision. Direct editors can choose this isolated workflow too. Complete tracked changes by accepting required drafts; accept dependencies first and review dependents again. Retain a proposal only when requested. No extra human approval step is implied. Without an editor or mutation tools, source editing is unavailable.
68
68
  For MCP-only focused repairs/migrations, use ads_units and guarded ads_apply_patch({unit,patch,dryRun}); include the owner's scenarios, fixtures and required public re-exports while preserving unrelated source. Use ads_apply_transaction for coupled owners. Token/runtime companionFiles allow only required foundation imports or selected-owner style-boundary changes. ads_prepare_patch stages an owner diff; ads_prepare_token_samples reconciles explicit bindings. Configuration/guard/compiler changes use configuration, shared globals foundation, guides documentation and assets their discovered assets/* unit. Keep mandatory ADS gates. Never bypass rejected patches or acceptance by switching to direct writes. Binary/large patches can use patchFile under .ds/patches/. Reuse the local public API (${context.publicEntry}). Edit presentation in its ADS owner; keep application data/services/routing in application code and development fixtures beside their scenario; larger scenarios live in composition/. Demo framing and token renderers live in development-only review/, imported through ${context.review.importFrom}; never export them from the production barrel or import them into application runtime. Read ads://guides/review for review owners/aliases and ads://guides/contracts when editing static owner declarations, .ads. development roles, constrained paints/bindings or declarative APIs. Contract registration, source evidence and browser verification remain separate. Use ads_prepare_patch action: migrate for a reviewable owner draft, then normal diff and guarded application. Shared foundation Data is the only design-value catalogue. Components/patterns map shared roles; independent owner token namespaces and value sheets are rejected. Existing project font, text and spacing roles take precedence over divergent upstream constants. Read ads://guides/tokens for the source contract and overlap review. Linaria extracts owned styling. Inspect relevant tokens with ads_tokens and source/owning guides before edits.
69
69
  6. ${route.validation} Registered commands: ${context.commands.map((command) => command.args?.join(" ") ?? `choose the project package manager for ${command.script}`).join("; ") || "none discovered; inspect the project's build setup"}. Run them from ${context.projectRoot}.
70
- Execution replies from ads_verify and guarded edits contain counts, acceptance and resultId, not full reports. Read only needed outcomes/diagnostics/captures with ads_results, following nextCursor with identical filters. A truncated row has recordIndex for bounded text ranges. For one failure, use ads_investigate with its unit/check/runId; read request/error/artifact sections only when needed. Only the latest verification and mutation results, and latest investigation per check, are available. Notifications do not establish freshness.
70
+ Execution replies from ads_verify and guarded edits contain counts, acceptance and resultId, not full reports. Read only needed outcomes/diagnostics/captures with ads_results, following nextCursor with identical filters. A truncated row has recordIndex for bounded text ranges. For one failure, use ads_investigate with its unit/check/runId; read request/error/artifact sections only when needed. Results are retained by immutable run ID with bounded retention; exact investigation run IDs select retained historical evidence. Shared-server checks and accepted-source writes serialize; ADS_VALIDATION_LOCKED includes the holder and progress. A source edit can stop validation with ADS_SOURCE_CHANGED_DURING_RUN. Read ads_status.execution before retrying. Notifications do not establish freshness.
71
71
 
72
72
  7. After edits, inspect ads_status.build or ads://project/build explicitly. Running/unreported/old output is not a current successful preview. Fix diagnostics in owned source, wait for rebuilding and invoke the preview tool again. Notifications may not start an agent turn.
73
73
 
@@ -0,0 +1,38 @@
1
+ import { AsyncLocalStorage } from "node:async_hooks";
2
+ import { readFileSync } from "node:fs";
3
+
4
+ export const executionContext = new AsyncLocalStorage();
5
+ export function processIdentity(pid) {
6
+ try {
7
+ const text=readFileSync(`/proc/${pid}/stat`,"utf8"),parts=text.slice(text.lastIndexOf(")")+2).split(" ");
8
+ if (["Z","X"].includes(parts[0])) return null;
9
+ return {pid,start:parts[19],boot:readFileSync("/proc/sys/kernel/random/boot_id","utf8").trim()};
10
+ } catch { return null; }
11
+ }
12
+ export function sameProcess(expected) {
13
+ const actual=expected && processIdentity(expected.pid);
14
+ return !!actual && actual.start===expected.start && actual.boot===expected.boot;
15
+ }
16
+ export function trackExecutionChild(child) {
17
+ const identity=child.pid && processIdentity(child.pid);
18
+ if(identity)executionContext.getStore()?.trackChild(identity);
19
+ }
20
+
21
+ /** Do not admit another run while an ownership guard still cleans descendants. */
22
+ export async function finishExecutionGuard(guard) {
23
+ if(!guard)return;
24
+ if(guard.exitCode!==null||guard.signalCode!==null)return;
25
+ await new Promise((resolve,reject)=>{
26
+ const timer=setTimeout(()=>{guard.kill("SIGKILL");reject(new Error("Runner ownership cleanup did not finish within 5 seconds."));},5000);
27
+ guard.once("exit",()=>{clearTimeout(timer);resolve();});
28
+ guard.stdin.end("cleanup\n");
29
+ });
30
+ }
31
+
32
+ export function trackExecutionArtifact(root,directory) {
33
+ const execution=executionContext.getStore();
34
+ execution?.trackArtifact(root,directory);
35
+ }
36
+ export function trackExecutionWorkspace(directory) {
37
+ executionContext.getStore()?.trackWorkspace(directory);
38
+ }
@@ -0,0 +1,220 @@
1
+ import { createHash, randomUUID } from "node:crypto";
2
+ import { existsSync, lstatSync, mkdirSync, readFileSync, readdirSync, realpathSync, renameSync, rmSync, watch, writeFileSync } from "node:fs";
3
+ import path from "node:path";
4
+ import os from "node:os";
5
+ import { loadConfig, isInside } from "../config.mjs";
6
+ import { validationInputs } from "../validation.mjs";
7
+ import { createPreviewFileFilter } from "../preview-files.mjs";
8
+ import { executionContext, processIdentity, sameProcess } from "./execution-context.mjs";
9
+
10
+ const processes=new Map();
11
+ const uuid=/^[a-f0-9]{8}(?:-[a-f0-9]{4}){3}-[a-f0-9]{12}$/;
12
+ const ignored=new Set(["output","test-results","playwright-report",".playwright-cli"]);
13
+ const error=(code,message,detail={})=>Object.assign(new Error(message),{code,...detail});
14
+ const relative=(root,file)=>path.relative(root,file).replaceAll("\\","/");
15
+
16
+ /** One lease across protocol instances. The interactive preview lane is independent. */
17
+ export function createExecutionCoordinator(root,{results,onChange=()=>{}}={}) {
18
+ root=path.resolve(root);
19
+ const directory=path.join(root,".ds/execution-runs"),instanceId=randomUUID(),processOwner=processIdentity(process.pid)??{pid:process.pid,start:null,boot:null};
20
+ const shared=processes.get(root)??{active:undefined,generation:0,observers:new Set()};processes.set(root,shared);shared.observers.add(onChange);
21
+ let recovering, initialized=false, closed=false;
22
+ const emit=()=>{shared.generation++;for(const observer of shared.observers)try{observer();}catch{/* Status polling remains available. */}};
23
+ function write(record,suffix="") {
24
+ let ancestor=directory;while(!existsSync(ancestor))ancestor=path.dirname(ancestor);
25
+ if(realpathSync(ancestor)!==ancestor)throw new Error("Execution journal cannot resolve through a symlink.");
26
+ mkdirSync(directory,{recursive:true});
27
+ if(realpathSync(directory)!==directory)throw new Error("Execution journal cannot resolve through a symlink.");
28
+ const file=path.join(directory,`${record.runId}${suffix}.json`),temporary=`${file}.${randomUUID()}.tmp`;
29
+ try {writeFileSync(temporary,JSON.stringify(record));renameSync(temporary,file);}finally{rmSync(temporary,{force:true});}
30
+ }
31
+ function journalEntries() {
32
+ if(!existsSync(directory)||realpathSync(directory)!==directory)return [];
33
+ return readdirSync(directory).filter(name=>uuid.test(name.slice(0,-5))&&name.endsWith(".json")).flatMap(name=>{
34
+ const file=path.join(directory,name);
35
+ try{const stat=lstatSync(file);if(!stat.isFile()||stat.isSymbolicLink()||stat.size>1024*1024)return [];const record=JSON.parse(readFileSync(file,"utf8"));return record.runId===name.slice(0,-5)&&["validation","verification","mutation"].includes(record.kind)?[record]:[];}catch{return [];}
36
+ });
37
+ }
38
+ function ownerAlive(record){
39
+ if(shared.active?.record.runId===record.runId)return true;
40
+ if(sameProcess(record.processOwner))return true;
41
+ // Without a verifiable start identity, liveness only protects a journal.
42
+ // It never grants authority to signal a possibly reused process ID.
43
+ if(record.processOwner?.start===null&&Number.isSafeInteger(record.processOwner.pid))try{process.kill(record.processOwner.pid,0);return true;}catch{return false;}
44
+ return false;
45
+ }
46
+ async function recover() {
47
+ for(const record of journalEntries().filter(row=>["running","stopping"].includes(row.state))) {
48
+ if(ownerAlive(record))continue; // Another live ADS process is not ours.
49
+ for(const child of record.children??[])if(sameProcess(child))try{process.kill(-child.pid,"SIGKILL");}catch(e){if(e.code!=="ESRCH")throw e;}
50
+ // EOF ownership guards can still be cleaning descendants in other groups.
51
+ if(record.children?.length||record.processOwner?.start===null)await new Promise(resolve=>setTimeout(resolve,1600));
52
+ if((record.children??[]).some(sameProcess))throw error("ADS_RECOVERY_PENDING","An abandoned runner is still stopping; retry shortly.");
53
+ for(const file of record.workspaces??[])if(typeof file==="string"&&(/^\.ds\/mutation-[a-zA-Z0-9]+$/.test(file)||path.dirname(file)===os.tmpdir()&&/^ads-architecture-[a-zA-Z0-9]+$/.test(path.basename(file)))){
54
+ const workspace=path.isAbsolute(file)?file:path.join(root,file);if(existsSync(workspace)&&realpathSync(workspace)===workspace)rmSync(workspace,{recursive:true,force:true});
55
+ }
56
+ if(results.has(record.runId)){
57
+ const saved=JSON.parse(results.readResource(`ads://results/${record.runId}`).text);
58
+ write({...record,state:saved.execution?.state??"completed",completedAt:saved.execution?.completedAt??saved.createdAt});
59
+ rmSync(path.join(directory,`${record.runId}.baseline.json`),{force:true});continue;
60
+ }
61
+ if(record.baseline&&/^(?:acceptance|validation)-baseline\.json$/.test(record.baseline.file)){
62
+ const file=path.join(root,".ds",record.baseline.file),backup=path.join(directory,`${record.runId}.baseline.json`);
63
+ try{
64
+ if(realpathSync(file)===file&&JSON.parse(readFileSync(file,"utf8")).executionRunId===record.runId&&realpathSync(backup)===backup){
65
+ const previous=JSON.parse(readFileSync(backup,"utf8")).previous;
66
+ if(previous===null)rmSync(file,{force:true});else writeFileSync(file,previous);
67
+ }
68
+ }catch{/* An absent baseline needs no rollback. */}
69
+ rmSync(backup,{force:true});
70
+ }
71
+ const execution={...record,state:"interrupted",completedAt:new Date().toISOString(),code:"ADS_RUN_INTERRUPTED"};
72
+ if(!results.has(record.runId))results.save(record.kind,{ok:false,current:false,execution,diagnostics:[{rule:"execution-interrupted",message:"ADS restarted before this run completed.",code:"ADS_RUN_INTERRUPTED"}]},{resultId:record.runId});
73
+ write(execution);
74
+ }
75
+ results.collect({protectedIds:journalEntries().filter(row=>["running","stopping"].includes(row.state)&&ownerAlive(row)).map(row=>row.runId)});
76
+ }
77
+ function status() {
78
+ const lease=shared.active?.record;
79
+ return {instanceId,generation:shared.generation,recovering:!!recovering,lock:lease?{...lease,children:undefined,processOwner:undefined,workspaces:undefined,artifacts:undefined,progress:lease.progress??null,estimatedRemainingMs:estimate(lease)}:null,retention:results.retentionStatus()};
80
+ }
81
+ function estimate(record) {
82
+ const p=record.progress;
83
+ // Per-profile counts do not estimate the remaining whole-policy stages.
84
+ if(record.operation!=="ads_verify"||!p?.total||!p.completed||p.completed>=p.total)return null;
85
+ return Math.round(Math.max(0,p.elapsedMs??0)/p.completed*(p.total-p.completed));
86
+ }
87
+ function lockError() {
88
+ const lock=status().lock;
89
+ const estimate=lock.estimatedRemainingMs===null?"":` (about ${Math.max(1,Math.ceil(lock.estimatedRemainingMs/60000))} min)`;
90
+ return error("ADS_VALIDATION_LOCKED",`Another client is validating this project; retry after it finishes${estimate}. This process currently serializes all checks and accepted-source writes.`,{lock});
91
+ }
92
+ function fence(lease) {
93
+ const options=loadConfig(root),baseline=validationInputs(options).files,skip=createPreviewFileFilter(options),watchers=[],watched=new Set();
94
+ const mandatory=[options.dsRoot,options.sourceRoot,...options.config.assets.publicDirs.map(file=>path.resolve(root,file)),...options.config.validation.inputs.map(file=>path.resolve(root,file))];
95
+ let stopped=false,timer;
96
+ function stop(changes) {
97
+ if(stopped||lease.signal.aborted)return;
98
+ lease.sourceChanges=changes;
99
+ lease.record.sourceChange={files:changes.slice(0,20),total:changes.length,attribution:{kind:"external",clientId:null},observedAt:new Date().toISOString()};
100
+ lease.record.state="stopping";write(lease.record);emit();
101
+ lease.abort.abort(error("ADS_SOURCE_CHANGED_DURING_RUN","Relevant source changed during this run.",{sourceChange:lease.record.sourceChange}));
102
+ }
103
+ function fullCheck(hint) {
104
+ clearTimeout(timer);timer=setTimeout(()=>{
105
+ if(stopped||lease.signal.aborted)return;
106
+ try{
107
+ const after=validationInputs(loadConfig(root)).files;
108
+ const changes=[...new Set([...Object.keys(baseline),...Object.keys(after)])].filter(file=>baseline[file]!==after[file]).map(file=>({path:file,change:baseline[file]==null?"added":after[file]==null?"deleted":"modified"}));
109
+ if(changes.length)stop(changes);
110
+ }catch{stop([{path:hint,change:"modified"}]);}
111
+ },75);timer.unref();
112
+ }
113
+ function event(directory,file) {
114
+ if(stopped||lease.signal.aborted)return;
115
+ if(!file){fullCheck(relative(root,directory));return;}
116
+ const absolute=path.join(directory,String(file)),name=relative(root,absolute);
117
+ if(skip(absolute)||name.split("/").some(part=>ignored.has(part)))return;
118
+ try{const stat=lstatSync(absolute);if(stat.isDirectory()&&!stat.isSymbolicLink())visit(absolute);}catch{/* Removed path. */}
119
+ if(Object.hasOwn(baseline,name)) {
120
+ let actual=null;
121
+ try{if(lstatSync(absolute).isFile())actual=`sha256:${createHash("sha256").update(readFileSync(absolute)).digest("hex")}`;}catch{/* Deleted input. */}
122
+ if(actual!==baseline[name])stop([{path:name,change:actual===null?"deleted":baseline[name]===null?"added":"modified"}]);
123
+ }else if(mandatory.some(base=>isInside(base,absolute))||/\.(?:test|spec)\.[cm]?[jt]sx?$/.test(name)||Object.keys(baseline).some(key=>key.startsWith(name+"/")))fullCheck(name);
124
+ else try{if(lstatSync(absolute).isDirectory()){visit(absolute);fullCheck(name);}}catch{/* Unrelated deletion. */}
125
+ }
126
+ function visit(directory) {
127
+ if(watched.has(directory))return;watched.add(directory);
128
+ try{
129
+ const watcher=watch(directory,(_type,file)=>event(directory,file));watcher.unref();watcher.on("error",()=>fullCheck(relative(root,directory)));watchers.push(watcher);
130
+ for(const entry of readdirSync(directory,{withFileTypes:true})){
131
+ const file=path.join(directory,entry.name);
132
+ if(entry.isDirectory()&&!entry.isSymbolicLink()&&!skip(file)&&!ignored.has(entry.name))visit(file);
133
+ }
134
+ }catch{fullCheck(relative(root,directory));}
135
+ }
136
+ visit(root);
137
+ lease.checkSource=()=>{
138
+ if(lease.signal.aborted&&!lease.record.sourceChange)return;
139
+ const after=validationInputs(loadConfig(root)).files;
140
+ const changes=[...new Set([...Object.keys(baseline),...Object.keys(after)])].filter(file=>baseline[file]!==after[file]).map(file=>({path:file,change:baseline[file]==null?"added":after[file]==null?"deleted":"modified"}));
141
+ if(lease.record.sourceChange){
142
+ lease.sourceChanges=[...new Map([...(lease.sourceChanges??[]),...changes].map(change=>[change.path,change])).values()];
143
+ lease.record.sourceChange={...lease.record.sourceChange,files:lease.sourceChanges.slice(0,20),total:lease.sourceChanges.length};
144
+ }else if(changes.length)stop(changes);
145
+ };
146
+ return ()=>{stopped=true;clearTimeout(timer);for(const watcher of watchers)watcher.close();};
147
+ }
148
+ return {
149
+ status,
150
+ async ready(){if(initialized)return;if(!recovering)recovering=recover().then(()=>{initialized=true;}).finally(()=>{recovering=undefined;});await recovering;},
151
+ async execute({operation,kind,owner,selection={},watchSource=true},signal,notify,work) {
152
+ if(closed)throw error("ADS_EXECUTION_CLOSED","ADS is shutting down.");
153
+ // Reserve synchronously: even requests arriving during recovery contend.
154
+ if(shared.active)throw lockError();
155
+ const abort=new AbortController(),runId=randomUUID();
156
+ const record={schemaVersion:1,runId,instanceId,processOwner,owner,operation,kind,...selection,state:"running",startedAt:new Date().toISOString(),children:[],artifacts:[],workspaces:[]};
157
+ let finish;const done=new Promise(resolve=>{finish=resolve;});
158
+ const lease={record,abort,commits:[],signal:signal?AbortSignal.any([signal,abort.signal]):abort.signal,done,trackChild(child){record.children.push(child);write(record);},trackArtifact(reportRoot,directory){
159
+ if(path.resolve(reportRoot)!==root)return;
160
+ const file=relative(root,directory);if(/^\.ds\/verification\/[a-f0-9-]{36}$/.test(file)){record.artifacts.push(file);write(record);}
161
+ },trackWorkspace(directory){
162
+ const file=relative(root,directory);if(/^\.ds\/mutation-[a-zA-Z0-9]+$/.test(file)||path.dirname(directory)===os.tmpdir()&&/^ads-architecture-[a-zA-Z0-9]+$/.test(path.basename(directory))){record.workspaces.push(file.startsWith(".ds/")?file:directory);write(record);}
163
+ }};
164
+ shared.active=lease;let stopFence;
165
+ const stopping=()=>{record.state="stopping";try{write(record);}catch{/* The final result reports storage failure. */}emit();};
166
+ lease.signal.addEventListener("abort",stopping,{once:true});
167
+ let lastWrite=0;
168
+ const progress=value=>{
169
+ record.progress={...value,cases:undefined};
170
+ if(value.scope)record.scope=value.scope;
171
+ if(value.policy)record.policy=value.policy;
172
+ if(value.units)record.units=value.units;
173
+ if(Date.now()-lastWrite>500){write(record);lastWrite=Date.now();emit();}notify?.(value);
174
+ };
175
+ try{
176
+ await this.ready();
177
+ write(record);emit();
178
+ let raw;
179
+ try{
180
+ if(watchSource&&!lease.signal.aborted)stopFence=fence(lease);
181
+ raw=await executionContext.run(lease,()=>work(lease.signal,progress));
182
+ }catch(e){raw={ok:false,diagnostics:[e.diagnostic??{rule:"execution-error",message:e.message,code:e.code??"ADS_EXECUTION_ERROR"}]};}
183
+ try{lease.checkSource?.();}catch(e){raw={...raw,ok:false,diagnostics:[...(raw.diagnostics??[]),{rule:"execution-inputs",message:e.message}]};}
184
+ const reason=lease.signal.reason;
185
+ if(lease.signal.aborted){
186
+ const code=reason?.code??"ADS_RUN_CANCELLED";
187
+ raw={...raw,ok:false,current:false,diagnostics:[...(raw.diagnostics??[]),{rule:code==="ADS_SOURCE_CHANGED_DURING_RUN"?"source-changed-during-run":"execution-cancelled",code,message:reason?.message??"The owning request was cancelled or disconnected.",...(record.sourceChange?{sourceChange:{...record.sourceChange,files:lease.sourceChanges??record.sourceChange.files}}:{})}]};
188
+ if(raw.acceptance)raw.acceptance={...raw.acceptance,status:"not_established"};
189
+ record.code=code;
190
+ }
191
+ if(raw.ok&&!lease.signal.aborted)try{for(const commit of lease.commits){
192
+ const baseline=path.basename(commit.file);
193
+ if(!/^(?:acceptance|validation)-baseline\.json$/.test(baseline)||path.dirname(commit.file)!==path.join(root,".ds"))throw new Error("Invalid deferred baseline target.");
194
+ const previous=existsSync(commit.file)?readFileSync(commit.file,"utf8"):null;
195
+ write({runId,previous},".baseline");record.baseline={file:baseline};write(record);
196
+ const temporary=`${commit.file}.${runId}.tmp`;
197
+ try{writeFileSync(temporary,JSON.stringify({...commit.value,executionRunId:runId}));renameSync(temporary,commit.file);}finally{rmSync(temporary,{force:true});}
198
+ }}catch(e){raw={...raw,ok:false,diagnostics:[...(raw.diagnostics??[]),{rule:"validation-baseline",message:e.message}]};}
199
+ if(!raw.ok&&raw.acceptance)raw.acceptance={...raw.acceptance,status:"not_established"};
200
+ record.state=lease.signal.aborted?(record.sourceChange?"source_changed":"cancelled"):raw.ok?"completed":"failed";
201
+ record.completedAt=new Date().toISOString();
202
+ if(raw.scope)record.scope=raw.scope;
203
+ if(raw.selection?.units)record.units=raw.selection.units;
204
+ const summary=results.save(kind,{...raw,execution:{...record,children:undefined,processOwner:undefined}},{resultId:runId});
205
+ write(record);rmSync(path.join(directory,`${runId}.baseline.json`),{force:true});
206
+ return {...summary,...(!raw.ok?{isError:true}:{})};
207
+ }finally{
208
+ stopFence?.();lease.signal.removeEventListener("abort",stopping);
209
+ if(shared.active===lease)shared.active=undefined;
210
+ finish();emit();
211
+ try{results.collect({protectedIds:[runId,...journalEntries().filter(row=>["running","stopping"].includes(row.state)&&ownerAlive(row)).map(row=>row.runId)]});}catch(e){process.stderr.write(`ads mcp: execution collection failed: ${e.message}\n`);}
212
+ }
213
+ },
214
+ async close(){
215
+ closed=true;const pending=shared.active;
216
+ if(pending?.record.instanceId===instanceId){pending.abort.abort(error("ADS_RUN_INTERRUPTED","ADS is stopping."));await pending.done;}
217
+ shared.observers.delete(onChange);if(!shared.observers.size&&!shared.active)processes.delete(root);
218
+ },
219
+ };
220
+ }
@@ -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 },
@@ -53,6 +52,7 @@ function summary(value, storageWarning) {
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)),
55
54
  failureCount: value.failureCount ?? failureRows.length, resourceUri,
55
+ ...(value.execution?{execution:compactRow(value.execution,1100)}:{}),
56
56
  next: value.detailsUnavailable ? null : { tool: "ads_results", arguments: { resultId, section, ...(section === "outcomes" && failedOutcomes.length ? { status: "not_passed" } : {}) } },
57
57
  ...((storageWarning ?? value.storageWarning) ? { storageWarning: storageWarning ?? value.storageWarning } : {}), byteLimit: resultBudgets.summary };
58
58
  if (jsonBytes(result) > resultBudgets.summary) {
@@ -70,60 +70,119 @@ function summary(value, storageWarning) {
70
70
  return result;
71
71
  }
72
72
 
73
- /** One immutable, replaceable snapshot per execution kind. No result history. */
74
- export function createExecutionResults(root) {
73
+ export const defaultResultRetention = {maxRuns:50,maxAgeDays:7,maxBytesMb:256};
74
+ /** Immutable run snapshots plus bounded latest indexes; no history lives in heap. */
75
+ export function createExecutionResults(root,{retention=()=>defaultResultRetention}={}) {
75
76
  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`); }
77
+ const folder = path.join(root, ".ds/tool-results"), history=path.join(folder,"runs"),memory=new Map();
78
+ let collection={overBudget:false};
79
+ const settings=()=>({...defaultResultRetention,...(typeof retention==="function"?retention():retention)});
80
+ const file=kind=>path.join(folder,`${kind}.json`);
81
+ function readJson(target,limit=maxStoredBytes) {
82
+ 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;}
83
+ }
84
+ function atomic(target,value) {
85
+ let ancestor=path.dirname(target);
86
+ while(!existsSync(ancestor))ancestor=path.dirname(ancestor);
87
+ if(realpathSync(ancestor)!==ancestor)throw new Error("Result output cannot resolve through a symlink.");
88
+ mkdirSync(path.dirname(target),{recursive:true});
89
+ if(realpathSync(path.dirname(target))!==path.dirname(target))throw new Error("Result output cannot resolve through a symlink.");
90
+ const staged=`${target}.${randomUUID()}.tmp`;
91
+ try {writeFileSync(staged,JSON.stringify(value));renameSync(staged,target);}finally{rmSync(staged,{force:true});}
92
+ }
93
+ function entries(){
94
+ const rows=readJson(path.join(folder,"index.json"),4*1024*1024)?.entries;
95
+ 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)):[]})):[];
96
+ }
97
+ function valid(value){return value?.schemaVersion===1&&kinds.includes(value.kind)&&uuid(value.resultId)&&resultSections.every(section=>Array.isArray(value.sections?.[section]));}
78
98
  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; }
99
+ const pending=memory.get(kind);if(pending?.memoryOnly)return pending.value;
100
+ const value=readJson(file(kind));return valid(value)?value:undefined;
87
101
  }
88
102
  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;
103
+ if(!uuid(resultId))throw new Error("Use an exact resultId returned by an execution summary.");
104
+ const value=readJson(path.join(history,`${resultId}.json`))??kinds.map(read).find(value=>value?.resultId===resultId);
105
+ if(valid(value))return value;
106
+ 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"});
107
+ throw Object.assign(new Error("Execution result is unavailable. Use an exact retained run/result ID."),{code:"ADS_RESULT_UNAVAILABLE"});
108
+ }
109
+ function bytes(directory) {
110
+ 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;}
111
+ }
112
+ function removeOwned(relative) {
113
+ if(typeof relative!=="string"||!/^\.ds\/(?:verification|investigation-runs)\/[a-f0-9-]{36}(?:\.json)?$/.test(relative))return;
114
+ const target=path.join(root,relative);
115
+ try {if(realpathSync(target)===target)rmSync(target,{recursive:true,force:true});}catch{/* Already collected. */}
93
116
  }
94
117
  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);
118
+ has(id){try{find(id);return true;}catch{return false;}},
119
+ save(kind,raw,{resultId=randomUUID()}={}) {
120
+ if(!kinds.includes(kind)||!uuid(resultId))throw new Error("Unknown execution kind or invalid result ID.");
121
+ if(this.has(resultId))throw new Error("Execution result IDs are immutable.");
122
+ const value=snapshot(kind,raw,resultId);
123
+ if(Buffer.byteLength(JSON.stringify(value))>maxStoredBytes){
124
+ const preview=summary(value);value.failurePreview=preview.failures;value.failureCount=preview.failureCount;
125
+ value.sections=Object.fromEntries(resultSections.map(section=>[section,[]]));value.acceptance=preview.acceptance;delete value.investigation;
126
+ 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
127
  }
128
+ const outcomes=raw.results??raw.behavior?.results??(raw.checks??[]).flatMap(check=>check.results??[]);
129
+ 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
130
  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.";
131
+ try{
132
+ atomic(path.join(history,`${resultId}.json`),value);atomic(file(kind),value);
133
+ atomic(path.join(folder,"index.json"),{schemaVersion:1,entries:[...entries(),{resultId,kind,createdAt:value.createdAt,owned,bytes:Buffer.byteLength(JSON.stringify(value))}]});
134
+ memory.set(kind,{memoryOnly:false});
135
+ }catch{
136
+ 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.";
137
+ }
138
+ return summary(value,storageWarning);
139
+ },
140
+ latest(kind){const value=read(kind);return value?summary(value,memory.get(kind)?.memoryOnly?"Result details are in server memory only.":undefined):null;},
141
+ retentionStatus(){return {...settings(),...collection};},
142
+ collect({protectedIds=[]}={}) {
143
+ if(existsSync(history)&&realpathSync(history)!==history)throw new Error("Result archive cannot resolve through a symlink.");
144
+ 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));
145
+ const kept=[],removed=[];let used=0;
146
+ for(const entry of all){
147
+ const size=entry.bytes+(entry.owned??[]).reduce((n,item)=>n+bytes(path.join(root,item)),0);
148
+ const expired=Date.now()-Date.parse(entry.createdAt)>policy.maxAgeDays*86400000;
149
+ if(!protectedSet.has(entry.resultId)&&(expired||kept.length>=policy.maxRuns||used+size>policy.maxBytesMb*1024*1024)){removed.push(entry);continue;}
150
+ kept.push(entry);used+=size;
151
+ }
152
+ const retainedOwned=new Set(kept.flatMap(entry=>entry.owned??[]));
153
+ if(removed.length){
154
+ const expired=readJson(path.join(folder,"expired.json"))?.ids??[];
155
+ atomic(path.join(folder,"expired.json"),{ids:[...new Set([...expired,...removed.map(entry=>entry.resultId)])].slice(-4096)});
156
+ for(const entry of removed){
157
+ rmSync(path.join(history,`${entry.resultId}.json`),{force:true});
158
+ const journal=path.join(root,".ds/execution-runs",`${entry.resultId}.json`);
159
+ if(!protectedSet.has(entry.resultId)&&(!existsSync(journal)||realpathSync(journal)===journal))rmSync(journal,{force:true});
160
+ rmSync(path.join(root,".ds/execution-runs",`${entry.resultId}.baseline.json`),{force:true});
161
+ for(const owned of entry.owned??[])if(!retainedOwned.has(owned))removeOwned(owned);
162
+ 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});}
163
+ }
164
+ const index=path.join(root,".ds/investigations.json"),investigations=readJson(index,2*1024*1024);
165
+ if(investigations?.bundles){
166
+ 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")));
167
+ investigations.bundles=Object.fromEntries(Object.entries(investigations.bundles).filter(([,value])=>!expiredRuns.has(value.runId)));
168
+ atomic(index,investigations);
169
+ }
170
+ atomic(path.join(folder,"index.json"),{schemaVersion:1,entries:kept});
171
+ }
172
+ // Orphan reports from abandoned executions are collected only after the age
173
+ // window and while no run is active. Never inspect arbitrary temp folders.
174
+ if(!protectedIds.length){
175
+ const reports=path.join(root,".ds/verification");
176
+ if(existsSync(reports)&&realpathSync(reports)===reports)for(const name of readdirSync(reports)){
177
+ const rel=`.ds/verification/${name}`,target=path.join(root,rel);
178
+ if(uuid(name)&&!retainedOwned.has(rel)&&Date.now()-lstatSync(target).mtimeMs>policy.maxAgeDays*86400000)removeOwned(rel);
179
+ }
121
180
  }
122
- return summary(value, storageWarning);
181
+ collection={retainedRuns:kept.length,retainedBytes:used,overBudget:used>policy.maxBytesMb*1024*1024||kept.length>policy.maxRuns};
182
+ return collection;
123
183
  },
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"); },
184
+ 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}))};},
185
+ fingerprint(){return [...kinds.map(kind=>read(kind)?.resultId??`${kind}:missing`),...entries().map(entry=>entry.resultId)].join("\n");},
127
186
  page({ resultId, section = "outcomes", status = "all", cursor, limit, recordIndex, offset, chars } = {}) {
128
187
  const value = find(resultId);
129
188
  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));