01 / 14
Poetry Platform

Agentic Framework Architecture

AI-powered autonomous campaign management with multi-step reasoning, human-in-the-loop escalation, and compliance-driven decision making.

8
Work Items Completed
ReAct
Reasoning Pattern
HITL
Safety Guardrails
8
Pull Requests
02 / 14

What We Built

Four interconnected agentic capabilities for autonomous campaign management

๐Ÿ“Š
RIV-456

Daily Optimization

Automated bid and budget recommendations based on ROAS/CPA performance with dual-mode execution.

๐Ÿค–
RIV-457

Autonomous Executor

Full autonomous execution with mandatory validation, risk assessment, and HITL escalation.

๐Ÿ›ก๏ธ
RIV-458

Compliance Checker

Proactive validation against regulations, platform policies, and internal rules before execution.

๐Ÿง 
RIV-453

KB Tools Interface

OpenAI-compatible function schemas enabling Claude to query the Knowledge Base for context.

03 / 14

System Architecture

End-to-end flow from client request to execution

CLIENT
Poetry Web App
API Gateway
BPMN Workflows
โ†“
FUNCTIONS
Daily Optimization
Autonomous Executor
Compliance Checker
โ†“
AGENTIC CORE
ReAct Loop
Tool Dispatcher
HITL Manager
โ†“
KNOWLEDGE
KB Query Tool
KB Search Tool
Compliance Rules
Best Practices
โ†“
EVIDENCE
Audit Trail
CDD Compliance
Trace Correlation
04 / 14

ReAct Reasoning Loop

THINK โ†’ ACT โ†’ OBSERVE: The core pattern for autonomous decision-making

1. THINK
Analyze & Plan
โ†’
2. ACT
Execute Tool
โ†’
3. OBSERVE
Process Result
โ†’
Loop or
Complete

THINK Phase

  • โœ“Claude analyzes the current state and available information
  • โœ“Determines what additional data is needed
  • โœ“Selects appropriate tool from available options

ACT Phase

  • โœ“Calls selected tool (KB query, metrics fetch, policy check)
  • โœ“Structured tool invocation with typed parameters
  • โœ“Evidence collected for audit trail
for iteration in range(config.max_iterations): # 1. THINK - Claude reasons about next step response = await claude.messages.create(messages, tools) # 2. ACT - Execute selected tool tool_result = await dispatch_tool(response.tool_use) # 3. OBSERVE - Feed result back, continue or complete messages.append(tool_result)
05 / 14
RIV-456

Daily Optimization Agent

Dual-mode execution: Fast rule-based OR intelligent agentic reasoning

Sync Mode (Default)

Fast, deterministic optimization using rule-based logic:

  • โœ“ROAS > 120% target + budget exhausted โ†’ Increase budget 20%
  • โœ“ROAS < 50% target โ†’ Decrease bid 15% or pause
  • โœ“CPA > 150% target โ†’ Decrease bid 20%
  • โœ“CPA < 70% target + good ROAS โ†’ Increase bid 15%

Agentic Mode

Multi-step reasoning with tool access:

  • โœ“Queries KB for platform-specific best practices
  • โœ“Fetches real-time metrics from ad platforms
  • โœ“Validates against OPA policies
  • โœ“Can request HITL for edge cases
# Mode selection via environment variable AGENTIC_MODE = os.getenv("CORTEXONE_AGENTIC_MODE", "false").lower() == "true" if AGENTIC_MODE: return _optimize_daily_agentic(event, context) # ReAct loop else: return _optimize_daily_sync(event) # Rule-based
06 / 14
RIV-457

Autonomous Executor

Full autonomous execution with mandatory validation and safety guardrails

1. Parse Request
โ†“
2. Gather Context (KB + Metrics)
โ†“
3. Compliance Validation
โ†“
4. Budget Validation
โ†“
5. Risk Assessment
โ†“
6. Execute or HITL Escalate

Key Safety Features

No Sync Fallback

Autonomous execution REQUIRES agentic mode. No shortcuts.

