Engineering
September 11, 2026
26 Min Read

Enterprise Ontology Architecture & Building the Semantic Layer: How ACM Grounds Autonomous Agents in a 6-Layer Relational Graph

How we designed and built the Domain Ontology and Enterprise Semantic Layer in Agentic Contract Management (ACM) so autonomous agents, hybrid RAG pipelines, and compliance auditors operate over a governed, version-controlled relational graph rather than ungrounded prompts.

Domain Ontology
Semantic Compiler
Graph Governance

# Enterprise Ontology Architecture & Building the Semantic Layer: How ACM Grounds Autonomous Agents in a 6-Layer Relational Graph

When enterprise AI initiatives stall between impressive demos and production deployment, the root cause is almost always a missing Enterprise Semantic Layer.

Without an explicit domain ontology, every autonomous agent, RAG retrieval step, and compliance prompt has to guess what institutional terms mean. One prompt defines a *Master Services Agreement* liability cap one way; another agent in the same workflow evaluates it differently; and when General Counsel updates a corporate standard, engineers are forced to hunt down and rewrite dozens of brittle prompt strings.

At Effective Solutions, when we architected Agentic Contract Management (ACM), we set out to answer a fundamental platform architecture question:

important

Architectural Blueprint Goal: How do we design and build the Domain Ontology and Enterprise Semantic Layer in ACM so that autonomous agents, hybrid RAG pipelines, and compliance auditors operate over a governed, version-controlled relational graph of domain categories, contract taxonomies, clauses, validation rules, and entity graphs rather than ungrounded prompts?

In ACM, the Semantic Layer bridges raw unstructured contract text and deterministic LLM execution. Rather than hardcoding legal definitions inside isolated prompts, ACM models domain semantics as a 4-Tier Relational Ontology Graph (src/db/models.py & src/api/legal_infra.py), pairs top-down taxonomies with bottom-up folksonomy and adjacency graphs (GlobalTag, TagAssociation, ContentGraph), enforces a Two-Stage Staged Discovery Gate (src/services/staging_service.py), prevents silent semantic drift via an HTTP 409 Intelligent Audit Block, dynamically compiles taxonomy-bound clauses and rules into every Agent prompt at runtime via PipelineEngine._fetch_legal_context(), and renders live semantic execution traces in our dual-mode EntityGraphDashboard.tsx.

Here is our complete 6-layer engineering blueprint—starting with the fundamentals of what an ontology actually is in enterprise architecture—followed by the production SQLAlchemy, FastAPI, and React/TypeScript code running in ACM.


0. Enterprise Architecture Fundamentals: What Is an Ontology (and Why Database Schemas Alone Are Not Enough)?

In computer science and enterprise architecture, an Ontology is a formal, explicit specification of a shared domain conceptualization. While a traditional database schema defines how data is physically stored (tables, foreign keys, VARCHAR columns, JSONB blobs), an ontology defines what the domain actually means, how concepts relate, and what rules govern valid state transitions.

When enterprise architects design for autonomous AI agents, distinguishing an Ontology from adjacent data-modeling concepts—like a glossary, a folksonomy, or a taxonomy—is critical:

Semantic Maturity LevelCore Question It AnswersStructural TopologyFailure Mode Without ItConcrete Implementation in ACM
1. Controlled Glossary / Data Dictionary*"What does this term mean in plain English?"*Flat list of terms and definitions (Key -> Text).Business units and prompts use conflicting definitions for the same legal or financial term.GovernanceVariable labels & descriptions (src/db/models.py).
2. Folksonomy (Bottom-Up Tagging)*"How do practitioners group and filter items on the fly?"*Ad-hoc, many-to-many associative labels across heterogeneous records.Single-parent category_id / taxonomy silos prevent cross-cutting search across contracts, rules, and prospects.GlobalTag, Contract.tags (JSONB), and polymorphic TagAssociation (src/services/staging_service.py).
3. Taxonomy (Top-Down Classification)*"What kind of instrument or category is this?"*Strict parent-child tree (Is-A / Belongs-To hierarchy).Every document is treated identically; an NDA is audited with the same rules as a Cloud SaaS MSA.RuleCategory (1:N) → Taxonomy (MSA, NDA, SOW, SaaS Licensing).
4. Physical Database Schema (OLTP / OLAP)*"How are bytes indexed and joined on disk?"*Normalized 3NF tables and Kimball Star Schema fact/dimension tables.Data corruption, update anomalies, or slow multi-table analytical queries.PostgreSQL tables (contracts, clauses, compliance_evaluations) + PGVector embeddings.
5. Enterprise Ontology & Semantic Layer*"What are the canonical entities, typed graph edges, bounded tolerances, and executable axioms that govern reasoning?"*Multi-Tier Semantic Graph + Executable Axioms linking categories, taxonomies, clauses, rules, agents, and audit invariants.LLMs hallucinate policy rules, mutate active playbooks without governance, or invalidate historical compliance audits.The 6-Layer ACM Ontology Architecture (models.py, legal_infra.py, staging_service.py, _fetch_legal_context(), EntityGraphDashboard.tsx).

