Skip to main content

ADR-007: Workflow Ontology Engine

Declarative Compliance Workflow System with AI-Powered Implementation Engine

FieldValue
StatusPROPOSED
Date2026-03-24
AuthorTrustRelay Engineering
SupersedesNone
ImpactsNew subsystem (additive)

Table of Contents

  1. Decision Summary
  2. Context & Problem Statement
  3. Architectural Decisions
  4. Implementation Architecture
  5. Workflow Schema Specification
  6. Rollback Strategy
  7. Phased Delivery Plan
  8. Effort Estimates
  9. Competitive Positioning
  10. Risks & Mitigations
  11. Success Criteria
  12. Related Decisions & Dependencies
  13. Decision

1. Decision Summary

We will build a Workflow Ontology Engine — a declarative, schema-driven system that defines compliance workflows in YAML, compiles them to Temporal workflow execution plans, and runs them via a generic DynamicComplianceWorkflow interpreter. This is paired with an AI-Powered Implementation Engine (the "Workflow Builder") that reads customer compliance procedures and generates workflow schema configurations using agents with full access to Atlas's database schemas, ontology definitions, API specifications, and Temporal capabilities.

The entire system is additive. It introduces new files, new database tables, and a new Temporal worker on a separate task queue. The existing InvestigationWorkflow, all seven investigation modules, the entity ontology, Neo4j graph sync, and all API endpoints remain completely untouched. Rollback requires removing one include_router line and commenting out one Docker service.

Core Architectural Principle

The workflow engine is a CONSUMER of Atlas, not a replacement for any part of it. It calls the existing InvestigationWorkflow as a child workflow — the same way an API consumer triggers an investigation today. All reads from existing tables are read-only. All writes go to new tables only.

2. Context & Problem Statement

2.1 Market Position

Atlas enters a market where configurable compliance workflow orchestration is already established. The competitive landscape includes well-funded platforms with significant customer traction:

CompetitorCapabilityCustomers/ScaleKey Differentiator
LexisNexis RiskNarrativeNo-code drag-and-drop journey builder with natural language rules, Decision Matrix, scorecard creation200+ businessesUnified decisioning engine across full lifecycle
AlloyIdentity decisioning platform with workflow builder, 200+ data source integrationsHundreds of banks, credit unions, fintechsVendor-agnostic orchestration layer
FenergoFinCrime OS with Autocompletion Agent, AI-powered document processingTier-1 banks (BNP Paribas, StoneX, LBBW)Enterprise CLM with agentic AI (79% auto-completion)
Unit21AI agents for detection + investigation, no-code rule building$92M raised, 300K+ alerts processed by AI agentEnd-to-end agentic AI (99% accuracy)
SumsubWorkflow Builder + Summy AI Copilot, platform-wideGlobal verification leaderLLM-based copilot for compliance teams
KYC HubNo-code workflow automation for financial crime lifecycleGrowing mid-marketPersonalized user journeys with success/failure conditions
FlagrightAI Forensics suite for screening, monitoring, governanceAI-native fintech complianceNatural language transaction monitoring rules
DiditVisual orchestrator canvas with plug-and-play connectorsDeveloper-focusedNo-code KYC with biometric + document modules
Jinba FlowChat-to-Flow feature — describe workflow in plain English40,000+ enterprise users (YC-backed)Natural language workflow generation

2.2 Strategic Assessment

Atlas is late to the workflow builder market. However, the competitive gap analysis reveals that all existing platforms are closed orchestration systems — customers configure workflows within the vendor's pre-built ecosystem using the vendor's data sources and rule engines. No competitor combines:

  • An open knowledge graph (Neo4j)
  • An open agent architecture (Temporal + configurable AI squads)
  • Evidence lineage with source hashing
  • Customer-editable workflow schemas

into a single platform.

The differentiation opportunity is not the workflow builder itself — it is the investigation intelligence underneath it and the AI-powered implementation engine on top of it. Atlas's seven-module deep investigation pipeline is unique; no other platform starts with a comprehensive company intelligence investigation and builds the workflow around it.

2.3 The AMLR 2027 Window

The EU Anti-Money Laundering Regulation applies from July 2027. Institutions need to begin procurement 12-18 months before go-live, placing buying decisions in Q4 2025 through Q4 2026. This creates a 6-9 month window to achieve market readiness. Missing this window means waiting for contract renewals — a significantly harder sale.

3. Architectural Decisions

3.1 Decision 1: Workflow Ontology Schema System

Define compliance workflows as declarative YAML schemas that mirror the pattern established by the entity ontology. The entity ontology (ontology_schema_v3.yaml) defines what things exist and how they relate. The workflow ontology defines what happens, in what order, under what conditions, and who decides.

The schema-driven pattern is proven within Atlas. The entity ontology drives seven subsystems (SchemaCache, entity_matcher, reconciliation, populator, cypher_generator, neo4j_sync, entity_repository) from a single YAML definition. The workflow ontology drives a parallel chain:

