Architecture Reference

How the System Works

Three isolated verticals — V1 procurement, V2 financial kernel, V5 MRO aviation — sharing one PostgreSQL database and connected by a proprietary cross-vertical event bus, with an autonomous AI agent pipeline running entirely inside Supabase.

Section 1

System Overview

V1 · Port 3000
Procurement Backbone
Requisitions + approvals
Purchase Orders (batched)
Goods Receipts
Invoices + 3-way match
Supplier management
AI agent fleet (14)
RFQ / Auctions / Telegram
🗄️
Supabase Postgres
proc_* · tsm_* · mro_*
pgvector · pg_net · RLS
90+ migrations
V2 · Port 3001
Financial Kernel
Treasury (5 compartments)
Buy-side state machine
Liquidity locks
GAAP/IFRS ledger
Marketplace API + API keys
LogiStack webshop
Sovereign dashboard
Cross-Vertical Event Bus
Typed tokens · immutable once emitted · causation-tracked · DB-native fan-out
V5 · Port 3004 · EASA Part-145
MRO Aviation Kernel
Work orders + tasks
Fleet registry (aircraft)
Receiving inspection
Component lifecycle
Life-limited parts (LLP)
Certificate of Release (CRS)
Part acceptance emits a typed token to V1 via the cross-vertical bus → MRO_PARTS_AVAILABLE task event
Section 2

Agent Handoff Network

Core P2P pipeline shown. 14 agents total — additional spawned agents handle RFQ orchestration, competitor price surveillance, pricing optimisation, entity viability monitoring, and SAP IDoc generation.

REQUISITION_SUBMITTEDrequisition-agentvalidates · routesPO_DRAFTpo-agentbatches · issues POPO_CONFIRMEDidoc-architectSAP IDoc XMLINVOICE_MATCHinvoice-matcher3-way match · ERSSETTLEMENTtsm_record_po_settlement() → OPERATING balanceEvents (blue) · Agents (amber) · Treasury (green)
Section 3

Data Flow Table

Event TypeTriggerAgentDB WriteTreasury Effect
REQUISITION_SUBMITTEDRequisition created or webshop OOSrequisition-agentproc_approvals, proc_task_events
PO_DRAFTCatalog requisition approvedpo-agentproc_purchase_orders, proc_po_batch_queuetsm_lock_liquidity()
RFQ_INITIATEOff-catalog requisition approvedrfq-orchestratorproc_rfps, proc_rfp_lines, proc_rfp_invitations
RFQ_EVALUATEHourly deadline checkrfq-orchestratorproc_rfp_responses (award), proc_purchase_orderstsm_lock_liquidity()
PO_CONFIRMEDPO issuedidoc-architectproc_idoc_queue
INVOICE_MATCHInvoice uploaded / OCRinvoice-matcherproc_three_way_matches, proc_payment_advices
Invoice approvedPATCH /api/invoices/[id](API route)proc_invoicestsm_record_po_settlement()
ARCHITECT_ANALYSISWeekly cronarchitect-agentproc_agent_proposals
MARKET_SCOUT_RUNWeekly cronmarket-scouttsm_market_intelligence
PRICE_OPTIMIZE_RUNScheduled triggerprice-optimizertsm_offerings (unit_price)
ENTITY_VIABILITY_CHECKMonthly cronviability-monitortsm_entity_snapshots
MRO_PARTS_AVAILABLEV5 part acceptance → cross-vertical busspawned_agentproc_task_events (work-order notification)
Section 4

State Machine Registry

Every valid state transition is a row in proc_state_machines — a single source of truth for what state changes are allowed. Triggers validate against this table at write time; adding a new valid transition is a single SQL INSERT, no code deploy needed.

136 transitions across 17 entity types — live from DB.

