@reqvire-org/ads 0.3.39 → 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 (43) hide show
  1. package/dist/bun-compiler.mjs +1 -1
  2. package/dist/config.mjs +4 -1
  3. package/dist/investigations.mjs +27 -8
  4. package/dist/mcp/build-status.mjs +27 -16
  5. package/dist/mcp/context.mjs +1 -1
  6. package/dist/mcp/drafts.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 +107 -48
  10. package/dist/mcp/mutations.mjs +2 -0
  11. package/dist/mcp/preview-widget.bundle.js +2 -2
  12. package/dist/mcp/resource-loader.js +3 -2
  13. package/dist/mcp/server.mjs +42 -13
  14. package/dist/preview-failure.mjs +20 -0
  15. package/dist/preview-resources.mjs +69 -21
  16. package/dist/scenarios-compiler.mjs +7 -6
  17. package/dist/showcase/client.bundle.js +43 -41
  18. package/dist/showcase/index.html +15 -1
  19. package/dist/showcase/preview-state.js +2 -1
  20. package/dist/showcase/style.css +4 -1
  21. package/dist/skills/ads-break-ui/references/behaviors.md +4 -5
  22. package/dist/skills/ads-break-ui/references/evidence.md +12 -8
  23. package/dist/skills/ads-break-ui/references/validation.md +33 -0
  24. package/dist/skills/ads-designer/references/behaviors.md +4 -5
  25. package/dist/skills/ads-designer/references/evidence.md +12 -8
  26. package/dist/skills/ads-designer/references/validation.md +33 -0
  27. package/dist/skills/ads-import/references/behaviors.md +4 -5
  28. package/dist/skills/ads-import/references/evidence.md +12 -8
  29. package/dist/skills/ads-import/references/validation.md +33 -0
  30. package/dist/skills/ads-motion/references/behaviors.md +4 -5
  31. package/dist/skills/ads-motion/references/evidence.md +12 -8
  32. package/dist/skills/ads-motion/references/validation.md +33 -0
  33. package/dist/skills/ads-port/references/behaviors.md +4 -5
  34. package/dist/skills/ads-port/references/evidence.md +12 -8
  35. package/dist/skills/ads-port/references/validation.md +33 -0
  36. package/dist/validation-checks.mjs +6 -2
  37. package/dist/validation.mjs +8 -2
  38. package/dist/verification.mjs +7 -3
  39. package/docs/ARCHITECTURE.md +21 -3
  40. package/docs/CHANGELOG.md +40 -28
  41. package/docs/MCP.md +66 -12
  42. package/docs/plans/execution-coordination.md +57 -0
  43. package/package.json +1 -1
@@ -8,6 +8,6 @@ import { checkCandidate } from "./validation-checks.mjs";
8
8
  export function compilePreviews(directory=process.cwd(),{watched=false}={}) {
9
9
  const root=path.resolve(directory);
10
10
  return runScenarioCompiler(root,{watched,compilerFiles:[import.meta.filename,...["preview-bun.mjs","preview-imports.mjs","bun-worker.mjs"].map(file=>fileURLToPath(new URL(file,import.meta.url)))],
11
- async validate(){const result=await checkCandidate(root);if(!result.ok)throw new Error(result.diagnostics.map(item=>`${item.file}:${item.line??1}: ${item.rule}: ${item.message}`).join("\n"));},buildGraph:createBunPreviewBuilder()});
11
+ async validate(){const result=await checkCandidate(root);if(!result.ok)throw Object.assign(new Error("ADS project validation failed."),{diagnostics:result.diagnostics});},buildGraph:createBunPreviewBuilder()});
12
12
  }
13
13
  if(process.argv[1]&&path.resolve(process.argv[1])===fileURLToPath(import.meta.url))await compilePreviews(process.cwd(),{watched:process.argv.includes("--watch")});
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);
@@ -7,15 +7,18 @@ import { previewSourceRevision } from "../preview-inputs.mjs";
7
7
  import { readPreviewManifest } from "../preview-resources.mjs";
8
8
  import { livePreviewOptions, previewArtifactPath, withPreviewSession } from "../preview-scope.mjs";
9
9
 
10
+ import { previewFailureTitle, previewDiagnosticText } from "../preview-failure.mjs";
11
+
10
12
  export const BUILD_URI = "ads://project/build";
11
13
  export const buildStatusFile = (root) => path.join(root, ".ds/build-status.json");
12
14
  const maxBytes = 256 * 1024;
13
15
  const diagnostic = z.object({ message: z.string().max(4000), file: z.string().max(1000).optional(), line: z.number().int().positive().optional(), column: z.number().int().positive().optional(), plugin: z.string().max(200).optional(), code: z.string().max(100).optional() }).strict();
