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: bind temporary cleanup to owned directories and await Chrome exit
tt-a1i2d2f550fbf05
diff --git a/archify/bin/archify.mjs b/archify/bin/archify.mjsindex 4af05f44..15b83c2d 100755--- a/archify/bin/archify.mjs+++ b/archify/bin/archify.mjs@@ -6802,9 +6802,12 @@ async function commandValidate(args) {return;}- const tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'archify-validate-'));+ const { createOwnedTempDirectory } = await import('../renderers/shared/owned-temp-directory.mjs');+ const temporary = createOwnedTempDirectory('archify-validate-');+ const tmp = temporary.path;const out = path.join(tmp, `${type}.html`);let exitCode = 0;+ let report = () => {};try {const snapshot = path.join(tmp, 'specification.snapshot.json');@@ -6815,7 +6818,7 @@ async function commandValidate(args) {});if (render.status !== 0) {const failure = rendererFailure(render);- reportValidateFailure({+ report = () => reportValidateFailure({json,stage: failure.diagnostics.some((entry) => entry.code.startsWith('input/')) ? 'input' : 'render',type,@@ -6836,7 +6839,7 @@ async function commandValidate(args) {} catch {checker = { ok: false, diagnostic: 'Artifact checker failed without a parseable receipt.' };}- reportValidateFailure({+ report = () => reportValidateFailure({json,stage: 'check',type,@@ -6857,7 +6860,7 @@ async function commandValidate(args) {};const resolvedQuality = quality || result.composition.profile || 'standard';const localeWarnings = await specificationLocaleDiagnostics(type, specification);- console.log(JSON.stringify({+ const receipt = {schemaVersion: 1,ok: true,command: 'validate',@@ -6883,19 +6886,41 @@ async function commandValidate(args) {composition: result.composition,...(engineeringProfile ? { engineeringProfile } : {}),...(localeWarnings.length ? { diagnostics: localeWarnings } : {}),- }, null, 2));+ };+ report = () => console.log(JSON.stringify(receipt, null, 2));} else {const engineering = engineeringProfile? `; engineering ${engineeringProfile}: pass`: '';- console.log(`ok ${type} ${path.resolve(input)} (${result.checks.length} artifact checks; composition ${result.composition.profile}: ${result.composition.summary.errors} errors, ${result.composition.summary.warnings} warnings${engineering})`);+ report = () => console.log(`ok ${type} ${path.resolve(input)} (${result.checks.length} artifact checks; composition ${result.composition.profile}: ${result.composition.summary.errors} errors, ${result.composition.summary.warnings} warnings${engineering})`);}}}} finally {- fs.rmSync(tmp, { recursive: true, force: true });+ try {+ await temporary.cleanup();+ } catch (error) {+ exitCode = 1;+ report = () => reportValidateFailure({+ json,+ stage: 'cleanup',+ type,+ input: path.resolve(input),+ error: error.message,+ diagnostics: [{+ code: 'validate/temp-cleanup-incomplete',+ severity: 'error',+ message: error.message,+ subject: { directory: tmp },+ evidence: { reason: error.cause?.code || error.code },+ supportedFixes: ['resolve the reported filesystem error and inspect the retained temporary directory before retrying'],+ }],+ status: 1,+ });+ }}+ report();if (exitCode !== 0) process.exitCode = exitCode;}diff --git a/archify/bin/visual-check.mjs b/archify/bin/visual-check.mjsindex 277505a0..05ec34ad 100644--- a/archify/bin/visual-check.mjs+++ b/archify/bin/visual-check.mjs@@ -1,4 +1,5 @@import { spawn } from 'node:child_process';+import { createOwnedTempDirectory } from '../renderers/shared/owned-temp-directory.mjs';import { createHash } from 'node:crypto';import fs from 'node:fs';import os from 'node:os';@@ -1522,13 +1523,17 @@ async function evaluate(cdp, sessionId, expression, awaitPromise = false) {}export class ChromeVisualBrowser {+ #profile;constructor(chromePath, {env = process.env,getuid = typeof process.getuid === 'function' ? () => process.getuid() : null,spawnImpl = spawn,startupTimeoutMs = CHROME_STARTUP_TIMEOUT_MS,+ shutdownTimeoutMs = 1500,} = {}) {- this.profileRoot = fs.mkdtempSync(path.join(os.tmpdir(), 'archify-visual-check-profile-'));+ this.#profile = createOwnedTempDirectory('archify-visual-check-profile-');+ this.profileRoot = this.#profile.path;+ this.shutdownTimeoutMs = shutdownTimeoutMs;this.stderr = '';const args = chromeVisualBrowserArgs(this.profileRoot, { env, getuid });this.child = spawnImpl(chromePath, args, { stdio: ['ignore', 'ignore', 'pipe', 'pipe', 'pipe'] });@@ -1819,24 +1824,33 @@ export class ChromeVisualBrowser {this.cdp.failAll(new Error('visual-check finished'));try {if (this.child.exitCode === null && this.child.signalCode === null) {- await new Promise((resolve) => {- let timer = null;- let settled = false;+ const exited = () => this.child.exitCode !== null || this.child.signalCode !== null;+ const signalAndWait = (signal) => new Promise((resolve, reject) => {+ let timer;const finish = () => {- if (settled) return;- settled = true;- if (timer) clearTimeout(timer);+ clearTimeout(timer);this.child.removeListener('exit', finish);- resolve();+ resolve(true);};this.child.once('exit', finish);- this.child.kill('SIGTERM');- if (settled) return;timer = setTimeout(() => {- if (this.child.exitCode === null && this.child.signalCode === null) this.child.kill('SIGKILL');- finish();- }, 1500);+ this.child.removeListener('exit', finish);+ resolve(exited());+ }, this.shutdownTimeoutMs);+ try {+ this.child.kill(signal);+ } catch (error) {+ clearTimeout(timer);+ this.child.removeListener('exit', finish);+ reject(error);+ }});+ if (!await signalAndWait('SIGTERM') && !await signalAndWait('SIGKILL')) {+ const error = new Error(`Chrome did not exit; retained temporary profile "${this.#profile.path}".`);+ error.code = 'ARCHIFY_TEMP_CLEANUP';+ error.directory = this.#profile.path;+ throw error;+ }}} finally {// `exit` only reports that Chrome's main process is gone. A helper may@@ -1846,11 +1860,7 @@ export class ChromeVisualBrowser {if (stream && !stream.destroyed) stream.destroy();}}- try {- fs.rmSync(this.profileRoot, { recursive: true, force: true });- } catch {- // Chrome may briefly retain profile files on Windows; evidence is done.- }+ await this.#profile.cleanup();}}@@ -2490,53 +2500,58 @@ async function runBrowserEvidence({{ ...entry, stagedPath: ownership.stagedOutputs.screenshots[index].path },]));- for (const viewport of VISUAL_CHECK_VIEWPORTS) {- const key = screenshotKey(viewport.width, viewport.height, 'light');- const screenshot = screenshotsByKey.get(key);- const metrics = await browser.inspect({- artifactPath: inspectionArtifact,- ...viewport,- theme: 'light',- ...(screenshot ? {- screenshotPath: screenshot.stagedPath,- writeScreenshot: (bytes) => writeStagedEvidence(ownership, screenshot.path, bytes),- } : {}),- });- verifyInspectionArtifact();- if (screenshot) {+ try {+ for (const viewport of VISUAL_CHECK_VIEWPORTS) {+ const key = screenshotKey(viewport.width, viewport.height, 'light');+ const screenshot = screenshotsByKey.get(key);+ const metrics = await browser.inspect({+ artifactPath: inspectionArtifact,+ ...viewport,+ theme: 'light',+ ...(screenshot ? {+ screenshotPath: screenshot.stagedPath,+ writeScreenshot: (bytes) => writeStagedEvidence(ownership, screenshot.path, bytes),+ } : {}),+ });+ verifyInspectionArtifact();+ if (screenshot) {+ if (screenshot && !ownership.stagedEntries.has(screenshot.path)) {+ registerStagedEvidence(ownership, screenshot.path);+ } else {+ const staged = ownership.stagedEntries.get(screenshot.path);+ if (!currentEvidenceMatches(staged.path, staged.identity, staged.evidence)) {+ throw new Error('The staged visual-check screenshot changed after capture.');+ }+ }+ }+ observations.set(key, observation({ ...viewport, theme: 'light', metrics }));+ }+ for (const viewport of CAPTURE_VIEWPORTS) {+ const key = screenshotKey(viewport.width, viewport.height, 'dark');+ const screenshot = screenshotsByKey.get(key);+ const metrics = await browser.inspect({+ artifactPath: inspectionArtifact,+ ...viewport,+ theme: 'dark',+ ...(screenshot ? {+ screenshotPath: screenshot.stagedPath,+ writeScreenshot: (bytes) => writeStagedEvidence(ownership, screenshot.path, bytes),+ } : {}),+ });+ verifyInspectionArtifact();if (screenshot && !ownership.stagedEntries.has(screenshot.path)) {registerStagedEvidence(ownership, screenshot.path);- } else {+ } else if (screenshot) {const staged = ownership.stagedEntries.get(screenshot.path);if (!currentEvidenceMatches(staged.path, staged.identity, staged.evidence)) {throw new Error('The staged visual-check screenshot changed after capture.');}}+ observations.set(key, observation({ ...viewport, theme: 'dark', metrics }));}- observations.set(key, observation({ ...viewport, theme: 'light', metrics }));- }- for (const viewport of CAPTURE_VIEWPORTS) {- const key = screenshotKey(viewport.width, viewport.height, 'dark');- const screenshot = screenshotsByKey.get(key);- const metrics = await browser.inspect({- artifactPath: inspectionArtifact,- ...viewport,- theme: 'dark',- ...(screenshot ? {- screenshotPath: screenshot.stagedPath,- writeScreenshot: (bytes) => writeStagedEvidence(ownership, screenshot.path, bytes),- } : {}),- });- verifyInspectionArtifact();- if (screenshot && !ownership.stagedEntries.has(screenshot.path)) {- registerStagedEvidence(ownership, screenshot.path);- } else if (screenshot) {- const staged = ownership.stagedEntries.get(screenshot.path);- if (!currentEvidenceMatches(staged.path, staged.identity, staged.evidence)) {- throw new Error('The staged visual-check screenshot changed after capture.');- }- }- observations.set(key, observation({ ...viewport, theme: 'dark', metrics }));++ } finally {+ if (browser?.close) await browser.close();}let artifactVerification = verifyRegularFileBinding(capturedArtifact.binding);@@ -2624,13 +2639,18 @@ async function runBrowserEvidence({receipt.captures.contactSheet = null;if (error.deliveryProvenance) receipt.provenance = error.deliveryProvenance.status;receipt.diagnostics = error.archifyDiagnostics || [failureDiagnostic({- code: startupTimeout ? 'viewer/chrome-startup-timeout' : `viewer/${command}-runtime`,- message: startupTimeout+ code: error.code === 'ARCHIFY_TEMP_CLEANUP' ? 'viewer/temp-cleanup-incomplete'+ : startupTimeout ? 'viewer/chrome-startup-timeout' : `viewer/${command}-runtime`,+ message: error.code === 'ARCHIFY_TEMP_CLEANUP'+ ? 'Browser cleanup could not safely finish; inspect the reported retained path.'+ : startupTimeout? 'Chrome did not finish its initial DevTools handshake within the startup window.': `${command} could not complete its Chrome inspection.`,subject: { artifact },- evidence: { reason: error.message },- supportedFixes: startupTimeout+ evidence: { reason: error.message, ...(error.directory ? { retainedDirectory: error.directory } : {}) },+ supportedFixes: error.code === 'ARCHIFY_TEMP_CLEANUP'+ ? ['resolve the reported process or filesystem failure; verify directory ownership before manual cleanup']+ : startupTimeout? ['do not edit or simplify the artifact because this is a browser-startup failure',`retry ${command} once after host load subsides; if it repeats, stop and report the environment failure`,@@ -2645,8 +2665,6 @@ async function runBrowserEvidence({ownership, command, capture,}),};- } finally {- if (browser?.close) await browser.close();}} finally {releaseRegularFileBinding(capturedArtifact.binding);diff --git a/archify/renderers/shared/owned-temp-directory.mjs b/archify/renderers/shared/owned-temp-directory.mjsnew file mode 100644index 00000000..7d4e2f5c--- /dev/null+++ b/archify/renderers/shared/owned-temp-directory.mjs@@ -0,0 +1,77 @@+import fs from 'node:fs';+import os from 'node:os';+import path from 'node:path';+import { setTimeout as delay } from 'node:timers/promises';++const retryable = new Set(['EBUSY', 'EPERM', 'EACCES', 'ENOTEMPTY']);++function directoryIdentity(directory) {+ const stat = fs.lstatSync(directory, { bigint: true });+ if (!stat.isDirectory() || stat.isSymbolicLink() || stat.ino === 0n) {+ throw new Error(`Temporary directory identity is unavailable or changed: ${directory}`);+ }+ return { directory, dev: stat.dev, ino: stat.ino, birthtimeNs: stat.birthtimeNs };+}++function verifyIdentity(expected) {+ const current = directoryIdentity(expected.directory);+ if (current.dev !== expected.dev || current.ino !== expected.ino+ || current.birthtimeNs !== expected.birthtimeNs) {+ throw new Error(`Temporary directory identity changed: ${expected.directory}`);+ }+}++// Bind cleanup to this creation, never to a caller-supplied deletion path.+// This detects substitution between creation and cleanup (including junctions)+// and between retries. Path-based Node APIs cannot eliminate a hostile mutation+// racing the final check and rm; this is not a filesystem sandbox.+export function createOwnedTempDirectory(prefix, { parent = os.tmpdir() } = {}) {+ if (!/^[a-zA-Z0-9-]+-$/.test(prefix)) throw new Error('Invalid temporary directory prefix');+ const canonicalParent = fs.realpathSync.native(path.resolve(parent));+ const ancestors = [];+ for (let current = canonicalParent; ; current = path.dirname(current)) {+ ancestors.push(directoryIdentity(current));+ if (path.dirname(current) === current) break;+ }+ const verifyAncestors = () => {+ // Check from the filesystem root down, before traversing a replaced parent.+ for (const ancestor of [...ancestors].reverse()) verifyIdentity(ancestor);+ };+ verifyAncestors();+ const directory = fs.mkdtempSync(path.join(canonicalParent, prefix));+ verifyAncestors();+ const identity = directoryIdentity(directory);++ function remove() {+ verifyAncestors();+ try {+ verifyIdentity(identity);+ } catch (error) {+ if (error.code === 'ENOENT') return;+ throw error;+ }+ // No internal retry: each new attempt must revalidate the entire binding.+ fs.rmSync(directory, { recursive: true, force: false, maxRetries: 0 });+ }++ return Object.freeze({+ path: directory,+ async cleanup() {+ for (let attempt = 0; ; attempt++) {+ try {+ remove();+ return;+ } catch (cause) {+ if (retryable.has(cause.code) && attempt < 3) {+ await delay(100 * (attempt + 1));+ continue;+ }+ const error = new Error(`Temporary directory cleanup failed; retained path "${directory}": ${cause.message}`, { cause });+ error.code = 'ARCHIFY_TEMP_CLEANUP';+ error.directory = directory;+ throw error;+ }+ }+ },+ });+}diff --git a/scripts/run-windows-path-tests.mjs b/scripts/run-windows-path-tests.mjsindex 4ece60d3..b6cfa27b 100644--- a/scripts/run-windows-path-tests.mjs+++ b/scripts/run-windows-path-tests.mjs@@ -558,6 +558,7 @@ const portabilitySuites = ['test/cli.test.mjs','test/preview.test.mjs','test/visual-check.test.mjs',+ 'test/temp-cleanup.test.mjs','test/update-notifier.test.mjs',];diff --git a/test/temp-cleanup.test.mjs b/test/temp-cleanup.test.mjsnew file mode 100644index 00000000..a61a3b7e--- /dev/null+++ b/test/temp-cleanup.test.mjs@@ -0,0 +1,260 @@+import { test } from 'node:test';+import os from 'node:os';+import { spawn, spawnSync } from 'node:child_process';+import { fileURLToPath, pathToFileURL } from 'node:url';+import { setTimeout as delay } from 'node:timers/promises';+import { createOwnedTempDirectory } from '../archify/renderers/shared/owned-temp-directory.mjs';+import assert from 'node:assert/strict';+import fs from 'node:fs';+import path from 'node:path';+import { EventEmitter } from 'node:events';+import { PassThrough } from 'node:stream';+import { ChromeVisualBrowser } from '../archify/bin/visual-check.mjs';++function browserWithChild(kill) {+ const child = new EventEmitter();+ child.exitCode = null;+ child.signalCode = null;+ child.stderr = new PassThrough();+ child.stdio = [null, null, child.stderr, new PassThrough(), new PassThrough()];+ child.kill = signal => kill(child, signal);+ const browser = new ChromeVisualBrowser('/fake/chrome', {+ spawnImpl: () => child,+ shutdownTimeoutMs: 20,+ });+ browser.sessionPromise.catch(() => {});+ return browser;+}++test('Chrome close refuses a directory substituted for its temporary profile', async () => {+ const browser = browserWithChild((child, signal) => {+ child.signalCode = signal;+ child.emit('exit', null, signal);+ });+ const original = browser.profileRoot;+ const moved = `${original}-moved`;+ fs.renameSync(original, moved);+ fs.mkdirSync(original);+ const sentinel = path.join(original, 'not-our-profile');+ fs.writeFileSync(sentinel, 'preserve');+ try {+ await assert.rejects(browser.close(), /identity|changed/i);+ assert.equal(fs.readFileSync(sentinel, 'utf8'), 'preserve');+ } finally {+ fs.rmSync(original, { recursive: true, force: true });+ fs.rmSync(moved, { recursive: true, force: true });+ }+});++test('Chrome close waits for exit after SIGKILL before removing its profile', async () => {+ let exited = false;+ let existedAtExit = false;+ const browser = browserWithChild((child, signal) => {+ if (signal === 'SIGTERM') return true;+ setTimeout(() => {+ existedAtExit = fs.existsSync(browser.profileRoot);+ exited = true;+ child.signalCode = signal;+ child.emit('exit', null, signal);+ }, 10);+ return true;+ });+ await browser.close();+ assert.equal(exited, true, 'close must await the exit event, not just kill()');+ assert.equal(existedAtExit, true, 'profile must survive until process exit');+ assert.equal(fs.existsSync(browser.profileRoot), false);+});++function fixture(t) {+ const parent = fs.mkdtempSync(path.join(os.tmpdir(), 'archify-owned-test-'));+ t.after(() => fs.rmSync(parent, { recursive: true, force: true }));+ return parent;+}++for (const replacement of ['directory', 'link']) {+ test(`cleanup refuses an ancestor replaced with a ${replacement}`, async t => {+ const base = fixture(t);+ const parent = path.join(base, 'parent');+ fs.mkdirSync(parent);+ const owned = createOwnedTempDirectory('test-', { parent });+ const moved = path.join(base, 'moved');+ fs.renameSync(parent, moved);+ if (replacement === 'link') fs.symlinkSync(moved, parent, process.platform === 'win32' ? 'junction' : 'dir');+ else fs.mkdirSync(parent);+ await assert.rejects(owned.cleanup(), /identity|changed/i);+ assert.ok(fs.existsSync(path.join(moved, path.basename(owned.path))));+ });+}++test('cleanup refuses a root symlink/junction and preserves the target', async t => {+ const parent = fixture(t);+ const owned = createOwnedTempDirectory('test-', { parent });+ const moved = path.join(parent, 'moved');+ fs.renameSync(owned.path, moved);+ fs.writeFileSync(path.join(moved, 'keep'), 'keep');+ fs.symlinkSync(moved, owned.path, process.platform === 'win32' ? 'junction' : 'dir');+ await assert.rejects(owned.cleanup(), /identity|changed/i);+ assert.equal(fs.readFileSync(path.join(moved, 'keep'), 'utf8'), 'keep');+});++test('relative temp parent stays bound across a cwd change', t => {+ const base = fixture(t);+ fs.mkdirSync(path.join(base, 'temp'));+ fs.mkdirSync(path.join(base, 'other'));+ const moduleUrl = new URL('../archify/renderers/shared/owned-temp-directory.mjs', import.meta.url).href;+ const result = spawnSync(process.execPath, ['--input-type=module', '-e', `+ import { createOwnedTempDirectory } from ${JSON.stringify(moduleUrl)};+ import fs from 'node:fs';+ const owned = createOwnedTempDirectory('test-', { parent: './temp' });+ process.chdir('other');+ await owned.cleanup();+ if (fs.existsSync(owned.path)) process.exitCode = 1;+ `], { cwd: base, encoding: 'utf8' });+ assert.equal(result.status, 0, result.stderr);+ assert.deepEqual(fs.readdirSync(path.join(base, 'temp')), []);+});++test('cleanup retries transient locks, then succeeds and is idempotent', async t => {+ const owned = createOwnedTempDirectory('test-', { parent: fixture(t) });+ const realRemove = fs.rmSync;+ let attempts = 0;+ const mock = t.mock.method(fs, 'rmSync', (target, options) => {+ if (target === owned.path && ++attempts < 3) throw Object.assign(new Error('locked'), { code: 'EPERM' });+ return realRemove(target, options);+ });+ await owned.cleanup();+ await owned.cleanup();+ mock.mock.restore();+ assert.equal(attempts, 3);+ assert.equal(fs.existsSync(owned.path), false);+});++test('permanent cleanup failure reports the retained path after bounded attempts', async t => {+ const owned = createOwnedTempDirectory('test-', { parent: fixture(t) });+ const realRemove = fs.rmSync;+ let attempts = 0;+ const mock = t.mock.method(fs, 'rmSync', (target, options) => {+ if (target === owned.path) {+ attempts++;+ throw Object.assign(new Error('locked'), { code: 'EBUSY' });+ }+ return realRemove(target, options);+ });+ await assert.rejects(owned.cleanup(), error => error.code === 'ARCHIFY_TEMP_CLEANUP'+ && error.directory === owned.path && error.cause.code === 'EBUSY');+ mock.mock.restore();+ assert.equal(attempts, 4);+ assert.ok(fs.existsSync(owned.path));+});++test('cleanup rechecks identity between retries', async t => {+ const parent = fixture(t);+ const owned = createOwnedTempDirectory('test-', { parent });+ const realRemove = fs.rmSync;+ let attempts = 0;+ const mock = t.mock.method(fs, 'rmSync', (target, options) => {+ if (target === owned.path) {+ attempts++;+ fs.renameSync(target, path.join(parent, 'moved'));+ fs.mkdirSync(target);+ fs.writeFileSync(path.join(target, 'keep'), 'keep');+ throw Object.assign(new Error('locked'), { code: 'EPERM' });+ }+ return realRemove(target, options);+ });+ await assert.rejects(owned.cleanup(), /identity changed/);+ mock.mock.restore();+ assert.equal(attempts, 1);+ assert.equal(fs.readFileSync(path.join(owned.path, 'keep'), 'utf8'), 'keep');+});++test('Chrome close retains its profile when termination never completes', async () => {+ const browser = browserWithChild(() => true);+ try {+ await assert.rejects(browser.close(), /Chrome did not exit/);+ assert.ok(fs.existsSync(browser.profileRoot));+ } finally {+ fs.rmSync(browser.profileRoot, { recursive: true, force: true });+ }+});++test('validate emits one failed JSON receipt when temporary cleanup is blocked', t => {+ const parent = fixture(t);+ const preload = path.join(parent, 'block-cleanup.mjs');+ fs.writeFileSync(preload, `+ import fs from 'node:fs';+ import path from 'node:path';+ const remove = fs.rmSync;+ fs.rmSync = (target, options) => {+ if (path.basename(String(target)).startsWith('archify-validate-')) {+ throw Object.assign(new Error('injected temporary lock'), { code: 'EPERM' });+ }+ return remove(target, options);+ };+ `);+ const cli = new URL('../archify/bin/archify.mjs', import.meta.url);+ const input = new URL('../archify/examples/agent-tool-call.workflow.json', import.meta.url);+ const result = spawnSync(process.execPath, ['--import', pathToFileURL(preload).href,+ fileURLToPath(cli), 'validate', 'workflow', fileURLToPath(input), '--json'], {+ encoding: 'utf8',+ env: { ...process.env, TMPDIR: parent, TEMP: parent, TMP: parent },+ });+ assert.equal(result.status, 1, result.stderr);+ const receipt = JSON.parse(result.stdout);+ assert.equal(receipt.ok, false);+ assert.equal(receipt.stage, 'cleanup');+ assert.equal(receipt.diagnostics[0].code, 'validate/temp-cleanup-incomplete');+ assert.ok(fs.existsSync(receipt.diagnostics[0].subject.directory));+});++test('Windows file share lock is reported, then cleanup succeeds after release', {+ skip: process.platform !== 'win32' ? 'requires actual Windows file sharing semantics' : false,+}, async t => {+ const parent = fixture(t);+ const owned = createOwnedTempDirectory('test-', { parent });+ const lockedFile = path.join(owned.path, 'locked');+ const ready = path.join(parent, 'ready');+ fs.writeFileSync(lockedFile, 'keep');+ const child = spawn('powershell.exe', ['-NoProfile', '-NonInteractive', '-Command', `+ $ErrorActionPreference = 'Stop'+ $stream = [System.IO.File]::Open($env:ARCHIFY_TEST_LOCK, 'Open', 'Read', 'None')+ try {+ [System.IO.File]::WriteAllText($env:ARCHIFY_TEST_READY, 'ready')+ $null = [Console]::ReadLine()+ } finally { $stream.Dispose() }+ `], { env: { ...process.env, ARCHIFY_TEST_LOCK: lockedFile, ARCHIFY_TEST_READY: ready }, stdio: ['pipe', 'pipe', 'pipe'] });+ child.stdin.on('error', () => {});+ let stderr = '';+ child.stderr.on('data', chunk => { stderr += chunk; });+ const exited = new Promise((resolve, reject) => {+ child.once('error', reject);+ child.once('exit', resolve);+ });+ try {+ for (let attempt = 0; attempt < 250 && !fs.existsSync(ready) && child.exitCode === null; attempt++) {+ await delay(20);+ }+ assert.ok(fs.existsSync(ready), `lock process did not become ready: ${stderr}`);+ await assert.rejects(owned.cleanup(), { code: 'ARCHIFY_TEMP_CLEANUP' });+ assert.ok(fs.existsSync(lockedFile));+ } finally {+ child.stdin.end('\n');+ await exited;+ }+ await owned.cleanup();+ assert.equal(fs.existsSync(owned.path), false);+});++test('changing the public profile path cannot redirect Chrome cleanup', async t => {+ const other = fixture(t);+ fs.writeFileSync(path.join(other, 'keep'), 'keep');+ const browser = browserWithChild((child, signal) => {+ child.signalCode = signal;+ child.emit('exit', null, signal);+ });+ const original = browser.profileRoot;+ browser.profileRoot = other;+ await browser.close();+ assert.equal(fs.existsSync(original), false);+ assert.equal(fs.readFileSync(path.join(other, 'keep'), 'utf8'), 'keep');+});diff --git a/test/visual-check.test.mjs b/test/visual-check.test.mjsindex 6c16cf70..b4493be9 100644--- a/test/visual-check.test.mjs+++ b/test/visual-check.test.mjs@@ -3191,3 +3191,27 @@ test('authored Architecture scroll requires readable unclipped document flow andassert.equal(viewport.readerLayout, null, 'the fixed canvas does not acquire adaptive scaling');}});+++test('browser cleanup failure publishes a failed receipt instead of successful evidence', async () => {+ const input = artifact('chrome-cleanup-failure.html');+ const browser = fakeBrowser();+ browser.close = async () => {+ const error = new Error('Temporary directory cleanup failed: locked');+ error.code = 'ARCHIFY_TEMP_CLEANUP';+ error.directory = '/retained/profile';+ throw error;+ };+ const result = await runVisualCheck({+ artifactPath: input,+ chromePath: '/fake/chrome',+ browserFactory: () => browser,+ });+ assert.equal(result.exitCode, 1);+ assert.equal(result.receipt.ok, false);+ assert.equal(result.receipt.diagnostics[0].code, 'viewer/temp-cleanup-incomplete');+ assert.equal(result.receipt.diagnostics[0].evidence.retainedDirectory, '/retained/profile');+ const saved = JSON.parse(fs.readFileSync(sidecarPaths(input).receipt, 'utf8'));+ assert.equal(saved.ok, false);+ assert.deepEqual(saved.captures.screenshots, []);+});