reference integrator

Published Spec Contract Reference

The exact schema of published_versions.spec — the data contract written by SmartRules and consumed by eApproval, the Portal, and integrations.


1. Overview

When SmartRules publishes a procedure, it writes a single JSON blob into published_versions.spec. This blob is an append-only snapshot: it freezes the procedure definition at publish time and becomes the canonical contract for every downstream consumer.

Key properties:

  • Immutable — once published, the spec never changes. New publishes create new published_versions rows.
  • Self-contained — every consumer must be able to operate from the spec alone, without querying SmartRules tables.
  • Defensively consumed — all runtime code uses .get() with sensible defaults. The Pydantic model FormSchemaV1 is used only at the public API boundary.
  • Backward-compatible — new keys are additive. Legacy specs missing newer keys are tolerated.

Current schema version: 1 (hard-coded in smartrules/publishing.py).


2. Top-Level Structure

{
  "schema_version": 1,
  "procedure": { ... },
  "agency": { ... },
  "total_requirements": 5,
  "sections": [ ... ],
  "registry": { ... },
  "trust_progression": { ... },
  "requirements": [ ... ],
  "roles": [ ... ],
  "edges": [ ... ],
  "evaluation_criteria": [ ... ],
  "filters": [ ... ],
  "event_bindings": [ ... ],
  "integration_standards_compliance": { ... }
}
KeyRequiredAddedDescription
schema_versionYesPlan 2Always 1
procedureYesPlan 1Procedure metadata
agencyYesPlan 1Agency reference
total_requirementsYesPlan 1Count of requirements
sectionsYesPlan 1Display-oriented requirement grouping
registryNoPlan 2 Task 11Registry contract block
registry_entitiesNoD26 Phase C Task 2One block per repeating group bound to a typed child entity
trust_progressionNoPlan 2 Task 11State machine definition
requirementsNoPlan 2 Task 11Registry-column-oriented requirement list
rolesYesPlan 1DAG nodes
edgesYesPlan 1DAG edges
evaluation_criteriaYesPlan 1Checklists per role/requirement
filtersYesPlan 1Display filters
event_bindingsNoPhase 2BSnapshotted SmartLink event bindings
integration_standards_complianceNoPhase 2BBinding compliance summary

Backward compatibility: registry, trust_progression, requirements, event_bindings, and integration_standards_compliance are all optional because specs published before Phase 2B/Plan 2 Task 11 do not contain them. Consumers must use .get() with defaults.


3. Block-by-Block Reference

3.1 procedure

{
  "id": "550e8400-e29b-41d4-a716-446655440000",
  "name": "Register a Business",
  "description": "Commerce registration procedure",
  "legal_basis": "Commerce Act 2024",
  "category": "Business",
  "version": 3,
  "verification_mode": "application",
  "max_correction_depth": 3
}
FieldTypeDefaultDescription
idstr (UUID)—Procedure primary key
namestr—Human-readable title
descriptionstr | nullnullLong-form description
legal_basisstr | nullnullLegal authority
categorystr | nullnullCategory label
versionint—Monotonically increasing publish counter
verification_modestr"application""application" or "claim"
max_correction_depthint3Max correction loops before terminal rejection

Consumers:

  • published/routes.py — procedure.name for public listing
  • eapproval/routes.py — procedure.name for application list items
  • eapproval/projections.py — procedure.verification_mode (default "application")
  • eapproval/routes.py — procedure.max_correction_depth (default 3)
  • eapproval/notification_threads/inbox_service.py — procedure.name for inbox display

3.2 agency

{
  "id": "550e8400-e29b-41d4-a716-446655440001"
}
FieldTypeDescription
idstr (UUID)Agency primary key

Note: The agency ID and name are stored directly, not resolved at runtime. country_code is also stored as of D26 Phase C Task 2 (smartrules/publishing.py:1698) — it scopes registry_entities (see §2’s row above; shape documented in docs/specs/embedded-mode-contract.md) the same way registry.country_code already scopes the embedded-mode top-level table (§3.5 below). Any other agency metadata beyond these three fields is still resolved at runtime via the deployments registry or cached separately.


3.3 total_requirements

An integer equal to len(requirements) at publish time. Used by the Portal for progress indicators.


3.4 sections

Display-oriented grouping of requirements. Requirements are grouped by their section name (default "General").

