@whzxc/agent-design-gallery 0.9.0 → 0.13.1

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 (61) hide show
  1. package/README.md +19 -3
  2. package/package.json +4 -1
  3. package/public/annotations.js +816 -0
  4. package/public/app.js +245 -12
  5. package/public/assets.js +4 -13
  6. package/public/frame-identity.js +223 -0
  7. package/public/icons.js +1 -0
  8. package/public/index.html +3 -0
  9. package/public/selection.js +1 -1
  10. package/public/style.css +72 -2
  11. package/src/annotations.mjs +238 -0
  12. package/src/cli-output.mjs +49 -2
  13. package/src/cli.mjs +83 -12
  14. package/src/http.mjs +2 -1
  15. package/src/hub/instances.mjs +1 -1
  16. package/src/hub/registry.mjs +1 -1
  17. package/src/hub.mjs +2 -2
  18. package/src/server.mjs +59 -11
  19. package/src/service.mjs +1 -1
  20. package/src/toolkit/arch-git.mjs +19 -0
  21. package/src/toolkit/arch-overlay.mjs +1 -1
  22. package/src/toolkit/asset-rules.mjs +42 -3
  23. package/src/toolkit/build-store.mjs +5 -3
  24. package/src/toolkit/build-worker.mjs +5 -2
  25. package/src/toolkit/build.mjs +36 -14
  26. package/src/toolkit/commands.mjs +85 -22
  27. package/src/toolkit/config.mjs +8 -6
  28. package/src/toolkit/diff-inputs.mjs +5 -5
  29. package/src/toolkit/diff.mjs +18 -11
  30. package/src/toolkit/document.mjs +6 -6
  31. package/src/toolkit/frame-document.mjs +6 -0
  32. package/src/toolkit/frame-facets.mjs +167 -0
  33. package/src/toolkit/frame-identity.mjs +100 -0
  34. package/src/toolkit/frame-observation.mjs +147 -0
  35. package/src/toolkit/frame-primitives.mjs +85 -0
  36. package/src/toolkit/html.mjs +1 -0
  37. package/src/toolkit/impact-eligibility.mjs +136 -0
  38. package/src/toolkit/impact-inputs.mjs +52 -0
  39. package/src/toolkit/impact-output.mjs +46 -0
  40. package/src/toolkit/impact-proof.mjs +67 -0
  41. package/src/toolkit/impact-selection.mjs +96 -0
  42. package/src/toolkit/impact.mjs +382 -0
  43. package/src/toolkit/implementation-query.mjs +53 -0
  44. package/src/toolkit/input-generation.mjs +51 -0
  45. package/src/toolkit/inspect-encoding.mjs +459 -0
  46. package/src/toolkit/inspect-observation.mjs +56 -0
  47. package/src/toolkit/inspect-output.mjs +169 -0
  48. package/src/toolkit/inspect-styles.mjs +34 -0
  49. package/src/toolkit/inspect.d.ts +118 -0
  50. package/src/toolkit/inspect.mjs +125 -0
  51. package/src/toolkit/owner-observation.mjs +23 -189
  52. package/src/toolkit/owner-search.mjs +2 -2
  53. package/src/toolkit/owner.mjs +37 -45
  54. package/src/toolkit/part-diff.mjs +2 -0
  55. package/src/toolkit/part-snapshot.mjs +15 -23
  56. package/src/toolkit/project-index.mjs +100 -22
  57. package/src/toolkit/project.mjs +52 -6
  58. package/src/toolkit/results.mjs +2 -2
  59. package/src/toolkit/runtime.d.ts +7 -5
  60. package/src/toolkit/runtime.mjs +20 -7
  61. package/src/toolkit/token-reachability.mjs +71 -0
@@ -16,5 +16,5 @@ export function hitSelection(assets, x, y, elements = true) {
16
16
  return null;
17
17
  }
18
18
  export function exportFrames(asset, owner) {
19
- return (asset?.parts ?? []).filter(part => part.elements?.some(element => element.owners.some(o => o.source === owner.source && o.export === owner.export)));
19
+ return (asset?.parts ?? []).filter(part => part.elements?.some(element => (element.owners ?? []).some(o => o.source === owner.source && o.export === owner.export)));
20
20
  }
