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