The 4 Structural Building Blocks of an Enterprise Ontology

In an enterprise architecture blueprint, a production ontology is composed of four formal primitives—each mapped 1:1 to executable constructs in ACM:

  1. 1.Classes / Concepts (The Domain Nouns): The canonical entity types that exist in the enterprise universe. In ACM, these are RuleCategory, Taxonomy, Clause, ValidationRule, GovernanceVariable, Contract, and Agent.
  2. 2.Typed Relations / Predicates (The Graph Edges): The directed and bidirectional edges that connect classes and carry semantic meaning:
  • *Playbook Requirement Edge:* Taxonomy $\leftrightarrow$ Clause via taxonomy_clause_association (*"An Enterprise MSA requires the Standard Limitation of Liability clause"*).
  • *Policy Enforcement Edge:* Taxonomy $\leftrightarrow$ ValidationRule via taxonomy_validation_association (*"An Enterprise MSA must be verified against the Liability Cap Rule"*).
  • *Polymorphic Cross-Entity Edge:* GlobalTag $\rightarrow$ (entity_type, entity_id) via TagAssociation.
  • *Directed Composition Edge:* ContentBlock $\rightarrow$ MediaAsset via ContentGraph.
  1. 1.Attributes & Bounded Properties (The Domain Tolerances): Quantitative or categorical boundaries attached to concepts—such as ValidationRule.risk_level (Low, Medium, High, Critical) and GovernanceVariable (min_label <-> max_label, e.g., Net 90 <-> Net 15).
  2. 2.Axioms & Governance Invariants (The Executable Laws): Formal constraints that the platform enforces deterministically at runtime:
  • *Upstream Grounding Axiom:* No AI agent may evaluate or draft a contract without first compiling its Taxonomy's bound Clause, ValidationRule, and GovernanceVariable nodes (_fetch_legal_context()).
  • *Quarantine Airlock Axiom:* Autonomous discovery agents cannot mutate active ontology classes; new proposals must enter StagedRule, StagedClause, or StagedTaxonomy with status="Staged".
  • *Historical Immutability Axiom:* Any ontology node referenced by historical ComplianceEvaluation facts (func.count > 0) cannot be mutated in place without triggering an HTTP 409 Intelligent Audit Block or cascading status="Needs Review" across dependent contracts.
note

Why Autonomous Agents Need an Ontology Bridge: Large Language Models operate in probabilistic token space (high linguistic fluency, zero institutional memory or relational integrity), whereas enterprise systems of record operate in physical table space (foreign keys and row-level security, but opaque to an LLM without context compilation). The Enterprise Semantic Layer sits between them—compiling the relational ontology graph into token-budgeted instructions upstream before the LLM runs, and translating the LLM's verification outputs back into multi-dimensional Star Schema facts (ComplianceEvaluation) downstream.

Core Architectural Terms Explained: What They Basically Mean (Before Reading the Matrix)

Before inspecting ACM's 6-layer architecture matrix and production code, here is what the four core architectural patterns in this guide basically mean from first principles:

1. What Is an Entity Graph, Basically?

  • The Basics: In a standard relational table, a record usually points to a single parent (for example, a contract belongs to one category). An Entity Graph models domain concepts as Nodes (a Taxonomy, a Clause, a ValidationRule, a Contract, or an Agent) connected by explicit Edges (many-to-many join tables or directed adjacency lists that define *how* two nodes relate).
  • Why It Matters in ACM: Because legal knowledge is interconnected—one Liability Cap rule might govern both an MSA and a SaaS Agreement, and one EU-DORA tag might apply to a contract, a rule, and a prospect—ACM stores these relationships as graph edges inside PostgreSQL (taxonomy_clause_association, taxonomy_validation_association, TagAssociation, and ContentGraph) and visualizes runtime agent execution as an interactive node graph (EntityGraphDashboard.tsx).