clm_contract15 transitions
FromToTerminalGuard FunctionRequires
activeexpiring_soon
activeterminatedTERMINAL
activerenewedTERMINAL
approvedactive
approvedterminatedTERMINAL
draftreview
draftterminatedTERMINAL
expiredrenewedTERMINAL
expiring_soonactive
expiring_soonexpiredTERMINAL
expiring_soonrenewedTERMINAL
expiring_soonterminatedTERMINAL
reviewapproved
reviewdraft
reviewterminatedTERMINAL
ls_adverse_event8 transitions
FromToTerminalGuard FunctionRequires
escalatedregulatory_notified
escalatedclosedTERMINAL
receivedtriaged
regulatory_notifiedclosedTERMINAL
triagedunder_investigation
triagedregulatory_notified
under_investigationregulatory_notified
under_investigationescalated
ls_clinical_trial10 transitions
FromToTerminalGuard FunctionRequires
activecompleted
activesuspended
activeterminatedTERMINAL
completeddata_lockedTERMINAL
ethics_approvedregulatory_approved
protocol_submittedethics_approved
recruitingactive
regulatory_approvedrecruiting
suspendedactive
suspendedterminatedTERMINAL
ls_document8 transitions
FromToTerminalGuard FunctionRequires
approvedeffective
draftunder_review
effectivesupersededTERMINAL
effectiveretiredTERMINAL
pending_approvalapproved
pending_approvalrejectedTERMINAL
under_reviewpending_approval
under_reviewdraft
ls_document:sop9 transitions
FromToTerminalGuard FunctionRequires
approvedeffective
draftunder_review
effectivesupersededTERMINAL
effectiveretiredTERMINAL
pending_approvalapproved
pending_approvaldraft
rejecteddraft
under_reviewpending_approval
under_reviewdraft
ls_workflow_task16 transitions
FromToTerminalGuard FunctionRequires
ai_draft_readypending_review
ai_draft_readyin_progress
assignedin_progress
assignedcancelledTERMINAL
escalatedin_progress
escalatedcancelledTERMINAL
in_progressai_draft_ready
in_progresspending_review
in_progresspending_signature
in_progressescalated
pendingassigned
pendingin_progress
pendingcancelledTERMINAL
pending_reviewcompletedTERMINAL
pending_reviewin_progress
pending_signaturecompletedTERMINAL
mro_aircraft5 transitions
FromToTerminalGuard FunctionRequires
activemaintenance
activegrounded
groundedactive
groundedderegisteredTERMINAL
maintenanceactive
mro_crs4 transitions
FromToTerminalGuard FunctionRequires
draftpending_review
endorsedarchivedTERMINAL
pending_reviewsigned
signedendorsed
mro_workflow_task5 transitions
FromToTerminalGuard FunctionRequires
assignedin_progress
assigneddeferred
in_progresscompletedTERMINAL
pendingassigned
pendingcancelledTERMINAL
mro_work_order8 transitions
FromToTerminalGuard FunctionRequires
crs_pendingclosedTERMINAL
draftopen
in_progressinspection
in_progresson_hold
inspectioncrs_pending
on_holdin_progress
openin_progress
opencancelledTERMINAL
proc_dispute9 transitions
FromToTerminalGuard FunctionRequires
EVIDENCE_RECEIVEDPARTIAL_RELEASE
EVIDENCE_RECEIVEDRELEASEDTERMINAL
EVIDENCE_RECEIVEDSOVEREIGN_OVERRIDETERMINALsovereign_override_token_hash + reason required
EVIDENCE_REQUESTEDEVIDENCE_RECEIVEDsupplier_document_path must be set
EVIDENCE_REQUESTEDSOVEREIGN_OVERRIDETERMINALsovereign_override_token_hash + reason required
OPENEVIDENCE_REQUESTED
OPENSOVEREIGN_OVERRIDETERMINALsovereign_override_token_hash + reason required
PARTIAL_RELEASERELEASEDTERMINAL
PARTIAL_RELEASESOVEREIGN_OVERRIDETERMINALsovereign_override_token_hash + reason required
tem_dispute6 transitions
FromToTerminalGuard FunctionRequires
carrier_acknowledgedresolved
carrier_acknowledgedescalated
draftedsubmitted
escalatedresolved
resolvedclosedTERMINAL
submittedcarrier_acknowledged
tem_invoice7 transitions
FromToTerminalGuard FunctionRequires
approvedpaidTERMINAL
auditingapproved
auditingdisputed
disputedresolved
extractingauditing
receivedextracting
resolvedapproved
tem_service_line6 transitions
FromToTerminalGuard FunctionRequires
activeflagged_inactive
activesuspended
deprovisioningterminatedTERMINAL
flagged_inactivedeprovisioning
flagged_inactiveactive
suspendedactive
tsm_entity5 transitions
FromToTerminalGuard FunctionRequires
activeunderperforming
activewinding_down
underperformingactive
underperformingwinding_down
winding_downterminalTERMINAL
tsm_order6 transitions
FromToTerminalGuard FunctionRequires
FULFILLMENTREVENUE_RECOGNIZEDtsm_book_revenue
FULFILLMENTCANCELLEDTERMINAL
ORDER_RECEIVEDFULFILLMENT
ORDER_RECEIVEDREVENUE_RECOGNIZEDtsm_book_revenue
ORDER_RECEIVEDCANCELLEDTERMINAL
REVENUE_RECOGNIZEDREFUNDEDTERMINALtsm_refund_order
tsm_transaction9 transitions
FromToTerminalGuard FunctionRequires
COMMITMENTEXECUTION
COMMITMENTABANDONEDTERMINAL
DISPUTEDSETTLEMENTTERMINALtsm_record_po_settlement
EXECUTIONSETTLEMENTTERMINALtsm_record_po_settlement
EXECUTIONDISPUTED
INTENTNEGOTIATION
NEGOTIATIONCOMMITMENTtsm_guard_commitment
NEGOTIATIONABANDONEDTERMINAL
NULL (initial)INTENT
Section 5

