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: add explicit output crash recovery
tt-a1i26108d3d9830
diff --git a/archify/bin/recover-output.mjs b/archify/bin/recover-output.mjsnew file mode 100644index 00000000..b389d34c--- /dev/null+++ b/archify/bin/recover-output.mjs@@ -0,0 +1,26 @@+import { recoverRetiredPublication } from '../renderers/shared/atomic-output.mjs';++function usage() {+ process.stderr.write('Usage: node bin/recover-output.mjs <private-recovery-directory> [--json]\n');+}++const args = process.argv.slice(2);+const json = args.at(-1) === '--json';+if (json) args.pop();+if (args.length !== 1) {+ usage();+ process.exitCode = 64;+} else {+ const result = recoverRetiredPublication(args[0]);+ if (json) {+ process.stdout.write(`${JSON.stringify(result)}\n`);+ } else {+ const reason = result.reason?.code || 'publication-recovery-unknown';+ process.stdout.write(`${result.status}: ${reason}\n`);+ }+ // A complete prior recovery is idempotent. A preserved target is a safe,+ // deliberate non-action that needs the operator to inspect the claimant.+ process.exitCode = ['recovered', 'absent'].includes(result.status)+ ? 0+ : result.status === 'preserved' ? 2 : 1;+}diff --git a/archify/references/delivery-contract.md b/archify/references/delivery-contract.mdindex 85368d9c..f9a24d08 100644--- a/archify/references/delivery-contract.md+++ b/archify/references/delivery-contract.md@@ -103,11 +103,37 @@ creates the new public name with an exclusive hard link. A caught failure rollsback when the public slot and recovery binding still permit it. A processinterruption between those namespace operations can instead leave the publicpath absent while the verified previous bytes remain in an adjacent private-recovery backup. Single-artifact publication uses-`.archify-remove-*/previous`; paired flows retain the backup in their private-transaction staging directory. Preserve and inspect that backup before serial-recovery; for `deliver`, the pending journal and lock keep strict checkers-fail-closed. The portable Node.js filesystem API has no pathname+recovery backup. Single-artifact publication records the original slot/alias+identity and backup inode, mode, SHA-256, and byte count in private+`.archify-remove-*/publication-recovery-v1.json`, beside `previous`. To make a+specific interrupted publication visible again, stop concurrent writers and run:++```bash+node bin/recover-output.mjs /absolute/path/to/.archify-remove-<id> --json+```++This is explicit recovery, not a directory scanner. Before linking, the helper+checks for a changed parent or alias, an altered/hardlinked record or backup,+digest or inode mismatch, and any existing public target. It restores only by+no-clobber hard link, so a new claimant is preserved rather than overwritten;+it never recursively removes unknown entries. A completed recovery is+idempotent. The record is evidence to be independently verified, not an+authority to restore arbitrary private bytes: the helper accepts it only from+the recorded generated child of the original physical target parent, with the+same directory identity. Name the exact directory reported by the interrupted+process and inspect an uncertain record manually. A non-cooperating process can+still swap pathnames after those checks and before Node.js `linkSync`; Node does+not expose a descriptor-bound link operation. Post-link identity verification+then fails closed and retains recovery evidence, rather than claiming recovery+or deleting an uncertain name. If recovery itself is interrupted after the+link, the old public bytes and private backup can both remain; a later recovery+run preserves the public target and needs explicit operator resolution. The+record is fsynced before the old public name is retired on platforms supporting+directory sync, and the tested guarantee is recovery after a killed process;+this is not a claim of power-loss, storage-controller, NFS, or SMB durability.+Paired flows retain their backup in private transaction staging. For `deliver`,+the pending journal and lock keep strict checkers fail-closed. The portable+Node.js filesystem API has no pathnamecompare-and-swap that both replaces an existing name atomically and refuses tooverwrite a late claimant: `rename` would close the visibility gap only byoverwriting that claimant.diff --git a/archify/renderers/shared/atomic-output.mjs b/archify/renderers/shared/atomic-output.mjsindex 4f332320..de695e20 100644--- a/archify/renderers/shared/atomic-output.mjs+++ b/archify/renderers/shared/atomic-output.mjs@@ -95,6 +95,9 @@ const regularFileBindingGroups = new Map();const digestChunkBytes = 64 * 1024;const removalCleanupSignal = new Int32Array(new SharedArrayBuffer(4));const removalCleanupAttempts = 10;+const publicationRecoveryRecordName = 'publication-recovery-v1.json';+const publicationRecoveryRecordVersion = 1;+const publicationRecoveryRecordMaxBytes = 16 * 1024;export function removeEmptyDirectoryWithRetry(directory, { retry = true } = {}) {const attempts = retry ? removalCleanupAttempts : 1;@@ -545,6 +548,202 @@ function removalRecovery(subject, code, filePath, quarantineDirectory, quarantin};}+function decimal(value) {+ return value.toString();+}++function parseDecimal(value) {+ if (typeof value !== 'string' || !/^(?:0|[1-9]\d*)$/.test(value)) return null;+ try {+ return BigInt(value);+ } catch {+ return null;+ }+}++function parseSafeInteger(value) {+ return Number.isSafeInteger(value) && value >= 0 ? value : null;+}++function serializeRequestedEntry(entry) {+ if (entry?.kind === 'absent') return { kind: 'absent' };+ if (entry?.kind !== 'existing' || typeof entry.entryType !== 'string'+ || typeof entry.device !== 'bigint' || typeof entry.inode !== 'bigint') {+ return null;+ }+ return {+ kind: 'existing',+ entryType: entry.entryType,+ device: decimal(entry.device),+ inode: decimal(entry.inode),+ ...(entry.entryType === 'symbolic-link' ? {+ changedAtNs: decimal(entry.changedAtNs),+ createdAtNs: decimal(entry.createdAtNs),+ } : {}),+ };+}++function createPublicationRecoveryRecord(directory, snapshot, previous) {+ const requestedEntry = serializeRequestedEntry(snapshot?.requestedEntry);+ const slot = snapshot?.slot;+ if (!requestedEntry || !slot || typeof snapshot?.requestedPath !== 'string'+ || typeof snapshot?.requestedEntryPolicy !== 'string'+ || typeof slot.commitPath !== 'string' || typeof slot.parentPath !== 'string'+ || typeof slot.name !== 'string' || typeof slot.parentDevice !== 'bigint'+ || typeof slot.parentInode !== 'bigint' || !previous?.identity+ || !previous?.content || !Number.isSafeInteger(previous.mode)) {+ return relation('unknown', 'publication-recovery-record-input-invalid');+ }+ const recordPath = path.join(directory, publicationRecoveryRecordName);+ let directoryMetadata;+ let parentMetadata;+ try {+ directoryMetadata = fs.lstatSync(directory, { bigint: true });+ parentMetadata = fs.statSync(path.dirname(directory), { bigint: true });+ } catch (error) {+ return filesystemFailure('publication-recovery-directory-inspection-failed', error, {+ recoveryDirectory: directory,+ });+ }+ if (!directoryMetadata.isDirectory() || directoryMetadata.ino === 0n+ || !parentMetadata.isDirectory()+ || parentMetadata.dev !== slot.parentDevice || parentMetadata.ino !== slot.parentInode+ || !/^\.archify-remove-[a-f\d]{32}$/.test(path.basename(directory))) {+ return relation('unknown', 'publication-recovery-directory-invalid', {+ recoveryDirectory: directory,+ });+ }+ const record = {+ version: publicationRecoveryRecordVersion,+ kind: 'archify-retired-output-recovery',+ backup: {+ name: 'previous',+ sha256: previous.content.sha256,+ bytes: previous.content.bytes,+ mode: previous.mode,+ device: decimal(previous.identity.device),+ inode: decimal(previous.identity.inode),+ },+ recovery: {+ name: path.basename(directory),+ device: decimal(directoryMetadata.dev),+ inode: decimal(directoryMetadata.ino),+ },+ target: {+ requestedPath: snapshot.requestedPath,+ requestedEntryPolicy: snapshot.requestedEntryPolicy,+ requestedEntry,+ commitPath: slot.commitPath,+ parentPath: slot.parentPath,+ parentDevice: decimal(slot.parentDevice),+ parentInode: decimal(slot.parentInode),+ name: slot.name,+ },+ };+ const bytes = Buffer.from(`${JSON.stringify(record)}\n`);+ let descriptor;+ let writeFailure;+ try {+ descriptor = fs.openSync(+ recordPath,+ fs.constants.O_WRONLY | fs.constants.O_CREAT | fs.constants.O_EXCL,+ 0o600,+ );+ let offset = 0;+ while (offset < bytes.byteLength) {+ const wrote = fs.writeSync(descriptor, bytes, offset, bytes.byteLength - offset);+ if (wrote <= 0) throw Object.assign(new Error('short recovery record write'), { code: 'EIO' });+ offset += wrote;+ }+ fs.fsyncSync(descriptor);+ } catch (error) {+ writeFailure = error;+ } finally {+ if (descriptor !== undefined) {+ try {+ fs.closeSync(descriptor);+ } catch (error) {+ writeFailure ||= error;+ }+ }+ }+ if (writeFailure) {+ return filesystemFailure('publication-recovery-record-write-failed', writeFailure, {+ recoveryDirectory: directory,+ recoveryFile: recordPath,+ });+ }+ // POSIX requires the parent directory entry to be synced separately. Do not+ // claim a kill-recovery record is durable where the platform cannot do that.+ if (process.platform !== 'win32') {+ let directoryDescriptor;+ let directoryFailure;+ try {+ directoryDescriptor = fs.openSync(directory, fs.constants.O_RDONLY);+ fs.fsyncSync(directoryDescriptor);+ } catch (error) {+ directoryFailure = error;+ } finally {+ if (directoryDescriptor !== undefined) {+ try {+ fs.closeSync(directoryDescriptor);+ } catch (error) {+ directoryFailure ||= error;+ }+ }+ }+ if (directoryFailure) {+ return filesystemFailure('publication-recovery-record-directory-sync-failed', directoryFailure, {+ recoveryDirectory: directory,+ recoveryFile: recordPath,+ });+ }+ }+ const captured = captureRegularFileBinding(recordPath, {+ subject: 'publication-recovery-record',+ expectedSha256: createHash('sha256').update(bytes).digest('hex'),+ expectedBytes: bytes.byteLength,+ // Windows reports a synthetic POSIX mode whose read bits cannot represent+ // the private ACL established by the exclusive create above.+ expectedMode: process.platform === 'win32' ? undefined : 0o600,+ expectedLinks: 1,+ });+ if (captured.status !== 'captured') {+ return {+ ...captured,+ recoveryDirectory: directory,+ recoveryFile: recordPath,+ };+ }+ return {+ status: 'created',+ recordPath,+ binding: captured.binding,+ };+}++function discardPublicationRecoveryRecord(record) {+ if (!record?.binding || typeof record.recordPath !== 'string') return null;+ let removed;+ let released;+ try {+ removed = quarantineRemoveRegularFileBinding(record.binding, record.recordPath, {+ subject: 'publication-recovery-record',+ expectedLinks: 1,+ });+ } finally {+ released = releaseRegularFileBinding(record.binding);+ }+ if (released.status !== 'released') return released;+ return removed.status === 'removed' ? null : removed;+}++function releasePublicationRecoveryRecord(record) {+ if (!record?.binding) return null;+ const released = releaseRegularFileBinding(record.binding);+ return released.status === 'released' ? null : released;+}+/*** Remove a public regular-file name without a verify-to-unlink race. The* public entry is first moved into an unpredictable private directory and is@@ -938,6 +1137,7 @@ export function publishRegularFileBinding(binding, candidatePath, snapshot, {let previousBinding;let recoveryDirectory;let backupPath;+ let recoveryRecord;let previousBackedUp = false;const finishPrevious = () => {if (!previousBinding) return null;@@ -975,6 +1175,10 @@ export function publishRegularFileBinding(binding, candidatePath, snapshot, {if (claimantRemoval.status === 'removed') publicRemoval = claimantRemoval;}const restored = restorePrevious();+ const recordCleanup = restored?.status === 'match'+ ? discardPublicationRecoveryRecord(recoveryRecord)+ : releasePublicationRecoveryRecord(recoveryRecord);+ recoveryRecord = undefined;const released = finishPrevious();const directoryCleanup = cleanupRecoveryDirectory();return {@@ -982,11 +1186,12 @@ export function publishRegularFileBinding(binding, candidatePath, snapshot, {...(publicRemoval.status !== 'removed' && publicRemoval.status !== 'absent'? { publicState: publicRemoval.reason } : {}),...(restored && restored.status !== 'match' ? { restoreState: restored.reason } : {}),+ ...(recordCleanup ? { recoveryRecordState: recordCleanup.reason } : {}),...(released ? { releaseState: released.reason } : {}),...(directoryCleanup ? {recoveryDirectory: directoryCleanup.reason?.recoveryDirectory || recoveryDirectory,} : {}),- ...((restored && restored.status !== 'match') || directoryCleanup+ ...((restored && restored.status !== 'match') || recordCleanup || directoryCleanup? { recoveryFile: backupPath } : {}),};};@@ -1010,6 +1215,18 @@ export function publishRegularFileBinding(binding, candidatePath, snapshot, {}recoveryDirectory = quarantine.directory;backupPath = path.join(recoveryDirectory, 'previous');+ const recovery = createPublicationRecoveryRecord(recoveryDirectory, snapshot, previous);+ if (recovery.status !== 'created') {+ const released = finishPrevious();+ const directoryCleanup = cleanupRecoveryDirectory();+ return {+ ...recovery,+ ...(recoveryDirectory ? { recoveryDirectory } : {}),+ ...(released ? { releaseState: released.reason } : {}),+ ...(directoryCleanup ? { directoryCleanupState: directoryCleanup.reason } : {}),+ };+ }+ recoveryRecord = recovery;const backup = backupPublicRegularFileBinding(previousBinding,commitPath,@@ -1018,10 +1235,15 @@ export function publishRegularFileBinding(binding, candidatePath, snapshot, {);previousBackedUp = backup.status === 'backed-up';if (!previousBackedUp) {+ const recordCleanup = backup.backupCreated+ ? releasePublicationRecoveryRecord(recoveryRecord)+ : discardPublicationRecoveryRecord(recoveryRecord);+ recoveryRecord = undefined;const released = finishPrevious();const directoryCleanup = backup.backupCreated ? null : cleanupRecoveryDirectory();return {...backup,+ ...(recordCleanup ? { recoveryRecordState: recordCleanup.reason } : {}),...(released ? { releaseState: released.reason } : {}),...(directoryCleanup ? { directoryCleanupState: directoryCleanup.reason } : {}),};@@ -1078,6 +1300,11 @@ export function publishRegularFileBinding(binding, candidatePath, snapshot, {{ subject: 'previous-output-backup', expectedLinks: 1 },);if (backupRemoval.status !== 'removed') cleanupWarning = backupRemoval;+ const recordCleanup = backupRemoval.status === 'removed'+ ? discardPublicationRecoveryRecord(recoveryRecord)+ : releasePublicationRecoveryRecord(recoveryRecord);+ recoveryRecord = undefined;+ cleanupWarning ||= recordCleanup;}const released = finishPrevious();const directoryCleanup = cleanupRecoveryDirectory();@@ -1379,3 +1606,370 @@ export function verifyAtomicOutput(snapshot) {}return relation('match', 'atomic-output-match', { commitPath: previousSlot.commitPath });}++function parsePublicationRecoveryRecord(buffer) {+ if (!Buffer.isBuffer(buffer) || buffer.byteLength > publicationRecoveryRecordMaxBytes) {+ return relation('unknown', 'publication-recovery-record-too-large');+ }+ let parsed;+ try {+ parsed = JSON.parse(buffer.toString('utf8'));+ } catch (error) {+ return filesystemFailure('publication-recovery-record-invalid-json', error);+ }+ const backup = parsed?.backup;+ const recovery = parsed?.recovery;+ const target = parsed?.target;+ const requestedEntry = target?.requestedEntry;+ const validEntry = requestedEntry?.kind === 'absent'+ || (requestedEntry?.kind === 'existing'+ && typeof requestedEntry.entryType === 'string'+ && parseDecimal(requestedEntry.device) !== null+ && parseDecimal(requestedEntry.inode) !== null+ && (requestedEntry.entryType !== 'symbolic-link'+ || (parseDecimal(requestedEntry.changedAtNs) !== null+ && parseDecimal(requestedEntry.createdAtNs) !== null)));+ const valid = parsed?.version === publicationRecoveryRecordVersion+ && parsed?.kind === 'archify-retired-output-recovery'+ && backup?.name === 'previous'+ && typeof backup.sha256 === 'string' && /^[a-f\d]{64}$/i.test(backup.sha256)+ && parseSafeInteger(backup.bytes) !== null+ && Number.isSafeInteger(backup.mode) && backup.mode >= 0 && backup.mode <= 0o777+ && parseDecimal(backup.device) !== null && parseDecimal(backup.inode) !== null+ && typeof recovery?.name === 'string' && /^\.archify-remove-[a-f\d]{32}$/.test(recovery.name)+ && parseDecimal(recovery.device) !== null+ && parseDecimal(recovery.inode) !== null+ && typeof target?.requestedPath === 'string' && path.isAbsolute(target.requestedPath)+ && typeof target.requestedEntryPolicy === 'string'+ && ['followable-alias', 'regular-or-absent'].includes(target.requestedEntryPolicy)+ && validEntry+ && typeof target.commitPath === 'string' && path.isAbsolute(target.commitPath)+ && typeof target.parentPath === 'string' && path.isAbsolute(target.parentPath)+ && typeof target.name === 'string' && target.name === path.basename(target.commitPath)+ && target.parentPath === path.dirname(target.commitPath)+ && parseDecimal(target.parentDevice) !== null && parseDecimal(target.parentInode) !== null;+ if (!valid) return relation('unknown', 'publication-recovery-record-invalid');+ return {+ status: 'parsed',+ record: {+ backup: {+ ...backup,+ device: parseDecimal(backup.device),+ inode: parseDecimal(backup.inode),+ },+ recovery: {+ ...recovery,+ device: parseDecimal(recovery.device),+ inode: parseDecimal(recovery.inode),+ },+ target: {+ ...target,+ parentDevice: parseDecimal(target.parentDevice),+ parentInode: parseDecimal(target.parentInode),+ requestedEntry: requestedEntry.kind === 'absent' ? requestedEntry : {+ ...requestedEntry,+ device: parseDecimal(requestedEntry.device),+ inode: parseDecimal(requestedEntry.inode),+ ...(requestedEntry.entryType === 'symbolic-link' ? {+ changedAtNs: parseDecimal(requestedEntry.changedAtNs),+ createdAtNs: parseDecimal(requestedEntry.createdAtNs),+ } : {}),+ },+ },+ },+ };+}++function verifyPublicationRecoveryDirectory(directory, metadata, record) {+ let parentMetadata;+ try {+ parentMetadata = fs.statSync(path.dirname(directory), { bigint: true });+ } catch (error) {+ return filesystemFailure('publication-recovery-parent-inspection-failed', error, {+ recoveryDirectory: directory,+ });+ }+ if (path.basename(directory) !== record.recovery.name+ || !parentMetadata.isDirectory()+ || parentMetadata.dev !== record.target.parentDevice+ || parentMetadata.ino !== record.target.parentInode) {+ return relation('different', 'publication-recovery-directory-not-target-child', {+ recoveryDirectory: directory,+ expectedParentPath: record.target.parentPath,+ });+ }+ if (metadata.dev !== record.recovery.device || metadata.ino !== record.recovery.inode) {+ return relation('different', 'publication-recovery-directory-identity-changed', {+ recoveryDirectory: directory,+ });+ }+ return relation('match', 'publication-recovery-directory-match', {+ recoveryDirectory: directory,+ });+}++function verifyRetiredPublicationSlot(record) {+ const { target } = record;+ const slot = captureWriteSlot(target.requestedPath);+ if (slot.status !== 'captured') return slot;+ if (slot.slot.commitPath !== target.commitPath+ || slot.slot.parentPath !== target.parentPath+ || slot.slot.name !== target.name+ || slot.slot.parentDevice !== target.parentDevice+ || slot.slot.parentInode !== target.parentInode) {+ return relation('different', 'publication-recovery-slot-changed', {+ requestedPath: target.requestedPath,+ commitPath: target.commitPath,+ });+ }+ try {+ fs.lstatSync(target.commitPath, { bigint: true });+ return relation('preserved', 'publication-recovery-target-present', {+ commitPath: target.commitPath,+ });+ } catch (error) {+ if (error?.code !== 'ENOENT') {+ return filesystemFailure('publication-recovery-target-inspection-failed', error, {+ commitPath: target.commitPath,+ });+ }+ }+ let requested;+ try {+ requested = fs.lstatSync(target.requestedPath, { bigint: true });+ } catch (error) {+ if (error?.code !== 'ENOENT') {+ return filesystemFailure('publication-recovery-requested-entry-inspection-failed', error, {+ requestedPath: target.requestedPath,+ });+ }+ }+ if (target.requestedEntry.kind === 'existing'+ && target.requestedEntry.entryType === 'symbolic-link') {+ if (!requested?.isSymbolicLink()+ || requested.dev !== target.requestedEntry.device+ || requested.ino !== target.requestedEntry.inode+ || requested.ctimeNs !== target.requestedEntry.changedAtNs+ || requested.birthtimeNs !== target.requestedEntry.createdAtNs) {+ return relation('different', 'publication-recovery-requested-alias-changed', {+ requestedPath: target.requestedPath,+ });+ }+ } else if (requested) {+ return relation('different', 'publication-recovery-requested-entry-reclaimed', {+ requestedPath: target.requestedPath,+ });+ }+ return relation('match', 'publication-recovery-slot-match', {+ commitPath: target.commitPath,+ });+}++function releaseRecoveryBindings(result, recordBinding, backupBinding) {+ const failures = [];+ if (backupBinding) {+ const released = releaseRegularFileBinding(backupBinding);+ if (released.status !== 'released') failures.push(released.reason);+ }+ if (recordBinding) {+ const released = releaseRegularFileBinding(recordBinding);+ if (released.status !== 'released') failures.push(released.reason);+ }+ if (failures.length === 0) return result;+ return {+ ...result,+ status: 'recovery-required',+ releaseState: failures,+ };+}++/**+ * Explicitly restore one retired output after a process crash. This is not a+ * directory scanner: callers must name the private recovery directory they+ * intend to recover. A record is only a claim; the restored byte stream must+ * still match its recorded inode, mode, SHA-256 and size, the original parent+ * slot and aliases must still resolve identically, and the public name must be+ * absent. `linkSync` is deliberately no-clobber, so a later claimant wins.+ */+export function recoverRetiredPublication(recoveryDirectory) {+ const directory = path.resolve(recoveryDirectory);+ let directoryMetadata;+ try {+ directoryMetadata = fs.lstatSync(directory, { bigint: true });+ } catch (error) {+ if (error?.code === 'ENOENT') {+ return relation('absent', 'publication-recovery-already-complete', { recoveryDirectory: directory });+ }+ return filesystemFailure('publication-recovery-directory-inspection-failed', error, {+ recoveryDirectory: directory,+ });+ }+ if (!directoryMetadata.isDirectory()) {+ return relation('unsupported', 'publication-recovery-directory-not-directory', {+ recoveryDirectory: directory,+ entryType: entryType(directoryMetadata),+ });+ }+ if (process.platform !== 'win32' && Number(directoryMetadata.mode & 0o077n) !== 0) {+ return relation('unsupported', 'publication-recovery-directory-not-private', {+ recoveryDirectory: directory,+ });+ }+ const recordPath = path.join(directory, publicationRecoveryRecordName);+ let recordMetadata;+ try {+ recordMetadata = fs.lstatSync(recordPath, { bigint: true });+ } catch (error) {+ return filesystemFailure('publication-recovery-record-inspection-failed', error, {+ recoveryDirectory: directory,+ recoveryFile: recordPath,+ });+ }+ if (!recordMetadata.isFile() || recordMetadata.nlink !== 1n+ || recordMetadata.size > BigInt(publicationRecoveryRecordMaxBytes)) {+ return relation('unsupported', 'publication-recovery-record-not-private-regular-file', {+ recoveryDirectory: directory,+ recoveryFile: recordPath,+ });+ }+ const capturedRecord = captureRegularFileBinding(recordPath, {+ subject: 'publication-recovery-record',+ expectedLinks: 1,+ includeContent: true,+ });+ if (capturedRecord.status !== 'captured') return capturedRecord;+ const parsed = parsePublicationRecoveryRecord(capturedRecord.content.buffer);+ if (parsed.status !== 'parsed') {+ return releaseRecoveryBindings(parsed, capturedRecord.binding);+ }+ const recoveryDirectoryState = verifyPublicationRecoveryDirectory(+ directory,+ directoryMetadata,+ parsed.record,+ );+ if (recoveryDirectoryState.status !== 'match') {+ return releaseRecoveryBindings({+ ...recoveryDirectoryState,+ recoveryDirectory: directory,+ recoveryFile: recordPath,+ }, capturedRecord.binding);+ }+ const slot = verifyRetiredPublicationSlot(parsed.record);+ if (slot.status !== 'match') {+ return releaseRecoveryBindings({+ ...slot,+ recoveryDirectory: directory,+ recoveryFile: recordPath,+ }, capturedRecord.binding);+ }+ const backupPath = path.join(directory, parsed.record.backup.name);+ const capturedBackup = captureRegularFileBinding(backupPath, {+ subject: 'publication-recovery-backup',+ expectedSha256: parsed.record.backup.sha256,+ expectedBytes: parsed.record.backup.bytes,+ expectedMode: parsed.record.backup.mode,+ expectedIdentity: {+ device: parsed.record.backup.device,+ inode: parsed.record.backup.inode,+ },+ expectedLinks: 1,+ });+ if (capturedBackup.status !== 'captured') {+ return releaseRecoveryBindings({+ ...capturedBackup,+ recoveryDirectory: directory,+ recoveryFile: backupPath,+ }, capturedRecord.binding);+ }+ // This second check narrows the remaining path-based link window. It cannot+ // make `linkSync` descriptor-bound, but it avoids linking after an ordinary+ // observed parent, alias, target, or backup change.+ const beforeLinkSlot = verifyRetiredPublicationSlot(parsed.record);+ const beforeLinkBackup = verifyRegularFileBinding(capturedBackup.binding, {+ filePath: backupPath,+ expectedLinks: 1,+ });+ if (beforeLinkSlot.status !== 'match' || beforeLinkBackup.status !== 'match') {+ return releaseRecoveryBindings({+ status: beforeLinkSlot.status === 'match' ? beforeLinkBackup.status : beforeLinkSlot.status,+ reason: {+ code: 'publication-recovery-pre-link-verification-failed',+ slotState: beforeLinkSlot.reason,+ backupState: beforeLinkBackup.reason,+ },+ recoveryDirectory: directory,+ recoveryFile: backupPath,+ }, capturedRecord.binding, capturedBackup.binding);+ }+ try {+ fs.linkSync(backupPath, parsed.record.target.commitPath);+ } catch (error) {+ return releaseRecoveryBindings(relation(+ error?.code === 'EEXIST' ? 'preserved' : 'unknown',+ error?.code === 'EEXIST'+ ? 'publication-recovery-target-created'+ : 'publication-recovery-link-failed',+ {+ recoveryDirectory: directory,+ recoveryFile: backupPath,+ commitPath: parsed.record.target.commitPath,+ ...(typeof error?.code === 'string' ? { systemCode: error.code } : {}),+ },+ ), capturedRecord.binding, capturedBackup.binding);+ }+ const publicState = verifyRegularFileBinding(capturedBackup.binding, {+ filePath: parsed.record.target.commitPath,+ expectedLinks: 2,+ });+ const backupState = verifyRegularFileBinding(capturedBackup.binding, {+ filePath: backupPath,+ expectedLinks: 2,+ });+ if (publicState.status !== 'match' || backupState.status !== 'match') {+ // We may have introduced an alias to a pathname that was swapped after the+ // pre-link checks. Remove only that alias when it is still a verified+ // two-link pair; otherwise preserve every uncertain name for inspection.+ const linkedAliasCleanup = quarantineRemoveLinkedRegularFileAlias(+ backupPath,+ parsed.record.target.commitPath,+ { subject: 'publication-recovery-unverified-link' },+ );+ return releaseRecoveryBindings(relation('recovery-required', 'publication-recovery-link-verification-failed', {+ recoveryDirectory: directory,+ recoveryFile: backupPath,+ commitPath: parsed.record.target.commitPath,+ publicState: publicState.reason,+ backupState: backupState.reason,+ linkedAliasCleanup: linkedAliasCleanup.reason,+ }), capturedRecord.binding, capturedBackup.binding);+ }+ const backupRemoval = quarantineRemoveRegularFileBinding(capturedBackup.binding, backupPath, {+ subject: 'publication-recovery-backup',+ expectedLinks: 2,+ });+ if (backupRemoval.status !== 'removed') {+ return releaseRecoveryBindings({+ ...backupRemoval,+ status: 'recovered-with-warning',+ recoveryDirectory: directory,+ recoveryFile: backupPath,+ target: parsed.record.target.commitPath,+ }, capturedRecord.binding, capturedBackup.binding);+ }+ const recordCleanup = discardPublicationRecoveryRecord({+ recordPath,+ binding: capturedRecord.binding,+ });+ const directoryCleanup = removeEmptyQuarantine(directory);+ const result = {+ status: recordCleanup || directoryCleanup ? 'recovered-with-warning' : 'recovered',+ reason: {+ code: 'publication-recovery-restored',+ recoveryDirectory: directory,+ commitPath: parsed.record.target.commitPath,+ },+ ...(recordCleanup ? { recoveryRecordState: recordCleanup.reason } : {}),+ ...(directoryCleanup ? { directoryCleanupState: directoryCleanup.reason } : {}),+ };+ return releaseRecoveryBindings(result, undefined, capturedBackup.binding);+}diff --git a/archify/test/atomic-output-recovery.test.mjs b/archify/test/atomic-output-recovery.test.mjsnew file mode 100644index 00000000..39bb07d8--- /dev/null+++ b/archify/test/atomic-output-recovery.test.mjs@@ -0,0 +1,409 @@+import fs from 'node:fs';+import os from 'node:os';+import path from 'node:path';+import { createHash } from 'node:crypto';+import { spawnSync } from 'node:child_process';+import { fileURLToPath } from 'node:url';+import test from 'node:test';+import assert from 'node:assert/strict';++import {+ captureAtomicOutput,+ captureRegularFileBinding,+ publishRegularFileBinding,+ recoverRetiredPublication,+ releaseRegularFileBinding,+} from '../renderers/shared/atomic-output.mjs';++const here = path.dirname(fileURLToPath(import.meta.url));+const skillRoot = path.resolve(here, '..');+const atomicOutput = path.join(skillRoot, 'renderers/shared/atomic-output.mjs');+const recoveryCli = path.join(skillRoot, 'bin/recover-output.mjs');++function workspace(t, prefix) {+ const root = fs.mkdtempSync(path.join(os.tmpdir(), prefix));+ t.after(() => fs.rmSync(root, { recursive: true, force: true }));+ return root;+}++function recoveryDirectory(parent) {+ const matches = fs.readdirSync(parent, { withFileTypes: true })+ .filter((entry) => entry.isDirectory() && entry.name.startsWith('.archify-remove-'));+ assert.equal(matches.length, 1, `expected one recovery directory in ${parent}`);+ return path.join(parent, matches[0].name);+}++function crashPublisher({ output, candidate, phase }) {+ const script = `+ import fs from 'node:fs';+ import {+ captureAtomicOutput,+ captureRegularFileBinding,+ publishRegularFileBinding,+ } from ${JSON.stringify(atomicOutput)};++ const output = process.env.ARCHIFY_RECOVERY_OUTPUT;+ const candidatePath = process.env.ARCHIFY_RECOVERY_CANDIDATE;+ const snapshot = captureAtomicOutput(output);+ if (snapshot.status !== 'captured') throw new Error(JSON.stringify(snapshot));+ const candidate = captureRegularFileBinding(candidatePath, { subject: 'crash-candidate' });+ if (candidate.status !== 'captured') throw new Error(JSON.stringify(candidate));+ const linkSync = fs.linkSync.bind(fs);+ fs.linkSync = (source, target) => {+ if (source === candidatePath && target === snapshot.commitPath) {+ if (process.env.ARCHIFY_RECOVERY_PHASE === 'after-link') {+ linkSync(source, target);+ }+ process.kill(process.pid, 'SIGKILL');+ }+ return linkSync(source, target);+ };+ publishRegularFileBinding(candidate.binding, candidatePath, snapshot.snapshot, { subject: 'crash-candidate' });+ `;+ return spawnSync(process.execPath, ['--input-type=module', '--eval', script], {+ encoding: 'utf8',+ env: {+ ...process.env,+ ARCHIFY_RECOVERY_OUTPUT: output,+ ARCHIFY_RECOVERY_CANDIDATE: candidate,+ ARCHIFY_RECOVERY_PHASE: phase,+ },+ });+}++function crashRecoveryAfterLink(directory) {+ const script = `+ import fs from 'node:fs';+ import { recoverRetiredPublication } from ${JSON.stringify(atomicOutput)};++ const linkSync = fs.linkSync.bind(fs);+ fs.linkSync = (source, target) => {+ const result = linkSync(source, target);+ if (path.basename(source) === 'previous' && path.basename(target) === 'diagram.html') {+ process.kill(process.pid, 'SIGKILL');+ }+ return result;+ };+ recoverRetiredPublication(process.env.ARCHIFY_RECOVERY_DIRECTORY);+ `;+ return spawnSync(process.execPath, ['--input-type=module', '--eval', `import path from 'node:path';${script}`], {+ encoding: 'utf8',+ env: { ...process.env, ARCHIFY_RECOVERY_DIRECTORY: directory },+ });+}++function runRecovery(directory) {+ const result = spawnSync(process.execPath, [recoveryCli, directory, '--json'], {+ encoding: 'utf8',+ });+ return {+ ...result,+ body: result.stdout ? JSON.parse(result.stdout) : undefined,+ };+}++function portableRecoveryFixture(t) {+ const root = workspace(t, 'archify-portable-publication-recovery-');+ const output = path.join(root, 'diagram.html');+ const recovery = path.join(root, `.archify-remove-${'a'.repeat(32)}`);+ const backup = path.join(recovery, 'previous');+ const recordPath = path.join(recovery, 'publication-recovery-v1.json');+ const previous = 'portable previous artifact\n';+ const targetSnapshot = captureAtomicOutput(output);+ assert.equal(targetSnapshot.status, 'captured');+ fs.mkdirSync(recovery, { mode: 0o700 });+ fs.writeFileSync(backup, previous);+ const backupMetadata = fs.lstatSync(backup, { bigint: true });+ const recoveryMetadata = fs.lstatSync(recovery, { bigint: true });+ const record = {+ version: 1,+ kind: 'archify-retired-output-recovery',+ backup: {+ name: 'previous',+ sha256: createHash('sha256').update(previous).digest('hex'),+ bytes: Buffer.byteLength(previous),+ mode: Number(backupMetadata.mode & 0o777n),+ device: backupMetadata.dev.toString(),+ inode: backupMetadata.ino.toString(),+ },+ recovery: {+ name: path.basename(recovery),+ device: recoveryMetadata.dev.toString(),+ inode: recoveryMetadata.ino.toString(),+ },+ target: {+ requestedPath: targetSnapshot.snapshot.requestedPath,+ requestedEntryPolicy: targetSnapshot.snapshot.requestedEntryPolicy,+ requestedEntry: targetSnapshot.snapshot.requestedEntry,+ commitPath: targetSnapshot.snapshot.slot.commitPath,+ parentPath: targetSnapshot.snapshot.slot.parentPath,+ parentDevice: targetSnapshot.snapshot.slot.parentDevice.toString(),+ parentInode: targetSnapshot.snapshot.slot.parentInode.toString(),+ name: targetSnapshot.snapshot.slot.name,+ },+ };+ fs.writeFileSync(recordPath, `${JSON.stringify(record)}\n`, { mode: 0o600 });+ return { output, recovery, backup, previous };+}++function interruptedReplacement(t, { phase = 'before-link', throughAlias = false } = {}) {+ if (process.platform === 'win32') {+ t.skip('SIGKILL recovery regression is POSIX-only');+ return null;+ }+ const root = workspace(t, 'archify-publication-recovery-');+ const actualParent = throughAlias ? path.join(root, 'actual') : root;+ if (throughAlias) fs.mkdirSync(actualParent);+ const requestedParent = throughAlias ? path.join(root, 'alias') : actualParent;+ if (throughAlias) fs.symlinkSync(actualParent, requestedParent, 'dir');+ const output = path.join(requestedParent, 'diagram.html');+ const candidate = path.join(actualParent, '.archify-render-candidate');+ const previous = '<!doctype html><title>previous trusted artifact</title>\n';+ const next = '<!doctype html><title>new candidate artifact</title>\n';+ fs.writeFileSync(output, previous);+ fs.writeFileSync(candidate, next);+ const crashed = crashPublisher({ output, candidate, phase });+ assert.equal(crashed.signal, 'SIGKILL', crashed.stderr);+ return {+ root,+ actualParent,+ requestedParent,+ output,+ candidate,+ previous,+ next,+ recovery: recoveryDirectory(actualParent),+ };+}++test('an actual killed publisher after old-name retirement restores only its bound previous output', (t) => {+ const interrupted = interruptedReplacement(t);+ if (!interrupted) return;+ const { output, candidate, previous, next, recovery } = interrupted;+ assert.equal(fs.existsSync(output), false);+ assert.equal(fs.readFileSync(path.join(recovery, 'previous'), 'utf8'), previous);+ assert.equal(fs.lstatSync(path.join(recovery, 'publication-recovery-v1.json')).nlink, 1);+ assert.equal(fs.statSync(recovery).mode & 0o077, 0);++ const recovered = runRecovery(recovery);+ assert.equal(recovered.status, 0, recovered.stderr);+ assert.equal(recovered.body.status, 'recovered');+ assert.equal(fs.readFileSync(output, 'utf8'), previous);+ assert.equal(fs.readFileSync(candidate, 'utf8'), next);+ assert.equal(fs.existsSync(recovery), false);++ const repeated = runRecovery(recovery);+ assert.equal(repeated.status, 0, repeated.stderr);+ assert.equal(repeated.body.status, 'absent');+});++test('the explicit recovery consumer accepts a bound portable fixture and preserves a claimant', (t) => {+ const recoverable = portableRecoveryFixture(t);+ const restored = runRecovery(recoverable.recovery);+ assert.equal(restored.status, 0, restored.stderr);+ assert.equal(restored.body.status, 'recovered');+ assert.equal(fs.readFileSync(recoverable.output, 'utf8'), recoverable.previous);++ const claimed = portableRecoveryFixture(t);+ fs.writeFileSync(claimed.output, 'new public claimant\n', { flag: 'wx' });+ const preserved = runRecovery(claimed.recovery);+ assert.equal(preserved.status, 2, preserved.stderr);+ assert.equal(preserved.body.status, 'preserved');+ assert.equal(preserved.body.reason.code, 'publication-recovery-target-present');+ assert.equal(fs.readFileSync(claimed.output, 'utf8'), 'new public claimant\n');+ assert.equal(fs.readFileSync(claimed.backup, 'utf8'), claimed.previous);+});++test('a process killed after the recovery link preserves both public bytes and recovery evidence', (t) => {+ if (process.platform === 'win32') {+ t.skip('SIGKILL recovery-interruption regression is POSIX-only');+ return;+ }+ const fixture = portableRecoveryFixture(t);+ const crashed = crashRecoveryAfterLink(fixture.recovery);+ assert.equal(crashed.signal, 'SIGKILL', crashed.stderr);+ assert.equal(fs.readFileSync(fixture.output, 'utf8'), fixture.previous);+ assert.equal(fs.readFileSync(fixture.backup, 'utf8'), fixture.previous);+ assert.equal(fs.existsSync(path.join(fixture.recovery, 'publication-recovery-v1.json')), true);++ const repeated = runRecovery(fixture.recovery);+ assert.equal(repeated.status, 2, repeated.stderr);+ assert.equal(repeated.body.status, 'preserved');+ assert.equal(repeated.body.reason.code, 'publication-recovery-target-present');+});++test('explicit recovery preserves a new public claimant and remains repeatable', (t) => {+ const interrupted = interruptedReplacement(t);+ if (!interrupted) return;+ const { output, previous, recovery } = interrupted;+ fs.writeFileSync(output, 'new claimant\n', { flag: 'wx' });++ for (let attempt = 0; attempt < 2; attempt += 1) {+ const result = runRecovery(recovery);+ assert.equal(result.status, 2, result.stderr);+ assert.equal(result.body.status, 'preserved');+ assert.match(result.body.reason.code, /target-present|target-created/);+ assert.equal(fs.readFileSync(output, 'utf8'), 'new claimant\n');+ assert.equal(fs.readFileSync(path.join(recovery, 'previous'), 'utf8'), previous);+ }+});++test('recovery refuses a tampered record or backup without recreating the public name', (t) => {+ const recordInterrupted = interruptedReplacement(t);+ if (!recordInterrupted) return;+ const recordPath = path.join(recordInterrupted.recovery, 'publication-recovery-v1.json');+ fs.writeFileSync(recordPath, '{"untrusted":true}\n');+ const recordResult = runRecovery(recordInterrupted.recovery);+ assert.equal(recordResult.status, 1, recordResult.stderr);+ assert.equal(fs.existsSync(recordInterrupted.output), false);+ assert.equal(fs.existsSync(path.join(recordInterrupted.recovery, 'previous')), true);++ const backupInterrupted = interruptedReplacement(t);+ const backupPath = path.join(backupInterrupted.recovery, 'previous');+ fs.writeFileSync(backupPath, 'tampered backup\n');+ const backupResult = runRecovery(backupInterrupted.recovery);+ assert.equal(backupResult.status, 1, backupResult.stderr);+ assert.equal(fs.existsSync(backupInterrupted.output), false);+ assert.equal(fs.readFileSync(backupPath, 'utf8'), 'tampered backup\n');+});++test('recovery refuses a replaced directory alias even while the former target is absent', (t) => {+ const interrupted = interruptedReplacement(t, { throughAlias: true });+ if (!interrupted) return;+ const replacement = path.join(interrupted.root, 'replacement');+ fs.mkdirSync(replacement);+ fs.unlinkSync(interrupted.requestedParent);+ fs.symlinkSync(replacement, interrupted.requestedParent, 'dir');++ const result = runRecovery(interrupted.recovery);+ assert.equal(result.status, 1, result.stderr);+ assert.equal(result.body.status, 'different');+ assert.match(result.body.reason.code, /slot-changed/);+ assert.equal(fs.existsSync(path.join(replacement, 'diagram.html')), false);+ assert.equal(fs.readFileSync(path.join(interrupted.recovery, 'previous'), 'utf8'), interrupted.previous);+});++test('recovery record is bound to its generated direct-parent directory identity', (t) => {+ const copied = interruptedReplacement(t);+ if (!copied) return;+ const copiedDirectory = path.join(+ copied.actualParent,+ `.archify-remove-${'1'.repeat(32)}`,+ );+ fs.cpSync(copied.recovery, copiedDirectory, { recursive: true });+ fs.chmodSync(copiedDirectory, 0o700);+ const copiedResult = runRecovery(copiedDirectory);+ assert.equal(copiedResult.status, 1, copiedResult.stderr);+ assert.equal(copiedResult.body.status, 'different');+ assert.equal(copiedResult.body.reason.code, 'publication-recovery-directory-not-target-child');+ assert.equal(fs.existsSync(copied.output), false);++ const replaced = interruptedReplacement(t);+ const replacementDirectory = path.join(replaced.root, 'replacement-directory');+ fs.cpSync(replaced.recovery, replacementDirectory, { recursive: true });+ fs.chmodSync(replacementDirectory, 0o700);+ fs.rmSync(replaced.recovery, { recursive: true, force: true });+ fs.renameSync(replacementDirectory, replaced.recovery);+ const replacedResult = runRecovery(replaced.recovery);+ assert.equal(replacedResult.status, 1, replacedResult.stderr);+ assert.equal(replacedResult.body.status, 'different');+ assert.equal(replacedResult.body.reason.code, 'publication-recovery-directory-identity-changed');+ assert.equal(fs.existsSync(replaced.output), false);++ const moved = interruptedReplacement(t);+ const foreignParent = path.join(moved.root, 'foreign');+ fs.mkdirSync(foreignParent);+ const movedDirectory = path.join(foreignParent, path.basename(moved.recovery));+ fs.renameSync(moved.recovery, movedDirectory);+ const movedResult = runRecovery(movedDirectory);+ assert.equal(movedResult.status, 1, movedResult.stderr);+ assert.equal(movedResult.body.status, 'different');+ assert.equal(movedResult.body.reason.code, 'publication-recovery-directory-not-target-child');+ assert.equal(fs.existsSync(moved.output), false);+});++test('a parent swap during recovery linking removes only the positively identified new alias', (t) => {+ if (process.platform === 'win32') {+ t.skip('directory rename with live POSIX descriptors regression');+ return;+ }+ const fixture = portableRecoveryFixture(t);+ const displacedRoot = `${path.dirname(fixture.output)}-displaced`;+ const originalLink = fs.linkSync;+ let swapped = false;+ t.after(() => fs.rmSync(displacedRoot, { recursive: true, force: true }));+ t.mock.method(fs, 'linkSync', (source, target, ...args) => {+ if (!swapped && path.basename(String(source)) === 'previous'+ && path.basename(String(target)) === 'diagram.html') {+ swapped = true;+ const parent = path.dirname(fixture.output);+ fs.renameSync(parent, displacedRoot);+ fs.mkdirSync(parent);+ const fakeRecovery = path.join(parent, path.basename(fixture.recovery));+ fs.mkdirSync(fakeRecovery, { mode: 0o700 });+ fs.writeFileSync(path.join(fakeRecovery, 'previous'), 'untrusted replacement\n');+ }+ return originalLink(source, target, ...args);+ });++ const result = recoverRetiredPublication(fixture.recovery);+ assert.equal(swapped, true);+ assert.equal(result.status, 'recovery-required');+ assert.equal(result.reason.code, 'publication-recovery-link-verification-failed');+ assert.equal(fs.existsSync(fixture.output), false);+ assert.equal(+ fs.readFileSync(path.join(displacedRoot, path.basename(fixture.recovery), 'previous'), 'utf8'),+ fixture.previous,+ );+ assert.equal(+ fs.readFileSync(path.join(path.dirname(fixture.output), path.basename(fixture.recovery), 'previous'), 'utf8'),+ 'untrusted replacement\n',+ );+});++test('a killed publisher after candidate publication leaves the new public output intact', (t) => {+ const interrupted = interruptedReplacement(t, { phase: 'after-link' });+ if (!interrupted) return;+ const { output, next, previous, recovery } = interrupted;+ assert.equal(fs.readFileSync(output, 'utf8'), next);++ const result = runRecovery(recovery);+ assert.equal(result.status, 2, result.stderr);+ assert.equal(result.body.status, 'preserved');+ assert.equal(result.body.reason.code, 'publication-recovery-target-present');+ assert.equal(fs.readFileSync(output, 'utf8'), next);+ assert.equal(fs.readFileSync(path.join(recovery, 'previous'), 'utf8'), previous);+});++test('a failed recovery-record create leaves the old output and no empty recovery directory', (t) => {+ const root = workspace(t, 'archify-publication-recovery-record-create-');+ const output = path.join(root, 'diagram.html');+ const candidatePath = path.join(root, '.archify-render-candidate');+ fs.writeFileSync(output, 'previous artifact\n');+ fs.writeFileSync(candidatePath, 'candidate artifact\n');+ const snapshot = captureAtomicOutput(output);+ const candidate = captureRegularFileBinding(candidatePath, { subject: 'record-create-candidate' });+ assert.equal(snapshot.status, 'captured');+ assert.equal(candidate.status, 'captured');+ const openSync = fs.openSync;+ t.mock.method(fs, 'openSync', (file, ...args) => {+ if (path.basename(String(file)) === 'publication-recovery-v1.json') {+ throw Object.assign(new Error('injected recovery record create failure'), { code: 'EIO' });+ }+ return openSync(file, ...args);+ });+ try {+ const result = publishRegularFileBinding(candidate.binding, candidatePath, snapshot.snapshot, {+ subject: 'record-create-candidate',+ });+ assert.equal(result.status, 'unknown');+ assert.equal(result.reason.code, 'publication-recovery-record-write-failed');+ assert.equal(fs.readFileSync(output, 'utf8'), 'previous artifact\n');+ assert.deepEqual(+ fs.readdirSync(root).filter((entry) => entry.startsWith('.archify-remove-')),+ [],+ );+ } finally {+ releaseRegularFileBinding(candidate.binding);+ }+});