Entity Ontology ChainWorkflow Ontology Chain
ontology_schema_v3.yamlworkflow_schema_v1.yaml
SchemaCache (loader)WorkflowSchemaCache (loader)
Populator (extraction)Compiler (schema -> execution plan)
EntityMatcher (dedup)ActivityResolver (agent binding)
CypherGenerator (graph)GateEvaluator (condition checking)
Neo4jSync (persistence)RuleEngine (rule binding)

Workflow Schema Primitives

Each workflow schema defines phases, and each phase has a type that maps to a Temporal execution primitive:

Phase TypeTemporal MappingPurpose
portalActivity (form handling)Customer data collection, document uploads
investigationChild Workflow (InvestigationSquadWorkflow)Parallel agent execution with configurable modules
rule_evaluationActivity (rule engine)Risk scoring, EBA matrix population, rule evaluation
reviewSignal-based wait (ReviewGateWorkflow)Human-in-the-loop decisions with SLA monitoring
actionActivity (create/notify/schedule)Customer creation, notifications, pKYC scheduling

Schema Structure

Each workflow schema contains the following top-level sections:

  • inputs: Required and optional data fields the workflow needs before starting, with type validation
  • phases: Ordered sequence of processing phases, each with steps, agents, conditions, gates, and dependencies
  • subject_entity_types: Links to entity ontology types this workflow operates on (LegalEntity, Person, etc.)
  • audit: Retention policies, evidence hashing configuration, logging requirements
  • sla: End-to-end timing targets and alerting thresholds
  • metrics: KPIs tracked per workflow (completion rate, auto-approval rate, escalation rate)

Within each phase, the schema defines:

  • agents: References to the agent registry (not hardcoded), with optional config_overrides and conditions
  • execution: Strategy (parallel/sequential), concurrency limits, timeout, partial failure handling
  • gate: Quality gate conditions that must pass before advancing (completeness, confidence threshold, score computed)
  • routes: Conditional branching based on prior phase outputs (risk score ranges, sanctions matches, etc.)
  • escalation: Timeout actions, role hierarchies, and maximum escalation levels

Compilation Chain

The WorkflowCompiler takes a validated YAML schema and produces a compiled execution plan (JSON) stored in PostgreSQL. The compilation:

  1. Resolves phase dependencies via topological sort
  2. Identifies parallel execution groups
  3. Binds agent type references to the live agent configuration registry
  4. Validates rule condition field paths against the rule_field_registry table
  5. Produces a structure the DynamicComplianceWorkflow can interpret at runtime

Critically, no Python code is generated or deployed per customer. A single generic DynamicComplianceWorkflow interprets all compiled schemas. Adding a new customer workflow means inserting a new schema row — not deploying new code.

3.2 Decision 2: DynamicComplianceWorkflow Interpreter

A single Temporal workflow definition that executes any compiled workflow schema. It reads the compiled execution plan and processes phases in dependency order, executing child workflows for investigation phases, activities for rule evaluation and actions, and signal-based waits for human review gates.

Key design properties:

  • Durable execution: Temporal guarantees the workflow survives crashes, restarts, and network partitions. A human reviewer can take three days to respond and the workflow picks up where it left off.
  • Signal-based human input: Phase decisions, form submissions, and review approvals are delivered via Temporal signals. No polling, no cron jobs, no lost state.
  • Query-based status: The workflow exposes its current phase, completed phases, and pending human inputs via Temporal queries — enabling real-time UI updates without database polling.
  • Conditional phase execution: Phases with conditions (e.g., EDD investigation only triggers if decision_routing produces "escalate_to_edd") are evaluated at runtime against the accumulated workflow context.
  • Phase loopback: Phases can route back to earlier phases (e.g., EDD results loop back to decision_routing for final judgment), enabling complex compliance workflows with multiple review cycles.
@workflow.defn
class DynamicComplianceWorkflow:
"""Generic workflow that executes any compiled workflow schema."""

def __init__(self):
self.phase_decisions = {}
self.phase_results = {}
self.status = "initialized"

@workflow.signal
async def submit_decision(self, phase_id: str, decision: dict):
self.phase_decisions[phase_id] = decision

@workflow.signal
async def submit_form_data(self, phase_id: str, data: dict):
self.phase_decisions[phase_id] = data

@workflow.query
def get_status(self) -> dict:
return {
"current_phase": self.status,
"completed_phases": list(self.phase_results.keys()),
"awaiting_input": [
pid for pid, p in self.compiled.phases_by_id.items()
if p.awaiting_human_input and pid not in self.phase_decisions
],
}

@workflow.run
async def run(self, input: DynamicWorkflowInput):
self.compiled = await workflow.execute_activity(
load_compiled_workflow,
input.workflow_schema_id,
start_to_close_timeout=timedelta(seconds=30),
)
context = WorkflowContext(inputs=input.data)

for group in self.compiled.parallel_groups:
executable = [
phase for phase in group
if self._evaluate_condition(phase.condition, context)
]