Database-Level Invariants

Critical business rules are enforced by PostgreSQL triggers — not application code. Rules are catalogued at 4 levels of progressively broader scope: attribute → tuple → table → database. Business logic lives in the database, not scattered across microservices.

19 constraints catalogued — live from proc_db_constraints.

attribute5 constraints
TableConstraintDescriptionEnforcementReversible
proc_dispute_statesvalid_dispute_typedispute_type must be one of: price_variance, qty_variance, missing_gr, sku_mismatch, multi — set at INSERT and semantically immutableCHECKno
tsm_offeringsunit_price_positiveunit_price must be greater than 0 — prevents zero-price listings that would corrupt revenue accountingCHECKyes
tsm_transactionsvalid_state_enumcurrent_state must be one of: INTENT, NEGOTIATION, COMMITMENT, EXECUTION, SETTLEMENT, DISPUTED, ABANDONEDCHECKyes
tsm_transactionsexception_reason_requiredexception_reason must be set when current_state is DISPUTED or ABANDONED — enforced by CHECK constraintCHECKno
tsm_treasury_accountsbalance_non_negativeTreasury compartment balance cannot go below zero — enforced by tsm_guard_treasury_balance() BEFORE UPDATE trigger and CHECK (balance >= 0) constraintTRIGGERno
tuple4 constraints
TableConstraintDescriptionEnforcementReversible
proc_dispute_statesfinancial_split_integrityundisputed_amount + disputed_amount must equal total_invoice_amount within 1 cent — enforced by proc_dispute_invariants() BEFORE INSERT OR UPDATE trigger (De Brock Ch 3: tuple-level constraint)TRIGGERno
tsm_owner_parameterssingle_current_versionAt most one row can have is_current=true — enforced by partial unique index idx_tsm_params_current; INSERT trigger tsm_rotate_owner_parameters() auto-deactivates previous current versionUNIQUEyes
tsm_transactionscommitment_requires_negotiationTransition to COMMITMENT state requires previous state to be NEGOTIATION — enforced by tsm_guard_commitment() BEFORE UPDATE triggerTRIGGERno
tsm_transactionsapproval_sig_when_approvedowner_approval_sig must be set when owner_approved_at is not null — prevents approval records without cryptographic signatureCHECKyes
table5 constraints
TableConstraintDescriptionEnforcementReversible
proc_dispute_statesforward_only_state_machineDispute states can only advance forward in the transition relation — backward transitions and invalid jumps rejected by proc_dispute_invariants() using proc_state_machines lookup table. De Brock Ch 5: Transition RelationsTRIGGERno
tsm_ledger_eventsimmutable_ledgerDouble-entry GAAP ledger entries cannot be updated or deleted — BEFORE UPDATE/DELETE trigger raises exception. amount_eur is a tamper-evident GENERATED columnTRIGGERno
tsm_order_transitionsimmutable_order_auditOrder state transition rows cannot be updated or deleted — BEFORE UPDATE/DELETE trigger raises exceptionTRIGGERno
tsm_price_changesimmutable_price_historyPricing audit rows cannot be updated or deleted — tsm_log_price_change() AFTER UPDATE trigger writes entries that are immediately locked by BEFORE UPDATE/DELETE triggerTRIGGERno
tsm_state_transitionsimmutable_audit_logState transition rows cannot be updated or deleted — BEFORE UPDATE/DELETE trigger raises exception. 10-year retention enforced by retention_until generated column. De Brock Ch 5: irreversible transitions (Definition 5.2)TRIGGERno
database5 constraints
TableConstraintDescriptionEnforcementReversible
proc_dispute_statesevidence_gated_transitionsEVIDENCE_RECEIVED requires supplier_document_path; SOVEREIGN_OVERRIDE requires token_hash and override_reason; terminal states (RELEASED, SOVEREIGN_OVERRIDE) require resolved_at — all enforced cross-field by proc_dispute_invariants()TRIGGERno
proc_gr_lineswebshop_fulfillment_triggerEvery goods receipt line INSERT fires proc_fulfill_waiting_webshop_orders() which traces GR to PO to req to tsm_order chain, updates proc_inventory.qty_on_hand, sets procurement_status=FULFILLED, and updates tsm_orders.fulfillment_payload atomicallyTRIGGERno
tsm_offeringsprice_floor_enforcementOffering unit_price cannot drop below COGS x (1 + floor_margin) — tsm_validate_price_floor() BEFORE UPDATE trigger reads tsm_pricing_rules cross-table to compute the floor at write timeTRIGGERno
tsm_treasury_accountsliquidity_guardCOMMITMENT transitions require OPERATING balance >= committed_amount + min_reserve_balance — tsm_guard_commitment() checks tsm_available_liquidity() and tsm_owner_parameters cross-table in a single BEFORE UPDATE triggerTRIGGERno
tsm_withdrawal_requestswithdrawal_from_profit_onlyWithdrawal requests must reference the PROFIT treasury compartment only — enforced by CHECK constraint on the account_type FK joinCHECKno
Section 6

