Skip to content

Turn any idea, plan, or codebase into a beautiful interactive diagram. An agent skill for Claude Code, Codex, and more.

fix: tolerate SMB staging visibility delay

sunsunsund96c9471d8d2
diff --git a/archify.zip b/archify.zip
index a632339d..1a4a8c81 100644
Binary files a/archify.zip and b/archify.zip differ
diff --git a/archify/bin/archify.mjs b/archify/bin/archify.mjs
index 2040760f..be1b6d8f 100755
--- a/archify/bin/archify.mjs
+++ b/archify/bin/archify.mjs
@@ -877,6 +877,50 @@ function createStagingRetirementQuarantine(parent) {
return undefined;
}
+const stagingRemovalSignal = new Int32Array(new SharedArrayBuffer(4));
+const stagingRemovalAttempts = 10;
+
+function removeEmptyStagingDirectoryWithRetry(directory) {
+ let failure;
+ for (let attempt = 0; attempt < stagingRemovalAttempts; attempt += 1) {
+ try {
+ fs.rmdirSync(directory);
+ return;
+ } catch (error) {
+ failure = error;
+ // SMB can acknowledge the last file removal before the directory view
+ // catches up. Retrying an empty-directory removal is claimant-safe: any
+ // real entry keeps returning ENOTEMPTY and is never removed recursively.
+ if (error?.code !== 'ENOTEMPTY' || attempt === stagingRemovalAttempts - 1) break;
+ Atomics.wait(
+ stagingRemovalSignal,
+ 0,
+ 0,
+ Math.min(5 * (2 ** attempt), 250),
+ );
+ }
+ }
+ throw failure;
+}
+
+function stagingDirectoryAppearsEmpty(directory) {
+ for (let attempt = 0; attempt < stagingRemovalAttempts; attempt += 1) {
+ try {
+ if (fs.readdirSync(directory).length === 0) return true;
+ } catch {
+ return false;
+ }
+ if (attempt === stagingRemovalAttempts - 1) break;
+ Atomics.wait(
+ stagingRemovalSignal,
+ 0,
+ 0,
+ Math.min(5 * (2 ** attempt), 250),
+ );
+ }
+ return false;
+}
+
function removeOwnedEmptyStagingDirectory(directory, identity, { throwOnFailure = false } = {}) {
let current;
try {
@@ -890,11 +934,7 @@ function removeOwnedEmptyStagingDirectory(directory, identity, { throwOnFailure
|| current.ino === 0n
|| current.dev !== identity.device
|| current.ino !== identity.inode) return false;
- try {
- if (fs.readdirSync(directory).length !== 0) return false;
- } catch {
- return false;
- }
+ if (!stagingDirectoryAppearsEmpty(directory)) return false;
const quarantine = createStagingRetirementQuarantine(path.dirname(directory));
if (!quarantine) return false;
const movedPath = path.join(quarantine, path.basename(directory));
@@ -922,8 +962,8 @@ function removeOwnedEmptyStagingDirectory(directory, identity, { throwOnFailure
try {
// The unpredictable 0700 quarantine closes the public replacement race.
// Never recurse: unexpected contents remain available for recovery.
- fs.rmdirSync(movedPath);
- fs.rmdirSync(quarantine);
+ removeEmptyStagingDirectoryWithRetry(movedPath);
+ removeEmptyStagingDirectoryWithRetry(quarantine);
return true;
} catch (error) {
if (throwOnFailure) throw error;
diff --git a/archify/bin/preview.mjs b/archify/bin/preview.mjs
index 53af8a54..364e8cf1 100644
--- a/archify/bin/preview.mjs
+++ b/archify/bin/preview.mjs
@@ -13,6 +13,7 @@ import {
captureRegularFileBinding,
publishRegularFileBinding,
releaseRegularFileBinding,
+ removeEmptyDirectoryWithRetry,
removeOwnedRegularFile,
verifyAtomicOutput,
} from '../renderers/shared/atomic-output.mjs';
@@ -296,7 +297,7 @@ function cleanupOwnedDirectory(directoryPath, identity) {
|| current.dev !== identity.device
|| current.ino !== identity.inode) return;
try {
- fs.rmdirSync(directoryPath);
+ removeEmptyDirectoryWithRetry(directoryPath);
} catch (error) {
// An entry whose identity was never bound to this preview may be an
// external claimant. Preserve the private directory as recovery material
diff --git a/archify/bin/visual-check.mjs b/archify/bin/visual-check.mjs
index 28fd59f7..d6dfe4b5 100644
--- a/archify/bin/visual-check.mjs
+++ b/archify/bin/visual-check.mjs
@@ -15,6 +15,7 @@ import {
quarantineRemoveLinkedRegularFileAlias,
quarantineRemoveRegularFileBinding,
releaseRegularFileBinding,
+ removeEmptyDirectoryWithRetry,
verifyAtomicOutput,
verifyRegularFileBinding,
} from '../renderers/shared/atomic-output.mjs';
@@ -563,7 +564,7 @@ function cleanupStagedEvidence(ownership, { removeDirectory = false } = {}) {
reason: 'staging directory identity changed; it was preserved',
});
} else {
- fs.rmdirSync(ownership.stagingDirectory);
+ removeEmptyDirectoryWithRetry(ownership.stagingDirectory);
}
} catch (error) {
if (error?.code !== 'ENOENT') {
diff --git a/archify/renderers/shared/atomic-output.mjs b/archify/renderers/shared/atomic-output.mjs
index bfad9581..af283d70 100644
--- a/archify/renderers/shared/atomic-output.mjs
+++ b/archify/renderers/shared/atomic-output.mjs
@@ -95,6 +95,30 @@ const digestChunkBytes = 64 * 1024;
const removalCleanupSignal = new Int32Array(new SharedArrayBuffer(4));
const removalCleanupAttempts = 10;
+export function removeEmptyDirectoryWithRetry(directory, { retry = true } = {}) {
+ const attempts = retry ? removalCleanupAttempts : 1;
+ let failure;
+ for (let attempt = 0; attempt < attempts; attempt += 1) {
+ try {
+ fs.rmdirSync(directory);
+ return;
+ } catch (error) {
+ failure = error;
+ // SMB can acknowledge unlink before a following directory removal sees
+ // the deleted entry disappear. Retrying rmdir is claimant-safe: a real
+ // entry keeps the directory non-empty and is never removed recursively.
+ if (error?.code !== 'ENOTEMPTY' || attempt === attempts - 1) break;
+ Atomics.wait(
+ removalCleanupSignal,
+ 0,
+ 0,
+ Math.min(5 * (2 ** attempt), 250),
+ );
+ }
+ }
+ throw failure;
+}
+
function validExpectedLinks(value) {
return Number.isSafeInteger(value) && value > 0;
}
@@ -468,25 +492,12 @@ function createRemovalQuarantine(parentPath) {
}
function removeEmptyQuarantine(directory, { retry = false } = {}) {
- const attempts = retry ? removalCleanupAttempts : 1;
let failure;
- for (let attempt = 0; attempt < attempts; attempt += 1) {
- try {
- fs.rmdirSync(directory);
- return null;
- } catch (error) {
- failure = error;
- // SMB can acknowledge unlink before a following directory removal sees
- // the deleted entry disappear. Retrying rmdir is claimant-safe: a real
- // entry keeps the directory non-empty and is never removed recursively.
- if (error?.code !== 'ENOTEMPTY' || attempt === attempts - 1) break;
- Atomics.wait(
- removalCleanupSignal,
- 0,
- 0,
- Math.min(5 * (2 ** attempt), 250),
- );
- }
+ try {
+ removeEmptyDirectoryWithRetry(directory, { retry });
+ return null;
+ } catch (error) {
+ failure = error;
}
return filesystemFailure('removal-quarantine-cleanup-failed', failure, {
recoveryDirectory: directory,
diff --git a/archify/test/cli.test.mjs b/archify/test/cli.test.mjs
index deb6c399..f0625672 100644
--- a/archify/test/cli.test.mjs
+++ b/archify/test/cli.test.mjs
@@ -2487,6 +2487,79 @@ 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-')),
+ );
+ fs.writeFileSync(wrapper, `
+import fs from 'node:fs';
+import path from 'node:path';
+const rmdirSync = fs.rmdirSync.bind(fs);
+let injected = false;
+fs.rmdirSync = (directory, ...args) => {
+ if (!injected
+ && path.basename(path.dirname(String(directory))).startsWith('.archify-staging-remove-')
+ && path.basename(String(directory)).startsWith('.archify-delivery-')) {
+ injected = true;
+ throw Object.assign(new Error('simulated remote deletion visibility delay'), { code: 'ENOTEMPTY' });
+ }
+ return rmdirSync(directory, ...args);
+};
+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({ injected }));
+`);
+
+ 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);
+ assert.equal(JSON.parse(fs.readFileSync(observation, 'utf8')).injected, true);
+ assert.doesNotMatch(delivered.stderr, /Warning: could not remove delivery staging directory/);
+ 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)),
+ [],
+ );
+});
+
+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');
+ fs.writeFileSync(wrapper, `
+import fs from 'node:fs';
+import path from 'node:path';
+const readdirSync = fs.readdirSync.bind(fs);
+let injected = false;
+fs.readdirSync = (directory, ...args) => {
+ if (!injected && path.basename(String(directory)).startsWith('.archify-delivery-')) {
+ injected = true;
+ return ['recently-deleted-entry.tmp'];
+ }
+ return readdirSync(directory, ...args);
+};
+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({ injected }));
+`);
+
+ 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);
+ assert.equal(JSON.parse(fs.readFileSync(observation, 'utf8')).injected, true);
+ assert.doesNotMatch(delivered.stderr, /Warning: could not remove delivery staging directory/);
+ assert.deepEqual(deliveryStagingEntries(path.dirname(out)), []);
+});
+
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/preview.test.mjs b/archify/test/preview.test.mjs
index a5d281ec..0545cc4a 100644
--- a/archify/test/preview.test.mjs
+++ b/archify/test/preview.test.mjs
@@ -928,6 +928,33 @@ test('preview: cleanup stays bound to the physical output parent after a directo
assert.equal(fs.readFileSync(sentinel, 'utf8'), 'preserve claimant');
});
+test('preview: cleanup retries transient remote ENOTEMPTY', { timeout: 10000 }, async (t) => {
+ const tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'archify-preview-cleanup-enotempty-'));
+ t.after(() => fs.rmSync(tmp, { recursive: true, force: true }));
+ const input = path.join(skillRoot, 'examples', 'web-app.architecture.json');
+ const output = path.join(tmp, 'diagram.html');
+ const preview = await startPreview({
+ type: 'architecture', input, output, open: false, watch: false, pollMs: 60_000,
+ });
+ const rmdirSync = fs.rmdirSync.bind(fs);
+ let injected = false;
+ t.mock.method(fs, 'rmdirSync', (directory, ...args) => {
+ if (!injected && path.basename(String(directory)).startsWith('.archify-preview-')) {
+ injected = true;
+ throw Object.assign(new Error('simulated remote deletion visibility delay'), { code: 'ENOTEMPTY' });
+ }
+ return rmdirSync(directory, ...args);
+ });
+
+ await preview.stop();
+
+ assert.equal(injected, true);
+ assert.deepEqual(
+ fs.readdirSync(tmp).filter((entry) => entry.startsWith('.archify-preview-')),
+ [],
+ );
+});
+
test('preview: publishing through a dangling output symlink creates its target without replacing the link', { timeout: 10000 }, async (t) => {
const tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'archify-preview-output-dangling-'));
t.after(() => fs.rmSync(tmp, { recursive: true, force: true }));
diff --git a/archify/test/visual-check.test.mjs b/archify/test/visual-check.test.mjs
index bf958712..a3b4e6b3 100644
--- a/archify/test/visual-check.test.mjs
+++ b/archify/test/visual-check.test.mjs
@@ -2055,6 +2055,31 @@ test('public visual-check CLI reports a committed cleanup warning', (t) => {
assert.equal(JSON.parse(fs.readFileSync(outputs.receipt, 'utf8')).status, 'skipped');
});
+test('visual-check retries transient remote ENOTEMPTY during staging cleanup', async (t) => {
+ const input = artifact('transient-staging-enotempty.html');
+ const outputDirectory = path.dirname(input);
+ const rmdirSync = fs.rmdirSync.bind(fs);
+ let injected = false;
+ t.mock.method(fs, 'rmdirSync', (directory, ...args) => {
+ if (!injected && path.basename(String(directory)).startsWith('.archify-visual-check-')) {
+ injected = true;
+ throw Object.assign(new Error('simulated remote deletion visibility delay'), { code: 'ENOTEMPTY' });
+ }
+ return rmdirSync(directory, ...args);
+ });
+
+ const result = await runVisualCheck({
+ artifactPath: input,
+ chromePath: '/fake/chrome',
+ browserFactory: async () => fakeBrowser(),
+ });
+
+ assert.equal(injected, true);
+ assert.equal(result.exitCode, 0);
+ assert.deepEqual(result.receipt.diagnostics, []);
+ assert.deepEqual(stagingDirectories(outputDirectory), []);
+});
+
test('visual-check rolls back when staged evidence changes after receipt binding', async (t) => {
const input = artifact('staged-content-changed-after-receipt-binding.html');
const outputs = sidecarPaths(input);
diff --git a/scripts/run-windows-path-tests.mjs b/scripts/run-windows-path-tests.mjs
index 82a3bb4f..08659b3c 100644
--- a/scripts/run-windows-path-tests.mjs
+++ b/scripts/run-windows-path-tests.mjs
@@ -65,11 +65,26 @@ function removeChildren(directory) {
}
}
+const remoteVisibilitySignal = new Int32Array(new SharedArrayBuffer(4));
+
function assertNoPrivateStaging(directory, prefix) {
+ let remaining = [];
+ for (let attempt = 0; attempt < 10; attempt += 1) {
+ remaining = fs.readdirSync(directory).filter((entry) => entry.startsWith(prefix));
+ if (remaining.length === 0) return;
+ if (attempt < 9) {
+ Atomics.wait(
+ remoteVisibilitySignal,
+ 0,
+ 0,
+ Math.min(5 * (2 ** attempt), 250),
+ );
+ }
+ }
assert.deepEqual(
- fs.readdirSync(directory).filter((entry) => entry.startsWith(prefix)),
+ remaining,
[],
- `${prefix} staging must be removed from ${directory}`,
+ `${prefix} staging must disappear after bounded remote visibility convergence in ${directory}`,
);
}