# How Archify Validates Its JSON Intermediate Representation (IR)

> Discover how Archify validates its JSON IR with a multi-layer pipeline including CLI parsing schema validation and post-render checks for robust diagnostics.

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

---

**Archify validates JSON IR through a multi-layer pipeline: CLI parsing → schema validation via generated AJV validators → post-render composition checks → structured diagnostic reporting.**

The **JSON Intermediate Representation (IR)** serves as the bridge between AI agents and Archify's diagram generation system. According to the `tt-a1i/archify` source code, the **`archify validate`** command implements a rigorous, three-stage validation pipeline that guarantees both structural correctness and visual integrity.

## The Three-Layer Validation Pipeline

Archify's validation architecture operates in distinct phases, each with dedicated responsibilities and failure modes.

### Layer 1: CLI Parsing and Environment Setup

The `commandValidate` function in `archify/bin/archify.mjs` extracts critical parameters before any validation begins:

- **`type`** — the diagram category (architecture, workflow, etc.)
- **`input`** — path to the JSON IR file
- **`--json`** — flag for machine-readable output
- **`--layout-json`** — flag to emit layout data without HTML generation
- **`--repo-root`** — optional path for resolving source-evidence links

```js
// From archify/bin/archify.mjs#L78-L85
const { type, input, json, layoutJson, repoRoot } = extractQualityArgs(args);

```

The `extractQualityArgs` and `extractRepoRootArgs` utilities normalize these inputs. When `--repo-root` is provided, the renderer can validate `SRC n` evidence links back to the original codebase—though this is enforced only for architecture diagrams via `assertEvidenceType`.

### Layer 2: Schema Validation via Generated Validators

The core **JSON IR validation** happens inside type-specific renderers. The CLI invokes the renderer with `ARCHIFY_DIAGNOSTIC_FORMAT=json` set in the environment:

```js
// From archify/bin/archify.mjs
const render = runNode([renderer, input, out], {
  stdio: 'pipe',
  env: rendererEnv(quality, repoRoot, true)   // forces JSON diagnostics
});

```