[
  {
    "title": "Business",
    "requirements": [
      {
        "id": "550e8400-e29b-41d4-a716-446655440002",
        "field_name": "businessName",
        "field_type": "text",
        "label": "Business Name",
        "description": "Official registered name",
        "section": "Business",
        "sort_order": 1,
        "is_required": true,
        "condition": null,
        "formal_criteria": { ... },
        "substantial_criteria": null,
        "labels": null,
        "standard_ref": null,
        "variants": null,
        "field_capabilities": { ... }
      }
    ]
  }
]

SectionRequirement fields:

FieldTypeDescription
idstr (UUID)Requirement primary key
field_namestrCamelCase identifier (used as form key)
field_typestrtext, number, date, boolean, yes_no, list, document, email, phone, address
labelstrHuman label
descriptionstr | nullHelper text
sectionstr | nullGrouping name
sort_orderintDisplay order within section
is_requiredboolWhether the field is mandatory
conditionstr | nullJSONata or conditional expression
formal_criteriaobject | nullProof modes, rules, binding config
substantial_criteriaobject | nullSubstantive evaluation criteria
labelsobject | nulli18n label overrides
standard_refstr | nullReference to external standard
variantsobject | array | nullVariant definitions
field_capabilitiesobject | nullPublish-time resolved SmartLink metadata

Consumers:

  • Portal — renders forms from sections[].requirements[]
  • published/lookup_routes.py — resolves field lookups by field_name
  • eapproval/bots.py — collects API proof modes from formal_criteria
  • eapproval/registry_view.py — fallback column derivation when requirements contract block is absent

3.5 registry

The registry contract block defines how the published procedure maps to a physical registry table.

{
  "table_name": "ls_register_a_business",
  "primary_key": "reference_number",
  "status_vocabulary": [
    "submitted",
    "pending_commerce_review",
    "pending_tax_review",
    "registered"
  ],
  "registered_state": "registered",
  "country_code": "LS"
}
FieldTypeDerivation
table_namestr{country_code.lower()}_{slugify(procedure.name)}
primary_keystrHard-coded "reference_number"
status_vocabularyarray[str]["submitted"] + pending_<role> per topo order + ["registered"]
registered_statestrHard-coded "registered"
country_codestrAgency.country_code

Status vocabulary derivation:

  1. Start with ["submitted"]
  2. Append "pending_<slugified_role_name>" for each verification role in DAG topological order
  3. Append ["registered"]

Example: If verification roles are commerce_review then tax_review, the vocabulary is ["submitted", "pending_commerce_review", "pending_tax_review", "registered"].

Consumers:

  • eapproval/registry_view.py — contract-based column derivation
  • External integrations — table name for registry sync

3.6 trust_progression

State machine metadata derived from the registry vocabulary.

{
  "states": [
    "submitted",
    "pending_commerce_review",
    "pending_tax_review",
    "registered",
    "rejected"
  ],
  "initial_state": "submitted",
  "terminal_states": ["registered", "rejected"]
}
FieldTypeDerivation
statesarray[str]status_vocabulary + ["rejected"]
initial_statestr"submitted"
terminal_statesarray[str]["registered", "rejected"]

3.7 requirements (contract block)

The registry-column-oriented view of requirements. This block has a different shape from sections[].requirements[] — it is optimised for database schema generation and state transition tracking.

[
  {
    "id": "550e8400-e29b-41d4-a716-446655440002",
    "field_name": "businessName",
    "field_type": "text",
    "label": "Business Name",
    "section": "Business",
    "registry_column": {
      "name": "business_name",
      "logical_type": "text",
      "max_length": 255,
      "nullable": false,
      "status_column": "business_name_status",
      "initial_status": "submitted"
    },
    "state_transitions": [
      {
        "from": "submitted",
        "to": "pending_commerce_review",
        "role": "550e8400-e29b-41d4-a716-446655440010",
        "action": "assert"
      }
    ]
  }
]

ContractRequirement fields:

FieldTypeDescription
idstr (UUID)Requirement primary key
field_namestrCamelCase identifier
field_typestrSame as SectionRequirement
labelstr | nullHuman label
sectionstr | nullGrouping name
registry_columnobjectColumn definition (see below)
state_transitionsarray[object]Per-requirement state transitions

registry_column sub-block:

