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: reconcile filesystem lifetimes across Windows and Linux
sunsunsun918eeb6eac7a
diff --git a/archify.zip b/archify.zipindex 1a4a8c81..6b8c7ffa 100644Binary files a/archify.zip and b/archify.zip differdiff --git a/archify/bin/visual-check.mjs b/archify/bin/visual-check.mjsindex d6dfe4b5..58089ccd 100644--- a/archify/bin/visual-check.mjs+++ b/archify/bin/visual-check.mjs@@ -541,7 +541,7 @@ function publishedRemovalError(file, result) {function cleanupStagedEvidence(ownership, { removeDirectory = false } = {}) {const errors = [];for (const [finalPath, entry] of [...ownership.stagedEntries]) {- const result = unlinkOwnedEntry(entry.path, entry.identity);+ const result = unlinkOwnedEntry(entry.path, entry.identity, { evidence: entry.evidence });if (result.status === 'removed' || result.status === 'absent') {ownership.stagedEntries.delete(finalPath);} else {diff --git a/archify/renderers/shared/atomic-output.mjs b/archify/renderers/shared/atomic-output.mjsindex af283d70..4f332320 100644--- a/archify/renderers/shared/atomic-output.mjs+++ b/archify/renderers/shared/atomic-output.mjs@@ -91,6 +91,7 @@ function captureRegularFileHandle(filePath, initial, subject) {}const regularFileBindings = new WeakMap();+const regularFileBindingGroups = new Map();const digestChunkBytes = 64 * 1024;const removalCleanupSignal = new Int32Array(new SharedArrayBuffer(4));const removalCleanupAttempts = 10;@@ -384,13 +385,20 @@ export function captureRegularFileBinding(filePath, {});}+ const identityKey = `${identity.device}:${identity.inode}`;+ let cleanupGroup = regularFileBindingGroups.get(identityKey);+ if (!cleanupGroup) {+ cleanupGroup = { identityKey, bindings: 0, deferredCleanupDirectories: new Set() };+ regularFileBindingGroups.set(identityKey, cleanupGroup);+ }+ cleanupGroup.bindings += 1;const binding = Object.freeze({});regularFileBindings.set(binding, {descriptor,filePath: resolvedPath,subject,expectedLinks,- deferredCleanupDirectories: new Set(),+ cleanupGroup,identity,mode,sha256: inspected.content.sha256,@@ -461,11 +469,20 @@ export function releaseRegularFileBinding(binding) {captured.subject,captured.filePath,);- if (failure) return failure;- for (const directory of captured.deferredCleanupDirectories) {- const cleanup = removeEmptyQuarantine(directory, { retry: true });- if (cleanup) return cleanup;+ const { cleanupGroup } = captured;+ cleanupGroup.bindings -= 1;+ let cleanupFailure;+ if (cleanupGroup.bindings === 0) {+ regularFileBindingGroups.delete(cleanupGroup.identityKey);+ // A staging registry and its publication transaction can bind the same+ // inode independently. SMB may keep a retired name visible until every+ // descriptor closes, so cleanup belongs to the inode's last binding.+ for (const directory of cleanupGroup.deferredCleanupDirectories) {+ const cleanup = removeEmptyQuarantine(directory, { retry: true });+ cleanupFailure ||= cleanup;+ }}+ if (failure || cleanupFailure) return failure || cleanupFailure;return relation('released', `${captured.subject}-binding-released`, {filePath: captured.filePath,});@@ -509,7 +526,7 @@ function deferEmptyQuarantineCleanup(binding, cleanup) {|| cleanup.reason.systemCode !== 'ENOTEMPTY') return false;const captured = regularFileBindings.get(binding);if (!captured) return false;- captured.deferredCleanupDirectories.add(cleanup.reason.recoveryDirectory);+ captured.cleanupGroup.deferredCleanupDirectories.add(cleanup.reason.recoveryDirectory);return true;}@@ -544,6 +561,12 @@ export function quarantineRemoveRegularFileBinding(binding, filePath, {return relation('unknown', 'invalid-regular-file-binding-expectation');}const resolvedPath = path.resolve(filePath);+ const beforeMove = verifyRegularFileBinding(binding, {+ filePath: resolvedPath,+ expectedLinks,+ });+ if (beforeMove.status !== 'match') return beforeMove;+const quarantine = createRemovalQuarantine(path.dirname(resolvedPath));if (quarantine.status !== 'created') return quarantine;const quarantineFile = path.join(quarantine.directory, path.basename(resolvedPath));@@ -553,15 +576,6 @@ export function quarantineRemoveRegularFileBinding(binding, filePath, {return cleanup && deferEmptyQuarantineCleanup(binding, cleanup) ? null : cleanup;};- const beforeMove = verifyRegularFileBinding(binding, {- filePath: resolvedPath,- expectedLinks,- });- if (beforeMove.status !== 'match') {- const cleanup = removeEmpty();- return cleanup || beforeMove;- }-try {fs.renameSync(resolvedPath, quarantineFile);} catch (error) {@@ -1248,6 +1262,14 @@ function captureRequestedEntry(requestedPath, policy) {entryType: type,device: metadata.dev,inode: metadata.ino,+ // An unlinked symlink's inode can be reused immediately. Its target can+ // stay the same while the requested directory entry is a new object.+ // Reading the link only changes atime, so these no-follow timestamps+ // distinguish that replacement without tracking target-file writes.+ ...(type === 'symbolic-link' ? {+ changedAtNs: metadata.ctimeNs,+ createdAtNs: metadata.birthtimeNs,+ } : {}),},};}@@ -1257,7 +1279,10 @@ function requestedEntryMatches(left, right) {return left.kind === 'absent'|| (left.entryType === right.entryType&& left.device === right.device- && left.inode === right.inode);+ && left.inode === right.inode+ && (left.entryType !== 'symbolic-link'+ || (left.changedAtNs === right.changedAtNs+ && left.createdAtNs === right.createdAtNs)));}/**diff --git a/archify/renderers/shared/path-semantics.mjs b/archify/renderers/shared/path-semantics.mjsindex b88da614..59dc039c 100644--- a/archify/renderers/shared/path-semantics.mjs+++ b/archify/renderers/shared/path-semantics.mjs@@ -630,8 +630,6 @@ function probeNameAlias(directoryPath, leftName, rightName) {const lookupPath = path.join(directoryPath, lookupName);descriptor = fs.openSync(probePath, 'wx', 0o600);probeStat = fs.fstatSync(descriptor, { bigint: true });- fs.closeSync(descriptor);- descriptor = undefined;let authoredStat;let lookupStat;@@ -663,14 +661,16 @@ function probeNameAlias(directoryPath, leftName, rightName) {} catch (error) {comparison = systemFailure('future-name-probe-failed', error, { method: 'filesystem-probe' });} finally {+ // Pin the inode until cleanup finishes. Once the final handle is closed,+ // an unlinked probe's inode can be reused by a replacement at the same name.+ if (probeStat) cleanupError = removeOwnedProbe(probePath, probeStat);if (descriptor !== undefined) {try {fs.closeSync(descriptor);} catch (error) {- cleanupError = error;+ cleanupError = cleanupError ?? error;}}- if (probeStat) cleanupError = cleanupError ?? removeOwnedProbe(probePath, probeStat);}if (cleanupError) {diff --git a/archify/test/cli.test.mjs b/archify/test/cli.test.mjsindex f0625672..9aadbe3f 100644--- a/archify/test/cli.test.mjs+++ b/archify/test/cli.test.mjs@@ -2489,12 +2489,10 @@ await import(${JSON.stringify(pathToFileURL(cli).href)});test('cli: delivery staging cleanup retries transient remote ENOTEMPTY', () => {const input = path.join(skillRoot, 'examples/agent-tool-call.workflow.json');- const out = path.join(tmp, 'delivery-staging-transient-enotempty.html');- const observation = path.join(tmp, 'delivery-staging-transient-enotempty.json');- const wrapper = path.join(tmp, 'delivery-staging-transient-enotempty.mjs');- const quarantineBefore = new Set(- fs.readdirSync(path.dirname(out)).filter((entry) => entry.startsWith('.archify-staging-remove-')),- );+ const directory = fs.mkdtempSync(path.join(tmp, 'delivery-staging-transient-enotempty-'));+ const out = path.join(directory, 'diagram.html');+ const observation = path.join(directory, 'observation.json');+ const wrapper = path.join(directory, 'inject-enotempty.mjs');fs.writeFileSync(wrapper, `import fs from 'node:fs';import path from 'node:path';@@ -2523,17 +2521,17 @@ fs.writeFileSync(${JSON.stringify(observation)}, JSON.stringify({ injected }));assert.deepEqual(deliveryStagingEntries(path.dirname(out)), []);assert.deepEqual(fs.readdirSync(path.dirname(out))- .filter((entry) => entry.startsWith('.archify-staging-remove-'))- .filter((entry) => !quarantineBefore.has(entry)),+ .filter((entry) => entry.startsWith('.archify-staging-remove-')),[],);});test('cli: delivery staging cleanup retries a stale remote directory listing', () => {const input = path.join(skillRoot, 'examples/agent-tool-call.workflow.json');- const out = path.join(tmp, 'delivery-staging-stale-listing.html');- const observation = path.join(tmp, 'delivery-staging-stale-listing.json');- const wrapper = path.join(tmp, 'delivery-staging-stale-listing.mjs');+ const directory = fs.mkdtempSync(path.join(tmp, 'delivery-staging-stale-listing-'));+ const out = path.join(directory, 'diagram.html');+ const observation = path.join(directory, 'observation.json');+ const wrapper = path.join(directory, 'inject-stale-listing.mjs');fs.writeFileSync(wrapper, `import fs from 'node:fs';import path from 'node:path';@@ -2560,6 +2558,82 @@ fs.writeFileSync(${JSON.stringify(observation)}, JSON.stringify({ injected }));assert.deepEqual(deliveryStagingEntries(path.dirname(out)), []);});+test('cli: delivery closes every candidate handle before cleaning delete-pending remote entries', () => {+ const input = path.join(skillRoot, 'examples/agent-tool-call.workflow.json');+ const directory = fs.mkdtempSync(path.join(tmp, 'delivery-remote-open-handles-'));+ const out = path.join(directory, 'diagram.html');+ const observation = path.join(directory, 'observation.json');+ const wrapper = path.join(directory, 'simulate-delete-pending.mjs');+ fs.writeFileSync(wrapper, `+import fs from 'node:fs';+import path from 'node:path';+const openSync = fs.openSync.bind(fs);+const fstatSync = fs.fstatSync.bind(fs);+const closeSync = fs.closeSync.bind(fs);+const unlinkSync = fs.unlinkSync.bind(fs);+const rmdirSync = fs.rmdirSync.bind(fs);+const handles = new Map();+const pendingDirectories = new Map();+const multiplyBoundFiles = new Set();+const identity = (metadata) => String(metadata.dev) + ':' + String(metadata.ino);+let blockedRemovals = 0;+fs.openSync = (file, ...args) => {+ const descriptor = openSync(file, ...args);+ const metadata = fstatSync(descriptor, { bigint: true });+ if (metadata.isFile()) handles.set(descriptor, {+ identity: identity(metadata), file: path.basename(String(file)),+ });+ return descriptor;+};+fs.closeSync = (descriptor) => {+ const result = closeSync(descriptor);+ handles.delete(descriptor);+ return result;+};+fs.unlinkSync = (file) => {+ const parent = path.dirname(String(file));+ if (path.basename(parent).startsWith('.archify-remove-')) {+ const key = identity(fs.lstatSync(file, { bigint: true }));+ pendingDirectories.set(parent, key);+ const owners = [...handles.values()].filter((owner) => owner.identity === key);+ if (owners.length > 1) owners.forEach((owner) => multiplyBoundFiles.add(owner.file));+ }+ return unlinkSync(file);+};+fs.rmdirSync = (directory, ...args) => {+ const key = pendingDirectories.get(String(directory));+ if (key && [...handles.values()].some((owner) => owner.identity === key)) {+ blockedRemovals += 1;+ throw Object.assign(new Error('remote child deletion waits for all open handles'), { code: 'ENOTEMPTY' });+ }+ const result = rmdirSync(directory, ...args);+ pendingDirectories.delete(String(directory));+ return result;+};+process.argv = [process.execPath, ${JSON.stringify(cli)}, 'deliver', 'workflow', ${JSON.stringify(input)}, ${JSON.stringify(out)}, '--json'];+await import(${JSON.stringify(pathToFileURL(cli).href)});+fs.writeFileSync(${JSON.stringify(observation)}, JSON.stringify({+ blockedRemovals,+ multiplyBoundFiles: [...multiplyBoundFiles],+ remainingHandles: handles.size,+ pendingDirectories: [...pendingDirectories.keys()],+}));+`);++ const delivered = spawnSync(process.execPath, [wrapper], { cwd: skillRoot, encoding: 'utf8' });++ assert.equal(delivered.status, 0, delivered.stderr || delivered.stdout);+ assert.equal(JSON.parse(delivered.stdout).ok, true);+ const observed = JSON.parse(fs.readFileSync(observation, 'utf8'));+ assert.ok(observed.blockedRemovals > 0, JSON.stringify(observed));+ assert.ok(observed.multiplyBoundFiles.includes('diagram.html'), JSON.stringify(observed));+ assert.ok(observed.multiplyBoundFiles.includes('delivery-provenance.json'), JSON.stringify(observed));+ assert.equal(observed.remainingHandles, 0);+ assert.deepEqual(observed.pendingDirectories, []);+ assert.equal(delivered.stderr, '');+ assert.deepEqual(fs.readdirSync(directory).filter((name) => name.startsWith('.archify-')), []);+});+test('cli: repeated lock handle identity failures close the descriptor, remove only the owned lock, and permit retry', () => {const input = path.join(skillRoot, 'examples/agent-tool-call.workflow.json');const out = path.join(tmp, 'delivery-lock-first-fstat.html');diff --git a/archify/test/desktop-reader-browser.test.mjs b/archify/test/desktop-reader-browser.test.mjsindex dcb8d297..89ea2386 100644--- a/archify/test/desktop-reader-browser.test.mjs+++ b/archify/test/desktop-reader-browser.test.mjs@@ -38,7 +38,7 @@ test('all packaged HTML examples pass the real visual-check desktop gate', {const issue250TallGroup = {schema_version: 2,diagram_type: 'workflow',- meta: { title: 'Issue 250 stacked stages' },+ meta: { title: 'Issue 250 stacked stages', output: 'issue-250.html' },lanes: [{ id: 'cage', label: 'One cage' }],groups: [{id: 'group', label: 'Cage', lane: 'cage', fromCol: 1, toCol: 3, variant: 'security',@@ -61,7 +61,7 @@ const issue250TallGroup = {const issue250FiveStageGroup = {...issue250TallGroup,- meta: { title: 'Issue 250 five stacked stages' },+ meta: { title: 'Issue 250 five stacked stages', output: 'issue-250-five-stage.html' },mainPath: ['stageA', 'stageB', 'stageC', 'stageD', 'stageE'],nodes: [{ id: 'stageA', lane: 'cage', col: 2, type: 'security', label: 'stageA', yOffset: -300 },@@ -130,9 +130,11 @@ test('offline intrinsic workflows fit while authored overflow still identifies lconst repaired = JSON.parse(fs.readFileSync(path.join(fixtureRoot, 'order-reflow.workflow.json'), 'utf8'));const meaning = ({ lane, col, yOffset, ...node }) => node;assert.deepEqual(failed.nodes.map(meaning), repaired.nodes.map(meaning));- for (const key of ['edges', 'semanticChecks', 'mainPath', 'cards', 'phases', 'meta']) {+ for (const key of ['edges', 'semanticChecks', 'mainPath', 'cards', 'phases']) {assert.deepEqual(repaired[key], failed[key], key);}+ // Each fixture publishes to its own file; all authored metadata stays the same.+ assert.deepEqual({ ...repaired.meta, output: failed.meta.output }, failed.meta);const tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'archify-workflow-viewport-'));try {for (const name of ['order-overflow', 'order-reflow', 'order-pinned-overflow']) {diff --git a/archify/test/path-semantics.test.mjs b/archify/test/path-semantics.test.mjsindex a44b9fbc..beb26bae 100644--- a/archify/test/path-semantics.test.mjs+++ b/archify/test/path-semantics.test.mjs@@ -560,7 +560,8 @@ test('sameLocation proves distinct safe-ASCII names without writing to the directest('sameLocation proves a long Unicode artifact distinct from a bounded hash sidecar', (t) => {const root = scratchDirectory(t);- const longNfd = `${'e\u0301'.repeat(100)}-architecture.html`;+ // Valid on byte-limited filesystems, but too long to prepend a probe name.+ const longNfd = `${'e\u0301'.repeat(76)}-architecture.html`;const hashSidecar = '.archify-delivery-a3f5712c9e19.json';t.mock.method(fs, 'openSync', () => {throw new Error('a distinct-name proof must not write a probe');@@ -623,27 +624,58 @@ test('sameLocation fails closed when a direct probe would exceed the component l}});-test('probe cleanup never deletes a replacement entry', (t) => {+test('probe cleanup never deletes a replacement entry even when released inodes are reused', (t) => {const root = scratchDirectory(t);const openSync = fs.openSync.bind(fs);const closeSync = fs.closeSync.bind(fs);+ const fstatSync = fs.fstatSync.bind(fs);+ const statSync = fs.statSync.bind(fs);+ const lstatSync = fs.lstatSync.bind(fs);let probePath;+ let probeDescriptor;+ let probeIdentity;+ let replacementIdentity;+ let descriptorOpen = false;let replaced = false;t.mock.method(fs, 'openSync', (targetPath, ...args) => {const descriptor = openSync(targetPath, ...args);- if (path.basename(targetPath).startsWith('.archify-path-semantics-')) {+ if (args[0] === 'wx' && path.basename(targetPath).startsWith('.archify-path-semantics-')) {probePath = targetPath;+ probeDescriptor = descriptor;+ descriptorOpen = true;}return descriptor;});+ t.mock.method(fs, 'fstatSync', (descriptor, ...args) => {+ const stat = fstatSync(descriptor, ...args);+ if (descriptor === probeDescriptor) probeIdentity = stat;+ return stat;+ });t.mock.method(fs, 'closeSync', (descriptor) => {closeSync(descriptor);- if (probePath && !replaced) {+ if (descriptor === probeDescriptor) descriptorOpen = false;+ });+ // Linux may immediately reuse an unlinked inode once its final handle closes.+ // Emulate that allocation policy so the safety assertion is portable.+ const reuseReleasedInode = (stat) => {+ if (!descriptorOpen && replacementIdentity+ && stat.dev === replacementIdentity.dev && stat.ino === replacementIdentity.ino) {+ stat.dev = probeIdentity.dev;+ stat.ino = probeIdentity.ino;+ }+ return stat;+ };+ t.mock.method(fs, 'statSync', (targetPath, ...args) => {+ if (targetPath === probePath && !replaced) {replaced = true;fs.unlinkSync(probePath);fs.writeFileSync(probePath, 'replacement sentinel');+ replacementIdentity = statSync(probePath, { bigint: true });}+ return reuseReleasedInode(statSync(targetPath, ...args));});+ t.mock.method(fs, 'lstatSync', (targetPath, ...args) =>+ reuseReleasedInode(lstatSync(targetPath, ...args)));const comparison = sameLocation(path.join(root, 'Future.HTML'),diff --git a/archify/test/preview.test.mjs b/archify/test/preview.test.mjsindex 0545cc4a..df219955 100644--- a/archify/test/preview.test.mjs+++ b/archify/test/preview.test.mjs@@ -987,7 +987,7 @@ test('preview: publishing through a dangling output symlink creates its target w}});-test('preview: recreating an output symlink to the same target fails the commit', { timeout: 10000 }, async (t) => {+test('preview: recreating an output symlink to the same target fails the commit even when its inode is reused', { timeout: 10000 }, async (t) => {const tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'archify-preview-output-recreated-symlink-'));t.after(() => fs.rmSync(tmp, { recursive: true, force: true }));const input = path.join(tmp, 'diagram.json');@@ -1007,6 +1007,17 @@ test('preview: recreating an output symlink to the same target fails the commit'}throw error;}+ // Filesystems can immediately reuse an unlinked symlink's inode. Preserve+ // that behavior deterministically instead of depending on the host allocator.+ const lstatSync = fs.lstatSync.bind(fs);+ const originalLink = lstatSync(output, { bigint: true });+ t.mock.method(fs, 'lstatSync', (filePath, ...args) => {+ const metadata = lstatSync(filePath, ...args);+ if (String(filePath) === output && metadata.isSymbolicLink()) {+ metadata.ino = typeof metadata.ino === 'bigint' ? originalLink.ino : Number(originalLink.ino);+ }+ return metadata;+ });writeDelayedDeliveryCli(deliveryCli, marker, 'Must not publish');const preview = await startPreview({@@ -1016,7 +1027,12 @@ test('preview: recreating an output symlink to the same target fails the commit'await waitForPath(marker, 'fake delivery did not start');fs.unlinkSync(output);fs.symlinkSync(target, output, process.platform === 'win32' ? 'file' : undefined);- const state = await waitForState(preview.url, (candidate) => candidate.status === 'needs-fix', 'recreated symlink did not fail preview');+ const state = await waitForState(+ preview.url,+ (candidate) => ['needs-fix', 'verified'].includes(candidate.status),+ 'recreated symlink did not finish preview',+ );+ assert.equal(state.status, 'needs-fix', 'a recreated output symlink must prevent publication');assert.equal(state.failure.stage, 'commit');assert.equal(state.failure.code, 'output/target-changed');assert.equal(state.failure.evidence.relation.code, 'requested-entry-changed');diff --git a/archify/test/release-package-gates.test.mjs b/archify/test/release-package-gates.test.mjsindex 1d56bd36..3baefcb5 100644--- a/archify/test/release-package-gates.test.mjs+++ b/archify/test/release-package-gates.test.mjs@@ -1545,7 +1545,11 @@ test('CI and tagged releases share the maintained Windows path contract on Nodeassert.match(runner, /let extendedLongDirectory = extendedUncRoot/);assert.match(runner, /extended UNC delivery beyond traditional MAX_PATH/);assert.match(runner, /path\.win32\.join\(ordinaryLongDirectory, `\$\{token\}-preview[.]html`\)/);- assert.match(runner, /assertNoPrivateStaging\(ordinaryLongDirectory, '[.]archify-delivery-'\)/);+ assert.match(+ runner,+ /assertNoPrivateStaging\(ordinaryLongDirectory, '[.]archify-delivery-', ordinaryLongDelivery\)/,+ );+ assert.match(runner, /fs[.]lstatSync\(path[.]toNamespacedPath\(path[.]join\(directory, entry\)\)\)/);assert.match(runner, /assertNoPrivateStaging\(evidenceDirectory, '[.]archify-visual-check-'\)/);assert.match(runner, /assertNoPrivateStaging\(ordinaryLongDirectory, '[.]archify-preview-'\)/);assert.match(runner, /case-sensitive upper artifact visual-check to shared UNC/);diff --git a/archify/test/renderer-atomic-write.test.mjs b/archify/test/renderer-atomic-write.test.mjsindex 39776ee9..de76ace3 100644--- a/archify/test/renderer-atomic-write.test.mjs+++ b/archify/test/renderer-atomic-write.test.mjs@@ -267,7 +267,10 @@ test('an existing output with no stable file identity fails closed before staginassert.throws(() => writeWorkflow(loaded),(error) => error.archifyDiagnostics?.[0]?.code === 'output/target-indeterminate'- && error.archifyDiagnostics[0].evidence.relation.code === 'target-identity-unavailable',+ // Without a directory alias, the requested-entry inspection encounters+ // the unavailable identity before the resolved-target inspection does.+ && ['requested-entry-identity-unavailable', 'target-identity-unavailable']+ .includes(error.archifyDiagnostics[0].evidence.relation.code),);assert.match(fs.readFileSync(output, 'utf8'), /original/);assert.deepEqual(renderCandidates(root), []);@@ -396,6 +399,9 @@ test('an existing output whose handle cannot be inspected fails closed before st&& error.archifyDiagnostics[0].evidence.relation.systemCode === 'EBUSY',);assert.equal(writes, 0);+ // Node 18 readFileSync calls the public openSync; stop injecting the fault+ // before inspecting the original bytes preserved by the failed render.+ fs.openSync.mock.restore();assert.match(fs.readFileSync(output, 'utf8'), /original/);assert.deepEqual(renderCandidates(root), []);});@@ -1334,6 +1340,56 @@ test('quarantine removal defers remote ENOTEMPTY until its binding handle closes}});+test('remote quarantine cleanup waits for every binding of the published inode to close', (t) => {+ const root = workspace(t, 'archify-quarantine-remove-duplicate-handles-');+ const candidate = path.join(root, 'candidate.html');+ const published = path.join(root, 'published.html');+ fs.writeFileSync(candidate, 'owned artifact\n');+ const staging = captureRegularFileBinding(candidate, { subject: 'staging-entry' });+ const transaction = captureRegularFileBinding(candidate, { subject: 'transaction-entry' });+ assert.equal(staging.status, 'captured');+ assert.equal(transaction.status, 'captured');+ fs.linkSync(candidate, published);+ const closeSync = fs.closeSync.bind(fs);+ const rmdirSync = fs.rmdirSync.bind(fs);+ let closedBindings = 0;+ t.mock.method(fs, 'closeSync', (descriptor) => {+ const result = closeSync(descriptor);+ closedBindings += 1;+ return result;+ });+ t.mock.method(fs, 'rmdirSync', (directory) => {+ if (path.basename(String(directory)).startsWith('.archify-remove-')+ && closedBindings < 2) {+ throw Object.assign(new Error('remote deletion is pending on another binding handle'), { code: 'ENOTEMPTY' });+ }+ return rmdirSync(directory);+ });+ let transactionReleased = false;+ let stagingReleased = false;+ try {+ const removed = quarantineRemoveRegularFileBinding(transaction.binding, candidate, {+ expectedLinks: 2,+ });+ assert.equal(removed.status, 'removed');+ const releasedTransaction = releaseRegularFileBinding(transaction.binding);+ transactionReleased = true;+ assert.equal(releasedTransaction.status, 'released');+ assert.equal(fs.existsSync(candidate), false);+ assert.equal(fs.readFileSync(published, 'utf8'), 'owned artifact\n');++ const retiredStaging = quarantineRemoveRegularFileBinding(staging.binding, candidate);+ assert.equal(retiredStaging.reason.systemCode, 'ENOENT');+ const releasedStaging = releaseRegularFileBinding(staging.binding);+ stagingReleased = true;+ assert.equal(releasedStaging.status, 'released');+ assert.deepEqual(fs.readdirSync(root), ['published.html']);+ } finally {+ if (!transactionReleased) releaseRegularFileBinding(transaction.binding);+ if (!stagingReleased) releaseRegularFileBinding(staging.binding);+ }+});+test('deferred quarantine cleanup preserves a real claimant and fails closed', (t) => {const root = workspace(t, 'archify-quarantine-remove-deferred-claimant-');const target = path.join(root, 'public.lock');diff --git a/archify/test/semantic-radar.test.mjs b/archify/test/semantic-radar.test.mjsindex 16fe3ba7..5c75ff31 100644--- a/archify/test/semantic-radar.test.mjs+++ b/archify/test/semantic-radar.test.mjs@@ -423,7 +423,7 @@ test('Semantic Radar automatically avoids a tall Semantic Passport', {fs.writeFileSync(input, JSON.stringify({schema_version: 1,diagram_type: 'architecture',- meta: { title: 'Tall Passport Radar Regression', output: artifact },+ meta: { title: 'Tall Passport Radar Regression', output: 'tall-passport.html' },components: [...peers,{ id: 'hub', type: 'security', label: 'Relationship Hub', sublabel: 'Many authored links', pos: [900, 500], size: [150, 70] },diff --git a/archify/test/sequence-header-clearance.test.mjs b/archify/test/sequence-header-clearance.test.mjsindex b6fe0e0c..98a40d9e 100644--- a/archify/test/sequence-header-clearance.test.mjs+++ b/archify/test/sequence-header-clearance.test.mjs@@ -17,7 +17,7 @@ test('sequence headers reserve an icon/brand rail without shrinking or changingconst chrome=findChrome();assert.ok(chrome,'The configured browser regression requires Chrome.');const dir=fs.mkdtempSync(path.join(os.tmpdir(),'archify-sequence-header-'));- const spec={schema_version:1,diagram_type:'sequence',meta:{title:'Sequence header clearance regression',quality_profile:'standard',column_fit:'spread',viewBox:[1700,600]},participants:[+ const spec={schema_version:1,diagram_type:'sequence',meta:{title:'Sequence header clearance regression',output:'output.html',quality_profile:'standard',column_fit:'spread',viewBox:[1700,600]},participants:[{id:'transfer',type:'backend',label:'Cloud File Transfer (CFTS)',sublabel:'Transfer participant'},{id:'without-context',type:'external',label:'Cloud File Transfer (CFTS)'},{id:'branded',type:'database',label:'Redis',sublabel:'Cache participant',brand:'redis'},diff --git a/archify/test/visual-check.test.mjs b/archify/test/visual-check.test.mjsindex a3b4e6b3..bb3c2a03 100644--- a/archify/test/visual-check.test.mjs+++ b/archify/test/visual-check.test.mjs@@ -338,38 +338,50 @@ test('visual-check inspects a private snapshot even if the public artifact is reassert.deepEqual(fs.readFileSync(input), original);});-test('visual-check preserves a regular screenshot claimant swapped before registration', async (t) => {- const input = artifact('staged-screenshot-regular-claimant.html');- const outputs = sidecarPaths(input);- const browser = fakeBrowser();- const inspect = browser.inspect.bind(browser);- const sentinel = Buffer.from('external regular screenshot claimant\n');- let claimantPath;- browser.inspect = async (args) => {- const metrics = await inspect(args);- if (!claimantPath && args.screenshotPath) {- claimantPath = args.screenshotPath;- fs.unlinkSync(claimantPath);- fs.writeFileSync(claimantPath, sentinel, { flag: 'wx' });- }- return metrics;- };- t.after(() => {- for (const directory of stagingDirectories(path.dirname(outputs.receipt))) {- fs.rmSync(path.join(path.dirname(outputs.receipt), directory), { recursive: true, force: 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 },+]) {+ test(`visual-check preserves ${scenario.name}`, async (t) => {+ const input = artifact(`staged-screenshot-regular-claimant-${scenario.replace}.html`);+ const outputs = sidecarPaths(input);+ const browser = fakeBrowser();+ const inspect = browser.inspect.bind(browser);+ const sentinel = Buffer.from('external regular screenshot claimant\n');+ const stagingBefore = new Set(stagingDirectories(path.dirname(outputs.receipt)));+ let claimantPath;+ browser.inspect = async (args) => {+ const metrics = await inspect(args);+ if (!claimantPath && args.screenshotPath) {+ claimantPath = args.screenshotPath;+ const before = entryIdentity(claimantPath);+ if (scenario.replace) fs.unlinkSync(claimantPath);+ fs.writeFileSync(claimantPath, sentinel, { flag: scenario.replace ? 'wx' : 'w' });+ if (!scenario.replace) assert.deepEqual(entryIdentity(claimantPath), before);+ }+ return metrics;+ };+ t.after(() => {+ for (const directory of stagingDirectories(path.dirname(outputs.receipt))) {+ if (!stagingBefore.has(directory)) {+ fs.rmSync(path.join(path.dirname(outputs.receipt), directory), { recursive: true, force: true });+ }+ }+ });- const result = await runVisualCheck({- artifactPath: input,- chromePath: '/fake/chrome',- browserFactory: async () => browser,- });+ const result = await runVisualCheck({+ artifactPath: input,+ chromePath: '/fake/chrome',+ browserFactory: async () => browser,+ });- assert.equal(result.exitCode, 1);- assert.deepEqual(fs.readFileSync(claimantPath), sentinel);- assert.equal(fs.existsSync(outputs.receipt), false);-});+ assert.equal(result.exitCode, 1);+ assert.deepEqual(fs.readFileSync(claimantPath), sentinel);+ assert.equal(fs.existsSync(outputs.receipt), false);+ const cleanupErrors = result.receipt.diagnostics.at(-1)?.evidence?.errors;+ assert.ok(cleanupErrors.some((entry) => entry.file === claimantPath && /preserved/.test(entry.reason)));+ });+}test('visual-check cleanup preserves a successor swapped at its final removal boundary', async (t) => {const input = artifact('staged-cleanup-successor.html');@@ -2085,13 +2097,23 @@ test('visual-check rolls back when staged evidence changes after receipt bindingconst outputs = sidecarPaths(input);const sentinel = Buffer.from('mutated staged screenshot bytes\n');const linkSync = fs.linkSync.bind(fs);+ const stagingBefore = new Set(stagingDirectories(path.dirname(outputs.receipt)));+ let changedPath;+ t.after(() => {+ for (const directory of stagingDirectories(path.dirname(outputs.receipt))) {+ if (!stagingBefore.has(directory)) {+ fs.rmSync(path.join(path.dirname(outputs.receipt), directory), { recursive: true, force: true });+ }+ }+ });let injected = false;t.mock.method(fs, 'linkSync', (source, target) => {const result = linkSync(source, target);if (!injected&& path.basename(String(source)) === 'contact-sheet.html'&& path.basename(path.dirname(String(source))).startsWith('.archify-visual-check-')) {- fs.writeFileSync(path.join(path.dirname(String(source)), 'capture-0.png'), sentinel);+ changedPath = path.join(path.dirname(String(source)), 'capture-0.png');+ fs.writeFileSync(changedPath, sentinel);injected = true;}return result;@@ -2113,7 +2135,9 @@ test('visual-check rolls back when staged evidence changes after receipt bindingassert.equal(fs.existsSync(outputs.receipt), false);assert.equal(fs.existsSync(outputs.contactSheet), false);assert.equal(outputs.screenshots.every((entry) => !fs.existsSync(entry.path)), true);- assert.deepEqual(stagingDirectories(path.dirname(outputs.receipt)), []);+ assert.deepEqual(fs.readFileSync(changedPath), sentinel);+ const rollbackErrors = result.receipt.diagnostics.at(-1)?.evidence?.rollbackErrors;+ assert.ok(rollbackErrors.some((entry) => entry.file === changedPath && /content changed; it was preserved/.test(entry.reason)));});test('visual-check preserves digest-mismatched evidence instead of treating its receipt as ownership', async () => {