Each renderer imports from **`archify/renderers/shared/generated-validators.mjs`**—auto-generated AJV validators compiled from JSON Schema definitions like [`workflow.schema.json`](https://github.com/tt-a1i/archify/blob/main/workflow.schema.json) and [`architecture.schema.json`](https://github.com/tt-a1i/archify/blob/main/architecture.schema.json). If schema validation fails, the renderer exits with a structured diagnostic payload captured by `rendererFailure` (lines 39-50 in `archify/bin/archify.mjs`).

### Layer 3: Post-Render Composition Checks

Successful schema validation triggers **artifact-level validation** via `scripts/check-render-output.mjs`. This script performs deterministic checks:

- **Label-route clearance** — ensures labels don't overlap routes
- **Crossing detection** — validates edge crossing minimization
- **SVG sanity** — verifies output validity

The script's JSON receipt feeds into `checkerDiagnostics` for uniform reporting. Failure at this stage produces a receipt with stage: `"check"` and error codes like `artifact/label_route_clearance`.

### Layer 4: Structured Receipt Generation

The `reportValidateFailure` utility (lines 29-33 in `archify/bin/archify.mjs`) assembles the final diagnostic receipt containing:

| Field | Purpose |
|-------|---------|
| `code` | Canonical error identifier (e.g., `input/json-parse`, `render/schema-validation`) |
| `message` | Human-readable description |
| `subject` | Entity that failed validation |
| `evidence` | Supporting context (line numbers, paths) |
| `supportedFixes` | Auto-fix suggestions when available |

With `--json`, the receipt prints to `stdout`; otherwise, a concise summary appears:

```

ok architecture /path/to/input.json (12 artifact checks; composition standard: 0 errors, 1 warnings)

```

## Special Validation Modes

### Layout-Only Validation (`--layout-json`)

For architecture diagrams, this flag short-circuits the pipeline after renderer execution, streaming node positions, route data, and label placements as JSON without generating HTML:

```bash
archify validate architecture examples/web-app.architecture.json --layout-json

```

### Repository-Aware Validation (`--repo-root`)

Enables validation of source-evidence links. The renderer resolves `SRC n` references against the provided root directory, ensuring traceability from diagram elements back to originating code.

## Code Examples

### Command-Line JSON IR Validation

Validate a workflow IR with full machine-readable output:

```bash
archify validate workflow examples/agent-tool-call.workflow.json --json

```

Sample receipt:

```json
{
  "schemaVersion": 1,
  "ok": true,
  "command": "validate",
  "type": "workflow",
  "input": "/abs/path/examples/agent-tool-call.workflow.json",
  "checks": [...],
  "composition": {...}
}

```

### Programmatic Validation via Node.js

```js
import { spawnSync } from 'node:child_process';

function validateIR(type, file, repoRoot = null) {
  const args = ['archify', 'validate', type, file, '--json'];
  if (repoRoot) args.push('--repo-root', repoRoot);
  
  const result = spawnSync(process.execPath, args, { encoding: 'utf8' });
  if (result.status !== 0) throw new Error(result.stderr);
  return JSON.parse(result.stdout);
}

// Validate with evidence link resolution
const receipt = validateIR(
  'architecture',
  'examples/web-app.architecture.json',
  '/home/user/myproject'
);
console.log('Schema valid:', receipt.ok);
console.log('Composition issues:', receipt.composition?.warnings ?? 0);

```

## Key Source Files for JSON IR Validation

| File | Role |
|------|------|
| `archify/bin/archify.mjs` (`commandValidate`, lines 78-100) | CLI orchestration and receipt assembly |
| `archify/renderers/shared/generated-validators.mjs` | Auto-generated AJV validators per diagram type |
| `archify/scripts/check-render-output.mjs` | Post-render composition and layout validation |
| `archify/renderers/<type>/render-<type>.mjs` | Type-specific schema validation and rendering |
| `archify/bin/archify.mjs` (`rendererFailure`, lines 39-50; `reportValidateFailure`, lines 29-33) | Diagnostic formatting and structured error reporting |

## Summary

- **Schema-first validation** via generated AJV validators ensures JSON IR conforms to strict type definitions before any rendering occurs.
- **Post-render composition checks** verify visual correctness through deterministic layout analysis in `scripts/check-render-output.mjs`.
- **Structured diagnostic receipts** provide machine-readable error codes, human messages, and auto-fix hints through `reportValidateFailure`.
- **Specialized modes** (`--layout-json`, `--repo-root`) adapt the pipeline for layout extraction and source-code traceability.

## Frequently Asked Questions

### What happens if the JSON IR fails schema validation?

The renderer exits with a non-zero status and emits a JSON diagnostic payload. The `rendererFailure` helper in `archify/bin/archify.mjs` captures this, and `reportValidateFailure` produces a receipt with `stage: "render"` and `code: "render/schema-validation"` containing specific schema violations.

### Can I validate IR without generating HTML output?

Yes. The `--layout-json` flag causes the architecture renderer to emit layout data (node positions, routes, labels) and exit before HTML generation. The CLI short-circuits after Layer 2, skipping post-render composition checks.

### How does Archify handle source-code evidence links?

When `--repo-root` is provided, the renderer validates `SRC n` references against the actual source files. This is restricted to architecture diagrams via `assertEvidenceType`. Validation fails with `input/evidence-not-found` if referenced files or line ranges are missing.

### Are the JSON Schema validators handwritten?

No. The validators in `archify/renderers/shared/generated-validators.mjs` are auto-generated from schema definitions ([`.schema.json`](https://github.com/tt-a1i/archify/blob/main/.schema.json) files). This guarantees validator and specification stay synchronized as the IR format evolves.