@reqvire-org/ads 0.3.53 → 0.4.0

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 (138) hide show
  1. package/README.md +9 -8
  2. package/dist/assets.mjs +1 -1
  3. package/dist/behaviors.mjs +6 -5
  4. package/dist/boundaries.mjs +5 -5
  5. package/dist/browser-audit.mjs +10 -5
  6. package/dist/bun-compiler.mjs +14 -7
  7. package/dist/check-service.mjs +83 -0
  8. package/dist/check.mjs +16 -17
  9. package/dist/cli.mjs +4 -2
  10. package/dist/config.mjs +17 -40
  11. package/dist/contracts.d.mts +9 -0
  12. package/dist/fonts-generated.mjs +2 -0
  13. package/dist/generated-entries.mjs +131 -0
  14. package/dist/icons.mjs +1 -1
  15. package/dist/init.mjs +11 -32
  16. package/dist/layers.mjs +7 -3
  17. package/dist/lint-config.mjs +4 -2
  18. package/dist/mcp/catalog.mjs +2 -1
  19. package/dist/mcp/context.mjs +3 -3
  20. package/dist/mcp/drafts.mjs +136 -121
  21. package/dist/mcp/mutations.mjs +65 -19
  22. package/dist/mcp/preview-watch.mjs +31 -5
  23. package/dist/mcp/prompts.mjs +1 -1
  24. package/dist/mcp/server.mjs +79 -38
  25. package/dist/mcp/showcase-host.mjs +20 -7
  26. package/dist/oxlint.mjs +3 -2
  27. package/dist/program-cache.mjs +36 -0
  28. package/dist/public-api.mjs +2 -1
  29. package/dist/scenarios-compiler.mjs +82 -14
  30. package/dist/scenarios-vite.mjs +1 -1
  31. package/dist/scenarios.mjs +4 -3
  32. package/dist/showcase/client.bundle.js +1 -1
  33. package/dist/showcase/index.html +2 -2
  34. package/dist/skills/ads-break-ui/SKILL.md +25 -28
  35. package/dist/skills/ads-break-ui/references/behaviors.md +7 -6
  36. package/dist/skills/ads-break-ui/references/captures.md +7 -32
  37. package/dist/skills/ads-break-ui/references/contracts.md +58 -25
  38. package/dist/skills/ads-break-ui/references/drafts.md +59 -43
  39. package/dist/skills/ads-break-ui/references/evidence.md +1 -1
  40. package/dist/skills/ads-break-ui/references/guarded-editing.md +58 -47
  41. package/dist/skills/ads-break-ui/references/review.md +9 -8
  42. package/dist/skills/ads-break-ui/references/scenarios.md +1 -1
  43. package/dist/skills/ads-break-ui/references/validation.md +8 -4
  44. package/dist/skills/ads-break-ui/references/workflows.md +15 -8
  45. package/dist/skills/ads-designer/SKILL.md +25 -28
  46. package/dist/skills/ads-designer/references/accessibility.md +9 -5
  47. package/dist/skills/ads-designer/references/behaviors.md +7 -6
  48. package/dist/skills/ads-designer/references/captures.md +7 -32
  49. package/dist/skills/ads-designer/references/cli.md +5 -1
  50. package/dist/skills/ads-designer/references/contracts.md +58 -25
  51. package/dist/skills/ads-designer/references/drafts.md +59 -43
  52. package/dist/skills/ads-designer/references/evidence.md +1 -1
  53. package/dist/skills/ads-designer/references/guarded-editing.md +58 -47
  54. package/dist/skills/ads-designer/references/performance.md +3 -2
  55. package/dist/skills/ads-designer/references/review.md +9 -8
  56. package/dist/skills/ads-designer/references/scenarios.md +1 -1
  57. package/dist/skills/ads-designer/references/validation.md +8 -4
  58. package/dist/skills/ads-designer/references/workflows.md +15 -8
  59. package/dist/skills/ads-import/SKILL.md +25 -28
  60. package/dist/skills/ads-import/references/behaviors.md +7 -6
  61. package/dist/skills/ads-import/references/captures.md +7 -32
  62. package/dist/skills/ads-import/references/cli.md +5 -1
  63. package/dist/skills/ads-import/references/contracts.md +58 -25
  64. package/dist/skills/ads-import/references/drafts.md +59 -43
  65. package/dist/skills/ads-import/references/evidence.md +1 -1
  66. package/dist/skills/ads-import/references/guarded-editing.md +58 -47
  67. package/dist/skills/ads-import/references/review.md +9 -8
  68. package/dist/skills/ads-import/references/scenarios.md +1 -1
  69. package/dist/skills/ads-import/references/validation.md +8 -4
  70. package/dist/skills/ads-import/references/workflows.md +15 -8
  71. package/dist/skills/ads-motion/SKILL.md +25 -28
  72. package/dist/skills/ads-motion/references/behaviors.md +7 -6
  73. package/dist/skills/ads-motion/references/captures.md +7 -32
  74. package/dist/skills/ads-motion/references/contracts.md +58 -25
  75. package/dist/skills/ads-motion/references/drafts.md +59 -43
  76. package/dist/skills/ads-motion/references/evidence.md +1 -1
  77. package/dist/skills/ads-motion/references/guarded-editing.md +58 -47
  78. package/dist/skills/ads-motion/references/review.md +9 -8
  79. package/dist/skills/ads-motion/references/scenarios.md +1 -1
  80. package/dist/skills/ads-motion/references/validation.md +8 -4
  81. package/dist/skills/ads-motion/references/workflows.md +15 -8
  82. package/dist/skills/ads-port/SKILL.md +25 -28
  83. package/dist/skills/ads-port/references/behaviors.md +7 -6
  84. package/dist/skills/ads-port/references/captures.md +7 -32
  85. package/dist/skills/ads-port/references/cli.md +5 -1
  86. package/dist/skills/ads-port/references/contracts.md +58 -25
  87. package/dist/skills/ads-port/references/drafts.md +59 -43
  88. package/dist/skills/ads-port/references/evidence.md +1 -1
  89. package/dist/skills/ads-port/references/guarded-editing.md +58 -47
  90. package/dist/skills/ads-port/references/native-implementation.md +6 -6
  91. package/dist/skills/ads-port/references/review.md +9 -8
  92. package/dist/skills/ads-port/references/scenarios.md +1 -1
  93. package/dist/skills/ads-port/references/validation.md +8 -4
  94. package/dist/skills/ads-port/references/workflows.md +15 -8
  95. package/dist/starters/preact/design-system/components/Layout/Grid/Grid.ads.contract.ts +6 -0
  96. package/dist/starters/preact/design-system/review/token-preview/TokenPreview.ads.contract.ts +6 -0
  97. package/dist/starters/preact/ds.config.json +0 -14
  98. package/dist/starters/react/README.md +9 -5
  99. package/dist/starters/react/design-system/components/Actions/Button/Button.ads.exports.ts +1 -0
  100. package/dist/starters/react/design-system/components/Actions/IconButton/IconButton.ads.exports.ts +1 -0
  101. package/dist/starters/react/design-system/components/Content/Icon/Icon.ads.exports.ts +1 -0
  102. package/dist/starters/react/design-system/components/Content/Image/Image.ads.exports.ts +1 -0
  103. package/dist/starters/react/design-system/components/Content/Logo/Logo.ads.exports.ts +1 -0
  104. package/dist/starters/react/design-system/components/Forms/TextField/TextField.ads.exports.ts +1 -0
  105. package/dist/starters/react/design-system/components/Layout/Grid/Grid.ads.contract.ts +6 -0
  106. package/dist/starters/react/design-system/components/Layout/Grid/Grid.ads.exports.ts +1 -0
  107. package/dist/starters/react/design-system/controllers/Palette/Palette.ads.exports.ts +1 -0
  108. package/dist/starters/react/design-system/index.ts +3 -7
  109. package/dist/starters/react/design-system/patterns/Search/SearchBar/SearchBar.ads.exports.ts +1 -0
  110. package/dist/starters/react/design-system/review/brand-preview/BrandPreview.ads.exports.ts +1 -0
  111. package/dist/starters/react/design-system/review/demo-frame/DemoFrame.ads.exports.ts +1 -0
  112. package/dist/starters/react/design-system/review/grid-cell/GridCell.ads.exports.ts +1 -0
  113. package/dist/starters/react/design-system/review/index.ts +4 -3
  114. package/dist/starters/react/design-system/review/screen-frame/ScreenFrame.ads.exports.ts +1 -0
  115. package/dist/starters/react/design-system/review/token-preview/TokenPreview.ads.contract.ts +6 -0
  116. package/dist/starters/react/design-system/review/token-preview/TokenPreview.ads.exports.ts +1 -0
  117. package/dist/starters/react/design-system/styles.css +1 -0
  118. package/dist/starters/react/ds.config.json +0 -14
  119. package/dist/style-boundaries.mjs +7 -6
  120. package/dist/test-boundaries.mjs +2 -2
  121. package/dist/themes-watch.mjs +9 -3
  122. package/dist/token-fixtures.mjs +1 -1
  123. package/dist/unit-contracts.mjs +38 -4
  124. package/dist/units.mjs +16 -91
  125. package/dist/validation-checks.mjs +7 -1
  126. package/docs/ADS.md +10 -10
  127. package/docs/ARCHITECTURE.md +79 -43
  128. package/docs/BEHAVIORS.md +8 -7
  129. package/docs/CACHING.md +15 -6
  130. package/docs/CHANGELOG.md +61 -12
  131. package/docs/COMPARISON.md +1 -1
  132. package/docs/CONTRACTS.md +10 -25
  133. package/docs/GUIDE.md +64 -55
  134. package/docs/MCP.md +116 -151
  135. package/package.json +1 -1
  136. package/dist/contract-migration.mjs +0 -110
  137. package/dist/mcp/draft-exports.mjs +0 -40
  138. package/dist/mcp/edit-preparation.mjs +0 -115
