@reqvire-org/ads 0.3.32 → 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.
Files changed (56) hide show
  1. package/README.md +9 -0
  2. package/dist/bootstrap-ds/vite.config.ts +2 -1
  3. package/dist/boundaries.mjs +2 -0
  4. package/dist/capture.mjs +5 -3
  5. package/dist/config.mjs +5 -2
  6. package/dist/draft-boundary.mjs +27 -0
  7. package/dist/draft-workspace.mjs +10 -0
  8. package/dist/lint-config.mjs +1 -0
  9. package/dist/mcp/context.mjs +2 -2
  10. package/dist/mcp/draft-exports.mjs +40 -0
  11. package/dist/mcp/drafts.mjs +341 -0
  12. package/dist/mcp/edit-preparation.mjs +8 -7
  13. package/dist/mcp/execution-results.mjs +2 -0
  14. package/dist/mcp/mutations.mjs +6 -2
  15. package/dist/mcp/preview-watch.mjs +11 -3
  16. package/dist/mcp/preview-widget.bundle.js +13 -13
  17. package/dist/mcp/prompts.mjs +3 -2
  18. package/dist/mcp/server.mjs +75 -18
  19. package/dist/mcp/widget.bundle.js +1 -1
  20. package/dist/preview-files.mjs +2 -0
  21. package/dist/scenarios-compiler.mjs +2 -0
  22. package/dist/scenarios-vite.d.mts +1 -0
  23. package/dist/scenarios-vite.mjs +1 -0
  24. package/dist/showcase/client.bundle.js +43 -43
  25. package/dist/showcase/comparison.js +21 -0
  26. package/dist/showcase/index.html +2 -1
  27. package/dist/showcase/style.css +5 -0
  28. package/dist/skills/README.md +5 -0
  29. package/dist/skills/ads-break-ui/SKILL.md +26 -0
  30. package/dist/skills/ads-break-ui/references/captures.md +7 -0
  31. package/dist/skills/ads-break-ui/references/drafts.md +107 -0
  32. package/dist/skills/ads-break-ui/references/guarded-editing.md +6 -0
  33. package/dist/skills/ads-designer/SKILL.md +26 -0
  34. package/dist/skills/ads-designer/assets/bootstrap-ds/vite.config.ts +2 -1
  35. package/dist/skills/ads-designer/references/captures.md +7 -0
  36. package/dist/skills/ads-designer/references/drafts.md +107 -0
  37. package/dist/skills/ads-designer/references/guarded-editing.md +6 -0
  38. package/dist/skills/ads-import/SKILL.md +26 -0
  39. package/dist/skills/ads-import/references/captures.md +7 -0
  40. package/dist/skills/ads-import/references/drafts.md +107 -0
  41. package/dist/skills/ads-import/references/guarded-editing.md +6 -0
  42. package/dist/skills/ads-motion/SKILL.md +26 -0
  43. package/dist/skills/ads-motion/references/captures.md +7 -0
  44. package/dist/skills/ads-motion/references/drafts.md +107 -0
  45. package/dist/skills/ads-motion/references/guarded-editing.md +6 -0
  46. package/dist/skills/ads-port/SKILL.md +26 -0
  47. package/dist/skills/ads-port/references/captures.md +7 -0
  48. package/dist/skills/ads-port/references/drafts.md +107 -0
  49. package/dist/skills/ads-port/references/guarded-editing.md +6 -0
  50. package/docs/ADS.md +13 -0
  51. package/docs/ARCHITECTURE.md +12 -0
  52. package/docs/CHANGELOG.md +19 -0
  53. package/docs/CONTRACTS.md +8 -0
  54. package/docs/GUIDE.md +17 -5
  55. package/docs/MCP.md +50 -0
  56. package/package.json +1 -1