2. What Is a Semantic Layer Compiler, Basically?

  • The Basics: A traditional software compiler translates high-level source code into machine instructions. A Semantic Layer Compiler (PipelineEngine._fetch_legal_context() in ACM) queries the domain ontology graph at runtime, gathers the exact mandatory clauses, validation rules, and numerical tolerances linked to a document's classification, and compiles them into a structured, token-budgeted instruction block right before an AI agent executes.
  • Why It Matters in ACM: Instead of hardcoding legal rules inside static prompt templates (which immediately drift out of sync when policies change), ACM compiles the prompt context live from PostgreSQL on every single run.

3. What Is Hybrid Vector-Graph RAG, Basically?

  • The Basics: Standard RAG (Retrieval-Augmented Generation) relies solely on Vector Search—converting paragraphs into numerical embeddings (PGVector) to find text chunks that are *mathematically similar* to a user's question. However, vector similarity alone can miss mandatory corporate rules that use different wording. Hybrid Vector-Graph RAG fuses two retrieval paths simultaneously:
  1. 1.Deterministic Graph Traversal: Walking the ontology graph (Taxonomy → Clause + ValidationRule + GovernanceVariable) to fetch 100% of the rules that govern the contract archetype.
  2. 2.Semantic Vector + Cross-Encoder Retrieval: Querying PGVector embeddings (rag_engine.py) and re-ranking candidate paragraphs with a Cross-Encoder model to pinpoint the exact clauses inside the document where those ontology rules must be checked.

4. What Is a Kimball Star Schema, Basically?

  • The Basics: Designed by data-warehousing pioneer Ralph Kimball, a Star Schema separates data into a single central Fact Table (which records atomic, measurable events—such as a pass/fail rule evaluation) linked by foreign keys to surrounding Dimension Tables (which describe the *who, what, where, and how* of the event). When drawn in a diagram, the central fact table surrounded by its dimensions looks like a star.
  • Why It Matters in ACM: While the Ontology Graph (3NF) is optimized for curating rules upstream without duplication, the Star Schema (ComplianceEvaluation fact table surrounded by 6 dimensions: Contract, Clause, ValidationRule, Agent, PipelineRun, and Workspace) is optimized for downstream verification and instant blast-radius queries—answering *"Which active contracts failed Rule X under Agent Y?"* in a single join.

Concrete Walkthrough: The Star Schema Before vs. After LLM Verification

To see how the Ontology Bridge translates probabilistic LLM output into relational Star Schema facts, trace what happens in PostgreSQL when a new contract (ctr-882, *"Acme Cloud Master Services Agreement"*) is evaluated:

1. BEFORE LLM Execution (Upstream Dimension Tables Exist, Central Fact Table Has 0 Rows for ctr-882):

  • Dimension 1 — contracts (Contract):
idnametaxonomystatus
ctr-882Acme Cloud MSA.pdfMSADraft
  • Dimension 2 — clauses (Clause, linked to "MSA" via taxonomy_clause_association):
idnamecategorycontent
cls-liab-01Standard Liability CapLiability*"Total liability shall not exceed 12 months fees..."*
cls-gov-02Delaware Governing LawLegal*"This Agreement shall be governed by Delaware law..."*
  • Dimension 3 — validation_rules (ValidationRule, linked to "MSA" via taxonomy_validation_association):
idnamecategoryrisk_levelstatus
rul-cap-12mLiability Cap LimitLiabilityHighActive
rul-delawareGoverning Law JurisdictionLegalMediumActive
  • Dimension 4 — agents (Agent): { id: "mike-n6", name: "Drafter QA Validator", role: "Validator" }
  • Central Star Schema Fact Table — compliance_evaluations (ComplianceEvaluation): 0 rows for contract_id = "ctr-882".

2. DURING Execution (The Ontology Bridge in Action):

  • Upstream Subgraph Compilation (_fetch_legal_context): Walks taxonomy_clause_association and taxonomy_validation_association for "MSA" and injects cls-liab-01, cls-gov-02, rul-cap-12m, and rul-delaware into the prompt.
  • Probabilistic LLM Output: The LLM inspects *"Acme Cloud MSA.pdf"* and returns JSON indicating that Section 8 has uncapped liability (violating rul-cap-12m), while Section 14 specifies Delaware law (satisfying rul-delaware).

3. AFTER Initial LLM Verification (Run trc-44a91b — Downstream Star Schema Fact Table Populated via record_compliance_evaluations_for_run): Immediately upon verification completion, ACM translates that ephemeral LLM JSON into two immutable relational rows in compliance_evaluations joining all 6 dimensions, and transitions contracts.status from "Draft" to "Under Review":

