diff --git a/archify.zip b/archify.zip index b98a17cd87..fa3f2c9617 100644 Binary files a/archify.zip and b/archify.zip differ diff --git a/archify/modules/code-analysis/bin/serve.mjs b/archify/modules/code-analysis/bin/serve.mjs index afc7b818b2..afeb7328aa 100644 --- a/archify/modules/code-analysis/bin/serve.mjs +++ b/archify/modules/code-analysis/bin/serve.mjs @@ -436,14 +436,15 @@ function client(token, messages, makeTranslator, standalone, entryCss) { }; // Re-analysis: the server runs a new analysis; the page then reloads and opens it, // which re-mounts the layer cleanly instead of patching a live one. - window.__archifyReanalyze = async function () { + window.__archifyReanalyze = async function (reading) { var response = await fetch('/analyze', { method: 'POST', headers: { 'X-Analysis-Token': token, 'X-Analysis-Refresh': '1' } }); if (!response.ok) { var body = {}; try { body = await response.json(); } catch (e) { /* not JSON */ } throw new Error(body.error || tr("analysis failed")); } - location.replace(location.pathname + '?analysis=open'); + history.replaceState({ analysisRefresh: { token: token, reading: reading } }, '', location.pathname); + location.reload(); }; button.addEventListener('click', async function () { button.disabled = true; button.setAttribute('aria-busy', 'true'); setLabel(tr("Analyzing…")); say(tr("Reading the repository — imports, modules, rules.")); @@ -480,13 +481,16 @@ function client(token, messages, makeTranslator, standalone, entryCss) { if (toggle && document.documentElement.getAttribute('data-bauify') !== 'on') toggle.click(); var params = new URLSearchParams(location.search), selectedFinding = params.get('finding'); if (selectedFinding && window.__archifyShowFinding) window.__archifyShowFinding(selectedFinding, params.get('from') === 'findings' ? 'findings' : 'summary'); - if (location.search) history.replaceState(null, '', location.pathname); + if (refreshReading) window.__archifyRestoreReading?.(refreshReading); + if (location.search || refreshReading) history.replaceState(null, '', location.pathname); } catch (error) { button.disabled = false; button.removeAttribute('aria-busy'); setLabel(tr("Code Analysis")); say(tr("Analysis failed: ") + error.message + tr(" — click Code Analysis to retry.")); } }); - if (standalone || new URLSearchParams(location.search).get('analysis') === 'open') button.click(); + var savedRefresh = history.state?.analysisRefresh; + var refreshReading = savedRefresh?.token === token && savedRefresh.reading; + if (standalone || refreshReading || new URLSearchParams(location.search).get('analysis') === 'open') button.click(); } if (process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.meta.url)) { diff --git a/archify/modules/code-analysis/overlay/atlas.mjs b/archify/modules/code-analysis/overlay/atlas.mjs index 05dcd2d0f6..f04d79bbc3 100644 --- a/archify/modules/code-analysis/overlay/atlas.mjs +++ b/archify/modules/code-analysis/overlay/atlas.mjs @@ -20,9 +20,58 @@ // coupling; the side panel states the unresolved counts. Source text stays in // the Classic view, which the Atlas links to for any finding's evidence. import fs from 'node:fs'; +import { createHash } from 'node:crypto'; +import { createRequire } from 'node:module'; import { clientAsset } from './client-assets.mjs'; const compareText = (a, b) => (a < b ? -1 : a > b ? 1 : 0); +const require = createRequire(import.meta.url); + +// A function expression's measured range does not include its binding. Only +// accept a uniquely bound top-level anonymous expression whose captured range +// still matches the parsed source; otherwise its apparent name may be local +// to the expression or ambiguous across scopes. +function boundExpressions(facts) { + const wanted = new Set((facts.functions || []).filter(fn => fn.syntaxKind === 'FunctionExpression').map(fn => fn.file)); + const result = new Map(); + if (!wanted.size) return result; + const ts = require('../vendor/typescript.cjs'); + for (const file of facts.files || []) { + if (!wanted.has(file.path) || typeof file.sourceText !== 'string') continue; + const source = ts.createSourceFile(file.path, file.sourceText, ts.ScriptTarget.Latest, true); + if (source.parseDiagnostics.length) continue; + const declarations = new Map(), expressions = [], pending = [source]; + while (pending.length) { + const node = pending.pop(); + if (ts.isVariableDeclaration(node) && ts.isIdentifier(node.name)) { + const name = node.name.text; + declarations.set(name, (declarations.get(name) || 0) + 1); + let init = node.initializer; + while (init && (ts.isParenthesizedExpression(init) || ts.isAsExpression(init) || ts.isSatisfiesExpression?.(init) || ts.isTypeAssertionExpression(init))) init = init.expression; + if (init && ts.isFunctionExpression(init) && !init.name && node.parent?.parent?.parent === source) expressions.push({ name, init }); + } + ts.forEachChild(node, child => { pending.push(child); }); + } + for (const { name, init } of expressions) { + if (declarations.get(name) !== 1) continue; + const start = init.getStart(source), end = init.getEnd(), pos = source.getLineAndCharacterOfPosition(start); + const digest = createHash('sha256').update(file.sourceText.slice(start, end)).digest('hex'); + result.set(`${file.path}\0${pos.line + 1}\0${pos.character + 1}`, { name, digest }); + } + } + return result; +} + +function stableFunctionName(fn, expressions) { + if (fn.syntaxKind === 'FunctionExpression') { + const binding = expressions.get(`${fn.file}\0${fn.line}\0${fn.sourceRange?.column}`); + if (!binding || binding.name !== fn.name || binding.digest !== fn.sourceRange?.sha256) return false; + } + const name = fn.qualname || fn.name; + const owner = /^(?:MethodDeclaration|GetAccessor|SetAccessor)$/.test(fn.syntaxKind || '') && fn.name && name.endsWith(fn.name) + ? name.slice(0, -fn.name.length) : name; + return !/<(?:callback of |anonymous(?:#\d+)?>|(?:static|instance) initializer>)/.test(owner); +} // Shortest unambiguous label for each module: the fewest trailing path // segments that no other module shares (`executor`, `cache/decorators`). @@ -100,6 +149,10 @@ export function buildAtlas({ graph, facts, findings = [], review = null }) { const accepted = new Set(Object.entries(review?.findings || {}).filter(([, r]) => r.status === 'accepted').map(([id]) => id)); const listed = []; + // A qualified name can identify multiple declarations in the same file. + // Link only a unique finding and function with the same declaration range. + const functionKey = (file, name, line, endLine) => file && name && Number.isInteger(line) && Number.isInteger(endLine) && endLine >= line + ? JSON.stringify([file, name, line, endLine]) : null; const functionFinding = new Map(); for (const f of findings) { const s = f.subject || {}; @@ -113,7 +166,8 @@ export function buildAtlas({ graph, facts, findings = [], review = null }) { } } else if (f.code === 'complexity/function' && fileIndex.has(s.file)) { entry.kind = 'function'; - functionFinding.set(`${s.file}\u0000${s.function}`, listed.length); + const key = functionKey(s.file, s.function, s.line, s.endLine); + if (key) functionFinding.set(key, functionFinding.has(key) ? -1 : listed.length); } else if (f.code === 'coupling/import-cycle' && Array.isArray(s.files)) { entry.kind = 'cycle'; entry.files = s.files.filter((p) => fileIndex.has(p)).map((p) => fileIndex.get(p)); @@ -147,11 +201,22 @@ export function buildAtlas({ graph, facts, findings = [], review = null }) { } // [file, name, line, complexity, nesting, length, finding index or -1] + const expressions = boundExpressions(facts); + const functionCounts = new Map(); + for (const fn of facts.functions || []) { + const key = functionKey(fn.file, fn.qualname || fn.name, fn.line, fn.endLine); + if (key) functionCounts.set(key, (functionCounts.get(key) || 0) + 1); + } const functions = (facts.functions || []) .filter((fn) => fileIndex.has(fn.file)) .map((fn) => [fileIndex.get(fn.file), fn.qualname || fn.name, fn.line, fn.complexity, fn.nesting ?? 0, (fn.endLine ?? fn.line) - fn.line + 1, - functionFinding.has(`${fn.file}\u0000${fn.qualname}`) ? functionFinding.get(`${fn.file}\u0000${fn.qualname}`) : -1, - fn.sourceRange ? { column: fn.sourceRange.column, endLine: fn.sourceRange.endLine, endColumn: fn.sourceRange.endColumn } : null]) + functionCounts.get(functionKey(fn.file, fn.qualname || fn.name, fn.line, fn.endLine)) === 1 + ? functionFinding.get(functionKey(fn.file, fn.qualname || fn.name, fn.line, fn.endLine)) ?? -1 : -1, + fn.sourceRange ? { column: fn.sourceRange.column, endLine: fn.sourceRange.endLine, endColumn: fn.sourceRange.endColumn } : null, + fn.definition ? fn.definition.sourceRange?.sha256 || null : fn.sourceRange?.sha256 || null, + // Display names of callbacks and Java anonymous owners are numbered by + // source order. A quoted JS method named is a real name. + stableFunctionName(fn, expressions)]) .sort((a, b) => a[0] - b[0] || a[2] - b[2] || compareText(a[1], b[1])); for (const [i, fn] of functions.entries()) if (fn[6] !== -1) listed[fn[6]].fn = i; @@ -159,7 +224,7 @@ export function buildAtlas({ graph, facts, findings = [], review = null }) { return { language: facts.repository?.language ?? null, measured: Array.isArray(facts.functions), - modules: modules.map((m, i) => ({ id: m.id, label: labels[i], path: m.path, fanIn: m.fanIn, fanOut: m.fanOut })), + modules: modules.map((m, i) => ({ id: m.id, label: labels[i], path: m.path, rootGroup: m.path === '' && m.label === '(root)', fanIn: m.fanIn, fanOut: m.fanOut })), files: files.map((f) => [f.path, f.module, f.loc]), edges, functions, diff --git a/archify/modules/code-analysis/overlay/client/atlas.js b/archify/modules/code-analysis/overlay/client/atlas.js index ccaafb88d4..3a0510d8ba 100644 --- a/archify/modules/code-analysis/overlay/client/atlas.js +++ b/archify/modules/code-analysis/overlay/client/atlas.js @@ -1108,6 +1108,7 @@ // One view at a time; the diagram is the default page ('' or 'diagram'). function showView(kind) { if (!views) return; + views.hidden = root.getAttribute('data-bauify') !== 'on'; var next = kind === 'diagram' ? '' : kind || ''; // Set first: the layout (summary column hidden, full width) must settle before a view draws. if (next) root.setAttribute('data-bauify-views', next); else root.removeAttribute('data-bauify-views'); @@ -1166,12 +1167,41 @@ var index = M.findIndex(function (m) { return m.id === id; }); select(index, -1); }, - saveSelection: function () { return { module: state.focusModule, finding: state.finding, file: state.file, changedFile: changedSelection, scope: fileScope?.value, tab: filePane.hidden ? 'map' : 'files', query: fileQuery.value, zoom: focusZoom, view: sideView() }; }, + saveSelection: function (portable, active) { + var saved = { module: state.focusModule, finding: state.finding, file: state.file, changedFile: changedSelection, scope: fileScope?.value, tab: filePane.hidden ? 'map' : 'files', query: fileQuery.value, zoom: focusZoom, view: sideView() }; + if (!portable) return saved; + return { + ...saved, portable: true, module: M[saved.module] ? { path: M[saved.module].path, rootFile: M[saved.module].path || M[saved.module].rootGroup ? null : F.find(function (entry) { return entry[1] === saved.module; })?.[0] } : null, finding: FD[saved.finding]?.id, file: F[saved.file]?.[0], + changedFile: changedFiles[saved.changedFile]?.path, + view: { ...saved.view, groups: [...saved.view.groups] }, fileScroll: filePane.scrollTop, + focus: active === fileQuery ? 'search' : active === fileScope ? 'scope' + : active && fileList.contains(active) ? 'file' : active?.classList.contains('atlas-tab') ? 'tab' : null + }; + }, restoreSelection: function (saved) { fileQuery.value = saved.query || ''; if (fileScope && saved.scope) fileScope.value = saved.scope; - select(saved.module, saved.finding, saved, saved.file, saved.changedFile); + var module = saved.module, finding = saved.finding, file = saved.file, changed = saved.changedFile; + if (saved.portable) { + var matchingModules = saved.module ? M.map(function (entry, index) { + var rootFile = entry.path || entry.rootGroup ? null : F.find(function (file) { return file[1] === index; })?.[0]; + return entry.path === saved.module.path && rootFile === saved.module.rootFile ? index : -1; + }).filter(function (index) { return index >= 0; }) : []; + module = matchingModules.length === 1 ? matchingModules[0] : -1; + finding = FD.findIndex(function (entry) { return entry.id === saved.finding; }); + file = F.findIndex(function (entry) { return entry[0] === saved.file; }); + changed = changedFiles.findIndex(function (entry) { return entry.path === saved.changedFile; }); + saved = { ...saved, view: { ...saved.view, groups: new Set(saved.view.groups) } }; + } + select(module, finding, saved, file, changed); showTab(saved.tab === 'files'); + if (saved.portable && saved.tab === 'files') filePane.scrollTop = saved.fileScroll; + if (saved.portable && !panel.hidden && saved.focus) { + var target = saved.focus === 'search' ? fileQuery : saved.focus === 'scope' ? fileScope + : saved.focus === 'file' ? fileList.querySelector('[aria-current="true"]') || fileQuery : panel.querySelector('.atlas-tab[aria-selected="true"]'); + if (target?.getClientRects().length) target.focus({ preventScroll: true }); + } + return saved.portable && ((saved.module && module < 0) || (saved.finding && finding < 0) || (saved.file && file < 0) || (saved.changedFile && changed < 0)); } }; if (standalone) open(); diff --git a/archify/modules/code-analysis/overlay/client/atlas3d.js b/archify/modules/code-analysis/overlay/client/atlas3d.js index 10f9ff9330..eb6a86ab95 100644 --- a/archify/modules/code-analysis/overlay/client/atlas3d.js +++ b/archify/modules/code-analysis/overlay/client/atlas3d.js @@ -684,7 +684,44 @@ } resize(); updateCamera(); renderSide(); applyMarks(); requestAnimationFrame(frame); - return { host, select, state, consistent, counts: { files: drawnFiles, functions: drawnFns, branchDeps, threadDeps, insideDeps }, trunk: M[trunk].label, refresh: () => { resize(); dirty = true; } }; + function functionIdentity(index) { + const fn = FN[index]; + if (!fn) return null; + return { file: F[fn[0]][0], name: fn[1], line: fn[2], digest: fn[8], stableName: fn[9] === true, unique: !!fn[8] && FN.filter(candidate => candidate[0] === fn[0] && candidate[1] === fn[1] && candidate[8] === fn[8]).length === 1 }; + } + function matchingFunction(saved) { + if (!saved || !saved.stableName || !saved.unique || !saved.digest) return []; + return FN.map((fn, i) => F[fn[0]][0] === saved.file && fn[9] === true && fn[1] === saved.name && fn[8] === saved.digest ? i : -1).filter(i => i !== -1); + } + function saveSelection() { + if (state.fn !== -1) return { type: 'function', ...functionIdentity(state.fn) }; + if (state.finding !== -1) { const finding = FD[state.finding]; return { type: 'finding', id: finding.id, ...(finding.kind === 'function' ? { function: functionIdentity(finding.fn) } : {}) }; } + if (state.file !== -1) return { type: 'file', path: F[state.file][0] }; + if (state.module !== -1) { const m = M[state.module]; return { type: 'module', path: m.path, rootFile: m.path || m.rootGroup ? null : F.find(f => f[1] === state.module)?.[0] }; } + return null; + } + function restoreSelection(saved) { + if (!saved) return false; + let indexes = []; + if (saved.type === 'function') { + // A generated name can be reassigned to a new function. Without + // independent owner provenance it is safer to report it unavailable. + indexes = matchingFunction(saved); + } + if (saved.type === 'finding') { + indexes = FD.map((f, i) => f.id === saved.id ? i : -1).filter(i => i !== -1); + if (indexes.length === 1 && FD[indexes[0]].kind === 'function') { + const matches = matchingFunction(saved.function); + if (matches.length !== 1 || matches[0] !== FD[indexes[0]].fn) return true; + } + } + if (saved.type === 'file') indexes = F.map((f, i) => f[0] === saved.path ? i : -1).filter(i => i !== -1); + if (saved.type === 'module') indexes = M.map((m, i) => m.path === saved.path && (m.path || (m.rootGroup ? null : F.find(f => f[1] === i)?.[0]) === saved.rootFile) ? i : -1).filter(i => i !== -1); + if (indexes.length !== 1) return true; + select({ type: saved.type, index: indexes[0] }); + return false; + } + return { host, select, state, saveSelection, restoreSelection, consistent, counts: { files: drawnFiles, functions: drawnFns, branchDeps, threadDeps, insideDeps }, trunk: M[trunk].label, refresh: () => { resize(); dirty = true; } }; } window.__archifyAtlas3d = { mount, get view() { return mounted; } }; diff --git a/archify/modules/code-analysis/overlay/client/overlay.css b/archify/modules/code-analysis/overlay/client/overlay.css index 6aaf7e492c..10485855fa 100644 --- a/archify/modules/code-analysis/overlay/client/overlay.css +++ b/archify/modules/code-analysis/overlay/client/overlay.css @@ -693,3 +693,15 @@ html[data-bauify="on"][data-bauify-code="on"][data-bauify-pick] #bauify-edges .b html[data-bauify="on"][data-bauify-pick] path.bauify-coded.bauify-lit { opacity: 1; } html[data-bauify="on"] g[data-node-id] { transition: opacity .3s; } .pr-source-pin { display: block; overflow-wrap: anywhere; } + +.toolbar .analysis-refresh { position: relative; display: none; } +html[data-bauify="on"] .toolbar .analysis-refresh { display: inline-flex; } +.toolbar .analysis-refresh-button[aria-busy="true"] { cursor: progress; } +.analysis-refresh-status:not(:empty) { + position: absolute; z-index: 12; inset: calc(100% + 8px) 0 auto auto; + width: max-content; max-width: min(340px, 70vw); padding: 8px 12px; + background: var(--panel, #fff); color: var(--text, #0f172a); + border: 1px solid var(--panel-border, #cbd5e1); border-radius: 8px; + font-size: 12px; line-height: 1.35; +} +.analysis-refresh-status:empty { position: absolute; } diff --git a/archify/modules/code-analysis/overlay/client/overlay.js b/archify/modules/code-analysis/overlay/client/overlay.js index 26b6c51023..43dcce1624 100644 --- a/archify/modules/code-analysis/overlay/client/overlay.js +++ b/archify/modules/code-analysis/overlay/client/overlay.js @@ -150,14 +150,14 @@ overview.id = 'bauify-overview'; overview.hidden = true; overview.setAttribute('aria-label', tr("Code analysis overview")); reader.appendChild(overview); var findingById = {}; (data.findings || []).forEach(function (f) { findingById[f.id] = f; }); - var overviewMode = 'summary', listScroll = 0, findingReturn = null; + var overviewMode = 'summary', listScroll = 0, findingReturn = null, reading = { kind: 'overview' }; var filters = { source: 'all', category: 'all', severity: 'all', status: 'open', search: '', unverified: false, page: 0 }; var filterKey = 'archify-findings:' + (data.repository.root || '') + ':' + location.pathname; try { var restored = JSON.parse(sessionStorage.getItem(filterKey)); if (restored) Object.keys(filters).forEach(function (key) { if (typeof restored[key] === typeof filters[key]) filters[key] = restored[key]; }); } catch (error) { /* Storage is optional for offline reports. */ } var entryById = {}; ((data.overview && data.overview.findings) || []).forEach(function (e) { entryById[e.id] = e; }); var moduleInfo = {}; data.components.forEach(function (c) { c.modules.forEach(function (m) { moduleInfo[m.id] = m; }); }); - (data.unmapped || []).forEach(function (m) { if (!moduleInfo[m.id]) moduleInfo[m.id] = { id: m.id, label: m.label, path: m.label, files: m.files, loc: m.loc, fanIn: m.fanIn, fanOut: m.fanOut, fileList: m.fileList || [] }; }); + (data.unmapped || []).forEach(function (m) { if (!moduleInfo[m.id]) moduleInfo[m.id] = { id: m.id, label: m.label, path: m.path ?? m.label, files: m.files, loc: m.loc, fanIn: m.fanIn, fanOut: m.fanOut, fileList: m.fileList || [] }; }); var detail = document.createElement('section'); detail.id = 'bauify-detail'; detail.hidden = true; detail.setAttribute('aria-label', tr("Bauify finding details")); reader.appendChild(detail); @@ -297,6 +297,7 @@ return camera.centerAt(x, y, { scale: camera.state ? camera.state().scale : 1, instant: true }); } function showOverview() { + reading = { kind: 'overview' }; overviewMode = 'summary'; clearPick(); readerPage(tr("Overview")); root.removeAttribute('data-bauify-source'); @@ -358,6 +359,7 @@ return findings.length ? findings.map(findingWhat).join(';') : tr(indicator.value); } function show(id) { + reading = { kind: 'component', id: id }; readerPage(tr("Component")); root.removeAttribute('data-bauify-source'); var c = byId[id]; if (!c) return; @@ -568,6 +570,7 @@ if (hit) codePane.scrollTop = Math.max(0, hit.offsetTop - codePane.offsetTop - codePane.clientHeight / 2); } function showDetail(c, key) { + reading = { kind: 'indicator', id: c.id, key: key }; readerPage(tr("Problem")); root.removeAttribute('data-bauify-source'); panel.hidden = true; @@ -582,11 +585,11 @@ if (!externalGroup) h += ("
" + "" + tr("Relationships and metrics") + "") + diagram(c, key, fl) + '
'; h += ("
" + tr("Findings · ")) + fl.length + '
'; if (!fl.length) h += '
' + (key === 'instability' ? tr("Instability measures dependency direction: out / (in + out). 0 = no outgoing dependencies, 1 = no incoming dependents. It is not a failure probability or a quality verdict.") : tr("No finding for this indicator; this is not a safety guarantee.")) + '
'; - fl.forEach(function (f) { h += f.external ? findingListRow(f) : quickHandoff(f) + evidencePreview(f) + findingCard(f) + taskHtml(f); }); + fl.forEach(function (f) { h += '
' + (f.external ? findingListRow(f) : quickHandoff(f) + evidencePreview(f) + findingCard(f) + taskHtml(f)) + '
'; }); detail.innerHTML = h; detail.hidden = false; codePane.hidden = true; - var backToComponent = function () { readerPage(tr("Component")); detail.hidden = true; codePane.hidden = true; panel.hidden = false; panel.querySelectorAll('.ind.active').forEach(function (x) { x.classList.remove('active'); }); }; + var backToComponent = function () { reading = { kind: 'component', id: c.id }; readerPage(tr("Component")); detail.hidden = true; codePane.hidden = true; panel.hidden = false; panel.querySelectorAll('.ind.active').forEach(function (x) { x.classList.remove('active'); }); }; detail.querySelector('.close').addEventListener('click', backToComponent); detail.querySelector('.back').addEventListener('click', backToComponent); wireRefs(); @@ -696,6 +699,7 @@ (review.status === 'accepted' ? ("" + tr("Accepted")) + (f.severity === 'error' ? tr(" · still present") : '') + '' : review.status === 'accepted-changed' ? ("" + tr("Accepted evidence changed · review again") + "") : external && external.binding !== 'verified' ? ("" + tr("Report binding: ")) + esc(bindingLabel(external.binding).toLowerCase()) + '' : '') + ''; } function showFindings(source) { + reading = { kind: 'findings' }; if (typeof source === 'string') { filters.source = source; filters.category = 'all'; filters.severity = 'all'; filters.status = 'open'; filters.unverified = false; filters.search = ''; filters.page = 0; listScroll = 0; } overviewMode = 'findings'; clearPick(); readerPage(tr("Findings")); root.removeAttribute('data-bauify-source'); panel.hidden = detail.hidden = codePane.hidden = true; overview.hidden = false; setFocus([]); @@ -703,6 +707,7 @@ } function renderFindingList() { var sources = externalSources(), dimensions = [...new Set(data.findings.map(function (f) { return f.dimension; }))].sort(); + if (!sources.length) filters.unverified = false; var option = function (value, label) { return ''; }; overview.innerHTML = ("" + "
" + "