Mandatory Validation

All 5 validation steps must complete before execution.

Rollback Capability

Every executed action includes rollback metadata.

07 / 14

HITL Escalation Framework

Risk-based thresholds determine when human approval is required

LOW RISK

Auto-Approve

  • Budget impact < $1,000
  • Change magnitude < 20%
  • Action aligns with historical patterns

MEDIUM RISK

Proceed with Caution

  • Budget impact $1,000 - $5,000
  • Change magnitude 20% - 50%
  • First-time action on campaign

HIGH RISK

Requires HITL

  • Budget impact > $5,000
  • Change magnitude > 50%
  • Pause affecting >5 campaigns
  • Policy violation detected
# Risk thresholds in autonomous-executor HIGH_RISK_BUDGET_THRESHOLD = 5000 # Actions affecting >$5000 require human approval HIGH_RISK_CHANGE_PERCENT = 50 # Changes >50% require human approval # HITL Request Pattern if risk_level == "high": return "HITL_REQUEST: Budget change of $12,500 exceeds threshold. Approve?"
08 / 14
RIV-458

Compliance Checker Agent

Proactive validation across three compliance domains

Regulatory Compliance

  • GDPR - Data privacy
  • CCPA - Consumer rights
  • HIPAA - Healthcare
  • SEC - Financial
  • Geographic restrictions

Platform Policies

  • Meta Advertising Policies
  • Google Ads Policies
  • TikTok Ad Policies
  • LinkedIn Marketing
  • Content restrictions

Internal Policies

  • Budget approval thresholds
  • Brand safety guidelines
  • Audience restrictions
  • Creative approvals
  • Spend limits

Quick Check (Rule-Based)

Fast validation for common scenarios:

# Age-restricted content check if 'alcohol' in content_categories: if not has_age_restriction(21): violations.append("AGE-ALCOHOL-US")

Full Check (Agentic)

Comprehensive multi-step validation:

# Full compliance with KB queries compliance_context = { 'check_type': 'full', 'require_evidence': True, 'domains': ['regulatory', 'platform', 'internal'] }
09 / 14
RIV-453

Knowledge Base Tools Interface

OpenAI-compatible function schemas for seamless Claude integration

Tool Purpose Key Parameters
query_knowledge_base Natural language Q&A with RAG question, collection, include_sources
search_knowledge_base Semantic similarity search query, limit, similarity_threshold
get_compliance_rules Domain-specific compliance rules domain, platform, region
get_platform_best_practices Platform optimization guidance platform, topic, campaign_type
# Tool invocation request (OpenAI-compatible) { "tool_name": "query_knowledge_base", "parameters": { "question": "What are Meta's best practices for lookalike audiences?", "collection": "poetry", "include_sources": true }, "persona": "campaign_manager", "include_evidence": true, "trace_id": "req-abc123" }
10 / 14

Evidence Collection for CDD

Complete audit trail for Compliance-Driven Development

Evidence Metadata Structure

{ "evidence_id": "ev-abc123", "timestamp": "2025-12-28T10:30:00Z", "tool_name": "query_knowledge_base", "query_hash": "sha256:a1b2c3...", "persona": "campaign_manager", "confidence": 0.92, "sources": [...], "trace_id": "req-xyz789" }

Key Features

  • โœ“SHA-256 Query Hashing - Tamper-proof query verification
  • โœ“Trace Correlation - Links evidence across requests
  • โœ“Source Provenance - Document/chunk citations
  • โœ“Confidence Scores - Quantified reliability
  • โœ“Persona Context - Role-based filtering

Why Evidence Matters

๐Ÿ“‹
Audit Compliance

Complete decision trail for regulators

๐Ÿ”
Explainability

Understand why AI made decisions

๐Ÿ”„
Reproducibility

Replay decisions for debugging

โš–๏ธ
Accountability

Clear ownership of outcomes

11 / 14

Complete Request Flow

Example: Budget increase request through the agentic pipeline

Step 1

Request Received

