# Understanding the Archify Delta Module Architecture for Comparing Architecture Snapshots

> Explore the Archify delta module architecture. This multi-layered pipeline deterministically compares architecture snapshots, generating detailed receipts and interactive visualizations of all changes.

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

---

**The Archify delta module provides a deterministic, multi-layered pipeline that compares two architecture JSON snapshots and produces both a machine-readable receipt and an interactive SVG/HTML visualization of every change.**

The **delta module** in `archify/delta/architecture-delta.mjs` is the core engine behind Archify's snapshot comparison capabilities. It transforms raw architecture snapshots into a stable, comparable format, detects precisely what changed between versions, and renders those differences into a self-contained HTML artifact. This article examines the module's layered architecture, data flow, and key implementation patterns drawn directly from the `tt-a1i/archify` source code.

## The Seven-Layer Architecture of the Delta Module

### 1. Normalization: Creating Stable, Comparable Representations

Before any comparison occurs, snapshots must become order-independent. The normalization layer handles this through `canonicalArchitecture`, `canonicalArchitectureJson`, and specialized normalizers for each entity type.

```javascript
// From archify/delta/architecture-delta.mjs
import { canonicalArchitecture } from './archify/delta/architecture-delta.mjs';

const canonical = canonicalArchitecture(rawSnapshot);
// Strips irrelevant fields, sorts arrays and object keys

```

**Key functions in this layer:**

- **`canonicalArchitecture`** – Top-level canonicalization entry point
- **`normalizeRepository`** – Strips volatile metadata while preserving identity fields
- **`normalizeComponent`** and **`normalizeBoundary`** – Entity-specific normalization rules

This canonicalization guarantees that two semantically identical snapshots produce identical internal representations regardless of JSON formatting or field ordering.

### 2. Indexing & Validation: Establishing Stable Identities

The module refuses to compare incomparable snapshots. The indexing layer creates `Map` structures keyed by stable identifiers and validates structural compatibility.

```javascript
// Stable indexing creates lookup maps
const componentMap = stableIndex(canonical.components);  // keyed by `id`
const boundaryMap = boundaryIndex(canonical.boundaries); // keyed by `kind+label`

```

**Critical validation via `requireComparableShape`:**

- Rejects snapshots with mismatched repository origins
- Throws `ArchitectureDeltaError` with code `delta/repository-mismatch` when base and head derive from different repos
- Enforces ID uniqueness; duplicates trigger `delta/relationship-id-required`

### 3. Change Detection: Classifying Every Difference

The comparison engine iterates over the union of all entity IDs, analyzing what changed and how.

**`compareEntities`** performs the core iteration, delegating to:

- **`fieldChanges`** – Detects which specific fields differ between matching entities
- **`statusFor`** – Translates field changes into high-level statuses: `added`, `removed`, `changed`, `moved`, `unchanged`

Changes are categorized into four semantic groups:

| Classification | Meaning | Visual Marker |
|----------------|---------|---------------|
| **semantic** | Business logic changes (names, types) | `~` |
| **evidence** | Documentation or metadata updates | `E` |
| **geometry** | Position, size, or layout changes | `↔` |
| **topology** | Connection endpoints altered | `~` |

### 4. Receipt Construction: The Single Source of Truth

The **`compareArchitecture`** function serves as the module's main entry point. It aggregates all detected changes into a comprehensive receipt object:

```javascript
import { compareArchitecture } from './archify/delta/architecture-delta.mjs';

const receipt = compareArchitecture(baseSnapshot, headSnapshot);
// Returns: { summary, components, connections, boundaries, proofLevel, provenance }

```

**Receipt structure:**

- **`summary`** – Aggregated counts (`added`, `changed`, `moved`, `removed`, `unchanged`)
- **`proofLevel`** – Either `revision-pinned` (both snapshots have verified SHA-1s) or `authored` (unverified)
- **Per-entity arrays** – Each change includes `id`, `status`, `classifications`, and `fieldChanges`

### 5. SVG Extraction & Annotation: Preparing Visual Assets

Architecture snapshots embed SVG visualizations. The module extracts and enriches these for delta rendering.

**Key functions:**

- **`extractArchitectureSvg`** – Pulls the primary `<svg>` element from snapshot HTML
- **`annotateArchitectureSideSvg`** – Walks the DOM, adding data attributes:

```javascript
// Applied to each node/edge in the head SVG
element.setAttribute('data-delta-state', 'changed');
element.setAttribute('data-delta-classifications', 'geometry,semantic');

```

**Helper utilities:**

- **`addState`** – Sets the delta state attribute
- **`addNodeMarker`** – Injects visual change indicators
- **`prefixSvgIds`** – Ensures ID uniqueness across merged views

### 6. Delta SVG Assembly: Building the Visual Diff

The **`buildDeltaSvg`** function creates a unified visualization:

1. Takes annotated base and head SVGs
2. Creates **phantom elements** for removed or moved items (preserved from base as semi-transparent overlays)
3. Injects marker symbols (`+`, `−`, `↔`, `E`) at change locations
4. Merges into a single navigable view

```javascript
const deltaSvg = buildDeltaSvg(baseSvg, headSvg, receipt);
// Returns: DocumentFragment containing the merged, annotated SVG

```

