# How Archify's JSON IR Validation Pipeline Works and How to Debug Schema Errors

> Learn how Archify validates JSON IR with Ajv and JSON-Schemas. Debug schema errors efficiently with annotated error messages pinpointing exact element IDs.

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

---

**Archify validates JSON intermediate representation (IR) diagrams using pre-generated Ajv validators that check against strict JSON-Schemas, throwing annotated errors that pinpoint exact element IDs when validation fails.**

Archify is an open-source diagram-as-code tool that transforms JSON-based intermediate representations into visual diagrams. Before rendering, every JSON-IR document passes through a rigorous **JSON IR validation pipeline** that ensures structural integrity using JSON-Schema validation. Understanding this pipeline is essential for troubleshooting schema errors and ensuring your diagram definitions meet the required specifications.

## The Validation Pipeline Architecture

The validation flow follows a seven-step process from CLI invocation to renderer handoff, with each step implemented in specific source files.

### CLI Entry Point

Validation begins at the command line. The `archify validate <type> <file>` command parses arguments and loads the input file in `archify/bin/archify.mjs`. This entry point handles file I/O and initial argument validation before delegating to the validation engine.

### Schema Dispatch and Selection

The CLI calls `validateSchema(diagramType, diagram)` from `archify/renderers/shared/validator.mjs`. This central dispatcher acts as the orchestration layer, looking up the appropriate validator based on the diagram type (workflow, sequence, dataflow, lifecycle, or architecture).

### Ajv Validator Lookup

Within `validator.mjs`, the system retrieves a pre-generated validator function from `archify/renderers/shared/generated-validators.mjs`. These validators are stored in a lookup object (`validators[diagramType]`), providing O(1) access to the correct validation logic for the specific diagram type.

### Standalone Validation Execution

The selected validator is a **stand-alone Ajv function** created by `archify/scripts/generate-validators.mjs`. These functions check the JSON-IR against corresponding schemas in `archify/schemas/*.schema.json` without requiring Ajv as a runtime dependency. The validation uses Ajv 2020 with strict mode enabled, ensuring rigorous schema compliance.

### Error Handling with Element IDs

If `validate(data)` returns `false`, `validator.mjs` triggers `formatErrors(validate.errors, data)`. This formatter annotates each Ajv error with the **element id** (or array index) that caused the failure. For example, an error in the fourth node of a workflow array generates a message pointing to `/nodes/3`, making the problem immediately traceable back to the source JSON.

### Degraded Mode Fallback

When Ajv cannot be loaded (such as in minimal installations), the pipeline falls back to a tiny hand-rolled check in `validator.mjs` that only guarantees the top-level shape is an object. This prevents renderer crashes while providing surface-level validation, though with generic error messages.

### Renderer Handoff

Once validation succeeds, the verified diagram object passes to the specific renderer (e.g., `render-workflow.mjs`, `render-architecture.mjs`) at lines like `archify/renderers/workflow/render-workflow.mjs#L95`, which proceeds with layout calculations and HTML/SVG generation.

## How Pre-Generated Validators Are Built

The validators are not compiled at runtime but generated during the build process. The script `archify/scripts/generate-validators.mjs` reads every schema in `archify/schemas/`, feeds them to **Ajv 2020** (`new Ajv2020({strict:true})`), and writes a single bundle (`generated-validators.mjs`) that exports a function per diagram type.

Key implementation details from the generator:

```javascript
import Ajv2020 from 'ajv/dist/2020.js';
import standaloneCode from 'ajv/dist/standalone/index.js';
const ajv = new Ajv2020({strict:true});
ajv.addSchema(JSON.parse(fs.readFileSync(path.join(schemasDir, 'common.schema.json'), 'utf8')));
// ...
let validatorCode = standaloneCode(ajv, schemaIds);

```

This approach produces standalone validation code, meaning the runtime does not need to install Ajv as a dependency, reducing installation size and improving startup performance.

## Debugging Schema Errors in Practice

When validation fails, Archify provides multiple mechanisms to diagnose and fix schema violations.

### Using the --json Flag for Machine-Readable Errors

Run the validator with the `--json` flag to receive structured error output:

```bash
archify validate workflow my-diagram.json --json

```

This outputs a JSON array of error objects containing `instancePath`, `schemaPath`, `keyword`, `message`, and the derived element `id`, enabling programmatic error processing and precise debugging.