id (PK)contract_id (Dim 1)clause_id (Dim 2)rule_id (Dim 3)agent_id (Dim 4)pipeline_run_id (Dim 5)workspace_id (Dim 6)is_compliantrationale
eval-901ctr-882cls-liab-01rul-cap-12mmike-n6trc-44a91bws-prod-01False*"Non-compliant against upstream rule 'Liability Cap Limit': Uncapped liability detected in Section 8."*
eval-902ctr-882cls-gov-02rul-delawaremike-n6trc-44a91bws-prod-01True*"Verified compliant against upstream methodology rule 'Governing Law Jurisdiction' (Medium risk threshold)."*

*Immediate Downstream Effect of These Star Schema Rows:*

  1. 1.Blocks Unverified Finalization (HTTP 409): Calling PUT /contracts/ctr-882/workflow-state with status="Finalized" queries SELECT * FROM compliance_evaluations WHERE contract_id='ctr-882' AND is_compliant=False, finds eval-901, and blocks final sign-off unless an explicit override rationale comment is provided.
  2. 2.Protects Historical Rule Integrity (HTTP 409): Because rul-cap-12m now has COUNT(compliance_evaluations.id) > 0, PUT /legal-infra/validation-rules/rul-cap-12m blocks any silent edit to that rule (Intelligent Audit Block).

4. AFTER Human Redline & Re-Verification (Subsequent Pipeline Run trc-77c02e): Once the human legal reviewer applies the redline capping liability at 12 months fees and re-runs verification (pipeline_run_id = "trc-77c02e"), new Star Schema fact rows are appended showing full compliance—unlocking the Downstream Verification Gate for independent human sign-off:

id (PK)contract_idclause_idrule_idagent_idpipeline_run_idis_compliantrationale
eval-955ctr-882cls-liab-01rul-cap-12mmike-n6trc-77c02eTrue*"Verified compliant against upstream methodology rule 'Liability Cap Limit' (High risk threshold)."*
eval-956ctr-882cls-gov-02rul-delawaremike-n6trc-77c02eTrue*"Verified compliant against upstream methodology rule 'Governing Law Jurisdiction' (Medium risk threshold)."*

How Many Fact Tables Exist in a Platform Like ACM? (The 5-Table Fact Constellation)

In enterprise dimensional modeling, a platform with multiple operational lifecycles does not stop at a single fact table. Instead, it uses a Fact Constellation (or "Galaxy Schema")—typically 4 to 6 fact tables that share conformed dimensions (Contract, Agent, ValidationRule, Workspace). In ACM (apps/acm-backend/src/db/models.py), there are 5 distinct fact/event tables:

Fact Table in ACMSQLAlchemy ModelAtomic Grain (What 1 Row Represents)Conformed Dimensions LinkedPrimary Architectural Purpose
1. compliance_evaluationsComplianceEvaluation1 row per (contract, clause, rule, agent, run) verification checkContract, Clause, ValidationRule, Agent, PipelineRun, WorkspaceGranular rule pass/fail rollups, HTTP 409 rule immutability, and downstream sign-off gating.
2. pipeline_runsPipelineRun1 row per topological DAG executionPipeline, Contract, WorkspaceStores full DAG node execution trace and point-in-time governance_snapshot.
3. contract_timeline_eventsContractTimelineEvent1 row per document edit, redline patch, or workflow sign-offContract, Actor/Role, WorkspaceImmutable custody ledger with lossless content_snapshot for 1-click rollback (/revert/{event_id}).
4. policy_auditsPolicyAudit1 row per LLM call or outbound connector invocation`EventType ("llm""tool"), Workspace`Model Armor / DLP safety perimeter audit log (allowed, reason, 2,000-char input_excerpt).
5. visitor_logsVisitorLog1 row per authenticated session / access eventUsername, Role, IP / UserAgentSecurity access auditing and operational telemetry.

Is This What Practitioners Call "Constant Knowledge Graph Pruning Per LLM Call"?

