@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
@@ -0,0 +1,200 @@
1
+ import { parseTokens, themeCss } from '../toolkit/tokens.mjs';
2
+ import { motionBoardCss, motionCards } from './motion-board.mjs';
3
+ import { escape } from '../toolkit/html.mjs';
4
+ import { boardCss, boardHeader, sectionMarkup, boardWidth, specimenWidth } from './board.mjs';
5
+
6
+ const sizeTrackWidth = (specimenWidth - 32) / 2;
7
+
8
+ const tokenStyles = `
9
+ [data-adg-token-groups]{display:flex;flex-direction:column;gap:40px}
10
+ [data-adg-token-group]>h3{margin:0 0 16px;font-size:var(--text-body,13px);line-height:18px;font-weight:600}
11
+ [data-adg-token-grid]{display:grid;grid-template-columns:repeat(7,minmax(0,1fr));gap:32px 24px;align-items:start}
12
+ [data-adg-token]{min-width:0;margin:0}
13
+ [data-adg-token] code{display:block;font:var(--text-meta,12px)/17px var(--font-mono,ui-monospace,monospace);overflow-wrap:anywhere}
14
+ [data-adg-token] small{display:block;margin-top:2px;color:var(--text-tertiary,#777);font:var(--text-caption,11px)/16px var(--font-mono,ui-monospace,monospace);overflow-wrap:anywhere}
15
+ [data-adg-token-swatch]{display:flex;height:72px;margin-bottom:8px;overflow:hidden;border:1px solid var(--border,#deded9);border-radius:var(--radius-tile,var(--radius-row,8px))}
16
+ [data-adg-token-swatch]>span{flex:1;min-width:0}
17
+ [data-adg-type-scale]{display:flex;flex-direction:column}
18
+ [data-adg-type-row]{display:grid;grid-template-columns:160px minmax(0,1fr) 160px;align-items:baseline;gap:24px;padding:16px 0;border-bottom:1px solid var(--border,#deded9)}
19
+ [data-adg-type-row]>small{text-align:right}
20
+ [data-adg-family-grid]{display:grid;grid-template-columns:repeat(4,minmax(0,1fr));gap:24px}
21
+ [data-adg-family]{padding:16px 20px;border-radius:var(--radius-card,var(--radius-menu,12px));background:var(--canvas,#f0f0ee)}
22
+ [data-adg-family-sample]{margin-bottom:8px;font-size:18px;line-height:26px;overflow-wrap:anywhere}
23
+ [data-adg-shape-grid]{display:grid;grid-template-columns:repeat(auto-fit,minmax(88px,1fr));gap:24px 16px}
24
+ [data-adg-radius]{height:88px;width:88px;margin:0 auto 12px;border:1px solid var(--border-strong,var(--border,#ccc));background:var(--surface-subtle,var(--surface-section,#f5f5f2))}
25
+ [data-adg-shape-grid] [data-adg-token]{text-align:center}
26
+ [data-adg-shadow-grid]{display:grid;grid-template-columns:repeat(4,minmax(0,1fr));gap:32px;padding:40px;border-radius:var(--radius-card,var(--radius-menu,12px));background:var(--canvas,#f0f0ee)}
27
+ [data-adg-shadow]{height:120px;margin-bottom:16px;border-radius:var(--radius-card,var(--radius-menu,12px));background:var(--surface,#fff)}
28
+ [data-adg-size-list]{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:28px 32px;align-items:start}
29
+ [data-adg-size-group]{--adg-size-maximum:var(--adg-size-maximum-light);--adg-size-scale:calc(${sizeTrackWidth}px / var(--adg-size-maximum))}
30
+ [data-adg-size-track]{height:16px;margin-bottom:10px;background:var(--canvas,#f0f0ee)}
31
+ [data-adg-size]{--adg-size-length:var(--adg-size-length-light);width:calc(var(--adg-size-length) * var(--adg-size-scale));height:100%;background:var(--action,var(--accent,#333))}
32
+ :where([data-theme="dark"]) [data-adg-size-group],[data-adg-board][data-theme="dark"] [data-adg-size-group]{--adg-size-maximum:var(--adg-size-maximum-dark)}
33
+ :where([data-theme="dark"]) [data-adg-size],[data-adg-board][data-theme="dark"] [data-adg-size]{--adg-size-length:var(--adg-size-length-dark)}
34
+ [data-adg-size-scale]{font-size:clamp(0px,calc((1 - var(--adg-size-scale)) * 100000px),var(--text-body,13px));font-weight:400;counter-reset:adg-size-scale round(calc(var(--adg-size-scale) * 100))}
35
+ [data-adg-size-scale]::after{content:" · " counter(adg-size-scale) "%"}
36
+ [data-adg-motion-grid]{display:grid;grid-template-columns:repeat(4,minmax(0,1fr));gap:32px 24px;align-items:start}
37
+ [data-adg-easing]{display:block;width:100%;height:128px;margin-bottom:12px;border-radius:var(--radius-card,var(--radius-menu,12px));background:var(--canvas,#f0f0ee);color:var(--text,#20201e)}
38
+ [data-adg-duration-track]{height:12px;margin:24px 0 20px;border-radius:var(--radius-keycap,6px);background:var(--canvas,#f0f0ee);overflow:hidden}
39
+ [data-adg-duration]{height:100%;min-width:2px;border-radius:var(--radius-keycap,6px);background:var(--action,var(--accent,#333))}
40
+ [data-adg-type-extras]{display:grid;grid-template-columns:repeat(3,minmax(0,1fr));gap:20px 24px}
41
+ `;
42
+
43
+ function tokenHeadings(css) {
44
+ const root = /:root\s*\{([\s\S]*?)\}/.exec(css)?.[1] ?? '';
45
+ const headings = new Map();
46
+ let heading;
47
+ for (const line of root.split('\n')) {
48
+ const comment = /^\s*\/\*\s*(.*?)\s*\*\/\s*$/.exec(line);
49
+ if (comment) { heading = comment[1]; continue; }
50
+ const token = /^\s*(--[\w-]+)\s*:/.exec(line);
51
+ if (token && heading) headings.set(token[1], heading);
52
+ }
53
+ return headings;
54
+ }
55
+
56
+ function tokenGroups(headings, names) {
57
+ const groups = new Map();
58
+ for (const name of names) {
59
+ const title = headings.get(name) ?? name.slice(2).split('-')[0];
60
+ if (!groups.has(title)) groups.set(title, []);
61
+ groups.get(title).push(name);
62
+ }
63
+ return groups;
64
+ }
65
+
66
+ function resolvedValue(name, values, seen = new Set()) {
67
+ if (seen.has(name)) return values.get(name) ?? '';
68
+ const visited = new Set([...seen, name]);
69
+ return (values.get(name) ?? '').replace(/var\(\s*(--[\w-]+)\s*(?:,\s*([^()]+))?\)/g,
70
+ (match, reference, fallback) => values.has(reference) ? resolvedValue(reference, values, visited) : fallback ?? match);
71
+ }
72
+
73
+ function caption(name, light, dark) {
74
+ return `<code>${escape(name)}</code><small>Light: ${escape(light)}</small>${light !== dark ? `<small>Dark: ${escape(dark)}</small>` : ''}`;
75
+ }
76
+
77
+ function sizeLength(value) {
78
+ const match = /^(-?(?:\d+\.?\d*|\.\d+))(px|rem|em|vh|vw|%)?$/.exec(value);
79
+ if (!match || (!match[2] && Number(match[1]) !== 0)) return null;
80
+ const number = Math.max(0, Number(match[1]));
81
+ if (match[2] === '%') return `${number / 100 * sizeTrackWidth}px`;
82
+ if (match[2] === 'em') return `${number * 16}px`;
83
+ return `${number}${match[2] ?? 'px'}`;
84
+ }
85
+
86
+ function tokenCategory(name, value, colours) {
87
+ if (colours.has(name)) return 'colour';
88
+ if (/^--(?:font-size|text)-/.test(name) && /^[-.\d]+(?:px|rem|em)$/.test(value)) return 'type';
89
+ if (/^--(?:font|family)-/.test(name) && !/^--font-(?:size|weight|stretch|style|tracking|line)/.test(name)) return 'family';
90
+ if (/^--(?:radius|round)-/.test(name)) return 'radius';
91
+ if (/shadow/.test(name)) return 'shadow';
92
+ if (/^(?:cubic-bezier\(|steps\(|linear\(|ease(?:-in|-out|-in-out)?$|linear$)/.test(value)) return 'easing';
93
+ if (/^[\d.]+m?s$/.test(value)) return 'duration';
94
+ if (/^--(?:line|weight|tracking|font-weight|font-line|letter-spacing)/.test(name)) return 'type-extra';
95
+ return 'size';
96
+ }
97
+
98
+ function easingCurve(value) {
99
+ const points = /^cubic-bezier\(\s*([\d.+-]+)\s*,\s*([\d.+-]+)\s*,\s*([\d.+-]+)\s*,\s*([\d.+-]+)\s*\)$/.exec(value);
100
+ const presets = { ease: [.25,.1,.25,1], 'ease-in': [.42,0,1,1], 'ease-out': [0,0,.58,1], 'ease-in-out': [.42,0,.58,1] };
101
+ const p = points ? points.slice(1).map(Number) : presets[value];
102
+ let curve = 'M16 112 L112 16';
103
+ if (p) curve = `M16 112 C${16 + p[0] * 96} ${112 - p[1] * 96} ${16 + p[2] * 96} ${112 - p[3] * 96} 112 16`;
104
+ const steps = /^steps\(\s*(\d+)(?:\s*,\s*(start|end|jump-start|jump-end))?\s*\)$/.exec(value);
105
+ if (steps) {
106
+ const count = Math.min(100, Number(steps[1]));
107
+ const start = steps[2] === 'start' || steps[2] === 'jump-start';
108
+ curve = `M16 ${start ? 112 - 96 / count : 112}`;
109
+ for (let i = 1; i <= count; i++) curve += ` H${16 + i * 96 / count} V${112 - Math.min(count, i + (start ? 1 : 0)) * 96 / count}`;
110
+ }
111
+ return `<svg data-adg-easing viewBox="0 0 128 128" role="img" aria-label="${escape(value)}"><path d="M16 16 V112 H112" fill="none" stroke="currentColor" opacity=".18"/><path d="${curve}" fill="none" stroke="currentColor" stroke-width="2.5"/></svg>`;
112
+ }
113
+
114
+ export function tokenBoard(source, css, { projectName = 'Design library', patterns, inventory, patternError, prefix = '', patternSource = source } = {}) {
115
+ const tokens = parseTokens(css);
116
+ const darkValues = new Map([...tokens.light, ...tokens.dark]);
117
+ const themes = themeCss(tokens);
118
+ const colours = new Set([...tokens.light.keys()].filter(name => themes.includes(`--color-${name.slice(2)}:var(`)));
119
+ const categories = new Map();
120
+ for (const [name, value] of tokens.light) {
121
+ const category = tokenCategory(name, value, colours);
122
+ if (!categories.has(category)) categories.set(category, []);
123
+ categories.get(category).push(name);
124
+ }
125
+ const light = name => resolvedValue(name, tokens.light);
126
+ const dark = name => resolvedValue(name, darkValues);
127
+ const headings = tokenHeadings(css);
128
+ const groups = (names, render) => `<div data-adg-token-groups>${[...tokenGroups(headings, names)].map(([title, group]) =>
129
+ `<div data-adg-token-group><h3>${escape(title)}</h3>${render(group)}</div>`).join('')}</div>`;
130
+ const article = (name, content, attrs = '') => `<article data-adg-token data-specimen="${escape(`${source}#${name}`)}"${attrs}>${content}</article>`;
131
+ const label = name => caption(name, tokens.light.get(name), tokens.dark.get(name) ?? tokens.light.get(name));
132
+ const section = (title, content) => sectionMarkup({ title, source, content }).replace(
133
+ `data-adg-section="${escape(source)}"`, `data-adg-section="${escape(`${source}#${title.toLowerCase()}`)}"`);
134
+ const sections = [];
135
+ if (categories.has('colour')) {
136
+ sections.push(section('Colour', groups(categories.get('colour'), names => `<div data-adg-token-grid>${names.map(name => article(name,
137
+ `<div data-adg-token-swatch><span style="background:${escape(light(name))}"></span><span style="background:${escape(dark(name))}"></span></div>${label(name)}`)).join('')}</div>`)));
138
+ }
139
+ if (categories.has('type') || categories.has('family') || categories.has('type-extra')) {
140
+ const sizeRow = name => {
141
+ const role = name.replace(/^--(?:font-size|text)-/, '');
142
+ const line = [`--line-${role}`, `--line-height-${role}`, `--font-line-${role}`].find(key => tokens.light.has(key));
143
+ const weight = [`--weight-${role}`, `--font-weight-${role}`].find(key => tokens.light.has(key));
144
+ const style = `font-size:var(${name});line-height:${line ? `var(${line})` : '1.4'};font-weight:${weight ? `var(${weight})` : '400'}`;
145
+ const metrics = [name, line, weight].filter(Boolean).map(key => key === name ? escape(tokens.light.get(key)) : `<span data-specimen="${escape(`${source}#${key}`)}">${escape(tokens.light.get(key))}</span>`).join(' / ');
146
+ return article(name, `<code>${escape(name)}</code><span style="${escape(style)}">The quick brown fox</span><small>${metrics}</small>`, ' data-adg-type-row');
147
+ };
148
+ const paired = new Set((categories.get('type') ?? []).flatMap(name => {
149
+ const role = name.replace(/^--(?:font-size|text)-/, '');
150
+ return [`--line-${role}`, `--line-height-${role}`, `--font-line-${role}`, `--weight-${role}`, `--font-weight-${role}`];
151
+ }));
152
+ const extras = (categories.get('type-extra') ?? []).filter(name => !paired.has(name));
153
+ const names = [...tokens.light.keys()].filter(name => ['type', 'family'].includes(tokenCategory(name, tokens.light.get(name), colours)) || extras.includes(name));
154
+ sections.push(section('Type', groups(names, group => {
155
+ const sizes = group.filter(name => categories.get('type')?.includes(name)).map(sizeRow).join('');
156
+ const families = group.filter(name => categories.get('family')?.includes(name)).map(name => article(name,
157
+ `<div data-adg-family-sample style="font-family:var(${escape(name)})">Aa Bb 0123</div>${label(name)}`, ' data-adg-family')).join('');
158
+ const remaining = group.filter(name => extras.includes(name)).map(name => article(name, label(name))).join('');
159
+ return `${sizes ? `<div data-adg-type-scale>${sizes}</div>` : ''}${families ? `<div data-adg-family-grid>${families}</div>` : ''}${remaining ? `<div data-adg-type-extras>${remaining}</div>` : ''}`;
160
+ })));
161
+ }
162
+ if (categories.has('radius')) sections.push(section('Shape', groups(categories.get('radius'), names => `<div data-adg-shape-grid>${names.map(name => article(name, `<div data-adg-radius style="border-radius:var(${escape(name)})"></div>${label(name)}`)).join('')}</div>`)));
163
+ if (categories.has('shadow')) sections.push(section('Elevation', groups(categories.get('shadow'), names => `<div data-adg-shadow-grid>${names.map(name => article(name, `<div data-adg-shadow style="--hub-color:var(--accent,var(--text,#333));box-shadow:var(${escape(name)})"></div>${label(name)}`)).join('')}</div>`)));
164
+ if (categories.has('size')) {
165
+ const sizeGroups = [...tokenGroups(headings, categories.get('size'))].map(([title, names]) => {
166
+ const lengths = names.map(name => ({ name, light: sizeLength(light(name)), dark: sizeLength(dark(name)) }));
167
+ const maximum = (theme) => `max(${sizeTrackWidth}px,${lengths.map(length => length[theme]).filter(Boolean).join(',') || '0px'})`;
168
+ const scale = `--adg-size-maximum-light:${maximum('light')};--adg-size-maximum-dark:${maximum('dark')}`;
169
+ const bars = lengths.map(length => {
170
+ const preview = length.light === null ? '' : `<div data-adg-size-track><div data-adg-size style="--adg-size-length-light:${length.light};--adg-size-length-dark:${length.dark ?? length.light}"></div></div>`;
171
+ return article(length.name, preview + label(length.name));
172
+ }).join('');
173
+ return `<div data-adg-token-group data-adg-size-group style="${escape(scale)}"><h3>${escape(title)}<span data-adg-size-scale></span></h3><div data-adg-size-list>${bars}</div></div>`;
174
+ }).join('');
175
+ sections.push(section('Sizing', `<div data-adg-token-groups>${sizeGroups}</div>`));
176
+ }
177
+ const cards = patterns ? motionCards(patterns, inventory, patternSource, prefix) : {
178
+ adopted: patternError ? `<p role="status">${escape(patternError)}</p>` : '', notAdopted: '',
179
+ };
180
+ if (cards.adopted || cards.notAdopted || categories.has('easing') || categories.has('duration')) {
181
+ const milliseconds = name => parseFloat(light(name)) * (light(name).endsWith('ms') ? 1 : 1000);
182
+ const names = [...tokens.light.keys()].filter(name => categories.get('easing')?.includes(name) || categories.get('duration')?.includes(name));
183
+ sections.push(section('Motion', cards.adopted + groups(names, group => {
184
+ const maximum = Math.max(1, ...group.filter(name => categories.get('duration')?.includes(name)).map(milliseconds));
185
+ return `<div data-adg-motion-grid>${group.map(name => article(name, categories.get('easing')?.includes(name)
186
+ ? easingCurve(light(name)) + label(name)
187
+ : `<div data-adg-duration-track><div data-adg-duration style="width:${milliseconds(name) / maximum * 100}%"></div></div>${label(name)}`)).join('')}</div>`;
188
+ }) + cards.notAdopted));
189
+ }
190
+ const body = `<main data-adg-board>${boardHeader({ title: 'Tokens', projectName, layer: 'Tokens', number: 1, sourceCount: 1, frameCount: tokens.light.size, countLabel: 'tokens' })}${sections.join('')}</main>`;
191
+ // Scope project tokens to the board so a DOM overlay never changes viewer chrome.
192
+ const declarations = values => [...values].map(([name, value]) => `${name}:${value};`).join('\n');
193
+ const scopedTokens = `[data-adg-board]{${declarations(tokens.light)}}
194
+ :where([data-theme="dark"]) [data-adg-board], [data-adg-board][data-theme="dark"]{${declarations(tokens.dark)}}`;
195
+ return {
196
+ key: source, source, name: 'Tokens', layer: 'Tokens', kind: 'board',
197
+ width: boardWidth, height: null, sourceCount: 1, frameCount: tokens.light.size,
198
+ body, css: `${scopedTokens}\n${boardCss}\n${tokenStyles}\n${motionBoardCss}`,
199
+ };
200
+ }
@@ -5,7 +5,7 @@ import { AsyncLocalStorage } from 'node:async_hooks';
5
5
  /** @typedef {{argv: string[], reason: string}} NextAction */
6
6
  /** @typedef {{code: string, message: string, next: NextAction[]}} Diagnostic */
7
7
  /** @typedef {keyof typeof errorCatalog} ErrorCode */
8
- /** @typedef {{schemaVersion: 1, command: string, ok: boolean, data: unknown, warnings: Diagnostic[], error: Diagnostic | null}} Envelope */
8
+ /** @typedef {{schemaVersion: 2, command: string, ok: boolean, data: unknown, warnings: Diagnostic[], error: Diagnostic | null}} Envelope */
9
9
  /** @typedef {{command?: string, project?: string, stateDirectory?: string, gitCause?: 'repository' | 'revision' | 'read', inspectCatalog?: boolean, inspectSources?: string[], positionals?: string[], values?: Record<string, string | string[] | boolean>, failureCode?: ErrorCode}} ErrorContext */
10
10
  /** @typedef {{json: boolean, command: string, revealKey?: boolean, stdout?: (text: string) => void, stderr?: (text: string) => void}} OutputOptions */
11
11
 
@@ -56,9 +56,10 @@ export const errorCatalog = {
56
56
  COMPARE_ADAPTER_FAILED: [2, 'compare', 'Retry after repairing the adapter callback.'],
57
57
  COMPARE_UNSETTLED: [2, 'compare', 'Retry after stabilizing fixture readiness.'],
58
58
  STATE_INVALID: [2, 'help', 'Inspect the reported state file before retrying.'],
59
+ COMMENT_NOT_FOUND: [2, 'comments', 'List open threads to choose an existing comment.'],
60
+ COMMENT_FORBIDDEN: [2, 'comments', 'Read the comment thread to check who authored the message.'],
59
61
  HUB_KEY_INVALID: [2, 'rotate', 'Replace the invalid key; existing access will expire.'],
60
62
  SERVICE_UNSUPPORTED: [2, 'serve-help', 'Use a foreground hub on this platform.'],
61
- SERVICE_ALREADY_INSTALLED: [2, 'status', 'Inspect the existing installation.'],
62
63
  SERVICE_FAILED: [2, 'logs', 'Inspect service diagnostics before retrying.'],
63
64
  WATCH_FAILED: [2, 'check', 'Inspect project inputs before reopening the viewer.'],
64
65
  SHUTDOWN_FAILED: [2, 'help', 'Inspect the reported resource before retrying.'],
@@ -66,6 +67,7 @@ export const errorCatalog = {
66
67
  NETWORK_FAILED: [2, 'compare', 'Retry after restoring fixture connectivity.'],
67
68
  AUTH_REQUIRED: [2, 'compare', 'Retry after providing fixture access.'],
68
69
  IO_FAILED: [2, 'help', 'Repair access to the reported path before retrying.'],
70
+ MOTION_EDGE_NOT_FOUND: [2, 'motion-check', 'List motion edges with adg check --transitions --read-only --json.'],
69
71
  INTERNAL_ERROR: [2, 'version', 'Record the runtime version with the diagnostic.'],
70
72
  };
71
73
 
@@ -83,7 +85,8 @@ export class CliError extends Error {
83
85
  }
84
86
 
85
87
  const canonicalCommands = new Set([
86
- 'annotations', 'open', 'link', 'serve', 'root', 'service', 'migrate', 'init', 'check', 'render', 'compare', 'diff', 'owner', 'impact', 'inspect',
88
+ 'comments', 'open', 'link', 'serve', 'root', 'service', 'migrate', 'init', 'check', 'render', 'compare', 'diff', 'owner', 'impact', 'inspect', 'motion',
89
+ 'comments list', 'comments read', 'comments reply', 'comments resolve',
87
90
  'root add', 'root remove', 'root list', 'root scan',
88
91
  'service install', 'service uninstall', 'service status', 'service logs', 'service migrate',
89
92
  'help', 'version', 'adg',
@@ -115,6 +118,7 @@ export function nextActions(code, context = {}) {
115
118
  const state = context.stateDirectory ? ['--state-dir', context.stateDirectory] : [];
116
119
  let argv;
117
120
  switch (recovery) {
121
+ case 'motion-check': argv = ['adg','check','--transitions','--read-only','--json']; break;
118
122
  case 'check': argv = ['adg', 'check', '--read-only', '--json', ...(context.positionals?.length && context.command === 'check' ? ['--', ...context.positionals] : [])]; break;
119
123
  case 'install': argv = ['npm', 'install', '-g', '@whzxc/agent-design-gallery']; break;
120
124
  case 'migrate': argv = context.project ? ['adg', 'migrate', context.project, '--json'] : helpArgv('migrate'); break;
@@ -167,6 +171,7 @@ export function nextActions(code, context = {}) {
167
171
  }
168
172
  case 'serve-help': argv = helpArgv('serve'); break;
169
173
  case 'roots': argv = ['adg', 'root', 'list', ...state, '--json']; break;
174
+ case 'comments': argv = ['adg', 'comments', ...state, '--json']; break;
170
175
  case 'rotate': argv = ['adg', 'serve', '--rotate-key', ...state, '--json']; break;
171
176
  case 'status': argv = ['adg', 'service', 'status', ...state, '--json']; break;
172
177
  case 'logs': argv = ['adg', 'service', 'logs', ...state, '--json']; break;
@@ -308,11 +313,11 @@ export function createOutput({ json, command, revealKey = false, stdout = text =
308
313
  /** @param {string} text */
309
314
  progress: text => stderr(`${sanitize(text)}\n`),
310
315
  /** @param {unknown} data @param {Diagnostic[]} [warnings] */
311
- success(data, warnings = []) { emit({ schemaVersion: 1, command, ok: true, data: data ?? null, warnings, error: null }); },
316
+ success(data, warnings = []) { emit({ schemaVersion: 2, command, ok: true, data: data ?? null, warnings, error: null }); },
312
317
  /** @param {unknown} cause @param {ErrorContext} [context] */
313
318
  failure(cause, context = {}) {
314
319
  const failure = classifyError(cause, { ...context, command });
315
- if (json) emit({ schemaVersion: 1, command, ok: false, data: failure.data, warnings: failure.warnings, error: failure.error });
320
+ if (json) emit({ schemaVersion: 2, command, ok: false, data: failure.data, warnings: failure.warnings, error: failure.error });
316
321
  else if (!(cause instanceof CliError && cause.humanReported)) stderr(`adg: ${failure.error.message}\n`);
317
322
  return failure.exitCode;
318
323
  },
package/src/cli.mjs CHANGED
@@ -6,34 +6,38 @@ import { realpathSync } from 'node:fs';
6
6
  import { VERSION, loadConfig } from './toolkit/config.mjs';
7
7
  import { CliError, createOutput, withHumanOutput } from './cli-output.mjs';
8
8
 
9
- export const commands = ['annotations', 'open', 'link', 'serve', 'root', 'service', 'migrate', 'init', 'check', 'render', 'compare', 'diff', 'owner', 'impact', 'inspect'];
9
+ export const commands = ['comments', 'open', 'link', 'serve', 'root', 'service', 'migrate', 'init', 'check', 'render', 'compare', 'diff', 'review', 'owner', 'impact', 'inspect', 'motion'];
10
10
  const targetOptions = '[--asset=<path> [--frame=<name>] | --group=<name> | --layer=<name> | --tokens] [--mode=query|path] [--base=<rev>]';
11
11
  const usage = {
12
- annotations: '[list [--status=open|addressed|resolved|all] | read <id> | reply <id> --message=<text> | address <id> --message=<text> | resolve <id> | reopen <id>] [--state-dir=<path>] [--json]',
12
+ comments: '[[list] [--status=open|resolved|all] [--source=<path>] [--frame=<name>] | read <n> | reply <n> --author=<name> --message=<text> | resolve <n> --author=<name> [--message=<text>]] [--state-dir=<path>] [--json]',
13
13
  open: `[directory] [--port=<n>] [--no-open] [--state-dir=<path>] ${targetOptions}`,
14
- link: `<viewer-url> ${targetOptions}`,
14
+ link: `<viewer-url> [--comment=<n> | ${targetOptions}]`,
15
15
  serve: '[--port=4310] [--state-dir=<path>] [--print-key | --rotate-key]',
16
- service: 'install|uninstall|status|logs|migrate [--state-dir=<path>] [--port=4310]',
16
+ service: 'install|uninstall|status|logs|migrate [--state-dir=<path>] [--port=4310] [--public-origin=<origin>]',
17
17
  root: 'add <dir> [--depth=2] | remove <dir> | list | scan [dir] [--state-dir=<path>]',
18
- migrate: '[project]', init: '', check: '[source...] [--read-only] [--impacted --base=<rev> [--frame=<name>] [--theme=both|light|dark] [--state-dir=<path>] [--explain]]', render: '[source...] [--frame=<name>] [--theme=both|light|dark] [--scale=2] [--out-dir=<path>] [--json] [--base=<rev>] [--impacted [--state-dir=<path>] [--explain]]',
19
- compare: '<source> --frame=<name> [--fixture=<name>] [--region=<name> | --selector=<css> | --page] [--origin="<x> <y>"] [--click=<name>...] [--viewport=<w>x<h>] | --all',
20
- diff: '[source...] --base=<rev> [--frame=<name>] [--theme=both|light|dark] [--scale=2] [--out-dir=<path>] [--json] [--impacted [--state-dir=<path>] [--explain]]',
21
- owner: '(--file=<path|directory|glob> [--line=<n>] [--symbol=<name>] | --text=<text> [--contains] [--locale=<tag>] | --color=<css> | --token=<name> | --part=<source>[#<Export>]) [--theme=both|light|dark] [--state-dir=<path>] [--json]',
22
- inspect: '[source] [--frame=<name>] [--theme=both|light|dark] [--part=<source>#<Export> | --element=<id> | --text=<text> [--contains]] [--depth=<n|all>] [--fields=<groups>] [--wrappers=semantic|all] [--expand] [--state-dir=<path>] [--json]',
23
- impact: '(--source=<path>... [--part=<name>] | --token=<name>... | --file=<path|directory|glob> [--line=<n>] [--symbol=<name>] | --base=<rev> [--head=<rev>]) [--theme=both|light|dark] [--explain] [--state-dir=<path>] [--json]',
18
+ motion: '[--css | --json]',
19
+ migrate: '[project]', init: '', check: '[source...] [--transitions] [--read-only] [--motion-only] [--motion-details] [--impacted --base=<rev> [--frame=<name>] [--theme=both|light|dark] [--state-dir=<path>] [--explain]]', render: '[source...] [--frame=<name>] [--theme=both|light|dark|system] [--scale=2] [--out-dir=<path>] [--json] [--base=<rev>] [--impacted [--state-dir=<path>] [--explain]]',
20
+ compare: '<source> --frame=<name> [--fixture=<name>] [--region=<name> | --selector=<css> | --page] [--origin="<x> <y>"] [--click=<name>...] [--viewport=<w>x<h>] [--no-screenshots] | --all',
21
+ diff: '[source...] --base=<rev> [--frame=<name>] [--theme=both|light|dark|system] [--scale=2] [--out-dir=<path>] [--json] [--impacted [--state-dir=<path>] [--explain]]',
22
+ review: '--base=<rev> [--format=html|png|embed] [--theme=system|light|dark] [--out=<file>] [--viewer-url=<project-url>] [--exact] [--json]',
23
+ owner: '[--transitions] (--transition=<id> | --file=<path|directory|glob> [--line=<n>] [--symbol=<name>] | --text=<text> [--contains] [--locale=<tag>] | --color=<css> | --token=<name> | --part=<source>[#<Export>]) [--theme=both|light|dark] [--state-dir=<path>] [--json]',
24
+ inspect: '[--transition=<id> [--explain] | <source> --frame=<name> --transitions] [source] [--frame=<name>] [--theme=both|light|dark] [--part=<source>#<Export> | --element=<id> | --text=<text> [--contains]] [--depth=<n|all>] [--fields=<groups>] [--wrappers=semantic|all] [--expand] [--state-dir=<path>] [--json]',
25
+ impact: '[--transitions] (--source=<path>... [--part=<name>] | --token=<name>... | --file=<path|directory|glob> [--line=<n>] [--symbol=<name>] | --base=<rev> [--head=<rev>]) [--theme=both|light|dark] [--explain] [--state-dir=<path>] [--json]',
24
26
  };
25
27
  const details = {
26
- annotations: 'List, read, reply to, address, resolve or reopen project annotations stored outside the repository. Run from the project directory.',
28
+ motion: 'Export project motion tokens and raw spring parameters. --css emits a token stylesheet with generated linear() springs.',
29
+ comments: 'List open project comment threads by default, or read, reply to or resolve a thread by number, #number or ID. Run from the project directory.',
27
30
  migrate: 'Rename a project configuration and runtime imports, update editor paths and ignore entries, remove old generated files and regenerate declarations. Refuses mixed config names; safe to run again.',
28
31
  serve: 'Run the resident multi-project hub on 127.0.0.1. Projects build on viewer access and idle viewers stop after five minutes. --print-key prints the key and exits; --rotate-key rotates the running hub key and exits. Forwarded data requests require a header or query key; direct-local requests are exempt.',
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.',
32
+ service: 'Manage the macOS resident hub LaunchAgent. install creates or updates it with RunAtLoad and KeepAlive, recording absolute Node/CLI paths. --port and --public-origin apply only to install. Set --public-origin to an HTTP(S) origin for public comment links. Reinstalling keeps the port, state directory and public origin unless specified. 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
33
  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
34
  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. --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
- 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.',
35
+ link: 'Print a clean ADG preview URL. --comment=<n> opens a comment thread. --base=<rev> enables Git overlays for architecture diagrams. Query mode isolates a target. Path mode locates it in the design hierarchy.',
36
+ 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×. --theme=system resolves the current macOS appearance, otherwise light, and reports the resolved themes. --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
37
  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, 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
- 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.',
38
+ 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 also writes review-sheet.png with up to 12 image cards at 2× plus lists of removed and moved frames. The sheet uses the explicit single theme or system appearance. --theme=system resolves the current macOS appearance, otherwise light. --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.',
39
+ review: 'Generate one review of the Git base and working tree. Defaults to interactive HTML, the system theme and <configured output>/review.html. Use --format=embed for a compact inline review widget at <configured output>/review-embed.html, or --format=png for a static summary at <configured output>/review.png. --out must match the selected format. Uses structural prefiltering with pixel comparison for the remaining frames. --exact uses pixel comparison for every frame scheduled by impact analysis. A registered hub supplies HTML frame links, or set --viewer-url. Exit 0 when written, including changes, or 2 for incomplete generation.',
40
+ 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 tags 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
41
  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
42
  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.',
39
43
  };
@@ -42,6 +46,7 @@ const helpExamples = {
42
46
  render: 'adg render --impacted --base=HEAD --json\nadg render arch/catalog.mmd --base=HEAD --json',
43
47
  check: 'adg check --impacted --base=HEAD --read-only --json\nadg check --read-only --json',
44
48
  diff: 'adg diff --base=HEAD --impacted --json',
49
+ review: 'adg review --base=HEAD --json\nadg review --base=HEAD --format=embed --json\nadg review --base=HEAD --format=png --json',
45
50
  };
46
51
  export function help(command) {
47
52
  if (command) return `Usage: adg ${command} ${usage[command]}\n\n${details[command]}${helpExamples[command] ? `\n\nExamples:\n${helpExamples[command]}` : ''}\n\n-h, --help Show help\nExit codes: 0 success, 1 check/compare/diff problems, 2 usage/configuration/environment error.`;
@@ -53,14 +58,22 @@ export function parseCli(args) {
53
58
  const explicit = commands.includes(args[0]), command = explicit ? args[0] : 'open';
54
59
  const options = { help: { type: 'boolean', short: 'h' }, version: { type: 'boolean', short: 'v' }, json: { type: 'boolean' } };
55
60
  const locators = ['asset', 'frame', 'group', 'layer', 'mode', 'base'];
56
- const strings = { annotations: ['status', 'message', 'state-dir'], open: ['port', 'state-dir', ...locators], link: locators, serve: ['port', 'state-dir'], root: ['depth', 'state-dir'], service: ['port', 'state-dir'], check: ['base', 'frame', 'theme', 'state-dir'], render: ['scale', 'frame', 'theme', 'out-dir', 'base', 'state-dir'], diff: ['base', 'frame', 'theme', 'scale', 'out-dir', 'state-dir'], compare: ['frame', 'fixture', 'region', 'selector', 'viewport', 'origin'], owner: ['file', 'text', 'color', 'token', 'part', 'line', 'symbol', 'locale', 'theme', 'state-dir'], impact: ['source', 'part', 'token', 'file', 'line', 'symbol', 'base', 'head', 'theme', 'state-dir'], inspect: ['frame','theme','part','element','text','depth','fields','wrappers','state-dir'] };
61
+ const strings = { comments: ['status', 'source', 'frame', 'author', 'message', 'state-dir'], open: ['port', 'state-dir', ...locators], link: [...locators, 'comment'], serve: ['port', 'state-dir'], root: ['depth', 'state-dir'], service: ['port', 'state-dir', 'public-origin'], check: ['base', 'frame', 'theme', 'state-dir'], render: ['scale', 'frame', 'theme', 'out-dir', 'base', 'state-dir'], diff: ['base', 'frame', 'theme', 'scale', 'out-dir', 'state-dir'], compare: ['frame', 'fixture', 'region', 'selector', 'viewport', 'origin'], owner: ['transition','file', 'text', 'color', 'token', 'part', 'line', 'symbol', 'locale', 'theme', 'state-dir'], impact: ['source', 'part', 'token', 'file', 'line', 'symbol', 'base', 'head', 'theme', 'state-dir'], inspect: ['transition','frame','theme','part','element','text','depth','fields','wrappers','state-dir'] };
57
62
  for (const name of strings[command] ?? []) options[name] = { type: 'string' };
63
+ if (command === 'review') {
64
+ for (const name of ['base', 'format', 'theme', 'out', 'viewer-url']) options[name] = { type: 'string' };
65
+ options.exact = { type: 'boolean' };
66
+ }
58
67
  if (command === 'serve') for (const name of ['print-key', 'rotate-key']) options[name] = { type: 'boolean' };
59
68
  if (command === 'open') options['no-open'] = { type: 'boolean' };
60
69
  if (command === 'open' || command === 'link') options.tokens = { type: 'boolean' };
61
- if (command === 'check') options['read-only'] = { type: 'boolean' };
70
+ if (command === 'check') for (const name of ['read-only','motion-only','motion-details']) options[name] = { type: 'boolean' };
71
+ if (command === 'compare') options['no-screenshots'] = { type: 'boolean' };
72
+ if (command === 'motion') options.css = { type: 'boolean' };
62
73
  if (['render', 'check', 'diff'].includes(command)) { options.impacted = { type: 'boolean' }; options.explain = { type: 'boolean' }; }
63
74
  if (command === 'owner' || command === 'inspect') options.contains = { type: 'boolean' };
75
+ if (['inspect','owner','impact','check'].includes(command)) options.transitions = {type:'boolean'};
76
+ if (command === 'inspect') options.explain = {type:'boolean'};
64
77
  if (command === 'inspect') options.expand = { type: 'boolean' };
65
78
  if (command === 'impact') {
66
79
  options.explain = { type: 'boolean' };
@@ -74,6 +87,20 @@ const strings = { annotations: ['status', 'message', 'state-dir'], open: ['port'
74
87
  const { values, positionals } = parsed;
75
88
  if (globalJson) values.json = true;
76
89
  if (!values.help && !values.version) {
90
+ if (command === 'motion' && (positionals.length || values.css && values.json)) throw new CliError('USAGE_INVALID', 'Choose --css or --json.');
91
+ if (command === 'check' && ((values['motion-only'] && (positionals.length || values.impacted || values.transitions)) ||
92
+ (values['motion-details'] && (positionals.length || values.impacted))))
93
+ throw new CliError('USAGE_INVALID', 'Motion inventory flags apply to a whole-project check.');
94
+ if (command === 'review') {
95
+ const format = values.format ?? 'html';
96
+ const extension = format === 'png' ? '.png' : '.html';
97
+ if (positionals.length || !values.base?.trim() ||
98
+ !['html', 'png', 'embed'].includes(format) ||
99
+ (values.theme !== undefined && !['system', 'light', 'dark'].includes(values.theme)) ||
100
+ (values.out !== undefined && !values.out.toLowerCase().endsWith(extension)) || values['viewer-url'] === '') {
101
+ throw new CliError('USAGE_INVALID', 'Set --base=<rev>, choose one theme and format, and match --out to the format; run adg review --help.');
102
+ }
103
+ }
77
104
  if (['render', 'check', 'diff'].includes(command)) {
78
105
  if (!values.impacted && (values.explain !== undefined || values['state-dir'] !== undefined)) throw new CliError('USAGE_INVALID', '--explain and --state-dir require --impacted --base=<rev>.');
79
106
  if (values.impacted && (typeof values.base !== 'string' || !values.base.trim())) throw new CliError('USAGE_INVALID', '--impacted requires --base=<rev>.');
@@ -84,6 +111,9 @@ const strings = { annotations: ['status', 'message', 'state-dir'], open: ['port'
84
111
  for(const token of parsed.tokens)if(token.kind==='option'&&!['json','help','version'].includes(token.name)){
85
112
  if(seen.has(token.name))throw new CliError('USAGE_INVALID',`Do not repeat --${token.name}; run adg inspect --help.`);seen.add(token.name);
86
113
  }
114
+ if ((values.transition!==undefined && (positionals.length || Object.keys(values).some(k=>!['transition','json','theme','explain','state-dir'].includes(k)))) ||
115
+ (values.explain && !values.transition) || (values.transitions && (!values.frame || positionals.length!==1 || Object.keys(values).some(k=>!['frame','transitions','state-dir','json'].includes(k)))))
116
+ throw new CliError('USAGE_INVALID','Choose --transition=<id> or <source> --frame=<name> --transitions.');
87
117
  if(positionals.length>1 || strings.inspect.some(k=>values[k]!==undefined&&!values[k].trim()) ||
88
118
  ['part','element','text'].filter(k=>values[k]!==undefined).length>1 || values.contains!==undefined&&values.text===undefined ||
89
119
  values.theme!==undefined&&!['both','light','dark'].includes(values.theme) ||
@@ -105,12 +135,13 @@ const strings = { annotations: ['status', 'message', 'state-dir'], open: ['port'
105
135
  values.line !== undefined && (!/^[1-9]\d*$/.test(values.line) || !Number.isSafeInteger(Number(values.line)))) throw new CliError('USAGE_INVALID', 'Choose one nonempty impact selector family and compatible options; run adg impact --help.');
106
136
  }
107
137
  if (command === 'owner') {
108
- const kinds = ['file', 'text', 'color', 'token', 'part'].filter(key => values[key] !== undefined);
138
+ const kinds = ['file', 'text', 'color', 'token', 'part','transition'].filter(key => values[key] !== undefined);
109
139
  const seen = new Set();
110
140
  for (const token of parsed.tokens) if (token.kind === 'option' && !['json', 'help', 'version'].includes(token.name)) {
111
141
  if (seen.has(token.name)) throw new CliError('USAGE_INVALID', `Do not repeat --${token.name}; run adg owner --help.`);
112
142
  seen.add(token.name);
113
143
  }
144
+ if (values.transitions && !['token','file'].includes(kinds[0])) throw new CliError('USAGE_INVALID','Use --transitions with --file or --token.');
114
145
  if (positionals.length || kinds.length !== 1 || strings.owner.some(key => values[key] !== undefined && !values[key].trim()) ||
115
146
  values.theme !== undefined && !['both', 'light', 'dark'].includes(values.theme) ||
116
147
  (values.line !== undefined || values.symbol !== undefined) && kinds[0] !== 'file' ||
@@ -121,19 +152,22 @@ const strings = { annotations: ['status', 'message', 'state-dir'], open: ['port'
121
152
  if (command === 'diff' && (typeof values.base !== 'string' || !values.base.trim())) throw new CliError('USAGE_INVALID', 'Set --base to a Git revision; run adg diff --help.');
122
153
  if ((command === 'init' && positionals.length) || (['open', 'migrate'].includes(command) && positionals.length > 1) || (command === 'compare' && (values.all ? positionals.length || values.frame : positionals.length !== 1 || !values.frame))) throw new CliError('USAGE_INVALID', `Invalid arguments; run adg ${command} --help`);
123
154
  if (command === 'link' && positionals.length !== 1) throw new CliError('USAGE_INVALID', 'Expected one viewer URL. Run adg link --help.');
124
- if (command === 'service' && (positionals.length !== 1 || !serviceActions.includes(positionals[0]) || (values.port !== undefined && positionals[0] !== 'install'))) throw new CliError('USAGE_INVALID', 'Invalid arguments; run adg service --help');
155
+ if (command === 'service' && (positionals.length !== 1 || !serviceActions.includes(positionals[0]) || (['port', 'public-origin'].some(name => values[name] !== undefined) && positionals[0] !== 'install'))) throw new CliError('USAGE_INVALID', 'Invalid arguments; run adg service --help');
125
156
  if (command === 'root') {
126
157
  const [action, directory, ...extra] = positionals;
127
158
  if (extra.length || !rootActions.includes(action) || (['add', 'remove'].includes(action) && !directory) || (action === 'list' && directory) || (values.depth !== undefined && action !== 'add')) throw new CliError('USAGE_INVALID', 'Invalid arguments; run adg root --help');
128
159
  }
129
- if (command === 'annotations') {
160
+ if (command === 'comments') {
130
161
  const [action = 'list', id, ...extra] = positionals;
131
- if (!['list', 'read', 'reply', 'address', 'resolve', 'reopen'].includes(action) || extra.length ||
132
- (action === 'list' ? id !== undefined || values.message !== undefined : !id || values.status !== undefined) ||
133
- (values.status !== undefined && !['open', 'addressed', 'resolved', 'all'].includes(values.status)) ||
134
- (['reply', 'address'].includes(action) ? typeof values.message !== 'string' || !values.message.trim() : values.message !== undefined) ||
135
- (values['state-dir'] !== undefined && !values['state-dir'].trim())) {
136
- throw new CliError('USAGE_INVALID', 'Use annotations list, read <id>, reply <id> --message=<text>, address <id> --message=<text>, resolve <id> or reopen <id>; run adg annotations --help.');
162
+ const write = action === 'reply' || action === 'resolve';
163
+ const hasFilter = ['status', 'source', 'frame'].some(key => values[key] !== undefined);
164
+ if (!commentActions.includes(action) || extra.length ||
165
+ (action === 'list' ? id !== undefined : !id?.trim() || hasFilter) ||
166
+ (write ? values.author === undefined : values.author !== undefined || values.message !== undefined) ||
167
+ (action === 'reply' && values.message === undefined) ||
168
+ strings.comments.some(key => values[key] !== undefined && !values[key].trim()) ||
169
+ (values.status !== undefined && !['open', 'resolved', 'all'].includes(values.status))) {
170
+ throw new CliError('USAGE_INVALID', 'Choose a comment action and its options. Run adg comments --help.');
137
171
  }
138
172
  }
139
173
  if (command === 'serve' && positionals.length) throw new CliError('USAGE_INVALID', 'Invalid arguments; run adg serve --help');
@@ -145,10 +179,12 @@ const strings = { annotations: ['status', 'message', 'state-dir'], open: ['port'
145
179
  }
146
180
  const rootActions = ['add', 'remove', 'list', 'scan'];
147
181
  const serviceActions = ['install', 'uninstall', 'status', 'logs', 'migrate'];
182
+ const commentActions = ['list', 'read', 'reply', 'resolve'];
148
183
 
149
- export function commandIdentity({ command, positionals = [] }) {
150
- const actions = command === 'root' ? rootActions : command === 'service' ? serviceActions : [];
151
- return actions.includes(positionals[0]) ? `${command} ${positionals[0]}` : command;
184
+ export function commandIdentity({ command, positionals = [], values }) {
185
+ const actions = command === 'root' ? rootActions : command === 'service' ? serviceActions : command === 'comments' ? commentActions : [];
186
+ const action = positionals[0] ?? (command === 'comments' && !values?.help ? 'list' : undefined);
187
+ return actions.includes(action) ? `${command} ${action}` : command;
152
188
  }
153
189
 
154
190
  export function jsonRequested(args) {
@@ -195,13 +231,30 @@ async function dispatch({ command, values, positionals }, cwd, output, serviceOp
195
231
  return {data:values['print-key'] ? {action:'print-key',stateDirectory,key} : {action:'rotate-key',stateDirectory,rotated:true}};
196
232
  }
197
233
  const config = await loadConfig(cwd);
198
- if (command === 'annotations') {
234
+ if (command === 'comments') {
199
235
  const [action = 'list', id] = positionals;
200
236
  const stateDir = values['state-dir'] ? path.resolve(cwd, values['state-dir']) : undefined;
201
- const mod = await import('./annotations.mjs');
202
- const data = action === 'read'
203
- ? await mod.readAnnotationContext(config, stateDir, id)
204
- : await mod.annotations(config.root, stateDir, action, { id, status: values.status ?? 'open', message: values.message, author: 'agent' });
237
+ const { changeComment, listComments, readCommentContext } = await import('./comments.mjs');
238
+ const data = action === 'list'
239
+ ? await listComments(config.root, stateDir, { status: values.status ?? 'open', source: values.source, frame: values.frame })
240
+ : action === 'read'
241
+ ? await readCommentContext(config, stateDir, id)
242
+ : await changeComment(config.root, stateDir, { action, id, message: values.message }, { author: values.author });
243
+ if (!values.json) output.log(JSON.stringify(data, null, 2));
244
+ return { data };
245
+ }
246
+ if (command === 'motion') {
247
+ const { loadMotionPatterns, patternParameters } = await import('./toolkit/motion-patterns.mjs');
248
+ const { motionTokenCss } = await import('./toolkit/motion-primitives.mjs');
249
+ const { tokens, springs, patterns } = loadMotionPatterns(config);
250
+ if (values.css) {
251
+ output.log(motionTokenCss(tokens).trimEnd());
252
+ return { data: null };
253
+ }
254
+ const used = new Set([...patterns.values()].flatMap(pattern => ['enter', 'exit'].flatMap(direction => Object.values(patternParameters(pattern, direction)))));
255
+ const names = Object.fromEntries([...tokens.light].filter(([name]) => used.has(name) || /^--(?:adg-motion|motion)-/.test(name)).map(([name, value]) =>
256
+ [name, { light: value, ...(tokens.dark.has(name) ? { dark: tokens.dark.get(name) } : {}) }]));
257
+ const data = { tokens: names, springs };
205
258
  if (!values.json) output.log(JSON.stringify(data, null, 2));
206
259
  return { data };
207
260
  }
@@ -211,6 +264,7 @@ async function dispatch({ command, values, positionals }, cwd, output, serviceOp
211
264
  if (command === 'init') return { data: (await import('./toolkit/project.mjs')).init(config, output.log) };
212
265
  if (command === 'compare') return (await import('./toolkit/compare.mjs')).compare(config, positionals, values, {log:output.log});
213
266
  if (command === 'diff') return (await import('./toolkit/diff.mjs')).diff(config, positionals, values, { log: output.log });
267
+ if (command === 'review') return (await import('./toolkit/review.mjs')).review(config, values, { log: output.log });
214
268
  const toolkit = await import('./toolkit/commands.mjs');
215
269
  return command === 'check' ? toolkit.check(config, positionals, values, output.log, output.progress) : toolkit.render(config, positionals, values, output.log);
216
270
  }