Skip to content

VGSF CONSTITUTION BOOK II — PART C: PLATFORM ARCHITECTURE
Chapter 3 of 6 in this Part

P3 — Backend Service Architecture

Document record
FieldValue
Constitutional SeriesP — Platform Architecture
Source DocumentsFOUNDATION_G8A_BACKEND_ARCHITECTURE_DOCTRINE.md · FOUNDATION_G9_BACKEND_REFERENCE_ARCHITECTURE.md · FOUNDATION_G8_API_CONSTITUTION.md · FOUNDATION_G9_API_CONSTITUTION.md · FOUNDATION_G8_SEARCH_AND_DISCOVERY_ARCHITECTURE.md · FOUNDATION_G8_WORKFLOW_AND_NOTIFICATION_DOCTRINE.md
Source Pathdharma_erp/01_CONSTITUTION/doctrine/G8A_PLATFORM_COMPLETION/ · dharma_erp/01_CONSTITUTION/doctrine/G9_CONSTITUTIONAL_TECHNICAL_ARCHITECTURE/ · dharma_erp/01_CONSTITUTION/doctrine/G8_PLATFORM_ARCHITECTURE/
Version1.0
CertifiedRatified — G8A_CONSTITUTIONALLY_ACCEPTED (98/100) · G9_CONSTITUTIONALLY_ACCEPTED (98/100)
Certifying ProgramConstitutional Architecture Council — G8A, G9 phases
REF DomainN/A — Backend Architecture Doctrine (applies to all REF domains)
Classification TripleN/A — Constitutional Technical Architecture
AmendmentG8A-D01 establishes Hybrid Constitutional Architecture; G8A-03 amends API Constitution; G8A-04 adds WORKFLOW-07
Position in BookPart C, Chapter 3 of 6 chapters in this Part

⚠ STACK-DECISION CURRENCY BANNER — ADR-0003 (supersedes ADR-0002), Primary Steward verdict, 2026-06-26.
Frontend: Next.js (React) — one app, all audiences. ERP pages: Server Components (data-sovereign). Donor/Audit/Board: Client Components. Public: SSG. Backend: FastAPI · PostgreSQL · asyncpg raw SQL, no ORM (Backend Option D). Source of truth: 03_PLATFORM/docs/decisions/ADR-0003-Greenfield-Stack-Decision.md.


P2 established the database substrate — the schemas, triggers, RLS policies, and registry model that give constitutional domain records their permanent home. P3 now establishes the service layer: the constitutional contract surface through which every actor — human users, automated systems, federation partners — interacts with domain records.


§1 — The Hybrid Constitutional Architecture

Backend Architecture Candidates Evaluated

Five backend patterns were evaluated in G8A:

PatternScoreConstitutional Verdict
Hybrid Constitutional Architecture (Modular Monolith + Event Bus + Federation Adapter)95/100CONSTITUTIONALLY SELECTED
Microservices58/100CONSTITUTIONALLY REJECTED
Classic Monolith72/100Acceptable at M1; does not scale to M4+
Event-Sourcing Primary61/100Constitutional complexity without benefit
Serverless Functions54/100Cannot maintain RLS session state; cold-start performance

The Hybrid Constitutional Architecture

The constitutional backend architecture is a Modular Monolith with three specialized sub-architectures:

HYBRID CONSTITUTIONAL ARCHITECTURE
├── Domain Modules (one per REF domain)
│   ├── Each module owns its domain's service logic
│   ├── Each module owns its domain's router (API endpoints)
│   ├── Each module owns its domain's schemas (Pydantic input/output models)
│   └── Modules do NOT directly access each other's database schemas
│
├── Shared Infrastructure
│   ├── Constitutional middleware (auth, audit, PROHIB-001 enforcement)
│   ├── Database connection pool (single PostgreSQL instance per entity)
│   ├── Registry service (shared controlled vocabulary access)
│   └── Notification service (outbound only)
│
├── Domain Integration Layer (Internal Event Bus)
│   ├── Publish-Subscribe pattern for cross-domain events
│   ├── Domain events are constitutional facts: immutable, append-only
│   ├── Example: PartyCreated → triggers REF002 default relationship creation
│   └── Internal only: not exposed externally; not a microservice boundary
│
├── Federation Adapter Layer
│   ├── Single point of all cross-entity API calls
│   ├── GPI resolution (Global Party Identifier)
│   ├── Inter-entity transfer initiation and tracking
│   └── Federation knowledge catalog synchronization
│
└── External API Layer (FastAPI application)
    ├── OpenAPI 3.1 specification (the constitutional contract)
    ├── 6 API categories (API-CAT-01 through API-CAT-06)
    ├── Constitutional middleware stack (in order of execution)
    └── Response envelope with constitutional metadata