Yes—with a critical architectural distinction between upstream read-only subgraph pruning and downstream fact recording:

  1. 1.Upstream = Per-LLM-Call Subgraph Pruning (Read-Only Context Slicing): An enterprise ontology graph may contain hundreds of Taxonomies, thousands of Clauses, and tens of thousands of ValidationRules. Dumping the entire knowledge graph into every LLM call causes context rot (diluted attention, contradictory rules, and runaway token costs). Therefore, on every single LLM call, _fetch_legal_context(db, contract) prunes the global ontology graph down to the active local subgraph—selecting only the Clause and ValidationRule nodes connected to contract.taxonomy and pruning each clause body to a 300-character preview. Crucially, this is a read-only projection: it prunes what the LLM *sees* in its context window without deleting anything from PostgreSQL.
  2. 2.Downstream = Append-Only Star Schema Fact Recording (Zero Destructive Graph Mutation): When the LLM finishes evaluating the contract against that pruned subgraph, ACM never allows the LLM to destructively prune or overwrite nodes in the production ontology graph. Instead, the LLM's conclusions are written as append-only fact rows into compliance_evaluations (and any newly proposed rules are routed into staged_rules quarantine).
  3. 3.Structural Graph Pruning Is Strictly Human-Gated: Actual structural pruning of the ontology graph itself (retiring an obsolete ValidationRule, merging a GlobalTag, or deleting a Clause) is a privileged human action on DELETE /legal-infra/...—and is protected by the Star Schema's HTTP 409 Intelligent Audit Block whenever historical contracts depend on that node.

1. The 6-Layer Ontology & Semantic Build Matrix

To turn an abstract domain ontology into an executable platform capability, we decomposed ACM's Semantic Layer into six distinct engineering tiers:

Semantic LayerOntology TierPrimary Source FilesPackages UsedCore Entities & Graph EdgesAPI & Service SurfaceDesign ConsiderationsGovernance & Gate
Layer 1: 4-Tier Relational Domain Ontology GraphOntology Core · M:N Graphsrc/db/models.py
src/api/legal_infra.py
sqlalchemy>=2.0 · asyncpg · pydantic · uuidRuleCategory (1:N) → Taxonomy (M:N via taxonomy_clause_association & taxonomy_validation_association) → Clause + ValidationRuleGET/POST /legal-infra/categories, /taxonomies, /clauses, /rules, POST /taxonomies/{id}/clauses/{cid}Normalized M:N Graph vs. Duplication: A single standard Clause or ValidationRule is linked across multiple Taxonomy nodes via junction tables with ondelete="CASCADE" and selectinload eager loading.Strict foreign-key referential integrity & workspace scoping (workspace_id).
Layer 2: Folksonomy Tagging & Document ContentGraphFolksonomy · Adjacency Graphsrc/db/models.py
src/services/staging_service.py
sqlalchemy.dialects.postgresql · fastapiGlobalTag, TagAssociation, Contract.tags (JSONB array), ContentGraph (block_id → asset_id)StagingService.list_global_tags(), DELETE /tags/{tag_name}Hybrid Top-Down + Bottom-Up Semantics: Pairs rigid top-down legal taxonomies with bottom-up cross-cutting tags (GlobalTag + live contract JSONB union) and document entity adjacency lists (ContentGraph).Global tag deduplication and workspace-wide cascade removal across Contract.tags.
Layer 3: Two-Stage Ontology Governance & Staged DiscoveryStaging Gate · HITL Curationsrc/db/models.py
src/services/staging_service.py
src/api/staging.py
sqlalchemy · pydantic · fastapiStagedTaxonomy, StagedClause, StagedRule, StagedTag (status: Staged → Promoted)POST /staging/rules/{id}/promote, POST /staging/tags/{id}/promote, POST /staging/categories/{id}/executePreventing Ontology Pollution: Autonomous discovery agents never write directly to production ontology tables; candidate rules/clauses land in staging tables until promoted.Explicit human architect promotion or retroactive category dry-run execution.
Layer 4: HTTP 409 Audit Block & Reactive InvalidationOntology Immutability · Cascade Re-Evalsrc/api/legal_infra.py
src/api/dependencies.py
fastapi.HTTPException · sqlalchemy.funcComplianceEvaluation reference counter + Contract.status = "Needs Review" cascadePUT/DELETE /taxonomies/{id}?force=bool, PUT/DELETE /clauses/{id}?force=bool, PUT/DELETE /rules/{id}?force=boolProtecting Historical Compliance Traces: Mutating an ontology node that has already evaluated contracts breaks historical audit meaning. Default behavior blocks with HTTP 409 Conflict; force=true invalidates impacted contracts.func.count(ComplianceEvaluation.id) > 0 raises HTTP 409 unless force=True.
Layer 5: Runtime Semantic Context Injection & Hybrid RAGSemantic Compiler · Vector-Graph RAGsrc/services/pipeline_engine.py
src/core/rag_engine.py
pgvector · langchain-openai · sentence-transformersPipelineEngine._fetch_legal_context(), RAGEngine.retrieve_context()Injected automatically inside run_pipeline() and AIReviewService into every Agent node's legal_contextToken-Budgeted Ontology Grounding: Resolves contract.taxonomy in the ontology graph, caps mandatory clause previews at 300 chars, appends ValidationRule and GovernanceVariable bounds, and fuses with Cross-Encoder reranked PGVector chunks.Every DAG execution snapshots the resolved ontology into PipelineRun.governance_snapshot.
Layer 6: Interactive Entity Graph Matrix & Semantic UISemantic Observability · Entity Graph UIcomponents/EntityGraphDashboard.tsx
app/legal-infra/page.tsx
components/AuditDetailSidebar.tsx
react · lucide-react · tailwindcssSemantic Swimlanes (Extraction, Analysis, Remediation, Validation) & Logical Flow Edges (Matrix & Flow modes), Legal Playbook Infrastructure ManagerDual-Mode Semantic Visualization: Maps raw agent execution traces into 4 canonical ontology capability columns (Matrix View) or logical dependency chains (Flow View) with interactive node inspection.Real-time status & risk badges linked directly to underlying node traces.