if len(executable) == 1:
result = await self._execute_phase(executable[0], context)
context.merge_phase_result(executable[0].id, result)
else:
results = await asyncio.gather(*[
self._execute_phase(phase, context)
for phase in executable
])
for phase, result in zip(executable, results):
context.merge_phase_result(phase.id, result)

return DynamicWorkflowResult(
workflow_id=self.compiled.workflow_id,
phase_results=self.phase_results,
final_decision=context.get("final_decision"),
audit_trail=context.audit_trail,
)

3.3 Decision 3: AI-Powered Implementation Engine (Workflow Builder)

The Workflow Builder is a Temporal workflow that operates on the same phased pattern as the GSD (Get Shit Done) spec-driven development system. It takes customer compliance procedure documents as input and produces validated workflow schema configurations as output, using agents with full access to Atlas's live system state.

Builder Phases

The builder follows a discuss -> plan -> generate -> verify -> review pipeline:

PhaseGSD EquivalentWhat HappensAgent Access
Ingest/gsd:new-projectParse procedure documents (PDF/DOCX), extract structured requirements, identify ambiguitiesDocument content only
Discuss/gsd:discuss-phaseSurface clarification questions, wait for customer answers via Temporal signal, resolve ambiguitiesExtracted requirements
Plan/gsd:plan-phaseMap resolved requirements to Atlas capabilities, identify gaps, select templates to forkPostgreSQL (agent_configurations, rule_field_registry, workflow_templates), Neo4j (entity types, relationships), API specs, ontology schema
Generate/gsd:execute-phaseProduce workflow YAML, rule DSL JSON, escalation policies, document templates — all in parallelRule DSL schema, Temporal workflow capabilities, agent configuration format
Verify/gsd:verify-workValidate generated configs against real schemas, check field references exist, coverage analysis, Temporal dry-runPostgreSQL (rule_field_registry), Rule engine validator, Temporal schema validator
Review/gsd:shipPresent draft to compliance officer with coverage report, warnings, and gap analysis. Wait for approval signal.Generated configurations + verification results
Activatemerge/deployLoad approved schema into workflow_schemas table, compile, and make available for executionworkflow_schemas table (write)

Why Agent Database Access Matters

  • The planning agent queries the actual agent_configurations table to know what investigation modules exist.
  • The generation agent queries rule_field_registry to use correct field paths (e.g., mebo.ownership_layers).
  • The verification agent validates generated rules against the live rule engine and checks field references against the actual database.
  • When a new module or data source is added to Atlas, the builder agents automatically discover it. No maintenance needed.

Builder as Internal Tool First

The builder should initially serve as an internal implementation accelerator used by the TrustRelay team during customer onboarding. This collapses implementation timelines from weeks to days, reduces implementation cost, and generates repeatable, validated configurations. Productization as a self-service "policy import" feature for customers comes later, once the builder has been validated across multiple real deployments.

3.4 Decision 4: Integrate, Don't Separate

The workflow engine is a feature of Atlas, not a separate product. The rationale:

  • No customers, limited runway, and a 6-9 month window before AMLR 2027 procurement locks. Splitting focus between two products is distraction, not strategy.
  • Generic workflow builders compete against n8n (open source), Temporal's own UI, Retool Workflows, Inngest, and dozens of others with tens of millions in funding.
  • Compliance buyers don't want a blank canvas. They want pre-built templates (KYB onboarding, vendor due diligence, periodic review, EDD escalation) that they fork and customize.
  • The differentiation is that when a compliance officer drags an "investigate company" block into a workflow, seven AI agents actually perform the investigation. No generic workflow tool can replicate this.

The workflow engine should be built with clean internal boundaries so it could theoretically be extracted later (Year 2-3), but extraction is not a design goal for this phase.

3.5 Decision 5: Non-Invasive Implementation

The entire workflow engine can be implemented without modifying any existing Atlas code, tables, or configurations. This is the most critical architectural constraint.

Existing code that stays untouched:

src/temporal/workflows.py <- InvestigationWorkflow unchanged
src/temporal/activities.py <- All module activities unchanged
src/temporal/enrichment_activities.py <- Enrichment unchanged
src/ontology/ <- Entity ontology unchanged
src/graph/ <- Neo4j sync unchanged
src/database/ <- All 16 repositories unchanged
src/tools/ <- All investigation tools unchanged
src/pipelines/ <- LangGraph pipelines unchanged
src/integrations/ <- MCP clients, North Data unchanged
config/ontology_schema_v3.yaml <- Entity schema unchanged

4. Implementation Architecture

4.1 File Structure (All New)

src/workflows/ # NEW directory
├── __init__.py
├── schema/
│ ├── loader.py # WorkflowSchemaCache
│ ├── validator.py # Schema validation
│ └── compiler.py # Schema -> compiled execution plan
├── engine/
│ ├── dynamic_workflow.py # DynamicComplianceWorkflow (Temporal)
│ ├── phase_executors.py # Phase type handlers
│ ├── gate_evaluator.py # Gate condition evaluation
│ └── context.py # WorkflowContext (shared state between phases)
├── activities/
│ ├── investigation_activities.py # Triggers existing InvestigationWorkflow
│ ├── portal_activities.py # Data collection / form handling
│ ├── review_activities.py # Human review notifications
│ ├── action_activities.py # Customer creation, notifications
│ └── builder_activities.py # GSD-style workflow builder agents
├── repository.py # WorkflowSchema + Execution repos
├── router.py # FastAPI endpoints
└── worker.py # Separate Temporal worker

