# How Archify Handles Schema Validation Errors: AJV Integration and Diagnostic Receipts

> Archify uses Ajv for fail-closed schema validation, aborting operations on violations and providing diagnostic receipts with error codes, evidence, and fixes.

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

---

**Archify implements a fail-closed validation system using Ajv (draft 2020-12) that aborts operations on schema violations and returns structured diagnostic receipts containing detailed error codes, evidence, and suggested fixes.**

The open-source Archify project (`tt-a1i/archify`) processes architecture diagrams into interactive visualizations by first validating their JSON Intermediate Representation (IR) against strict schemas. Understanding how Archify handles schema validation errors is essential for debugging diagram issues and building automated repair workflows that consume the validation output.

## The Fail-Closed Validation Architecture

Archify compiles its JSON Schema files using **Ajv** (Another JSON Schema Validator) supporting draft 2020-12 specifications. According to `archify/scripts/generate-validators.mjs`, the system builds standalone validators that are shipped with the CLI tooling.

When validation runs, the system operates in a **fail-closed** mode. This means any schema violation immediately aborts the rendering operation rather than producing partial or corrupted output. As noted in [`examples/archify-repo.html`](https://github.com/tt-a1i/archify/blob/main/examples/archify-repo.html) at line 5362, "ajv schema validation sits on the IR (fail-closed)." This design ensures that only schema-compliant diagrams proceed through the rendering pipeline.

## Anatomy of a Validation Receipt

When Archify encounters schema validation errors, it generates a structured **validation receipt** rather than simple text error messages. This receipt serves as a machine-readable audit trail that downstream tooling can parse to drive automated repairs or CI/CD pipeline gates.

### Diagnostic Entry Fields

Each error transforms into a diagnostic entry containing five critical fields:

- **code**: A short, namespaced identifier (e.g., `clean-flow/edge-through-node`)
- **message**: Human-readable description prefixed with the JSON-Pointer to the offending element
- **subject**: The specific IR element (node, edge, etc.) that triggered the error
- **evidence**: Contextual data such as property values, geometry coordinates, or obstacle identifiers
- **supportedFixes**: An array of suggested automatic fixes the CLI can apply (e.g., `route/via/...`)

### Validation Summary Structure

The receipt root contains metadata about the validation run:

```json
{
  "checksPassed": 0,
  "checkCount": 5,
  "checks": [
    { "name": "ajv-strict-schema", "ok": false },
    { "name": "geometry-consistency", "ok": true }
  ],
  "diagnostics": []
}

```

## Degraded Mode and Graceful Fallbacks

If the Ajv dependency is not installed, Archify enters a degraded mode. As implemented in `archify/test/degraded.test.mjs` at line 147, the system prints a warning message ("ajv is not installed|skipping JSON-schema validation") and skips schema validation entirely.

However, the rendering pipeline continues processing the diagram. This design ensures that environments without Ajv can still generate outputs, though without schema guarantees, preventing hard dependency failures in constrained deployment environments.

## Handling Archify Schema Validation Errors in Practice

### Command Line Validation and Exit Codes

When invoked from the command line, Archify commands that encounter validation errors exit with a non-zero status code. According to [`CHANGELOG.md`](https://github.com/tt-a1i/archify/blob/main/CHANGELOG.md) at line 226, schema violations exit non-zero with path-prefixed messages. If the `--json` flag is provided, the validation receipt streams to `stdout`; otherwise, error details route to `stderr`.

```bash

# Validate an architecture diagram and capture JSON receipt

archify validate architecture diagram.json --json

```

A typical failure response appears as:

```json
{
  "checksPassed": 0,
  "checkCount": 5,
  "checks": [
    {"name":"ajv-strict-schema","ok":false},
    {"name":"geometry-consistency","ok":true}
  ],
  "diagnostics": [
    {
      "code":"clean-flow/edge-through-node",
      "message":"/edges/3 (id/label: \"users-to-cdn\"): edge cannot pass through a node",
      "subject":{"id":"users-to-cdn","type":"edge"},
      "evidence":{"obstacleId":"auth","segmentIndex":0,"clearancePx":2},
      "supportedFixes":["route/via/…"]
    }
  ]
}

```

### Programmatic Error Handling

Node.js applications can invoke validation programmatically and parse the receipt for automated workflows:

```javascript
const { spawnSync } = require('child_process');

const result = spawnSync(process.execPath, [
  require.resolve('archify/cli.mjs'), 
  'validate', 
  'architecture',
  'diagram.json', 
  '--json'
]);

if (result.status !== 0) {
  const receipt = JSON.parse(result.stdout);
  console.error('Validation failed:', receipt.diagnostics);
  // Implement repair logic based on receipt.diagnostics
}

```

The `archify/test/repair-receipt.test.mjs` file (lines 36-44) demonstrates how test suites consume these receipts to verify error details and validate repair workflows that use the diagnostic data.

## Key Implementation Files

Understanding the validation pipeline requires familiarity with these specific source locations:

- **`archify/scripts/generate-validators.mjs`**: Compiles standalone Ajv validators from JSON Schema definitions
- **`archify/renderers/shared/cli.mjs`**: Parses CLI arguments, invokes the validator, and formats the validation receipt
- **`archify/test/repair-receipt.test.mjs`** (lines 36-44): Verifies that validation errors are turned into detailed diagnostic entries
- **`archify/test/degraded.test.mjs`** (line 147): Ensures graceful degradation when Ajv is missing
- **[`CHANGELOG.md`](https://github.com/tt-a1i/archify/blob/main/CHANGELOG.md)** (line 226): Documents non-zero exit behavior for schema violations
- **[`examples/archify-repo.html`](https://github.com/tt-a1i/archify/blob/main/examples/archify-repo.html)** (line 5362): Visual documentation of the fail-closed architecture

## Summary

- Archify uses **Ajv (draft 2020-12)** to validate JSON IR against strict schemas before rendering begins.
- The system operates in **fail-closed mode**, aborting operations immediately upon schema violations to prevent invalid outputs.
- Errors generate **structured validation receipts** with diagnostic codes, contextual evidence, and suggested automatic fixes.
- **Degraded mode** allows operation without Ajv but skips validation entirely, logging warnings instead of failing.
- The CLI returns **non-zero exit codes** on validation failure and supports JSON output for automation and CI integration.
- Receipt data powers downstream **repair workflows** and pipeline gates, as tested in the repair-receipt test suite.

## Frequently Asked Questions

### What happens when Archify schema validation errors occur during rendering?

When validation errors occur, Archify immediately aborts the rendering operation and returns a non-zero exit code. The system generates a validation receipt containing detailed diagnostic entries that identify the specific IR elements causing violations, along with contextual evidence and potential automatic fixes that client applications can apply.

### Can Archify skip schema validation if the Ajv dependency is missing?

Yes. If Ajv is not installed, Archify enters a degraded mode where it prints a warning message and skips JSON schema validation entirely, allowing the rendering pipeline to continue. This behavior is tested in `archify/test/degraded.test.mjs` at line 147, which verifies the "ajv is not installed|skipping JSON-schema validation" warning appears while processing continues.

### How do I interpret the validation receipt JSON format?

The receipt contains a `checks` array summarizing each validation rule and a `diagnostics` array with specific errors. Each diagnostic includes a `code` (namespaced identifier), `message` (human-readable description with JSON-Pointer path), `subject` (the offending IR element), `evidence` (contextual data), and `supportedFixes` (repair suggestions). The top-level `checksPassed` and `checkCount` fields provide a quick health overview for automated monitoring.

### What exit code does Archify return when schema validation fails?

Archify exits with a non-zero status code when schema validation fails. According to [`CHANGELOG.md`](https://github.com/tt-a1i/archify/blob/main/CHANGELOG.md) at line 226, the CLI streams the validation receipt to `stdout` when using the `--json` flag, or to `stderr` for human-readable output, making it suitable for CI/CD pipelines that need to gate deployments based on diagram validity and parse structured error data programmatically.