@reqvire-org/ads 0.3.32 → 0.3.34

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 (84) hide show
  1. package/README.md +9 -0
  2. package/dist/behavior-libraries.mjs +93 -0
  3. package/dist/behaviors.mjs +0 -6
  4. package/dist/bootstrap-ds/ds.config.json +1 -0
  5. package/dist/bootstrap-ds/vite.config.ts +2 -1
  6. package/dist/boundaries.mjs +2 -0
  7. package/dist/capture.mjs +8 -6
  8. package/dist/check.mjs +2 -0
  9. package/dist/config.mjs +9 -2
  10. package/dist/draft-boundary.mjs +27 -0
  11. package/dist/draft-workspace.mjs +10 -0
  12. package/dist/lint-config.mjs +8 -0
  13. package/dist/mcp/build-status.mjs +1 -1
  14. package/dist/mcp/catalog.mjs +4 -2
  15. package/dist/mcp/context.mjs +2 -2
  16. package/dist/mcp/draft-discovery.mjs +55 -0
  17. package/dist/mcp/draft-exports.mjs +40 -0
  18. package/dist/mcp/drafts.mjs +460 -0
  19. package/dist/mcp/edit-preparation.mjs +8 -7
  20. package/dist/mcp/execution-results.mjs +2 -0
  21. package/dist/mcp/mutations.mjs +6 -2
  22. package/dist/mcp/preview-watch.mjs +24 -5
  23. package/dist/mcp/preview-widget.bundle.js +14 -14
  24. package/dist/mcp/prompts.mjs +3 -2
  25. package/dist/mcp/server.mjs +178 -39
  26. package/dist/mcp/widget.bundle.js +1 -1
  27. package/dist/preview-files.mjs +2 -0
  28. package/dist/scenario-inspector.mjs +5 -5
  29. package/dist/scenario-program.mjs +36 -0
  30. package/dist/scenario-registry.mjs +90 -0
  31. package/dist/scenarios-compiler.mjs +68 -22
  32. package/dist/scenarios-vite.d.mts +1 -0
  33. package/dist/scenarios-vite.mjs +1 -0
  34. package/dist/scenarios.mjs +2 -1
  35. package/dist/showcase/client.bundle.js +28 -28
  36. package/dist/showcase/comparison.js +45 -0
  37. package/dist/showcase/draft-navigation.js +41 -0
  38. package/dist/showcase/preview-state.js +19 -0
  39. package/dist/showcase/style.css +5 -0
  40. package/dist/skills/README.md +5 -0
  41. package/dist/skills/ads-break-ui/SKILL.md +26 -0
  42. package/dist/skills/ads-break-ui/references/behaviors.md +10 -0
  43. package/dist/skills/ads-break-ui/references/captures.md +7 -0
  44. package/dist/skills/ads-break-ui/references/drafts.md +146 -0
  45. package/dist/skills/ads-break-ui/references/guarded-editing.md +6 -0
  46. package/dist/skills/ads-break-ui/references/validation.md +6 -0
  47. package/dist/skills/ads-designer/SKILL.md +33 -0
  48. package/dist/skills/ads-designer/assets/bootstrap-ds/ds.config.json +1 -0
  49. package/dist/skills/ads-designer/assets/bootstrap-ds/vite.config.ts +2 -1
  50. package/dist/skills/ads-designer/references/behaviors.md +10 -0
  51. package/dist/skills/ads-designer/references/captures.md +7 -0
  52. package/dist/skills/ads-designer/references/drafts.md +146 -0
  53. package/dist/skills/ads-designer/references/guarded-editing.md +6 -0
  54. package/dist/skills/ads-designer/references/validation.md +6 -0
  55. package/dist/skills/ads-import/SKILL.md +30 -0
  56. package/dist/skills/ads-import/references/behaviors.md +10 -0
  57. package/dist/skills/ads-import/references/captures.md +7 -0
  58. package/dist/skills/ads-import/references/drafts.md +146 -0
  59. package/dist/skills/ads-import/references/guarded-editing.md +6 -0
  60. package/dist/skills/ads-import/references/validation.md +6 -0
  61. package/dist/skills/ads-motion/SKILL.md +26 -0
  62. package/dist/skills/ads-motion/references/behaviors.md +10 -0
  63. package/dist/skills/ads-motion/references/captures.md +7 -0
  64. package/dist/skills/ads-motion/references/drafts.md +146 -0
  65. package/dist/skills/ads-motion/references/guarded-editing.md +6 -0
  66. package/dist/skills/ads-motion/references/validation.md +6 -0
  67. package/dist/skills/ads-port/SKILL.md +34 -1
  68. package/dist/skills/ads-port/references/behaviors.md +10 -0
  69. package/dist/skills/ads-port/references/captures.md +7 -0
  70. package/dist/skills/ads-port/references/drafts.md +146 -0
  71. package/dist/skills/ads-port/references/guarded-editing.md +6 -0
  72. package/dist/skills/ads-port/references/native-implementation.md +14 -1
  73. package/dist/skills/ads-port/references/validation.md +6 -0
  74. package/dist/unit-contracts.mjs +2 -2
  75. package/dist/units.mjs +6 -0
  76. package/dist/verification/browser.d.mts +27 -0
  77. package/dist/verification.mjs +3 -0
  78. package/docs/ADS.md +13 -0
  79. package/docs/ARCHITECTURE.md +94 -0
  80. package/docs/CHANGELOG.md +111 -0
  81. package/docs/CONTRACTS.md +8 -0
  82. package/docs/GUIDE.md +46 -9
  83. package/docs/MCP.md +90 -0
  84. package/package.json +6 -4
