Keyra companion governance

The Companion Platform Reference Architecture

Implementation blueprint for services, schemas, runtimes, observability, and deployment.

THE COMPANION PLATFORM REFERENCE ARCHITECTURE

Definitive technical blueprint for implementing the Human Sovereignty Operating System


Instrument: The Companion Platform Reference Architecture

Function: Master implementation blueprint translating all twelve founding instruments into implementable platform architecture for engineers, architects, platform/infrastructure/product/security teams, government, telecom, and banking teams

Version: 1.0 (Reference Architecture)

Status: Subordinate to the Human Sovereignty Charter and all twelve prior founding instruments

Core constraint: Architecture follows sovereignty; human-first, local-first, trust-first, companion-first


Preamble

The Human Sovereignty Operating System is not a product roadmap. It is a constitutional and technical composition — twelve founding instruments that together define how humans, companions, digital twins, life graphs, families, organizations, agents, vaults, devices, marketplaces, and global trust infrastructure coexist under human authority. Engineers cannot implement sovereignty by accident. Architects cannot federate trust by improvisation. Platform teams cannot scale to billions of humans and hundreds of billions of agents without a reference architecture that translates rights into runtime behavior, persistence into storage models, and governance into enforceable service boundaries.

This document defines the Companion Platform Reference Architecture — the master implementation blueprint through which the Human Sovereignty Charter, Companion Charter, Life Operating System, Human Digital Twin Architecture, Life Graph Architecture, Family Trust Network, Organization Graph Enterprise Companion Framework, KAAI Standard, Trust Vault Architecture, Device Trust Mesh, Companion Marketplace & Agent Economy, and Global Trust Economy & Sovereign Network Framework become deployable platform architecture.

The Reference Architecture is written for Engineers, Architects, Platform Teams, Infrastructure Teams, Product Teams, Security Teams, Government Teams, Telecommunications Teams, and Banking Teams. It specifies layers, services, schemas, APIs, runtimes, deployment models, observability contracts, and implementation roadmaps. It does not replace founding instruments. It implements them.

Preamble — Historical Context

Digital platforms evolved as application silos. Each silo optimized for engagement, retention, and data accumulation. Identity became authentication. Authorization became role-based access control inside vendor boundaries. Memory became training data. Relationships became social graphs owned by platforms. Agents arrived as features without certificates, without revocation semantics, without audit chains rooted in human grants.

The result is architectural fragmentation incompatible with human sovereignty. A human who cannot export authorization graphs does not possess portability. A companion that cannot enforce vault-bound grants does not mediate sovereignty. An agent that cannot produce KAAI certificate chains is not accountable. A family that cannot partition child-safe scopes cannot govern. An enterprise that cannot separate organizational overlays from member human roots cannot comply. A bank that settles without authorization evidence pointers settles money without trust economy conformance. A government that accredits without federation bridges creates jurisdictional dead ends.

The Companion Platform Reference Architecture addresses fragmentation by defining a single implementable stack where constitutional constraints precede product features, local-first execution precedes cloud convenience, trust verification precedes transaction finalization, and companion mediation precedes direct agent access to human life data.

Preamble — Relationship to Founding Instruments

This Reference Architecture is subordinate to the Human Sovereignty Charter. When implementation choices appear to conflict with human sovereignty, human sovereignty prevails and platform implementations MUST be corrected.

This Reference Architecture translates the following twelve founding instruments into platform architecture:

| # | Instrument | Platform translation |

|---|------------|---------------------|

| 1 | Human Sovereignty Charter | Constitutional invariants enforced at every layer; human root authority in identity, authorization, and audit |

| 2 | Companion Charter | Companion layer as mandatory mediation for high-risk operations; duty-of-care runtime policies |

| 3 | Life Operating System | Domain-scoped policy engine; life domain routing; governance constraints in platform services |

| 4 | Human Digital Twin Architecture | Twin service boundaries; projection APIs; synchronization and conflict resolution |

| 5 | Life Graph Architecture | Graph storage, query, and mutation services; temporal and authorization semantics |

| 6 | Family Trust Network | Family partition services; guardian approval workflows; child-safe policy overlays |

| 7 | Organization Graph Enterprise Companion Framework | Enterprise overlay separation; member sovereignty preservation; compliance partitions |

| 8 | KAAI Standard | Agent runtime; certificate validation; registration, execution, auditing, revocation |

| 9 | Trust Vault Architecture | Vault service; encryption hierarchy; export ceremonies; partition governance |

| 10 | Device Trust Mesh | Device registry; presence verification; trust synchronization protocol |

| 11 | Companion Marketplace & Agent Economy | Marketplace services; certification; billing; settlement integration |

| 12 | Global Trust Economy & Sovereign Network Framework | Federation gateways; trust settlement engine; cross-border interoperability |

No single layer owns the platform. The human owns the estate. The Reference Architecture composes services that persist, structure, mediate, authorize, and settle human digital life without capture.

Preamble — Normative Language

Throughout this document:

  • MUST, MUST NOT, REQUIRED, and SHALL denote absolute requirements for Companion Platform conformance
  • SHOULD and RECOMMENDED denote strong guidance with documented exceptions permitted only under human or institutional policy with audit
  • MAY denotes optional capability
  • Prohibited actions are void regardless of technical success; platform runtimes MUST reject them

Conformance is measured at four layers: constitutional (subordination to human authority), architectural (layer boundaries and service contracts), technical (APIs, schemas, encryption, federation), and operational (SLA, observability, incident response, disaster recovery).

Preamble — Standards Alignment

This Reference Architecture is written at institutional quality for enterprise architecture practice — aligned with TOGAF-style architecture domains (business, data, application, technology, security) while subordinating all views to human sovereignty rather than enterprise convenience alone. It meets enterprise architecture rigor for service boundaries, deployment topologies, and federation patterns, and PhD-level systems engineering depth for graph-SQL duality, cryptographic custody, multi-agent scale, and civilization-scale federation — without marketing or product language.

Preamble — Architectural Placement

The Companion Platform Reference Architecture sits between founding instruments (law and semantics) and deployable implementations (code and infrastructure):

```

┌──────────────────────────────────────────────────────────┐

│ Human Sovereignty Charter + 11 Founding Instruments │

├──────────────────────────────────────────────────────────┤

│ Companion Platform Reference Architecture (this doc) │

│ Layers · Services · Schemas · Runtimes · Deployment │

├──────────────────────────────────────────────────────────┤

│ Web · Flutter · APIs · Graph · SQL · Vault · Mesh │

├──────────────────────────────────────────────────────────┤

│ Cloud · Edge · Sovereign · Enterprise · Gov · Telco │

└──────────────────────────────────────────────────────────┘

```

Applications and interfaces are replaceable. Authorization graphs, vault contents, graph topology, and audit chains are not — they belong to the human and persist across platform migration when export ceremonies execute.

Preamble — Scope of Support

The Companion Platform Reference Architecture supports:

| Domain | Entities |

|--------|----------|

| Humans | Sovereign grantors, owners, inspectors, revokers |

| Companions | Mediation layer, policy enforcement, human-facing orchestration |

| Digital Twins | Bounded projections with synchronization and provenance |

| Life Graphs | Multi-typed property graphs with temporal and authorization semantics |

| Families | Federated partitions, guardian structures, child-safe overlays |

| Organizations | Enterprise overlays subordinate to member human roots |

| Agents | KAAI-authorized executors with certificate chains and trust scores |

| Trust Vaults | Encrypted credential and artifact custody with export packs |

| Devices | Hardware-rooted identity, presence, trust mesh synchronization |

| Marketplace | Agent discovery, certification, commerce, settlement |

| Global Trust | Federation, registries, cross-border settlement, trust metrics |

| Banks | Authorization-attested settlement participants |

| Telcos | Subscriber trust overlays, eSIM provisioning, device binding |

| Governments | Accreditation overlays, lawful channels, sovereign deployment |


PART I — Architecture Principles

Section 1.01 — Human-First Architecture

Human-first architecture means every platform decision — schema design, API default, deployment topology, analytics pipeline, agent runtime gate — is evaluated against a single question: does this preserve, extend, or usurp human authority?