FieldTypeDerivation
namestr_snake_case(field_name)
logical_typestrMapped from field_type (see mapping table)
max_lengthint | omitted255 for text types
precisionint | omitted18 for number
scaleint | omitted4 for number
nullableboolnot is_required
status_columnstr{name}_status
initial_statusstr"submitted"

Logical type mapping:

SmartRules field_typeRegistry logical_type
text, list, document, email, phone, addresstext
numberdecimal
datedate
boolean, yes_noboolean

state_transitions sub-block:

FieldTypeDescription
fromstrPrevious state
tostrNext state
rolestr (UUID)Role ID that triggers this transition
actionstrAlways "assert" in current implementation

Transitions are derived per-requirement based on which verification roles are assigned to it. A role with empty assigned_requirement_ids is treated as “all requirements.”

Consumers:

  • eapproval/registry_view.py — primary contract-based registry view

3.8 roles

DAG nodes. Each role becomes a gate in eApproval.

[
  {
    "id": "550e8400-e29b-41d4-a716-446655440010",
    "name": "Commerce Review",
    "abbreviation": "COM",
    "role_type": "official",
    "node_type": "verification",
    "agent_type": "human",
    "agent_composition": "single",
    "method": null,
    "institution_id": null,
    "precondition_ids": [],
    "assigned_requirement_ids": [],
    "sla_days": 5,
    "sla_day_kind": "calendar_days",
    "quorum": null,
    "sort_order": 1,
    "can_reject": false
  }
]
FieldTypeDescription
idstr (UUID)Role primary key
namestr | nullHuman name
abbreviationstr | nullShort code
role_typestr | nullofficial, system, etc.
node_typestr | nullverification, automation, convergence
agent_typestr | nullhuman, bot
agent_compositionstr | nullsingle, quorum
methodstr | nullExecution method hint
institution_idstr | nullExternal institution reference
precondition_idsarray[str]UUIDs of roles that must complete before this one
assigned_requirement_idsarray[str]UUIDs of requirements this role verifies (empty = all)
sla_daysint | nullService-level agreement
sla_day_kindstrD57: what sla_days counts in — calendar_days or working_days. Never null on a published snapshot: an unconfirmed authoring choice writes as calendar_days (spec D-10).
quorumint | nullRequired approver count
sort_orderint | nullDisplay/tiebreak order
can_rejectbool | nullWhether this role may issue a definitive no (Rule 2 renamed can_terminate)

Consumers:

  • eapproval/dag.py — DAG computation (topological sort, start roles)
  • eapproval/routes.py — claim validation, role existence checks
  • eapproval/bots.py — automation role dispatch
  • eapproval/registry_view.py — state transition mapping

3.9 edges

Explicit DAG edges. If absent or empty, the DAG engine falls back to deriving edges from roles[].precondition_ids with trigger "assert".

[
  {
    "from_role_id": "550e8400-e29b-41d4-a716-446655440010",
    "to_role_id": "550e8400-e29b-41d4-a716-446655440011",
    "trigger": "assert"
  }
]
FieldTypeDescription
from_role_idstr (UUID)Source role
to_role_idstr (UUID)Target role
triggerstrOne of: assert, object_correctable, object_terminal, bot_failed

Consumers:

  • eapproval/dag.py — primary edge source
  • eapproval/gates.py — gate recomputation after claims

3.10 evaluation_criteria

Checklists attached to role + requirement pairs.

[
  {
    "id": "550e8400-e29b-41d4-a716-446655440020",
    "role_id": "550e8400-e29b-41d4-a716-446655440010",
    "requirement_id": "550e8400-e29b-41d4-a716-446655440002",
    "checklist": [
      {"item": "Name is not offensive", "required": true}
    ]
  }
]
FieldTypeDescription
idstr (UUID)Criteria primary key
role_idstr (UUID)Owning role
requirement_idstr (UUID)Owning requirement
checklistarray | nullJSON array of checklist items

3.11 qualifications

What an applicant may qualify for, decided by their own answers (D58). A snapshot minted before M101 carries filters instead; read paths accept both, and a legacy filter reads as a qualification with no rule (it never applies, exactly as before, since nothing evaluated it).

