@whzxc/agent-design-gallery 0.14.1 → 0.16.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 (111) hide show
  1. package/README.md +29 -16
  2. package/package.json +2 -1
  3. package/public/access.css +15 -2
  4. package/public/app.js +1284 -521
  5. package/public/arrangement-worker.js +7 -7
  6. package/public/arrangement.js +35 -30
  7. package/public/assets.js +85 -48
  8. package/public/auth.js +59 -4
  9. package/public/boards.js +129 -0
  10. package/public/comment-anchors.js +50 -0
  11. package/public/comments.css +400 -0
  12. package/public/comments.js +1106 -0
  13. package/public/context-menu.js +97 -0
  14. package/public/frame-identity.js +51 -14
  15. package/public/hub.css +25 -3
  16. package/public/hub.html +10 -2
  17. package/public/hub.js +127 -23
  18. package/public/icons.js +9 -0
  19. package/public/index.html +26 -10
  20. package/public/instance-actions.js +9 -2
  21. package/public/layout.js +156 -86
  22. package/public/motion-flow.js +28 -0
  23. package/public/motion-identity.js +100 -0
  24. package/public/motion-paint.js +332 -0
  25. package/public/motion-scene.js +165 -0
  26. package/public/motion-specimens.js +335 -0
  27. package/public/player.css +270 -0
  28. package/public/player.js +753 -0
  29. package/public/recent-updates.js +535 -0
  30. package/public/selection.js +1 -1
  31. package/public/style.css +91 -154
  32. package/public/switcher.css +5 -4
  33. package/public/switcher.js +109 -34
  34. package/public/token-catalog.js +8 -3
  35. package/public/tokens.css +20 -1
  36. package/public/view-boards.css +131 -0
  37. package/public/view-boards.js +350 -0
  38. package/public/view-route.js +1 -2
  39. package/src/boards/board.mjs +30 -0
  40. package/src/boards/motion-board.mjs +202 -0
  41. package/src/boards/token-board.mjs +200 -0
  42. package/src/cli-output.mjs +10 -5
  43. package/src/cli.mjs +89 -35
  44. package/src/comments.mjs +293 -0
  45. package/src/http.mjs +7 -5
  46. package/src/hub/project-link.mjs +41 -0
  47. package/src/hub/registry.mjs +5 -0
  48. package/src/hub.mjs +14 -10
  49. package/src/link.mjs +13 -1
  50. package/src/recent-frames.mjs +295 -0
  51. package/src/recent-history.mjs +100 -0
  52. package/src/recent-job.mjs +63 -0
  53. package/src/recent-worker.mjs +171 -0
  54. package/src/server.mjs +285 -110
  55. package/src/service.mjs +46 -12
  56. package/src/toolkit/arch-git.mjs +8 -14
  57. package/src/toolkit/arch.mjs +3 -2
  58. package/src/toolkit/asset-rules.mjs +24 -1
  59. package/src/toolkit/browser.mjs +1 -13
  60. package/src/toolkit/build-store.mjs +9 -1
  61. package/src/toolkit/build-worker.mjs +6 -0
  62. package/src/toolkit/build.mjs +22 -16
  63. package/src/toolkit/commands.mjs +105 -9
  64. package/src/toolkit/compare.mjs +13 -11
  65. package/src/toolkit/config.mjs +2 -2
  66. package/{public/review.js → src/toolkit/diff-document.mjs} +137 -43
  67. package/src/toolkit/diff-inputs.mjs +97 -52
  68. package/src/toolkit/diff.mjs +198 -43
  69. package/src/toolkit/frame-declarations.mjs +36 -0
  70. package/src/toolkit/git-blobs.mjs +50 -0
  71. package/src/toolkit/impact-inputs.mjs +11 -19
  72. package/src/toolkit/impact-selection.mjs +27 -12
  73. package/src/toolkit/impact.mjs +49 -15
  74. package/src/toolkit/implementation-map.mjs +17 -6
  75. package/src/toolkit/input-generation.mjs +15 -0
  76. package/src/toolkit/inspect-output.mjs +1 -1
  77. package/src/toolkit/inspect.d.ts +9 -1
  78. package/src/toolkit/inspect.mjs +25 -1
  79. package/src/toolkit/motion-check.mjs +382 -0
  80. package/src/toolkit/motion-css.mjs +105 -0
  81. package/src/toolkit/motion-flows.mjs +95 -0
  82. package/src/toolkit/motion-impact.mjs +87 -0
  83. package/src/toolkit/motion-inventory.mjs +202 -0
  84. package/src/toolkit/motion-label.mjs +111 -0
  85. package/src/toolkit/motion-patterns.mjs +216 -0
  86. package/src/toolkit/motion-primitives.mjs +94 -0
  87. package/src/toolkit/motion-queries.mjs +169 -0
  88. package/src/toolkit/motion.mjs +300 -0
  89. package/src/toolkit/move-pairing.mjs +140 -0
  90. package/src/toolkit/owner.mjs +19 -6
  91. package/src/toolkit/play-endpoint.mjs +66 -0
  92. package/src/toolkit/project-index.mjs +4 -4
  93. package/src/toolkit/recent-structure.mjs +201 -0
  94. package/src/toolkit/results.mjs +3 -3
  95. package/src/toolkit/review-document.mjs +440 -0
  96. package/src/toolkit/review-embed-document.mjs +671 -0
  97. package/src/toolkit/review-filmstrip.mjs +76 -0
  98. package/src/toolkit/review-groups.mjs +29 -0
  99. package/src/toolkit/review-motion-card.mjs +51 -0
  100. package/src/toolkit/review-motion.mjs +159 -0
  101. package/src/toolkit/review-observation.mjs +131 -0
  102. package/src/toolkit/review-playback.js +123 -0
  103. package/src/toolkit/review-sheet.mjs +125 -0
  104. package/src/toolkit/review-specimens.mjs +60 -0
  105. package/src/toolkit/review.mjs +240 -0
  106. package/src/toolkit/runtime.mjs +8 -2
  107. package/src/toolkit/theme.mjs +16 -0
  108. package/src/viewer-cache.mjs +48 -12
  109. package/public/annotations.js +0 -816
  110. package/public/labels.js +0 -122
  111. package/src/annotations.mjs +0 -238