config/workflow_schemas/ # NEW directory
├── kyb_onboarding_standard_v1.yaml
├── vendor_due_diligence_v1.yaml
└── periodic_review_v1.yaml

migrations/ # Additive only
├── V53__workflow_schemas.sql
├── V54__workflow_executions.sql
└── V55__workflow_builder.sql

4.2 Database Schema (New Tables Only)

Five new tables are introduced. No existing tables are modified. The only foreign key pointing outward is workflow_investigation_links.investigation_id, which is a read-only reference to the existing investigations table.

-- V53__workflow_schemas.sql

CREATE TABLE workflow_schemas (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
workflow_id VARCHAR(100) NOT NULL,
version INTEGER NOT NULL DEFAULT 1,
name VARCHAR(255) NOT NULL,
category VARCHAR(50) NOT NULL,
schema_yaml TEXT NOT NULL,
compiled_json JSONB,
is_active BOOLEAN DEFAULT FALSE,
is_draft BOOLEAN DEFAULT TRUE,
created_by VARCHAR(100),
created_at TIMESTAMPTZ DEFAULT NOW(),
updated_at TIMESTAMPTZ DEFAULT NOW(),
UNIQUE(workflow_id, version)
);
-- V54__workflow_executions.sql

CREATE TABLE workflow_executions (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
workflow_schema_id UUID NOT NULL REFERENCES workflow_schemas(id),
temporal_workflow_id VARCHAR(255) NOT NULL,
status VARCHAR(20) NOT NULL DEFAULT 'pending',
input_data JSONB NOT NULL,
current_phase VARCHAR(100),
phase_results JSONB DEFAULT '{}',
started_at TIMESTAMPTZ DEFAULT NOW(),
completed_at TIMESTAMPTZ,
created_by VARCHAR(100)
);

CREATE TABLE workflow_investigation_links (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
workflow_execution_id UUID NOT NULL REFERENCES workflow_executions(id),
investigation_id UUID NOT NULL REFERENCES investigations(id),
phase_id VARCHAR(100) NOT NULL,
created_at TIMESTAMPTZ DEFAULT NOW()
);

CREATE TABLE workflow_phase_decisions (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
workflow_execution_id UUID NOT NULL REFERENCES workflow_executions(id),
phase_id VARCHAR(100) NOT NULL,
decision VARCHAR(50) NOT NULL,
rationale TEXT,
decided_by VARCHAR(100) NOT NULL,
decided_at TIMESTAMPTZ DEFAULT NOW()
);
-- V55__workflow_builder.sql

CREATE TABLE workflow_builder_sessions (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
temporal_workflow_id VARCHAR(255),
source_documents JSONB,
extracted_requirements JSONB,
clarification_questions JSONB,
clarification_answers JSONB,
generated_schema_id UUID REFERENCES workflow_schemas(id),
status VARCHAR(20) DEFAULT 'initiated',
created_by VARCHAR(100),
created_at TIMESTAMPTZ DEFAULT NOW()
);
TablePurposeRelationship to Existing
workflow_schemasStores workflow YAML definitions + compiled JSON cache, versionedNone — standalone
workflow_executionsTracks running workflow instances with phase statusReferences workflow_schemas only
workflow_investigation_linksJoin table linking workflow phases to triggered investigationsREAD-ONLY FK to investigations(id)
workflow_phase_decisionsRecords human decisions per phase with rationale and timestampReferences workflow_executions only
workflow_builder_sessionsTracks GSD-style builder sessions with source docs and generated outputOptional FK to workflow_schemas for generated output

4.3 Integration Points

The workflow engine integrates with existing Atlas through exactly two patterns:

Pattern 1: Trigger Investigation (Write Path)

The investigation phase activity starts the existing InvestigationWorkflow as a child workflow via the Temporal client. This is identical to what POST /investigations does today. The activity waits for the result and records the investigation_id linkage in the new workflow_investigation_links table.

@activity.defn
async def trigger_atlas_investigation(
input: InvestigationTriggerInput,
) -> InvestigationTriggerResult:
"""Triggers a standard Atlas investigation.

This is the ONLY integration point with the existing system.
It uses the existing Temporal client to start an InvestigationWorkflow,
exactly as the API endpoint does.
"""
client = await get_temporal_client()

handle = await client.start_workflow(
"InvestigationWorkflow",
InvestigationParams(
company_name=input.company_name,
registration_number=input.registration_number,
country_code=input.country_code,
modules=input.modules,
),
id=f"wf-inv-{input.workflow_execution_id}-{input.phase_id}",
task_queue="investigation-queue",
)

result = await handle.result()

