{
  "$id": "urn:manifest:spec:ir-v1",
  "title": "Manifest IR v1",
  "$comment": "SOURCE OF TRUTH (Binding): machine contract for IR JSON shape. See docs/SOURCE_OF_TRUTH_INDEX.md. Semantics prose: docs/spec/semantics.md.",
  "type": "object",
  "additionalProperties": false,
  "required": [
    "version",
    "provenance",
    "modules",
    "values",
    "entities",
    "enums",
    "stores",
    "events",
    "commands",
    "policies"
  ],
  "properties": {
    "version": {
      "const": "1.0"
    },
    "provenance": {
      "$ref": "#/definitions/IRProvenance"
    },
    "modules": {
      "type": "array",
      "items": {
        "$ref": "#/definitions/IRModule"
      }
    },
    "entities": {
      "type": "array",
      "items": {
        "$ref": "#/definitions/IREntity"
      }
    },
    "stores": {
      "type": "array",
      "items": {
        "$ref": "#/definitions/IRStore"
      }
    },
    "events": {
      "type": "array",
      "items": {
        "$ref": "#/definitions/IREvent"
      }
    },
    "commands": {
      "type": "array",
      "items": {
        "$ref": "#/definitions/IRCommand"
      }
    },
    "policies": {
      "type": "array",
      "items": {
        "$ref": "#/definitions/IRPolicy"
      }
    },
    "enums": {
      "type": "array",
      "items": {
        "$ref": "#/definitions/IREnum"
      }
    },
    "tenant": {
      "$ref": "#/definitions/IRTenant",
      "description": "Multi-tenancy isolation configuration. When present, persistent entities are tenant-scoped."
    },
    "values": {
      "type": "array",
      "items": {
        "$ref": "#/definitions/IRValueObject"
      },
      "description": "Reusable composite value types (embedded, no separate table). Immutable by design."
    },
    "reactions": {
      "type": "array",
      "items": {
        "$ref": "#/definitions/IRReactionRule"
      },
      "description": "Declarative event-reaction rules. When a matching event is emitted, the runtime dispatches the target command."
    },
    "sagas": {
      "type": "array",
      "items": {
        "$ref": "#/definitions/IRSaga"
      },
      "description": "Saga orchestration definitions sequencing commands with compensation."
    },
    "roles": {
      "type": "array",
      "items": {
        "$ref": "#/definitions/IRRole"
      },
      "description": "Role hierarchy with permission inheritance. effectivePermissions is the deny-resolved flattened set."
    },
    "webhooks": {
      "type": "array",
      "items": {
        "$ref": "#/definitions/IRWebhook"
      },
      "description": "Webhook declarations mapping inbound HTTP payloads to Manifest command invocations."
    },
    "schedules": {
      "type": "array",
      "items": {
        "$ref": "#/definitions/IRSchedule"
      },
      "description": "Scheduled command declarations with triggers and parameter bindings."
    }
  },
  "definitions": {
    "IRProvenance": {
      "type": "object",
      "additionalProperties": false,
      "required": [
        "contentHash",
        "compilerVersion",
        "schemaVersion",
        "compiledAt"
      ],
      "properties": {
        "contentHash": {
          "type": "string",
          "description": "SHA-256 hash of the source manifest"
        },
        "irHash": {
          "type": "string",
          "description": "SHA-256 hash of the IR itself for runtime integrity verification"
        },
        "compilerVersion": {
          "type": "string",
          "description": "Version of the compiler that generated this IR"
        },
        "schemaVersion": {
          "type": "string",
          "description": "IR schema version"
        },
        "compiledAt": {
          "type": "string",
          "description": "ISO 8601 timestamp of compilation"
        },
        "sources": {
          "type": "array",
          "description": "Source files contributing to this IR. Present only for multi-file compilation.",
          "items": {
            "$ref": "#/definitions/IRProvenanceSource"
          }
        }
      }
    },
    "IRProvenanceSource": {
      "type": "object",
      "additionalProperties": false,
      "required": ["path", "contentHash"],
      "properties": {
        "path": {
          "type": "string",
          "description": "Relative path from project root"
        },
        "contentHash": {
          "type": "string",
          "description": "SHA-256 content hash of this source file"
        }
      }
    },
    "IRModule": {
      "type": "object",
      "additionalProperties": false,
      "required": [
        "name",
        "entities",
        "commands",
        "stores",
        "events",
        "policies"
      ],
      "properties": {
        "name": {
          "type": "string"
        },
        "entities": {
          "type": "array",
          "items": {
            "type": "string"
          }
        },
        "commands": {
          "type": "array",
          "items": {
            "type": "string"
          }
        },
        "stores": {
          "type": "array",
          "items": {
            "type": "string"
          }
        },
        "events": {
          "type": "array",
          "items": {
            "type": "string"
          }
        },
        "policies": {
          "type": "array",
          "items": {
            "type": "string"
          }
        },
        "enums": {
          "type": "array",
          "items": {
            "type": "string"
          }
        },
        "reactions": {
          "type": "array",
          "items": {
            "type": "string"
          },
          "description": "Reaction rule names declared in this module"
        },
        "sagas": {
          "type": "array",
          "items": {
            "type": "string"
          },
          "description": "Saga names declared in this module"
        },
        "roles": {
          "type": "array",
          "items": {
            "type": "string"
          },
          "description": "Role names declared in this module"
        },
        "webhooks": {
          "type": "array",
          "items": {
            "type": "string"
          },
          "description": "Webhook names declared in this module"
        },
        "schedules": {
          "type": "array",
          "items": {
            "type": "string"
          },
          "description": "Schedule names declared in this module"
        }
      }
    },
    "IREnum": {
      "type": "object",
      "additionalProperties": false,
      "required": [
        "name",
        "values"
      ],
      "properties": {
        "name": {
          "type": "string",
          "description": "Enum type name"
        },
        "module": {
          "type": "string",
          "description": "Module name if defined in a module"
        },
        "values": {
          "type": "array",
          "items": {
            "$ref": "#/definitions/IREnumValue"
          },
          "description": "Enum member values"
        }
      }
    },
    "IREnumValue": {
      "type": "object",
      "additionalProperties": false,
      "required": [
        "name"
      ],
      "properties": {
        "name": {
          "type": "string",
          "description": "Enum member name (identifier)"
        },
        "label": {
          "type": "string",
          "description": "Display label for UI"
        },
        "ordinal": {
          "type": "number",
          "description": "Optional ordinal value for sorting/database mapping"
        }
      }
    },
    "IREntity": {
      "type": "object",
      "additionalProperties": false,
      "required": [
        "name",
        "properties",
        "computedProperties",
        "relationships",
        "commands",
        "constraints",
        "policies"
      ],
      "properties": {
        "name": {
          "type": "string"
        },
        "module": {
          "type": "string"
        },
        "parent": {
          "type": "string",
          "description": "Parent entity name for inheritance (from `extends` keyword)"
        },
        "mixins": {
          "type": "array",
          "items": {
            "type": "string"
          },
          "description": "Mixin entity names for composition (from `mixin` keyword)"
        },
        "properties": {
          "type": "array",
          "items": {
            "$ref": "#/definitions/IRProperty"
          }
        },
        "computedProperties": {
          "type": "array",
          "items": {
            "$ref": "#/definitions/IRComputedProperty"
          }
        },
        "relationships": {
          "type": "array",
          "items": {
            "$ref": "#/definitions/IRRelationship"
          }
        },
        "commands": {
          "type": "array",
          "items": {
            "type": "string"
          }
        },
        "constraints": {
          "type": "array",
          "items": {
            "$ref": "#/definitions/IRConstraint"
          }
        },
        "policies": {
          "type": "array",
          "items": {
            "type": "string"
          }
        },
        "defaultPolicies": {
          "type": "array",
          "items": {
            "type": "string"
          },
          "description": "Policy names inherited by all commands unless overridden (vNext)"
        },
        "key": {
          "type": "array",
          "items": {
            "type": "string"
          },
          "description": "Composite primary key column names, e.g. [\"tenantId\", \"id\"]"
        },
        "alternateKeys": {
          "type": "array",
          "items": {
            "type": "array",
            "items": {
              "type": "string"
            }
          },
          "description": "Alternate unique constraints for non-PK FK reference targets"
        },
        "versionProperty": {
          "type": "string",
          "description": "Name of version field for optimistic concurrency control"
        },
        "versionAtProperty": {
          "type": "string",
          "description": "Name of timestamp field for version tracking"
        },
        "timestamps": {
          "type": "boolean",
          "description": "When true, createdAt/updatedAt are auto-injected and populated at runtime"
        },
        "realtime": {
          "type": "boolean",
          "description": "Projection hint: generate SSE subscription surfaces for this entity. No runtime execution semantics."
        },
        "external": {
          "type": "boolean",
          "description": "When true, the entity is a reference to one owned by another system/file (from the `external entity` modifier). Persistence projections skip it."
        },
        "transitions": {
          "type": "array",
          "items": {
            "$ref": "#/definitions/IRTransition"
          },
          "description": "Optional allowed state transitions for validation"
        },
        "approvals": {
          "type": "array",
          "items": {
            "$ref": "#/definitions/IRApproval"
          },
          "description": "Approval workflow declarations gating command execution"
        }
      }
    },
    "IRTransition": {
      "type": "object",
      "additionalProperties": false,
      "required": [
        "property",
        "from",
        "to"
      ],
      "properties": {
        "property": {
          "type": "string",
          "description": "Property name that holds state"
        },
        "from": {
          "type": "string",
          "description": "Value the property transitions FROM"
        },
        "to": {
          "type": "array",
          "items": {
            "type": "string"
          },
          "description": "Allowed values the property can transition TO"
        }
      }
    },
    "IRApprovalStage": {
      "type": "object",
      "additionalProperties": false,
      "required": [
        "name",
        "policy",
        "required"
      ],
      "properties": {
        "name": {
          "type": "string",
          "description": "Stage name (unique within the approval)"
        },
        "policy": {
          "$ref": "#/definitions/IRExpression",
          "description": "Boolean expression authorizing an approver for this stage"
        },
        "required": {
          "type": "number",
          "description": "Number of approvals required to satisfy this stage"
        },
        "when": {
          "$ref": "#/definitions/IRExpression",
          "description": "Optional condition gating whether this stage applies"
        }
      }
    },
    "IRApproval": {
      "type": "object",
      "additionalProperties": false,
      "required": [
        "name",
        "command",
        "stages",
        "emits"
      ],
      "properties": {
        "name": {
          "type": "string",
          "description": "Approval workflow name"
        },
        "command": {
          "type": "string",
          "description": "Command name this approval gates"
        },
        "stages": {
          "type": "array",
          "items": {
            "$ref": "#/definitions/IRApprovalStage"
          },
          "description": "Ordered approval stages"
        },
        "timeout": {
          "type": "number",
          "description": "Timeout in hours for pending approval"
        },
        "onTimeout": {
          "description": "Behavior when approval times out: cancel, or escalate with an open author-defined target expression (not a closed person/department enum).",
          "oneOf": [
            {
              "type": "string",
              "enum": ["cancel"]
            },
            {
              "type": "object",
              "additionalProperties": false,
              "required": ["action", "to", "status", "timeout"],
              "properties": {
                "action": {
                  "type": "string",
                  "const": "escalate"
                },
                "to": {
                  "$ref": "#/definitions/IRExpression",
                  "description": "Author-defined escalation target expression; evaluated at timeout; opaque routing metadata"
                },
                "status": {
                  "type": "string",
                  "enum": ["pending", "granted", "denied", "expired"],
                  "description": "Approval status entered after escalation"
                },
                "timeout": {
                  "description": "Hours from escalation instant, 'none' to clear expiry, or 'reset' to re-apply the approval timeout",
                  "oneOf": [
                    { "type": "number" },
                    { "type": "string", "enum": ["none", "reset"] }
                  ]
                }
              }
            }
          ]
        },
        "emits": {
          "type": "array",
          "items": {
            "type": "string"
          },
          "description": "Lifecycle events emitted during the approval workflow"
        }
      }
    },
    "IRProperty": {
      "type": "object",
      "additionalProperties": false,
      "required": [
        "name",
        "type",
        "modifiers"
      ],
      "properties": {
        "name": {
          "type": "string"
        },
        "type": {
          "$ref": "#/definitions/IRType"
        },
        "defaultValue": {
          "$ref": "#/definitions/IRValue"
        },
        "autoNow": {
          "type": "boolean",
          "description": "Property default is a current-time call (= now()/= today()); runtime stamps current time on create."
        },
        "modifiers": {
          "type": "array",
          "items": {
            "enum": [
              "required",
              "unique",
              "indexed",
              "private",
              "readonly",
              "optional",
              "searchable",
              "encrypted",
              "masked"
            ]
          }
        },
        "maskStrategy": {
          "$ref": "#/definitions/IRMaskStrategy"
        }
      }
    },
    "IRMaskStrategy": {
      "type": "object",
      "additionalProperties": false,
      "required": [
        "type"
      ],
      "properties": {
        "type": {
          "enum": [
            "redact",
            "partial",
            "email",
            "phone",
            "last4"
          ]
        },
        "params": {
          "type": "array",
          "items": {
            "type": "number"
          }
        },
        "unmaskWhen": {
          "$ref": "#/definitions/IRExpression"
        }
      }
    },
    "IRComputedPropertyCache": {
      "type": "object",
      "additionalProperties": false,
      "required": ["strategy"],
      "properties": {
        "strategy": {
          "type": "string",
          "enum": ["request", "session", "ttl"]
        },
        "ttlSeconds": {
          "type": "number"
        }
      }
    },
    "IRComputedProperty": {
      "type": "object",
      "additionalProperties": false,
      "required": [
        "name",
        "type",
        "expression",
        "dependencies"
      ],
      "properties": {
        "name": {
          "type": "string"
        },
        "type": {
          "$ref": "#/definitions/IRType"
        },
        "expression": {
          "$ref": "#/definitions/IRExpression"
        },
        "dependencies": {
          "type": "array",
          "items": {
            "type": "string"
          }
        },
        "cache": {
          "$ref": "#/definitions/IRComputedPropertyCache"
        }
      }
    },
    "IRForeignKey": {
      "type": "object",
      "additionalProperties": false,
      "required": [
        "fields"
      ],
      "properties": {
        "fields": {
          "type": "array",
          "items": {
            "type": "string"
          },
          "description": "Local FK column names"
        },
        "references": {
          "type": "array",
          "items": {
            "type": "string"
          },
          "description": "Remote/referenced column names. Absent means projection defaults to [\"id\"]"
        }
      }
    },
    "IRRelationship": {
      "type": "object",
      "additionalProperties": false,
      "required": [
        "name",
        "kind",
        "target"
      ],
      "not": {
        "required": ["foreignKey", "through"],
        "description": "foreignKey and through are mutually exclusive. The compiler enforces this and emits an error diagnostic if both are present."
      },
      "properties": {
        "name": {
          "type": "string"
        },
        "kind": {
          "enum": [
            "hasMany",
            "hasOne",
            "belongsTo",
            "ref"
          ]
        },
        "target": {
          "type": "string"
        },
        "foreignKey": {
          "$ref": "#/definitions/IRForeignKey",
          "description": "Structured FK column mapping. Mutually exclusive with 'through' — the compiler rejects programs that supply both."
        },
        "through": {
          "type": "string",
          "description": "Join-table entity name for many-to-many. Mutually exclusive with 'foreignKey' — the compiler rejects programs that supply both."
        },
        "onDelete": {
          "type": "string",
          "enum": [
            "cascade",
            "restrict",
            "setNull",
            "setDefault",
            "noAction"
          ],
          "description": "Referential action on parent delete. Absent = let projection/DB default."
        },
        "onUpdate": {
          "type": "string",
          "enum": [
            "cascade",
            "restrict",
            "setNull",
            "setDefault",
            "noAction"
          ],
          "description": "Referential action on parent update. Absent = let projection/DB default."
        }
      }
    },
    "IRConstraint": {
      "type": "object",
      "additionalProperties": false,
      "required": [
        "name",
        "code",
        "expression"
      ],
      "properties": {
        "name": {
          "type": "string"
        },
        "code": {
          "type": "string",
          "description": "Stable identifier for overrides/auditing (defaults to name)"
        },
        "expression": {
          "$ref": "#/definitions/IRExpression"
        },
        "message": {
          "type": "string"
        },
        "severity": {
          "type": "string",
          "enum": [
            "ok",
            "warn",
            "block"
          ],
          "description": "Constraint severity level (default: block)"
        },
        "failWhen": {
          "type": "boolean",
          "description": "Expression polarity. When true, a truthy expression marks a VIOLATION (passed = !expr). Absent or false means a falsy expression is a violation (default positive polarity)."
        },
        "messageTemplate": {
          "type": "string",
          "description": "Template for error messages with interpolation"
        },
        "detailsMapping": {
          "type": "object",
          "additionalProperties": {
            "$ref": "#/definitions/IRExpression"
          },
          "description": "Structured details for UI (key-value pairs with expression values)"
        },
        "overrideable": {
          "type": "boolean",
          "description": "Can this constraint be overridden?"
        },
        "overridePolicyRef": {
          "type": "string",
          "description": "Policy that authorizes overrides"
        }
      }
    },
    "IRStore": {
      "type": "object",
      "additionalProperties": false,
      "required": [
        "entity",
        "target",
        "config"
      ],
      "properties": {
        "entity": {
          "type": "string"
        },
        "target": {
          "type": "string",
          "description": "Built-in targets: memory, localStorage, postgres, supabase, durable, mongodb, eventSourced. Custom adapter schemes (e.g. redis, dynamodb) are valid when a matching StoreAdapterPlugin is registered."
        },
        "config": {
          "type": "object",
          "additionalProperties": {
            "$ref": "#/definitions/IRValue"
          }
        }
      }
    },
    "IREvent": {
      "type": "object",
      "additionalProperties": false,
      "required": [
        "name",
        "channel",
        "payload"
      ],
      "properties": {
        "name": {
          "type": "string"
        },
        "channel": {
          "type": "string"
        },
        "payload": {
          "oneOf": [
            {
              "$ref": "#/definitions/IRType"
            },
            {
              "type": "array",
              "items": {
                "$ref": "#/definitions/IREventField"
              }
            }
          ]
        }
      }
    },
    "IREventField": {
      "type": "object",
      "additionalProperties": false,
      "required": [
        "name",
        "type",
        "required"
      ],
      "properties": {
        "name": {
          "type": "string"
        },
        "type": {
          "$ref": "#/definitions/IRType"
        },
        "required": {
          "type": "boolean"
        }
      }
    },
    "IRCommand": {
      "type": "object",
      "additionalProperties": false,
      "required": [
        "name",
        "parameters",
        "guards",
        "actions",
        "emits"
      ],
      "properties": {
        "name": {
          "type": "string"
        },
        "module": {
          "type": "string"
        },
        "entity": {
          "type": "string"
        },
        "parameters": {
          "type": "array",
          "items": {
            "$ref": "#/definitions/IRParameter"
          }
        },
        "guards": {
          "type": "array",
          "items": {
            "$ref": "#/definitions/IRExpression"
          }
        },
        "constraints": {
          "type": "array",
          "items": {
            "$ref": "#/definitions/IRConstraint"
          },
          "description": "Command-level constraints (pre-execution validation)"
        },
        "policies": {
          "type": "array",
          "items": {
            "type": "string"
          },
          "description": "Policy names for authorization (explicit or inherited from entity defaults)"
        },
        "retry": {
          "$ref": "#/definitions/IRRetry",
          "description": "Retry policy for resilient execution"
        },
        "rateLimit": {
          "$ref": "#/definitions/IRRateLimit",
          "description": "Rate limit policy for this command"
        },
        "actions": {
          "type": "array",
          "items": {
            "$ref": "#/definitions/IRAction"
          }
        },
        "emits": {
          "type": "array",
          "items": {
            "type": "string"
          }
        },
        "emitPayloads": {
          "type": "array",
          "description": "Explicit event payload field expressions from `emit Event { field: expr }`.",
          "items": {
            "$ref": "#/definitions/IREmitPayload"
          }
        },
        "returns": {
          "$ref": "#/definitions/IRType",
          "description": "Declared command result type for projections (TypeScript/OpenAPI/Zod/etc.). Projection-only metadata — the reference runtime does not validate or coerce CommandResult against this type."
        },
        "async": {
          "type": "boolean",
          "description": "When true, defers action execution to a background worker queue. The command returns a JobId immediately after policies/guards pass."
        },
        "completionEvent": {
          "type": "string",
          "description": "Auto-derived completion event name, synthesized when async is true. Format: {commandName}Completed."
        },
        "failureEvent": {
          "type": "string",
          "description": "Auto-derived failure event name, synthesized when async is true. Format: {commandName}Failed."
        },
        "initialization": {
          "$ref": "#/definitions/IRInitializationPlan",
          "description": "Authoritative atomic construction plan for allocating commands. When present, runtime and projections MUST construct one final valid document (draft → mutate → validate → persist once) and MUST NOT persist a partial document before mutations."
        }
      }
    },
    "IRInitializationPlan": {
      "type": "object",
      "additionalProperties": false,
      "required": [
        "initializationInputs",
        "authenticatedOwnershipFields",
        "declaredDefaults",
        "initialLifecycleState",
        "commandOwnedFields",
        "draftFields",
        "finalDocumentRequirements",
        "dynamicGuardIndexes",
        "redundantGuardIndexes"
      ],
      "properties": {
        "initializationInputs": {
          "type": "array",
          "items": { "type": "string" },
          "description": "Client-facing command parameter names (excludes trustedSource)."
        },
        "authenticatedOwnershipFields": {
          "type": "array",
          "items": { "type": "string" },
          "description": "Fields filled from authenticated ownership / tenant context."
        },
        "declaredDefaults": {
          "type": "array",
          "items": {
            "type": "object",
            "additionalProperties": false,
            "required": ["property", "source"],
            "properties": {
              "property": { "type": "string" },
              "source": {
                "type": "string",
                "enum": ["defaultValue", "autoNow", "timestamps", "version"]
              }
            }
          }
        },
        "initialLifecycleState": {
          "type": "array",
          "items": {
            "type": "object",
            "additionalProperties": false,
            "required": ["property", "value"],
            "properties": {
              "property": { "type": "string" },
              "value": { "$ref": "#/definitions/IRValue" }
            }
          }
        },
        "commandOwnedFields": {
          "type": "array",
          "items": { "type": "string" },
          "description": "Entity fields written by this command's actions."
        },
        "draftFields": {
          "type": "array",
          "items": { "type": "string" },
          "description": "Fields available on the pre-mutation draft for precondition evaluation."
        },
        "finalDocumentRequirements": {
          "type": "array",
          "items": { "type": "string" },
          "description": "Required non-null entity fields that must exist on the final persisted document."
        },
        "dynamicGuardIndexes": {
          "type": "array",
          "items": { "type": "integer", "minimum": 0 },
          "description": "Guard indexes that need runtime evaluation."
        },
        "redundantGuardIndexes": {
          "type": "array",
          "items": { "type": "integer", "minimum": 0 },
          "description": "Guard indexes that only restate initialization facts (optional; not required by authors)."
        }
      }
    },
    "IREmitPayload": {
      "type": "object",
      "additionalProperties": false,
      "required": [
        "eventName",
        "fields"
      ],
      "properties": {
        "eventName": {
          "type": "string"
        },
        "fields": {
          "type": "array",
          "items": {
            "$ref": "#/definitions/IREmitPayloadField"
          }
        }
      }
    },
    "IREmitPayloadField": {
      "type": "object",
      "additionalProperties": false,
      "required": [
        "name",
        "expression"
      ],
      "properties": {
        "name": {
          "type": "string"
        },
        "expression": {
          "$ref": "#/definitions/IRExpression"
        }
      }
    },
    "IRParameter": {
      "type": "object",
      "additionalProperties": false,
      "required": [
        "name",
        "type",
        "required"
      ],
      "properties": {
        "name": {
          "type": "string"
        },
        "type": {
          "$ref": "#/definitions/IRType"
        },
        "required": {
          "type": "boolean"
        },
        "defaultValue": {
          "$ref": "#/definitions/IRValue"
        },
        "trustedSource": {
          "type": "string",
          "description": "Dotted context path (e.g. context.actorId). When set, the parameter is server-owned: strip client values and inject from RuntimeContext before execution."
        }
      }
    },
    "IRAction": {
      "oneOf": [
        {
          "type": "object",
          "additionalProperties": false,
          "required": [
            "kind",
            "target",
            "expression"
          ],
          "properties": {
            "kind": {
              "const": "mutate"
            },
            "target": {
              "type": "string"
            },
            "expression": {
              "$ref": "#/definitions/IRExpression"
            }
          }
        },
        {
          "type": "object",
          "additionalProperties": false,
          "required": [
            "kind",
            "expression"
          ],
          "properties": {
            "kind": {
              "enum": [
                "emit",
                "compute",
                "effect",
                "publish",
                "persist"
              ]
            },
            "target": {
              "type": "string"
            },
            "expression": {
              "$ref": "#/definitions/IRExpression"
            }
          }
        }
      ]
    },
    "IRPolicy": {
      "type": "object",
      "additionalProperties": false,
      "required": [
        "name",
        "action",
        "expression"
      ],
      "properties": {
        "name": {
          "type": "string"
        },
        "module": {
          "type": "string"
        },
        "entity": {
          "type": "string"
        },
        "action": {
          "enum": [
            "read",
            "write",
            "delete",
            "execute",
            "all",
            "override"
          ]
        },
        "expression": {
          "$ref": "#/definitions/IRExpression"
        },
        "rateLimit": {
          "$ref": "#/definitions/IRRateLimit",
          "description": "Rate limit policy for this policy"
        },
        "message": {
          "type": "string"
        }
      }
    },
    "IRType": {
      "type": "object",
      "additionalProperties": false,
      "required": [
        "name",
        "nullable"
      ],
      "properties": {
        "name": {
          "type": "string"
        },
        "generic": {
          "$ref": "#/definitions/IRType"
        },
        "nullable": {
          "type": "boolean"
        },
        "params": {
          "type": "object",
          "additionalProperties": false,
          "description": "Type parameters such as precision/scale for decimal types",
          "properties": {
            "precision": {
              "type": "number",
              "description": "Total number of significant digits (for decimal/money types)"
            },
            "scale": {
              "type": "number",
              "description": "Number of digits after decimal point (for decimal/money types)"
            }
          }
        }
      }
    },
    "IRValue": {
      "oneOf": [
        {
          "type": "object",
          "additionalProperties": false,
          "required": [
            "kind",
            "value"
          ],
          "properties": {
            "kind": {
              "const": "string"
            },
            "value": {
              "type": "string"
            }
          }
        },
        {
          "type": "object",
          "additionalProperties": false,
          "required": [
            "kind",
            "value"
          ],
          "properties": {
            "kind": {
              "const": "number"
            },
            "value": {
              "type": "number"
            }
          }
        },
        {
          "type": "object",
          "additionalProperties": false,
          "required": [
            "kind",
            "value"
          ],
          "properties": {
            "kind": {
              "const": "boolean"
            },
            "value": {
              "type": "boolean"
            }
          }
        },
        {
          "type": "object",
          "additionalProperties": false,
          "required": [
            "kind"
          ],
          "properties": {
            "kind": {
              "const": "null"
            }
          }
        },
        {
          "type": "object",
          "additionalProperties": false,
          "required": [
            "kind",
            "elements"
          ],
          "properties": {
            "kind": {
              "const": "array"
            },
            "elements": {
              "type": "array",
              "items": {
                "$ref": "#/definitions/IRValue"
              }
            }
          }
        },
        {
          "type": "object",
          "additionalProperties": false,
          "required": [
            "kind",
            "properties"
          ],
          "properties": {
            "kind": {
              "const": "object"
            },
            "properties": {
              "type": "object",
              "additionalProperties": {
                "$ref": "#/definitions/IRValue"
              }
            }
          }
        }
      ]
    },
    "IRExpression": {
      "oneOf": [
        {
          "type": "object",
          "additionalProperties": false,
          "required": [
            "kind",
            "value"
          ],
          "properties": {
            "kind": {
              "const": "literal"
            },
            "value": {
              "$ref": "#/definitions/IRValue"
            }
          }
        },
        {
          "type": "object",
          "additionalProperties": false,
          "required": [
            "kind",
            "name"
          ],
          "properties": {
            "kind": {
              "const": "identifier"
            },
            "name": {
              "type": "string"
            }
          }
        },
        {
          "type": "object",
          "additionalProperties": false,
          "required": [
            "kind",
            "object",
            "property"
          ],
          "properties": {
            "kind": {
              "const": "member"
            },
            "object": {
              "$ref": "#/definitions/IRExpression"
            },
            "property": {
              "type": "string"
            }
          }
        },
        {
          "type": "object",
          "additionalProperties": false,
          "required": [
            "kind",
            "operator",
            "left",
            "right"
          ],
          "properties": {
            "kind": {
              "const": "binary"
            },
            "operator": {
              "type": "string"
            },
            "left": {
              "$ref": "#/definitions/IRExpression"
            },
            "right": {
              "$ref": "#/definitions/IRExpression"
            }
          }
        },
        {
          "type": "object",
          "additionalProperties": false,
          "required": [
            "kind",
            "operator",
            "operand"
          ],
          "properties": {
            "kind": {
              "const": "unary"
            },
            "operator": {
              "type": "string"
            },
            "operand": {
              "$ref": "#/definitions/IRExpression"
            }
          }
        },
        {
          "type": "object",
          "additionalProperties": false,
          "required": [
            "kind",
            "callee",
            "args"
          ],
          "properties": {
            "kind": {
              "const": "call"
            },
            "callee": {
              "$ref": "#/definitions/IRExpression"
            },
            "args": {
              "type": "array",
              "items": {
                "$ref": "#/definitions/IRExpression"
              }
            }
          }
        },
        {
          "type": "object",
          "additionalProperties": false,
          "required": [
            "kind",
            "condition",
            "consequent",
            "alternate"
          ],
          "properties": {
            "kind": {
              "const": "conditional"
            },
            "condition": {
              "$ref": "#/definitions/IRExpression"
            },
            "consequent": {
              "$ref": "#/definitions/IRExpression"
            },
            "alternate": {
              "$ref": "#/definitions/IRExpression"
            }
          }
        },
        {
          "type": "object",
          "additionalProperties": false,
          "required": [
            "kind",
            "elements"
          ],
          "properties": {
            "kind": {
              "const": "array"
            },
            "elements": {
              "type": "array",
              "items": {
                "$ref": "#/definitions/IRExpression"
              }
            }
          }
        },
        {
          "type": "object",
          "additionalProperties": false,
          "required": [
            "kind",
            "properties"
          ],
          "properties": {
            "kind": {
              "const": "object"
            },
            "properties": {
              "type": "array",
              "items": {
                "type": "object",
                "additionalProperties": false,
                "required": [
                  "key",
                  "value"
                ],
                "properties": {
                  "key": {
                    "type": "string"
                  },
                  "value": {
                    "$ref": "#/definitions/IRExpression"
                  }
                }
              }
            }
          }
        },
        {
          "type": "object",
          "additionalProperties": false,
          "required": [
            "kind",
            "params",
            "body"
          ],
          "properties": {
            "kind": {
              "const": "lambda"
            },
            "params": {
              "type": "array",
              "items": {
                "type": "string"
              }
            },
            "body": {
              "$ref": "#/definitions/IRExpression"
            }
          }
        },
        {
          "type": "object",
          "additionalProperties": false,
          "required": [
            "kind",
            "op",
            "entity",
            "predicates"
          ],
          "properties": {
            "kind": {
              "const": "aggregate"
            },
            "op": {
              "enum": ["count", "sum"],
              "description": "Aggregate operation: count rows, or sum a numeric field."
            },
            "entity": {
              "type": "string",
              "description": "Entity whose rows are counted."
            },
            "predicates": {
              "type": "array",
              "description": "ANDed equality predicates: counted row.<field> == <value>. At least one (the foreign-key match) is expected.",
              "items": {
                "type": "object",
                "additionalProperties": false,
                "required": ["field", "value"],
                "properties": {
                  "field": {
                    "type": "string",
                    "description": "Property on the counted entity."
                  },
                  "value": {
                    "$ref": "#/definitions/IRExpression",
                    "description": "Expression evaluated in the surrounding context (reaction params: the event payload)."
                  }
                }
              }
            },
            "field": {
              "type": "string",
              "description": "Required when `op` is `sum` — the numeric property to aggregate."
            }
          }
        }
      ]
    },
    "ConstraintOutcome": {
      "type": "object",
      "additionalProperties": false,
      "required": [
        "code",
        "constraintName",
        "severity",
        "formatted",
        "passed"
      ],
      "properties": {
        "code": {
          "type": "string",
          "description": "Stable constraint identifier"
        },
        "constraintName": {
          "type": "string",
          "description": "Constraint name for reference"
        },
        "severity": {
          "type": "string",
          "enum": [
            "ok",
            "warn",
            "block"
          ],
          "description": "Severity level of the constraint"
        },
        "formatted": {
          "type": "string",
          "description": "Formatted expression string"
        },
        "message": {
          "type": "string",
          "description": "Optional message from constraint"
        },
        "details": {
          "type": "object",
          "additionalProperties": true,
          "description": "Structured details for UI (resolved values)"
        },
        "passed": {
          "type": "boolean",
          "description": "Whether the constraint passed"
        },
        "overridden": {
          "type": "boolean",
          "description": "Whether the constraint was overridden"
        },
        "overriddenBy": {
          "type": "string",
          "description": "User who authorized the override"
        },
        "resolved": {
          "type": "array",
          "items": {
            "type": "object",
            "required": [
              "expression",
              "value"
            ],
            "properties": {
              "expression": {
                "type": "string"
              },
              "value": true
            }
          },
          "description": "Resolved expression values for debugging"
        }
      }
    },
    "OverrideRequest": {
      "type": "object",
      "additionalProperties": false,
      "required": [
        "constraintCode",
        "reason",
        "authorizedBy",
        "timestamp"
      ],
      "properties": {
        "constraintCode": {
          "type": "string",
          "description": "Constraint code to override"
        },
        "reason": {
          "type": "string",
          "description": "Reason for the override"
        },
        "authorizedBy": {
          "type": "string",
          "description": "User authorizing the override"
        },
        "timestamp": {
          "type": "number",
          "description": "Timestamp of override request"
        }
      }
    },
    "ConcurrencyConflict": {
      "type": "object",
      "additionalProperties": false,
      "required": [
        "entityType",
        "entityId",
        "expectedVersion",
        "actualVersion",
        "conflictCode"
      ],
      "properties": {
        "entityType": {
          "type": "string",
          "description": "Type of entity that conflicted"
        },
        "entityId": {
          "type": "string",
          "description": "ID of the entity instance"
        },
        "expectedVersion": {
          "type": "number",
          "description": "Expected version number"
        },
        "actualVersion": {
          "type": "number",
          "description": "Actual version in storage"
        },
        "conflictCode": {
          "type": "string",
          "description": "Conflict code for categorization"
        }
      }
    },
    "IRValueObject": {
      "type": "object",
      "additionalProperties": false,
      "required": [
        "name",
        "properties"
      ],
      "properties": {
        "name": {
          "type": "string"
        },
        "properties": {
          "type": "array",
          "items": {
            "$ref": "#/definitions/IRProperty"
          },
          "description": "Value object properties (immutable, embedded inline in entity properties)"
        }
      }
    },
    "IRTenant": {
      "type": "object",
      "additionalProperties": false,
      "required": [
        "property",
        "type",
        "contextPath"
      ],
      "properties": {
        "property": {
          "type": "string",
          "description": "Property name injected into tenant-scoped entities"
        },
        "type": {
          "$ref": "#/definitions/IRType"
        },
        "contextPath": {
          "type": "string",
          "description": "Context path to extract tenant value at runtime"
        }
      }
    },
    "IRReactionRule": {
      "type": "object",
      "additionalProperties": false,
      "required": [
        "event",
        "targetEntity",
        "targetCommand"
      ],
      "properties": {
        "event": {
          "type": "string",
          "description": "Name of the triggering event (must match a declared event)"
        },
        "targetEntity": {
          "type": "string",
          "description": "Entity type on which to invoke the command"
        },
        "targetCommand": {
          "type": "string",
          "description": "Command name to execute on the target entity"
        },
        "match": {
          "type": "array",
          "items": {
            "type": "object",
            "additionalProperties": false,
            "required": ["field", "source"],
            "properties": {
              "field": {
                "type": "string",
                "description": "Field on targetEntity to match against"
              },
              "source": {
                "$ref": "#/definitions/IRExpression",
                "description": "Expression evaluated against event payload; compared to field value"
              }
            }
          }
        },
        "elseCreate": {
          "type": "boolean",
          "description": "When true: zero matches in match → run command without instanceId (allocate / createVia path)"
        },
        "resolve": {
          "$ref": "#/definitions/IRExpression",
          "description": "Expression evaluated against event payload to resolve the target instance ID. Absent for fanOut reactions (the collection match replaces single-target resolution)."
        },
        "fanOut": {
          "type": "object",
          "additionalProperties": false,
          "required": ["matchField", "matchSource"],
          "properties": {
            "matchField": {
              "type": "string",
              "description": "Field on the matched (source) entity to compare to matchSource"
            },
            "matchSource": {
              "$ref": "#/definitions/IRExpression",
              "description": "Expression evaluated against the event payload; every matchEntity row with row.<matchField> == matchSource is selected"
            },
            "matchEntity": {
              "type": "string",
              "description": "Entity queried for matches. When absent, equals targetEntity (same-entity fanOut). When set and different from targetEntity, params bind self/target to each matched source row and create runs without that row's instance id (foreach-create)."
            }
          },
          "description": "1:N cascade: for each matchEntity (default targetEntity) row matching matchField == matchSource, run targetEntity.targetCommand. Cross-entity form enables foreach-create (e.g. fanOut LineItem run Shipment.create)."
        },
        "params": {
          "type": "array",
          "items": {
            "$ref": "#/definitions/IRReactionParam"
          },
          "description": "Parameter mappings from event payload to command input"
        },
        "module": {
          "type": "string",
          "description": "Module that declares this reaction"
        },
        "entity": {
          "type": "string",
          "description": "Entity that declares this reaction (if entity-scoped)"
        }
      }
    },
    "IRReactionParam": {
      "type": "object",
      "additionalProperties": false,
      "required": [
        "name",
        "expression"
      ],
      "properties": {
        "name": {
          "type": "string",
          "description": "Target command parameter name"
        },
        "expression": {
          "$ref": "#/definitions/IRExpression",
          "description": "Expression evaluated against event payload to produce the parameter value"
        }
      }
    },
    "IRSaga": {
      "type": "object",
      "additionalProperties": false,
      "required": ["name", "steps", "onFailure", "emits"],
      "properties": {
        "name": {
          "type": "string",
          "description": "Saga name (unique within program)"
        },
        "module": {
          "type": "string",
          "description": "Module name if defined in a module"
        },
        "steps": {
          "type": "array",
          "items": {
            "$ref": "#/definitions/IRSagaStep"
          },
          "description": "Ordered saga steps"
        },
        "onFailure": {
          "type": "string",
          "enum": ["compensate", "abort"],
          "description": "Failure strategy: compensate runs completed steps in reverse, abort halts without compensation"
        },
        "emits": {
          "type": "array",
          "items": {
            "type": "string"
          },
          "description": "Lifecycle events emitted by the saga orchestrator"
        }
      }
    },
    "IRSagaStep": {
      "type": "object",
      "additionalProperties": false,
      "required": ["name", "commandEntity", "command"],
      "properties": {
        "name": {
          "type": "string",
          "description": "Step identifier (unique within saga)"
        },
        "commandEntity": {
          "type": "string",
          "description": "Entity on which the forward command is invoked"
        },
        "command": {
          "type": "string",
          "description": "Forward command name"
        },
        "compensateEntity": {
          "type": "string",
          "description": "Entity for the compensating command (present only when compensate is declared)"
        },
        "compensate": {
          "type": "string",
          "description": "Compensating command name (absent = no compensation for this step)"
        }
      }
    },
    "IRRolePermission": {
      "type": "object",
      "additionalProperties": false,
      "required": [
        "action"
      ],
      "properties": {
        "action": {
          "type": "string",
          "minLength": 1,
          "pattern": "^[A-Za-z_][A-Za-z0-9_]*$",
          "description": "Permission action. `all` is the wildcard and `read`/`write`/`delete`/`execute` are the conventional actions with built-in semantics (command-execution RBAC checks `execute`/`all`). Any other identifier is a custom, capability-style permission token, opaque to the engine and matched exactly (e.g. `salesAccess`)."
        },
        "target": {
          "type": "string",
          "description": "Optional command/entity name to narrow the permission scope"
        }
      }
    },
    "IRRole": {
      "type": "object",
      "additionalProperties": false,
      "required": [
        "name",
        "allow",
        "deny",
        "effectivePermissions"
      ],
      "properties": {
        "name": {
          "type": "string",
          "description": "Role name (unique within program)"
        },
        "module": {
          "type": "string",
          "description": "Module name if defined in a module"
        },
        "parent": {
          "type": "string",
          "description": "Parent role name for inheritance (single parent)"
        },
        "allow": {
          "type": "array",
          "items": {
            "$ref": "#/definitions/IRRolePermission"
          },
          "description": "Declared allow permissions (sorted)"
        },
        "deny": {
          "type": "array",
          "items": {
            "$ref": "#/definitions/IRRolePermission"
          },
          "description": "Declared deny permissions (sorted). Deny is absolute and overrides inherited allows."
        },
        "effectivePermissions": {
          "type": "array",
          "items": {
            "$ref": "#/definitions/IRRolePermission"
          },
          "description": "Compiler-computed flattened permission set after inheritance + deny resolution. Deterministic, sorted."
        }
      }
    },
    "IRWebhookSignature": {
      "type": "object",
      "required": ["algorithm", "header", "secret"],
      "additionalProperties": false,
      "properties": {
        "algorithm": {
          "type": "string",
          "enum": ["hmac-sha256", "hmac-sha512"],
          "description": "HMAC signature algorithm for payload verification"
        },
        "header": {
          "type": "string",
          "description": "HTTP header containing the signature value (e.g. \"X-Hub-Signature-256\")"
        },
        "secret": {
          "type": "string",
          "description": "Context path to extract the shared secret at runtime (e.g. \"context.webhookSecret\")"
        }
      }
    },
    "IRWebhookParam": {
      "type": "object",
      "required": ["name", "expression"],
      "additionalProperties": false,
      "properties": {
        "name": { "type": "string" },
        "expression": { "$ref": "#/definitions/IRExpression" }
      }
    },
    "IRWebhook": {
      "type": "object",
      "required": ["name", "path", "command"],
      "additionalProperties": false,
      "properties": {
        "name": { "type": "string" },
        "module": { "type": "string" },
        "path": {
          "type": "string",
          "description": "HTTP path pattern for this webhook route (e.g. \"/webhooks/stripe\")"
        },
        "method": {
          "type": "string",
          "description": "HTTP method to match. Defaults to POST at runtime."
        },
        "command": { "type": "string" },
        "entity": { "type": "string", "description": "Optional entity context for entity-scoped commands" },
        "signature": { "$ref": "#/definitions/IRWebhookSignature" },
        "idempotencyHeader": {
          "type": "string",
          "description": "HTTP header name from which to extract the idempotency key for deduplication"
        },
        "transform": {
          "type": "array",
          "items": { "$ref": "#/definitions/IRWebhookParam" },
          "description": "Payload transformation expressions: maps command parameter names to payload field expressions"
        }
      }
    },
    "IRRetry": {
      "type": "object",
      "required": ["maxAttempts", "backoff", "delayMs"],
      "additionalProperties": false,
      "properties": {
        "maxAttempts": {
          "type": "number",
          "description": "Maximum number of retry attempts"
        },
        "backoff": {
          "type": "string",
          "enum": ["fixed", "linear", "exponential"],
          "description": "Backoff strategy for retry delays"
        },
        "delayMs": {
          "type": "number",
          "description": "Base delay in milliseconds"
        },
        "maxDelayMs": {
          "type": "number",
          "description": "Optional upper bound on each computed backoff delay in milliseconds"
        },
        "jitter": {
          "type": "boolean",
          "description": "Whether to apply jitter to retry delays"
        },
        "retryOn": {
          "type": "array",
          "items": { "type": "string" },
          "description": "Error codes that trigger a retry (e.g. CONCURRENCY_CONFLICT, TIMEOUT)"
        }
      }
    },
    "IRRateLimit": {
      "type": "object",
      "required": ["maxRequests", "windowMs", "scope"],
      "additionalProperties": false,
      "properties": {
        "maxRequests": {
          "type": "number",
          "description": "Maximum number of requests per window"
        },
        "windowMs": {
          "type": "number",
          "description": "Time window in milliseconds"
        },
        "scope": {
          "type": "string",
          "enum": ["user", "tenant", "global"],
          "description": "Scope of rate limiting: user, tenant, or global"
        },
        "burstAllowance": {
          "type": "number",
          "description": "Burst allowance: additive requests above maxRequests"
        }
      }
    },
    "IRTrigger": {
      "type": "object",
      "required": ["kind"],
      "additionalProperties": false,
      "properties": {
        "kind": {
          "type": "string",
          "enum": ["cron", "interval", "every"],
          "description": "Trigger type: cron (expression-based), interval (milliseconds), or every (duration)"
        },
        "cron": {
          "type": "string",
          "description": "Cron expression (5 fields: minute hour day month dayOfWeek) when kind='cron'"
        },
        "durationMs": {
          "type": "number",
          "description": "Duration in milliseconds for interval or every triggers"
        }
      }
    },
    "IRScheduleParam": {
      "type": "object",
      "additionalProperties": false,
      "required": ["name", "expression"],
      "properties": {
        "name": {
          "type": "string",
          "description": "Parameter name"
        },
        "expression": {
          "$ref": "#/definitions/IRExpression",
          "description": "Expression evaluated at schedule fire time to produce the parameter value"
        }
      }
    },
    "IRSchedule": {
      "type": "object",
      "required": ["name", "commandName", "trigger"],
      "additionalProperties": false,
      "properties": {
        "name": {
          "type": "string",
          "description": "Schedule name (unique within program)"
        },
        "module": {
          "type": "string",
          "description": "Module name if defined in a module"
        },
        "entityName": {
          "type": "string",
          "description": "Entity on which the command is invoked (absent for global commands)"
        },
        "commandName": {
          "type": "string",
          "description": "Command name to invoke"
        },
        "trigger": {
          "$ref": "#/definitions/IRTrigger",
          "description": "Trigger configuration (cron, interval, or every)"
        },
        "params": {
          "type": "array",
          "items": {
            "$ref": "#/definitions/IRScheduleParam"
          },
          "description": "Parameters bound to the scheduled command"
        }
      }
    }
  }
}