Why Microservices Were Constitutionally Rejected

The microservices pattern received 58/100 and is constitutionally rejected. The constitutional reasons:

  1. RLS Session Context Cannot Cross Service Boundaries: RLS depends on app.current_entity_id being set in the PostgreSQL session. In a microservices architecture, each service has its own database connection pool, and the session context must be re-established for every inter-service call. This creates a security gap: if a microservice fails to set the entity context before its database query, RLS does not protect the query.
  2. Four-Eyes Cannot Be Enforced Across Service Boundaries Without Distributed Transactions: The Four-Eyes check requires knowing, at the moment of approval, who recorded the original transaction. In a microservices architecture, this requires a distributed query across the recording service and the approval service — which introduces the possibility of a consistency gap between the time of recording and the time of approval check.
  3. No-Delete Trigger Is Not Cross-Service: Each microservice owns its own database. The no-delete trigger protects its own database. But if a service orchestrator (e.g., a saga) issues compensating DELETE actions to achieve cross-service rollback, the trigger would fire and the rollback would fail — leaving the system in a constitutionally correct but operationally inconsistent state.
  4. Premature Complexity at M1–M3: VGSF at M1–M2 operates at the scale of dozens of concurrent users. Microservices introduce operational complexity (service discovery, distributed tracing, inter-service authentication) that is constitutionally premature before the M4 federation activation threshold.

The Modular Monolith with internal event bus satisfies all constitutional requirements while remaining operationally manageable from M1 through M3, and supports the eventual evolution to a federation-ready deployment at M4+ through the Federation Adapter Layer.


§2 — The Five-Layer Backend Architecture

The backend is organized in five layers from outermost to innermost:

Layer 1 — External API Layer (FastAPI)

The API layer receives HTTP requests, executes the constitutional middleware stack, routes to the appropriate domain module, and returns the standardized response envelope.

# Directory structure — constitutional backend
vgsf_backend/
├── main.py                          # FastAPI application entry point
├── constitutional/
│   ├── middleware.py                # PROHIB-001 enforcement, audit, auth
│   ├── db.py                        # asyncpg connection pool + per-request entity/SET ROLE context
│   ├── exceptions.py                # ConstitutionalViolation exception hierarchy
│   └── registry.py                  # Registry service (shared)
├── domains/
│   ├── ref001_identity/
│   │   ├── router.py                # FastAPI router for REF001 endpoints
│   │   ├── service.py               # Service layer (constitutional enforcement; raw parameterized SQL)
│   │   ├── sql.py                   # Raw parameterized SQL statements for REF001 (no ORM)
│   │   └── schemas.py               # Pydantic input/output schemas
│   ├── ref002_relationship/
│   ├── ref003_place/
│   ├── ref004_event/
│   ├── ref005_resource/
│   ├── ref006_document/
│   ├── ref007_obligation/
│   ├── ref008_authority/
│   ├── ref009_interaction/
│   ├── ref010_case/
│   ├── ref011_schedule/
│   ├── ref013_knowledge/
│   └── ref014_initiative/
├── federation/
│   ├── adapter.py                   # Federation Adapter Layer
│   └── gpi.py                       # GPI resolution service
├── events/
│   └── bus.py                       # Internal Event Bus
└── migrations/
    └── ddl/                         # Hand-authored .sql DDL files per domain (no Alembic)

Layer 2 — Shared Infrastructure

The shared infrastructure provides constitutional services that all domain modules consume:

  • Database connection pool: Single asyncpg connection pool (no ORM). For every request/transaction the shared infrastructure acquires a connection, sets the domain GUC (SET LOCAL app.current_entity_id = $1) and applies SET ROLE for the domain step (Backend Option D) before the first query executes. All data access is raw parameterized SQL against the certified DDL.
# Per-request entity + SET ROLE context (Backend Option D) — constitutional/db.py
# asyncpg pool; raw parameterized SQL; no ORM, no session factory.
import asyncpg
from contextlib import asynccontextmanager

pool: asyncpg.Pool   # created at application startup