Phantom elements ensure users can see what disappeared—critical for reviewing deletions.

### 7. HTML Rendering: The Self-Contained Artifact

**`renderArchitectureDeltaHtml`** produces the final deliverable: a standalone HTML file with no external dependencies.

```javascript
const html = renderArchitectureDeltaHtml({
  receipt,           // Embedded as JSON in a <script> tag
  baseSvg,           // For side-by-side view
  headSvg,           // For side-by-side view
  deltaSvg,          // The merged diff view
  artifactCss        // Inlined styles
});

```

**Included UI controls:**

- View switching (delta vs. side-by-side)
- Change list with filtering
- Legend explaining markers
- Export functionality

## Runtime Validation: Ensuring Artifact Integrity

The module includes **`validateArchitectureDeltaHtml`** for verifying generated artifacts. This function, exercised extensively in `archify/delta/architecture-delta.test.mjs`, checks:

- No duplicate IDs across merged SVGs
- All nodes have required `data-delta-state` attributes
- Receipt signatures match embedded data
- Phantom elements correctly reference removed entities

Validation failures indicate corrupted or tampered artifacts, triggering early rejection.

## Complete Workflow Example

```javascript
import {
  compareArchitecture,
  renderArchitectureDeltaHtml
} from './archify/delta/architecture-delta.mjs';
import fs from 'node:fs';

// Load snapshots
const base = JSON.parse(fs.readFileSync('v1.architecture.json', 'utf8'));
const head = JSON.parse(fs.readFileSync('v2.architecture.json', 'utf8'));

// Generate receipt
const receipt = compareArchitecture(base, head);

// Extract and annotate SVGs
const baseSvg = extractArchitectureSvg(base.html);
const headSvg = extractArchitectureSvg(head.html);

// Build delta visualization
const deltaSvg = buildDeltaSvg(baseSvg, headSvg, receipt);

// Render final artifact
const html = renderArchitectureDeltaHtml({
  receipt,
  baseSvg,
  headSvg,
  deltaSvg,
  artifactCss: fs.readFileSync('archify/assets/archify.css', 'utf8')
});

fs.writeFileSync('architecture-delta.html', html);

```

## Key Design Decisions in the Delta Module Architecture

**Deterministic comparison.** By canonicalizing before comparing, the module eliminates false positives from formatting differences.

**Stable ID enforcement.** The algorithm operates exclusively on `id` (components/connections) and `kind+label` (boundaries). No positional or temporal heuristics.

**Rich classification.** Four distinct change categories enable precise UI feedback—users see *how* something changed, not just *that* it changed.

**Proof levels.** Distinguishing `revision-pinned` from `authored` snapshots supports both strict compliance workflows and rapid iteration.

**Offline portability.** Single-file HTML output with inlined assets enables secure sharing without network dependencies.

## Summary

- The **Archify delta module** implements a seven-layer pipeline for comparing architecture snapshots in `archify/delta/architecture-delta.mjs`
- **Canonicalization** via `canonicalArchitecture` ensures order-independent comparison
- **Stable indexing** with `stableIndex` and `boundaryIndex` creates reliable lookup maps; `requireComparableShape` validates compatibility
- **Change detection** through `compareEntities`, `fieldChanges`, and `statusFor` classifies additions, removals, changes, and moves
- **Receipt generation** via `compareArchitecture` produces a machine-readable change record with proof levels
- **SVG processing** extracts, annotates, merges, and enhances visualizations with `extractArchitectureSvg`, `annotateArchitectureSideSvg`, and `buildDeltaSvg`
- **HTML rendering** via `renderArchitectureDeltaHtml` creates self-contained, interactive review artifacts
- **Validation** through `validateArchitectureDeltaHtml` ensures artifact integrity

## Frequently Asked Questions

### How does the delta module handle semantically identical snapshots with different JSON formatting?

The **`canonicalArchitecture`** function strips irrelevant metadata and recursively sorts all object keys and array contents. This **deterministic canonicalization** guarantees that two snapshots describing the same architecture produce identical internal representations, regardless of pretty-printing, field ordering, or timestamp differences. The comparison layer then operates on these normalized structures.

### What happens when snapshots from different repositories are compared?

The **`requireComparableShape`** validation throws **`ArchitectureDeltaError`** with code `delta/repository-mismatch`. This early failure prevents nonsensical comparisons between unrelated codebases. The error includes a `details` object identifying the mismatched repositories. In the CLI, this surfaces as a failed comparison with an explanatory receipt.

### Why does the delta SVG include phantom elements for removed items?

**`buildDeltaSvg`** creates phantom representations—semi-transparent overlays preserved from the base snapshot—to ensure visual completeness. Without these elements, deletions would leave gaps or require users to switch to side-by-side view to understand what disappeared. Phantoms maintain spatial context and enable direct visual comparison of before/after states within the unified delta view.

### How is the receipt's proof level determined?

The **`compareArchitecture`** function inspects both snapshots for verified repository information. When both contain a `revision` field with a SHA-1 hash, the receipt records **`proofLevel: 'revision-pinned'`**. Otherwise, it defaults to **`'authored'`**. This distinction appears in the rendered HTML UI—revision-pinned comparisons display verification badges, while authored snapshots show an "AUTHORED SNAPSHOTS" banner warning of potential unverified changes.