Architecture · v2.0

The kernel, end to end.

AIPROCUREMENT.CLUB runs on three isolated vertical instances sharing one PostgreSQL database, connected by a typed event bus. Agents run as Supabase edge functions. Logic lives in PL/pgSQL constraint triggers, not application code.

01

System overview

Three Next.js 16 instances (P2P :3000, Treasury :3001, MRO :3004) plus ClinKernel and Telecom share the same Postgres 16 with row-level security. The cross-vertical event bus is database-native: typed tokens, immutable once emitted, causation-tracked.

:3000
Procure-to-Pay
14 agents
:3001
Treasury & Revenue
9 agents
:3002
ClinKernel
6 agents
:3003
Telecom Expense Management
5 agents
:3004
MRO / Aviation
in development
event bus signature
-- Cross-vertical event bus (extract)
CREATE TABLE events (
  id           UUID PRIMARY KEY,
  event_type   TEXT NOT NULL,        -- e.g. 'po.created'
  emitted_at   TIMESTAMPTZ NOT NULL DEFAULT now(),
  emitted_by   TEXT NOT NULL,        -- agent or actor id
  vertical     TEXT NOT NULL,        -- 'p2p' | 'treasury' | …
  payload      JSONB NOT NULL,
  causation_id UUID REFERENCES events(id),
  correlation  UUID NOT NULL,
  prev_hash    BYTEA NOT NULL,       -- SHA-256 of previous event
  self_hash    BYTEA NOT NULL
);

CREATE INDEX events_correlation_idx ON events (correlation, emitted_at);
CREATE TRIGGER events_immutable BEFORE UPDATE OR DELETE ON events
  FOR EACH ROW EXECUTE FUNCTION raise_immutable();
02

Agent handoff network

Agents are stateless edge functions. Coordination is by event consumption, not RPC. A typical P2P pipeline:

requisition-agentpo-agentidoc-architectinvoice-matcherpayment-agent

Spawned in parallel for RFQ, surveillance, pricing, and SAP integration. Each agent writes to the event bus; downstream agents subscribe.

03

Data flow table

EventTriggerAgentDB writesTreasury effect
requisition.createdTelegram /reqrequisition-agentrequisitions, audit_events
po.issuedrequisition.approvedpo-agentpurchase_orders, idocscommitment posted
goods.receivedWMS scangoods-agentgoods_receipts
invoice.receivedemail / OCRinvoice-matcherinvoices, match_resultsliability accrued
invoice.matched3-way match okinvoice-matcherinvoices.state, ledgerpayment scheduled
payment.releaseddue date reachedpayment-agentledger_eventscash decrement
discount.proposedtreasury floatpricing-agentdiscount_offersprovisional gain
dispute.openedinvoice.disputeddispute-arbitratordisputes, evidence_hashesliability frozen
04

State machine registry · 131 transitions across 16 entities

Transitions live in the proc_state_machines table. Adding a new valid transition is a single SQL INSERT — no code deploy.

EntityVerticalSample statesTransitions
requisitionsp2pdraft → submitted → classified → approved → po_issued → closed12
purchase_ordersp2pdraft → sent → acknowledged → received → invoiced → closed → cancelled9
invoicesp2preceived → matching → matched → disputed → approved → paid11
suppliersp2ponboarding → active → blocked → offboarded7
rfqsp2popen → evaluating → awarded → cancelled → closed8
workflow_taskscrossqueued → running → succeeded → failed → retried16
documentscrossdraft → review → approved → effective → superseded → retired8
adverse_eventslife-sciencesreported → triaged → assessed → susar → closed8
clinical_trialslife-sciencesdesign → enrolling → active → locked → closed10
capa_cycleslife-sciencesopened → root-cause → action → verification → closed6
sopslife-sciencesdraft → approved → effective → superseded5
transactionstreasuryposted → locked → reversed7
discount_offerstreasuryproposed → accepted → rejected → expired5
mro_aircraftmroactive → grounded → in-maintenance → retired6
work_ordersmroopened → planned → executing → released8
disputescrossopened → arbitrating → resolved → closed5
adding a transition
INSERT INTO proc_state_machines (entity, from_state, event, to_state, requires_evidence)
VALUES ('invoices', 'matched', 'auto_pay', 'paid', true);
05

Database invariants · 19 constraints

Constraints enforced by Postgres, not by application code. Cataloged across four levels.

LevelInvariantDescription
attributepositive_quantityqty > 0 on every catalog and inventory row.
attributepositive_priceprice > 0 enforced at column level.
attributeenum_statestate column constrained to declared enum.
attributeiso_currencycurrency ∈ ISO 4217 codes.
attributeutc_timestampall timestamps stored UTC, timezone-aware.
tuplesplit_sums_to_totalsum(line.amount) = header.total per invoice/PO.
tuplesingle_current_versionexactly one row with is_current=true per logical id.
tupleapproval_quorumevery approval row carries ≥1 valid signature.
tuplethree_way_match_keysinvoice ↔ PO ↔ GR keys match before paid.
tableforward_only_statestate can never go backwards on terminal entities.
tableimmutable_ledgerledger_events.append-only; updates rejected by trigger.
tableimmutable_auditaudit_events table is INSERT-only.
tablemonotonic_versionsdocument.version is strictly increasing per logical id.
tableno_orphan_linesevery line FKs a header (FK + ON DELETE RESTRICT).
databaseevidence_gated_transitionstate changes that require evidence reject without it.
databasewebshop_fulfillmentwebshop order cannot ship without paid + stock.
databaseprice_floorno quote below configured floor per category.
databasesso_domain_uniqueone SSO config per email domain across all tenants.
databasehash_chain_continuityaudit head_hash recomputable from prev_hash chain.
06

Workflow invariants (Petri-net theory)

Place invariants are conservation laws over active tokens. Transition invariants prove processes reach terminal states. Verification: proc_check_place_invariants().

9 PLACE INVARIANTS
  • adverse event lifecycle
  • analysis cycle
  • capital deployment
  • document lifecycle
  • entity registry
  • invoice lifecycle
  • purchase order lifecycle
  • requisition lifecycle
  • RFQ lifecycle
8 active
requisitions
3 active
analysis cycles
100%
hash chain integrity
7 TRANSITION INVARIANTS
  • CAPA completion
  • market intelligence cycle
  • requisition rejection path
  • SOP lifecycle
  • spawn / close cycle
  • procurement workflow
  • SUSAR reporting
07

Technology stack

Framework
Next.js 16 · App Router · 3 instances
Database
PostgreSQL 16 · RLS · pgvector (HNSW, 1536-dim)
Edge
Supabase · 14 edge functions
LLM
OpenRouter · Claude Opus 4.6 · Gemini Flash (OCR)
Integration
Telegram Bot · SAP ORDERS05 IDocs · Slack
CI/CD
GitHub Actions · pgTAP · Playwright smoke
Continue to API reference →