@whzxc/agent-design-gallery 0.13.1 → 0.14.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.
package/README.md CHANGED
@@ -47,13 +47,12 @@ Path links locate a selection within its design hierarchy. Query links open an i
47
47
  ## Share a design update
48
48
 
49
49
  ```sh
50
- adg link https://gallery.example/p/project/ --asset=components/button.tsx --frame=disabled
51
- adg link https://gallery.example/p/project/ --asset=components/button.tsx --frame=disabled --mode=path
52
- adg open ./design --asset=components/button.tsx --frame=disabled --no-open
53
- adg render components/button --frame=disabled --theme=dark --out-dir=output/review --json
50
+ adg diff --base=<rev> --impacted --json
51
+ adg link https://gallery.example/p/project/ --base=<rev>
52
+ adg open ./design --base=<rev> --no-open
54
53
  ```
55
54
 
56
- Use the independent link in a change report. Add the path link when the surrounding assets matter. Use the project URL on a hub the recipient can reach. `adg open` provides a live loopback preview while its server runs. `render` exports exact frame PNGs for attachments or automation. Without `--theme`, it exports both themes. See the [review handoff workflow](docs/design-toolkit.md#review-handoff).
55
+ Set `--base=<rev>` to the task's starting commit. Git supplies the added, removed and changed frames. A change report carries one reachable review URL from `adg link <viewer-url> --base=<rev>` and the `added`, `removed` and `changed` counts from `adg diff --base=<rev> --impacted`, with no per-frame images. The hub and direct viewer serve the same review page at `?base=<rev>`, showing counts at the top followed by added, removed and changed frames in both themes (`light` and `dark`) with before, after and difference side by side. Targeted `--asset`, `--frame`, `--group`, `--layer`, `--tokens` and `--mode=path` links remain available for interactive navigation, and `adg render` exports frame PNGs for automation. See the [review handoff workflow](docs/design-toolkit.md#review-handoff).
57
56
 
58
57
  Every command accepts `--json`: finite commands return one versioned envelope, while foreground `open`/`serve` stream NDJSON events. `render` PNGs are in `data.captures`, with CSS and PNG pixel dimensions. See the [agent CLI interface](docs/agent-interface.md) for schemas, exits and recovery actions.
59
58
 
@@ -118,8 +117,11 @@ adg diff --base=HEAD --impacted --json
118
117
 
119
118
  Builds produce standalone HTML and renders produce `<frame>-light.png` and `<frame>-dark.png` under `output/design/<source>/`. After configuring an implementation adapter and frame fixture/capture, use `adg compare <source> --frame=<name>` or `adg compare --all`. Flags override Frame capture props; `--all` writes a linked HTML index and `summary.json` under `output/design/compare/`. `sync` and `measure` have been removed.
120
119
 
121
- `adg diff --base=<rev>` writes per-frame/theme before, after and difference PNGs plus
122
- `report.json` for Git and working-tree sources, including added/removed frames. Existing
120
+ `adg diff --base=<rev>` overwrites `<configured output>/diff` and writes a self-contained
121
+ `index.html` review page, per-frame/theme before, after and difference PNGs, plus
122
+ `report.json` for Git and working-tree sources, including added/removed frames. `index.html`
123
+ shows the `added`, `removed` and `changed` frame counts (`data.review`) at the top, followed
124
+ by each affected frame in both themes with before, after and difference side by side. Existing
123
125
  frames require exact pixels and size. New part Frames can declare `parent` and use
124
126
  consumer `diff.thresholds`; a `structural` batch requires full existing-frame coverage
125
127
  in both themes. Exit 0 is `identical`/`structural`, 1 is completed `changed`, and 2 is
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@whzxc/agent-design-gallery",
3
- "version": "0.13.1",
3
+ "version": "0.14.0",
4
4
  "description": "Local TSX design toolkit and SVG viewer",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -28,7 +28,7 @@
28
28
  "start": "node src/cli.mjs",
29
29
  "benchmark": "node tooling/benchmark.mjs",
30
30
  "compare": "node tooling/compare.mjs",
31
- "test": "node --test test/*.test.mjs",
31
+ "test": "node --import ./tooling/test-temp.mjs --test test/*.test.mjs",
32
32
  "prepack": "node tooling/package.mjs"
33
33
  },
