@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.
- package/README.md +19 -3
- package/package.json +4 -1
- package/public/annotations.js +816 -0
- package/public/app.js +245 -12
- package/public/assets.js +4 -13
- package/public/frame-identity.js +223 -0
- package/public/icons.js +1 -0
- package/public/index.html +3 -0
- package/public/selection.js +1 -1
- package/public/style.css +72 -2
- package/src/annotations.mjs +238 -0
- package/src/cli-output.mjs +49 -2
- package/src/cli.mjs +83 -12
- package/src/http.mjs +2 -1
- package/src/hub/instances.mjs +1 -1
- package/src/hub/registry.mjs +1 -1
- package/src/hub.mjs +2 -2
- package/src/server.mjs +59 -11
- package/src/service.mjs +1 -1
- package/src/toolkit/arch-git.mjs +19 -0
- package/src/toolkit/arch-overlay.mjs +1 -1
- package/src/toolkit/asset-rules.mjs +42 -3
- package/src/toolkit/build-store.mjs +5 -3
- package/src/toolkit/build-worker.mjs +5 -2
- package/src/toolkit/build.mjs +36 -14
- package/src/toolkit/commands.mjs +85 -22
- package/src/toolkit/config.mjs +8 -6
- package/src/toolkit/diff-inputs.mjs +5 -5
- package/src/toolkit/diff.mjs +18 -11
- package/src/toolkit/document.mjs +6 -6
- package/src/toolkit/frame-document.mjs +6 -0
- package/src/toolkit/frame-facets.mjs +167 -0
- package/src/toolkit/frame-identity.mjs +100 -0
- package/src/toolkit/frame-observation.mjs +147 -0
- package/src/toolkit/frame-primitives.mjs +85 -0
- package/src/toolkit/html.mjs +1 -0
- package/src/toolkit/impact-eligibility.mjs +136 -0
- package/src/toolkit/impact-inputs.mjs +52 -0
- package/src/toolkit/impact-output.mjs +46 -0
- package/src/toolkit/impact-proof.mjs +67 -0
- package/src/toolkit/impact-selection.mjs +96 -0
- package/src/toolkit/impact.mjs +382 -0
- package/src/toolkit/implementation-query.mjs +53 -0
- package/src/toolkit/input-generation.mjs +51 -0
- package/src/toolkit/inspect-encoding.mjs +459 -0
- package/src/toolkit/inspect-observation.mjs +56 -0
- package/src/toolkit/inspect-output.mjs +169 -0
- package/src/toolkit/inspect-styles.mjs +34 -0
- package/src/toolkit/inspect.d.ts +118 -0
- package/src/toolkit/inspect.mjs +125 -0
- package/src/toolkit/owner-observation.mjs +23 -189
- package/src/toolkit/owner-search.mjs +2 -2
- package/src/toolkit/owner.mjs +37 -45
- package/src/toolkit/part-diff.mjs +2 -0
- package/src/toolkit/part-snapshot.mjs +15 -23
- package/src/toolkit/project-index.mjs +100 -22
- package/src/toolkit/project.mjs +52 -6
- package/src/toolkit/results.mjs +2 -2
- package/src/toolkit/runtime.d.ts +7 -5
- package/src/toolkit/runtime.mjs +20 -7
- package/src/toolkit/token-reachability.mjs +71 -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
|
+
}
|
|
@@ -0,0 +1,382 @@
|
|
|
1
|
+
import path from 'node:path';
|
|
2
|
+
import { readFile, realpath, stat } from 'node:fs/promises';
|
|
3
|
+
import { CliError, nextActions } from '../cli-output.mjs';
|
|
4
|
+
import { openProjectIndex } from './project-index.mjs';
|
|
5
|
+
import { prepareImpactInputs, configInputFiles } from './impact-inputs.mjs';
|
|
6
|
+
import { matchDiffFrames } from './diff-inputs.mjs';
|
|
7
|
+
import { selectSources, relative } from './project.mjs';
|
|
8
|
+
import { loadImplementationMap, implementationFiles } from './implementation-map.mjs';
|
|
9
|
+
import { normalizeFileQuery, implementationScope } from './implementation-query.mjs';
|
|
10
|
+
import { selectorMatches } from './owner-locators.mjs';
|
|
11
|
+
import { relatedSources } from '../../public/relationships.js';
|
|
12
|
+
import { commandFailure, cleanup } from './results.mjs';
|
|
13
|
+
import { indexDigest } from './index-store.mjs';
|
|
14
|
+
import { groupImpactFrames, impactFrameCount } from './impact-output.mjs';
|
|
15
|
+
import { canonicalBytes, capturePolicy, entryProjection, equalEntryProof, architectureProjection, equalProof } from './impact-proof.mjs';
|
|
16
|
+
import { trackedHash, inputBytes as bytes, verifyInputGeneration } from './input-generation.mjs';
|
|
17
|
+
import { createEligibilityChecker } from './impact-eligibility.mjs';
|
|
18
|
+
|
|
19
|
+
const slash = name => name.split(path.sep).join('/');
|
|
20
|
+
const compare = (a, b) => a < b ? -1 : a > b ? 1 : 0;
|
|
21
|
+
const outside = name => name === '..' || name.startsWith('../') || path.isAbsolute(name);
|
|
22
|
+
const array = value => value === undefined ? [] : Array.isArray(value) ? value : [value];
|
|
23
|
+
const themesFor = values => values.theme && values.theme !== 'both' ? [values.theme] : ['light', 'dark'];
|
|
24
|
+
|
|
25
|
+
async function sourceInput(config, input, inventory) {
|
|
26
|
+
try { return relative(config, selectSources(config, [input], { write: false })[0]); }
|
|
27
|
+
catch (error) { if (error.code !== 'SOURCE_NOT_FOUND') throw error; }
|
|
28
|
+
for (const candidate of [path.resolve(config.root, input), path.resolve(config.design, input)]) {
|
|
29
|
+
let file, info;
|
|
30
|
+
try { file = await realpath(candidate); info = await stat(file); }
|
|
31
|
+
catch (error) { if (['ENOENT', 'ENOTDIR'].includes(error.code)) continue; throw error; }
|
|
32
|
+
const name = slash(path.relative(await realpath(config.root), file));
|
|
33
|
+
if (outside(name) || outside(slash(path.relative(await realpath(config.design), file)))) continue;
|
|
34
|
+
if (info.isFile() && !inventory.includes(name)) return name;
|
|
35
|
+
}
|
|
36
|
+
throw new CliError('SOURCE_NOT_FOUND', `Unknown design source/input ${input}; choose an existing source or design dependency.`);
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
function mappingBuild(facts) {
|
|
40
|
+
return { parts: facts.parts, frames: facts.frames.map(frame => ({ name: frame.name,
|
|
41
|
+
owners: frame.parts.map(part => ({ source: part.source, export: part.part })) })) };
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/** Candidate queries and operation-local fresh-input proofs for exact Git endpoints. */
|
|
45
|
+
export async function impact(config, values, { log = console.log, openIndex = openProjectIndex, prepareInputs = prepareImpactInputs, consume } = {}) {
|
|
46
|
+
const started = performance.now(), themes = themesFor(values);
|
|
47
|
+
const timings = { prepareMs: 0, indexMs: 0, materializeMs: 0, proofMs: 0, queryMs: 0, totalMs: 0 };
|
|
48
|
+
const timed = async (name, work) => { const start = performance.now(); try { return await work(); } finally { timings[name] += performance.now() - start; } };
|
|
49
|
+
let inputs, data, primary;
|
|
50
|
+
const views = [], warnings = [], tracked = new Map();
|
|
51
|
+
async function track(file) { if (!tracked.has(file)) tracked.set(file, trackedHash(await bytes(file))); }
|
|
52
|
+
const warn = (code, message, next = []) => { if (!warnings.some(warning => warning.code === code)) warnings.push({ code, message, next }); };
|
|
53
|
+
const checkNext = reason => [{ argv: ['adg', 'check', '--read-only', '--json'], reason }];
|
|
54
|
+
const verifyGeneration=()=>verifyInputGeneration({tracked,views,inputs});
|
|
55
|
+
|
|
56
|
+
try {
|
|
57
|
+
let query, fileInput;
|
|
58
|
+
await timed('prepareMs', async () => {
|
|
59
|
+
if (values.base !== undefined) { inputs = await prepareInputs(config, values); query = inputs.query; warnings.push(...inputs.warnings); }
|
|
60
|
+
else if (values.file !== undefined) {
|
|
61
|
+
fileInput = await normalizeFileQuery(config, values);
|
|
62
|
+
const { kind, input, normalized, pathKind, line, symbol } = fileInput.query;
|
|
63
|
+
query = { kind, input, normalized, pathKind, line, symbol };
|
|
64
|
+
} else if (values.token !== undefined) query = { kind: 'token', tokens: [...new Set(array(values.token))] };
|
|
65
|
+
else query = { kind: 'source', sources: [], part: values.part ?? null };
|
|
66
|
+
});
|
|
67
|
+
data = { project: config.root, complete: false, query,
|
|
68
|
+
before: inputs ? { kind: 'revision', sha: query.base.sha } : null,
|
|
69
|
+
after: { kind: inputs?.after.revision ? 'revision' : 'working_tree', sha: inputs?.head ?? null },
|
|
70
|
+
selection: { themes, explain: !!values.explain }, changes: [], facts: [], frames: [], mappingFindings: [], unresolvedInputs: [],
|
|
71
|
+
coverage: { inventory: 'incomplete', mapping: 'not_requested', expectedRows: 0, candidateRows: 0, directRows: 0, transitiveRows: 0,
|
|
72
|
+
renderRows: 0, provenRows: 0, unassessedRows: 0, proofComplete: false,
|
|
73
|
+
tokenScan: { reachableRows: 0, fullSheetRows: 0, fallbackReasons: [] } }, timings };
|
|
74
|
+
|
|
75
|
+
if (inputs && !inputs.after.revision) for (const change of inputs.changes) {
|
|
76
|
+
for (const name of [change.before, change.after].filter(Boolean)) await track(path.join(inputs.repository, name));
|
|
77
|
+
}
|
|
78
|
+
for (const [side, endpoint] of inputs ? [['before', inputs.before], ['after', inputs.after]] : [['after', { config, revision: null }]]) {
|
|
79
|
+
const view = await timed('indexMs', async () => {
|
|
80
|
+
const current = endpoint.config;
|
|
81
|
+
const index = await openIndex(current, { stateDirectory: values['state-dir'], persist: !inputs && !endpoint.revision, fresh: !!inputs,
|
|
82
|
+
artifactDirectory: side === 'after' && values['out-dir'] !== undefined ? path.resolve(current.root, values['out-dir']) : undefined });
|
|
83
|
+
const view = { side, config: current, index, facts: new Map(), built: new Map(), architecture: new Map(),
|
|
84
|
+
graph: null, routes: new Map(), tokens: null, map: null, configInputs: new Set(), resolved: canonicalBytes(current) };
|
|
85
|
+
views.push(view);
|
|
86
|
+
for (const file of await configInputFiles(current)) { await track(file); view.configInputs.add(slash(path.relative(await realpath(current.root), file))); }
|
|
87
|
+
for (const name of ['adg.config.mjs', 'adg.config.js', 'adg.config.ts']) await track(path.join(current.root, name));
|
|
88
|
+
view.tokenFile = path.join(current.design, 'tokens.css');
|
|
89
|
+
await track(view.tokenFile); view.tokenBytes = await bytes(view.tokenFile);
|
|
90
|
+
if (inputs) for (const source of index.inventory.tsx) await track(path.join(current.root, source));
|
|
91
|
+
return view;
|
|
92
|
+
});
|
|
93
|
+
const { index, config: current } = view;
|
|
94
|
+
if (inputs) await timed('materializeMs', async () => {
|
|
95
|
+
const settled = await Promise.allSettled(index.inventory.tsx.map(async source => [source, await index.materialize(source)]));
|
|
96
|
+
for (const result of settled) { if (result.status === 'rejected') throw result.reason; view.built.set(...result.value); }
|
|
97
|
+
});
|
|
98
|
+
await timed('indexMs', async () => {
|
|
99
|
+
for (const source of index.inventory.tsx) {
|
|
100
|
+
const facts = await index.source(source, { tokens: query.kind === 'token' || query.kind === 'git', fresh: !!inputs });
|
|
101
|
+
view.facts.set(source, facts);
|
|
102
|
+
for (const frame of facts.tokenDependencies ?? []) for (const row of frame.themes) if (themes.includes(row.theme)) {
|
|
103
|
+
const scan = data.coverage.tokenScan;
|
|
104
|
+
if (row.mode === 'reachable_declarations') scan.reachableRows++;
|
|
105
|
+
else scan.fullSheetRows++;
|
|
106
|
+
for (const reason of row.fallbackReasons) if (!scan.fallbackReasons.includes(reason)) scan.fallbackReasons.push(reason);
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
for (const source of index.inventory.architecture) {
|
|
110
|
+
const metadata = await index.architecture(source), file = path.join(current.root, source), sidecar = path.join(current.root, metadata.sidecar);
|
|
111
|
+
await track(file); await track(sidecar);
|
|
112
|
+
view.architecture.set(source, { source: await bytes(file), sidecar: await bytes(sidecar), tokens: view.tokenBytes, config: current });
|
|
113
|
+
view.facts.set(source, { source, parts: [], imports: [], dependencies: [source, metadata.sidecar, relative(current, view.tokenFile)], frames: [{ name: 'default', parts: [] }] });
|
|
114
|
+
}
|
|
115
|
+
view.graph = await index.relationships({ facts: view.facts, projectPaths: true });
|
|
116
|
+
view.tokens = view.facts.size || query.kind === 'token' ? index.tokens() : [];
|
|
117
|
+
if (query.kind === 'file' || query.kind === 'git') { view.map = await loadImplementationMap(current); await track(view.map.file); }
|
|
118
|
+
});
|
|
119
|
+
}
|
|
120
|
+
const scan = data.coverage.tokenScan;
|
|
121
|
+
scan.fallbackReasons.sort(compare);
|
|
122
|
+
if (scan.fullSheetRows) warn('IMPACT_TOKEN_FALLBACK', `Token scan used the full sheet for ${scan.fullSheetRows} frame/theme inputs: ${scan.fallbackReasons.join(', ')}.`,
|
|
123
|
+
checkNext('Repair the reported token syntax or unbalanced var() declaration, then repeat the impact query.'));
|
|
124
|
+
const current = views.at(-1), previous = inputs ? views[0] : null;
|
|
125
|
+
const allSources = [...new Set(views.flatMap(view => [...view.facts.keys()]))].sort(compare);
|
|
126
|
+
let rows;
|
|
127
|
+
if (inputs) {
|
|
128
|
+
const renames = inputs.changes.filter(change => change.status === 'renamed').map(change => ({
|
|
129
|
+
before: slash(path.relative(inputs.projectPrefix || '.', change.before)), after: slash(path.relative(inputs.projectPrefix || '.', change.after)) }));
|
|
130
|
+
rows = matchDiffFrames(allSources, previous.facts, current.facts, renames);
|
|
131
|
+
} else rows = allSources.flatMap(source => current.facts.get(source).frames.map(frame => ({ source, frame: frame.name, status: 'current', matchKind: null, matchCandidates: [], before: null, after: frame })));
|
|
132
|
+
data.coverage.expectedRows = rows.length * themes.length;
|
|
133
|
+
const eligibility = createEligibilityChecker();
|
|
134
|
+
const entryChecks = new Map(), projections = new Map();
|
|
135
|
+
const projection = (view, built, frame, theme, reach) => {
|
|
136
|
+
if (!projections.has(built)) projections.set(built, entryProjection(built, capturePolicy(view.config)));
|
|
137
|
+
return projections.get(built)(frame, theme, reach);
|
|
138
|
+
};
|
|
139
|
+
const eligible = (built, frame, theme) => {
|
|
140
|
+
if (!entryChecks.has(built)) entryChecks.set(built, eligibility.withCss(built.css.replace(/<\/style/gi, '<\\/style')));
|
|
141
|
+
return entryChecks.get(built)(frame.html);
|
|
142
|
+
};
|
|
143
|
+
const assessments = new Map();
|
|
144
|
+
const requiredParents = new Set(rows.filter(row => row.status === 'added' && row.after.parent).map(row => JSON.stringify([row.after.parent.source, row.after.parent.frame])));
|
|
145
|
+
const seeds = [], factKeys = new Map();
|
|
146
|
+
function seed(view, kind, source, { part = null, token = null, selectedThemes = themes, pathIndexes = [], pointer = null, frames = null } = {}) {
|
|
147
|
+
const key = JSON.stringify([kind, source, part, token, selectedThemes, pointer, pathIndexes]);
|
|
148
|
+
let fact = factKeys.get(key);
|
|
149
|
+
if (!fact) { fact = { id: `f${factKeys.size + 1}`, kind, source, part, token, themes: selectedThemes, sides: [], pathIndexes }; factKeys.set(key, fact); data.facts.push(fact); }
|
|
150
|
+
if (!fact.sides.includes(view.side)) fact.sides.push(view.side);
|
|
151
|
+
seeds.push({ view, fact, pointer, frames });
|
|
152
|
+
}
|
|
153
|
+
function unresolved(name, reason) { if (!data.unresolvedInputs.some(input => input.path === name && input.reason === reason)) data.unresolvedInputs.push({ path: name, reason, fallback: 'none' }); }
|
|
154
|
+
async function mappings(view, indices, pathIndexes = []) {
|
|
155
|
+
if (!view.map.present) { data.coverage.mapping = data.coverage.mapping === 'stale' ? 'stale' : 'absent'; unresolved(view.map.source, 'mapping_absent'); return; }
|
|
156
|
+
if (data.coverage.mapping === 'not_requested') data.coverage.mapping = 'valid';
|
|
157
|
+
const validated = await view.index.mappings({ map: view.map, mappingIndices: indices,
|
|
158
|
+
getBuild: source => {
|
|
159
|
+
const facts = view.facts.get(source);
|
|
160
|
+
// Mapping validators expect design-relative marker provenance.
|
|
161
|
+
const built = mappingBuild(facts);
|
|
162
|
+
for (const frame of built.frames) for (const owner of frame.owners) owner.source = slash(path.relative(view.config.design, path.join(view.config.root, owner.source)));
|
|
163
|
+
return built;
|
|
164
|
+
} });
|
|
165
|
+
for (const finding of validated.findings) {
|
|
166
|
+
const existing = data.mappingFindings.find(item => JSON.stringify({ ...item, sides: undefined }) === JSON.stringify(finding));
|
|
167
|
+
if (existing) { if (!existing.sides.includes(view.side)) existing.sides.push(view.side); }
|
|
168
|
+
else data.mappingFindings.push({ ...finding, sides: [view.side] });
|
|
169
|
+
}
|
|
170
|
+
if (validated.findings.length) data.coverage.mapping = 'stale';
|
|
171
|
+
for (const [file, hash] of Object.entries(validated.implementationHashes)) {
|
|
172
|
+
const name = path.join(view.config.root, file);
|
|
173
|
+
const contents = await bytes(name), fingerprint = trackedHash(contents);
|
|
174
|
+
if (contents === null || indexDigest(contents) !== hash || tracked.has(name) && tracked.get(name) !== fingerprint) throw new CliError('IMPACT_INPUT_CHANGED', `Implementation input changed during query: ${name}.`);
|
|
175
|
+
tracked.set(name, fingerprint);
|
|
176
|
+
}
|
|
177
|
+
for (const binding of validated.bindings) {
|
|
178
|
+
const target = binding.design, facts = view.facts.get(target.source);
|
|
179
|
+
if (!facts) continue;
|
|
180
|
+
// A stale locator does not erase the resolvable declared source/part scope.
|
|
181
|
+
const part = target.part && facts.parts.includes(target.part) ? target.part : null;
|
|
182
|
+
const boundFrames = (target.frames ?? binding.frames).filter(name => facts.frames.some(frame => frame.name === name));
|
|
183
|
+
seed(view, 'mapping', target.source, { part, frames: boundFrames, pointer: binding.pointer, pathIndexes });
|
|
184
|
+
}
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
const proofBeforeQuery = timings.proofMs;
|
|
188
|
+
await timed('queryMs', async () => {
|
|
189
|
+
if (query.kind === 'source') {
|
|
190
|
+
for (const input of array(values.source)) {
|
|
191
|
+
const source = await sourceInput(config, input, allSources); if (!query.sources.includes(source)) query.sources.push(source);
|
|
192
|
+
}
|
|
193
|
+
if (query.part && (query.sources.length !== 1 || !current.facts.get(query.sources[0])?.parts.includes(query.part))) throw new CliError('IMPACT_INPUT_NOT_FOUND', `Unknown design part ${query.part}; choose a registered export in one TSX source.`);
|
|
194
|
+
for (const source of query.sources) { await track(path.join(config.root, source)); seed(current, query.part ? 'part' : 'source', source, { part: query.part }); }
|
|
195
|
+
} else if (query.kind === 'token') {
|
|
196
|
+
for (const token of query.tokens) {
|
|
197
|
+
if (!current.tokens.some(item => item.name === token)) throw new CliError('IMPACT_INPUT_NOT_FOUND', `Unknown token ${token}; choose a name declared in tokens.css.`);
|
|
198
|
+
seed(current, 'token', relative(config, path.join(config.design, 'tokens.css')), { token });
|
|
199
|
+
}
|
|
200
|
+
} else if (query.kind === 'file') {
|
|
201
|
+
const selector = { [query.pathKind === 'directory' ? 'directory' : query.pathKind === 'glob' ? 'glob' : 'file']: query.normalized };
|
|
202
|
+
const files = await implementationFiles(config, selector);
|
|
203
|
+
const { mappingIndices } = implementationScope(current.map, query, fileInput.text, files, { includeStale: true });
|
|
204
|
+
for (const file of files) { await track(path.join(config.root, file)); seed(current, 'implementation', file); }
|
|
205
|
+
await mappings(current, mappingIndices);
|
|
206
|
+
if (!mappingIndices.size) unresolved(query.normalized, 'mapping_unmatched');
|
|
207
|
+
} else {
|
|
208
|
+
const knownDependencies = new Set(views.flatMap(view => [...view.facts.values()].flatMap(facts => facts.dependencies)));
|
|
209
|
+
const mapMatches = name => views.some(view => view.map.mappings.some(mapping => selectorMatches(mapping.implementation, name)));
|
|
210
|
+
for (const change of inputs.changes) {
|
|
211
|
+
const names = [change.before, change.after].filter(Boolean).map(name => slash(path.relative(inputs.projectPrefix || '.', name)));
|
|
212
|
+
const is = predicate => names.some(predicate);
|
|
213
|
+
let role;
|
|
214
|
+
if (is(name => views.some(view => relative(view.config, path.join(view.config.design, 'tokens.css')) === name))) role = 'token';
|
|
215
|
+
else if (is(name => views.some(view => view.map.source === name))) role = 'mapping';
|
|
216
|
+
else if (is(name => views.some(view => view.configInputs.has(name)))) role = 'config';
|
|
217
|
+
else if (is(name => /(?:^|\/)(?:package\.json|package-lock\.json|npm-shrinkwrap\.json|pnpm-lock\.yaml|yarn\.lock|bun\.lockb?)$/.test(name))) role = 'environment';
|
|
218
|
+
else if (names.every(outside)) role = 'outside_design_inputs';
|
|
219
|
+
else if (is(name => views.some(view => view.index.inventory.architecture.includes(name) || view.index.inventory.architecture.includes(name.replace(/\.md$/, '.mmd'))))) role = 'architecture';
|
|
220
|
+
else if (is(name => knownDependencies.has(name) && name.endsWith('.css'))) role = 'global_css';
|
|
221
|
+
else if (is(name => allSources.includes(name) || knownDependencies.has(name) || views.some(view => name.startsWith(relative(view.config, view.config.design) + '/')))) role = 'design';
|
|
222
|
+
else if (is(name => mapMatches(name) || /\.(?:[cm]?[jt]sx?|css|vue|svelte|rs|go|py|swift|c|h|cpp)$/.test(name))) role = 'implementation';
|
|
223
|
+
else if (is(name => /\.(?:md|txt|png|jpe?g|svg|webp)$/.test(name))) role = 'outside_design_inputs';
|
|
224
|
+
else role = 'unknown';
|
|
225
|
+
const pathIndex = data.changes.length; data.changes.push({ ...change, role });
|
|
226
|
+
if (!inputs.after.revision) for (const name of [change.before, change.after].filter(Boolean)) await track(path.join(inputs.repository, name));
|
|
227
|
+
for (const view of views) {
|
|
228
|
+
const repositoryName = view.side === 'before' ? change.before : change.after ?? (['implementation', 'mapping'].includes(role) ? change.before : null);
|
|
229
|
+
if (!repositoryName) continue;
|
|
230
|
+
const name = slash(path.relative(inputs.projectPrefix || '.', repositoryName)), options = { pathIndexes: [pathIndex] };
|
|
231
|
+
if (role === 'token') {
|
|
232
|
+
const other = view === current ? previous : current;
|
|
233
|
+
for (const item of view.tokens) {
|
|
234
|
+
const selectedThemes = themes.filter(theme => item.values.find(value => value.theme === theme)?.declaration !== other.tokens.find(token => token.name === item.name)?.values.find(value => value.theme === theme)?.declaration);
|
|
235
|
+
if (selectedThemes.length) seed(view, 'token', name, { ...options, token: item.name, selectedThemes });
|
|
236
|
+
}
|
|
237
|
+
} else if (role === 'mapping') {
|
|
238
|
+
if (!current.map.present) { data.coverage.mapping = 'absent'; unresolved(current.map.source, 'mapping_absent'); }
|
|
239
|
+
const otherMap = (view === current ? previous : current).map;
|
|
240
|
+
const indices = new Set(view.map.mappings.flatMap((mapping, i) => otherMap.mappings.some(other => JSON.stringify(other) === JSON.stringify(mapping)) ? [] : [i]));
|
|
241
|
+
await mappings(view, indices, [pathIndex]);
|
|
242
|
+
} else if (role === 'implementation') {
|
|
243
|
+
seed(view, 'implementation', name, options);
|
|
244
|
+
const indices = new Set(view.map.mappings.flatMap((mapping, i) => names.some(candidate => selectorMatches(mapping.implementation, candidate)) ? [i] : []));
|
|
245
|
+
await mappings(view, indices, [pathIndex]);
|
|
246
|
+
if (!indices.size) unresolved(name, 'mapping_unmatched');
|
|
247
|
+
} else if (role === 'architecture') seed(view, 'architecture', name.endsWith('.md') ? name.replace(/\.md$/, '.mmd') : name, options);
|
|
248
|
+
else if (role !== 'outside_design_inputs') seed(view, role === 'design' ? 'source' : role, outside(name) ? null : name, options);
|
|
249
|
+
}
|
|
250
|
+
}
|
|
251
|
+
}
|
|
252
|
+
|
|
253
|
+
for (const row of rows) {
|
|
254
|
+
const frame = { ref: { source: row.source, frame: row.frame }, status: row.status, matchKind: row.matchKind, matchCandidates: row.matchCandidates, themes: [] };
|
|
255
|
+
for (const theme of themes) {
|
|
256
|
+
const reasons = new Map();
|
|
257
|
+
function add(seed, kind, scope, witness, count = 1) {
|
|
258
|
+
const key = JSON.stringify([seed.fact.id, kind, scope]);
|
|
259
|
+
let reason = reasons.get(key);
|
|
260
|
+
if (!reason) { reason = { fact: seed.fact.id, class: kind, scope, sides: [], count: 0, ...(values.explain ? { witness } : {}) }; reasons.set(key, reason); }
|
|
261
|
+
if (!reason.sides.includes(seed.view.side)) { reason.sides.push(seed.view.side); reason.count += count; }
|
|
262
|
+
}
|
|
263
|
+
for (const item of seeds) {
|
|
264
|
+
if (!item.fact.themes.includes(theme)) continue;
|
|
265
|
+
const facts = item.view.facts.get(row.source), declared = facts?.frames.find(frame => frame.name === row.frame);
|
|
266
|
+
if (!declared) continue;
|
|
267
|
+
const { kind, source, part, token } = item.fact;
|
|
268
|
+
const witness = { origin: 'build', source, part, token, via: [], mappingPointer: item.pointer };
|
|
269
|
+
if (['config', 'global_css', 'environment', 'unknown'].includes(kind)) { add(item, kind === 'unknown' ? 'unknown' : 'global', 'global', witness); continue; }
|
|
270
|
+
if (kind === 'token') {
|
|
271
|
+
const reach = facts.tokenDependencies?.find(value => value.frame === row.frame)?.themes.find(value => value.theme === theme);
|
|
272
|
+
if (reach?.names.includes(token)) add(item, 'token_dependency', 'transitive', { ...witness, origin: 'lexical', via: reach.via[token] ?? [] });
|
|
273
|
+
else if (facts.source.endsWith('.mmd')) add(item, 'dependency', 'transitive', witness);
|
|
274
|
+
continue;
|
|
275
|
+
}
|
|
276
|
+
const direct = row.source === source;
|
|
277
|
+
if (direct || facts.dependencies.includes(source)) {
|
|
278
|
+
if (values.explain && !direct && !item.view.routes.has(source)) item.view.routes.set(source, new Map(relatedSources(item.view.graph, source, 'usedBy').map(value => [value.path, value.via])));
|
|
279
|
+
const route = values.explain && !direct ? item.view.routes.get(source)?.get(row.source) ?? [] : [];
|
|
280
|
+
add(item, 'dependency', direct ? 'direct' : 'transitive', { ...witness, via: route });
|
|
281
|
+
}
|
|
282
|
+
const occurrences = declared.parts.filter(owner => owner.source === source && (!part || owner.part === part));
|
|
283
|
+
if (occurrences.length) add(item, 'part_occurrence', direct ? 'direct' : 'transitive', { ...witness, origin: 'emitted', part: occurrences[0].part }, occurrences.length);
|
|
284
|
+
if (kind === 'mapping' && direct && item.frames.includes(row.frame)) add(item, 'mapping', 'declared', { ...witness, origin: 'declaration' });
|
|
285
|
+
}
|
|
286
|
+
if (inputs && ['added', 'removed'].includes(row.status)) {
|
|
287
|
+
const view = row.status === 'added' ? current : previous;
|
|
288
|
+
let lifecycle = seeds.find(seed => seed.view === view && seed.fact.source === row.source);
|
|
289
|
+
if (!lifecycle) { seed(view, row.source.endsWith('.mmd') ? 'architecture' : 'source', row.source); lifecycle = seeds.at(-1); }
|
|
290
|
+
add(lifecycle, 'lifecycle', 'direct', { origin: 'build', source: row.source, part: null, token: null, via: [], mappingPointer: null });
|
|
291
|
+
}
|
|
292
|
+
if (inputs && requiredParents.has(JSON.stringify([row.source, row.frame]))) {
|
|
293
|
+
const child = rows.find(child => child.status === 'added' && child.after.parent?.source === row.source && child.after.parent.frame === row.frame);
|
|
294
|
+
let support = seeds.find(seed => seed.view === current && seed.fact.source === child.source);
|
|
295
|
+
if (!support) { seed(current, 'source', child.source); support = seeds.at(-1); }
|
|
296
|
+
add(support, 'dependency', 'support', { origin: 'build', source: child.source, part: null, token: null, via: [], mappingPointer: null });
|
|
297
|
+
}
|
|
298
|
+
const ordered = [...reasons.values()].sort((a, b) => compare(a.fact, b.fact) || compare(a.class, b.class) || compare(a.scope, b.scope));
|
|
299
|
+
if (reasons.size) {
|
|
300
|
+
data.coverage.candidateRows++;
|
|
301
|
+
if (ordered.some(reason => reason.scope === 'direct')) data.coverage.directRows++;
|
|
302
|
+
if (ordered.some(reason => reason.scope === 'transitive')) data.coverage.transitiveRows++;
|
|
303
|
+
}
|
|
304
|
+
const result = { theme, candidate: !!reasons.size, disposition: 'render', reasons: ordered, proof: null, unassessedReasons: [] };
|
|
305
|
+
if (inputs) await timed('proofMs', async () => {
|
|
306
|
+
if (row.status !== 'matched' || row.matchKind !== 'exact') result.unassessedReasons = ['missing_side'];
|
|
307
|
+
else if (row.source.endsWith('.mmd')) {
|
|
308
|
+
const before = architectureProjection(previous.architecture.get(row.source)), after = architectureProjection(current.architecture.get(row.source));
|
|
309
|
+
result.proof = equalProof(before, after, 'architecture_inputs_equal', 'full_sheet', values.explain);
|
|
310
|
+
} else {
|
|
311
|
+
const builtBefore = previous.built.get(row.source), builtAfter = current.built.get(row.source);
|
|
312
|
+
const before = builtBefore.frames.find(frame => frame.name === row.frame), after = builtAfter.frames.find(frame => frame.name === row.frame);
|
|
313
|
+
result.unassessedReasons = [...new Set([...eligible(builtBefore, before, theme), ...eligible(builtAfter, after, theme)])].sort(compare);
|
|
314
|
+
if (!result.unassessedReasons.length) {
|
|
315
|
+
const reach = (view, frame) => view.facts.get(row.source).tokenDependencies.find(item => item.frame === frame.name).themes.find(item => item.theme === theme);
|
|
316
|
+
const left = projection(previous, builtBefore, before, theme, reach(previous, before));
|
|
317
|
+
const right = projection(current, builtAfter, after, theme, reach(current, after));
|
|
318
|
+
result.proof = equalEntryProof(left, right, values.explain);
|
|
319
|
+
}
|
|
320
|
+
}
|
|
321
|
+
if (result.proof && !requiredParents.has(JSON.stringify([row.source, row.frame]))) result.disposition = 'proven_unaffected';
|
|
322
|
+
else result.proof = null;
|
|
323
|
+
});
|
|
324
|
+
if (inputs) {
|
|
325
|
+
if (result.disposition === 'proven_unaffected') data.coverage.provenRows++;
|
|
326
|
+
else data.coverage.renderRows++;
|
|
327
|
+
} else if (reasons.size) data.coverage.renderRows++;
|
|
328
|
+
else { result.disposition = 'unassessed'; data.coverage.unassessedRows++; }
|
|
329
|
+
assessments.set(JSON.stringify([row.source, row.frame, theme]), result);
|
|
330
|
+
if (result.candidate || result.disposition === 'render') frame.themes.push(result);
|
|
331
|
+
}
|
|
332
|
+
if (frame.themes.length) data.frames.push(frame);
|
|
333
|
+
}
|
|
334
|
+
});
|
|
335
|
+
timings.queryMs = Math.max(0, timings.queryMs - (timings.proofMs - proofBeforeQuery));
|
|
336
|
+
data.coverage.inventory = 'complete';
|
|
337
|
+
if (data.unresolvedInputs.length || data.mappingFindings.length) warn('IMPACT_MAPPING_INCOMPLETE', 'Some implementation mappings are absent, unmatched or stale; inspect the resolvable targets and findings.', checkNext('Repair implementation.json and its reported locators before repeating the query.'));
|
|
338
|
+
if (!data.frames.length) {
|
|
339
|
+
const observed = query.kind === 'token' ? { token: query.tokens[0], theme: values.theme } : query.kind === 'file' ? { file: query.input, theme: values.theme } : null;
|
|
340
|
+
warn(query.kind === 'git' ? 'IMPACT_NO_CHANGES' : 'IMPACT_NO_MATCH', 'No frame candidates matched the changed design facts.',
|
|
341
|
+
query.kind === 'git' ? [] : observed ? nextActions('OWNER_UNSETTLED', { command: 'owner', values: observed }) : checkNext('Inspect design inputs and emitted part coverage.'));
|
|
342
|
+
}
|
|
343
|
+
|
|
344
|
+
if (consume) await consume({ views, rows, assessments, inputs, data });
|
|
345
|
+
} catch (cause) {
|
|
346
|
+
if (inputs) { try { await verifyGeneration(); } catch (changed) { cause = changed; } }
|
|
347
|
+
if (cause.code === 'OWNER_INDEX_CHANGED') cause = new CliError('IMPACT_INPUT_CHANGED', cause.message, { cause });
|
|
348
|
+
if (inputs) { cause.message = inputs.translate(cause.message); if (cause.context) cause.context = inputs.translate(cause.context); }
|
|
349
|
+
primary = data ? commandFailure(cause, data, warnings) : cause;
|
|
350
|
+
} finally {
|
|
351
|
+
for (const view of [...views].reverse()) {
|
|
352
|
+
try { await cleanup(() => view.index.close(), primary); } catch (cause) { primary = data ? commandFailure(cause, data, warnings) : cause; }
|
|
353
|
+
}
|
|
354
|
+
if (!primary) {
|
|
355
|
+
try { await verifyGeneration(); data.coverage.proofComplete = !!inputs; }
|
|
356
|
+
catch (cause) {
|
|
357
|
+
if (cause.code === 'OWNER_INDEX_CHANGED') cause = new CliError('IMPACT_INPUT_CHANGED', cause.message, { cause });
|
|
358
|
+
if (inputs) cause.message = inputs.translate(cause.message);
|
|
359
|
+
primary = data ? commandFailure(cause, data, warnings) : cause;
|
|
360
|
+
}
|
|
361
|
+
}
|
|
362
|
+
try { await cleanup(() => inputs?.close(), primary); } catch (cause) { primary = data ? commandFailure(cause, data, warnings) : cause; }
|
|
363
|
+
}
|
|
364
|
+
|
|
365
|
+
timings.totalMs = performance.now() - started;
|
|
366
|
+
if (primary && data) {
|
|
367
|
+
data.coverage.proofComplete = false;
|
|
368
|
+
data.coverage.unassessedRows += data.coverage.provenRows; data.coverage.provenRows = 0;
|
|
369
|
+
for (const frame of data.frames) for (const row of frame.themes) if (row.proof) {
|
|
370
|
+
row.proof = null; row.disposition = 'unassessed'; row.unassessedReasons = ['incomplete_identity'];
|
|
371
|
+
}
|
|
372
|
+
}
|
|
373
|
+
if (data) data.frames = groupImpactFrames(data.frames, { explain: !!values.explain });
|
|
374
|
+
if (primary) throw primary;
|
|
375
|
+
data.complete = true;
|
|
376
|
+
if (!values.json) {
|
|
377
|
+
log(`${impactFrameCount(data.frames)} listed frames; ${data.coverage.candidateRows} theme rows; ${data.coverage.unassessedRows} unassessed. ${data.coverage.provenRows} proven.`);
|
|
378
|
+
for (const group of data.frames) log(`${group.source}#${group.frames.join(', ')} [${group.rows.flatMap(row => row.themes).join(',')}] ${[...new Set(group.rows.flatMap(row => (row.reasons ?? []).map(reason => reason.class)))].join(', ')}`);
|
|
379
|
+
for (const warning of warnings) log(`${warning.code}: ${warning.message}`);
|
|
380
|
+
}
|
|
381
|
+
return { data, warnings };
|
|
382
|
+
}
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
import { readFile, realpath, stat } from 'node:fs/promises';
|
|
2
|
+
import path from 'node:path';
|
|
3
|
+
import { CliError } from '../cli-output.mjs';
|
|
4
|
+
import { portablePath, selectorMatches, resolveLocator, symbolRegions, regionAt, sourceLineCount } from './owner-locators.mjs';
|
|
5
|
+
|
|
6
|
+
export async function normalizeFileQuery(config, values) {
|
|
7
|
+
const root = await realpath(config.root), input = values.file;
|
|
8
|
+
if (typeof input !== 'string' || !input.trim()) throw new CliError('USAGE_INVALID', 'Set one nonempty --file input.');
|
|
9
|
+
let absolute = path.resolve(root, input);
|
|
10
|
+
if (path.isAbsolute(input) && !/[?*]/.test(input)) {
|
|
11
|
+
try { absolute = await realpath(input); } catch (error) { if (!['ENOENT', 'ENOTDIR'].includes(error.code)) throw error; throw new CliError('OWNER_INPUT_NOT_FOUND', 'Ownership input does not name an existing file or directory.'); }
|
|
12
|
+
}
|
|
13
|
+
const relative = path.relative(root, absolute).split(path.sep).join('/');
|
|
14
|
+
if (relative === '..' || relative.startsWith('../') || path.isAbsolute(relative)) throw new CliError('USAGE_INVALID', 'Ownership input must stay inside the project root.');
|
|
15
|
+
let pathKind, normalized = relative;
|
|
16
|
+
if (/[?*]/.test(relative)) {
|
|
17
|
+
if (!portablePath(relative, { glob: true })) throw new CliError('USAGE_INVALID', 'Use a POSIX glob with *, ? and whole-segment **.');
|
|
18
|
+
pathKind = 'glob';
|
|
19
|
+
} else {
|
|
20
|
+
let info;
|
|
21
|
+
try { info = await stat(absolute); } catch (error) { if (!['ENOENT', 'ENOTDIR'].includes(error.code)) throw error; throw new CliError('OWNER_INPUT_NOT_FOUND', 'Ownership input does not name an existing file or directory.'); }
|
|
22
|
+
const physical = path.relative(root, await realpath(absolute));
|
|
23
|
+
if (physical === '..' || physical.startsWith('..' + path.sep) || path.isAbsolute(physical)) throw new CliError('USAGE_INVALID', 'Ownership input resolves outside the project root.');
|
|
24
|
+
if (!info.isFile() && !info.isDirectory()) throw new CliError('USAGE_INVALID', 'Choose a regular implementation file or directory.');
|
|
25
|
+
pathKind = info.isDirectory() ? 'directory' : 'file';
|
|
26
|
+
if (pathKind === 'directory') normalized = relative ? relative + '/' : './';
|
|
27
|
+
}
|
|
28
|
+
const line = values.line === undefined ? null : Number(values.line), symbol = values.symbol ?? null;
|
|
29
|
+
if ((line !== null || symbol !== null) && pathKind !== 'file') throw new CliError('USAGE_INVALID', '--line and --symbol require a single file.');
|
|
30
|
+
const text = line !== null || symbol !== null ? await readFile(absolute, 'utf8') : null;
|
|
31
|
+
if (line !== null && (!Number.isSafeInteger(line) || line < 1 || line > sourceLineCount(text))) throw new CliError('USAGE_INVALID', '--line must name an existing 1-based line in the implementation file.');
|
|
32
|
+
if (values.theme !== undefined && !['both', 'light', 'dark'].includes(values.theme)) throw new CliError('USAGE_INVALID', 'Use --theme=both, light or dark.');
|
|
33
|
+
return { query: { kind: 'file', input, normalized, pathKind, line, symbol, contains: false, locale: null, themes: !values.theme || values.theme === 'both' ? ['light', 'dark'] : [values.theme], rgba: null }, text };
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
/** Reuse owner's exact file/symbol/region scoping without starting its collector. */
|
|
38
|
+
export function implementationScope(map, query, text, files, { includeStale = false } = {}) {
|
|
39
|
+
const selectors = map.mappings.map(mapping => mapping.implementation).filter(s => s.file === query.normalized && s.symbol);
|
|
40
|
+
const region = text === null ? null : regionAt(symbolRegions(text, query.normalized, selectors), query.line ?? 1);
|
|
41
|
+
const mappingIndices = new Set();
|
|
42
|
+
map.mappings.forEach((mapping, i) => {
|
|
43
|
+
const s = mapping.implementation;
|
|
44
|
+
if (!files.some(file => selectorMatches(s, file))) return;
|
|
45
|
+
if (s.symbol && query.symbol !== null && s.symbol !== query.symbol) return;
|
|
46
|
+
if (s.symbol && query.line !== null) {
|
|
47
|
+
const locator = resolveLocator(text, s);
|
|
48
|
+
if (!(includeStale && locator.stale) && (region?.line !== locator.line || !region?.mapped.includes(s.symbol))) return;
|
|
49
|
+
}
|
|
50
|
+
mappingIndices.add(i);
|
|
51
|
+
});
|
|
52
|
+
return { mappingIndices, region };
|
|
53
|
+
}
|