async with get_db_pool() as pool:
await pool.execute("""
INSERT INTO workflow_investigation_links
(workflow_execution_id, investigation_id, phase_id)
VALUES ($1, $2, $3)
""", input.workflow_execution_id, result.investigation_id,
input.phase_id)

return InvestigationTriggerResult(
investigation_id=result.investigation_id,
risk_score=result.risk_score,
risk_level=result.risk_level,
risk_indicators=result.risk_indicators,
entities=result.entities,
)

Pattern 2: Read Investigation Results (Read Path)

The risk evaluation activity reads from the existing risk_indicators and investigation_entities tables to evaluate workflow-specific rules. All reads use standard SELECT queries. No writes to existing tables occur. Results are written to new workflow tables only.

@activity.defn
async def evaluate_risk_rules(
input: RiskEvaluationInput,
) -> RiskEvaluationResult:
"""Reads investigation results and evaluates workflow rules.
Only READS from existing tables. Never writes to them."""

async with get_db_pool() as pool:
risk_indicators = await pool.fetch(
"SELECT * FROM risk_indicators WHERE investigation_id = $1",
input.investigation_id)

entities = await pool.fetch(
"SELECT * FROM investigation_entities WHERE investigation_id = $1",
input.investigation_id)

rule_engine = WorkflowRuleEngine()
results = rule_engine.evaluate(
rules=input.phase_rules,
data={
"risk_indicators": risk_indicators,
"entities": entities,
"investigation_result": input.investigation_result,
},
)

# Write results to NEW workflow tables only
async with get_db_pool() as pool:
await pool.execute("""
INSERT INTO workflow_phase_results
(workflow_execution_id, phase_id, result_data)
VALUES ($1, $2, $3)
""", input.workflow_execution_id, input.phase_id,
json.dumps(results))

return results

4.4 Temporal Worker Isolation

The workflow engine runs on a separate Temporal task queue (workflow-engine-queue) in a separate worker process, optionally as a separate Docker service. The existing investigation worker on investigation-queue is unaffected. Stopping the workflow worker has zero impact on investigation processing.

# docker-compose.yml addition
workflow-worker:
build: .
command: python -m src.workflows.worker
depends_on:
- temporal
- postgres
environment:
<<: *common-env
# Comment out to disable workflow engine entirely

4.5 API Integration

A single new router is registered in main.py behind a feature flag:

# src/api/main.py — ONE LINE CHANGE
if settings.workflow_engine_enabled:
from src.workflows.router import router as workflow_router
app.include_router(workflow_router)

New endpoints (all under /workflows prefix):

MethodEndpointPurpose
POST/workflows/Start a workflow execution from a schema
GET/workflows/{id}Get workflow execution status and phase results
POST/workflows/{id}/phases/{phase_id}/decisionSubmit human decision for review phase
POST/workflows/{id}/phases/{phase_id}/dataSubmit form data for portal phase
GET/workflows/schemasList available workflow schemas
POST/workflows/schemasCreate or update a workflow schema
POST/workflows/schemas/{id}/compileCompile and validate a schema
POST/workflows/builderStart a GSD-style builder session
GET/workflows/builder/{id}Get builder session status and questions
POST/workflows/builder/{id}/answersSubmit answers to builder clarification questions
POST/workflows/builder/{id}/approveApprove generated schema from builder

5. Workflow Schema Specification

A complete example of a KYB onboarding workflow schema:

schema_version: "1.0"
workflow_id: kyb_onboarding_standard
name: "Standard KYB Customer Onboarding"
description: "Risk-based onboarding for corporate customers"
category: onboarding
regulatory_basis:
- "AMLR Art. 16-18 (CDD)"
- "EBA ML/TF Risk Factor Guidelines"

subject_entity_types:
- LegalEntity
- Person

inputs:
required:
- field: company_name
type: string
- field: registration_number
type: string
nullable: true
- field: country_code
type: string
validation: iso_3166_alpha2
- field: requesting_entity
type: string
optional:
- field: known_ubos
type: list[Person]

phases:
- id: data_collection
name: "Customer Data Collection"
type: portal

steps:
- id: company_details
type: form
template: kyb_company_details_v2
required_fields:
- legal_name
- registration_number
- registered_address
- incorporation_date
- business_activity_codes

- id: ubo_declarations
type: form
template: ubo_declaration_v1
repeat: "for_each_ubo"
min_count: 1

- id: document_upload
type: document_collection
required_documents:
- type: certificate_of_incorporation
accept: [pdf, jpg, png]
validation: ocr_extract
- type: shareholder_register
accept: [pdf, xlsx]
- type: proof_of_address
accept: [pdf, jpg, png]
max_age_months: 3
conditional_documents:
- type: source_of_funds_declaration
condition:
field: phases.risk_assessment.risk_score
operator: greater_than
value: 60

gate:
type: completeness
condition: all_required_fields_and_documents
timeout_hours: 168
timeout_action: send_reminder
max_reminders: 3

- id: investigation
name: "Automated Due Diligence"
type: investigation
depends_on: [data_collection]