@asynccontextmanager
async def domain_step(entity_id, db_role):
    """
    Acquire a pooled connection, open a transaction, set the RLS GUC and the
    domain role BEFORE any query runs. SET LOCAL / SET ROLE are scoped to the
    transaction and reset automatically on commit/rollback.
    """
    async with pool.acquire() as conn:
        async with conn.transaction():
            # entity_id GUC drives RLS (P2.§4); set before the first query
            await conn.execute("SELECT set_config('app.current_entity_id', $1, true)",
                               str(entity_id))
            # SET ROLE per domain step — the certified DDL's RLS/grants are the guard
            await conn.execute(f"SET LOCAL ROLE {db_role}")
            yield conn   # service layer issues raw parameterized SQL on this conn
  • Registry service: Cached access to all registry values. Cache invalidated on registry change events.
  • Notification service: Outbound notification dispatch (email, in-app). Consumes REF009.C1 (Communication) domain records.
  • Search service: Elasticsearch/OpenSearch integration for full-text and relationship search (M3+). PostgreSQL full-text search for M1–M2.

Layer 3 — Domain Integration (Internal Event Bus)

The internal event bus implements a synchronous publish-subscribe pattern within the monolith:

# Internal event bus — constitutional domain events
from dataclasses import dataclass
from typing import Callable, Dict, List
import uuid

@dataclass
class DomainEvent:
    event_id: uuid.UUID
    event_type: str         # 'PartyCreated', 'EventApproved', 'ObligationFulfilled', etc.
    domain: str             # 'REF001', 'REF004', 'REF007', etc.
    record_id: uuid.UUID    # ID of the affected record
    actor_party_id: uuid.UUID
    entity_id: uuid.UUID
    payload: dict           # Domain-specific event data

class ConstitutionalEventBus:
    def __init__(self):
        self._handlers: Dict[str, List[Callable]] = {}

    def subscribe(self, event_type: str, handler: Callable):
        self._handlers.setdefault(event_type, []).append(handler)

    async def publish(self, event: DomainEvent):
        # All handlers are called within the same database transaction
        # as the action that generated the event
        for handler in self._handlers.get(event.event_type, []):
            await handler(event)
        # Event is also written to audit.action_log
        await self._write_audit_record(event)

Layer 4 — Federation Adapter Layer

The Federation Adapter Layer is the sole constitutional point of cross-entity data exchange:

# GPI Resolution — Global Party Identifier
class GPIResolver:
    """
    Resolves cross-entity party identity through GPI.
    Raw personal data (name, address, ID numbers) never crosses entity boundaries.
    Only GPI identifiers are exchanged; each entity resolves GPI to its own REF001 record.
    """

    async def resolve_gpi(self, gpi_id: uuid.UUID, requesting_entity_id: uuid.UUID) -> dict:
        # Check authorization: does requesting entity have permission to resolve this GPI?
        await self._check_gpi_authorization(gpi_id, requesting_entity_id)

        # Resolve within the requesting entity's own data
        local_party = await self._find_local_party_by_gpi(gpi_id, requesting_entity_id)
        if local_party:
            return {'gpi_id': gpi_id, 'local_party_id': local_party.id, 'resolved': True}

        # GPI exists but no local record — return GPI metadata only (no cross-entity data)
        return {'gpi_id': gpi_id, 'local_party_id': None, 'resolved': False}

Layer 5 — Domain Module Pattern

Each domain module follows a constitutional pattern. The EventService (REF004) is the reference implementation:

# Domain module service layer — REF004 Event (reference pattern)
from constitutional.middleware import require_authority
from constitutional.exceptions import ConstitutionalViolation