Workflow Invariants

Mathematical safety guarantees baked into the database. A place invariant is a conservation law — the weighted sum of tokens across a set of workflow states stays constant regardless of what sequence of operations fires. A transition invariant proves that every work item can reach a terminal state: no business process can get permanently stuck, and no capital is ever created or destroyed.

9 place invariants · 7 transition invariants — live from proc_net_place_invariants + proc_net_transition_invariants. Verified by proc_check_place_invariants().

Live token counts from proc_check_place_invariants() actual_sum = current work in flight across each invariant's places. Expected 0 when system is idle; N > 0 = N active tokens (healthy live system). Negative values or unexpected spikes indicate structural anomalies.

0adverse event lifecycle conservation
3analysis cycle conservation
0capital deployment conservation
0document lifecycle conservation
0entity lifecycle conservation
0invoice lifecycle conservation
0invoice matching single active
0purchase order lifecycle conservation
9requisition lifecycle conservation
🔗
Hash chain integrity: 100% all token movements cryptographically verified
1 chain links verified via proc_check_chain_integrity() · SHA-256 · FDA 21 CFR Part 11 §11.70

Place Invariants — Conservation Laws

InvariantPlaces (weight vector)GuaranteeStatus
adverse event lifecycle conservation
ae_closedae_triagedae_receivedae_escalatedae_regulatory_notifiedae_under_investigation
Conservation law: no adverse event token is created or destroyed outside defined transitions.
0 active
idle
analysis cycle conservation
scout_runningscout_triggeredarchitect_analysingarchitect_triggered
Proves analysis agents do not accumulate in-flight tokens — each analysis cycle completes cleanly.
3 active
work in flight
capital deployment conservation
satellite_capital_deployedsatellite_capital_returned
Spawn debits core PROFIT; close credits core OPERATING. Net capital flow across full lifecycle sums to zero.
0 active
idle
document lifecycle conservation
doc_draftdoc_retireddoc_approveddoc_effectivedoc_supersededdoc_under_reviewdoc_pending_approval
Every document reaches a terminal state (superseded, retired) or stays effective.
0 active
idle
entity lifecycle conservation
entity_activeentity_winding_downentity_underperforming
Counts entities in non-terminal lifecycle states. Zero = idle; N > 0 = N active satellite businesses in operation.
0 active
idle
invoice lifecycle conservation
invoice_matchedinvoice_approvedinvoice_disputedinvoice_receivedinvoice_matching_activeinvoice_payment_scheduled
Proves every invoice reaches either payment or dispute resolution — no invoice is silently abandoned.
0 active
idle
invoice matching single active
invoice_matching_active
Mathematical proof that parallel invoice matching for the same PO is structurally impossible. The capacity=1 constraint and this invariant together guarantee serialisation.
0 active
idle
purchase order lifecycle conservation
po_sentpo_draftingpo_confirmedidoc_generating
Proves every purchase order moves through the defined lifecycle without silent failures.
0 active
idle
requisition lifecycle conservation
requisition_approvedrequisition_rejectedrequisition_screeningrequisition_submittedrequisition_pending_approval
Proves requisitions are neither created nor destroyed outside the defined transition relation. Each requisition has exactly one active token at any point.
9 active
work in flight