### Interpreting Formatted Error Messages

The standard formatter adds element IDs to error messages. A typical error appears as:

```

workflow schema validation failed:
/nodes/3 – additionalProperties: property "colour" is not allowed

```

This tells you exactly which node in the JSON-IR contains the offending property. The `instancePath` (e.g., `/nodes/3`) corresponds directly to the JSON pointer location in your input file.

### Cross-Referencing Schema Definitions

Open the relevant schema file (e.g., [`archify/schemas/workflow.schema.json`](https://github.com/tt-a1i/archify/blob/main/archify/schemas/workflow.schema.json)) to inspect property rules. The workflow schema defines required fields as:

```json
"required": ["schema_version","diagram_type","meta","lanes","nodes","edges"]

```

When you encounter `required` errors, check this list to identify missing mandatory properties. For `additionalProperties` errors, verify that you haven't added fields not defined in the schema's `properties` or `patternProperties` sections.

### Common Validation Pitfalls

- **Typos in enum values**: Ajv reports `enum` errors when string values don't match allowed options.
- **Missing required fields**: `required` errors indicate absent mandatory properties.
- **Extra properties**: `additionalProperties` errors appear when adding undefined fields (e.g., `colour` on a node).

### Testing Against Known Failures

The repository's test suite in `archify/test/layout-rules.test.mjs` deliberately triggers Ajv errors. For example, line 146-150 demonstrates an `additionalProperties` violation:

```javascript
d.nodes[3].colour = 'red'; // unknown property → ajv additionalProperties

```

Use these tests as reference patterns for understanding how specific schema violations manifest in error messages.

## Programmatic Validation Example

For custom scripts or CI pipelines, import the validator directly:

```javascript
import { validateSchema } from './archify/renderers/shared/validator.mjs';
import fs from 'fs';

const diagram = JSON.parse(fs.readFileSync('my-diagram.json'));
try {
  validateSchema('workflow', diagram);
  console.log('✅ Diagram is valid');
} catch (e) {
  console.error(e.message); // formatted error with element IDs
}

```

## Summary

- **Archify's JSON IR validation pipeline** uses pre-generated Ajv validators to check diagram structure before rendering.
- The **entry point** is `archify/bin/archify.mjs`, which delegates to `validator.mjs` for schema dispatch.
- **Validators are built** by `scripts/generate-validators.mjs` using Ajv 2020 in strict mode, producing standalone functions that require no runtime Ajv dependency.
- **Error messages** include element IDs (e.g., `/nodes/3`) that map directly to JSON-IR locations, making debugging straightforward.
- Use **`--json`** flag for machine-readable error output suitable for programmatic processing.
- **Degraded mode** provides basic object validation when Ajv is unavailable, though with limited diagnostic information.

## Frequently Asked Questions

### What is JSON IR in Archify?

**JSON IR (Intermediate Representation)** is the canonical JSON format that describes diagram structure, metadata, nodes, edges, and layout properties before rendering. It serves as the bridge between your diagram definition and Archify's rendering engines, ensuring a consistent data structure across all diagram types (workflow, sequence, architecture, etc.).

### Why does Archify use pre-generated Ajv validators instead of runtime compilation?

Archify generates standalone validator functions during the build process to **eliminate the Ajv dependency at runtime**. This reduces the installation footprint, improves startup performance, and ensures consistent validation behavior across different environments. The `generated-validators.mjs` file contains pure JavaScript functions generated by `scripts/generate-validators.mjs`, allowing validation without loading the full Ajv library.

### How do I fix "additionalProperties" validation errors?

`additionalProperties` errors indicate you've included fields not defined in the schema. **Remove the offending property** or check for typos in property names. For example, if you see `/nodes/0 – additionalProperties: property "colour" is not allowed`, delete the `colour` field from that node. Use `archify validate <type> <file> --json` to see the exact `instancePath` where the violation occurs.

### What happens if Ajv is not installed in my environment?

If Ajv cannot be loaded, `validator.mjs` falls back to a **degraded mode** that only checks if the input is a valid object. While this prevents renderer crashes, it provides only surface-level validation with generic error messages. To get full schema validation and detailed error reporting, ensure you're running Archify in an environment where Ajv can be required (the default npm install includes Ajv as a dependency).