class EventService:
    """
    REF004 Event Service.
    All service methods enforce PROHIB-001: authority check before data operation.
    """

    async def create_event(
        self,
        event_data: EventCreate,
        actor_party_id: uuid.UUID,
        entity_id: uuid.UUID,
        authority_grant_id: uuid.UUID,
        conn: asyncpg.Connection      # entity GUC + SET ROLE already applied (Option D)
    ) -> dict:
        # PROHIB-001: Authority check is FIRST — before any database operation
        await require_authority(
            actor_party_id=actor_party_id,
            entity_id=entity_id,
            grant_type='EVENT_CREATION_AUTHORITY',
            authority_grant_id=authority_grant_id,
            conn=conn
        )

        # Validate registry references
        await self._validate_event_type(event_data.event_type, conn)
        await self._validate_place_exists(event_data.location_place_id, entity_id, conn)

        # Create the domain record — raw parameterized INSERT (no ORM)
        row = await conn.fetchrow(
            """
            INSERT INTO ref004.events
                (id, entity_id, title, event_type, event_date, location_place_id,
                 basis_document_id, created_by, lifecycle_status, version)
            VALUES
                (gen_random_uuid(), $1, $2, $3, $4, $5, $6, $7, 'ACTIVE', 1)
            RETURNING *
            """,
            entity_id, event_data.title, event_data.event_type, event_data.event_date,
            event_data.location_place_id, event_data.basis_document_id, actor_party_id,
        )
        event = dict(row)

        # Publish domain event (internal bus)
        await event_bus.publish(DomainEvent(
            event_type='EventCreated',
            domain='REF004',
            record_id=event['id'],
            actor_party_id=actor_party_id,
            entity_id=entity_id,
            payload=event
        ))

        return event

    async def transition_lifecycle(
        self,
        event_id: uuid.UUID,
        new_status: str,
        actor_party_id: uuid.UUID,
        entity_id: uuid.UUID,
        authority_grant_id: uuid.UUID,
        conn: asyncpg.Connection
    ) -> dict:
        # PROHIB-001 enforced for lifecycle transitions too
        await require_authority(
            actor_party_id=actor_party_id,
            entity_id=entity_id,
            grant_type='EVENT_LIFECYCLE_AUTHORITY',
            authority_grant_id=authority_grant_id,
            conn=conn
        )

        event = await self._get_event(event_id, entity_id, conn)

        # Validate lifecycle transition (constitutional state machine)
        self._validate_lifecycle_transition(event['lifecycle_status'], new_status)

        # Record change history before updating
        await self._record_change_history(event, new_status, actor_party_id, conn)

        # Raw parameterized UPDATE (no ORM); optimistic-lock version bump
        updated = await conn.fetchrow(
            """
            UPDATE ref004.events
               SET lifecycle_status = $1,
                   updated_by       = $2,
                   updated_at       = now(),
                   version          = version + 1
             WHERE id = $3 AND entity_id = $4
            RETURNING *
            """,
            new_status, actor_party_id, event_id, entity_id,
        )
        return dict(updated)

§3 — The Universal Audit Middleware

The universal audit middleware (Law G9-5) wraps every API endpoint and creates an audit record before the response is returned:

# Universal audit middleware — runs for every API request
from fastapi import Request, Response
from starlette.middleware.base import BaseHTTPMiddleware
import uuid
from datetime import datetime

class ConstitutionalAuditMiddleware(BaseHTTPMiddleware):
    """
    Universal audit middleware.
    Runs for every API request.
    Cannot be disabled by configuration.
    """

    EXEMPT_PATHS = {'/health', '/metrics', '/api/v1/registries'}
    # Registry reads (GET only) and health checks are exempt
    # All modifying operations (POST, PUT, PATCH) are ALWAYS audited

    async def dispatch(self, request: Request, call_next) -> Response:
        request_id = str(uuid.uuid4())
        request.state.request_id = request_id

        # Execute the request
        response = await call_next(request)

        # Write audit record for all non-exempt, authenticated requests
        if (request.url.path not in self.EXEMPT_PATHS
                and hasattr(request.state, 'actor_party_id')
                and request.method in {'POST', 'PUT', 'PATCH', 'DELETE'}):
            await self._write_audit_log(
                entity_id=request.state.entity_id,
                actor_party_id=request.state.actor_party_id,
                action_type=self._method_to_action(request.method),
                domain=self._extract_domain(request.url.path),
                record_id=self._extract_record_id(request.url.path),
                action_timestamp=datetime.utcnow(),
                request_id=request_id,
                authority_grant_id=request.headers.get('X-Authority-Grant-ID'),
                ip_address=request.client.host,
                user_agent=request.headers.get('User-Agent'),
                response_status=response.status_code
            )

        response.headers['X-Request-ID'] = request_id
        return response

§4 — The Six API Categories

Law G8-3 establishes that every capability must be accessible through a constitutional API before any UI is built. The six API categories constitute the complete constitutional API grammar:

API-CAT-01: Object APIs

One Object API per constitutional domain. Object APIs follow the universal CRUD + lifecycle grammar:

GET    /api/v1/{domain}/                          List (paginated)
POST   /api/v1/{domain}/                          Create
GET    /api/v1/{domain}/{id}                      Retrieve single record
PUT    /api/v1/{domain}/{id}                      Update (full replacement)
PATCH  /api/v1/{domain}/{id}                      Update (partial)
POST   /api/v1/{domain}/{id}/lifecycle-transition Lifecycle transition (never DELETE)
GET    /api/v1/{domain}/{id}/history              Full change history for this record

Constitutional Rule: There is NO DELETE /api/v1/{domain}/{id} endpoint. The absence of the DELETE verb is a constitutional design decision. Any HTTP client that issues DELETE on a domain endpoint receives HTTP 405 Method Not Allowed with the response body: {"constitutional_violation": "DELETE is not permitted on constitutional domain records. Use /lifecycle-transition with status ARCHIVED or HISTORICAL."}.