package/public/style.css CHANGED
@@ -1,5 +1,5 @@
1
- :root { color-scheme:light; font:var(--text-body)/1.2 var(--font-ui); color:var(--text); background:var(--canvas); }
2
- :root[data-theme="dark"] { color-scheme:dark; }
1
+ :root { color-scheme:light; font:var(--text-body)/1.2 var(--font-ui); color:var(--text); background:var(--canvas); --note-open:#2f6fed; --note-addressed:#1d8356; --note-stale:#b36a14; }
2
+ :root[data-theme="dark"] { color-scheme:dark; --note-open:#5b93ff; --note-addressed:#3fb984; --note-stale:#e5a247; }
3
3
  * { box-sizing:border-box; }
4
4
  html,body,.gallery { margin:0; width:100%; height:100%; overflow:hidden; }
5
5
  button,input { font:inherit; color:inherit; }
@@ -192,3 +192,73 @@ kbd { display:inline-flex; align-items:center; height:22px; padding:0 7px; borde
192
192
  #error { position:fixed; bottom:72px; left:50%; transform:translateX(-50%); background:var(--surface); color:var(--danger); border-radius:var(--radius-field); padding:12px; box-shadow:var(--shadow-float); max-width:80vw; }
193
193
  #empty { position:absolute; inset:45% 0 auto; text-align:center; color:var(--text-tertiary); }
194
194
  .sr { position:absolute; width:1px; height:1px; padding:0; margin:-1px; overflow:hidden; clip-path:inset(50%); white-space:nowrap; }
195
+ #context-menu { min-width:220px; max-width:min(288px, calc(100vw - 16px)); z-index:8; }
196
+ #annotations-panel { top:var(--panel-top); right:12px; width:min(320px, calc(100vw - 24px)); max-height:calc(100% - var(--panel-top) - 76px); display:flex; flex-direction:column; overflow:hidden; z-index:1; }
197
+ body:has(#source:not([hidden])) #annotations-panel { right:min(324px, calc(100vw - 332px)); }
198
+ @media (max-width:700px) {
199
+ body:has(#source:not([hidden])) #annotations-panel { right:12px; z-index:3; }
200
+ }
201
+ .annotations-header { display:flex; align-items:center; justify-content:space-between; gap:8px; padding:14px 16px 10px; }
202
+ .annotations-title { display:flex; align-items:center; gap:8px; min-width:0; }
203
+ .annotations-copy-prompt { display:inline-flex; align-items:center; gap:6px; height:28px; padding:0 10px; border-radius:var(--radius-field); background:var(--surface-sunken); font-size:var(--text-meta); font-weight:550; color:var(--text-secondary); }
204
+ .annotations-copy-prompt:hover:not(:disabled) { color:var(--text); }
205
+ .annotations-filters { display:flex; flex-direction:column; gap:6px; padding:0 16px 10px; border-bottom:1px solid var(--border); }
206
+ .annotations-filter-group { display:flex; gap:2px; padding:2px; border-radius:var(--radius-field); background:var(--surface-sunken); }
207
+ .annotations-filter-group button { flex:1; height:24px; padding:0 6px; border-radius:6px; font-size:var(--text-caption); font-weight:550; color:var(--text-secondary); justify-content:center; display:inline-flex; align-items:center; }
208
+ .annotations-filter-group button[aria-pressed="true"] { background:var(--surface); color:var(--text); box-shadow:0 1px 2px rgb(0 0 0 / 8%); }
209
+ .annotation-list { overflow:auto; padding:8px; display:flex; flex-direction:column; gap:4px; min-height:0; }
210
+ .annotation-empty { margin:12px 8px; font-size:var(--text-meta); color:var(--text-secondary); line-height:1.4; }
211
+ .annotation-row-item { display:flex; align-items:stretch; gap:4px; }
212
+ .annotation-row { flex:1; min-width:0; display:flex; flex-direction:column; gap:4px; padding:8px 10px; border-radius:var(--radius-row); text-align:left; white-space:normal; }
213
+ .annotation-row[data-highlighted="true"] { background:var(--surface-sunken); outline:1px solid var(--note-open); outline-offset:-1px; }
214
+ .annotation-row-meta { display:flex; align-items:center; gap:6px; width:100%; min-width:0; font-size:var(--text-caption); color:var(--text-tertiary); }
215
+ .annotation-row-frame { min-width:0; overflow:hidden; text-overflow:ellipsis; white-space:nowrap; color:var(--text-secondary); }
216
+ .annotation-row-replies { margin-left:auto; flex:none; }
217
+ .annotation-row-excerpt { display:-webkit-box; -webkit-line-clamp:2; -webkit-box-orient:vertical; overflow:hidden; font-size:var(--text-meta); line-height:1.35; color:var(--text); overflow-wrap:anywhere; }
218
+ .annotation-row-action { flex:none; align-self:center; height:24px; padding:0 8px; font-size:var(--text-caption); color:var(--text-secondary); background:var(--surface-sunken); }
219
+ .annotation-number { font-family:var(--font-mono); font-size:var(--text-caption); font-weight:650; color:var(--text); flex:none; }
220
+ .annotation-badge { display:inline-flex; align-items:center; height:18px; padding:0 6px; border-radius:999px; font-size:10px; font-weight:600; text-transform:capitalize; flex:none; background:var(--surface-sunken); color:var(--text-secondary); }
221
+ .annotation-badge[data-status="open"] { color:var(--note-open); background:color-mix(in srgb, var(--note-open) 14%, var(--surface)); }
222
+ .annotation-badge[data-status="addressed"] { color:var(--note-addressed); background:color-mix(in srgb, var(--note-addressed) 16%, var(--surface)); }
223
+ .annotation-badge[data-stale="true"] { color:var(--note-stale); background:color-mix(in srgb, var(--note-stale) 16%, var(--surface)); }
224
+ .annotation-layer { position:absolute; inset:0; pointer-events:none; overflow:visible; will-change:transform; }
225
+ .annotation-layer svg { position:absolute; width:100%; height:100%; overflow:visible; }
226
+ .annotation-layer polyline { fill:none; stroke:var(--note-open); stroke-width:1.5; }
227
+ .annotation-layer polyline[data-state="addressed"] { stroke:var(--note-addressed); }
228
+ .annotation-layer polyline[data-stale="true"] { stroke:var(--note-stale); stroke-dasharray:4 3; }
229
+ .annotation-point,.annotation-card,.annotation-frame-badge { position:absolute; pointer-events:auto; }
230
+ .annotation-point { transform:translate(-50%,-50%); display:grid; place-items:center; width:26px; height:26px; border-radius:50%; border:2px solid var(--surface); background:var(--note-open); color:#fff; font-size:var(--text-caption); font-weight:650; box-shadow:var(--shadow-float); }
231
+ .annotation-point:hover { background:var(--note-open); filter:brightness(1.06); }
232
+ .annotation-point[data-state="addressed"] { background:var(--note-addressed); border-radius:8px; }
233
+ .annotation-point[data-stale="true"] { background:var(--surface); color:var(--note-stale); border:2px dashed var(--note-stale); }
234
+ .annotation-point[data-highlighted="true"] { outline:2px solid var(--accent); outline-offset:2px; }
235
+ .annotation-frame-badge { transform:translate(-50%,-50%); display:inline-flex; align-items:center; justify-content:center; min-width:22px; height:22px; padding:0 6px; border-radius:999px; border:2px solid var(--surface); background:var(--note-open); color:#fff; font-size:var(--text-caption); font-weight:650; box-shadow:var(--shadow-float); }
236
+ .annotation-frame-badge[data-status="addressed"] { background:var(--note-addressed); }
237
+ .annotation-frame-badge[data-stale="true"] { border-style:dashed; border-color:var(--note-stale); }
238
+ .annotation-card { width:244px; background:var(--surface); color:var(--text); border:1px solid color-mix(in srgb, var(--note-open) 55%, var(--border)); border-left:3px solid var(--note-open); border-radius:var(--radius-menu); padding:8px 10px; box-shadow:var(--shadow-float); display:flex; flex-direction:column; gap:6px; }
239
+ .annotation-card[data-state="addressed"] { border-color:color-mix(in srgb, var(--note-addressed) 55%, var(--border)); border-left-color:var(--note-addressed); background:color-mix(in srgb, var(--note-addressed) 5%, var(--surface)); }
240
+ .annotation-card[data-stale="true"] { border:1px dashed var(--note-stale); border-left:3px dashed var(--note-stale); }
241
+ .annotation-card[data-highlighted="true"] { outline:2px solid var(--accent); outline-offset:1px; }
242
+ .annotation-card-header { display:flex; align-items:center; gap:5px; min-width:0; }
243
+ .annotation-owner { margin-left:auto; min-width:0; overflow:hidden; text-overflow:ellipsis; white-space:nowrap; font-family:var(--font-mono); font-size:10px; color:var(--text-tertiary); }
244
+ .annotation-card .annotation-note { display:block; width:100%; padding:2px 4px; margin:0 -4px; border-radius:6px; text-align:left; white-space:pre-wrap; overflow:auto; max-height:64px; font-size:var(--text-body); line-height:1.35; overflow-wrap:anywhere; }
245
+ .annotation-thread { display:flex; flex-direction:column; gap:4px; padding-top:4px; border-top:1px solid var(--border); max-height:96px; overflow:auto; }
246
+ .annotation-reply { font-size:var(--text-meta); line-height:1.35; padding:4px 6px; border-radius:6px; background:var(--surface-sunken); }
247
+ .annotation-reply[data-author="agent"] { border-left:2px solid var(--note-addressed); }
248
+ .annotation-reply-author { display:block; font-size:10px; font-weight:600; color:var(--text-tertiary); margin-bottom:1px; }
249
+ .annotation-reply-body { white-space:pre-wrap; overflow-wrap:anywhere; color:var(--text); }
250
+ .annotation-actions { display:flex; flex-wrap:wrap; gap:2px; padding-top:2px; }
251
+ .annotation-actions button { height:22px; padding:0 6px; font-size:var(--text-caption); color:var(--text-secondary); border-radius:6px; }
252
+ .annotation-actions button:hover { color:var(--text); background:var(--surface-sunken); }
253
+ .annotation-editor { width:400px; padding:18px; border-radius:var(--radius-dialog); border:1px solid var(--border); background:var(--surface); color:var(--text); box-shadow:var(--shadow-menu); }
254
+ .annotation-editor-meta { margin-top:4px; font:var(--text-caption)/1.3 var(--font-mono); color:var(--text-tertiary); overflow:hidden; text-overflow:ellipsis; white-space:nowrap; }
255
+ .annotation-editor textarea { margin-top:12px; width:100%; min-height:88px; resize:vertical; padding:8px 10px; border:1px solid var(--border); border-radius:var(--radius-field); background:var(--surface-sunken); color:var(--text); font:var(--text-body)/1.4 var(--font-ui); outline:none; }
256
+ .annotation-editor textarea:focus-visible { border-color:var(--accent); }
257
+ .annotation-editor-footer { margin-top:12px; display:flex; align-items:center; justify-content:space-between; gap:8px; }
258
+ .annotation-editor-hint { font-size:var(--text-caption); color:var(--text-tertiary); }
259
+ .annotation-editor-buttons { display:flex; gap:6px; }
260
+ .annotation-editor-buttons button:not(.primary) { height:32px; padding:0 12px; border-radius:var(--radius-field); color:var(--text-secondary); }
261
+ .annotating { cursor:crosshair !important; }
262
+ @media (prefers-reduced-motion: reduce) {
263
+ .annotation-layer, .annotation-point, .annotation-card, .annotation-row { transition:none !important; animation:none !important; }
264
+ }
@@ -0,0 +1,238 @@
1
+ import { readFile, mkdir, rename, writeFile } from 'node:fs/promises';
2
+ import { existsSync } from 'node:fs';
3
+ import { createHash, randomUUID } from 'node:crypto';
4
+ import { execFileSync } from 'node:child_process';
5
+ import path from 'node:path';
6
+ import { CliError } from './cli-output.mjs';
7
+ import { defaultStateDirectory } from './hub/registry.mjs';
8
+ import { relative } from './toolkit/project.mjs';
9
+
10
+ const queues = new Map();
11
+ const validStatuses = ['open', 'addressed', 'resolved'];
12
+
13
+ export function annotationFile(project, state = defaultStateDirectory) {
14
+ return path.join(state, 'annotations', createHash('sha256').update(path.resolve(project)).digest('hex') + '.json');
15
+ }
16
+
17
+ function gitHead(project) {
18
+ try {
19
+ return execFileSync('git', ['rev-parse', 'HEAD'], { cwd: project, encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'] }).trim() || null;
20
+ } catch {
21
+ return null;
22
+ }
23
+ }
24
+
25
+ function validateElement(element) {
26
+ if (element === null || element === undefined) return null;
27
+ if (typeof element !== 'object' || Array.isArray(element) ||
28
+ typeof element.id !== 'string' || !element.id.trim() ||
29
+ typeof element.owner !== 'object' || !element.owner || Array.isArray(element.owner) ||
30
+ typeof element.owner.source !== 'string' || !element.owner.source.trim() ||
31
+ !(element.owner.export === null || (typeof element.owner.export === 'string' && element.owner.export.trim())) ||
32
+ !['x', 'y'].every(k => Number.isFinite(element[k]) && element[k] >= 0 && element[k] <= 1)) {
33
+ throw new CliError('USAGE_INVALID', 'Provide a valid element anchor with id, owner and normalized x/y coordinates.');
34
+ }
35
+ return {
36
+ id: element.id.trim(),
37
+ owner: { source: element.owner.source.trim(), export: element.owner.export === null ? null : element.owner.export.trim() },
38
+ x: element.x,
39
+ y: element.y,
40
+ };
41
+ }
42
+
43
+ function normalizeRow(row) {
44
+ return {
45
+ ...row,
46
+ element: row.element ?? null,
47
+ replies: Array.isArray(row.replies) ? row.replies : [],
48
+ status: validStatuses.includes(row.status) ? row.status : 'open',
49
+ };
50
+ }
51
+
52
+ export async function annotations(project, state, action = 'list', payload = {}) {
53
+ const file = annotationFile(project, state);
54
+ const previous = queues.get(file) ?? Promise.resolve();
55
+ const operation = previous.catch(() => {}).then(async () => {
56
+ let rows;
57
+ try { rows = JSON.parse(await readFile(file, 'utf8')); }
58
+ catch (e) { if (e.code !== 'ENOENT') throw new CliError('STATE_INVALID', `Cannot read annotations: ${e.message}`); rows = []; }
59
+ if (!Array.isArray(rows)) throw new CliError('STATE_INVALID', 'Cannot read annotations: expected a JSON array.');
60
+ rows = rows.map(normalizeRow);
61
+ if (action === 'list') {
62
+ const status = payload.status ?? 'all';
63
+ if (![...validStatuses, 'all'].includes(status)) throw new CliError('USAGE_INVALID', 'Choose --status=open, addressed, resolved or all.');
64
+ return status === 'all' ? rows : rows.filter(r => r.status === status);
65
+ }
66
+ let row = rows.find(r => r.id === payload.id);
67
+ if (action !== 'create' && !row) throw new CliError('USAGE_INVALID', 'Annotation not found. List annotations to choose an ID.');
68
+ if (action === 'read') return row;
69
+ const now = new Date().toISOString();
70
+ if (action === 'create' || action === 'update') {
71
+ const value = { ...row, ...payload };
72
+ if (typeof value.note !== 'string' || !value.note.trim() || value.note.length > 10000 ||
73
+ typeof value.source !== 'string' || !value.source ||
74
+ typeof value.frame !== 'string' || !value.frame ||
75
+ !['x', 'y'].every(k => Number.isFinite(value[k]) && value[k] >= 0 && value[k] <= 1)) {
76
+ throw new CliError('USAGE_INVALID', 'Provide a note, source, frame and normalized x/y coordinates.');
77
+ }
78
+ const element = validateElement(Object.hasOwn(payload, 'element') ? payload.element : row?.element ?? null);
79
+ const fields = { note: value.note, source: value.source, frame: value.frame, x: value.x, y: value.y, element };
80
+ if (row) {
81
+ Object.assign(row, fields, { updatedAt: now });
82
+ } else {
83
+ row = {
84
+ ...fields,
85
+ id: randomUUID(),
86
+ number: Math.max(0, ...rows.map(r => r.number)) + 1,
87
+ replies: [],
88
+ revision: gitHead(project),
89
+ status: 'open',
90
+ createdAt: now,
91
+ updatedAt: now,
92
+ };
93
+ rows.push(row);
94
+ }
95
+ } else if (action === 'reply') {
96
+ if (typeof payload.message !== 'string' || !payload.message.trim() || payload.message.length > 10000) {
97
+ throw new CliError('USAGE_INVALID', 'Provide a non-empty --message up to 10000 characters.');
98
+ }
99
+ const author = payload.author ?? 'agent';
100
+ if (!['user', 'agent'].includes(author)) throw new CliError('USAGE_INVALID', 'Reply author must be user or agent.');
101
+ row.replies = [...row.replies, { author, message: payload.message.trim(), at: now }];
102
+ row.updatedAt = now;
103
+ } else if (action === 'address') {
104
+ if (typeof payload.message !== 'string' || !payload.message.trim() || payload.message.length > 10000) {
105
+ throw new CliError('USAGE_INVALID', 'Provide a non-empty --message explaining what was addressed.');
106
+ }
107
+ row.replies = [...row.replies, { author: 'agent', message: payload.message.trim(), at: now }];
108
+ row.status = 'addressed';
109
+ row.updatedAt = now;
110
+ } else if (action === 'resolve') {
111
+ Object.assign(row, { status: 'resolved', updatedAt: now });
112
+ } else if (action === 'reopen') {
113
+ Object.assign(row, { status: 'open', updatedAt: now });
114
+ } else if (action === 'delete') {
115
+ rows = rows.filter(r => r.id !== payload.id);
116
+ } else {
117
+ throw new CliError('USAGE_INVALID', 'Unknown annotation action.');
118
+ }
119
+ await mkdir(path.dirname(file), { recursive: true });
120
+ const temp = file + '.' + randomUUID();
121
+ await writeFile(temp, JSON.stringify(rows, null, 2));
122
+ await rename(temp, file);
123
+ return row;
124
+ });
125
+ queues.set(file, operation);
126
+ try { return await operation; } finally { if (queues.get(file) === operation) queues.delete(file); }
127
+ }
128
+
129
+ function toProjectPath(config, candidate) {
130
+ if (!candidate) return null;
131
+ const inDesign = path.join(config.design, candidate);
132
+ if (existsSync(inDesign)) return relative(config, inDesign);
133
+ const inRoot = path.join(config.root, candidate);
134
+ if (existsSync(inRoot)) return relative(config, inRoot);
135
+ const prefix = path.relative(config.root, config.design).split(path.sep).join('/');
136
+ if (!prefix || candidate === prefix || candidate.startsWith(prefix + '/')) return candidate;
137
+ return path.posix.join(prefix, candidate);
138
+ }
139
+
140
+ const quoteShell = value => /^[A-Za-z0-9_./:=+-]+$/.test(value) ? value : `'${String(value).replace(/'/g, `'\\''`)}'`;
141
+
142
+ export async function readAnnotationContext(config, state, id) {
143
+ const row = await annotations(config.root, state, 'read', { id });
144
+ const sourcePath = toProjectPath(config, row.source);
145
+ const ownerSourcePath = row.element?.owner?.source ? toProjectPath(config, row.element.owner.source) : null;
146
+ const head = gitHead(config.root);
147
+ let stale = true, frameBox = null, elementBox = null;
148
+ const fullFile = path.join(config.root, sourcePath);
149
+ if (sourcePath?.endsWith('.tsx') && existsSync(fullFile)) {
150
+ const [{ buildSource }, { frameDocument }, { launch, browserTask }, { installFramePrimitives }, { elementIdentities }] = await Promise.all([
151
+ import('./toolkit/build.mjs'),
152
+ import('./toolkit/frame-document.mjs'),
153
+ import('./toolkit/browser.mjs'),
154
+ import('./toolkit/frame-primitives.mjs'),
155
+ import('./toolkit/frame-identity.mjs'),
156
+ ]);
157
+ let browser;
158
+ try {
159
+ const built = await buildSource(config, fullFile, { write: false });
160
+ const frame = built.frames.find(f => f.name === row.frame);
161
+ if (frame) {
162
+ browser = await launch();
163
+ const page = await browserTask(browser, () => browser.newPage({
164
+ viewport: { width: frame.width ?? 1600, height: frame.height ?? 1200 },
165
+ locale: 'en-US', timezoneId: 'UTC', deviceScaleFactor: 1,
166
+ }));
167
+ await page.setContent(frameDocument(frame, 'light', built.css), { waitUntil: 'load' });
168
+ await page.evaluate(() => document.fonts.ready);
169
+ await page.addScriptTag({ content: `${installFramePrimitives}; installFramePrimitives();` });
170
+ const observed = await page.evaluate(() => {
171
+ const shell = document.querySelector('[data-adg-frame]'), root = shell?.firstElementChild;
172
+ if (!root || shell.children.length !== 1) return null;
173
+ const { inventory, relativeBox, reads, identityNode } = globalThis.__adgFramePrimitives;
174
+ const origin = shell.getBoundingClientRect(), { elements, paths, neutralCandidates } = inventory(root);
175
+ const { style, rect } = reads();
176
+ const box = r => relativeBox(r, origin, true);
177
+ function clipped(node) {
178
+ const nr = rect(node);
179
+ let left = Math.max(nr.left, origin.left), right = Math.min(nr.right, origin.right);
180
+ let top = Math.max(nr.top, origin.top), bottom = Math.min(nr.bottom, origin.bottom);
181
+ for (let p = node; p && p !== shell; p = p.parentElement) {
182
+ const s = style(p);
183
+ if (s.display === 'none' || (p === node && s.visibility !== 'visible') || Number(s.opacity) === 0) return null;
184
+ if (p !== node && s.display !== 'inline') {
185
+ const cr = rect(p);
186
+ if (/(hidden|clip|scroll|auto)/.test(s.overflowX)) { left = Math.max(left, cr.left); right = Math.min(right, cr.right); }
187
+ if (/(hidden|clip|scroll|auto)/.test(s.overflowY)) { top = Math.max(top, cr.top); bottom = Math.min(bottom, cr.bottom); }
188
+ }
189
+ }
190
+ return right > left && bottom > top ? box({ left, right, top, bottom }) : null;
191
+ }
192
+ const identities = [], boxes = {};
193
+ for (const node of elements) {
194
+ const p = paths.get(node), own = JSON.parse(node.getAttribute('data-adg-owners') ?? '[]');
195
+ identities.push(identityNode(node, p, paths.get(node.parentElement) ?? null, own, style(node), neutralCandidates.has(node)));
196
+ boxes[p] = clipped(node);
197
+ }
198
+ return { frameBox: { x: 0, y: 0, width: origin.width, height: origin.height }, identities, boxes };
199
+ });
200
+ if (observed) {
201
+ frameBox = observed.frameBox;
202
+ if (!row.element) {
203
+ stale = false;
204
+ } else {
205
+ const assigned = elementIdentities(observed.identities, { source: sourcePath, frame: frame.name });
206
+ const hit = assigned.find(item => item.id === row.element.id);
207
+ const box = hit ? observed.boxes[hit.path] : null;
208
+ if (box) {
209
+ stale = false;
210
+ elementBox = box;
211
+ }
212
+ }
213
+ }
214
+ }
215
+ } catch {
216
+ stale = true;
217
+ } finally {
218
+ await browser?.close();
219
+ }
220
+ }
221
+ const inspectElementFlag = row.element?.id && !stale ? ` --element=${quoteShell(row.element.id)}` : '';
222
+ return {
223
+ ...row,
224
+ project: config.root,
225
+ sourcePath,
226
+ ownerSourcePath,
227
+ export: row.element?.owner?.export ?? null,
228
+ elementId: row.element?.id ?? null,
229
+ stale,
230
+ frameBox,
231
+ elementBox,
232
+ head,
233
+ commands: {
234
+ inspect: `adg inspect ${quoteShell(sourcePath)} --frame=${quoteShell(row.frame)}${inspectElementFlag} --json`,
235
+ render: `adg render ${quoteShell(sourcePath)} --frame=${quoteShell(row.frame)} --json`,
236
+ },
237
+ };
238
+ }
@@ -6,7 +6,7 @@ import { AsyncLocalStorage } from 'node:async_hooks';
6
6
  /** @typedef {{code: string, message: string, next: NextAction[]}} Diagnostic */
7
7
  /** @typedef {keyof typeof errorCatalog} ErrorCode */
8
8
  /** @typedef {{schemaVersion: 1, command: string, ok: boolean, data: unknown, warnings: Diagnostic[], error: Diagnostic | null}} Envelope */
9
- /** @typedef {{command?: string, project?: string, stateDirectory?: string, gitCause?: 'repository' | 'revision' | 'read', positionals?: string[], values?: Record<string, string | string[] | boolean>, failureCode?: ErrorCode}} ErrorContext */
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
 
12
12
  // Recovery kinds keep the catalog declarative; actions are constructed from known operands.
@@ -19,7 +19,16 @@ export const errorCatalog = {
19
19
  OWNER_COLOR_INVALID: [2, 'owner-help', 'Supply an absolute supported CSS color or query a token name.'],
20
20
  OWNER_INPUT_NOT_FOUND: [2, 'owner-help', 'Choose an existing in-project file or directory.'],
21
21
  OWNER_UNSETTLED: [2, 'owner', 'Stabilize the named frame and resources before repeating the query.'],
22
+ INSPECT_IDENTITY_CONFLICT: [2, 'owner', 'Give repeated instances unique keys or anchors, then repeat the query.'],
23
+ INSPECT_FRAME_AMBIGUOUS: [2, 'inspect', 'Select one of the reported source/frame candidates.'],
24
+ INSPECT_ELEMENT_NOT_FOUND: [2, 'inspect-full', 'Read the current full frame and choose an observed element identity.'],
25
+ INSPECT_PART_NOT_FOUND: [2, 'inspect-full', 'Read the current frame and choose an observed defining part.'],
26
+ INSPECT_SOURCE_UNSUPPORTED: [2, 'inspect-help', 'Choose a discovered TSX design source.'],
27
+ INSPECT_UNSETTLED: [2, 'inspect', 'Stabilize the named frame and resources before retrying.'],
28
+ INSPECT_INPUT_CHANGED: [2, 'inspect', 'Finish concurrent input edits before retrying.'],
22
29
  OWNER_INDEX_CHANGED: [2, 'owner', 'Finish concurrent input edits before repeating the query.'],
30
+ IMPACT_INPUT_NOT_FOUND: [2, 'impact-help', 'Choose an existing design input, registered part or declared token.'],
31
+ IMPACT_INPUT_CHANGED: [2, 'impact', 'Finish concurrent input edits before repeating the query.'],
23
32
  MIGRATION_REQUIRED: [2, 'migrate', 'Migrate the legacy project.'],
24
33
  MIGRATION_CONFLICT: [2, 'migration', 'Inspect migration inputs before resolving the conflict.'],
25
34
  VERSION_UNSATISFIED: [2, 'install', 'Install a version satisfying project requires.'],
@@ -74,7 +83,7 @@ export class CliError extends Error {
74
83
  }
75
84
 
76
85
  const canonicalCommands = new Set([
77
- 'open', 'link', 'serve', 'root', 'service', 'migrate', 'init', 'check', 'render', 'compare', 'diff', 'owner',
86
+ 'annotations', 'open', 'link', 'serve', 'root', 'service', 'migrate', 'init', 'check', 'render', 'compare', 'diff', 'owner', 'impact', 'inspect',
78
87
  'root add', 'root remove', 'root list', 'root scan',
79
88
  'service install', 'service uninstall', 'service status', 'service logs', 'service migrate',
80
89
  'help', 'version', 'adg',
@@ -99,6 +108,10 @@ function helpArgv(command = 'adg') {
99
108
  /** @param {ErrorCode} code @param {ErrorContext} [context] @returns {NextAction[]} */
100
109
  export function nextActions(code, context = {}) {
101
110
  const [, recovery, reason] = errorCatalog[code];
111
+ if(context.inspectCatalog)return nextActions('INSPECT_UNSETTLED',{...context,inspectCatalog:false,command:'inspect',values:context.values?.['state-dir']?{'state-dir':context.values['state-dir']}:{}});
112
+ if(code==='INSPECT_FRAME_AMBIGUOUS'&&context.inspectSources?.length){
113
+ return context.inspectSources.map(source=>nextActions('INSPECT_UNSETTLED',{...context,inspectSources:undefined,positionals:[source]})[0]);
114
+ }
102
115
  const state = context.stateDirectory ? ['--state-dir', context.stateDirectory] : [];
103
116
  let argv;
104
117
  switch (recovery) {
@@ -109,8 +122,41 @@ export function nextActions(code, context = {}) {
109
122
  case 'migrate-help': argv = helpArgv('migrate'); break;
110
123
  case 'check-help': argv = helpArgv('check'); break;
111
124
  case 'render-help': argv = helpArgv('render'); break;
125
+ case 'inspect-help': argv = helpArgv('inspect'); break;
126
+ case 'inspect':
127
+ case 'inspect-full': {
128
+ if(context.inspectCatalog){argv=['adg','inspect','--json',...(context.positionals?.length?['--',...context.positionals]:[])];break;}
129
+ if(context.command!=='inspect'){argv=helpArgv('inspect');break;}
130
+ const values=context.values??{};argv=['adg','inspect'];
131
+ for(const key of ['frame','theme','part','element','text','depth','fields','wrappers'])if(typeof values[key]==='string' && !(recovery==='inspect-full'&&['part','element','text','depth'].includes(key)))argv.push(`--${key}=${values[key]}`);
132
+ if(values.contains&&recovery!=='inspect-full')argv.push('--contains');
133
+ if(values['state-dir'])argv.push(`--state-dir=${values['state-dir']}`);
134
+ argv.push('--json');if(context.positionals?.length)argv.push('--',...context.positionals);break;
135
+ }
112
136
  case 'owner-help': argv = helpArgv('owner'); break;
137
+ case 'impact-help': argv = helpArgv('impact'); break;
138
+ case 'impact': {
139
+ if (['render', 'check', 'diff'].includes(context.command) && context.values?.impacted && typeof context.values.base === 'string') {
140
+ argv = ['adg', context.command, '--impacted'];
141
+ for (const key of ['base', 'frame', 'theme', 'scale', 'out-dir', 'state-dir']) if (typeof context.values[key] === 'string') argv.push(`--${key}=${context.values[key]}`);
142
+ if (context.values['read-only']) argv.push('--read-only');
143
+ if (context.values.explain) argv.push('--explain');
144
+ argv.push('--json');
145
+ if (context.positionals?.length) argv.push('--', ...context.positionals);
146
+ break;
147
+ }
148
+ if (context.command !== 'impact') { argv = helpArgv('impact'); break; }
149
+ const values = context.values ?? {};
150
+ argv = ['adg', 'impact'];
151
+ for (const key of ['source', 'part', 'token', 'file', 'line', 'symbol', 'base', 'head', 'theme', 'state-dir']) {
152
+ const inputs = Array.isArray(values[key]) ? values[key] : typeof values[key] === 'string' ? [values[key]] : [];
153
+ for (const value of inputs) argv.push(`--${key}=${value}`);
154
+ }
155
+ if (values.explain) argv.push('--explain');
156
+ argv.push('--json'); break;
157
+ }
113
158
  case 'owner': {
159
+ if(context.command==='inspect')return nextActions('INSPECT_UNSETTLED',context);
114
160
  const values = context.values ?? {};
115
161
  if (context.command !== 'owner' || !['file', 'text', 'color', 'token'].some(key => typeof values[key] === 'string' && values[key].trim())) { argv = helpArgv('owner'); break; }
116
162
  argv = ['adg', 'owner'];
@@ -139,6 +185,7 @@ export function nextActions(code, context = {}) {
139
185
  for (const key of ['base', 'frame', 'theme', 'scale', 'out-dir']) {
140
186
  if (typeof values[key] === 'string') argv.push(`--${key}=${values[key]}`);
141
187
  }
188
+ if (values.impacted) argv.push('--impacted');
142
189
  argv.push('--json');
143
190
  if (context.positionals?.length) argv.push('--', ...context.positionals);
144
191
  break;
package/src/cli.mjs CHANGED
@@ -6,33 +6,45 @@ 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 = ['open', 'link', 'serve', 'root', 'service', 'migrate', 'init', 'check', 'render', 'compare', 'diff', 'owner'];
9
+ export const commands = ['annotations', 'open', 'link', 'serve', 'root', 'service', 'migrate', 'init', 'check', 'render', 'compare', 'diff', 'owner', 'impact', 'inspect'];
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
13
  open: `[directory] [--port=<n>] [--no-open] [--state-dir=<path>] ${targetOptions}`,
13
14
  link: `<viewer-url> ${targetOptions}`,
14
15
  serve: '[--port=4310] [--state-dir=<path>] [--print-key | --rotate-key]',
15
16
  service: 'install|uninstall|status|logs|migrate [--state-dir=<path>] [--port=4310]',
16
17
  root: 'add <dir> [--depth=2] | remove <dir> | list | scan [dir] [--state-dir=<path>]',
17
- migrate: '[project]', init: '', check: '[source...] [--read-only]', render: '[source...] [--frame=<name>] [--theme=both|light|dark] [--scale=2] [--out-dir=<path>] [--json] [--base=<rev>]',
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]]',
18
19
  compare: '<source> --frame=<name> [--fixture=<name>] [--region=<name> | --selector=<css> | --page] [--origin="<x> <y>"] [--click=<name>...] [--viewport=<w>x<h>] | --all',
19
- diff: '[source...] --base=<rev> [--frame=<name>] [--theme=both|light|dark] [--scale=2] [--out-dir=<path>] [--json]',
20
- owner: '(--file=<path|directory|glob> [--line=<n>] [--symbol=<name>] | --text=<text> [--contains] [--locale=<tag>] | --color=<css> | --token=<name>) [--theme=both|light|dark] [--state-dir=<path>] [--json]',
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]',
21
24
  };
22
25
  const details = {
26
+ annotations: 'List, read, reply to, address, resolve or reopen project annotations stored outside the repository. Run from the project directory.',
23
27
  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.',
24
28
  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.',
25
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.',
26
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.',
27
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.',
28
32
  link: 'Print a clean ADG preview URL. Query mode isolates a target. Path mode locates it in the design hierarchy.',
29
- check: 'Check import direction and every selected frame in both themes. --read-only skips generated types and build files.', render: 'Render selected frames as PNG. Defaults to both themes at 2×. --json prints a versioned result with capture geometry and absolute paths.',
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.',
30
34
  compare: 'Compare fixture text positions. Flags override Frame fixture and capture. --all writes a summary for every fixture frame.',
31
- 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. 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.',
32
- 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. --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.',
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.',
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
+ 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
+ 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
+ };
40
+ const helpExamples = {
41
+ impact: 'adg impact --source=design/components/badge.tsx --part=Badge --json\nadg impact --token=--accent --json\nadg impact --base=HEAD --json',
42
+ render: 'adg render --impacted --base=HEAD --json\nadg render arch/catalog.mmd --base=HEAD --json',
43
+ check: 'adg check --impacted --base=HEAD --read-only --json\nadg check --read-only --json',
44
+ diff: 'adg diff --base=HEAD --impacted --json',
33
45
  };
34
46
  export function help(command) {
35
- if (command) return `Usage: adg ${command} ${usage[command]}\n\n${details[command]}\n\n-h, --help Show help\nExit codes: 0 success, 1 check/compare/diff problems, 2 usage/configuration/environment error.`;
47
+ 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.`;
36
48
  return `Usage: adg [open] [directory] [options]\n\n${commands.map(name => ` adg ${name} ${usage[name]}`).join('\n')}\n\nAny first argument that is not a command opens a directory. Use adg open check for a directory named check.\nRun adg <command> --help for details. -v, --version prints the installed version.`;
37
49
  }
38
50
  export function parseCli(args) {
@@ -41,23 +53,59 @@ export function parseCli(args) {
41
53
  const explicit = commands.includes(args[0]), command = explicit ? args[0] : 'open';
42
54
  const options = { help: { type: 'boolean', short: 'h' }, version: { type: 'boolean', short: 'v' }, json: { type: 'boolean' } };
43
55
  const locators = ['asset', 'frame', 'group', 'layer', 'mode', 'base'];
44
- const strings = { open: ['port', 'state-dir', ...locators], link: locators, serve: ['port', 'state-dir'], root: ['depth', 'state-dir'], service: ['port', 'state-dir'], render: ['scale', 'frame', 'theme', 'out-dir', 'base'], diff: ['base', 'frame', 'theme', 'scale', 'out-dir'], compare: ['frame', 'fixture', 'region', 'selector', 'viewport', 'origin'], owner: ['file', 'text', 'color', 'token', 'line', 'symbol', 'locale', 'theme', 'state-dir'] };
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'] };
45
57
  for (const name of strings[command] ?? []) options[name] = { type: 'string' };
46
58
  if (command === 'serve') for (const name of ['print-key', 'rotate-key']) options[name] = { type: 'boolean' };
47
59
  if (command === 'open') options['no-open'] = { type: 'boolean' };
48
60
  if (command === 'open' || command === 'link') options.tokens = { type: 'boolean' };
49
61
  if (command === 'check') options['read-only'] = { type: 'boolean' };
50
- if (command === 'owner') options.contains = { type: 'boolean' };
62
+ if (['render', 'check', 'diff'].includes(command)) { options.impacted = { type: 'boolean' }; options.explain = { type: 'boolean' }; }
63
+ if (command === 'owner' || command === 'inspect') options.contains = { type: 'boolean' };
64
+ if (command === 'inspect') options.expand = { type: 'boolean' };
65
+ if (command === 'impact') {
66
+ options.explain = { type: 'boolean' };
67
+ for (const name of ['source', 'token']) options[name].multiple = true;
68
+ }
51
69
  if (command === 'compare') { options.all = { type: 'boolean' }; options.page = { type: 'boolean' }; }
52
70
  if (command === 'compare') options.click = { type: 'string', multiple: true };
53
71
  let parsed;
54
- try { parsed = parseArgs({ args: explicit ? args.slice(1) : args, options, allowPositionals: true, tokens: command === 'owner' }); }
72
+ try { parsed = parseArgs({ args: explicit ? args.slice(1) : args, options, allowPositionals: true, tokens: ['owner','impact','inspect'].includes(command) }); }
55
73
  catch (error) { throw new CliError('USAGE_INVALID', `${error.message}; run adg ${command} --help`); }
56
74
  const { values, positionals } = parsed;
57
75
  if (globalJson) values.json = true;
58
76
  if (!values.help && !values.version) {
77
+ if (['render', 'check', 'diff'].includes(command)) {
78
+ if (!values.impacted && (values.explain !== undefined || values['state-dir'] !== undefined)) throw new CliError('USAGE_INVALID', '--explain and --state-dir require --impacted --base=<rev>.');
79
+ if (values.impacted && (typeof values.base !== 'string' || !values.base.trim())) throw new CliError('USAGE_INVALID', '--impacted requires --base=<rev>.');
80
+ if (command === 'check' && !values.impacted && ['base', 'frame', 'theme', 'state-dir', 'explain'].some(key => values[key] !== undefined)) throw new CliError('USAGE_INVALID', 'Check selection flags require --impacted --base=<rev>.');
81
+ }
82
+ if (command === 'inspect') {
83
+ const seen=new Set();
84
+ for(const token of parsed.tokens)if(token.kind==='option'&&!['json','help','version'].includes(token.name)){
85
+ if(seen.has(token.name))throw new CliError('USAGE_INVALID',`Do not repeat --${token.name}; run adg inspect --help.`);seen.add(token.name);
86
+ }
87
+ if(positionals.length>1 || strings.inspect.some(k=>values[k]!==undefined&&!values[k].trim()) ||
88
+ ['part','element','text'].filter(k=>values[k]!==undefined).length>1 || values.contains!==undefined&&values.text===undefined ||
89
+ values.theme!==undefined&&!['both','light','dark'].includes(values.theme) ||
90
+ values.wrappers!==undefined&&!['semantic','all'].includes(values.wrappers) ||
91
+ values.depth!==undefined&&values.depth!=='all'&&(!/^(0|[1-9]\d*)$/.test(values.depth)||!Number.isSafeInteger(Number(values.depth))) ||
92
+ values.fields!==undefined&&values.fields.split(',').some(k=>!['structure','layout','typography','color','text'].includes(k)))throw new CliError('USAGE_INVALID','Choose compatible inspect selectors and field groups; run adg inspect --help.');
93
+ }
94
+ if (command === 'impact') {
95
+ const kinds = ['source', 'token', 'file', 'base'].filter(key => values[key] !== undefined), seen = new Set();
96
+ for (const token of parsed.tokens) if (token.kind === 'option' && !['json', 'help', 'version', 'source', 'token'].includes(token.name)) {
97
+ if (seen.has(token.name)) throw new CliError('USAGE_INVALID', `Do not repeat --${token.name}; run adg impact --help.`);
98
+ seen.add(token.name);
99
+ }
100
+ if (positionals.length || kinds.length !== 1 || strings.impact.some(key => values[key] !== undefined && (Array.isArray(values[key]) ? values[key] : [values[key]]).some(value => !value.trim())) ||
101
+ values.theme !== undefined && !['both', 'light', 'dark'].includes(values.theme) ||
102
+ values.part !== undefined && (kinds[0] !== 'source' || values.source.length !== 1) ||
103
+ values.head !== undefined && kinds[0] !== 'base' ||
104
+ (values.line !== undefined || values.symbol !== undefined) && kinds[0] !== 'file' ||
105
+ 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
+ }
59
107
  if (command === 'owner') {
60
- const kinds = ['file', 'text', 'color', 'token'].filter(key => values[key] !== undefined);
108
+ const kinds = ['file', 'text', 'color', 'token', 'part'].filter(key => values[key] !== undefined);
61
109
  const seen = new Set();
62
110
  for (const token of parsed.tokens) if (token.kind === 'option' && !['json', 'help', 'version'].includes(token.name)) {
63
111
  if (seen.has(token.name)) throw new CliError('USAGE_INVALID', `Do not repeat --${token.name}; run adg owner --help.`);
@@ -66,6 +114,7 @@ export function parseCli(args) {
66
114
  if (positionals.length || kinds.length !== 1 || strings.owner.some(key => values[key] !== undefined && !values[key].trim()) ||
67
115
  values.theme !== undefined && !['both', 'light', 'dark'].includes(values.theme) ||
68
116
  (values.line !== undefined || values.symbol !== undefined) && kinds[0] !== 'file' ||
117
+ values.part !== undefined && (values.line !== undefined || values.symbol !== undefined || values.locale !== undefined || values.contains !== undefined) ||
69
118
  (values.contains !== undefined || values.locale !== undefined) && kinds[0] !== 'text' ||
70
119
  values.line !== undefined && (!/^[1-9]\d*$/.test(values.line) || !Number.isSafeInteger(Number(values.line)))) throw new CliError('USAGE_INVALID', 'Choose one nonempty owner input and compatible options; run adg owner --help.');
71
120
  }
@@ -77,6 +126,16 @@ export function parseCli(args) {
77
126
  const [action, directory, ...extra] = positionals;
78
127
  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');
79
128
  }
129
+ if (command === 'annotations') {
130
+ 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.');
137
+ }
138
+ }
80
139
  if (command === 'serve' && positionals.length) throw new CliError('USAGE_INVALID', 'Invalid arguments; run adg serve --help');
81
140
  if (command === 'serve' && ((values['print-key'] && values['rotate-key']) || (values.port !== undefined && (values['print-key'] || values['rotate-key'])))) throw new CliError('USAGE_INVALID','Choose --print-key or --rotate-key without --port; run adg serve --help');
82
141
  } else if (values.json && values.help && ['root', 'service'].includes(command) && (positionals.length > 1 || (positionals.length && !(command === 'root' ? rootActions : serviceActions).includes(positionals[0])))) {
@@ -136,6 +195,18 @@ async function dispatch({ command, values, positionals }, cwd, output, serviceOp
136
195
  return {data:values['print-key'] ? {action:'print-key',stateDirectory,key} : {action:'rotate-key',stateDirectory,rotated:true}};
137
196
  }
138
197
  const config = await loadConfig(cwd);
198
+ if (command === 'annotations') {
199
+ const [action = 'list', id] = positionals;
200
+ 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' });
205
+ if (!values.json) output.log(JSON.stringify(data, null, 2));
206
+ return { data };
207
+ }
208
+ if (command === 'inspect') return (await import('./toolkit/inspect.mjs')).inspect(config, positionals, { ...values, ...(values['state-dir'] !== undefined ? { 'state-dir': path.resolve(cwd, values['state-dir']) } : {}) }, { log: output.log });
209
+ if (command === 'impact') return (await import('./toolkit/impact.mjs')).impact(config, { ...values, ...(values['state-dir'] !== undefined ? { 'state-dir': path.resolve(cwd, values['state-dir']) } : {}) }, { log: output.log });
139
210
  if (command === 'owner') return (await import('./toolkit/owner.mjs')).owner(config, { ...values, ...(values['state-dir'] !== undefined ? { 'state-dir': path.resolve(cwd, values['state-dir']) } : {}) }, { log: output.log });
140
211
  if (command === 'init') return { data: (await import('./toolkit/project.mjs')).init(config, output.log) };
141
212
  if (command === 'compare') return (await import('./toolkit/compare.mjs')).compare(config, positionals, values, {log:output.log});