@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
@@ -17,11 +17,11 @@ export function compareReport(asset, frame, fixture, design, implementation) {
17
17
  offBy2px: rows.filter(row => row.off > 2).sort((a, b) => b.off - a.off), missing: missing.map(m => m.text), extra: extra.map(e => e.text) };
18
18
  }
19
19
  const cell = value => String(value).replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/"/g, '&quot;');
20
- export function reportHtml(report) {
20
+ export function reportHtml(report, screenshots = true) {
21
21
  const fmt = value => (value > 0 ? '+' : '') + value.toFixed(1);
22
22
  return `<!doctype html><meta charset="utf-8"><title>${cell(report.asset)} ${cell(report.frame)}</title><style>body{font:13px system-ui;margin:24px;background:#f4f4f4}.row{display:flex;gap:16px;align-items:flex-start;overflow:auto}figure{margin:0}img{display:block;max-width:none;border:1px solid #ccc}table{border-collapse:collapse;margin-top:24px}td,th{padding:4px 10px;border-bottom:1px solid #ddd;text-align:left}td.n{font-family:ui-monospace,monospace;text-align:right}</style>
23
23
  <h1>${cell(report.asset)} · ${cell(report.frame)} vs ${cell(report.fixture)}</h1><p>Matched ${report.matched} texts. ${report.offBy2px.length} differ by more than 2px. ${report.missing.length} missing in implementation. ${report.extra.length} extra in implementation.</p>
24
- <div class="row">${['design', 'implementation', 'overlay'].map(name => `<figure><figcaption>${name}</figcaption><img src="${name}.png"></figure>`).join('')}</div>
24
+ ${screenshots ? `<div class="row">${['design', 'implementation', 'overlay'].map(name => `<figure><figcaption>${name}</figcaption><img src="${name}.png"></figure>`).join('')}</div>` : ''}
25
25
  <table><tr><th>Text</th><th>dx</th><th>dy</th><th>dw</th></tr>${report.offBy2px.map(row => `<tr><td>${cell(row.text)}</td><td class="n">${fmt(row.dx)}</td><td class="n">${fmt(row.dy)}</td><td class="n">${fmt(row.dw)}</td></tr>`).join('')}</table>
26
26
  <h2>Missing in implementation</h2><p>${report.missing.map(cell).join(' · ') || 'None'}</p><h2>Extra in implementation</h2><p>${report.extra.map(cell).join(' · ') || 'None'}</p>`;
27
27
  }
@@ -110,7 +110,8 @@ async function compareFrame(config, file, definition, options, data, { launchBro
110
110
  design = await sheet.locator('[data-adg-frame] > :first-child').evaluate(implementationTexts);
111
111
  const target = path.join(config.output, 'compare', `${path.relative(config.design,file).replace(/\.tsx$/, '').split(path.sep).join('-')}-${safeName(frame)}-${safeName(fixtureName)}`);
112
112
  mkdirSync(target, { recursive: true });
113
- await sheet.screenshot({ path: path.join(target, 'design.png'), clip: frameBox });
113
+ const screenshots = !options['no-screenshots'];
114
+ if (screenshots) await sheet.screenshot({ path: path.join(target, 'design.png'), clip: frameBox });
114
115
  const app = await browser.newPage({ viewport: size, colorScheme: fixture.theme, reducedMotion: 'reduce', locale: fixture.locale, timezoneId: fixture.timezone });
115
116
  for (const pattern of adapter.block ?? []) await app.route(pattern, route => route.abort());
116
117
  await app.addInitScript(({ clock, theme }) => {
@@ -158,15 +159,16 @@ async function compareFrame(config, file, definition, options, data, { launchBro
158
159
  }
159
160
  return result;
160
161
  }, clock);
161
- const screenshot = { path: path.join(target, 'implementation.png') };
162
- if (capture) await app.screenshot({ ...screenshot, clip: capture });
163
- else await panel.screenshot(screenshot);
164
- const canvasPage = await browser.newPage();
165
- await overlay(canvasPage, target);
162
+ if (screenshots) {
163
+ const screenshot = { path: path.join(target, 'implementation.png') };
164
+ if (capture) await app.screenshot({ ...screenshot, clip: capture });
165
+ else await panel.screenshot(screenshot);
166
+ await overlay(await browser.newPage(), target);
167
+ }
166
168
  const report = { ...compareReport(relative(config, file), frame, fixtureName, {...design,box:frameBox}, implementation), settled };
167
169
  writeFileSync(path.join(target, 'report.json'), JSON.stringify(report, null, 2) + '\n');
168
- writeFileSync(path.join(target, 'index.html'), reportHtml(report));
169
- const paths = { design: path.join(target,'design.png'), implementation: path.join(target,'implementation.png'), overlay: path.join(target,'overlay.png'), report: path.join(target,'report.json'), html: path.join(target,'index.html') };
170
+ writeFileSync(path.join(target, 'index.html'), reportHtml(report, screenshots));
171
+ const paths = { ...(screenshots ? { design: path.join(target,'design.png'), implementation: path.join(target,'implementation.png'), overlay: path.join(target,'overlay.png') } : {}), report: path.join(target,'report.json'), html: path.join(target,'index.html') };
170
172
  const {asset, ...measured} = report;
171
173
  data.comparisons.push({source:asset, ...measured, theme:fixture.theme, paths});
172
174
  data.summary.frames++;
@@ -203,7 +205,7 @@ export async function compare(config, args = [], options = {}, { launchBrowser =
203
205
  if (!warnings.length) warnings.push({code:'COMPARE_FRAMES_SKIPPED',message:'Frames without fixtures were skipped.',next:[]});
204
206
  continue;
205
207
  }
206
- reports.push(await compareFrame(config,file,frame,options.all ? {frame:frame.name} : options,data,{launchBrowser,clock,log}));
208
+ reports.push(await compareFrame(config,file,frame,options.all ? {frame:frame.name, 'no-screenshots':options['no-screenshots']} : options,data,{launchBrowser,clock,log}));
207
209
  if (!data.comparisons.at(-1).settled) throw new CliError('COMPARE_UNSETTLED', 'Comparison text boxes did not settle within 5 seconds.', {humanReported:true});
208
210
  }
209
211
  }
@@ -126,7 +126,7 @@ export async function loadConfig(cwd = process.cwd(), { checkVersion = true, dis
126
126
  for (const key of ['design', 'output', 'arch']) if (config[key] !== undefined && !(key === 'arch' && config[key] === false) && (typeof config[key] !== 'string' || !config[key].trim())) throw new CliError('CONFIG_INVALID', `Set ${key} to a directory path in adg.config.mjs`);
127
127
  if (config.check !== undefined && (!config.check || typeof config.check!=='object' || Array.isArray(config.check))) throw new CliError('CONFIG_INVALID', 'Set check to an object in adg.config.mjs');
128
128
  if (config.check?.importDirection !== undefined && typeof config.check.importDirection!=='boolean') throw new CliError('CONFIG_INVALID', 'Set check.importDirection to true or false in adg.config.mjs');
129
- for (const key of ['strictLayers', 'lifecycle', 'singleConsumer']) if (config.check?.[key] !== undefined && typeof config.check[key] !== 'boolean') throw new CliError('CONFIG_INVALID', `Set check.${key} to true or false in adg.config.mjs`);
129
+ for (const key of ['strictLayers', 'strictMotion', 'lifecycle', 'singleConsumer']) if (config.check?.[key] !== undefined && typeof config.check[key] !== 'boolean') throw new CliError('CONFIG_INVALID', `Set check.${key} to true or false in adg.config.mjs`);
130
130
  const compare = { port: 5188, viewport: '1280x800', ...config.compare };
131
131
  viewport(compare.viewport);
132
132
  if (!Number.isInteger(compare.port) || compare.port < 1 || compare.port > 65535) throw new CliError('CONFIG_INVALID', 'Set compare.port to an integer from 1 to 65535 in adg.config.mjs');
@@ -136,5 +136,5 @@ export async function loadConfig(cwd = process.cwd(), { checkVersion = true, dis
136
136
  if (typeof config.arch === 'string' && (path.isAbsolute(config.arch) || path.relative(root,path.resolve(root,config.arch)).startsWith('..'))) throw new CliError('CONFIG_INVALID', 'Set arch to a project-root-relative directory in adg.config.mjs');
137
137
  const arch = config.arch === false ? false : path.resolve(root,config.arch ?? 'arch');
138
138
  const design=path.resolve(root,config.design??'design');
139
- return { root, name: config.name ?? path.basename(root), requires: config.requires ?? null, compatible, archDirectory: arch, arch: arch && (config.arch !== undefined || archFiles(arch).length) ? arch : false, sources: sourceDirectories({...config,design}), design, output: path.resolve(root, config.output ?? 'output/design'), check:{archMaxEdges:30,importDirection:true,strictLayers:false,lifecycle:false,singleConsumer:true,...config.check}, compare, diff: resolveDiffPolicy(config.diff) };
139
+ return { root, name: config.name ?? path.basename(root), requires: config.requires ?? null, compatible, archDirectory: arch, arch: arch && (config.arch !== undefined || archFiles(arch).length) ? arch : false, sources: sourceDirectories({...config,design}), design, output: path.resolve(root, config.output ?? 'output/design'), check:{archMaxEdges:30,importDirection:true,strictLayers:false,strictMotion:false,lifecycle:false,singleConsumer:true,...config.check}, compare, diff: resolveDiffPolicy(config.diff) };
140
140
  }
@@ -1,3 +1,5 @@
1
+ import { groupReview } from './review-groups.mjs';
2
+
1
3
  const escapeHtml = value => String(value ?? '').replace(/[&<>"']/g, char => (
2
4
  { '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' }[char]
3
5
  ));
@@ -25,14 +27,24 @@ function themeSummary(item) {
25
27
 
26
28
  export function buildReview(data, imagesById = new Map(), { label } = {}) {
27
29
  const grouped = new Map();
30
+ const moves = new Map();
28
31
  for (const row of data.comparisons ?? []) {
29
32
  const key = JSON.stringify([row.source, row.frame]);
33
+ if (row.status === 'moved') {
34
+ if (!moves.has(key)) moves.set(key, {
35
+ before: row.before ?? { source: row.previousSource, frame: row.frame },
36
+ after: row.after ?? { source: row.source, frame: row.frame },
37
+ });
38
+ continue;
39
+ }
30
40
  let entry = grouped.get(key);
31
41
  if (!entry) {
32
42
  entry = {
33
43
  source: row.source,
34
44
  frame: row.frame,
35
45
  status: row.status,
46
+ change: row.change,
47
+ previousSource: row.previousSource,
36
48
  rows: new Map(),
37
49
  };
38
50
  grouped.set(key, entry);
@@ -63,133 +75,210 @@ export function buildReview(data, imagesById = new Map(), { label } = {}) {
63
75
  sections.added.push({ source: entry.source, frame: entry.frame, status: 'added', themes: orderedThemes });
64
76
  } else if (entry.status === 'removed') {
65
77
  sections.removed.push({ source: entry.source, frame: entry.frame, status: 'removed', themes: orderedThemes });
66
- } else if (orderedThemes.some(item => item.verdict === 'changed')) {
67
- sections.changed.push({ source: entry.source, frame: entry.frame, status: 'changed', themes: orderedThemes });
78
+ } else if (entry.previousSource || orderedThemes.some(item => item.verdict === 'changed')) {
79
+ // Core classifies moves across both themes, even when only one theme is displayed.
80
+ sections.changed.push({ source: entry.source, frame: entry.frame, status: 'changed', change: entry.change,
81
+ ...(entry.previousSource ? { previousSource: entry.previousSource } : {}), themes: orderedThemes });
68
82
  }
69
83
  }
70
84
 
71
85
  const fallbackLabel = data.project ? data.project.split(/[\\/]/).filter(Boolean).at(-1) : 'Design review';
72
- return {
86
+ const review = {
73
87
  label: label || fallbackLabel || 'Design review',
74
88
  base: data.base ?? { rev: 'HEAD', sha: '' },
75
89
  current: data.current ?? { kind: 'working_tree', head: null },
76
90
  complete: !!data.complete,
91
+ failures: data.failures ?? [],
77
92
  verdict: data.verdict ?? null,
78
93
  counts: {
79
94
  added: sections.added.length,
80
95
  removed: sections.removed.length,
96
+ moved: moves.size,
81
97
  changed: sections.changed.length,
82
98
  },
99
+ movePairs: [...moves.values()],
83
100
  sections,
84
101
  };
102
+ return { ...review, ...groupReview(review) };
85
103
  }
86
104
 
87
- function renderSide(side, label, src, absentLabel, alt, theme) {
105
+ function renderSide(side, label, src, absentLabel, alt, theme, source) {
88
106
  const diffClass = side === 'difference' ? ' review-stage-diff' : '';
89
107
  const body = src
90
108
  ? `<div class="review-stage${diffClass}" data-stage-theme="${escapeHtml(theme)}"><img src="${escapeHtml(src)}" alt="${escapeHtml(alt)}" loading="lazy"></div>`
91
109
  : `<div class="review-absent">${escapeHtml(absentLabel)}</div>`;
92
- return `<figure class="review-pane" data-side="${escapeHtml(side)}"><figcaption>${escapeHtml(label)}</figcaption>${body}</figure>`;
110
+ return `<figure class="review-pane" data-side="${escapeHtml(side)}"><figcaption>${escapeHtml(label)}${source ? ` · <code>${escapeHtml(source)}</code>` : ''}</figcaption>${body}</figure>`;
93
111
  }
94
112
 
95
- function renderFrameCard(item) {
96
- const label = `${item.source} · ${item.frame}`;
113
+ function renderFrameCard(item, { paired = false, label: statusLabel = item.status } = {}) {
114
+ const label = `${item.source}#${item.frame}`;
115
+ const sides = item.status === 'added'
116
+ ? ['after']
117
+ : (paired && !item.themes.some(t => t.images?.difference))
118
+ ? ['before', 'after']
119
+ : ['before', 'after', 'difference'];
97
120
  const themeBlocks = item.themes.map(themeItem => {
98
121
  const theme = themeItem.theme;
99
122
  const summary = themeSummary(themeItem);
123
+ const absentLabels = { before: 'Absent at base', after: 'Removed in working tree', difference: 'No difference image' };
124
+ const panes = sides.map(side => {
125
+ const source = side === 'before' ? item.previousSource : null;
126
+ const alt = `${source ? `${source}#${item.frame}` : label} (${theme} ${side})`;
127
+ return renderSide(side, side[0].toUpperCase() + side.slice(1), themeItem.images?.[side], absentLabels[side], alt, theme, source);
128
+ }).join('');
100
129
  return `<div class="review-theme" data-theme-row="${escapeHtml(theme)}" data-verdict="${escapeHtml(themeItem.verdict)}">
101
130
  <div class="review-theme-head">
102
131
  <span class="review-theme-name">${escapeHtml(theme)}</span>
103
132
  <span class="review-theme-meta">${escapeHtml(summary)}</span>
104
133
  </div>
105
- <div class="review-columns">
106
- ${renderSide('before', 'Before', themeItem.images.before, 'Absent at base', `${label} (${theme} before)`, theme)}
107
- ${renderSide('after', 'After', themeItem.images.after, 'Removed in working tree', `${label} (${theme} after)`, theme)}
108
- ${renderSide('difference', 'Difference', themeItem.images.difference, 'No difference image', `${label} (${theme} difference)`, theme)}
134
+ <div class="review-columns" style="--review-columns:${sides.length}">
135
+ ${panes}
109
136
  </div>
110
137
  </div>`;
111
138
  }).join('');
112
139
  return `<article class="review-frame" data-source="${escapeHtml(item.source)}" data-frame="${escapeHtml(item.frame)}" data-status="${escapeHtml(item.status)}">
113
140
  <header class="review-frame-head">
114
- <h3><code>${escapeHtml(item.source)}</code><span class="review-dot">·</span><span>${escapeHtml(item.frame)}</span></h3>
115
- <span class="review-status-pill" data-status="${escapeHtml(item.status)}">${escapeHtml(item.status)}</span>
141
+ <h3><code>${escapeHtml(label)}</code></h3>
142
+ <div class="review-frame-actions">
143
+ <span class="review-status-pill" data-status="${escapeHtml(item.status)}">${escapeHtml(statusLabel)}</span>
144
+ </div>
116
145
  </header>
117
146
  <div class="review-themes">${themeBlocks}</div>
118
147
  </article>`;
119
148
  }
120
149
 
121
- export function renderReviewBody(review) {
122
- const counts = review.counts ?? { added: 0, removed: 0, changed: 0 };
150
+ export function renderReviewFailures(failures = []) {
151
+ if (!failures.length) return '';
152
+ return `<section class="review-failures" role="alert"><h2>Some sources could not be built</h2><ul>${failures.map(failure =>
153
+ `<li><code>${escapeHtml(failure.source)}</code> (${escapeHtml(failure.side)}) — ${escapeHtml(failure.message)}</li>`
154
+ ).join('')}</ul></section>`;
155
+ }
156
+
157
+ function renderNames(entries) {
158
+ return `<ul class="review-names">${entries.map(entry => `<li data-source="${escapeHtml(entry.source)}" data-frame="${escapeHtml(entry.frame)}" data-status="${escapeHtml(entry.status)}"><code>${escapeHtml(entry.source)}#${escapeHtml(entry.frame)}</code></li>`).join('')}</ul>`;
159
+ }
160
+
161
+ export function renderReviewMoves(pairs) {
162
+ const groups = new Map();
163
+ for (const { before, after } of pairs) {
164
+ const key = JSON.stringify([before.source, after.source]);
165
+ if (!groups.has(key)) groups.set(key, { from: before.source, to: after.source, count: 0, renamed: [] });
166
+ const group = groups.get(key);
167
+ group.count++;
168
+ if (before.frame !== after.frame) group.renamed.push({ before, after });
169
+ }
170
+ const frameLabel = ({ source, frame }) => `<code>${escapeHtml(`${source}#${frame}`)}</code>`;
171
+ return `<ul class="review-names">${[...groups.values()].map(({ from, to, count, renamed }) =>
172
+ `<li data-moved-count="${count}"><code>${escapeHtml(from)}</code> → <code>${escapeHtml(to)}</code> · ${count} ${count === 1 ? 'frame' : 'frames'}${
173
+ renamed.length ? `<ul>${renamed.map(({ before, after }) => `<li>${frameLabel(before)} → ${frameLabel(after)}</li>`).join('')}</ul>` : ''}</li>`
174
+ ).join('')}</ul>`;
175
+ }
176
+
177
+ function sameFrame(left, right) {
178
+ return left.source === right.source && left.frame === right.frame;
179
+ }
180
+
181
+ function renderGroup(group) {
182
+ const outliers = group.outliers.filter(entry => !sameFrame(entry, group.representative));
183
+ const others = group.frames.filter(entry => !sameFrame(entry, group.representative));
184
+ const remaining = others.filter(entry => !outliers.some(outlier => sameFrame(entry, outlier)));
185
+ const causes = group.causes.map(cause => `<code>${escapeHtml(cause)}</code>`).join(', ');
186
+ return `<article class="review-group">
187
+ <header class="review-group-head"><h3>${causes}</h3><span>${group.frames.length} ${group.frames.length === 1 ? 'frame' : 'frames'}</span></header>
188
+ ${renderFrameCard(group.representative, { paired: true, label: 'Representative' })}
189
+ ${outliers.map(entry => renderFrameCard(entry, { paired: true, label: 'Outlier' })).join('')}
190
+ ${remaining.length ? `<details class="review-group-members"><summary>Show ${remaining.length} more inherited ${remaining.length === 1 ? 'frame' : 'frames'}</summary><div class="review-section-list">${remaining.map(entry => renderFrameCard(entry, { paired: true, label: 'Inherited' })).join('')}</div></details>` : ''}
191
+ </article>`;
192
+ }
193
+
194
+ function renderReviewBody(review) {
195
+ const grouped = { ...review, ...groupReview(review) };
196
+ const { counts } = grouped;
197
+ const count = (kind, content) => `<span class="review-count" data-kind="${kind}"${counts[kind] === 0 ? ' data-zero="true"' : ''}>${content}</span>`;
123
198
  const baseLabel = review.base?.sha
124
199
  ? `${review.base.rev} (${shortSha(review.base.sha)})`
125
200
  : (review.base?.rev ?? 'base');
126
201
  const headLabel = review.current?.head ? `working tree (${shortSha(review.current.head)})` : 'working tree';
202
+ const direct = (review.sections?.changed ?? []).filter(entry => entry.change?.kind !== 'inherited');
127
203
  const sectionSpecs = [
128
- ['added', 'Added', review.sections?.added ?? []],
129
- ['removed', 'Removed', review.sections?.removed ?? []],
130
- ['changed', 'Changed', review.sections?.changed ?? []],
204
+ ['added', 'Added', review.sections?.added ?? [], items => items.map(item => renderFrameCard(item)).join('')],
205
+ ['direct', 'Direct changes', direct, items => items.map(item => renderFrameCard(item)).join('')],
206
+ ['inherited', 'Inherited changes', grouped.groups ?? [], items => items.map(group => renderGroup(group)).join('')],
207
+ ['removed', 'Removed', review.sections?.removed ?? [], renderNames],
208
+ ['moved', 'Moved', review.movePairs ?? [], renderReviewMoves],
131
209
  ];
132
210
  const renderedSections = sectionSpecs
133
211
  .filter(([, , items]) => items.length > 0)
134
- .map(([kind, title, items]) => `<section class="review-section" data-section="${kind}">
135
- <h2 class="review-section-title">${escapeHtml(title)} <span class="review-section-count">${items.length}</span></h2>
136
- <div class="review-section-list">${items.map(renderFrameCard).join('')}</div>
212
+ .map(([kind, title, items, render]) => `<section class="review-section" data-section="${kind}">
213
+ <h2 class="review-section-title">${escapeHtml(title)} <span class="review-section-count">${kind === 'inherited' ? counts.inherited : items.length}</span></h2>
214
+ <div class="review-section-list">${render(items)}</div>
137
215
  </section>`)
138
216
  .join('');
139
217
  const empty = renderedSections
140
218
  ? ''
141
- : `<p class="review-empty" role="status">No added, removed, or changed frames against <code>${escapeHtml(review.base?.rev ?? 'base')}</code>.</p>`;
142
-
219
+ : `<p class="review-empty" role="status">No added, removed, moved, or changed frames against <code>${escapeHtml(review.base?.rev ?? 'base')}</code>.</p>`;
143
220
  return `<header class="review-header">
144
221
  <div class="review-heading">
145
222
  <h1 id="review-title">${escapeHtml(review.label)}</h1>
146
223
  <code class="review-revisions">base ${escapeHtml(baseLabel)} → ${escapeHtml(headLabel)}</code>
147
224
  </div>
148
225
  <div class="review-counts" data-review-counts>
149
- <span class="review-count" data-kind="added"><strong>${counts.added}</strong> added</span>
150
- <span class="review-count" data-kind="removed"><strong>${counts.removed}</strong> removed</span>
151
- <span class="review-count" data-kind="changed"><strong>${counts.changed}</strong> changed</span>
226
+ ${count('added', `<strong>${counts.added}</strong> added`)}
227
+ ${count('removed', `<strong>${counts.removed}</strong> removed`)}
228
+ ${count('moved', `<strong>${counts.moved}</strong> moved`)}
229
+ ${count('changed', `<strong>${counts.changed}</strong> changed (direct ${counts.direct}, inherited ${counts.inherited})`)}
152
230
  </div>
153
231
  </header>
154
- <div class="review-scroll">${renderedSections}${empty}</div>`;
155
- }
156
-
157
- export function renderReview(container, review) {
158
- container.innerHTML = renderReviewBody(review);
232
+ <div class="review-scroll">${renderReviewFailures(review.failures)}${renderedSections}${empty}</div>`;
159
233
  }
160
234
 
161
235
  export const REVIEW_STYLES = `
162
- .review-header { display:flex; align-items:center; justify-content:space-between; flex-wrap:wrap; gap:12px 20px; padding:16px 20px; border-bottom:1px solid var(--border); flex:none; }
163
- .review-heading { display:flex; align-items:baseline; flex-wrap:wrap; gap:8px 12px; min-width:0; }
236
+ .review-failures { padding:16px; border:1px solid var(--border); border-radius:var(--radius-row); background:var(--surface-sunken); overflow-wrap:anywhere; }
237
+ .review-failures h2 { margin:0 0 8px; font-size:var(--text-section); }
238
+ .review-failures ul { margin:0; padding-left:20px; }
239
+ .review-failures li + li { margin-top:8px; }
240
+
241
+ .review-header { display:flex; align-items:center; justify-content:space-between; flex-wrap:wrap; gap:12px 16px; padding:16px 20px; border-bottom:1px solid var(--border); flex:none; }
242
+ .review-heading { display:flex; align-items:baseline; flex-wrap:wrap; gap:8px 12px; min-width:0; margin-right:auto; }
164
243
  .review-heading h1 { font-size:var(--text-title); font-weight:650; line-height:20px; margin:0; }
165
244
  .review-revisions { font:var(--text-meta)/1.4 var(--font-mono); color:var(--text-secondary); }
166
245
  .review-counts { display:flex; align-items:center; flex-wrap:wrap; gap:8px; }
167
- .review-count { display:inline-flex; align-items:center; gap:5px; padding:4px 10px; border-radius:999px; background:var(--surface-sunken); font-size:var(--text-meta); color:var(--text-secondary); }
246
+ .review-count { display:inline-flex; align-items:center; gap:5px; padding:4px 10px; border:1px solid transparent; border-radius:var(--radius-pill, 999px); background:var(--surface-sunken); font:var(--text-meta)/1.2 var(--font-ui); color:var(--text-secondary); }
247
+ .review-count[data-zero="true"] { opacity:.6; }
168
248
  .review-count strong { font-family:var(--font-mono); font-weight:650; color:var(--text); }
169
249
  .review-scroll { min-height:0; flex:1; overflow:auto; padding:20px; display:flex; flex-direction:column; gap:28px; }
170
250
  .review-section { display:flex; flex-direction:column; gap:14px; }
171
251
  .review-section-title { display:flex; align-items:center; gap:8px; font-size:var(--text-section); font-weight:650; color:var(--text); margin:0; }
172
- .review-section-count { display:inline-flex; align-items:center; justify-content:center; min-width:22px; height:20px; padding:0 6px; border-radius:999px; background:var(--surface-sunken); font:600 var(--text-caption)/1 var(--font-mono); color:var(--text-secondary); }
252
+ .review-section-count { display:inline-flex; align-items:center; justify-content:center; min-width:22px; height:20px; padding:0 6px; border-radius:var(--radius-pill, 999px); background:var(--surface-sunken); font:600 var(--text-caption)/1 var(--font-mono); color:var(--text-secondary); }
173
253
  .review-section-list { display:flex; flex-direction:column; gap:16px; }
174
254
  .review-frame { border:1px solid var(--border); border-radius:var(--radius-menu); background:var(--surface-section); overflow:hidden; }
175
255
  .review-frame-head { display:flex; align-items:center; justify-content:space-between; gap:12px; padding:12px 16px; border-bottom:1px solid var(--border); background:var(--surface); }
176
- .review-frame-head h3 { display:flex; align-items:baseline; flex-wrap:wrap; gap:6px; margin:0; font-size:var(--text-body); font-weight:600; color:var(--text); }
177
- .review-frame-head code { font:var(--text-meta)/1.4 var(--font-mono); color:var(--text-secondary); }
256
+ .review-frame-head h3 { display:flex; align-items:baseline; flex-wrap:wrap; gap:6px; margin:0; min-width:0; font-size:var(--text-body); font-weight:600; color:var(--text); }
257
+ .review-frame-head code { font:var(--text-meta)/1.4 var(--font-mono); color:var(--text-secondary); overflow-wrap:anywhere; }
258
+ .review-frame-actions { display:flex; align-items:center; gap:8px; flex:none; }
259
+ .review-group { display:flex; flex-direction:column; gap:14px; padding:16px; border:1px solid var(--border); border-radius:var(--radius-menu); }
260
+ .review-group-head { display:flex; align-items:baseline; justify-content:space-between; gap:12px; }
261
+ .review-group-head h3 { margin:0; font:var(--text-meta)/1.5 var(--font-mono); overflow-wrap:anywhere; }
262
+ .review-group-head span { flex:none; color:var(--text-secondary); }
263
+ .review-names { margin:0; padding-left:20px; font:var(--text-meta)/1.6 var(--font-mono); overflow-wrap:anywhere; }
264
+ .review-group-members summary { cursor:pointer; color:var(--text-secondary); font-size:var(--text-meta); font-weight:550; }
265
+ .review-group-members summary:hover { color:var(--text); }
266
+ .review-group-members[open] summary { margin-bottom:14px; }
178
267
  .review-dot { color:var(--text-tertiary); }
179
- .review-status-pill { flex:none; padding:2px 8px; border-radius:999px; background:var(--surface-sunken); font-size:var(--text-caption); font-weight:600; text-transform:capitalize; color:var(--text-secondary); }
268
+ .review-status-pill { flex:none; padding:2px 8px; border-radius:var(--radius-pill, 999px); background:var(--surface-sunken); font-size:var(--text-caption); font-weight:600; text-transform:capitalize; color:var(--text-secondary); }
180
269
  .review-themes { display:flex; flex-direction:column; gap:1px; background:var(--border); }
181
270
  .review-theme { background:var(--surface); padding:14px 16px 16px; display:flex; flex-direction:column; gap:10px; }
182
271
  .review-theme-head { display:flex; align-items:center; justify-content:space-between; flex-wrap:wrap; gap:8px; }
183
272
  .review-theme-name { font-size:var(--text-meta); font-weight:650; text-transform:capitalize; color:var(--text); }
184
273
  .review-theme-meta { font:var(--text-caption)/1.4 var(--font-mono); color:var(--text-tertiary); }
185
- .review-columns { display:grid; grid-template-columns:repeat(3, minmax(0, 1fr)); gap:12px; align-items:start; }
274
+ .review-columns { display:grid; grid-template-columns:repeat(var(--review-columns, 3), minmax(0, 1fr)); gap:12px; align-items:start; }
186
275
  @media (max-width:900px) { .review-columns { grid-template-columns:1fr; } }
187
276
  .review-pane { margin:0; display:flex; flex-direction:column; gap:6px; min-width:0; }
188
277
  .review-pane figcaption { font-size:var(--text-caption); font-weight:550; color:var(--text-secondary); }
189
- .review-stage { border:1px solid var(--border); border-radius:var(--radius-row); padding:10px; display:flex; align-items:center; justify-content:center; min-height:96px; overflow:auto; background:#ecece9; }
190
- .review-stage[data-stage-theme="dark"] { background:#121212; border-color:#2d2d2d; }
191
- .review-stage-diff { background:repeating-conic-gradient(var(--surface-sunken) 0% 25%, var(--surface) 0% 50%) 50% / 14px 14px; }
192
- .review-stage-diff[data-stage-theme="dark"] { background:repeating-conic-gradient(#1f1f1f 0% 25%, #161616 0% 50%) 50% / 14px 14px; }
278
+ .review-stage { --review-stage-bg:var(--review-canvas-light, #ecece9); --review-stage-border:var(--border); border:1px solid var(--review-stage-border); border-radius:var(--radius-row); padding:10px; display:flex; align-items:center; justify-content:center; min-height:96px; overflow:auto; background:var(--review-stage-bg); }
279
+ .review-stage[data-stage-theme="dark"] { --review-stage-bg:var(--review-canvas-dark, #121212); --review-stage-border:var(--review-border-dark, #2d2d2d); }
280
+ .review-stage-diff { --review-checker-a:var(--review-checker-light-a, #f1f1ee); --review-checker-b:var(--review-checker-light-b, #ffffff); background:repeating-conic-gradient(var(--review-checker-a) 0% 25%, var(--review-checker-b) 0% 50%) 50% / 14px 14px; }
281
+ .review-stage-diff[data-stage-theme="dark"] { --review-checker-a:var(--review-checker-dark-a, #1f1f1f); --review-checker-b:var(--review-checker-dark-b, #161616); }
193
282
  .review-stage img { display:block; max-width:100%; height:auto; }
194
283
  .review-absent { border:1px dashed var(--border); border-radius:var(--radius-row); min-height:96px; padding:12px; display:flex; align-items:center; justify-content:center; text-align:center; font-size:var(--text-meta); color:var(--text-tertiary); background:var(--surface-sunken); }
195
284
  .review-empty { margin:12px 0; color:var(--text-secondary); font-size:var(--text-body); }
@@ -216,7 +305,10 @@ export function reviewDocumentHtml(review) {
216
305
  --text-caption: 11px;
217
306
  --radius-panel: 14px;
218
307
  --radius-menu: 12px;
308
+ --radius-field: 9px;
219
309
  --radius-row: 8px;
310
+ --radius-keycap: 6px;
311
+ --radius-pill: 999px;
220
312
  --canvas: #ecece9;
221
313
  --surface: #ffffff;
222
314
  --surface-section: #f5f5f3;
@@ -225,6 +317,7 @@ export function reviewDocumentHtml(review) {
225
317
  --text: #1c1c1a;
226
318
  --text-secondary: #5b5b57;
227
319
  --text-tertiary: #7c7c77;
320
+ --accent: #1c1c1a;
228
321
  }
229
322
  @media (prefers-color-scheme: dark) {
230
323
  :root {
@@ -236,6 +329,7 @@ export function reviewDocumentHtml(review) {
236
329
  --text: #efefed;
237
330
  --text-secondary: #a8a8a4;
238
331
  --text-tertiary: #85857f;
332
+ --accent: #efefed;
239
333
  }
240
334
  }
241
335
  * { box-sizing: border-box; }
@@ -1,12 +1,13 @@
1
1
  import path from 'node:path';
2
2
  import { existsSync } from 'node:fs';
3
3
  import { mkdir, readFile, realpath, rm, symlink } from 'node:fs/promises';
4
- import { resolveBase, materializeBase, sourceRenames, revisionValue, revisionError } from './arch-git.mjs';
4
+ import { resolveBase, materializeBase, revisionValue, revisionError, revisionChanges } from './arch-git.mjs';
5
+ import { configInputFiles } from './input-generation.mjs';
5
6
  import { loadConfig, legacyConfigFile } from './config.mjs';
6
7
  import { selectSources, relative } from './project.mjs';
7
8
  import { buildSource } from './build.mjs';
8
9
  import { cleanup } from './results.mjs';
9
- import { CliError, withHumanOutputMapping } from '../cli-output.mjs';
10
+ import { CliError, asCliError, withHumanOutputMapping } from '../cli-output.mjs';
10
11
 
11
12
  const environmentFiles = ['package.json', 'package-lock.json', 'npm-shrinkwrap.json', 'pnpm-lock.yaml', 'yarn.lock', 'bun.lock', 'bun.lockb'];
12
13
  const slash = value => value.split(path.sep).join('/');
@@ -54,6 +55,12 @@ function historicalFailure(error) {
54
55
  return new CliError('DIFF_BASE_DEPENDENCIES_UNAVAILABLE', `Historical import failed: ${error.message}`, { cause: error });
55
56
  }
56
57
 
58
+ export function sourceFailure(error, source, side, translate = value => value) {
59
+ if (['OWNER_INDEX_CHANGED', 'IMPACT_INPUT_CHANGED'].includes(error.code)) throw error;
60
+ const failure = asCliError(side === 'base' ? historicalFailure(error) : error, 'SOURCE_BUILD_FAILED');
61
+ return { source, side, code: failure.code, message: translate(failure.message) };
62
+ }
63
+
57
64
  function inventory(config, repository) {
58
65
  return new Map(selectSources(config, [], { write: false }).map(file => {
59
66
  const source = relative(config, file);
@@ -135,11 +142,8 @@ function groupFrames(rows, field) {
135
142
  return groups;
136
143
  }
137
144
 
138
- /** Prepare revision inputs. The caller closes the session and owns any supplied browser. */
139
- export async function prepareDiffInputs(config, args = [], options = {}) {
140
- const base = await resolveBase(config, options.base);
141
- const root = await realpath(config.root);
142
- const tree = await materializeBase(base);
145
+ export async function openDiffRevision(base, root, temporaryDirectory) {
146
+ const tree = await materializeBase(base, temporaryDirectory);
143
147
  const warnings = [];
144
148
  try {
145
149
  const configDependencies = await reuseEnvironment(base, tree, root);
@@ -148,6 +152,7 @@ export async function prepareDiffInputs(config, args = [], options = {}) {
148
152
  message: `Base config uses current node_modules; environment files differ: ${configDependencies.changedFiles.join(', ')}.`, next: [],
149
153
  });
150
154
  const beforeRoot = path.join(tree.directory, path.relative(base.root, root));
155
+ await mkdir(beforeRoot,{recursive:true});
151
156
  const baseMigration = { applied: false, changes: [] };
152
157
  const translate = value => revisionValue(value, tree.directory, base.root);
153
158
  let beforeConfig;
@@ -165,75 +170,115 @@ export async function prepareDiffInputs(config, args = [], options = {}) {
165
170
  }
166
171
  return loadConfig(beforeRoot, { discover: false });
167
172
  }, translate);
168
- } catch (error) { throw revisionError(historicalFailure(error), tree.directory, base); }
169
- const before = { config: beforeConfig, sources: inventory(beforeConfig, tree.directory) };
173
+ } catch (error) { throw historicalFailure(error); }
174
+ return { config: beforeConfig, sources: inventory(beforeConfig, tree.directory), revision: base,
175
+ warnings, translate, environment: { configDependencies, baseMigration }, close: tree.close };
176
+ } catch (cause) {
177
+ const failure = revisionError(cause, tree.directory, base);
178
+ await cleanup(tree.close, failure);
179
+ throw failure;
180
+ }
181
+ }
182
+
183
+ /** Prepare both endpoints before selecting sources, hints or parent support frames. */
184
+ export async function prepareDiffInputs(config, args = [], options = {}) {
185
+ const root = await realpath(config.root);
186
+ const open = options.openRevision ?? (async rev => openDiffRevision(await resolveBase(config, rev), root));
187
+ const before = await open(options.base);
188
+ const { revision: base, translate, environment: { configDependencies, baseMigration } } = before;
189
+ const warnings = [...before.warnings];
190
+ let target;
191
+ const close = async () => { try { await target?.close(); } finally { await before.close(); } };
192
+ try {
193
+ if (options.head) { target = await open(options.head); warnings.push(...target.warnings); }
170
194
  // Resolve symlinked project roots consistently with the Git base identity.
171
195
  const currentConfig = { ...config, root };
172
196
  for (const key of ['design', 'arch', 'archDirectory', 'output']) {
173
197
  if (config[key]) currentConfig[key] = path.resolve(root, path.relative(config.root, config[key]));
174
198
  }
175
- const after = { config: currentConfig, sources: inventory(currentConfig, base.root) };
199
+ const after = target ?? { config: currentConfig, sources: inventory(currentConfig, base.root) };
176
200
  const union = new Set([...before.sources.keys(), ...after.sources.keys()]);
177
- const sources = await selectedSources(currentConfig, beforeConfig, root, union, args);
178
- const renames = (await sourceRenames(base)).flatMap(rename => {
179
- const old = path.relative(root, path.join(base.root, rename.before));
180
- const current = path.relative(root, path.join(base.root, rename.after));
181
- return outside(old) || outside(current) ? [] : [{ before: slash(old), after: slash(current) }];
182
- });
201
+ const sources = await selectedSources(currentConfig, before.config, root, union, args);
202
+ const inputs = await revisionChanges(base, target?.revision);
203
+ const projectPath = name => name === null ? null : slash(path.relative(root, path.join(base.root, name)));
204
+ const changes = inputs.map(change => ({...change, before:projectPath(change.before), after:projectPath(change.after)}));
205
+ const renames = changes.filter(c => c.status === 'renamed' && !outside(c.before) && !outside(c.after));
206
+ const changed = new Set(changes.flatMap(change => [change.before, change.after]).filter(Boolean));
207
+ const configFiles = await Promise.all([before, after].map(async side =>
208
+ (await configInputFiles(side.config)).map(file => relative(side.config, file))));
209
+ const globalChanges = [...new Set([...configFiles.flat(), ...configDependencies.changedFiles.map(name =>
210
+ slash(path.relative(root, path.join(base.root, name))))])].filter(name => changed.has(name));
183
211
  let closed = false;
184
212
  return {
185
- base, before, after, sources, warnings, translateDiagnostic: translate, environment: { configDependencies, baseMigration },
186
- async buildFrames({ browser, materialized, sources: requestedSources = sources, frame: requestedFrame = options.frame } = {}) {
213
+ base, before, after, sources, renames, changes, globalChanges, warnings, translateDiagnostic: value => translate(target ? target.translate(value) : value), environment: { configDependencies, baseMigration },
214
+ async buildFrames({ browser, materialized, failures: previousFailures = [], sources: requestedSources = sources, frame: requestedFrame = options.frame, deferParts = false } = {}) {
187
215
  if (closed) throw new CliError('SOURCE_BUILD_FAILED', 'Diff inputs are closed; prepare a new comparison.');
188
216
  const built = materialized ? materialized.map(values => new Map(values)) : [new Map(), new Map()], snapshots = [new Map(), new Map()];
217
+ const failures = [...previousFailures];
218
+ const failed = new Set(failures.map(failure => failure.source));
219
+ const attempts = [new Set(), new Set()];
189
220
  const build = async (side, index, source) => {
190
- if (built[index].has(source) || !side.sources.has(source)) return;
221
+ if (attempts[index].has(source) || previousFailures.some(failure => failure.source === source) || built[index].has(source) || !side.sources.has(source)) return;
222
+ attempts[index].add(source);
191
223
  try {
192
224
  const work = () => buildSource(side.config, side.sources.get(source), { write: false, allowLegacy: false, snapshot: snapshots[index], browser });
193
225
  built[index].set(source, await (side === before ? withHumanOutputMapping(work, translate) : work()));
194
226
  } catch (error) {
195
- const failure = side === before ? revisionError(historicalFailure(error), tree.directory, base) : error;
196
- if (failure instanceof CliError) failure.warnings.push(...warnings);
197
- throw failure;
227
+ failures.push(sourceFailure(error, source, index === 0 ? 'base' : 'current', translate));
228
+ failed.add(source);
198
229
  }
199
230
  };
200
231
  for (const source of requestedSources) {
201
232
  await build(before, 0, source);
202
233
  await build(after, 1, source);
203
234
  }
204
- const frames = matchDiffFrames(requestedSources, built[0], built[1], renames, requestedFrame);
205
- const support = [], parents = new Map();
206
- const selected = new Map(frames.map(row => [frameKey(row), row]));
207
- for (const row of frames.filter(row => row.status === 'added' && row.after.parent)) {
208
- const ref = row.after.parent, key = frameKey({ source: ref.source, frame: ref.frame });
209
- if (!parents.has(key)) {
210
- await build(before, 0, ref.source);
211
- await build(after, 1, ref.source);
212
- const old = built[0].get(ref.source)?.frames.find(frame => frame.name === ref.frame);
213
- const current = built[1].get(ref.source)?.frames.find(frame => frame.name === ref.frame);
214
- if (!old || !current) throw new CliError('DIFF_REFERENCE_INVALID', `${row.source}: ${row.frame}: parent ${ref.source}: ${ref.frame} must exist at both revisions.`);
215
- const parent = selected.get(key) ?? { source: ref.source, frame: ref.frame, before: old, after: current, status: 'matched', matchKind: 'exact', matchCandidates: [] };
216
- parents.set(key, parent);
217
- if (!selected.has(key)) support.push(parent);
218
- }
219
- row.parentRow = parents.get(key);
235
+ const frames = matchDiffFrames(requestedSources.filter(source => !failed.has(source)), built[0], built[1], renames)
236
+ .filter(row => requestedFrame === undefined || row.frame === requestedFrame);
237
+ if (requestedFrame !== undefined && !frames.some(row => row.frame === requestedFrame) && !failures.length) {
238
+ throw new CliError('FRAME_NOT_FOUND', `Unknown frame ${requestedFrame}; choose a frame present on either side.`);
220
239
  }
221
- const candidates = frames.filter(row => row.matchKind === 'renamed_or_unknown');
222
- if (candidates.length) warnings.push({
223
- code: 'DIFF_RENAMED_OR_UNKNOWN',
224
- message: `Unmatched frames have rename candidates: ${candidates.map(row => frameKey(row)).join(', ')}.`, next: [],
225
- });
226
- return { frames, before: built[0], after: built[1], support };
240
+ const result = { frames, before: built[0], after: built[1], support: [], failures };
241
+ // Diff pairs moves before linking structural additions to their parents.
242
+ const prepareParts = async () => {
243
+ const { frames, support } = result, parents = new Map();
244
+ const selected = new Map(frames.map(row => [frameKey(row), row]));
245
+ for (const row of frames.filter(row => row.status === 'added' && row.after.parent)) {
246
+ if (failed.has(row.source)) continue;
247
+ const ref = row.after.parent, key = frameKey({ source: ref.source, frame: ref.frame });
248
+ if (!parents.has(key)) {
249
+ await build(before, 0, ref.source);
250
+ await build(after, 1, ref.source);
251
+ if (failed.has(ref.source)) {
252
+ failures.push({ source: row.source, side: 'current', code: 'DIFF_REFERENCE_INVALID', message: `${row.source}: ${row.frame}: parent source ${ref.source} failed to build.` });
253
+ failed.add(row.source);
254
+ continue;
255
+ }
256
+ const old = built[0].get(ref.source)?.frames.find(frame => frame.name === ref.frame);
257
+ const current = built[1].get(ref.source)?.frames.find(frame => frame.name === ref.frame);
258
+ if (!old || !current) throw new CliError('DIFF_REFERENCE_INVALID', `${row.source}: ${row.frame}: parent ${ref.source}: ${ref.frame} must exist at both revisions.`);
259
+ const parent = selected.get(key) ?? { source: ref.source, frame: ref.frame, before: old, after: current, status: 'matched', matchKind: 'exact', matchCandidates: [] };
260
+ parents.set(key, parent);
261
+ if (!selected.has(key)) support.push(parent);
262
+ }
263
+ row.parentRow = parents.get(key);
264
+ }
265
+ const candidates = frames.filter(row => row.matchKind === 'renamed_or_unknown');
266
+ if (candidates.length) warnings.push({
267
+ code: 'DIFF_RENAMED_OR_UNKNOWN',
268
+ message: `Unmatched frames have rename candidates: ${candidates.map(row => frameKey(row)).join(', ')}.`, next: [],
269
+ });
270
+ for (const source of failed) for (const values of built) values.delete(source);
271
+ result.frames = frames.filter(row => !failed.has(row.source));
272
+ result.support = support.filter(row => !failed.has(row.source));
273
+ };
274
+ if (deferParts) result.prepareParts = prepareParts;
275
+ else await prepareParts();
276
+ return result;
227
277
  },
228
- async close() { closed = true; await tree.close(); },
278
+ async close() { closed = true; await close(); },
229
279
  };
230
280
  } catch (error) {
231
- const failure = error instanceof CliError ? error : revisionError(error, tree.directory, base);
232
- failure.message = revisionValue(failure.message, tree.directory, base.root);
233
- failure.context = revisionValue(failure.context, tree.directory, base.root);
234
- failure.warnings.push(...warnings);
235
- await cleanup(tree.close, failure);
236
- failure.warnings = revisionValue(failure.warnings, tree.directory, base.root);
237
- throw failure;
281
+ await cleanup(close, error);
282
+ throw error;
238
283
  }
239
284
  }