API-CAT-02: Lifecycle APIs

Universal lifecycle transition grammar, applicable to every domain:

POST /api/v1/{domain}/{id}/lifecycle-transition

Request body:
{
  "new_status": "ARCHIVED",          // From Lifecycle Status Registry (REG-04)
  "reason": "Programme completed",   // Human-readable reason
  "authority_grant_id": "...",       // REF008 grant authorizing this transition
  "effective_date": "2025-06-30"     // Date from which transition is effective
}

Response:
{
  "success": true,
  "record_id": "...",
  "previous_status": "ACTIVE",
  "new_status": "ARCHIVED",
  "transition_recorded_at": "2025-06-30T12:34:56+05:30",
  "change_history_id": "..."         // Reference to the change history record
}

API-CAT-03: Search APIs

POST /api/v1/search/global            Global search across all domains
POST /api/v1/search/{domain}          Domain search within one domain
POST /api/v1/search/relationship      Relationship graph search (REF002)
POST /api/v1/search/historical        Historical search (as_of date parameter)
POST /api/v1/search/federation        Cross-entity search (M4+, authorized)
POST /api/v1/search/knowledge         Knowledge catalog full-text (REF013)

→ See: [P3.§8] — Full Search and Discovery Architecture

API-CAT-04: Registry APIs

GET  /api/v1/registries/{registry_code}                      List active values
GET  /api/v1/registries/{registry_code}?as_of=2024-01-01    Historical state
GET  /api/v1/registries/{registry_code}/{value_code}         Single value detail
POST /api/v1/registries/{registry_code}/values               Add new value (authorized)
PUT  /api/v1/registries/{registry_code}/{value_code}/retire  Retire value (authorized)

API-CAT-05: Federation APIs

GET  /api/v1/federation/gpi/{gpi_id}                        GPI resolution
POST /api/v1/federation/transfers                            Inter-entity transfer initiation
GET  /api/v1/federation/transfers/{transfer_id}             Transfer status
POST /api/v1/federation/knowledge/sync                      Knowledge catalog sync
GET  /api/v1/federation/entities                            List federation members (authorized)

API-CAT-06: Audit APIs

GET  /api/v1/audit/trail/{domain}/{record_id}               Audit trail for a record
GET  /api/v1/audit/actor/{party_id}                         All actions by a Party
GET  /api/v1/audit/entity                                   Full entity audit log (paginated)
GET  /api/v1/audit/reports/four-eyes/{transaction_id}       Four-eyes audit for a transaction
GET  /api/v1/audit/reports/donor-transparency               Donor transparency report

§5 — The Constitutional API Standard

The constitutional API standard (G8 + G9) establishes the grammar every endpoint must follow:

Universal Request Headers

Authorization: Bearer {JWT token}              — Required for all authenticated endpoints
X-Entity-ID: {entity UUID}                    — Required; selects entity context (maps to RLS)
X-Authority-Grant-ID: {grant UUID}            — Required for all modifying endpoints
X-Request-ID: {UUID}                          — Optional; client-provided; used for idempotency
Content-Type: application/json                — Required for all request bodies

Universal Response Envelope

{
  "success": true,
  "data": { /* domain record or list */ },
  "metadata": {
    "request_id": "...",
    "timestamp": "2025-06-15T10:30:00+05:30",
    "entity_id": "...",
    "domain": "REF001",
    "version": "1.0",
    "authority_grant_id": "..."
  },
  "pagination": {                             // Present only for list responses
    "page": 1,
    "page_size": 50,
    "total_count": 1247,
    "total_pages": 25
  }
}

Constitutional Error Grammar

{
  "success": false,
  "error": {
    "code": "AUTHORITY_INSUFFICIENT",
    "message": "The requesting party does not hold an active authority grant of type EVENT_CREATION_AUTHORITY for this entity.",
    "constitutional_reference": "Law G8-5 (Authority Traceability) / PROHIB-001",
    "resolution": "Obtain an EVENT_CREATION_AUTHORITY grant from a Party holding MANAGEMENT_AUTHORITY for the Events domain."
  },
  "metadata": {
    "request_id": "...",
    "timestamp": "..."
  }
}

Constitutional Error Codes