14
- const preview = z.object({ id: z.string().max(256), state: z.enum(["idle", "building", "ready", "error"]), revision: z.number().int().nonnegative(), lastSuccessfulRevision: z.number().int().positive().nullable(), artifactDigest: z.string().regex(/^sha256:[a-f0-9]{64}$/).nullable(), sourceRevision:z.string().regex(/^[a-f0-9]{64}$/).optional(), diagnostics: z.array(diagnostic).max(20), diagnosticSet: z.number().int().nonnegative().optional() }).strict();
16
+ const failureSchema=z.object({scope:z.enum(["project","graph","scenario"]),phase:z.enum(["validation","discovery","build"])}).strict();
17
+ const preview = z.object({ id: z.string().max(256), state: z.enum(["idle", "building", "ready", "error"]), revision: z.number().int().nonnegative(), lastSuccessfulRevision: z.number().int().positive().nullable(), artifactDigest: z.string().regex(/^sha256:[a-f0-9]{64}$/).nullable(), sourceRevision:z.string().regex(/^[a-f0-9]{64}$/).optional(), diagnostics: z.array(diagnostic).max(20), diagnosticSet: z.number().int().nonnegative().optional(), failure:failureSchema.optional() }).strict();
15
18
  const progressSchema = z.object({ phase: z.enum(["queued", "validation", "compilation", "validation-and-compilation", "publication", "idle"]), startedAt: z.string().datetime(), updatedAt: z.string().datetime() }).strict();
16
19
  const liveSchema = z.object({ revision: z.string().regex(/^[a-f0-9]{64}$/), sourceRevision: z.string().regex(/^[a-f0-9]{64}$/) }).strict();
17
20
  const warmupSchema=z.object({state:z.enum(["warming","ready","error"]),completed:z.number().int().nonnegative(),total:z.number().int().nonnegative(),failed:z.number().int().nonnegative(),active:z.string().max(256).optional()}).strict();