Transition Invariants — Complete Cycles

CycleTransitionsPlaces CoveredMinimal
capa completion cycle
Every CAPA action must either complete or be cancelled. No CAPA can be created and never resolved.
capa_cancel_firescapa_create_firescapa_complete_fires
capa_pendingcapa_in_progresscapa_completedcapa_cancelled
yes
market intelligence cycle
Periodic analysis cycle: market scout fires (gathers competitor data) → architect fires (analyses data and writes proposals). Both source-to-sink flows complete independently.
architect_firesmarket_scout_fires
scout_triggeredscout_runningarchitect_triggeredarchitect_analysing
yes
requisition rejection cycle
Cycle covering rejected requisitions: req_screener fires once and routes the token to the rejected sink. No PO is created. This is a valid complete cycle.
req_screener_fires
requisition_submittedrequisition_screeningrequisition_pending_approvalrequisition_rejected
yes
sop must reach terminal or effective
Every SOP draft must eventually reach either effective or a terminal state. No SOP can be permanently stuck in review.
sop_reject_firessop_submit_firessop_approve_fires
doc_draftdoc_under_reviewdoc_pending_approvaldoc_approveddoc_effective
yes
spawn close cycle
Every spawn_business transition must eventually be followed by proc_close_satellite or remain active — no entity stuck in spawning state
spawn_business_firesproc_close_satellite_fires
entity_activeentity_terminal
yes
standard procurement cycle
The canonical happy-path cycle: requisition screened → PO drafted → invoice matched. All three AI-agent transitions fire once per procurement unit. Covers the full procure-to-pay workflow.
po_drafter_firesreq_screener_firesinvoice_matcher_fires
requisition_submittedrequisition_screeningrequisition_approvedpo_draftingpo_sentpo_confirmed+5 more
yes
susar 7day reporting cycle
Every SUSAR must complete: received → triaged → regulatory_notified within 7 calendar days.
ae_triage_firesae_receive_firesae_regulatory_notify_fires
ae_receivedae_triagedae_regulatory_notified
yes
Section 7

Technology Stack

Next.js 16 (×3)
V1 :3000 · V2 :3001 · V5 :3004
Supabase Postgres
PostgreSQL 16 + RLS + pgvector
pgvector
HNSW 1536-dim agent memory
pg_net
Async HTTP from SQL triggers
OpenRouter LLM
claude-opus-4-6 · gemini-flash OCR
Edge Functions (14)
6 deployed · 8 via spawned_agent
Telegram Bot API
Employee requisition channel
SAP ORDERS05
IDoc XML via idoc-architect
Cross-Vertical Bus
Proprietary DB-native event isolation
GitHub Actions CI
Lint · build · pgTAP · smoke tests