agents:
- id: cir
agent_type: corporate_identity_registration
required: true
- id: roa
agent_type: registered_operational_addresses
required: true
- id: mebo
agent_type: management_employees_beneficial_owners
required: true
config_overrides:
ubo_threshold: 0.25
- id: spepws
agent_type: sanctions_pep_watchlist_screening
required: true
- id: amlrr
agent_type: adverse_media_litigation_reputational_risk
required: true
- id: dfwo
agent_type: digital_footprint_website_ownership
required: false
- id: frls
agent_type: financial_regulatory_licensing_status
required: true

execution:
strategy: parallel
max_concurrent: 7
timeout_minutes: 30
on_partial_failure: continue
min_required_success: 5

gate:
type: all_required_complete

- id: risk_assessment
name: "Risk Scoring & Classification"
type: rule_evaluation
depends_on: [investigation]

rulesets:
- category: risk_scoring
apply: all_active
- category: eba_risk_matrix
apply: all_active

risk_matrix:
type: eba_ml_tf
dimensions:
- id: customer_risk
source_fields:
- mebo.ownership_layers
- mebo.has_nominee_shareholders
- cir.incorporation_age_months
- cir.jurisdiction_risk_level
weight: 0.30
- id: geographic_risk
source_fields:
- roa.country_risk_classification
- roa.is_virtual_office
- mebo.ubo_nationalities
weight: 0.25
- id: product_service_risk
source_fields:
- inputs.business_activity_codes
- frls.regulatory_licenses
weight: 0.20
- id: channel_risk
source_fields:
- dfwo.website_exists
- dfwo.domain_age_months
weight: 0.15
- id: transaction_risk
source_fields:
- inputs.expected_transaction_volume
weight: 0.10

gate:
type: score_computed

- id: decision_routing
name: "Risk-Based Decision"
type: review
depends_on: [risk_assessment]

routes:
- id: auto_approve
condition:
field: phases.risk_assessment.risk_level
operator: in
value: [clear, low]
action:
type: auto_decision
decision: approve
next_phase: activation

- id: simplified_review
condition:
field: phases.risk_assessment.risk_level
operator: equals
value: medium
action:
type: human_review
assignee_role: compliance_analyst
sla_hours: 24
decisions: [approve, reject, escalate_to_edd]

- id: full_review
condition:
field: phases.risk_assessment.risk_level
operator: in
value: [high, critical]
action:
type: human_review
assignee_role: senior_compliance_officer
sla_hours: 4
required_actions:
- review_full_investigation
- review_risk_matrix
- document_rationale
decisions: [approve_with_conditions, reject, escalate_to_edd]

- id: auto_reject
condition:
operator: OR
rules:
- field: phases.investigation.agents.spepws.sanctions_match
operator: equals
value: true
- field: phases.risk_assessment.risk_score
operator: greater_than
value: 95
action:
type: auto_decision
decision: reject
next_phase: rejection_handling

escalation:
timeout_action: escalate_to_next_role
max_escalation_levels: 3
roles_hierarchy:
- compliance_analyst
- senior_compliance_officer
- mlro

- id: edd_investigation
name: "Enhanced Due Diligence"
type: investigation
depends_on: [decision_routing]
condition:
field: phases.decision_routing.decision
operator: equals
value: escalate_to_edd

agents:
- id: source_of_wealth
agent_type: source_of_wealth_verification
required: true
- id: source_of_funds
agent_type: source_of_funds_analysis
required: true
- id: extended_media
agent_type: extended_media_monitoring
required: true
config_overrides:
lookback_months: 60

gate:
type: all_required_complete
then:
route_to: decision_routing
with_context: edd_complete

- id: activation
name: "Customer Activation"
type: action
depends_on: [decision_routing]
condition:
field: phases.decision_routing.decision
operator: in
value: [approve, approve_with_conditions]

steps:
- id: create_customer_record
action: create_entity
entity_type: Customer
map_from:
source: phases.data_collection
fields: [legal_name, registration_number, country_code]

- id: set_review_schedule
action: schedule_review
config:
low_risk: { months: 36 }
medium_risk: { months: 12 }
high_risk: { months: 6 }
based_on: phases.risk_assessment.risk_level

- id: enable_monitoring
action: activate_pkyc
config:
triggers:
- sanctions_update
- registry_change
- adverse_media
- ownership_change

- id: notify_requestor
action: notification
template: onboarding_approved
channel: [email, in_app]
recipient: inputs.requesting_entity

- id: rejection_handling
name: "Rejection Processing"
type: action
depends_on: [decision_routing]
condition:
field: phases.decision_routing.decision
operator: equals
value: reject

steps:
- id: generate_rejection_record
action: create_case
case_type: rejection
include_evidence: true

- id: notify_rejection
action: notification
template: onboarding_rejected
channel: [email]
recipient: inputs.requesting_entity
include_reason: false # tipping off prevention

- id: file_sar_if_required
action: evaluate_sar_requirement
condition:
field: phases.investigation.agents.spepws.sanctions_match
operator: equals
value: true

