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: close Windows path contract review gaps
sunsunsun6ee68078a02b
diff --git a/archify.zip b/archify.zipindex e1c2e97e..2b3ad726 100644Binary files a/archify.zip and b/archify.zip differdiff --git a/archify/bin/archify.mjs b/archify/bin/archify.mjsindex ce484b26..20568a5e 100755--- a/archify/bin/archify.mjs+++ b/archify/bin/archify.mjs@@ -6,7 +6,6 @@ import fs from 'node:fs';import os from 'node:os';import path from 'node:path';import { fileURLToPath, pathToFileURL } from 'node:url';-const __dirname = path.dirname(fileURLToPath(import.meta.url));const skillRoot = path.resolve(__dirname, '..');@@ -18,37 +17,19 @@ const DELIVERY_SIDECAR_SUFFIXES = Object.freeze([]);const COMPARE_SIDECAR_SUFFIXES = Object.freeze(['.receipt.json']);const DELIVERY_DIRECTORY_LOCK = '.archify-delivery-lock.json';-const SIDECAR_STEM_NAMESPACE = /\.~archify-[0-9a-f]{64}$/iu;let sidecarNamespaceComponentKeyRuntime;--function sidecarStemNeedsBounding(stem, suffixes) {- const fits = (value) => value.length <= 255 && Buffer.byteLength(value, 'utf8') <= 255;- return !suffixes.every((suffix) => fits(`${stem}${suffix}`));-}--function boundedSidecarStem(stem, suffixes, { force = false, hashDomain } = {}) {- if (!force && !sidecarStemNeedsBounding(stem, suffixes)- && !SIDECAR_STEM_NAMESPACE.test(stem)) return stem;- const hashInput = hashDomain ? `${hashDomain}\0${stem}` : stem;- const marker = `.~archify-${createHash('sha256').update(hashInput).digest('hex')}`;- const codePoints = [...stem];- while (codePoints.length && sidecarStemNeedsBounding(`${codePoints.join('')}${marker}`, suffixes)) {- codePoints.pop();- }- return `${codePoints.join('')}${marker}`;-}--function sidecarStemFromComponent(component) {- if (component.endsWith('.html')) {- return {- stem: component.slice(0, -'.html'.length),- options: undefined,- };- }- return {- stem: component,- options: { force: true, hashDomain: 'full-component' },- };+let boundedSidecarStem;+let isBoundedSidecarStem;+let sidecarStemFromComponent;+let sidecarStemNeedsBounding;++async function loadSidecarPathRuntime() {+ ({+ boundedSidecarStem,+ isBoundedSidecarStem,+ sidecarStemFromComponent,+ sidecarStemNeedsBounding,+ } = await import('../renderers/shared/sidecar-path.mjs'));}function deliverySidecarNamespace(artifactPath) {@@ -96,7 +77,7 @@ function rawHeadDeliverySidecarPath(artifactPath, suffix) {const { directory, stem, options } = deliverySidecarNamespace(artifactPath);if (options?.force) return undefined;if (sidecarStemNeedsBounding(stem, DELIVERY_SIDECAR_SUFFIXES)- || !SIDECAR_STEM_NAMESPACE.test(stem)) return undefined;+ || !isBoundedSidecarStem(stem)) return undefined;return path.join(directory, `${stem}${suffix}`);}@@ -108,6 +89,22 @@ function rawHeadDeliveryPendingPath(artifactPath) {return rawHeadDeliverySidecarPath(artifactPath, '.delivery-pending.json');}+function legacyExtensionDeliverySidecarPath(artifactPath, suffix) {+ let artifact = path.resolve(artifactPath);+ try {+ artifact = fs.realpathSync.native(artifact);+ } catch (error) {+ if (error?.code !== 'ENOENT' && error?.code !== 'ENOTDIR') throw error;+ }+ const component = path.basename(artifact);+ if (!/\.html$/iu.test(component) || component.endsWith('.html')) return undefined;+ const legacyComponent = `${component.slice(0, -'.html'.length)}${suffix}`;+ if (legacyComponent.length > 255 || Buffer.byteLength(legacyComponent, 'utf8') > 255) {+ return undefined;+ }+ return path.join(path.dirname(artifact), legacyComponent);+}+function canonicalExistingDeliveryOutput(outputPath) {const output = path.resolve(outputPath);try {@@ -586,7 +583,18 @@ function acquireDeliveryLock(rejectExistingDeliveryLock(existingLegacyLocks[0], output, fileBindingRuntime);}const openedLocks = [];- let ownership;+ const ownership = Object.freeze({});+ deliveryOwnershipStates.set(ownership, {+ output: stableOutput,+ lockPath,+ pendingPath,+ provenancePath,+ receiptId,+ pid: process.pid,+ ownedLocks: openedLocks,+ fileBindingRuntime,+ phase: 'acquiring',+ });let collisionPath;try {const openOwnedLock = (ownedLockPath, { allowOwnedAlias = false } = {}) => {@@ -608,28 +616,39 @@ function acquireDeliveryLock(if (error.code === 'EEXIST') collisionPath = ownedLockPath;throw error;}+ let handleIdentity;+ let handleIdentityError;+ try {+ handleIdentity = fs.fstatSync(descriptor, { bigint: true });+ } catch (error) {+ // A transient first inspection failure must not strand the public+ // lock. Bind ownership from the still-open handle before cleanup.+ try {+ handleIdentity = fs.fstatSync(descriptor, { bigint: true });+ } catch {}+ if (!handleIdentity) throw error;+ handleIdentityError = error;+ }const ownedLock = {path: ownedLockPath,- identity: fs.fstatSync(descriptor, { bigint: true }),+ identity: handleIdentity,descriptor,};openedLocks.push(ownedLock);+ const pathIdentity = fs.lstatSync(ownedLockPath, { bigint: true });+ if (!handleIdentity.isFile()+ || handleIdentity.ino === 0n+ || !pathIdentity.isFile()+ || pathIdentity.isSymbolicLink()+ || pathIdentity.ino === 0n+ || !sameFileIdentity(pathIdentity, handleIdentity)) {+ throw new Error('Delivery lock path identity could not be verified safely.');+ }+ if (handleIdentityError) throw handleIdentityError;return ownedLock;};openOwnedLock(lockPath);- ownership = Object.freeze({});- deliveryOwnershipStates.set(ownership, {- output: stableOutput,- lockPath,- pendingPath,- provenancePath,- receiptId,- pid: process.pid,- ownedLocks: openedLocks,- fileBindingRuntime,- phase: 'acquiring',- });for (const legacyLockPath of legacyLockPaths) {openOwnedLock(legacyLockPath, { allowOwnedAlias: true });}@@ -663,41 +682,37 @@ function acquireDeliveryLock(error.lockCleanupError = closeError.message;}}- if (ownership) {- const state = deliveryOwnershipStates.get(ownership);- let preserveOwnership = false;- try {- if (state.phase === 'initializing') {- assertDeliveryOwnership(ownership, 'record a lock initialization failure', { allowInitializing: true });- error.deliveryFailureRecord = recordInitializationFailure?.(error, ownership);- if (error.deliveryFailureRecord?.journalRecovery) {- error.deliveryJournalRecovery = error.deliveryFailureRecord.journalRecovery.deliveryJournalRecovery;- preserveOwnership = true;- }- if (error.deliveryFailureRecord?.provenanceRecovery) {- error.deliveryProvenanceRecovery = error.deliveryFailureRecord.provenanceRecovery.deliveryProvenanceRecovery;- preserveOwnership = true;- }+ const state = deliveryOwnershipStates.get(ownership);+ let preserveOwnership = false;+ try {+ if (state.phase === 'initializing') {+ assertDeliveryOwnership(ownership, 'record a lock initialization failure', { allowInitializing: true });+ error.deliveryFailureRecord = recordInitializationFailure?.(error, ownership);+ if (error.deliveryFailureRecord?.journalRecovery) {+ error.deliveryJournalRecovery = error.deliveryFailureRecord.journalRecovery.deliveryJournalRecovery;+ preserveOwnership = true;}- if (!preserveOwnership) {- releaseDeliveryOwnership(ownership, { allowInitializing: true });+ if (error.deliveryFailureRecord?.provenanceRecovery) {+ error.deliveryProvenanceRecovery = error.deliveryFailureRecord.provenanceRecovery.deliveryProvenanceRecovery;+ preserveOwnership = true;}- } catch (cleanupError) {- if (cleanupError.deliveryOwnershipCode) {- cleanupError.deliveryOwnershipDetails = {- ...(cleanupError.deliveryOwnershipDetails || {}),- initializationError: error.message,- ...(error?.code ? { initializationSystemCode: error.code } : {}),- };- if (cleanupError.deliveryOwnershipCode === 'delivery/lock-release' && error.deliveryFailureRecord) {- cleanupError.deliveryFailureRecord = error.deliveryFailureRecord;- }- throw cleanupError;+ }+ if (!preserveOwnership) {+ releaseDeliveryOwnership(ownership, { allowInitializing: true });+ }+ } catch (cleanupError) {+ if (cleanupError.deliveryOwnershipCode) {+ cleanupError.deliveryOwnershipDetails = {+ ...(cleanupError.deliveryOwnershipDetails || {}),+ initializationError: error.message,+ ...(error?.code ? { initializationSystemCode: error.code } : {}),+ };+ if (cleanupError.deliveryOwnershipCode === 'delivery/lock-release' && error.deliveryFailureRecord) {+ cleanupError.deliveryFailureRecord = error.deliveryFailureRecord;}- error.lockCleanupError = cleanupError.message;+ throw cleanupError;}- if (collisionPath) rejectExistingDeliveryLock(collisionPath, output, fileBindingRuntime);- throw error;+ error.lockCleanupError = cleanupError.message;}if (collisionPath) rejectExistingDeliveryLock(collisionPath, output, fileBindingRuntime);throw error;@@ -1555,6 +1570,14 @@ function inspectDeliveryProvenance(artifactPath, artifact, {const rawHeadSidecar = rawHeadDeliveryProvenancePath(artifactPath);const pending = deliveryPendingPath(artifactPath);const rawHeadPending = rawHeadDeliveryPendingPath(artifactPath);+ const legacyExtensionPending = legacyExtensionDeliverySidecarPath(+ artifactPath,+ '.delivery-pending.json',+ );+ const legacyExtensionSidecar = legacyExtensionDeliverySidecarPath(+ artifactPath,+ '.delivery.json',+ );const stableOutput = canonicalExistingDeliveryOutput(artifactPath);const locks = [deliveryLockPath(stableOutput),@@ -1562,7 +1585,11 @@ function inspectDeliveryProvenance(artifactPath, artifact, {];let foundPending;try {- for (const candidate of [pending, rawHeadPending].filter(Boolean)) {+ for (const candidate of [...new Set([+ pending,+ rawHeadPending,+ legacyExtensionPending,+ ].filter(Boolean))]) {if (pathEntryExists(candidate)) {foundPending = candidate;break;@@ -1615,6 +1642,14 @@ function inspectDeliveryProvenance(artifactPath, artifact, {return invalidProvenance(artifactPath, rawHeadSidecar, error.message);}}+ if (!found && legacyExtensionSidecar) {+ try {+ found = pathEntryExists(legacyExtensionSidecar);+ if (found) sidecar = legacyExtensionSidecar;+ } catch (error) {+ return invalidProvenance(artifactPath, legacyExtensionSidecar, error.message);+ }+ }if (!found) {if (!requireProvenance) return { ok: true, status: 'unknown' };const message = 'Delivery provenance is required, but the artifact has no .delivery.json sidecar.';@@ -1962,6 +1997,7 @@ function extractOutDirArgs(args) {function rendererEnv(quality, repoRoot, diagnosticJson = false) {return {+ ARCHIFY_REQUIRE_META_OUTPUT: '1',...(quality ? { ARCHIFY_QUALITY_PROFILE: quality } : {}),...(repoRoot ? { ARCHIFY_REPO_ROOT: repoRoot } : {}),...(diagnosticJson ? { ARCHIFY_DIAGNOSTIC_FORMAT: 'json' } : {}),@@ -3108,7 +3144,12 @@ function renderValidatedArchitecture(inputPath, outputPath, quality, repoRoot) {}async function commandCompare(args) {- const { canonicalFuturePath, resolveOutputPath } = await import('../renderers/shared/output-path.mjs');+ await loadSidecarPathRuntime();+ const {+ canonicalFuturePath,+ resolveOutputPath,+ validateAuthoredOutputPath,+ } = await import('../renderers/shared/output-path.mjs');const {captureAtomicOutput,verifyAtomicOutput,@@ -3260,6 +3301,27 @@ async function commandCompare(args) {return;}+ for (const [side, document] of [['base', base], ['head', head]]) {+ try {+ validateAuthoredOutputPath(document?.meta?.output);+ } catch (error) {+ const diagnosticEntry = error.archifyDiagnostics?.[0];+ reportCompareFailure({+ json: options.json,+ stage: 'input',+ error: `${side === 'base' ? 'Base' : 'Head'} snapshot failed validation: ${error.message}`,+ code: diagnosticEntry?.code || `delta/${side}-validation`,+ details: {+ side,+ ...(diagnosticEntry?.subject?.path ? { path: diagnosticEntry.subject.path } : {}),+ ...(diagnosticEntry?.evidence || {}),+ supportedFixes: diagnosticEntry?.supportedFixes || [],+ },+ });+ return;+ }+ }+let outputDirectory = path.dirname(outputPath);if (receiptPath) {const explicitReceiptDirectoryIdentity = sameParent(outputPath, receiptPath);@@ -3483,8 +3545,12 @@ async function commandCompare(args) {// Validation must see the exact authored inputs. Only after both sides// pass do we canonicalize their collection order for deterministic SVG// geometry and stable artifact bytes.- fs.writeFileSync(canonicalBaseInput, JSON.stringify(canonicalArchitecture(base)));- fs.writeFileSync(canonicalHeadInput, JSON.stringify(canonicalArchitecture(head)));+ const canonicalBase = canonicalArchitecture(base);+ const canonicalHead = canonicalArchitecture(head);+ canonicalBase.meta.output = base.meta.output;+ canonicalHead.meta.output = head.meta.output;+ fs.writeFileSync(canonicalBaseInput, JSON.stringify(canonicalBase));+ fs.writeFileSync(canonicalHeadInput, JSON.stringify(canonicalHead));baseResult = renderValidatedArchitecture(canonicalBaseInput, baseCandidate, qualityArgs.quality, repoArgs.repoRoot);headResult = renderValidatedArchitecture(canonicalHeadInput, headCandidate, qualityArgs.quality, repoArgs.repoRoot);@@ -3748,6 +3814,7 @@ function engineeringProfileFromArtifact(artifact) {}async function commandDeliver(args) {+ await loadSidecarPathRuntime();const qualityArgs = extractQualityArgs(args);const repoArgs = extractRepoRootArgs(qualityArgs.rest);const json = repoArgs.rest.includes('--json');@@ -3770,6 +3837,7 @@ async function commandDeliver(args) {canonicalFuturePath,pathsAlias,resolveOutputPath,+ validateAuthoredOutputPath,} = await import('../renderers/shared/output-path.mjs');const {captureAtomicOutput,@@ -3833,13 +3901,12 @@ async function commandDeliver(args) {return;}- const authoredOutput = typeof diagram?.meta?.output === 'string'- ? diagram.meta.output- : undefined;+ const authoredOutput = diagram?.meta?.output;let outputPath;let provenancePath;let preparedDeliveryTargets;try {+ validateAuthoredOutputPath(authoredOutput);({ outputPath } = resolveOutputPath({requestedOutput,authoredOutput,@@ -3852,7 +3919,11 @@ async function commandDeliver(args) {// spelling. That keeps its realpath-derived sidecars discoverable.outputPath = canonicalFuturePath(outputPath);} catch (error) {- const attemptedOutput = path.resolve(requestedOutput || authoredOutput || `${type}.html`);+ const attemptedOutput = path.resolve(+ requestedOutput+ || (typeof authoredOutput === 'string' && authoredOutput)+ || `${type}.html`,+ );const failure = {json,stage: 'prepare',@@ -4555,6 +4626,17 @@ async function commandPreview(args) {if (!type || !input || positional.length > 3) fail(usage());rendererPath(type);+ try {+ const source = JSON.parse(fs.readFileSync(path.resolve(input), 'utf8'));+ const { validateAuthoredOutputPath } = await import('../renderers/shared/output-path.mjs');+ validateAuthoredOutputPath(source?.meta?.output);+ } catch (error) {+ // Preserve live repair for unreadable or malformed JSON. A parsed document,+ // however, must already carry the durable output contract before preview+ // allocates a server, watcher, or staging directory.+ if (error?.archifyDiagnostics) fail(`Could not start live preview: ${error.message}`, 1);+ }+let runPreview;try {({ runPreview } = await import('./preview.mjs'));@@ -4577,6 +4659,7 @@ async function commandPreview(args) {async function loadPathIdentityRuntime() {try {+ await loadSidecarPathRuntime();const {sameEntry,sidecarNamespaceComponentKey,@@ -5023,6 +5106,13 @@ async function commandDoctor(args) {missing: fs.existsSync(pathSemanticsRuntime) ? 0 : 1,});+ const sidecarPathRuntime = path.join(skillRoot, 'renderers/shared/sidecar-path.mjs');+ checks.push({+ label: 'Sidecar path naming runtime',+ ok: fs.existsSync(sidecarPathRuntime),+ missing: fs.existsSync(sidecarPathRuntime) ? 0 : 1,+ });+const portablePathRuntime = path.join(skillRoot, 'renderers/shared/portable-path.mjs');checks.push({label: 'Portable path contract runtime',@@ -5409,7 +5499,7 @@ async function commandMigrate(args) {verifyAtomicOutput,verifyRegularFileBinding,} = await import('../renderers/shared/atomic-output.mjs');- if (typeof sourceDocument?.meta?.output === 'string') {+ if (sourceDocument?.meta?.output !== undefined) {try {validateAuthoredOutputPath(sourceDocument.meta.output);} catch (error) {@@ -5466,6 +5556,18 @@ async function commandMigrate(args) {return;}+ if (sourceDocument?.meta?.output === undefined) {+ try {+ validateAuthoredOutputPath(sourceDocument?.meta?.output);+ } catch (error) {+ reportMigrationFailure({+ ...migration,+ preExistingDiagnostics: migrationPathDiagnostics(error, sourcePath, destinationPath),+ });+ return;+ }+ }+const destinationDirectory = path.dirname(destinationPath);let stagingDirectory;let destinationCapture;diff --git a/archify/bin/preview.mjs b/archify/bin/preview.mjsindex a058edb1..ee7c7980 100644--- a/archify/bin/preview.mjs+++ b/archify/bin/preview.mjs@@ -236,7 +236,18 @@ function stagePreviewCommit(commitPath, artifact, mode) {fs.constants.O_WRONLY | fs.constants.O_CREAT | fs.constants.O_EXCL | noFollow,mode ?? 0o666,);- const metadata = fs.fstatSync(descriptor, { bigint: true });+ let metadata;+ try {+ metadata = fs.fstatSync(descriptor, { bigint: true });+ } catch (error) {+ try {+ const retry = fs.fstatSync(descriptor, { bigint: true });+ if (retry.isFile() && retry.ino !== 0n) {+ identity = { device: retry.dev, inode: retry.ino };+ }+ } catch {}+ throw error;+ }if (!metadata.isFile() || metadata.ino === 0n) {throw new Error('Preview commit candidate identity could not be verified safely.');}@@ -262,13 +273,6 @@ function stagePreviewCommit(commitPath, artifact, mode) {});}-function cleanupIdentity(filePath, subject = 'candidate') {- const captured = captureRegularFileBinding(filePath, { subject });- if (captured.status !== 'captured') return null;- const released = releaseRegularFileBinding(captured.binding);- return released.status === 'released' ? captured.identity : null;-}-function captureOwnedDirectory(directoryPath) {const metadata = fs.lstatSync(directoryPath, { bigint: true });if (!metadata.isDirectory() || metadata.ino === 0n) {@@ -291,7 +295,52 @@ function cleanupOwnedDirectory(directoryPath, identity) {|| current.ino === 0n|| current.dev !== identity.device|| current.ino !== identity.inode) return;- fs.rmSync(directoryPath, { recursive: true, force: false });+ try {+ fs.rmdirSync(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+ // instead of recursively deleting unknown contents.+ if (error?.code !== 'ENOTEMPTY' && error?.code !== 'EEXIST') throw error;+ }+}++function captureOwnedDeliverySidecars(candidatePath, snapshotPath, receipt) {+ const suffixes = ['.delivery.json', '.delivery-pending.json'];+ const capturedSidecars = [];+ for (const suffix of suffixes) {+ const sidecarPath = candidatePath.replace(/\.html$/iu, suffix);+ const captured = captureRegularFileBinding(sidecarPath, {+ subject: 'preview-delivery-sidecar',+ expectedLinks: 1,+ includeContent: true,+ });+ if (captured.status !== 'captured') continue;+ try {+ const sidecar = JSON.parse(captured.content.buffer.toString('utf8'));+ const commonMatches = sidecar?.schemaVersion === 1+ && sidecar.command === 'deliver'+ && sameLocation(sidecar.output, candidatePath).status === 'match'+ && (!receipt?.receiptId || sidecar.receiptId === receipt.receiptId);+ const currentMatches = suffix === '.delivery.json'+ && commonMatches+ && sidecar.status === 'current'+ && receipt?.artifact?.sha256+ && sidecar.artifact?.sha256 === receipt.artifact.sha256;+ const pendingMatches = suffix === '.delivery-pending.json'+ && commonMatches+ && sidecar.status === 'pending'+ && sameLocation(sidecar.input, snapshotPath).status === 'match';+ if (currentMatches || pendingMatches) {+ capturedSidecars.push({ path: sidecarPath, identity: captured.identity });+ }+ } catch {+ // Preserve malformed or claimant-controlled sidecars for recovery.+ } finally {+ releaseRegularFileBinding(captured.binding);+ }+ }+ return capturedSidecars;}export async function startPreview(options) {@@ -735,6 +784,11 @@ export async function startPreview(options) {const stale = generationEpoch !== sourceEpoch;let supersededBy = null;let candidateIdentity;+ const deliverySidecars = captureOwnedDeliverySidecars(+ candidatePath,+ snapshotPath,+ receipt,+ );child = null;clearTimeout(stopGraceTimer);clearTimeout(stopKillTimer);@@ -747,12 +801,26 @@ export async function startPreview(options) {generationHash,outputCapture,));+ } else if (code === 0 && receipt?.ok) {+ const abandonedCandidate = captureRegularFileBinding(candidatePath, {+ subject: 'abandoned-preview-candidate',+ expectedSha256: receipt.artifact?.sha256,+ expectedBytes: receipt.artifact?.bytes,+ });+ if (abandonedCandidate.status === 'captured') {+ candidateIdentity = abandonedCandidate.identity;+ releaseRegularFileBinding(abandonedCandidate.binding);+ }} else if (!stopping && !stale) {publishFailure(receipt, stdout, stderr, candidatePath, snapshotPath);}- candidateIdentity ||= cleanupIdentity(candidatePath);if (candidateIdentity) removeOwnedRegularFile(candidatePath, candidateIdentity);if (snapshotIdentity) removeOwnedRegularFile(snapshotPath, snapshotIdentity, { subject: 'snapshot' });+ for (const deliverySidecar of deliverySidecars) {+ removeOwnedRegularFile(deliverySidecar.path, deliverySidecar.identity, {+ subject: 'preview-delivery-sidecar',+ });+ }if (stopping) {finishStop();diff --git a/archify/bin/visual-check.mjs b/archify/bin/visual-check.mjsindex e949209a..5797c9ae 100644--- a/archify/bin/visual-check.mjs+++ b/archify/bin/visual-check.mjs@@ -23,6 +23,10 @@ import {sameParent,sidecarNamespaceComponentKey,} from '../renderers/shared/path-semantics.mjs';+import {+ boundedSidecarStem,+ sidecarStemFromComponent,+} from '../renderers/shared/sidecar-path.mjs';export const VISUAL_CHECK_VIEWPORTS = Object.freeze([DESKTOP_READABILITY_VIEWPORT,@@ -45,7 +49,6 @@ const VISUAL_SIDECAR_SUFFIXES = Object.freeze([(theme) => `.visual-check.${width}x${height}.${theme}.png`,)),]);-const SIDECAR_STEM_NAMESPACE = /\.~archify-[0-9a-f]{64}$/iu;const visualEvidenceOwnerships = new WeakSet();function sha256(buffer) {@@ -145,21 +148,6 @@ function screenshotKey(width, height, theme) {return `${width}x${height}:${theme}`;}-function boundedSidecarStem(stem, { force = false, hashDomain } = {}) {- const fits = (value) => value.length <= 255 && Buffer.byteLength(value, 'utf8') <= 255;- const needsBounding = (value) => !VISUAL_SIDECAR_SUFFIXES.every(- (suffix) => fits(`${value}${suffix}`),- );- if (!force && !needsBounding(stem) && !SIDECAR_STEM_NAMESPACE.test(stem)) return stem;- const hashInput = hashDomain ? `${hashDomain}\0${stem}` : stem;- const marker = `.~archify-${sha256(Buffer.from(hashInput, 'utf8'))}`;- const codePoints = [...stem];- while (codePoints.length && needsBounding(`${codePoints.join('')}${marker}`)) {- codePoints.pop();- }- return `${codePoints.join('')}${marker}`;-}-function resolvedSidecarNamespace(artifact, component) {const namespace = sidecarNamespaceComponentKey(path.dirname(artifact), component);if (namespace.status === 'resolved') return namespace;@@ -171,19 +159,6 @@ function resolvedSidecarNamespace(artifact, component) {throw error;}-function sidecarStemFromComponent(component) {- if (component.endsWith('.html')) {- return {- stem: component.slice(0, -'.html'.length),- options: undefined,- };- }- return {- stem: component,- options: { force: true, hashDomain: 'full-component' },- };-}-export function sidecarPaths(artifactPath, { outDir } = {}) {let artifact = path.resolve(artifactPath);try {@@ -197,7 +172,11 @@ export function sidecarPaths(artifactPath, { outDir } = {}) {const namespace = resolvedSidecarNamespace(artifact, path.basename(artifact));artifact = path.join(namespace.directoryPath, path.basename(artifact));const namespaceStem = sidecarStemFromComponent(namespace.componentKey);- const stem = boundedSidecarStem(namespaceStem.stem, namespaceStem.options);+ const stem = boundedSidecarStem(+ namespaceStem.stem,+ VISUAL_SIDECAR_SUFFIXES,+ namespaceStem.options,+ );const directory = outDir ? path.resolve(outDir) : path.dirname(artifact);const base = path.join(directory, `${stem}.visual-check`);const screenshots = CAPTURE_VIEWPORTS.flatMap(({ width, height }) => THEMES.map((theme) => ({@@ -1484,7 +1463,7 @@ export class ChromeVisualBrowser {return attached.sessionId;}- async inspect({ artifactPath, width, height, theme, screenshotPath }) {+ async inspect({ artifactPath, width, height, theme, screenshotPath, writeScreenshot }) {const sessionId = await this.sessionPromise;await this.cdp.send('Emulation.setDeviceMetricsOverride', {width,@@ -1496,6 +1475,10 @@ export class ChromeVisualBrowser {const url = new URL(pathToFileURL(artifactPath).href);url.searchParams.set('theme', theme);const loaded = this.cdp.waitFor('Page.loadEventFired', sessionId);+ // Navigation can fail before this waiter is awaited. Attach a rejection+ // handler immediately so a later load failure never escapes as an+ // unhandled rejection; awaiting `loaded` below still reports it normally.+ loaded.catch(() => {});const navigation = await this.cdp.send('Page.navigate', { url: url.href }, sessionId);if (navigation.errorText) throw new Error(`Chrome navigation failed: ${navigation.errorText}`);await loaded;@@ -1638,7 +1621,9 @@ export class ChromeVisualBrowser {captureBeyondViewport: false,}, sessionId, 20000);if (!capture.data) throw new Error('Chrome returned an empty screenshot.');- fs.writeFileSync(screenshotPath, Buffer.from(capture.data, 'base64'), { flag: 'wx' });+ const screenshot = Buffer.from(capture.data, 'base64');+ if (writeScreenshot) writeScreenshot(screenshot);+ else fs.writeFileSync(screenshotPath, screenshot, { flag: 'wx' });}return metrics;}@@ -2072,6 +2057,31 @@ export async function runVisualCheck({return { exitCode: EXIT.fail, receipt };}const ownership = preflight.ownership;+ const inspectionArtifact = path.join(ownership.stagingDirectory, 'artifact-snapshot.html');+ ownership.stagingPaths.set(artifact, inspectionArtifact);+ try {+ writeStagedEvidence(ownership, artifact, artifactBytes);+ } catch (error) {+ return { exitCode: EXIT.fail, receipt: persistVisualCheckFailure(artifact, {+ ...receipt,+ status: 'fail',+ ok: false,+ error: `visual-check could not stage its private artifact snapshot: ${error.message}`,+ diagnostics: [failureDiagnostic({+ code: 'viewer/artifact-snapshot',+ message: 'visual-check could not bind a private artifact snapshot.',+ subject: { artifact },+ evidence: { reason: error.message },+ supportedFixes: ['retry after resolving the reported staging filesystem error'],+ })],+ }, { outDir, compareSidecarParents, ownership }) };+ }+ const verifyInspectionArtifact = () => {+ const entry = ownership.stagedEntries.get(artifact);+ if (!entry || !currentEvidenceMatches(entry.path, entry.identity, entry.evidence)) {+ throw new Error('The private visual-check artifact snapshot changed during inspection.');+ }+ };try {verifyArtifact?.(artifactBytes);} catch (error) {@@ -2127,24 +2137,46 @@ export async function runVisualCheck({const key = screenshotKey(viewport.width, viewport.height, 'light');const screenshot = screenshotsByKey.get(key);const metrics = await browser.inspect({- artifactPath: artifact,+ artifactPath: inspectionArtifact,...viewport,theme: 'light',- ...(screenshot ? { screenshotPath: screenshot.stagedPath } : {}),+ ...(screenshot ? {+ screenshotPath: screenshot.stagedPath,+ writeScreenshot: (bytes) => writeStagedEvidence(ownership, screenshot.path, bytes),+ } : {}),});- if (screenshot) registerStagedEvidence(ownership, screenshot.path);+ verifyInspectionArtifact();+ if (screenshot) {+ if (!ownership.stagedEntries.has(screenshot.path)) {+ registerStagedEvidence(ownership, screenshot.path);+ } else {+ const staged = ownership.stagedEntries.get(screenshot.path);+ if (!currentEvidenceMatches(staged.path, staged.identity, staged.evidence)) {+ throw new Error('The staged visual-check screenshot changed after capture.');+ }+ }+ }observations.set(key, observation({ ...viewport, theme: 'light', metrics }));}for (const viewport of CAPTURE_VIEWPORTS) {const key = screenshotKey(viewport.width, viewport.height, 'dark');const screenshot = screenshotsByKey.get(key);const metrics = await browser.inspect({- artifactPath: artifact,+ artifactPath: inspectionArtifact,...viewport,theme: 'dark',screenshotPath: screenshot.stagedPath,+ writeScreenshot: (bytes) => writeStagedEvidence(ownership, screenshot.path, bytes),});- registerStagedEvidence(ownership, screenshot.path);+ verifyInspectionArtifact();+ if (!ownership.stagedEntries.has(screenshot.path)) {+ registerStagedEvidence(ownership, screenshot.path);+ } else {+ const staged = ownership.stagedEntries.get(screenshot.path);+ if (!currentEvidenceMatches(staged.path, staged.identity, staged.evidence)) {+ throw new Error('The staged visual-check screenshot changed after capture.');+ }+ }observations.set(key, observation({ ...viewport, theme: 'dark', metrics }));}diff --git a/archify/examples/brand-aware-delivery.architecture.json b/archify/examples/brand-aware-delivery.architecture.jsonindex 1ccc9c02..c44b5d2e 100644--- a/archify/examples/brand-aware-delivery.architecture.json+++ b/archify/examples/brand-aware-delivery.architecture.json@@ -3,6 +3,7 @@"diagram_type": "architecture","meta": {"title": "Brand-aware AI delivery",+ "output": "brand-aware-delivery.html","quality_profile": "showcase","viewBox": [1120, 640],"views": [diff --git a/archify/examples/checkout-platform.base.architecture.json b/archify/examples/checkout-platform.base.architecture.jsonindex 6a0697c1..0f4537f4 100644--- a/archify/examples/checkout-platform.base.architecture.json+++ b/archify/examples/checkout-platform.base.architecture.json@@ -3,6 +3,7 @@"diagram_type": "architecture","meta": {"title": "Checkout Platform — Baseline",+ "output": "checkout-platform.base.html","visual_preset": "signal-flow"},"components": [diff --git a/archify/examples/checkout-platform.head.architecture.json b/archify/examples/checkout-platform.head.architecture.jsonindex 224d62b4..ba384386 100644--- a/archify/examples/checkout-platform.head.architecture.json+++ b/archify/examples/checkout-platform.head.architecture.json@@ -3,6 +3,7 @@"diagram_type": "architecture","meta": {"title": "Checkout Platform — Fraud Gate",+ "output": "checkout-platform.head.html","visual_preset": "signal-flow"},"components": [diff --git a/archify/migrations/workflow-v2.mjs b/archify/migrations/workflow-v2.mjsindex 85ba80cb..e9731fcd 100644--- a/archify/migrations/workflow-v2.mjs+++ b/archify/migrations/workflow-v2.mjs@@ -46,6 +46,7 @@ function legacyLayoutProbe(workflow, qualityProfile) {diagram_type: 'workflow',meta: {title: workflow.meta.title,+ output: workflow.meta.output,...(workflow.meta.locale ? { locale: workflow.meta.locale } : {}),legend: { mode: 'hidden' },},diff --git a/archify/renderers/shared/cli.mjs b/archify/renderers/shared/cli.mjsindex 1a3944f2..9ea59822 100644--- a/archify/renderers/shared/cli.mjs+++ b/archify/renderers/shared/cli.mjs@@ -59,10 +59,12 @@ export function loadDiagram({ rendererDir, diagramType, defaultExample, argv = psupportedFixes: ['repair the JSON syntax and run validation again'],}]);}- if (typeof diagram?.meta?.output === 'string') {- validateAuthoredOutputPath(diagram.meta.output);- }+ const authoredOutput = diagram?.meta?.output;+ if (authoredOutput !== undefined) validateAuthoredOutputPath(authoredOutput);validateSchema(diagramType, diagram);+ if (authoredOutput === undefined && process.env.ARCHIFY_REQUIRE_META_OUTPUT === '1') {+ validateAuthoredOutputPath(authoredOutput);+ }validateGuidedViews(diagramType, diagram);validateRelationshipIds(diagramType, diagram);validateEngineeringProfile(diagramType, diagram);@@ -163,7 +165,21 @@ function stageRenderedHtml(outputPath, html, mode) {fs.constants.O_WRONLY | fs.constants.O_CREAT | fs.constants.O_EXCL | noFollow,mode ?? 0o666,);- const metadata = fs.fstatSync(descriptor, { bigint: true });+ let metadata;+ try {+ metadata = fs.fstatSync(descriptor, { bigint: true });+ } catch (error) {+ // A transient first inspection failure must not strand the exclusive+ // candidate. A successful retry binds cleanup to the still-open file;+ // if both inspections fail, preserving the unknown entry is safer.+ try {+ const retry = fs.fstatSync(descriptor, { bigint: true });+ if (retry.isFile() && retry.ino !== 0n) {+ identity = { device: retry.dev, inode: retry.ino };+ }+ } catch {}+ throw error;+ }if (!metadata.isFile() || metadata.ino === 0n) {throw new Error('Temporary render candidate identity could not be verified safely.');}diff --git a/archify/renderers/shared/output-path.mjs b/archify/renderers/shared/output-path.mjsindex fc7aa039..634e65fb 100644--- a/archify/renderers/shared/output-path.mjs+++ b/archify/renderers/shared/output-path.mjs@@ -114,6 +114,12 @@ function windowsExtendedTailComponents(rawOutput, tail) {return authoredComponents.filter(Boolean);}+function rejectWindowsIpcShare(rawOutput, share) {+ if (/^(?:pipe|mailslot)$/iu.test(share)) {+ throwNativeOutputDiagnostic(rawOutput, 'windows-ipc-namespace', { share });+ }+}+function validateWindowsNativeComponent(rawOutput, component, componentIndex) {try {// Prefix the component so a colon is classified as an ADS separator,@@ -169,6 +175,7 @@ function windowsExtendedPathComponents(rawOutput) {if (components.length < 2 || components[0].length === 0 || components[1].length === 0) {throwNativeOutputDiagnostic(rawOutput, 'windows-extended-root');}+ rejectWindowsIpcShare(rawOutput, components[1]);return windowsExtendedTailComponents(rawOutput, authoredTail);}@@ -195,6 +202,7 @@ function windowsPathComponents(rawOutput, normalized) {if (normalized.startsWith('\\\\')) {const unc = normalized.match(/^\\\\([^\\]+)\\([^\\]+)(?:\\|$)/u);if (!unc) throwNativeOutputDiagnostic(rawOutput, 'windows-unc-root');+ rejectWindowsIpcShare(rawOutput, unc[2]);validateWindowsNativeComponent(rawOutput, unc[1], 0);validateWindowsNativeComponent(rawOutput, unc[2], 1);return normalized.slice(unc[0].length).split('\\').filter(Boolean);@@ -380,7 +388,13 @@ export function resolveOutputPath({// Alias checks above retain priority when a target would overwrite an input.if (source === 'cli') {const resolvedOutput = canonicalFuturePath(outputPath);- const authoredMatches = path.extname(rawOutput).toLowerCase() === requiredExtension;+ const authoredExtension = path.extname(rawOutput).toLowerCase();+ const existingWindowsHtmlAlias = platform === 'win32'+ && requiredExtension === '.html'+ && authoredExtension === '.htm'+ && path.extname(resolvedOutput).toLowerCase() === requiredExtension+ && pathsAlias(outputPath, resolvedOutput);+ const authoredMatches = authoredExtension === requiredExtension || existingWindowsHtmlAlias;const resolvedMatches = path.extname(resolvedOutput).toLowerCase() === requiredExtension;if (!authoredMatches || !resolvedMatches) {const message = `CLI output must ${authoredMatches ? 'resolve to' : 'target'} a ${requiredExtension} file.`;diff --git a/archify/renderers/shared/path-semantics.mjs b/archify/renderers/shared/path-semantics.mjsindex 8638bb77..6cac0c89 100644--- a/archify/renderers/shared/path-semantics.mjs+++ b/archify/renderers/shared/path-semantics.mjs@@ -189,6 +189,7 @@ function compareKnownEntries(left, right, operation) {});}+ // path-contract-allow: lexical-capability -- Canonical paths are compared inside the identity primitive.if (left.realPath === right.realPath) {return result('match', 'native-realpath-match', {operation,@@ -829,6 +830,7 @@ export function sameParent(leftPath, rightPath) {function parentEntry(entry) {const parentPath = hostPath().dirname(entry.realPath);+ // path-contract-allow: lexical-capability -- Both values are canonical paths captured by this primitive.if (parentPath === entry.realPath) return null;try {const realPath = fs.realpathSync.native(parentPath);diff --git a/archify/renderers/shared/sidecar-path.mjs b/archify/renderers/shared/sidecar-path.mjsnew file mode 100644index 00000000..32e73601--- /dev/null+++ b/archify/renderers/shared/sidecar-path.mjs@@ -0,0 +1,38 @@+import { createHash } from 'node:crypto';++const SIDECAR_STEM_NAMESPACE = /\.~archify-[0-9a-f]{64}$/iu;++export function sidecarStemNeedsBounding(stem, suffixes) {+ const fits = (value) => value.length <= 255 && Buffer.byteLength(value, 'utf8') <= 255;+ return !suffixes.every((suffix) => fits(`${stem}${suffix}`));+}++export function boundedSidecarStem(stem, suffixes, { force = false, hashDomain } = {}) {+ if (!force && !sidecarStemNeedsBounding(stem, suffixes)+ && !SIDECAR_STEM_NAMESPACE.test(stem)) return stem;+ const hashInput = hashDomain ? `${hashDomain}\0${stem}` : stem;+ const marker = `.~archify-${createHash('sha256').update(hashInput).digest('hex')}`;+ const codePoints = [...stem];+ while (codePoints.length+ && sidecarStemNeedsBounding(`${codePoints.join('')}${marker}`, suffixes)) {+ codePoints.pop();+ }+ return `${codePoints.join('')}${marker}`;+}++export function sidecarStemFromComponent(component) {+ if (component.endsWith('.html')) {+ return {+ stem: component.slice(0, -'.html'.length),+ options: undefined,+ };+ }+ return {+ stem: component,+ options: { force: true, hashDomain: 'full-component' },+ };+}++export function isBoundedSidecarStem(stem) {+ return SIDECAR_STEM_NAMESPACE.test(stem);+}diff --git a/archify/scripts/check-update.mjs b/archify/scripts/check-update.mjsindex f7427b30..30d529aa 100644--- a/archify/scripts/check-update.mjs+++ b/archify/scripts/check-update.mjs@@ -254,7 +254,7 @@ function isWithinDirectory(directory, target) {|| (!path.isAbsolute(relative) && relative !== '..' && !relative.startsWith(`..${path.sep}`));}-function physicalDirectorySuffix(directory, target) {+async function physicalDirectorySuffix(directory, target) {const absoluteTarget = path.resolve(target);const parsed = path.parse(absoluteTarget);const segments = absoluteTarget.slice(parsed.root.length).split(path.sep).filter(Boolean);@@ -262,7 +262,13 @@ function physicalDirectorySuffix(directory, target) {for (let index = 0; index < segments.length; index += 1) {prefix = path.join(prefix, segments[index]);const relation = sameEntry(directory, prefix);- if (relation.status === 'match') return segments.slice(index + 1);+ if (relation.status === 'match') {+ const metadata = await fs.lstat(prefix, { bigint: true });+ if (metadata.isSymbolicLink()) {+ throw new Error(`trusted cache prefix is a symbolic link or junction: ${prefix}`);+ }+ return segments.slice(index + 1);+ }if (relation.status === 'unknown' && relation.reason.code === 'entry-missing') break;}return null;@@ -274,7 +280,7 @@ async function canonicalizeTrustedDirectoryPrefix(target) {path.resolve(directory))))].sort((left, right) => right.length - left.length);for (const trustedDirectory of trustedDirectories) {- const suffix = physicalDirectorySuffix(trustedDirectory, absoluteTarget);+ const suffix = await physicalDirectorySuffix(trustedDirectory, absoluteTarget);if (suffix === null) continue;try {const canonicalDirectory = await fs.realpath(trustedDirectory);diff --git a/archify/test/architecture-delta-markers.test.mjs b/archify/test/architecture-delta-markers.test.mjsindex 4ff2dae8..a1804423 100644--- a/archify/test/architecture-delta-markers.test.mjs+++ b/archify/test/architecture-delta-markers.test.mjs@@ -105,7 +105,13 @@ test('checkout compare resolves all three baseline arrowheads and keeps snapshot});function variantFixture(operation) {- const base = { schema_version: 1, diagram_type: 'architecture', meta: { title: 'Marker variants' }, components: [], connections: [] };+ const base = {+ schema_version: 1,+ diagram_type: 'architecture',+ meta: { title: 'Marker variants', output: 'marker-variants-base.html' },+ components: [],+ connections: [],+ };for (const [index, variant] of variants.entries()) {const y = 100 + index * 260;for (const [column, suffix] of ['a', 'b', 'c'].entries()) {@@ -114,6 +120,7 @@ function variantFixture(operation) {base.connections.push({ id: variant, from: `${variant}-a`, to: `${variant}-b`, variant });}const head = structuredClone(base);+ head.meta.output = 'marker-variants-head.html';if (operation === 'removed') head.connections = [];else head.connections.forEach((edge, index) => {const y = 200 + index * 260;diff --git a/archify/test/architecture-delta.test.mjs b/archify/test/architecture-delta.test.mjsindex e064d734..55f93d2b 100644--- a/archify/test/architecture-delta.test.mjs+++ b/archify/test/architecture-delta.test.mjs@@ -57,7 +57,7 @@ function provenanceFixture() {const diagram = {schema_version: 1,diagram_type: 'architecture',- meta: { title: 'Provenance-only delta' },+ meta: { title: 'Provenance-only delta', output: 'provenance-only-delta.html' },components: [{id: 'service',type: 'backend',@@ -176,7 +176,7 @@ test('compare reports brand-only changes in the receipt and exact review target'const base = {schema_version: 1,diagram_type: 'architecture',- meta: { title: 'Cache' },+ meta: { title: 'Cache', output: 'cache.html' },components: [{ id: 'cache', type: 'database', label: 'Cache', pos: [100, 100], size: [160, 80] }],};const basePath = path.join(tmp, 'brand-base.json');@@ -309,7 +309,12 @@ test('baseline boundary title masks stay below current components and carry deltconst documentAt = (pos, pad) => ({schema_version: 1,diagram_type: 'architecture',- meta: { title: 'Boundary mask z-order', quality_profile: 'standard', viewBox: [600, 400] },+ meta: {+ title: 'Boundary mask z-order',+ output: 'boundary-mask-z-order.html',+ quality_profile: 'standard',+ viewBox: [600, 400],+ },components: [{ id: 'node', type: 'backend', label: 'Current node', pos, size: [120, 60] }],connections: [],boundaries: [{ kind: 'region', label: 'Boundary label', wraps: ['node'], pad }],diff --git a/archify/test/artifact-receipt-flush.test.mjs b/archify/test/artifact-receipt-flush.test.mjsindex 50ec9465..2a3971ab 100644--- a/archify/test/artifact-receipt-flush.test.mjs+++ b/archify/test/artifact-receipt-flush.test.mjs@@ -87,7 +87,11 @@ function denseArchitecture() {return {schema_version: 1,diagram_type: 'architecture',- meta: { title: 'Large receipt regression', quality_profile: 'standard' },+ meta: {+ title: 'Large receipt regression',+ output: 'large-receipt-regression.html',+ quality_profile: 'standard',+ },components,connections,};diff --git a/archify/test/authored-straight-routes.test.mjs b/archify/test/authored-straight-routes.test.mjsindex 37fadbde..7acbf11d 100644--- a/archify/test/authored-straight-routes.test.mjs+++ b/archify/test/authored-straight-routes.test.mjs@@ -55,7 +55,9 @@ function orthogonalCheck(result) {}function inputFor(name, document) {const input = path.join(tmp, `${name}.json`);- fs.writeFileSync(input, JSON.stringify(document));+ const cliDocument = structuredClone(document);+ cliDocument.meta = { ...cliDocument.meta, output: `${name}.html` };+ fs.writeFileSync(input, JSON.stringify(cliDocument));return input;}function assertPassed(result) {diff --git a/archify/test/cli.test.mjs b/archify/test/cli.test.mjsindex 2dbcbd43..684dfba3 100644--- a/archify/test/cli.test.mjs+++ b/archify/test/cli.test.mjs@@ -195,6 +195,7 @@ test('cli: doctor reports a complete installation is ready', () => {assert.match(result.stdout, /\[ok\] Example renderer/);assert.match(result.stdout, /\[ok\] Live preview runtime/);assert.match(result.stdout, /\[ok\] Atomic output safety runtime/);+ assert.match(result.stdout, /\[ok\] Sidecar path naming runtime/);assert.match(result.stdout, /\[ok\] Scenario recipe guide/);assert.match(result.stdout, /\[ok\] Progressive authoring references/);assert.match(result.stdout, /\[ok\] Architecture compare runtime and proof fixtures/);@@ -2373,7 +2374,44 @@ await import(${JSON.stringify(pathToFileURL(cli).href)});assert.equal(fs.existsSync(fake.log), false);});-for (const failureMode of ['empty-write', 'partial-write', 'close', 'replacement', 'zero-identity-replacement', 'cleanup-failure']) {+test('cli: a first lock handle identity failure leaves no public lock and permits retry', () => {+ const input = path.join(skillRoot, 'examples/agent-tool-call.workflow.json');+ const out = path.join(tmp, 'delivery-lock-first-fstat.html');+ const lockPath = deliveryLockPath(out);+ const wrapper = path.join(tmp, 'delivery-lock-first-fstat.mjs');+ fs.writeFileSync(wrapper, `+import fs from 'node:fs';+const openSync = fs.openSync;+const fstatSync = fs.fstatSync;+let lockDescriptor;+let injected = false;+fs.openSync = (file, ...args) => {+ const descriptor = openSync(file, ...args);+ if (lockDescriptor === undefined && String(file) === ${JSON.stringify(lockPath)}) {+ lockDescriptor = descriptor;+ }+ return descriptor;+};+fs.fstatSync = (descriptor, ...args) => {+ if (descriptor === lockDescriptor && !injected) {+ injected = true;+ throw Object.assign(new Error('injected first lock fstat failure'), { code: 'EIO' });+ }+ return fstatSync(descriptor, ...args);+};+process.argv = [process.execPath, ${JSON.stringify(cli)}, 'deliver', 'workflow', ${JSON.stringify(input)}, ${JSON.stringify(out)}, '--json'];+await import(${JSON.stringify(pathToFileURL(cli).href)});+`);++ const failed = spawnSync(process.execPath, [wrapper], { cwd: skillRoot, encoding: 'utf8' });+ assert.equal(failed.status, 1, failed.stderr || failed.stdout);+ assert.equal(JSON.parse(failed.stdout).diagnostics[0].code, 'delivery/lock-acquire');+ assert.equal(fs.existsSync(lockPath), false, 'failed identity capture leaked the public lock');+ const retry = run(['deliver', 'workflow', input, out, '--json']);+ assert.equal(retry.status, 0, retry.stderr || retry.stdout);+});++for (const failureMode of ['empty-write', 'partial-write', 'close', 'replacement', 'cleanup-failure']) {test(`cli: portable delivery lock: failed lock initialization is cleaned up and delivery can retry (${failureMode})`, () => {const input = path.join(skillRoot, 'examples/agent-tool-call.workflow.json');const out = path.join(tmp, `lock-init-${failureMode}.html`);@@ -2948,7 +2986,7 @@ await import(${JSON.stringify(pathToFileURL(cli).href)}););});-test('cli: using the existing receipt as input preserves it and invalidates the previous delivery', () => {+test('cli: using the existing receipt as input fails before invalidating the previous delivery', () => {const input = path.join(skillRoot, 'examples/agent-tool-call.workflow.json');const out = path.join(tmp, 'receipt-as-input.html');assert.equal(run(['deliver', 'workflow', input, out, '--json']).status, 0);@@ -2956,12 +2994,14 @@ test('cli: using the existing receipt as input preserves it and invalidates theconst prior = fs.readFileSync(sidecar);const failed = run(['deliver', 'workflow', sidecar, out, '--json']);assert.equal(failed.status, 1);- assert.equal(JSON.parse(failed.stdout).provenance, 'unrecorded');+ const failure = JSON.parse(failed.stdout);+ assert.equal(failure.stage, 'prepare');+ assert.equal(failure.diagnostics[0].code, 'output/meta-path-syntax');assert.deepEqual(fs.readFileSync(sidecar), prior);for (const flags of [[], ['--require-provenance']]) {const checked = run(['check', out, ...flags]);- assert.equal(checked.status, 1);- assert.equal(JSON.parse(checked.stdout).provenance, 'failed');+ assert.equal(checked.status, 0);+ assert.equal(JSON.parse(checked.stdout).provenance, 'current');}assert.equal(run(['deliver', 'workflow', input, out, '--json']).status, 0);assert.equal(run(['check', out, '--require-provenance']).status, 0);@@ -3227,7 +3267,7 @@ test('cli: deliver reports unreadable input as json without touching the target'assert.equal(fs.readFileSync(out, 'utf8'), trustedPriorArtifact);});-test('cli: invalid source output metadata still fails inside the renderer', () => {+test('cli: invalid source output metadata fails before renderer or delivery side effects', () => {const workingDirectory = path.join(tmp, 'invalid-output-metadata');fs.mkdirSync(workingDirectory, { recursive: true });const input = path.join(workingDirectory, 'source.architecture.json');@@ -3241,9 +3281,13 @@ test('cli: invalid source output metadata still fails inside the renderer', () =const result = run(['deliver', 'architecture', input, '--json'], { cwd: workingDirectory });assert.equal(result.status, 1);const failure = JSON.parse(result.stdout);- assert.equal(failure.stage, 'render');- assert.match(failure.error, /schema validation failed/i);+ assert.equal(failure.stage, 'prepare');+ assert.equal(failure.diagnostics[0].code, 'output/meta-path-syntax');assert.equal(fs.readFileSync(out, 'utf8'), trustedPriorArtifact);+ assert.deepEqual(fs.readdirSync(workingDirectory).sort(), [+ 'architecture.html',+ 'source.architecture.json',+ ]);});test('cli: deliver rejects a non-regular target before commit without a false success receipt', () => {@@ -3329,6 +3373,7 @@ test('cli: validate JSON exposes only the primary v1 column-capacity diagnostic'diagram_type: 'workflow',meta: {title: 'Pinned issue 126 diagnostic boundary',+ output: 'pinned-column-capacity.html',viewBox: [720, 400],legend: { mode: 'hidden' },},diff --git a/archify/test/delivery-sidecar-path.test.mjs b/archify/test/delivery-sidecar-path.test.mjsindex 1141ebb3..89cdbd7f 100644--- a/archify/test/delivery-sidecar-path.test.mjs+++ b/archify/test/delivery-sidecar-path.test.mjs@@ -83,6 +83,38 @@ test('delivery keeps every derived sidecar component within portable limits', ()assert.equal(JSON.parse(checked.stdout).provenance, 'current');});+test('strict provenance recognizes legacy sidecars for mixed-case HTML extensions', (t) => {+ const cwd = fs.mkdtempSync(path.join(os.tmpdir(), 'archify-legacy-extension-sidecar-'));+ t.after(() => fs.rmSync(cwd, { recursive: true, force: true }));+ const caseProbe = path.join(cwd, 'case-probe');+ fs.writeFileSync(caseProbe, 'probe');+ if (fs.existsSync(path.join(cwd, 'CASE-PROBE'))) {+ t.skip('requires a case-sensitive filesystem');+ return;+ }+ fs.unlinkSync(caseProbe);+ const output = path.join(cwd, 'diagram.HTML');+ const delivered = run(['deliver', 'workflow', input, output, '--json'], cwd);+ assert.equal(delivered.status, 0, delivered.stderr || delivered.stdout);+ const currentProvenance = fs.readdirSync(cwd)+ .map((name) => path.join(cwd, name))+ .find((candidate) => candidate.endsWith('.delivery.json'));+ assert.ok(currentProvenance);+ const legacyProvenance = path.join(cwd, 'diagram.delivery.json');+ assert.notEqual(currentProvenance, legacyProvenance);+ fs.renameSync(currentProvenance, legacyProvenance);++ const checked = run(['check', output, '--require-provenance'], cwd);+ assert.equal(checked.status, 0, checked.stderr || checked.stdout);+ assert.equal(JSON.parse(checked.stdout).provenance, 'current');++ const legacyPending = path.join(cwd, 'diagram.delivery-pending.json');+ fs.writeFileSync(legacyPending, '{"status":"pending"}\n');+ const blocked = run(['check', output, '--require-provenance'], cwd);+ assert.equal(blocked.status, 1, blocked.stderr || blocked.stdout);+ assert.equal(JSON.parse(blocked.stdout).diagnostics[0].code, 'delivery/provenance-failed');+});+test('delivery rejects an illegal output extension before preparing its missing parent', () => {const cwd = fs.mkdtempSync(path.join(os.tmpdir(), 'archify-illegal-output-parent-'));const parent = path.join(cwd, 'must-remain-absent');@@ -963,16 +995,11 @@ test('Windows delivery accepts an existing 8.3 artifact alias and keeps strict p? fs.mkdtempSync(path.join(controlledRoot.root, 'delivery-')): fs.mkdtempSync(path.join(os.tmpdir(), 'archify-delivery-eight-dot-three-'));t.after(() => fs.rmSync(cwd, { recursive: true, force: true }));- const shortCwd = controlledRoot- ? path.win32.join(controlledRoot.shortRoot, path.basename(cwd))- : null;const directory = path.join(cwd, 'directory name requiring short alias');fs.mkdirSync(directory);const output = path.join(directory, 'diagram artifact with long name.html');assert.equal(run(['deliver', 'workflow', input, output, '--json'], cwd).status, 0);- const shortOutput = shortCwd- ? path.win32.join(shortCwd, path.basename(directory), path.basename(output))- : windowsShortPath(output);+ const shortOutput = windowsShortPath(output);if (!shortOutput) {t.skip('the Windows volume does not expose a distinct 8.3 artifact alias');return;@@ -982,6 +1009,11 @@ test('Windows delivery accepts an existing 8.3 artifact alias and keeps strict pfs.realpathSync.native(output).toLowerCase(),'the artifact path must resolve through the controlled explicit 8.3 alias',);+ assert.equal(+ path.win32.extname(shortOutput).toLowerCase(),+ '.htm',+ 'the regression must exercise the three-character 8.3 file extension',+ );const redelivered = run(['deliver', 'workflow', input, shortOutput, '--json'], cwd);assert.equal(redelivered.status, 0, redelivered.stderr || redelivered.stdout);diff --git a/archify/test/fixtures/v1-workflow-explicit-coordinates.workflow.json b/archify/test/fixtures/v1-workflow-explicit-coordinates.workflow.jsonindex 203be266..b26cb85f 100644--- a/archify/test/fixtures/v1-workflow-explicit-coordinates.workflow.json+++ b/archify/test/fixtures/v1-workflow-explicit-coordinates.workflow.json@@ -3,6 +3,7 @@"diagram_type": "workflow","meta": {"title": "Pinned coordinate migration",+ "output": "pinned-coordinate-migration.html","viewBox": [720, 700],"legend": { "mode": "hidden" }},diff --git a/archify/test/layout-rules.test.mjs b/archify/test/layout-rules.test.mjsindex b7ca1157..1e20b76d 100644--- a/archify/test/layout-rules.test.mjs+++ b/archify/test/layout-rules.test.mjs@@ -54,7 +54,9 @@ function render(mode, doc) {function validateCli(mode, doc, quality = 'showcase') {const input = path.join(tmp, `${mode}-cli-${Math.abs(hash(JSON.stringify(doc)))}.json`);- fs.writeFileSync(input, JSON.stringify(doc));+ const cliDoc = structuredClone(doc);+ cliDoc.meta = { ...cliDoc.meta, output: `${mode}-validation.html` };+ fs.writeFileSync(input, JSON.stringify(cliDoc));try {const stdout = execFileSync('node', [path.join(skillRoot, 'bin', 'archify.mjs'),@@ -77,7 +79,9 @@ function validateCli(mode, doc, quality = 'showcase') {function deliverCli(mode, doc, quality = 'showcase') {const input = path.join(tmp, `${mode}-deliver-${Math.abs(hash(JSON.stringify(doc)))}.json`);const outPath = path.join(tmp, `${mode}-deliver-${Math.abs(hash(JSON.stringify(doc)))}.html`);- fs.writeFileSync(input, JSON.stringify(doc));+ const cliDoc = structuredClone(doc);+ cliDoc.meta = { ...cliDoc.meta, output: `${mode}-delivery.html` };+ fs.writeFileSync(input, JSON.stringify(cliDoc));try {const stdout = execFileSync('node', [path.join(skillRoot, 'bin', 'archify.mjs'),diff --git a/archify/test/legend-contract.test.mjs b/archify/test/legend-contract.test.mjsindex 978f951e..b7aa78d3 100644--- a/archify/test/legend-contract.test.mjs+++ b/archify/test/legend-contract.test.mjs@@ -107,7 +107,9 @@ function run(type, doc, command = 'render') {const id = sequence++;const input = path.join(tmp, `${id}-${type}.json`);const output = path.join(tmp, `${id}-${type}.html`);- fs.writeFileSync(input, JSON.stringify(doc));+ const source = clone(doc);+ source.meta.output ??= `${type}.html`;+ fs.writeFileSync(input, JSON.stringify(source));const args = command === 'render'? [cli, 'render', type, input, output]: [cli, 'validate', type, input, '--json'];diff --git a/archify/test/meta-output-contract.test.mjs b/archify/test/meta-output-contract.test.mjsindex 2c0364da..8e66c44f 100644--- a/archify/test/meta-output-contract.test.mjs+++ b/archify/test/meta-output-contract.test.mjs@@ -30,6 +30,15 @@ function writeDocument(directory, name, source, output) {return target;}+function writeDocumentWithoutValidOutput(directory, name, source, output = undefined) {+ const document = JSON.parse(fs.readFileSync(source, 'utf8'));+ if (output === undefined) delete document.meta.output;+ else document.meta.output = output;+ const target = path.join(directory, name);+ fs.writeFileSync(target, `${JSON.stringify(document, null, 2)}\n`);+ return target;+}+function run(args, cwd) {return spawnSync(process.execPath, [cli, ...args], { cwd, encoding: 'utf8' });}@@ -93,6 +102,86 @@ test('an explicit CLI output does not hide an invalid durable authored output',assert.equal(fs.existsSync(override), false);});+for (const [label, output] of [['missing', undefined], ['non-string', 42]]) {+ test(`all artifact commands reject ${label} durable meta.output before creating outputs`, t => {+ const directory = workspace(t);+ const input = writeDocumentWithoutValidOutput(+ directory,+ `${label}.architecture.json`,+ architectureExample,+ output,+ );++ for (const command of ['validate', 'render', 'deliver']) {+ const commandDirectory = path.join(directory, command);+ const artifact = path.join(commandDirectory, 'override.html');+ const args = command === 'validate'+ ? [command, 'architecture', input, '--json']+ : command === 'deliver'+ ? [command, 'architecture', input, artifact, '--json']+ : [command, 'architecture', input, artifact];+ const result = run(args, directory);+ assert.equal(result.status, 1, `${command}: ${result.stderr || result.stdout}`);+ assert.equal(fs.existsSync(commandDirectory), false, `${command} created its output directory`);+ assert.equal(+ fs.readdirSync(directory).some((entry) => /delivery|archify-render/u.test(entry)),+ false,+ `${command} left a sidecar or staging entry`,+ );+ }+ });++ test(`compare and preview reject ${label} durable meta.output before creating outputs`, t => {+ const directory = workspace(t);+ const input = writeDocumentWithoutValidOutput(+ directory,+ `${label}.architecture.json`,+ architectureExample,+ output,+ );+ const peer = writeDocument(+ directory,+ 'peer.architecture.json',+ architectureExample,+ 'peer.html',+ );++ const compareDirectory = path.join(directory, 'compare');+ const compare = run([+ 'compare', 'architecture', input, peer, path.join(compareDirectory, 'delta.html'), '--json',+ ], directory);+ assert.equal(compare.status, 1, compare.stderr || compare.stdout);+ assert.equal(jsonOutput(compare).diagnostics[0].code, 'output/meta-path-syntax');+ assert.equal(fs.existsSync(compareDirectory), false, 'compare created its output directory');++ const previewDirectory = path.join(directory, 'preview');+ const preview = run([+ 'preview', 'architecture', input, path.join(previewDirectory, 'diagram.html'), '--no-open',+ ], directory);+ assert.equal(preview.status, 1, preview.stderr || preview.stdout);+ assert.match(preview.stderr, /meta\.output must be a portable POSIX-relative path/);+ assert.equal(fs.existsSync(previewDirectory), false, 'preview created its output directory');+ });++ test(`migration rejects ${label} durable meta.output before creating its destination`, t => {+ const directory = workspace(t);+ const source = writeDocumentWithoutValidOutput(+ directory,+ `${label}.workflow.json`,+ workflowFixture,+ output,+ );+ const destinationDirectory = path.join(directory, 'migration');+ const destination = path.join(destinationDirectory, 'migrated.workflow.json');+ const result = run([+ 'migrate', 'workflow', source, destination, '--to-schema', '2', '--json',+ ], directory);+ assert.equal(result.status, 1, result.stderr || result.stdout);+ assert.equal(jsonOutput(result).diagnostics[0].code, 'output/meta-path-syntax');+ assert.equal(fs.existsSync(destinationDirectory), false, 'migration created its destination directory');+ });+}+test('migration rejects a non-portable authored output without mutating its destination', t => {const directory = workspace(t);const source = writeDocument(diff --git a/archify/test/native-output-path.test.mjs b/archify/test/native-output-path.test.mjsindex 0252b166..3f3ceea5 100644--- a/archify/test/native-output-path.test.mjs+++ b/archify/test/native-output-path.test.mjs@@ -52,6 +52,10 @@ test('Windows CLI outputs reject ambiguous or special namespace forms', () => {String.raw`C:\reports\CON.html`,String.raw`C:\reports\diagram .html `,String.raw`C:\reports\bad?.html`,+ String.raw`\\localhost\pipe\diagram.html`,+ String.raw`\\server\mailslot\diagram.html`,+ String.raw`\\?\UNC\localhost\pipe\diagram.html`,+ String.raw`\\?\UNC\server\MAILSLOT\diagram.html`,]) nativeFailure(value, { platform: 'win32' });});diff --git a/archify/test/output-path.test.mjs b/archify/test/output-path.test.mjsindex 6702ce7e..6418fd1c 100644--- a/archify/test/output-path.test.mjs+++ b/archify/test/output-path.test.mjs@@ -289,6 +289,10 @@ test('deliver rechecks aliases immediately before committing a verified candidatpath.join(skillRoot, 'renderers/shared/atomic-output.mjs'),path.join(installedShared, 'atomic-output.mjs'),);+ fs.copyFileSync(+ path.join(skillRoot, 'renderers/shared/sidecar-path.mjs'),+ path.join(installedShared, 'sidecar-path.mjs'),+ );fs.writeFileSync(path.join(installedRenderer, 'render-workflow.mjs'), `import fs from 'node:fs';const [, output] = process.argv.slice(2);@@ -316,7 +320,7 @@ console.log(JSON.stringify({fs.symlinkSync(initialOutputDirectory, linkedDirectory, 'dir');const input = path.join(inputDirectory, 'diagram.html');const output = path.join(linkedDirectory, 'diagram.html');- const source = Buffer.from('{"meta":{"title":"race input"}}');+ const source = Buffer.from('{"meta":{"title":"race input","output":"diagram.html"}}');fs.writeFileSync(input, source);const marker = path.join(cwd, 'renderer-started');@@ -979,6 +983,10 @@ test('compare rechecks every target immediately before committing the artifact ppath.join(skillRoot, 'renderers/shared/atomic-output.mjs'),path.join(installedShared, 'atomic-output.mjs'),);+ fs.copyFileSync(+ path.join(skillRoot, 'renderers/shared/sidecar-path.mjs'),+ path.join(installedShared, 'sidecar-path.mjs'),+ );fs.writeFileSync(path.join(installedRenderer, 'render-architecture.mjs'), `import fs from 'node:fs';import path from 'node:path';@@ -1031,9 +1039,9 @@ export const validateArchitectureDeltaHtml = () => ({ checksPassed: 1, checkCounconst base = path.join(inputDirectory, 'diagram.html');const head = path.join(cwd, 'head.json');const output = path.join(linkedDirectory, 'diagram.html');- const source = Buffer.from('{"side":"base"}');+ const source = Buffer.from('{"meta":{"output":"base.html"},"side":"base"}');fs.writeFileSync(base, source);- fs.writeFileSync(head, '{"side":"head"}');+ fs.writeFileSync(head, '{"meta":{"output":"head.html"},"side":"head"}');const marker = path.join(cwd, 'renderer-started');const child = spawn(process.execPath, [@@ -1090,6 +1098,7 @@ test('doctor reports a missing output-path safety runtime in an installed skill'for (const [relative, label] of [['renderers/shared/path-semantics.mjs', 'Physical path semantics runtime'],['renderers/shared/portable-path.mjs', 'Portable path contract runtime'],+ ['renderers/shared/sidecar-path.mjs', 'Sidecar path naming runtime'],]) {test(`doctor reports a missing ${path.basename(relative)} runtime without crashing`, () => {const cwd = fs.mkdtempSync(path.join(os.tmpdir(), 'archify-output-doctor-dependency-'));diff --git a/archify/test/path-boundary-contract.test.mjs b/archify/test/path-boundary-contract.test.mjsindex 76ad7696..f3be24fb 100644--- a/archify/test/path-boundary-contract.test.mjs+++ b/archify/test/path-boundary-contract.test.mjs@@ -33,7 +33,7 @@ const protectedCallers = productionSourceRoots.flatMap(productionSources).sort()const exemption = /path-contract-allow:\s*(?:git-path|portable-logical-path|url-path|lexical-capability)\s+--\s+\S/u;const exemptionMarker = /path-contract-allow:/u;const pathIdentifier = String.raw`(?:[$A-Z_a-z][$\w]*(?:Path|Root|Directory|Dir|File|Canonical|Location)|path|root|directory|dir|file|output|input|target|destination|artifact|receipt|relative|resolved|canonical)`;-const pathProperty = String.raw`(?:[$A-Z_a-z][$\w.]*\.(?:path|root|directory|dir|file|output|input|target|source|destination|artifact|receipt))`;+const pathProperty = String.raw`(?:[$A-Z_a-z][$\w.]*\.(?:path|realPath|canonicalPath|root|directory|dir|file|output|input|target|source|destination|artifact|receipt))`;const pathOperand = String.raw`(?:${pathIdentifier}|${pathProperty})`;const rawPathEquality = new RegExp(String.raw`\b${pathOperand}\s*(?:===|!==)\s*${pathOperand}\b`, 'u');const nativePathCall = String.raw`(?:path\.(?:resolve|normalize|dirname|relative|basename)|fs\.realpathSync(?:\.native)?)\s*\(`;@@ -85,6 +85,20 @@ function inspectPathBoundarySource(source, file = '<fixture>') {violations.push({ file, line: index + 1, rule: 'native-path-string-prefix-containment' });}}+ for (const rule of [+ ['native-path-raw-equality', rawPathEquality],+ ['native-path-raw-equality', directNativeEquality],+ ]) {+ const pattern = new RegExp(rule[1].source, 'gu');+ for (const match of source.matchAll(pattern)) {+ if (!match[0].includes('\n')) continue;+ const line = source.slice(0, match.index).split(/\r?\n/u).length;+ if (hasValidExemption(lines, line - 1)) continue;+ if (!violations.some((entry) => entry.line === line && entry.rule === rule[0])) {+ violations.push({ file, line, rule: rule[0] });+ }+ }+ }return violations;}@@ -106,6 +120,19 @@ test('path-boundary detector rejects the three native-path regression patterns',]);});+test('path-boundary detector rejects multiline equality and canonical-path properties', () => {+ const violations = inspectPathBoundarySource([+ 'if (outputPath ===',+ ' inputPath) fail();',+ 'if (left.realPath === right.realPath) fail();',+ ].join('\n'));++ assert.deepEqual(violations.map(({ rule }) => rule), [+ 'native-path-raw-equality',+ 'native-path-raw-equality',+ ]);+});+test('path-boundary detector permits explicit logical-path and lexical-capability exemptions', () => {const violations = inspectPathBoundarySource(['// path-contract-allow: git-path -- Git tree entries use repository-relative POSIX syntax.',diff --git a/archify/test/preview.test.mjs b/archify/test/preview.test.mjsindex 43801146..e92d48a8 100644--- a/archify/test/preview.test.mjs+++ b/archify/test/preview.test.mjs@@ -599,6 +599,53 @@ test('preview: replacing the staged commit candidate preserves the claimant', {}});+test('preview: replacing the delivered source candidate preserves the claimant', { timeout: 10000 }, async (t) => {+ const tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'archify-preview-source-replacement-'));+ t.after(() => fs.rmSync(tmp, { recursive: true, force: true }));+ const input = path.join(tmp, 'diagram.json');+ const output = path.join(tmp, 'diagram.html');+ const deliveryCli = path.join(tmp, 'delivery.mjs');+ const marker = path.join(tmp, 'delivery-started');+ const detachedCandidate = path.join(tmp, 'detached-delivery-candidate.html');+ const sentinel = '<!doctype html><title>delivery claimant must survive</title>';+ fs.writeFileSync(input, '{}');+ writeDelayedDeliveryCli(deliveryCli, marker, 'Delivered source identity binding');++ const lstatSync = fs.lstatSync;+ let candidatePath;+ let replaced = false;+ t.mock.method(fs, 'lstatSync', (target, ...args) => {+ if (!replaced+ && path.basename(String(target)) === 'generation-1.html'+ && fs.existsSync(target)) {+ candidatePath = path.resolve(target);+ fs.renameSync(candidatePath, detachedCandidate);+ fs.writeFileSync(candidatePath, sentinel, { flag: 'wx' });+ replaced = true;+ }+ return lstatSync(target, ...args);+ });++ const preview = await startPreview({+ type: 'architecture', input, output, open: false, watch: false,+ pollMs: 60_000, debounceMs: 10, deliveryCli,+ });+ try {+ await waitForState(+ preview.url,+ (candidate) => candidate.status === 'needs-fix',+ 'source candidate replacement did not fail preview',+ );+ assert.equal(replaced, true);+ assert.equal(fs.readFileSync(candidatePath, 'utf8'), sentinel);+ assert.equal(fs.existsSync(output), false);+ } finally {+ await preview.stop();+ }+ assert.equal(fs.readFileSync(candidatePath, 'utf8'), sentinel);+ assert.equal(fs.existsSync(detachedCandidate), true);+});+test('preview: a delivery candidate replaced by a symlink is rejected without following it', { timeout: 10000 }, async (t) => {const tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'archify-preview-source-symlink-'));t.after(() => fs.rmSync(tmp, { recursive: true, force: true }));diff --git a/archify/test/release-package-gates.test.mjs b/archify/test/release-package-gates.test.mjsindex 71cd9937..042a604e 100644--- a/archify/test/release-package-gates.test.mjs+++ b/archify/test/release-package-gates.test.mjs@@ -637,6 +637,7 @@ canonicalZipTest('built archives contain the embedded notifier runtime', () => {assert.ok(entries.has('archify/scripts/check-update.mjs'));assert.ok(entries.has('archify/scripts/update-contract.mjs'));assert.ok(entries.has('archify/renderers/shared/atomic-output.mjs'));+ assert.ok(entries.has('archify/renderers/shared/sidecar-path.mjs'));} finally {fs.rmSync(fixture, { recursive: true, force: true });}@@ -1376,7 +1377,8 @@ test('CI and tagged releases share the maintained Windows path contract on Nodeassert.match(runner, /updater rejects a case-only alias/);assert.match(runner, /symlink cache root/);assert.match(runner, /symlink cache ancestor/);- assert.match(runner, /trusted cache prefix switched/);+ assert.match(runner, /authored symlink is rejected/);+ assert.match(runner, /trusted directory through a symlink/);assert.match(runner, /preview runs from an installed skill/);assert.match(runner, /watcher accepts/);assert.match(runner, /findChrome/);@@ -1397,6 +1399,11 @@ test('CI and tagged releases share the maintained Windows path contract on Nodeassert.match(runner, /fs\.linkSync\(fileTarget, hardlink\)/);assert.match(runner, /runCli\(\[\s*'visual-check'/);assert.match(runner, /--require-provenance/);+ assert.match(runner, /architecture compare to extended UNC/);+ assert.match(runner, /repository root through drive-letter case alias/);+ assert.match(runner, /stageCleanSkill\(\{ repoRoot: driveCaseRepoRoot/);+ assert.match(runner, /checkForUpdate\(\{/);+ assert.match(runner, /delivery beyond traditional MAX_PATH/);assert.match(runner, /build-zip[.]sh/);const previewSuite = fs.readFileSync(path.join(repoRoot, 'archify', 'test', 'preview.test.mjs'), 'utf8');diff --git a/archify/test/render-failure-diagnostics.test.mjs b/archify/test/render-failure-diagnostics.test.mjsindex 1ca8aff9..9c9a58d3 100644--- a/archify/test/render-failure-diagnostics.test.mjs+++ b/archify/test/render-failure-diagnostics.test.mjs@@ -103,7 +103,12 @@ test('render layout rejection exposes the existing diagnostic and preserves an efs.writeFileSync(input, JSON.stringify({schema_version: 1,diagram_type: 'architecture',- meta: { title: 'Wide label', quality_profile: 'standard', viewBox: [975, 395] },+ meta: {+ title: 'Wide label',+ output: 'wide-label.html',+ quality_profile: 'standard',+ viewBox: [975, 395],+ },components: [{ id: 'node', type: 'security', label: '字'.repeat(40), pos: [40, 40], size: [88, 71] }],}));fs.writeFileSync(output, 'trusted artifact');diff --git a/archify/test/renderer-atomic-write.test.mjs b/archify/test/renderer-atomic-write.test.mjsindex d45ae36a..87f32848 100644--- a/archify/test/renderer-atomic-write.test.mjs+++ b/archify/test/renderer-atomic-write.test.mjs@@ -55,6 +55,36 @@ function createFifo(target) {return true;}+test('a first candidate handle identity failure removes the exclusive render candidate', (t) => {+ const root = workspace(t, 'archify-render-atomic-first-fstat-');+ const input = path.join(root, 'diagram.workflow.json');+ const output = path.join(root, 'diagram.html');+ fs.copyFileSync(workflowFixture, input);+ const loaded = loadWorkflow(input, output);+ const openSync = fs.openSync;+ const fstatSync = fs.fstatSync;+ let candidateDescriptor;+ let injected = false;+ t.mock.method(fs, 'openSync', (target, ...args) => {+ const descriptor = openSync(target, ...args);+ if (path.basename(String(target)).startsWith('.archify-render-')) {+ candidateDescriptor = descriptor;+ }+ return descriptor;+ });+ t.mock.method(fs, 'fstatSync', (descriptor, ...args) => {+ if (!injected && descriptor === candidateDescriptor) {+ injected = true;+ throw Object.assign(new Error('injected first candidate fstat failure'), { code: 'EIO' });+ }+ return fstatSync(descriptor, ...args);+ });++ assert.throws(() => writeWorkflow(loaded), /injected first candidate fstat failure/);+ assert.equal(fs.existsSync(output), false);+ assert.deepEqual(renderCandidates(root), []);+});+function fileSymlinksAvailable(t, root) {const target = path.join(root, 'symlink-capability-target');const link = path.join(root, 'symlink-capability-link');diff --git a/archify/test/repair-receipt.test.mjs b/archify/test/repair-receipt.test.mjsindex 0b3029b0..3f0b2045 100644--- a/archify/test/repair-receipt.test.mjs+++ b/archify/test/repair-receipt.test.mjs@@ -20,6 +20,7 @@ function run(args) {function writeFixture(name, source) {const file = path.join(tmp, name);+ if (source?.meta && source.meta.output === undefined) source.meta.output = 'fixture.html';fs.writeFileSync(file, JSON.stringify(source, null, 2));return file;}diff --git a/archify/test/update-notifier.test.mjs b/archify/test/update-notifier.test.mjsindex 8528e165..eb950041 100644--- a/archify/test/update-notifier.test.mjs+++ b/archify/test/update-notifier.test.mjs@@ -1773,6 +1773,43 @@ test('a symlink cache root cannot write into its target', async (t) => {assert.deepEqual(fs.readdirSync(protectedTarget), ['settings.json']);});+test('a cache path equal to a trusted directory through a symlink is still rejected', async (t) => {+ const testFixture = fixture();+ const originalTmpdir = os.tmpdir;+ const protectedTarget = path.join(testFixture.root, 'trusted-target');+ const authoredAlias = path.join(testFixture.root, 'trusted-alias');+ fs.mkdirSync(protectedTarget);+ fs.writeFileSync(path.join(protectedTarget, 'settings.json'), '{"protected":true}\n');+ try {+ fs.symlinkSync(+ protectedTarget,+ authoredAlias,+ process.platform === 'win32' ? 'junction' : 'dir',+ );+ } catch (error) {+ if (['EPERM', 'EACCES', 'ENOTSUP'].includes(error?.code)) {+ t.skip(`directory symlinks are unavailable: ${error.code}`);+ return;+ }+ throw error;+ }+ os.tmpdir = () => protectedTarget;+ t.after(() => {+ os.tmpdir = originalTmpdir;+ fs.rmSync(testFixture.root, { recursive: true, force: true });+ });+ let requests = 0;++ const result = await checkForUpdate(options(testFixture, async () => {+ requests += 1;+ return response(remoteRelease());+ }, { cacheDirectory: authoredAlias }));++ assert.deepEqual(result, { status: 'silent', reason: 'cache-unavailable' });+ assert.equal(requests, 0);+ assert.deepEqual(fs.readdirSync(protectedTarget), ['settings.json']);+});+test('a symlink cache ancestor cannot redirect cache writes', async (t) => {const testFixture = fixture();t.after(() => fs.rmSync(testFixture.root, { recursive: true, force: true }));@@ -1993,7 +2030,7 @@ test('a cache ancestor replacement restored after reservation creation fails cloassert.deepEqual(fs.readdirSync(path.join(replacementVersion, reservations[0])), []);});-test('a trusted cache prefix switched after validation cannot redirect later writes', async (t) => {+test('an authored symlink is rejected even when it is also reported as a trusted prefix', async (t) => {const testFixture = fixture();const originalHomedir = os.homedir;const originalLstat = fsPromises.lstat;@@ -2051,12 +2088,10 @@ test('a trusted cache prefix switched after validation cannot redirect later wricacheDirectory,}));- assert.equal(switched, true);- assert.equal(result.status, 'update_available');+ assert.equal(switched, false);+ assert.deepEqual(result, { status: 'silent', reason: 'cache-unavailable' });assert.deepEqual(fs.readdirSync(protectedTarget), ['settings.json']);- assert.ok(fs.readdirSync(canonicalVersionDirectory).some(- (entry) => entry.startsWith('committed-'),- ));+ assert.equal(fs.existsSync(canonicalVersionDirectory), false);});test('concurrent checks use one writer and leave a valid cache', async (t) => {diff --git a/archify/test/v1-compatibility.test.mjs b/archify/test/v1-compatibility.test.mjsindex 21c6f9cb..259ae21b 100644--- a/archify/test/v1-compatibility.test.mjs+++ b/archify/test/v1-compatibility.test.mjs@@ -28,7 +28,9 @@ function render(mode, doc) {function validate(mode, doc) {const input = path.join(tmp, `${mode}-validate.json`);- fs.writeFileSync(input, JSON.stringify(doc));+ const cliDoc = structuredClone(doc);+ cliDoc.meta = { ...cliDoc.meta, output: `${mode}-v1-validation.html` };+ fs.writeFileSync(input, JSON.stringify(cliDoc));try {execFileSync('node', [path.join(skillRoot, 'bin/archify.mjs'),diff --git a/archify/test/vertical-edge.test.mjs b/archify/test/vertical-edge.test.mjsindex ba13e3b2..710c7dac 100644--- a/archify/test/vertical-edge.test.mjs+++ b/archify/test/vertical-edge.test.mjs@@ -14,7 +14,11 @@ const tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'archify-vertical-edge-'));const REPRO = {schema_version: 1,diagram_type: 'dataflow',- meta: { title: 'Vertical edge arrowhead repro', quality_profile: 'showcase' },+ meta: {+ title: 'Vertical edge arrowhead repro',+ output: 'vertical-edge-arrowhead.html',+ quality_profile: 'showcase',+ },stages: [{ label: 'Parse' }, { label: 'Store' }],nodes: [{ id: 'extract', type: 'backend', label: 'Extract', stage: 0, row: 0 },diff --git a/archify/test/visual-check.test.mjs b/archify/test/visual-check.test.mjsindex b33c0589..e2e77bbd 100644--- a/archify/test/visual-check.test.mjs+++ b/archify/test/visual-check.test.mjs@@ -47,12 +47,15 @@ function fakeBrowser({ overflowAt, unreadableAt, chromeCollisionAt, stageCollisiconst calls = [];return {calls,- async inspect({ width, height, theme, screenshotPath }) {+ async inspect({ width, height, theme, screenshotPath, writeScreenshot }) {calls.push({ width, height, theme, screenshotPath });if (screenshotPath && screenshotFailure?.({ width, height, theme })) {throw new Error('synthetic screenshot failure');}- if (screenshotPath) fs.writeFileSync(screenshotPath, png, { flag: 'wx' });+ if (screenshotPath) {+ if (writeScreenshot) writeScreenshot(png);+ else fs.writeFileSync(screenshotPath, png, { flag: 'wx' });+ }const overflow = overflowAt?.({ width, height, theme }) || false;const unreadable = unreadableAt?.({ width, height, theme }) || false;const chromeCollision = chromeCollisionAt?.({ width, height, theme }) || false;@@ -299,6 +302,75 @@ test('visual-check records four containment viewports and four endpoint theme ca}});+test('visual-check inspects a private snapshot even if the public artifact is replaced and restored', async () => {+ const input = artifact('private-inspection-snapshot.html');+ const original = fs.readFileSync(input);+ const displaced = path.join(tmp, 'private-inspection-original.html');+ const replacement = Buffer.from('<!doctype html><title>replacement must not be inspected</title>');+ const browser = fakeBrowser();+ const inspect = browser.inspect.bind(browser);+ const inspectedPaths = [];+ let calls = 0;+ browser.inspect = async (args) => {+ inspectedPaths.push(path.resolve(args.artifactPath));+ assert.deepEqual(fs.readFileSync(args.artifactPath), original);+ calls += 1;+ if (calls === 1) {+ fs.renameSync(input, displaced);+ fs.writeFileSync(input, replacement, { flag: 'wx' });+ }+ if (calls === 6) {+ fs.unlinkSync(input);+ fs.renameSync(displaced, input);+ }+ return inspect(args);+ };++ const result = await runVisualCheck({+ artifactPath: input,+ chromePath: '/fake/chrome',+ browserFactory: async () => browser,+ });++ assert.equal(result.exitCode, 0, JSON.stringify(result.receipt.diagnostics));+ assert.equal(inspectedPaths.length, 6);+ assert.equal(inspectedPaths.every((candidate) => candidate !== path.resolve(input)), true);+ assert.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 });+ }+ });++ 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);+});+test('sidecarPaths places outputs in outDir instead of beside the artifact', () => {const input = artifact('outdir-source.html');const separateDir = path.join(tmp, 'evidence-nested', 'deeper');diff --git a/archify/test/workflow-compiler.test.mjs b/archify/test/workflow-compiler.test.mjsindex 1b32bfff..8b707fa6 100644--- a/archify/test/workflow-compiler.test.mjs+++ b/archify/test/workflow-compiler.test.mjs@@ -198,6 +198,7 @@ function adjacentWorkflow({nodeLabels = ['A', 'B'],viewBox,frames = false,+ output,} = {}) {const workflow = {schema_version: 2,@@ -206,6 +207,7 @@ function adjacentWorkflow({title: `Adjacent ranks ${fromCol} to ${toCol}`,legend: { mode: 'hidden' },...(viewBox ? { viewBox } : {}),+ ...(output ? { output } : {}),},lanes: [{ id: 'main', label: 'Main' }],nodes: [@@ -1322,6 +1324,7 @@ test('CLI validate workflow --layout-json prints the stable compiler receipt', (fromCol: 3,label: 'liga',viewBox: [1080, 420],+ output: 'layout-json.html',})));const result = spawnSync(process.execPath, [@@ -1348,7 +1351,11 @@ test('CLI validate workflow --layout-json returns only the causal compiler failufs.writeFileSync(input, JSON.stringify({schema_version: 1,diagram_type: 'workflow',- meta: { title: 'Issue 126 failure receipt', legend: { mode: 'hidden' } },+ meta: {+ title: 'Issue 126 failure receipt',+ output: 'layout-json-failure.html',+ legend: { mode: 'hidden' },+ },lanes: [{ id: 'main', label: 'Main' }],nodes: [{ id: 'a', lane: 'main', col: 1, type: 'backend', label: 'A' },diff --git a/archify/test/workflow-migration.test.mjs b/archify/test/workflow-migration.test.mjsindex c0ab2ebf..93178b50 100644--- a/archify/test/workflow-migration.test.mjs+++ b/archify/test/workflow-migration.test.mjs@@ -75,6 +75,7 @@ function explicitPinConflictWorkflow() {diagram_type: 'workflow',meta: {title: 'Unmappable explicit label pin',+ output: 'unmappable-explicit-label-pin.html',viewBox: [900, 420],legend: { mode: 'hidden' },},@@ -99,6 +100,7 @@ function heightConstrainedWorkflow() {diagram_type: 'workflow',meta: {title: 'Legacy height capacity',+ output: 'legacy-height-capacity.html',viewBox: [720, 240],legend: { mode: 'hidden' },},@@ -120,6 +122,7 @@ function profileDivergenceWorkflow() {diagram_type: 'workflow',meta: {title: 'profile divergence',+ output: 'profile-divergence.html',quality_profile: 'showcase',legend: { mode: 'hidden' },},@@ -494,7 +497,12 @@ test('fallback planning preserves straight-edge rank constraints when mapping abconst document = {schema_version: 1,diagram_type: 'workflow',- meta: { title: 'Fallback rank mapping', viewBox: [720, 520], legend: { mode: 'hidden' } },+ meta: {+ title: 'Fallback rank mapping',+ output: 'fallback-rank-mapping.html',+ viewBox: [720, 520],+ legend: { mode: 'hidden' },+ },lanes: [{ id: 'pin', label: 'Pinned label' },{ id: 'straight', label: 'Straight constraint' },diff --git a/examples/checkout-platform-delta.receipt.json b/examples/checkout-platform-delta.receipt.jsonindex a2d570f5..cdbb5873 100644--- a/examples/checkout-platform-delta.receipt.json+++ b/examples/checkout-platform-delta.receipt.json@@ -9,15 +9,15 @@"proofLevel": "authored","base": {"title": "Checkout Platform — Baseline",- "rawSha256": "c112195e7285e3e4aedaeab3e1f85f5891d30fccc2c260aebe4e1da12c80cf84",+ "rawSha256": "81d55a2e86fc39f6473b32dfba986a12d3b7a705a95821844865b1dc831c9fe7","semanticSha256": "5d2f362ed389af82b117a01d36201e27cb83503093b14c50f7cd8dada55f243a",- "bytes": 2234+ "bytes": 2279},"head": {"title": "Checkout Platform — Fraud Gate",- "rawSha256": "e3aaf47f77afeadafc81c6ce853dc1df68cc1e6932dec972cf478f4008fdda99",+ "rawSha256": "eb4ae056035dd3316414a5d7f6599525107b5d1af7bedbd905460ade77daf5c6","semanticSha256": "0b378c8f24d23ec63feecacd7ff84a4944534f4306fc2b7e3266dff9ba258852",- "bytes": 2368+ "bytes": 2413},"summary": {"components": {diff --git a/scripts/copy-site-assets.mjs b/scripts/copy-site-assets.mjsindex 53a97db6..00e6dc77 100644--- a/scripts/copy-site-assets.mjs+++ b/scripts/copy-site-assets.mjs@@ -43,7 +43,18 @@ function stageSiteAsset(source, commitPath, mode) {fs.constants.O_WRONLY | fs.constants.O_CREAT | fs.constants.O_EXCL | noFollow,mode ?? 0o666,);- const metadata = fs.fstatSync(descriptor, { bigint: true });+ let metadata;+ try {+ metadata = fs.fstatSync(descriptor, { bigint: true });+ } catch (error) {+ try {+ const retry = fs.fstatSync(descriptor, { bigint: true });+ if (retry.isFile() && retry.ino !== 0n) {+ identity = { device: retry.dev, inode: retry.ino };+ }+ } catch {}+ throw error;+ }if (!metadata.isFile() || metadata.ino === 0n) {throw new Error('Temporary site asset identity could not be verified safely.');}diff --git a/scripts/package-smoke.mjs b/scripts/package-smoke.mjsindex 02654f47..829e775c 100644--- a/scripts/package-smoke.mjs+++ b/scripts/package-smoke.mjs@@ -253,7 +253,12 @@ try {const legacyWorkflow = {schema_version: 1,diagram_type: 'workflow',- meta: { title: 'Package migration smoke', viewBox: [720, 400], legend: { mode: 'hidden' } },+ meta: {+ title: 'Package migration smoke',+ output: 'package-migration-smoke.html',+ viewBox: [720, 400],+ legend: { mode: 'hidden' },+ },lanes: [{ id: 'main', label: 'Main' }],nodes: [{ id: 'source', lane: 'main', col: 0, type: 'frontend', label: 'Source' },@@ -342,7 +347,7 @@ try {const tangentEndpoint = {schema_version: 1,diagram_type: 'architecture',- meta: { title: 'Endpoint direction smoke' },+ meta: { title: 'Endpoint direction smoke', output: 'endpoint-direction-smoke.html' },components: [{ id: 'source', type: 'external', label: 'Source', pos: [300, 100], size: [100, 60] },{ id: 'target', type: 'backend', label: 'Target', pos: [100, 240], size: [100, 60] },@@ -370,7 +375,7 @@ try {const inferredBridge = {schema_version: 1,diagram_type: 'architecture',- meta: { title: 'Inferred endpoint bridge smoke' },+ meta: { title: 'Inferred endpoint bridge smoke', output: 'inferred-endpoint-bridge.html' },components: [{ id: 'workspace', type: 'frontend', label: 'Workspace UI', pos: [40, 300], size: [120, 60] },{ id: 'runtime-server', type: 'backend', label: 'Runtime Server', pos: [220, 300], size: [120, 60] },diff --git a/scripts/run-windows-path-tests.mjs b/scripts/run-windows-path-tests.mjsindex c983e259..4849dbdb 100644--- a/scripts/run-windows-path-tests.mjs+++ b/scripts/run-windows-path-tests.mjs@@ -7,6 +7,8 @@ import path from 'node:path';import { fileURLToPath } from 'node:url';import { sameLocation } from '../archify/renderers/shared/path-semantics.mjs';+import { checkForUpdate } from '../archify/scripts/check-update.mjs';+import { stageCleanSkill } from './stage-clean-skill.mjs';const repoRoot = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');const skillRoot = path.join(repoRoot, 'archify');@@ -115,6 +117,8 @@ async function runControlledWindowsPathE2E() {const token = `archify-windows-${process.pid}-${Date.now().toString(36)}`;const architectureInput = path.join(skillRoot, 'examples', 'web-app.architecture.json');const workflowInput = path.join(skillRoot, 'examples', 'agent-tool-call.workflow.json');+ const comparisonBase = path.join(skillRoot, 'examples', 'checkout-platform.base.architecture.json');+ const comparisonHead = path.join(skillRoot, 'examples', 'checkout-platform.head.architecture.json');let preview;try {const aliasRoot = path.join(caseRoot, `${token}-native-aliases`);@@ -168,6 +172,30 @@ async function runControlledWindowsPathE2E() {requireSuccess('strict check through drive-letter case alias', strictDriveCaseCheck);assert.equal(JSON.parse(strictDriveCaseCheck.stdout).provenance, 'current');+ const driveCaseRepoRoot = driveLetterCaseAlias(repoRoot);+ const revision = spawnSync('git', ['-C', repoRoot, 'rev-parse', 'HEAD'], {+ encoding: 'utf8',+ });+ requireSuccess('repository revision discovery', revision);+ const evidenceDiagram = JSON.parse(fs.readFileSync(architectureInput, 'utf8'));+ evidenceDiagram.meta.repository = {+ url: 'https://github.com/tt-a1i/archify',+ revision: revision.stdout.trim(),+ };+ evidenceDiagram.components[0].sources = [{+ path: 'archify/bin/archify.mjs',+ line: 1,+ label: 'CLI entry point',+ }];+ const evidenceInput = path.join(caseRoot, `${token}-repository-evidence.architecture.json`);+ fs.writeFileSync(evidenceInput, `${JSON.stringify(evidenceDiagram, null, 2)}\n`);+ const repositoryValidation = runCli([+ 'validate', 'architecture', evidenceInput,+ '--repo-root', driveCaseRepoRoot, '--json',+ ]);+ requireSuccess('repository root through drive-letter case alias', repositoryValidation);+ assert.equal(JSON.parse(repositoryValidation.stdout).ok, true);+const ordinaryRender = path.win32.join(uncRoot, `${token}-ordinary-render.html`);const extendedRender = path.win32.join(extendedUncRoot, `${token}-extended-render.html`);requireSuccess('ordinary UNC render', runCli([@@ -210,6 +238,58 @@ async function runControlledWindowsPathE2E() {requireSuccess('strict check through ordinary UNC alias', strictOrdinaryCheck);assert.equal(JSON.parse(strictOrdinaryCheck.stdout).provenance, 'current');+ const compareOutput = path.win32.join(extendedUncRoot, `${token}-compare.html`);+ const compared = runCli([+ 'compare', 'architecture', comparisonBase, comparisonHead, compareOutput, '--json',+ ]);+ requireSuccess('architecture compare to extended UNC', compared);+ assert.equal(JSON.parse(compared.stdout).ok, true);+ assert.ok(fs.existsSync(path.win32.join(uncRoot, path.win32.basename(compareOutput))));++ const stagedSkill = path.win32.join(uncRoot, `${token}-staged-skill`);+ stageCleanSkill({ repoRoot: driveCaseRepoRoot, destination: stagedSkill });+ assert.ok(fs.existsSync(path.join(stagedSkill, 'renderers', 'shared', 'sidecar-path.mjs')));++ const localRelease = JSON.parse(fs.readFileSync(path.join(skillRoot, 'skill-release.json'), 'utf8'));+ localRelease.channel = 'stable';+ localRelease.version = '2.15.0';+ const releasePath = path.join(caseRoot, `${token}-skill-release.json`);+ fs.writeFileSync(releasePath, `${JSON.stringify(localRelease)}\n`);+ const stableManifest = fs.readFileSync(+ path.join(repoRoot, 'docs', 'skill-updates', 'archify', 'stable.json'),+ 'utf8',+ );+ const updateCache = path.win32.join(eightDotThreeShortRoot, `${token}-update-cache`);+ const update = await checkForUpdate({+ releasePath,+ cacheDirectory: updateCache,+ fetchImpl: async () => new Response(stableManifest, {+ status: 200,+ headers: {+ 'content-type': 'application/json',+ etag: `"${token}"`,+ },+ }),+ now: () => Date.parse('2026-09-18T12:00:00Z'),+ random: () => 0.5,+ });+ assert.equal(update.status, 'update_available');++ let longDirectory = extendedUncRoot;+ for (let index = 0; longDirectory.length <= 320; index += 1) {+ longDirectory = path.win32.join(longDirectory, `${token.slice(0, 24)}-${index}-long-path`);+ }+ fs.mkdirSync(longDirectory, { recursive: true });+ const longOutput = path.win32.join(longDirectory, 'diagram.html');+ assert.ok(longOutput.length > 320, 'controlled path must exceed the traditional MAX_PATH limit');+ const longDelivery = runCli([+ 'deliver', 'workflow', workflowInput, longOutput,+ '--quality', 'showcase', '--json',+ ]);+ requireSuccess('delivery beyond traditional MAX_PATH', longDelivery);+ assert.equal(JSON.parse(longDelivery.stdout).ok, true);+ assert.ok(fs.existsSync(longOutput));+const evidenceDirectory = path.win32.join(uncRoot, `${token}-visual-evidence`);const visual = runCli(['visual-check', ordinaryDelivery, '--json', '--require-provenance',@@ -313,7 +393,7 @@ const portabilityPattern = ['updater rejects a case-only alias','symlink cache root','symlink cache ancestor',- 'trusted cache prefix switched',+ 'authored symlink is rejected|trusted directory through a symlink','findChrome','visual-check','doctor identifies an incomplete installation',diff --git a/scripts/stage-clean-skill.mjs b/scripts/stage-clean-skill.mjsindex 1dca77b0..c8f44cff 100644--- a/scripts/stage-clean-skill.mjs+++ b/scripts/stage-clean-skill.mjs@@ -23,6 +23,7 @@ const RUNTIME_DEPENDENCIES = Object.freeze(['archify/renderers/shared/output-path.mjs','archify/renderers/shared/path-semantics.mjs','archify/renderers/shared/portable-path.mjs',+ 'archify/renderers/shared/sidecar-path.mjs',]);const EXCLUDED_FILES = new Set(['archify/package-lock.json',diff --git a/scripts/write-deterministic-zip.mjs b/scripts/write-deterministic-zip.mjsindex 074d5813..57156daf 100644--- a/scripts/write-deterministic-zip.mjs+++ b/scripts/write-deterministic-zip.mjs@@ -269,7 +269,18 @@ try {fs.constants.O_WRONLY | fs.constants.O_CREAT | fs.constants.O_EXCL | noFollow,0o666,);- const candidateMetadata = fs.fstatSync(descriptor, { bigint: true });+ let candidateMetadata;+ try {+ candidateMetadata = fs.fstatSync(descriptor, { bigint: true });+ } catch (error) {+ try {+ const retry = fs.fstatSync(descriptor, { bigint: true });+ if (retry.isFile() && retry.ino !== 0n) {+ candidateIdentity = { device: retry.dev, inode: retry.ino };+ }+ } catch {}+ throw error;+ }if (!candidateMetadata.isFile() || candidateMetadata.ino === 0n) {throw new Error(`archive candidate identity is unavailable: ${temporary}`);}