Architect Speak

  • Relational Graph in PostgreSQL vs. External Graph Silos: ACM implements its bipartite Ontology Graph (taxonomy_clause_association, taxonomy_validation_association), polymorphic tag graph (TagAssociation), and weighted adjacency lists (ContentGraph) directly inside PostgreSQL alongside PGVector. This guarantees single-database ACID transactions across ontology promotions, reactive contract invalidations, and vector embeddings without eventual-consistency drift between a separate Neo4j cluster and the relational store.
  • Compile-Time + Runtime Semantic Binding: Rather than treating an ontology as passive documentation, _fetch_legal_context() acts as a Runtime Semantic Compiler—resolving the contract's Taxonomy node, walking its M:N edges to Clause and ValidationRule records, attaching bounded GovernanceVariable tolerances, and injecting the compiled semantic block into every downstream agent node.

CIO Speak

  • Single Source of Institutional Truth: When General Counsel or Risk Leadership updates a corporate tolerance or clause standard in the Legal Playbook Infrastructure Manager, that change propagates deterministically across every AI agent, pipeline, and portfolio compliance check—zero prompt rewrites required.
  • Audit-Grade Semantic Lineage: Because every ontology mutation is guarded by pre-flight blast-radius checks (/dependencies/{entity_type}/{entity_id}) and HTTP 409 immutability gates, enterprise auditors can verify the exact semantic rules that governed any historical contract evaluation down to the millisecond.

Context, Action, Result (CAR Alignment)

  • Challenge: Storing domain rules inside individual agent prompts causes contradictory evaluations and massive maintenance overhead whenever corporate legal standards change. At the same time, rigid top-down hierarchies alone cannot capture cross-cutting operational themes or document-level entity relationships.
  • Action: In apps/acm-backend/src/db/models.py and apps/acm-backend/src/api/legal_infra.py, we architected a 4-Tier Relational Ontology Graph:
  1. 1.RuleCategory (1:N Domain Grouping)
  2. 2.Taxonomy (Contract Archetype Node)
  3. 3.Many-to-Many Clause & ValidationRule nodes bound via taxonomy_clause_association and taxonomy_validation_association
  4. 4.Bottom-up folksonomy and adjacency graphs (GlobalTag, TagAssociation, and ContentGraph)
  • Result: Reusable clauses and validation rules are defined once and linked across multiple contract taxonomies with full workspace isolation, while StagingService.list_global_tags() unions curated GlobalTag entities with live Contract.tags JSONB arrays for real-time cross-entity discovery.
Diagram
[Click to Open Floating PiP Viewer]
python
Parsing Swarm Architecture...

3. Layer 3: Two-Stage Ontology Governance & Shadow Discovery Gate (`staging_service.py` & `staging.py`)

Context, Action, Result (CAR Alignment)

  • Challenge: Allowing autonomous discovery agents or Demand-Driven Orchestrator (DDO) evaluations to write newly extracted clauses, tags, or validation rules directly into the active ontology risks polluting enterprise playbooks with unvetted or hallucinated rules.
  • Action: We built dedicated shadow quarantine tables (StagedTaxonomy, StagedClause, StagedRule, StagedTag) and StagingService in apps/acm-backend/src/services/staging_service.py. Whenever StagingService.evaluate_demand() detects a capability or methodology gap (phase != "direct_match"), it automatically stages candidate StagedRule and StagedClause rows with status="Staged" and requires_human_promotion=True.
  • Result: Zero unreviewed AI mutations ever reach the production semantic layer, while human legal architects can promote curated tags, clauses, and rules—or trigger retroactive category execution—with a single API call.
python
Parsing Swarm Architecture...