FieldTypeDescription
codestrstable identity; fee lines and application stamps join on it
name, labelsstr, {locale: str}the title the applicant sees
explanation, explanationsstr | null, {locale: str} | nullthe one sentence the applicant reads
ruleobject | null{"operator": "all"|"any", "children": [...]}; a leaf is a comparison, membership, pattern or temporal rule plus field
summarystr | nullthe plain sentence of the rule, written by the editor
visibility"applicant" | "agency"agency-only qualifications never appear in public responses
assigned_requirement_idsarray[str]questions asked only when the qualification applies
legal_basisstr | nullthe act and section that create it
legacy_conditionstr | nullthe sentence a converted filter or fee condition carried

The OpenAPI document carries the applicant-visible ones as x-opengov-qualifications; a legacy snapshot also keeps x-opengov-filters. POST /procedures/{id}/qualifications/evaluate with {"answers": {...}} returns each visible qualification’s state (indicated, not_indicated, undecidable, unreadable) and a reason that names a question, never an answer.


3.12 event_bindings

Snapshotted SmartLink event bindings at publish time. Changes to live EventBinding rows after publish do not affect already-published specs.

[
  {
    "id": "550e8400-e29b-41d4-a716-446655440040",
    "name": "Notify LRA on registration",
    "description": "Sends business data to LRA",
    "trigger": "gate_passed",
    "filter": {"role_id": "550e8400-e29b-41d4-a716-446655440010"},
    "connector_code": "lra",
    "operation_code": "register_business",
    "operation_version_pin": null,
    "payload_template": null,
    "recipient_idempotency": "verified_by_probe",
    "terminal_activation_ack": false,
    "schema_hash": "a3f7c2..."
  }
]
FieldTypeDescription
idstr (UUID)Binding primary key
namestrHuman label
descriptionstr | nullLong-form description
triggerstrgate_passed, gate_failed, all_gates_passed, convergence_passed
filterobjectDefault {}; may contain role_id
connector_codestrSmartLink connector code
operation_codestrSmartLink operation code
operation_version_pinint | nullOptional version pin
payload_templatestr | nullJSONata template for request body
recipient_idempotencystrverified_by_probe, attested_by_admin, not_supported, unknown
terminal_activation_ackboolWhether binding requires explicit activation ack
schema_hashstrSHA-256 of the operation’s request schema at publish time

3.13 integration_standards_compliance

Aggregate summary of event bindings for compliance dashboards.

{
  "bindings_count": 3,
  "verified_by_probe_count": 2,
  "attested_by_admin_count": 0,
  "not_supported_count": 0,
  "unknown_count": 1,
  "external_bindings_count": 1,
  "terminal_activation_ack_count": 0,
  "last_probe_summary": {
    "earliest_last_probe_at": "2026-04-01T12:00:00Z",
    "latest_last_probe_at": "2026-04-05T12:00:00Z"
  }
}
FieldTypeDescription
bindings_countintTotal bindings
verified_by_probe_countintBindings with recipient_idempotency == "verified_by_probe"
attested_by_admin_countintBindings with recipient_idempotency == "attested_by_admin"
not_supported_countintBindings with recipient_idempotency == "not_supported"
unknown_countintBindings with recipient_idempotency == "unknown"
external_bindings_countintBindings targeting external connectors
terminal_activation_ack_countintBindings with terminal_activation_ack == true
last_probe_summaryobject | null{earliest_last_probe_at, latest_last_probe_at} or null

4. Proof Modes

Proof modes live inside sections[].requirements[].formal_criteria as a free-form dict with a canonical shape.

4.1 Canonical structure

{
  "modes_of_proof": [
    {
      "type": "agency_api",
      "smartlink_binding": {
        "connector_code": "lra",
        "operation_code": "validate_tin"
      },
      "input_fields": ["tin"],
      "required_inputs": ["tin"],
      "lookup_mode": "display",
      "lookup_label": "Validate TIN",
      "debounce_ms": 500,
      "response_to_form_mapping": {}
    },
    {
      "type": "self_assertion"
    }
  ],
  "preferred_mode": "agency_api"
}

4.2 Valid type values

From src/opengov/smartrules/constants.py:

TypeMeaning
self_assertionApplicant declares the value without evidence
applicant_documentUploaded document provided by applicant
agency_documentDocument held by the agency
agency_apiReal-time API call to agency system (SmartLink)
third_party_documentDocument from an external party
third_party_apiReal-time API call to third party (SmartLink)

4.3 API proof mode extra fields

Only agency_api and third_party_api may carry:

FieldTypeDescription
smartlink_bindingobject{connector_code, operation_code}
input_fieldsarray[str]Form field names to send in the request
required_inputsarray[str]Subset that must be non-empty before triggering
lookup_modestrdisplay (show result), fill (auto-fill form), validate (green/red)
lookup_labelstrButton / link label
debounce_msintDelay before triggering lookup on typing
response_to_form_mappingobjectMapping of response keys → form field names (only for fill)

5. field_capabilities

Injected at publish time if an API proof mode has a valid SmartLink binding and the operation exists.

{
  "has_lookup": true,
  "lookup_mode": "display",
  "lookup_label": "Validate TIN",
  "debounce_ms": 500,
  "requires_auth": false,
  "cache_scope": "shared",
  "input_fields": ["tin"],
  "required_inputs": ["tin"],
  "response_to_form_mapping": {}
}
FieldTypeDescription
has_lookupboolAlways true if emitted
lookup_modestrdisplay, fill, validate
lookup_labelstrHuman label
debounce_msintDelay before trigger
requires_authboolWhether the operation requires authenticated callers
cache_scopestrshared, user, session
input_fieldsarray[str]Fields to send
required_inputsarray[str]Required fields before trigger
response_to_form_mappingobjectFill mapping (only when lookup_mode == "fill")

Important: field_capabilities is resolved at publish time against the current SmartLink operation config. If the operation is deleted or changed later, already-published specs retain the old capabilities.


6. Consumer Expectations

ConsumerReads from specFallback if missing
Portal listingprocedure.name""
Portal formsections[].requirements[]Empty form
Portal lookupsections[].requirements[].field_capabilities + formal_criteria.modes_of_proof[].smartlink_bindingHTTP 422 (lookup not configured)
eApproval DAGroles[], edges[]Derive edges from precondition_ids
eApproval gatesroles[].node_type, roles[].can_terminateDefaults (verification, false)
eApproval claimsroles[].idHTTP 400 (invalid role)
eApproval botssections[].requirements[].formal_criteria.modes_of_proof[]manual_needed
eApproval registry viewrequirements[].registry_column + state_transitionsFallback to sections[].requirements[]
eApproval inboxprocedure.name"(untitled)"
Published APIFull spec via FormSchemaV1Pydantic validation error at API boundary
Integration eventsevent_bindings[]No events dispatched

7. Backward Compatibility Rules

  1. New keys are additive. Never remove a key that existing consumers read.
  2. Consumers use .get() with defaults. All runtime code is defensive.
  3. Optional keys in FormSchemaV1. The Pydantic model marks post-Plan-2 keys as | None = None.
  4. Schema version is static. schema_version: 1 is hard-coded. There is no migration logic for spec contents.
  5. Legacy specs without requirements contract block are handled by eapproval/registry_view.py falling back to sections[].requirements[].
  6. Legacy specs without event_bindings simply dispatch no integration events.

8. Versioning & Evolution

If a breaking change to the spec schema is ever needed:

  1. Bump schema_version to 2 in smartrules/publishing.py.
  2. Add a new Pydantic model (e.g. FormSchemaV2) in published/schemas.py.
  3. Teach consumers to branch on schema_version.
  4. Update tests/published/test_formschema_v1.py to cover both versions.

Current policy: Avoid breaking changes. Add optional keys instead.


9. Minimal vs Maximal Example

Minimal spec (legacy, pre-Plan 2)

{
  "schema_version": 1,
  "procedure": {
    "id": "uuid",
    "name": "Simple Procedure",
    "version": 1
  },
  "agency": {"id": "uuid"},
  "total_requirements": 0,
  "sections": [],
  "roles": [],
  "edges": [],
  "evaluation_criteria": [],
  "filters": []
}

Maximal spec (Phase 2B)

See tests/evals/_seeds/lesotho_business_permit/procedure.json for a real-world maximal example.


10. Further Reading

  • src/opengov/smartrules/publishing.py — publish_procedure() and spec construction
  • src/opengov/published/schemas.py — FormSchemaV1 Pydantic model
  • src/opengov/eapproval/dag.py — DAG computation from spec
  • src/opengov/eapproval/gates.py — Gate initialization from spec
  • src/opengov/eapproval/registry_view.py — Contract-based registry view
  • tests/published/test_formschema_v1.py — Schema validation tests
  • tests/smartrules/test_publishing.py — Publish-time assertions
  • docs/runbooks/module-interactions.md — How to read the spec via SmartRulesService