@reqvire-org/ads 0.3.31 → 0.3.33
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.
- package/README.md +9 -0
- package/dist/bootstrap-ds/vite.config.ts +2 -1
- package/dist/boundaries.mjs +2 -0
- package/dist/capture.mjs +5 -3
- package/dist/config.mjs +5 -2
- package/dist/draft-boundary.mjs +27 -0
- package/dist/draft-workspace.mjs +10 -0
- package/dist/lint-config.mjs +1 -0
- package/dist/mcp/apps.mjs +3 -1
- package/dist/mcp/context.mjs +2 -2
- package/dist/mcp/draft-exports.mjs +40 -0
- package/dist/mcp/drafts.mjs +341 -0
- package/dist/mcp/edit-preparation.mjs +8 -7
- package/dist/mcp/execution-results.mjs +2 -0
- package/dist/mcp/mutations.mjs +8 -3
- package/dist/mcp/preview-watch.mjs +11 -3
- package/dist/mcp/preview-widget.bundle.js +13 -13
- package/dist/mcp/prompts.mjs +3 -2
- package/dist/mcp/server.mjs +75 -18
- package/dist/mcp/widget.bundle.js +1 -1
- package/dist/preview-files.mjs +2 -0
- package/dist/scenarios-compiler.mjs +2 -0
- package/dist/scenarios-vite.d.mts +1 -0
- package/dist/scenarios-vite.mjs +1 -0
- package/dist/showcase/client.bundle.js +42 -42
- package/dist/showcase/comparison.js +21 -0
- package/dist/showcase/index.html +3 -2
- package/dist/showcase/style.css +9 -0
- package/dist/skills/README.md +5 -0
- package/dist/skills/ads-break-ui/SKILL.md +26 -0
- package/dist/skills/ads-break-ui/references/captures.md +7 -0
- package/dist/skills/ads-break-ui/references/drafts.md +107 -0
- package/dist/skills/ads-break-ui/references/guarded-editing.md +6 -0
- package/dist/skills/ads-designer/SKILL.md +26 -0
- package/dist/skills/ads-designer/assets/bootstrap-ds/vite.config.ts +2 -1
- package/dist/skills/ads-designer/references/captures.md +7 -0
- package/dist/skills/ads-designer/references/drafts.md +107 -0
- package/dist/skills/ads-designer/references/guarded-editing.md +6 -0
- package/dist/skills/ads-import/SKILL.md +26 -0
- package/dist/skills/ads-import/references/captures.md +7 -0
- package/dist/skills/ads-import/references/drafts.md +107 -0
- package/dist/skills/ads-import/references/guarded-editing.md +6 -0
- package/dist/skills/ads-motion/SKILL.md +26 -0
- package/dist/skills/ads-motion/references/captures.md +7 -0
- package/dist/skills/ads-motion/references/drafts.md +107 -0
- package/dist/skills/ads-motion/references/guarded-editing.md +6 -0
- package/dist/skills/ads-port/SKILL.md +26 -0
- package/dist/skills/ads-port/references/captures.md +7 -0
- package/dist/skills/ads-port/references/drafts.md +107 -0
- package/dist/skills/ads-port/references/guarded-editing.md +6 -0
- package/dist/units.mjs +7 -1
- package/dist/validation-inputs.mjs +11 -1
- package/docs/ADS.md +13 -0
- package/docs/ARCHITECTURE.md +12 -0
- package/docs/CHANGELOG.md +31 -0
- package/docs/CONTRACTS.md +8 -0
- package/docs/GUIDE.md +19 -5
- package/docs/MCP.md +50 -0
- package/package.json +1 -1
|
@@ -0,0 +1,341 @@
|
|
|
1
|
+
import { createHash, randomUUID } from "node:crypto";
|
|
2
|
+
import { cpSync, existsSync, lstatSync, mkdirSync, readFileSync, readdirSync, realpathSync, renameSync, rmSync, symlinkSync, 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 { inspectScenarios } from "../scenarios.mjs";
|
|
9
|
+
import { validationInputFiles } from "../validation-inputs.mjs";
|
|
10
|
+
import { textDiff } from "./text-diff.mjs";
|
|
11
|
+
import { storePreparedPatch, preparedFileDiff } from "./edit-preparation.mjs";
|
|
12
|
+
import { mergeDraftExports, isDraftExportEntry } from "./draft-exports.mjs";
|
|
13
|
+
import { inspectTokens } from "../tokens.mjs";
|
|
14
|
+
|
|
15
|
+
export const DRAFTS_URI = "ads://project/drafts";
|
|
16
|
+
const hash = bytes => createHash("sha256").update(bytes).digest("hex");
|
|
17
|
+
const idSchema = z.string().regex(/^[a-z0-9][a-z0-9-]{0,79}$/);
|
|
18
|
+
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.");
|
|
19
|
+
const fileSchema = z.object({ target: relative, source: relative.nullable(), baseline: z.string().regex(/^[a-f0-9]{64}$/).nullable(), unit: z.string().max(256) }).strict();
|
|
20
|
+
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();
|
|
21
|
+
export const draftIdSchema = idSchema;
|
|
22
|
+
export const draftRevisionSchema = z.string().regex(/^[a-f0-9]{64}$/);
|
|
23
|
+
|
|
24
|
+
function safe(root, relativePath) {
|
|
25
|
+
relative.parse(relativePath);
|
|
26
|
+
const target = path.resolve(root, relativePath);
|
|
27
|
+
if (!isInside(root, target) || target === root) throw new Error("Draft paths must stay inside their project or proposal.");
|
|
28
|
+
for (let current = target; isInside(root, current); current = path.dirname(current)) {
|
|
29
|
+
const stat = lstatSync(current, { throwIfNoEntry: false });
|
|
30
|
+
if (stat?.isSymbolicLink() || stat && current === target && (!stat.isFile() || stat.nlink !== 1)) throw new Error("Draft paths require ordinary directories and unlinked regular files.");
|
|
31
|
+
if (current === root) break;
|
|
32
|
+
if (stat && current !== target && !stat.isDirectory()) throw new Error("Invalid draft directory.");
|
|
33
|
+
}
|
|
34
|
+
return target;
|
|
35
|
+
}
|
|
36
|
+
function bytes(file) {
|
|
37
|
+
if (!existsSync(file)) return null;
|
|
38
|
+
const stat = lstatSync(file);
|
|
39
|
+
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.");
|
|
40
|
+
return readFileSync(file);
|
|
41
|
+
}
|
|
42
|
+
const fileHash = content => content === null ? null : hash(content);
|
|
43
|
+
function atomic(file, content) {
|
|
44
|
+
mkdirSync(path.dirname(file), { recursive: true });
|
|
45
|
+
if (realpathSync(path.dirname(file)) !== path.dirname(file)) throw new Error("Draft storage cannot resolve through a symlink.");
|
|
46
|
+
const staging = `${file}.${randomUUID()}.tmp`;
|
|
47
|
+
try { writeFileSync(staging, content); renameSync(staging, file); }
|
|
48
|
+
finally { rmSync(staging, { force: true }); }
|
|
49
|
+
}
|
|
50
|
+
const storedName = target => `files/${target}.ads`;
|
|
51
|
+
|
|
52
|
+
/** Tracked proposal source is separate from disposable compiler state. No Git checkout is required. */
|
|
53
|
+
export function createDraftController(directory, { edits, startPreview } = {}) {
|
|
54
|
+
const root = path.resolve(directory), storage = path.join(root, DRAFT_DIRECTORY);
|
|
55
|
+
const previews = new Map();
|
|
56
|
+
let active, closed = false;
|
|
57
|
+
const manifestFile = id => safe(root, `${DRAFT_DIRECTORY}/${idSchema.parse(id)}/proposal.ads.draft.json`);
|
|
58
|
+
const save = manifest => atomic(manifestFile(manifest.id), JSON.stringify(manifestSchema.parse(manifest), null, 2) + "\n");
|
|
59
|
+
function read(id) {
|
|
60
|
+
const file = manifestFile(id), content = bytes(file);
|
|
61
|
+
if (!content || content.length > 256 * 1024) throw new Error("Unknown or oversized ADS draft manifest.");
|
|
62
|
+
const manifest = manifestSchema.parse(JSON.parse(content.toString("utf8")));
|
|
63
|
+
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.");
|
|
64
|
+
for (const unit of manifest.units) validateUnitId(unit);
|
|
65
|
+
for (const file of manifest.files) {
|
|
66
|
+
safe(root, file.target);
|
|
67
|
+
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.");
|
|
68
|
+
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/.");
|
|
69
|
+
if (file.source) safe(path.dirname(manifestFile(id)), file.source);
|
|
70
|
+
}
|
|
71
|
+
return manifest;
|
|
72
|
+
}
|
|
73
|
+
// Keep machine execution records out of Git; proposal source/manifests are durable.
|
|
74
|
+
const eventFile = path.join(root, ".ds/draft-events.json");
|
|
75
|
+
function events() { try { const value = JSON.parse(bytes(eventFile)?.toString() ?? "[]"); return Array.isArray(value) ? value.slice(-100) : []; } catch { return []; } }
|
|
76
|
+
function event(id, revision, state, extra = {}) {
|
|
77
|
+
const value = { id: randomUUID(), draft: id, revision, state, at: new Date().toISOString(), ...extra };
|
|
78
|
+
atomic(eventFile, JSON.stringify([...events(), value].slice(-100)));
|
|
79
|
+
return value;
|
|
80
|
+
}
|
|
81
|
+
function inspect(id, stack = [], context = {inputs:validationInputFiles(loadConfig(root)),seen:new Set(),memo:new Map()}) {
|
|
82
|
+
if (stack.includes(id)) throw new Error(`Draft dependency cycle: ${[...stack, id].join(" → ")}`);
|
|
83
|
+
if(context.memo.has(id))return context.memo.get(id);
|
|
84
|
+
context.seen.add(id);if(context.seen.size>32||stack.length>16)throw new Error("Draft dependency graph exceeds 32 drafts/16 levels.");
|
|
85
|
+
const manifest = read(id), folder = path.dirname(manifestFile(id));
|
|
86
|
+
const files = manifest.files.map(file => ({ ...file, content: file.source ? bytes(safe(folder, file.source)) : null }));
|
|
87
|
+
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.");
|
|
88
|
+
if (files.reduce((size, file) => size + (file.content?.length ?? 0), 0) > 32 * 1024 * 1024) throw new Error("Draft exceeds 32 MiB.");
|
|
89
|
+
const dependencies = [], dependencyErrors = [];
|
|
90
|
+
for(const dependency of manifest.dependencies){
|
|
91
|
+
try{const value=inspect(dependency,[...stack,id],context);dependencies.push(value);dependencyErrors.push(...value.dependencyErrors);}
|
|
92
|
+
catch(error){dependencyErrors.push({draft:dependency,message:error.message});}
|
|
93
|
+
}
|
|
94
|
+
const projectInputs = context.inputs;
|
|
95
|
+
const revision = hash(JSON.stringify([manifest, files.map(file => [file.target, fileHash(file.content)]), dependencies.map(dependency => [dependency.manifest.id, dependency.revision]), dependencyErrors, projectInputs]));
|
|
96
|
+
const changes = files.filter(file => fileHash(file.content) !== file.baseline);
|
|
97
|
+
const conflicts = changes.filter(file => fileHash(bytes(safe(root, file.target))) !== file.baseline).map(file => file.target);
|
|
98
|
+
const result={ manifest, files, changes, dependencies, dependencyErrors, revision, conflicts };context.memo.set(id,result);return result;
|
|
99
|
+
}
|
|
100
|
+
function ids() {
|
|
101
|
+
if (!existsSync(storage)) return [];
|
|
102
|
+
if (realpathSync(storage) !== storage) throw new Error("Draft storage cannot be a symlink.");
|
|
103
|
+
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();
|
|
104
|
+
}
|
|
105
|
+
function summary(value) {
|
|
106
|
+
const { manifest, revision, conflicts, changes } = value;
|
|
107
|
+
const last = events().filter(event => event.draft === manifest.id).at(-1);
|
|
108
|
+
return { id: manifest.id, title: manifest.title, units: manifest.units, dependencies: manifest.dependencies, tokenGroups:manifest.tokenGroups, revision, changes: changes.length, conflicts,
|
|
109
|
+
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",
|
|
110
|
+
manifest: path.relative(root, manifestFile(manifest.id)).replaceAll("\\", "/") };
|
|
111
|
+
}
|
|
112
|
+
function list({ id, unit, query = "", offset = 0, limit = 20 } = {}) {
|
|
113
|
+
const diagnostics = [], all = [];
|
|
114
|
+
let inputs;
|
|
115
|
+
for (const selected of id ? [id] : ids()) {
|
|
116
|
+
try {
|
|
117
|
+
inputs??=validationInputFiles(loadConfig(root));
|
|
118
|
+
const value = inspect(selected,[],{inputs,seen:new Set(),memo:new Map()}), item = summary(value);
|
|
119
|
+
diagnostics.push(...value.dependencyErrors.map(error=>({...error,draft:selected,dependency:error.draft})));
|
|
120
|
+
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);
|
|
121
|
+
} catch (error) { diagnostics.push({ draft: selected, message: error.message }); }
|
|
122
|
+
}
|
|
123
|
+
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 };
|
|
124
|
+
}
|
|
125
|
+
function tokenGroups() {
|
|
126
|
+
const options=loadConfig(root),directory=path.join(options.dsRoot,options.config.tokenDir),groups=new Map();
|
|
127
|
+
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);}
|
|
128
|
+
return [...groups.values()].map(({tokens,...group})=>({...group,count:tokens.size})).sort((a,b)=>a.id.localeCompare(b.id));
|
|
129
|
+
}
|
|
130
|
+
function create({ units, title, id = randomUUID(), dependencies = [], tokenGroups: selectedGroups = [] }) {
|
|
131
|
+
if (closed) throw new Error("Draft controller is closed.");
|
|
132
|
+
idSchema.parse(id);
|
|
133
|
+
if (existsSync(manifestFile(id))) throw new Error("Draft already exists.");
|
|
134
|
+
const options = loadConfig(root), inventory = inspectUnits(options), files = new Map();
|
|
135
|
+
const groups=selectedGroups.length?tokenGroups():[];
|
|
136
|
+
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.");
|
|
137
|
+
for (const unit of units) {
|
|
138
|
+
validateUnitId(unit);
|
|
139
|
+
const owner = inventory.units.find(item => item.id === unit);
|
|
140
|
+
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.");
|
|
141
|
+
const paths = [...(owner?.files ?? []), ...(owner?.companionFiles ?? []).map(file => file.path)];
|
|
142
|
+
if (/^(?:components|patterns|controllers)\//.test(unit)) paths.push(path.relative(root, path.join(options.dsRoot, options.config.publicEntry)).replaceAll("\\", "/"));
|
|
143
|
+
if (unit.startsWith("review/")) paths.push(path.relative(root, path.join(options.dsRoot, options.config.reviewEntry)).replaceAll("\\", "/"));
|
|
144
|
+
for (const target of paths) if (!files.has(target)) {
|
|
145
|
+
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;
|
|
146
|
+
const content = bytes(safe(root, target));
|
|
147
|
+
if (content === null) continue;
|
|
148
|
+
const source = storedName(target);
|
|
149
|
+
files.set(target, { target, source, baseline: hash(content), unit });
|
|
150
|
+
}
|
|
151
|
+
}
|
|
152
|
+
const manifest = manifestSchema.parse({ schemaVersion: 1, id, title: title ?? units.join(", "), units, dependencies, tokenGroups:selectedGroups, files: [...files.values()] });
|
|
153
|
+
for (const dependency of dependencies) {const value=inspect(dependency,[id]);if(value.dependencyErrors.length)throw new Error(value.dependencyErrors[0].message);}
|
|
154
|
+
for (const file of manifest.files) atomic(safe(path.dirname(manifestFile(id)), file.source), bytes(safe(root, file.target)));
|
|
155
|
+
save(manifest);
|
|
156
|
+
const value = inspect(id); event(id, value.revision, "created");
|
|
157
|
+
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." };
|
|
158
|
+
}
|
|
159
|
+
function update({ id, revision, changes = [], dependencies }) {
|
|
160
|
+
const value = inspect(id);
|
|
161
|
+
if (value.revision !== revision) throw new Error("Draft revision changed. Read ads_drafts again before editing.");
|
|
162
|
+
const manifest = value.manifest;
|
|
163
|
+
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; }
|
|
164
|
+
for (const change of changes) {
|
|
165
|
+
if (!manifest.units.includes(change.unit)) throw new Error("Changes must belong to a declared draft unit.");
|
|
166
|
+
let file = manifest.files.find(file => file.target === change.path);
|
|
167
|
+
if (!file) { file = { target: change.path, source: null, baseline: fileHash(bytes(safe(root, change.path))), unit: change.unit }; manifest.files.push(file); }
|
|
168
|
+
file.unit = change.unit;
|
|
169
|
+
if (change.content === null) file.source = null;
|
|
170
|
+
else {
|
|
171
|
+
file.source ??= storedName(change.path);
|
|
172
|
+
const content = Buffer.from(change.content, change.encoding === "base64" ? "base64" : "utf8");
|
|
173
|
+
atomic(safe(path.dirname(manifestFile(id)), file.source), content);
|
|
174
|
+
}
|
|
175
|
+
}
|
|
176
|
+
save(manifest);
|
|
177
|
+
return summary(inspect(id));
|
|
178
|
+
}
|
|
179
|
+
function prepare(id) {
|
|
180
|
+
const value = inspect(id);
|
|
181
|
+
if(value.dependencyErrors.length)throw new Error(`Draft dependency error: ${value.dependencyErrors[0].message}`);
|
|
182
|
+
if (value.conflicts.length) throw new Error(`Draft baseline conflict: ${value.conflicts.join(", ")}`);
|
|
183
|
+
let session = previews.get(id);
|
|
184
|
+
if (!session) {
|
|
185
|
+
const workspace = path.join(root, ".ds/draft-previews", id, "project");
|
|
186
|
+
mkdirSync(workspace, { recursive: true });
|
|
187
|
+
if (realpathSync(workspace) !== workspace) throw new Error("Draft preview workspace cannot be a symlink.");
|
|
188
|
+
session = { workspace, inputs: new Map() }; previews.set(id, session);
|
|
189
|
+
}
|
|
190
|
+
const inputs = validationInputFiles(loadConfig(root)), desired = new Map();
|
|
191
|
+
let size = 0;
|
|
192
|
+
for (const [target, digest] of Object.entries(inputs)) if (digest && target !== "installed-dependencies") {
|
|
193
|
+
const content = bytes(safe(root, target));
|
|
194
|
+
if (content !== null) { desired.set(target, content); size += content.length; }
|
|
195
|
+
if (desired.size > 100000 || size > 2 * 1024 ** 3) throw new Error("Draft preview input limit exceeded.");
|
|
196
|
+
}
|
|
197
|
+
const applied = new Map();
|
|
198
|
+
function overlay(proposal) {
|
|
199
|
+
if (proposal.conflicts.length) throw new Error(`Dependency draft conflict: ${proposal.conflicts.join(", ")}`);
|
|
200
|
+
for (const dependency of proposal.dependencies) overlay(dependency);
|
|
201
|
+
for (const file of proposal.changes) {
|
|
202
|
+
const digest = fileHash(file.content);
|
|
203
|
+
if (isDraftExportEntry(file.target, loadConfig(root)) && file.content !== null) {
|
|
204
|
+
const merged = mergeDraftExports(desired.get(file.target)?.toString() ?? "", file.content.toString(), bytes(safe(root,file.target))?.toString() ?? "", file.target, loadConfig(root), proposal.manifest.units);
|
|
205
|
+
desired.set(file.target,Buffer.from(merged.content));
|
|
206
|
+
continue;
|
|
207
|
+
}
|
|
208
|
+
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.`);
|
|
209
|
+
applied.set(file.target, digest);
|
|
210
|
+
if (file.content === null) desired.delete(file.target); else desired.set(file.target, file.content);
|
|
211
|
+
}
|
|
212
|
+
}
|
|
213
|
+
overlay(value);
|
|
214
|
+
for (const target of session.inputs.keys()) if (!desired.has(target)) rmSync(safe(session.workspace, target), { force: true });
|
|
215
|
+
for (const [target, content] of desired) if (session.inputs.get(target) !== hash(content)) atomic(safe(session.workspace, target), content);
|
|
216
|
+
session.inputs = new Map([...desired].map(([target, content]) => [target, hash(content)]));
|
|
217
|
+
const modules = path.join(session.workspace, "node_modules");
|
|
218
|
+
if (!existsSync(modules) && existsSync(path.join(root, "node_modules"))) symlinkSync(realpathSync(path.join(root, "node_modules")), modules, process.platform === "win32" ? "junction" : "dir");
|
|
219
|
+
if (!existsSync(path.join(session.workspace, "dist")) && existsSync(path.join(root, "dist/cli.mjs"))) {
|
|
220
|
+
let count=0,total=0;
|
|
221
|
+
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;}});
|
|
222
|
+
}
|
|
223
|
+
atomic(path.join(session.workspace, ".ds/draft-preview.json"), JSON.stringify({ previewOnly: true }));
|
|
224
|
+
session.revision = value.revision;
|
|
225
|
+
session.error=undefined;
|
|
226
|
+
const watched=new Set();
|
|
227
|
+
for(const target of Object.keys(inputs)){
|
|
228
|
+
let file=target==="installed-dependencies"?path.join(root,"node_modules/.package-lock.json"):path.join(root,target);
|
|
229
|
+
while(isInside(root,file)){watched.add(file);if(file===root)break;file=path.dirname(file);}
|
|
230
|
+
}
|
|
231
|
+
session.watchFiles=[...watched];session.observed=watchStamp(session)+draftStamp();
|
|
232
|
+
return { ...value, session };
|
|
233
|
+
}
|
|
234
|
+
async function show({ id, scenario }) {
|
|
235
|
+
if (closed) throw new Error("Draft controller is closed.");
|
|
236
|
+
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]);}
|
|
237
|
+
const value = prepare(id), { session } = value;
|
|
238
|
+
const registry = inspectScenarios(loadConfig(session.workspace));
|
|
239
|
+
const owned = registry.scenarios.find(item => value.manifest.units.some(unit => item.id === unit || item.id.startsWith(unit + "/") || item.id.startsWith(unit + ".")))?.id;
|
|
240
|
+
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.");
|
|
241
|
+
const selected = scenario ?? owned ?? registry.scenarios[0]?.id;
|
|
242
|
+
if (scenario && !registry.scenarios.some(item => item.id === scenario)) throw new Error("Unknown draft scenario. Read ads_show_draft without scenario to discover it.");
|
|
243
|
+
session.starting ??= startPreview(session.workspace).then(runtime => session.runtime = runtime).catch(error => { session.starting = undefined; throw error; });
|
|
244
|
+
await session.starting;
|
|
245
|
+
const url = new URL(session.runtime.url); if (selected) url.searchParams.set("scenario", selected);
|
|
246
|
+
const acceptedExists = inspectScenarios(loadConfig(root)).scenarios.some(item => item.id === selected);
|
|
247
|
+
const previewResult=selected&&session.runtime.callTool?await session.runtime.callTool("ads_show_scenario",{id:selected,waitFor:"compiled"}):undefined;
|
|
248
|
+
return { ...summary(value), scenario: selected, scenarios: registry.scenarios.map(({id, title, kind}) => ({id, title, kind})), diagnostics: registry.diagnostics, showcaseUrl: url.href, acceptedExists, previewOnly: true, previewResult,draftScope:`ads://drafts/${id}/resource?uri=`, next: "Inspect the actual rendered draft. Reopen after edits; accept only the revision you reviewed. Full acceptance checks have not run." };
|
|
249
|
+
}
|
|
250
|
+
async function retire(id) { const session = previews.get(id); previews.delete(id); if (session) { await session.starting; await session.runtime?.close(); rmSync(path.dirname(session.workspace), { recursive: true, force: true }); } }
|
|
251
|
+
async function drop({ id, revision }) {
|
|
252
|
+
if (active) throw new Error("Wait for acceptance before dropping a draft.");
|
|
253
|
+
const value = inspect(id);
|
|
254
|
+
if (revision !== value.revision) throw new Error("Draft revision changed; read ads_drafts again.");
|
|
255
|
+
await retire(id);
|
|
256
|
+
rmSync(path.dirname(manifestFile(id)), { recursive: true });
|
|
257
|
+
return { dropped: true, event: event(id, revision, "dropped") };
|
|
258
|
+
}
|
|
259
|
+
async function accept({ id, revision }, signal, progress) {
|
|
260
|
+
if (closed || active) throw new Error("Wait for the active acceptance, or reopen ADS.");
|
|
261
|
+
const value = inspect(id);
|
|
262
|
+
if(value.dependencyErrors.length)throw new Error(`Draft dependency error: ${value.dependencyErrors[0].message}`);
|
|
263
|
+
if (value.revision !== revision) throw new Error("Draft revision changed. Review the current draft before accepting.");
|
|
264
|
+
if (value.dependencies.length) throw new Error("Accept dependency drafts first. Dependent previews will automatically use their accepted implementations.");
|
|
265
|
+
if (value.conflicts.length) throw new Error(`Draft baseline conflict: ${value.conflicts.join(", ")}`);
|
|
266
|
+
if (!value.changes.length) throw new Error("The draft has no changes to accept. Drop it instead.");
|
|
267
|
+
const groups = new Map();
|
|
268
|
+
for (const file of value.changes) {
|
|
269
|
+
const before = bytes(safe(root, file.target));
|
|
270
|
+
if (isDraftExportEntry(file.target, loadConfig(root)) && before !== null && file.content !== null) {
|
|
271
|
+
const merged=mergeDraftExports(before.toString(),file.content.toString(),before.toString(),file.target,loadConfig(root),value.manifest.units);
|
|
272
|
+
for(const stage of merged.stages)groups.set(stage.unit,(groups.get(stage.unit)??"")+textDiff(file.target,stage.before,stage.content));
|
|
273
|
+
} 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"));
|
|
274
|
+
}
|
|
275
|
+
const plans = value.manifest.units.filter(unit=>groups.has(unit)).map(unit => ({ unit, ...storePreparedPatch(loadConfig(root), groups.get(unit)) })).map(({unit, patchFile}) => ({unit, patchFile}));
|
|
276
|
+
const originals = new Map(value.changes.map(file => [file.target,bytes(safe(root,file.target))]));
|
|
277
|
+
const abort = new AbortController();
|
|
278
|
+
active = { id, abort }; event(id, revision, "checking");
|
|
279
|
+
try {
|
|
280
|
+
const result = await edits.apply(plans.length === 1 ? plans[0] : {patches: plans}, signal ? AbortSignal.any([signal, abort.signal]) : abort.signal, progress, { beforeApply() {
|
|
281
|
+
if (inspect(id).revision !== revision) throw new Error("Draft changed during acceptance; no changes were applied. Review and accept the new revision.");
|
|
282
|
+
} });
|
|
283
|
+
let outcome;
|
|
284
|
+
try{outcome=event(id, revision, result.applied ? "applied" : "failed", { diagnostics: result.diagnostics?.slice(0,3) });}
|
|
285
|
+
catch(error){if(!result.applied)throw error;result.warnings=[...(result.warnings??[]),{rule:"draft-event",message:`Source applied; event storage needs recovery: ${error.message}`}];}
|
|
286
|
+
if (result.applied) {
|
|
287
|
+
const updated = [];
|
|
288
|
+
for (const dependent of ids().filter(other => other !== id)) {
|
|
289
|
+
try{
|
|
290
|
+
const manifest = read(dependent);
|
|
291
|
+
if (manifest.dependencies.includes(id)) {
|
|
292
|
+
for(const file of manifest.files)if(originals.has(file.target)&&file.baseline===fileHash(originals.get(file.target))){
|
|
293
|
+
const accepted=bytes(safe(root,file.target)),source=file.source?bytes(safe(path.dirname(manifestFile(dependent)),file.source)):null;
|
|
294
|
+
if(fileHash(source)===file.baseline){file.baseline=fileHash(accepted);if(file.source&&accepted)atomic(safe(path.dirname(manifestFile(dependent)),file.source),accepted);}
|
|
295
|
+
else if(source&&accepted&&isDraftExportEntry(file.target,loadConfig(root))){
|
|
296
|
+
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. */}
|
|
297
|
+
}
|
|
298
|
+
}
|
|
299
|
+
manifest.dependencies = manifest.dependencies.filter(dependency => dependency !== id); save(manifest); updated.push(dependent);
|
|
300
|
+
}
|
|
301
|
+
}catch(error){result.warnings=[...(result.warnings??[]),{rule:"draft-dependency",message:`Source applied; dependent ${dependent} needs recovery: ${error.message}`}];}
|
|
302
|
+
}
|
|
303
|
+
try{rmSync(path.dirname(manifestFile(id)), { recursive: true });await retire(id);}
|
|
304
|
+
catch(error){result.warnings=[...(result.warnings??[]),{rule:"draft-cleanup",message:`Source applied; draft ${id} cleanup needs recovery: ${error.message}`}];}
|
|
305
|
+
return { ...result, draft: id, revision, event: outcome, updatedDependents: updated };
|
|
306
|
+
}
|
|
307
|
+
return { ...result, draft: id, revision, event: outcome };
|
|
308
|
+
} finally { active = undefined; }
|
|
309
|
+
}
|
|
310
|
+
function draftStamp(){
|
|
311
|
+
const rows=[];
|
|
312
|
+
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.");}}
|
|
313
|
+
walk(storage);if(existsSync(eventFile))rows.push(bytes(eventFile)?.toString());return hash(JSON.stringify(rows));
|
|
314
|
+
}
|
|
315
|
+
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];}})));}
|
|
316
|
+
const timer = setInterval(() => {
|
|
317
|
+
let tracked;try{tracked=draftStamp();}catch{return;}
|
|
318
|
+
for (const [id,session] of previews) {
|
|
319
|
+
if(session.observed===watchStamp(session)+tracked)continue;
|
|
320
|
+
try { prepare(id); } catch(error) { session.error=error.message; }
|
|
321
|
+
}
|
|
322
|
+
}, 1000);
|
|
323
|
+
timer.unref();
|
|
324
|
+
return { list, create, update, show, drop, accept, prepare, events, inspect, tokenGroups,
|
|
325
|
+
readFile(file,{offset=0,limit=12000}={}){
|
|
326
|
+
const parts=file.split("/");
|
|
327
|
+
if(parts[0]!==DRAFT_DIRECTORY||parts.length<3)throw new Error("Use a tracked draft path from ads_drafts.");
|
|
328
|
+
const manifest=read(parts[1]),folder=path.dirname(manifestFile(parts[1]));
|
|
329
|
+
const mapping=manifest.files.find(entry=>entry.source===parts.slice(2).join("/"));
|
|
330
|
+
if(!mapping&&parts.slice(2).join("/")!=="proposal.ads.draft.json")throw new Error("Draft reads are limited to the manifest and registered source files.");
|
|
331
|
+
const content=bytes(safe(folder,parts.slice(2).join("/")));
|
|
332
|
+
if(content===null)throw new Error("Draft source is missing.");
|
|
333
|
+
const binary=content.includes(0)||!Buffer.from(content.toString("utf8")).equals(content),text=content.toString("utf8"),end=offset+limit;
|
|
334
|
+
if(!Number.isSafeInteger(offset)||offset<0||offset>text.length||!Number.isSafeInteger(limit)||limit<1||limit>12000)throw new Error("Invalid draft read range.");
|
|
335
|
+
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};
|
|
336
|
+
},
|
|
337
|
+
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);},
|
|
338
|
+
fingerprint:draftStamp,
|
|
339
|
+
async close() { closed = true; clearInterval(timer); active?.abort.abort(); await Promise.allSettled([...previews.keys()].map(retire)); },
|
|
340
|
+
};
|
|
341
|
+
}
|
|
@@ -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
|
-
|
|
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" } : {}) } },
|
package/dist/mcp/mutations.mjs
CHANGED
|
@@ -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();
|
|
@@ -262,7 +262,8 @@ export function createMutationController(directory, { captures = createCaptureCo
|
|
|
262
262
|
const candidateOptions = loadConfig(candidate);
|
|
263
263
|
// A proposed configuration may add roots or explicit inputs. Preserve
|
|
264
264
|
// already patched files while bringing those additional live inputs in.
|
|
265
|
-
|
|
265
|
+
const proposedInputs = Object.keys(validationInputFiles(candidateOptions));
|
|
266
|
+
copyInputs({root,config:candidateOptions.config,dsRoot:path.resolve(root,candidateOptions.config.dsDir),sourceRoot:path.resolve(root,candidateOptions.config.sourceDir)},candidate,[...patchPaths,...proposedInputs],{baseline:copiedInputs,changed:new Set(changes.map(change=>change.path)),budget:copyBudget});
|
|
266
267
|
const inputPaths = [...new Set([...changes.map(change=>change.path),...Object.keys(validationInputFiles(candidateOptions))])];
|
|
267
268
|
const scopedInputs = () => {
|
|
268
269
|
const files = {};
|
|
@@ -297,7 +298,10 @@ export function createMutationController(directory, { captures = createCaptureCo
|
|
|
297
298
|
const brand = await generateBrandAssets(candidate);
|
|
298
299
|
verified.push({ name: "brand assets", passed: true, skipped: !!brand.skipped });
|
|
299
300
|
}
|
|
300
|
-
for (const check of extraChecks
|
|
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
|
+
}
|
|
301
305
|
boundary=evidenceFailure("runner","behavior-verification","ADS_BEHAVIOR_SETUP");
|
|
302
306
|
const behaviorUnits = affectedBehaviorUnits(candidateOptions, changes.map(change => change.path));
|
|
303
307
|
if (behaviorUnits.length) {
|
|
@@ -328,6 +332,7 @@ export function createMutationController(directory, { captures = createCaptureCo
|
|
|
328
332
|
screenshots = { ok: true, captures: captures.store.list(inspectScenarios(loadConfig(root)).scenarios, screenshots.baseRevision).captures.filter(record => selected.has(record.key)) };
|
|
329
333
|
}
|
|
330
334
|
if (!dryRun) {
|
|
335
|
+
beforeApply?.();
|
|
331
336
|
const written = [];
|
|
332
337
|
const directories = [];
|
|
333
338
|
function mkdir(directory) { if (!existsSync(directory)) { mkdir(path.dirname(directory)); mkdirSync(directory); directories.push(directory); } }
|
|
@@ -3,6 +3,7 @@ import { randomUUID } from "node:crypto";
|
|
|
3
3
|
import { statSync, mkdirSync, 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
|
|
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
|
|
97
|
-
child.stderr
|
|
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.
|