Turn any idea, plan, or codebase into a beautiful interactive diagram. An agent skill for Claude Code, Codex, and more.
HTML agent-skillsai-agentsarchitecture-diagramclaude-codeclaude-skillscodexcoding-agentsdeepseek-harnessdeveloper-toolsdiagramsdiagrams-as-codedsh-pluginflowchartllmmermaidopencodesequence-diagramsoftware-architecturesystem-designvisualization
fix: inspect verified snapshots outside Windows UNC paths
sunsunsunb78cca5b0b9a
diff --git a/archify.zip b/archify.zipindex 31d1bb73..2aa99ba8 100644Binary files a/archify.zip and b/archify.zip differdiff --git a/archify/bin/visual-check.mjs b/archify/bin/visual-check.mjsindex 47b4a443..45092762 100644--- a/archify/bin/visual-check.mjs+++ b/archify/bin/visual-check.mjs@@ -555,20 +555,28 @@ function cleanupStagedEvidence(ownership, { removeDirectory = false } = {}) {});}}- if (removeDirectory) {+ const directories = [+ ownership.inspection,+ ...(removeDirectory ? [{+ directory: ownership.stagingDirectory,+ identity: ownership.stagingIdentity,+ }] : []),+ ].filter(Boolean);+ for (const { directory, identity } of directories) {try {- const stat = fs.lstatSync(ownership.stagingDirectory, { bigint: true });- if (!identityMatches(stat, ownership.stagingIdentity, { directory: true })) {+ const stat = fs.lstatSync(directory, { bigint: true });+ if (!identity || !identityMatches(stat, identity, { directory: true })) {errors.push({- file: ownership.stagingDirectory,+ file: directory,+ recoveryDirectory: directory,reason: 'staging directory identity changed; it was preserved',});} else {- removeEmptyDirectoryWithRetry(ownership.stagingDirectory);+ removeEmptyDirectoryWithRetry(directory);}} catch (error) {if (error?.code !== 'ENOENT') {- errors.push({ file: ownership.stagingDirectory, reason: error.message });+ errors.push({ file: directory, recoveryDirectory: directory, reason: error.message });}}}@@ -941,7 +949,8 @@ function restoreOwnedBackup(backup, errors) {function commitVisualEvidence(artifactPath, outputs, ownership, desiredPaths) {const verification = verifyVisualEvidenceTargets(artifactPath, outputs, ownership);if (!verification.ok) {- cleanupStagedEvidence(ownership, { removeDirectory: true });+ const cleanupErrors = cleanupStagedEvidence(ownership, { removeDirectory: true });+ if (cleanupErrors.length) verification.diagnostic.evidence.rollbackErrors = cleanupErrors;ownership.active = false;return verification;}@@ -1180,6 +1189,7 @@ function commitVisualEvidence(artifactPath, outputs, ownership, desiredPaths) {recoveryDirectory = ownership.stagingDirectory;}} catch {}+ recoveryDirectory ||= cleanupErrors.find((entry) => entry.recoveryDirectory)?.recoveryDirectory;}return {ok: true,@@ -1333,6 +1343,10 @@ class PipeCdp {this.failureDetails = failureDetails;this.nextId = 1;this.buffer = '';+ this.receivedBytes = 0;+ this.receivedMessages = 0;+ this.completedWrites = 0;+ this.writtenBytes = 0;this.pending = new Map();this.waiters = [];this.writePipe = child.stdio[3];@@ -1341,6 +1355,9 @@ class PipeCdp {this.readPipe.on('data', (chunk) => this.consume(chunk));this.writePipe.on('error', (error) => this.failAll(this.failure('write pipe', error)));this.readPipe.on('error', (error) => this.failAll(this.failure('read pipe', error)));+ this.readPipe.once('end', () => this.failAll(this.failure('read pipe', new Error('stream ended'))));+ this.readPipe.once('close', () => this.failAll(this.failure('read pipe', new Error('stream closed'))));+ this.writePipe.once('close', () => this.failAll(this.failure('write pipe', new Error('stream closed'))));child.once('error', (error) => this.failAll(this.failure('process launch', error)));child.once('close', (code, signal) => {const ending = signal ? `signal ${signal}` : `exit code ${code}`;@@ -1354,10 +1371,14 @@ class PipeCdp {return new Error([`Chrome DevTools ${stage} failed: ${error?.message || String(error)}${code}`,details,+ `Chrome transport: Node ${process.version}, libuv ${process.versions.uv}, ${process.platform}; pid=${this.child.pid ?? 'unavailable'}, exitCode=${this.child.exitCode}, signalCode=${this.child.signalCode}.`,+ `Chrome read pipe: readable=${this.readPipe.readable}, ended=${this.readPipe.readableEnded}, destroyed=${this.readPipe.destroyed}, receivedBytes=${this.receivedBytes}, messages=${this.receivedMessages}, bufferedBytes=${Buffer.byteLength(this.buffer)}.`,+ `Chrome write pipe: writable=${this.writePipe.writable}, ended=${this.writePipe.writableEnded}, destroyed=${this.writePipe.destroyed}, completedWrites=${this.completedWrites}, writtenBytes=${this.writtenBytes}, bufferedBytes=${this.writePipe.writableLength}.`,].filter(Boolean).join('\n'));}consume(chunk) {+ this.receivedBytes += Buffer.byteLength(chunk);this.buffer += chunk;let boundary;while ((boundary = this.buffer.indexOf('\0')) >= 0) {@@ -1371,6 +1392,7 @@ class PipeCdp {this.failAll(new Error(`Chrome DevTools returned invalid JSON: ${error.message}`));continue;}+ this.receivedMessages += 1;if (message.id) {const pending = this.pending.get(message.id);if (!pending) continue;@@ -1397,12 +1419,18 @@ class PipeCdp {return new Promise((resolve, reject) => {const timer = setTimeout(() => {this.pending.delete(id);- reject(new Error(`${method}: timed out after ${timeoutMs}ms`));+ reject(this.failure('command timeout', new Error(`${method}: timed out after ${timeoutMs}ms`)));}, timeoutMs);this.pending.set(id, { method, resolve, reject, timer });try {- this.writePipe.write(`${JSON.stringify(message)}\0`, (error) => {- if (error) this.failAll(this.failure('write pipe', error));+ const serialized = `${JSON.stringify(message)}\0`;+ this.writePipe.write(serialized, (error) => {+ if (error) {+ this.failAll(this.failure('write pipe', error));+ } else {+ this.completedWrites += 1;+ this.writtenBytes += Buffer.byteLength(serialized);+ }});} catch (error) {this.failAll(this.failure('write pipe', error));@@ -1415,7 +1443,7 @@ class PipeCdp {const waiter = { method, sessionId, resolve, reject, timer: null };waiter.timer = setTimeout(() => {this.waiters.splice(this.waiters.indexOf(waiter), 1);- reject(new Error(`${method}: event timed out after ${timeoutMs}ms`));+ reject(this.failure('event timeout', new Error(`${method}: event timed out after ${timeoutMs}ms`)));}, timeoutMs);this.waiters.push(waiter);});@@ -1478,22 +1506,6 @@ async function evaluate(cdp, sessionId, expression, awaitPromise = false) {return response.result?.value;}-export function chromeVisualArtifactUrl(artifactPath, theme, { platform = process.platform } = {}) {- const localhostUnc = platform === 'win32'- ? /^(?:\\\\\?\\UNC\\|\\\\)localhost\\(.+)$/i.exec(artifactPath)- : null;- if (localhostUnc) {- // WHATWG file URLs erase the localhost host, turning this UNC share into- // a drive-root path. Chromium retains the raw host for non-drive paths.- // Send this string directly to DevTools without reparsing it as a URL.- const encodedPath = localhostUnc[1].split('\\').map(encodeURIComponent).join('/');- return 'file://localhost/' + encodedPath + '?' + new URLSearchParams({ theme });- }- const url = pathToFileURL(artifactPath);- url.searchParams.set('theme', theme);- return url.href;-}-export class ChromeVisualBrowser {constructor(chromePath, {env = process.env,@@ -1551,13 +1563,14 @@ export class ChromeVisualBrowser {mobile: false,}, sessionId);- const url = chromeVisualArtifactUrl(artifactPath, theme);+ const url = pathToFileURL(artifactPath);+ url.searchParams.set('theme', theme);const loaded = this.cdp.waitFor('Page.loadEventFired', sessionId);// Navigation can fail before this waiter is awaited. Attach a rejection// handler immediately so a later load failure never escapes as an// unhandled rejection; awaiting `loaded` below still reports it normally.loaded.catch(() => {});- const navigation = await this.cdp.send('Page.navigate', { url }, sessionId);+ const navigation = await this.cdp.send('Page.navigate', { url: url.href }, sessionId);if (navigation.errorText) throw new Error(`Chrome navigation failed: ${navigation.errorText}`);await loaded;await evaluate(this.cdp, sessionId, `(function () {@@ -2135,9 +2148,20 @@ export async function runVisualCheck({return { exitCode: EXIT.fail, receipt };}const ownership = preflight.ownership;- const inspectionArtifact = path.join(ownership.stagingDirectory, 'artifact-snapshot.html');- ownership.stagingPaths.set(artifact, inspectionArtifact);+ let inspectionArtifact;try {+ // Chrome's file loader cannot reliably open long Windows/UNC paths. Keep+ // the one inspected snapshot local; publish evidence on its target volume.+ ownership.inspection = {+ directory: fs.mkdtempSync(path.join(os.tmpdir(), 'archify-inspection-')),+ };+ const stat = fs.lstatSync(ownership.inspection.directory, { bigint: true });+ if (!stat.isDirectory() || stat.isSymbolicLink() || stat.ino === 0n) {+ throw new Error('the private inspection directory has no stable identity');+ }+ ownership.inspection.identity = fileIdentity(stat);+ inspectionArtifact = path.join(ownership.inspection.directory, 'artifact-snapshot.html');+ ownership.stagingPaths.set(artifact, inspectionArtifact);writeStagedEvidence(ownership, artifact, artifactBytes);} catch (error) {return { exitCode: EXIT.fail, receipt: persistVisualCheckFailure(artifact, {diff --git a/archify/references/delivery-contract.md b/archify/references/delivery-contract.mdindex 24b88346..0b3f8409 100644--- a/archify/references/delivery-contract.md+++ b/archify/references/delivery-contract.md@@ -317,6 +317,12 @@ and final names a link count of two; unlinking the verified staged name mustleave the final entry with a link count of one. An unexpected external hardlink fails closed and its alias is never removed.+Chrome inspects one identity- and content-checked copy of the captured artifact+in a private local temporary directory, so browser file loading does not depend+on UNC or long-path support. The six publication candidates remain on the+evidence volume. Both temporary directories are cleaned without recursively+deleting unknown contents; retained entries include their recovery locations.+Immediately before committing anything, `visual-check` re-resolves and verifiesthe complete six-path set. An absent-path claimant, existing-path replacement,symbolic-link or dangling-link retarget, parent-topology change, hard link, ordiff --git a/archify/test/chrome-pipe-transport.test.mjs b/archify/test/chrome-pipe-transport.test.mjsnew file mode 100644index 00000000..0daf92d5--- /dev/null+++ b/archify/test/chrome-pipe-transport.test.mjs@@ -0,0 +1,73 @@+import assert from 'node:assert/strict';+import { EventEmitter } from 'node:events';+import { PassThrough } from 'node:stream';+import { test } from 'node:test';++import { ChromeVisualBrowser } from '../bin/visual-check.mjs';++function chromeChild() {+ const child = new EventEmitter();+ child.pid = 7321;+ child.exitCode = null;+ child.signalCode = null;+ child.stderr = new PassThrough();+ child.stdio = [null, null, child.stderr, new PassThrough(), new PassThrough()];+ child.kill = (signal) => {+ child.signalCode = signal;+ queueMicrotask(() => {+ child.emit('exit', null, signal);+ child.emit('close', null, signal);+ });+ return true;+ };+ return child;+}++function browserFor(child) {+ return new ChromeVisualBrowser('/fake/chrome', {+ env: {},+ getuid: () => 1001,+ spawnImpl: () => child,+ });+}++test('Chrome first-command timeout reports the running process, pipe progress and stderr', async (t) => {+ const setTimeout = globalThis.setTimeout;+ t.mock.method(globalThis, 'setTimeout', (callback, delay, ...args) =>+ setTimeout(callback, delay === 15000 ? 5 : delay, ...args));+ const child = chromeChild();+ const browser = browserFor(child);+ child.stderr.write('Browser initialization is waiting for a service\n');+ try {+ await assert.rejects(browser.sessionPromise, (error) => {+ assert.match(error.message, /Target\.getTargets: timed out after 15000ms/);+ assert.match(error.message, /Chrome process: still running/);+ assert.match(error.message, /pid=7321/);+ assert.match(error.message, /Node v\d+.*libuv/);+ assert.match(error.message, /completedWrites=1/);+ assert.match(error.message, /receivedBytes=0/);+ assert.match(error.message, /Browser initialization is waiting for a service/);+ return true;+ });+ } finally {+ await browser.close();+ }+});++test('Chrome pipe EOF fails the pending first command without waiting for process close', async () => {+ const child = chromeChild();+ const browser = browserFor(child);+ try {+ const result = assert.rejects(browser.sessionPromise, /Chrome DevTools read pipe failed:.*ended/);+ child.stdio[4].end();+ await Promise.race([+ result,+ new Promise((_, reject) => {+ const timer = setTimeout(() => reject(new Error('pipe EOF did not reject the pending command')), 100);+ timer.unref();+ }),+ ]);+ } finally {+ await browser.close();+ }+});diff --git a/archify/test/visual-check-browser-url.test.mjs b/archify/test/visual-check-browser-url.test.mjsdeleted file mode 100644index abf9760f..00000000--- a/archify/test/visual-check-browser-url.test.mjs+++ /dev/null@@ -1,55 +0,0 @@-import { test } from 'node:test';-import assert from 'node:assert/strict';-import path from 'node:path';-import { pathToFileURL } from 'node:url';--import { ChromeVisualBrowser, chromeVisualArtifactUrl } from '../bin/visual-check.mjs';--test('Chrome inspection preserves localhost UNC shares instead of treating them as drive-root paths', () => {- for (const prefix of [String.raw`\\localhost`, String.raw`\\?\UNC\localhost`]) {- const artifact = `${prefix}\\share\\nested folder\\图 #%25.html`;- assert.equal(- chromeVisualArtifactUrl(artifact, 'dark', { platform: 'win32' }),- 'file://localhost/share/nested%20folder/%E5%9B%BE%20%23%2525.html?theme=dark',- );- }-});--test('Chrome inspection preserves localhost UNC paths beyond MAX_PATH', () => {- const directories = Array.from({ length: 10 }, (_, index) => `long-directory-${index}-${'x'.repeat(20)}`);- const artifact = `\\\\?\\UNC\\LOCALHOST\\share\\${directories.join('\\')}\\artifact-snapshot.html`;- assert.ok(artifact.length > 320);- assert.equal(- chromeVisualArtifactUrl(artifact, 'light', { platform: 'win32' }),- `file://localhost/share/${directories.join('/')}/artifact-snapshot.html?theme=light`,- );-});--test('Chrome inspection retains native file URL escaping and theme query semantics', () => {- const artifact = path.resolve('图 # 100%.html');- const expected = pathToFileURL(artifact);- expected.searchParams.set('theme', 'dark&unintended=value');- assert.equal(chromeVisualArtifactUrl(artifact, 'dark&unintended=value'), expected.href);-});--test('Chrome inspection sends the localhost UNC URL directly to DevTools without recanonicalizing it', async () => {- const artifact = String.raw`\\?\UNC\localhost\share\artifact-snapshot.html`;- const browser = Object.create(ChromeVisualBrowser.prototype);- const calls = [];- browser.sessionPromise = Promise.resolve('test-session');- browser.cdp = {- waitFor: () => Promise.resolve(),- async send(method, parameters) {- calls.push({ method, parameters });- return method === 'Page.navigate' ? { errorText: 'stop after navigation' } : {};- },- };- const platformDescriptor = Object.getOwnPropertyDescriptor(process, 'platform');- try {- Object.defineProperty(process, 'platform', { ...platformDescriptor, value: 'win32' });- await assert.rejects(browser.inspect({ artifactPath: artifact, width: 1440, height: 900, theme: 'dark' }), /stop after navigation/);- } finally {- Object.defineProperty(process, 'platform', platformDescriptor);- }- assert.equal(calls.find(({ method }) => method === 'Page.navigate').parameters.url, 'file://localhost/share/artifact-snapshot.html?theme=dark');-});diff --git a/archify/test/visual-check.test.mjs b/archify/test/visual-check.test.mjsindex 7040fb43..adea1356 100644--- a/archify/test/visual-check.test.mjs+++ b/archify/test/visual-check.test.mjs@@ -338,6 +338,156 @@ test('visual-check inspects a private snapshot even if the public artifact is reassert.deepEqual(fs.readFileSync(input), original);});+for (const browserFailure of [false, true]) {+ test(`visual-check uses and retires a short local snapshot with long evidence paths${browserFailure ? ' after a browser failure' : ''}`, async (t) => {+ const input = artifact(`local-inspection-${browserFailure}.html`);+ const original = fs.readFileSync(input);+ const originalDigest = sha256(input);+ const root = fs.mkdtempSync(path.join(tmp, 'long-evidence-'));+ const outDir = path.join(root, ...Array.from({ length: 5 }, (_, index) => `${index}-${'long'.repeat(16)}`));+ t.after(() => fs.rmSync(root, { recursive: true, force: true }));+ const browser = fakeBrowser();+ const inspect = browser.inspect.bind(browser);+ let inspectionPath;+ browser.inspect = async (args) => {+ inspectionPath = args.artifactPath;+ assert.ok(!fs.realpathSync(inspectionPath).startsWith(`${fs.realpathSync(outDir)}${path.sep}`));+ assert.equal(fs.realpathSync(path.dirname(path.dirname(inspectionPath))), fs.realpathSync(os.tmpdir()));+ assert.ok(inspectionPath.length < outDir.length);+ assert.deepEqual(fs.readFileSync(inspectionPath), original);+ assert.equal(sha256(inspectionPath), originalDigest);+ if (args.screenshotPath) assert.ok(fs.realpathSync(path.dirname(args.screenshotPath)).startsWith(`${fs.realpathSync(outDir)}${path.sep}`));+ if (browserFailure) throw new Error('synthetic local snapshot browser failure');+ return inspect(args);+ };++ const result = await runVisualCheck({+ artifactPath: input,+ outDir,+ chromePath: '/fake/chrome',+ browserFactory: async () => browser,+ });++ assert.equal(result.exitCode, browserFailure ? 1 : 0, JSON.stringify(result.receipt.diagnostics));+ assert.ok(inspectionPath);+ assert.equal(fs.existsSync(inspectionPath), false);+ assert.equal(fs.existsSync(path.dirname(inspectionPath)), false);+ assert.deepEqual(stagingDirectories(outDir), []);+ assert.equal(fs.existsSync(sidecarPaths(input, { outDir }).receipt), true);+ if (browserFailure) assert.match(result.receipt.error, /synthetic local snapshot browser failure/);+ });+}++test('visual-check retains and reports a local inspection directory that cannot be removed', async (t) => {+ const input = artifact('local-inspection-rmdir-failure.html');+ const browser = fakeBrowser();+ const inspect = browser.inspect.bind(browser);+ const rmdirSync = fs.rmdirSync.bind(fs);+ let inspectionDirectory;+ browser.inspect = async (args) => {+ inspectionDirectory = path.dirname(args.artifactPath);+ return inspect(args);+ };+ t.mock.method(fs, 'rmdirSync', (directory, ...args) => {+ if (String(directory) === inspectionDirectory) {+ throw Object.assign(new Error('synthetic local inspection directory removal failure'), { code: 'EACCES' });+ }+ return rmdirSync(directory, ...args);+ });+ t.after(() => {+ t.mock.restoreAll();+ if (inspectionDirectory) fs.rmSync(inspectionDirectory, { recursive: true, force: true });+ });++ const result = await runVisualCheck({+ artifactPath: input,+ chromePath: '/fake/chrome',+ browserFactory: async () => browser,+ });++ assert.equal(result.exitCode, 1);+ assert.equal(fs.realpathSync(path.dirname(inspectionDirectory)), fs.realpathSync(os.tmpdir()));+ assert.equal(result.receipt.publication?.status, 'committed-with-warning');+ assert.equal(result.receipt.publication?.recoveryDirectory, inspectionDirectory);+ assert.ok(result.receipt.publication.cleanupErrors.some((entry) => entry.file === inspectionDirectory));+ assert.deepEqual(fs.readdirSync(inspectionDirectory), []);+});++test('visual-check reports the retained local snapshot directory when its identity is unavailable', async (t) => {+ const input = artifact('local-inspection-unknown-identity.html');+ const lstatSync = fs.lstatSync.bind(fs);+ let inspectionDirectory;+ let browserStarted = false;+ t.mock.method(fs, 'lstatSync', (file, ...args) => {+ const stat = lstatSync(file, ...args);+ if (!inspectionDirectory && path.basename(String(file)).startsWith('archify-inspection-')) {+ inspectionDirectory = String(file);+ stat.ino = 0n;+ }+ return stat;+ });+ t.after(() => {+ if (inspectionDirectory) fs.rmSync(inspectionDirectory, { recursive: true, force: true });+ });++ const result = await runVisualCheck({+ artifactPath: input,+ chromePath: '/fake/chrome',+ browserFactory: async () => {+ browserStarted = true;+ return fakeBrowser();+ },+ });++ assert.equal(result.exitCode, 1);+ assert.equal(browserStarted, false);+ assert.equal(result.receipt.diagnostics[0]?.code, 'viewer/artifact-snapshot');+ assert.ok(result.receipt.diagnostics.at(-1)?.evidence?.errors.some(+ (entry) => entry.file === inspectionDirectory && entry.recoveryDirectory === inspectionDirectory,+ ));+ assert.deepEqual(fs.readdirSync(inspectionDirectory), []);+});++for (const claimantFile of [false, true]) {+ test(`visual-check preserves a replacement local snapshot directory${claimantFile ? ' containing a file' : ' that is empty'} and reports its location`, async (t) => {+ const input = artifact(`local-inspection-directory-claimant-${claimantFile}.html`);+ const sentinel = 'external local snapshot directory claimant\n';+ let inspectionDirectory;+ let detached;+ let claimantPath;+ t.after(() => {+ if (inspectionDirectory) fs.rmSync(inspectionDirectory, { recursive: true, force: true });+ if (detached) fs.rmSync(detached, { recursive: true, force: true });+ });+ const result = await runVisualCheck({+ artifactPath: input,+ chromePath: '/fake/chrome',+ browserFactory: async () => ({+ async inspect({ artifactPath }) {+ inspectionDirectory = path.dirname(artifactPath);+ detached = `${inspectionDirectory}-detached`;+ fs.renameSync(inspectionDirectory, detached);+ fs.mkdirSync(inspectionDirectory);+ claimantPath = path.join(inspectionDirectory, 'artifact-snapshot.html');+ if (claimantFile) fs.writeFileSync(claimantPath, sentinel, { flag: 'wx' });+ throw new Error('synthetic browser failure after directory replacement');+ },+ async close() {},+ }),+ });++ assert.equal(result.exitCode, 1);+ assert.equal(fs.realpathSync(path.dirname(inspectionDirectory)), fs.realpathSync(os.tmpdir()));+ if (claimantFile) assert.equal(fs.readFileSync(claimantPath, 'utf8'), sentinel);+ else assert.deepEqual(fs.readdirSync(inspectionDirectory), []);+ const errors = result.receipt.diagnostics.at(-1)?.evidence?.errors;+ assert.ok(errors.some((entry) => entry.file === inspectionDirectory+ && entry.recoveryDirectory === inspectionDirectory+ && /identity changed; it was preserved/.test(entry.reason)));+ assert.equal(fs.existsSync(path.join(detached, 'artifact-snapshot.html')), true);+ });+}+for (const scenario of [{ name: 'a regular screenshot claimant swapped before registration', replace: true },{ name: 'screenshot bytes changed after capture without an identity change', replace: false },@@ -412,6 +562,7 @@ test('visual-check cleanup preserves a successor swapped at its final removal bo});t.after(() => {fs.rmSync(detached, { force: true });+ if (stagedPath) fs.rmSync(path.dirname(stagedPath), { recursive: true, force: true });for (const directory of stagingDirectories(path.dirname(outputs.receipt))) {fs.rmSync(path.join(path.dirname(outputs.receipt), directory), { recursive: true, force: true });}@@ -2699,3 +2850,59 @@ test('vertical workflow overflow reports measured frames and conditional reflowassert.equal(horizontalOverflow.evidence.workflowLanes, undefined);assert.equal(horizontalOverflow.supportedFixes.length, 1);});++test('visual-check reports local inspection cleanup failure alongside an evidence target conflict', async (t) => {+ const input = artifact('inspection-cleanup-target-conflict.html');+ const outDir = fs.mkdtempSync(path.join(tmp, 'inspection-cleanup-target-conflict-'));+ const outputs = sidecarPaths(input, { outDir });+ const sentinel = 'external receipt claimant\n';+ const browser = fakeBrowser();+ const inspect = browser.inspect.bind(browser);+ const rmdirSync = fs.rmdirSync.bind(fs);+ let inspectionDirectory;+ let claimed = false;+ let cleanupAttempts = 0;+ browser.inspect = async (args) => {+ inspectionDirectory = path.dirname(args.artifactPath);+ if (!claimed) {+ fs.writeFileSync(outputs.receipt, sentinel, { flag: 'wx' });+ claimed = true;+ }+ return inspect(args);+ };+ t.mock.method(fs, 'rmdirSync', (directory, ...args) => {+ if (String(directory) === inspectionDirectory) {+ cleanupAttempts += 1;+ throw Object.assign(new Error('synthetic inspection cleanup denied during target conflict'), {+ code: 'EACCES',+ });+ }+ return rmdirSync(directory, ...args);+ });+ t.after(() => {+ t.mock.restoreAll();+ if (inspectionDirectory) fs.rmSync(inspectionDirectory, { recursive: true, force: true });+ fs.rmSync(outDir, { recursive: true, force: true });+ });++ const result = await runVisualCheck({+ artifactPath: input,+ outDir,+ chromePath: '/fake/chrome',+ browserFactory: async () => browser,+ });++ assert.equal(claimed, true);+ assert.ok(cleanupAttempts > 0, 'the fixture must exercise local inspection cleanup failure');+ assert.equal(result.exitCode, 1);+ assert.equal(fs.readFileSync(outputs.receipt, 'utf8'), sentinel);+ assert.deepEqual(fs.readdirSync(inspectionDirectory), []);+ assert.deepEqual(stagingDirectories(outDir), []);+ const conflict = result.receipt.diagnostics.at(-1);+ assert.equal(conflict?.code, 'viewer/evidence-path-conflict');+ assert.ok(conflict.evidence.rollbackErrors?.some((entry) => (+ entry.file === inspectionDirectory+ && entry.recoveryDirectory === inspectionDirectory+ && /synthetic inspection cleanup denied/.test(entry.reason)+ )), 'the conflict must report the retained local inspection directory');+});