package/README.md CHANGED
@@ -37,6 +37,9 @@ uses Preact. See [implementation support](docs/GUIDE.md#implementation-support).
37
37
  dry runs that validate architecture, lint and registered project checks.
38
38
  - **Compare visual changes** with on-demand screenshots of current source and
39
39
  proposed candidates, exposed as MCP image resources.
40
+ - **Iterate in tracked drafts** without rerunning acceptance checks after every
41
+ edit. Commit proposals for PR review, compare Accepted/Draft in Explorer, and
42
+ let the agent accept an exact reviewed revision after required checks pass.
40
43
  - **Verify behavior** through project-owned guarantees and registered tests,
41
44
  with progress, timings and evidence tied to current source.
42
45
  - **Keep contracts explicit** for typed paint inputs, scoped data bindings and
@@ -50,6 +53,12 @@ See [using ADS through MCP](docs/GUIDE.md#use-ads-through-mcp) for the workflow
50
53
  [visual captures](docs/MCP.md#screenshots-and-candidate-comparison) for screenshot
51
54
  setup and comparison.
52
55
 
56
+ For iterative work, use the [auto-mode draft workflow](skills/ads-designer/references/drafts.md).
57
+ Drafts can cover token groups, components, patterns and complete views. Pattern
58
+ and composition previews can use dependency drafts through normal `@ds` imports;
59
+ accepting a dependency automatically switches dependent drafts to accepted source.
60
+ Drafts survive restart and Git clone, but cannot enter production imports.
61
+
53
62
  ## Set up your project
54
63
 
55
64
  Run **inside your project**, where `package.json` lives. Use Node 22.12+ or Bun 1.3.13+.
@@ -3,9 +3,10 @@ import { defineConfig } from "vite";
3
3
  import react from "@vitejs/plugin-react";
4
4
  import wyw from "@wyw-in-js/vite";
5
5
  import { linariaTagResolver } from "@reqvire-org/ads/linaria";
6
+ import { draftImportGuard } from "@reqvire-org/ads/scenarios/vite";
6
7
 
7
8
  export default defineConfig({
8
- plugins: [wyw({ tagResolver: linariaTagResolver }), react()],
9
+ plugins: [draftImportGuard(), wyw({ tagResolver: linariaTagResolver }), react()],
9
10
  resolve: {
10
11
  alias: { "@ds/review": path.resolve(import.meta.dirname, "design-system/review/index.ts"), "@ds": path.resolve(import.meta.dirname, "design-system/index.ts") },
11
12
  },
@@ -1,4 +1,5 @@
1
1
  import path from "node:path";
2
+ import { draftImportViolation } from "./draft-boundary.mjs";
2
3
  import ts from "typescript";
3
4
  import { importedUiName } from "./ui-framework.mjs";
4
5
  import { isInside, isStateVariable, isTestFile, isDevelopmentFile } from "./config.mjs";
@@ -51,6 +52,7 @@ export function appImportViolation(specifier, filename, options, resolve = impor
51
52
  }
52
53
 
53
54
  export function showcaseImportViolation(specifier, filename, options, resolve = importResolver(options)) {
55
+ if (draftImportViolation(specifier, filename, resolve)) return true;
54
56
  if (isTestFile(filename)) return false;
55
57
  if (isDevelopmentFile(filename, options)) return false;
56
58
  return resolve(specifier, filename).some((file) => isDevelopmentFile(file, options) || isTestFile(file));
package/dist/capture.mjs CHANGED
@@ -25,13 +25,14 @@ export function createCaptureController(root) {
25
25
  store,
26
26
  status: () => ({ running: !!active, ...(progress ? { progress: { ...progress, elapsedMs: Date.now() - progress.startedAt } } : {}) }),
27
27
  async close() { active?.abort(); await active?.completion; },
28
- async run({ captures, candidateRoot, proposal, publish = true } = {}, signal, notifyProgress) {
28
+ async run({ captures, candidateRoot, proposal, publish = true, previewHosts = [] } = {}, signal, notifyProgress) {
29
29
  if (active) throw new Error("A screenshot capture is already running. Wait for ads_status.captures.running to clear.");
30
30
  const selections = captureSelections(captures);
31
31
  const controller = new AbortController(); active = controller;
32
32
  signal = signal ? AbortSignal.any([signal, controller.signal]) : controller.signal;
33
33
  let finish; controller.completion = new Promise(resolve => { finish = resolve; });
34
34
  const hosts = [];
35
+ const ownedHosts = [];
35
36
  let temporary;
36
37
  const startedAt = Date.now();
37
38
  const update = (stage = progress?.stage ?? "preparing", completed = progress?.completed ?? 0, total = progress?.total ?? selections.length * (candidateRoot ? 2 : 1)) => {
@@ -76,7 +77,8 @@ export function createCaptureController(root) {
76
77
  for (const [projectIndex, project] of projects.entries()) {
77
78
  if (signal.aborted) throw new Error("Screenshot capture cancelled.");
78
79
  if (!project.apps.length) { hosts.push(null); continue; }
79
- const host = await startAdsMcp(project.options.root, { stdio: false, showcase: true });
80
+ const host = previewHosts[projectIndex] ?? await startAdsMcp(project.options.root, { stdio: false, showcase: true });
81
+ if(!previewHosts[projectIndex])ownedHosts.push(host);
80
82
  hosts.push(host);
81
83
  for (const selection of project.apps) {
82
84
  const url = new URL(host.url); url.searchParams.set("scenario", selection.scenario); url.searchParams.set("capture", "1"); url.searchParams.set("theme", selection.theme);
@@ -109,7 +111,7 @@ export function createCaptureController(root) {
109
111
  store.commit(records);
110
112
  return { ok: true, captures: store.list(inspectScenarios(loadConfig(root)).scenarios, projects[0].revision).captures.filter(record => selections.some(selection => captureKey(selection) === record.key)) };
111
113
  } finally {
112
- try { await Promise.all(hosts.map(host => host?.close())); }
114
+ try { await Promise.all(ownedHosts.map(host => host?.close())); }
113
115
  finally { clearInterval(heartbeat); try { if (temporary) rmSync(temporary, { recursive: true, force: true }); } finally { active = undefined; progress = undefined; finish(); } }
114
116
  }
115
117
  },
package/dist/config.mjs CHANGED
@@ -1,5 +1,6 @@
1
1
  import { existsSync, readFileSync, readdirSync } from "node:fs";
2
2
  import path from "node:path";
3
+ import { isDraftFile, draftImportViolation } from "./draft-boundary.mjs";
3
4
  import { isSharedToken } from "./token-policy.mjs";
4
5
 
5
6
  export const supportedFrameworks = ["react", "preact"];
@@ -185,6 +186,7 @@ export function scenarioIdentity(file, dsRoot) {
185
186
  }
186
187
 
187
188
  export function isDevelopmentFile(file, { dsRoot }) {
189
+ if (isDraftFile(file)) return true;
188
190
  if (!isInside(dsRoot, file)) return isTestFile(file) || adsFileRole(file) !== null;
189
191
  const relative = path.relative(dsRoot, file).replaceAll("\\", "/");
190
192
  return adsFileRole(file) !== null || isTestFile(file) || isScenarioFile(file) || isFixtureFile(file) || isBehaviorFile(file)
@@ -195,7 +197,7 @@ export function isDevelopmentFile(file, { dsRoot }) {
195
197
 
196
198
  /** Review implementations may own demo presentation; scenarios/fixtures may not. */
197
199
  export function isReviewFile(file, { dsRoot }) {
198
- return isInside(path.join(dsRoot, "review"), file) && adsFileRole(file) === null && !isTestFile(file) && !isScenarioFile(file) && !isFixtureFile(file) && !isBehaviorFile(file);
200
+ return !isDraftFile(file) && isInside(path.join(dsRoot, "review"), file) && adsFileRole(file) === null && !isTestFile(file) && !isScenarioFile(file) && !isFixtureFile(file) && !isBehaviorFile(file);
199
201
  }
200
202
 
201
203
  const ignored = new Set(["node_modules", "dist", "dist-showcase", "dist-kit", ".git", ".vite", ".ds", "coverage"]);
@@ -204,7 +206,7 @@ export function sourceFiles(root) {
204
206
  if (!existsSync(root)) return [];
205
207
  const files = [];
206
208
  for (const entry of readdirSync(root, { withFileTypes: true })) {
207
- if (ignored.has(entry.name) || entry.isSymbolicLink()) continue;
209
+ if (ignored.has(entry.name) || entry.isSymbolicLink() || isDraftFile(path.join(root, entry.name))) continue;
208
210
  const file = path.join(root, entry.name);
209
211
  if (entry.isDirectory()) files.push(...sourceFiles(file));
210
212
  else if (entry.isFile() && (/\.(css|html|[cm]?[jt]sx?)$/.test(entry.name) || isBehaviorFile(entry.name))) files.push(file);
@@ -213,6 +215,7 @@ export function sourceFiles(root) {
213
215
  }
214
216
 
215
217
  export function importViolation(specifier, filename, options, resolve) {
218
+ if (draftImportViolation(specifier, filename, resolve ?? ((id, file) => [path.resolve(path.dirname(file), id)]))) return true;
216
219
  const { root, dsRoot, config } = options;
217
220
  // ADS implementation code needs its private imports; the showcase is a consumer.
218
221
  if (isInside(dsRoot, filename) && (!isDevelopmentFile(filename, options) || isContractFile(filename))) return false; // Contract symbol ownership is checked without executing imports.
@@ -0,0 +1,27 @@
1
+ import { existsSync, realpathSync } from "node:fs";
2
+ import path from "node:path";
3
+
4
+ export const DRAFT_DIRECTORY = "ads-drafts";
5
+ /** The marker is reserved even outside the conventional tracked directory. */
6
+ export function isDraftFile(file) {
7
+ const name = file.replaceAll("\\", "/").split(/[?#]/)[0];
8
+ return name.split("/").includes(DRAFT_DIRECTORY) || name.endsWith(".ads") || /\.ads\.draft(?:\.|$)/.test(path.basename(name));
9
+ }
10
+ export function draftImportViolation(specifier, importer, resolve) {
11
+ if (isDraftFile(importer)) return false;
12
+ return isDraftFile(specifier) || resolve(specifier, importer).some(file => isDraftFile(file) || existsSync(file) && isDraftFile(realpathSync(file)));
13
+ }
14
+
15
+ /** Install in application bundlers as well as using the mandatory ADS checks. */
16
+ export function draftImportGuard() {
17
+ return { name: "ads-no-draft-imports", enforce: "pre",
18
+ async resolveId(source, importer, options) {
19
+ if (!importer) return;
20
+ if (isDraftFile(source)) this.error("Unaccepted ADS drafts cannot be imported. Preview with ads_show_draft, then accept the exact revision.");
21
+ const resolved = await this.resolve(source, importer, { ...options, skipSelf: true });
22
+ if (resolved && (isDraftFile(resolved.id) || existsSync(resolved.id.split("?")[0]) && isDraftFile(realpathSync(resolved.id.split("?")[0])))) this.error("Unaccepted ADS drafts cannot be imported through aliases or symlinks.");
23
+ return resolved;
24
+ },
25
+ load(id) { if (isDraftFile(id)) this.error("Unaccepted ADS drafts are not production modules."); },
26
+ };
27
+ }
@@ -0,0 +1,10 @@
1
+ import { existsSync, readFileSync, realpathSync } from "node:fs";
2
+ import path from "node:path";
3
+
4
+ /** Only generated, isolated preview workspaces may skip acceptance validation. */
5
+ export function isDraftPreviewWorkspace(root) {
6
+ if (path.basename(root) !== "project" || path.basename(path.dirname(path.dirname(root))) !== "draft-previews" || path.basename(path.dirname(path.dirname(path.dirname(root)))) !== ".ds") return false;
7
+ const marker = path.join(root, ".ds/draft-preview.json");
8
+ try { return existsSync(marker) && realpathSync(root) === root && JSON.parse(readFileSync(marker, "utf8")).previewOnly === true; }
9
+ catch { return false; }
10
+ }
@@ -16,6 +16,7 @@ export function createLintConfig({ root, config }) {
16
16
  const options = { projectRoot: root, sourceDir: config.sourceDir, dsDir: config.dsDir, publicAlias: config.publicAlias, publicEntry: config.publicEntry, reviewEntry: config.reviewEntry, stylesEntry: config.stylesEntry, inlineStyleFiles: config.inlineStyleFiles,
17
17
  configurationFiles: [...configurationFiles({ root, config, sourceRoot: path.resolve(root,config.sourceDir), dsRoot: path.resolve(root,config.dsDir) })].sort() };
18
18
  return {
19
+ ignorePatterns: ["../ads-drafts/**", "**/*.ads", "**/*.ads.draft.*"],
19
20
  jsPlugins: [{ name: "ads", specifier: fileURLToPath(new URL("./oxlint.mjs", import.meta.url)) }, ...projectPlugins],
20
21
  rules: {
21
22
  "ads/public-import": ["error", options],
@@ -6,7 +6,7 @@ import { developmentRuntime, packageScriptCommand } from "../development-runtime
6
6
 
7
7
  export const GUIDE_URI = "ads://project/guide";
8
8
  // Put the task triggers and entry path first: some hosts shorten server guidance.
9
- export const serverInstructions = "Use ADS for UI work: components, patterns, controllers, hooks, tokens, themes, branding, layout, interaction, accessibility, motion and showcase review. Start with ads_status; if tools are not exposed, read ads://project/guide then ads://project/status. Use the returned projectRoot and commands. When ads_status.mutations.enabled, use ads_units and guarded ads_apply_patch for one owner; use ads_apply_transaction only for coupled owner patches. Find existing public UI with ads_catalog; discover its previews with ads_scenarios and open ads_show_scenario. Starting ADS also serves its built-in showcase: use ads_status.showcaseUrl for browser review instead of starting another runtime/compiler or project browser app. Read one relevant ADS skill before editing. Inspect the real preview, edit its owned source, check the build and review again. Scope source/guides to the project, its instruction ancestry and user-selected import/reference sources; broad searches of /mnt or home are not ADS discovery. Domain-model/requirements work is a separate project workflow. For requested visual evidence, use ads_capture or screenshot-enabled patch dry runs; read ads://guides/captures for named targets, image resources and the current/candidate lifecycle. For behavior work, read ads://guides/behaviors and use ads_behaviors/ads_verify: scenario exercises are demonstrations, and registered guarantees need current passing execution evidence. Use ads_validate with scope changed during editing, and the default full scope after test/ownership/config migrations, before releases, or for explicit complete audits. Read ads://guides/validation; report actual scope/revision and inspect failures through ads_results. Execution replies are bounded summaries. Read only needed sections with ads_results(resultId, section, status, cursor); follow nextCursor without rerunning. For a failure, inspect its boundary and acceptance, then ads_investigate with the outcome's exact unit/check/runId; detail sections and artifacts load separately (ads://guides/evidence). Preserve valid APIs when source tracing is inconclusive. After targeted investigation, record suspected ADS defects with ads_report_bug or missing capabilities with ads_request_feature; read ads://guides/reporting. These are local untriaged reports, not established causes or upstream issues. Use the configured project framework and declared dependencies; MCP hosts supply no ad hoc APIs. MCP source checks do not replace browser tests; direct edits still need project checks. Reading HTML is not rendering, and reading a skill is not native activation. A running watcher is not proof of current source: inspect ads_status.build or ads://project/build after edits. Notifications may not reach the agent. Only explicitly enabled mutation tools edit project-owned ADS units after validation. Checks and compiler commands come from validated project configuration, never an ad hoc command argument.";
9
+ export const serverInstructions = "Use ADS for UI work: components, patterns, controllers, hooks, tokens, themes, branding, layout, interaction, accessibility, motion and showcase review. Start with ads_status; if tools are not exposed, read ads://project/guide then ads://project/status. Use the returned projectRoot and commands. When ads_status.mutations.enabled, use tracked auto-mode drafts for iterative design: read ads://guides/drafts, create/edit a draft, inspect ads_show_draft in the browser and call ads_accept with the exact reviewed revision. List pending work with ads_drafts. Do not finish a coherent design change with its requested work left only in drafts; fix acceptance failures or report the blocker as unfinished. Pattern/composition previews may declare draft dependencies using normal @ds imports; accept dependencies first, then review dependent revisions again. Low-level repairs can use ads_units and guarded ads_apply_patch for one owner; use ads_apply_transaction only for coupled owner patches. Find existing public UI with ads_catalog; discover its previews with ads_scenarios and open ads_show_scenario. Starting ADS also serves its built-in showcase: use ads_status.showcaseUrl for browser review instead of starting another runtime/compiler or project browser app. Read one relevant ADS skill before editing. Inspect the real preview, edit its owned source, check the build and review again. Scope source/guides to the project, its instruction ancestry and user-selected import/reference sources; broad searches of /mnt or home are not ADS discovery. Domain-model/requirements work is a separate project workflow. For requested visual evidence, use ads_capture or screenshot-enabled patch dry runs; read ads://guides/captures for named targets, image resources and the current/candidate lifecycle. For behavior work, read ads://guides/behaviors and use ads_behaviors/ads_verify: scenario exercises are demonstrations, and registered guarantees need current passing execution evidence. Use ads_validate with scope changed during editing, and the default full scope after test/ownership/config migrations, before releases, or for explicit complete audits. Read ads://guides/validation; report actual scope/revision and inspect failures through ads_results. Execution replies are bounded summaries. Read only needed sections with ads_results(resultId, section, status, cursor); follow nextCursor without rerunning. For a failure, inspect its boundary and acceptance, then ads_investigate with the outcome's exact unit/check/runId; detail sections and artifacts load separately (ads://guides/evidence). Preserve valid APIs when source tracing is inconclusive. After targeted investigation, record suspected ADS defects with ads_report_bug or missing capabilities with ads_request_feature; read ads://guides/reporting. These are local untriaged reports, not established causes or upstream issues. Use the configured project framework and declared dependencies; MCP hosts supply no ad hoc APIs. MCP source checks do not replace browser tests; direct edits still need project checks. Reading HTML is not rendering, and reading a skill is not native activation. A running watcher is not proof of current source: inspect ads_status.build or ads://project/build after edits. Notifications may not reach the agent. Only explicitly enabled mutation tools edit project-owned ADS units after validation. Checks and compiler commands come from validated project configuration, never an ad hoc command argument.";
10
10
 
11
11
  function manager(root, pkg) {
12
12
  if (typeof pkg.packageManager === "string") return pkg.packageManager.split("@")[0];
@@ -59,7 +59,7 @@ Use this server for UI components/patterns, tokens/themes/branding, layout, inte
59
59
  3. Select one workflow with ads_skills, then ads_read_skill. ${route.skills.map((skill) => `${skill.task}: ${skill.name}`).join("; ")}. Native skill activation is host-controlled. Relative skill references resolve from its SKILL.md URI. Read support files only when relevant.
60
60
  4. ${route.preview} Token samples: ads_scenarios(kind: tokens), then ads_show_scenario or ads_show_tokens(category: id). Token source inspection: ads_tokens with a focused query. Registered previews: ${previews.map((preview) => `${preview.id}: ${preview.tool ?? "ads_show_scenario"}`).join(", ") || "none"}. Showcase URL: ${context.showcase.url ?? "not configured; use the project's showcase command"}.
61
61
  Inspection connects a public export to its owning source, available guides, token values and discovered preview IDs. Bounded tools keep discovery focused; explicit resource reads supply detail. Source metadata does not prove layout, interaction or motion. A scenario renders the real public implementation and its fixture context in either review surface.
62
- 5. Check ads_status.mutations. When enabled, discover one owner with ads_units, read relevant source ranges with ads_read_file and submit only a Git unified diff through ads_apply_patch({unit, patch, dryRun}). Include that owner's scenarios, fixtures and required public re-exports, never peer units. tokens is the foundation unit; its manifest lists companionFiles for required canonical foundation imports when token files are created/deleted in the same patch. Preserve unrelated imports/comments and public-entry statements; a real selected-owner re-export can remove its redundant export {};. Dry-run to inspect validation; apply only a passing patch. Fix rejected patches in the owning unit; use ads_apply_transaction for coupled owners instead of bypassing rejection with direct writes. ads_prepare_patch creates a local owner draft/diff; ads_prepare_token_samples reconciles explicit project bindings without guessing visual meaning. Intentional project setup, registered guard/compiler code and exceptions use configuration; shared globals use foundation, guides documentation and assets their discovered assets/* unit. Keep mandatory ADS gates. Binary/large Git diffs may use patchFile under .ds/patches/ to avoid model-context bytes. In read-only mode, source edits use the client editor/filesystem tools. Reuse the local public API (${context.publicEntry}). Edit presentation in its ADS owner; keep application data/services/routing in application code and development fixtures beside their scenario; larger scenarios live in composition/. Demo framing and token renderers live in development-only review/, imported through ${context.review.importFrom}; never export them from the production barrel or import them into application runtime. Read ads://guides/review for review owners/aliases and ads://guides/contracts when editing static owner declarations, .ads. development roles, constrained paints/bindings or declarative APIs. Contract registration, source evidence and browser verification remain separate. Use ads_prepare_patch action: migrate for a reviewable owner draft, then normal diff and guarded application. Shared foundation Data is the only design-value catalogue. Components/patterns map shared roles; independent owner token namespaces and value sheets are rejected. Existing project font, text and spacing roles take precedence over divergent upstream constants. Read ads://guides/tokens for the source contract and overlap review. Linaria extracts owned styling. Inspect relevant tokens with ads_tokens and source/owning guides before edits.
62
+ 5. For iterative design, read ads://guides/drafts. Use ads_create_draft for a coherent set of owners, normal source edits or ads_update_draft, ads_show_draft for rendered review, then ads_accept with the exact reviewed revision. ads_drafts lists pending work; catalogue entries show draft refs. Pattern/composition drafts can depend on component/pattern/token drafts through ordinary @ds imports in the isolated overlay. Accept dependencies first; dependent drafts then use accepted source automatically and need another review. Do not finish requested design work in an unaccepted draft unless the user explicitly wants a retained proposal. Failed acceptance means unfinished work, not permission to bypass checks. Drop/delete replaces refusal. For low-level repairs and migrations: check ads_status.mutations. When enabled, discover one owner with ads_units, read relevant source ranges with ads_read_file and submit only a Git unified diff through ads_apply_patch({unit, patch, dryRun}). Include that owner's scenarios, fixtures and required public re-exports, never peer units. tokens is the foundation unit; its manifest lists companionFiles for required canonical foundation imports when token files are created/deleted in the same patch. Preserve unrelated imports/comments and public-entry statements; a real selected-owner re-export can remove its redundant export {};. Dry-run to inspect validation; apply only a passing patch. Fix rejected patches in the owning unit; use ads_apply_transaction for coupled owners instead of bypassing rejection with direct writes. ads_prepare_patch creates a local owner draft/diff; ads_prepare_token_samples reconciles explicit project bindings without guessing visual meaning. Intentional project setup, registered guard/compiler code and exceptions use configuration; shared globals use foundation, guides documentation and assets their discovered assets/* unit. Keep mandatory ADS gates. Binary/large Git diffs may use patchFile under .ds/patches/ to avoid model-context bytes. In read-only mode, source edits use the client editor/filesystem tools. Reuse the local public API (${context.publicEntry}). Edit presentation in its ADS owner; keep application data/services/routing in application code and development fixtures beside their scenario; larger scenarios live in composition/. Demo framing and token renderers live in development-only review/, imported through ${context.review.importFrom}; never export them from the production barrel or import them into application runtime. Read ads://guides/review for review owners/aliases and ads://guides/contracts when editing static owner declarations, .ads. development roles, constrained paints/bindings or declarative APIs. Contract registration, source evidence and browser verification remain separate. Use ads_prepare_patch action: migrate for a reviewable owner draft, then normal diff and guarded application. Shared foundation Data is the only design-value catalogue. Components/patterns map shared roles; independent owner token namespaces and value sheets are rejected. Existing project font, text and spacing roles take precedence over divergent upstream constants. Read ads://guides/tokens for the source contract and overlap review. Linaria extracts owned styling. Inspect relevant tokens with ads_tokens and source/owning guides before edits.
63
63
  6. ${route.validation} Registered commands: ${context.commands.map((command) => command.args?.join(" ") ?? `choose the project package manager for ${command.script}`).join("; ") || "none discovered; inspect the project's build setup"}. Run them from ${context.projectRoot}.
64
64
  Execution replies from ads_verify and guarded edits contain counts, acceptance and resultId, not full reports. Read only needed outcomes/diagnostics/captures with ads_results, following nextCursor with identical filters. A truncated row has recordIndex for bounded text ranges. For one failure, use ads_investigate with its unit/check/runId; read request/error/artifact sections only when needed. Only the latest verification and mutation results, and latest investigation per check, are available. Notifications do not establish freshness.
65
65
 
@@ -0,0 +1,40 @@
1
+ import path from "node:path";
2
+ import ts from "typescript";
3
+
4
+ const parse = content => ts.createSourceFile("index.ts", content, ts.ScriptTarget.Latest, true);
5
+ function exportOwner(node, file, options, units) {
6
+ if (!ts.isExportDeclaration(node) || !node.moduleSpecifier || !ts.isStringLiteralLike(node.moduleSpecifier)) return null;
7
+ const target = path.resolve(path.dirname(file), node.moduleSpecifier.text).replace(/\.[cm]?[jt]sx?$/, "");
8
+ return [...units].sort((a,b)=>b.length-a.length).find(unit => {
9
+ const base = path.join(options.dsRoot,unit);
10
+ return target === base || target.startsWith(base + path.sep) || target.startsWith(base + ".");
11
+ }) ?? null;
12
+ }
13
+ const emptyExport = node => ts.isExportDeclaration(node) && !node.moduleSpecifier && node.exportClause && ts.isNamedExports(node.exportClause) && !node.exportClause.elements.length;
14
+ export function isDraftExportEntry(target, options) {
15
+ return [options.config.publicEntry,options.config.reviewEntry].some(entry => path.resolve(options.root,target) === path.join(options.dsRoot,entry));
16
+ }
17
+ /** Shared barrels merge only declared owners' re-exports; all other code is preserved. */
18
+ export function mergeDraftExports(current, proposed, baseline, target, options, units) {
19
+ const file = path.resolve(options.root,target), before = parse(baseline), next = parse(proposed);
20
+ const owner = node => exportOwner(node,file,options,units);
21
+ const cleanup = next.statements.some(owner) && !next.statements.some(emptyExport);
22
+ const unrelated = ast => ast.statements.filter(node => !owner(node) && !(cleanup && emptyExport(node))).map(node=>node.getText(ast));
23
+ if (JSON.stringify(unrelated(before)) !== JSON.stringify(unrelated(next))) throw new Error("Draft public-entry changes may change only declared owners' re-exports; preserve other statements.");
24
+ let result = current;
25
+ const stages = [];
26
+ for (const unit of units) {
27
+ const ast = parse(result), replacement = next.statements.filter(node=>owner(node)===unit).map(node=>node.getFullText(next)).join("");
28
+ let inserted = false;
29
+ let value = ast.statements.map(node => {
30
+ if (owner(node) !== unit) return cleanup && emptyExport(node) ? "" : node.getFullText(ast);
31
+ if (inserted) return "";
32
+ inserted = true; return replacement;
33
+ }).join("");
34
+ if (!inserted && replacement) value += "\n" + replacement;
35
+ value = value.trimEnd() + "\n";
36
+ if (value !== result) stages.push({unit,before:result,content:value});
37
+ result = value;
38
+ }
39
+ return { content:result, stages };
40
+ }
@@ -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
+ }