# How Architecture Delta Compare Works in Archify: A Technical Deep Dive

> Learn how Archify's Architecture Delta comparison works. Discover its four-stage process for detailed, interactive architectural diffs between JSON snapshots.

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

---

**Architecture Delta performs a deterministic, four-stage comparison of two Architecture JSON snapshots that canonicalizes inputs, validates stable IDs, computes field-level changes, and renders an interactive HTML artifact with Before/Delta/After views.**

The Architecture Delta feature in the `tt-a1i/archify` repository provides deterministic, fail-closed comparison of validated Architecture snapshots. It transforms two JSON inputs into a self-contained HTML report that visualizes exactly what authored facts have changed between versions. This tool ensures that cosmetic differences like whitespace or key order never affect the diff, while enforcing strict validation rules that abort early when structural contracts are violated.

## Invoking the Architecture Delta Comparison

You trigger the comparison through the CLI or programmatically via the core module. The command accepts two JSON snapshots and produces a self-contained HTML file alongside a machine-readable receipt.

```bash
node archify/bin/archify.mjs compare architecture \
  <base.json> <head.json> \
  [output.html] \
  [--json] \
  [--repo-root path]

```

The `--json` flag outputs additional structured data, while `--repo-root` specifies the repository path for normalization.

## The Four Stages of Architecture Delta Processing

The `compareArchitecture` function in `archify/delta/architecture-delta.mjs` executes four tightly-coupled stages to ensure repeatable, deterministic outputs.

### Stage 1: Load and Validate

Both input files are read and parsed through the normal Architecture renderer (`renderValidatedArchitecture`). If either file fails validation, the command aborts immediately with a structured `ArchitectureDeltaError` receipt. This stage ensures that only semantically valid architectures enter the comparison pipeline.

### Stage 2: Canonicalize

Each diagram transforms into a canonical representation via `canonicalArchitecture` and `canonicalArchitectureJson`. This process sorts components, connections, and boundaries (lines 53-64), normalizes repository URLs via `normalizeRepository`, and removes transient fields like `meta.output`. The canonical form guarantees that cosmetic differences—whitespace, key ordering, or non-semantic metadata—do **not** affect the resulting diff.

### Stage 3: Compute the Diff

The `compareArchitecture` function performs the core comparison through several validated checks:

- **Stable ID Enforcement**: The `stableIndex` function (lines 86-110) validates that component, connection, and boundary IDs exist and are unique. Missing IDs trigger `delta/*-id-required` errors; duplicates cause immediate aborts.
- **Shared Component Check**: At least one component ID must exist in both snapshots, otherwise the system raises `delta/no-shared-component-id`.
- **Repository Normalization**: Repository URLs and revisions are normalized; mismatched repositories trigger `delta/repository-mismatch`.
- **Field-Level Changes**: The `fieldChanges` function (lines 40-48) groups entity fields into semantic categories (semantic, evidence, geometry, topology) and compares them. The `statusFor` classifier (lines 63-67) maps differences to statuses: `added`, `removed`, `changed`, `evidence-changed`, `moved`, or `rerouted`.
- **Summary Generation**: The system produces a counts object (`summary`) and a `proofLevel` classification (`revision-pinned` vs `authored`).

### Stage 4: Render the Delta Artifact

The final stage generates three SVG representations:

1. **Base SVG**: Validated snapshot of the before state
2. **Head SVG**: Validated snapshot of the after state
3. **Delta SVG**: Constructed by `buildDeltaSvg` (lines 107-165), which layers the head SVG, injects *phantom* elements for removed/moved items from the base, and adds visual markers (`+`, `−`, `~`, `↔`) via `markerFor`

