@whzxc/agent-design-gallery 0.9.0 → 0.10.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.
@@ -9,6 +9,7 @@ import { pixelComparator, imageDifference } from './pixel-diff.mjs';
9
9
  import { partContext, captureEvidence, capturePart, isolateParent, frameIdentity, comparisonIdentity } from './part-diff.mjs';
10
10
  import { commandFailure, cleanup, emptySelection } from './results.mjs';
11
11
  import { CliError, classifyError, asCliError, nextActions } from '../cli-output.mjs';
12
+ import { withImpacted } from './impact-selection.mjs';
12
13
  import { resolveDiffPolicy } from './diff-policy.mjs';
13
14
 
14
15
  const metadata = JSON.parse(readFileSync(new URL('../../package.json', import.meta.url), 'utf8'));
@@ -125,7 +126,9 @@ async function writePair(output, pair, thresholds) {
125
126
  }
126
127
 
127
128
  /** Exact ordinary frames and evidence-backed structural part comparisons. */
128
- export async function diff(config, args = [], options = {}, { launchBrowser = launch, prepareInputs = prepareDiffInputs, log = console.log, clock } = {}) {
129
+ export async function diff(config, args = [], options = {}, { launchBrowser = launch, prepareInputs = prepareDiffInputs, log = console.log, clock, session } = {}) {
130
+ if (options.impacted && !session) return withImpacted(config, args, options, 'diff', selected =>
131
+ diff(config, args, options, { launchBrowser, prepareInputs, log, clock, session: selected }));
129
132
  const started = performance.now(), scale = Number(options.scale ?? 2), themeOption = options.theme ?? 'both';
130
133
  if (!Number.isFinite(scale) || scale <= 0) throw new CliError('USAGE_INVALID', 'Invalid --scale; use a positive number.');
131
134
  if (!['both', 'light', 'dark'].includes(themeOption)) throw new CliError('USAGE_INVALID', 'Choose --theme=both, light, or dark.');
@@ -143,7 +146,7 @@ export async function diff(config, args = [], options = {}, { launchBrowser = la
143
146
  };
144
147
  try {
145
148
  const head = await timed('prepareMs', async () => {
146
- inputs = await prepareInputs(config, args, options);
149
+ inputs = session ? session.diffInputs : await prepareInputs(config, args, options);
147
150
  return currentHead(inputs.base);
148
151
  });
149
152
  warnings.push(...inputs.warnings);
@@ -154,26 +157,27 @@ export async function diff(config, args = [], options = {}, { launchBrowser = la
154
157
  existingCoverage: !inputs.sources.length ? 'empty' : args.length || options.frame !== undefined || themes.length !== 2 ? 'partial' : 'full' },
155
158
  environment: { adg: metadata.version, node: process.version, platform: process.platform, arch: process.arch, chromium: null,
156
159
  ...metadata.dependencies, locale: 'en-US', timezone: 'UTC', ...inputs.environment, baseThresholds: inputs.before.config.diff.thresholds },
157
- classifierVersion: 1, thresholds, comparisons: [], support: [], verdict: null, reasons: [],
160
+ impact: session?.selection ?? null, classifierVersion: 1, thresholds, comparisons: [], support: [], verdict: null, reasons: [],
158
161
  summary: { sources: inputs.sources.length, frames: 0, comparisons: 0, supportComparisons: 0, isolationCaptures: 0,
159
162
  added: 0, removed: 0, matched: 0, identical: 0, structural: 0, changed: 0,
160
163
  classPixels: Object.fromEntries(classNames.map(name => [name, 0])) },
161
164
  differencePalette: { equal: '#00000000', imperceptible: '#64748b', antialiasing: '#f59e0b', boundary_bleed: '#0ea5e9', bitmap_resampling: '#a855f7', other: '#ff00ff' }, reportPath: null, timings,
162
165
  };
163
- if (inputs.sources.length) browser = await launchBrowser();
166
+ if (session ? session.chosen.some(row => row.source.endsWith('.mmd') && session.themes.some(theme => session.scheduled(row, theme))) : inputs.sources.length) browser = await launchBrowser();
164
167
  const built = await timed('buildMs', () => inputs.buildFrames({ browser }));
168
+ if (session) built.frames = built.frames.filter(row => themes.some(theme => session.scheduled(row, theme)));
165
169
  context = partContext(built, inputs, scale, themes, clock);
166
170
  for (const warning of inputs.warnings) if (!warnings.includes(warning)) warnings.push(warning);
167
171
  data.summary.frames = built.frames.length;
168
172
  for (const row of built.frames) data.summary[row.status]++;
169
- if (!built.frames.length) emptySelection(warnings);
170
- else browser ??= await launchBrowser();
173
+ if (!built.frames.length && (!session || !session.selection.coverage.expectedRows)) emptySelection(warnings);
174
+ else if (built.frames.length) browser ??= await launchBrowser();
171
175
  if (browser) data.environment.chromium = browser.version();
172
176
  const selectedOrder = new Map(built.frames.flatMap(row => themes.map(theme => comparisonIdentity(row, theme))).map((key, index) => [key, index]));
173
177
  const supportKeys = new Set(built.support.map(frameIdentity));
174
178
  const ordinary = [...built.frames.filter(row => !row.parentRow), ...built.support.map(row => ({ ...row, support: true }))];
175
- const ordinaryJobs = ordinary.flatMap(row => themes.map(theme => ({ row, theme })));
176
- const partJobs = built.frames.filter(row => row.parentRow).flatMap(row => themes.map(theme => ({ row, theme })));
179
+ const ordinaryJobs = ordinary.flatMap(row => themes.filter(theme => !session || row.support || session.scheduled(row, theme)).map(theme => ({ row, theme })));
180
+ const partJobs = built.frames.filter(row => row.parentRow).flatMap(row => themes.filter(theme => !session || session.scheduled(row, theme)).map(theme => ({ row, theme })));
177
181
  const concurrency = Math.min(4, availableParallelism());
178
182
  for (const jobs of [ordinaryJobs, partJobs]) for (let start = 0; start < jobs.length; start += concurrency) {
179
183
  const failures = [], openPairs = [];
@@ -244,8 +248,8 @@ export async function diff(config, args = [], options = {}, { launchBrowser = la
244
248
  timings.totalMs = performance.now() - started;
245
249
  data.reportPath = path.join(output, 'report.json');
246
250
  try {
247
- await mkdir(output, { recursive: true });
248
- await writeFile(data.reportPath, JSON.stringify(data, null, 2) + '\n');
251
+ if (!session) await mkdir(output, { recursive: true });
252
+ if (!session) await writeFile(data.reportPath, JSON.stringify(data, null, 2) + '\n');
249
253
  } catch (error) {
250
254
  data.reportPath = null; data.complete = false; data.verdict = null;
251
255
  if (primary) primary.warnings.push(classifyError(error).error);
@@ -0,0 +1,6 @@
1
+ import { escape } from './runtime.mjs';
2
+
3
+ /** The builder and operation-local proof use the same exact document construction. */
4
+ export function frameDocument(frame, theme, css) {
5
+ return `<!doctype html><html data-theme="${theme}"><head><meta charset="utf-8"><style>${css.replace(/<\/style/gi, '<\\/style')}</style></head><body><div data-adg-frame="${escape(frame.name)}" style="${frame.width ? `width:${frame.width}px;` : 'width:max-content;'}${frame.height ? `height:${frame.height}px;` : ''}">${frame.html}</div></body></html>`;
6
+ }
@@ -0,0 +1,136 @@
1
+ import { parse } from 'parse5';
2
+ import { tokenize, tokenTypes as T } from 'css-tree';
3
+ import { decodeCssEscapes } from './token-reachability.mjs';
4
+
5
+ const svg = 'http://www.w3.org/2000/svg';
6
+ const scriptTags = new Set(['script', 'iframe', 'object', 'embed']);
7
+ const urlAttributes = new Set(['href', 'src', 'action', 'formaction', 'data', 'poster', 'background', 'codebase', 'cite', 'longdesc', 'profile', 'usemap', 'manifest']);
8
+ const svgPaintAttributes = new Set(['fill', 'stroke', 'filter', 'clip-path', 'mask', 'marker', 'marker-start', 'marker-mid', 'marker-end', 'cursor', 'color-profile']);
9
+ const javascript = value => /^javascript:/i.test(value.replace(/[\u0000-\u0020]/g, ''));
10
+
11
+ // WHATWG srcset URLs consume non-whitespace bytes (including data-URL commas).
12
+ function srcsetUrls(value) {
13
+ const urls = [];
14
+ let i = 0;
15
+ while (i < value.length) {
16
+ while (/[\s,]/.test(value[i] ?? '') && i < value.length) i++;
17
+ const start = i;
18
+ while (i < value.length && !/\s/.test(value[i])) i++;
19
+ const url = value.slice(start, i);
20
+ if (url) urls.push(url.replace(/,+$/, ''));
21
+ if (url.endsWith(',')) continue;
22
+ let depth = 0;
23
+ while (i < value.length) {
24
+ const char = value[i++];
25
+ if (char === '(') depth++;
26
+ if (char === ')') depth--;
27
+ if (char === ',' && !depth) break;
28
+ }
29
+ }
30
+ return urls;
31
+ }
32
+
33
+ /** Two parsed-document checks only; no browser, rendering, or environment certificate. */
34
+ export function createEligibilityChecker() {
35
+ const resources = new Map(), stylesheets = new Map(), documents = new Map();
36
+ function cssReasons(css) {
37
+ if (stylesheets.has(css)) return stylesheets.get(css);
38
+ const reasons = new Set(), stack = [];
39
+ let importing = false;
40
+ try {
41
+ tokenize(css, (type, start, end) => {
42
+ const raw = css.slice(start, end);
43
+ if (type === T.BadString || type === T.BadUrl) reasons.add('unsupported_css');
44
+ if (type === T.AtKeyword) importing = decodeCssEscapes(raw.slice(1)).toLowerCase() === 'import';
45
+ if (type === T.Url) {
46
+ for (const reason of urlReasons(decodeCssEscapes(raw.slice(raw.indexOf('(') + 1, raw.endsWith(')') ? -1 : undefined).trim()))) reasons.add(reason);
47
+ importing = false;
48
+ } else if (type === T.String) {
49
+ if (raw.length < 2 || raw.at(-1) !== raw[0]) reasons.add('unsupported_css');
50
+ if (importing || ['url', 'image', 'image-set', '-webkit-image-set'].includes(stack.at(-1)?.name)) {
51
+ for (const reason of urlReasons(decodeCssEscapes(raw.slice(1, -1)))) reasons.add(reason);
52
+ }
53
+ importing = false;
54
+ } else if (type === T.Function) {
55
+ const name = decodeCssEscapes(raw.slice(0, -1)).toLowerCase();
56
+ if (['var', 'attr'].includes(name) && stack.some(context => ['image', 'image-set', '-webkit-image-set'].includes(context?.name))) reasons.add('unsupported_css');
57
+ stack.push({ name, start: end });
58
+ }
59
+ else if (type === T.LeftParenthesis) stack.push(null);
60
+ else if (type === T.RightParenthesis) {
61
+ const context = stack.pop();
62
+ if (context?.name === 'url') {
63
+ let value = css.slice(context.start, start).trim();
64
+ if (/^['"]/.test(value)) value = value.slice(1, -1);
65
+ for (const reason of urlReasons(decodeCssEscapes(value))) reasons.add(reason);
66
+ }
67
+ }
68
+ else if (type === T.Semicolon) importing = false;
69
+ });
70
+ if (stack.length) reasons.add('unsupported_css');
71
+ } catch { reasons.add('unsupported_css'); }
72
+ const result = [...reasons].sort(); stylesheets.set(css, result); return result;
73
+ }
74
+ function urlReasons(value) {
75
+ value = value.trim();
76
+ if (javascript(value)) return ['dynamic_document'];
77
+ if (value.startsWith('#')) return [];
78
+ if (!/^data:/i.test(value)) return ['external_resource'];
79
+ if (resources.has(value)) return resources.get(value);
80
+ resources.set(value, []);
81
+ let result = [];
82
+ try {
83
+ const comma = value.indexOf(',');
84
+ if (comma < 0) return ['incomplete_identity'];
85
+ const header = value.slice(5, comma), encoded = decodeURIComponent(value.slice(comma + 1));
86
+ const text = /;base64(?:;|$)/i.test(header) ? Buffer.from(encoded, 'base64').toString('utf8') : encoded;
87
+ if (/^(?:image\/svg\+xml|text\/html|application\/xhtml\+xml)(?:;|$)/i.test(header) || /^\s*<(?:svg|html|!doctype)/i.test(text)) result = htmlReasons(text);
88
+ else if (/^text\/css(?:;|$)/i.test(header)) result = cssReasons(text);
89
+ } catch { result = ['incomplete_identity']; }
90
+ resources.set(value, result); return result;
91
+ }
92
+ function htmlReasons(document) {
93
+ if (documents.has(document)) return documents.get(document);
94
+ const reasons = new Set();
95
+ try {
96
+ const tree = parse(document);
97
+ function visit(node) {
98
+ const tag = node.tagName?.toLowerCase();
99
+ if (scriptTags.has(tag)) reasons.add('dynamic_document');
100
+ const attrs = Object.fromEntries((node.attrs ?? []).map(attr => [attr.name.toLowerCase(), attr.value]));
101
+ for (const attr of node.attrs ?? []) {
102
+ const name = attr.name.toLowerCase(), value = attr.value;
103
+ if (name.startsWith('on') || urlAttributes.has(name) && javascript(value)) reasons.add('dynamic_document');
104
+ if (name === 'style') for (const reason of cssReasons(value)) reasons.add(reason);
105
+ if (node.namespaceURI === svg && svgPaintAttributes.has(name)) for (const reason of cssReasons(value)) reasons.add(reason);
106
+ if (['src', 'poster', 'background'].includes(name) || name === 'href' && (node.namespaceURI === svg || ['link', 'base'].includes(tag))) {
107
+ for (const reason of urlReasons(value)) reasons.add(reason);
108
+ }
109
+ if (['srcset', 'imagesrcset'].includes(name)) for (const url of srcsetUrls(value)) for (const reason of urlReasons(url)) reasons.add(reason);
110
+ }
111
+ if (tag === 'meta' && attrs['http-equiv']?.toLowerCase() === 'refresh') {
112
+ const url = /(?:^|;)\s*url\s*=\s*['"]?([^'"]+)/i.exec(attrs.content ?? '')?.[1];
113
+ for (const reason of urlReasons(url ?? '')) reasons.add(reason);
114
+ }
115
+ // SMIL is allowed, but animated resource URLs still have to be closed.
116
+ if (['animate', 'set'].includes(tag)) {
117
+ for (const name of ['from', 'to', 'by', 'values']) if (attrs[name]) {
118
+ if (['href', 'xlink:href', 'src'].includes(attrs.attributename?.toLowerCase())) {
119
+ for (const url of attrs[name].split(';')) for (const reason of urlReasons(url)) reasons.add(reason);
120
+ } else for (const reason of cssReasons(attrs[name])) reasons.add(reason);
121
+ }
122
+ }
123
+ if (tag === 'style') for (const reason of cssReasons((node.childNodes ?? []).map(child => child.value ?? '').join(''))) reasons.add(reason);
124
+ for (const child of node.childNodes ?? []) visit(child);
125
+ if (node.content) visit(node.content);
126
+ }
127
+ visit(tree);
128
+ } catch { reasons.add('incomplete_identity'); }
129
+ const result = [...reasons].sort(); documents.set(document, result); return result;
130
+ }
131
+ htmlReasons.withCss = css => {
132
+ const shared = cssReasons(css);
133
+ return markup => [...new Set([...shared, ...htmlReasons(markup)])].sort();
134
+ };
135
+ return htmlReasons;
136
+ }
@@ -0,0 +1,71 @@
1
+ import path from 'node:path';
2
+ import { readFile, realpath, stat } from 'node:fs/promises';
3
+ import { configFile } from './config.mjs';
4
+ import { prepareDiffInputs } from './diff-inputs.mjs';
5
+ import { revisionChanges, currentHead } from './arch-git.mjs';
6
+ import { cleanup } from './results.mjs';
7
+ import { CliError } from '../cli-output.mjs';
8
+
9
+ const slash = name => name.split(path.sep).join('/');
10
+ const within = (name, directory) => !directory || name === directory || name.startsWith(directory + '/');
11
+
12
+ /** Literal local config imports supply path roles; opaque inputs retain unknown classification. */
13
+ export async function configInputFiles(config) {
14
+ const found = new Set(), entry = configFile(config.root);
15
+ async function visit(file) {
16
+ file = await realpath(file);
17
+ if (found.has(file)) return;
18
+ found.add(file);
19
+ const text = await readFile(file, 'utf8');
20
+ for (const [, specifier] of text.matchAll(/\b(?:from\s*|import\s*(?:\(\s*)?|require\(\s*)['"](\.[^'"]+)['"]/g)) {
21
+ const requested = path.resolve(path.dirname(file), specifier);
22
+ for (const candidate of [requested, ...['.ts', '.js', '.mjs', '/index.ts', '/index.js'].map(extension => requested + extension)]) {
23
+ try { if ((await stat(candidate)).isFile()) { await visit(candidate); break; } }
24
+ catch (error) { if (!['ENOENT', 'ENOTDIR'].includes(error.code)) throw error; }
25
+ }
26
+ }
27
+ }
28
+ if (entry) await visit(entry);
29
+ return [...found];
30
+ }
31
+
32
+ /** Reuse diff's historical config, dependency environment and disposable-tree lifecycle. */
33
+ export async function prepareImpactInputs(config, values) {
34
+ const sessions = [];
35
+ try {
36
+ const base = await prepareDiffInputs(config, [], { base: values.base }); sessions.push(base);
37
+ let head;
38
+ if (values.head !== undefined) { head = await prepareDiffInputs(config, [], { base: values.head }); sessions.push(head); }
39
+ const before = base.before, after = head ? head.before : base.after;
40
+ const projectPrefix = slash(path.relative(base.base.root, await realpath(config.root)));
41
+ const outputs = [before, after].map(side => slash(path.join(projectPrefix, path.relative(side.config.root, side.config.output))));
42
+ const artifacts = values['out-dir'] === undefined ? null : slash(path.relative(base.base.root, path.resolve(await realpath(config.root), values['out-dir'])));
43
+ const excluded = name => name.split('/').some(part => ['.git', 'node_modules', '.adg'].includes(part)) || outputs.some(output => within(name, output)) || artifacts !== null && within(name, artifacts) && /\.(?:png|json)$/.test(name);
44
+ const changes = (await revisionChanges(base.base, head?.base)).filter(change => [change.before, change.after].some(name => name !== null && !excluded(name)));
45
+ return {
46
+ session: base,
47
+ before: { config: before.config, revision: base.base },
48
+ after: { config: after.config, revision: head?.base ?? null },
49
+ query: { kind: 'git', base: { rev: base.base.rev, sha: base.base.sha }, head: head ? { rev: head.base.rev, sha: head.base.sha } : null },
50
+ repository: base.base.root, projectPrefix, changes,
51
+ head: head?.base.sha ?? await currentHead(base.base),
52
+ warnings: sessions.flatMap(session => session.warnings),
53
+ translate: value => sessions.reduce((result, session) => session.translateDiagnostic(result), value),
54
+ async verifyChanges() {
55
+ if (head) return;
56
+ const current = (await revisionChanges(base.base)).filter(change => [change.before, change.after].some(name => name !== null && !excluded(name)));
57
+ if (JSON.stringify(current) !== JSON.stringify(changes)) throw new CliError('IMPACT_INPUT_CHANGED', 'Git input inventory changed during query.');
58
+ },
59
+ async close() {
60
+ let failure;
61
+ for (const session of [...sessions].reverse()) {
62
+ try { await session.close(); } catch (error) { failure ??= error; }
63
+ }
64
+ if (failure) throw failure;
65
+ },
66
+ };
67
+ } catch (error) {
68
+ for (const session of [...sessions].reverse()) await cleanup(() => session.close(), error);
69
+ throw error;
70
+ }
71
+ }
@@ -0,0 +1,46 @@
1
+ const present = object => Object.fromEntries(Object.entries(object).filter(([, value]) => value !== null && value !== undefined && (!Array.isArray(value) || value.length)));
2
+
3
+ function record(row, explain) {
4
+ return present({ candidate: row.candidate, disposition: row.disposition,
5
+ reasons: row.reasons.map(({ witness, ...reason }) => ({ ...reason, ...(explain && witness ? { witness: present(witness) } : {}) })),
6
+ proof: row.proof ? present({ ...row.proof, projection: explain ? row.proof.projection : undefined }) : null,
7
+ unassessedReasons: row.unassessedReasons });
8
+ }
9
+
10
+ // Witnesses and proof digests describe the first represented row, not a grouping boundary.
11
+ function identity(row) {
12
+ const { proof, reasons, ...rest } = row;
13
+ return { ...rest, ...(proof ? { proof: Object.fromEntries(Object.entries(proof).filter(([key]) => key !== 'projection')) } : {}),
14
+ ...(reasons ? { reasons: reasons.map(({ witness, ...reason }) => reason) } : {}) };
15
+ }
16
+
17
+ function addCounts(target, next) {
18
+ for (let i = 0; i < (target.reasons?.length ?? 0); i++) target.reasons[i].count += next.reasons[i].count;
19
+ }
20
+
21
+ /** Shared wire projection for ImpactData and the later ImpactSelection. */
22
+ export function groupImpactFrames(frames, { explain = false } = {}) {
23
+ const groups = [], byIdentity = new Map();
24
+ for (const frame of frames) {
25
+ const rows = [], byRecord = new Map();
26
+ for (const input of frame.themes) {
27
+ const value = record(input, explain), key = JSON.stringify(identity(value));
28
+ const same = byRecord.get(key);
29
+ if (same) { same.themes.push(input.theme); addCounts(same, value); }
30
+ else { const row = { themes: [input.theme], ...value }; rows.push(row); byRecord.set(key, row); }
31
+ }
32
+ const metadata = present({ source: frame.ref.source, status: frame.status, matchKind: frame.matchKind, matchCandidates: frame.matchCandidates });
33
+ const key = JSON.stringify({ ...metadata, rows: rows.map(identity) });
34
+ const same = byIdentity.get(key);
35
+ if (same) {
36
+ same.frames.push(frame.ref.frame);
37
+ for (let i = 0; i < rows.length; i++) addCounts(same.rows[i], rows[i]);
38
+ } else {
39
+ const group = { ...metadata, frames: [frame.ref.frame], rows };
40
+ groups.push(group); byIdentity.set(key, group);
41
+ }
42
+ }
43
+ return groups;
44
+ }
45
+
46
+ export const impactFrameCount = groups => groups.reduce((count, group) => count + group.frames.length, 0);
@@ -0,0 +1,67 @@
1
+ import path from 'node:path';
2
+ import { frameDocument } from './frame-document.mjs';
3
+ import { tokenReachability } from './token-reachability.mjs';
4
+ import { indexDigest } from './index-store.mjs';
5
+
6
+ export function canonicalBytes(value) {
7
+ const normalize = value => {
8
+ if (typeof value === 'function') return { function: Function.prototype.toString.call(value) };
9
+ if (Array.isArray(value)) return value.map(normalize);
10
+ if (value && typeof value === 'object') return Object.fromEntries(Object.keys(value).sort().map(key => [key, normalize(value[key])]));
11
+ return value;
12
+ };
13
+ return JSON.stringify(normalize(value));
14
+ }
15
+
16
+ /** Resolved design-capture policy; implementation compare hooks are never invoked. */
17
+ export function capturePolicy(config) {
18
+ return { initialViewport: { width: 1600, height: 1200 }, reducedMotion: 'reduce',
19
+ locale: 'en-US', timezone: 'UTC', animations: 'disabled', caret: 'hide', diff: config.diff };
20
+ }
21
+
22
+ export function materializedProjection(built, frame, theme, policy, reach = undefined) {
23
+ const documentWithoutTokens = frameDocument(frame, theme, built.cssBeforeTokens + built.cssAfterTokens);
24
+ reach ??= tokenReachability(documentWithoutTokens, built.tokenCss, theme);
25
+ const replacement = reach.mode === 'full_sheet' ? built.tokenCss : canonicalBytes(reach.declarations);
26
+ return { bytes: canonicalBytes({ document: frameDocument(frame, theme, built.cssBeforeTokens + replacement + built.cssAfterTokens),
27
+ structural: { parent: frame.parent ?? null, width: frame.width ?? null, height: frame.height ?? null }, policy }),
28
+ tokenMode: reach.mode };
29
+ }
30
+
31
+ export function architectureConfig(config) {
32
+ return { arch: config.arch ? path.relative(config.root, config.arch).split(path.sep).join('/') : false,
33
+ check: config.check, capture: capturePolicy(config) };
34
+ }
35
+
36
+ export function architectureProjection({ source, sidecar, tokens, config }) {
37
+ // null sidecar and an empty present file are deliberately different inputs.
38
+ const identity = value => value == null ? null : Buffer.from(value).toString('base64');
39
+ return canonicalBytes({ source: identity(source), sidecar: identity(sidecar), tokens: identity(tokens), config: architectureConfig(config) });
40
+ }
41
+
42
+ export function equalProof(before, after, kind, tokenMode, explain) {
43
+ if (before !== after) return null;
44
+ return { kind, version: 1, tokenMode, ...(explain ? { projection: indexDigest(before) } : {}) };
45
+ }
46
+
47
+ /** Compare an exact document as its shared style bytes and remaining document bytes.
48
+ * The fixed builder boundary makes this equivalent to whole-document equality.
49
+ * Keep large style strings out of per-frame JSON serialization. */
50
+ export function entryProjection(built, policy) {
51
+ const styles = new Map(), policyBytes = canonicalBytes(policy);
52
+ return (frame, theme, reach) => {
53
+ const replacement = reach.mode === 'full_sheet' ? built.tokenCss : canonicalBytes(reach.declarations);
54
+ if (!styles.has(replacement)) styles.set(replacement, (built.cssBeforeTokens + replacement + built.cssAfterTokens).replace(/<\/style/gi, '<\\/style'));
55
+ return { css: styles.get(replacement), markup: frameDocument(frame, theme, ''),
56
+ metadata: canonicalBytes({ parent: frame.parent ?? null, width: frame.width ?? null, height: frame.height ?? null }),
57
+ policy: policyBytes, tokenMode: reach.mode,
58
+ canonical: () => materializedProjection(built, frame, theme, policy, reach).bytes };
59
+ };
60
+ }
61
+
62
+ export function equalEntryProof(before, after, explain) {
63
+ if (before.css !== after.css || before.markup !== after.markup || before.metadata !== after.metadata || before.policy !== after.policy) return null;
64
+ return { kind: 'materialized_inputs_equal', version: 1,
65
+ tokenMode: before.tokenMode === 'full_sheet' || after.tokenMode === 'full_sheet' ? 'full_sheet' : 'reachable_declarations',
66
+ ...(explain ? { projection: indexDigest(before.canonical()) } : {}) };
67
+ }
@@ -0,0 +1,96 @@
1
+ import { CliError } from '../cli-output.mjs';
2
+ import { impact } from './impact.mjs';
3
+ import { selectedSources } from './diff-inputs.mjs';
4
+ import { groupImpactFrames } from './impact-output.mjs';
5
+ import { commandFailure } from './results.mjs';
6
+ import { mkdir, writeFile } from 'node:fs/promises';
7
+ import path from 'node:path';
8
+
9
+ export const impactRowKey = (row, theme) => JSON.stringify([row.source, row.frame, theme]);
10
+
11
+ /** Keep fresh proofs, captures and final generation validation in one owned operation. */
12
+ export async function withImpacted(config, args, options, command, work) {
13
+ if (typeof options.base !== 'string' || !options.base.trim() || options.frame === '' || options.theme !== undefined && !['both', 'light', 'dark'].includes(options.theme)) throw new CliError('USAGE_INVALID', 'Choose --impacted --base=<rev> and a valid frame/theme selection.');
14
+ let outcome, failure, selection, workMs = 0;
15
+ const warnings = [];
16
+ function discardProofs() {
17
+ if (selection) {
18
+ selection.coverage.proofComplete = false;
19
+ selection.coverage.uncoveredRows += selection.coverage.provenRows; selection.coverage.provenRows = 0; selection.coverage.scope = 'partial'; selection.coverage.basis = command === 'check' ? 'selected' : 'rendered';
20
+ for (const group of selection.frames) for (const row of group.rows) if (row.proof) { delete row.proof; row.disposition = 'unassessed'; row.unassessedReasons = ['incomplete_identity']; }
21
+ }
22
+ if (outcome?.data && 'verdict' in outcome.data) outcome.data.verdict = null;
23
+ }
24
+ try {
25
+ const plan = await impact(config, { base: options.base, json: true, 'state-dir': options['state-dir'], 'out-dir': options['out-dir'], explain: options.explain }, {
26
+ consume: async session => {
27
+ const { rows, views, assessments, inputs, data } = session;
28
+ const sources = await selectedSources(views[1].config, views[0].config, views[1].config.root, new Set(rows.map(row => row.source)), args);
29
+ const themes = options.theme && options.theme !== 'both' ? [options.theme] : ['light', 'dark'];
30
+ const chosen = rows.filter(row => sources.includes(row.source) && (options.frame === undefined || row.frame === options.frame));
31
+ if (options.frame !== undefined && !chosen.length) {
32
+ throw new CliError('FRAME_NOT_FOUND', `Unknown frame ${options.frame}; choose a frame present on either side.`);
33
+ }
34
+ const exclusions = { source_filter: 0, frame_filter: 0, theme_filter: 0, hypothetical_input: 0, not_checked: 0 };
35
+ for (const row of rows) for (const theme of ['light', 'dark']) {
36
+ if (!sources.includes(row.source)) exclusions.source_filter++;
37
+ else if (options.frame !== undefined && row.frame !== options.frame) exclusions.frame_filter++;
38
+ else if (!themes.includes(theme)) exclusions.theme_filter++;
39
+ }
40
+ selection = { query: data.query, facts: data.facts, frames: groupImpactFrames(data.frames.filter(frame => chosen.some(row => row.source === frame.ref.source && row.frame === frame.ref.frame))
41
+ .map(frame => ({ ...frame, themes: frame.themes.filter(row => themes.includes(row.theme)) })).filter(frame => frame.themes.length), { explain: !!options.explain }),
42
+ coverage: { scope: 'partial', basis: command === 'check' ? 'selected' : 'proven', expectedRows: rows.length * 2, renderedRows: 0,
43
+ provenRows: 0, uncoveredRows: 0, deletedRows: 0, exclusions, proofComplete: false }, timings: data.timings };
44
+ const usedFacts = new Set(selection.frames.flatMap(group => group.rows.flatMap(row => (row.reasons ?? []).map(reason => reason.fact))));
45
+ selection.facts = data.facts.filter(fact => usedFacts.has(fact.id));
46
+ const selected = new Set(chosen.flatMap(row => themes.map(theme => impactRowKey(row, theme))));
47
+ const scheduled = (row, theme) => selected.has(impactRowKey(row, theme)) && assessments.get(impactRowKey(row, theme)).disposition === 'render';
48
+ for (const row of chosen) for (const theme of themes) {
49
+ if (row.status === 'removed') selection.coverage.deletedRows++;
50
+ if (assessments.get(impactRowKey(row, theme)).disposition === 'proven_unaffected') {
51
+ if (command === 'check') exclusions.not_checked++;
52
+ else selection.coverage.provenRows++;
53
+ }
54
+ }
55
+ const finalize = data => {
56
+ const coverage = selection.coverage;
57
+ coverage.renderedRows = command === 'diff' ? data.summary.comparisons + data.summary.supportComparisons : command === 'check' ? data.summary.evaluations : data.captures.length;
58
+ const deleted = command === 'render' ? coverage.deletedRows : 0;
59
+ coverage.uncoveredRows = Math.max(0, coverage.expectedRows - coverage.renderedRows - coverage.provenRows - deleted);
60
+ coverage.scope = !coverage.expectedRows ? 'empty' : coverage.uncoveredRows || args.length || options.frame !== undefined || themes.length !== 2 ? 'partial' : 'full';
61
+ coverage.basis = command === 'check' ? 'selected' : coverage.renderedRows ? coverage.provenRows ? 'rendered_and_proven' : 'rendered' : coverage.provenRows ? 'proven' : 'selected';
62
+ data.impact = selection;
63
+ };
64
+ const next = [{ argv: ['adg', command, ...(command === 'diff' ? [`--base=${options.base}`] : command === 'check' ? ['--read-only'] : []),
65
+ ...(options.scale !== undefined && command !== 'check' ? [`--scale=${options.scale}`] : []), '--json'], reason: 'Evaluate the full project without impact filtering.' }];
66
+ session.selection = selection; session.sources = sources; session.chosen = chosen; session.themes = themes; session.scheduled = scheduled;
67
+ session.diffInputs = { ...inputs.session, sources, close: async () => {},
68
+ buildFrames: async ({ browser }) => inputs.session.buildFrames({ browser, materialized: views.map(view => view.built),
69
+ frame: options.frame, sources: [...new Set(chosen.filter(row => themes.some(theme => scheduled(row, theme))).map(row => row.source))] }) };
70
+ const workStarted = performance.now();
71
+ try { outcome = await work(session); } catch (cause) { failure = cause; outcome = { data: cause.data, warnings: cause.warnings ?? [] }; }
72
+ workMs = performance.now() - workStarted;
73
+ if (outcome?.data) {
74
+ finalize(outcome.data);
75
+ if (selection.coverage.scope === 'partial') warnings.push({ code: 'IMPACT_COVERAGE_PARTIAL', message: 'Impact selection has partial frame/theme coverage.', next });
76
+ if (!failure && !chosen.some(row => (command === 'diff' || row.after) && themes.some(theme => scheduled(row, theme)))) warnings.push({ code: 'IMPACT_NO_CHANGES', message: 'No capture or browser-evaluation jobs were scheduled.', next });
77
+ }
78
+ if (failure && !['CHECK_FAILED', 'DIFF_FAILED'].includes(failure.code)) throw failure;
79
+ },
80
+ });
81
+ warnings.push(...plan.warnings.filter(w => !['IMPACT_NO_CHANGES', 'IMPACT_NO_MATCH'].includes(w.code)));
82
+ if (selection) selection.coverage.proofComplete = true;
83
+ if (outcome?.data) outcome.data.timings = { ...outcome.data.timings, impactMs: plan.data.timings.totalMs - workMs, workMs, materializeMs: plan.data.timings.materializeMs, proofMs: plan.data.timings.proofMs, totalMs: plan.data.timings.totalMs };
84
+ } catch (cause) {
85
+ discardProofs();
86
+ if (!outcome?.data) cause.data = null;
87
+ failure = outcome?.data ? commandFailure(cause, outcome.data, warnings) : cause;
88
+ }
89
+ if (outcome) outcome.warnings = [...new Set([...outcome.warnings, ...warnings])];
90
+ if (outcome?.data?.reportPath) {
91
+ try { await mkdir(path.dirname(outcome.data.reportPath), { recursive: true }); await writeFile(outcome.data.reportPath, JSON.stringify(outcome.data, null, 2) + '\n'); }
92
+ catch (cause) { discardProofs(); outcome.data.reportPath = null; failure = commandFailure(cause, outcome.data, outcome.warnings); }
93
+ }
94
+ if (failure) { if (outcome?.data) failure = commandFailure(failure, outcome.data, outcome.warnings); throw failure; }
95
+ return outcome;
96
+ }