@@ -5,12 +5,15 @@ import { groupImpactFrames } from './impact-output.mjs';
5
5
  import { commandFailure } from './results.mjs';
6
6
  import { mkdir, writeFile } from 'node:fs/promises';
7
7
  import path from 'node:path';
8
+ import { resolveThemes } from './theme.mjs';
8
9
 
9
10
  export const impactRowKey = (row, theme) => JSON.stringify([row.source, row.frame, theme]);
10
11
 
11
12
  /** Keep fresh proofs, captures and final generation validation in one owned operation. */
12
13
  export async function withImpacted(config, args, options, command, work) {
13
- if (typeof options.base !== 'string' || !options.base.trim() || options.frame === '' || options.theme !== undefined && !['both', 'light', 'dark'].includes(options.theme)) throw new CliError('USAGE_INVALID', 'Choose --impacted --base=<rev> and a valid frame/theme selection.');
14
+ const themes = resolveThemes(options.theme);
15
+ options = { ...options, theme: themes.length === 2 ? 'both' : themes[0] };
16
+ if (typeof options.base !== 'string' || !options.base.trim() || options.frame === '') throw new CliError('USAGE_INVALID', 'Choose --impacted --base=<rev> and a valid frame/theme selection.');
14
17
  let outcome, failure, selection, workMs = 0;
15
18
  const warnings = [];
16
19
  function discardProofs() {
@@ -22,13 +25,14 @@ export async function withImpacted(config, args, options, command, work) {
22
25
  if (outcome?.data && 'verdict' in outcome.data) outcome.data.verdict = null;
23
26
  }
24
27
  try {
25
- const plan = await impact(config, { base: options.base, json: true, 'state-dir': options['state-dir'], 'out-dir': options['out-dir'], explain: options.explain }, {
28
+ const plan = await impact(config, { base: options.base, head: options.head, openRevision: options.openRevision, json: true, 'state-dir': options['state-dir'], 'out-dir': options['out-dir'], explain: options.explain }, {
26
29
  consume: async session => {
27
30
  const { rows, views, assessments, inputs, data } = session;
28
- const sources = await selectedSources(views[1].config, views[0].config, views[1].config.root, new Set(rows.map(row => row.source)), args);
29
- const themes = options.theme && options.theme !== 'both' ? [options.theme] : ['light', 'dark'];
31
+ const sources = await selectedSources(views[1].config, views[0].config, views[1].config.root,
32
+ new Set([...rows.map(row => row.source), ...data.failures.map(failure => failure.source)]), args);
33
+ const failures = data.failures.filter(failure => sources.includes(failure.source));
30
34
  const chosen = rows.filter(row => sources.includes(row.source) && (options.frame === undefined || row.frame === options.frame));
31
- if (options.frame !== undefined && !chosen.length) {
35
+ if (options.frame !== undefined && !chosen.length && !failures.length) {
32
36
  throw new CliError('FRAME_NOT_FOUND', `Unknown frame ${options.frame}; choose a frame present on either side.`);
33
37
  }
34
38
  const exclusions = { source_filter: 0, frame_filter: 0, theme_filter: 0, hypothetical_input: 0, not_checked: 0 };
@@ -59,17 +63,26 @@ export async function withImpacted(config, args, options, command, work) {
59
63
  const finalize = data => {
60
64
  const coverage = selection.coverage;
61
65
  coverage.renderedRows = command === 'diff' ? data.summary.comparisons + data.summary.supportComparisons : command === 'check' ? data.summary.evaluations : data.captures.length;
66
+ if (command === 'diff') {
67
+ // A revision comparison of a move covers both original impact rows.
68
+ const pairedRows = (data.comparisons ?? []).filter(row => row.previousSource).length;
69
+ coverage.renderedRows += pairedRows;
70
+ coverage.deletedRows -= pairedRows;
71
+ }
62
72
  const deleted = command === 'render' ? coverage.deletedRows : 0;
63
73
  coverage.uncoveredRows = Math.max(0, coverage.expectedRows - coverage.renderedRows - coverage.provenRows - deleted);
64
- coverage.scope = !coverage.expectedRows ? 'empty' : coverage.uncoveredRows || args.length || options.frame !== undefined || themes.length !== 2 ? 'partial' : 'full';
74
+ coverage.scope = failures.length ? 'partial' : !coverage.expectedRows ? 'empty' : coverage.uncoveredRows || args.length || options.frame !== undefined || themes.length !== 2 ? 'partial' : 'full';
65
75
  coverage.basis = command === 'check' ? 'selected' : coverage.renderedRows ? coverage.provenRows ? 'rendered_and_proven' : 'rendered' : coverage.provenRows ? 'proven' : 'selected';
66
76
  data.impact = selection;
67
77
  };
68
78
  const next = [{ argv: ['adg', command, ...(command === 'diff' ? [`--base=${options.base}`] : command === 'check' ? ['--read-only'] : []),
69
79
  ...(options.scale !== undefined && command !== 'check' ? [`--scale=${options.scale}`] : []), '--json'], reason: 'Evaluate the full project without impact filtering.' }];
70
80
  session.selection = selection; session.sources = sources; session.chosen = chosen; session.themes = themes; session.scheduled = scheduled;
71
- session.diffInputs = { ...inputs.session, sources, close: async () => {},
72
- buildFrames: async ({ browser }) => inputs.session.buildFrames({ browser, materialized: views.map(view => view.built),
81
+ session.diffInputs = { ...inputs.session, sources,
82
+ changes: inputs.changes.map(change => Object.fromEntries(['before', 'after'].map(side => [side,
83
+ change[side] === null ? null : path.posix.relative(inputs.projectPrefix || '.', change[side])]))),
84
+ close: async () => {},
85
+ buildFrames: async ({ browser, deferParts }) => inputs.session.buildFrames({ browser, deferParts, materialized: views.map(view => view.built), failures,
73
86
  frame: options.frame, sources: [...new Set(chosen.filter(row => themes.some(theme => scheduled(row, theme))).map(row => row.source))] }) };
74
87
  const workStarted = performance.now();
75
88
  try { outcome = await work(session); } catch (cause) { failure = cause; outcome = { data: cause.data, warnings: cause.warnings ?? [] }; }
@@ -77,23 +90,25 @@ export async function withImpacted(config, args, options, command, work) {
77
90
  if (outcome?.data) {
78
91
  finalize(outcome.data);
79
92
  if (selection.coverage.scope === 'partial') warnings.push({ code: 'IMPACT_COVERAGE_PARTIAL', message: 'Impact selection has partial frame/theme coverage.', next });
80
- if (!failure && !chosen.some(row => (command === 'diff' || row.after) && themes.some(theme => scheduled(row, theme)))) warnings.push({ code: 'IMPACT_NO_CHANGES', message: 'No capture or browser-evaluation jobs were scheduled.', next });
93
+ if (!failure && !outcome.data.motion?.count && !chosen.some(row => (command === 'diff' || row.after) && themes.some(theme => scheduled(row, theme)))) warnings.push({ code: 'IMPACT_NO_CHANGES', message: 'No capture or browser-evaluation jobs were scheduled.', next });
81
94
  }
82
- if (failure && !['CHECK_FAILED', 'DIFF_FAILED'].includes(failure.code)) throw failure;
95
+ if (failure && !['CHECK_FAILED', 'DIFF_FAILED'].includes(failure.code) && !(command === 'diff' && failure.partialSourceFailures === true)) throw failure;
83
96
  },
97
+ tolerateSourceFailures: command === 'diff',
84
98
  });
85
99
  warnings.push(...plan.warnings.filter(w => !['IMPACT_NO_CHANGES', 'IMPACT_NO_MATCH'].includes(w.code)));
86
- if (selection) selection.coverage.proofComplete = true;
100
+ if (selection) selection.coverage.proofComplete = !plan.data.failures.length;
87
101
  if (outcome?.data) outcome.data.timings = { ...outcome.data.timings, impactMs: plan.data.timings.totalMs - workMs, workMs, materializeMs: plan.data.timings.materializeMs, proofMs: plan.data.timings.proofMs, totalMs: plan.data.timings.totalMs };
88
102
  } catch (cause) {
89
103
  discardProofs();
104
+ if (failure) delete failure.partialSourceFailures;
90
105
  if (!outcome?.data) cause.data = null;
91
106
  failure = outcome?.data ? commandFailure(cause, outcome.data, warnings) : cause;
92
107
  }
93
108
  if (outcome) outcome.warnings = [...new Set([...outcome.warnings, ...warnings])];
94
109
  if (outcome?.data?.reportPath) {
95
110
  try { await mkdir(path.dirname(outcome.data.reportPath), { recursive: true }); await writeFile(outcome.data.reportPath, JSON.stringify(outcome.data, null, 2) + '\n'); }
96
- catch (cause) { discardProofs(); outcome.data.reportPath = null; if ('indexPath' in outcome.data) outcome.data.indexPath = null; failure = commandFailure(cause, outcome.data, outcome.warnings); }
111
+ catch (cause) { discardProofs(); outcome.data.reportPath = null; if ('indexPath' in outcome.data) outcome.data.indexPath = null; failure = commandFailure(cause, outcome.data, outcome.warnings); delete failure.partialSourceFailures; }
97
112
  }
98
113
  if (failure) { if (outcome?.data) failure = commandFailure(failure, outcome.data, outcome.warnings); throw failure; }
99
114
  return outcome;
@@ -1,9 +1,11 @@
1
+ import { motionFiles, readMotion, motionSummary } from './motion.mjs';
2
+ import { impactedEdges } from './motion-impact.mjs';
1
3
  import path from 'node:path';
2
4
  import { readFile, realpath, stat } from 'node:fs/promises';
3
5
  import { CliError, nextActions } from '../cli-output.mjs';
4
6
  import { openProjectIndex } from './project-index.mjs';
5
7
  import { prepareImpactInputs, configInputFiles } from './impact-inputs.mjs';
6
- import { matchDiffFrames } from './diff-inputs.mjs';
8
+ import { matchDiffFrames, sourceFailure } from './diff-inputs.mjs';
7
9
  import { selectSources, relative } from './project.mjs';
8
10
  import { loadImplementationMap, implementationFiles } from './implementation-map.mjs';
9
11
  import { normalizeFileQuery, implementationScope } from './implementation-query.mjs';
@@ -42,7 +44,7 @@ function mappingBuild(facts) {
42
44
  }
43
45
 
44
46
  /** Candidate queries and operation-local fresh-input proofs for exact Git endpoints. */
45
- export async function impact(config, values, { log = console.log, openIndex = openProjectIndex, prepareInputs = prepareImpactInputs, consume } = {}) {
47
+ export async function impact(config, values, { log = console.log, openIndex = openProjectIndex, prepareInputs = prepareImpactInputs, consume, tolerateSourceFailures = false } = {}) {
46
48
  const started = performance.now(), themes = themesFor(values);
47
49
  const timings = { prepareMs: 0, indexMs: 0, materializeMs: 0, proofMs: 0, queryMs: 0, totalMs: 0 };
48
50
  const timed = async (name, work) => { const start = performance.now(); try { return await work(); } finally { timings[name] += performance.now() - start; } };
@@ -51,7 +53,11 @@ export async function impact(config, values, { log = console.log, openIndex = op
51
53
  async function track(file) { if (!tracked.has(file)) tracked.set(file, trackedHash(await bytes(file))); }
52
54
  const warn = (code, message, next = []) => { if (!warnings.some(warning => warning.code === code)) warnings.push({ code, message, next }); };
53
55
  const checkNext = reason => [{ argv: ['adg', 'check', '--read-only', '--json'], reason }];
54
- const verifyGeneration=()=>verifyInputGeneration({tracked,views,inputs});
56
+ const verifyGeneration=async()=>{
57
+ await verifyInputGeneration({tracked,views,inputs});
58
+ for(const v of views)if(v.motion && JSON.stringify(v.motion.files)!==JSON.stringify(motionFiles(v.config).map(f=>relative(v.config,f))))
59
+ throw new CliError('IMPACT_INPUT_CHANGED','Motion sidecar inventory changed during query.');
60
+ };
55
61
 
56
62
  try {
57
63
  let query, fileInput;
@@ -67,7 +73,7 @@ export async function impact(config, values, { log = console.log, openIndex = op
67
73
  data = { project: config.root, complete: false, query,
68
74
  before: inputs ? { kind: 'revision', sha: query.base.sha } : null,
69
75
  after: { kind: inputs?.after.revision ? 'revision' : 'working_tree', sha: inputs?.head ?? null },
70
- selection: { themes, explain: !!values.explain }, changes: [], facts: [], frames: [], mappingFindings: [], unresolvedInputs: [],
76
+ selection: { themes, explain: !!values.explain }, changes: [], facts: [], frames: [], failures: [], mappingFindings: [], unresolvedInputs: [],
71
77
  coverage: { inventory: 'incomplete', mapping: 'not_requested', expectedRows: 0, candidateRows: 0, directRows: 0, transitiveRows: 0,
72
78
  renderRows: 0, provenRows: 0, unassessedRows: 0, proofComplete: false,
73
79
  tokenScan: { reachableRows: 0, fullSheetRows: 0, fallbackReasons: [] } }, timings };
@@ -85,18 +91,32 @@ export async function impact(config, values, { log = console.log, openIndex = op
85
91
  views.push(view);
86
92
  for (const file of await configInputFiles(current)) { await track(file); view.configInputs.add(slash(path.relative(await realpath(current.root), file))); }
87
93
  for (const name of ['adg.config.mjs', 'adg.config.js', 'adg.config.ts']) await track(path.join(current.root, name));
94
+ const sidecars=motionFiles(current);
95
+ for(const file of sidecars)await track(file);
96
+ view.motion=readMotion(current,sidecars);
97
+ view.motionBindingHits=new Set();
88
98
  view.tokenFile = path.join(current.design, 'tokens.css');
89
99
  await track(view.tokenFile); view.tokenBytes = await bytes(view.tokenFile);
90
100
  if (inputs) for (const source of index.inventory.tsx) await track(path.join(current.root, source));
91
101
  return view;
92
102
  });
93
103
  const { index, config: current } = view;
104
+ const failed = new Set();
94
105
  if (inputs) await timed('materializeMs', async () => {
95
106
  const settled = await Promise.allSettled(index.inventory.tsx.map(async source => [source, await index.materialize(source)]));
96
- for (const result of settled) { if (result.status === 'rejected') throw result.reason; view.built.set(...result.value); }
107
+ for (const [position, result] of settled.entries()) {
108
+ if (result.status === 'fulfilled') view.built.set(...result.value);
109
+ else {
110
+ if (!tolerateSourceFailures) throw result.reason;
111
+ const source = index.inventory.tsx[position];
112
+ failed.add(source);
113
+ data.failures.push(sourceFailure(result.reason, source, side === 'before' ? 'base' : 'current', inputs.translate));
114
+ }
115
+ }
97
116
  });
98
117
  await timed('indexMs', async () => {
99
118
  for (const source of index.inventory.tsx) {
119
+ if (failed.has(source)) continue;
100
120
  const facts = await index.source(source, { tokens: query.kind === 'token' || query.kind === 'git', fresh: !!inputs });
101
121
  view.facts.set(source, facts);
102
122
  for (const frame of facts.tokenDependencies ?? []) for (const row of frame.themes) if (themes.includes(row.theme)) {
@@ -107,16 +127,26 @@ export async function impact(config, values, { log = console.log, openIndex = op
107
127
  }
108
128
  }
109
129
  for (const source of index.inventory.architecture) {
110
- const metadata = await index.architecture(source), file = path.join(current.root, source), sidecar = path.join(current.root, metadata.sidecar);
111
- await track(file); await track(sidecar);
112
- view.architecture.set(source, { source: await bytes(file), sidecar: await bytes(sidecar), tokens: view.tokenBytes, config: current });
113
- view.facts.set(source, { source, parts: [], imports: [], dependencies: [source, metadata.sidecar, relative(current, view.tokenFile)], frames: [{ name: 'default', parts: [] }] });
130
+ try {
131
+ const metadata = await index.architecture(source), file = path.join(current.root, source), sidecar = path.join(current.root, metadata.sidecar);
132
+ await track(file); await track(sidecar);
133
+ view.architecture.set(source, { source: await bytes(file), sidecar: await bytes(sidecar), tokens: view.tokenBytes, config: current });
134
+ view.facts.set(source, { source, parts: [], imports: [], dependencies: [source, metadata.sidecar, relative(current, view.tokenFile)], frames: [{ name: 'default', parts: [] }] });
135
+ } catch (error) {
136
+ if (!tolerateSourceFailures) throw error;
137
+ data.failures.push(sourceFailure(error, source, side === 'before' ? 'base' : 'current', inputs.translate));
138
+ }
114
139
  }
115
- view.graph = await index.relationships({ facts: view.facts, projectPaths: true });
140
+ view.graph = await index.relationships({ facts: view.facts, projectPaths: true, sources: index.inventory.tsx.filter(source => !failed.has(source)) });
116
141
  view.tokens = view.facts.size || query.kind === 'token' ? index.tokens() : [];
117
142
  if (query.kind === 'file' || query.kind === 'git') { view.map = await loadImplementationMap(current); await track(view.map.file); }
118
143
  });
119
144
  }
145
+ const failedSources = new Set(data.failures.map(failure => failure.source));
146
+ for (const view of views) for (const source of failedSources) {
147
+ view.facts.delete(source);
148
+ view.built.delete(source);
149
+ }
120
150
  const scan = data.coverage.tokenScan;
121
151
  scan.fallbackReasons.sort(compare);
122
152
  if (scan.fullSheetRows) warn('IMPACT_TOKEN_FALLBACK', `Token scan used the full sheet for ${scan.fullSheetRows} frame/theme inputs: ${scan.fallbackReasons.join(', ')}.`,
@@ -154,7 +184,7 @@ export async function impact(config, values, { log = console.log, openIndex = op
154
184
  async function mappings(view, indices, pathIndexes = []) {
155
185
  if (!view.map.present) { data.coverage.mapping = data.coverage.mapping === 'stale' ? 'stale' : 'absent'; unresolved(view.map.source, 'mapping_absent'); return; }
156
186
  if (data.coverage.mapping === 'not_requested') data.coverage.mapping = 'valid';
157
- const validated = await view.index.mappings({ map: view.map, mappingIndices: indices,
187
+ const validated = await view.index.mappings({ map: view.map, mappingIndices: indices, selected: failedSources.size ? [...view.facts.keys()] : undefined,
158
188
  getBuild: source => {
159
189
  const facts = view.facts.get(source);
160
190
  // Mapping validators expect design-relative marker provenance.
@@ -174,6 +204,7 @@ export async function impact(config, values, { log = console.log, openIndex = op
174
204
  if (contents === null || indexDigest(contents) !== hash || tracked.has(name) && tracked.get(name) !== fingerprint) throw new CliError('IMPACT_INPUT_CHANGED', `Implementation input changed during query: ${name}.`);
175
205
  tracked.set(name, fingerprint);
176
206
  }
207
+ for(const binding of validated.transitionBindings??[])if(binding.active && (query.kind==='file' || pathIndexes.some(i=>data.changes[i].role==='implementation')))view.motionBindingHits.add(binding.design.transition);
177
208
  for (const binding of validated.bindings) {
178
209
  const target = binding.design, facts = view.facts.get(target.source);
179
210
  if (!facts) continue;
@@ -333,15 +364,18 @@ export async function impact(config, values, { log = console.log, openIndex = op
333
364
  }
334
365
  });
335
366
  timings.queryMs = Math.max(0, timings.queryMs - (timings.proofMs - proofBeforeQuery));
336
- data.coverage.inventory = 'complete';
367
+ data.coverage.inventory = data.failures.length ? 'incomplete' : 'complete';
337
368
  if (data.unresolvedInputs.length || data.mappingFindings.length) warn('IMPACT_MAPPING_INCOMPLETE', 'Some implementation mappings are absent, unmatched or stale; inspect the resolvable targets and findings.', checkNext('Repair implementation.json and its reported locators before repeating the query.'));
338
- if (!data.frames.length) {
369
+ for(const view of views)view.motionTokenHits=seeds.filter(s=>s.view===view && s.fact.kind==='token').map(s=>s.fact);
370
+ const motion=await impactedEdges(views,query,themes,assessments,values.explain,values.transitions);
371
+ motionSummary(data,motion,values.transitions);
372
+ if (!data.frames.length && !motion.length) {
339
373
  const observed = query.kind === 'token' ? { token: query.tokens[0], theme: values.theme } : query.kind === 'file' ? { file: query.input, theme: values.theme } : null;
340
374
  warn(query.kind === 'git' ? 'IMPACT_NO_CHANGES' : 'IMPACT_NO_MATCH', 'No frame candidates matched the changed design facts.',
341
375
  query.kind === 'git' ? [] : observed ? nextActions('OWNER_UNSETTLED', { command: 'owner', values: observed }) : checkNext('Inspect design inputs and emitted part coverage.'));
342
376
  }
343
377
 
344
- if (consume) await consume({ views, rows, assessments, inputs, data });
378
+ if (consume) await consume({ views, rows, assessments, inputs, data, motionIds:new Set(motion.map(r=>r.id)) });
345
379
  } catch (cause) {
346
380
  if (inputs) { try { await verifyGeneration(); } catch (changed) { cause = changed; } }
347
381
  if (cause.code === 'OWNER_INDEX_CHANGED') cause = new CliError('IMPACT_INPUT_CHANGED', cause.message, { cause });
@@ -352,7 +386,7 @@ export async function impact(config, values, { log = console.log, openIndex = op
352
386
  try { await cleanup(() => view.index.close(), primary); } catch (cause) { primary = data ? commandFailure(cause, data, warnings) : cause; }
353
387
  }
354
388
  if (!primary) {
355
- try { await verifyGeneration(); data.coverage.proofComplete = !!inputs; }
389
+ try { await verifyGeneration(); data.coverage.proofComplete = !!inputs && !data.failures.length; }
356
390
  catch (cause) {
357
391
  if (cause.code === 'OWNER_INDEX_CHANGED') cause = new CliError('IMPACT_INPUT_CHANGED', cause.message, { cause });
358
392
  if (inputs) cause.message = inputs.translate(cause.message);
@@ -4,6 +4,7 @@ import { CliError } from '../cli-output.mjs';
4
4
  import { portablePath, globPattern, resolveLocator, symbolRegions, selectorMatches } from './owner-locators.mjs';
5
5
  import { indexDigest } from './index-store.mjs';
6
6
  import { mappingFacts } from './source-facts.mjs';
7
+ import { readMotion, edgeId } from './motion.mjs';
7
8
  import { jsonLocations } from './json-locations.mjs';
8
9
 
9
10
  const object = value => value !== null && typeof value === 'object' && !Array.isArray(value);
@@ -17,7 +18,7 @@ const invalid = message => { throw new CliError('OWNER_MAP_INVALID', message); }
17
18
  export function parseImplementationMap(text) {
18
19
  let value;
19
20
  try { value = JSON.parse(text); } catch { invalid('Invalid implementation.json JSON; repair the mapping file.'); }
20
- if (!keys(value, ['version', 'mappings']) || value.version !== 1 || !Array.isArray(value.mappings)) invalid('implementation.json needs version 1 and a mappings array.');
21
+ if (!keys(value, ['version', 'mappings']) || ![1,2].includes(value.version) || !Array.isArray(value.mappings)) invalid('implementation.json needs version 1 or 2 and a mappings array.');
21
22
  value.mappings.forEach((mapping, index) => {
22
23
  const pointer = `/mappings/${index}`, fail = reason => invalid(`${pointer}: ${reason}`);
23
24
  if (!keys(mapping, ['implementation', 'design']) || !Array.isArray(mapping.design) || !mapping.design.length) fail('use an implementation selector and nonempty design bindings.');
@@ -29,6 +30,7 @@ export function parseImplementationMap(text) {
29
30
  if (s.anchor !== undefined && (!nonempty(s.anchor) || !s.symbol)) fail('a nonempty anchor requires a symbol.');
30
31
  if (s.symbol && !/\.(?:ts|tsx|js|jsx|mjs|cjs)$/.test(s.file) && s.anchor === undefined) fail('this file type requires an explicit symbol anchor.');
31
32
  for (const target of mapping.design) {
33
+ if (value.version===2 && keys(target,['source','transition']) && portablePath(target.source) && target.source.endsWith('.tsx') && edgeId(target.transition)) continue;
32
34
  if (!keys(target, ['source', 'part', 'frames']) || !portablePath(target.source) || !target.source.endsWith('.tsx') ||
33
35
  target.part !== undefined && !nonempty(target.part) || target.frames !== undefined && (!Array.isArray(target.frames) || !target.frames.length || target.frames.some(frame => !nonempty(frame)))) fail('use a TSX source, optional part and nonempty exact frame list.');
34
36
  }
@@ -81,7 +83,9 @@ export async function implementationFiles(config, selector) {
81
83
  return files.sort();
82
84
  }
83
85
 
84
- export async function validateImplementationMap(config, map, { sources, selected, getBuild, onFinding = () => {}, mappingIndices, implementationSelection }) {
86
+ export async function validateImplementationMap(config, map, { sources, selected, getBuild, onFinding = () => {}, mappingIndices, implementationSelection, targetFilter }) {
87
+ let motion;
88
+ const transitionBindings = [];
85
89
  const findings = [], bindings = [], regions = {}, seen = new Set(), builds = new Map(), contents = new Map();
86
90
  const sourceSet = new Set(sources), scope = selected && new Set(selected);
87
91
  const report = (code, pointer, selector, target, message, candidates = [], frame = null) => {
@@ -91,7 +95,7 @@ export async function validateImplementationMap(config, map, { sources, selected
91
95
  };
92
96
  for (const [index, mapping] of map.mappings.entries()) {
93
97
  if (mappingIndices && !mappingIndices.has(index)) continue;
94
- const targets = mapping.design.map((target, i) => ({ target, pointer: `/mappings/${index}/design/${i}` })).filter(({ target }) => !scope || scope.has(target.source));
98
+ const targets = mapping.design.map((target, i) => ({ target, pointer: `/mappings/${index}/design/${i}` })).filter(({ target }) => (!scope || scope.has(target.source)) && (!targetFilter || targetFilter(target)));
95
99
  if (!targets.length) continue;
96
100
  const selector = mapping.implementation, pointer = `/mappings/${index}/implementation`;
97
101
  const files = implementationSelection ? implementationSelection.filter(file => selectorMatches(selector, file)) : await implementationFiles(config, selector);
@@ -105,10 +109,17 @@ export async function validateImplementationMap(config, map, { sources, selected
105
109
  }
106
110
  for (const { target, pointer: targetPointer } of targets) {
107
111
  let valid = files.length > 0 && !locator.stale, frames = [];
108
- const duplicate = JSON.stringify([Object.fromEntries(Object.entries(selector).sort()), { source: target.source, part: target.part ?? null, frames: target.frames ? [...target.frames].sort() : null }]);
112
+ const duplicate = JSON.stringify([Object.fromEntries(Object.entries(selector).sort()), { source: target.source, part: target.part ?? null, transition: target.transition ?? null, frames: target.frames ? [...target.frames].sort() : null }]);
109
113
  if (seen.has(duplicate)) { report('OWNER_MAPPING_DUPLICATE', targetPointer, selector, target, 'Duplicate implementation/design binding.'); continue; }
110
114
  seen.add(duplicate);
111
115
  if (!sourceSet.has(target.source)) { report('OWNER_SOURCE_MISSING', targetPointer, selector, target, `Undiscovered source ${target.source}.`); valid = false; }
116
+ else if (target.transition) {
117
+ motion ??= readMotion(config);
118
+ const matches = motion.ids.get(target.transition) ?? [];
119
+ if (matches.length !== 1 || matches[0].owner !== target.source || !matches[0].valid) {
120
+ report('MOTION_BINDING', targetPointer, selector, target, 'Binding needs a unique transition in its owning source.'); valid=false;
121
+ }
122
+ }
112
123
  else if (!implementationSelection || valid) {
113
124
  if (!builds.has(target.source)) builds.set(target.source, Promise.resolve(getBuild(target.source)).then(mappingFacts));
114
125
  const built = await builds.get(target.source);
@@ -121,9 +132,9 @@ export async function validateImplementationMap(config, map, { sources, selected
121
132
  frames = frames.filter(matches);
122
133
  }
123
134
  }
124
- bindings.push({ pointer: targetPointer, implementation: selector, design: target, files, anchorLine: locator.line, frames: frames.map(frame => frame.name), active: valid });
135
+ (target.transition ? transitionBindings : bindings).push({ pointer: targetPointer, implementation: selector, design: target, files, anchorLine: locator.line, frames: frames.map(frame => frame.name), active: valid });
125
136
  }
126
137
  }
127
138
  for (const [file, text] of contents) regions[file] = symbolRegions(text, file, map.mappings.map(m => m.implementation).filter(s => s.file === file));
128
- return { findings, bindings, regions, implementationHashes: Object.fromEntries([...contents].map(([file, text]) => [file, indexDigest(text)])) };
139
+ return { findings, bindings, transitionBindings, regions, implementationHashes: Object.fromEntries([...contents].map(([file, text]) => [file, indexDigest(text)])) };
129
140
  }
@@ -49,3 +49,18 @@ export async function verifyInputGeneration({ tracked, views, inputs, verifyConf
49
49
  }
50
50
  await verifyTracked();await inputs?.verifyChanges();
51
51
  }
52
+
53
+ export async function liveDependencies(views,temporaryDirectory) {
54
+ const files = new Map(), checked = new Set();
55
+ for (const view of views) for (const built of view.built.values()) {
56
+ for (const [name,hash] of Object.entries(built.dependencyHashes)) {
57
+ const file=path.resolve(view.config.design,name);
58
+ if (checked.has(file)) continue;
59
+ checked.add(file);
60
+ if (file.startsWith(temporaryDirectory+path.sep) && !file.includes(path.sep+'node_modules'+path.sep)) continue;
61
+ const physical=await realpath(file).catch(()=>file);
62
+ if (!physical.startsWith(temporaryDirectory+path.sep)) files.set(physical,hash);
63
+ }
64
+ }
65
+ return [...files];
66
+ }
@@ -154,7 +154,7 @@ export function projectInspection(data, observation, theme, config, intern, defi
154
154
  }
155
155
  }
156
156
  const scene={roots,context:elements.filter(e=>context.has(e.id)).map(e=>({...e,children:e.children.filter(id=>context.has(id)||included.has(id))})),elements:emitted,instances:[],runs:emittedRuns,size:rich.size};
157
- return {scene,matches,limitations,instanceRows:instanceRows.filter(i=>included.has(i.root)||[...context].some(id=>id===i.root)),counts:{raw:scope.size,retained:scope.size-collapsed,collapsed,logical:included.size-collapsed,cutOff:scope.size-included.size,runs:emittedRuns.length}};
157
+ return {scene,matches,scopePaths:query?new Set(idRows.filter(row=>scope.has(row.id)).map(row=>row.path)):null,limitations,instanceRows:instanceRows.filter(i=>included.has(i.root)||[...context].some(id=>id===i.root)),counts:{raw:scope.size,retained:scope.size-collapsed,collapsed,logical:included.size-collapsed,cutOff:scope.size-included.size,runs:emittedRuns.length}};
158
158
  }
159
159
 
160
160
  export function pruneTables(data) {
@@ -42,7 +42,7 @@ export interface Resource {
42
42
  }
43
43
  export interface SVGNode {id:string;tag:string;attributes:Record<string,string>;children:string[]}
44
44
  export interface InspectCommon {
45
- inspectVersion:1;identityVersion:1;project:string;complete:boolean;mode:'catalog'|'frame';
45
+ motion?:{count:number};inspectVersion:1;identityVersion:1;project:string;complete:boolean;mode:'catalog'|'frame';
46
46
  selection:{source:string|null;frame:string|null;themes:Theme[];subtree:null|{kind:'part'|'element'|'text';input:string;contains:boolean};depth:number|null;fields:FieldGroup[];wrappers:'semantic'|'all';expand:boolean};
47
47
  catalog:{source:string;frames:{name:string;locale:string|null;width:number|null;height:number|null}[]}[];
48
48
  frame:{source:string;name:string;locale:string|null;authored:{width:number|null;height:number|null};parent:{source:string;frame:string;selector:string}|null}|null;
@@ -114,5 +114,13 @@ export interface CompactInspectData extends Omit<InspectCommon,'matches'|'limita
114
114
  limitations:(Omit<InspectCommon['limitations'][number],'elements'>&{elements:number[]})[];
115
115
  }
116
116
  export type InspectData=ExpandedInspectData|CompactInspectData;
117
+ export interface MotionInspection {
118
+ project:string; complete:boolean; motionVersion:1; mode:'transitions'|'transition';
119
+ label?:string;
120
+ motion?:{count:number;edges:{id:string;label:string;from:{source:string;frame:string};to:{source:string;frame:string};input:'click'|'hover'|'focus'|'key'|'input';proposed?:string}[]};
121
+ edge?:Record<string,unknown>;bound?:boolean;findings?:Record<string,unknown>[];
122
+ themes?:Partial<Record<Theme,{sameAs:Theme}|{counts:{match:number;enter:number;exit:number;ambiguous:number};timings:Record<string,string|number|null>}>>;
123
+ }
124
+ export function inspect(config:object,args:string[],values:({transition:string}|{transitions:true;frame:string}) & {json?:boolean;explain?:boolean;theme?:Theme|'both'},options?:object):Promise<{data:MotionInspection;warnings:unknown[]}>;
117
125
  export function inspect(config:object,args?:string[],values?:Record<string,string|boolean>,options?:object):Promise<{data:InspectData;warnings:{code:string;message:string;next:{argv:string[];reason:string}[]}[]}>;
118
126
  export function inspectText(data:InspectData):string;
@@ -1,3 +1,6 @@
1
+ import { instanceKeyMatches } from './motion-check.mjs';
2
+ import { readMotion, motionFiles, motionSummary, motionRows } from './motion.mjs';
3
+ import { transitionQuery, targetsFor } from './motion-queries.mjs';
1
4
  import path from 'node:path';
2
5
  import { CliError, nextActions } from '../cli-output.mjs';
3
6
  import { openProjectIndex } from './project-index.mjs';
@@ -22,6 +25,8 @@ export function inspectSelection(values) {
22
25
  }
23
26
 
24
27
  export async function inspect(config, args=[], values={}, {log=console.log, openIndex=openProjectIndex, launchBrowser=launch, environment=observationEnvironment}={}) {
28
+ if(values.transition || values.transitions)return transitionQuery(config,'inspect',args,values,log);
29
+ const motionIds=new Set();
25
30
  const resolvedConfig=canonicalBytes(config);
26
31
  const start=performance.now(),selection=inspectSelection(values),warnings=[],tracked=new Map();
27
32
  let data={inspectVersion:1,identityVersion:1,project:config.root,complete:false,mode:'catalog',encoding:'expanded',selection,catalog:[],frame:null,
@@ -35,7 +40,9 @@ export async function inspect(config, args=[], values={}, {log=console.log, open
35
40
  const getPage=async()=>{browser??=await launchBrowser();page??=await browserTask(browser,()=>browser.newPage({locale:'en-US',timezoneId:'UTC',deviceScaleFactor:1}));return page;};
36
41
  try {
37
42
  const files=await configInputFiles(config),configInputs=new Set(files.map(f=>relative(config,f)));
38
- for(const file of [...files,path.join(config.design,'tokens.css')])tracked.set(file,trackedHash(await inputBytes(file)));
43
+ const sidecars=motionFiles(config);
44
+ for(const file of [...files,...sidecars,path.join(config.design,'tokens.css')])tracked.set(file,trackedHash(await inputBytes(file)));
45
+ const graph=readMotion(config,sidecars);
39
46
  index=await openIndex(config,{stateDirectory:values['state-dir'],fresh:true});data.coverage.discoveredSources=index.inventory.tsx.length;
40
47
  let sources=index.inventory.tsx;
41
48
  await timed('prepareMs',async()=>{
@@ -53,6 +60,8 @@ export async function inspect(config, args=[], values={}, {log=console.log, open
53
60
  const candidates=data.catalog.flatMap(s=>s.frames.filter(f=>!values.frame||f.name===values.frame).map(f=>({source:s.source,frame:f.name})));
54
61
  if(values.frame && !candidates.length)throw new CliError('FRAME_NOT_FOUND',`Unknown frame ${values.frame}.`);
55
62
  if(values.frame && candidates.length>1)throw new CliError('INSPECT_FRAME_AMBIGUOUS',`Frame ${values.frame} occurs in ${candidates.length} sources: ${candidates.map(c=>c.source).join(', ')}.`,{context:{inspectSources:candidates.map(c=>c.source)}});
63
+ const incident=motionRows(graph.records.filter(r=>r.valid && candidates.some(c=>[r.edge.from,r.edge.to].some(ref=>ref.source===c.source && ref.frame===c.frame))));
64
+ if(!selection.subtree)for(const r of incident)motionIds.add(r.edge.id);
56
65
  if(!values.frame && candidates.length!==1){
57
66
  if(['theme','part','element','text','contains','depth','fields','wrappers','expand'].some(k=>values[k]!==undefined))throw new CliError('USAGE_INVALID','Choose a unique frame before setting frame-only options.',{context:{inspectCatalog:true}});
58
67
  if(!candidates.length)warn('EMPTY_SELECTION','No TSX frames were discovered.');
@@ -83,6 +92,19 @@ export async function inspect(config, args=[], values={}, {log=console.log, open
83
92
  data.coverage.cacheHits+=Number(result.hit);data.coverage.completedObservations++;
84
93
  observations.push({theme,palette:result.value.rich.palette});
85
94
  const projected=await timed('projectMs',()=>projectInspection(data,result.value,theme,config,intern,tokens));
95
+ if(projected.scopePaths && incident.length){
96
+ const nodes=result.value.identities, byPath=new Map(nodes.map(n=>[n.path,n]));
97
+ const root=nodes[0]?.path, scoped=nodes.filter(n=>projected.scopePaths.has(n.path));
98
+ const inScope=t=>scoped.some(n=>{
99
+ if(t.frame)return n.path===root;
100
+ if(t.anchor)return n.attributes?.['data-adg-id']===t.anchor;
101
+ if(!n.owners?.some(o=>path.posix.join(relative(config,config.design),o.source)+'#'+o.export===t.part))return false;
102
+ if(t.key===undefined)return true;
103
+ const ancestors=[];for(let p=n;p;p=byPath.get(p.parentPath))ancestors.push(p);
104
+ return instanceKeyMatches(ancestors,t.key);
105
+ });
106
+ for(const {edge} of incident)if(['from','to'].some(side=>edge[side].source===chosen.source && edge[side].frame===chosen.frame && targetsFor(edge,side).some(inScope)))motionIds.add(edge.id);
107
+ }
86
108
  if(data.baseline===null){data.baselineTheme=theme;data.baseline=projected.scene;}else data.additionalThemes[theme]=projected.scene;
87
109
  for(const match of projected.matches){const existing=data.matches.find(m=>m.element===match.element);if(existing)existing.themes.push(theme);else data.matches.push(match);}
88
110
  for(const row of projected.instanceRows)if(!data.partInstances.some(i=>i.id===row.id))data.partInstances.push(row);
@@ -103,10 +125,12 @@ export async function inspect(config, args=[], values={}, {log=console.log, open
103
125
 
104
126
  }
105
127
  await index.close();
128
+ if(JSON.stringify(sidecars)!==JSON.stringify(motionFiles(config)))throw new CliError('INSPECT_INPUT_CHANGED','Transition sidecar inventory changed during inspection.');
106
129
  await verifyInputGeneration({tracked,views:[{index,config,resolved:resolvedConfig,configInputs}],verifyConfig:true,code:'INSPECT_INPUT_CHANGED'});
107
130
  } catch(cause){if(cause.code==='OWNER_INDEX_CHANGED')cause=new CliError('INSPECT_INPUT_CHANGED',cause.message,{cause});primary=commandFailure(cause,data,warnings);}
108
131
  for(const close of [()=>page?.close(),()=>browser?.close(),()=>index?.close()])try{await cleanup(close,primary);}catch(cause){primary=commandFailure(cause,data,warnings);}
109
132
  data.timings.totalMs=performance.now()-start;
133
+ motionSummary(data,[...motionIds]);
110
134
  if(primary)throw primary;
111
135
  data.complete=true;
112
136
  const projectStart=performance.now();data=compactInspection(data);if(values.expand)data=expandInspection(data);