# How Archify Live Preview Mode Works: Technical Deep Dive into the Real-Time Diagram Authoring Loop

> Explore Archify's live preview mode technical deep dive. Discover how this zero-dependency authoring loop regenerates diagrams in real-time from JSON without exposing state.

- Repository: [tt-a1i/archify](https://github.com/tt-a1i/archify)
- Tags: deep-dive
- Published: 2026-08-06

---

**Archify's live preview mode is a zero-dependency, desktop-only authoring loop that continuously watches a JSON source file, regenerates diagrams on verified changes, and updates a local iframe without exposing state to the final artifact.**

The live preview system in **Archify** (`tt-a1i/archify`) enables iterative diagram development through an isolated, secure feedback loop. This feature—implemented entirely in the CLI binary—lets authors see changes immediately while guaranteeing that broken or incomplete edits never corrupt the visible output.

## Architecture Overview of the Preview Loop

The live preview system lives in `archify/bin/preview.mjs` and is invoked through the CLI entry point `archify/bin/archify.mjs` via the `archify preview` command. The architecture follows seven strict design principles that prioritize stability, security, and performance.

### Local-Only Server Binding

When preview starts, the system binds to a random **127.0.0.1** port and creates a private staging directory with the pattern `.archify-preview-*`. The server exposes exactly two endpoints: [`/artifact.html`](https://github.com/tt-a1i/archify/blob/main//artifact.html) (the current rendered diagram) and a minimal status shell. No external hosts, path traversal, or write requests are ever accepted—eliminating entire classes of remote attack surface.

### Dual-Strategy File Watching

Archify watches the source JSON file through two independent mechanisms working in concert:

- **`fs.watch`** (or equivalent debounce-aware watcher) for immediate change detection
- **SHA-256 digest polling** at configurable intervals for content verification

This dual strategy ensures that rapid rename bursts, editor atomic-save patterns, or missed native file system events all converge on the same stable source state.

### Generation Snapshots and Verification Gating

Every stable change creates a **generation snapshot** capturing the exact source bytes. This snapshot feeds directly into the existing `deliver` pipeline—the same atomic builder used for standard renders. After rendering completes, the artifact must pass all **composition gates**; only when status reaches **verified** does the preview replace the iframe content and increment the displayed revision counter.

## The "Last-Good" Fallback Strategy

The live preview mode's most critical reliability feature is its **last-good fallback behavior**. Invalid, missing, half-written, or failed generations never corrupt the visible preview.

| Scenario | Behavior |
|----------|----------|
| Source file temporarily missing | Previous verified artifact remains visible |
| JSON parse error | Previous verified artifact remains visible; error shown in status panel |
| Render pipeline failure | Previous verified artifact remains visible; diagnostics displayed |
| Identical source digest | Ignored—no rebuild triggered |
| Identical artifact bytes | Ignored—no iframe reload |

This guarantees that authors always see a working diagram even during active editing, with diagnostic feedback available through the status panel rather than broken renders.

## CLI Usage and Command Syntax

Start a live preview session using the `archify preview` command:

```bash

# Basic architecture diagram preview

archify preview architecture model.json preview.html

# Mind map with quality and browser control

archify preview mindmap story.json out.html --quality showcase --no-open

# Specify repository root for relative path resolution

archify preview architecture model.json preview.html --repo-root /my/project

```

The command accepts the following key options:

- `type` — renderer type (`architecture`, `mindmap`, or other registered types)
- `input` — path to source JSON file
- `output` — optional output path for final artifact
- `--quality` — render quality preset
- `--no-open` — suppress automatic browser launch
- `--repo-root` — base directory for relative path resolution

## Programmatic API: `startPreview`

Internal tooling and test suites can import the preview system directly from `archify/bin/preview.mjs`:

```javascript
import { startPreview } from 'archify/bin/preview.mjs';

const preview = await startPreview({
  type: 'architecture',      // renderer type
  input: 'model.json',       // source JSON file to watch
  output: 'preview.html',    // optional output path
  open: true,                // auto-open browser window
  debounceMs: 100,           // file-watch event debounce
  pollMs: 500,               // content-digest poll interval
});

```

The returned preview object exposes a minimal, promise-based interface:

```javascript
// Graceful shutdown with in-flight delivery draining
await preview.stop();

// Base URL of the running preview server
const state = await preview.url;

```

### Configuration Parameters

| Parameter | Default | Purpose |
|-----------|---------|---------|
| `debounceMs` | 100ms | Coalesces rapid file system events from atomic editors |
| `pollMs` | 500ms | Guarantees eventual consistency via content digest |

## Graceful Shutdown and Resource Cleanup

On **SIGINT** or **SIGTERM**, the preview system executes a deterministic cleanup sequence:

1. Drain any in-flight delivery operations
2. Stop the loopback HTTP server
3. Remove the temporary staging directory (`.archify-preview-*`)
4. Exit with appropriate status code

This ensures no orphaned processes or temporary directories remain after interruption.

## Security and Isolation Guarantees

The Archify live preview mode maintains strict boundaries:

- **Zero runtime dependencies** — No additional libraries added to generated HTML, SVG, WebM, or Share Card artifacts
- **No state leakage** — Preview infrastructure never serializes into final outputs
- **Desktop-only operation** — Explicitly excluded from server or CI environments
- **No network exposure** — Loopback-only binding prevents external access

These guarantees are validated by the test suite in `archify/test/preview-contract.test.mjs`.

## File Reference Map

| File Path | Responsibility |
|-----------|---------------|
| `archify/bin/preview.mjs` | Core implementation: server, watcher, digest polling, delivery orchestration, last-good logic |
| `archify/bin/archify.mjs` | CLI entry point; argument parsing and `startPreview` invocation |
| `archify/test/preview.test.mjs` | Functional tests for watching, verification, fallback, deduplication, shutdown |
| `archify/test/preview-contract.test.mjs` | Architectural contract tests: desktop-only, explicit opt-in, last-good preservation |
| [`ROADMAP.md`](https://github.com/tt-a1i/archify/blob/main/ROADMAP.md) — *Live Preview* section | Design goals and security guarantees |
| [`CHANGELOG.md`](https://github.com/tt-a1i/archify/blob/main/CHANGELOG.md) — *Last-Good Live Preview* entry | v2.13 feature summary |
| [`README.md`](https://github.com/tt-a1i/archify/blob/main/README.md) — Preview table row | User-facing feature description |

## Summary

- **Archify live preview mode** provides real-time diagram feedback through a local-only, zero-dependency authoring loop in `archify/bin/preview.mjs`
- **Dual-strategy watching** (`fs.watch` + SHA-256 digest polling) ensures reliable change detection across all editor behaviors
- **Verification gating** guarantees only validated artifacts reach the preview iframe
- **Last-good fallback** preserves working output when sources are broken or incomplete
- **Graceful shutdown** with full resource cleanup protects against interruption artifacts

## Frequently Asked Questions

### What happens if I save a file with syntax errors during live preview?

The preview iframe **retains the last verified artifact** and continues displaying it. Error diagnostics appear in the status panel, but the diagram remains visible. Once you fix the error and the source stabilizes, a new verified generation replaces the iframe content.

### Can I run Archify live preview on a remote server or in CI?

**No.** The live preview mode is explicitly designed as **desktop-only** according to `archify/test/preview-contract.test.mjs`. The loopback-only server binding (`127.0.0.1`) and temporary staging directory architecture assume local, interactive use. For CI or server environments, use standard `archify render` commands.

### How does the preview avoid rebuilding on every keystroke?

Two **deduplication layers** prevent unnecessary work: identical source digests skip the render pipeline entirely, and identical artifact bytes skip iframe reload. The `debounceMs` parameter (default 100ms) additionally coalesces rapid events from atomic-save editors.

### Is any preview infrastructure included in the final output files?

**No.** The preview system is **zero-dependency** with respect to generated artifacts. The loop in `archify/bin/preview.mjs` manages its own HTTP server and staging directory completely outside the `deliver` pipeline. Final HTML, SVG, WebM, and Share Card outputs contain no preview code, state, or references.