CodeHTTP StatusConstitutional Reference
AUTHORITY_INSUFFICIENT403Law G8-5, PROHIB-001
AUTHORITY_EXPIRED403REF008 grant expiry
AUTHORITY_GRANT_NOT_FOUND403Law G8-5
ENTITY_NOT_AUTHORIZED403RLS entity isolation
LIFECYCLE_TRANSITION_INVALID422Domain lifecycle state machine
DELETE_PROHIBITED405Law G8-2, Law G9-2
REGISTRY_VALUE_INVALID422Law G8-6
FOUR_EYES_VIOLATION422Law G9-4
RECORD_NOT_FOUND404Standard
VALIDATION_ERROR422Pydantic schema
CONSTITUTIONAL_VIOLATION400General constitutional

API Versioning Rules

Rule V1 — Version in URL Path: All API endpoints include the version in the URL path: /api/v1/.... The version is a major version number. Minor and patch changes to the API are backward-compatible and do not require a version increment.

Rule V2 — Backward Compatibility: A new API version (v2) may only be published when a breaking change is required. Breaking changes are: removing a field from a response, changing a field type, changing authentication requirements, or removing an endpoint. New endpoints, new optional fields, and new optional request parameters are not breaking changes.

Rule V3 — Minimum 12-Month Overlap: When a new version (v2) is published, v1 is maintained for a minimum of 12 months. v1 is never removed without Primary Steward authorization and advance notice to all API consumers.

Rule V4 — OpenAPI First: The OpenAPI 3.1 specification is the source of truth. Every endpoint is described in the specification before implementation. The FastAPI framework generates documentation from the specification; the specification is not generated from implementation.


§6 — PROHIB-001: The Single Most Consequential Platform Doctrine

PROHIB-001 is the single most consequential platform doctrine because it determines whether authority enforcement is constitutionally verifiable.

PROHIB-001 Statement: Authority checks MUST be performed at the API middleware layer (specifically: as the first operation in every service method that modifies domain data), before any database operation executes. Authority checks MUST NOT be performed in application logic, UI components, database triggers, or any other layer.

The require_authority function:

# PROHIB-001 implementation — require_authority
import asyncpg
from constitutional.exceptions import AuthorityInsufficientError, AuthorityExpiredError
import uuid
from datetime import datetime

async def require_authority(
    actor_party_id: uuid.UUID,
    entity_id: uuid.UUID,
    grant_type: str,
    authority_grant_id: uuid.UUID,
    conn: asyncpg.Connection
) -> None:
    """
    PROHIB-001 enforcement function.
    Must be called as the FIRST operation in every service method
    that creates, modifies, or transitions domain records.
    
    Raises AuthorityInsufficientError if the check fails.
    Returns None (not the grant record) if the check passes.
    The check passing is the only constitutional signal needed.
    """
    # Fetch the claimed authority grant — raw parameterized SQL (no ORM)
    grant = await conn.fetchrow(
        "SELECT * FROM ref008.authority_grants WHERE id = $1",
        authority_grant_id,
    )

    if grant is None:
        raise AuthorityInsufficientError(
            f"Authority grant {authority_grant_id} not found."
        )

    if grant['grant_holder_party_id'] != actor_party_id:
        raise AuthorityInsufficientError(
            f"Authority grant {authority_grant_id} does not belong to actor {actor_party_id}."
        )

    if grant['entity_id'] != entity_id:
        raise AuthorityInsufficientError(
            f"Authority grant {authority_grant_id} is not scoped to entity {entity_id}."
        )

    if grant['grant_type'] != grant_type:
        raise AuthorityInsufficientError(
            f"Authority grant {authority_grant_id} is of type {grant['grant_type']}, "
            f"not {grant_type} as required for this operation."
        )

    if grant['lifecycle_status'] != 'ACTIVE':
        raise AuthorityInsufficientError(
            f"Authority grant {authority_grant_id} is {grant['lifecycle_status']}, not ACTIVE."
        )

    if grant['effective_to'] and grant['effective_to'] < datetime.utcnow():
        raise AuthorityExpiredError(
            f"Authority grant {authority_grant_id} expired on {grant['effective_to']}."
        )

    # Grant is valid. Return None.
    # Caller proceeds to database operation.

Why the API middleware layer, not the database layer:

  • Database triggers cannot access REF008 authority grant records (they are in a different schema)
  • Database triggers fire after the SQL statement is prepared, not before
  • The audit record must capture the authority grant reference — only the service layer has this information at the time of the check

Why the API middleware layer, not the UI layer:

  • API calls can arrive from sources other than the UI: mobile apps, external integrations, federation adapters, background jobs, migration scripts
  • A UI check that is not backed by a service-layer check provides no constitutional protection

§7 — The Search and Discovery Architecture

The G8 Search and Discovery Architecture establishes six search types:

The Six Search Types