Metadata including IDs, classifications, and change signatures embed as `data-delta-*` attributes, enabling the interactive review UI. Finally, `renderArchitectureDeltaHtml` assembles a self-contained HTML page featuring a **Before | Delta | After** switch, an interactive change list, and a machine-readable receipt (`<script id="archify-compare-receipt" type="application/json">`). The result writes atomically alongside a matching [`.receipt.json`](https://github.com/tt-a1i/archify/blob/main/.receipt.json) file.

## Programmatic Usage and Integration

### CLI Example

Compare two architecture snapshots and generate the delta report:

```bash
node archify/bin/archify.mjs compare architecture \
  examples/checkout-platform.base.architecture.json \
  examples/checkout-platform.head.architecture.json \
  checkout-platform-delta.html \
  --json

```

### Node.js API

Import the comparator directly for custom workflows:

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

const base = JSON.parse(readFileSync('base.json', 'utf8'));
const head = JSON.parse(readFileSync('head.json', 'utf8'));

const receipt = compareArchitecture(base, head, {
  baseRawSha256: createHash('sha256').update(JSON.stringify(base)).digest('hex'),
  headRawSha256: createHash('sha256').update(JSON.stringify(head)).digest('hex')
});

console.log('Changes summary:', receipt.summary);

```

### Embedding in Web Pages

The generated HTML artifact is self-contained and iframe-friendly:

```html
<iframe 
  src="checkout-platform-delta.html" 
  style="width:100%;height:80vh;">
</iframe>

```

## Key Implementation Files

- **`archify/delta/architecture-delta.mjs`**: Core comparator implementing canonicalization, stable-ID checks, diff computation, SVG assembly, and receipt generation.
- **`archify/bin/archify.mjs`**: CLI entry point that parses the `compare` command, orchestrates validation, staging, and atomic commit of results.
- **`archify/renderers/architecture/render-architecture.mjs`**: Produces validated HTML/SVG for individual snapshots; invoked twice (for base and head) before delta construction.

## Summary

- **Architecture Delta** compares two validated JSON snapshots through deterministic, pure functions without external services or timestamps.
- **Canonicalization** eliminates cosmetic differences by sorting objects, normalizing IDs, and stripping transient fields before comparison.
- **Stable ID enforcement** requires unique, present identifiers for all components, connections, and boundaries, failing fast with specific error codes when violated.
- **Change classification** categorizes modifications into semantic statuses including `added`, `removed`, `changed`, `evidence-changed`, `moved`, and `rerouted`.
- **Artifact generation** produces a self-contained HTML file with interactive Before/Delta/After views and an embedded machine-readable JSON receipt.

## Frequently Asked Questions

### What causes an Architecture Delta comparison to fail immediately?

The comparison fails fast when validation contracts are violated. According to the `tt-a1i/archify` source code, this includes missing or duplicate IDs (triggering `delta/*-id-required` errors), no shared component IDs between snapshots (`delta/no-shared-component-id`), or repository mismatches (`delta/repository-mismatch`). Each error includes `supportedFixes` guidance, such as "add a unique id to every component."

### How does Architecture Delta handle whitespace or key ordering differences?

The system uses `canonicalArchitecture` and `canonicalArchitectureJson` to transform inputs into canonical forms before comparison. This process sorts all components, connections, and boundaries, normalizes repository URLs, and removes transient fields like `meta.output`. Because diffing occurs on canonical representations, cosmetic differences never produce false positives.

### What statuses can appear in an Architecture Delta report?

The `statusFor` classifier in `archify/delta/architecture-delta.mjs` maps field changes to six specific statuses: `added` for new entities, `removed` for deleted entities, `changed` for modified semantic fields, `evidence-changed` for updated evidence links, `moved` for repositioned components, and `rerouted` for altered connections.

### Can Architecture Delta determine if changes are safe to merge?

No. As implemented in `archify/delta/architecture-delta.mjs`, the tool intentionally limits scope to authored fact verification. It highlights exactly what facts changed between snapshots but does not infer runtime impact, assess risk levels, or determine mergeability. The output provides the diff artifact and receipt; merge decisions remain the responsibility of human reviewers or downstream CI pipelines.