@@ -221,14 +221,71 @@ export async function restoreCompiledPreviews(options, compilerFiles) {
221
221
  return {restored:true,revision:publication.revision,scenarios:entries.length};
222
222
  }
223
223
 
224
- /** Shared scheduling and cache; the project supplies its own React/Preact build. */
225
- export async function runScenarioCompiler(directory, { watched = false, validate, build, buildGraph, compilerFiles = [] }) {
224
+ /** One compile at a time in a process: the viewed draft first, then the project's view, then
225
+ * the project's other requests, then drafts' background work. */
226
+ function createScheduler() {
227
+ const queue = []; let running = false, order = 0;
228
+ function pump() {
229
+ if (running || !queue.length) return;
230
+ queue.sort((a, b) => a.priority - b.priority || a.order - b.order);
231
+ const job = queue.shift(); running = true;
232
+ Promise.resolve().then(job.run).then(job.resolve, job.reject).finally(() => { running = false; pump(); });
233
+ }
234
+ return kind => (run, { foreground = false } = {}) => new Promise((resolve, reject) => {
235
+ queue.push({ run, resolve, reject, order: order++, priority: foreground ? (kind === "draft" ? 0 : 1) : (kind === "draft" ? 3 : 2) });
236
+ pump();
237
+ });
238
+ }
239
+
240
+ /**
241
+ * The draft workspaces the MCP server lists in its control file compile in this process, each
242
+ * with the options setup(root) gives for its own root and a builder of its own. Compiler options
243
+ * fixed to one root cannot build a draft; each draft then reports that instead of waiting.
244
+ */
245
+ function hostDrafts(file, setup, schedule) {
246
+ const instances = new Map();
247
+ async function reconcile() {
248
+ let wanted = [];
249
+ try { wanted = JSON.parse(readFileSync(file, "utf8")).drafts ?? []; } catch { /* No drafts yet. */ }
250
+ const sessions = new Set(wanted.map(entry => entry.session));
251
+ for (const [session, instance] of instances) if (!sessions.has(session)) { instances.delete(session); (await instance)?.stop(); }
252
+ for (const entry of wanted) {
253
+ if (instances.has(entry.session) || !isDraftPreviewWorkspace(entry.root)) continue;
254
+ const context = { session: entry.session, requestFile: entry.requestFile, statusFile: entry.statusFile, prewarm: false, schedule: schedule("draft") };
255
+ if (!setup) {
256
+ instances.set(entry.session, Promise.resolve(null));
257
+ createBuildReporter(entry.root, { apps: [], session: entry.session, file: entry.statusFile })
258
+ .failure(scopedPreviewFailure(new Error("This project's preview compiler passes runScenarioCompiler options for one root, so it cannot build drafts. Pass a function of the root that returns the options instead."), "project", "discovery"));
259
+ continue;
260
+ }
261
+ instances.set(entry.session, runScenarioCompiler(entry.root, draftRoot => ({ ...setup(draftRoot), watched: true, context }))
262
+ .catch(error => { console.error(error); instances.delete(entry.session); }));
263
+ }
264
+ }
265
+ void reconcile();
266
+ let timer;
267
+ const watcher = watch(path.dirname(file), (_event, name) => { if (String(name) === path.basename(file)) { clearTimeout(timer); timer = setTimeout(() => void reconcile(), 16); } });
268
+ return { async stop() { watcher.close(); clearTimeout(timer); for (const instance of instances.values()) (await instance)?.stop(); instances.clear(); } };
269
+ }
270
+
271
+ /**
272
+ * One project's compiler; the project supplies its own React/Preact build. `setup` is the
273
+ * options, or a function of the project root that returns them. A process may host several
274
+ * watched instances, the project and its draft workspaces, each with its own session, request
275
+ * and status file: the project instance hosts the drafts the MCP server lists, building each
276
+ * from setup(draftRoot), so it needs the function form.
277
+ */
278
+ export async function runScenarioCompiler(directory, setup) {
226
279
  const root = path.resolve(directory);
227
- let options = withPreviewSession(loadConfig(root), process.env.ADS_MCP_BUILD_SESSION);
280
+ const { watched = false, validate, build, buildGraph, compilerFiles = [], context = {} } = typeof setup === "function" ? setup(root) : setup;
281
+ const control = process.env.ADS_MCP_DRAFT_CONTROL, hosting = watched && !context.session && control && existsSync(path.dirname(control));
282
+ const scheduler = hosting ? createScheduler() : null;
283
+ const { session: buildSession = process.env.ADS_MCP_BUILD_SESSION, requestFile = process.env.ADS_MCP_REQUEST_FILE, statusFile = process.env.ADS_MCP_BUILD_STATUS, prewarm: prewarmViews = process.env.ADS_MCP_PREWARM_VIEWS === "1", schedule = scheduler ? scheduler("project") : run => run() } = context;
284
+ let options = withPreviewSession(loadConfig(root), buildSession);
228
285
  if (buildGraph && (!options.config.mcp.previewManifest || !options.config.framework)) throw new Error("Resource preview builds require an explicit framework and mcp.previewManifest in ds.config.json.");
229
286
  const cache = createPreviewCache(options, compilerFiles);
230
287
  function registry() {
231
- options = withPreviewSession(loadConfig(root), process.env.ADS_MCP_BUILD_SESSION);
288
+ options = withPreviewSession(loadConfig(root), buildSession);
232
289
  const result = discoverScenarioRegistry(options);
233
290
  if (result.diagnostics.length) throw Object.assign(new Error(result.diagnostics.map(item => `${item.file}: ${item.message}`).join("\n")), { scenarios: result.scenarios });
234
291
  mkdirSync(path.join(root, ".ds/scenarios"), { recursive: true });
@@ -243,11 +300,11 @@ export async function runScenarioCompiler(directory, { watched = false, validate
243
300
  }
244
301
  finally { if (watched && buildGraph) releaseScenarioRegistry(root); }
245
302
  const buildApps = () => entries.map(entry => ({ id: entry.id, file: previewArtifactPath(options, entry.artifact) }));
246
- const reporter = createBuildReporter(root, { apps: buildApps() });
303
+ const reporter = createBuildReporter(root, { apps: buildApps(), ...(buildSession ? { session: buildSession } : {}), ...(statusFile ? { file: statusFile } : {}) });
247
304
  const requested = new Set();
248
305
  const pending = new Set();
249
306
  let active;
250
- const prewarm = watched && process.env.ADS_MCP_PREWARM_VIEWS === "1";
307
+ const prewarm = watched && prewarmViews;
251
308
  const warmed = new Set(), warmFailures = new Set();
252
309
  let preferred, warming;
253
310
  if(prewarm)try{preferred=JSON.parse(readFileSync(path.join(root,".ds/last-preview.json"),"utf8")).scenario;}catch{/* First startup warms the first view. */}
@@ -270,10 +327,14 @@ export async function runScenarioCompiler(directory, { watched = false, validate
270
327
  let observedSourceRevision = previewSourceRevision(options);
271
328
  let invalidation;
272
329
  let fullRequest, completedFull;
273
- const inspector = watched && buildGraph ? createScenarioInspector(root) : null;
330
+ // Keep the registry inspector warm while previews are in use: a cold TypeScript program costs ~1.7 s per edit.
331
+ const inspector = watched && buildGraph ? createScenarioInspector(root, { idleMs: 10 * 60 * 1000 }) : null;
274
332
  let discovering, unknownRevision;
275
333
  let liveCandidate, verifying = false;
334
+ let handle;
276
335
  function failure(error) {
336
+ // A retired draft workspace is deleted while its instance stops: nothing left to report.
337
+ if (watched && !existsSync(root)) { handle?.stop(); return; }
277
338
  try { reporter.failure(scopedPreviewFailure(error,"project","discovery")); } catch (reportError) { console.error(reportError); }
278
339
  console.error(error);
279
340
  if (!watched) process.exitCode = 1;
@@ -589,7 +650,8 @@ export async function runScenarioCompiler(directory, { watched = false, validate
589
650
  const id = pending.has(active) ? active : pending.values().next().value;
590
651
  pending.delete(id);
591
652
  const entry = entries.find(entry => entry.id === id);
592
- if (entry) {warming=id;warmProgress();try{await compile(entry);}finally{warming=undefined;warmProgress();}}
653
+ // Instances in one process take turns: the viewed draft, then the project, then warming.
654
+ if (entry) {warming=id;warmProgress();try{await schedule(() => compile(entry), { foreground: id === active });}finally{warming=undefined;warmProgress();}}
593
655
  }
594
656
  } catch (error) { failure(error); }
595
657
  finally { compiling = false; }
@@ -612,11 +674,11 @@ export async function runScenarioCompiler(directory, { watched = false, validate
612
674
  }).catch(error => { if (!stopped) failure(error); }).finally(() => { discovering = undefined; });
613
675
  }
614
676
  function request(startBuild = true) {
615
- const file = process.env.ADS_MCP_REQUEST_FILE;
677
+ const file = requestFile;
616
678
  if (!file || !existsSync(file)) return;
617
679
  try {
618
680
  const value = JSON.parse(readFileSync(file, "utf8"));
619
- if (value.session !== process.env.ADS_MCP_BUILD_SESSION) return;
681
+ if (value.session !== buildSession) return;
620
682
  if (typeof value.full === "string" && /^[\w-]{1,100}$/.test(value.full)) fullRequest = value.full;
621
683
  if (value.invalidation !== invalidation) {
622
684
  invalidation = value.invalidation;
@@ -658,7 +720,7 @@ export async function runScenarioCompiler(directory, { watched = false, validate
658
720
  try {
659
721
  // Registry inspection for live graphs runs in the verification worker.
660
722
  // Existing entry identities can compile immediately while it checks.
661
- if (buildGraph) options = withPreviewSession(loadConfig(root), process.env.ADS_MCP_BUILD_SESSION);
723
+ if (buildGraph) options = withPreviewSession(loadConfig(root), buildSession);
662
724
  else entries = registry();
663
725
  observedSourceRevision = previewSourceRevision(options);
664
726
  registryFailure = undefined;
@@ -708,7 +770,7 @@ export async function runScenarioCompiler(directory, { watched = false, validate
708
770
  if (addWatch(directory, (event, file, topology) => sourceChanged(event, file && path.join(relative, file), topology)) && !initial) sourceChanged("rename", relative, true);
709
771
  }
710
772
  mkdirSync(path.join(root, ".ds"), { recursive: true });
711
- addWatch(path.join(root, ".ds"), (_event, file) => { if (file === path.basename(process.env.ADS_MCP_REQUEST_FILE ?? "")) request(); });
773
+ addWatch(path.join(root, ".ds"), (_event, file) => { if (file === path.basename(requestFile ?? "")) request(); });
712
774
  for (const [directory, { watcher }] of watchers) if (!wanted.has(directory) || !existsSync(directory)) {
713
775
  watcher.close(); watchers.delete(directory);
714
776
  if (!initial && directory !== root && directory !== path.join(root, ".ds")) sourceChanged("rename", path.relative(root, directory), true);
@@ -717,6 +779,8 @@ export async function runScenarioCompiler(directory, { watched = false, validate
717
779
  }
718
780
  reconcileWatches(true);
719
781
  const reconcileTimer = setInterval(() => {
782
+ // A retired draft workspace disappears before its host stops this instance.
783
+ if (!existsSync(root)) { handle.stop(); return; }
720
784
  reconcileWatches();
721
785
  try {
722
786
  const current = previewSourceRevision(options);
@@ -730,9 +794,13 @@ export async function runScenarioCompiler(directory, { watched = false, validate
730
794
  request();
731
795
  if(prewarm)void drain();
732
796
  console.log(`Scenario compiler ready: ${entries.length} entries; ${prewarm?"sequential background warming enabled":"builds are requested on demand"}.`);
733
- for (const signal of ["SIGINT", "SIGTERM"]) process.once(signal, () => {
797
+ const drafts = hosting ? hostDrafts(control, typeof setup === "function" ? setup : null, scheduler) : null;
798
+ handle = { stop() {
799
+ if (stopped) return;
734
800
  stopped = true; clearTimeout(timer); clearInterval(reconcileTimer); for (const { watcher } of watchers.values()) watcher.close();
801
+ void drafts?.stop();
735
802
  void inspector?.close();
736
803
  void buildGraph?.close?.();
737
- });
804
+ } };
805
+ return handle;
738
806
  }
@@ -28,7 +28,7 @@ export function scenarioRegistryPlugin(directory = process.cwd()) {
28
28
  },
29
29
  configureServer(server) {
30
30
  const changed = (file) => {
31
- if (!isInside(options.dsRoot, file) || !/\.(?:scenario\.[jt]sx?|[jt]sx?)$/.test(file)) return;
31
+ if (!isInside(options.dsRoot, file) || !/\.[jt]sx?$/.test(file)) return;
32
32
  const module = server.moduleGraph.getModuleById(resolved);
33
33
  if (module) { server.moduleGraph.invalidateModule(module); server.ws.send({ type: "full-reload" }); }
34
34
  };
@@ -4,6 +4,7 @@ import ts from "typescript";
4
4
  import { publicApi, scenarioApi } from "./public-api.mjs";
5
5
  import { uiOperation } from "./ui-framework.mjs";
6
6
  import { isDevelopmentFile, isInside, isScenarioFile, scenarioIdentity, sourceFiles } from "./config.mjs";
7
+ import { cachedProgram } from "./program-cache.mjs";
7
8
  import { projectCompilerOptions } from "./boundaries.mjs";
8
9
  import { inspectTokens } from "./tokens.mjs";
9
10
  import { isSharedToken } from "./token-policy.mjs";
@@ -44,7 +45,7 @@ export function inspectScenarios(options, suppliedProgram) {
44
45
  const { root, dsRoot } = options;
45
46
  const files = sourceFiles(dsRoot).filter(isScenarioFile);
46
47
  const contracts = inspectUnitContracts(options, suppliedProgram);
47
- const program = suppliedProgram ?? contracts.program ?? ts.createProgram([path.join(dsRoot, options.config.publicEntry), path.join(dsRoot, options.config.reviewEntry), ...files], { ...projectCompilerOptions(options), allowJs: true });
48
+ const program = suppliedProgram ?? contracts.program ?? cachedProgram(`scenarios:${options.root}`, [path.join(dsRoot, options.config.publicEntry), path.join(dsRoot, options.config.reviewEntry), ...files], { ...projectCompilerOptions(options), allowJs: true });
48
49
  const apis = scenarioApi(program, options);
49
50
  const duplicate = apis.find((item, index) => apis.some((other, otherIndex) => index !== otherIndex && item.name === other.name));
50
51
  const known = new Map(apis.filter(item => item.kind !== "controllers").map((item) => [item.name, item]));
@@ -106,9 +107,9 @@ export function inspectScenarios(options, suppliedProgram) {
106
107
  if (props && !optional && checker.getTypeOfSymbolAtLocation(props, source).getProperties().some(item => !(item.flags & ts.SymbolFlags.Optional))) report(file, "Scenario entrypoints cannot require caller props. Supply required inputs in the colocated fixture adapter.");
107
108
  }
108
109
  }
109
- const fixtureBase = path.basename(file).startsWith("Scenario.") ? path.join(path.dirname(file), "fixture") : file.replace(/\.scenario\.[^.]+$/, ".fixture");
110
+ const fixtureBase = file.replace(/\.ads\.scenario\.[^.]+$/, ".ads.fixture");
110
111
  const fixture = [".ts", ".tsx", ".js", ".jsx", ".mts", ".cts", ".mjs", ".cjs", ".json"].map(extension => fixtureBase + extension).find(existsSync);
111
- if (!fixture) report(file, "Keep this scenario's inputs beside it: fixture.ts (directory entry) or <Owner>.fixture.ts (flat entry). An empty fixture is valid for a component without inputs.");
112
+ if (!fixture) report(file, "Keep this scenario's inputs beside it in <Owner>.ads.fixture.ts. An empty fixture is valid for a component without inputs.");
112
113
  function entryNode(field, index) {
113
114
  let value = metadataExpression;
114
115
  const seen = new Set();
@@ -122,4 +122,4 @@ container holding the app. Specify either width or maxWidth, and either height o
122
122
  `)}function l_(){Se(fe?"Updating preview…":"Opening preview…",!1,"reloading")}function mn(){return sa().find((e)=>e.id===De[te])}function fn(e=mn()){let t=un.find((r)=>r.id===Hc&&Sd.get(r.id)?.scenario===e?.id);return e?.drafts?.find((r)=>r.id===Hc)??t??e?.drafts?.[0]}function yd(){return Boolean(fn()&&(mn()?.draftOnly||hn))}function ra(){return`${te}:${De[te]}${yd()?`:draft:${fn().id}`:""}`}function Dc(e=fe){return e?.key===ra()}function u_(e=na){if(yd()){let t=e?.drafts?.find((r)=>r.id===fn()?.id);return t?.scenarios?.find((r)=>r.id===De[te])??t}return e?.previews?.find((t)=>t.id===De[te])}var d_=(e)=>JSON.stringify(e&&[e.session,e.revision,e.current,e.live]);function p_(){({scenarios:Gc,categories:_d}=WS(gd,r_,un,Sd))}function qw(e){Sd.set(e.structuredContent.id,e.structuredContent),p_()}async function fd(e,t,r=so.signal){let o=(rt?.previewWatch?.buildTimeoutMs??30000)+15000;try{return await i_(e,t,{signal:AbortSignal.any([so.signal,r]),timeout:o})}catch(n){if(n.code!=="REQUEST_TIMEOUT")throw n;throw Object.assign(Error(`The preview request timed out after ${Math.ceil(o/1000)} seconds. No preview result was received. Retry the preview.`,{cause:n}),{code:"ADS_PREVIEW_REQUEST_TIMEOUT",category:"transport"})}}async function vd(e,t,r){let o=mn()?.id===t&&mn().pendingDraftScenario||e.units?.includes(t)&&!gd.some((s)=>s.id===t),n=await fd("ads_show_draft",{id:e.id,...!o&&t?{scenario:t}:{}},r);if(n.isError)throw Error(n.content?.find((s)=>s.type==="text")?.text??"Draft preview failed.");if(o){let s=n.structuredContent.scenarios.find((i)=>t==="tokens"?i.kind==="tokens":i.unit?i.unit===t:ad(t,i.id));if(!s)throw Error("Draft owner has no scenario yet. Add an independently mountable scenario before previewing it.");if(s.id!==n.structuredContent.scenario)n=await fd("ads_show_draft",{id:e.id,scenario:s.id},r);if(n.isError)throw Error(n.content?.find((i)=>i.type==="text")?.text??"Draft preview failed.")}return qw(n),n}function Wt(e=!1){if(e)cn=fe?.key;dn=void 0,k("loader").hidden=!0,k("preview").setAttribute("aria-busy","false")}function t_(e){let t=new URL(location.href);for(let n of["scenario","category","draft","split","section"])t.searchParams.delete(n);if(te==="icons")return t.searchParams.set("section","icons"),t.pathname+t.search+t.hash;if(e)t.searchParams.set("scenario",e);let r=sa().find((n)=>n.id===e),o=fn(r);if(o&&(r.draftOnly||hn)){if(t.searchParams.set("draft",o.id),!r.draftOnly)t.searchParams.set("split","1")}return t.pathname+t.search+t.hash}function sa(){return te==="tokens"?_d:te==="icons"?[]:Gc.filter((e)=>e.kind===te)}function h_(e,t){let{state:r,label:o}=KS(t,na,Hc),n=e.querySelector(".entry-preview");if(!n)n=document.createElement("span"),n.className="entry-preview",n.setAttribute("aria-hidden","true"),e.append(n);n.dataset.state=r,n.title=o,n.innerHTML=`<svg viewBox="0 0 16 16">${GS[r]}</svg>`,e.dataset.buildState=r,e.setAttribute("aria-description",o)}var ln=!1;function io(){return{theme:hd(),adsTheme:Kt,...mt?{adsBrand:mt}:{},gridOverlay:ln,displayMode:"inline",containerDimensions:{width:k("frame-slot").clientWidth,height:k("frame-slot").clientHeight}}}function ia(){let e=Gc.some((n)=>n.kind==="brand");if(k("sections").querySelector('[data-section="brand"]').hidden=!e,te==="brand"&&!e)te="tokens";if(k("sections").querySelector('[data-section="icons"]').hidden=!rt?.icons,te==="icons"&&!rt?.icons)te="tokens";document.body.dataset.activeSection=te;let t=sa();if(!t.some((n)=>n.id===De[te]))De[te]=t[0]?.id??null;history.replaceState(null,"",t_(De[te]));let r=k("sidebar").scrollTop;k("entries").setAttribute("aria-label",te[0].toUpperCase()+te.slice(1));let o=(n)=>{let s=document.createElement("a");if(s.textContent=n.title,n.drafts?.length){let i=document.createElement("span");i.className="draft-badge",i.textContent=n.drafts.length>1?`Drafts ${n.drafts.length}`:"Draft",i.title=n.draftOnly?"Draft only; no accepted version yet":"Draft available; use Split view to compare",s.append(" ",i)}if(s.href=t_(n.id),s.dataset.scenario=n.id,h_(s,n),n.id===De[te])s.setAttribute("aria-current","page");return s.addEventListener("click",(i)=>{if(i.button||i.metaKey||i.ctrlKey||i.shiftKey||i.altKey)return;i.preventDefault(),De[te]=n.id,ia(),Gt().catch(ft)}),s};k("entries").replaceChildren(...VS(t).flatMap((n)=>{if(!n.label)return n.entries.map(o);let s=`${te}:${n.label}`,i=document.createElement("details");i.className="entry-group",i.open=e_.get(s)??!0;let a=document.createElement("summary");a.textContent=n.label;let l=document.createElement("div");return l.setAttribute("role","group"),l.setAttribute("aria-label",n.label),l.append(...n.entries.map(o)),i.append(a,l),i.addEventListener("toggle",()=>{if(i.isConnected)e_.set(s,i.open)}),[i]})),k("sidebar").scrollTop=r;for(let n of k("sections").querySelectorAll("button"))if(n.dataset.section===te)n.setAttribute("aria-current","page");else n.removeAttribute("aria-current");Wc()}function ft(e){if(!Xc&&!ta)Wt(),k("status").dataset.errorCategory=e.category??(e.code==="ADS_RESOURCE_TRANSPORT"?"transport":"runner"),k("status").dataset.errorCode=e.code??"ADS_HOST_STARTUP",Se(`${e.message}${fe?`
123
123
  The retained preview is not verified against the current source.`:""}`,!0)}async function Sr(e){if(!e)return;try{await e.teardownResource({},{timeout:500})}catch{}await e.close()}function m_(){if(Xc||ta)return;ta=!0,so.abort(),++Ye,clearTimeout(Jc),Wt(),Se("MCP disconnected. The retained preview is stale. Refresh the page after restarting ADS.",!0);let e=ve;ve=void 0,Sr(e),++Ot,oa()}async function zd(){let e=await bd("ads://project/explorer");if(rt=e.status,na=rt.build,Yc=e.tools,rt.themes?.length){if(ot=rt.themes,!ot.some((s)=>s.name===Kt))Kt=ot[0].name;o_(),ve?.setHostContext(io())}no=rt.brands??[],mt=no.some((s)=>s.name===mt)?mt:no[0]?.name??null,n_(),ve?.setHostContext(io()),r_=e.categories,gd=e.scenarios,un=e.drafts,k("title").textContent=(rt.drafts?.previewOnly?"Draft · ":"")+rt.project.showcase.title,k("title").title=rt.projectRoot,p_();let t=Xi?QS:De[te],r=Xi&&un.find((s)=>s.id===Hc),o=fe?.draft&&un.find((s)=>s.id===fe.draftId);if(r||o&&ye&&(o.revision!==ye.revision||ye.discovery?.state==="pending")){let s=await vd(r||o,r?QS:ye.scenario);if(r)t=s.structuredContent.scenario;if(fe?.draft&&o){ye=s.structuredContent,Kc=s;for(let i of _r)if(i.side==="draft")await i.updateResult(s)}}let n=Gc.find((s)=>s.id===t);if(n&&Mw.includes(n.kind))te=n.kind,De[te]=n.id;else if(Xi&&_d.some((s)=>s.id===t))te="tokens",De.tokens=t;else if(Xi&&Fe.get("section")==="icons"&&rt.icons)te="icons";Xi=!1,ia()}function Gt({force:e=!1}={}){if(ta)return Promise.resolve();if(te==="icons")return Lw(e);if(Fc=!1,k("frame-slot").querySelector(":scope > .icons-view"))k("frame-slot").replaceChildren();let t=De[te],r=ra();if(an?.key===r)return an.promise;if(!e&&ea?.key===r)return Promise.resolve();if(!e&&!an&&fe?.key===r)return Promise.resolve();ea=void 0;let o={key:r};return an=o,o.promise=jw(t,r,te==="tokens").finally(()=>{if(an===o)an=void 0}),o.promise}async function jw(e,t,r){Vc?.abort();let o=Vc=new AbortController,n=++Ye;dn=!0,k("loader").hidden=t===cn,k("preview").setAttribute("aria-busy","true");try{if(++Ot,await oa(),n!==Ye)return;if(yd()){await Sr(ve),ve=void 0,gr=void 0,Bt=void 0;let u=fn(),d=await vd(u,e,o.signal);if(n!==Ye)return;if(ye=d.structuredContent,Kc=d,mn()?.pendingDraftScenario||!sa().some((m)=>m.id===e))De[te]=ye.scenario;fe={key:ra(),id:ye.scenario,draftId:u.id,generation:n,draft:!0},Wc(),await Dw(),ia(),Wt(!0),Se("Draft preview only. Acceptance checks have not run.",!1,"ready");return}if(ye=void 0,Wc(),!e&&!r){if(await Sr(ve),n!==Ye)return;ve=void 0,fe=void 0,cn=void 0,gr=void 0,Bt=void 0,k("frame-slot").replaceChildren(),Wt(),Se("No scenarios discovered. Colocate an independently mountable scenario and fixture with the public implementation.");return}let s=Yc.find((u)=>u.name===(r?"ads_show_tokens":"ads_show_scenario"));if(!s?._meta?.ui?.resourceUri)throw Error("The server did not expose a preview App tool.");let i=r?e?{category:e}:{}:{id:e};if(s.inputSchema?.properties?.waitFor)i.waitFor=Fe.get("capture")==="1"||Fe.get("waitFor")==="verified"?"verified":"compiled";l_();let a=await fd(s.name,i,o.signal);if(n!==Ye)return;if(a.isError)throw Object.assign(Error(a.content?.find((u)=>u.type==="text")?.text??"Preview build failed."),a.structuredContent?.failure);fe={key:t,id:e,generation:n,token:r&&!a.structuredContent?.scenario,build:a.structuredContent?.build,manifestRevision:a.structuredContent?.manifestRevision};let l=await Uw(s._meta.ui.resourceUri);if(n!==Ye)return;if(gr==="ui://ads/preview"&&!fe.manifestRevision)throw Error("The resource preview has no manifest revision.");if(cn!==t)cn=void 0;if(await l.sendToolInput({arguments:i}),await l.sendToolResult(a),n===Ye&&!a.structuredContent?.manifestUri)Wt(!0),Se("")}catch(s){if(n===Ye)ea={key:ra(),build:d_(u_())},ft(s)}}async function Lw(e){if(Fc&&!e&&k("frame-slot").querySelector(":scope > .icons-view"))return;Vc?.abort();let t=++Ye;if(!k("frame-slot").querySelector(":scope > .icons-view")){k("loader").hidden=!1,++Ot,await oa();let r=ve;ve=void 0,fe=void 0,cn=void 0,gr=void 0,Bt=void 0,ye=void 0,await Sr(r)}try{let r=await bd(Uc);if(t!==Ye||te!=="icons")return;XS(k("frame-slot"),r),Fc=!0,Wt(),Se(""),Wc()}catch(r){if(t===Ye)ft(r)}}async function Uw(e){if(gr===e&&Bt)return Bt;let t=++dd,r=ve;ve=void 0,gr=e,Bt=(async()=>{await Sr(r);let o=await Bc({uri:e});if(t!==dd||Xc||ta)throw Error("Preview opening was superseded.");let n=o.contents.find((u)=>u.mimeType==="text/html;profile=mcp-app"&&typeof u.text==="string");if(!n)throw Error("The preview resource contains no MCP App.");let s=document.createElement("iframe");s.title="Design-system preview",s.setAttribute("sandbox","allow-scripts allow-same-origin allow-forms"),s.src=Qi,k("frame-slot").replaceChildren(s);let i=new Yi(null,{name:"ADS showcase",version:"1.0.0"},{serverResources:{},serverTools:{},logging:{}},{hostContext:io()});ve=i,i.onreadresource=(u)=>Bc(u),i.oncalltool=a_,i.onloggingmessage=(u)=>{if(i!==ve||u.logger!=="ads-preview"||fe?.generation!==Ye||!Dc()||u.data?.id!==fe?.id)return;let d=u.data.revision===fe.manifestRevision||u.data.selectionRevision===fe.manifestRevision;if(u.data.state==="ready"&&d)fe.manifestRevision=u.data.revision,Wt(!0),Se("");else if(u.data.state==="checking"&&(!dn||d))Wt(!0),Se("Checking changes…");else if(u.data.state==="loading")Se("Updating preview…",!1,"reloading");else if(u.data.state==="reverting")Se("Restoring the last verified preview…",!1,"reverting");else if(u.data.code==="ADS_PREVIEW_REOPEN")ve=void 0,gr=void 0,Bt=void 0,l_(),Sr(i).then(()=>Gt({force:!0})).catch(ft);else if(u.data.state==="error"){if(Wt(),k("status").dataset.errorCategory=u.data.category??"build",k("status").dataset.errorCode=u.data.code??"ADS_PREVIEW_BUILD",u.data.resourceUri)k("status").dataset.resourceUri=u.data.resourceUri;else delete k("status").dataset.resourceUri;Se([u.data.message,u.data.code,u.data.resourceUri].filter(Boolean).join(`
124
124
  `),!0)}},i.onerror=ft;let a,l=new Promise((u,d)=>{a=setTimeout(()=>d(Error("MCP App initialization timed out.")),15000),i.oninitialized=()=>{clearTimeout(a),u()}});i.onsandboxready=()=>i.sendSandboxResourceReady({html:n.text,csp:n._meta?.ui?.csp,sandbox:"allow-scripts allow-forms"});try{await Promise.all([i.connect(new Gi(s.contentWindow,s.contentWindow)),l])}catch(u){throw await Sr(i),u}finally{clearTimeout(a)}return i})();try{return await Bt}catch(o){if(t===dd)gr=void 0,Bt=void 0;throw o}}async function Zw(){let e=fe,t=await bd("ads://project/build");na=t,c_();for(let o of k("entries").querySelectorAll("a[data-scenario]")){let n=sa().find((s)=>s.id===o.dataset.scenario);if(n)h_(o,n)}if(ea?.key===ra()){let o=u_(t);if(o&&(o.current||o.live)&&d_(o)!==ea.build)await Gt({force:!0});return}if(!e||e.token||dn||!Dc(e))return;if(e.draft){let o=t.drafts?.find((i)=>i.id===e.draftId),n=o?.scenarios?.find((i)=>i.id===ye?.scenario)??o,s=n&&JSON.stringify([o?.session,n.revision,n.live?.revision,n.current]);if(n&&(n.current||n.live)&&e.buildSignature!==s){e.buildSignature=s;let i=un.find((a)=>a.id===e.draftId);if(i){let a=await vd(i,ye.scenario);if(fe!==e||dn||!Dc(e))return;ye=a.structuredContent,Kc=a;for(let l of _r)if(l.side==="draft")await l.updateResult(a)}}if(n?.state==="error")Se("Draft preview build failed. Showing the previous preview.",!0);else if(n?.building)Se(n.live||n.state==="checking"?"Draft preview compiled; checking changes…":"Building draft preview… Showing the previous preview.",!1,n.live||n.state==="checking"?"checking":"compiling");else if(n?.current&&pd?.state==="ready")Se("Draft preview ready · unaccepted.");return}if(fe!==e||dn||!Dc(e))return;let r=t.previews.find((o)=>o.id===e.id);if(!r){Se("The selected scenario is no longer registered.",!0);return}if(["idle","building"].includes(r.state)&&e.build?.current&&r.session===e.build.session&&r.revision<=e.build.revision)return;if(r.state==="error"){Se(`${Ra(r)}. Showing an earlier view.
125
- ${Pd(r.diagnostics)}`,!0);return}if(["idle","building"].includes(r.state)){Se(r.live?"Checking changes…":"Compiling changes… The current view is the previous preview.",!1,r.live?"checking":"compiling");return}if(r.current&&(r.revision!==e.build?.revision||r.session!==e.build?.session))await Gt({force:!0})}function aa(e=!1,t=!1){if(Zc||=e,t&&fe?.token)fe.key="invalidated";if(clearTimeout(Jc),s_)return;Jc=setTimeout(()=>{if(ud){aa(e,t);return}ud=(async()=>{if(Zc)Zc=!1,await zd();await Gt(),await Zw()})().catch(ft).finally(()=>{ud=void 0})},150)}async function Dw(){if(!ye)return;let e=ye,t=Kc;pd=void 0;let r=++Ot;if(await oa(),r!==Ot)return;let o=hn&&e.acceptedExists;nt.setAttribute("aria-pressed",String(o));let n=document.createElement("div");n.className="draft-comparison",n.dataset.split=String(o);for(let s of o?["accepted","draft"]:["draft"]){let i=document.createElement("section");i.className="draft-version";let a=document.createElement("h2");a.dataset.version=s,a.textContent=s==="accepted"?"Accepted":"Draft · unaccepted";let l=document.createElement("div");l.className="draft-stage",l.dataset.version=s,i.append(a,l),n.append(i)}k("frame-slot").replaceChildren(n),await Promise.all([...n.querySelectorAll(".draft-stage")].map(async(s)=>{let i=s.dataset.version,a=i==="draft"?t:await i_("ads_show_scenario",{id:e.scenario,waitFor:"compiled"});if(a.isError)throw Error(a.content?.find((d)=>d.type==="text")?.text??"Comparison build failed.");if(r!==Ot)return;let l=Yc.find((d)=>d.name===(i==="draft"?"ads_show_draft":"ads_show_scenario")),u=await BS({slot:s,title:i==="draft"?"Draft version":"Accepted version",sandboxUrl:Qi,resourceUri:l._meta.ui.resourceUri,result:a,readResource:Bc,callTool:a_,context:(d)=>({theme:Kt,...mt?{adsBrand:mt}:{},gridOverlay:ln,displayMode:"inline",containerDimensions:{width:d.clientWidth,height:d.clientHeight}}),onError:(d)=>{if(r===Ot)ft(d)},onState:(d)=>{if(r!==Ot||i!=="draft")return;if(pd=d,d.state==="ready")Se("Draft preview ready · unaccepted.");else if(d.state==="checking")Se("Draft preview compiled; checking changes…",!1,"checking");else if(["loading","reverting"].includes(d.state))Se("Updating draft preview…",!1,"reloading")}});if(r!==Ot)await u.close();else _r.push({...u,side:i})}))}function Wc(){let e=mn(),t=Boolean(fn(e))&&!e?.draftOnly;nt.disabled=!t,nt.title=e?.draftOnly?"No accepted version yet":t?"Compare accepted and draft versions":"No draft for this entry",nt.setAttribute("aria-pressed",String(t&&hn));let r=document.querySelector('.draft-version h2[data-version="draft"]');if(r&&ye){let o={draft:"unaccepted",checking:"checking acceptance",failed:"acceptance failed",conflict:"source conflict",interrupted:"acceptance interrupted","dependency-error":"dependency needs attention"};r.textContent=`Draft · ${o[ye.state]??ye.state}`,r.title=ye.dependencies?.length?`Draft dependencies: ${ye.dependencies.join(", ")}`:""}}nt.addEventListener("click",()=>{hn=!hn,ia(),Gt().catch(ft)});for(let e of k("sections").querySelectorAll("button"))e.addEventListener("click",()=>{te=e.dataset.section,ia(),Gt().catch(ft)});var wd=window.matchMedia("(max-width: 760px)");function f_(e){document.body.classList.toggle("collapsed",e),k("pane-toggle").setAttribute("aria-expanded",String(!e)),k("pane-toggle").setAttribute("aria-label",e?"Show navigation pane":"Hide navigation pane"),k("pane-toggle").title=e?"Show navigation pane":"Hide navigation pane",k("pane-toggle").querySelector("path").setAttribute("d",e?"M6 4l4 4-4 4":"M10 4l-4 4 4 4")}var Rd=()=>f_(k("header").hidden||wd.matches);Rd();wd.addEventListener("change",Rd);k("pane-toggle").addEventListener("click",()=>f_(!document.body.classList.contains("collapsed")));function g_(){document.documentElement.dataset.viewport=pn?"phone":"auto",k("viewport").setAttribute("aria-pressed",String(pn)),k("viewport").title=pn?"Use available preview width":"Preview at phone width (390 px)"}g_();k("viewport").addEventListener("click",()=>{pn=!pn,g_();let e=new URL(location.href);if(pn)e.searchParams.set("viewport","phone");else e.searchParams.delete("viewport");history.replaceState(null,"",e.pathname+e.search+e.hash)});k("theme").addEventListener("click",()=>{Kt=ot[(ot.findIndex((e)=>e.name===Kt)+1)%ot.length].name,o_(),ve?.setHostContext(io())});k("theme").addEventListener("click",()=>{for(let e of _r)e.refreshContext()});k("brand-select").addEventListener("change",()=>{mt=k("brand-select").value,n_(),ve?.setHostContext(io());for(let e of _r)e.refreshContext()});k("grid-overlay").addEventListener("click",()=>{ln=!ln,k("grid-overlay").setAttribute("aria-pressed",String(ln)),k("grid-overlay").setAttribute("aria-label",ln?"Hide grid overlay":"Show grid overlay"),k("grid-overlay").title=k("grid-overlay").getAttribute("aria-label"),ve?.setHostContext(io());for(let e of _r)e.refreshContext()});k("minimize").addEventListener("click",()=>{k("header").hidden=!0,document.body.classList.add("collapsed")});var S_=new ResizeObserver(()=>ve?.setHostContext(io()));S_.observe(k("frame-slot"));k("retry-preview").addEventListener("click",()=>{(async()=>{await zd(),await Gt({force:!0})})().catch(ft)});window.addEventListener("pagehide",()=>{Xc=!0,Vc?.abort(),so.abort(),clearTimeout(Jc),S_.disconnect(),wd.removeEventListener("change",Rd),Sr(ve),++Ot,oa(),md?.close(),Nt.close()},{once:!0});Nt.onclose=m_;Nt.setNotificationHandler("notifications/resources/list_changed",()=>aa(!0));Nt.setNotificationHandler("notifications/tools/list_changed",()=>aa(!0));Nt.setNotificationHandler("notifications/resources/updated",({params:e})=>{if(e.uri===Uc)Fc=!1;aa(e.uri==="ads://project/explorer",e.uri==="ads://project/tokens")});try{if(Qi=(await fetch("/host.json").then((e)=>e.json())).sandboxUrl,!Qi||new URL(Qi).origin===location.origin)throw Error("The separate-origin MCP App sandbox is unavailable.");if(await Nt.connect(new OS(new URL("/mcp",location.href))),md=await Nt.listen({resourcesListChanged:!0,toolsListChanged:!0,resourceSubscriptions:["ads://project/build","ads://project/tokens","ads://project/explorer",Uc]}),md.closed.then((e)=>{if(e!=="local")m_()}),await zd(),s_=!1,await Gt(),Zc)aa()}catch(e){ft(e)}
125
+ ${Pd(r.diagnostics)}`,!0);return}if(["idle","building"].includes(r.state)){Se(r.live?"Checking changes…":"Compiling changes… The current view is the previous preview.",!1,r.live?"checking":"compiling");return}if(r.current&&(r.revision!==e.build?.revision||r.session!==e.build?.session))await Gt({force:!0})}function aa(e=!1,t=!1){if(Zc||=e,t&&fe?.token)fe.key="invalidated";if(clearTimeout(Jc),s_)return;Jc=setTimeout(()=>{if(ud){aa(e,t);return}ud=(async()=>{if(Zc)Zc=!1,await zd();await Gt(),await Zw()})().catch(ft).finally(()=>{ud=void 0})},150)}async function Dw(){if(!ye)return;let e=ye,t=Kc;pd=void 0;let r=++Ot;if(await oa(),r!==Ot)return;let o=hn&&e.acceptedExists;nt.setAttribute("aria-pressed",String(o));let n=document.createElement("div");n.className="draft-comparison",n.dataset.split=String(o);for(let s of o?["accepted","draft"]:["draft"]){let i=document.createElement("section");i.className="draft-version";let a=document.createElement("h2");a.dataset.version=s,a.textContent=s==="accepted"?"Accepted":"Draft · unaccepted";let l=document.createElement("div");l.className="draft-stage",l.dataset.version=s,i.append(a,l),n.append(i)}k("frame-slot").replaceChildren(n),await Promise.all([...n.querySelectorAll(".draft-stage")].map(async(s)=>{let i=s.dataset.version,a=i==="draft"?t:await i_("ads_show_scenario",{id:e.scenario,waitFor:"compiled"});if(a.isError)throw Error(a.content?.find((d)=>d.type==="text")?.text??"Comparison build failed.");if(r!==Ot)return;let l=Yc.find((d)=>d.name===(i==="draft"?"ads_show_draft":"ads_show_scenario")),u=await BS({slot:s,title:i==="draft"?"Draft version":"Accepted version",sandboxUrl:Qi,resourceUri:l._meta.ui.resourceUri,result:a,readResource:Bc,callTool:a_,context:(d)=>({theme:Kt,...mt?{adsBrand:mt}:{},gridOverlay:ln,displayMode:"inline",containerDimensions:{width:d.clientWidth,height:d.clientHeight}}),onError:(d)=>{if(r===Ot)ft(d)},onState:(d)=>{if(r!==Ot||i!=="draft")return;if(pd=d,d.state==="ready")Se("Draft preview ready · unaccepted.");else if(d.state==="checking")Se("Draft preview compiled; checking changes…",!1,"checking");else if(["loading","reverting"].includes(d.state))Se("Updating draft preview…",!1,"reloading")}});if(r!==Ot)await u.close();else _r.push({...u,side:i})}))}function Wc(){let e=mn(),t=Boolean(fn(e))&&!e?.draftOnly;nt.disabled=!t,nt.title=e?.draftOnly?"No accepted version yet":t?"Compare accepted and draft versions":"No draft for this entry",nt.setAttribute("aria-pressed",String(t&&hn));let r=document.querySelector('.draft-version h2[data-version="draft"]');if(r&&ye){let o={draft:"unaccepted",checking:"checking acceptance",failed:"acceptance failed",conflict:"source conflict",interrupted:"acceptance interrupted","dependency-error":"dependency needs attention"};r.textContent=`Draft · ${o[ye.state]??ye.state}`,r.title=ye.dependencies?.length?`Draft dependencies: ${ye.dependencies.join(", ")}`:""}}nt.addEventListener("click",()=>{hn=!hn,ia(),Gt().catch(ft)});for(let e of k("sections").querySelectorAll("button"))e.addEventListener("click",()=>{te=e.dataset.section,ia(),Gt().catch(ft)});var wd=window.matchMedia("(max-width: 760px)");function f_(e){document.body.classList.toggle("collapsed",e),k("pane-toggle").setAttribute("aria-expanded",String(!e)),k("pane-toggle").setAttribute("aria-label",e?"Show navigation pane":"Hide navigation pane"),k("pane-toggle").title=e?"Show navigation pane":"Hide navigation pane",k("pane-toggle").querySelector("path").setAttribute("d",e?"M6 4l4 4-4 4":"M10 4l-4 4 4 4")}var Rd=()=>f_(k("header").hidden||wd.matches);Rd();wd.addEventListener("change",Rd);k("pane-toggle").addEventListener("click",()=>f_(!document.body.classList.contains("collapsed")));function g_(){document.documentElement.dataset.viewport=pn?"phone":"auto",k("viewport").setAttribute("aria-pressed",String(pn)),k("viewport").title=pn?"Use available preview width":"Preview at phone width (390 px)"}g_();k("viewport").addEventListener("click",()=>{pn=!pn,g_();let e=new URL(location.href);if(pn)e.searchParams.set("viewport","phone");else e.searchParams.delete("viewport");history.replaceState(null,"",e.pathname+e.search+e.hash)});k("theme").addEventListener("click",()=>{Kt=ot[(ot.findIndex((e)=>e.name===Kt)+1)%ot.length].name,o_(),ve?.setHostContext(io())});k("theme").addEventListener("click",()=>{for(let e of _r)e.refreshContext()});k("brand-select").addEventListener("change",()=>{mt=k("brand-select").value,n_(),ve?.setHostContext(io());for(let e of _r)e.refreshContext()});k("grid-overlay").addEventListener("click",()=>{ln=!ln,k("grid-overlay").setAttribute("aria-pressed",String(ln)),k("grid-overlay").setAttribute("aria-label",ln?"Hide grid overlay":"Show grid overlay"),k("grid-overlay").title=k("grid-overlay").getAttribute("aria-label"),ve?.setHostContext(io());for(let e of _r)e.refreshContext()});k("minimize").addEventListener("click",()=>{k("header").hidden=!0,document.body.classList.add("collapsed")});var S_=new ResizeObserver(()=>ve?.setHostContext(io()));S_.observe(k("frame-slot"));k("retry-preview").addEventListener("click",()=>{(async()=>{await zd(),await Gt({force:!0})})().catch(ft)});window.addEventListener("pagehide",()=>{Xc=!0,Vc?.abort(),so.abort(),clearTimeout(Jc),S_.disconnect(),wd.removeEventListener("change",Rd),Sr(ve),++Ot,oa(),md?.close(),Nt.close()},{once:!0});Nt.onclose=m_;Nt.setNotificationHandler("notifications/resources/list_changed",()=>aa(!0));Nt.setNotificationHandler("notifications/tools/list_changed",()=>aa(!0));Nt.setNotificationHandler("notifications/resources/updated",({params:e})=>{if(e.uri===Uc)Fc=!1;aa(e.uri==="ads://project/explorer",e.uri==="ads://project/tokens")});try{if(Qi=(await fetch("host.json").then((e)=>e.json())).sandboxUrl,!Qi||new URL(Qi).origin===location.origin)throw Error("The separate-origin MCP App sandbox is unavailable.");if(await Nt.connect(new OS(new URL("mcp",location.href))),md=await Nt.listen({resourcesListChanged:!0,toolsListChanged:!0,resourceSubscriptions:["ads://project/build","ads://project/tokens","ads://project/explorer",Uc]}),md.closed.then((e)=>{if(e!=="local")m_()}),await zd(),s_=!1,await Gt(),Zc)aa()}catch(e){ft(e)}
@@ -1,6 +1,6 @@
1
1
  <!doctype html>
2
2
  <html lang="en" data-theme="light">
3
- <head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>ADS Showcase</title><link rel="stylesheet" href="/style.css"></head>
3
+ <head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>ADS Showcase</title><link rel="stylesheet" href="style.css"></head>
4
4
  <body>
5
5
  <header id="header">
6
6
  <div id="brand"><span class="mark">ADS</span><span id="title">Design System</span><button id="pane-toggle" aria-label="Hide navigation pane" aria-expanded="true" aria-controls="sidebar" title="Hide navigation pane"><svg viewBox="0 0 16 16"><path d="M10 4l-4 4 4 4"/></svg></button></div>
@@ -29,5 +29,5 @@
29
29
  </section>
30
30
  </section>
31
31
  </main>
32
- <script type="module" src="/client.js"></script>
32
+ <script type="module" src="client.js"></script>
33
33
  </body></html>
@@ -59,28 +59,24 @@ inside a different or nested repository. Inspect the selected public API, owning
59
59
  source/available guides and relevant tokens, then mount its discovered scenario.
60
60
  Metadata and source reads do not prove rendered behavior.
61
61
 
62
- For MCP-only guarded editing with `ads_status.mutations.enabled`, discover the
63
- owner with `ads_units`, read
64
- relevant ranges with `ads_read_file` and send only a Git unified diff through
65
- `ads_apply_patch({ unit, patch, dryRun })`. A unit includes its own implementation,
66
- scenarios and fixtures; imported peers remain separate. `tokens` is the token
67
- foundation unit. Unit discovery and file ownership are distinct from preview IDs.
68
- Include only that owner's required re-exports in the public entry; preserve
69
- unrelated statements. Its real re-export may accompany removal of a redundant
70
- `export {};` placeholder; do not add empty exports. A `tokens` manifest lists the foundation
71
- entry in `companionFiles`: when creating/deleting a canonical token file such as
72
- `fonts.css`, include only its required import change there in the same patch.
73
- Preserve other imports/comments and the canonical order. Runtime owner manifests
74
- also list a `ds.config.json` companion: change only that owner's `inlineStyleFiles`
75
- and `boundaries.styleWrites` entries together with its source. Unused permissions
76
- fail the core checks; do not pre-register a boundary without its implementation.
77
- Use `dryRun: true` to
78
- inspect validation, including affected registered behavior checks on the isolated
79
- candidate. For a prepared draft, request its diff and dry-run the returned
80
- `patchFile`; `ads_verify` checks current source and accepts no draft argument.
81
- Applying re-runs the gates. Fix rejected patches in their
82
- owner. Use `ads_apply_transaction` for genuinely coupled owner patches;
83
- never bypass a rejection with direct source writes. Shared styles/helpers use `foundation`, root guides use
62
+ For MCP-only guarded editing with `ads_status.mutations.enabled`, every source change
63
+ goes through a draft: discover the owner with `ads_units`, create its draft with
64
+ `ads_create_draft`, read relevant ranges with `ads_read_file`, edit the draft's files
65
+ or send a Git unified diff with `ads_update_draft({id, revision, patch})`, review it
66
+ with `ads_show_draft`, then `ads_accept` its exact revision (`dryRun: true` checks
67
+ without writing). A unit includes its own implementation, scenarios and fixtures;
68
+ imported peers remain separate. `tokens` is the token foundation unit. Unit
69
+ discovery and file ownership are distinct from preview IDs. An owner is in at most
70
+ one open draft; coupled owners share one draft, and a draft can depend on another
71
+ owner's open draft. Every authored file has one owner: an owner declares its public
72
+ names in `<Owner>.ads.exports.ts` and its style permissions (`styles.writes`,
73
+ `styles.inline`, `customization`) in `<Owner>.ads.contract.ts`. The public barrel,
74
+ review entry and styles entry are generated, so no draft edits them. Unused
75
+ permissions fail the core checks; do not declare a permission without its
76
+ implementation. Acceptance runs the mandatory ADS gates and the project's acceptance
77
+ policy; registered tests run when `acceptance.behaviorChecks` is true. `ads_verify`
78
+ checks current source and accepts no draft argument. Fix a failed acceptance in the
79
+ draft; never bypass a rejection with direct source writes. Shared styles/helpers use `foundation`, root guides use
84
80
  `documentation`, and branding/fonts use their discovered `assets/*` unit.
85
81
  Intentional configuration, rule exceptions, registered guard code and compiler
86
82
  changes use `configuration`; validate the proposed settings and keep mandatory
@@ -303,7 +299,7 @@ may name its review renderer in `covers`; ordinary component/pattern scenarios
303
299
  cover their production subjects. Keep review exports in the separate review entry.
304
300
  Remove redundant helper catalogue scenarios during migration. Product UI retains
305
301
  its real render-coverage requirement. Keep directory ownership anchored by its
306
- implementation entry (`index` or a file matching the directory name) or colocated fixture.
302
+ implementation entry (`index` or a file matching the directory name).
307
303
  Import colocated image/font fixtures so MCP serves them through asset resources.
308
304
  For a broken-image case, use a local failing fixture, rather than an external
309
305
  network failure or a domain-specific CSP exception. Production asset APIs remain
@@ -352,11 +348,12 @@ Run ADS's own gates directly with `ads check`; acceptance and validation do not
352
348
  require Oxlint. Register project-specific checks as explicit package scripts in
353
349
  `mcp.mutationChecks` / `validation.checks`, and behavior tests through ADS contracts.
354
350
  A project can use its own linter in those scripts when desired. Measured renderer properties and documented
355
- non-state hooks use explicit `boundaries`; shared token writes and primitive
356
- state overrides cannot be allowlisted. When migrating JSX inline geometry to
357
- imperative writes, port the source and replace its own boundary entries together
358
- in the owner's patch. Remove obsolete `inlineStyleFiles` entries and unused
359
- `styleWrites` properties; do not broaden permissions to keep a migration passing.
351
+ non-state hooks are declared in the owner's contract (`styles.writes`,
352
+ `styles.inline`, `customization`); shared token writes and primitive state overrides
353
+ cannot be allowed. When moving JSX inline geometry to imperative writes, change the
354
+ source and its contract permissions together in the owner's draft. Remove obsolete
355
+ `styles.inline` entries and unused `styles.writes` properties; do not broaden
356
+ permissions to keep a change passing.
360
357
  Pointer-capture advisories call for review of cancellation, capture loss and
361
358
  teardown, including cleanup delegated to hooks. Verify actual cleanup in a browser;
362
359
  a locally present handler alone does not prove correctness.
@@ -19,7 +19,8 @@ or assume a renderer/library supplied by an MCP host. The framework field select
19
19
  compilation/mounting; controller checks also validate runtime imports. Type-only
20
20
  UI references are allowed, but shared controllers cannot import component/pattern
21
21
  runtime implementations. Keep business data in application adapters. Measured
22
- style writes retain exact `boundaries.styleWrites` properties; they do not allow
22
+ style writes retain the exact properties declared in the owner contract's
23
+ `styles.writes`; they do not allow
23
24
  shared-token overrides or an extra styling layer.
24
25
  Projects explicitly approve installed runtime packages through
25
26
  `behaviorLibraries` in `ds.config.json`; each must also be a `package.json`
@@ -38,7 +39,7 @@ build and browser review; declaring a dependency does not prove it is headless.
38
39
  Register owner behavior in `<Owner>.ads.contract.ts` with actual API and
39
40
  implementation references. The
40
41
  [contract reference](contracts.md) covers static authoring, `.ads.behavior.spec.ts`,
41
- declarative `exercises`, required browser checks and guarded migration.
42
+ declarative `exercises` and required browser checks.
42
43
  A contract declaration alone is not passing evidence. Use
43
44
  `auditBehaviorPaints(frame)` after relevant binding updates to repeat the current
44
45
  App's generic paint audit, in addition to assertions for the named guarantee.
@@ -46,7 +47,7 @@ App's generic paint audit, in addition to assertions for the named guarantee.
46
47
  ## Development boundary
47
48
 
48
49
  Production includes real components, controllers, tokens and compiled styles.
49
- Scenarios and fixtures are included only in previews. Behavior manifests and test
50
+ Scenarios and fixtures are included only in previews. Owner contracts and test
50
51
  files are development/tooling inputs. Runtime imports and public re-exports of
51
52
  those inputs are rejected, including dynamic imports and aliases.
52
53
 
@@ -384,9 +385,9 @@ project policy; registration alone does not require execution at acceptance.
384
385
  `ads_verify` always runs the requested checks. See [validation policies](validation.md). Imported shared
385
386
  controller changes also select dependent contracts conservatively. Rejected and
386
387
  dry-run patches publish no source changes. Verification output stays under `.ds/`.
387
- To check a prepared draft, request its diff and pass the returned `patchFile` to
388
- `ads_apply_patch` with `dryRun:true`. This checks the isolated candidate using the acceptance policy, including
389
- affected behavior contracts and their configured browser preview when enabled. Candidate evidence
388
+ To check a draft, call `ads_accept({id, revision, dryRun:true})`. This checks the
389
+ candidate using the acceptance policy, including affected behavior contracts and
390
+ their browser preview when enabled, rendered through the project's own compiler. Candidate evidence
390
391
  is not persisted as passing evidence for live source. `ads_verify` selects checks
391
392
  for current source and has no draft argument.
392
393
 
@@ -81,43 +81,18 @@ Screenshots hide the text caret and disable animations by default. Set
81
81
  `animations:"allow"` when motion must remain active, and account for nondeterminism.
82
82
  The same capture settings are used for both sides of a candidate comparison.
83
83
 
84
- ## Review a patch without applying it
84
+ ## Review a draft without accepting it
85
85
 
86
- Prepare/diff an owner draft normally, then request screenshots during its guarded
87
- dry run:
86
+ Capture the draft's exact revision beside the accepted version, without acceptance
87
+ checks:
88
88
 
89
89
  ```js
90
- ads_apply_patch({
91
- unit: "components/Example",
92
- patchFile: ".ds/patches/<returned-name>.patch",
93
- dryRun: true,
94
- screenshot: true,
95
- captures: [{ scenario: "components/Example", target: "control", theme: "light" }]
96
- })
90
+ ads_capture({ scenario: "components/Example", target: "control", theme: "light", draft: "<draft id>", revision: "<draft revision>" })
97
91
  ```
98
92
 
99
- The placeholder owner/ID/path must come from discovery/preparation. Transactions
100
- accept the same `screenshot`/`captures` fields. Select 1–8 distinct scenario/target
101
- pairs explicitly; do not capture every affected scenario by default. Ordinary dry
102
- runs and patches create no screenshots. `screenshot:true` requires `dryRun:true`.
103
-
104
- Core, registered lint/project and affected behavior gates pass first. ADS then
105
- captures current source and the isolated candidate under matching theme, viewport,
106
- animation and browser settings. Candidate screenshots survive candidate-directory
107
- cleanup. Final source/conflict checks still run before the pair is published. A
108
- failed/cancelled capture does not replace existing image slots or apply source.
109
- If a scenario/target is newly introduced, `current` is null with an explicit
110
- `currentAbsent` explanation; only the real candidate image exists.
111
-
112
- The edit reply is a summary. Read `ads_results({resultId,section:"captures"})` for
113
- the requested image resource URIs and `section:"diagnostics"` for relevant
114
- messages; follow `nextCursor` when needed. Read image resources explicitly.
115
- Standalone `ads_capture` continues returning its selected capture directly.
116
-
117
- Review those images and diagnostics, fix the draft if necessary, then apply
118
- with `dryRun:false`. Apply reruns all gates. An image is promoted only when the
119
- accepted source revision matches the captured candidate; other proposals remain
120
- stale. Images do not approve a patch or certify interaction/accessibility/parity.
93
+ The placeholder IDs come from discovery and `ads_drafts`. A capture is an explicit
94
+ call: acceptance and its dry run take no screenshots. A new scenario has only a
95
+ candidate image. Edits during capture prevent publication of its image slots.
121
96
 
122
97
  ## Two slots, no automatic history
123
98
 
@@ -42,6 +42,54 @@ the runtime dependency closure. Review custom emitter configurations through
42
42
  the configuration owner before migrating a consuming project. Guards remain tooling. Production prop types
43
43
  belong in runtime files, never inferred from a development contract.
44
44
 
45
+ ## Public names and generated entries
46
+
47
+ Each owner declares its public names in its own `<Owner>.ads.exports.ts`, beside its
48
+ source (`components/Button.ads.exports.ts` for a flat owner,
49
+ `components/Forms/Input/Input.ads.exports.ts` for a directory owner):
50
+
51
+ ```ts
52
+ export { Button } from "./Button";
53
+ export type { ButtonProps } from "./Button";
54
+ ```
55
+
56
+ An exports file holds only named re-exports of its own owner's modules by relative
57
+ path: no `export *`, no other code, no peers' files. Public names are unique across
58
+ owners. ADS generates the public barrel (`publicEntry`, normally `index.ts`) by copying
59
+ every exports file's re-exports with paths rebased onto the barrel, so it names each
60
+ public export directly from its source and a product build never includes an exports
61
+ file. The review entry is generated the same way from the exports files under `review/`. It also generates the styles entry (`stylesEntry`) with one `@import`
62
+ per canonical token sheet in foundation order; the public barrel imports it first.
63
+ Never edit a generated entry: `ads check` reports a stale or hand-edited one
64
+ (`generated-entry`), and the showcase, the MCP server, draft previews, acceptance
65
+ and `ads assets` rewrite them. An exports file belongs to its owner's layer:
66
+ production, or development under `review/`.
67
+
68
+ ## Style permissions
69
+
70
+ An owner declares the style permissions its own code needs in its contract, with
71
+ paths relative to the contract:
72
+
73
+ ```ts
74
+ export default {
75
+ schemaVersion: 1,
76
+ styles: {
77
+ writes: { "./Menu.tsx": ["--ds-menu-x", "--ds-menu-y"] },
78
+ inline: ["./Menu.tsx"],
79
+ },
80
+ customization: ["--ds-menu-gap"],
81
+ } satisfies UnitContract;
82
+ ```
83
+
84
+ `styles.writes` lists the CSS properties or owned `--ds-`/`--ux-`/`--showcase-`
85
+ variables a file writes at runtime (never `cssText`, state variables or shared
86
+ tokens); `styles.inline` lists files that may use inline JSX/factory styles for
87
+ measured geometry; `customization` lists a component's non-state `--ds-*` variables
88
+ that patterns, the showcase and the application may set. Contracts are allowed for
89
+ component, pattern, controller, review and showcase owners; `customization` only for
90
+ components. An unused permission is reported as stale on the contract.
91
+ `ds.config.json` holds no per-owner entries.
92
+
45
93
  ## A contract uses actual implementation references
46
94
 
47
95
  ```ts
@@ -251,34 +299,19 @@ Shared token samples belong under the token directory. See
251
299
  project-specific audits of shared alias relationships. It supplements mandatory
252
300
  core source checks and does not enable independent local values.
253
301
 
254
- ## Migration and MCP editing
302
+ ## MCP editing
255
303
 
256
- Use the static owner contract for new registrations. Competing declarations fail.
304
+ The static owner contract is the only token, paint, declarative-part and behavior
305
+ registration. Competing declarations fail.
257
306
  Contracts participate in discovery, ownership, source revisions, affected-check
258
307
  selection and candidate gates. `ads_units` exposes `contractFile`; `ads_catalog`
259
308
  reports constrained paint paths and declarative parent/consumer/check references.
260
309
  Use bounded file reads and paged detailed results, not repeated whole-project dumps.
261
310
 
262
- Install supporting ADS tooling before migrating a consuming project and reconnect
263
- MCP before replacing a package used by a running server. Then:
264
-
265
- 1. Discover one owner with `ads_units`.
266
- 2. `ads_prepare_patch({ unit, action: "migrate" })` creates a normal local draft.
267
- 3. Review the converted contract, renamed files/imports and migration notes.
268
- 4. `ads_prepare_patch({ unit, action: "diff", draft })` emits its Git patchFile.
269
- 5. Dry-run/apply with `ads_apply_patch`, or a genuinely coupled transaction.
270
-
271
- Migration never edits live source or bypasses gates. It retains stable scenario
272
- IDs, check case IDs and directory ownership. A canonical `<Owner>.ads.scenario.tsx` is the same
273
- development entry as `Scenario.tsx`, even without a production entry or owner
274
- contract. Explicit flat IDs and existing flat peer families remain separate.
275
- An optional static `scenario.id` preserves a legacy
276
- identity when a renamed filename would otherwise be ambiguous; it must stay
277
- inside the owning unit and be unique. Whole-file or unimportable private behavior subjects stay
278
- in legacy registration with a note until deliberately resolved. Unknown runner
279
- globs, custom adapters and documentation references require review. Ambiguous
280
- flat-to-directory renames stay in the legacy form with a migration note so file
281
- ownership cannot silently change. Preserve
282
- licenses, pending drafts and unrelated work; keep transactions within their limits.
283
- There is no alternate JSON contract editor. Do not loosen a guard or make a valid
284
- API private merely to complete a migration.
311
+ A canonical `<Dir>/<Dir>.ads.scenario.tsx` is the development entry of the
312
+ directory owner `<Dir>`, even without a production entry or owner contract. In a
313
+ folder without that entry, each `<Owner>.ads.scenario.tsx` belongs to its own flat
314
+ owner, and an explicit flat `scenario.id` (`<Dir>/<Dir>`) keeps the canonical file
315
+ a flat entry. An optional static `scenario.id` keeps an identity stable when a
316
+ renamed filename would otherwise be ambiguous; it must stay inside the owning unit
317
+ and be unique.