Search Type 1 — Global Search:
Queries across all domain records for which the actor holds VIEW authority. Returns results grouped by domain with preview information. Does not expose records outside the actor's authority scope.

POST /api/v1/search/global
{
  "query": "Krishna das",
  "domains": ["REF001", "REF006", "REF009"],    // Optional; omit for all
  "limit_per_domain": 5
}

Search Type 2 — Domain Search:
Full-featured search within a single domain. Supports filtering by every indexed field plus full-text search on text fields.

POST /api/v1/search/ref001
{
  "query": "Gopinath",
  "filters": {
    "party_type": "PERSON",
    "lifecycle_status": ["ACTIVE"],
    "relationship_type": "MEMBER_OF",
    "organization_id": "..."
  },
  "sort": {"field": "created_at", "direction": "desc"},
  "page": 1,
  "page_size": 50
}

Search Type 3 — Relationship Search:
Graph traversal search across REF002 relationships. Supports depth-limited traversal and relationship type filtering.

POST /api/v1/search/relationship
{
  "start_party_id": "...",
  "relationship_types": ["MENTORED_BY", "EMPLOYED_BY"],
  "direction": "outbound",    // "outbound", "inbound", "both"
  "max_depth": 3,
  "include_inactive": false
}

Search Type 4 — Historical Search:
Time-bounded search that returns records as they existed at a specific point in time. Requires M3+ (12+ months of data for meaningful historical queries).

POST /api/v1/search/historical
{
  "domain": "REF007",
  "query": "development fund",
  "as_of": "2024-06-30T23:59:59+05:30",    // Point-in-time
  "include_archived": true,
  "include_historical": true
}

Search Type 5 — Federation Search:
Cross-entity search with explicit federation authorization. Available at M4+. Returns only records the requesting entity is constitutionally authorized to view.

POST /api/v1/search/federation
{
  "query": "training programme outcomes",
  "domains": ["REF013"],     // Knowledge domain only for M4 activation
  "federation_auth_token": "...",
  "target_entities": ["entity-uuid-A", "entity-uuid-B"]   // Authorized entities
}

Search Type 6 — Knowledge Search:
Full-text search with semantic ranking across REF013 (Knowledge) records. Supports category filtering, tag search, and knowledge type filtering.

POST /api/v1/search/knowledge
{
  "query": "crowd management temple programme",
  "knowledge_types": ["LESSON_LEARNED", "BEST_PRACTICE", "PROCEDURE"],
  "categories": ["EVENT_MANAGEMENT"],
  "include_archived": false
}

Search Index Architecture

M1–M2:  PostgreSQL full-text search (tsvector columns, GIN indexes)
         — Adequate for < 100,000 records per entity
         — Supports all six search types at reduced performance

M3+:    Elasticsearch / OpenSearch
         — Deployed alongside PostgreSQL; PostgreSQL remains the authoritative store
         — Search index is eventually consistent with PostgreSQL (lag < 30 seconds)
         — If search index is unavailable, fall back to PostgreSQL full-text search
         — Index updated by domain event bus (EventIndexed subscriber)

Constitutional Rule: The search index is always derived from PostgreSQL — it is never the authoritative record. If a search result and a PostgreSQL record conflict, PostgreSQL is correct.


§8 — The Workflow and Notification Doctrine

The G8 Workflow Doctrine establishes six constitutional workflow types:

WORKFLOW-01 — Approval Workflow

Applied to: Event approval, Project approval, Document issuance, Budget approval, Authority grant issuance.

Constitutional Rules:

  • Approval requires an explicit REF008 Authority Grant of type APPROVAL_AUTHORITY for the relevant domain
  • Approval workflows cannot be bypassed (no "fast-track" that skips authority verification)
  • Approval is a lifecycle transition (DRAFT → PENDING_APPROVAL → APPROVED or REJECTED)
  • Rejection requires a reason (mandatory field in the lifecycle transition payload)
  • Both approval and rejection create audit log entries
  • Authority chain: approval by a Party who does not hold APPROVAL_AUTHORITY is constitutionally null

WORKFLOW-02 — Authority Grant Workflow

Applied to: All REF008 grant issuances and revocations.

Constitutional Rules:

  • Issuing an authority grant requires the issuer to hold DELEGATION_AUTHORITY for the grant type being issued
  • Authority grants cannot be issued without a basis document (REF006 document ID required)
  • Authority grants are time-bounded (effective_from and effective_to are mandatory)
  • Revocation is immediate: the grant transitions to REVOKED status and is no longer valid for any subsequent action
  • The authority chain is auditable: each grant traces back to the constitutional authority it was delegated from