34
34
  "dependencies": {
package/public/app.js CHANGED
@@ -9,6 +9,7 @@ import { prepare, imageURL, arrange, groupAssets, evictPreviews, metadataContext
9
9
  import { sourceRelationships, relatedSources } from './relationships.js';
10
10
  import { hitSelection, frameBox, exportFrames } from './selection.js';
11
11
  import { groupTokens, renderTokenTable } from './token-catalog.js';
12
+ import { renderReview } from './review.js';
12
13
  import { readViewRoute, viewURL } from './view-route.js';
13
14
  import { createArranger } from './arrangement.js';
14
15
  const arranger = createArranger();
@@ -23,6 +24,7 @@ const viewport = $(".gallery-viewport"),
23
24
  let manifest,
24
25
  catalog = null,
25
26
  tokenManifest = null,
27
+ reviewManifest = null,
26
28
  tokenCategory = null,
27
29
  pendingNavigation = null,
28
30
  groups = [],
@@ -137,7 +139,7 @@ let route = {}, routeError;
137
139
  try { route = readViewRoute(new URL(location.href)); }
138
140
  catch (error) { routeError = error; }
139
141
  let initialLink = route.target, strictRoute = route.strict, queryView = !!route.isolated;
140
- let scopeRequest = fixtureName ? 'all' : route.scope ?? 'default', onlyFrame = route.onlyFrame ?? null;
142
+ let scopeRequest = fixtureName ? 'all' : (route.base && route.scope === 'default' ? 'review' : route.scope ?? 'default'), onlyFrame = route.onlyFrame ?? null;
141
143
  let initializedScope, initializedFrame, scopeEntry;
142
144
  const currentItem = () => inspection || assets.find((a) => a.id === selectedId);
143
145
  function remember() {
@@ -177,13 +179,13 @@ function back() {
177
179
  function changeScope(next, entry = null, record = true) {
178
180
  const nextFrame = entry?.onlyFrame ?? null;
179
181
  if (next === scopeRequest && nextFrame === onlyFrame) return;
180
- if ((initializedScope || tokenManifest) && !catalog) {
181
- if (record && !tokenManifest && next !== 'tokens') remember();
182
+ if ((initializedScope || tokenManifest || reviewManifest) && !catalog) {
183
+ if (record && !tokenManifest && !reviewManifest && next !== 'tokens' && next !== 'review') remember();
182
184
  void persistPreferences();
183
185
  }
184
186
  scopeRequest = next;
185
187
  onlyFrame = nextFrame;
186
- queryView = entry?.queryView ?? !['all', 'layer'].includes(scopeKind(next));
188
+ queryView = entry?.queryView ?? (next !== 'review' && !['all', 'layer'].includes(scopeKind(next)));
187
189
  strictRoute = false;
188
190
  scopeEntry = entry;
189
191
  initialLink = null;
@@ -200,23 +202,30 @@ function toggleSidebar(value = !sidebar) {
200
202
  }
201
203
  function updateChrome() {
202
204
  updateSwitcherLabels();
203
- const opened = !!(tokenManifest ?? catalog ?? manifest)?.directory;
205
+ const opened = !!(reviewManifest ?? tokenManifest ?? catalog ?? manifest)?.directory;
204
206
  const showTokens = !!tokenManifest;
205
- const canInspect = opened && !showTokens && !!selected;
206
- $('.gallery').classList.toggle('tokens-mode', showTokens);
207
+ const showReview = !!reviewManifest;
208
+ const canInspect = opened && !showTokens && !showReview && !!selected;
209
+ $('.gallery').classList.toggle('tokens-mode', showTokens || showReview);
207
210
  $('#token-catalog').hidden = !showTokens;
208
- viewport.inert = showTokens;
209
- $('#sidebar').hidden = !opened || !sidebar;
211
+ $('#review-page').hidden = !showReview;
212
+ viewport.inert = showTokens || showReview;
213
+ $('#sidebar').hidden = !opened || showReview || !sidebar;
214
+ $('#sidebar-toggle').hidden = showReview;
215
+ $('.search-divider').hidden = showReview;
216
+ $('.search-field').hidden = showReview;
217
+ $('#annotate').hidden = showReview;
218
+ $('#inspect').hidden = showReview;
210
219
  $('#app-bar').hidden = !opened;
211
220
  if (fixtureState) $('#app-directory .switcher-chevron').hidden = false;
212
221
  $('#tools').hidden = !opened;
213
- $('.zoom').hidden = !opened || showTokens;
222
+ $('.zoom').hidden = !opened || showTokens || showReview;
214
223
  $('#source').hidden = !canInspect || !inspector;
215
224
  $('#inspect').disabled = !canInspect;
216
225
  $('#inspect').setAttribute('aria-expanded', String(canInspect && inspector));
217
- $('#arrange').hidden = showTokens;
218
- if (!opened) $('#minimap').hidden = true;
219
- $('#sidebar-toggle').setAttribute('aria-expanded', String(opened && sidebar));
226
+ $('#arrange').hidden = showTokens || showReview;
227
+ if (!opened || showReview) $('#minimap').hidden = true;
228
+ $('#sidebar-toggle').setAttribute('aria-expanded', String(opened && !showReview && sidebar));
220
229
  positionZoomMenu();
221
230
  }
222
231
  function positionZoomMenu() {
@@ -229,8 +238,9 @@ const media = matchMedia("(prefers-color-scheme: dark)");
229
238
  const modifiedDate = new Intl.DateTimeFormat('en-US', {month:'short',day:'numeric',hour:'2-digit',minute:'2-digit',hourCycle:'h23'});
230
239
  window.__adg = {
231
240
  ready: false,
232
- get metadataComplete() {return !!tokenManifest || (!!manifest && !manifest.loading);},
233
- get scope() {return tokenManifest?.scope ?? initializedScope;},
241
+ get metadataComplete() {return !!reviewManifest || !!tokenManifest || (!!manifest && !manifest.loading);},
242
+ get scope() {return (reviewManifest ?? tokenManifest)?.scope ?? initializedScope;},
243
+ get review() {return reviewManifest?.review ?? null;},
234
244
  get cachePending() {return cacheWrites+loading+queued.length;},
235
245
  get cacheFlush() {return flushCache();},
236
246
  get cacheFailures() {return cacheFailures;},
@@ -238,7 +248,7 @@ window.__adg = {
238
248
  return { ...view };
239
249
  },
240
250
  get assets() {
241
- return tokenManifest ? 0 : assets.length;
251
+ return reviewManifest || tokenManifest ? 0 : assets.length;
242
252
  },
243
253
  get previews() {
244
254
  return {entries: cache.size, decoded: [...cache.values()].filter(e => e.image).length,
@@ -283,7 +293,7 @@ async function api(url, data, keepalive = false, signal) {
283
293
  return result;
284
294
  }
285
295
  function preferences() {
286
- if (tokenManifest || onlyFrame) return { theme };
296
+ if (reviewManifest || tokenManifest || onlyFrame) return { theme };
287
297
  return {
288
298
  view,
289
299
  scope: initializedScope,
@@ -333,11 +343,11 @@ function restoreSelection(target) {
333
343
  }
334
344
  function persistPreferences(keepalive = false) {
335
345
  clearTimeout(saveTimer);
336
- if (fixtureState || catalog || !(tokenManifest ?? manifest)?.directory) return;
346
+ if (fixtureState || catalog || !(reviewManifest ?? tokenManifest ?? manifest)?.directory) return;
337
347
  return api('preferences', preferences(), keepalive).catch(e => error(e.message));
338
348
  }
339
349
  function save() {
340
- if(fixtureState || catalog || !(tokenManifest ?? manifest)?.directory) return;
350
+ if(fixtureState || catalog || !(reviewManifest ?? tokenManifest ?? manifest)?.directory) return;
341
351
  clearTimeout(saveTimer);
342
352
  saveTimer = setTimeout(persistPreferences, 220);
343
353
  }
@@ -452,6 +462,7 @@ function navigate(action) {
452
462
  function scopedUI(data) { return !!data.layers && (!data.fixture || !!data.fixture.scope); }
453
463
  function scopeLabel(scope) {
454
464
  const target = scopeTarget(scope);
465
+ if (scope === 'review') return 'Review';
455
466
  if (scope === 'all') return 'All designs';
456
467
  if (scope === 'tokens') return 'Tokens';
457
468
  if (scopeKind(scope) === 'layer') return target[0].toUpperCase() + target.slice(1);
@@ -460,7 +471,8 @@ function scopeLabel(scope) {
460
471
  }
461
472
  function renderScopeTabs(data) {
462
473
  const tabs = $('#scope-tabs');
463
- const choices = [...(data.tokenSource ? ['tokens'] : []), ...(data.layers ?? []).map(layer => 'layer:' + layer), 'all'];
474
+ const hasBase = new URL(location.href).searchParams.has('base');
475
+ const choices = [...(hasBase ? ['review'] : []), ...(data.tokenSource ? ['tokens'] : []), ...(data.layers ?? []).map(layer => 'layer:' + layer), 'all'];
464
476
  const signature = JSON.stringify([data.scope, choices]);
465
477
  $('#sidebar').classList.toggle('scoped', scopedUI(data));
466
478
  if (tabs.dataset.signature === signature) return;
@@ -517,9 +529,13 @@ function navFile(a, options = {}) {
517
529
  return row;
518
530
  }
519
531
  function renderNav() {
520
- const data = tokenManifest ?? catalog ?? manifest;
532
+ const data = reviewManifest ?? tokenManifest ?? catalog ?? manifest;
521
533
  if (!data) return;
522
534
  renderScopeTabs(data);
535
+ if (reviewManifest) {
536
+ requestDraw();
537
+ return;
538
+ }
523
539
  const scoped = scopedUI(data), kind = scoped ? scopeKind(data.scope) : null;
524
540
  const focusKey = document.activeElement?.dataset.navkey;
525
541
  const query = $("#search").value.trim().toLowerCase(), nodes = [];
@@ -735,7 +751,7 @@ const annotationUI = createAnnotations({
735
751
  getState: () => {
736
752
  const a = currentItem(), p = a?.parts.find(part => part.id === selectedForm);
737
753
  return {
738
- opened: Boolean(manifest?.directory) && !tokenManifest,
754
+ opened: Boolean(manifest?.directory) && !tokenManifest && !reviewManifest,
739
755
  projectRoot: manifest?.projectRoot ?? manifest?.directory ?? null,
740
756
  sourcePrefix: manifest?.sourcePrefix ?? '',
741
757
  revision: manifest?.revision ?? 0,
@@ -977,8 +993,9 @@ function draw() {
977
993
  const endDrawing = globalThis.__adgTiming?.span('drawing');
978
994
  raf = 0;
979
995
  drawBackground();
980
- if (tokenManifest) {
996
+ if (tokenManifest || reviewManifest) {
981
997
  window.__adg.ready = true;
998
+ window.__adg.revision = (reviewManifest ?? tokenManifest)?.revision;
982
999
  if (fixtureState) document.documentElement.dataset.fixtureReady = fixtureState.name;
983
1000
  endDrawing?.(); return;
984
1001
  }
@@ -1168,12 +1185,12 @@ for (const b of $("#themes").children)
1168
1185
  b.onclick = () => {
1169
1186
  theme = b.dataset.theme;
1170
1187
  applyTheme();
1171
- void refresh(true);
1188
+ if (!reviewManifest) void refresh(true);
1172
1189
  save();
1173
1190
  };
1174
1191
  media.addEventListener("change", () => {
1175
1192
  applyTheme();
1176
- void refresh(true);
1193
+ if (!reviewManifest) void refresh(true);
1177
1194
  });
1178
1195
  viewport.addEventListener(
1179
1196
  "wheel",
@@ -1364,7 +1381,7 @@ function openSelectionContextMenu({ worldPoint = null, screenX, screenY, returnF
1364
1381
  ], { x: screenX, y: screenY, returnFocus });
1365
1382
  }
1366
1383
  viewport.addEventListener('contextmenu', e => {
1367
- if (tokenManifest || !manifest?.directory) return;
1384
+ if (reviewManifest || tokenManifest || !manifest?.directory) return;
1368
1385
  if (e.target.closest('.annotation-point, .annotation-card')) return;
1369
1386
  e.preventDefault();
1370
1387
  viewport.focus({ preventScroll: true });
@@ -1379,7 +1396,7 @@ viewport.addEventListener('contextmenu', e => {
1379
1396
  });
1380
1397
  document.addEventListener('keydown', e => {
1381
1398
  if (!(e.key === 'ContextMenu' || (e.key === 'F10' && e.shiftKey))) return;
1382
- if (tokenManifest || !manifest?.directory || document.querySelector('dialog[open]')) return;
1399
+ if (reviewManifest || tokenManifest || !manifest?.directory || document.querySelector('dialog[open]')) return;
1383
1400
  e.preventDefault();
1384
1401
  const activeEl = document.activeElement;
1385
1402
  const noteEl = activeEl?.closest?.('[data-annotation-id]');
@@ -1475,7 +1492,7 @@ $("#arrange").onclick = async () => {
1475
1492
  let placed;
1476
1493
  try {if(!data.loading)placed=await arranger.arrange(layoutData(data));}
1477
1494
  catch(failure){if(failure.name!=='AbortError')error(failure.message);requestDraw();return;}
1478
- if(manifest!==data || catalog!==previousCatalog || tokenManifest){requestDraw();return;}
1495
+ if(manifest!==data || catalog!==previousCatalog || tokenManifest || reviewManifest){requestDraw();return;}
1479
1496
  const old = assets,
1480
1497
  oldGroups = groups;
1481
1498
  layout(manifest,false,{placed,provisional:!!data.loading});
@@ -1552,9 +1569,10 @@ function relationshipGraph(data, measured) {
1552
1569
  return sourceRelationships([...entries].map(([path,imports])=>({path,imports})));
1553
1570
  }
1554
1571
  function applyTokenManifest(data) {
1555
- const previous = tokenManifest ?? catalog ?? manifest;
1572
+ const previous = reviewManifest ?? tokenManifest ?? catalog ?? manifest;
1556
1573
  const entering = !tokenManifest || tokenManifest.directory !== data.directory;
1557
1574
  tokenManifest = { ...data, tokenGroups: groupTokens(data.tokens ?? []) };
1575
+ reviewManifest = null;
1558
1576
  scopeRequest = data.scope;
1559
1577
  catalog = null;
1560
1578
  if (entering) {
@@ -1579,17 +1597,40 @@ function applyTokenManifest(data) {
1579
1597
  annotationUI.render();
1580
1598
  renderNav();
1581
1599
  }
1600
+ function applyReviewManifest(data) {
1601
+ const previous = reviewManifest ?? tokenManifest ?? catalog ?? manifest;
1602
+ reviewManifest = data;
1603
+ tokenManifest = null;
1604
+ catalog = null;
1605
+ scopeRequest = 'review';
1606
+ fixtureState = null;
1607
+ if (previous?.directory !== data.directory) {
1608
+ theme = data.theme;
1609
+ sidebar = false;
1610
+ applyTheme();
1611
+ }
1612
+ for (const element of document.querySelectorAll('.directory-name')) element.textContent = data.label;
1613
+ $('#app-directory').title = data.directory || '';
1614
+ document.title = `${data.label} · Review — Agent Design Gallery`;
1615
+ const url = viewURL(location.href, 'review');
1616
+ if (url.href !== location.href) window.history.replaceState(window.history.state, '', url);
1617
+ renderReview($('#review-page'), data.review);
1618
+ updateChrome();
1619
+ annotationUI.render();
1620
+ renderNav();
1621
+ requestDraw();
1622
+ }
1582
1623
  async function applyManifest(data, force = false) {
1583
1624
  if (data.scope === 'tokens') {
1584
1625
  if (force || tokenManifest?.directory !== data.directory || tokenManifest?.revision !== data.revision) applyTokenManifest(data);
1585
1626
  return;
1586
1627
  }
1587
- const leavingTokens = !!tokenManifest;
1628
+ const leavingOverlayView = !!tokenManifest || !!reviewManifest;
1588
1629
  const changedRoot = initializedDirectory !== data.directory, changedScope = initializedScope !== data.scope || initializedFrame !== onlyFrame;
1589
1630
  const first = changedRoot || changedScope;
1590
- if (!force && !first && !leavingTokens && manifest.revision === data.revision)
1631
+ if (!force && !first && !leavingOverlayView && manifest.revision === data.revision)
1591
1632
  return;
1592
- if (leavingTokens) {
1633
+ if (leavingOverlayView) {
1593
1634
  initialLink = null;
1594
1635
  $('#search').value = '';
1595
1636
  }
@@ -1597,7 +1638,7 @@ async function applyManifest(data, force = false) {
1597
1638
  fixtureState=data.fixture ?? null;
1598
1639
  theme = data.theme;
1599
1640
  applyTheme();
1600
- if (!leavingTokens) sidebar = !!fixtureState?.sidebar;
1641
+ if (!leavingOverlayView) sidebar = !!fixtureState?.sidebar;
1601
1642
  inspector = !!fixtureState && data.inspector;
1602
1643
  history = [];
1603
1644
  }
@@ -1633,7 +1674,7 @@ async function applyManifest(data, force = false) {
1633
1674
  restorePacking(data.packing);
1634
1675
  const previous=manifest, results=new Array(data.assets.length), signal=refreshController?.signal;
1635
1676
  let next=0,publishFrame=0,streamView=null,streamMoved=false,publishedCount=0,nextPublish=1;
1636
- const streaming=first && !leavingTokens;
1677
+ const streaming=first && !leavingOverlayView;
1637
1678
  const publish=()=>{
1638
1679
  publishFrame=0;
1639
1680
  if(signal?.aborted||versionTheme!==effectiveTheme)return;
@@ -1692,6 +1733,7 @@ async function applyManifest(data, force = false) {
1692
1733
  for(const key of metadataCache.keys())if(!live.has(key))metadataCache.delete(key);
1693
1734
  manifest = { ...data, assets: results, relationships:relationshipGraph(data,results), renderTheme: versionTheme };
1694
1735
  tokenManifest = null;
1736
+ reviewManifest = null;
1695
1737
  // Early streamed worlds can use a much larger camera scale. Discard those
1696
1738
  // raster intermediates so the completed world starts at its exact final scale.
1697
1739
  if(streaming&&publishedCount)for(const entry of cache.values()){delete entry.bitmap;delete entry.bitmapScale;}
@@ -1835,6 +1877,14 @@ async function refresh(force = false) {
1835
1877
  fetching = true;refreshController=new AbortController();
1836
1878
  try {
1837
1879
  if (routeError) throw routeError;
1880
+ if (scopeRequest === 'review') {
1881
+ window.__adg.ready = false;
1882
+ const signal = refreshController.signal, data = await api('review', null, false, signal);
1883
+ signal.throwIfAborted();
1884
+ applyReviewManifest(data);
1885
+ error("");
1886
+ return;
1887
+ }
1838
1888
  const query=new URLSearchParams({context:metadataContext(),theme:effectiveTheme,scope:scopeRequest});
1839
1889
  if (strictRoute) query.set('strict', '1');
1840
1890
  if (onlyFrame) query.set('frame', onlyFrame);
@@ -1861,7 +1911,7 @@ async function refresh(force = false) {
1861
1911
  }
1862
1912
  await refresh();
1863
1913
  if(fixtureState) { try { await applyFixture(); } catch(e) { error(e.message); } }
1864
- if ((tokenManifest || manifest) && !isUnauthorized()) {
1914
+ if ((reviewManifest || tokenManifest || manifest) && !isUnauthorized()) {
1865
1915
  const events = new EventSource(keyURL('events'));
1866
1916
  window.addEventListener('adg-unauthorized', () => events.close(), { once: true });
1867
1917
  events.onmessage = (e) => {
@@ -1881,6 +1931,7 @@ if ((tokenManifest || manifest) && !isUnauthorized()) {
1881
1931
 
1882
1932
  document.addEventListener("keydown", (e) => {
1883
1933
  if ((e.metaKey || e.ctrlKey) && e.key.toLowerCase() === "f") {
1934
+ if (reviewManifest) return;
1884
1935
  e.preventDefault();
1885
1936
  $("#search").focus();
1886
1937
  return;
@@ -1888,6 +1939,7 @@ document.addEventListener("keydown", (e) => {
1888
1939
  if (e.key !== "Escape" || document.querySelector("dialog[open]")) return;
1889
1940
  if (document.querySelector(":popover-open")) return;
1890
1941
  if (annotationUI.cancelMove()) return;
1942
+ if (reviewManifest) return;
1891
1943
  if (tokenManifest) {
1892
1944
  if ($('#search').value) $('#search-clear').click();
1893
1945
  return;
package/public/index.html CHANGED
@@ -23,6 +23,7 @@
23
23
  <p id="token-status" role="status" hidden></p>
24
24
  </div>
25
25
  </main>
26
+ <main id="review-page" class="floating" aria-labelledby="review-title" hidden></main>
26
27
  <div id="app-bar" class="floating" role="toolbar" aria-label="Gallery navigation" hidden>
27
28
  <button id="sidebar-toggle" class="icon-button" aria-label="Contents" aria-controls="sidebar" aria-expanded="false" data-tooltip="Contents"><span data-icon="panel-left"></span></button>
28
29
  <button type="button" id="app-directory" class="picker" aria-label="Current project"><span data-icon="folder" data-size="14"></span><span class="directory-name"></span><span class="switcher-chevron" data-icon="chevron-down" data-size="12" hidden></span></button>
@@ -0,0 +1,255 @@
1
+ const escapeHtml = value => String(value ?? '').replace(/[&<>"']/g, char => (
2
+ { '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' }[char]
3
+ ));
4
+
5
+ const safeImageSrc = value => typeof value === 'string' && value.startsWith('data:image/png;base64,') ? value : null;
6
+
7
+ const shortSha = value => typeof value === 'string' && value.length > 12 ? value.slice(0, 12) : value;
8
+
9
+ function formatSize(size) {
10
+ if (!size) return null;
11
+ return `${size.width}×${size.height} (${size.pixelWidth}×${size.pixelHeight}px)`;
12
+ }
13
+
14
+ function themeSummary(item) {
15
+ const sizes = [formatSize(item.beforeSize), formatSize(item.afterSize)].filter(Boolean);
16
+ const uniqueSizes = [...new Set(sizes)];
17
+ const sizeLabel = uniqueSizes.join(' → ');
18
+ const diffLabel = item.verdict === 'identical'
19
+ ? 'identical'
20
+ : item.verdict === 'structural'
21
+ ? 'structural'
22
+ : `${item.differentPixels.toLocaleString('en-US')} px changed`;
23
+ return [sizeLabel, diffLabel].filter(Boolean).join(' · ');
24
+ }
25
+
26
+ export function buildReview(data, imagesById = new Map(), { label } = {}) {
27
+ const grouped = new Map();
28
+ for (const row of data.comparisons ?? []) {
29
+ const key = JSON.stringify([row.source, row.frame]);
30
+ let entry = grouped.get(key);
31
+ if (!entry) {
32
+ entry = {
33
+ source: row.source,
34
+ frame: row.frame,
35
+ status: row.status,
36
+ rows: new Map(),
37
+ };
38
+ grouped.set(key, entry);
39
+ }
40
+ const rawImages = imagesById.get(row.id) ?? {};
41
+ entry.rows.set(row.theme, {
42
+ theme: row.theme,
43
+ verdict: row.verdict,
44
+ reasons: row.reasons ?? [],
45
+ beforeSize: row.beforeSize ?? null,
46
+ afterSize: row.afterSize ?? null,
47
+ differentPixels: row.pixels?.differentPixels ?? 0,
48
+ images: {
49
+ before: safeImageSrc(rawImages.before),
50
+ after: safeImageSrc(rawImages.after),
51
+ difference: safeImageSrc(rawImages.difference),
52
+ },
53
+ });
54
+ }
55
+
56
+ const sections = { added: [], removed: [], changed: [] };
57
+ for (const entry of grouped.values()) {
58
+ const orderedThemes = ['light', 'dark'].filter(theme => entry.rows.has(theme)).map(theme => entry.rows.get(theme));
59
+ for (const [theme, value] of entry.rows) {
60
+ if (!['light', 'dark'].includes(theme)) orderedThemes.push(value);
61
+ }
62
+ if (entry.status === 'added') {
63
+ sections.added.push({ source: entry.source, frame: entry.frame, status: 'added', themes: orderedThemes });
64
+ } else if (entry.status === 'removed') {
65
+ 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 });
68
+ }
69
+ }
70
+
71
+ const fallbackLabel = data.project ? data.project.split(/[\\/]/).filter(Boolean).at(-1) : 'Design review';
72
+ return {
73
+ label: label || fallbackLabel || 'Design review',
74
+ base: data.base ?? { rev: 'HEAD', sha: '' },
75
+ current: data.current ?? { kind: 'working_tree', head: null },
76
+ complete: !!data.complete,
77
+ verdict: data.verdict ?? null,
78
+ counts: {
79
+ added: sections.added.length,
80
+ removed: sections.removed.length,
81
+ changed: sections.changed.length,
82
+ },
83
+ sections,
84
+ };
85
+ }
86
+
87
+ function renderSide(side, label, src, absentLabel, alt, theme) {
88
+ const diffClass = side === 'difference' ? ' review-stage-diff' : '';
89
+ const body = src
90
+ ? `<div class="review-stage${diffClass}" data-stage-theme="${escapeHtml(theme)}"><img src="${escapeHtml(src)}" alt="${escapeHtml(alt)}" loading="lazy"></div>`
91
+ : `<div class="review-absent">${escapeHtml(absentLabel)}</div>`;
92
+ return `<figure class="review-pane" data-side="${escapeHtml(side)}"><figcaption>${escapeHtml(label)}</figcaption>${body}</figure>`;
93
+ }
94
+
95
+ function renderFrameCard(item) {
96
+ const label = `${item.source} · ${item.frame}`;
97
+ const themeBlocks = item.themes.map(themeItem => {
98
+ const theme = themeItem.theme;
99
+ const summary = themeSummary(themeItem);
100
+ return `<div class="review-theme" data-theme-row="${escapeHtml(theme)}" data-verdict="${escapeHtml(themeItem.verdict)}">
101
+ <div class="review-theme-head">
102
+ <span class="review-theme-name">${escapeHtml(theme)}</span>
103
+ <span class="review-theme-meta">${escapeHtml(summary)}</span>
104
+ </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)}
109
+ </div>
110
+ </div>`;
111
+ }).join('');
112
+ return `<article class="review-frame" data-source="${escapeHtml(item.source)}" data-frame="${escapeHtml(item.frame)}" data-status="${escapeHtml(item.status)}">
113
+ <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>
116
+ </header>
117
+ <div class="review-themes">${themeBlocks}</div>
118
+ </article>`;
119
+ }
120
+
121
+ export function renderReviewBody(review) {
122
+ const counts = review.counts ?? { added: 0, removed: 0, changed: 0 };
123
+ const baseLabel = review.base?.sha
124
+ ? `${review.base.rev} (${shortSha(review.base.sha)})`
125
+ : (review.base?.rev ?? 'base');
126
+ const headLabel = review.current?.head ? `working tree (${shortSha(review.current.head)})` : 'working tree';
127
+ const sectionSpecs = [
128
+ ['added', 'Added', review.sections?.added ?? []],
129
+ ['removed', 'Removed', review.sections?.removed ?? []],
130
+ ['changed', 'Changed', review.sections?.changed ?? []],
131
+ ];
132
+ const renderedSections = sectionSpecs
133
+ .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>
137
+ </section>`)
138
+ .join('');
139
+ const empty = renderedSections
140
+ ? ''
141
+ : `<p class="review-empty" role="status">No added, removed, or changed frames against <code>${escapeHtml(review.base?.rev ?? 'base')}</code>.</p>`;
142
+
143
+ return `<header class="review-header">
144
+ <div class="review-heading">
145
+ <h1 id="review-title">${escapeHtml(review.label)}</h1>
146
+ <code class="review-revisions">base ${escapeHtml(baseLabel)} → ${escapeHtml(headLabel)}</code>
147
+ </div>
148
+ <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>
152
+ </div>
153
+ </header>
154
+ <div class="review-scroll">${renderedSections}${empty}</div>`;
155
+ }
156
+
157
+ export function renderReview(container, review) {
158
+ container.innerHTML = renderReviewBody(review);
159
+ }
160
+
161
+ 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; }
164
+ .review-heading h1 { font-size:var(--text-title); font-weight:650; line-height:20px; margin:0; }
165
+ .review-revisions { font:var(--text-meta)/1.4 var(--font-mono); color:var(--text-secondary); }
166
+ .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); }
168
+ .review-count strong { font-family:var(--font-mono); font-weight:650; color:var(--text); }
169
+ .review-scroll { min-height:0; flex:1; overflow:auto; padding:20px; display:flex; flex-direction:column; gap:28px; }
170
+ .review-section { display:flex; flex-direction:column; gap:14px; }
171
+ .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); }
173
+ .review-section-list { display:flex; flex-direction:column; gap:16px; }
174
+ .review-frame { border:1px solid var(--border); border-radius:var(--radius-menu); background:var(--surface-section); overflow:hidden; }
175
+ .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); }
178
+ .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); }
180
+ .review-themes { display:flex; flex-direction:column; gap:1px; background:var(--border); }
181
+ .review-theme { background:var(--surface); padding:14px 16px 16px; display:flex; flex-direction:column; gap:10px; }
182
+ .review-theme-head { display:flex; align-items:center; justify-content:space-between; flex-wrap:wrap; gap:8px; }
183
+ .review-theme-name { font-size:var(--text-meta); font-weight:650; text-transform:capitalize; color:var(--text); }
184
+ .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; }
186
+ @media (max-width:900px) { .review-columns { grid-template-columns:1fr; } }
187
+ .review-pane { margin:0; display:flex; flex-direction:column; gap:6px; min-width:0; }
188
+ .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; }
193
+ .review-stage img { display:block; max-width:100%; height:auto; }
194
+ .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
+ .review-empty { margin:12px 0; color:var(--text-secondary); font-size:var(--text-body); }
196
+ .review-empty code { font:var(--text-meta)/1.4 var(--font-mono); }
197
+ `.trim();
198
+
199
+ export function reviewDocumentHtml(review) {
200
+ const title = `${review.label} · Design review`;
201
+ return `<!doctype html>
202
+ <html lang="en">
203
+ <head>
204
+ <meta charset="utf-8">
205
+ <meta name="viewport" content="width=device-width,initial-scale=1">
206
+ <title>${escapeHtml(title)}</title>
207
+ <style>
208
+ :root {
209
+ color-scheme: light dark;
210
+ --font-ui: -apple-system, BlinkMacSystemFont, "SF Pro Text", "PingFang SC", "Segoe UI", Inter, sans-serif;
211
+ --font-mono: "SF Mono", ui-monospace, Menlo, Consolas, monospace;
212
+ --text-title: 15px;
213
+ --text-section: 14px;
214
+ --text-body: 13px;
215
+ --text-meta: 12px;
216
+ --text-caption: 11px;
217
+ --radius-panel: 14px;
218
+ --radius-menu: 12px;
219
+ --radius-row: 8px;
220
+ --canvas: #ecece9;
221
+ --surface: #ffffff;
222
+ --surface-section: #f5f5f3;
223
+ --surface-sunken: #f1f1ee;
224
+ --border: #e2e2de;
225
+ --text: #1c1c1a;
226
+ --text-secondary: #5b5b57;
227
+ --text-tertiary: #7c7c77;
228
+ }
229
+ @media (prefers-color-scheme: dark) {
230
+ :root {
231
+ --canvas: #121212;
232
+ --surface: #1f1f1f;
233
+ --surface-section: #191919;
234
+ --surface-sunken: #2a2a2a;
235
+ --border: #2d2d2d;
236
+ --text: #efefed;
237
+ --text-secondary: #a8a8a4;
238
+ --text-tertiary: #85857f;
239
+ }
240
+ }
241
+ * { box-sizing: border-box; }
242
+ body { margin: 0; font: var(--text-body)/1.35 var(--font-ui); color: var(--text); background: var(--canvas); }
243
+ main#review-document { max-width: 1480px; margin: 16px auto; background: var(--surface); border: 1px solid var(--border); border-radius: var(--radius-panel); overflow: hidden; }
244
+ main#review-document .review-scroll { overflow: visible; }
245
+ ${REVIEW_STYLES}
246
+ </style>
247
+ </head>
248
+ <body>
249
+ <main id="review-document" aria-labelledby="review-title">
250
+ ${renderReviewBody(review)}
251
+ </main>
252
+ </body>
253
+ </html>
254
+ `;
255
+ }
package/public/style.css CHANGED
@@ -99,6 +99,42 @@ h3 { font-size:var(--text-meta); color:var(--text-tertiary); font-weight:550; li
99
99
  .token-length span::before { content:''; width:100%; height:1px; background:var(--text-tertiary); }
100
100
  .token-radius { height:48px; border:1px solid var(--border); background:var(--surface-sunken); }
101
101
  #token-status { margin:16px 0; color:var(--text-secondary); }
102
+ #review-page { inset:var(--panel-top) 12px 12px; display:flex; flex-direction:column; overflow:hidden; }
103
+ .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; }
104
+ .review-heading { display:flex; align-items:baseline; flex-wrap:wrap; gap:8px 12px; min-width:0; }
105
+ .review-heading h1 { font-size:var(--text-title); font-weight:650; line-height:20px; margin:0; }
106
+ .review-revisions { font:var(--text-meta)/1.4 var(--font-mono); color:var(--text-secondary); }
107
+ .review-counts { display:flex; align-items:center; flex-wrap:wrap; gap:8px; }
108
+ .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); }
109
+ .review-count strong { font-family:var(--font-mono); font-weight:650; color:var(--text); }
110
+ .review-scroll { min-height:0; flex:1; overflow:auto; padding:20px; display:flex; flex-direction:column; gap:28px; }
111
+ .review-section { display:flex; flex-direction:column; gap:14px; }
112
+ .review-section-title { display:flex; align-items:center; gap:8px; font-size:var(--text-section); font-weight:650; color:var(--text); margin:0; }
113
+ .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); }
114
+ .review-section-list { display:flex; flex-direction:column; gap:16px; }
115
+ .review-frame { border:1px solid var(--border); border-radius:var(--radius-menu); background:var(--surface-section); overflow:hidden; }
116
+ .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); }
117
+ .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); }
118
+ .review-frame-head code { font:var(--text-meta)/1.4 var(--font-mono); color:var(--text-secondary); }
119
+ .review-dot { color:var(--text-tertiary); }
120
+ .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); }
121
+ .review-themes { display:flex; flex-direction:column; gap:1px; background:var(--border); }
122
+ .review-theme { background:var(--surface); padding:14px 16px 16px; display:flex; flex-direction:column; gap:10px; }
123
+ .review-theme-head { display:flex; align-items:center; justify-content:space-between; flex-wrap:wrap; gap:8px; }
124
+ .review-theme-name { font-size:var(--text-meta); font-weight:650; text-transform:capitalize; color:var(--text); }
125
+ .review-theme-meta { font:var(--text-caption)/1.4 var(--font-mono); color:var(--text-tertiary); }
126
+ .review-columns { display:grid; grid-template-columns:repeat(3, minmax(0, 1fr)); gap:12px; align-items:start; }
127
+ @media (max-width:900px) { .review-columns { grid-template-columns:1fr; } }
128
+ .review-pane { margin:0; display:flex; flex-direction:column; gap:6px; min-width:0; }
129
+ .review-pane figcaption { font-size:var(--text-caption); font-weight:550; color:var(--text-secondary); }
130
+ .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; }
131
+ .review-stage[data-stage-theme="dark"] { background:#121212; border-color:#2d2d2d; }
132
+ .review-stage-diff { background:repeating-conic-gradient(var(--surface-sunken) 0% 25%, var(--surface) 0% 50%) 50% / 14px 14px; }
133
+ .review-stage-diff[data-stage-theme="dark"] { background:repeating-conic-gradient(#1f1f1f 0% 25%, #161616 0% 50%) 50% / 14px 14px; }
134
+ .review-stage img { display:block; max-width:100%; height:auto; }
135
+ .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); }
136
+ .review-empty { margin:12px 0; color:var(--text-secondary); font-size:var(--text-body); }
137
+ .review-empty code { font:var(--text-meta)/1.4 var(--font-mono); }
102
138
  @media (max-width:600px) {
103
139
  #token-table .token-length, #token-table .token-radius { display:none; }
104
140
  #token-table th, #token-table td { padding-right:8px; }
@@ -43,6 +43,7 @@ export function viewURL(base, scope, target = {}, { isolated = false, onlyFrame
43
43
  const url = new URL(base);
44
44
  url.pathname = viewerBase(url.pathname);
45
45
  for (const key of locatorKeys) url.searchParams.delete(key);
46
+ if (scope === 'review') return url;
46
47
  const { path, group, form, element } = target;
47
48
  if (onlyFrame) {
48
49
  url.searchParams.set('asset', path);
package/src/cli.mjs CHANGED
@@ -29,10 +29,10 @@ const details = {
29
29
  service: 'Manage the macOS resident hub LaunchAgent. install starts it with RunAtLoad and KeepAlive, recording absolute Node/CLI paths. --port applies only to install. status prints JSON; logs prints the last 200 lines per log. Uninstall retains state and logs. migrate moves old hub state and replaces its LaunchAgent, then lists other agents referencing the old state path. --state-dir selects the migration destination. Other platforms are unsupported.',
30
30
  root: 'Manage registered scan roots. add scans immediately. scan rescans registered roots only; depth is 0 through 3. Hidden directories, node_modules and Git worktrees are skipped.',
31
31
  open: 'Browse TSX, Mermaid architecture sources and legacy SVG designs on an independent random-port server.', init: 'Create design sources, tokens and editor configuration without overwriting files.',
32
- link: 'Print a clean ADG preview URL. Query mode isolates a target. Path mode locates it in the design hierarchy.',
32
+ link: 'Print a clean ADG preview URL. --base=<rev> on a clean viewer URL opens the Git frame review page. Query mode isolates a target. Path mode locates it in the design hierarchy.',
33
33
  check: 'Check import direction and every selected frame in both themes. --read-only skips generated types and build files. --impacted --base=<rev> evaluates scheduled current rows; proven rows remain not_checked with partial coverage.', render: 'Render selected frames as PNG. Defaults to both themes at 2×. --impacted --base=<rev> captures scheduled plain current frames and reports deletions, with operation-local proofs for skipped rows. Ordinary architecture --base produces proposal overlays; --impacted never does. --json prints completed captures and impact coverage, including zero-job runs.',
34
34
  compare: 'Compare fixture text positions. Flags override Frame fixture and capture. --all writes a summary for every fixture frame.',
35
- diff: 'Compare the Git base and working-tree source/frame union. Existing frames require exact pixels and CSS/device size; added Frame parent declarations enable structural part evidence under diff.thresholds. Defaults to both themes at 2× and <configured output>/diff. Writes before, after and difference PNGs plus report.json. --impacted captures only scheduled rows; unqualified both-theme runs count fresh proofs toward full coverage. Required parents/support always capture. A structural batch requires all existing frames in both themes; source/frame/theme restrictions report partial coverage. Exit 0 identical/structural, 1 changed, 2 incomplete.',
35
+ diff: 'Compare the Git base and working-tree source/frame union. Existing frames require exact pixels and CSS/device size; added Frame parent declarations enable structural part evidence under diff.thresholds. Defaults to both themes at 2× and <configured output>/diff, overwriting previous diff artifacts and writing a self-contained index.html review page, before/after/difference PNGs and report.json. --impacted captures only scheduled rows (both themes when either theme of a frame is impacted); unqualified both-theme runs count fresh proofs toward full coverage. Required parents/support always capture. A structural batch requires all existing frames in both themes; source/frame/theme restrictions report partial coverage. Exit 0 identical/structural, 1 changed, 2 incomplete.',
36
36
  owner: 'Find owning design sources, parts, frames and tokens from an implementation path, rendered text, absolute CSS color or token name. Paths resolve from the project root; quote globs. --part reverses the lookup from a design source or source#Export to implementation bindings with resolved files and symbol regions. --line returns the containing export/anchor region, including unmapped exports; non-exported helpers belong to the preceding export. Text is NFC/whitespace normalized and exact unless --contains; --locale filters exact Frame locale annotations without translation. Colors use 8-bit sRGB RGBA equality. Owner evidence is scoped to the query: mappings for files, text runs for text, computed paint for colors and authored references for tokens. Text authoredIn lists literal-search copy candidates; escaped or concatenated strings may be missed. Color evidence may include compact same-element/property references. Defaults to both themes. Broad color/token JSON can be around 100 KB; read owners first and narrow with --theme. Empty, stale and ambiguous results exit 0; invalid/incomplete requests exit 2.',
37
37
  inspect: 'Read TSX frame structure, text, CSS-pixel boxes, computed styles and token-reference evidence. Without a unique frame, return a catalog. Default: both themes, all fields, full depth. Field groups: structure,layout,typography,color,text. Shared styles, semantic wrappers, repeated subtrees and a sparse dark delta keep the default compact. --expand reconstructs ordinary element records for both themes. No consumer application or viewer is started. Exit 0 completed observation, 2 invalid/incomplete.',
38
38
  impact: 'Query direct/transitive candidates from sources, named parts, tokens or implementation mappings, or compare exact Git endpoints. --base includes staged, unstaged and untracked working files; --head selects another exact commit. Hypothetical selectors cannot prove skips; token candidates assume unchanged Tailwind classification. Git mode freshly executes both endpoint source sets and compares eligible materialized inputs. Closure or occurrence absence never proves safety. Groups merge equal theme and same-source frame records; noncandidate proofs remain counts. --explain samples witnesses/digests without splitting groups. No browser launch. Render/check/diff --impacted compute their own operation-local proofs. Exit 0 completed, including empty/stale mappings; 2 invalid/incomplete.',
package/src/http.mjs CHANGED
@@ -13,6 +13,7 @@ export const viewerFiles = {
13
13
  '/arrangement.js': 'arrangement.js', '/arrangement-worker.js': 'arrangement-worker.js',
14
14
  '/relationships.js': 'relationships.js', '/selection.js': 'selection.js', '/style.css': 'style.css', '/tokens.css': 'tokens.css',
15
15
  '/token-catalog.js': 'token-catalog.js',
16
+ '/review.js': 'review.js',
16
17
  '/annotations.js': 'annotations.js',
17
18
  '/view-route.js': 'view-route.js',
18
19
  };
package/src/server.mjs CHANGED
@@ -8,6 +8,7 @@ import {
8
8
  writeFile,
9
9
  mkdir,
10
10
  readdir,
11
+ rm,
11
12
  stat,
12
13
  realpath,
13
14
  } from "node:fs/promises";
@@ -25,6 +26,7 @@ import { loadConfig } from './toolkit/config.mjs';
25
26
  import { parseTokens } from './toolkit/tokens.mjs';
26
27
  import { sourceRelationships } from '../public/relationships.js';
27
28
  import { resolveScope } from '../public/assets.js';
29
+ import { diff } from './toolkit/diff.mjs';
28
30
  const digest = value => createHash('sha256').update(value).digest('hex');
29
31
  const tokenFile = 'tokens.css';
30
32
  function tokenSourcePath(directory, project) {
@@ -62,7 +64,7 @@ export async function startServer({
62
64
  revision = 0,
63
65
  closing = false,
64
66
  buildStore, viewerCache, codePaths=new Set();
65
- const overlayStores = new Map(), overlayHashes = new Set();
67
+ const overlayStores = new Map(), overlayHashes = new Set(), activeReviews = new Set();
66
68
  let resettingOverlays = false;
67
69
  const knownBuilds = new Map(), legacyDependencies = new Map(), failedSources=new Set(), dirtyBuilds=new Set();
68
70
  const describe=built=>({...built,css:undefined,frames:built.frames.map(({html,...frame})=>frame)});
@@ -427,6 +429,37 @@ export async function startServer({
427
429
  data.features={compactSources:1,persistedMetadata:1,incrementalHashes:1};
428
430
  return applyFixtureManifest(data,url.searchParams.get('fixture'));
429
431
  }
432
+ async function reviewManifest(url) {
433
+ const baseParam = url.searchParams.get('base');
434
+ if (typeof baseParam !== 'string' || !baseParam.trim())
435
+ throw new CliError('USAGE_INVALID', 'Set ?base=<rev> to a Git revision.');
436
+ if (!activeProject || !root)
437
+ throw new CliError('DIRECTORY_NOT_FOUND', 'No project is open.');
438
+ const data = baseManifest();
439
+ const { layers } = resolveScope(data, sources, 'all');
440
+ const reviewDir = path.join(stateDirectory, 'cache', digest(root), 'review', randomUUID());
441
+ let review = null;
442
+ const task = (async () => {
443
+ try {
444
+ await diff(activeProject, [], {
445
+ base: baseParam,
446
+ impacted: true,
447
+ 'out-dir': reviewDir,
448
+ 'state-dir': stateDirectory,
449
+ json: true,
450
+ }, { log: () => {}, onReview: value => { review = value; } });
451
+ } catch (error) {
452
+ if (error.code !== 'DIFF_FAILED') throw error;
453
+ } finally {
454
+ await rm(reviewDir, { recursive: true, force: true }).catch(() => {});
455
+ }
456
+ if (!review) throw new CliError('INTERNAL_ERROR', 'Review output was not produced.');
457
+ return { ...data, scope: 'review', layers, assets: [], base: review.base, review: { ...review, label: data.label } };
458
+ })();
459
+ activeReviews.add(task);
460
+ try { return await task; }
461
+ finally { activeReviews.delete(task); }
462
+ }
430
463
  async function sourceBuild(name) {
431
464
  const endBuild = perfSpan('build', name);
432
465
  let built;
@@ -635,6 +668,9 @@ export async function startServer({
635
668
  if (url.pathname === "/manifest") {
636
669
  content = JSON.stringify(await manifest(url));
637
670
  type = "application/json";
671
+ } else if (url.pathname === "/review") {
672
+ content = JSON.stringify(await reviewManifest(url));
673
+ type = "application/json";
638
674
  } else if (url.pathname === "/relationships") {
639
675
  const assets = await Promise.all([...files.keys()].filter(name => /\.(tsx|mmd)$/.test(name)).map(async name => ({path:name, imports:(await sourceBuild(name)).imports})));
640
676
  content = JSON.stringify(sourceRelationships(assets));
@@ -692,6 +728,7 @@ export async function startServer({
692
728
  },
693
729
  async () => { await writes; },
694
730
  async () => { await buildStore?.close(); },
731
+ async () => { await Promise.allSettled([...activeReviews]); },
695
732
  closeOverlays,
696
733
  async () => { await viewerCache?.close(); },
697
734
  ]) {
@@ -20,7 +20,7 @@ function frameStructure(frame) {
20
20
  .trim();
21
21
  }
22
22
 
23
- function frameOwnsPart(frame, source, part, config) {
23
+ function frameOwnsPart(frame, source, part) {
24
24
  return (frame.owners ?? frameOwners(frame.html)).some(owner => owner.source === source && owner.export === part);
25
25
  }
26
26
 
@@ -300,10 +300,11 @@ export async function check(config, args = [], options = {}, log = console.log,
300
300
  const active = validatedMap.bindings.filter(binding => binding.active);
301
301
  const hasBinding = (source, part = null) => active.some(binding => binding.design.source === source && (part === null ? binding.design.part === undefined : binding.design.part === part));
302
302
  for (const [source, built] of allBuilt) {
303
- const layer = source.split('/')[0];
303
+ const designSource = path.relative(config.design, path.join(config.root, source)).split(path.sep).join('/');
304
+ const layer = designSource.split('/')[0];
304
305
  if (!production.includes(layer)) continue;
305
306
  for (const part of built.parts ?? []) {
306
- const frames = built.frames.filter(frame => frameOwnsPart(frame, source.replace(/^design\//, ''), part, config));
307
+ const frames = built.frames.filter(frame => frameOwnsPart(frame, designSource, part));
307
308
  if (layer !== top && !hasBinding(source, part) && !frames.some(frame => frame.proposed)) add({ code: 'OWNER_PART_UNBOUND', message: `Exported part ${part} has no implementation binding or proposed frame; add a binding or mark a review frame with proposed`, line: null, column: null }, path.join(config.root, source));
308
309
  }
309
310
  if (layer === top && !hasBinding(source)) add({ code: 'OWNER_SURFACE_UNBOUND', message: `Surface source has no whole-source implementation binding; add a binding without part`, line: null, column: null }, path.join(config.root, source));
@@ -311,7 +312,7 @@ export async function check(config, args = [], options = {}, log = console.log,
311
312
  }
312
313
  }
313
314
  if (config.check?.singleConsumer !== false) {
314
- for (const warning of singleConsumerComponents(graph, sourceDirectories(config), Object.fromEntries([...allBuilt].map(([source, built]) => [source.replace(/^design\//, ''), built.parts ?? []])))) {
315
+ for (const warning of singleConsumerComponents(graph, sourceDirectories(config), Object.fromEntries([...allBuilt].map(([source, built]) => [path.relative(config.design, path.join(config.root, source)).split(path.sep).join('/'), built.parts ?? []])))) {
315
316
  warnings.push({ code: warning.code, message: warning.message, next: [] });
316
317
  if (!options.json) log(`WARNING ${warning.message}`);
317
318
  }
@@ -1,6 +1,6 @@
1
1
  import path from 'node:path';
2
2
  import { readFileSync } from 'node:fs';
3
- import { mkdir, writeFile } from 'node:fs/promises';
3
+ import { mkdir, rm, writeFile } from 'node:fs/promises';
4
4
  import { availableParallelism } from 'node:os';
5
5
  import { launch, loadFrame, browserTask, readyResources } from './browser.mjs';
6
6
  import { prepareDiffInputs } from './diff-inputs.mjs';
@@ -11,6 +11,7 @@ import { commandFailure, cleanup, emptySelection } from './results.mjs';
11
11
  import { CliError, classifyError, asCliError, nextActions } from '../cli-output.mjs';
12
12
  import { withImpacted } from './impact-selection.mjs';
13
13
  import { resolveDiffPolicy } from './diff-policy.mjs';
14
+ import { buildReview, reviewDocumentHtml } from '../../public/review.js';
14
15
 
15
16
  const metadata = JSON.parse(readFileSync(new URL('../../package.json', import.meta.url), 'utf8'));
16
17
  const safeName = name => encodeURIComponent(name).replace(/\./g, '%2E');
@@ -78,7 +79,7 @@ async function comparePair(browser, pair, thresholds, context) {
78
79
  } catch (error) { throw frameFailure(error, pair.row, pair.theme); }
79
80
  }
80
81
 
81
- async function writePair(output, pair, thresholds) {
82
+ async function writePair(output, pair, thresholds, reviewImages) {
82
83
  const { row, theme } = pair;
83
84
  const directory = path.join(output, row.support ? 'support' : 'frames', ...row.source.split('/').map(safeName), safeName(row.frame), theme);
84
85
  await mkdir(directory, { recursive: true });
@@ -116,6 +117,13 @@ async function writePair(output, pair, thresholds) {
116
117
  metadata: { before: row.before ? { locale: row.before.locale ?? null, proposed: row.before.proposed ?? null, fixture: row.before.fixture ?? null, capture: row.before.capture ?? null } : null,
117
118
  after: row.after ? { locale: row.after.locale ?? null, proposed: row.after.proposed ?? null, fixture: row.after.fixture ?? null, capture: row.after.capture ?? null } : null }, paths,
118
119
  };
120
+ if (!row.support) {
121
+ reviewImages.set(comparison.id, {
122
+ before: pair.before ? `data:image/png;base64,${pair.before.png.toString('base64')}` : null,
123
+ after: pair.after ? `data:image/png;base64,${pair.after.png.toString('base64')}` : null,
124
+ difference: `data:image/png;base64,${pair.difference.toString('base64')}`,
125
+ });
126
+ }
119
127
  await Promise.all([
120
128
  pair.before && writeFile(paths.before, pair.before.png),
121
129
  pair.after && writeFile(paths.after, pair.after.png),
@@ -129,9 +137,9 @@ async function writePair(output, pair, thresholds) {
129
137
  }
130
138
 
131
139
  /** Exact ordinary frames and evidence-backed structural part comparisons. */
132
- export async function diff(config, args = [], options = {}, { launchBrowser = launch, prepareInputs = prepareDiffInputs, log = console.log, clock, session } = {}) {
140
+ export async function diff(config, args = [], options = {}, { launchBrowser = launch, prepareInputs = prepareDiffInputs, log = console.log, clock, session, onReview } = {}) {
133
141
  if (options.impacted && !session) return withImpacted(config, args, options, 'diff', selected =>
134
- diff(config, args, options, { launchBrowser, prepareInputs, log, clock, session: selected }));
142
+ diff(config, args, options, { launchBrowser, prepareInputs, log, clock, session: selected, onReview }));
135
143
  const started = performance.now(), scale = Number(options.scale ?? 2), themeOption = options.theme ?? 'both';
136
144
  if (!Number.isFinite(scale) || scale <= 0) throw new CliError('USAGE_INVALID', 'Invalid --scale; use a positive number.');
137
145
  if (!['both', 'light', 'dark'].includes(themeOption)) throw new CliError('USAGE_INVALID', 'Choose --theme=both, light, or dark.');
@@ -139,7 +147,7 @@ export async function diff(config, args = [], options = {}, { launchBrowser = la
139
147
  const themes = themeOption === 'both' ? ['light', 'dark'] : [themeOption];
140
148
  const output = options['out-dir'] === undefined ? path.join(config.output, 'diff') : path.resolve(config.root, options['out-dir']);
141
149
  const timings = { prepareMs: 0, buildMs: 0, captureMs: 0, compareMs: 0, writeMs: 0, totalMs: 0 };
142
- const warnings = [], completed = [];
150
+ const warnings = [], completed = [], reviewImages = new Map();
143
151
  const thresholds = config.diff?.thresholds ?? resolveDiffPolicy().thresholds;
144
152
  let inputs, browser, data, primary, context;
145
153
  const timed = async (name, work) => {
@@ -164,8 +172,11 @@ export async function diff(config, args = [], options = {}, { launchBrowser = la
164
172
  summary: { sources: inputs.sources.length, frames: 0, comparisons: 0, supportComparisons: 0, isolationCaptures: 0,
165
173
  added: 0, removed: 0, matched: 0, identical: 0, structural: 0, changed: 0,
166
174
  classPixels: Object.fromEntries(classNames.map(name => [name, 0])) },
167
- differencePalette: { equal: '#00000000', imperceptible: '#64748b', antialiasing: '#f59e0b', boundary_bleed: '#0ea5e9', bitmap_resampling: '#a855f7', other: '#ff00ff' }, reportPath: null, timings,
175
+ review: { added: 0, removed: 0, changed: 0 },
176
+ differencePalette: { equal: '#00000000', imperceptible: '#64748b', antialiasing: '#f59e0b', boundary_bleed: '#0ea5e9', bitmap_resampling: '#a855f7', other: '#ff00ff' }, reportPath: null, indexPath: null, timings,
168
177
  };
178
+ await timed('writeMs', () => Promise.all(['frames', 'support', 'report.json', 'index.html'].map(entry =>
179
+ rm(path.join(output, entry), { recursive: true, force: true }))));
169
180
  if (session ? session.chosen.some(row => row.source.endsWith('.mmd') && session.themes.some(theme => session.scheduled(row, theme))) : inputs.sources.length) browser = await launchBrowser();
170
181
  const built = await timed('buildMs', () => inputs.buildFrames({ browser }));
171
182
  if (session) built.frames = built.frames.filter(row => themes.some(theme => session.scheduled(row, theme)));
@@ -198,7 +209,7 @@ export async function diff(config, args = [], options = {}, { launchBrowser = la
198
209
  ? browserTask(browser, () => capturePart(browser, job.row, job.theme, context)).catch(error => { throw frameFailure(error, job.row, job.theme); })
199
210
  : capturePair(browser, job.row, job.theme, scale, context)));
200
211
  const compared = await phase('compareMs', openPairs, pair => comparePair(browser, pair, thresholds, context));
201
- const rows = await phase('writeMs', compared, pair => writePair(output, pair, thresholds));
212
+ const rows = await phase('writeMs', compared, pair => writePair(output, pair, thresholds, reviewImages));
202
213
  for (const row of rows) {
203
214
  context?.comparisons.set(comparisonIdentity(row, row.theme), row);
204
215
  if (supportKeys.has(frameIdentity(row))) { data.support.push(row); data.summary.supportComparisons++; }
@@ -248,18 +259,23 @@ export async function diff(config, args = [], options = {}, { launchBrowser = la
248
259
  warnings.push({ code: 'DIFF_COVERAGE_INCOMPLETE', message: 'A structural batch requires every existing frame in both themes.', next });
249
260
  }
250
261
  }
262
+ const reviewModel = buildReview(data, reviewImages, { label: config.name ?? path.basename(config.root) });
263
+ data.review = reviewModel.counts;
264
+ onReview?.(reviewModel);
251
265
  timings.totalMs = performance.now() - started;
252
266
  data.reportPath = path.join(output, 'report.json');
267
+ data.indexPath = path.join(output, 'index.html');
253
268
  try {
254
- if (!session) await mkdir(output, { recursive: true });
269
+ await mkdir(output, { recursive: true });
270
+ await writeFile(data.indexPath, reviewDocumentHtml(reviewModel));
255
271
  if (!session) await writeFile(data.reportPath, JSON.stringify(data, null, 2) + '\n');
256
272
  } catch (error) {
257
- data.reportPath = null; data.complete = false; data.verdict = null;
273
+ data.reportPath = null; data.indexPath = null; data.complete = false; data.verdict = null;
258
274
  if (primary) primary.warnings.push(classifyError(error).error);
259
275
  else primary = commandFailure(error, data, warnings);
260
276
  }
261
277
  if (primary) throw primary;
262
- if (!options.json) log(`${data.verdict}: ${data.summary.frames} frames. ${data.reportPath}`);
278
+ if (!options.json) log(`${data.verdict}: ${data.review.added} added, ${data.review.removed} removed, ${data.review.changed} changed (${data.summary.frames} frames). ${data.indexPath}`);
263
279
  if (data.verdict === 'changed') throw new CliError('DIFF_FAILED', 'Design differences require review.', { data, warnings });
264
280
  return { data, warnings };
265
281
  }
@@ -44,10 +44,14 @@ export async function withImpacted(config, args, options, command, work) {
44
44
  const usedFacts = new Set(selection.frames.flatMap(group => group.rows.flatMap(row => (row.reasons ?? []).map(reason => reason.fact))));
45
45
  selection.facts = data.facts.filter(fact => usedFacts.has(fact.id));
46
46
  const selected = new Set(chosen.flatMap(row => themes.map(theme => impactRowKey(row, theme))));
47
- const scheduled = (row, theme) => selected.has(impactRowKey(row, theme)) && assessments.get(impactRowKey(row, theme)).disposition === 'render';
47
+ const renderRow = (row, theme) => assessments.get(impactRowKey(row, theme))?.disposition === 'render';
48
+ const scheduled = (row, theme) => selected.has(impactRowKey(row, theme)) && (
49
+ renderRow(row, theme) ||
50
+ (command === 'diff' && themes.length === 2 && themes.some(other => renderRow(row, other)))
51
+ );
48
52
  for (const row of chosen) for (const theme of themes) {
49
53
  if (row.status === 'removed') selection.coverage.deletedRows++;
50
- if (assessments.get(impactRowKey(row, theme)).disposition === 'proven_unaffected') {
54
+ if (!scheduled(row, theme) && assessments.get(impactRowKey(row, theme)).disposition === 'proven_unaffected') {
51
55
  if (command === 'check') exclusions.not_checked++;
52
56
  else selection.coverage.provenRows++;
53
57
  }
@@ -89,7 +93,7 @@ export async function withImpacted(config, args, options, command, work) {
89
93
  if (outcome) outcome.warnings = [...new Set([...outcome.warnings, ...warnings])];
90
94
  if (outcome?.data?.reportPath) {
91
95
  try { await mkdir(path.dirname(outcome.data.reportPath), { recursive: true }); await writeFile(outcome.data.reportPath, JSON.stringify(outcome.data, null, 2) + '\n'); }
92
- catch (cause) { discardProofs(); outcome.data.reportPath = null; failure = commandFailure(cause, outcome.data, outcome.warnings); }
96
+ catch (cause) { discardProofs(); outcome.data.reportPath = null; if ('indexPath' in outcome.data) outcome.data.indexPath = null; failure = commandFailure(cause, outcome.data, outcome.warnings); }
93
97
  }
94
98
  if (failure) { if (outcome?.data) failure = commandFailure(failure, outcome.data, outcome.warnings); throw failure; }
95
99
  return outcome;