audit:
retention_years: 5
log_all_decisions: true
log_all_data_access: true
evidence_hashing: sha256

sla:
total_workflow_hours: 120
alert_at_percentage: 75

metrics:
- completion_rate
- average_duration_hours
- auto_approval_rate
- edd_escalation_rate
- rejection_rate

6. Rollback Strategy

Complete rollback requires four steps, none of which affect existing Atlas functionality:

  1. Remove router registration: Delete or comment out the include_router(workflow_router) line in src/api/main.py
  2. Stop workflow worker: Comment out the workflow-worker service in docker-compose.yml
  3. Drop new tables (optional): DROP TABLE workflow_builder_sessions, workflow_phase_decisions, workflow_investigation_links, workflow_executions, workflow_schemas CASCADE
  4. Delete new code (optional): Remove src/workflows/ directory and config/workflow_schemas/ directory

After rollback, Atlas returns to its exact pre-workflow state. No migrations need reverting on existing tables. No code changes to undo in existing files. The investigations table, entities table, risk indicators, Neo4j graph, and ontology schema are all untouched throughout.

Rollback Verification Checklist:

  • POST /investigations still works identically
  • All seven investigation modules execute as before
  • Entity ontology schema loads normally
  • Neo4j graph sync operates without changes
  • Risk scoring produces identical results
  • Existing API endpoints return same responses
  • Existing Temporal worker processes investigations on investigation-queue
  • No orphaned foreign keys from existing tables to dropped tables

7. Phased Delivery Plan

Phase 1: Foundation (Weeks 1-4)

Deliver the minimum viable workflow engine that can execute a hardcoded KYB onboarding schema.

  • Database migrations for new tables (V53-V55)
  • WorkflowSchemaCache: YAML loader with validation
  • WorkflowCompiler: Schema to execution plan for investigation and review phase types only
  • DynamicComplianceWorkflow: Core interpreter supporting investigation + review phases
  • trigger_atlas_investigation activity: Integration point with existing InvestigationWorkflow
  • ReviewGateWorkflow adaptation: Signal-based human decision with SLA timeout
  • Workflow router with basic CRUD and execution endpoints
  • First template: kyb_onboarding_standard_v1.yaml

Phase 2: Rule Engine Integration (Weeks 5-6)

Add rule_evaluation phase type so workflows can compute risk scores and populate risk matrices.

  • Rule evaluation activity: Read investigation results, evaluate workflow-specific rules
  • EBA risk matrix output format: Structured risk factor scoring across customer, geographic, product/service, channel, and transaction dimensions
  • Conditional routing: Decision phase that routes based on risk scores
  • Second template: vendor_due_diligence_v1.yaml

Phase 3: Portal & Actions (Weeks 7-9)

Add portal (data collection) and action (customer creation, notifications) phase types for complete end-to-end onboarding workflows.

  • Portal activity: Form schema rendering, document upload handling, completeness gates
  • Action activities: Customer record creation, pKYC scheduling, notification dispatch
  • EDD investigation phase: Extended investigation with source of wealth/funds agents
  • Phase loopback: EDD results route back to decision phase
  • Third template: periodic_review_v1.yaml

Phase 4: Workflow Builder (Weeks 10-14)

Build the GSD-style AI implementation engine as an internal tool.

  • Ingest phase: Document parsing (PDF/DOCX) with structured requirement extraction
  • Discuss phase: Ambiguity detection and clarification question generation with signal-based wait
  • Plan phase: Agents with database, Neo4j, and API spec access to map requirements to Atlas capabilities
  • Generate phase: Parallel agents producing workflow YAML, rule DSL, escalation policies
  • Verify phase: Schema validation, field reference checking, coverage analysis, Temporal dry-run
  • Review phase: Present generated configuration to compliance officer for approval
  • Builder session tracking in workflow_builder_sessions table

Phase 5: Visual Builder & Productization (Weeks 15-20)

Productize the workflow system for customer self-service.

  • Visual workflow editor in React/Blueprint.js that generates YAML schemas
  • Template library: Pre-built schemas customers can fork and customize
  • Schema versioning UI: Diff between versions, regulatory change tracking
  • Workflow execution dashboard: Real-time status, phase progress, SLA monitoring
  • Customer-facing builder: Guided workflow creation from procedure upload

8. Effort Estimates

ComponentEstimateDependencies
Database migrations0.5 weeksNone
Schema loader + validator + compiler2 weeksMigrations
DynamicComplianceWorkflow interpreter2 weeksCompiler
Investigation integration activity0.5 weeksInterpreter
Review gate adaptation0.5 weeksInterpreter
Rule evaluation phase1.5 weeksInterpreter
Portal + action phase types2 weeksInterpreter
Workflow router + API1 weekAll phase types
Builder: Ingest + Discuss phases2 weeksRouter
Builder: Plan + Generate phases3 weeksIngest/Discuss
Builder: Verify + Review + Activate2 weeksPlan/Generate
Visual workflow editor (frontend)3 weeksRouter + schemas
Template library (3 templates)1 weekCompiler
Testing + integration2 weeksAll components
Total23 weeks