Budget increase +25% for campaigns with high ROAS

โ†’
Step 2

Query KB

Fetch platform best practices for budget scaling

โ†’
Step 3

Fetch Metrics

Get current ROAS, CPA, spend from ad platforms

โ†“
Step 4

Compliance Check

Validate against budget policies, spending limits

โ†’
Step 5

Risk Assessment

Calculate risk level based on thresholds

โ†’
Step 6

Execute / HITL

Auto-execute or escalate based on risk

# Request payload { "action_type": "budget_increase", "target_ids": ["campaign-001", "campaign-002"], "parameters": { "increase_percent": 25, "reason": "High ROAS performance" } }
# Response with evidence { "execution_status": "executed", "risk_assessment": { "level": "medium", "confidence": 0.88 }, "evidence": { ... } }
12 / 14
RIV-454

Worker HITL + WebSocket Streaming

Real-time agent progress visibility with human intervention controls

WebSocket Streaming

  • โœ“execution_started - Agent begins processing
  • โœ“step_started/completed - Reasoning step progress
  • โœ“tool_called - Tool invocation with params/results
  • โœ“human_input_requested - HITL escalation
  • โœ“execution_completed/failed - Final status

BaseAgenticWorker Features

  • โœ“Extended 120s timeout for multi-step execution
  • โœ“Automatic lock extension to prevent task expiry
  • โœ“AgentTrace capture in process variables
  • โœ“HITL callback for human input requests
  • โœ“Auto-reconnection with exponential backoff
// WebSocket event handling wsManager.on('tool_called', (event) => { console.log(`Tool: ${event.toolName}`); console.log(`Result: ${JSON.stringify(event.result)}`); }); wsManager.on('human_input_requested', (event) => { // Show HITL dialog to user showHITLDialog(event.request); });
13 / 14
RIV-459

Agent Progress Panel UI

Real-time visualization of agent reasoning with human intervention controls

๐Ÿ”„

Live Step Visualization

Real-time display of observe/think/act/final phases with duration and token counts per step.

๐Ÿ› ๏ธ

Tool Call Display

Expandable tool invocations showing parameters, results, and copy-to-clipboard functionality.

๐Ÿ‘ค

Human Controls

Pause, resume, abort buttons plus context injection textarea for human guidance.

Component Architecture

AgentProgressPanel

Main container with WebSocket connection, progress bar, and controls

โ†’
AgentStepCard

Individual step with phase indicator and expandable content

โ†’
HITL Dialog

Text input or multiple choice for human responses

shadcn/ui
Card
Button
Progress
Alert
ScrollArea
14 / 14

Key Takeaways

What makes this architecture production-ready

Autonomous but Safe

ReAct reasoning enables complex decisions while HITL escalation ensures human oversight for high-risk actions.

Compliance-First

Every action validated against regulatory, platform, and internal policies before execution.

Evidence-Driven

Complete audit trail with query hashing, source provenance, and trace correlation for CDD compliance.

Knowledge-Powered

OpenAI-compatible KB interface enables Claude to access domain expertise during reasoning.

All Pull Requests (8 Total)

PR #413
Core Framework (RIV-452)
PR #418
Daily Optimization (RIV-456)
PR #419
Autonomous Executor (RIV-457)
PR #420
Compliance Checker (RIV-458)
PR #422
KB Tools Interface (RIV-453)
PR #423
Policy/Budget APIs (RIV-455)
PR #424
Progress Panel UI (RIV-459)
PR #425
Worker HITL (RIV-454)
15 / 20
EVOLUTION

Architecture Evolution: Build vs Buy

Why we built custom vs. using existing frameworks

Framework ReAct HITL Streaming RAG BPMN Compliance
LangGraph โœ… โœ… Interrupts โœ… โœ… โŒ Limited
CrewAI โœ… โœ… human_input Limited โœ… โŒ HIPAA/SOC2
LlamaIndex โœ… Limited โœ… Best โŒ Limited
Claude Agent SDK โœ… Custom Limited Limited โŒ Custom
Poetry (Rival) โœ… โœ… โœ… โœ… โœ… CDD

