# Understanding the Archify Delivery Contract and Atomic Commit Mechanism

> Learn about the Archify delivery contract a three-phase pipeline that ensures safe atomic commit of HTML artifacts after successful JSON validation and receipt generation.

- Repository: [tt-a1i/archify](https://github.com/tt-a1i/archify)
- Tags: internals
- Published: 2026-08-04

---

**The Archify delivery contract is a three-phase pipeline that validates JSON specifications, generates cryptographic receipts, and atomically commits HTML artifacts only after all verification steps pass, guaranteeing that partial or failed renders never corrupt existing trusted outputs.**

The Archify delivery contract defines the authoritative specification for transforming design-time JSON into trusted HTML artifacts within the `tt-a1i/archify` repository. This contract ensures **safety** through fail-fast validation, **traceability** via SHA-256 hashes, and **reliability** using filesystem-level atomic operations. Understanding how the Archify delivery contract implements atomic commits is essential for anyone deploying architecture diagrams in production environments.

## What Is the Archify Delivery Contract?

The Archify delivery contract specifies a rigorous three-phase pipeline that governs how the tool converts specification files into published artifacts:

1. **Validate & render** – The JSON specification is read, validated against the schema, and rendered to a temporary candidate file.
2. **Deterministic receipt** – The system produces a receipt containing SHA-256 hashes and byte counts for both the original specification and the rendered artifact.
3. **Atomic commit** – Only after the receipt passes all artifact-checking steps does Archify rename the candidate to the final output, ensuring the previous trusted artifact is never overwritten on failure.

This workflow matters because it provides **safety** (aborts and leaves existing output untouched if any step fails), **traceability** (proves byte-level identity through `specification_sha256` and `artifact_sha256`), and controlled **preview capabilities** (the `--open` flag runs only after the atomic commit succeeds).

## How Atomic Commit Works in Archify

The atomic commit implementation lives in `archify/bin/archify.mjs` within the `commandDeliver` function. The code enforces an all-or-nothing delivery through six critical steps:

### Create a Same-Filesystem Staging Directory

Archify creates a staging folder adjacent to the target path so the final rename constitutes a single filesystem operation. As implemented in lines 40-44:

```javascript
// Keep the candidate beside the target so the final rename is one
// same-filesystem commit. A render or artifact-check failure never touches
// an existing trusted output.
const stagingDirectory = fs.mkdtempSync(path.join(outputDirectory, '.archify-delivery-'));

```

This placement ensures `fs.renameSync` operates atomically.

### Freeze the Specification

The tool writes an immutable snapshot of the input specification using the `wx` flag, which prevents accidental overwrites (lines 70-73):

```javascript
// Write specification.snapshot.json with wx flag
fs.writeFileSync(specPath, JSON.stringify(specification), { flag: 'wx' });

```

### Render and Validate the Candidate

The renderer generates the HTML artifact and runs the artifact-checker. If either step fails, `reportDeliveryFailure` is invoked and the function returns before any rename occurs (lines 95-108, 122-134). This prevents corrupted renders from reaching the output path.

### Parse and Verify the Receipt

The artifact-checker writes a deterministic receipt that Archify parses for validation. If receipt parsing fails, delivery aborts immediately (lines 140-155):

```javascript
const receipt = JSON.parse(fs.readFileSync(receiptPath, 'utf8'));
if (!receipt.ok) {
  throw new Error(`Artifact check failed: ${receipt.error}`);
}

```

### Generate the Final Receipt

Upon successful validation, Archify generates the definitive receipt (lines 1000-1030) containing:

- `specification.sha256` and `artifact.sha256` for byte-level verification
- Validation counts (`checksPassed`, `checkCount`)
- Composition profile and status
- Optional repository evidence

### Perform the Atomic Rename

The commit executes via `fs.renameSync(candidatePath, outputPath)` (lines 61-63). Because the candidate resides on the same filesystem as the target, this rename is atomic—it either completely replaces the old file or leaves it untouched, with no intermediate state visible to other processes.

### Cleanup and Safety Guarantees

A `finally` block (lines 9-13) ensures the staging directory is cleaned up regardless of success or failure. If any step throws, the original output remains unchanged and the candidate is discarded.

## Practical Usage Examples

### Deliver a Diagram with Contract Enforcement

Run the full delivery pipeline to render an architecture diagram and atomically commit the result:

```bash
node bin/archify.mjs deliver architecture diagram.json \
    output.html --quality showcase --json

```

This command reads [`diagram.json`](https://github.com/tt-a1i/archify/blob/main/diagram.json), validates the schema, renders the HTML, runs artifact checks, and renames the candidate to [`output.html`](https://github.com/tt-a1i/archify/blob/main/output.html) only if all steps succeed.

### Use the Optional Preview Flag

Trigger a local OS opener after the atomic commit completes:

```bash
node bin/archify.mjs deliver architecture diagram.json \
    output.html --quality showcase --open

```

The `--open` flag executes **after** the atomic rename, ensuring that preview failures cannot corrupt the published artifact.

### Inspect the Delivery Receipt

Generate a JSON receipt to audit the delivery:

```bash
node bin/archify.mjs deliver architecture diagram.json \
    output.html --quality showcase --json

```

The receipt provides cryptographic proof of integrity:

```json
{
  "schemaVersion": 1,
  "ok": true,
  "command": "deliver",
  "type": "architecture",
  "output": "/abs/path/output.html",
  "specification": { "sha256": "c1a2…", "bytes": 1234 },
  "artifact":      { "sha256": "d4e5…", "bytes": 5678 },
  "validation": {
    "checksPassed": 9,
    "checkCount": 9,
    "compositionProfile": "showcase",
    "compositionStatus": "passed"
  }
}

```

## Key Implementation Files

The Archify delivery contract and atomic commit mechanism are implemented across the following files:

- **[`archify/references/delivery-contract.md`](https://github.com/tt-a1i/archify/blob/main/archify/references/delivery-contract.md)** – Human-readable specification describing the delivery pipeline, receipt format, and optional opening behavior.
- **`archify/bin/archify.mjs`** – CLI entry point containing the `commandDeliver` function that enforces atomic commit logic.
- **`archify/scripts/check-render-output.mjs`** – Artifact checker invoked during delivery; produces the deterministic receipt used for validation.
- **`archify/renderers/shared/output-path.mjs`** – Resolves safe output paths and ensures the staging directory resides on the same filesystem as the final target.
- **`archify/open-artifact.mjs`** – Handles the optional `--open` step, executing only after successful atomic commit.

## Summary

- The **Archify delivery contract** enforces a three-phase pipeline: validate and render, generate deterministic receipts, and atomically commit only after all checks pass.
- **Atomic commits** use same-filesystem staging directories (prefixed with `.archify-delivery-`) to ensure single-operation replacements via `fs.renameSync`.
- **SHA-256 hashes** in the receipt provide byte-level audit trails for both specifications and artifacts, enabling complete traceability.
- The **`--open` flag** executes only after successful commit, preventing preview operations from influencing delivery outcomes.
- **Failure handling** ensures staging cleanup and preserves existing trusted artifacts if any validation, rendering, or receipt-parsing step fails.

## Frequently Asked Questions

### What happens if the artifact checker fails during delivery?

If the artifact checker fails, `commandDeliver` invokes `reportDeliveryFailure` and returns immediately before reaching the rename operation. The staging directory is cleaned up in the `finally` block, and the existing output file remains untouched, maintaining the integrity of the previously trusted artifact.

### Why must the staging directory be created next to the target output?

Creating the staging directory adjacent to the final output (using `path.join(outputDirectory, '.archify-delivery-')`) ensures that the candidate file and target file reside on the same filesystem. This allows `fs.renameSync` to perform an atomic operation that is instantaneous and immune to interruption, rather than requiring a copy-and-delete sequence that could leave partial files.

### How does the receipt prove artifact integrity?

The receipt contains `specification.sha256` and `artifact.sha256` fields that uniquely identify the exact bytes of the input JSON and output HTML. By comparing these hashes across deliveries, auditors can verify that a specific specification produced a specific artifact, and that no byte-level corruption occurred during the render process.

### Can the atomic commit mechanism be disabled or bypassed?

No, the atomic commit is a core enforcement mechanism of the Archify delivery contract and cannot be disabled through CLI flags. The contract mandates that all artifact-checking steps must pass before `fs.renameSync` executes, ensuring that broken renders, validation failures, or corrupted receipts never overwrite existing trusted outputs.