The foundation (Phases 1-2, 8 weeks) delivers a working workflow engine that can orchestrate investigations with human review gates and risk-based routing. This is sufficient for early customer demonstrations and pilot deployments.

9. Competitive Positioning

What This Gets Atlas That Competitors Don't Have

Open, inspectable workflow definitions: The YAML schema IS the compliance documentation. When an auditor asks "what's your onboarding process?" the customer hands them the schema. Every field, condition, threshold, escalation rule, and regulatory reference is readable, version-controlled, and diffable. No other competitor offers this level of transparency.

Investigation-first orchestration: When a workflow reaches an investigation phase, seven AI agents perform a deep company intelligence investigation. No other workflow platform starts from investigation depth — they start from identity verification or transaction monitoring and work inward.

AI-powered implementation: "Upload your compliance procedures, get a working system in days instead of months" is a value proposition no competitor can currently match. It turns Atlas's late market entry into an advantage by meeting customers where they already are.

Knowledge graph context: Workflow decisions can leverage Neo4j graph queries — e.g., "if this entity shares a director with any previously flagged entity in the graph, escalate to EDD." Network intelligence informs workflow routing in a way that flat rule engines cannot replicate.

Unified ontology: Both what you know (entities, relationships) and what you do (investigate, assess, decide) are defined in the same schema-driven architecture. The workflow schema references entity types, and the entity ontology feeds investigation results into workflow decisions. This tight integration is architecturally unique.

Positioning Statement

Atlas is not a workflow builder with investigation capabilities. Atlas is an AI-powered investigation platform with configurable compliance workflow orchestration. The investigation intelligence is the product. The workflow is how it's delivered.

10. Risks & Mitigations

RiskSeverityLikelihoodMitigation
Builder agents generate invalid configurationsHighMediumVerify phase catches errors before human review. Rule engine validates against live schema. Temporal dry-run validates workflow structure. No configuration activates without human approval.
Customer procedures are ambiguous or contradictoryMediumHighDiscuss phase surfaces ambiguities explicitly. Gap analysis agent identifies conflicts. Builder outputs a coverage report showing what's fully/partially/not covered.
Schema complexity exceeds what YAML can expressMediumLowStart with the five phase types that cover 95% of compliance workflows. Add escape hatches (custom activity references) for edge cases.
DynamicComplianceWorkflow becomes a performance bottleneckMediumLowEach phase delegates to child workflows/activities. The interpreter is a thin orchestration layer. Temporal handles scaling natively.
Customers don't want schema-level controlMediumMediumShip pre-built templates that work out of the box. Most customers fork a template and adjust thresholds. The visual builder abstracts YAML for non-technical users.
AMLR 2027 procurement window closes before readinessCriticalMediumPhase 1-2 (8 weeks) delivers a demonstrable product. Prioritize customer pilots over feature completeness.
Zero customer references block enterprise salesCriticalHighTarget 2-3 pilot customers in first 6 months using the builder as an implementation accelerator. Offer aggressive pilot pricing. First reference customer is existential priority.

11. Success Criteria

CriterionTargetMeasurement
Workflow schema compiles to valid Temporal execution100% of shipped templatesAutomated test suite
Investigation phase triggers existing workflow without modificationZero changes to InvestigationWorkflowIntegration test
End-to-end onboarding workflow completes successfully< 30 min (automated) + SLA for human reviewWorkflow execution metrics
Builder generates valid schema from procedure documents> 80% of rule conditions correct on first passManual audit of generated configs
Implementation time for new customer< 5 days (down from 4-8 weeks industry standard)Project tracking
Rollback without data loss or service disruption< 15 minutes, zero impact on existing investigationsRollback drill
First paying customer on workflow engineWithin 6 months of Phase 1 completionRevenue
  • Entity Ontology (existing): The workflow ontology extends the schema-driven pattern. No changes required to the entity ontology, but the workflow schema references entity types defined there.
  • Agentic Investigation Squads (ADR-TBD): The workflow engine benefits from but does not require the agent framework migration. The existing InvestigationWorkflow with its seven modules is sufficient for Phase 1-3. The agentic squad architecture enhances Phase 4+ with more granular agent configuration.
  • No-Code Visual Rule Builder (ADR-TBD): The rule_evaluation phase type uses the Rule DSL and Rule Engine. The visual rule builder is a frontend for creating rule definitions, which the workflow engine consumes. These can be built in parallel.
  • Case Management (ADR-TBD): The review phase type creates cases when human review is required. The case management system provides the UI for analysts to action these reviews. The workflow engine sends notifications and receives decisions via Temporal signals.

13. Decision

We accept this ADR and proceed with implementation starting at Phase 1 (Foundation). Development begins on a feature branch with the workflow_engine_enabled feature flag defaulting to false. The flag is enabled for testing and pilot customers only until Phase 2 is complete and validated. All existing Atlas functionality remains untouched throughout implementation and can be verified by running the existing test suite without modification.