@@ -0,0 +1,460 @@
1
+ import { createHash, randomUUID } from "node:crypto";
2
+ import { cpSync, existsSync, lstatSync, mkdirSync, readFileSync, readdirSync, realpathSync, renameSync, rmSync, symlinkSync, watch, writeFileSync } from "node:fs";
3
+ import path from "node:path";
4
+ import { z } from "zod";
5
+ import { loadConfig, isInside } from "../config.mjs";
6
+ import { DRAFT_DIRECTORY } from "../draft-boundary.mjs";
7
+ import { inspectUnits, validateUnitId } from "../units.mjs";
8
+ import { validationInputFiles } from "../validation-inputs.mjs";
9
+ import { textDiff } from "./text-diff.mjs";
10
+ import { storePreparedPatch, preparedFileDiff } from "./edit-preparation.mjs";
11
+ import { mergeDraftExports, isDraftExportEntry } from "./draft-exports.mjs";
12
+ import { inspectTokens } from "../tokens.mjs";
13
+ import { previewFileIgnored, previewWatchDirectories } from "../preview-files.mjs";
14
+ import { createDraftDiscovery } from "./draft-discovery.mjs";
15
+
16
+ export const DRAFTS_URI = "ads://project/drafts";
17
+ const hash = bytes => createHash("sha256").update(bytes).digest("hex");
18
+ const idSchema = z.string().regex(/^[a-z0-9][a-z0-9-]{0,79}$/);
19
+ const relative = z.string().min(1).max(500).refine(value => !path.isAbsolute(value) && !value.includes("\\") && !value.includes("\0") && !value.split("/").some(part => !part || part === "." || part === ".."), "Use a canonical project-relative path.");
20
+ const fileSchema = z.object({ target: relative, source: relative.nullable(), baseline: z.string().regex(/^[a-f0-9]{64}$/).nullable(), unit: z.string().max(256) }).strict();
21
+ const manifestSchema = z.object({ schemaVersion: z.literal(1), id: idSchema, title: z.string().min(1).max(160), units: z.array(z.string().min(1).max(256)).min(1).max(8).refine(values=>new Set(values).size===values.length,"Draft owners must be unique."), dependencies: z.array(idSchema).max(8).refine(values=>new Set(values).size===values.length,"Draft dependencies must be unique.").default([]), tokenGroups:z.array(z.string().min(1).max(160)).max(32).default([]), files: z.array(fileSchema).max(256) }).strict();
22
+ export const draftIdSchema = idSchema;
23
+ export const draftRevisionSchema = z.string().regex(/^[a-f0-9]{64}$/);
24
+
25
+ function safe(root, relativePath) {
26
+ relative.parse(relativePath);
27
+ const target = path.resolve(root, relativePath);
28
+ if (!isInside(root, target) || target === root) throw new Error("Draft paths must stay inside their project or proposal.");
29
+ for (let current = target; isInside(root, current); current = path.dirname(current)) {
30
+ const stat = lstatSync(current, { throwIfNoEntry: false });
31
+ if (stat?.isSymbolicLink() || stat && current === target && (!stat.isFile() || stat.nlink !== 1)) throw new Error("Draft paths require ordinary directories and unlinked regular files.");
32
+ if (current === root) break;
33
+ if (stat && current !== target && !stat.isDirectory()) throw new Error("Invalid draft directory.");
34
+ }
35
+ return target;
36
+ }
37
+ function bytes(file) {
38
+ if (!existsSync(file)) return null;
39
+ const stat = lstatSync(file);
40
+ if (!stat.isFile() || stat.nlink !== 1 || realpathSync(file) !== file || stat.size > 16 * 1024 * 1024) throw new Error("Draft inputs must be ordinary files no larger than 16 MiB.");
41
+ return readFileSync(file);
42
+ }
43
+ const fileHash = content => content === null ? null : hash(content);
44
+ function atomic(file, content) {
45
+ mkdirSync(path.dirname(file), { recursive: true });
46
+ if (realpathSync(path.dirname(file)) !== path.dirname(file)) throw new Error("Draft storage cannot resolve through a symlink.");
47
+ const staging = `${file}.${randomUUID()}.tmp`;
48
+ try { writeFileSync(staging, content); renameSync(staging, file); }
49
+ finally { rmSync(staging, { force: true }); }
50
+ }
51
+ const storedName = target => `files/${target}.ads`;
52
+
53
+ /** Tracked proposal source is separate from disposable compiler state. No Git checkout is required. */
54
+ export function createDraftController(directory, { edits, startPreview, prewarm = false, onChange, scenarioInspector } = {}) {
55
+ const root = path.resolve(directory), storage = path.join(root, DRAFT_DIRECTORY);
56
+ const previews = new Map();
57
+ let active, closed = false;
58
+ let changeTimer, prewarmTimer, prewarming, pendingPrewarm;
59
+ const watchers = new Map();
60
+ let discoveryVersion = 0;
61
+ const discovery = createDraftDiscovery(root, { inspector: scenarioInspector, onChange: () => { ++discoveryVersion; onChange?.(); } });
62
+ const manifestFile = id => safe(root, `${DRAFT_DIRECTORY}/${idSchema.parse(id)}/proposal.ads.draft.json`);
63
+ const save = manifest => atomic(manifestFile(manifest.id), JSON.stringify(manifestSchema.parse(manifest), null, 2) + "\n");
64
+ function read(id) {
65
+ const file = manifestFile(id), content = bytes(file);
66
+ if (!content || content.length > 256 * 1024) throw new Error("Unknown or oversized ADS draft manifest.");
67
+ const manifest = manifestSchema.parse(JSON.parse(content.toString("utf8")));
68
+ if (manifest.id !== id || new Set(manifest.units).size !== manifest.units.length || new Set(manifest.files.map(file => file.target)).size !== manifest.files.length) throw new Error("Draft IDs, units and target paths must be unique and consistent.");
69
+ for (const unit of manifest.units) validateUnitId(unit);
70
+ for (const file of manifest.files) {
71
+ safe(root, file.target);
72
+ if (!manifest.units.includes(file.unit) || file.target.split("/").some(part => [DRAFT_DIRECTORY, ".ds", "node_modules", ".git"].includes(part))) throw new Error("Draft targets must be normal source owned by a declared unit.");
73
+ if (file.source && (!file.source.startsWith("files/") || !file.source.endsWith(".ads"))) throw new Error("Draft sources must use the non-importable .ads extension under files/.");
74
+ if (file.source) safe(path.dirname(manifestFile(id)), file.source);
75
+ }
76
+ return manifest;
77
+ }
78
+ // Keep machine execution records out of Git; proposal source/manifests are durable.
79
+ const eventFile = path.join(root, ".ds/draft-events.json");
80
+ function events() { try { const value = JSON.parse(bytes(eventFile)?.toString() ?? "[]"); return Array.isArray(value) ? value.slice(-100) : []; } catch { return []; } }
81
+ function event(id, revision, state, extra = {}) {
82
+ const value = { id: randomUUID(), draft: id, revision, state, at: new Date().toISOString(), ...extra };
83
+ atomic(eventFile, JSON.stringify([...events(), value].slice(-100)));
84
+ return value;
85
+ }
86
+ function inspect(id, stack = [], context = {inputs:validationInputFiles(loadConfig(root)),seen:new Set(),memo:new Map()}) {
87
+ if (stack.includes(id)) throw new Error(`Draft dependency cycle: ${[...stack, id].join(" → ")}`);
88
+ if(context.memo.has(id))return context.memo.get(id);
89
+ context.seen.add(id);if(context.seen.size>32||stack.length>16)throw new Error("Draft dependency graph exceeds 32 drafts/16 levels.");
90
+ const manifest = read(id), folder = path.dirname(manifestFile(id));
91
+ const files = manifest.files.map(file => ({ ...file, content: file.source ? bytes(safe(folder, file.source)) : null }));
92
+ if (files.some(file => file.source && file.content === null)) throw new Error("A registered draft source is missing. Use ads_update_draft with content:null to propose deletion.");
93
+ if (files.reduce((size, file) => size + (file.content?.length ?? 0), 0) > 32 * 1024 * 1024) throw new Error("Draft exceeds 32 MiB.");
94
+ const dependencies = [], dependencyErrors = [];
95
+ for(const dependency of manifest.dependencies){
96
+ try{const value=inspect(dependency,[...stack,id],context);dependencies.push(value);dependencyErrors.push(...value.dependencyErrors);}
97
+ catch(error){dependencyErrors.push({draft:dependency,message:error.message});}
98
+ }
99
+ const projectInputs = context.inputs;
100
+ const revision = hash(JSON.stringify([manifest, files.map(file => [file.target, fileHash(file.content)]), dependencies.map(dependency => [dependency.manifest.id, dependency.revision]), dependencyErrors, projectInputs]));
101
+ const changes = files.filter(file => fileHash(file.content) !== file.baseline);
102
+ const conflicts = changes.filter(file => fileHash(bytes(safe(root, file.target))) !== file.baseline).map(file => file.target);
103
+ const result={ manifest, files, changes, dependencies, dependencyErrors, revision, conflicts };context.memo.set(id,result);return result;
104
+ }
105
+ function ids() {
106
+ if (!existsSync(storage)) return [];
107
+ if (realpathSync(storage) !== storage) throw new Error("Draft storage cannot be a symlink.");
108
+ return readdirSync(storage, { withFileTypes: true }).filter(entry => entry.isDirectory() && !entry.isSymbolicLink() && idSchema.safeParse(entry.name).success && existsSync(manifestFile(entry.name))).map(entry => entry.name).sort();
109
+ }
110
+ function summary(value) {
111
+ const { manifest, revision, conflicts, changes } = value;
112
+ const last = events().filter(event => event.draft === manifest.id).at(-1);
113
+ return { id: manifest.id, title: manifest.title, units: manifest.units, dependencies: manifest.dependencies, tokenGroups:manifest.tokenGroups, revision, changes: changes.length, conflicts,
114
+ state: active?.id === manifest.id ? "checking" : value.dependencyErrors.length ? "dependency-error" : conflicts.length ? "conflict" : last?.state === "checking" ? "interrupted" : last?.state === "failed" && last.revision === revision ? "failed" : "draft",
115
+ preview: previewStatus(manifest.id, revision), manifest: path.relative(root, manifestFile(manifest.id)).replaceAll("\\", "/") };
116
+ }
117
+ const scopedBuild = id => `ads://drafts/${id}/resource?uri=${encodeURIComponent("ads://project/build")}`;
118
+ function previewStatus(id, revision) {
119
+ const session = previews.get(id), build = session?.build ?? { state: "unreported", building: false, current: false, stale: null, scenarios: [], resourceUri: scopedBuild(id) };
120
+ if (revision && session?.revision !== revision && build.scenarios.length) return { ...build, state: "queued", building: true, current: false, stale: true,
121
+ scenarios: build.scenarios.map(item => ({ ...item, state: "queued", building: true, current: false, stale: true })) };
122
+ return build;
123
+ }
124
+ function recordBuild(id, session, report) {
125
+ if (closed || previews.get(id) !== session) return;
126
+ 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,
127
+ building: ["idle", "building"].includes(item.state), current: item.current, stale: item.stale, revision: item.revision,
128
+ ...(item.live ? { live: item.live } : {}), diagnosticCount: item.diagnostics.length }));
129
+ const building = scenarios.some(item => item.building);
130
+ 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;
131
+ const build = { state, building, current: state === "ready", stale: state === "ready" ? false : scenarios.length ? true : null,
132
+ session: report.session, sequence: report.sequence, ...(report.progress ? { phase: report.progress.phase } : {}),
133
+ scenarios: scenarios.slice(0, 32), scenarioCount: scenarios.length, resourceUri: scopedBuild(id) };
134
+ if (JSON.stringify(build) === JSON.stringify(session.build)) return;
135
+ session.build = build; ++discoveryVersion; onChange?.();
136
+ }
137
+ function list({ id, unit, query = "", offset = 0, limit = 20 } = {}) {
138
+ const diagnostics = [], all = [];
139
+ let inputs;
140
+ for (const selected of id ? [id] : ids()) {
141
+ try {
142
+ inputs??=validationInputFiles(loadConfig(root));
143
+ const value = inspect(selected,[],{inputs,seen:new Set(),memo:new Map()}), item = summary(value);
144
+ diagnostics.push(...value.dependencyErrors.map(error=>({...error,draft:selected,dependency:error.draft})));
145
+ if ((!unit || item.units.includes(unit)) && `${item.id} ${item.title} ${item.units.join(" ")}`.toLowerCase().includes(query.toLowerCase())) all.push(id ? { ...item, files: value.files.slice(offset, offset + limit).map(({content: _content, ...file}) => ({ ...file, source: file.source ? `${DRAFT_DIRECTORY}/${id}/${file.source}` : null })), fileCount: value.files.length, ...(offset + limit < value.files.length ? { nextOffset: offset + limit } : {}) } : item);
146
+ } catch (error) { diagnostics.push({ draft: selected, message: error.message }); }
147
+ }
148
+ return { mode: "auto", total: all.length, drafts: id ? all : all.slice(offset, offset + limit), ...(!id && offset + limit < all.length ? { nextOffset: offset + limit } : {}), diagnostics, events: events().slice(-10), resourceUri: DRAFTS_URI };
149
+ }
150
+ function tokenGroups() {
151
+ const options=loadConfig(root),directory=path.join(options.dsRoot,options.config.tokenDir),groups=new Map();
152
+ for(const token of inspectTokens(root).tokens)for(const definition of token.definitions){const id=path.relative(directory,path.join(root,definition.file)).replaceAll("\\","/").replace(/\.css$/,"");if(!groups.has(id))groups.set(id,{id,file:definition.file,tokens:new Set()});groups.get(id).tokens.add(token.name);}
153
+ return [...groups.values()].map(({tokens,...group})=>({...group,count:tokens.size})).sort((a,b)=>a.id.localeCompare(b.id));
154
+ }
155
+ function create({ units, title, id = randomUUID(), dependencies = [], tokenGroups: selectedGroups = [] }) {
156
+ if (closed) throw new Error("Draft controller is closed.");
157
+ idSchema.parse(id);
158
+ if (existsSync(manifestFile(id))) throw new Error("Draft already exists.");
159
+ const options = loadConfig(root), inventory = inspectUnits(options), files = new Map();
160
+ const groups=selectedGroups.length?tokenGroups():[];
161
+ if(selectedGroups.length&&(!units.includes("tokens")||selectedGroups.some(id=>!groups.some(group=>group.id===id))))throw new Error("Choose discovered tokenGroups from ads_tokens and include the tokens owner.");
162
+ for (const unit of units) {
163
+ validateUnitId(unit);
164
+ const owner = inventory.units.find(item => item.id === unit);
165
+ if (!owner && !/^(?:components|patterns|controllers|composition|review)\/.+/.test(unit)) throw new Error("Choose a discovered owner or a new component/pattern/controller/composition/review owner.");
166
+ const paths = [...(owner?.files ?? []), ...(owner?.companionFiles ?? []).map(file => file.path)];
167
+ if (/^(?:components|patterns|controllers)\//.test(unit)) paths.push(path.relative(root, path.join(options.dsRoot, options.config.publicEntry)).replaceAll("\\", "/"));
168
+ if (unit.startsWith("review/")) paths.push(path.relative(root, path.join(options.dsRoot, options.config.reviewEntry)).replaceAll("\\", "/"));
169
+ for (const target of paths) if (!files.has(target)) {
170
+ if(unit==="tokens"&&selectedGroups.length&&target.endsWith(".css")&&isInside(path.join(options.dsRoot,options.config.tokenDir),path.join(root,target))&&!groups.some(group=>selectedGroups.includes(group.id)&&group.file===target))continue;
171
+ const content = bytes(safe(root, target));
172
+ if (content === null) continue;
173
+ const source = storedName(target);
174
+ files.set(target, { target, source, baseline: hash(content), unit });
175
+ }
176
+ }
177
+ const manifest = manifestSchema.parse({ schemaVersion: 1, id, title: title ?? units.join(", "), units, dependencies, tokenGroups:selectedGroups, files: [...files.values()] });
178
+ for (const dependency of dependencies) {const value=inspect(dependency,[id]);if(value.dependencyErrors.length)throw new Error(value.dependencyErrors[0].message);}
179
+ for (const file of manifest.files) atomic(safe(path.dirname(manifestFile(id)), file.source), bytes(safe(root, file.target)));
180
+ save(manifest);
181
+ const value = inspect(id); event(id, value.revision, "created");
182
+ reconcileWatches(); queuePrewarm(id);
183
+ return { ...summary(value), directory: `${DRAFT_DIRECTORY}/${id}`, next: "Edit the marked source files, or register new/deleted files with ads_update_draft. Use ads_show_draft, review the rendered result, then ads_accept with its exact revision. Do not finish a design change with unaccepted drafts." };
184
+ }
185
+ function update({ id, revision, changes = [], dependencies }) {
186
+ const value = inspect(id);
187
+ if (value.revision !== revision) throw new Error("Draft revision changed. Read ads_drafts again before editing.");
188
+ const manifest = value.manifest;
189
+ if (dependencies) { for (const dependency of dependencies) {const value=inspect(dependency,[id]);if(value.dependencyErrors.length)throw new Error(value.dependencyErrors[0].message);} manifest.dependencies = dependencies; }
190
+ for (const change of changes) {
191
+ if (!manifest.units.includes(change.unit)) throw new Error("Changes must belong to a declared draft unit.");
192
+ let file = manifest.files.find(file => file.target === change.path);
193
+ if (!file) { file = { target: change.path, source: null, baseline: fileHash(bytes(safe(root, change.path))), unit: change.unit }; manifest.files.push(file); }
194
+ file.unit = change.unit;
195
+ if (change.content === null) file.source = null;
196
+ else {
197
+ file.source ??= storedName(change.path);
198
+ const content = Buffer.from(change.content, change.encoding === "base64" ? "base64" : "utf8");
199
+ atomic(safe(path.dirname(manifestFile(id)), file.source), content);
200
+ }
201
+ }
202
+ save(manifest);
203
+ changed();
204
+ return summary(inspect(id));
205
+ }
206
+ function prepare(id) {
207
+ const value = inspect(id);
208
+ if(value.dependencyErrors.length)throw new Error(`Draft dependency error: ${value.dependencyErrors[0].message}`);
209
+ if (value.conflicts.length) throw new Error(`Draft baseline conflict: ${value.conflicts.join(", ")}`);
210
+ let session = previews.get(id);
211
+ if (!session) {
212
+ const workspace = path.join(root, ".ds/draft-previews", id, "project");
213
+ mkdirSync(workspace, { recursive: true });
214
+ if (realpathSync(workspace) !== workspace) throw new Error("Draft preview workspace cannot be a symlink.");
215
+ session = { workspace, inputs: new Map() }; previews.set(id, session); reconcileWatches();
216
+ }
217
+ const inputs = validationInputFiles(loadConfig(root)), desired = new Map();
218
+ let size = 0;
219
+ for (const [target, digest] of Object.entries(inputs)) if (digest && target !== "installed-dependencies") {
220
+ const content = bytes(safe(root, target));
221
+ if (content !== null) { desired.set(target, content); size += content.length; }
222
+ if (desired.size > 100000 || size > 2 * 1024 ** 3) throw new Error("Draft preview input limit exceeded.");
223
+ }
224
+ const applied = new Map();
225
+ function overlay(proposal) {
226
+ if (proposal.conflicts.length) throw new Error(`Dependency draft conflict: ${proposal.conflicts.join(", ")}`);
227
+ for (const dependency of proposal.dependencies) overlay(dependency);
228
+ for (const file of proposal.changes) {
229
+ const digest = fileHash(file.content);
230
+ if (isDraftExportEntry(file.target, loadConfig(root)) && file.content !== null) {
231
+ const merged = mergeDraftExports(desired.get(file.target)?.toString() ?? "", file.content.toString(), bytes(safe(root,file.target))?.toString() ?? "", file.target, loadConfig(root), proposal.manifest.units);
232
+ desired.set(file.target,Buffer.from(merged.content));
233
+ continue;
234
+ }
235
+ if (applied.has(file.target) && applied.get(file.target) !== digest) throw new Error(`Drafts both change ${file.target}; use one coupled draft for overlapping edits.`);
236
+ applied.set(file.target, digest);
237
+ if (file.content === null) desired.delete(file.target); else desired.set(file.target, file.content);
238
+ }
239
+ }
240
+ overlay(value);
241
+ for (const target of session.inputs.keys()) if (!desired.has(target)) rmSync(safe(session.workspace, target), { force: true });
242
+ for (const [target, content] of desired) if (session.inputs.get(target) !== hash(content)) atomic(safe(session.workspace, target), content);
243
+ session.inputs = new Map([...desired].map(([target, content]) => [target, hash(content)]));
244
+ const modules = path.join(session.workspace, "node_modules");
245
+ if (!existsSync(modules) && existsSync(path.join(root, "node_modules"))) symlinkSync(realpathSync(path.join(root, "node_modules")), modules, process.platform === "win32" ? "junction" : "dir");
246
+ if (!existsSync(path.join(session.workspace, "dist")) && existsSync(path.join(root, "dist/cli.mjs"))) {
247
+ let count=0,total=0;
248
+ cpSync(path.join(root,"dist"),path.join(session.workspace,"dist"),{recursive:true,filter(file){const stat=lstatSync(file);if(stat.isSymbolicLink())throw new Error("Generated runtime copies cannot contain symlinks.");if(stat.isFile()){count++;total+=stat.size;}if(count>100000||total>2*1024**3)throw new Error("Generated runtime exceeds the preview limit.");return true;}});
249
+ }
250
+ atomic(path.join(session.workspace, ".ds/draft-preview.json"), JSON.stringify({ previewOnly: true }));
251
+ if (session.revision && session.revision !== value.revision && session.runtime && session.build?.scenarios.length) {
252
+ const before = previewStatus(id);
253
+ session.build = { ...before, state: "queued", building: true, current: false, stale: true,
254
+ scenarios: before.scenarios.map(item => ({ ...item, state: "queued", building: true, current: false, stale: true })) };
255
+ }
256
+ session.revision = value.revision;
257
+ session.projectRevision = hash(JSON.stringify(inputs));
258
+ session.error=undefined;
259
+ const watched=new Set();
260
+ for(const target of Object.keys(inputs)){
261
+ let file=target==="installed-dependencies"?path.join(root,"node_modules/.package-lock.json"):path.join(root,target);
262
+ while(isInside(root,file)){watched.add(file);if(file===root)break;file=path.dirname(file);}
263
+ }
264
+ session.watchFiles=[...watched];session.observed=watchStamp(session)+draftStamp();
265
+ return { ...value, session };
266
+ }
267
+ async function show({ id, scenario }) {
268
+ if (closed) throw new Error("Draft controller is closed.");
269
+ if(!previews.has(id)&&[...previews.values()].filter(session=>session.starting).length>=4){const oldest=[...previews].find(([,session])=>session.starting);if(oldest)await retire(oldest[0]);}
270
+ const value = prepare(id), { session } = value;
271
+ session.opened = true;
272
+ const options = loadConfig(session.workspace), units = inspectUnits(options);
273
+ const metadata = discovery.refresh(session.workspace, value.revision);
274
+ let registry = metadata.registry;
275
+ const known = scenario ? registry?.scenarios.find(item => item.id === scenario)
276
+ : registry?.scenarios.find(item => value.manifest.units.includes(units.owner(units.relative(item.file))));
277
+ if (!registry || !known || !existsSync(path.join(session.workspace, known.file)) || registry.diagnostics.length) registry = await discovery.current(session.workspace, value.revision);
278
+ const metadataRevision = metadata.revision;
279
+ const scenarios = registry.scenarios.map(({ id, title, kind, group, file }) => ({ id, title, kind, ...(group ? { group } : {}), unit: units.owner(units.relative(file)) }));
280
+ const owned = scenarios.find(item => value.manifest.units.includes(item.unit))?.id;
281
+ if(!scenario&&!owned&&value.manifest.units.some(unit=>/^(?:components|patterns|composition)\//.test(unit)))throw new Error("Draft has no independently mountable owner scenario yet. Add its scenario/fixture or select an explicit existing context scenario.");
282
+ const selected = scenario ?? owned ?? registry.scenarios[0]?.id;
283
+ session.selected = selected;
284
+ if (scenario && !registry.scenarios.some(item => item.id === scenario)) throw new Error("Unknown draft scenario. Read ads_show_draft without scenario to discover it.");
285
+ await startSession(id, session);
286
+ if (metadata.revision === value.revision) session.runtime.primeRegistry?.(registry);
287
+ const url = new URL(session.runtime.url); if (selected) url.searchParams.set("scenario", selected);
288
+ const accepted = await discovery.current(root, session.projectRevision);
289
+ const acceptedExists = accepted.scenarios.some(item => item.id === selected);
290
+ const previewResult=selected&&session.runtime.callTool?await session.runtime.callTool("ads_show_scenario",{id:selected,waitFor:"compiled"}):undefined;
291
+ if (session.runtime.buildStatus) recordBuild(id, session, session.runtime.buildStatus());
292
+ return { ...summary(value), scenario: selected, scenarios, diagnostics: registry.diagnostics, discovery: discovery.status(metadata, metadataRevision), build: previewResult?.structuredContent?.build ?? previewStatus(id), showcaseUrl: url.href, acceptedExists, previewOnly: true, previewResult,draftScope:`ads://drafts/${id}/resource?uri=`, next: "Inspect the actual rendered draft and its build freshness. Catalogue metadata may refresh in the background. Subscribe to ads://project/build and ads://project/drafts for updates. Reopen after edits; accept only the revision you reviewed. Full acceptance checks have not run." };
293
+ }
294
+ async function startSession(id, session) {
295
+ session.starting ??= (async () => {
296
+ if ([...previews.values()].filter(item => item !== session && item.starting).length >= 4) {
297
+ const oldest = [...previews].find(([other, item]) => other !== id && item.starting);
298
+ if (oldest) await retire(oldest[0]);
299
+ }
300
+ if (closed || previews.get(id) !== session) throw new Error("Draft preview was closed before startup.");
301
+ const runtime = await startPreview(session.workspace);
302
+ if (closed || previews.get(id) !== session) { await runtime.close(); throw new Error("Draft preview startup was cancelled."); }
303
+ session.unsubscribeBuild = runtime.onBuildChange?.(report => recordBuild(id, session, report));
304
+ return session.runtime = runtime;
305
+ })().catch(error => { session.starting = undefined; throw error; });
306
+ return session.starting;
307
+ }
308
+ async function retire(id) { const session = previews.get(id); previews.delete(id); if (session) { discovery.remove(session.workspace); try { await session.starting; } catch { /* Failed prewarming remains retryable. */ } session.unsubscribeBuild?.(); await session.runtime?.close(); if (!previews.has(id)) rmSync(path.dirname(session.workspace), { recursive: true, force: true }); } }
309
+ function queuePrewarm(id) {
310
+ if (!prewarm || !startPreview || !loadConfig(root).config.mcp.previewWatch) return;
311
+ pendingPrewarm = id;
312
+ clearTimeout(prewarmTimer);
313
+ prewarmTimer = setTimeout(warmNext, 50); prewarmTimer.unref();
314
+ }
315
+ function warmNext() {
316
+ if (closed || prewarming || !pendingPrewarm) return;
317
+ const id = pendingPrewarm; pendingPrewarm = undefined;
318
+ prewarming = (async () => {
319
+ if (!existsSync(manifestFile(id))) return;
320
+ for (const [other, session] of previews) if (other !== id && session.prewarmed && !session.opened) await retire(other);
321
+ const { session } = prepare(id);
322
+ session.prewarmed = true;
323
+ await startSession(id, session);
324
+ await session.runtime.prewarm?.();
325
+ })().catch(() => { /* A malformed/incomplete draft can be edited and retried through show(). */ }).finally(() => {
326
+ prewarming = undefined;
327
+ if (!closed && pendingPrewarm) { prewarmTimer = setTimeout(warmNext, 0); prewarmTimer.unref(); }
328
+ });
329
+ }
330
+ async function drop({ id, revision }) {
331
+ if (active) throw new Error("Wait for acceptance before dropping a draft.");
332
+ const value = inspect(id);
333
+ if (revision !== value.revision) throw new Error("Draft revision changed; read ads_drafts again.");
334
+ await retire(id);
335
+ rmSync(path.dirname(manifestFile(id)), { recursive: true });
336
+ return { dropped: true, event: event(id, revision, "dropped") };
337
+ }
338
+ async function accept({ id, revision }, signal, progress) {
339
+ if (closed || active) throw new Error("Wait for the active acceptance, or reopen ADS.");
340
+ const value = inspect(id);
341
+ if(value.dependencyErrors.length)throw new Error(`Draft dependency error: ${value.dependencyErrors[0].message}`);
342
+ if (value.revision !== revision) throw new Error("Draft revision changed. Review the current draft before accepting.");
343
+ if (value.dependencies.length) throw new Error("Accept dependency drafts first. Dependent previews will automatically use their accepted implementations.");
344
+ if (value.conflicts.length) throw new Error(`Draft baseline conflict: ${value.conflicts.join(", ")}`);
345
+ if (!value.changes.length) throw new Error("The draft has no changes to accept. Drop it instead.");
346
+ const groups = new Map();
347
+ for (const file of value.changes) {
348
+ const before = bytes(safe(root, file.target));
349
+ if (isDraftExportEntry(file.target, loadConfig(root)) && before !== null && file.content !== null) {
350
+ const merged=mergeDraftExports(before.toString(),file.content.toString(),before.toString(),file.target,loadConfig(root),value.manifest.units);
351
+ for(const stage of merged.stages)groups.set(stage.unit,(groups.get(stage.unit)??"")+textDiff(file.target,stage.before,stage.content));
352
+ } else groups.set(file.unit, (groups.get(file.unit) ?? "") + preparedFileDiff(file.target,before,file.content,safe(root,file.target),file.source?safe(path.dirname(manifestFile(id)),file.source):"/dev/null"));
353
+ }
354
+ const plans = value.manifest.units.filter(unit=>groups.has(unit)).map(unit => ({ unit, ...storePreparedPatch(loadConfig(root), groups.get(unit)) })).map(({unit, patchFile}) => ({unit, patchFile}));
355
+ const originals = new Map(value.changes.map(file => [file.target,bytes(safe(root,file.target))]));
356
+ const abort = new AbortController();
357
+ active = { id, abort }; event(id, revision, "checking");
358
+ try {
359
+ const result = await edits.apply(plans.length === 1 ? plans[0] : {patches: plans}, signal ? AbortSignal.any([signal, abort.signal]) : abort.signal, progress, { beforeApply() {
360
+ if (inspect(id).revision !== revision) throw new Error("Draft changed during acceptance; no changes were applied. Review and accept the new revision.");
361
+ } });
362
+ let outcome;
363
+ try{outcome=event(id, revision, result.applied ? "applied" : "failed", { diagnostics: result.diagnostics?.slice(0,3) });}
364
+ catch(error){if(!result.applied)throw error;result.warnings=[...(result.warnings??[]),{rule:"draft-event",message:`Source applied; event storage needs recovery: ${error.message}`}];}
365
+ if (result.applied) {
366
+ const updated = [];
367
+ for (const dependent of ids().filter(other => other !== id)) {
368
+ try{
369
+ const manifest = read(dependent);
370
+ if (manifest.dependencies.includes(id)) {
371
+ for(const file of manifest.files)if(originals.has(file.target)&&file.baseline===fileHash(originals.get(file.target))){
372
+ const accepted=bytes(safe(root,file.target)),source=file.source?bytes(safe(path.dirname(manifestFile(dependent)),file.source)):null;
373
+ if(fileHash(source)===file.baseline){file.baseline=fileHash(accepted);if(file.source&&accepted)atomic(safe(path.dirname(manifestFile(dependent)),file.source),accepted);}
374
+ else if(source&&accepted&&isDraftExportEntry(file.target,loadConfig(root))){
375
+ try{const merged=mergeDraftExports(accepted.toString(),source.toString(),originals.get(file.target)?.toString()??"",file.target,loadConfig(root),manifest.units);atomic(safe(path.dirname(manifestFile(dependent)),file.source),merged.content);file.baseline=fileHash(accepted);}catch{/* An overlapping edit remains an explicit baseline conflict. */}
376
+ }
377
+ }
378
+ manifest.dependencies = manifest.dependencies.filter(dependency => dependency !== id); save(manifest); updated.push(dependent);
379
+ }
380
+ }catch(error){result.warnings=[...(result.warnings??[]),{rule:"draft-dependency",message:`Source applied; dependent ${dependent} needs recovery: ${error.message}`}];}
381
+ }
382
+ try{rmSync(path.dirname(manifestFile(id)), { recursive: true });await retire(id);}
383
+ catch(error){result.warnings=[...(result.warnings??[]),{rule:"draft-cleanup",message:`Source applied; draft ${id} cleanup needs recovery: ${error.message}`}];}
384
+ return { ...result, draft: id, revision, event: outcome, updatedDependents: updated };
385
+ }
386
+ return { ...result, draft: id, revision, event: outcome };
387
+ } finally { active = undefined; }
388
+ }
389
+ function draftStamp(){
390
+ const rows=[];
391
+ function walk(folder){if(!existsSync(folder))return;for(const entry of readdirSync(folder,{withFileTypes:true})){const file=path.join(folder,entry.name);if(entry.isSymbolicLink())continue;if(entry.isDirectory())walk(file);else{const stat=lstatSync(file);rows.push([file,stat.mtimeMs,stat.ctimeMs,stat.size]);}if(rows.length>20000)throw new Error("Too many draft files.");}}
392
+ walk(storage);if(existsSync(eventFile))rows.push(bytes(eventFile)?.toString());return hash(JSON.stringify(rows));
393
+ }
394
+ function watchStamp(session){return hash(JSON.stringify((session.watchFiles??[]).map(file=>{try{const stat=lstatSync(file);return[file,stat.mtimeMs,stat.ctimeMs,stat.ino,stat.size];}catch{return[file,null];}})));}
395
+ function syncPreviews() {
396
+ let tracked;try{tracked=draftStamp();}catch{return;}
397
+ for (const [id,session] of previews) {
398
+ if(session.observed===watchStamp(session)+tracked)continue;
399
+ try { prepare(id); } catch(error) { session.error=error.message; }
400
+ }
401
+ }
402
+ function changed() {
403
+ if (closed) return;
404
+ clearTimeout(changeTimer);
405
+ changeTimer = setTimeout(() => {
406
+ if (closed) return;
407
+ reconcileWatches(); syncPreviews(); onChange?.();
408
+ }, 16);
409
+ changeTimer.unref();
410
+ }
411
+ function reconcileWatches() {
412
+ if (closed) return;
413
+ const wanted = new Set([root]);
414
+ function draftDirectories(folder) {
415
+ if (!existsSync(folder) || realpathSync(folder) !== folder) return;
416
+ wanted.add(folder);
417
+ for (const entry of readdirSync(folder, { withFileTypes: true })) if (entry.isDirectory() && !entry.isSymbolicLink()) draftDirectories(path.join(folder, entry.name));
418
+ }
419
+ try {
420
+ draftDirectories(storage);
421
+ const options = loadConfig(root);
422
+ if (previews.size) for (const folder of previewWatchDirectories(options)) wanted.add(folder);
423
+ for (const folder of wanted) {
424
+ const stat = lstatSync(folder), identity = `${stat.dev}:${stat.ino}`;
425
+ if (watchers.get(folder)?.identity === identity) continue;
426
+ watchers.get(folder)?.watcher.close();
427
+ const watcher = watch(folder, (event, file) => {
428
+ if (!file) return;
429
+ const target = path.join(folder, String(file));
430
+ if (!isInside(storage, target) && previewFileIgnored(options, target)) return;
431
+ if (isInside(storage, target) || event === "rename" || /\.(?:[cm]?[jt]sx?|css|html|json|md|svg|png|jpe?g|webp|gif|woff2?|ttf|otf|lock|lockb)$/.test(target)) changed();
432
+ });
433
+ watcher.unref(); watcher.on("error", () => { watcher.close(); watchers.delete(folder); });
434
+ watchers.set(folder, { identity, watcher });
435
+ }
436
+ for (const [folder, item] of watchers) if (!wanted.has(folder) || !existsSync(folder)) { item.watcher.close(); watchers.delete(folder); }
437
+ } catch { /* Reconciliation retries removed/replaced directories. */ }
438
+ }
439
+ const timer = setInterval(() => { if (!closed) { reconcileWatches(); syncPreviews(); } }, 5000);
440
+ timer.unref();
441
+ reconcileWatches();
442
+ return { list, create, update, show, drop, accept, prepare, events, inspect, tokenGroups,
443
+ previewStatuses: () => [...previews].map(([id, session]) => ({ id, revision: session.revision, ...previewStatus(id) })),
444
+ readFile(file,{offset=0,limit=12000}={}){
445
+ const parts=file.split("/");
446
+ if(parts[0]!==DRAFT_DIRECTORY||parts.length<3)throw new Error("Use a tracked draft path from ads_drafts.");
447
+ const manifest=read(parts[1]),folder=path.dirname(manifestFile(parts[1]));
448
+ const mapping=manifest.files.find(entry=>entry.source===parts.slice(2).join("/"));
449
+ if(!mapping&&parts.slice(2).join("/")!=="proposal.ads.draft.json")throw new Error("Draft reads are limited to the manifest and registered source files.");
450
+ const content=bytes(safe(folder,parts.slice(2).join("/")));
451
+ if(content===null)throw new Error("Draft source is missing.");
452
+ const binary=content.includes(0)||!Buffer.from(content.toString("utf8")).equals(content),text=content.toString("utf8"),end=offset+limit;
453
+ if(!Number.isSafeInteger(offset)||offset<0||offset>text.length||!Number.isSafeInteger(limit)||limit<1||limit>12000)throw new Error("Invalid draft read range.");
454
+ return{path:file,draft:parts[1],unit:mapping?.unit??null,digest:`sha256:${hash(content)}`,bytes:content.length,binary,content:binary?null:text.slice(offset,end),offset,nextOffset:!binary&&end<text.length?end:null,totalChars:binary?null:text.length,startLine:text.slice(0,offset).split("\n").length};
455
+ },
456
+ async readResource(id,uri,signal){const session=previews.get(id);if(!session?.starting)throw new Error("Draft preview is not active. Reopen ads_show_draft.");if(session.error)throw new Error(`Draft preview is stale: ${session.error}`);await session.starting;return session.runtime.readResource(uri,signal);},
457
+ fingerprint:()=>`${draftStamp()}:${discoveryVersion}`,
458
+ async close() { closed = true; clearInterval(timer); clearTimeout(changeTimer); clearTimeout(prewarmTimer); pendingPrewarm = undefined; for (const { watcher } of watchers.values()) watcher.close(); watchers.clear(); active?.abort.abort(); await Promise.allSettled([discovery.close(), ...[...previews.keys()].map(retire)]); await prewarming; },
459
+ };
460
+ }
@@ -9,6 +9,13 @@ import { migrateContractDraft } from "../contract-migration.mjs";
9
9
 
10
10
  const hash = value => createHash("sha256").update(value).digest("hex");
11
11
  const binary = bytes => bytes?.includes(0) || bytes && !Buffer.from(bytes.toString("utf8")).equals(bytes);
12
+ export function preparedFileDiff(file, left, right, original, next) {
13
+ if (!binary(left) && !binary(right)) return textDiff(file,left?.toString()??null,right?.toString()??null);
14
+ let diff;
15
+ try { diff=execFileSync("git",["diff","--no-index","--binary","--no-ext-diff","--no-textconv","--",left===null?"/dev/null":original,right===null?"/dev/null":next],{encoding:"utf8",maxBuffer:16*1024*1024}); }
16
+ catch(error){if(error.status!==1)throw error;diff=error.stdout;}
17
+ return diff.replace(/^diff --git .+$/m,`diff --git a/${file} b/${file}`);
18
+ }
12
19
  function generated(options, relative) {
13
20
  const target = path.join(options.root, ".ds", relative);
14
21
  mkdirSync(path.dirname(target), {recursive:true});
@@ -101,13 +108,7 @@ export function prepareUnitPatch(options, {unit, action = "create", draft}) {
101
108
  if (bytes > 32 * 1024 * 1024) throw new Error("Draft changes exceed 32 MiB.");
102
109
  const change = {path:file,originalContent:left === null ? null : binary(left) ? left : left.toString(),content:right === null ? null : binary(right) ? right : right.toString()};
103
110
  changes.push(change);
104
- if (!binary(left) && !binary(right)) patch += textDiff(file,change.originalContent,change.content);
105
- else {
106
- let diff;
107
- try { diff = execFileSync("git",["diff","--no-index","--binary","--no-ext-diff","--no-textconv","--",left === null ? "/dev/null" : original,right === null ? "/dev/null" : next],{encoding:"utf8",maxBuffer:16*1024*1024}); }
108
- catch (error) { if (error.status !== 1) throw error; diff=error.stdout; }
109
- patch += diff.replace(/^diff --git .+$/m,`diff --git a/${file} b/${file}`);
110
- }
111
+ patch += preparedFileDiff(file,left,right,original,next);
111
112
  }
112
113
  if (changes.length) checkUnitFiles(options,unit,changes,inventory,true);
113
114
  return {unit,draft,changes:changes.map(entry=>entry.path),...storePreparedPatch(options,patch),next:"Apply with ads_apply_patch using this unit and patchFile. Preparation is not validation or publication."};
@@ -34,6 +34,7 @@ function snapshot(kind, raw) {
34
34
  return { schemaVersion: 1, resultId, kind, createdAt: new Date().toISOString(), ok: !!raw.ok,
35
35
  ...(raw.applied !== undefined ? { applied: raw.applied } : {}), ...(raw.unit ? { unit: raw.unit } : {}),
36
36
  ...(raw.units ? { units: raw.units } : {}), ...(raw.transaction ? { transaction: true } : {}),
37
+ ...(raw.draft ? {draft:raw.draft,draftRevision:raw.revision,draftEvent:raw.event?{id:raw.event.id,state:raw.event.state}:null,updatedDependents:raw.updatedDependents??[]} : {}),
37
38
  ...(kind === "validation" ? {scope:raw.scope,requestedScope:raw.requestedScope,sourceRevision:raw.sourceRevision,current:raw.current,elapsedMs:raw.elapsedMs,...(raw.fallback?{fallback:raw.fallback}:{})} : {}),
38
39
  acceptance: raw.acceptance, investigation: raw.investigation,
39
40
  sections: Object.fromEntries(Object.entries(sections).map(([key, rows]) => [key, rows.map((row, recordIndex) => ({ recordIndex, ...(row && typeof row === "object" ? row : {message:row}) }))])),
@@ -49,6 +50,7 @@ function summary(value, storageWarning) {
49
50
  const section = failedOutcomes.length ? "outcomes" : value.sections.diagnostics.length ? "diagnostics" : value.sections.captures.length ? "captures" : value.sections.outcomes.length ? "outcomes" : "checks";
50
51
  const result = { ok, resultId, kind, ...(kind === "validation" ? {scope:value.scope,requestedScope:value.requestedScope,sourceRevision:value.sourceRevision,current:value.current,elapsedMs:value.elapsedMs,...(value.fallback?{fallback:value.fallback}:{})} : {}), ...(applied !== undefined ? { applied } : {}), ...(unit ? { unit } : {}),
51
52
  ...(units ? { units } : {}), ...(transaction ? { transaction } : {}), createdAt, counts, freshness:"recorded-at-completion",
53
+ ...(value.draft?{draft:value.draft,draftRevision:value.draftRevision,draftEvent:value.draftEvent,updatedDependentCount:value.updatedDependents.length}:{}),
52
54
  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)),
53
55
  failureCount: value.failureCount ?? failureRows.length, resourceUri,
54
56
  next: value.detailsUnavailable ? null : { tool: "ads_results", arguments: { resultId, section, ...(section === "outcomes" && failedOutcomes.length ? { status: "not_passed" } : {}) } },
@@ -169,7 +169,7 @@ export function createMutationController(directory, { captures = createCaptureCo
169
169
  return { ...source, unit, content, offset, nextOffset: end < source.content.length ? end : null, totalChars: source.content.length,
170
170
  startLine: source.content.slice(0, offset).split("\n").length };
171
171
  },
172
- async apply({ unit, patch, patchFile, patches, dryRun = false, screenshot = false, captures: selections }, signal, notifyProgress) {
172
+ async apply({ unit, patch, patchFile, patches, dryRun = false, screenshot = false, captures: selections }, signal, notifyProgress, { beforeApply } = {}) {
173
173
  if (busy) return mutationEvidence({ ok: false, applied: false, diagnostics: [{ rule: "mutation-busy", message: "Another mutation is validating; retry after it finishes.",failure:evidenceFailure("runner","mutation-execution","ADS_MUTATION_BUSY") }] });
174
174
  busy = true;
175
175
  active = new AbortController();
@@ -298,7 +298,10 @@ export function createMutationController(directory, { captures = createCaptureCo
298
298
  const brand = await generateBrandAssets(candidate);
299
299
  verified.push({ name: "brand assets", passed: true, skipped: !!brand.skipped });
300
300
  }
301
- for (const check of extraChecks) verified.push(await checkCommand(check.command, check.args, candidate, signal, undefined, {category:"build",phase:`project-check:${check.args.at(-1)}`}, candidateOptions.config.mcp.mutationCheckTimeoutMs));
301
+ for (const [index,check] of extraChecks.entries()) {
302
+ progress={stage:"project-checks",completed:index,total:extraChecks.length,message:`Checking ${check.command} ${check.args.join(" ")}`};notifyProgress?.(progress);
303
+ verified.push(await checkCommand(check.command, check.args, candidate, signal, undefined, {category:"build",phase:`project-check:${check.args.at(-1)}`}, candidateOptions.config.mcp.mutationCheckTimeoutMs));
304
+ }
302
305
  boundary=evidenceFailure("runner","behavior-verification","ADS_BEHAVIOR_SETUP");
303
306
  const behaviorUnits = affectedBehaviorUnits(candidateOptions, changes.map(change => change.path));
304
307
  if (behaviorUnits.length) {
@@ -329,6 +332,7 @@ export function createMutationController(directory, { captures = createCaptureCo
329
332
  screenshots = { ok: true, captures: captures.store.list(inspectScenarios(loadConfig(root)).scenarios, screenshots.baseRevision).captures.filter(record => selected.has(record.key)) };
330
333
  }
331
334
  if (!dryRun) {
335
+ beforeApply?.();
332
336
  const written = [];
333
337
  const directories = [];
334
338
  function mkdir(directory) { if (!existsSync(directory)) { mkdir(path.dirname(directory)); mkdirSync(directory); directories.push(directory); } }
@@ -1,8 +1,9 @@
1
1
  import { spawn } from "node:child_process";
2
2
  import { randomUUID } from "node:crypto";
3
- import { statSync, mkdirSync, writeFileSync, renameSync, rmSync, realpathSync } from "node:fs";
3
+ import { statSync, mkdirSync, readFileSync, writeFileSync, renameSync, rmSync, realpathSync } from "node:fs";
4
4
  import path from "node:path";
5
5
  import { fileURLToPath } from "node:url";
6
+ import { Writable } from "node:stream";
6
7
  import { buildFailure, inspectBuildStatus } from "./build-status.mjs";
7
8
  import { previewSessionDirectories, withPreviewSession } from "../preview-scope.mjs";
8
9
  import { developmentExecutable } from "../development-runtime.mjs";
@@ -32,6 +33,13 @@ export function createPreviewWatch(root, config, { log = process.stderr, buildTi
32
33
  const baselines = new Map();
33
34
  const ready = new Set();
34
35
  const requests = new Set();
36
+ function diagnostics(stream){
37
+ // A private writable keeps each pipe's lifecycle/backpressure listeners off
38
+ // the shared stderr socket when several draft/capture compilers are warm.
39
+ const output=new Writable({write(chunk,encoding,done){log.write(chunk,encoding,done);}});
40
+ output.on("error",failure=>{error??=`Preview diagnostics failed: ${failure.message}`;if(state==="running"){state="failed";kill("SIGKILL");}});
41
+ stream.pipe(output);
42
+ }
35
43
  let active;
36
44
  let invalidation;
37
45
  let requestFile = path.join(root, ".ds", `preview-requests-${session}.json`);
@@ -83,7 +91,7 @@ export function createPreviewWatch(root, config, { log = process.stderr, buildTi
83
91
  stdio: ["pipe", "ignore", "pipe"], detached: process.platform !== "win32", windowsHide: true,
84
92
  });
85
93
  guard.stdin.on("error", () => {}); // Owner shutdown can race guard exit.
86
- guard.stderr.pipe(log, { end: false });
94
+ diagnostics(guard.stderr);
87
95
  function guardFailed(failure) {
88
96
  if (ownerGuard !== guard || state === "stopping" || childClosed) return;
89
97
  error = `Preview ownership guard failed: ${failure.message ?? failure}. Invoke the preview again after fixing the launcher.`;
@@ -93,8 +101,8 @@ export function createPreviewWatch(root, config, { log = process.stderr, buildTi
93
101
  guard.once("error", guardFailed);
94
102
  guard.once("exit", (code, signal) => guardFailed(signal ?? code));
95
103
  }
96
- child.stdout.pipe(log, { end: false });
97
- child.stderr.pipe(log, { end: false });
104
+ diagnostics(child.stdout);
105
+ diagnostics(child.stderr);
98
106
  closed = new Promise((resolve) => child.once("close", (code, signal) => {
99
107
  // Closing the launcher's pipes does not prove every compiler exited.
100
108
  // Finish cleanup now, before discarding the owned process-group ID.
@@ -193,7 +201,17 @@ export function createPreviewWatch(root, config, { log = process.stderr, buildTi
193
201
  })();
194
202
  return stopping;
195
203
  }
196
- return { start, ensure, invalidate() { invalidation = randomUUID(); if (active) request(active,true); }, async warm(files) {
204
+ return { start, ensure, async initialize() {
205
+ if (disposed || !command) return;
206
+ if (state === "failed" || restarting || stalled) await restart();
207
+ start();
208
+ const deadline = Date.now() + buildTimeout;
209
+ while (!disposed && state === "running" && Date.now() < deadline) {
210
+ try { if (JSON.parse(readFileSync(reportFile, "utf8")).session === session) return; } catch { /* Waiting for compiler initialization, without requesting a graph. */ }
211
+ await new Promise(resolve => setTimeout(resolve, 20));
212
+ }
213
+ if (!disposed) throw new Error(error ?? "Preview compiler initialization timed out.");
214
+ }, invalidate() { invalidation = randomUUID(); if (active) request(active,true); }, async warm(files) {
197
215
  if (disposed || !command || !files.length) return;
198
216
  const selected=active;
199
217
  if (state === "failed" || restarting || stalled) await restart();
@@ -219,6 +237,7 @@ export function createReconfigurablePreviewWatch(root, config, options) {
219
237
  let pending = Promise.resolve(), replacing = false, stopped = false;
220
238
  return {
221
239
  start() { if (!stopped && !replacing) current.start(); },
240
+ async initialize() { await pending; if (!stopped) return current.initialize(); },
222
241
  async ensure(file, signal, options) { await pending; if (stopped) throw new Error("Preview watcher is stopped."); return current.ensure(file, signal, options); },
223
242
  status() { return replacing ? { state: "reconfiguring" } : current.status(); },
224
243
  resourceSession() { return current.resourceSession(); },