{
    "$schema": "https://json-schema.org/draft/2020-12/schema",
    "id": "https://valkyrlabs.com/schemas/thorapi-openapi-rules-v1.json",
    "title": "ThorAPI OpenAPI Canonical Ruleset (v1)",
    "version": "1.0.0",
    "description": "Canonical, authoritative rule set for authoring OpenAPI specs for ThorAPI (suitable for ThorAPI validator and agentic frameworks like ValorIDE).",
    "meta": {
        "author": "ValkyrLabs",
        "publishedAt": "2026-07-18",
        "sources": [
            "GET /v1/abi/rules",
            "/products/thorapi/extension-reference"
        ]
    },
    "reservedWords": {
        "openapi_yaml": [
            "meta",
            "class"
        ],
        "url_chars": [
            "%",
            "?",
            "*",
            "@",
            "!",
            "(",
            ")"
        ],
        "java_keywords": [
            "String",
            "Float",
            "Integer",
            "Object",
            "Long",
            "Array",
            "Boolean"
        ],
        "sql_keywords": [
            "UNION",
            "JOIN",
            "SELECT",
            "INSERT",
            "UPDATE",
            "DELETE"
        ],
        "thorapi_objects": [
            "ApiUtil",
            "MediaType",
            "Mono",
            "Content"
        ]
    },
    "autoGeneratedFields": [
        "id",
        "modified_date",
        "created_date",
        "owner_id",
        "key_hash",
        "last_modified_by_id",
        "last_modified_date",
        "last_accessed_by_id",
        "last_accessed_date",
        "trashed"
    ],
    "vendorExtensions": {
        "x-thorapi-nonCrud": {
            "type": "boolean",
            "semantics": "marks operation as non-CRUD; generator emits streamlined method"
        },
        "x-thorapi-disable-stats": {
            "type": "boolean",
            "semantics": "prevents get*Stats endpoint generation"
        },
        "x-thorapi-handler-class": {
            "type": "string",
            "semantics": "FQCN to autowire for delegated handling"
        },
        "x-thorapi-handler-bean": {
            "type": "string",
            "semantics": "bean name to autowire"
        },
        "x-thorapi-handler-method": {
            "type": "string",
            "semantics": "method name on bean to call"
        },
        "x-thorapi-secureField": {
            "type": "boolean",
            "semantics": "mark this property as encrypted at rest/in memory; THORAPI_SECRET_KEY required"
        },
        "x-thorapi-dataField": {
            "type": [
                "string",
                "object"
            ],
            "semantics": "PII tagging / data-field metadata (e.g. 'unique=true, fieldGroup=personal-details')"
        },
        "x-thorapi-suppress-audit": {
            "type": "boolean",
            "semantics": "prevent default injection of audit fields for this schema"
        },
        "x-thorapi-hidden": {
            "type": "boolean",
            "semantics": "mark property as hidden (readOnly in generated API)"
        },
        "x-thorapi-generateService": {
            "type": "boolean",
            "semantics": "force generation of service layer"
        },
        "x-thorapi-generateRepository": {
            "type": "boolean",
            "semantics": "force generation of repository"
        },
        "x-thorapi-relationship-contract": {
            "type": "string",
            "allowedValues": [
                "shared",
                "owned"
            ],
            "semantics": "declares generated persistence lifecycle ownership. Use shared for lookup/reference rows that must survive deletes; use owned for aggregate child collections that may be orphan/cascade deleted with the parent."
        },
        "x-thorapi-mapped-by": {
            "type": "string",
            "semantics": "names the child-side JPA relationship that owns the foreign key for an owned bidirectional collection"
        }
    },
    "rules": [
        {
            "id": "no-additionalProperties-object",
            "title": "Disallow object 'additionalProperties' in component schemas",
            "severity": "error",
            "description": "Free-form or complex object-style 'additionalProperties' definitions are not supported for ThorAPI model components because they cannot be mapped safely to database schema/persistent entities and break serialization. Primitive maps such as string, integer, number, and boolean values are supported by ThorAPI's element-map handling.",
            "check": "Any schema under '#/components/schemas/*' must not include 'additionalProperties: true' or complex object sub-schemas. Primitive map values are allowed when 'additionalProperties' declares type string, integer, number, or boolean.",
            "fix": "Use a primitive additionalProperties schema for element maps, replace complex map values with explicit named fields/$ref relationships, or change the field to 'type: string' if free-form JSON text storage is acceptable.",
            "examples": {
                "invalid": [
                    "MyObj:\n  type: object\n  properties:\n    attrs:\n      type: object\n      additionalProperties: true",
                    "MyObj:\n  type: object\n  properties:\n    attrs:\n      type: object\n      additionalProperties:\n        type: object\n        properties:\n          value:\n            type: string"
                ],
                "valid": [
                    "MyObj:\n  type: object\n  properties:\n    labels:\n      type: object\n      additionalProperties:\n        type: string",
                    "AttrsJson:\n  type: string\n  description: 'Free-form json stored as text'"
                ]
            },
            "sources": [
                "README.md:NOTE: Never use 'additionalProperties' ...",
                ".valoride/archive/valoride-rag-support.json"
            ]
        },
        {
            "id": "use-named-schemas-for-complex-types",
            "title": "Use named schemas ($ref) for complex/inline objects",
            "severity": "error",
            "description": "Avoid inline anonymous object schemas (e.g., 'type: object' with inline properties). Instead, create a named component schema and reference it with '$ref'. This improves codegen, DB mapping, and avoids 'java.lang.Object' association errors.",
            "check": "All complex property definitions (object with properties or array items that are objects) must use '$ref' to '#/components/schemas/...'.",
            "fix": "Move inline object into '#/components/schemas/<Name>' and set the property to '$ref: \"#/components/schemas/<Name>\"'.",
            "examples": {
                "invalid": [
                    "myProp:\n  type: object\n  properties:\n    a:\n      type: string"
                ],
                "valid": [
                    "MyType:\n  $ref: '#/components/schemas/MyType'\n# and separate component:\nMyType:\n  type: object\n  properties:\n    a:\n      type: string"
                ]
            },
            "sources": [
                ".valoride/archive/valoride-rag-support.json",
                "README.md"
            ]
        },
        {
            "id": "shared-scalar-enum-components",
            "title": "Allow typed shared scalar enum components",
            "severity": "error",
            "description": "Top-level shared enum components are supported when they declare a scalar type such as string, integer, number, or boolean. ThorAPI marks these scalar enum schemas as non-CRUD during enhancement so they generate as Java enums and do not become persistence entities, repositories, services, or database tables. Bare enum-only schemas without a scalar type are ambiguous and invalid.",
            "check": "A schema under '#/components/schemas/*' may contain enum values without properties only when it also declares a supported scalar type and has no '$ref'. Bare enum schemas without type must be rejected.",
            "fix": "For shared enums, add an explicit scalar type, usually 'type: string'. For persisted records, model an object schema and put the enum on a property.",
            "examples": {
                "invalid": [
                    "SharedStatus:\n  enum:\n    - ACTIVE\n    - ARCHIVED"
                ],
                "valid": [
                    "SharedStatus:\n  type: string\n  enum:\n    - ACTIVE\n    - ARCHIVED",
                    "Task:\n  type: object\n  properties:\n    status:\n      $ref: '#/components/schemas/SharedStatus'"
                ]
            },
            "sources": [
                "thorapi/src/main/java/com/valkyrlabs/ThorAPI.java:markScalarEnumSchemasNonCrud",
                "thorapi/src/main/java/com/valkyrlabs/ThorApiRulesValidator.java",
                "valkyrai/src/test/java/com/valkyrlabs/valkyrai/template/EnumModelTemplateGenerationContractTest.java"
            ]
        },
        {
            "id": "forbid-auto-generated-fields-in-spec",
            "title": "Do not declare ThorAPI auto-generated fields in your component schemas",
            "severity": "error",
            "description": "Fields that ThorAPI/ValkyrAI inject automatically must not be pre-declared in component schemas. Let ThorAPI manage them or use 'x-thorapi-suppress-audit: true' if you truly need to avoid injection.",
            "check": "Schema properties must not include any property in the 'autoGeneratedFields' list unless you have an explicit justification and know how to manage conflicts.",
            "fix": "Remove these fields from your spec; if you must control audit fields, set 'x-thorapi-suppress-audit: true' at the schema level and coordinate behavior with ThorAPI team.",
            "examples": {
                "invalid": [
                    "MyModel:\n  properties:\n    id:\n      type: string"
                ],
                "valid": [
                    "MyModel:\n  x-thorapi-suppress-audit: true\n  properties:\n    name:\n      type: string"
                ]
            },
            "sources": [
                "README.md:Auto-Generated Fields",
                "thorapi/src/main/java/com/valkyrlabs/ThorAPI.java"
            ]
        },
        {
            "id": "reserved-words-avoidance",
            "title": "Avoid reserved words and characters in identifiers",
            "severity": "error",
            "description": "Do not use reserved words (OpenAPI, Java, SQL, ThorAPI objects) or URL-special characters in model names or property names. This prevents SQL or codegen syntax errors.",
            "check": "Any '#/components/schemas/*' name or property name containing reserved words/characters must be flagged.",
            "fix": "Rename the identifier (examples: 'Content' -> 'ContentData', 'Mono' -> 'MonoResource', 'schema' -> 'schema_' with @Column mapping if necessary).",
            "examples": {
                "invalid": [
                    "properties:\n  schema:\n    type: string"
                ],
                "valid": [
                    "properties:\n  _class:\n    type: string\n    x-field-extra-annotation: '@Column(name = \"class\")'"
                ]
            },
            "sources": [
                "README.md:Reserved Words"
            ]
        },
        {
            "id": "secure-field-requirements",
            "title": "Rules for encrypted fields (SecureField)",
            "severity": "error",
            "description": "To enable field-level encryption, mark a property with 'x-thorapi-secureField: true'. A THORAPI_SECRET_KEY MUST be provided to ThorAPI at build/run-time; losing this key will permanently make encrypted data unrecoverable.",
            "check": "Properties with 'x-thorapi-secureField' must be booleans and THORAPI builds must be run with THORAPI_SECRET_KEY provided in env or command line.",
            "fix": "Add 'x-thorapi-secureField: true' to property you want encrypted and ensure THORAPI_SECRET_KEY is set in CI/build environment. Do not change key without rotating & migrating data.",
            "examples": {
                "invalid": [
                    "password:\n  type: string"
                ],
                "valid": [
                    "password:\n  type: string\n  x-thorapi-secureField: true"
                ]
            },
            "sources": [
                "README.md:SecureField",
                "README.md:THORAPI_SECRET_KEY is MANDATORY"
            ]
        },
        {
            "id": "vendor-extensions-types-and-usage",
            "title": "x-thorapi vendor extensions: types and semantics",
            "severity": "error",
            "description": "Vendor extensions must use documented keys and value types. Unknown or misspelled x-thorapi keys should be flagged to avoid unexpected generator behavior.",
            "check": "All extension keys matching /^x-thorapi-/ must be in the known 'vendorExtensions' list and have the expected type (boolean/string/object).",
            "fix": "Correct the key name and value type or consult documentation for new extensions.",
            "examples": {
                "invalid": [
                    "x-thorapi-disable-stats: 'yes'"
                ],
                "valid": [
                    "x-thorapi-disable-stats: true"
                ]
            },
            "sources": [
                "README.md:ThorAPI OpenAPI Extensions",
                "thorapi/src/main/java/com/valkyrlabs/ThorAPI.java"
            ]
        },
        {
            "id": "suppress-audit-flag-behavior",
            "title": "If 'x-thorapi-suppress-audit' is set, ThorAPI will not inject audit fields",
            "severity": "info",
            "description": "Setting 'x-thorapi-suppress-audit: true' on a schema prevents ThorAPI from injecting audit fields (id, createdDate, ownerId, etc.). Use cautiously.",
            "check": "If schema has 'x-thorapi-suppress-audit: true' then audit fields will not be injected; validator should allow that but surface as informational note.",
            "fix": "Set the flag only when you're intentionally avoiding audit injection and have a compatible persistence strategy.",
            "sources": [
                "thorapi/src/main/java/com/valkyrlabs/ThorAPI.java"
            ]
        },
        {
            "id": "no-inline-objects-in-array-items",
            "title": "Array 'items' should reference named schemas for complex objects",
            "severity": "error",
            "description": "Array items that are objects must use '$ref' to a named schema rather than inline anonymous object schemas.",
            "check": "For any property where type: array AND items is an object with properties, require a $ref to a component schema.",
            "fix": "Define the items type under '#/components/schemas' and use $ref for the array items.",
            "examples": {
                "invalid": [
                    "tags:\n  type: array\n  items:\n    type: object\n    properties:\n      name:\n        type: string"
                ],
                "valid": [
                    "tags:\n  type: array\n  items:\n    $ref: '#/components/schemas/Tag'\n# components: Tag -> type: object ..."
                ]
            },
            "sources": [
                ".valoride/archive/valoride-rag-support.json",
                "README.md"
            ]
        },
        {
            "id": "allof-oneof-guidance",
            "title": "Guidance for using allOf / oneOf / anyOf",
            "severity": "error",
            "description": "Avoid anonymous inline schemas inside allOf/oneOf/anyOf for entities. Prefer referencing named component schemas for each discriminator branch or combined type. For polymorphic models, include an explicit discriminator when different branches map to different concrete entities.",
            "check": "If a schema uses allOf/oneOf/anyOf where any item is an inline object schema (has properties inline), require conversion to named '$ref' component schemas; if polymorphism is intended, require a 'discriminator' field mapping.",
            "fix": "Refactor inline schemas into components under '#/components/schemas' and reference them via $ref. For polymorphism add a 'discriminator' object to the parent schema per OpenAPI rules.",
            "examples": {
                "invalid": [
                    "Pet:\n  oneOf:\n    - type: object\n      properties:\n        name:\n          type: string\n    - type: object\n      properties:\n        amount:\n          type: number"
                ],
                "valid": [
                    "Pet:\n  oneOf:\n    - $ref: '#/components/schemas/Cat'\n    - $ref: '#/components/schemas/Dog'\n# and in components: Cat/Dog are named objects with properties"
                ]
            },
            "sources": [
                "OpenAPI:a best practice",
                ".valoride/archive/valoride-rag-support.json"
            ]
        },
        {
            "id": "allof-property-conflict",
            "title": "Detect property conflicts across allOf/oneOf merging",
            "severity": "error",
            "description": "When using allOf to compose multiple component schemas, ensure merged properties do not conflict in type/format or required-ness. Conflicting declarations can lead to generated code and DB mapping errors.",
            "check": "For any schema that composes via allOf, compare property definitions across referenced components; flag if the same property name has inconsistent types/formats or contradictory required flags.",
            "fix": "Unify property definitions in a single named component, or rename conflicting properties. Consider explicit type compatibility or wrapper fields.",
            "examples": {
                "invalid": [
                    "A:\n  allOf:\n    - $ref: '#/components/schemas/Part1'\n    - $ref: '#/components/schemas/Part2'\n# where Part1 has 'count: type: string' and Part2 has 'count: type: integer'"
                ],
                "valid": [
                    "A:\n  allOf:\n    - $ref: '#/components/schemas/Part1'\n    - $ref: '#/components/schemas/Part2'\n# where both define 'count' as integer"
                ]
            },
            "sources": [
                "OpenAPI:composition guidance",
                "ThorAPI codegen best practices"
            ]
        },
        {
            "id": "x-thorapi-datafield-format",
            "title": "Validate 'x-thorapi-dataField' formatting and keys",
            "severity": "error",
            "description": "The 'x-thorapi-dataField' extension can be either a string of comma-separated key=value pairs or an object. When a string is used, it must be parseable into key=value pairs using comma separation. When an object is used, only allowed keys are permitted and values must be of the expected type.",
            "check": "For 'x-thorapi-dataField' values that are strings, validate they parse as comma-separated 'k=v' pairs and keys are from the allowed set (unique, fieldGroup, advanced, index, hidden). For object values validate keys and types (boolean for unique/advanced/hidden/index, string for fieldGroup).",
            "fix": "Use an object form for clarity (e.g., x-thorapi-dataField: {\"unique\":true, \"fieldGroup\":\"personal-details\"}) or ensure string is valid 'unique=true, fieldGroup=personal'.",
            "examples": {
                "invalid": [
                    "x-thorapi-dataField: 'yes,group=personal'",
                    "x-thorapi-dataField: 'unique=maybe'"
                ],
                "valid": [
                    "x-thorapi-dataField: \"unique=true,fieldGroup=personal-details\"",
                    "x-thorapi-dataField:\n  unique: true\n  fieldGroup: \"personal-details\""
                ]
            },
            "sources": [
                "README.md:x-thorapi-dataField conventions",
                "ThorAPI enhancement logic"
            ]
        },
        {
            "id": "typescript-rtk-query-boundaries",
            "title": "Keep generated ThorAPI RTK Query output and custom RTK slices separate",
            "severity": "error",
            "description": "Generated ThorAPI TypeScript RTK Query clients and generated UI components are generated artifacts. Custom, non-generated REST APIs must live under the application redux tree, while generated behavior must be changed through OpenAPI or mustache templates and regenerated.",
            "check": "Generated RTK Query services, hooks, models, and components under src/thorapi/redux must not be hand-edited. Custom RTK Query slices belong under src/redux/services and must be registered in the app Redux store. If generated behavior needs to change, update api.hbs.yaml, the OpenAPI source, or web/src/main/resources/templates/typescript-redux-query/*.mustache and run ./vaix generate.",
            "fix": "Move custom RTK Query code to src/redux/services and register it in src/redux/store.tsx. For generated client/component behavior, update api.hbs.yaml or the typescript-redux-query mustache templates, then regenerate with ./vaix generate instead of patching src/thorapi/redux output.",
            "examples": {
                "invalid": [
                    "Patch src/thorapi/redux/services/WidgetService.tsx by hand to add cache tags.",
                    "Create a canonical REST client in src/services/widgetApi.ts that bypasses RTK Query for ThorAPI data."
                ],
                "valid": [
                    "Update web/src/main/resources/templates/typescript-redux-query/modelService.mustache, then run ./vaix generate.",
                    "Create src/redux/services/creditsApi.ts for non-generated credits endpoints and register creditsApi.reducer and creditsApi.middleware in src/redux/store.tsx."
                ]
            },
            "sources": [
                "README.md:Frontend RTK Query Boundaries",
                "docs/THORAPI_OPENAPI_SPEC_AGENT_GUIDE.md:TypeScript RTK Query Boundaries",
                "web/src/main/resources/templates/typescript-redux-query/"
            ]
        },
        {
            "id": "relationship-contract-required-for-nontrivial-refs",
            "title": "Declare relationship ownership for generated persistence references",
            "severity": "error",
            "description": "Relationship fields that participate in generated persistence should declare whether target rows are shared references or owned aggregate children. ThorAPI uses this to generate safe delete/update behavior: shared nullable references detach with ON DELETE SET NULL, many-to-many relationships remove only join rows, and owned one-to-many child collections may be orphan/cascade deleted.",
            "check": "For object references and arrays of object references where lifecycle ownership is non-obvious, set x-thorapi-relationship-contract to 'shared' or 'owned'. 'owned' is valid for aggregate child collections; use 'shared' for lookup/reference/principal/org/tag/content rows that can be used by multiple parents.",
            "fix": "Add x-thorapi-relationship-contract: shared or x-thorapi-relationship-contract: owned on the relationship property. Do not use CascadeType.REMOVE on shared ManyToOne or ManyToMany relationships.",
            "examples": {
                "invalid": [
                    "Order:\n  properties:\n    customer:\n      $ref: '#/components/schemas/Customer'",
                    "Invoice:\n  properties:\n    lineItems:\n      type: array\n      items:\n        $ref: '#/components/schemas/InvoiceLineItem'"
                ],
                "valid": [
                    "Order:\n  properties:\n    customer:\n      $ref: '#/components/schemas/Customer'\n      x-thorapi-relationship-contract: shared",
                    "Invoice:\n  properties:\n    lineItems:\n      type: array\n      items:\n        $ref: '#/components/schemas/InvoiceLineItem'\n      x-thorapi-relationship-contract: owned"
                ]
            },
            "sources": [
                "valkyrai/src/main/resources/templates/JavaSpring/pojo.mustache",
                "valkyrai/src/main/resources/templates/JavaSpring/repository.mustache",
                "thorapi/src/main/java/com/valkyrlabs/ThorAPI.java"
            ]
        }
    ],
    "usage": {
        "validatorIntegration": "Rules should be applied as JSON-schema style checks or custom AST checks during spec validation (e.g., in ValorIDE or ThorAPI pre-processing).",
        "agentGuidance": "Agents that generate or modify specs/templates MUST obey these rules: rename reserved identifiers, replace inline objects with $ref, avoid additionalProperties for persisted objects, keep generated ThorAPI RTK Query output untouched, put custom RTK Query slices under src/redux/services, and fix generated client behavior through api.hbs.yaml or mustache templates followed by ./vaix generate.",
        "cli": "Run './vaix generate' and './vaix test' to ensure ThorAPI enhancement and codegen are executed before tests or builds. Do not run 'mvn' directly without the helper (see README)."
    }
}