Key Differentiator: BPMN Integration

No existing framework supports BPMN/Camunda integration. This is core to Poetry's architecture - agents ARE Camunda external task workers with process variable capture, lock extension, and compliance audit trails.

16 / 20
SECURITY

MCP + mTLS Security Architecture

Enterprise-grade agent communication with mutual TLS

API Key Authentication (Current)

EncryptionVia HTTPS
Client IdentityNone (key only)
Key TheftSingle secret
RevocationHard
AuditWhich service?

mTLS Authentication (Target)

EncryptionVia TLS
Client IdentityCertificate
Cert TheftNeed cert + key
RevocationEasy (CRL/OCSP)
AuditCertificate identifies
# mTLS Configuration (from previous implementation) context = ssl.create_default_context(ssl.Purpose.SERVER_AUTH) context.load_cert_chain( certfile="/etc/certs/agent-client.pem", # Client certificate keyfile="/etc/certs/agent-client.key" # Client private key ) context.load_verify_locations("/etc/certs/ca.pem") # Trust CA context.verify_mode = ssl.CERT_REQUIRED # Require server cert
17 / 20
MODELER

Custom BPMN Task Types

Visual differentiation for Agentic Tasks and Rival Functions

[A]
Daily Optimization
โš™๏ธ

Agentic Task

Multi-step reasoning with HITL

[F]
Predictive Engine
โš™๏ธ

Rival Function

CortexOne function invocation

Popup Menu

Custom entries in "Change element" menu with Rival section separator

Visual Badges

Purple [A] for Agentic, Blue [F] for Functions - instant recognition

Properties Panel

Context-aware panels with agent config, tools, HITL settings

18 / 20
VISUALIZATION

Agent Execution Visualizer

Real-time observation of agent reasoning and tool calls

๐Ÿค– Daily Optimization Agent โฑ๏ธ 47s / 120s
REASONING
"Analyzing campaign performance data to determine if budget increase is justified..."
TOOL CALLS
โœ… query_knowledge_base 1.2s
Server: knowledge-base (MCP/mTLS)
โœ… fetch_campaign_metrics 3.4s
Server: predictive-engine (Rival Function)
โณ validate_policy running...
Server: policy-service (MCP/mTLS)
CONFIDENCE โ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–‘โ–‘ 68%
EVIDENCE ๐Ÿ“š 3 docs ยท ๐Ÿ“Š 7 days
WebSocket Streaming
Real-time Updates
Tool Call Tracking
Confidence Meter
19 / 20
ARCHITECTURE

Target Architecture

Unified Agentic Platform with MCP Gateway

MODELER
[A] Agentic Task
[F] Rival Function
Properties Panel
โ†“ Deploy
ENGINE
Camunda (BPMN)
External Tasks
Process Variables
โ†“ External Task
WORKER
Unified Worker
AgenticStrategy
FunctionStrategy
โ†“ MCP/mTLS
GATEWAY
MCP Gateway
Agent Registry
Health Tracking
โ†“
AGENTS
Claude SDK
KB Server
Policy Service
Rival Functions
20 / 20

Implementation Roadmap

Phased delivery with working reference implementation

Stream 1

BPMN Modeler

  • RivalPopupMenuProvider
  • RivalRenderer (badges)
  • Properties Panels
  • Combined RivalPalette
Stream 2

Visualization

  • AgentExecutionVisualizer
  • ToolCallCard
  • ExecutionTimeline
  • ConfidenceMeter
Stream 3

Backend

  • Claude Agent SDK
  • MCP Gateway + mTLS
  • Agent Registry
  • Unified Worker

Reference Implementation Goal

๐Ÿ“
Define

Create tasks in modeler

๐Ÿš€
Deploy

Deploy to Camunda

โ–ถ๏ธ
Execute

Run end-to-end

๐Ÿ‘๏ธ
Observe

Watch in visualizer