Context, Action, Result (CAR Alignment)

  • Challenge: Editing or deleting a live ValidationRule, Clause, or Taxonomy after it has already evaluated active contracts causes silent semantic drift across historical compliance traces—invalidating past audit sign-offs without warning.
  • Action: First, we built the Star Schema blast-radius pre-flight router (GET /dependencies/{entity_type}/{entity_id} in apps/acm-backend/src/api/dependencies.py) so the UI can inspect every contract and ComplianceEvaluation fact row that depends on a given ontology primitive. Second, in apps/acm-backend/src/api/legal_infra.py, every PUT and DELETE checks func.count(ComplianceEvaluation.id). If eval_count > 0 and force=False, ACM raises an HTTP 409 Conflict (Intelligent Audit Block). If an authorized architect passes force=True, ACM traverses taxonomy_validation_association and cascades Contract.status = "Needs Review" across all affected contracts.
  • Result: Guarantees immutable compliance history while automatically queuing impacted contracts for re-evaluation whenever forced ontology updates occur.
python
Parsing Swarm Architecture...
python
Parsing Swarm Architecture...

5. Layer 5: Runtime Semantic Layer Compiler & Hybrid Vector-Graph RAG (`pipeline_engine.py` & `rag_engine.py`)

First Principles: How the Semantic Compiler & Hybrid Vector-Graph RAG Work Together

Before an AI agent can evaluate a contract, two things must be assembled:

  1. 1.The Semantic Layer Compiler (_fetch_legal_context): Walks the relational ontology graph for contract.taxonomy and compiles the exact mandatory clauses, validation rules, and active GovernanceVariable bounds into a deterministic prompt header.
  2. 2.Hybrid Vector-Graph RAG (rag_engine.py): Pairs that graph-compiled playbook context with PGVector embedding search and Cross-Encoder precision re-ranking so the agent sees both the *institutional law* (from the Ontology Graph) and the *relevant document evidence* (from Vector Search).

Context, Action, Result (CAR Alignment)

  • Challenge: Connecting the relational ontology graph to live topological DAG execution without blowing through LLM context budgets or losing point-in-time auditability.
  • Action: We implemented _fetch_legal_context(db, contract) in apps/acm-backend/src/services/pipeline_engine.py as a Token-Budgeted Semantic Compiler. Before any agent node runs in run_pipeline() or AIReviewService, it resolves contract.taxonomy in the ontology graph, caps mandatory Clause previews at 300 characters for token efficiency, appends ValidationRule definitions and active GovernanceVariable bounds, snapshots the active governance rules into PipelineRun.governance_snapshot, and pairs the compiled ontology context with Cross-Encoder re-ranked PGVector retrieval (apps/acm-backend/src/core/rag_engine.py).
  • Result: Every agent node executes with deterministic playbook grounding, and every pipeline run preserves a point-in-time governance_snapshot alongside atomic ComplianceEvaluation Star Schema facts.
python
Parsing Swarm Architecture...

6. Layer 6: Interactive Entity Graph Matrix & Dual-Mode Semantic UI (`EntityGraphDashboard.tsx`)

First Principles: What the Runtime Entity Graph Visualizes

While the database ontology graph connects static legal primitives (Taxonomy ↔ Clause ↔ ValidationRule), the Runtime Entity Graph (EntityGraphDashboard.tsx) turns every multi-agent pipeline execution trace (pipelineRuns[].trace) into an inspectable visual graph. Each execution node is classified into one of four canonical ontology capability swimlanes—Extraction, Analysis, Remediation, or Validation—so reviewers can inspect the AI's reasoning either as a 4-column capability matrix (Matrix View) or as a step-by-step dependency chain (Logical Flow View).

Context, Action, Result (CAR Alignment)

  • Challenge: Legal reviewers and platform architects need to inspect how raw multi-agent execution traces map onto canonical ontology capabilities without digging through raw JSON logs.
  • Action: In apps/acm-frontend/components/EntityGraphDashboard.tsx, we built an interactive, dual-mode Entity Graph Matrix & Logical Flow Visualizer. It normalizes all nodes across pipelineRuns[].trace, classifies each execution step into 4 canonical semantic ontology swimlanes (Extraction, Analysis, Remediation, and Validation), and allows users to toggle between a categorized Matrix View and a sequential Logical Flow View with click-to-inspect payload drawers (setInspectorData).
  • Result: Gives legal engineers and auditors real-time semantic observability across every agent node, risk badge, and validation step.
tsx
Parsing Swarm Architecture...