Implementations MUST:

  • Represent the Sovereign Human as the root grantor in identity, authorization, and audit systems
  • Default to human inspectability for all consequential operations
  • Require explicit human or human-delegated authorization for data access, agent dispatch, financial movement, and cross-border federation
  • Prohibit silent scope expansion — agents, companions, and services MUST NOT accumulate permissions without recorded grants
  • Surface revocation as a first-class operation with measurable propagation SLA
  • Human-first architecture is not a UX preference. It is a runtime invariant. Services that bypass human-root validation for operational convenience are non-conformant.

    Section 1.02 — Local-First Architecture

    Local-first architecture means the authoritative replica of human digital life — vault secrets, graph projections, twin state, companion memory indices, device trust credentials — resides on devices the human controls, with federation for authorized synchronization rather than cloud custody as default.

    Implementations MUST:

  • Operate vault read/write against local encrypted stores before optional cloud federation
  • Support offline-capable companion interaction for inspectability, revocation initiation, and low-risk operations
  • Treat cloud replicas as derived, never as root authority over keys or grants
  • Implement conflict resolution that preserves human-directed merge outcomes
  • Enable export ceremonies without network dependency where cryptographically feasible
  • Local-first architecture integrates with Device Trust Mesh presence requirements. High-risk operations MAY require online device participation; they MUST NOT require surrender of local key custody.

    Section 1.03 — Trust-First Architecture

    Trust-first architecture means trust verification — authorization certificate validation, device presence attestation, trust score gates, certification level checks — precedes action execution, data disclosure, marketplace settlement, and federation bridge traversal.

    Implementations MUST:

  • Validate KAAI Authorization Certificate chains before agent execution
  • Verify Device Trust Mesh attestation when scope requires presence conditions
  • Apply trust score and certification gates at marketplace discovery and settlement
  • Hash-chain audit records to Trust Vault evidence partitions
  • Propagate revocation before finalizing irreversible operations where policy requires
  • Trust-first architecture rejects the pattern of "authenticate then hope." Authentication establishes session; trust establishes grant fidelity.

    Section 1.04 — Companion-First Architecture

    Companion-first architecture means the Keyra Companion is the primary human-facing mediation layer for life operations — not a chat widget atop siloed backends. Companions orchestrate vault access, graph queries, twin projections, agent dispatch, family approvals, and marketplace negotiations under Companion Charter duty-of-care policies.

    Implementations MUST:

  • Route high-risk operations through Companion mediation APIs
  • Enforce Companion policy engine integration with Life Operating System domain rules
  • Prohibit direct agent-to-vault access without Companion or explicit human-bypass ceremony for defined emergency scopes
  • Maintain Companion audit trails linked to human authorization references
  • Support Companion succession — migration of mediation configuration across devices and platform versions
  • Companion-first architecture does not mean companions hold root keys. Companions mediate; humans authorize; vaults persist.

    Section 1.05 — Why Architecture Follows Sovereignty

    Sovereignty is not implemented by policy documents alone. Sovereignty requires architecture that makes violation technically difficult and detectable. When architecture inverts — cloud-first custody, platform-root identity, agent-direct data access, engagement-optimized trust proxies — sovereignty becomes rhetorical.

    The Companion Platform Reference Architecture inverts the default platform stack:

    | Default platform pattern | Sovereign platform pattern |

    |--------------------------|---------------------------|

    | Cloud as source of truth | Human device vault as primary replica |

    | Platform identity | Human-rooted identity with vault keys |

    | OAuth scope accumulation | KAAI certificate chains with decay |

    | Agent API keys | Agent ID + Authorization Certificate |

    | Engagement scoring | Trust index from evidentiary inputs |

    | Siloed app databases | Life Graph with exportable topology |

    | Institutional CRM as person record | Human-owned graph with org overlays |

    Architecture follows sovereignty because rights without enforceable structure are unenforceable. The twelve founding instruments define rights and semantics. This Reference Architecture defines enforceable structure.

    Section 1.06 — Principle Enforcement Matrix

    | Principle | Presentation layer | Service layer | Data layer | Operational layer |

    |-----------|-------------------|---------------|------------|-------------------|

    | Human-first | Revocation UI, grant inspection | Authorization service validation | Human-root foreign keys | Audit to human-accessible logs |

    | Local-first | Offline modes | Edge-sync protocol | Local vault replica | Conflict resolution SLA |

    | Trust-first | Trust badges, cert display | KAAI runtime gates | Trust score tables | Revocation propagation metrics |

    | Companion-first | Companion Home routing | Companion mediation API | Companion config vault partition | Companion analytics |

    Section 1.07 — Scenario 1 — Architecture Rejects Silent Capture

    A platform team proposes storing human vault master keys in cloud HSM with vendor-controlled recovery. The Reference Architecture evaluation:

  • Human-first: Violates human key custody default — REJECTED
  • Local-first: Cloud HSM may hold wrapped replicas only with human-held root — CONDITIONAL
  • Trust-first: Recovery MUST require multi-factor human ceremony — REQUIRED if conditional approved
  • Companion-first: Recovery flow MUST route through Companion with audit — REQUIRED
  • The approved pattern: human-held root key on Keyra Key; cloud stores encrypted vault blobs only; recovery requires Device Trust Mesh quorum and human presence proof.

    Section 1.08 — Document Map (All 20 Parts)

    | Part | Subject |

    |------|---------|

    | I | Architecture Principles |

    | II | System Architecture |

    | III | Front-End Architecture |

    | IV | Flutter Architecture |

    | V | Backend Architecture |

    | VI | Graph Architecture |

    | VII | SQL Architecture |

    | VIII | Twin Architecture |

    | IX | Trust Vault Architecture |

    | X | KAAI Runtime |

    | XI | Device Trust Mesh Runtime |

    | XII | AI Architecture |

    | XIII | Security Architecture |

    | XIV | Marketplace Architecture |

    | XV | Trust Settlement Architecture |

    | XVI | Scalability Architecture |

    | XVII | Observability |

    | XVIII | Deployment Architecture |

    | XIX | Disaster Recovery |

    | XX | Reference Implementation |


    PART II — System Architecture

    Section 2.01 — Layered Architecture Overview

    The Companion Platform implements a nine-layer reference model subordinate to constitutional instruments and superior to application silos:

    ```

    ┌─────────────────────────────────────────────────────────────────┐

    │ L1 PRESENTATION LAYER │

    │ Web domains · Flutter apps · Voice · Accessibility │

    ├─────────────────────────────────────────────────────────────────┤

    │ L2 COMPANION LAYER │

    │ Mediation · Policy · Orchestration · Duty of care │

    ├─────────────────────────────────────────────────────────────────┤

    │ L3 AGENT LAYER (KAAI Runtime) │

    │ Registration · Execution · Authorization · Audit │

    ├─────────────────────────────────────────────────────────────────┤

    │ L4 TWIN LAYER │

    │ Identity · Preference · Goal · Context · Memory projections │

    ├─────────────────────────────────────────────────────────────────┤

    │ L5 GRAPH LAYER │

    │ Life · Family · Organization · Trust · Authorization graphs │

    ├─────────────────────────────────────────────────────────────────┤

    │ L6 VAULT LAYER │

    │ Identity · Memory · Authorization · Legacy partitions │

    ├─────────────────────────────────────────────────────────────────┤

    │ L7 TRUST LAYER │

    │ Trust scores · Certification · Federation · Settlement refs │

    ├─────────────────────────────────────────────────────────────────┤

    │ L8 AUTHORIZATION LAYER │

    │ Grants · Certificates · Revocation · Scope validation │

    ├─────────────────────────────────────────────────────────────────┤

    │ L9 INFRASTRUCTURE LAYER │

    │ Compute · Storage · Network · Edge · Sovereign regions │

    └─────────────────────────────────────────────────────────────────┘

    ```

    Layers MUST communicate through defined service APIs. Direct layer bypass — e.g., Presentation to Vault without Authorization validation — is prohibited for consequential operations.

    Section 2.02 — Presentation Layer

    The Presentation Layer delivers human-facing interfaces across web domains and Flutter applications. Responsibilities:

    • Render human-inspectable views of grants, graph subgraphs, vault partition metadata, trust scores, and agent status
    • Initiate authorization ceremonies (signing, approval, revocation)
    • Localize and adapt accessibility per Life Operating System domain preferences
    • MUST NOT embed business authorization logic — delegates to Companion and Authorization layers

    Section 2.03 — Companion Layer

    The Companion Layer implements Keyra Companion mediation per Companion Charter. Responsibilities:

    • Orchestrate multi-service workflows (e.g., agent purchase → family approval → vault credential bind → marketplace settlement)
    • Enforce Life Operating System domain policies
    • Present comparative options to humans before consequential commits
    • Maintain Companion session context with provenance references to graph and twin state

    Section 2.04 — Agent Layer

    The Agent Layer hosts KAAI Runtime per KAAI Standard. Responsibilities:

    • Agent registration, certificate issuance, execution sandboxing
    • Pre-execution Authorization Certificate validation
    • Post-execution audit emission to vault and graph
    • Trust score updates and revocation propagation hooks

    Section 2.05 — Twin Layer

    The Twin Layer implements Human Digital Twin projections. Responsibilities:

    • Layered twin state: Identity, Relationship, Preference, Goal, Context, Decision, Memory, Prediction
    • Synchronization between local and federated replicas
    • Bounded projection APIs — agents receive projections, not raw vault

    Section 2.06 — Graph Layer

    The Graph Layer implements Life Graph Architecture and related graphs. Responsibilities:

    • Multi-typed node and edge storage with temporal versioning
    • Authorization-governed query and mutation
    • Cross-graph references: Family, Organization, Trust, Authorization, Memory, Device, Agent

    Section 2.07 — Vault Layer

    The Vault Layer implements Trust Vault Architecture. Responsibilities:

    • Encrypted artifact storage with partition hierarchy
    • Key management integration with Device Trust Mesh
    • Export pack generation and import validation
    • Access audit hash chaining

    Section 2.08 — Trust Layer

    The Trust Layer implements trust metrics, certification state, and federation references per Global Trust Economy. Responsibilities:

    • Trust score computation inputs and history
    • Certification level registry integration
    • Federation bridge routing for cross-border verification
    • Settlement evidence pointer resolution

    Section 2.09 — Authorization Layer

    The Authorization Layer is the cross-cutting enforcement plane. Responsibilities:

    • Grant storage and certificate chain validation
    • Revocation registry and propagation
    • Scope evaluation engine (data, financial, communication, family, enterprise, government)
    • Integration point for all layers — every consequential API MUST pass Authorization Layer validation

    Section 2.10 — Infrastructure Layer

    The Infrastructure Layer provides compute, storage, networking, and regional deployment substrates. Responsibilities:

    • Sovereign region isolation where policy requires
    • Edge nodes for local-first sync
    • Hardware security module integration for institutional deployments
    • Network policies enforcing zero-trust service mesh

    Section 2.11 — Reference Request Flow

    ASCII diagram — authorized agent action:

    ```

    Human → Companion UI → Companion Service → Authorization Service (validate grant)

    KAAI Runtime (agent execute)

    Graph Service (read context) ← Vault Service (secrets by ref)

    Device Trust Mesh (presence if required)

    Audit → Vault + Graph + Trust Layer

    ```

    Section 2.12 — Layer Dependency Matrix

    | Layer | Depends on | MUST NOT depend on |

    |-------|------------|-------------------|

    | Presentation | Companion, Authorization | Vault direct |

    | Companion | Authorization, Graph, Twin | Agent internal state |

    | Agent | Authorization, Vault refs, Graph | Presentation session |

    | Twin | Graph, Vault | Marketplace billing |

    | Graph | Authorization, Vault refs | Agent runtime |

    | Vault | Authorization, Device Trust | Marketplace |

    | Trust | Authorization, Graph, Vault audit | Engagement analytics |

    | Authorization | Vault keys, Device Trust | Application silos |

    | Infrastructure | — | Business logic |

    Section 2.13 — Scenario 2 — Cross-Layer Family Approval

    A teenager requests agent installation with financial scope. Flow:

  • Presentation: Marketplace agent detail → install request
  • Companion: Presents scope manifest, trust score, certification level to human and guardian
  • Authorization: Creates pending grant; requires guardian co-signature per Family Trust Network
  • Device Trust Mesh: Guardian Keyra Key presence attestation
  • Vault: Stores agent certificate binding upon approval
  • Graph: Creates `Human → authorizes → Agent` edge with temporal bounds
  • KAAI Runtime: Registers agent; enables execution within scope
  • Trust Layer: Records installation in trust history
  • Bypassing Companion for install would violate Companion-first architecture. Bypassing guardian validation would violate Family Trust Network conformance.


    PART III — Front-End Architecture

    Section 3.01 — Web Platform Domain Architecture

    The Companion Platform web presence operates across six sovereign domains, each scoped to a life domain per Life Operating System:

    | Domain | Purpose | Primary audience |

    |--------|---------|------------------|

    | companion.keyra.ie | Companion Home, chat, voice, life dashboard | Sovereign Humans |

    | family.keyra.ie | Family network, guardian approvals, shared vaults | Families |

    | work.keyra.ie | Organization graph, enterprise companion, work twin | Professionals, enterprises |

    | trust.keyra.ie | Trust vault inspection, authorization center, audit | Security-conscious users |

    | developers.keyra.ie | Agent SDK, KAAI registration, API docs, sandbox | Developers |

    | market.keyra.ie | Agent discovery, certification, billing, settlement | Humans, publishers |

    Each domain MUST share a common identity substrate (human-root session) while enforcing domain-scoped authorization. Cross-domain navigation MUST re-validate grants; session alone MUST NOT imply cross-domain scope.

    Section 3.02 — Front-End Architecture Pattern

    Web applications implement a modular monorepo front-end with:

  • Shell application — authentication bootstrap, domain routing, localization, accessibility baseline
  • Domain micro-frontends — independently deployable bundles per domain with shared design system
  • Companion SDK — JavaScript/TypeScript client for Companion API, Authorization ceremonies, real-time sync
  • Graph Explorer SDK — visualization and query builder for authorized subgraphs
  • Vault SDK — partition metadata display; secret operations delegate to secure ceremonies
  • Implementations SHOULD use progressive enhancement: core inspectability and revocation flows MUST work without WebAssembly or heavy client dependencies.

    Section 3.03 — Routing Architecture

    Routing follows domain-first, resource-second patterns:

    ```

    companion.keyra.ie/home

    companion.keyra.ie/chat/{conversationId}

    companion.keyra.ie/voice

    companion.keyra.ie/dashboard/{domain}

    family.keyra.ie/network

    family.keyra.ie/approvals/pending

    work.keyra.ie/org/{orgId}/companion

    trust.keyra.ie/vault/{partitionId}

    trust.keyra.ie/authorizations/{grantId}

    developers.keyra.ie/agents/register

    market.keyra.ie/agents/{agentId}

    ```

    Route guards MUST invoke Authorization Service before rendering protected resources. Deep links MUST carry grant context tokens validated server-side.

    Section 3.04 — State Management Architecture

    Front-end state divides into four categories:

    | State type | Storage | Sync | Example |

    |------------|---------|------|---------|

    | Session | Memory + secure cookie | Server session | Auth tokens, human ID |

    | UI | Local component state | None | Panel expansion |

    | Domain | Redux/Zustand store | WebSocket + REST | Companion conversation |

    | Sovereign | IndexedDB + Vault refs | CRDT or event sync | Offline grant cache |

    Sovereign state MUST NOT store vault secrets in localStorage. IndexedDB entries MUST be encrypted with device-derived keys where offline cache is required.

    Section 3.05 — Authentication Architecture

    Web authentication implements human-root identity with:

  • Primary: Device Trust Mesh-bound WebAuthn / passkey ceremony tied to Keyra Key or phone secure enclave
  • Secondary: Recovery flows with multi-factor human verification and Companion mediation
  • Federation: Institutional SSO overlays for work.keyra.ie — subordinate to human root, not substitute
  • Sessions MUST bind to device attestation where policy requires. Session tokens MUST be short-lived with refresh tied to presence re-verification for high-risk domains (trust.keyra.ie, market.keyra.ie financial flows).

    Section 3.06 — Authorization Architecture (Front-End)

    Front-end authorization is declarative and server-validated:

    • UI components declare required scopes: `requiredScopes: ['vault.read.identity', 'graph.query.life']`
    • Authorization Service returns capability tokens for rendering
    • Write operations invoke signing ceremonies — never silent POST

    Prohibited: hiding controls without server enforcement. If a button is hidden client-side but API permits action, the implementation is non-conformant.

    Section 3.07 — Localization Architecture

    Localization MUST support:

    • Unicode throughout; RTL layouts for Arabic, Hebrew, and related scripts
    • Locale-aware date, number, currency formatting per human preference in Twin Preference layer
    • Jurisdiction-aware legal copy for marketplace and trust domains without substituting human consent
    • Accessibility strings separated from business logic

    Section 3.08 — Accessibility Architecture

    Accessibility conformance MUST target WCAG 2.2 AA minimum:

    • Voice navigation integration with Companion voice layer
    • Screen reader announcements for authorization state changes and revocation confirmation
    • Keyboard-complete flows for trust.keyra.ie ceremonies
    • Reduced motion and high contrast themes per Life Operating System preferences

    Section 3.09 — Scenario 3 — Cross-Domain Authorization

    A user authenticated on companion.keyra.ie navigates to market.keyra.ie to purchase an agent. The shell detects domain change, requests market-scoped capability token, evaluates existing grants. Financial scope absent — Companion presents grant extension ceremony. User signs with Keyra Key. Authorization Service issues time-bounded market token. Purchase proceeds. Audit records cite grant extension ID.


    PART IV — Flutter Architecture

    Section 4.01 — Flutter as Primary Mobile Companion Shell

    Flutter implements the primary mobile Companion experience — local-first, Device Trust Mesh-integrated, vault-adjacent. Flutter applications MUST operate as sovereign clients, not thin shells over platform-controlled WebViews for consequential operations.

    Section 4.02 — Flutter Module Architecture

    ```

    keyra_companion_app/

    ├── core/ # DI, routing, auth, localization

    ├── modules/

    │ ├── companion_home/

    │ ├── chat/

    │ ├── voice/

    │ ├── life_dashboard/

    │ ├── trust_vault/

    │ ├── permissions/

    │ ├── agent_manager/

    │ ├── family_network/

    │ ├── device_mesh/

    │ ├── authorization_center/

    │ ├── memory_explorer/

    │ ├── life_graph_explorer/

    │ └── twin_explorer/

    ├── platform/ # iOS, Android, desktop bridges

    └── sync/ # Local-first replication engine

    ```

    Each module MUST declare Authorization scopes in `module_manifest.yaml`. Modules MUST NOT access vault APIs without manifest-declared scopes validated at runtime.

    Section 4.03 — Companion Home Module

    Companion Home is the default entry surface:

    • Life domain cards per Life Operating System
    • Pending approvals, trust alerts, agent activity summary
    • Quick actions: voice, chat, revoke all session grants (emergency)
    • Local-first: renders from cached graph summary when offline

    Section 4.04 — Chat Module

    Chat integrates Companion intelligence layer with:

    • Message provenance (human, companion, agent) visibly distinguished
    • Agent messages MUST display Agent ID and certification badge
    • Tool calls require inline authorization preview before execution
    • Conversation memory references vault partitions — not raw storage in chat DB

    Section 4.05 — Voice Module

    Voice module implements on-device and hybrid speech:

    • Wake word and push-to-talk configurable per human preference
    • Voice commands map to Companion intents, not direct agent dispatch
    • High-risk voice confirmations require secondary attestation (Keyra Key tap)

    Section 4.06 — Life Dashboard Module

    Dashboard aggregates authorized metrics across life domains:

    • Health, wealth, travel, family, work widgets — each scoped by graph authorization
    • Widget data fetched via Graph Service subgraph queries
    • Drill-down routes to Life Graph Explorer with preserved scope context

    Section 4.07 — Trust Vault Module

    Vault module provides partition navigation and ceremonies:

    • Biometric or Keyra Key gate for partition unlock
    • Export pack initiation with progress and hash verification
    • Access log viewer with authorization reference drill-down
    • MUST use platform secure storage and Flutter platform channels for crypto operations

    Section 4.08 — Permissions Module

    Permissions module surfaces grant graph:

    • Active grants by agent, organization, family member
    • Scope timelines and decay schedules
    • One-tap revocation with propagation status indicator

    Section 4.09 — Agent Manager Module

    Agent Manager lists installed KAAI agents:

    • Certificate expiry, trust score trend, last action summary
    • Install from marketplace with in-app grant ceremony
    • Sandbox toggle for Experimental certification agents

    Section 4.10 — Family Network Module

    Family Network implements Family Trust Network UX:

    • Member roster, guardian relationships, child profiles
    • Approval queue for child agent and scope requests
    • Family budget visualization linked to marketplace settlement

    Section 4.11 — Device Mesh Module

    Device Mesh module displays Device Trust Mesh state:

    • Registered devices: phone, Keyra Key, watch, laptop, vehicle, home, enterprise
    • Trust level per device, last sync, presence capability
    • Device revocation and re-enrollment ceremonies

    Section 4.12 — Authorization Center Module

    Authorization Center consolidates signing workflows:

    • Pending signatures, delegation chains, certificate renewal
    • QR and NFC ceremonies for cross-device authorization

    Section 4.13 — Memory Explorer Module

    Memory Explorer navigates authorized memory partitions:

    • Temporal timeline, full-text search within scope
    • Deletion and retention policy controls per Life Operating System
    • Provenance chain to agent or human origin

    Section 4.14 — Life Graph Explorer Module

    Graph Explorer renders interactive subgraphs:

    • Force-directed or hierarchical layouts
    • Edge type filters: trust, authorization, ownership, dependency
    • Mutation requires write scope; read-only default

    Section 4.15 — Twin Explorer Module

    Twin Explorer displays Digital Twin layers:

    • Layer tabs: Identity, Preference, Goal, Context, Decision, Memory, Prediction
    • Projection diff view when twin diverges from human-directed corrections
    • Sync status with conflict resolution UI

    Section 4.16 — Flutter Platform Channels

    Platform channels MUST implement:

    | Channel | Responsibility |

    |---------|----------------|

    | vault_crypto | Encrypt/decrypt, key derivation |

    | device_trust | Attestation, presence, mesh sync |

    | secure_enclave | Key storage, signing |

    | biometrics | Local authentication |

    | nfc_keyra | Keyra Key tap ceremonies |

    Section 4.17 — Scenario 4 — Offline Revocation

    Human loses network connectivity. Agent misbehaves. Human opens Agent Manager offline, initiates revocation. Local revocation record written to vault partition with monotonic clock. Device Trust Mesh queues propagation. On reconnect, Authorization Service processes revocation; KAAI Runtime invalidates certificates within SLA. Audit shows offline-initiated revocation with device timestamp and subsequent sync confirmation.


    PART V — Backend Architecture

    Section 5.01 — Service-Oriented Backend Model

    The Companion Platform backend implements domain-bounded microservices with a unified API gateway and service mesh enforcing zero-trust mutual TLS. Services communicate via gRPC internally; external exposure via REST and GraphQL gateway per audience.

    Section 5.02 — API Layer

    The API Layer comprises:

    | Gateway | Audience | Protocols |

    |---------|----------|-----------|

    | Public API Gateway | Developers, partners | REST, GraphQL, webhooks |

    | Companion API Gateway | Web, Flutter clients | REST, WebSocket, SSE |

    | Institutional Gateway | Banks, telcos, government | REST, ISO 20022 overlays, custom FHIR where applicable |

    | Federation Gateway | Cross-border trust | Federation protocol, mTLS |

    All gateways MUST terminate TLS 1.3+, validate Authorization Layer tokens, and emit distributed trace context.

    Section 5.03 — Companion Service

    Companion Service responsibilities:

    • Session orchestration, conversation state, policy evaluation
    • Mediation endpoints: `POST /companion/mediate/agent-action`, `POST /companion/mediate/marketplace-purchase`
    • Integration with Life Operating System policy engine
    • MUST NOT store vault secrets — references only

    Section 5.04 — Agent Service

    Agent Service wraps KAAI Runtime (see Part X):

    • Registration, lifecycle, certificate management
    • Execution dispatch to sandboxed runtimes
    • Audit emission

    Section 5.05 — Authorization Service

    Authorization Service is the authoritative grant plane:

    • `POST /authz/grants`, `POST /authz/revoke`, `GET /authz/validate`
    • Certificate chain verification
    • Revocation registry with propagation workers
    • All other services MUST call validate before consequential operations

    Section 5.06 — Trust Service

    Trust Service manages:

    • Trust score computation and history
    • Certification level registry
    • Federation bridge lookups
    • Integration with Global Trust Economy indices

    Section 5.07 — Vault Service

    Vault Service manages:

    • Partition metadata, blob storage orchestration
    • Encrypted object store (client-side encryption default)
    • Export pack assembly and import validation
    • Access audit ingestion

    Section 5.08 — Twin Service

    Twin Service manages:

    • Twin layer CRUD per Human Digital Twin Architecture
    • Projection APIs for agents and companions
    • Sync conflict resolution with human-merge priority

    Section 5.09 — Graph Service

    Graph Service manages:

    • Life, Family, Organization, Trust, Authorization, Memory, Device, Agent graphs
    • Cypher-like query language with authorization injection
    • Temporal versioning and subgraph export

    Section 5.10 — Marketplace Service

    Marketplace Service manages:

    • Agent catalog, certification status, publisher records
    • Purchase flows, subscription billing integration
    • Settlement handoff to Trust Settlement Service

    Section 5.11 — Settlement Service

    Settlement Service manages:

    • Trust transaction clearing, escrow, hold windows
    • Cross-border settlement message routing
    • Bank and telco rail integration per Global Trust Economy

    Section 5.12 — Service Boundary Rules

    | Rule | Enforcement |

    |------|-------------|

    | No shared databases across bounded contexts | Separate schemas per service |

    | Authorization validate on every write | API middleware + service mesh policy |

    | Events over sync coupling | Kafka/NATS for domain events |

    | Idempotent mutations | Idempotency keys on financial and grant APIs |

    | Human-root foreign keys | SQL schemas reference sovereign_human_id |

    Section 5.13 — Event Architecture

    Domain events MUST include:

    ```json

    {

    "event_id": "uuid",

    "event_type": "authz.grant.created",

    "sovereign_human_id": "uuid",

    "authorization_ref": "grant-uuid",

    "provenance": { "companion_session_id": "uuid", "device_id": "uuid" },

    "audit_hash": "sha256",

    "timestamp": "ISO8601"

    }

    ```

    Consumers: Audit Service, Trust Service, Graph projection workers, Settlement Service.

    Section 5.14 — Scenario 5 — Service Failure Isolation

    Vault Service experiences outage. Companion Service MUST degrade gracefully: read-only graph and cached vault metadata available; write and agent execution requiring secrets MUST halt with human-visible error. Authorization Service remains available for revocation — revocations MUST queue for vault audit write when vault recovers. No silent fallback to unencrypted cache.


    PART VI — Graph Architecture

    Section 6.01 — Multi-Graph Platform Model

    The Companion Platform implements eight graph domains unified under Graph Service with shared authorization and temporal semantics per Life Graph Architecture:

    | Graph | Center node | Primary edges |

    |-------|-------------|---------------|

    | Life Graph | Sovereign Human | relationships, ownership, goals, events |

    | Family Graph | Family Trust Network | guardianship, approval, shared vault refs |

    | Organization Graph | Organization | employment, role, compliance overlay |

    | Trust Graph | Trust entities | trust scores, certification, decay |

    | Authorization Graph | Grants | scope, delegation, revocation |

    | Memory Graph | Memory artifacts | provenance, retention, partition ref |

    | Device Graph | Devices | trust level, presence, binding |

    | Agent Graph | KAAI agents | sponsorship, execution, accountability |

    Section 6.02 — Graph Schema Primitives

    All graphs share primitives:

    ```

    Node {

    id: UUID

    type: enum

    sovereign_human_id: UUID // root authority reference

    properties: JSONB

    valid_from: timestamp

    valid_to: timestamp | null

    provenance_ref: UUID

    authorization_scope: scope_id

    }

    Edge {

    id: UUID

    type: enum

    from_node_id: UUID

    to_node_id: UUID

    weight: float | null // trust graphs

    properties: JSONB

    valid_from: timestamp

    valid_to: timestamp | null

    provenance_ref: UUID

    }

    ```

    Mutations MUST create new temporal versions; destructive delete prohibited for audit-relevant edges — use `valid_to` closure.

    Section 6.03 — Life Graph Schema

    Core Life Graph node types:

    | Node type | Description |

    |-----------|-------------|

    | Human | Sovereign or related person |

    | Organization | Institution with bounded overlay |

    | Asset | Physical, digital, financial asset |

    | Goal | Human-authorized objective |

    | Event | Temporal life event |

    | MemoryRef | Pointer to vault partition |

    | Device | Device Trust Mesh member |

    | Agent | KAAI agent reference |

    Core edge types: `knows`, `owns`, `committed_to`, `authorized`, `depends_on`, `member_of`, `guardian_of`.

    Section 6.04 — Family Graph Schema

    Family Graph extends Life Graph with:

    • `FamilyNetwork` supernode linking members
    • `guardian_of` edges with approval policy properties
    • `child_safe_scope` edges binding agent catalogs
    • Budget edges linking to marketplace settlement accounts

    Child nodes MUST enforce guardian co-authorization on scope expansion.

    Section 6.05 — Organization Graph Schema

    Organization Graph implements Organization Graph Enterprise Companion Framework:

    • `Organization` node with compliance overlay properties
    • `employs` edges — employment does NOT transfer human root
    • `enterprise_agent_fleet` edges with department scope
    • `enterprise_vault_partition` refs subordinate to member vaults

    Section 6.06 — Graph APIs

    Graph Service exposes:

    | Endpoint | Method | Purpose |

    |----------|--------|---------|

    | `/graph/query` | POST | Authorized subgraph query |

    | `/graph/nodes` | POST | Create node with provenance |

    | `/graph/edges` | POST | Create edge with authorization check |

    | `/graph/export` | GET | Subgraph export pack |

    | `/graph/import` | POST | Validated import with merge policy |

    Query language MUST inject authorization filters — queries MUST NOT return nodes outside caller scope.

    Section 6.07 — Graph Storage Models

    Implementations SHOULD support hybrid storage:

    | Tier | Engine | Use case |

    |------|--------|----------|

    | Hot | Neo4j or Amazon Neptune | Interactive traversal, Companion context |

    | Warm | PostgreSQL with pgvector + recursive CTE | Relational joins, reporting |

    | Cold | Object store JSONL export | Archive, legal hold |

    Life Graph authoritative semantics live in Graph Service API — storage engine is replaceable.

    Section 6.08 — Graph-Vault Reference Pattern

    Graph stores structure and references. Vault stores secrets and blobs. Pattern:

    ```

    LifeGraph: Human --owns--> MemoryRef --vault_ref--> vault://partition/memories/abc

    ```

    Agents query graph for context; vault access requires separate authorization validation per reference.

    Section 6.09 — Scenario 6 — Temporal Authorization Query

    Query: "What agents could access health data on 2024-03-15?" Graph Service traverses Authorization Graph with `valid_from`/`valid_to` temporal filter, joins Agent Graph, returns list with grant IDs. Human inspects via Life Graph Explorer. Revoked grants show `valid_to` closure date.


    PART VII — SQL Architecture

    Section 7.01 — Relational Model Purpose

    SQL schemas provide transactional consistency, reporting, and institutional integration complementing graph storage. Relational models MUST reference `sovereign_human_id` as root foreign key. Institutional overlays use separate schemas with explicit subordination constraints.

    Section 7.02 — Core Entity Model

    ```

    Users (Sovereign Humans)

    └── Companions (1:1 or 1:n per policy)

    └── Companion Sessions

    └── Digital Twins

    └── Vaults

    └── Devices

    └── Families (membership)

    └── Organizations (membership)

    └── Agents (authorizations)

    └── Permissions / Authorizations

    └── Trust Scores

    └── Marketplace Transactions

    └── Settlement Records

    ```

    Section 7.03 — CREATE TABLE — Users

    ```sql

    CREATE TABLE sovereign_humans (

    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),

    public_did VARCHAR(255) UNIQUE NOT NULL,

    display_name VARCHAR(255),

    locale VARCHAR(16) DEFAULT 'en-IE',

    jurisdiction VARCHAR(8),

    root_key_fingerprint VARCHAR(128) NOT NULL,

    status VARCHAR(32) DEFAULT 'active'

    CHECK (status IN ('active', 'suspended', 'deceased', 'exported')),

    created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),

    updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW()

    );

    CREATE INDEX idx_sovereign_humans_did ON sovereign_humans(public_did);

    CREATE INDEX idx_sovereign_humans_status ON sovereign_humans(status);

    ```

    Section 7.04 — CREATE TABLE — Companions

    ```sql

    CREATE TABLE companions (

    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),

    sovereign_human_id UUID NOT NULL REFERENCES sovereign_humans(id),

    companion_version VARCHAR(32) NOT NULL,

    policy_profile_id UUID,

    device_primary_id UUID,

    status VARCHAR(32) DEFAULT 'active',

    created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),

    UNIQUE (sovereign_human_id, companion_version)

    );

    CREATE INDEX idx_companions_human ON companions(sovereign_human_id);

    ```

    Section 7.05 — CREATE TABLE — Agents

    ```sql

    CREATE TABLE agents (

    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),

    kaai_agent_id VARCHAR(255) UNIQUE NOT NULL,

    publisher_id UUID NOT NULL,

    certification_level VARCHAR(64) NOT NULL,

    name VARCHAR(255) NOT NULL,

    manifest_hash VARCHAR(128) NOT NULL,

    status VARCHAR(32) DEFAULT 'registered'

    CHECK (status IN ('registered', 'active', 'suspended', 'revoked', 'retired')),

    registered_at TIMESTAMPTZ NOT NULL DEFAULT NOW()

    );

    CREATE TABLE agent_authorizations (

    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),

    sovereign_human_id UUID NOT NULL REFERENCES sovereign_humans(id),

    agent_id UUID NOT NULL REFERENCES agents(id),

    grant_id UUID NOT NULL,

    scope_manifest JSONB NOT NULL,

    valid_from TIMESTAMPTZ NOT NULL DEFAULT NOW(),

    valid_to TIMESTAMPTZ,

    revoked_at TIMESTAMPTZ,

    device_binding_id UUID,

    certificate_chain_ref VARCHAR(512) NOT NULL

    );

    CREATE INDEX idx_agent_auth_human ON agent_authorizations(sovereign_human_id);

    CREATE INDEX idx_agent_auth_agent ON agent_authorizations(agent_id);

    CREATE INDEX idx_agent_auth_valid ON agent_authorizations(valid_from, valid_to)

    WHERE revoked_at IS NULL;

    ```

    Section 7.06 — CREATE TABLE — Authorizations

    ```sql

    CREATE TABLE authorizations (

    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),

    sovereign_human_id UUID NOT NULL REFERENCES sovereign_humans(id),

    grantor_type VARCHAR(32) NOT NULL,

    grantor_id UUID NOT NULL,

    grantee_type VARCHAR(32) NOT NULL,

    grantee_id UUID NOT NULL,

    scope_type VARCHAR(64) NOT NULL,

    scope_payload JSONB NOT NULL,

    parent_grant_id UUID REFERENCES authorizations(id),

    signature_ref VARCHAR(512) NOT NULL,

    valid_from TIMESTAMPTZ NOT NULL DEFAULT NOW(),

    valid_to TIMESTAMPTZ,

    revoked_at TIMESTAMPTZ,

    audit_hash VARCHAR(128) NOT NULL

    );

    CREATE INDEX idx_auth_human ON authorizations(sovereign_human_id);

    CREATE INDEX idx_auth_grantee ON authorizations(grantee_type, grantee_id);

    CREATE INDEX idx_auth_active ON authorizations(sovereign_human_id, scope_type)

    WHERE revoked_at IS NULL AND (valid_to IS NULL OR valid_to > NOW());

    ```

    Section 7.07 — CREATE TABLE — Vaults

    ```sql

    CREATE TABLE vaults (

    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),

    sovereign_human_id UUID NOT NULL REFERENCES sovereign_humans(id),

    vault_type VARCHAR(32) NOT NULL

    CHECK (vault_type IN ('identity', 'memory', 'authorization',

    'family', 'organization', 'legacy', 'companion', 'agent')),

    partition_path VARCHAR(512) NOT NULL,

    encryption_key_ref VARCHAR(512) NOT NULL,

    storage_backend VARCHAR(64) NOT NULL,

    created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),

    UNIQUE (sovereign_human_id, vault_type, partition_path)

    );

    CREATE TABLE vault_access_log (

    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),

    vault_id UUID NOT NULL REFERENCES vaults(id),

    accessor_type VARCHAR(32) NOT NULL,

    accessor_id UUID NOT NULL,

    operation VARCHAR(32) NOT NULL,

    authorization_id UUID REFERENCES authorizations(id),

    audit_hash VARCHAR(128) NOT NULL,

    accessed_at TIMESTAMPTZ NOT NULL DEFAULT NOW()

    ) PARTITION BY RANGE (accessed_at);

    ```

    Section 7.08 — CREATE TABLE — Devices

    ```sql

    CREATE TABLE devices (

    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),

    sovereign_human_id UUID NOT NULL REFERENCES sovereign_humans(id),

    device_type VARCHAR(32) NOT NULL

    CHECK (device_type IN ('phone', 'keyra_key', 'watch', 'laptop',

    'vehicle', 'home', 'enterprise')),

    device_fingerprint VARCHAR(256) UNIQUE NOT NULL,

    trust_level DECIMAL(4,3) NOT NULL DEFAULT 0.500,

    attestation_ref VARCHAR(512),

    last_sync_at TIMESTAMPTZ,

    status VARCHAR(32) DEFAULT 'active',

    enrolled_at TIMESTAMPTZ NOT NULL DEFAULT NOW()

    );

    CREATE INDEX idx_devices_human ON devices(sovereign_human_id);

    CREATE INDEX idx_devices_trust ON devices(sovereign_human_id, trust_level DESC);

    ```

    Section 7.09 — CREATE TABLE — Trust Scores

    ```sql

    CREATE TABLE trust_scores (

    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),

    entity_type VARCHAR(32) NOT NULL,

    entity_id UUID NOT NULL,

    score DECIMAL(4,3) NOT NULL CHECK (score >= 0 AND score <= 1),

    index_value SMALLINT CHECK (index_value >= 0 AND index_value <= 100),

    inputs_snapshot JSONB NOT NULL,

    computed_at TIMESTAMPTZ NOT NULL DEFAULT NOW()

    );

    CREATE INDEX idx_trust_entity ON trust_scores(entity_type, entity_id, computed_at DESC);

    ```

    Section 7.10 — CREATE TABLE — Families and Organizations

    ```sql

    CREATE TABLE families (

    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),

    name VARCHAR(255),

    charter_ref VARCHAR(512),

    created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()

    );

    CREATE TABLE family_members (

    family_id UUID NOT NULL REFERENCES families(id),

    sovereign_human_id UUID NOT NULL REFERENCES sovereign_humans(id),

    role VARCHAR(32) NOT NULL

    CHECK (role IN ('member', 'guardian', 'child', 'executor')),

    joined_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),

    PRIMARY KEY (family_id, sovereign_human_id)

    );

    CREATE TABLE organizations (

    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),

    legal_name VARCHAR(512) NOT NULL,

    jurisdiction VARCHAR(8),

    org_graph_root_ref UUID,

    created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()

    );

    CREATE TABLE organization_members (

    organization_id UUID NOT NULL REFERENCES organizations(id),

    sovereign_human_id UUID NOT NULL REFERENCES sovereign_humans(id),

    role VARCHAR(64),

    employed_from TIMESTAMPTZ NOT NULL DEFAULT NOW(),

    employed_to TIMESTAMPTZ,

    PRIMARY KEY (organization_id, sovereign_human_id)

    );

    ```

    Section 7.11 — CREATE TABLE — Marketplace and Settlement

    ```sql

    CREATE TABLE marketplace_listings (

    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),

    agent_id UUID NOT NULL REFERENCES agents(id),

    publisher_id UUID NOT NULL,

    pricing_model VARCHAR(32) NOT NULL,

    price_cents BIGINT,

    currency CHAR(3),

    certification_level VARCHAR(64) NOT NULL,

    published_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),

    status VARCHAR(32) DEFAULT 'active'

    );

    CREATE TABLE marketplace_transactions (

    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),

    sovereign_human_id UUID NOT NULL REFERENCES sovereign_humans(id),

    listing_id UUID NOT NULL REFERENCES marketplace_listings(id),

    authorization_id UUID NOT NULL REFERENCES authorizations(id),

    amount_cents BIGINT NOT NULL,

    currency CHAR(3) NOT NULL,

    status VARCHAR(32) NOT NULL,

    created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()

    );

    CREATE TABLE settlement_records (

    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),

    transaction_id UUID NOT NULL REFERENCES marketplace_transactions(id),

    settlement_type VARCHAR(64) NOT NULL,

    authorization_ref VARCHAR(512) NOT NULL,

    trust_hold_until TIMESTAMPTZ,

    settled_at TIMESTAMPTZ,

    audit_hash VARCHAR(128) NOT NULL

    );

    ```

    Section 7.12 — Partitioning Strategy

    | Table | Strategy | Rationale |

    |-------|----------|-----------|

    | vault_access_log | Monthly RANGE on accessed_at | High volume, time-scoped queries |

    | authorizations | HASH on sovereign_human_id | Even sharding per human |

    | trust_scores | LIST on entity_type + time archive | Entity-scoped history |

    | settlement_records | Quarterly RANGE on settled_at | Financial reporting periods |

    Implementations at 100M+ humans SHOULD shard by `sovereign_human_id` hash across regional clusters.

    Section 7.13 — Index Strategy

    • All human-scoped queries MUST hit `sovereign_human_id` index first
    • Partial indexes on active grants (`revoked_at IS NULL`) reduce scan cost
    • Covering indexes for Companion dashboard aggregations SHOULD be maintained by read replicas
    • Graph projection tables MAY denormalize hot edges for SQL reporting — source of truth remains Graph Service

    Section 7.14 — Scenario 7 — Institutional Reporting Query

    Enterprise compliance officer queries organization_members joined with agent_authorizations for active workforce agents. SQL returns scoped list. Officer lacks human-root access to member personal partitions — query enforced by row-level security on `organization_id`. Personal agent grants outside enterprise scope excluded by `scope_payload->>'domain' != 'enterprise'` filter.


    PART VIII — Twin Architecture

    Section 8.01 — Twin Layer Model

    Human Digital Twin implements eight layers as bounded projections per Human Digital Twin Architecture:

    | Layer | Content | Mutability |

    |-------|---------|------------|

    | Identity | Names, identifiers, public attributes | Human-directed |

    | Relationship | Social and institutional bonds | Graph-sourced |

    | Preference | Settings, communication style | Human-directed |

    | Goal | Objectives, priorities | Human-directed |

    | Context | Situational state, location policy | Sensor-derived, human-overridable |

    | Decision | Decision patterns, stated principles | Human-correctable |

    | Memory | Authorized memory projections | Vault-sourced refs |

    | Prediction | Forward models, suggestions | Advisory only — non-binding |

    Prediction layer MUST NOT execute consequential actions without human or authorized agent grant.

    Section 8.02 — Twin Service APIs

    | Endpoint | Purpose |

    |----------|---------|

    | `GET /twin/{humanId}/layers/{layer}` | Authorized layer read |

    | `PATCH /twin/{humanId}/layers/{layer}` | Human-directed update |

    | `GET /twin/{humanId}/projection` | Bounded projection for agent scope |

    | `POST /twin/sync` | Multi-replica synchronization |

    | `GET /twin/{humanId}/conflicts` | Pending merge conflicts |

    Section 8.03 — Twin-Graph Integration

    Twin layers map to Life Graph nodes and edges:

    • Identity layer ↔ Human node properties
    • Relationship layer ↔ relationship edges
    • Goal layer ↔ Goal nodes
    • Memory layer ↔ MemoryRef nodes

    Twin Service MUST NOT duplicate graph topology — it projects and enriches.

    Section 8.04 — Twin-Vault Integration

    Sensitive twin attributes (health indicators, financial propensity models) MUST store values in vault partitions; twin holds references and redacted summaries for agent projection.

    Section 8.05 — Synchronization Architecture

    Twin sync implements human-priority conflict resolution:

  • Local device replica and cloud replica maintain version vectors
  • On conflict, Companion presents diff to human
  • Human merge decision recorded as provenance
  • Prediction layer resets on Identity or Preference breaking changes
  • Section 8.06 — Agent Projection API

    Agents receive `TwinProjection` bounded by authorization scope:

    ```json

    {

    "projection_id": "uuid",

    "scope": ["preference.communication", "goal.travel"],

    "layers": {

    "preference": { "timezone": "Europe/Dublin", "language": "en-IE" },

    "goal": { "active_goals": ["uuid-goal-1"] }

    },

    "expires_at": "ISO8601",

    "grant_ref": "authorization-uuid"

    }

    ```

    Out-of-scope layer requests MUST return 403 — not empty stubs that leak existence.

    Section 8.07 — Scenario 8 — Twin Correction

    Twin Prediction layer suggests aggressive investment rebalancing. Human rejects suggestion. Correction recorded in Decision layer with `human_override: true`. Prediction model receives feedback signal. Agent querying twin sees corrected decision pattern — not raw model output.


    PART IX — Trust Vault Architecture

    Section 9.01 — Vault Partition Hierarchy

    Trust Vault implements hierarchical partitions per Trust Vault Architecture:

    ```

    Vault Root (sovereign_human_id)

    ├── Identity/

    ├── Authorization/

    ├── Memory/

    │ ├── personal/

    │ ├── health/

    │ └── legacy/

    ├── Family/ (refs to family shared partitions)

    ├── Organization/ (enterprise overlays)

    ├── Companion/

    ├── Agent/ (certificate stores)

    └── Legacy/ (succession instruments)

    ```

    Section 9.02 — Storage Architecture

    | Component | Responsibility |

    |-----------|----------------|

    | Metadata DB | Partition tree, ACL refs, blob pointers |

    | Blob store | Encrypted objects (S3-compatible, local filesystem) |

    | Key service | Wrapped DEKs, human root key ceremony |

    | Audit log | Append-only hash chain |

    Client-side encryption MUST be default: server stores ciphertext; keys unwrapped on device.

    Section 9.03 — Encryption Architecture

  • Human root key — Keyra Key or secure enclave; never leaves device unwrapped
  • Partition DEK — AES-256-GCM per partition; wrapped by root
  • Blob encryption — per-object DEK wrapped by partition DEK
  • Transit — TLS 1.3 + optional double encryption for federation
  • Post-quantum readiness: implementations SHOULD support hybrid key exchange (X25519 + ML-KEM) for federation links per Security Architecture Part XIII.

    Section 9.04 — Vault APIs

    | Operation | Endpoint | Authorization |

    |-----------|----------|---------------|

    | List partitions | `GET /vault/partitions` | vault.read.metadata |

    | Read blob | `GET /vault/blobs/{id}` | vault.read.{partition} |

    | Write blob | `PUT /vault/blobs/{id}` | vault.write.{partition} |

    | Export pack | `POST /vault/export` | vault.export + human ceremony |

    | Import pack | `POST /vault/import` | vault.import + validation |

    | Delete | `DELETE /vault/blobs/{id}` | vault.delete + audit |

    Section 9.05 — Identity Vault

    Stores: government ID refs, biometric templates (hashed), recovery seeds, DID documents. Highest protection tier — all access requires presence attestation.

    Section 9.06 — Authorization Vault

    Stores: signing keys for grants, certificate chains, revocation receipts. Authorization Service reads validation material; private keys never exposed to agents.

    Section 9.07 — Memory Vault

    Stores: documents, media, conversation archives, health records. Linked from Memory Graph via refs. Retention policies enforced per Life Operating System domain rules.

    Section 9.08 — Family Vault

    Federated partitions with multi-human ACL. Guardian keys required for child partition access. Inheritance edges from Family Trust Network.

    Section 9.09 — Organization Vault

    Enterprise partitions for contracts, compliance archives. Employment termination MUST trigger access review — enterprise does not retain personal partitions.

    Section 9.10 — Legacy Vault

    Succession instruments, beneficiary designations, staged release timers. Executor grants per Trust Vault Architecture inheritance ceremonies.

    Section 9.11 — Export Ceremony

    Export pack contains: encrypted blobs, partition manifest, graph subgraph refs, authorization history hashes, provenance chain. Format MUST be versioned and interoperable across Companion Platform implementations.

    Section 9.12 — Scenario 9 — Vault Migration

    Human migrates from Region A to Region B deployment. Initiates export on device. Export pack generated locally. Import to Region B validates hashes. Federation Gateway updates DID registry pointers. Old region replicas scheduled for deletion after confirmation. Human root key unchanged — sovereignty preserved.


    PART X — KAAI Runtime

    Section 10.01 — Runtime Architecture Overview

    KAAI Runtime implements agent lifecycle per KAAI Standard:

    ```

    Registration → Certification → Authorization Binding → Execution Sandbox → Audit → Trust Update → Revocation

    ```

    Section 10.02 — Agent Registration

    Registration pipeline:

  • Publisher submits agent manifest (capabilities, scope requests, code hash)
  • Marketplace Service validates manifest schema
  • Certification workflow per certification level
  • Agent ID and Identity Certificate issued
  • Graph Agent node created with provenance
  • Section 10.03 — Execution Sandbox

    Sandbox MUST enforce:

    • CPU/memory/network quotas per certification level
    • Egress allowlist per scope manifest
    • No filesystem access outside designated scratch
    • Syscall filtering on Linux; WASM sandbox for portable agents

    Experimental agents MUST run in highest isolation tier.

    Section 10.04 — Authorization Gate

    Pre-execution checklist:

  • Valid Agent Identity Certificate
  • Valid Authorization Certificate chain rooted in sovereign human
  • Scope covers requested operation
  • Device presence attestation if required
  • Trust score above floor if required
  • Not on revocation list
  • Failure at any step MUST abort with auditable denial.

    Section 10.05 — Auditing

    Each execution emits KAAI-LOG record:

    ```

    timestamp | agent_id | human_id | grant_id | action | input_hash | output_hash | audit_hash

    ```

    Logs append to vault Agent partition and stream to observability pipeline.

    Section 10.06 — Trust Scoring Integration

    Post-execution: Trust Service receives outcome signals — success, human complaint, policy violation, anomaly. Scores update per KAAI trust decay rules.

    Section 10.07 — Revocation

    Revocation sources: human, guardian, organization admin (enterprise scope only), marketplace governance, trust incident. Propagation:

  • Authorization Service marks grant revoked
  • KAAI Runtime invalidates cached certificates within 60 seconds
  • Pending executions cancelled
  • Settlement holds applied if financial scope
  • Section 10.08 — Scenario 10 — Compromised Agent

    Anomaly detection flags agent exfiltration pattern. Trust Service auto-suspends agent pending human review. Authorization Service issues emergency revocation. Device Trust Mesh invalidates device binding. Human receives Companion alert with one-tap confirm revocation. Audit chain supports forensic review.


    PART XI — Device Trust Mesh Runtime

    Section 11.01 — Device Trust Mesh Purpose

    Device Trust Mesh implements hardware-rooted identity and presence verification per Device Trust Mesh instrument. The mesh binds authorization to physical devices the human controls — phone, Keyra Key, watch, laptop, vehicle, home systems, enterprise-managed devices.

    Section 11.02 — Device Classes

    | Device class | Trust anchor | Presence capability |

    |--------------|--------------|---------------------|

    | Phone | Secure enclave, biometrics | Continuous, NFC, BLE |

    | Keyra Key | Hardware secure element | Tap, NFC, physical possession |

    | Watch | Paired secure element | Wrist presence, heart rate optional |

    | Laptop | TPM 2.0 / Secure Enclave | Session presence |

    | Vehicle | Manufacturer HSM + pairing | Geofenced presence |

    | Home | Matter/Thread hub with vault ref | Location policy |

    | Enterprise | MDM-attested device | Corporate policy overlay |

    Section 11.03 — Trust Synchronization Protocol

    Mesh sync operates as gossip with authoritative reconciliation:

    ```

    Device A (phone) ←→ Sync Relay ←→ Device B (Keyra Key)

    ↓ ↓

    Local trust state Local trust state

    ↓ ↓

    └──────── Authorization Service ────────┘

    ```

    Protocol messages:

  • `TRUST_STATE_ANNOUNCE` — device ID, trust level, cert fingerprint, epoch
  • `TRUST_STATE_CHALLENGE` — nonce for attestation
  • `TRUST_STATE_RESPONSE` — signed attestation quote
  • `TRUST_STATE_REVOKE` — device revocation with human signature
  • `TRUST_MESH_SYNC` — epoch reconciliation for conflict resolution
  • Implementations MUST use monotonic epoch counters to prevent rollback attacks.

    Section 11.04 — Presence Verification

    Presence levels (0.0–1.0) computed from:

    • Recent attestation freshness
    • Biometric or Keyra Key confirmation for high-risk
    • Geolocation policy match (optional, human-configured)
    • Multi-device quorum for critical operations

    Authorization policies MAY require `presence_level >= threshold` for financial, health, and cross-border operations.

    Section 11.05 — Device Enrollment Ceremony

  • Human initiates enrollment on Companion
  • New device generates key pair in secure element
  • Existing trusted device (or Keyra Key) co-signs enrollment grant
  • Device record created in SQL and Device Graph
  • Trust level initialized per device class defaults
  • Section 11.06 — Device Revocation

    Revocation MUST propagate within 120 seconds to all mesh members. Revoked devices MUST NOT unwrap vault DEKs or sign authorizations. Re-enrollment requires fresh ceremony — no silent un-revoke.

    Section 11.07 — Enterprise Device Overlay

    Enterprise devices carry MDM attestation overlay. Organization MAY enforce compliance policies on enterprise partition access. Organization MUST NOT access personal vault partitions via enterprise device without member grant.

    Section 11.08 — Scenario 11 — Multi-Device Purchase Authorization

    Agent requests purchase above threshold. Policy requires Keyra Key tap (presence 0.9+) and phone online confirmation. Phone receives push; human taps Keyra Key to NFC field; Device Trust Mesh raises presence; Authorization Service issues one-time signing token; marketplace settlement proceeds.


    PART XII — AI Architecture

    Section 12.01 — AI Layer Placement

    AI capabilities span Local, Hybrid, and Cloud models orchestrated by Companion Intelligence Layer — never bypassing Authorization or Companion mediation for consequential actions.

    ```

    ┌─────────────────────────────────────────┐

    │ Companion Intelligence Layer │

    ├─────────────────────────────────────────┤

    │ Local Models │ Hybrid │ Cloud Models │

    ├─────────────────────────────────────────┤

    │ Vector DB │ Memory System │ Prompt Sys │

    ├─────────────────────────────────────────┤

    │ Reasoning │ Tool Router │ KAAI Runtime │

    └─────────────────────────────────────────┘

    ```

    Section 12.02 — Local Models

    Local models MUST support:

    • On-device inference for preference classification, intent routing, low-risk summarization
    • No training on human data without explicit grant
    • Model weights integrity verification on load

    Examples: small language models for offline chat drafts; embedding models for local memory search.

    Section 12.03 — Hybrid Models

    Hybrid pattern: local preprocessing (PII redaction, scope tagging) → authorized cloud inference → local post-processing and vault storage.

    Redaction MUST occur before egress. Cloud inference MUST receive TwinProjection — not raw vault.

    Section 12.04 — Cloud Models

    Cloud models used when:

    • Human grants cloud inference scope
    • Task exceeds local capability
    • Certification requires specific model lineage for audit

    Cloud providers MUST be selectable per human policy. Enterprise MAY mandate provider list for work domain only.

    Section 12.05 — Vector Databases

    Vector indices store embeddings for authorized memory search:

    • Per-partition indices with encryption at rest
    • Embedding generation logged with provenance
    • Deletion MUST remove vectors when human deletes source memory

    Implementations MAY use pgvector, Qdrant, or Milvus — partitioned by `sovereign_human_id`.

    Section 12.06 — Memory Systems

    Memory architecture tiers:

    | Tier | Latency | Content |

    |------|---------|---------|

    | Working | Session | Active conversation context |

    | Short-term | Hours–days | Recent interactions, cached projections |

    | Long-term | Permanent | Vault-backed with retention policy |

    Companion MUST distinguish memory tiers in UI. Long-term writes require vault authorization.

    Section 12.07 — Prompt Systems

    Prompt assembly pipeline:

  • Retrieve authorized twin projection
  • Inject graph context subgraph (bounded token budget)
  • Apply Life Operating System domain policy filters
  • Attach KAAI scope manifest for tool calls
  • Log prompt hash — not raw prompt — in audit for privacy
  • Section 12.08 — Reasoning Systems

    Multi-step reasoning MUST route tool calls through KAAI Runtime. Chain-of-thought MAY be stored in working memory only unless human opts into decision layer persistence.

    Section 12.09 — Companion Intelligence Layer

    Companion Intelligence Layer responsibilities:

    • Intent classification and routing (chat, voice, agent dispatch)
    • Risk classification for mediation depth
    • Model selection per policy (local vs cloud)
    • Human-facing explanation generation for agent proposals

    Section 12.10 — Scenario 12 — PII-Safe Cloud Inference

    Human asks health question requiring advanced model. Companion redacts identifiers locally, attaches health-scope grant token, sends redacted prompt to authorized cloud endpoint. Response validated for scope compliance before display. Audit records grant ref and prompt hash — not medical content.


    PART XIII — Security Architecture

    Section 13.01 — Zero Trust Foundation

    Companion Platform implements zero trust throughout:

    • No implicit trust by network location
    • Mutual TLS between all services
    • Every request authenticated and authorized
    • Least privilege service accounts
    • Continuous device and agent trust evaluation

    Section 13.02 — Hardware-Rooted Identity

    Human identity MUST anchor to hardware:

    • Keyra Key or device secure enclave generates root key material
    • Software-only root keys permitted only for sandbox/development with reduced trust level
    • TPM attestation for enterprise and government deployments

    Section 13.03 — Companion Trust

    Companion binaries MUST be signed and verified. Companion configuration integrity protected by vault partition. Tampered Companion MUST fail closed — no vault access.

    Section 13.04 — Vault Encryption

    See Part IX. Additional requirements:

    • HSM integration for institutional key ceremonies
    • Key rotation without plaintext exposure
    • Secure deletion verification for erased blobs

    Section 13.05 — Authorization Certificates

    X.509 or W3C Verifiable Credentials format for grants. Certificate fields MUST include: sovereign_human_id, grantee_id, scope manifest hash, valid_from, valid_to, device_binding_ref.

    Section 13.06 — KAAI Certificates

    Agent Identity Certificate and Authorization Certificate chains per KAAI Standard. OCSP-style revocation checking with mesh-local cache and federation fallback.

    Section 13.07 — Post-Quantum Readiness

    Implementations SHOULD implement hybrid cryptography:

    | Use case | Classical | Post-quantum supplement |

    |----------|-----------|-------------------------|

    | Key exchange | X25519 | ML-KEM-768 |

    | Signatures | Ed25519 | ML-DSA-65 (when standardized deployment) |

    | Vault wrapping | AES-256-GCM | Unchanged symmetric |

    Migration plan MUST support dual-stack verification during transition.

    Section 13.08 — Threat Model Summary

    | Threat | Mitigation |

    |--------|------------|

    | Stolen cloud credentials | No root keys in cloud; scoped tokens |

    | Compromised agent | Sandbox, scope limits, revocation SLA |

    | Insider platform admin | Audit, hash chains, human inspectability |

    | Federation bridge attack | mTLS, bridge attestation, anomaly detection |

    | Prompt injection | KAAI scope gate, human confirmation |

    | Device theft | Biometric, Keyra Key, remote revocation |

    Section 13.09 — Security Operations

    • 24/7 SOC for institutional deployments
    • Incident response playbooks linked to trust score suspension
    • Bug bounty for KAAI Runtime and vault crypto
    • Annual third-party penetration test for reference implementation

    Section 13.10 — Scenario 13 — Post-Quantum Migration

    Organization enables hybrid PQ TLS on federation gateway. Legacy clients negotiate classical-only during grace period. Vault export packs include algorithm agility metadata. Human inspects migration status in trust.keyra.ie security dashboard.


    PART XIV — Marketplace Architecture

    Section 14.01 — Marketplace Service Components

    | Component | Responsibility |

    |-----------|----------------|

    | Catalog Service | Agent listings, search, discovery |

    | Publisher Service | Developer accounts, manifest validation |

    | Certification Service | Level assignment, audit workflows |

    | Billing Service | Subscriptions, usage metering |

    | Governance Service | Complaints, suspensions, appeals |

    Section 14.02 — Agent Publishing Pipeline

  • Developer registers on developers.keyra.ie
  • Submit agent manifest + artifacts
  • Automated security scan (sandbox execution)
  • Certification review per requested level
  • Listing published to market.keyra.ie with trust metadata
  • Experimental agents MUST display prominent risk warnings.

    Section 14.03 — Discovery Architecture

    Search indexes: name, category, certification level, trust score, scope types, publisher reputation. Ranking MAY use relevance but MUST NOT use undisclosed engagement metrics as trust proxy per Global Trust Economy.

    Filters MUST include: certification level minimum, scope type, family-safe, enterprise-certified.

    Section 14.04 — Certification Integration

    Certification levels gate discovery and execution:

    | Level | Typical use |

    |-------|-------------|

    | Experimental | Sandbox, limited scopes |

    | Verified | General consumer agents |

    | Trusted | Financial, travel, health-adjacent |

    | Enterprise Certified | Organization fleet |

    | Government Accredited | Citizen services |

    | Critical Infrastructure | Banking, telecom, grid |

    Section 14.05 — Billing Architecture

    Billing models per Companion Marketplace:

    • Subscription (monthly agent access)
    • Usage (per invocation metering)
    • Transaction (percentage of agent-mediated commerce)
    • Revenue share (publisher/platform split)
    • Licensing (enterprise site licenses)

    All charges MUST cite authorization_id linking to human grant for purchase.

    Section 14.06 — Settlement Handoff

    Marketplace Billing Service emits settlement intents to Trust Settlement Service (Part XV). Financial movement MUST NOT finalize without authorization chain validation.

    Section 14.07 — Governance

    Complaint workflow: human reports agent → governance review → trust score impact → possible suspension → publisher appeal with audit trail.

    Section 14.08 — Scenario 14 — Family-Safe Catalog

    Guardian configures family marketplace partition. Catalog API filters to Verified+ certification, excludes financial scope agents, requires guardian approval for installs. Child device Agent Manager shows filtered catalog only.


    PART XV — Trust Settlement Architecture

    Section 15.01 — Settlement Engine Purpose

    Trust Settlement Architecture implements clearing for trust economy transactions per Global Trust Economy and Companion Marketplace — binding financial movement to authorization evidence.

    Section 15.02 — Settlement Types

    The Settlement Engine processes six canonical transaction classes:

    | Transaction class | Description |

    |-------------------|-------------|

    | Trust Transaction | Trust score impact recorded; may include escrow |

    | Authorization Transaction | Grant consumed or metered |

    | Identity Transaction | Verification event attested |

    | Companion Transaction | Mediated operation billing |

    | Agent Transaction | Per-invocation or outcome-based |

    | Cross-Border Transaction | Federation bridge + currency conversion |

    Settlement types map to clearing rails as follows:

    Section 15.03 — Settlement Engine Architecture

    ```

    Transaction Intent → Authorization Validate → Trust Hold Evaluate

    → Escrow (if required) → Rail Execute (bank/telco/internal)

    → Audit Hash → Trust Score Update → Finalize

    ```

    Section 15.04 — Escrow and Hold Windows

    Low trust score or Experimental certification triggers hold windows. Funds or authorization capacity held until trust verification completes or human releases.

    Hold duration formula SHOULD consider: trust score, certification level, transaction amount, cross-border flag.

    Section 15.05 — Bank Rail Integration

    ISO 20022 payment messages MUST carry `authorization_ref` and `trust_transaction_id` in supplementary data fields. Banks verify authorization chain before release for institutional integrations.

    Section 15.06 — Telco Rail Integration

    Telco settlement covers eSIM provisioning, subscriber agent charges, network trust premiums. Subscriber sovereignty preserved — telco does not hold human root.

    Section 15.07 — Cross-Border Settlement

    Federation Gateway routes settlement messages between regional clearing nodes. Currency conversion at bridge with disclosed fees. Jurisdiction accreditation checks before agent settlement across borders.

    Section 15.08 — Reconciliation

    Daily reconciliation: marketplace transactions ↔ settlement records ↔ bank statements. Mismatches trigger governance investigation and trust score review.

    Section 15.09 — Scenario 15 — Escrow Release

    Human purchases Trusted travel agent. Trust score 0.85 — 24-hour hold on first transaction. Hold placed. Agent executes booking. Human confirms satisfaction in Companion. Escrow releases to publisher. Audit chain complete.


    PART XVI — Scalability Architecture

    Section 16.01 — Scale Dimensions

    | Dimension | MVP | V1 | V2 | V3 | 5-year | 10-year |

    |-----------|-----|----|----|----|----|---------|

    | Humans | 10K | 1M | 10M | 100M | 1B | 10B |

    | Agents/human avg | 5 | 20 | 50 | 100 | 200 | 500 |

    | Total agents | 50K | 20M | 500M | 10B | 200B | 5T* |

    *10-year agent count assumes agent-to-human ratio growth; infrastructure uses hierarchical agent registries and regional sharding.

    Section 16.02 — 1M Humans Architecture

    • Single region deployment
    • PostgreSQL primary + read replicas
    • Neo4j single cluster
    • Kafka 3-broker event bus
    • Object store for vault blobs
    • CDN for static web assets

    Section 16.03 — 10M Humans Architecture

    • Multi-AZ within region
    • Sharded PostgreSQL by sovereign_human_id
    • Graph read replicas per AZ
    • Dedicated Authorization Service cluster
    • Edge sync nodes in major metros

    Section 16.04 — 100M Humans Architecture

    • Multi-region active-active
    • Regional sovereign data residency options
    • Federation gateways per region
    • KAAI Runtime pool autoscaling per certification tier
    • Separate observability cluster

    Section 16.05 — 1B Humans Architecture

    • Continental federation hubs
    • Global trust registry read replicas
    • Hierarchical agent registry (publisher → regional → global index)
    • Cold storage tier for vault archives
    • ML-based anomaly detection at scale

    Section 16.06 — 10B Humans Architecture

    • Planetary cell architecture — regional cells autonomous, federated
    • CRDT-based local-first sync dominant over central writes
    • Settlement clearing at regional level with global net settlement
    • Graph query federation — no single global graph store

    Section 16.07 — Agent Scale Strategies

    | Strategy | Application |

    |----------|-------------|

    | Agent registry sharding | By publisher_id hash |

    | Execution pool isolation | Per certification level |

    | Certificate cache | Edge OCSP caches |

    | Batch audit | Aggregate low-risk audit hashes |

    | Agent hibernation | Deactivate unused agents to reduce registry pressure |

    Section 16.08 — Bottleneck Mitigation

    | Bottleneck | Mitigation |

    |------------|------------|

    | Authorization validate | Cache valid grants with TTL; edge validation |

    | Graph traversal | Subgraph materialized views |

    | Vault blob IO | Tiered storage; client-side encryption reduces server load |

    | Marketplace search | Elasticsearch cluster sharded by category |

    | Settlement | Async clearing; sync only for hold decisions |

    Section 16.09 — Scenario 16 — Regional Failover

    Region EU-West fails. DNS routes to EU-Central. Humans continue with local-first vault and graph replicas. Federation Gateway redirects cross-border verification. RPO 15 minutes for async replicas; RTO 60 minutes for regional control plane.

    Section 16.10 — 100 Billion Agents Architecture

    At 100 billion registered agents — approximately two hundred agents per human at 500M active humans, or one hundred agents per human at 1B active humans — the Companion Platform MUST operate as a hierarchical agent civilization rather than a flat registry. One hundred billion agents is not a larger version of one million agents. It is a qualitatively different systems problem: certificate validation throughput, audit hash aggregation, marketplace discovery fan-out, execution sandbox scheduling, and revocation propagation each require dedicated sub-architectures with mathematically bounded hot-path cardinality.

    16.10.1 — Hierarchical Agent Registry Topology

    Implementations MUST deploy a three-tier agent registry:

    | Tier | Scope | Cardinality target | Responsibility |

    |------|-------|-------------------|----------------|

    | L0 — Publisher Registry | Per agent publisher | 10K–1M agents each | Manifest custody, version lineage, publisher liability |

    | L1 — Regional Agent Index | Per continental cell | 1B–10B agents | Sharded discovery, certification cache, trust score materialized views |

    | L2 — Global Agent Directory | Federated read model | 100B logical entries | Cross-region publisher lookup, equivalence mapping, revocation root |

    No single L1 shard MAY hold more than 500M agent records in hot storage. Agents beyond active utilization MUST transition to hibernation state — metadata retained, execution pools deallocated, certificate validation cached at edge with extended TTL subject to revocation subscription.

    16.10.2 — Certificate Validation at 100B Scale

    Authorization validation MUST NOT require full chain traversal to global root on every execution. Implementations SHALL deploy:

  • Edge OCSP/CRL caches — regional, publisher-scoped, with revocation webhook fan-in
  • Grant bloom filters — probabilistic negative lookup for revoked agent IDs with cryptographic false-positive bounds documented
  • Batch revalidation — low-risk agent classes revalidate certificates on schedule, not per invocation
  • Publisher attestation pools — trusted publishers with Critical Infrastructure certification MAY operate regional validation proxies under audit
  • Target: p99 authorization validate latency < 15ms at edge for hibernated and Standard certification agents; < 50ms for Experimental agents requiring live federation check.

    16.10.3 — Execution Pool Architecture

    KAAI Runtime MUST partition execution into isolation domains:

    ```

    ┌─────────────────────────────────────────────────────────────┐

    │ Global Scheduler (publisher + certification aware) │

    ├──────────────┬──────────────┬──────────────┬──────────────┤

    │ Pool A │ Pool B │ Pool C │ Pool D │

    │ Critical Inf │ Enterprise │ Consumer │ Experimental │

    │ Dedicated HW │ Dedicated AZ │ Shared burst │ Sandboxed │

    │ 1M concurrent│ 10M conc. │ 50M conc. │ 5M conc. │

    └──────────────┴──────────────┴──────────────┴──────────────┘

    ```

    Experimental agents MUST NOT share execution nodes with Critical Infrastructure agents. Scheduler MUST enforce per-human concurrent agent cap configurable by life domain policy — default 50 simultaneous executions, enterprise override with audit.

    16.10.4 — Audit Aggregation at Civilization Scale

    Writing 100B individual audit records per day to hot vault partitions is prohibitive. Implementations MUST implement tiered audit architecture:

    | Risk class | Audit granularity | Storage tier | Retention |

    |------------|-------------------|--------------|-----------|

    | Critical (financial, health, legal) | Per-operation hash chain | Hot vault partition | 7 years minimum |

    | Standard (commerce, communication) | Per-session Merkle root | Warm partition | 3 years |

    | Low (read-only projections) | Hourly aggregate hash | Cold archive | 1 year |

    Aggregate hashes MUST remain human-inspectable — any human MAY request drill-down to constituent operations within policy latency SLA (default 72 hours for cold tier retrieval).

    16.10.5 — Marketplace Discovery at 100B

    Elasticsearch-style flat search across 100B agents fails. Discovery MUST use:

  • Category-first routing — domain taxonomy (health, finance, family, government) shards discovery independently
  • Trust-gated pruning — agents below human-configured trust floor excluded before ranking
  • Publisher reputation pre-filter — L0 registry trust score eliminates bottom quartile before query
  • Federated catalog mirrors — national overlays maintain sovereign catalog replicas; global index is union, not master
  • 16.10.6 — Revocation at 100B

    Revocation propagation SLA tiers at civilization scale:

    | Scope | Target SLA | Mechanism |

    |-------|------------|-----------|

    | Single agent | 60 seconds global | Push revocation event + OCSP invalidate |

    | Publisher suspension | 5 minutes | L0 registry freeze + L1 index purge |

    | Certification downgrade | 15 minutes | Graduated execution pool migration |

    | Human estate revocation | Immediate local; 5 min federated | Device mesh + federation bridge |

    16.10.7 — Economic and Settlement Implications

    100B agents imply trillions of micro-transactions daily. Settlement MUST operate as regional net clearing with async global reconciliation — synchronous settlement reserved for hold decisions and escrow release. Banks and telcos participate as settlement cell anchors per region, not as global choke points.

    16.10.8 — Scenario 16.10 — Publisher Fleet at Scale

    Publisher "HealthAssist Global" registers 50M agents across 40 countries. L0 registry shards by agent product line. L1 indices in EU, Americas, APAC each hold 15–20M entries. A human in Ireland discovers agents via EU L1 with trust floor 0.7; Experimental agents excluded. Human authorizes agent; edge cache validates certificate in 8ms. Agent executes in Enterprise pool. Audit Merkle root written hourly; financial operation within session produces individual hash-chained record in hot partition. Publisher later suspended — L0 freeze propagates in 4 minutes; human inspects revocation in Authorization Center.


    PART XVII — Observability

    Section 17.01 — Observability Philosophy

    Observability in the Companion Platform is not operational convenience divorced from human sovereignty. Every metric, log, trace, and audit event MUST be evaluated against inspectability, non-capture, and grant fidelity. Platform operators observe infrastructure health; humans observe their authorization graphs, agent behavior, trust scores, and vault evidence. Institutional observability MUST NOT substitute surveillance for human inspectability.

    Implementations MUST distinguish four observability planes:

    | Plane | Audience | Purpose | Sovereignty constraint |

    |-------|----------|---------|------------------------|

    | Operational | Platform SRE, infra teams | Uptime, latency, capacity | Aggregated; no human PII in hot paths |

    | Security | SOC, incident response | Threat detection, anomaly | Scoped tokens; audit every access |

    | Human-inspectable | Sovereign human, guardians | Grants, agents, vault evidence | Human root authority; exportable |

    | Institutional | Enterprise, government, bank | Compliance, settlement attestation | Overlay subordinate to human root |

    Section 17.02 — Metrics Architecture

    17.02.1 — Platform Metrics

    Platform metrics MUST use OpenTelemetry as the canonical instrumentation layer. All services emit:

    • RED metrics — Rate, Errors, Duration per API endpoint
    • USE metrics — Utilization, Saturation, Errors for infrastructure resources
    • SLO burn rates — Multi-window alerting for authorization validate, vault read, agent execute, settlement finalize

    Metric labels MUST NOT include sovereign_human_id, vault partition contents, or grant scope details in plaintext. Human-correlated metrics REQUIRE pseudonymous correlation IDs rotatable per session with human visibility in observability.keyra.ie.

    17.02.2 — Trust Metrics

    Trust metrics integrate with Global Trust Economy indices:

    | Metric | Formula space | Collection |

    |--------|---------------|------------|

    | Authorization fidelity rate | Valid grants / validation attempts | Authorization Service |

    | Revocation propagation lag | p50/p99 seconds by scope tier | Federation Gateway |

    | Agent trust score distribution | Histogram by certification level | Trust Service |

    | Settlement attestation rate | Receipts with valid grant chain / total | Settlement Service |

    | Device presence verification rate | Successful attestations / required gates | Device Trust Mesh |

    17.02.3 — Companion Metrics

    Companion Service MUST emit:

    • Mediation latency (human request → policy decision → orchestration dispatch)
    • Duty-of-care intervention rate (companion blocked or escalated operations)
    • Family approval workflow completion time
    • Offline-capable operation success rate

    Companion metrics visible to humans in dashboard MUST map to plain language explanations, not raw Prometheus names.

    Section 17.03 — Logging Architecture

    17.03.1 — Structured Logging Standard

    All services MUST emit JSON structured logs with mandatory fields:

    ```

    timestamp, service, trace_id, span_id, severity, event_type,

    correlation_id, sovereign_human_id_hash (optional), outcome

    ```

    `s sovereign_human_id` MUST be hashed with per-deployment salt unless log partition is human-owned vault evidence.

    17.03.2 — Log Tiering

    | Tier | Content | Retention | Access |

    |------|---------|-----------|--------|

    | L0 — Operational | Infra, errors, latency | 30 days | Platform ops |

    | L1 — Security | Auth failures, anomaly signals | 1 year | SOC + audit |

    | L2 — Evidence | Grant operations, settlements, revocations | 7+ years | Human vault + institutional overlay |

    | L3 — Debug | Verbose traces | 7 days | Ephemeral; disabled in production default |

    L2 evidence logs MUST hash-chain to Trust Vault audit partitions per Trust Vault Architecture.

    17.03.3 — Prohibited Logging

    Implementations MUST NOT log: vault decryption keys, grant plaintext beyond scope manifest hash, biometric templates, child graph contents without family partition encryption, or model prompts containing unredacted PII unless human explicitly enables debug vault partition.

    Section 17.04 — Distributed Tracing

    Distributed tracing MUST propagate W3C Trace Context across all service boundaries including federation bridges and KAAI Runtime sandboxes.

    Trace spans MUST include:

    • `companion.mediation` — Companion orchestration steps
    • `authorization.validate` — Certificate chain validation
    • `agent.execute` — Sandbox execution with certification level tag
    • `vault.operation` — Partition and operation type (never blob content)
    • `settlement.finalize` — Clearing cell and receipt hash

    Tracing backends SHOULD deploy per-region collectors with 24-hour hot retention and sampled long-term storage. Humans MAY request trace export for their correlation IDs via observability.keyra.ie — traces containing other humans' data MUST be redacted.

    Section 17.05 — Audit Observability

    Audit is observability with legal and constitutional weight. Audit observability requirements:

  • Every consequential operation produces audit event before response commit (write-ahead audit)
  • Audit events are immutable append-only with hash chain per sovereign human estate
  • Humans inspect audit via Memory Explorer and Authorization Center
  • Institutional overlays receive evidence pointers, not raw audit stream subscription
  • Cross-border audit federation uses TEEP-compatible evidence packs
  • Audit query APIs MUST support temporal range, agent ID, grant ID, and outcome filters with pagination bounded to prevent enumeration attacks.

    Section 17.06 — Trust Analytics

    Trust Analytics Service aggregates authorization-correct behavioral signals:

    | Signal | Use | Prohibited use |

    |--------|-----|----------------|

    | Grant renewal rate | Agent reliability hint | Attention optimization |

    | Revocation frequency | Risk scoring input | Punitive shadow banning |

    | Settlement dispute rate | Publisher trust adjustment | Undisclosed price discrimination |

    | Certification audit pass rate | Marketplace ranking factor | Pay-to-rank without disclosure |

    | Federation bridge error rate | Infrastructure health | Jurisdictional profiling |

    Trust analytics MUST NOT use engagement time, scroll depth, or dark-pattern conversion as trust inputs.

    Section 17.07 — Companion Analytics

    Companion Analytics measures mediation quality for human benefit:

    • Task completion rate (human-initiated goals)
    • Policy explanation clarity scores (human feedback)
    • Escalation appropriateness (false positive/negative on duty-of-care)
    • Cross-domain orchestration success (multi-service workflows)

    Companion Analytics data belongs to the human vault memory partition by default. Enterprise overlays MAY receive aggregated team metrics with member consent per Organization Graph Framework.

    Section 17.08 — Agent Analytics

    Agent Analytics operates at publisher and human-authorized scopes:

    Publisher-visible (aggregated): execution count, error rate, average trust score, certification status, settlement volume.

    Human-visible: per-agent grant history, execution log, trust score trend, revocation events, cost attribution.

    Platform-visible: certification tier pool utilization, sandbox escape attempts, anomalous scope escalation patterns.

    Agent Analytics MUST NOT expose one human's agent usage patterns to publishers without explicit grant.

    Section 17.09 — Observability Stack Reference

    | Component | Technology class | Deployment |

    |-----------|----------------|------------|

    | Metrics | Prometheus / Grafana or cloud-native equivalent | Per-region |

    | Logs | Loki / OpenSearch with encryption | Per-region + vault L2 |

    | Traces | Jaeger / Tempo | Per-region collectors |

    | Dashboards | Grafana + human-facing observability.keyra.ie | Federated |

    | Alerting | PagerDuty / Opsgenie with runbook links | 24/7 institutional |

    | SLO tracking | Sloth / custom burn-rate alerts | Global config, regional data |

    Sovereign and government deployments MAY substitute approved national equivalents with conformance documentation.

    Section 17.10 — Scenario 17 — Human Inspects Agent Anomaly

    Human notices unfamiliar agent activity. Opens Authorization Center → Agent Analytics for agent ID. Views execution timeline with trace correlation. Companion explains mediation decision in plain language. Human revokes grant; observability records revocation span with 42-second federation propagation. Audit hash appended to vault evidence partition. Human exports audit slice as TEEP evidence pack for bank dispute.


    PART XVIII — Deployment Architecture

    Section 18.01 — Deployment Model Overview

    The Companion Platform MUST support eight deployment archetypes without architectural fork — configuration, sovereignty overlays, and infrastructure scale differentiate deployments; core service contracts remain identical.

    ```

    ┌────────────────────────────────────────────────────────────────┐

    │ DEPLOYMENT ARCHETYPE SELECTOR │

    ├──────────┬──────────┬──────────┬──────────┬──────────┬────────┤

    │ Consumer │ Family │ Enterprise│ Banking │ Telecom │ Government│

    ├──────────┴──────────┴──────────┴──────────┴──────────┴────────┤

    │ Sovereign (national cell) │ Global (federated multi-cell) │

    └────────────────────────────────────────────────────────────────┘

    ```

    Section 18.02 — Consumer Deployment

    Target: Individual humans and households on shared multi-tenant cloud.

    | Attribute | Specification |

    |-----------|---------------|

    | Scale | 10K–100M humans |

    | Tenancy | Logical isolation by sovereign_human_id |

    | Data residency | Regional default; human-selectable where offered |

    | Key custody | Device-first; optional cloud-assisted sync |

    | Services | Full stack; KAAI pools shared by certification tier |

    | Endpoints | app.keyra.ie, vault.keyra.ie, market.keyra.ie |

    Consumer deployment MUST preserve local-first vault on mobile devices. Cloud is derived replica, not authority.

    Section 18.03 — Family Deployment

    Target: Family Trust Network partitions with guardian structures and child-safe overlays.

    | Attribute | Specification |

    |-----------|---------------|

    | Scale | 2–12 members per family unit; millions of families |

    | Partition | Family graph + family vault overlay on member human roots |

    | Policy | Guardian approval workflows; child-safe agent catalog filter |

    | Deployment | Extends consumer with Family Service cluster |

    | Federation | Cross-border family continuity via Family Trust Network bridges |

    Family deployment MUST NOT merge child human root into parent root. Guardians operate overlays, not substitution.

    Section 18.04 — Enterprise Deployment

    Target: Organizations per Organization Graph Enterprise Companion Framework.

    | Attribute | Specification |

    |-----------|---------------|

    | Scale | 100–500K employees per org; thousands of orgs |

    | Tenancy | Dedicated org overlay + shared platform services |

    | Options | VPC peering, dedicated KAAI pools, HSM integration |

    | Identity | SSO federation subordinate to member human roots |

    | Compliance | SOC2, ISO27001, industry-specific partitions |

    | Endpoints | org.keyra.ie, enterprise companion policies |

    Enterprise deployment MUST preserve member human sovereignty — org revocation of enterprise agent does not revoke personal grants.

    Section 18.05 — Banking Deployment

    Target: Banks as settlement and attestation participants.

    | Attribute | Specification |

    |-----------|---------------|

    | Integration | Settlement rail, authorization chain validation API |

    | Deployment | Bank-operated verification nodes + platform settlement bus |

    | Requirements | PCI-DSS adjacent controls; hash-chained settlement receipts |

    | Trust | Bank validates grant chain before fund movement |

    | Audit | Trust Operation Receipt per Global Trust Economy |

    Banks MUST NOT custody human vault keys. Banks verify authorization evidence, not identity silos.

    Section 18.06 — Telecom Deployment

    Target: Mobile network operators as device trust and subscriber overlay facilitators.

    | Attribute | Specification |

    |-----------|---------------|

    | Integration | eSIM provisioning, subscriber trust overlay, device binding |

    | Deployment | Telco edge nodes for Device Trust Mesh sync |

    | Requirements | GSMA-aligned eSIM; subscriber consent for overlay |

    | Trust | Telco attests device presence; does not own human grants |

    | Use cases | SIM-swap detection, roaming trust continuity |

    Telco deployment MUST treat subscriber as sovereign human, not account inventory.

    Section 18.07 — Government Deployment

    Target: National digital services, accreditation, lawful channels.

    | Attribute | Specification |

    |-----------|---------------|

    | Scale | National population |

    | Deployment | Sovereign cloud or on-premise national cell |

    | Requirements | Constitutional subordination statement published |

    | Accreditation | Government agent certification overlay |

    | Lawful access | Documented channels with human notification where law permits |

    | Federation | National Trust Network bridge to regional/global |

    Government deployment MUST NOT establish national root over human vault. National layer is accredited overlay.

    Section 18.08 — Sovereign Deployment

    Target: Nation-state or regulated industry requiring full data and operational sovereignty.

    | Attribute | Specification |

    |-----------|---------------|

    | Isolation | Air-gapped option; no mandatory foreign control plane |

    | Stack | Full Companion Platform cell within jurisdiction |

    | Keys | National HSM; export ceremonies under national law |

    | Federation | Selective bridges with equivalence mapping |

    | Updates | Sovereign patch cadence with security advisory feed |

    Sovereign cells MUST interoperate via federation gateways — sovereignty is not silo.

    Section 18.09 — Global Deployment

    Target: Planetary federation of regional and sovereign cells.

    | Attribute | Specification |

    |-----------|---------------|

    | Topology | Continental hubs + sovereign cells + consumer cloud |

    | Registry | Hierarchical agent registry (Part XVI, Section 16.10) |

    | Settlement | Regional net clearing + global reconciliation |

    | Trust | Global Trust Registry read replicas; human root unchanged |

    | DNS | Geo-routed with health-aware failover |

    Global deployment is federation of sovereign humans, not global platform capture.

    Section 18.10 — Deployment Reference Topology

    ```

    ┌─────────────────────┐

    │ Global Trust Hub │

    │ (read replicas) │

    └──────────┬──────────┘

    ┌───────────────────┼───────────────────┐

    ▼ ▼ ▼

    ┌─────────────┐ ┌─────────────┐ ┌─────────────┐

    │ EU Cell │ │ Americas │ │ APAC Cell │

    │ Sovereign + │ │ Cell │ │ Sovereign + │

    │ Enterprise │ │ │ │ Enterprise │

    └──────┬──────┘ └──────┬──────┘ └──────┬──────┘

    │ │ │

    ┌──────┴──────┐ ┌──────┴──────┐ ┌──────┴──────┐

    │ Bank/Telco │ │ Bank/Telco │ │ Bank/Telco │

    │ Edge Nodes │ │ Edge Nodes │ │ Edge Nodes │

    └─────────────┘ └─────────────┘ └─────────────┘

    ```

    Section 18.11 — Scenario 18 — Multi-Archetype Enterprise

    Multinational bank deploys Banking nodes in EU and US. Enterprise companion for 80K employees federates SSO. Employees retain personal human roots; enterprise agents operate on org overlay. Settlement validates authorization chains before wire transfer. Government accreditation overlay in each jurisdiction publishes equivalence mapping. Family members of employees use consumer deployment — enterprise does not subsume family partitions.


    PART XIX — Disaster Recovery

    Section 19.01 — Disaster Recovery Philosophy

    Disaster recovery in the Companion Platform prioritizes human continuity over platform convenience. A human who loses cloud access MUST retain vault, grants, and revocation capability on device. DR plans MUST assume malicious recovery — attackers triggering failover — and enforce human inspectability during recovery ceremonies.

    DR objectives by class:

    | Class | RPO | RTO | Human impact |

    |-------|-----|-----|--------------|

    | Regional platform failure | 15 min | 60 min | Degraded sync; local-first continues |

    | Availability zone failure | 5 min | 15 min | Automatic failover |

    | Vault service corruption | 0 (device authority) | 4 hours | Restore from device export |

    | Identity compromise | 0 | Immediate | Human revocation + device re-enrollment |

    | Family partition loss | 1 hour | 8 hours | Guardian-coordinated recovery |

    | Organization overlay loss | 15 min | 2 hours | Member human roots unaffected |

    Section 19.02 — Companion Recovery

    Companion Service recovery procedures:

  • Stateless companion pods — rebuild from container images; no grant authority in companion memory
  • Policy cache rebuild — warm from Authorization Service; never authoritative
  • Mediation queue — durable Kafka retention 7 days; replay on recovery
  • Human-facing continuity — Flutter app operates offline for inspect, revoke, low-risk ops
  • Recovery validation — synthetic human journey test before traffic restoration
  • Companion recovery MUST NOT restore stale grants — Authorization Service is revalidation gate post-recovery.

    Section 19.03 — Twin Recovery

    Digital Twin recovery respects projection boundedness:

    | Twin projection | Recovery source | Conflict rule |

    |-----------------|-----------------|---------------|

    | Identity | Identity vault + graph | Human-directed merge |

    | Preference | Local device + vault | Latest human-confirmed |

    | Goal | Graph temporal | Human override wins |

    | Context | Ephemeral + vault snapshot | Discard stale context |

    | Memory | Memory vault partition | Hash-chain integrity required |

    Twin Service recovery MUST run integrity verification against vault evidence before serving projections to agents.

    Section 19.04 — Vault Recovery

    Vault recovery hierarchy:

  • Primary authority: human device — local encrypted store is root
  • Secondary: regional vault replicas — encrypted blobs; no platform key custody
  • Tertiary: cold archive — export ceremony packs, legacy partitions
  • Vault corruption response:

    • Detect via hash-chain break alert
    • Freeze affected partition writes
    • Human notification via Companion + Device Mesh
    • Recovery from device export ceremony or prior TEEP pack
    • Post-recovery re-encryption if key compromise suspected

    Platform operators MUST NOT possess keys to decrypt human vault for DR purposes.

    Section 19.05 — Identity Recovery

    Identity recovery distinguishes account recovery from sovereignty recovery:

    | Scenario | Procedure | Security |

    |----------|-----------|----------|

    | Lost device | Remaining mesh devices + Keyra Key | Multi-device quorum |

    | Lost all devices | Guardian/successor ceremony + identity proof | Time-delayed re-enrollment |

    | Compromised keys | Immediate revocation cascade | All grants suspended pending human |

    | Death/succession | Legacy vault ceremony | Successor grant per human directive |

    Identity recovery MUST NOT bypass human root — institutional recovery channels require published lawful process with audit.

    Section 19.06 — Family Recovery

    Family partition recovery coordinates guardians:

  • Detect family graph or vault partition unavailability
  • Notify guardians via out-of-band channels (device push, verified email/SMS per policy)
  • Guardian quorum approves recovery source (member device export, backup)
  • Child-safe scopes re-validated before child agent reactivation
  • Audit chain records recovery ceremony with guardian signatures
  • Family recovery MUST preserve minor human root — guardians restore access, not ownership.

    Section 19.07 — Organization Recovery

    Organization overlay recovery:

    | Component | RTO | Procedure |

    |-----------|-----|-----------|

    | Org graph | 2 hours | Restore from geo-replicated backup |

    | Enterprise agents | 4 hours | Rebind to org overlay; member grants unchanged |

    | Compliance partitions | 8 hours | Evidence pack validation |

    | SSO federation | 1 hour | IdP failover per enterprise DR plan |

    Member human roots, personal vaults, and personal agents MUST remain operational during org overlay recovery.

    Section 19.08 — Cross-Entity DR Orchestration

    DR Orchestration Service coordinates multi-entity recovery:

    ```

    Trigger → Assess scope → Notify humans → Isolate blast radius

    → Restore authoritative sources (device > vault > replica)

    → Revalidate authorization → Synthetic validation → Restore traffic

    ```

    Orchestration MUST produce DR Operation Receipt hash-chained to institutional audit with human-visible summary.

    Section 19.09 — DR Testing Requirements

    | Test type | Frequency | Scope |

    |-----------|-----------|-------|

    | Tabletop | Quarterly | All entity types |

    | Regional failover | Semi-annual | Production traffic subset |

    | Vault restore from device | Annual | Per deployment archetype |

    | Identity compromise simulation | Annual | Red team |

    | Family guardian recovery | Annual | Family deployment |

    | Federation bridge failover | Semi-annual | Cross-border cells |

    DR test results MUST publish to institutional compliance dashboards with remediation tracking.

    Section 19.10 — Scenario 19 — Vault Region Loss

    Vault blob storage region US-East unavailable. Humans continue read/write on devices. Companion displays sync degraded banner. DR orchestration promotes US-Central replica for blob fetch only — writes queue locally. Authorization Service validates from replicated grant store. Within 45 minutes, US-Central assumes blob serving. Human inspects DR receipt. No grant expansion occurred. Export ceremony available throughout from local device.


    PART XX — Reference Implementation

    Section 20.01 — Implementation Philosophy

    The Reference Implementation translates this architecture into deployable software without capturing human sovereignty. Reference Implementation code is exemplar, not exclusive — conformant implementations MAY use alternate technologies if service contracts, constitutional invariants, and audit semantics match.

    Implementation phases:

    | Phase | Codename | Humans | Focus |

    |-------|----------|--------|-------|

    | MVP | Genesis | 10K | Core loop: identity, companion, vault, one agent |

    | V1 | Foundation | 1M | Family, marketplace, KAAI runtime, device mesh |

    | V2 | Federation | 10M | Multi-region, enterprise, settlement rails |

    | V3 | Civilization | 100M+ | Global trust, 100B agents, sovereign cells |

    | 5-Year | Horizon | 1B | Planetary cells, regional clearing |

    | 10-Year | Epoch | 10B | CRDT-dominant, net settlement civilization |

    Section 20.02 — MVP Reference Implementation

    Timeline: Months 0–12

    Target: 10K pilot humans

    20.02.1 — MVP Scope

    | Layer | Deliverable |

    |-------|-------------|

    | Presentation | Web (Next.js) + Flutter iOS/Android shell |

    | Companion | Mediation service, chat orchestration, policy engine v1 |

    | Agent | KAAI Runtime sandbox, 5 pilot agents |

    | Twin | Identity + preference projections |

    | Graph | Life graph core schema, Neo4j single instance |

    | Vault | Local encrypted store + cloud blob sync |

    | Trust | Trust score v1, experimental certification only |

    | Authorization | Grant ceremony, certificate issue, revocation |

    | Infrastructure | Single region AWS/GCP, PostgreSQL, Kafka |

    20.02.2 — MVP Exclusions

    MVP explicitly excludes: enterprise SSO, banking settlement, government accreditation, federation bridges, marketplace payments, family guardian quorum, post-quantum hybrid.

    20.02.3 — MVP Success Criteria

    • Human completes enroll → grant → agent execute → inspect audit → revoke loop
    • Offline vault read and revocation initiation on Flutter
    • Export ceremony produces portable pack
    • p99 API latency < 500ms at 10K humans

    Section 20.03 — V1 Reference Implementation

    Timeline: Months 12–24

    Target: 1M humans

    20.03.1 — V1 Additions

    • Family Trust Network partitions and guardian approval
    • Companion Marketplace catalog, publisher onboarding, billing v1
    • Device Trust Mesh multi-device sync
    • KAAI certification levels through Standard
    • Authorization Center web module
    • Memory Explorer and Life Graph Explorer
    • Multi-AZ deployment, read replicas
    • Observability stack (Part XVII) production

    20.03.2 — V1 Architecture Changes

    • Sharded PostgreSQL by sovereign_human_id
    • Dedicated Authorization Service cluster
    • Elasticsearch for marketplace discovery
    • Edge sync nodes in 5 metro areas

    Section 20.04 — V2 Reference Implementation

    Timeline: Months 24–42

    Target: 10M humans

    20.04.1 — V2 Additions

    • Organization Graph enterprise overlays
    • Settlement Service with bank rail integration (pilot banks)
    • Telco eSIM device binding (pilot telcos)
    • Multi-region active-active (3 regions)
    • Federation gateway v1 (EU-US bridge)
    • KAAI Enterprise and Critical Infrastructure pools
    • Trust settlement with escrow
    • Government accreditation pilot (1 nation)

    20.04.2 — V2 Scale Targets

    • 500M registered agents
    • p99 authorization validate < 50ms
    • Regional RPO 15 min, RTO 60 min

    Section 20.05 — V3 Reference Implementation

    Timeline: Months 42–60

    Target: 100M humans

    20.05.1 — V3 Additions

    • Hierarchical agent registry (100B-ready architecture)
    • Global Trust Registry integration
    • Sovereign cell deployment template
    • Cross-border TEEP federation
    • Post-quantum hybrid TLS option
    • ML anomaly detection for trust analytics
    • CRDT local-first sync for graph projections
    • Continental federation hubs

    20.05.2 — V3 Scale Targets

    • 10B registered agents
    • 6+ sovereign national cells
    • 50+ bank/telco settlement participants

    Section 20.06 — Five-Year Roadmap

    Horizon phase: Years 3–5

    Target: 1B humans addressable; 200B agents

    | Year | Milestone |

    |------|-----------|

    | 3 | Planetary cell architecture production; 10 regions |

    | 3.5 | Regional net settlement clearing live |

    | 4 | 100B agent registry hierarchical index |

    | 4.5 | Government sovereign cells in 20 nations |

    | 5 | CRDT-dominant sync for 50% of graph mutations |

    | 5 | Global trust index methodology v2 published |

    Five-year roadmap MUST maintain backward compatibility for vault export and grant portability across all prior versions.

    Section 20.07 — Ten-Year Roadmap

    Epoch phase: Years 5–10

    Target: 10B humans addressable; 5T agent transactions annually

    | Year | Milestone |

    |------|-----------|

    | 6 | Graph query federation — no global graph store |

    | 7 | Agent hibernation at scale; 80% agents dormant |

    | 8 | Post-quantum mandatory for Critical Infrastructure |

    | 8.5 | Interplanetary latency-tolerant sync research production |

    | 9 | Autonomous sovereign cell self-healing |

    | 10 | Civilization-scale audit aggregation default |

    | 10 | Human sovereignty charter embedded in ISO reference |

    Ten-year roadmap assumes continuous constitutional subordination — technical evolution MUST NOT erode human root authority.

    Section 20.08 — Technology Stack Reference

    | Concern | MVP | V1+ Reference |

    |---------|-----|---------------|

    | Web | Next.js, TypeScript | Next.js App Router |

    | Mobile | Flutter 3.x | Flutter + platform channels |

    | API | REST + GraphQL | REST + GraphQL + gRPC internal |

    | Events | Kafka | Kafka / Pulsar |

    | Graph | Neo4j | Neo4j clustered / federated query |

    | SQL | PostgreSQL 16 | Sharded PostgreSQL |

    | Vault blobs | S3-compatible | Tiered S3 + glacier |

    | Search | — | Elasticsearch |

    | KAAI Runtime | Container sandbox | gVisor/Firecracker isolation |

    | Observability | Basic | OpenTelemetry full stack |

    Implementations MAY substitute equivalents with conformance documentation.

    Section 20.09 — Team and Operating Model

    | Function | MVP headcount | V3 headcount |

    |----------|---------------|--------------|

    | Platform engineering | 8 | 80 |

    | Security / crypto | 3 | 25 |

    | Companion / AI | 5 | 40 |

    | Mobile / web | 6 | 35 |

    | SRE / infra | 4 | 50 |

    | Compliance / governance | 2 | 20 |

    Reference Implementation teams MUST include human sovereignty reviewer on architecture decisions.

    Section 20.10 — Scenario 20 — MVP to V1 Migration

    Pilot cohort of 8K MVP humans upgrades to V1. Migration executes: schema migration on PostgreSQL shards, vault re-encryption ceremony (optional), device mesh enrollment prompt, family partition offer for households. Zero grant loss; audit chain continuous. Rollback available for 30 days via export ceremony. Migration receipt published to each human vault.


    Closing Declaration

    On Architecture and Sovereignty

    We declare that architecture follows sovereignty — not as slogan, but as implementable invariant. Every layer, service, schema, and deployment model in this Reference Architecture exists to translate human authority into runtime behavior that courts, families, banks, governments, and future generations can inspect, audit, and trust.

    Engineers who implement bypass paths for operational convenience build constitutional violations. Architects who centralize human keys for DR convenience build capture. Platform teams who optimize engagement over authorization build the old civilization in new clothing.

    On the Companion Platform

    The Companion Platform Reference Architecture is the master implementation blueprint through which twelve founding instruments become deployable reality. It does not replace the Human Sovereignty Charter. It serves it — with layers, APIs, encryption, federation, observability, deployment, disaster recovery, and phased implementation that scale from ten thousand pilot humans to ten billion addressable humans and one hundred billion agents without surrendering the human root.

    On Inspectability at Scale

    Scale is not an excuse for opacity. At one hundred billion agents, humans MUST still inspect their grants, revoke in seconds, export portably, and recover from disaster without platform permission. Observability serves humans first. Audit hash-chains answer to families and courts. Metrics without surveillance are achievable — and mandatory.

    On Deployment Diversity

    Consumer, family, enterprise, banking, telecom, government, sovereign, and global deployments share one architecture with configuration differentiation — not siloed forks that trap humans. A refugee with a single authorized companion and a multinational executive with an enterprise fleet use the same human root semantics. National cells federate; they do not capture.

    On Disaster and Continuity

    Disaster recovery that restores platform before human is failed recovery. Device authority, vault export, guardian ceremonies, and succession plans are not edge cases — they are core architecture. Humans survive regional failures, identity compromise, and mortality's threshold because the architecture was written for continuity under sovereignty.

    On Implementation Phases

    MVP proves the loop. V1 proves family and marketplace. V2 proves federation and settlement. V3 proves civilization scale. Five-year and ten-year roadmaps prove generational thinking — code written today must not imprison humans tomorrow. Export ceremonies and grant portability are migration strategy, not afterthought.

    Acknowledgment of Founding Instruments

    This Reference Architecture stands subordinate to the Human Sovereignty Charter and translates the Companion Charter, Life Operating System, Human Digital Twin Architecture, Life Graph Architecture, Family Trust Network, Organization Graph Enterprise Companion Framework, KAAI Standard, Trust Vault Architecture, Device Trust Mesh, Companion Marketplace & Agent Economy, and Global Trust Economy & Sovereign Network Framework into implementable platform architecture — each instrument necessary, none sufficient alone.

    Perpetual Subordination Clause

    This Reference Architecture may be amended for technical agility — service decomposition, storage engines, observability backends, deployment topologies. It may never be amended to permit platform root over human authority, cloud custody of vault keys, unauditable consequential operations, bypass of companion mediation for high-risk scope, or surveillance analytics substituting human inspectability. Such amendments are void ab initio per the Human Sovereignty Charter.

    Call to Implementers

    To engineers: enforce layer boundaries; reject bypass. To architects: federate without capture; shard without losing human root. To platform teams: measure SLOs AND human revocation latency. To security teams: fail closed; audit everything consequential. To governments and banks: accredit as overlay; verify grant chains. To humans: demand conformance — your sovereignty is not negotiable because scale is hard.

    Glossary of Core Terms

    | Term | Definition |

    |------|------------|

    | Companion Platform | Implementable stack translating founding instruments into services, APIs, and runtimes |

    | Reference Architecture | This document — master blueprint for platform implementation |

    | Sovereign Human | Root grantor of identity, authorization, and audit authority |

    | Layer bypass | Prohibited direct access between non-adjacent architectural layers for consequential operations |

    | Local-first | Authoritative human data replica on human-controlled devices |

    | Trust-first | Trust verification precedes execution, disclosure, and settlement |

    | Companion-first | Companion mediates high-risk operations per Companion Charter |

    | KAAI Runtime | Agent execution environment conforming to KAAI Standard |

    | Device Trust Mesh | Multi-device presence, enrollment, and trust synchronization |

    | Federation Gateway | Cross-cell and cross-border trust bridge with mTLS and equivalence mapping |

    | TEEP | Trust Economy Export Pack — portable trust state export format |

    | Observability plane | Operational, security, human-inspectable, or institutional telemetry scope |

    | Deployment archetype | Consumer, family, enterprise, banking, telecom, government, sovereign, or global configuration |

    | DR Operation Receipt | Hash-chained artifact documenting disaster recovery actions |

    | Agent hibernation | Dormant agent state retaining metadata without execution pool allocation |

    | Planetary cell | Autonomous regional deployment unit federated globally |

    | Constitutional invariant | Requirement that MUST NOT be violated regardless of scale or convenience |

    Conformance Self-Assessment Checklist

    Organizations and implementers MAY use this checklist for Companion Platform Reference Architecture readiness:

  • Human represented as root grantor in identity, authorization, and audit systems
  • Layer boundaries enforced — no consequential bypass (e.g., Presentation to Vault without Authorization)
  • Local-first vault operation with cloud as derived replica
  • KAAI authorization validation before agent execution
  • Device Trust Mesh integration for presence-gated operations
  • Trust Vault hash-chained audit for consequential operations
  • Companion mediation for high-risk scope per Companion Charter
  • Family and organization overlays subordinate to member human roots
  • Observability distinguishes operational and human-inspectable planes
  • Deployment archetype documented with sovereignty constraints
  • Disaster recovery tested with device-authoritative vault recovery
  • Export ceremony operational without vendor gatekeeping
  • Revocation propagation SLA tested quarterly
  • Federation gateway conformance for cross-border deployments
  • Implementation phase mapped with explicit MVP/V1+ scope boundaries
  • Conformance is a journey; partial conformance with documented roadmap is valid if audited and subordinate to human sovereignty.

    Document Maintenance

    Companion Platform Reference Architecture 1.0 is the founding reference blueprint. Technical errata publish quarterly. Minor version (1.x) may add deployment profiles, observability schemas, and scale refinements. Major version (2.0) requires Governance Council supermajority, human rights review, and explicit constitutional subordination reaffirmation. Subordination to the Human Sovereignty Charter is immutable across all versions.

    Amendments MUST include: migration guidance for existing implementations, export ceremony compatibility statement, and impact assessment on human revocation semantics.

    Final Affirmation

    We affirm that every human — infant with a family education agent, elder with healthcare and succession agents, refugee with a single authorized companion, executive with an enterprise fleet, farmer with an agricultural agent — deserves platform architecture that operates under their authority, inspectably, recoverably, and at civilization scale.

    This is not infrastructure for the technical elite. It is the engineering substrate of human dignity in the age of ubiquitous agents, federated nations, and digital life that persists across devices, decades, and borders.

    Architecture follows sovereignty. Human-first. Local-first. Trust-first. Companion-first. The platform serves the human. The human belongs to themselves. Always.


    End of Document

    The Companion Platform Reference Architecture v1.0 — Master Implementation Blueprint of the Keyra Companion Ecosystem