WORKFLOW-03 — Lifecycle Transition Workflow

Applied to: Every domain record lifecycle transition.

Constitutional Rules:

  • Lifecycle transitions follow the constitutional state machine for each domain (defined in G3.5 domain constitutions)
  • Invalid transitions raise LifecycleTransitionInvalid and are rejected before database write
  • Every transition is recorded in the change history table
  • ARCHIVED status: record is read-only; no further modifications permitted
  • HISTORICAL status: record is the result of a migration or bulk historical import; cannot be modified but may be superseded by an ACTIVE record

WORKFLOW-04 — Obligation Fulfillment Workflow

Applied to: REF007 Obligation fulfillment tracking (donor pledges, grant deliverables, financial commitments).

Constitutional Rules:

  • Obligation fulfillment is a multi-step workflow: COMMITTED → PARTIALLY_FULFILLED → FULLY_FULFILLED
  • Each fulfillment step creates a REF005 Resource transaction record
  • The conservation law (balance = Σ(recorded transitions)) is verified at each step
  • Partial fulfillment is constitutionally permitted; unfulfilled obligations are escalated (WORKFLOW-05)

WORKFLOW-05 — Escalation Workflow

Applied to: Overdue obligations, stalled approvals, unacknowledged notifications.

Constitutional Rules:

  • Escalation is automatic (time-triggered) — it does not require human initiation
  • Escalation creates a constitutional notification to the superior authority holder in the organizational hierarchy
  • Escalation itself is audited: the audit log records when escalation was triggered and to whom
  • Escalation is not a replacement for human authority: the escalation notifies; it does not approve

WORKFLOW-06 — Exception Workflow

Applied to: Emergency actions that cannot wait for the normal approval workflow.

Constitutional Rules:

  • Exception actions are taken under documented emergency authority (basis document required)
  • The action is taken first; ratification by the normal authority chain is required within 72 hours
  • If ratification is not completed within 72 hours, the action is automatically flagged for constitutional review
  • Exception workflow does NOT bypass the audit trail — exception actions are more heavily audited, not less

WORKFLOW-07 (G8A-04) — AI-Augmented Workflow (M5 only)

Applied to: AI-suggested actions in the M5 civilizational intelligence layer.

Constitutional Rules:

  • AI suggestions are presented as workflow inputs — they do not execute actions
  • The human authority holder reviews the AI suggestion and either accepts (triggering the normal approval workflow) or rejects it
  • Accepted AI suggestions carry ai_suggested: true metadata in all downstream records
  • AI suggestions carry the AI actor's Party ID (REF001 AI_SYSTEM party type) in their audit trail
  • Rejected AI suggestions are recorded in the audit log (including the reason for rejection, if provided)
  • AI may NEVER approve, execute, or finalize any action without explicit human authorization

Notification Classification

Notifications are classified by urgency and delivery channel:

PriorityTriggerDeliveryWindow
P1 — ImmediateSecurity alert, constitutional violationIn-app (immediate) + EmailWithin 1 minute
P2 — UrgentEscalation, approval deadline todayIn-app + EmailWithin 15 minutes
P3 — StandardApproval request, task assignmentIn-appWithin 1 hour
P4 — InformationalRegistry update, report availableIn-appWithin 24 hours
P5 — DigestWeekly summary, monthly reportEmail digestWeekly / Monthly

Constitutional Rule: All notifications are associated with a domain record and an actor. Notifications are constitutional communications — they are themselves REF009.C1 records and appear in the audit trail. Notifications are not marketing communications; they do not use tracking pixels or click analytics.


Constitutional Colophon — P3
This chapter establishes the backend service architecture of the Constitutional ERP: the Hybrid Constitutional Architecture (Modular Monolith with Domain Modules, Internal Event Bus, and Federation Adapter Layer); PROHIB-001 as the single most consequential platform doctrine; the universal audit middleware; the six API categories and their constitutional grammar; the search and discovery architecture with six search types; and the seven workflow types governing authority, obligation, lifecycle, and AI-augmented operations.
It operates within Part C under Law G8-3 (API Primacy): every capability must be accessible through a constitutional API before any UI is built, and the API is the permanent interface while the UI is an ephemeral rendering of it.
Readers proceeding to P4 — Frontend Architecture should carry forward: the frontend consumes the constitutional API exclusively — it never accesses the database directly, it never performs authority checks independent of the service layer, and it never exposes capabilities that the API does not authorize.


Test Dharma ERP and tell us what you find.

The trial uses sandboxed demo data across twelve core modules. Look around, try the forms, and review what works and what does not.