" + tr("Findings") + "

") + (sources.length ? ("' : '') + '
' + ("" + "' + @@ -742,6 +747,7 @@ pagination.querySelectorAll('button').forEach(function (button) { button.addEventListener('click', function () { filters.page += Number(button.getAttribute('data-page')); renderFindingRows(); overview.scrollTop = 0; }); }); } function showSources() { + reading = { kind: 'sources' }; var parent = overviewMode; overviewMode = 'sources'; readerPage(tr("Sources")); root.removeAttribute('data-bauify-source'); panel.hidden = detail.hidden = codePane.hidden = true; overview.hidden = false; setFocus([]); overview.innerHTML = '" + "

" + tr("Sources & coverage") + "

" + "

" + tr("Report import, source binding and scan scope are separate facts.") + "

") + externalSources().map(function (source) { @@ -1012,11 +1018,7 @@ var startCopy = overview.querySelector('.start-copy'); if (startCopy) startCopy.addEventListener('click', function () { copyText(data.ui.resume.command, overview.querySelector('.start-status'), overview.querySelector('.start-command'), tr('Copied start command.')); }); var again = overview.querySelector('.bauify-reanalyze'); - if (again) again.addEventListener('click', function () { - again.disabled = true; again.classList.add('busy'); again.setAttribute('aria-busy', 'true'); - var note = overview.querySelector('.brief-status'); note.classList.remove('reanalyze-error'); note.textContent = tr('Reading the repository — imports, modules, rules.'); - window.__archifyReanalyze().catch(function (error) { again.disabled = false; again.classList.remove('busy'); again.removeAttribute('aria-busy'); note.classList.add('reanalyze-error'); note.textContent = tr('Re-analysis failed: ') + error.message + tr(' The result shown is from the last successful run.'); }); - }); + if (again) wireRefresh(again, overview.querySelector('.brief-status')); overview.querySelectorAll('[data-finding]').forEach(function (el) { el.addEventListener('click', function () { showFinding(el.getAttribute('data-finding')); }); }); wireTasks(overview); } @@ -1225,9 +1227,10 @@ function showFinding(id, parent) { var f = findingById[id]; if (!f) return; parent = findingReturn ? findingReturn.parent : parent || (!overview.hidden && overviewMode === 'findings' ? 'findings' : 'summary'); + reading = { kind: 'finding', id: id, parent: parent }; if (standalone && !findingReturn) { var opener = document.activeElement; - findingReturn = { parent: parent, atlas: window.__archifyAtlas && window.__archifyAtlas.saveSelection(), opener: overview.contains(opener) && opener.getAttribute('data-finding') }; + findingReturn = { parent: parent, atlas: window.__archifyAtlas && window.__archifyAtlas.saveSelection(true), opener: overview.contains(opener) && opener.getAttribute('data-finding') }; } clearPick(); readerPage(tr("Finding")); detail.classList.remove('reviewing'); root.removeAttribute('data-bauify-source'); @@ -1670,6 +1673,7 @@ function flyClose(back) { return ''; } // A dependency between two components: whether the diagram draws it, and the imports behind it. function showEdge(from, to) { + reading = { kind: 'edge', from: from, to: to }; var e = codeEdgeByKey[from + '>' + to], undrawn = !!e && e.declared === false; readerPage(tr('Dependency')); root.removeAttribute('data-bauify-source'); overview.hidden = true; detail.hidden = true; codePane.hidden = true; setFocus([]); @@ -1682,13 +1686,13 @@ h += '
' + fmt(e.weight) + '' + esc(tr('imports')) + '
' + Object.keys(files).length + (e.evidence.length < e.weight ? '+' : '') + '' + esc(tr('source files')) + '
'; h += '

' + esc(undrawn ? tr('{from} imports {to} in the code, but the diagram draws no line between them. Add it to the diagram, or treat it as coupling that should not exist.', { from: compLabel(from), to: compLabel(to) }) : tr('The diagram draws this dependency and the code confirms it.')) + '

'; h += '

' + esc(tr('Which files cause it')) + '' + esc(e.evidence.length < e.weight ? tr('first {count}', { count: e.evidence.length }) : tr('all')) + '

'; - h += e.evidence.map(function (v) { return ''; }).join(''); + h += e.evidence.map(function (v) { return ''; }).join(''); h += '

'; } else h += '

' + esc(tr('The diagram draws this relationship, but no import between these components was found. It may come from configuration, runtime calls or an external system, or the diagram over-states it.')) + '

'; panel.innerHTML = h; panel.hidden = false; panel.scrollTop = 0; panel.querySelector('.close').addEventListener('click', showOverview); panel.querySelector('.back').addEventListener('click', function () { if (byId[from]) show(from); else showOverview(); }); - panel.querySelectorAll('.fly-ev').forEach(function (el) { el.addEventListener('click', function () { showCode(el.getAttribute('data-file'), parseInt(el.getAttribute('data-line'), 10), tr('Import from {from} to {to}.', { from: compLabel(from), to: compLabel(to) }), undrawn ? 'red' : 'info'); }); }); + panel.querySelectorAll('.fly-ev').forEach(function (el) { el.addEventListener('click', function () { panel.querySelectorAll('.fly-ev.active').forEach(function (item) { item.classList.remove('active'); }); el.classList.add('active'); showCode(el.getAttribute('data-file'), parseInt(el.getAttribute('data-line'), 10), tr('Import from {from} to {to}.', { from: compLabel(from), to: compLabel(to) }), undrawn ? 'red' : 'info'); }); }); var copy = panel.querySelector('.fly-copy'); if (copy) copy.addEventListener('click', function () { var text = tr('{from} → {to}: {count} imports in the code', { from: compLabel(from), to: compLabel(to), count: e.weight }) + (undrawn ? tr(', not drawn on the architecture diagram') : '') + '.\n' + e.evidence.map(function (v) { return '- ' + v.file + ':' + (v.line || '?') + ' → ' + v.to; }).join('\n'); @@ -1700,6 +1704,7 @@ // A module no component on the diagram owns. function showOff(id) { var m = moduleInfo[id]; if (!m) return; + reading = { kind: 'off', id: id, path: m.path, rootFile: m.path || m.label === '(root)' ? null : m.fileList[0]?.path }; readerPage(tr('Not on the diagram')); root.removeAttribute('data-bauify-source'); overview.hidden = true; detail.hidden = true; codePane.hidden = true; clearPick(); setFocus([]); var fs = data.findings.filter(function (f) { return (f.moduleIds || []).indexOf(id) !== -1; }); @@ -1746,6 +1751,120 @@ setFly(false); } else { setFly(false); if (stage) { setBeacon(false); setCodeDeps(false); } clearEdges(); setFocus([]); if (layer) layer.remove(); layer = null; panel.hidden = true; detail.hidden = true; codePane.hidden = true; overview.hidden = true; if (svg) svg.querySelectorAll('.bauify-mapped').forEach(function (g) { g.classList.remove('bauify-mapped'); }); } } + var refresh, refreshStatus, refreshing = false; + if (typeof window.__archifyReanalyze === 'function') { + var refreshWrap = document.createElement('span'); + refreshWrap.className = 'analysis-refresh'; + refreshWrap.innerHTML = iconButton('refresh', tr('Re-analyze'), ' analysis-refresh-button', ' id="analysis-refresh"') + + ''; + btn.after(refreshWrap); + refresh = refreshWrap.firstElementChild; + refreshStatus = refreshWrap.lastElementChild; + wireRefresh(refresh, refreshStatus); + } + function visibleReaderPage() { + return !codePane.hidden ? codePane : !detail.hidden ? detail : !panel.hidden ? panel : overview; + } + var readingControls = ['.back', '.locate', '.reader-toggle', '.browse-findings', '.bauify-reanalyze']; + var sourceKeys = ['data-file', 'data-line', 'data-range-start', 'data-range-end', 'data-match', 'data-target']; + function sourceIdentity(ref) { + var owner = ref.closest('[data-evidence-owner]'); + return { attributes: sourceKeys.map(function (key) { return ref.getAttribute(key); }), + role: ref.closest('.inline-evidence') ? 'inline' : ref.closest('.more-evidence') ? 'details' : 'other', + owner: owner ? owner.getAttribute('data-evidence-owner') : null }; + } + function captureReading(active) { + var pane = visibleReaderPage(); + return { + reading: reading, open: !flyMode || flyOpen, collapsed: readerCollapsed, sourceOpen: pane === codePane, + filters: Object.assign({}, filters), listScroll: overviewMode === 'findings' && pane === overview ? overview.scrollTop : listScroll, + view: root.getAttribute('data-bauify-views'), scroll: pane.scrollTop, + sourceRef: pane === codePane ? (function () { + var ref = reading.kind === 'edge' ? panel.querySelector('.fly-ev.active') : detail.querySelector('.ref.active'); + return ref ? sourceIdentity(ref) : null; + })() : null, + atlas: window.__archifyAtlas?.saveSelection(true, active), findingReturn: findingReturn, + atlas3d: root.getAttribute('data-bauify-views') === 'atlas3d' ? window.__archifyAtlas3d?.view?.saveSelection?.() : null, + focus: readingControls.find(function (selector) { return active?.matches(selector); }), + focusRefresh: active === refresh + }; + } + function wireRefresh(button, note) { + // A pointer click in the toolbar moves focus before click fires. + var beforePointer; + button.addEventListener('pointerdown', function () { beforePointer = captureReading(document.activeElement); }); + button.addEventListener('pointercancel', function () { beforePointer = null; }); + button.addEventListener('click', function (event) { + if (refreshing) return; + var saved = event.detail && beforePointer || captureReading(button); + beforePointer = null; + refreshing = true; + button.disabled = true; button.classList.add('busy'); button.setAttribute('aria-busy', 'true'); + note.classList.remove('reanalyze-error'); + note.textContent = tr('Reading the repository — imports, modules, rules.'); + window.__archifyReanalyze(saved).catch(function (error) { + refreshing = false; + button.disabled = false; button.classList.remove('busy'); button.removeAttribute('aria-busy'); + note.classList.add('reanalyze-error'); + note.textContent = tr('Re-analysis failed: ') + error.message + tr(' The result shown is from the last successful run.'); + if (beforePointer == null && (document.activeElement === document.body || document.activeElement === button)) button.focus({ preventScroll: true }); + }); + }); + } + window.__archifyRestoreReading = function (saved) { + if (!saved || !saved.reading) return; + var page = saved.reading, missing = false; + if (saved.filters) Object.keys(filters).forEach(function (key) { if (typeof saved.filters[key] === typeof filters[key]) filters[key] = saved.filters[key]; }); + if (typeof saved.listScroll === 'number') listScroll = saved.listScroll; + if (saved.open && page.kind === 'component' && Object.hasOwn(byId, page.id)) show(page.id); + else if (saved.open && page.kind === 'indicator' && byId[page.id]) { + show(page.id); + if (byId[page.id].indicators.items.some(function (item) { return item.key === page.key; })) showDetail(byId[page.id], page.key); + else missing = true; + } + else if (saved.open && page.kind === 'finding' && Object.hasOwn(findingById, page.id)) { + findingReturn = saved.findingReturn; + showFinding(page.id, page.parent); + } else if (saved.open && page.kind === 'findings') showFindings(); + else if (saved.open && page.kind === 'sources') showSources(); + else if (saved.open && page.kind === 'edge' && Object.hasOwn(byId, page.from) && Object.hasOwn(byId, page.to) && (codeEdgeByKey[page.from + '>' + page.to] || svg && Array.from(svg.querySelectorAll('path[data-edge-from][data-edge-to]')).some(function (edge) { return edge.getAttribute('data-edge-from') === page.from && edge.getAttribute('data-edge-to') === page.to; }))) showEdge(page.from, page.to); + else if (saved.open && page.kind === 'off') { + var matches = (data.unmapped || []).filter(function (item) { return page.path === undefined ? item.id === page.id : (item.path ?? item.label) === page.path && (page.path || (item.label === '(root)' ? null : item.fileList?.[0]?.path) === page.rootFile); }); + if (matches.length === 1) showOff(matches[0].id); else { missing = true; showOverview(); } + } + else if (saved.open) { + missing = page.kind !== 'overview'; + showOverview(); + } + if (saved.sourceOpen && !missing) { + // Only reopen the exact captured evidence item. A different block in the + // same file is not a safe substitute after a new analysis. + var refs = saved.sourceRef ? Array.from((page.kind === 'edge' ? panel : detail).querySelectorAll(page.kind === 'edge' ? '.fly-ev[data-file]' : '.ref[data-file]')).filter(function (link) { + var identity = sourceIdentity(link); + if (Array.isArray(saved.sourceRef)) return saved.sourceRef.every(function (value, index) { return identity.attributes[index] === value; }); + return identity.role === saved.sourceRef.role && identity.owner === saved.sourceRef.owner && sourceKeys.every(function (_key, index) { return identity.attributes[index] === saved.sourceRef.attributes[index]; }); + }) : []; + if (refs.length === 1) { + // Keep the selected evidence visible when returning from its source. + var ancestor = refs[0].parentElement; + while (ancestor && ancestor !== detail) { if (ancestor.tagName === 'DETAILS') ancestor.open = true; ancestor = ancestor.parentElement; } + refs[0].click(); + } else missing = true; + } + if (saved.collapsed) setReaderCollapsed(true); + if (saved.view === 'atlas' || saved.view === 'atlas3d') window.__archifyAtlas?.showView(saved.view); + if (saved.view === 'atlas3d' && saved.atlas3d) missing = window.__archifyAtlas3d?.view?.restoreSelection?.(saved.atlas3d) !== false || missing; + var pane = visibleReaderPage(); + if (!missing && (!saved.sourceOpen || pane === codePane)) pane.scrollTop = saved.scroll; + var target = saved.focusRefresh ? refresh : saved.focus && (pane.querySelector(saved.focus) || reader.querySelector(saved.focus)); + if (target?.getClientRects().length && !target.closest('[inert]')) target.focus({ preventScroll: true }); + else if (saved.open && !saved.collapsed && !saved.view && pane.getClientRects().length) { + var heading = pane.querySelector('h3') || pane.querySelector('.back'); + if (heading) { if (heading.tagName === 'H3') heading.tabIndex = -1; heading.focus({ preventScroll: true }); } + } else if (!saved.atlas?.focus) refresh?.focus({ preventScroll: true }); + if (saved.atlas && window.__archifyAtlas) missing = window.__archifyAtlas.restoreSelection(saved.atlas) || missing; + if (missing && refreshStatus) refreshStatus.textContent = tr('This selection is no longer available in the latest analysis.'); + }; btn.addEventListener('click', function () { setOn(root.getAttribute('data-bauify') !== 'on'); }); // The Atlas view hands a finding back here to show its source evidence. window.__archifyShowSource = function (file, line, snapshot, sourcePair, returnFocus) { diff --git a/archify/modules/code-analysis/overlay/i18n.mjs b/archify/modules/code-analysis/overlay/i18n.mjs index 605c525541..c9e802287c 100644 --- a/archify/modules/code-analysis/overlay/i18n.mjs +++ b/archify/modules/code-analysis/overlay/i18n.mjs @@ -177,7 +177,9 @@ const ZH_CN = { "Not run": "未运行", "Select a JSON file up to 2 MiB.": "请选择不超过 2 MiB 的 JSON 文件。", "Could not read the selected JSON file.": "无法读取选中的 JSON 文件。", + "The task does not match a retained analysis capture.": "任务与保留的分析快照均不匹配。", "The task does not match the previous analysis.": "任务与上一轮分析不匹配。", + "This selection is no longer available in the latest analysis.": "最新分析中已无此选中项。", "Invalid task or mismatched task findings.": "任务格式不正确,或发现与上一轮不符。", "The task ID does not match the selected findings.": "任务 ID 与所选发现不匹配。", "Task verification requires a local file or a secure page.": "任务验证需要本地文件或安全页面。", diff --git a/archify/modules/code-analysis/overlay/inject.mjs b/archify/modules/code-analysis/overlay/inject.mjs index 8ad9a79219..eb84dac70a 100644 --- a/archify/modules/code-analysis/overlay/inject.mjs +++ b/archify/modules/code-analysis/overlay/inject.mjs @@ -104,7 +104,7 @@ export function alignDiagram({ ir, graph, map = null, facts = null, findings = [ // Whether the diagram draws each code-level edge: the analysis page marks the ones it does not. for (const e of edges) e.declared = declared.has(`${e.from}>${e.to}`); const undeclaredEdges = edges.filter((e) => !e.declared); - const unmapped = graph.modules.filter((m) => !claimed.has(m.id)).map((m) => ({ id: m.id, label: m.label, files: m.files, loc: m.loc, fanIn: m.fanIn, fanOut: m.fanOut, fileList: (fileIndex.get(m.id) || []).map((f) => ({ ...f, module: m.id })) })); + const unmapped = graph.modules.filter((m) => !claimed.has(m.id)).map((m) => ({ id: m.id, label: m.label, path: m.path, files: m.files, loc: m.loc, fanIn: m.fanIn, fanOut: m.fanOut, fileList: (fileIndex.get(m.id) || []).map((f) => ({ ...f, module: m.id })) })); const fileModule = facts ? new Map([...fileIndex].flatMap(([id, list]) => list.map((f) => [f.path, id]))) : new Map(Object.entries(graph.fileModules || {})); diff --git a/archify/modules/code-analysis/test/atlas.test.mjs b/archify/modules/code-analysis/test/atlas.test.mjs index d940ec245d..3811d84a88 100644 --- a/archify/modules/code-analysis/test/atlas.test.mjs +++ b/archify/modules/code-analysis/test/atlas.test.mjs @@ -3,6 +3,7 @@ // lost or misattributed here is drawn wrong without any other check noticing. import assert from 'node:assert/strict'; import fs from 'node:fs'; +import os from 'node:os'; import { test } from 'node:test'; import { buildGraph, evaluateGraph, extractFacts, loadConfig } from '../lib/analysis.mjs'; import { buildAtlas, moduleLabels } from '../overlay/atlas.mjs'; @@ -20,6 +21,51 @@ function analyze(t) { return { facts, graph, findings, atlas: buildAtlas({ graph, facts, findings }) }; } +test('atlas: only function expressions named by a binding may restore', (t) => { + const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'archify-atlas-binding-')); + t.after(() => fs.rmSync(dir, { recursive: true, force: true })); + fs.writeFileSync(path.join(dir, 'bindings.ts'), 'const onSave = function /* comment */ () { return 1; };\nconst wrapped = (function () { return 4; });\nconst checked = (function () { return 5; }) satisfies () => number;\nconst asserted = (function () { return 6; }) as () => number;\nconst cast = <() => number>function () { return 7; };\nconst onCancel = function handler() { return 2; };\n{ const scoped = function () { return 3; }; }\n'); + const config = loadConfig(); + const { facts } = extractFacts(dir, { language: 'ts', config }); + const graph = buildGraph(facts, config); + const atlas = buildAtlas({ graph, facts }); + assert.equal(atlas.functions.find(fn => fn[1] === 'onSave')?.[9], true); + assert.equal(atlas.functions.find(fn => fn[1] === 'wrapped')?.[9], true, 'parenthesized bindings stay eligible'); + assert.equal(atlas.functions.find(fn => fn[1] === 'checked')?.[9], true, 'satisfies bindings stay eligible'); + assert.equal(atlas.functions.find(fn => fn[1] === 'asserted')?.[9], true, 'as assertions stay eligible'); + assert.equal(atlas.functions.find(fn => fn[1] === 'cast')?.[9], true, 'angle-bracket assertions stay eligible'); + assert.equal(atlas.functions.find(fn => fn[1] === 'handler')?.[9], false); + assert.equal(atlas.functions.find(fn => fn[1] === 'scoped')?.[9], false, 'scope is not captured as part of the binding identity'); + facts.files.find(file => file.path === 'bindings.ts').sourceText = facts.files[0].sourceText.replace('return 1', 'return 9'); + const mismatch = buildAtlas({ graph, facts }); + assert.equal(mismatch.functions.find(fn => fn[1] === 'onSave')?.[9], false, 'a mismatched captured digest cannot establish a binding'); +}); + +test('atlas: Java initializer and nested names are not stable identities', (t) => { + const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'archify-atlas-java-')); + t.after(() => fs.rmSync(dir, { recursive: true, force: true })); + fs.writeFileSync(path.join(dir, 'Demo.java'), 'class Demo { static { Runnable r = new Runnable() { public void run() {} }; } { int x = 1; } }\n'); + const config = loadConfig(); config.include = ['**/*.java']; + const { facts } = extractFacts(dir, { language: 'java', config }); + const atlas = buildAtlas({ graph: buildGraph(facts, config), facts }); + for (const kind of ['', '', '']) { + const matches = atlas.functions.filter(fn => kind === '' ? fn[1].includes(kind) : fn[1].endsWith(kind)); + assert.ok(matches.length, `the real Java fixture contains ${kind}`); + assert.ok(matches.every(fn => fn[9] === false), `${kind} is order-dependent`); + } +}); + +test('atlas: function identity includes the full Python definition when present', (t) => { + const { facts, graph, findings } = analyze(t); + const fn = facts.functions.find(item => graph.fileModules[item.file]); + assert.ok(fn); + fn.sourceRange = { ...fn.sourceRange, sha256: 'metrics-only' }; + fn.definition = { kind: 'FunctionDef', sourceRange: { ...fn.sourceRange, sha256: 'definition-with-decorators' } }; + const atlas = buildAtlas({ graph, facts, findings }); + const entry = atlas.functions.find(item => atlas.files[item[0]][0] === fn.file && item[1] === (fn.qualname || fn.name)); + assert.equal(entry[8], 'definition-with-decorators'); +}); + test('atlas: every in-tree dependency between analyzed files is drawn once, between the right files', (t) => { const { facts, graph, atlas } = analyze(t); const paths = atlas.files.map((f) => f[0]); @@ -139,3 +185,29 @@ test('atlas: an internal-imports finding draws its cited imports and marks its m assert.deepEqual(entry.entries.map((i) => paths[i]), [entryFile], 'entry files outside the atlas are dropped'); assert.match(entry.title, /^Internal imports · /); }); + +test('atlas: same-named methods link each finding to its own declaration range', t => { + const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'archify-atlas-same-name-')); + t.after(() => fs.rmSync(dir, { recursive: true, force: true })); + const body = 'if(a) a++; '.repeat(20) + 'return a;'; + fs.writeFileSync(path.join(dir, 'service.ts'), `export class Service {\n static dispatch(a,b,c,d,e,f,g,h,i,j) { ${body} }\n dispatch(a,b,c,d,e,f,g,h,i,j) { ${body} }\n}\n`); + const config = loadConfig(); + const { facts } = extractFacts(dir, { language: 'ts', config }); + const graph = buildGraph(facts, config); + const findings = evaluateGraph(graph, config, facts).diagnostics.filter(f => f.code === 'complexity/function'); + const same = findings.filter(f => f.subject.function === 'Service.dispatch'); + assert.equal(same.length, 2, JSON.stringify({functions:facts.functions.map(fn=>fn.qualname), findings:findings.map(f=>f.subject)})); + const atlas = buildAtlas({ graph, facts, findings }); + for (const finding of same) { + const entry = atlas.findings.find(item => item.id === finding.id); + assert.notEqual(entry.fn, undefined, `missing function link for ${finding.id}`); + const fn = atlas.functions[entry.fn]; + assert.equal(fn[2], finding.subject.line, `declaration line for ${finding.id}`); + assert.equal(atlas.findings[fn[6]].id, finding.id, 'function links back to its finding'); + } + const ambiguousFacts = { ...facts, functions: facts.functions.map(fn => ({ ...fn, line: 2, endLine: 2 })) }; + const ambiguousFindings = same.map(f => ({ ...f, subject: { ...f.subject, line: 2, endLine: 2 } })); + const ambiguous = buildAtlas({ graph, facts: ambiguousFacts, findings: ambiguousFindings }); + assert.ok(ambiguous.findings.every(entry => entry.fn === undefined), 'indistinguishable declarations stay unlinked'); + assert.ok(ambiguous.functions.every(fn => fn[6] === -1), 'ambiguous functions do not select a finding'); +}); diff --git a/test/code-analysis-browser.test.mjs b/test/code-analysis-browser.test.mjs index 3f9cfe016f..e3478781bb 100644 --- a/test/code-analysis-browser.test.mjs +++ b/test/code-analysis-browser.test.mjs @@ -139,6 +139,18 @@ test('Code Analysis highlights exact duplicate characters and retains both locat await run("document.querySelector('#bauify-code .source-back').click()"); assert.equal((await marks(section + ' pre')).length, 2, 'returning preserves both duplicate previews'); } + // Re-analysis restoration must retain the second occurrence even when both + // ranges share the same file and line. + await run(`(() => { + const ref = document.querySelectorAll(${JSON.stringify(section + ' .ref')})[1]; + const keys = ['data-file', 'data-line', 'data-range-start', 'data-range-end', 'data-match']; + window.__archifyRestoreReading({ reading: { kind: 'finding', id: 'REDU-0001' }, open: true, + sourceOpen: true, sourceRef: keys.map(key => ref.getAttribute(key)), scroll: 0 }); + })()`); + assert.equal(await run("document.getElementById('bauify-code').hidden"), false); + assert.equal((await marks('#bauify-code pre'))[0].before, shortMarks[1].before, 'the second same-line occurrence is restored'); + await run("document.querySelector('#bauify-code .source-back').click()"); + if (process.env.ARCHIFY_C6_HIGHLIGHT_SCREENSHOT) { const shot = await send('Page.captureScreenshot', { format: 'png' }); fs.writeFileSync(process.env.ARCHIFY_C6_HIGHLIGHT_SCREENSHOT, Buffer.from(shot.data, 'base64')); @@ -872,6 +884,14 @@ test('Code Analysis Atlas draws the analyzed tree, focuses a module and hands a assert.equal(await run("typeof window.THREE"), 'object', 'three.js loads on first open'); await until(`document.documentElement.getAttribute('data-bauify-atlas3d-drawn') === '${atlas.functions.length}'`, 'Atlas 3D did not draw'); assert.deepEqual(await run("[window.__archifyAtlas3d.view.consistent, window.__archifyAtlas3d.view.counts.files]"), [true, atlas.files.length], 'every file, function and finding of the run is in the model'); + assert.deepEqual(await run(`(() => { + const view = window.__archifyAtlas3d.view; + view.select({ type: 'file', index: 0 }); + const saved = view.saveSelection(); + view.select({ type: 'module', index: 0 }); + const missing = view.restoreSelection(saved); + return [missing, view.saveSelection(), view.restoreSelection({ type: 'file', path: 'no-such-file' })]; + })()`), [false, { type: 'file', path: atlas.files[0][0] }, true], '3D selections restore by stable file identity and report missing files'); } else { assert.equal(await run("typeof window.THREE"), 'undefined', 'three.js stays inert without WebGL'); assert.match(await run("document.querySelector('#bauify-atlas3d .a3d-fallback')?.textContent || ''"), /WebGL/, 'without WebGL the view says so'); diff --git a/test/code-analysis-review-browser.test.mjs b/test/code-analysis-review-browser.test.mjs index 7a0ec8ec01..72a9d41d08 100644 --- a/test/code-analysis-review-browser.test.mjs +++ b/test/code-analysis-review-browser.test.mjs @@ -2,12 +2,136 @@ import assert from 'node:assert/strict'; import fs from 'node:fs'; import os from 'node:os'; import path from 'node:path'; +import { once } from 'node:events'; import { test } from 'node:test'; import { ChromeVisualBrowser, findChrome } from '../archify/bin/visual-check.mjs'; import { startAnalysisView } from '../archify/modules/code-analysis/bin/serve.mjs'; import { runCheck } from '../archify/modules/code-analysis/bin/check.mjs'; const chrome = process.env.ARCHIFY_CHROME ? findChrome() : null; +test('Java root build module survives an earlier-sorting source after re-analysis', { + skip: chrome ? false : 'Set ARCHIFY_CHROME to run Code Analysis browser coverage.', +}, async t => { + const scratch = fs.mkdtempSync(path.join(os.tmpdir(), 'archify-java-root-')); + t.after(() => fs.rmSync(scratch, { recursive: true, force: true })); + const root = path.join(scratch, 'repo'); + for (const dir of ['src/main/java/app', 'nested/src/main/java/app']) fs.mkdirSync(path.join(root, dir), { recursive: true }); + for (const file of ['pom.xml', 'nested/pom.xml']) fs.writeFileSync(path.join(root, file), ''); + fs.writeFileSync(path.join(root, 'src/main/java/app/Core.java'), 'package app; class Core {}\n'); + fs.writeFileSync(path.join(root, 'nested/src/main/java/app/Other.java'), 'package app; class Other {}\n'); + const ir = path.join(scratch, 'input.json'); + fs.writeFileSync(ir, JSON.stringify({ schema_version: 1, diagram_type: 'architecture', meta: { title: 'Java root', output: 'architecture.html' }, components: [{ id: 'app', type: 'backend', label: 'App', pos: [40, 40], size: [170, 64] }], connections: [] })); + const view = await startAnalysisView([root, '--ir', ir, '--out', path.join(scratch, 'view'), '--language', 'java']); + const sockets = new Set(); + view.server.on('connection', socket => { sockets.add(socket); socket.on('close', () => sockets.delete(socket)); }); + t.after(() => new Promise(resolve => { view.server.close(resolve); for (const socket of sockets) socket.destroy(); })); + const browser = new ChromeVisualBrowser(chrome); + t.after(async () => { + if (browser.child.exitCode === null && browser.child.signalCode === null) { + const exited = once(browser.child, 'exit', { signal: AbortSignal.timeout(5000) }).catch(() => {}); + await Promise.race([browser.cdp.send('Browser.close').catch(() => {}), exited]); + await exited; + } + await browser.close(); + }); + const session = await browser.sessionPromise; + const send = (method, params = {}) => browser.cdp.send(method, params, session); + const run = async expression => { const r = await send('Runtime.evaluate', { expression, awaitPromise: true, returnByValue: true }); assert.equal(r.exceptionDetails, undefined, r.exceptionDetails?.exception?.description); return r.result?.value; }; + const loaded = browser.cdp.waitFor('Page.loadEventFired', session); + await send('Page.navigate', { url: view.url }); await loaded; + await run("document.getElementById('code-analysis-start').click()"); + const readyBy = Date.now() + 60000; + while (Date.now() < readyBy) { + try { if (await run("Boolean(document.getElementById('bauify-analysis'))")) break; } catch { /* navigation */ } + await new Promise(resolve => setTimeout(resolve, 100)); + } + const module = await run(`(() => { const data = JSON.parse(document.getElementById('bauify-analysis').textContent); return data.unmapped.find(m => m.path === '' && m.label === '(root)'); })()`); + assert.ok(module, 'the root build module is present and is not mapped to the diagram'); + await run(`window.__archifyRestoreReading({ reading: { kind: 'off', id: ${JSON.stringify(module.id)}, path: '', rootFile: null }, open: true })`); + assert.match(await run("document.querySelector('#bauify-panel h3').textContent"), /\(root\)/); + fs.writeFileSync(path.join(root, 'src/main/java/app/Alpha.java'), 'package app; class Alpha {}\n'); + const before = await run("performance.timeOrigin"); + await run("document.getElementById('analysis-refresh').click()"); + const deadline = Date.now() + 60000; + while (Date.now() < deadline) { + try { if (await run(`performance.timeOrigin !== ${before} && !history.state`)) break; } catch { /* navigation */ } + await new Promise(resolve => setTimeout(resolve, 100)); + } + assert.notEqual(await run('performance.timeOrigin'), before, 'the updated Java analysis loaded'); + assert.equal(await run("document.getElementById('bauify-panel').hidden"), false); + assert.match(await run("document.querySelector('#bauify-panel h3').textContent"), /\(root\)/); + const atlasRoot = await run(`(() => { + document.querySelector('.views-option[data-view=atlas]').click(); + const atlas = JSON.parse(document.getElementById('bauify-atlas-data').textContent); + const item = atlas.modules.find(m => m.rootGroup); + if (item) window.__archifyAtlas.focusModule(item.id); + return item; + })()`); + assert.ok(atlasRoot, 'Atlas identifies the root build group separately from root files'); + fs.writeFileSync(path.join(root, 'src/main/java/app/Aardvark.java'), 'package app; class Aardvark {}\n'); + const atlasBefore = await run('performance.timeOrigin'); + await run("document.getElementById('analysis-refresh').dispatchEvent(new PointerEvent('pointerdown', { bubbles: true })); document.getElementById('analysis-refresh').dispatchEvent(new MouseEvent('click', { bubbles: true, detail: 1 }))"); + const atlasDeadline = Date.now() + 60000; + while (Date.now() < atlasDeadline) { + try { if (await run(`performance.timeOrigin !== ${atlasBefore} && !history.state`)) break; } catch { /* navigation */ } + await new Promise(resolve => setTimeout(resolve, 100)); + } + assert.notEqual(await run('performance.timeOrigin'), atlasBefore); + assert.match(await run("document.querySelector('#bauify-atlas .atlas-selection').textContent"), /root|\./i, 'Atlas keeps the root build selection'); + assert.equal(await run('window.__archifyAtlas.saveSelection(true).module.rootFile'), null); + const hasJava3d = await run(`(() => { + document.querySelector('.views-option[data-view=atlas3d]').click(); + const view = window.__archifyAtlas3d.view; + if (!view || view.failed) return false; + const atlas = JSON.parse(document.getElementById('bauify-atlas-data').textContent); + view.select({ type: 'module', index: atlas.modules.findIndex(m => m.rootGroup) }); + return true; + })()`); + if (hasJava3d) { + fs.writeFileSync(path.join(root, 'src/main/java/app/Aa.java'), 'package app; class Aa {}\n'); + const before3d = await run('performance.timeOrigin'); + await run("document.getElementById('analysis-refresh').dispatchEvent(new PointerEvent('pointerdown', { bubbles: true })); document.getElementById('analysis-refresh').dispatchEvent(new MouseEvent('click', { bubbles: true, detail: 1 }))"); + const until3d = Date.now() + 60000; + while (Date.now() < until3d) { + try { if (await run(`performance.timeOrigin !== ${before3d} && !history.state`)) break; } catch { /* navigation */ } + await new Promise(resolve => setTimeout(resolve, 100)); + } + assert.notEqual(await run('performance.timeOrigin'), before3d); + assert.deepEqual(await run('window.__archifyAtlas3d.view.saveSelection()'), { type: 'module', path: '', rootFile: null }, '3D keeps the Java root build selection'); + const core = path.join(root, 'src/main/java/app/Core.java'); + fs.writeFileSync(core, 'package app; class Core { Runnable a = new Runnable() { public void run() { int x = 1; } }; }\n'); + async function reload3d() { + const before = await run('performance.timeOrigin'); + await run("document.getElementById('analysis-refresh').dispatchEvent(new PointerEvent('pointerdown', { bubbles: true })); document.getElementById('analysis-refresh').dispatchEvent(new MouseEvent('click', { bubbles: true, detail: 1 }))"); + const deadline = Date.now() + 60000; + while (Date.now() < deadline) { + try { if (await run(`performance.timeOrigin !== ${before} && !history.state`)) break; } catch { /* navigation */ } + await new Promise(resolve => setTimeout(resolve, 100)); + } + assert.notEqual(await run('performance.timeOrigin'), before); + } + await reload3d(); + const javaMethod = await run(`(() => { + const atlas = JSON.parse(document.getElementById('bauify-atlas-data').textContent); + const i = atlas.functions.findIndex(fn => fn[1].includes(' { const atlas = JSON.parse(document.getElementById('bauify-atlas-data').textContent); const i = atlas.functions.findIndex(fn => fn[1].includes('')); if (i < 0) throw Error('initializer missing'); window.__archifyAtlas3d.view.select({ type: 'function', index: i }); return window.__archifyAtlas3d.view.saveSelection(); })()`); + assert.equal(initializer.stableName, false, 'the first Java initializer is order-dependent'); + fs.writeFileSync(core, 'package app; class Core { static { System.out.println("start"); } static { System.out.println("start"); } }\n'); + await reload3d(); + assert.equal(await run('window.__archifyAtlas3d.view.saveSelection()'), null, 'an inserted identical initializer is not selected in place of the original'); + } else t.diagnostic('Java root 3D handoff requires WebGL and was not exercised'); +}); test('Code Analysis marks baseline findings, re-analyzes without a restart, and keeps the last good result on failure', { skip: chrome ? false : 'Set ARCHIFY_CHROME to run Code Analysis browser coverage.', }, async t => { @@ -18,6 +142,7 @@ test('Code Analysis marks baseline findings, re-analyzes without a restart, and const write = (file, text) => fs.writeFileSync(path.join(root, file), text); write('a.mjs', "import './b.mjs';\n"); write('b.mjs', "import './a.mjs';\n"); + write('b2.mjs', 'export const replacement = 2;\n'); // The a <-> b cycle is known and accepted before the page is opened. const baseline = path.join(scratch, 'baseline.json'); const written = await runCheck([root, '--language', 'ts', '--baseline', baseline, '--update-baseline', '--reason', 'legacy loader pair']); @@ -25,19 +150,29 @@ test('Code Analysis marks baseline findings, re-analyzes without a restart, and // Then a new cycle appears. write('c.mjs', "import './d.mjs';\n"); write('d.mjs', "import './c.mjs';\n"); + write('scratch.mjs', 'export const scratch = 1;\n'); + fs.mkdirSync(path.join(root, 'a.b')); + fs.writeFileSync(path.join(root, 'a.b', 'index.mjs'), 'export const original = 1;\n'); const ir = path.join(scratch, 'input.json'); fs.writeFileSync(ir, JSON.stringify({ schema_version: 1, diagram_type: 'architecture', meta: { title: 'Review browser regression', output: 'architecture.html' }, - components: [{ id: 'app', type: 'backend', label: 'App', pos: [40, 40], size: [170, 64] }], connections: [] })); + components: [{ id: 'app', type: 'backend', label: 'App', pos: [40, 40], size: [170, 64] }, { id: 'storage', type: 'backend', label: 'Storage', pos: [300, 40], size: [170, 64] }], connections: [] })); const map = path.join(scratch, 'map.json'); - fs.writeFileSync(map, JSON.stringify({ app: ['a', 'b', 'c', 'd'] })); + fs.writeFileSync(map, JSON.stringify({ app: ['a', 'c', 'd'], storage: ['b', 'b2'] })); const out = path.join(scratch, 'view'); const view = await startAnalysisView([root, '--ir', ir, '--map', map, '--baseline', baseline, '--out', out, '--language', 'ts']); const sockets = new Set(); view.server.on('connection', socket => { sockets.add(socket); socket.on('close', () => sockets.delete(socket)); }); t.after(() => new Promise(resolve => { view.server.close(resolve); for (const socket of sockets) socket.destroy(); })); const browser = new ChromeVisualBrowser(chrome); - t.after(() => browser.close()); + t.after(async () => { + if (browser.child.exitCode === null && browser.child.signalCode === null) { + const exited = once(browser.child, 'exit', { signal: AbortSignal.timeout(5000) }).catch(() => {}); + await Promise.race([browser.cdp.send('Browser.close').catch(() => {}), exited]); + await exited; + } + await browser.close(); + }); const session = await browser.sessionPromise; const send = (method, params = {}) => browser.cdp.send(method, params, session); const run = async expression => { @@ -99,6 +234,261 @@ test('Code Analysis marks baseline findings, re-analyzes without a restart, and fs.writeFileSync(process.env.ARCHIFY_ANALYSIS_REVIEW_AFTER_SCREENSHOT, Buffer.from(shot.data, 'base64')); } + let toolbarClicks = 0; + const refreshFromCurrentFocus = async () => { + const { initialPage, x, y, hit } = await run(`(() => { + const button = document.getElementById('analysis-refresh'); + button.scrollIntoView({ block: 'nearest', inline: 'nearest' }); + const box = button.getBoundingClientRect(); + const x = box.left + box.width / 2, y = box.top + box.height / 2; + return { initialPage: performance.timeOrigin, x, y, hit: !document.documentElement.hasAttribute('data-bauify-views') && button.contains(document.elementFromPoint(x, y)) }; + })()`); + if (hit) { + toolbarClicks += 1; + await send('Input.dispatchMouseEvent', { type: 'mouseMoved', x, y }); + await send('Input.dispatchMouseEvent', { type: 'mousePressed', x, y, button: 'left', clickCount: 1 }); + await send('Input.dispatchMouseEvent', { type: 'mouseReleased', x, y, button: 'left', clickCount: 1 }); + } else { + // Atlas is modal and covers the toolbar: exercise state hand-off directly. + await run("document.getElementById('analysis-refresh').dispatchEvent(new PointerEvent('pointerdown', { bubbles: true })); document.getElementById('analysis-refresh').dispatchEvent(new MouseEvent('click', { bubbles: true, detail: 1 }))"); + } + const finished = `performance.timeOrigin !== ${initialPage} && document.documentElement.getAttribute('data-bauify') === 'on' && !history.state`; + try { + await wait(`(${finished}) || document.querySelector('.analysis-refresh-status.reanalyze-error')`); + } catch (error) { + const state = await run(`({ + reloaded: performance.timeOrigin !== ${initialPage}, + pending: document.querySelector('#analysis-refresh')?.getAttribute('aria-busy'), + notices: [...document.querySelectorAll('[role=status]')].map(node => node.textContent).filter(Boolean), + })`); + throw new Error(error.message + ': ' + JSON.stringify(state)); + } + assert.equal(await run(finished), true, await run("document.querySelector('.analysis-refresh-status')?.textContent")); + }; + + await run("document.querySelector('g[data-node-id=app]').dispatchEvent(new MouseEvent('click',{bubbles:true})); document.querySelector('#bauify-panel .back').focus()"); + await refreshFromCurrentFocus(); + assert.match(await run("document.querySelector('#bauify-panel h3').textContent"), /^App/); + assert.equal(await run("document.activeElement.matches('#bauify-panel .back')"), true); + await run("window.__archifyRestoreReading({ reading: { kind: 'indicator', id: 'app', key: 'missing-indicator' }, open: true })"); + assert.match(await run("document.querySelector('#bauify-panel h3').textContent"), /^App/, 'a removed indicator falls back to its component'); + assert.equal(await run("document.getElementById('bauify-panel').hidden"), false, 'the fallback component is visible'); + assert.match(await run("document.querySelector('.analysis-refresh-status').textContent"), /selection is no longer available/); + + const indicatorTitle = await run("document.querySelector('#bauify-panel .ind.link').click(); document.querySelector('#bauify-detail h3').textContent"); + await refreshFromCurrentFocus(); + assert.equal(await run("document.querySelector('#bauify-detail h3').textContent"), indicatorTitle, 'the selected indicator survives re-analysis'); + await run("document.querySelector('#bauify-detail .back').click()"); + + const beforeFinding = await run(`(() => { + const finding = JSON.parse(document.getElementById('bauify-analysis').textContent).findings[0]; + window.__archifyShowFinding(finding.id); + document.querySelector('#bauify-detail .back').focus(); + return { title: document.querySelector('#bauify-detail h3').textContent, id: finding.id }; + })()`); + await refreshFromCurrentFocus(); + assert.equal(await run("document.querySelector('#bauify-detail .ai-task').dataset.taskId"), beforeFinding.id); + assert.equal(await run("document.querySelector('#bauify-detail h3').textContent"), beforeFinding.title); + assert.equal(await run("document.activeElement.matches('#bauify-detail .back')"), true); + + const sourceRef = await run(`(() => { + const ref = document.querySelector('#bauify-detail .ref[data-file]'); + if (!ref) return null; + const result = [ref.getAttribute('data-file'), ref.getAttribute('data-line')]; + ref.click(); return result; + })()`); + assert.ok(sourceRef, 'the finding offers a captured source reference'); + await refreshFromCurrentFocus(); + assert.equal(await run("document.getElementById('bauify-code').hidden"), false, 'the same source remains open after re-analysis'); + assert.ok((await run("document.getElementById('bauify-code').textContent")).includes(sourceRef[0])); + await run("document.querySelector('#bauify-code .source-back').click()"); + + await run("document.querySelector('#bauify-detail .back').click(); document.querySelector('.browse-findings').click(); const input = document.querySelector('#finding-search'); input.value = 'cycle'; input.dispatchEvent(new Event('input', { bubbles: true }));"); + await refreshFromCurrentFocus(); + assert.equal(await run("document.querySelector('#finding-search').value"), 'cycle', 'finding search survives re-analysis'); + assert.equal(await run("document.querySelector('#bauify-overview h3').textContent"), 'Findings'); + await run("document.querySelector('.findings-back').click()"); + + // The generated ID changes when a later module has the same slug. The + // selection follows the stable grouping path instead of that generated ID. + await run(`(() => { + document.querySelector('.views-option[data-view=atlas]').click(); + const atlas = JSON.parse(document.getElementById('bauify-atlas-data').textContent); + const module = atlas.modules.find(item => item.path === 'a.b'); + window.__archifyAtlas.focusModule(module.id); + })()`); + fs.mkdirSync(path.join(root, 'a-b')); + fs.writeFileSync(path.join(root, 'a-b', 'index.mjs'), 'export const collision = 2;\n'); + await refreshFromCurrentFocus(); + assert.match(await run("document.querySelector('#bauify-atlas .atlas-selection').textContent"), /a\.b/, 'module selection survives an ID collision'); + assert.doesNotMatch(await run("document.querySelector('.analysis-refresh-status').textContent"), /no longer available/); + await run("document.querySelector('.views-option[data-view=diagram]').click()"); + await run("window.__archifyRestoreReading({ reading: { kind: 'off', id: 'obsolete-id', path: 'a.b', rootFile: null }, open: true })"); + assert.equal(await run("document.getElementById('bauify-panel').hidden"), false, 'an off-diagram module is located by path after IDs change'); + assert.match(await run("document.querySelector('#bauify-panel h3').textContent"), /a\.b/); + + await run(`document.querySelector('.views-option[data-view=atlas]').click(); + document.getElementById('atlas-tab-files').click(); + const fileSearch = document.querySelector('.atlas-file-query'); + fileSearch.value = 'scratch.mjs'; fileSearch.dispatchEvent(new Event('input')); + document.querySelector('.atlas-file-list button').click()`); + await refreshFromCurrentFocus(); + assert.equal(await run("document.getElementById('atlas-tab-files').getAttribute('aria-selected')"), 'true'); + assert.equal(await run("document.querySelector('.atlas-file-query').value"), 'scratch.mjs'); + assert.equal(await run("document.activeElement.matches('.atlas-file-list button') && document.activeElement.textContent"), 'scratch.mjs'); + assert.equal(await run("document.activeElement.getAttribute('aria-current')"), 'true'); + fs.unlinkSync(path.join(root, 'scratch.mjs')); + await refreshFromCurrentFocus(); + assert.equal(await run("document.querySelector('.atlas-file-query').value"), 'scratch.mjs'); + assert.equal(await run("document.activeElement.matches('.atlas-file-query')"), true); + assert.match(await run("document.querySelector('.analysis-refresh-status').textContent"), /selection is no longer available/); + await run("document.querySelector('.views-option[data-view=diagram]').click(); window.__archifyShowFinding(" + JSON.stringify(beforeFinding.id) + "); document.querySelector('#bauify-detail .ref[data-file]').click()"); + + await run("document.querySelector('g[data-node-id=app]').dispatchEvent(new MouseEvent('click',{bubbles:true})); document.querySelector('#bauify-panel .fly-rel[data-edge=\\\"app>storage\\\"]').click(); document.querySelector('#bauify-panel .fly-ev').click()"); + await refreshFromCurrentFocus(); + assert.equal(await run("document.getElementById('bauify-code').hidden"), false, 'dependency source remains open even when a previous finding link is still marked active'); + write('a.mjs', "import './b2.mjs';\n"); + await refreshFromCurrentFocus(); + assert.equal(await run("document.getElementById('bauify-code').hidden"), true, 'a different import on the same line is not reopened as the old evidence'); + assert.match(await run("document.querySelector('.analysis-refresh-status').textContent"), /selection is no longer available/); + write('a.mjs', 'export const a = 1;\n'); + await refreshFromCurrentFocus(); + assert.match(await run("document.querySelector('.analysis-refresh-status').textContent"), /selection is no longer available/, 'an undrawn dependency removed from code is not reported as declared'); + + write('complex.mjs', 'export function complex(x) {' + Array.from({ length: 25 }, (_, i) => `if (x === ${i}) return ${i};`).join('') + 'return 0; }\n'); + await refreshFromCurrentFocus(); + // Restore an old unverified-only filter after the last report disappears. + await run("window.__archifyRestoreReading({ reading: { kind: 'findings' }, open: true, filters: { unverified: true, search: '', status: 'all' } })"); + assert.equal(await run("Boolean(document.querySelector('.unverified-filter'))"), false); + assert.ok(await run("document.querySelectorAll('#bauify-overview .finding-row').length") > 0, 'internal findings stay visible when the external-only control is absent'); + await run("document.querySelector('.findings-back').click()"); + + const complexId = await run(`(() => { + const finding = JSON.parse(document.getElementById('bauify-analysis').textContent).findings.find(f => f.code === 'complexity/function' && f.subject.file === 'complex.mjs'); + if (!finding) return null; + window.__archifyShowFinding(finding.id); + document.querySelector('#bauify-detail .inline-evidence .ref').click(); + return finding.id; + })()`); + assert.ok(complexId, 'the fixture has a complex function and opens its inline source'); + await refreshFromCurrentFocus(); + assert.equal(await run("document.getElementById('bauify-code').hidden"), false, 'duplicate link locations do not hide the original inline source'); + assert.ok(toolbarClicks > 0, 'the toolbar was reached by a real browser pointer'); + await run("document.querySelector('#bauify-code .source-back').click(); document.querySelector('.more-evidence').open = true; document.querySelector('.more-evidence .ref[data-file]').click()"); + await refreshFromCurrentFocus(); + assert.equal(await run("document.getElementById('bauify-code').hidden"), false, 'expanded rule evidence reopens its source after re-analysis'); + await run("document.querySelector('#bauify-code .source-back').click()"); + assert.equal(await run("document.querySelector('.more-evidence').open"), true, 'returning from restored source leaves the evidence visible'); + assert.equal(await run("document.activeElement.matches('.more-evidence .ref[data-file]')"), true, 'returning from restored source focuses its visible evidence'); + await run("document.querySelector('#bauify-detail .back').click()"); + + const has3d = await run(`(() => { + document.querySelector('.views-option[data-view=atlas3d]').click(); + const view = window.__archifyAtlas3d.view; + if (!view || view.failed) return false; + const atlas = JSON.parse(document.getElementById('bauify-atlas-data').textContent); + const index = atlas.functions.findIndex(fn => atlas.files[fn[0]][0] === 'complex.mjs'); + if (index < 0) throw Error('complex function missing from 3D fixture'); + view.select({ type: 'function', index }); + return true; + })()`); + if (has3d) { + const before3d = await run('window.__archifyAtlas3d.view.saveSelection()'); + assert.equal(before3d.unique, true, 'the selected fixture function has a unique name'); + write('complex.mjs', '\n' + fs.readFileSync(path.join(root, 'complex.mjs'), 'utf8')); + await refreshFromCurrentFocus(); + const after3d = await run('window.__archifyAtlas3d.view.saveSelection()'); + assert.equal(after3d?.name, before3d.name, '3D restores the unique function after a line shift'); + assert.equal(after3d?.line, before3d.line + 1); + const findingId = await run(`(() => { const atlas = JSON.parse(document.getElementById('bauify-atlas-data').textContent); const i = atlas.findings.findIndex(f => f.kind === 'function' && atlas.files[atlas.functions[f.fn][0]][0] === 'complex.mjs'); if (i < 0) throw Error('stable finding missing'); window.__archifyAtlas3d.view.select({ type: 'finding', index: i }); return atlas.findings[i].id; })()`); + await refreshFromCurrentFocus(); + const restoredFinding = await run('window.__archifyAtlas3d.view.saveSelection()'); + assert.equal(restoredFinding?.type, 'finding', 'a stable function-backed finding keeps its selection type'); + assert.equal(restoredFinding?.id, findingId, 'a stable function-backed finding survives an unchanged run'); + const decisions = Array.from({ length: 20 }, (_, i) => `if (value === ${i}) value++;`).join(' '); + write('same-methods.mjs', `export class Service {\n static dispatch(value) { ${decisions} return value; }\n dispatch(value) { ${decisions} return value + 1; }\n}\n`); + await refreshFromCurrentFocus(); + const methodFindings = await run(`(() => { + const atlas = JSON.parse(document.getElementById('bauify-atlas-data').textContent); + return atlas.findings.filter(f => f.kind === 'function' && f.fn !== undefined + && atlas.files[atlas.functions[f.fn][0]][0] === 'same-methods.mjs') + .map(f => ({ id: f.id, line: atlas.functions[f.fn][2] })); + })()`); + assert.deepEqual(methodFindings.map(f => f.line).sort(), [2, 3], 'both same-named methods have distinct findings'); + for (const finding of methodFindings) { + await run(`(() => { const atlas = JSON.parse(document.getElementById('bauify-atlas-data').textContent); const index = atlas.findings.findIndex(f => f.id === ${JSON.stringify(finding.id)}); window.__archifyAtlas3d.view.select({ type: 'finding', index }); })()`); + await refreshFromCurrentFocus(); + const restored = await run('window.__archifyAtlas3d.view.saveSelection()'); + assert.equal(restored?.type, 'finding'); + assert.equal(restored?.id, finding.id, 'each same-named method restores its own finding'); + } + write('quoted.mjs', "const handlers = { ''() { return 'fallback'; } };\n"); + await refreshFromCurrentFocus(); + const quoted = await run(`(() => { + const atlas = JSON.parse(document.getElementById('bauify-atlas-data').textContent); + const i = atlas.functions.findIndex(fn => atlas.files[fn[0]][0] === 'quoted.mjs'); + if (i < 0) throw Error('quoted method missing from fixture'); + window.__archifyAtlas3d.view.select({ type: 'function', index: i }); + return window.__archifyAtlas3d.view.saveSelection(); + })()`); + assert.equal(quoted.unique, true, 'a quoted method has a unique captured definition'); + write('quoted.mjs', "\nconst handlers = { ''() { return 'fallback'; } };\n"); + await refreshFromCurrentFocus(); + const quotedAfter = await run('window.__archifyAtlas3d.view.saveSelection()'); + assert.equal(quotedAfter?.digest, quoted.digest, 'the explicitly named method survives a line shift'); + assert.equal(quotedAfter?.line, quoted.line + 1); + write('duplicate-names.mjs', '{ const repeated = () => 1; }\n{ const repeated = () => 1; }\n'); + await refreshFromCurrentFocus(); + const duplicate = await run(`(() => { const atlas = JSON.parse(document.getElementById('bauify-atlas-data').textContent); const i = atlas.functions.findIndex(fn => atlas.files[fn[0]][0] === 'duplicate-names.mjs' && fn[1] === 'repeated'); if (i < 0) throw Error('duplicate binding missing'); window.__archifyAtlas3d.view.select({ type: 'function', index: i }); return window.__archifyAtlas3d.view.saveSelection(); })()`); + assert.equal(duplicate.stableName, true); + assert.equal(duplicate.unique, false, 'identical stable bindings are ambiguous even when names match'); + await refreshFromCurrentFocus(); + assert.equal(await run('window.__archifyAtlas3d.view.saveSelection()'), null, 'an ambiguous stable binding is not restored'); + write('bindings.mjs', 'const onSave = () => 1;\n'); + await refreshFromCurrentFocus(); + await run(`(() => { const atlas = JSON.parse(document.getElementById('bauify-atlas-data').textContent); const i = atlas.functions.findIndex(fn => atlas.files[fn[0]][0] === 'bindings.mjs' && fn[1] === 'onSave'); if (i < 0) throw Error('binding missing'); window.__archifyAtlas3d.view.select({ type: 'function', index: i }); })()`); + write('bindings.mjs', 'const onCancel = () => 1;\nconst onSave = () => 2;\n'); + await refreshFromCurrentFocus(); + assert.equal(await run('window.__archifyAtlas3d.view.saveSelection()'), null, 'copying the old body under a different binding does not switch selection'); + write('callbacks.mjs', 'app.use(() => 1);\n'); + await refreshFromCurrentFocus(); + const callback = await run(`(() => { + const atlas = JSON.parse(document.getElementById('bauify-atlas-data').textContent); + const i = atlas.functions.findIndex(fn => atlas.files[fn[0]][0] === 'callbacks.mjs'); + if (i < 0) throw Error('callback missing from fixture'); + window.__archifyAtlas3d.view.select({ type: 'function', index: i }); + return window.__archifyAtlas3d.view.saveSelection(); + })()`); + assert.equal(callback.stableName, false, 'the callback name depends on source order'); + write('callbacks.mjs', 'app.use(() => 2);\napp.use(() => 1);\n'); + await refreshFromCurrentFocus(); + assert.equal(await run('window.__archifyAtlas3d.view.saveSelection()'), null, 'a newly inserted callback is not mistaken for the old selection'); + await run(`(() => { const atlas = JSON.parse(document.getElementById('bauify-atlas-data').textContent); const i = atlas.functions.findIndex(fn => atlas.files[fn[0]][0] === 'callbacks.mjs'); window.__archifyAtlas3d.view.select({ type: 'function', index: i }); })()`); + write('callbacks.mjs', 'app.use(() => 1);\napp.use(() => 1);\n'); + await refreshFromCurrentFocus(); + assert.equal(await run('window.__archifyAtlas3d.view.saveSelection()'), null, 'identical callbacks have no unique captured identity'); + const complexCallback = 'app.use((x) => {' + Array.from({ length: 25 }, (_, i) => `if (x === ${i}) return ${i};`).join('') + 'return 0; });\n'; + write('callbacks.mjs', complexCallback); + await refreshFromCurrentFocus(); + await run(`(() => { const atlas = JSON.parse(document.getElementById('bauify-atlas-data').textContent); const i = atlas.findings.findIndex(f => f.kind === 'function' && atlas.files[atlas.functions[f.fn][0]][0] === 'callbacks.mjs'); if (i < 0) throw Error('callback finding missing'); window.__archifyAtlas3d.view.select({type: 'finding', index: i}); })()`); + write('callbacks.mjs', complexCallback.replace('return 0;', 'return -1;') + complexCallback); + await refreshFromCurrentFocus(); + assert.equal(await run('window.__archifyAtlas3d.view.saveSelection()'), null, 'an inserted callback finding cannot inherit the selected finding identity'); + write('unnamed-binding.mjs', 'const onSave = function () { return 1; };\n'); + await refreshFromCurrentFocus(); + await run(`(() => { const atlas = JSON.parse(document.getElementById('bauify-atlas-data').textContent); const i = atlas.functions.findIndex(fn => atlas.files[fn[0]][0] === 'unnamed-binding.mjs'); if (i < 0) throw Error('bound anonymous expression missing'); window.__archifyAtlas3d.view.select({ type: 'function', index: i }); })()`); + await refreshFromCurrentFocus(); + assert.equal(await run('window.__archifyAtlas3d.view.saveSelection()?.name'), 'onSave', 'an unchanged anonymous expression with a stable variable binding is restored'); + write('named-bindings.mjs', 'const onSave = function handler() { return 1; };\n'); + await refreshFromCurrentFocus(); + await run(`(() => { const atlas = JSON.parse(document.getElementById('bauify-atlas-data').textContent); const i = atlas.functions.findIndex(fn => atlas.files[fn[0]][0] === 'named-bindings.mjs'); if (i < 0) throw Error('named expression missing'); window.__archifyAtlas3d.view.select({ type: 'function', index: i }); })()`); + write('named-bindings.mjs', 'const onCancel = function handler() { return 1; };\nconst onSave = function handler() { return 2; };\n'); + await refreshFromCurrentFocus(); + assert.equal(await run('window.__archifyAtlas3d.view.saveSelection()'), null, 'a copied named expression must not restore the wrong binding'); + assert.match(await run("document.querySelector('.analysis-refresh-status').textContent"), /selection is no longer available/); + } else t.diagnostic('3D re-analysis handoff requires WebGL and was not exercised'); + await run("document.querySelector('.views-option[data-view=diagram]').click()"); + // A failing run keeps the last good result on disk and on the page. const before = fs.readFileSync(path.join(out, 'analysis', 'findings.json'), 'utf8'); fs.writeFileSync(baseline, '{ "schema_version": 1, "accepted": [{ "id": "broken" }] }'); diff --git a/test/code-analysis-standalone-browser.test.mjs b/test/code-analysis-standalone-browser.test.mjs index 7fb35d27b9..3d1c4cd45a 100644 --- a/test/code-analysis-standalone-browser.test.mjs +++ b/test/code-analysis-standalone-browser.test.mjs @@ -43,13 +43,26 @@ test('standalone workbench keeps Atlas alongside evidence, both locales/themes a })`); const viewport = (width, height) => send('Emulation.setDeviceMetricsOverride', { width, height, deviceScaleFactor: 1, mobile: false }); const motion = value => send('Emulation.setEmulatedMedia', { features: [{ name: 'prefers-reduced-motion', value }] }); - const point = selector => run(`(() => { + const point = selector => run(`new Promise((resolve, reject) => { const node = document.querySelector(${JSON.stringify(selector)}); node.scrollIntoView({ block: 'nearest' }); - const r = node.getBoundingClientRect(); - return { x: r.left + r.width / 2, y: r.top + r.height / 2 }; - })()`); + const deadline = Date.now() + 4000; + let previous, stableSince = 0; + // Back transitions reveal a different scrollable panel; allow its layout + // to settle without delaying the other controls in the workflow. + const settleMs = /(?:source-back|#bauify-detail \.back)$/.test(${JSON.stringify(selector)}) ? 250 : 0; + function poll() { + const r = node.getBoundingClientRect(), x = r.left + r.width / 2, y = r.top + r.height / 2; + const hit = document.elementFromPoint(x, y), valid = r.width > 0 && r.height > 0 && node.contains(hit); + if (!valid || !previous || previous.x !== x || previous.y !== y) stableSince = Date.now(); + else if (Date.now() - stableSince >= settleMs) return resolve({ x, y }); + if (Date.now() >= deadline) return reject(new Error('Target is not stable and clickable: ' + ${JSON.stringify(selector)})); + previous = { x, y }; requestAnimationFrame(poll); + } + requestAnimationFrame(poll); + })`); const clickAt = async p => { + await send('Input.dispatchMouseEvent', { type: 'mouseMoved', ...p }); for (const type of ['mousePressed', 'mouseReleased']) await send('Input.dispatchMouseEvent', { type, ...p, button: 'left', clickCount: 1 }); }; const click = async selector => clickAt(await point(selector)); @@ -149,6 +162,7 @@ test('standalone workbench keeps Atlas alongside evidence, both locales/themes a && ${readerWidthSettled}`, 'finding reader did not return from source'); assert.equal(await run(selectedFinding), id, 'returning from source keeps the detail selected'); await click(`${details} .back`); + await wait("!document.getElementById('bauify-overview').hidden", 'finding did not return to overview'); assert.equal(await run("document.getElementById('bauify-overview').hidden"), false, 'Back opens the overview'); assert.equal(await run(selectedFinding), '', 'returning to the overview restores no selection'); assert.equal(await run("!document.querySelector('.atlas-selection .selected')"), true); diff --git a/test/code-analysis-task-browser.test.mjs b/test/code-analysis-task-browser.test.mjs index 1b12312ce9..9daf67e826 100644 --- a/test/code-analysis-task-browser.test.mjs +++ b/test/code-analysis-task-browser.test.mjs @@ -133,6 +133,8 @@ test('AI task reader: evidence first, live validation, clipboard fallback, downl await wait("/newer analysis snapshot/.test(document.querySelector('#bauify-detail .task-status').textContent)"); assert.equal(await run("document.querySelector('#bauify-detail .task-copy').disabled"), true, 'a stable ID must not mix old page evidence with a newer task'); assert.equal(await run("taskRequests.length > 0 && taskRequests.every(r => r.expected && r.ids.every(id => r.expected[id] === JSON.parse(document.getElementById('bauify-analysis').textContent).findings.find(f => f.id === id).reviewTarget))"), true, 'native preview, quick copy, refresh and download requests bind the claim displayed by the page'); + // The current finding is retained on refresh; return before testing the overview. + await run("document.querySelector('#bauify-detail .back').click()"); // Large reports remain navigable; accepted findings stay out of priority slots. fs.writeFileSync(sourceFile, source); const manyFile = path.join(root, 'many.py'); diff --git a/test/code-analysis.test.mjs b/test/code-analysis.test.mjs index 5e085e35d7..52d6fbdfe5 100644 --- a/test/code-analysis.test.mjs +++ b/test/code-analysis.test.mjs @@ -3,10 +3,16 @@ import { spawnSync } from 'node:child_process'; import path from 'node:path'; import { fileURLToPath } from 'node:url'; import { test } from 'node:test'; +import { createTranslator, messagesFor } from '../archify/modules/code-analysis/overlay/i18n.mjs'; const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..', 'archify'); const cli = path.join(root, 'bin/archify.mjs'); const moduleRoot = path.join(root, 'modules/code-analysis'); const run = args => spawnSync(process.execPath, [cli, 'code-analysis', ...args], { encoding: 'utf8' }); +test('verification labels and mismatch guidance have Chinese translations', () => { + const translate = createTranslator(messagesFor('zh-CN')); + assert.equal(translate('Task JSON from the previous run'), '上一轮导出的任务 JSON'); + assert.equal(translate('The task does not match the previous analysis.'), '任务与上一轮分析不匹配。'); +}); test('Code Analysis exposes the workbench, checks, task and verification commands through the Archify CLI', () => { const publicHelp = spawnSync(process.execPath, [cli, '--help'], { encoding: 'utf8' }); assert.equal(publicHelp.status, 0); diff --git a/test/temp-cleanup.test.mjs b/test/temp-cleanup.test.mjs index d844256e46..11aec89ebd 100644 --- a/test/temp-cleanup.test.mjs +++ b/test/temp-cleanup.test.mjs @@ -369,10 +369,13 @@ test('Windows file share lock is reported, then cleanup succeeds after release', child.once('exit', resolve); }); try { - for (let attempt = 0; attempt < 250 && !fs.existsSync(ready) && child.exitCode === null; attempt++) { - await delay(20); + // Windows CI can take longer than five seconds to launch PowerShell under + // load. Still require the real lock before asserting cleanup behavior. + const deadline = Date.now() + 30000; + while (!fs.existsSync(ready) && child.exitCode === null && child.signalCode === null && Date.now() < deadline) { + await delay(50); } - assert.ok(fs.existsSync(ready), `lock process did not become ready: ${stderr}`); + assert.ok(fs.existsSync(ready), `lock process did not become ready (exit ${child.exitCode}, signal ${child.signalCode}): ${stderr}`); await assert.rejects(owned.cleanup(), { code: 'ARCHIFY_TEMP_CLEANUP' }); assert.ok(fs.existsSync(lockedFile)); } finally {