18
- const snapshot = z.object({ schemaVersion: z.literal(1), session: z.string().regex(/^[\w-]{1,100}$/), sequence: z.number().int().nonnegative(), updatedAt: z.string().datetime(), progress: progressSchema.optional(), warmup:warmupSchema.optional(), live: liveSchema.optional(), previews: z.array(preview), diagnostics: z.array(diagnostic).max(20).optional(), diagnosticSets: z.array(z.array(diagnostic).max(20)).optional() }).strict().refine(value => value.previews.every(entry => entry.diagnosticSet === undefined || value.diagnosticSets?.[entry.diagnosticSet]), "Invalid shared diagnostic reference.");
21
+ const snapshot = z.object({ failure:failureSchema.optional(), schemaVersion: z.literal(1), session: z.string().regex(/^[\w-]{1,100}$/), sequence: z.number().int().nonnegative(), updatedAt: z.string().datetime(), progress: progressSchema.optional(), warmup:warmupSchema.optional(), live: liveSchema.optional(), previews: z.array(preview), diagnostics: z.array(diagnostic).max(20).optional(), diagnosticSets: z.array(z.array(diagnostic).max(20)).optional() }).strict().refine(value => value.previews.every(entry => entry.diagnosticSet === undefined || value.diagnosticSets?.[entry.diagnosticSet]), "Invalid shared diagnostic reference.");
19
22
  export const artifactDigest = (file) => {
20
23
  if (realpathSync(file) !== file) throw new Error("Preview output cannot resolve through a symlink.");
21
24
  if (statSync(file).size > 2 * 1024 * 1024) throw new Error("Preview exceeds 2 MiB.");
@@ -28,10 +31,15 @@ function normalizeDiagnostic(root, error) {
28
31
  const file = typeof source === "string" ? source.split("?")[0] : null;
29
32
  const line = location?.line ?? error?.line;
30
33
  const column = location?.column !== undefined ? location.column + 1 : error?.column;
31
- return { message: String(error?.message ?? error).slice(0, 4000),
34
+ return { message: ((typeof error?.rule === "string" ? `${error.rule}: ` : "")+String(error?.message ?? error)).slice(0, 4000),
32
35
  ...(file ? { file: (path.isAbsolute(file) ? path.relative(root, file) : file).replaceAll("\\", "/").slice(0, 1000) } : {}),
33
36
  ...(Number.isInteger(line) && line > 0 ? { line } : {}), ...(Number.isInteger(column) && column > 0 ? { column } : {}),
34
- ...(typeof error?.plugin === "string" ? { plugin: error.plugin.slice(0, 200) } : {}), ...(typeof error?.code === "string" ? { code: error.code.slice(0, 100) } : {}) };
37
+ ...(typeof error?.plugin === "string" ? { plugin: error.plugin.slice(0, 200) } : {}), ...(typeof (error?.code??error?.rule) === "string" ? { code: (error.code??error.rule).slice(0, 100) } : {}) };
38
+ }
39
+
40
+ function normalizedDiagnostics(root, value) {
41
+ const errors=Array.isArray(value)?value:Array.isArray(value?.diagnostics)?value.diagnostics:[value];
42
+ return errors.slice(0,20).map(error=>normalizeDiagnostic(root,error));
35
43
  }
36
44
 
37
45
  /** One publisher per project compiler; no dependency on a UI framework. */
@@ -42,11 +50,11 @@ export function createBuildReporter(directory, { apps, session = process.env.ADS
42
50
  const entries = new Map(apps.map((app) => [app.id, { id: app.id, state: "idle", revision: 0, lastSuccessfulRevision: null, artifactDigest: null, diagnostics: [] }]));
43
51
  let sequence = 0;
44
52
  let diagnostics = [];
45
- let progress, warmup;
53
+ let progress, warmup, failureContext;
46
54
  let live, batching = 0;
47
55
  function save() {
48
56
  if (batching) return;
49
- const value = { schemaVersion: 1, session, sequence: ++sequence, updatedAt: new Date().toISOString(), previews: [...entries.values()], ...(progress ? { progress } : {}), ...(warmup?{warmup}:{}), ...(live ? { live } : {}), ...(diagnostics.length ? { diagnostics } : {}) };
57
+ const value = { ...(failureContext?{failure:failureContext}:{}), schemaVersion: 1, session, sequence: ++sequence, updatedAt: new Date().toISOString(), previews: [...entries.values()], ...(progress ? { progress } : {}), ...(warmup?{warmup}:{}), ...(live ? { live } : {}), ...(diagnostics.length ? { diagnostics } : {}) };
50
58
  let text = JSON.stringify(snapshot.parse(value));
51
59
  // A shared graph failure applies to every scenario. Store repeated details
52
60
  // once only when necessary; ordinary reports retain inline diagnostics.
@@ -84,13 +92,14 @@ export function createBuildReporter(directory, { apps, session = process.env.ADS
84
92
  save();
85
93
  },
86
94
  failure(error) {
87
- diagnostics = (Array.isArray(error) ? error : [error]).slice(0, 20).map(error => normalizeDiagnostic(root, error));
95
+ diagnostics = normalizedDiagnostics(root,error);
96
+ failureContext=error?.previewFailure??{scope:"project",phase:"discovery"};
88
97
  for (const value of entries.values()) { value.state = "error"; ++value.revision; value.diagnostics = []; }
89
98
  save();
90
99
  },
91
100
  clearFailure() {
92
101
  if (!diagnostics.length) return;
93
- diagnostics = [];
102
+ diagnostics = [];failureContext=undefined;
94
103
  for (const value of entries.values()) if (value.state === "error" && !value.diagnostics.length) value.state = "idle";
95
104
  save();
96
105
  },
@@ -106,7 +115,7 @@ export function createBuildReporter(directory, { apps, session = process.env.ADS
106
115
  value.sourceRevision = sourceRevision;
107
116
  value.state = "building";
108
117
  value.revision++;
109
- value.diagnostics = [];
118
+ value.diagnostics = [];value.failure=undefined;
110
119
  save();
111
120
  return value.revision;
112
121
  },
@@ -117,7 +126,7 @@ export function createBuildReporter(directory, { apps, session = process.env.ADS
117
126
  value.artifactDigest = artifactDigest(projectPath(root, app.file, "mcp.apps.file"));
118
127
  value.state = "ready";
119
128
  value.lastSuccessfulRevision = revision;
120
- value.diagnostics = [];
129
+ value.diagnostics = [];value.failure=undefined;
121
130
  save();
122
131
  return true;
123
132
  },
@@ -125,7 +134,8 @@ export function createBuildReporter(directory, { apps, session = process.env.ADS
125
134
  const value = entry(id, revision);
126
135
  if (!value) return false;
127
136
  value.state = "error";
128
- value.diagnostics = (Array.isArray(failure) ? failure : [failure]).slice(0, 20).map((error) => normalizeDiagnostic(root, error));
137
+ value.diagnostics = normalizedDiagnostics(root,failure);
138
+ value.failure=failure?.previewFailure??{scope:"scenario",phase:"build"};
129
139
  save();
130
140
  return true;
131
141
  },
@@ -166,8 +176,9 @@ export function inspectBuildStatus(root, config, { session, previewSession, proc
166
176
  const previews = config.apps.map((app) => {
167
177
  const value = report?.previews.find((entry) => entry.id === app.id);
168
178
  let state = value?.state ?? "unreported";
179
+ let failure=value?.failure;
169
180
  let diagnostics = value?.diagnosticSet !== undefined ? report.diagnosticSets[value.diagnosticSet] : value?.diagnostics ?? [];
170
- if (report?.diagnostics?.length) { state = "error"; diagnostics = [...report.diagnostics, ...diagnostics].slice(0, 20); }
181
+ if (report?.diagnostics?.length) { failure=report.failure??{scope:"project",phase:"discovery"}; state = "error"; diagnostics = [...report.diagnostics, ...diagnostics].slice(0, 20); }
171
182
  const artifact = path.resolve(root, previewArtifactPath(options, app.file));
172
183
  const available = existsSync(artifact);
173
184
  if (reportError) { state = "error"; diagnostics = [{ message: reportError }]; }
@@ -185,10 +196,10 @@ export function inspectBuildStatus(root, config, { session, previewSession, proc
185
196
  const current = state === "ready";
186
197
  return { id: app.id, state, session: report?.session ?? null, revision: value?.revision ?? null, lastSuccessfulRevision: value?.lastSuccessfulRevision ?? null,
187
198
  ...(!current && state !== "error" && live?.scenarios.has(app.id) ? { live: { revision: live.revision, sourceRevision: live.sourceRevision, validated: false } } : {}),
188
- current, stale: state === "unreported" ? null : !current, available, ...(value?.sourceRevision ? {sourceRevision:value.sourceRevision} : {}), diagnostics };
199
+ ...(state==="error"&&failure?{failure}:{}), current, stale: state === "unreported" ? null : !current, available, ...(value?.sourceRevision ? {sourceRevision:value.sourceRevision} : {}), diagnostics };
189
200
  });
190
201
  const state = reportError || report?.diagnostics?.length || previews.some((entry) => entry.state === "error") ? "error" : previews.some((entry) => entry.state === "building") ? "building" : previews.some((entry) => entry.state === "unreported") ? "unreported" : previews.some(entry => entry.current) ? "ready" : previews.length ? "idle" : "disabled";
191
- return { state, reported: Boolean(report), session: report?.session ?? null, sequence: report?.sequence ?? null, updatedAt: report?.updatedAt ?? null, ...(report?.progress ? { progress: report.progress } : {}), ...(report?.warmup?{warmup:report.warmup}:{}), previews, ...(report?.diagnostics?.length ? { diagnostics: report.diagnostics } : {}), resourceUri: BUILD_URI };
202
+ return { ...(report?.failure?{failure:report.failure}:{}), state, reported: Boolean(report), session: report?.session ?? null, sequence: report?.sequence ?? null, updatedAt: report?.updatedAt ?? null, ...(report?.progress ? { progress: report.progress } : {}), ...(report?.warmup?{warmup:report.warmup}:{}), previews, ...(report?.diagnostics?.length ? { diagnostics: report.diagnostics } : {}), resourceUri: BUILD_URI };
192
203
  }
193
204
 
194
205
  export class PreviewBuildError extends Error {
@@ -207,6 +218,6 @@ export function summarizeBuild(build) {
207
218
 
208
219
  export function buildFailure(build) {
209
220
  const summary = summarizeBuild(build);
210
- const details = summary.diagnostics.map((entry) => `${entry.file ?? ""}${entry.line ? `:${entry.line}` : ""}${entry.file ? ": " : ""}${entry.message}`).join("\n");
211
- return new PreviewBuildError(`Preview build failed. ${details}${summary.diagnosticsTruncated ? `\nMore diagnostic detail: ${BUILD_URI}` : ""}`, summary);
221
+ const details = previewDiagnosticText(summary.diagnostics);
222
+ return new PreviewBuildError(`${previewFailureTitle(summary)}. ${details}${summary.diagnosticsTruncated ? `\nMore diagnostic detail: ${BUILD_URI}` : ""}`, summary);
212
223
  }
@@ -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
 
@@ -166,7 +166,7 @@ export function createDraftController(directory, { edits, startPreview, prewarm
166
166
  if (closed || previews.get(id) !== session) return;
167
167
  const scenarios = report.previews.filter(item => item.revision > 0 || item.live || item.state === "error").map(item => ({ id: item.id, state: item.live ? "checking" : item.state,
168
168
  building: ["idle", "building"].includes(item.state), current: item.current, stale: item.stale, revision: item.revision,
169
- ...(item.live ? { live: item.live } : {}), diagnosticCount: item.diagnostics.length }));
169
+ ...(item.live ? { live: item.live } : {}), ...(item.failure ? {failure:item.failure} : {}), diagnosticCount: item.diagnostics.length }));
170
170
  const building = scenarios.some(item => item.building);
171
171
  const state = scenarios.some(item => item.state === "error") ? "error" : building ? scenarios.some(item => item.live) ? "checking" : "building" : scenarios.some(item => item.current) ? "ready" : report.state;
172
172
  const build = { state, building, current: state === "ready", stale: state === "ready" ? false : scenarios.length ? true : null,
@@ -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
+ }