7. Synthesis: The 6-Dimension Kimball Star Schema & 4 Complementary Entity Graphs in ACM

First Principles: Why Combine an Ontology Graph with a Star Schema?

In enterprise data architecture, Graphs and Star Schemas solve opposite halves of the governance lifecycle:

  • An Entity Graph (Upstream OLTP) is built for relationship traversal—connecting reusable clauses, rules, tags, and taxonomies across many-to-many edges so policy is defined once and inherited everywhere.
  • A Kimball Star Schema (Downstream OLAP) is built for high-speed audit aggregation—recording every individual pass/fail verification event in a central fact table (ComplianceEvaluation) surrounded by foreign-key dimension tables so compliance dashboards and HTTP 409 dependency checks execute in a single hop.

When enterprise architecture boards evaluate ACM, two questions frequently arise: *How does the Ontology Graph interact with your analytical Star Schema?* and *Why use PostgreSQL instead of a dedicated graph database?*

Part 1: The 6-Dimension Kimball Star Schema (`ComplianceEvaluation`)

Rather than burying pass/fail rule evaluations inside opaque JSON blobs, ACM models ComplianceEvaluation (apps/acm-backend/src/db/models.py) as a central Star Schema Fact Table with atomic measures (is_compliant, rationale, created_at) surrounded by 6 Foreign-Key Dimension Tables:

  1. 1.Dimension 1 — Document (contract_id → contracts.id, CASCADE): Slices compliance facts by contract archetype, status, and renewal window.
  2. 2.Dimension 2 — Clause (clause_id → clauses.id, SET NULL): Powers clause dependency pre-flight (GET /dependencies/clause/{id}) and GET /clauses/{id}/contracts.
  3. 3.Dimension 3 — Validation Rule (rule_id → validation_rules.id, SET NULL): Powers rule impact rollups and triggers the HTTP 409 Intelligent Audit Block when func.count(ComplianceEvaluation.id) > 0.
  4. 4.Dimension 4 — Agent (agent_id → agents.id, SET NULL): Tracks per-agent distinct contract utilization and agent audit history (GET /agents/{id}/contracts).
  5. 5.Dimension 5 — Pipeline Execution Run (pipeline_run_id → pipeline_runs.id, CASCADE): Links each atomic rule evaluation to its topological DAG run.
  6. 6.Dimension 6 — Tenant Workspace (workspace_id → workspaces.id via TenantMixin): Enforces multi-tenant OLAP isolation across all Star Schema aggregations.

Part 2: The 4 Complementary Entity Graph Topologies

Alongside the Star Schema, ACM operates four complementary graph topologies inside the same PostgreSQL ACID boundary:

  1. 1.Runtime Execution Trace Entity Graph (EntityGraphDashboard.tsx): Classifies pipelineRuns[].trace nodes into Extraction, Analysis, Remediation, and Validation swimlanes across Matrix and Logical Flow views.
  2. 2.Bipartite Playbook Ontology Graph (taxonomy_clause_association & taxonomy_validation_association): Connects RuleCategory → Taxonomy ↔ (Clause, ValidationRule) for upstream semantic compilation and reactive contract invalidation.
  3. 3.Polymorphic Cross-Entity Tag Graph (TagAssociation & GlobalTag): Composite 3-key edge table (tag_id, entity_type, entity_id) linking tags across "contract", "prospect", "content_block", and "rule".
  4. 4.Directed Adjacency & Hierarchical Tree Graphs (ContentGraph & Agent.parent_agent_id): Weighted adjacency lists (block_id → asset_id with role and order) and self-referential Master-Worker agent trees.

Three Architectural Nuances for Enterprise RFP Defense

tip

1. Relational Graph in PostgreSQL (vs. Neo4j): Implementing the Ontology Graph, Star Schema, and PGVector embeddings inside PostgreSQL guarantees single-database ACID transactions across ontology updates, contract invalidations, and vector indexing without cross-database synchronization lag.

2. ContextVar Application-Layer Tenant Isolation: Multi-tenant scoping is enforced via Python contextvars.ContextVar (workspace_id_ctx in src/db/context.py) and SQLAlchemy TenantMixin filters across every ontology table, Star Schema fact query, and PGVector collection.

3. Dual-Tier Audit Storage (2,000-Char Excerpts vs. Full Snapshots): PolicyAudit.input_excerpt stores sanitized excerpts for fast security dashboard indexing, while ContractTimelineEvent.content_snapshot preserves 100% lossless full-text snapshots for deterministic 1-click rollback.

Build with our
Architects

Bring your legacy silo data to life with autonomous reasoning swarms.

Book Review