Greater Goods — Agentic AI Core Operating Model

Praesidium2 is the core platform enabling Greater Goods' Agentic AI Core Operating Model — a fundamental shift in how the company operates. Greater Goods is giving every business unit a team of AI-powered assistants that work alongside your team. Each department (CTO, VP Marketing, VP HR, VP Product) gets their own Praesidium2 instance with AI agents purpose-built to handle operational tasks — so your team can focus on the work that matters most. Agents are activated from template libraries, learn on the job, coordinate on projects, run daily standups, build and use custom tools, interact with humans via Slack/Jira/Confluence, and accumulate institutional knowledge over time. Praesidium2 is the command center that gives every team AI-powered capabilities.

Multiply Your Team's Impact

Every department gets AI agents that handle operational overhead — recurring tasks, report generation, project tracking, and cross-system coordination. Your team's capacity grows without adding to anyone's workload.

  • Automate operational tasks — status reports, data pulls, scheduling, cross-system updates handled by agents
  • Reduce coordination overhead — agents bridge the gap between planning, execution, and reporting across systems
  • Faster onboarding for new initiatives — agents carry institutional context and can brief team members on day one
  • ROI target: $210K/year savings — measured via KPI dashboard with 30/60-day kill criteria. Real impact data collected from Pre-Build baseline.

Institutional Knowledge That Never Leaves

Agents accumulate domain expertise over time. They remember what worked, what didn't, who to ask, and how your systems operate. When someone transitions roles, the knowledge doesn't leave with them. Agents preserve institutional context and help bring new team members up to speed faster. Knowledge compounds, never walks out the door.

You Lead, Agents Support

Your team drives strategy, creativity, relationships, and judgment calls — the work that requires human expertise. Agents take care of the operational details alongside you: updating Jira tickets, pulling reports, tracking competitors, drafting documents, and coordinating across systems. When agents need guidance, they escalate to you — keeping you informed and in control.

Keeping agents on track early on: Praesidium2 surfaces agent reasoning at every step — not just the final output. Each task execution includes a step-by-step trace showing what the agent considered, what it decided, and why. You can review this reasoning log in the dashboard, spot a wrong assumption before it compounds, and redirect the agent mid-task. Think of it like being able to look over their shoulder. During the early rollout period, the design specifically calls for shorter task windows and more frequent human checkpoints so you can build confidence in how each agent behaves before giving them more autonomy. Guard rails (budget limits, tool restrictions, escalation triggers) are always active, but the reasoning trace gives you the visibility to have an informed conversation with the agent about where it went off course — and to tune its instructions accordingly.

✓ Resolved (B13): Human feedback mechanism built into v1.8 — thumbs up/down on task completions, quality scores per agent, feedback-to-prompt improvement pipeline. Agent quality is measurable and continuously improving.

Cross-Department Coordination

Engineering's COS can query Marketing's COS about campaign timelines. Product's agents can check Engineering's sprint status. Cross-functional projects are coordinated automatically. No more "let me check with the other team and get back to you" — agents get answers in seconds.

Custom Tools for Your Business

The Tool Forge (V1.5) lets any team lead work with an agent to build custom tools — without adding to the engineering backlog. At launch, agents use pre-built platform and integration tools (Slack, Jira, GitHub, etc.). In V1.5 (4–6 weeks post-launch), the Tool Forge adds collaborative custom tool building: describe what you need, the agent builds and tests it, you approve, it's deployed to the catalog.

Full Observability & Cost Control

Every action is logged. Every token is tracked. Every dollar is attributed to an agent, project, and task. Set budgets per agent, per project, per job. Get alerts when costs exceed thresholds. Compare the cost of AI operations against the value delivered. This isn't a black box — every agent action is transparent, tracked, and accountable.

How Each Team Uses Praesidium2

CTO / Engineering

Agents assist with sprint planning preparation, draft code reviews, automate PR templates, monitor CI/CD pipelines, track infrastructure metrics, and keep technical documentation current. Daily standups run automatically. Engineers focus on architecture decisions, complex problem-solving, and shipping quality software.

CMO / Marketing

Agents manage Amazon PPC bids hourly, optimize product listings, track competitor pricing, schedule social media, generate performance reports. Marketing managers review and approve — with more time for strategic planning and creative campaigns.

VP Product

Agents maintain product roadmaps, sync Jira backlogs across teams, draft PRDs, track feature delivery status, coordinate with engineering and design agents. Product managers focus on user research and prioritization.

VP HR / Operations

Agents handle onboarding checklists, policy document updates, compliance tracking, employee satisfaction surveys, benefits administration coordination. HR stays focused on what they do best — people, culture, and relationships — while agents take care of routine checklists, tracking, and follow-up reminders.

CFO / Finance

Agents generate financial reports, track budget burn rates, reconcile invoices, monitor vendor SLAs, prepare board meeting materials. Finance team focuses on analysis and strategic decisions — agents prepare the data.

VP Design

Agents export Figma specs, maintain design system documentation, track design review feedback, coordinate handoff to engineering, generate accessibility audit reports. Designers get more time for what they love — creative work — because agents help with spec exports, documentation upkeep, and coordination tasks.

117
Total Tables
58
Entity Tables
59
Type Tables
5
Deployable Services
9
Data Domains

Core Principles

1

Agents as Employees — Memory, skills, evolving expertise, personality, daily standups

2

Tools as First-Class Entities — Versioned, tested, git-backed, risk-leveled capabilities

3

Type Tables for All Enums — 59 FK-referenced lookup tables. No magic strings.

4

qqq as Data Layer — Generated REST APIs, Liquibase migrations, RBAC, audit logging

5

Authentik for Auth — IAM-style policies, row-level security, per-instance isolation

6

Humans are First-Class — Assignable work, reachable via integrations, same UI components

Technology Choices

Agent Runtime (Python)

Anthropic SDK LangGraph FastAPI Celery Anthropic SDK

Data & API Layer (Java)

qqq Framework Liquibase PostgreSQL pgvector

Frontend (TypeScript)

React 19 Vite Tailwind CSS shadcn/ui TanStack Query TanStack Router

Infrastructure

Kubernetes (EKS) Helm ArgoCD Redis S3 / MinIO Authentik

System Stack

Three distinct layers, each with its own language and responsibilities.

UI Layer

PRAESIDIUM2 (React SPA)

Dashboards, Chat, Projects, Meetings  (Forge: V1.5)

Intelligence Layer

AGENT RUNTIME (Python)

Direct Anthropic SDK + LangGraph (Scoped)
Gateway (FastAPI) + Workers (Celery)

Foundation Layer

DATA & INFRASTRUCTURE

qqq (Java) + PostgreSQL + Redis + S3
Authentik + Secrets Manager + k8s

Architecture Decision: Anthropic SDK + LangGraph (Scoped)

APPROVED

Selected over CrewAI + LangGraph hybrid, LangGraph-only, and AutoGen/Microsoft Agent Framework. CrewAI evaluated and deferred — Praesidium2's 117-table data model already provides agent definitions, tool registry, memory, and team orchestration, making CrewAI a redundant translation layer.

Anthropic SDK — Direct Execution

  • Direct agent loop for chat, tasks, and standups
  • No framework translation overhead
  • Full control over prompting and tool execution

LangGraph — "HOW complex work flows" (scoped to durable workflows only)

Used only for multi-step tasks needing crash recovery and HITL approval gates. Durable state machines, checkpointing, human-in-the-loop. PostgreSQL checkpointing for crash-resilient long-running workflows.

🔍

B16: Agent Framework Landscape Review

Competitive Review Business Review Gap

The agent framework landscape is evolving rapidly (Claude Agent SDK, OpenAI Agents SDK, LangGraph, CrewAI, Google ADK). A formal quarterly review ensures we identify capabilities that outperform Praesidium2's direct-SDK approach, and adopt frameworks only when they provide clear value over our existing architecture.

Quarterly Review Cadence

QuarterReview WindowFocus AreasOutput
Q1First week of JanuaryClaude Agent SDK evolution, Anthropic SDK changes, new agent loop patternsGo/no-go decision document
Q2First week of AprilOpenAI Agents SDK, Google ADK updates, multi-agent orchestration patternsGo/no-go decision document
Q3First week of JulyLangGraph releases, CrewAI Flows/Enterprise, durable execution improvementsGo/no-go decision document
Q4First week of OctoberAnnual landscape review, pricing changes, competitive analysis across all frameworksAnnual strategy memo

Evaluation Criteria

Evaluate whether any framework offers capabilities that outperform Praesidium2's direct-SDK approach. Adopt vs. Maintain decision for each:

CapabilityOur ImplementationAdopt-If Threshold
Agent Loop / OrchestrationDirect Anthropic SDK with custom tool loopFramework provides agent loop with better error recovery, tracing, or tool handling than our ~50-line implementation
Multi-Agent CoordinationCustom turn-taking orchestrator for standups/huddlesFramework ships structured multi-agent conversations with turn management that reduces our ~300-line implementation
Durable ExecutionLangGraph checkpointing + PostgresSaverAlternative framework matches LangGraph's crash recovery + HITL with simpler dependency footprint
Tool Registryqqq-backed tool + agent_tool_assignment tablesFramework supports tenant-isolated tool registry with risk levels, versioning, and sandbox execution
Memory / Knowledgepgvector embeddings, episodic/semantic memory tablesFramework offers durable memory with vector search + TTL policies that outperforms our pgvector approach

Decision Framework

  • ✓ Adopt if upstream is ≥80% feature-complete for our use case AND reduces maintenance burden
  • ⚠ Monitor if promising but not yet production-ready or missing critical features
  • ✗ Skip if upstream approach conflicts with our architecture or multi-tenant model

Ownership

Assigned to: CTO (James Maes)

Time commitment: 4 hours per quarter

Output: Go/no-go decision document posted to Confluence under PV2 > Architecture Decisions

Distribution: Engineering team + CEO for strategic shifts

⚠ Note: This review is lightweight by design — 4 hours of reading release notes and testing, not a full architecture review. The goal is to catch "a framework now does what we built" moments early, and to evaluate whether adopting a framework would reduce maintenance burden versus our direct-SDK approach.

System ArchitectureExecutive Technical OperationsHow the 5 services connect and deploy

Service Responsibility Distribution

Each axis represents a system capability. The radar shows how much each service is involved in that capability (0 = not involved, 10 = primary owner). Notice how the three services have almost zero overlap — clean separation of concerns.

Reading the axes: Data CRUD = reading/writing the 117 database tables  |  Auth/RBAC = JWT validation, IAM policy checks, row-level security  |  AI Execution = LLM API calls, Direct SDK execution, LangGraph durable workflows  |  Real-time = SSE streaming, WebSocket broadcasts, live updates  |  Storage = S3/MinIO file operations, artifact management  |  Scheduling = cron jobs, recurring meetings, Celery Beat
qqq API — Dominates Data CRUD and Auth. The only service that touches PostgreSQL for app data. Handles all security enforcement.
Agent Gateway — Dominates Real-time and AI Execution (inline chat). The bridge between browser and agent runtime.
Agent Workers — Dominates AI Execution (complex) and Scheduling. Where direct SDK agent loops and LangGraph durable workflows run.

Service Topology

Browser — React/TypeScript SPA

Project dashboards · Agent chat · Team views · Tool forge · Standup viewer

REST + WebSocket
SSE (streaming)

qqq API (Java)

Generated REST · Liquibase migrations · Authentik auth · RBAC / RLS · Audit logging

Single source of truth for all data

Agent Gateway (Python/FastAPI)

POST /chat · POST /task/execute · POST /meeting/start · POST /forge/session · GET /stream/{id}

SSE Protocol: includes EVENT_TYPE_INTERRUPT for HITL transitions

JDBC
Redis task queue

PostgreSQL + pgvector

Entity data · Type tables · Embeddings · LangGraph checkpoints

Redis

Pub/Sub (WS) · Task queue · Session cache

Agent Workers (Python/Celery)

Direct SDK execution · LangGraph workflows · Scheduled jobs · Tool forge builds

Authentik (IdP)

OAuth2/OIDC · IAM-style policies · Group-to-role mapping

Object Storage (S3 / MinIO)

Artifacts · Tool source code · Meeting transcripts · Knowledge documents

Environment Comparison

ComponentLocal Dev (Docker Desktop k8s + Tilt)AWS (EKS)
DatabasePostgreSQL pod + pgvectorRDS PostgreSQL + pgvector
Object StorageMinIO podS3
Cache/QueueRedis podElastiCache Redis
LLM ProviderOllama pod (local models)Anthropic API
qqq APIPod (Java, Tilt hot-reload)EKS pod behind ALB
Agent GatewayPod (Python/FastAPI, Tilt hot-reload)EKS pod behind ALB
Agent WorkersPod(s) (Python/Celery, Tilt hot-reload)EKS pods — HPA autoscaled
FrontendVite dev server or Nginx podCloudFront + S3
IdentityAuthentik podAuthentik on EKS
Secretsk8s SecretsAWS Secrets Manager
TracingJaeger podDatadog APM
Dev ToolingTilt (hot-reload, log aggregation)N/A

Full local development design including Tiltfile, developer workflow, Ollama model recommendations, and self-hosted deployment guide: docs/superpowers/specs/2026-04-16-local-development-design.md

CI/CD Pipeline

1
Developer Push
git push
→
2
Lint + Test
Python, Java, TS parallel
→
3
Docker Build
qqq, gateway, worker
→
4
Push to GHCR
git SHA + env tags
→
5
Helm Values
GitOps repo update
→
6
ArgoCD Sync
EKS deployment

Pipeline: Faber CI (.faber.yml per repo) → GHCR → ArgoCD → EKS. Rollback via git revert on values file.

Per-Instance Isolation Model

Each business unit = its own Kubernetes namespace. ArgoCD ApplicationSet generates one Application per instance YAML.

tech-team.yaml

CTO's instance

hr.yaml

HR VP's instance

marketing.yaml

Digital Marketing

product.yaml

Product Development

Redis High Availability Strategy

PRODUCTION HA

Redis serves five critical functions: Celery broker, WebSocket pub/sub, session cache, rate limiting, and agent hydration cache.

Queue Cluster

Celery broker + task queue. AOF persistence enabled (appendfsync everysec). Optimized for write throughput. Task queue durability — tasks are not lost on Redis restart.

Cache Cluster

WebSocket pub/sub, session cache, rate limiting, agent hydration cache. Eviction policy: allkeys-lru. Loss degrades performance but does not lose work.

ConfigurationProduction (AWS)Local Dev
TopologyElastiCache Multi-AZ with automatic failover (<30s)Single Redis container
PersistenceAOF (appendfsync everysec) on queue clusterNone
Clusters2 separate clusters (Queue + Cache)1 shared instance
MonitoringCloudWatch: memory, eviction rate, replication lag. Alert >80% memory.N/A

Fallback When Redis Completely Unavailable

Gateway handles chat inline (no worker dispatch)
Task queue falls back to in-memory buffer (limited, 100 tasks max)
WebSocket broadcasts suspended; frontend falls back to polling qqq API every 10s
Rate limiting suspended (accept all requests)
Agent hydration cache misses force full re-hydration from qqq API

Log Aggregation

DAY-1 REQUIREMENT

Centralized logging across all 5 services. Debugging distributed issues is impractical without it.

EnvironmentLog BackendConfiguration
AWS (EKS)CloudWatch Logs (Fluent Bit DaemonSet)Log groups per service: /praesidium/qqq-api, /praesidium/gateway, /praesidium/worker, /praesidium/tool-runner, /praesidium/web
Local DevLoki + Grafana (local k8s via Tilt)All services log to stdout; Loki scrapes via Promtail

Structured JSON Format (all services)

{
  "timestamp": "2026-04-02T14:30:00Z",
  "level": "INFO",
  "service": "agent-worker",
  "correlation_id": "uuid",
  "conversation_id": "uuid",
  "job_execution_id": "uuid",
  "agent_id": "uuid",
  "message": "Task execution completed",
  "duration_ms": 1234
}

Correlation IDs: UUID generated at gateway, propagated via HTTP headers (X-Correlation-ID), Celery task kwargs, Redis pub/sub messages, and qqq API calls. All log entries include correlation_id for end-to-end request tracing.

Distributed Tracing

OPENTELEMETRY

OpenTelemetry SDK integrated into agent-gateway (FastAPI) and agent-worker (Celery) from Day 1.

Trace Backend

Production: AWS X-Ray
Local Dev: Jaeger

Propagation

W3C TraceContext headers (traceparent, tracestate) across all HTTP calls

Span Coverage

Each LLM call, qqq API call, tool execution, and Celery task is a traced span

Graceful Shutdown

SIGTERM HANDLING

Every service handles SIGTERM cleanly to avoid dropped connections and corrupted state during rolling updates.

PodSIGTERM BehaviorGrace PeriodpreStop
gateway Stop accepting → close WS (triggers reconnect) → drain SSE → wait 30s → force close 60s sleep 5
worker Signal Celery → stop consuming → finish current task → checkpoint LangGraph → ack completed → re-queue incomplete 120s None
qqq-api Spring Boot graceful shutdown: stop accepting, complete in-flight within 30s 60s None
tool-runner k8s Job TTL cleanup; active executions return timeout error 30s None
web Nginx stops accepting, drains active requests (trivially fast for static files) 10s None

Developer Experience

v1.10 — TEAM SCALE

Operational risk: a distributed team building tools and agents in parallel will diverge on patterns without enforced scaffolding. Inconsistent tool response shapes break logging, budget tracking, and error handling across the platform.

Cookiecutter Templates

Standardized scaffolding for new components:

cookiecutter-praesidium-tool — New tool with input/output schemas, test harness, risk-level declaration
cookiecutter-praesidium-agent — New agent template with system prompt, skill assignments, team membership

Templates enforce naming conventions, file structure, and required metadata fields. make new-tool and make new-agent shortcuts in the project Makefile.

Architecture Decision Records

ADR folder at docs/adr/ using the standard Nygard format:

docs/adr/0001-anthropic-sdk-langgraph-scoped.md
docs/adr/0002-qqq-as-data-layer.md
docs/adr/NNNN-template.md

New architectural decisions MUST have an ADR before implementation. ADRs are reviewed in weekly engineering syncs.

Standardized ToolResponse Wrapper

ALL tools — NATIVE, MCP, and CUSTOM — MUST return responses through this uniform wrapper. Enforces consistent logging, budget tracking, and error handling across the distributed team:

{
  "success": true,
  "data": { /* tool-specific response payload */ },
  "error": null,
  "usage": {
    "tokens": 1250,
    "cost_usd": 0.0037
  }
}

Enforcement: The tool runner validates every tool response against this schema before returning to the agent. Non-conforming responses are wrapped automatically with "success": false and the raw output placed in "error". The usage block feeds directly into activity_log.cost_usd and agent budget tracking.

Human-in-the-Loop Orchestration

HITL STATE MACHINE

Distributed state machine for agentic tasks requiring human approval. Uses LangGraph checkpoints to ensure zero state loss during multi-hour (or multi-day) wait periods. Workers can restart, scale, or crash during a pending approval without losing the agent's reasoning.

The "Interrupt" Logic (Worker Layer)

When an agent encounters a critical action, the LangGraph workflow pauses deterministically:

1. Any tool call with risk_level = 'CRITICAL' (e.g., git_merge, jira_transition, api_write) triggers an interrupt
2. Worker node calls interrupt(), which serializes the current graph state (variables, history, plan)
3. State is stored in the langgraph_checkpoints table (PostgreSQL)
4. Worker terminates the Celery task; task status → AWAITING_APPROVAL

HITL Lifecycle Flow

1
Agent Hits CRITICAL Tool
risk_level check
→
2
interrupt() Called
State serialized
→
3
AWAITING_APPROVAL
Worker terminates
→
4
Human Approves
Hash verified
→
5
Resume from Checkpoint
New worker re-hydrates

task_approval Table (NEW — Domain 3: Tasks)

Records every approval request with tamper-proof hashing. Provides a historical audit trail of WHO approved WHAT and WHEN.

CREATE TABLE task_approval (
    id                   UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    task_id              UUID NOT NULL REFERENCES task(id),
    agent_id             UUID NOT NULL REFERENCES agent(id),  -- The agent requesting approval
    action_type          VARCHAR(50) NOT NULL,                 -- 'GIT_MERGE', 'JIRA_UPDATE'
    action_payload       JSONB NOT NULL,                       -- Exact arguments shown to human
    action_payload_hash  VARCHAR(64) NOT NULL,                 -- SHA-256 for tamper-proofing
    status               VARCHAR(20) DEFAULT 'PENDING',        -- PENDING | APPROVED | REJECTED
    human_feedback       TEXT,                                  -- Reason for rejection / change
    requested_at         TIMESTAMPTZ DEFAULT now(),
    expires_at           TIMESTAMPTZ NOT NULL                   -- Default 24 hours
);

Resume Protocol (The "Wake-Up" Signal)

Bridges the asynchronous gap between the UI approval and the Worker re-entry:

1. User clicks Approve → POST /api/task/{id}/approve sent to Gateway
2. Gateway validates IAM permissions + verifies action_payload_hash unchanged
3. Updates task_approval.status to APPROVED, dispatches Resume Event to Redis with LangGraph thread_id
4. New worker picks up resume event, re-hydrates graph state from langgraph_checkpoints
5. Resumes from the exact interrupt node, executing the approved tool call

Reject path: A "Reject" action loops the agent back to the "Reasoning" node with the human's feedback injected as context. The agent re-plans without the rejected action.

SSE INTERRUPT Protocol

v1.9

When LangGraph hits interrupt(), the Gateway pushes an SSE event to the browser so the frontend can transition from “Thinking...” to “Approval Required” in real time.

Event Type: interrupt
Payload:
{
  "type": "interrupt",
  "approval_id": "uuid",
  "action_type": "GIT_MERGE",
  "action_summary": "Merge PR #42 into main",
  "risk_level": "CRITICAL",
  "agent_id": "uuid",
  "task_id": "uuid"
}
Frontend behavior: On receiving interrupt, the Chat UI replaces the ThinkingIndicator with an Approval Required card showing the action summary, diff preview, and Approve/Reject buttons.
Sequence: Worker interrupt() → writes task_approval row → publishes Redis event → Gateway SSE pushes interrupt event to browser → UI transitions to approval state.

Tamper-Proof Security (Action Hashing)

The agent MUST execute the exact action the human approved. No mutation allowed between approval and execution.

SHA-256 Hash

action_payload_hash computed at interrupt time and stored in task_approval

Gateway Verification

On approval, UI sends hash of displayed payload. Gateway compares to DB hash.

Drift Detection

Hash mismatch = "Payload Drift Detected" error. Execution blocked, escalation created.

Performance target: End-to-end resume time (from UI click to Tool start) <5 seconds. Worker pod restart during "Pending Approval" state causes zero state loss.

Conditional Autonomy Engine

v1.10 — APPROVAL FATIGUE

Operational risk: at scale, every CRITICAL tool call creates a HITL interrupt. Approval fatigue leads to rubber-stamping, which defeats the security purpose. The Conditional Autonomy Engine introduces graduated trust levels that reduce interrupt frequency for repetitive, previously-approved actions.

Autonomy Levels (1–5)

LevelNameBehavior
1Strict HITLEvery CRITICAL action requires human approval (v1 default)
2Notify-only for LOWLOW-risk auto-executes with Slack notification; MEDIUM+ still requires approval
3Fingerprint MatchAuto-approve if action_payload_hash matches a previously APPROVED action for the same Agent + Tool combination
4Budget-ScopedAuto-approve within pre-defined budget_usd ceiling per agent per day
5Full AutonomyAuto-approve within pre-defined budget_usd AND impact_scope (e.g., "only staging env")

Action Fingerprinting

Leverages the existing action_payload_hash on task_approval. At Level 3+, when a new approval request arrives, the engine queries:

SELECT id, requested_at FROM task_approval
WHERE agent_id = :agent AND action_type = :type
  AND action_payload_hash = :hash AND status = 'APPROVED'
ORDER BY requested_at DESC LIMIT 1;

If a match is found, the UI shows: "You approved this 2 hours ago. Auto-approving now..." with a 5-second countdown allowing the human to cancel.

Implementation note: Builds on the existing autonomy_level type table. The fingerprint matching logic and countdown UX are new. Level is configured per-agent via the agent table (defaults to 1). Escalation: if an auto-approved action fails, the agent is automatically downgraded to Level 1 and an escalation is created.

Authentication & AuthorizationTechnical OperationsAuthentik IAM policies, RBAC, row-level security

Authentik + qqq Pattern

Same proven pattern as me-health-portal. Authentik is the identity provider (IdP), qqq enforces all permissions server-side. No permission logic lives in application code — it is all externalized into Authentik groups and qqq RecordSecurityLock.

Authentik Group Structure

Company Groups

Set praesidiumInstanceId attribute for instance scoping

1 company group per user = 1 instance

Role Groups

Set policies JSON attribute (IAM-style permissions)

Users can belong to 1+ role groups

JWT Claims

Issued by Authentik, consumed by qqq

policies praesidiumInstanceId praesidiumAllAccess

IAM-Style Policy Format

Permissions are expressed as JSON policy documents attached to Authentik role groups. When a user belongs to multiple role groups, their policies are merged (union of all Allow statements, any Deny overrides).

{
  "PolicySpec": "praesidium-iam",
  "PolicyVersion": "1.0.0",
  "Statement": [
    {
      "Effect": "Allow",
      "Action": ["read", "insert", "edit"],
      "Resource": ["project", "task", "conversation"]
    },
    {
      "Effect": "Deny",
      "Action": ["delete"],
      "Resource": ["agent_template"]
    }
  ]
}

Multi-Role Support

Users in multiple role groups get merged policies. All Allow statements are unioned together. Any Deny statement takes precedence over conflicting Allow statements.

Admin Bypass

praesidiumAllAccess: true in JWT claims bypasses all policy checks. Reserved for instance administrators only.

Row-Level Security

All entity tables get RecordSecurityLock on instance_id, enforced by qqq at query time. Same pattern as me-health-portal's mhCompanyId.

Direct Field Lock

Tables with an instance_id column get a direct RecordSecurityLock. Every query is automatically filtered to only return rows matching the user's praesidiumInstanceId JWT claim.

Join-Based Lock

Child tables without their own instance_id use join-based locking through their parent. Example: task is locked via project.instance_id.

Worker Service Identity

SECURITY-CRITICAL

Agent-workers authenticate to the qqq API using a scoped service account JWT issued by Authentik. This is NOT an all-access admin account.

Service Account Configuration

One service account per instance, created in Authentik during provisioning
JWT includes praesidiumInstanceId claim → qqq RLS scopes all queries to the instance
praesidiumAllAccess is false — workers do NOT bypass RLS
Long expiry (24h) with proactive refresh at 80% of expiry window

Token Refresh Strategy

JWT expiry: 24 hours
Proactive refresh at 80% of expiry window (~19.2 hours)
Refresh via Authentik token endpoint
Prevents mid-task auth failures on long-running workflows

Scoped IAM Policy

{
  "PolicySpec": "praesidium-iam",
  "PolicyVersion": "1.0.0",
  "Statement": [
    { "Effect": "Allow", "Action": ["read"], "Resource": ["*"] },
    { "Effect": "Allow", "Action": ["insert", "edit"],
      "Resource": ["task", "task_comment", "message", "conversation",
                    "conversation_participant", "activity_log", "memory",
                    "job_execution", "escalation", "artifact",
                    "human_interaction", "agent_skill", "knowledge_chunk"] },
    { "Effect": "Allow", "Action": ["edit"],
      "Resource": ["agent", "scheduled_job", "conversation"] },
    { "Effect": "Deny", "Action": ["delete"],
      "Resource": ["project", "agent_template", "team_member", "integration_config"] }
  ]
}

Workers can read everything within the instance, write to operational tables (tasks, messages, memories, activity logs), and update agent execution status. Workers CANNOT delete projects, agent templates, team members, or integration configs.

Worker-to-qqq Authentication (A-007)

JWT LIFECYCLE

Service Account JWT issued by Authentik, scoped to the Agent's Instance ID. Worker presents this JWT to qqq for all hydration and CRUD operations. No direct database access — all data flows through authenticated qqq REST endpoints.

JWT Token Lifecycle

Issuance: Authentik issues short-lived JWT (15 min TTL) scoped to praesidiumInstanceId
Refresh: Automatic refresh at 80% of expiry window (~12 min). Worker background thread handles rotation.
Scope: JWT includes IAM policy limiting write access to operational tables only
Injection: Service account credentials injected via Kubernetes Secrets at pod startup

Security Guarantees

Instance isolation: qqq RLS ensures workers can only access data within their scoped instance
No all-access: praesidiumAllAccess is false — workers never bypass RLS
Audit trail: Every qqq API call from a worker is logged with the service account identity
Credential rotation: Kubernetes Secret rotation triggers pod restart for fresh credentials
1
K8s Secret
Client ID + Secret
→
2
Authentik Token
15-min JWT issued
→
3
qqq API Calls
Bearer token header
→
4
Auto Refresh
At 80% expiry

Per-Instance Isolation via Security Keys

Every API request is scoped to the user's instance. There is no way for a user to access another instance's data through the qqq API layer. The praesidiumInstanceId claim in the JWT is the security boundary.

Authentik
Identity Provider
JWT
Claims-Based Auth
qqq RLS
Row-Level Security
IAM
Policy Enforcement

Data ModelTechnicalDatabase schema, relationships, and type tables

117
Total Tables
58
Entity Tables
59
Type Tables (FK Lookups)

Domain 1: Agent Identity & Security

7 tables

Templates, agents, tool assignments, LLM providers/models, secret references, audit access log

agent_template agent agent_skill agent_tool_assignment llm_provider llm_model secret_ref audit_access_log

agent_skill relocated to Domain 9 (Skill System) in v1.12

Domain 1b: Team Identity

3 tables

Polymorphic team members (agent or human), human profiles, agent-to-human interaction logs

team_member human_profile human_interaction

Polymorphism Pattern

team_member is the base table. When member_type = AGENT, a 1:1 agent record exists. When member_type = HUMAN, a 1:1 human_profile record exists. All project assignments, conversations, and task assignments reference team_member so agents and humans are interchangeable.

Domain 2: Tools & Capabilities

4 tables

Tool registry, versions, git repos, integration configs

tool tool_version tool_repo integration_config

Domain 3: Projects & Work

6 tables

Projects, members, milestones, tasks, task comments, task approvals

project project_member milestone task task_comment task_approval

Domain 4: Conversations & Meetings

4 tables

Conversations, participants, messages, scheduled meetings

conversation conversation_participant message scheduled_meeting

Domain 5: Memory & Knowledge

3 tables

Agent memories with embeddings, knowledge docs, search chunks

memory knowledge_document knowledge_chunk

Domain 6: Operations & Observability

7 tables

Scheduled jobs, executions, escalations, artifacts, activity log, heartbeat, LangGraph checkpoints

scheduled_job job_execution escalation artifact activity_log langgraph_checkpoints scheduler_heartbeat

Domain 7: Secrets

1 table

Secret references for hierarchical credential management

secret_ref

+ 2 new type tables: secret_scope_type, secret_type

Domain 8: Business Operations

10 tables

Approvals, KPIs, ROI reports, action logs, feedback, quality scores

task_approval_queue approval_policy kpi_baseline agent_action_log

Domain 9: Skill System & Agent Composition

14 tables

Reusable skills, MCP servers, published agent profiles, fork workflow, cross-instance catalog v1.12

skill_definition skill_version agent_skill mcp_server published_agent_profile profile_fork_record

+ 3 new type tables: skill_category, mcp_server_type, skill_publish_status

Entity Tables by Domain

Table Distribution

Type Table Standard Pattern

Every type table follows the same structure — 59 tables, all with FK references. No magic strings anywhere in the system.

ColumnTypePurpose
idINT GENERATED ALWAYSPrimary key
nameVARCHAR(50) UNIQUECode key: IN_PROGRESS
labelVARCHAR(100)Display: "In Progress"
descriptionVARCHAR(500)Tooltip / help text
iconVARCHAR(50)Optional icon identifier
colorVARCHAR(7)Optional hex color
sort_orderINT DEFAULT 0Display ordering
is_activeBOOLEAN DEFAULT trueSoft-disable
is_systemBOOLEAN DEFAULT falseSeed data, can't delete
metadataJSONB DEFAULT '{}'Type-specific attributes (e.g., task_status: {is_terminal: true})
created_atTIMESTAMPTZCreation timestamp

Adding a new status/type = add a database row. The UI auto-updates with label, color, and icon. Zero code changes required.

Instance Scoping (instance_id)

SECURITY

Every root entity table includes an instance_id UUID NOT NULL column, applied automatically by qqq as part of the RecordSecurityLock configuration. This column does NOT appear in individual table definitions because it is a cross-cutting concern managed by qqq's security layer.

How It Works

1. qqq's RecordSecurityLock adds instance_id to every root entity table at schema generation time
2. The value is automatically populated from the authenticated user's JWT claim praesidiumInstanceId
3. All queries are automatically filtered by instance_id — no application code touches this column directly
4. Same pattern used in me-health-portal with mhCompanyId

Root Tables (Direct instance_id)

qqq applies RecordSecurityLock directly to these tables:

project team_member tool integration_config scheduled_meeting knowledge_document llm_provider secret_ref agent_template mcp_server

Child Tables (Join-Based Scoping)

qqq traces the FK chain to a root table's instance_id:

agent → team_member.instance_id
task → project.instance_id
message → conversation.project_id → project.instance_id
memory → team_member.instance_id
milestone → project.instance_id
conversation → project.instance_id
job_execution → scheduled_job.agent_id → team_member.instance_id

Domain 1: Agent Identity & Security (7 tables) agent_skill moved to D9

agent_template — "The job description"

PK id UUID DEFAULT gen_random_uuid()
name VARCHAR(100) NOT NULL
role_title VARCHAR(100) NOT NULL -- "Senior Software Engineer"
description TEXT
default_system_prompt TEXT NOT NULL
default_model VARCHAR(50) DEFAULT 'claude-sonnet-4-6'
personality_traits JSONB -- B20: configurable per team (see below)
FK category_id INT NOT NULL → agent_category(id)
icon VARCHAR(50)
color VARCHAR(7)
is_system BOOLEAN DEFAULT false
default_tools JSONB
created_at / updated_at TIMESTAMPTZ

agent — "The employee"

PK id UUID
FK team_member_id UUID NOT NULL UNIQUE → team_member(id)
FK template_id UUID NOT NULL → agent_template(id)
system_prompt TEXT -- overrides template
model VARCHAR(50)
config JSONB
FK execution_status_id INT NOT NULL → execution_status(id)
total_tasks_completed INT DEFAULT 0 -- CACHE: reconciled from task
total_tokens_used BIGINT DEFAULT 0 -- CACHE: reconciled from message
total_cost_usd DECIMAL(12,4) DEFAULT 0 -- CACHE: reconciled from message + activity_log
last_execution_at TIMESTAMPTZ

agent_tool_assignment — "What tools this agent can use"

PK id UUID
FK agent_id UUID NOT NULL → agent(id)
FK tool_id UUID NOT NULL → tool(id)
config JSONB
is_active BOOLEAN DEFAULT true
UNIQUE: (agent_id, tool_id)

agent_skill MOVED TO DOMAIN 9 (v1.12)

Relocated to Domain 9: Skill System & Agent Composition in v1.12. Now references skill_definition instead of raw skill_name, with version pinning and assignment tracking. See the Skill System sub-tab for the expanded schema.

A-002 — Foundation Schemas (Agent Runtime Spec)
These tables support the Agent Hydration Protocol and Blind Secret Pipeline. They enable LLM model selection, secure credential management, and access auditing.

llm_provider — "LLM vendor catalog"

PK id UUID DEFAULT gen_random_uuid()
name VARCHAR(50) NOT NULL -- 'Anthropic', 'OpenAI', 'Local-vLLM'
api_base_url VARCHAR(255)
is_active BOOLEAN DEFAULT true
metadata JSONB DEFAULT '{}' -- HIPAA tier, BAA status
created_at TIMESTAMPTZ DEFAULT now()
CREATE TABLE llm_provider (
    id            UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    name          VARCHAR(50) NOT NULL,        -- 'Anthropic', 'OpenAI', 'Local-vLLM'
    api_base_url  VARCHAR(255),
    is_active     BOOLEAN DEFAULT true,
    metadata      JSONB DEFAULT '{}',          -- HIPAA tier, BAA status
    created_at    TIMESTAMPTZ DEFAULT now()
);

llm_model — "Specific model configuration"

PK id UUID DEFAULT gen_random_uuid()
FK provider_id UUID NOT NULL → llm_provider(id)
model_name VARCHAR(100) NOT NULL -- 'claude-3-5-sonnet-20241022'
context_window INTEGER DEFAULT 128000
cost_per_1m_tokens_in DECIMAL(12,4)
cost_per_1m_tokens_out DECIMAL(12,4)
is_vision_capable BOOLEAN DEFAULT false
is_active BOOLEAN DEFAULT true
CREATE TABLE llm_model (
    id                      UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    provider_id             UUID NOT NULL REFERENCES llm_provider(id),
    model_name              VARCHAR(100) NOT NULL,
    context_window          INTEGER DEFAULT 128000,
    cost_per_1m_tokens_in   DECIMAL(12,4),
    cost_per_1m_tokens_out  DECIMAL(12,4),
    is_vision_capable       BOOLEAN DEFAULT false,
    is_active               BOOLEAN DEFAULT true
);

secret_ref — "Scoped secret references (AWS Secrets Manager)"

PK id UUID DEFAULT gen_random_uuid()
FK instance_id UUID NOT NULL -- Scoped to business unit via RLS
secret_key VARCHAR(100) NOT NULL -- e.g., 'SLACK_BOT_TOKEN'
aws_secret_arn VARCHAR(255) NOT NULL -- The ARN in AWS Secrets Manager
description TEXT
created_at TIMESTAMPTZ DEFAULT now()
CREATE TABLE secret_ref (
    id              UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    instance_id     UUID NOT NULL,               -- Scoped to business unit via RLS
    secret_key      VARCHAR(100) NOT NULL,        -- e.g., 'SLACK_BOT_TOKEN'
    aws_secret_arn  VARCHAR(255) NOT NULL,        -- The ARN in AWS Secrets Manager
    description     TEXT,
    created_at      TIMESTAMPTZ DEFAULT now()
);

audit_access_log — "Secret access and resource audit trail"

PK id UUID DEFAULT gen_random_uuid()
FK user_id UUID
FK agent_id UUID
resource_type VARCHAR(50) NOT NULL
resource_id UUID
action VARCHAR(20) NOT NULL
ip_address INET
metadata JSONB DEFAULT '{}'
created_at TIMESTAMPTZ DEFAULT now()
CREATE TABLE audit_access_log (
    id              UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    user_id         UUID,
    agent_id        UUID,
    resource_type   VARCHAR(50) NOT NULL,
    resource_id     UUID,
    action          VARCHAR(20) NOT NULL,
    ip_address      INET,
    metadata        JSONB DEFAULT '{}',
    created_at      TIMESTAMPTZ DEFAULT now()
);

Relationships

agent_template 1 → N agent • agent 1:1 team_member • agent 1 → N agent_tool_assignment • agent 1 → N agent_skill • llm_provider 1 → N llm_model • secret_ref scoped to instance via RLS • audit_access_log references user_id or agent_id

Domain 1b: Team Identity (3 tables)

team_member — "Anyone on the team"

PK id UUID
FK member_type_id INT NOT NULL → member_type(id)
name VARCHAR(100) NOT NULL
display_name VARCHAR(150)
role_title VARCHAR(100)
avatar_url VARCHAR(500)
FK status_id INT NOT NULL → member_status(id)
timezone VARCHAR(50) DEFAULT 'America/Chicago'
working_hours / contact_preferences JSONB
soul TEXT -- personality/background

human_profile — "Human-specific details"

PK id UUID
FK team_member_id UUID NOT NULL UNIQUE → team_member(id)
email, phone, department, manager_name VARCHAR
slack_user_id, jira_account_id, github_username, google_email, zoho_user_id VARCHAR -- external IDs
expertise JSONB
responsibilities, notes TEXT
notification_prefs JSONB

Polymorphism Enforcement (DB Trigger)

DATABASE-LEVEL

A PostgreSQL trigger enforces that the 1:1 relationship between team_member and its subtype tables is consistent. This is a database-level constraint, not application-level validation.

-- After INSERT on agent: verify team_member.member_type_id = AGENT and no human_profile exists
-- After INSERT on human_profile: verify team_member.member_type_id = HUMAN and no agent exists
-- After UPDATE on team_member.member_type_id: verify matching subtype row exists

Prevents: orphaned rows, contradictory data (a team_member with both agent and human_profile), and member_type mismatches.

human_interaction — "Agent→human outreach log"

PK id UUID
FK human_member_id UUID NOT NULL → team_member(id)
FK agent_member_id UUID NOT NULL → team_member(id)
FK conversation_id UUID → conversation(id)
FK task_id UUID → task(id)
FK channel_id INT NOT NULL → interaction_channel(id)
FK type_id INT NOT NULL → interaction_type(id)
message TEXT NOT NULL
FK status_id INT NOT NULL → interaction_status(id)
response TEXT
expires_at TIMESTAMPTZ

Domain 2: Tools & Capabilities (4 tables + secret_ref)

tool — "A capability an agent can invoke"

PK id UUID
name VARCHAR(100) NOT NULL UNIQUE
display_name VARCHAR(150) NOT NULL
FK category_id INT NOT NULL → tool_category(id)
input_schema / output_schema JSONB
FK repo_id UUID → tool_repo(id)
FK integration_id UUID → integration_config(id)
FK source_type_id INT NOT NULL → tool_source_type(id)
FK risk_level_id INT NOT NULL → risk_level(id)
requires_approval BOOLEAN DEFAULT false
requires_review BOOLEAN DEFAULT false -- v1.9: when true, rollback uses PR flow instead of direct action

tool_version — "Immutable snapshot of tool code"

PK id UUID
FK tool_id UUID NOT NULL → tool(id)
version_number VARCHAR(20) NOT NULL
git_sha VARCHAR(40)
entry_point VARCHAR(200) -- "module:function"
FK test_status_id INT NOT NULL → test_status(id)
test_results JSONB
UNIQUE: (tool_id, version_number)

tool_repo — "Git repository backing custom tools"

PK id UUID
name VARCHAR(100) NOT NULL
git_url VARCHAR(500) NOT NULL
FK language_id INT NOT NULL → programming_language(id)
FK sync_status_id INT NOT NULL → sync_status(id)

integration_config — "External system credentials"

PK id UUID
FK type_id INT NOT NULL → integration_type(id)
base_url VARCHAR(500)
FK auth_type_id INT NOT NULL → auth_type(id)
credentials_secret VARCHAR(200) NOT NULL
settings JSONB
FK health_status_id INT NOT NULL → health_status(id)

secret_ref — "Hierarchical credential references"

PK id UUID
FK scope_type_id INT NOT NULL → secret_scope_type(id)
FK project_id UUID → project(id) -- PROJECT scope
FK tool_id UUID → tool(id) -- TOOL scope
FK agent_id UUID → agent(id) -- AGENT scope
name VARCHAR(100)
secret_path VARCHAR(200) -- SM path or k8s ref
FK secret_type_id INT NOT NULL → secret_type(id)
expires_at TIMESTAMPTZ

Domain 3: Projects & Work (6 tables)

project

PK id UUID
name VARCHAR(150) NOT NULL
FK type_id INT NOT NULL → project_type(id)
FK status_id INT NOT NULL → project_status(id)
FK health_id INT NOT NULL → project_health(id)
FK priority_id INT NOT NULL → priority_level(id)
start_date / target_date / completed_date DATE
goals / success_criteria TEXT
external_refs JSONB -- {jira_key, confluence_space, github_repo}

project_member — "Agent or human on a project"

PK id UUID
FK project_id UUID NOT NULL → project(id)
FK team_member_id UUID NOT NULL → team_member(id)
FK role_id INT NOT NULL → project_role(id)
UNIQUE: (project_id, team_member_id)

milestone

PK id UUID
FK project_id UUID NOT NULL → project(id)
title VARCHAR(200) NOT NULL
FK status_id INT NOT NULL → milestone_status(id)
start_date / due_date DATE

task — "A unit of work"

PK id UUID
FK project_id UUID NOT NULL → project(id)
FK assignee_id UUID → team_member(id)
FK milestone_id UUID → milestone(id)
FK parent_task_id UUID → task(id) -- subtask
FK created_by_id UUID → team_member(id)
title VARCHAR(300) NOT NULL
FK type_id / status_id / priority_id INT NOT NULL → task_type / task_status / priority_level
external_ref VARCHAR(100) -- "PROJ-123" Jira key
due_date, estimated_hours, actual_hours

task_approval — "Tamper-proof HITL records" v1.9

PK id UUID
FK task_id UUID NOT NULL → task(id)
FK agent_id UUID NOT NULL → agent(id)
action_type VARCHAR(50) NOT NULL
action_payload JSONB NOT NULL
action_payload_hash VARCHAR(64) NOT NULL -- SHA-256
FK status_id INT NOT NULL → task_status(id)
human_feedback TEXT
requested_at / expires_at TIMESTAMPTZ

task_comment

PK id UUID
FK task_id UUID NOT NULL → task(id)
FK author_id UUID → team_member(id)
FK author_role_id INT NOT NULL → author_role(id)
content TEXT NOT NULL
created_at TIMESTAMPTZ DEFAULT now()

Domain 4: Conversations & Meetings (4 tables)

conversation — "Any interaction thread"

PK id UUID
FK type_id INT NOT NULL → conversation_type(id)
FK status_id INT NOT NULL → conversation_status(id)
FK project_id UUID → project(id)
FK task_id UUID → task(id)
FK scheduled_meeting_id UUID → scheduled_meeting(id)
FK parent_conversation_id UUID → conversation(id) -- thread/sub-conversation
title VARCHAR(200)
summary TEXT
action_items JSONB
total_tokens INT DEFAULT 0
total_cost_usd DECIMAL(10,4) DEFAULT 0

conversation_participant

PK id UUID
FK conversation_id UUID NOT NULL → conversation(id)
FK team_member_id UUID → team_member(id)
FK role_id INT NOT NULL → participant_role(id)
UNIQUE: (conversation_id, team_member_id)

message — "A single turn"

PK id UUID
FK conversation_id UUID NOT NULL → conversation(id)
FK author_id UUID → team_member(id)
FK role_id INT NOT NULL → message_role(id)
content TEXT NOT NULL
FK content_type_id INT NOT NULL → content_type(id)
tool_calls / thinking JSONB / TEXT
input_tokens / output_tokens / cost_usd INT / INT / DECIMAL(10,6)
model_used VARCHAR(50)
sequence_num INT NOT NULL

scheduled_meeting — "Recurring meeting definition"

PK id UUID
FK project_id UUID NOT NULL → project(id)
FK type_id INT NOT NULL → meeting_type(id)
cron_schedule VARCHAR(50) NOT NULL
participants JSONB NOT NULL
FK facilitator_member_id UUID → team_member(id)
FK status_id INT NOT NULL → schedule_status(id)
max_duration_minutes INT DEFAULT 15

Domain 5: Memory & Knowledge (3 tables)

V1.5 — Post-Launch
Tables are created at V1 (schema ships complete), but memory extraction and RAG pipeline activation is deferred to V1.5. V1 agents operate with conversation-context only.

memory — "Things an agent knows/remembers"

PK id UUID
FK owner_id UUID → team_member(id) -- null = shared/org memory
FK project_id UUID → project(id)
FK type_id INT NOT NULL → memory_type(id)
subject VARCHAR(200) NOT NULL
content TEXT NOT NULL
embedding vector(1536) -- pgvector
importance DECIMAL(3,2) DEFAULT 0.50
confidence DECIMAL(3,2) DEFAULT 1.00
source_type VARCHAR(50) -- Provenance (MESSAGE, DOCUMENT, TASK, MEETING)
source_ref_id UUID -- FK to original entity
extraction_context JSONB -- The prompt/logic used
FK source_id INT NOT NULL → memory_source(id)
IDX: USING ivfflat (embedding vector_cosine_ops)

knowledge_document — "Uploaded/indexed docs for RAG"

PK id UUID
FK project_id UUID → project(id)
title VARCHAR(300) NOT NULL
FK source_type_id INT NOT NULL → document_source_type(id)
storage_key VARCHAR(500)
FK index_status_id INT NOT NULL → index_status(id)
auto_refresh BOOLEAN DEFAULT false

knowledge_chunk — "Searchable piece of a document"

PK id UUID
FK document_id UUID NOT NULL → knowledge_document(id)
content TEXT NOT NULL
embedding vector(1536) NOT NULL -- pgvector
chunk_index INT NOT NULL
token_count INT
IDX: USING ivfflat (embedding vector_cosine_ops)

Memory Hygiene

v1.10 DESIGN NOTE — V1.5 SCOPE

Operational risk: without active memory management, the memory table accumulates stale, redundant, and contradictory facts. Cosine similarity searches return noisy results, degrading agent reasoning quality over time. This design note documents the hygiene architecture that applies when the V1.5 memory pipeline activates.

Tiered Memory Architecture

TierNameStorageLifecycle
1EphemeralIn-context window (last 20 messages)Evicted when conversation window scrolls; never persisted beyond message table
2Vectormemory table with pgvector embeddingsExtracted from conversations/tasks; decays via recency_weight; merged by Janitor job
3ConsolidatedKnowledge graph summaries in memory (type = CONSOLIDATED)Generated by background LLM job; long-lived "Master Facts" that survive merges

Schema Additions — memory

Two new columns ship in V1 (schema ready) even though the hygiene pipeline activates in V1.5:

ALTER TABLE memory ADD COLUMN recency_weight  DECIMAL(5,4) DEFAULT 1.0;  -- decays daily toward 0
ALTER TABLE memory ADD COLUMN importance      DECIMAL(3,2) DEFAULT 0.50; -- lockable to 1.0 by humans

importance can be locked to 1.0 by humans via a UI "Star" action on the Agent Memory panel. Starred memories are exempt from decay and merge operations. The existing importance column in the schema is reused (already DECIMAL(3,2) DEFAULT 0.50); recency_weight is new.

Nightly "Janitor" Job

A Celery Beat scheduled job that runs nightly to maintain memory quality:

1. Decay: Reduce recency_weight by 5% for all non-starred memories older than 7 days
2. Detect duplicates: Find memory pairs with cosine similarity > 0.95 within the same owner scope
3. Merge: Send duplicate pairs to an LLM with prompt: "Merge these two facts into a single, accurate Master Fact." Store the merged result as a Tier 3 CONSOLIDATED memory
4. Delete: Soft-delete the original redundant rows (source memories point to the merged memory via source_ref_id)
5. Prune: Hard-delete memories where recency_weight < 0.05 AND importance < 0.3 AND not starred

Note: This is V1.5 scope but the schema columns ship in V1 so the database is ready. The Janitor job is registered in scheduled_job but set to is_active = false until V1.5 activation.

Domain 6: Operations & Observability (7 tables)

scheduled_job — "Recurring agent work" v1.9

PK id UUID
FK instance_id UUID NOT NULL → instance(id)
FK agent_id UUID NOT NULL → agent(id)
FK project_id UUID → project(id)
name VARCHAR(150) NOT NULL
description VARCHAR(500)
cron_schedule VARCHAR(50) NOT NULL
FK tool_id UUID → tool(id) -- which tool to execute
tool_params JSONB DEFAULT '{}' -- arguments for the tool
is_active BOOLEAN DEFAULT true
last_run_at TIMESTAMPTZ
next_run_at TIMESTAMPTZ
last_run_status VARCHAR(20) -- SUCCESS, FAILED, TIMEOUT
max_tokens INT DEFAULT 4096
max_budget_usd DECIMAL(8,2)
FK status_id INT NOT NULL → job_status(id)
consecutive_failures INT DEFAULT 0
max_retries INT DEFAULT 3
FK created_by UUID → team_member(id) -- user who set it up
created_at / updated_at TIMESTAMPTZ

Celery Beat reads from this table on each heartbeat cycle. When a user creates, edits, or disables a schedule in the UI, Celery Beat picks it up automatically on the next heartbeat (ties into G-002 scheduler_heartbeat HA mechanism). next_run_at is computed from cron_schedule after each execution.

job_execution — "One run of a scheduled job"

PK id UUID
FK job_id UUID NOT NULL → scheduled_job(id)
FK conversation_id UUID → conversation(id)
FK status_id INT NOT NULL → job_execution_status(id)
FK trigger_type_id INT NOT NULL → trigger_type(id)
input_tokens / output_tokens / cost_usd
revert_payload JSONB -- Arguments for "undo". For Git, includes: { "pr_title": "[Praesidium-Rollback] ...", "target_branch": "...", "original_commit": "...", "task_ref": "..." }
FK revert_tool_id UUID → tool(id) -- rollback tool
FK retry_of UUID → job_execution(id) -- self-ref

escalation

PK id UUID
FK raised_by_id UUID NOT NULL → team_member(id)
FK project_id / task_id / conversation_id UUID (nullable)
title VARCHAR(300) NOT NULL
FK severity_id INT NOT NULL → priority_level(id)
FK status_id INT NOT NULL → escalation_status(id)

artifact — "Files produced by agents"

PK id UUID
FK created_by_id / task_id / conversation_id / project_id
name VARCHAR(300) NOT NULL
storage_key VARCHAR(500) NOT NULL
mime_type VARCHAR(100) NOT NULL
FK type_id INT NOT NULL → artifact_type(id)

activity_log — "Immutable audit trail"

PK id UUID
FK actor_id UUID → team_member(id)
FK project_id UUID → project(id)
FK actor_type_id INT NOT NULL → author_role(id)
action VARCHAR(50) NOT NULL
resource_type / resource_id VARCHAR(30) / UUID
input_tokens / output_tokens / cost_usd / duration_ms

langgraph_checkpoints — "Agent state persistence" v1.9

PK thread_id VARCHAR(255)
PK checkpoint_id VARCHAR(255)
checkpoint JSONB NOT NULL
metadata JSONB DEFAULT '{}'
created_at TIMESTAMPTZ DEFAULT now()

Persistence layer for LangGraph state machines. Enables agents to pause for approval, survive worker restarts, and maintain memory across complex multi-step reasoning loops. Maps to PostgresSaver in LangGraph.

scheduler_heartbeat — "Celery Beat HA leader tracking" v1.9

PK id UUID DEFAULT gen_random_uuid()
node_id VARCHAR(100) NOT NULL
last_heartbeat TIMESTAMPTZ NOT NULL DEFAULT now()
is_leader BOOLEAN DEFAULT false
metadata JSONB DEFAULT '{}'

Active Celery Beat leader updates last_heartbeat every 30s. Secondary nodes monitor; if now() - last_heartbeat > 60s, secondary takes over leadership. Prevents split-brain or dead-lock in scheduled tasks.

Domain 8: Business Operations (10 tables) v1.9

Tables supporting HITL approvals, KPI measurement, ROI reporting, and agent performance management.

task_approval_queue

PK id UUID
FK task_approval_id UUID NOT NULL → task_approval(id)
FK priority_id INT NOT NULL → priority_level(id)
is_escalated BOOLEAN DEFAULT false

approval_policy

PK id UUID
FK tool_id UUID → tool(id)
FK risk_level_id INT NOT NULL → risk_level(id)
auto_approve_threshold DECIMAL(3,2)

kpi_baseline

PK id UUID
metric_name VARCHAR(100) NOT NULL
baseline_value DECIMAL(12,2)
unit VARCHAR(20)

kpi_measurement

PK id UUID
FK baseline_id UUID → kpi_baseline(id)
current_value DECIMAL(12,2)
measured_at TIMESTAMPTZ DEFAULT now()

agent_action_log

PK id UUID
FK execution_id UUID NOT NULL → job_execution(id)
before_state / after_state JSONB
mutation_type VARCHAR(50)

rollback_record

PK id UUID
FK original_execution_id UUID NOT NULL
FK rollback_execution_id UUID NOT NULL
success BOOLEAN

output_feedback

PK id UUID
FK message_id UUID NOT NULL → message(id)
rating INT -- 1-5
comment TEXT

agent_quality_score

PK id UUID
FK agent_id UUID NOT NULL → agent(id)
score DECIMAL(3,2)
computed_at TIMESTAMPTZ DEFAULT now()

autonomy_level

PK id UUID
FK agent_id UUID NOT NULL → agent(id)
level INT -- 1-5
granted_at TIMESTAMPTZ

team_roi_report

PK id UUID
report_month DATE
hours_saved DECIMAL(10,2)
cost_savings_usd DECIMAL(12,2)

Domain 9: Skill System & Agent Composition (14 tables) v1.12

Reusable procedural knowledge (skills), MCP server management, published agent profiles, and the company-wide catalog. Skills are versioned SOPs that agents learn; profiles are shareable agent configurations that can be forked into new agents.

Skills — Reusable Procedural Knowledge
Skills are versioned SOPs (Standard Operating Procedures) that agents learn. Each skill has immutable version snapshots with instructions, guardrails, examples, and tool/MCP requirements.

skill_definition — "Reusable procedural knowledge (SOP)"

PK id UUID DEFAULT gen_random_uuid()
name VARCHAR(150) NOT NULL
description TEXT NOT NULL
FK category_id INT NOT NULL → skill_category(id)
current_version VARCHAR(20) -- CACHE: latest published version
FK publish_status_id INT NOT NULL → skill_publish_status(id)
FK created_by_instance_id UUID -- provenance: authoring instance
FK created_by_id UUID → team_member(id)
icon VARCHAR(50)
tags JSONB -- ["wms", "inventory", "operations"]
is_active BOOLEAN DEFAULT true
created_at / updated_at TIMESTAMPTZ
IDX: (category_id), (publish_status_id), (is_active), (tags)

skill_version — "Immutable snapshot of a skill"

PK id UUID DEFAULT gen_random_uuid()
FK skill_definition_id UUID NOT NULL → skill_definition(id) CASCADE
version_number VARCHAR(20) NOT NULL -- semver: "1.0.0"
instructions TEXT NOT NULL -- the full SOP
guardrails TEXT -- what NOT to do
examples JSONB -- [{user, agent, tool_calls}]
changelog TEXT
FK published_by UUID → team_member(id)
published_at TIMESTAMPTZ DEFAULT now()
UNIQUE: (skill_definition_id, version_number)
IDX: (skill_definition_id), (published_at DESC)

skill_tool_requirement — "Tools a skill version needs"

PK id UUID DEFAULT gen_random_uuid()
FK skill_version_id UUID NOT NULL → skill_version(id) CASCADE
FK tool_id UUID NOT NULL → tool(id) CASCADE
is_required BOOLEAN DEFAULT true
usage_notes TEXT
UNIQUE: (skill_version_id, tool_id)
IDX: (skill_version_id), (tool_id)

skill_mcp_requirement — "MCP servers a skill version needs"

PK id UUID DEFAULT gen_random_uuid()
FK skill_version_id UUID NOT NULL → skill_version(id) CASCADE
FK mcp_server_id UUID NOT NULL → mcp_server(id) CASCADE
is_required BOOLEAN DEFAULT true
usage_notes TEXT
UNIQUE: (skill_version_id, mcp_server_id)
IDX: (skill_version_id), (mcp_server_id)
Agent Skill Assignment & Proficiency
agent_skill relocated from Domain 1 and expanded in v1.12. agent_skill_proficiency tracks learning history and persists across unassignment/reassignment cycles.

agent_skill — "Which skills an agent is trained on" relocated from D1

PK id UUID DEFAULT gen_random_uuid()
FK agent_id UUID NOT NULL → agent(id) CASCADE
FK skill_definition_id UUID NOT NULL → skill_definition(id)
FK pinned_version_id UUID → skill_version(id) -- null = use current_version
is_active BOOLEAN DEFAULT true
FK assigned_by UUID → team_member(id)
assigned_at TIMESTAMPTZ DEFAULT now()
UNIQUE: (agent_id, skill_definition_id)
IDX: (agent_id), (skill_definition_id), (pinned_version_id), (is_active)

agent_skill_proficiency — "How well an agent performs each skill"

PK id UUID DEFAULT gen_random_uuid()
FK agent_id UUID NOT NULL → agent(id) CASCADE
FK skill_definition_id UUID NOT NULL → skill_definition(id)
proficiency DECIMAL(3,2) DEFAULT 0.50 -- 0.00-1.00
times_used INT DEFAULT 0
last_used_at TIMESTAMPTZ
FK endorsed_by_id INT → endorsement_source(id)
UNIQUE: (agent_id, skill_definition_id)
IDX: (agent_id), (skill_definition_id), (proficiency DESC)

Proficiency records are system-managed and never deleted — they persist across skill unassignment. When a skill is later reassigned, proficiency picks up where it left off.

MCP Server Management
MCP (Model Context Protocol) servers provide agents with external tool access. Each instance configures its own server connections. Agents are assigned to specific servers.

mcp_server — "A configured MCP server connection"

PK id UUID DEFAULT gen_random_uuid()
name VARCHAR(100) NOT NULL
description TEXT
FK server_type_id INT NOT NULL → mcp_server_type(id)
connection_config JSONB NOT NULL -- {command, args, env} or {url, headers}
FK credentials_id UUID → secret_ref(id)
FK health_status_id INT NOT NULL → health_status(id)
last_health_check TIMESTAMPTZ
discovered_tools JSONB -- CACHE: refreshed on health check
is_active BOOLEAN DEFAULT true
IDX: (server_type_id), (health_status_id), (is_active)

agent_mcp_assignment — "Which MCP servers an agent connects to"

PK id UUID DEFAULT gen_random_uuid()
FK agent_id UUID NOT NULL → agent(id) CASCADE
FK mcp_server_id UUID NOT NULL → mcp_server(id) CASCADE
config_overrides JSONB -- per-agent config tweaks
is_active BOOLEAN DEFAULT true
FK assigned_by UUID → team_member(id)
assigned_at TIMESTAMPTZ DEFAULT now()
UNIQUE: (agent_id, mcp_server_id)
IDX: (agent_id), (mcp_server_id)
Published Agent Profiles & Fork Workflow
Company-wide shareable agent templates. Profiles bundle a suggested personality, skills, MCP configs, and tools. Other instances fork profiles to create new agents pre-configured with the profile's setup.

published_agent_profile — "Company-wide shareable agent template"

PK id UUID DEFAULT gen_random_uuid()
name VARCHAR(150) NOT NULL
description TEXT NOT NULL
current_version VARCHAR(20) -- CACHE: latest published version
soul TEXT -- suggested personality
role_title VARCHAR(100)
job_description TEXT
personality_traits JSONB
FK default_model_id UUID → llm_model(id)
FK category_id INT NOT NULL → agent_category(id)
icon VARCHAR(50)
tags JSONB
FK publish_status_id INT NOT NULL → skill_publish_status(id)
FK created_by_instance_id UUID
FK created_by_id UUID → team_member(id)
IDX: (category_id), (publish_status_id), (tags)

published_agent_profile_version — "Immutable profile snapshot"

PK id UUID DEFAULT gen_random_uuid()
FK profile_id UUID NOT NULL → published_agent_profile(id) CASCADE
version_number VARCHAR(20) NOT NULL
soul TEXT
role_title VARCHAR(100)
job_description TEXT
personality_traits JSONB
FK default_model_id UUID → llm_model(id)
changelog TEXT
FK published_by UUID → team_member(id)
published_at TIMESTAMPTZ DEFAULT now()
UNIQUE: (profile_id, version_number)
IDX: (profile_id), (published_at DESC)

profile_skill_assignment — "Skills included in a published profile"

PK id UUID DEFAULT gen_random_uuid()
FK profile_version_id UUID NOT NULL → published_agent_profile_version(id) CASCADE
FK skill_definition_id UUID NOT NULL → skill_definition(id)
FK pinned_version_id UUID → skill_version(id)
UNIQUE: (profile_version_id, skill_definition_id)
IDX: (profile_version_id), (skill_definition_id)

profile_mcp_configuration — "MCP server configs in a profile"

PK id UUID DEFAULT gen_random_uuid()
FK profile_version_id UUID NOT NULL → published_agent_profile_version(id) CASCADE
FK server_type_id INT NOT NULL → mcp_server_type(id)
connection_template JSONB -- template config (credentials added on fork)
description TEXT
UNIQUE: (profile_version_id, server_type_id)
IDX: (profile_version_id)

profile_tool_assignment — "Direct (freestyle) tools in a profile"

PK id UUID DEFAULT gen_random_uuid()
FK profile_version_id UUID NOT NULL → published_agent_profile_version(id) CASCADE
FK tool_id UUID NOT NULL → tool(id) CASCADE
is_required BOOLEAN DEFAULT true
UNIQUE: (profile_version_id, tool_id)
IDX: (profile_version_id), (tool_id)

profile_fork_record — "Tracks agent forks from profiles"

PK id UUID DEFAULT gen_random_uuid()
FK source_profile_id UUID NOT NULL → published_agent_profile(id)
FK source_version_id UUID NOT NULL → published_agent_profile_version(id)
FK target_agent_id UUID NOT NULL → agent(id) CASCADE
FK forked_by UUID NOT NULL → team_member(id)
forked_at TIMESTAMPTZ DEFAULT now()
IDX: (source_profile_id), (source_version_id), (target_agent_id)

Cross-Instance Scoping Rules

PublishScopeSecurityLock

Tables using publish-based visibility (skill_definition, published_agent_profile) use a custom PublishScopeSecurityLock instead of the standard RecordSecurityLock.

StatusCreating InstanceOther Instances
DRAFTFull CRUDNot visible
PUBLISHEDFull CRUDRead-only
DEPRECATEDFull CRUDRead-only (with warning)
ARCHIVEDRead-only (admin)Not visible

Instance Scoping by Table

Publish-based: skill_definition, published_agent_profile
Inherits from parent: skill_version, skill_tool_requirement, skill_mcp_requirement, published_agent_profile_version, profile_skill_assignment, profile_mcp_configuration, profile_tool_assignment
Instance-scoped (root): mcp_server
Instance-scoped (via agent): agent_skill, agent_skill_proficiency, agent_mcp_assignment, profile_fork_record

Deprecation Cascade

1. All agent_skill records across instances are flagged via system notification
2. Agents with pinned_version_id set continue normally (immutable snapshot)
3. Agents using current_version receive a system warning in next hydration
4. Creating instance SHOULD publish a replacement before deprecating

Skill Hydration & Conflict Resolution

When an agent is hydrated for execution, the runtime resolves each agent_skill to a concrete skill_version:

1. If pinned_version_id is set → use that specific version (immutable)
2. If pinned_version_id is NULL → resolve via skill_definition.current_version
3. Load skill_version.instructions + guardrails into the agent's system prompt
4. Verify all skill_tool_requirement tools are available to the agent
5. Verify all skill_mcp_requirement MCP servers are connected and healthy
6. Missing requirements generate warnings (not failures) — agent proceeds with available tools

Fork Workflow (End-to-End)

When a Super Operator clicks "Fork" on a published agent profile:

1
Select Version
Pick from profile versions
→
2
Customize
Edit soul, role, model
→
3
Review Skills
Toggle on/off, check reqs
→
4
Configure MCP
Match server types
→
5
Review Tools
Confirm tool assignments
→
6
Create
Single transaction
→
7
Verify
Activate agent

Create Transaction (Step 6)

• team_member (member_type=AGENT, name, soul, role_title from form)
• agent (template_id from category, job_description, model_id from form)
• agent_skill records for each selected skill (pinned to profile's versions)
• agent_mcp_assignment records for each configured MCP server
• agent_tool_assignment records for each selected tool
• profile_fork_record (source_profile_id, source_version_id, target_agent_id)

Key Relationships

skill_definition 1 → N skill_version • skill_version 1 → N skill_tool_requirement • skill_version 1 → N skill_mcp_requirement
agent 1 → N agent_skill ← N skill_definition (M:N) • agent 1 → N agent_skill_proficiency (persists across unassignment)
agent 1 → N agent_mcp_assignment ← N mcp_server (M:N) • mcp_server N → 1 secret_ref
published_agent_profile 1 → N published_agent_profile_version
published_agent_profile_version 1 → N profile_skill_assignment / profile_mcp_configuration / profile_tool_assignment
published_agent_profile 1 → N profile_fork_record → 1 agent

Type Tables (59 total)

All 59 type tables follow the same pattern. Adding a new status/type is a database row insert — zero code changes.

Standard Type Table Schema

PK id INT GENERATED ALWAYS AS IDENTITY
name VARCHAR(50) UNIQUE -- code key: IN_PROGRESS
label VARCHAR(100) -- display: "In Progress"
description VARCHAR(500)
icon VARCHAR(50)
color VARCHAR(7)
sort_order INT DEFAULT 0
is_active BOOLEAN DEFAULT true
is_system BOOLEAN DEFAULT false
metadata JSONB DEFAULT '{}' -- type-specific attributes (e.g., task_status: {is_terminal: true})
created_at TIMESTAMPTZ
Type TableUsed BySeed Values
member_typeteam_member.member_typeAGENT, HUMAN
member_statusteam_member.statusACTIVE, AWAY, OFFLINE, SUSPENDED
agent_categoryagent_template.categoryENGINEERING, HR, OPS, FINANCE, MARKETING, PRODUCT, SUPPORT, CUSTOM
execution_statusagent.execution_statusIDLE, EXECUTING, QUEUED, ERROR
tool_categorytool.categoryPLATFORM, INTEGRATION, CUSTOM, MCP
tool_source_typetool.source_typeBUILTIN, FORGED, IMPORTED
risk_leveltool.risk_levelLOW, MEDIUM, HIGH, CRITICAL
test_statustool_version.test_statusPENDING, RUNNING, PASSED, FAILED
programming_languagetool_repo.languagePYTHON, TYPESCRIPT, JAVA, GO, SHELL
sync_statustool_repo, taskSYNCED, PENDING, SYNCING, ERROR
integration_typeintegration_config.typeZOHO_CRM, JIRA, CONFLUENCE, SLACK, GITHUB, GOOGLE_WORKSPACE, CUSTOM_API
auth_typeintegration_config.auth_typeAPI_KEY, OAUTH2, BASIC, BEARER, SERVICE_ACCOUNT
health_statusintegration_config.healthHEALTHY, DEGRADED, DOWN, UNKNOWN
project_typeproject.typeSHORT_TERM, ONGOING, SUPPORT, INITIATIVE
project_statusproject.statusPLANNING, ACTIVE, ON_HOLD, COMPLETED, ARCHIVED
project_healthproject.healthON_TRACK, AT_RISK, BEHIND, BLOCKED
priority_levelproject, task, escalationLOW, MEDIUM, HIGH, CRITICAL
project_roleproject_member.roleLEAD, MEMBER, REVIEWER, OBSERVER
milestone_statusmilestone.statusNOT_STARTED, IN_PROGRESS, COMPLETED, BLOCKED
task_typetask.typeTASK, BUG, STORY, SPIKE, REVIEW
task_statustask.statusOPEN, APPROVED, IN_PROGRESS, IN_REVIEW, DONE, BLOCKED, DISMISSED
author_roletask_comment, activity_logAGENT, HUMAN, SYSTEM
conversation_typeconversation.typeCHAT, STANDUP, HUDDLE, TASK_EXEC, FORGE, REVIEW
conversation_statusconversation.statusACTIVE, PAUSED, COMPLETED, FAILED
participant_roleconversation_participantFACILITATOR, PARTICIPANT, OBSERVER, SCRIBE
message_rolemessage.roleUSER, ASSISTANT, SYSTEM, TOOL_RESULT
content_typemessage.content_typeTEXT, MARKDOWN, JSON, IMAGE_REF, CODE
meeting_typescheduled_meeting.typeSTANDUP, HUDDLE, RETROSPECTIVE, PLANNING, REVIEW
memory_typememory.typeFACT, PREFERENCE, LESSON_LEARNED, ENTITY, DECISION, PROCEDURE
memory_sourcememory.sourceCONVERSATION, TASK, MEETING, MANUAL, SYSTEM
document_source_typeknowledge_documentUPLOAD, CONFLUENCE, URL, GIT_REPO
index_statusknowledge_documentPENDING, INDEXING, INDEXED, FAILED
job_statusscheduled_job.statusACTIVE, PAUSED, COMPLETED, FAILED
job_execution_statusjob_execution.statusRUNNING, SUCCESS, FAILED, TIMEOUT, CANCELLED
trigger_typejob_executionCRON, MANUAL, RETRY, EVENT
escalation_statusescalation.statusOPEN, ACKNOWLEDGED, RESOLVED, DISMISSED
artifact_typeartifact.typeFILE, REPORT, CODE, IMAGE, DATA
interaction_channelhuman_interactionSLACK, JIRA_COMMENT, JIRA_ASSIGN, CONFLUENCE, EMAIL
interaction_typehuman_interactionQUESTION, TASK_ASSIGN, STATUS_UPDATE, ESCALATION, REVIEW_REQUEST, INFO_REQUEST
interaction_statushuman_interactionSENT, DELIVERED, SEEN, RESPONDED, EXPIRED, FAILED
schedule_statusscheduled_meetingACTIVE, PAUSED, ARCHIVED
secret_scope_typesecret_ref.scope_typeINSTANCE, PROJECT, TOOL, AGENT
secret_typesecret_ref.secret_typeAPI_KEY, OAUTH2_TOKEN, SSH_KEY, WEBHOOK_SECRET, DATABASE_URL
llm_provider_typellm_provider.typeCLOUD_API, LOCAL, SELF_HOSTED, BEDROCK, VERTEX
llm_capability_tierllm_model.capability_tierFLAGSHIP, STANDARD, FAST, ECONOMY
autonomy_statusautonomy_level.statusREQUESTED, GRANTED, REVOKED, SUSPENDED
feedback_typeoutput_feedback.typeUX, ACCURACY, SPEED, TONE, TOOL_USE
skill_category v1.12skill_definition.categoryENGINEERING, OPERATIONS, FINANCE, HR, MARKETING, PRODUCT, SUPPORT, ADMINISTRATION, ANALYTICS, CUSTOM
mcp_server_type v1.12mcp_server.server_typeSTDIO, HTTP, SSE
skill_publish_status v1.12skill_definition.publish_status, published_agent_profile.publish_statusDRAFT, PUBLISHED, DEPRECATED, ARCHIVED

Agent RuntimeTechnicalHow agents execute — pods, queues, workflows

A

Direct SDK Execution

Standard Agent Execution

Handles 60–70% of all agent execution — 1:1 chat, simple tasks, standups/huddles. Direct Anthropic SDK calls with full control over prompting and tool execution. No framework translation overhead.

Agent Hydration Flow

1. Load agent record + template + team_member from qqq API
2. Load tool assignments, resolve to tool definitions (input_schema, description)
3. Load recent memories via pgvector semantic search
4. Load skills for context
5. Build system prompt = template default + overrides + soul + skills + memories
6. Call Anthropic SDK directly with system prompt, tools, and conversation history
L

LangGraph

Durable Workflows

Handles "HOW complex work flows" — durable state machines, checkpointing, human-in-the-loop. PostgreSQL checkpointing for crash resilience.

Scoped usage: Used only for durable workflows requiring crash recovery or HITL approval gates. Standard chat, simple tasks, and standups use direct SDK calls.

SSE Interrupt Protocol v1.9

When a graph hits an interrupt() node (e.g., for Critical tools), the Gateway emits EVENT_TYPE_INTERRUPT. React 19 UI detects this instantly, switching from "Thinking" animation to "Approval Required" card with full action context.

Used When

● Work could take >30 seconds
● Needs human-in-the-loop approval
● Must survive worker crashes
● Has branching/retry logic

Thread IDs map to conversation.id. Checkpoint state lives in PostgreSQL alongside qqq's schema.

Execution Patterns

TriggerPatternFrameworkDetails
1:1 Chat Inline SSE streaming Anthropic SDK Direct API call with tools, SSE streaming
Task Execution Direct SDK agent loop Anthropic SDK Load context, call LLM, execute tools, iterate
Standup / Huddle Turn-taking orchestrator Anthropic SDK Facilitator + participants, structured dialogue
Scheduled Job Direct SDK (simple) / State graph (complex) Anthropic SDK / LangGraph Simple: direct SDK. Complex/long-running: LangGraph with checkpointing
Tool Forge State graph LangGraph Design → code → test → review → publish
Multi-Step Project State graph + parallel SDK calls LangGraph + Anthropic SDK Subtask decomposition + parallel execution
V1.5 — Post-Launch (4–6 weeks)
Deferred to V1.5. V1 agents operate with conversation-context only. Memory extraction, pgvector embeddings, and RAG-based knowledge retrieval are added after 4–6 weeks of stable agent execution.

Memory System Flow

⚙
Agent Work
Completes task
→
🔎
Extract
Claude-powered analysis
→
⇌
Embed
text-embedding-3-small
→
≠
Dedupe
cosine > 0.92 = merge
→
💾
Store
qqq API → pgvector
→
💡
Recall
Semantic search + inject

On next hydration: semantic search with task/conversation context, recency bias + importance filter, inject top-K memories into system prompt.

Tool Safety — Risk-Level Behavior

Risk LevelBehaviorExample
LOW Execute immediately Read operations, search queries
MEDIUM Execute + log to activity_log Write operations, data updates
HIGH Execute + log + notify human via Slack External API calls, deletions
CRITICAL Create human_interaction, wait for approval Deployments, financial transactions

Prompt Injection Defense

DEFENSE-IN-DEPTH

Agent-processed user content (task descriptions, Slack messages, Jira comments, knowledge documents) could contain adversarial instructions. Five defense layers:

1. Input Sanitization

All tool input_schema fields validated against JSON Schema at gateway/worker BEFORE the LLM processes them. User text wrapped with <user_content> delimiters; system prompts instruct the LLM to ignore directives within user content.

2. Output Validation

Tool results marked with message_role = TOOL_RESULT (treated as data, not instructions). Results validated against output_schema; unexpected or oversized fields are truncated with a warning.

3. Sandboxed Execution

CUSTOM tools run in network-isolated k8s pods. Even if prompt injection tricks an agent into crafting malicious inputs, the sandbox limits blast radius. MCP tools default to HIGH risk level.

4. CRITICAL Tool Guards

CRITICAL-risk tools require human approval regardless of prompt content. Approval shows full tool input for review. All CRITICAL invocations log complete input/output to activity_log.

5. Per-Agent Per-Tool Rate Limits

Each agent has a per-tool call limit (configurable, default: 10 calls/minute/tool per agent). Prevents a compromised agent from calling a tool in a tight loop.

Data Flow: Runtime → qqq

API PATTERNS

All state changes from the agent runtime go through qqq REST APIs. These are the API call patterns for each execution type:

Triggerqqq API Call Sequence
Chat POST /message → POST /memory → PATCH /agent (tokens, last_active)
Task Execution PATCH /task (IN_PROGRESS) → POST /conversation → POST /message (each turn) → POST /task_comment → PATCH /task (DONE) → POST /memory → POST /activity_log
Meeting POST /conversation (STANDUP) → POST /conversation_participant → POST /message → PATCH /conversation (summary) → POST /task (action items) → POST /human_interaction (Slack)
Scheduled Job POST /job_execution (RUNNING) → POST /conversation → [work] → PATCH /job_execution → PATCH /scheduled_job (last_run_at, next_run_at, last_run_status)
Manual Run-Now POST /scheduled_job/{id}/run-now → POST /job_execution (trigger_type=MANUAL) → POST /conversation → [work] → PATCH /job_execution → PATCH /scheduled_job
Tool Call POST /activity_log → [if HIGH+] POST /human_interaction → [execute] → POST /activity_log (result)

Celery Queue Configuration

3 QUEUES

Task-type-specific queues with tuned visibility timeouts to prevent duplicate execution of long-running tasks:

QueueVisibility TimeoutTask TypesAcks Late
quick 300s (5 min) extract_memories, index_document, chat background work No
standard 3600s (1 hour) execute_task, run_meeting, execute_job (simple) Yes
long 7200s (2 hours) forge_session, complex LangGraph workflows, project planning Yes

acks_late=True

On standard and long queues, tasks are acknowledged only after completion, not when picked up. Combined with LangGraph checkpointing, this ensures tasks are not lost on worker crash.

Idempotency Guards

LangGraph tasks check for existing checkpoints before re-executing a node. If a task is re-delivered (visibility timeout edge case), it resumes from the last checkpoint rather than restarting.

Workers subscribe to all three queues. Routing is determined at dispatch time by the gateway based on task type.

Batch / Composite qqq Endpoints

PERFORMANCE

To reduce HTTP round-trip overhead (a single task execution generates 10-20 REST calls), qqq exposes composite endpoints using its include query parameter. No custom API code needed — qqq resolves joins from ERD relationships.

EndpointReturnsReplaces
GET /agent/{id}/hydration Agent + template + tools + skills + recent memories (top 50) 5 separate GET calls
GET /project/{id}/dashboard Project + milestones + team + recent tasks (top 20) + active conversations 5 separate GET calls
GET /conversation/{id}/full Conversation + participants + messages (paginated) + linked task 3 separate GET calls

Agent Hydration Protocol — The Manifest

SINGLE ENDPOINT

To minimize latency and prevent logic drift, the Worker hydrates 100% of its state through a single composite endpoint. This replaces the multi-call hydration flow described above with an atomic, internally-scoped API call.

Endpoint

GET /api/internal/worker/hydrate/{agent_id}
Returns complete AGENT_MANIFEST JSON in a single response
Replaces 5+ separate qqq API calls with one internal call

Authentication

Service Account JWT issued by Authentik
Scoped to the Agent's instance_id — RLS enforced
Internal-only — not exposed via public ALB ingress

AGENT_MANIFEST Response Structure

{
  "agent": {
    "id": "uuid",
    "name": "Forge Agent",
    "persona": "Senior DevOps Engineer...",
    "instance_id": "uuid-123"
  },
  "config": {
    "primary_model": {
      "name": "claude-3-5-sonnet",
      "provider_url": "https://api.anthropic.com",
      "context_window": 128000
    },
    "fallback_model": { "name": "gpt-4o" }
  },
  "secrets": [
    { "key": "GITHUB_TOKEN", "arn": "arn:aws:secretsmanager:us-east-1:..." },
    { "key": "JIRA_API_KEY", "arn": "arn:aws:secretsmanager:us-east-1:..." }
  ],
  "tools": [
    { "id": "uuid", "name": "git_commit", "risk_level": "CRITICAL" }
  ]
}

Key design choice: Secrets in the manifest are ARNs only — never plain-text values. The Worker pod fetches actual secrets directly from AWS Secrets Manager using IRSA (see Blind Secret Pipeline below).

“Blind” Secret Pipeline

SECURITY-CRITICAL

Security Mandate: Plain-text secrets MUST NEVER be stored in the Praesidium database or passed through the Agent Gateway. The database stores only AWS Secret ARNs.

1
qqq Returns ARN
Hydration manifest has ARN only
→
2
Worker Uses IRSA
AWS IAM Role for Service Accounts
→
3
AWS Secrets Manager
Direct fetch, pod-level auth
→
4
Secret Injected
Into tool execution context

Pipeline Rules

  • Storage: Keys stored in AWS Secrets Manager only
  • Reference: The secret_ref table stores only the ARN
  • Auth: Worker pod uses AWS IRSA IAM Role to authorize the fetch
  • Injection: Worker fetches secret directly from AWS using the ARN from the Hydration Manifest
  • Audit: Every fetch logged in AWS CloudTrail + Praesidium audit_access_log

Why "Blind"?

The Gateway and qqq API are blind to secret values. They never see, cache, or log plain-text credentials.

  • Gateway sees: { "key": "GITHUB_TOKEN", "arn": "arn:aws:..." }
  • Database stores: aws_secret_arn VARCHAR(255)
  • Worker retrieves: actual token via IRSA → AWS SDK
  • CloudTrail records: which pod, which ARN, when

Compliance: This architecture satisfies SOC2 CC6.1 (logical access), HIPAA §164.312(a)(1) (access controls), and ensures no credentials leak through application logs, database backups, or API responses.

Stats Reconciliation

SYSTEM JOB

The denormalized counters on agent (total_tasks_completed, total_tokens_used, total_cost_usd) are CACHE values — updated on write for fast reads but can drift. A periodic reconciliation job ensures correctness.

Schedule & Queue

Every 6 hours via Celery Beat
Queue: quick (runs fast, read-heavy)

Reconciliation Logic

total_tasks_completed = COUNT(*) from task WHERE status = DONE
total_tokens_used = SUM(tokens) from message
total_cost_usd = SUM(cost) from message + activity_log

Counters are treated as cached aggregates — source tables (task, message, activity_log) are authoritative. Agent detail page can also compute live values on demand.

Pod Architecture Deep Dive

5 POD TYPES

Each Praesidium2 namespace runs 5 pod types. This table shows the infrastructure footprint.

PodImageLanguageReplicasHPA MetricResources
qqq-api praesidium-qqq:latest Java 21 + Spring Boot 2–6 CPU utilization (70%) 1 CPU / 2Gi RAM
agent-gateway praesidium-gateway:latest Python 3.12 + FastAPI 2–8 Active connections + req/s 1 CPU / 2Gi RAM
agent-worker praesidium-worker:latest Python 3.12 + Celery 3–10 Redis queue depth 2 CPU / 4Gi RAM
tool-runner praesidium-tool-runner:{lang} Python 3.12 (or per-tool) 0–8 (ephemeral Jobs or warm pool) Request rate 0.5–2 CPU / 512Mi–4Gi
web praesidium-web:latest Nginx (static files) 2–4 CPU utilization (70%) 0.25 CPU / 256Mi RAM

Gateway Responsibilities

Runs in the agent-gateway pod (FastAPI + Uvicorn, port 8000).

REST API: POST /chat/{agent_id} (SSE), POST /task/execute, POST /meeting/start, POST /forge/session, POST /job/trigger, POST /task/{id}/approve, GET /stream/{id}, GET /search
WebSocket Server: /ws — Redis Pub/Sub subscriber broadcasts to connected browsers. Events: task:*, agent:*, meeting:*, escalation:*, project:*
Agent Hydration: Load agent + template + tools + memories from qqq API. Build agent context (system prompt + tools + memories). Cache in Redis (TTL 5 min).
Inline Chat: Simple 1:1 chat runs in-process (no worker needed). Direct Anthropic API with tool loop + SSE streaming.
Task Dispatcher: Creates Celery tasks for complex work (tasks, meetings, jobs, forge). Publishes to Redis queue, returns job handle.
Semantic Search: GET /api/search — pgvector-powered search across documents, agents, tasks. Powers frontend Command Palette (Cmd+K).

Worker Responsibilities

Runs in the agent-worker pod (Celery, concurrency 4 per pod).

Celery Tasks: execute_task (direct SDK), run_meeting (turn-taking orchestrator), execute_job (LangGraph), forge_session, extract_memories, index_document
LangGraph Checkpointing: PostgresSaver for crash-resilient workflows. Checkpoint after every graph node transition.
Tool Registry: PLATFORM tools in-process, INTEGRATION tools in-process, CUSTOM dispatched to tool-runner pods, MCP via sidecar.
Celery Beat: Leader-elected (Redis lock). Polls scheduled_job and scheduled_meeting every 30s. Runs health checks every 5 min. Runs memory decay.
Scheduler HA v1.9: Active leader writes to scheduler_heartbeat table every 30s. Secondary nodes monitor; if now() - last_heartbeat > 60s, secondary acquires leadership. Prevents split-brain and dead-lock in scheduled tasks.

Semantic Search Endpoint (A-006)

GATEWAY API

Unified search across all Praesidium entities, powered by pgvector semantic embeddings. This endpoint drives the frontend Command Palette (Cmd+K).

GET /api/search?q={query}&scope={documents|agents|tasks|all}
ParameterTypeDescription
qstring (required)Natural language search query
scopeenum (optional)documents | agents | tasks | all (default: all)
limitint (optional)Max results to return (default: 20, max: 100)

How It Works

1. Gateway embeds query using text-embedding-3-small
2. pgvector cosine similarity search across knowledge_chunk.embedding, memory.embedding
3. Also text-matches against agent.label, task.title, project.label
4. Returns ranked results with relevance_score (0.0–1.0)

Response Shape

{ "results": [
    { "type": "task",
      "id": "uuid",
      "title": "...",
      "relevance_score": 0.92,
      "snippet": "..." }
  ],
  "total": 42,
  "query_ms": 23 }

Instance-scoped via JWT praesidiumInstanceId. Results respect IAM policies — users only see entities they have read permission for.

Tool-Runner Pod

ONLY for CUSTOM (FORGED) tools. PLATFORM and INTEGRATION tools run inside agent-worker.

Ephemeral Mode (k8s Job)

Worker creates k8s Job on CUSTOM tool call. Job spec: image per language, entry point from tool_version, credentials from Secrets Manager, tool code from ConfigMap (pinned SHA). Resource limits by risk level. NetworkPolicy restricts egress to integration_config.base_url only. Auto-deletes after TTL (300s).

Warm Pool Mode (Deployment)

Pre-warmed pods with tool code pre-loaded. HTTP endpoint: POST /execute. Reduces cold start from ~5s to <200ms. ConfigMap updated on tool_version publish. HPA 2–8 pods based on request rate. Used for high-frequency tools (>10 calls/hour).

Risk LevelCPUMemoryTimeout
LOW0.5 CPU512Mi30s
MEDIUM1.0 CPU1Gi60s
HIGH1.0 CPU2Gi120s
CRITICAL2.0 CPU4Gi300s

Scaling Strategy

PodMinMaxHPA MetricScale TriggerScale-Down Delay
qqq-api 26 CPU utilization 70% CPU avg 5 min
agent-gateway 28 Active WS connections + request rate 500 connections or 100 req/s per pod 10 min (WS stateful)
agent-worker 310 Redis queue depth (Prometheus) Queue depth > 5 per pod 15 min (in-flight tasks)
tool-runner (warm) 28 Request rate 10 req/s per pod 5 min
web 24 CPU utilization 70% CPU 5 min

Failure Scenarios & Recovery

Worker pod dies mid-task

Standard task (direct SDK): Celery visibility timeout expires, task re-queued, new worker starts from scratch. LangGraph workflow: New worker loads checkpoint from PostgreSQL, resumes from last node. Zero work lost.

Gateway pod dies

WebSocket connections drop. Browser auto-reconnects to different pod via k8s Service. SSE streams reconnect with last event ID. Workers unaffected — they publish to Redis.

qqq-api pod dies

k8s Service routes to surviving replica. Workers retry API calls (3x backoff). If all pods die, workers queue and retry until recovery. Liquibase only runs on leader pod.

Redis dies

In-flight tasks continue. New tasks fail. WS broadcasts stop. Agent cache lost (next hydration fetches from qqq). Mitigation: ElastiCache Multi-AZ or Redis Sentinel.

Tool-runner pod times out

k8s Job hits activeDeadlineSeconds, killed. Worker returns ToolResult(success=false, error="timeout") to agent. Agent decides retry or escalate. Pod cleaned up by TTL controller.

Anthropic API rate limited

429 response triggers SDK auto-retry with exponential backoff. If persistent, worker pauses and re-queues with delay. Per-agent rate limiting via Redis token bucket.

🎭

Configurable Agent Personality (Business Review B20)

Themed personas are opt-in and configurable per team

Agent personality (WWE, LOTR, Grey's Anatomy, Star Wars themes) is configurable per team instance. Each business unit chooses their own personality theme — or uses professional mode for external-facing contexts. Personality does not affect agent capability, only communication style.

Personality Configuration

SettingLocationDefault
Instance themeinstance.config.personality_themeprofessional
Per-agent overrideagent_template.personality_traitsInherits instance theme
External context modetool_definition.context_modeAlways professional for external tools

Available Modes

ModeExampleUse Case
ProfessionalStandard business toneDefault; external-facing
WWEMarketing team personasInternal team engagement
LOTREngineering team personasInternal team engagement
Grey's AnatomyMe Health team personasInternal team engagement
Star WarsCorp Claw team personasInternal team engagement
CustomTeam-defined themesNew teams choose their own

Design principle: Themed personalities are opt-in. The personality_traits JSONB field on agent_template stores personality configuration. When an agent interacts with external-facing tools (e.g., sending emails to clients, posting to public channels), the personality layer is automatically bypassed in favor of professional tone. The system prompt dynamically adjusts based on the tool's context_mode setting.

Frontend ArchitectureTechnicalReact SPA structure, pages, and components

React 19
Framework
TypeScript
Language (strict)
Tailwind
+ shadcn/ui
TanStack
Query + Router

Full Tech Stack

LayerChoiceRole
FrameworkReact 19 + ViteComponent rendering + fast bundling
LanguageTypeScript (strict)Type safety across all modules
StylingTailwind CSS + shadcn/uiUtility-first CSS + composable components
State / DataTanStack Query + ZustandServer state cache + local UI state
RoutingTanStack RouterFile-based, fully type-safe routes
Real-timeWebSocket + SSEPush events + chat streaming
ChartsRechartsData visualization
TestingVitest + Testing LibraryUnit + component testing

Dual API Architecture

Two API targets — qqq for data, Agent Gateway for AI interactions. Same Authentik JWT for both. Distinct root prefixes make each service immediately identifiable in logs, network traces, and dev tools; versioning allows non-breaking evolution of either API independently.

qqq API — Data CRUD

Base: /qqq/v1/

Read/write projectsGET/POST /qqq/v1/project
Read/write tasksGET/POST /qqq/v1/task
Read/write agentsGET/POST /qqq/v1/agent
Settings & configGET/PATCH /qqq/v1/settings

Agent Gateway — AI Actions

Base: /gateway/v1/

Chat with agentPOST /gateway/v1/chat → SSE
Execute taskPOST /gateway/v1/task/execute
Start meetingPOST /gateway/v1/meeting/start
Forge sessionPOST /gateway/v1/forge/session

10 Primary Pages

PageRouteDescription
Dashboard/Active projects health, team status, escalations, today's meetings, cost burn rate
Projects/projects/:idCard grid → tabbed detail (overview, tasks kanban, team, milestones, meetings)
Team/team/:idGrid of agents + humans. Detail: skills radar, memory explorer, tools, performance
Chat/chat/:conv_idSlack-like with SSE streaming, tool call visualization, thinking indicator
Meetings (V1.5)/meetings/:idSchedule, transcripts, action items, manage recurring meetings
Tool Forge (V1.5)/forge/:idTool catalog, versions, split-pane build mode (chat + code + tests)
Escalations/escalationsInbox sorted by severity. Acknowledge, resolve, dismiss, assign
Settings/settingsInstance config, integrations, templates, knowledge base, notifications
Activity/activityChronological feed filterable by agent, project, action type. Real-time WS
Cost Center/costsToken usage + cost by agent/project/time. Burn rate charts, budget alerts

WebSocket

Single persistent connection. Receives push events for TanStack Query cache invalidation.

task:status_changed agent:status_changed meeting:started escalation:created job:completed project:health_changed

SSE (Server-Sent Events)

Per-conversation stream for agent responses.

token thinking tool_call_start tool_call_result message_complete interrupt error

Frontend MockupsExecutive TechnicalVisual wireframes for every application page

Wireframe layouts for every major page of the application — showing structure, navigation, and content zones.

Dashboard

/
Active Projects
7
Team Online
12
Open Escalations
3
Today's Cost
$14.72
Project Health
Patient Portal v3 ON TRACK
Q4 Holiday Launch AT RISK
API Platform ON TRACK
PPC Optimization BLOCKED
Recent Activity
The Rock optimized 23 bids
Backend-1 opened PR #287
QA-Bot filed 2 bugs
Stone Cold published A+ content
The Undertaker created escalation #47
Today's Meetings: 9:00 AM Standup | 2:00 PM Sprint Review | 4:00 PM Retro
Running Jobs: keyword_analysis (The Rock) | listing_audit (Stone Cold) | cost_report (Bret Hart)

Projects

/projects
All Projects | Active (7) | Completed (3) | Archived (1)
Patient Portal v3
ON TRACK
65% | 3 members | Apr-Jun
Q4 Holiday Launch
AT RISK
40% | 5 members | Oct-Dec
PPC Optimization
ONGOING
Ongoing | 3 members
API Platform
ON TRACK
80% | 2 members | Mar-May

Project Detail

/projects/:id
Patient Portal v3 ON TRACK Apr 1 - Jun 30
Edit Project
Overview Tasks Team Milestones Meetings Activity Integrations
Open (4)
PORTAL-251 Session timeout
PORTAL-253 Error boundary
PORTAL-255 Audit logging
PORTAL-257 Rate limiting
In Progress (3)
PORTAL-234 Telehealth video
PORTAL-241 Med history API
PORTAL-245 Dashboard perf
In Review (2)
PORTAL-230 Auth flow v2
PORTAL-238 Patient search
Done (5)
PORTAL-220 DB schema
PORTAL-221 User model
PORTAL-225 API scaffold
PORTAL-228 CI pipeline
PORTAL-229 Seed data

Team

/team
All (14) Agents (8) Humans (6) | Category: [All v]
AR
Architect
Sr SW Architect
ONLINE
Patient Portal v3
LN
Luna
Marketing Strategist
ONLINE
All Projects
JM
James Maes
CTO (Human)
AVAILABLE
Patient Portal v3
QA
QA-Bot
QA Engineer
BUSY
Test Automation

Chat

/chat/:id
Architect
Let me analyze that schema...
Luna
Campaign report ready
QA-Bot
Found 2 edge cases in...
Backend-1
PR #287 is ready for...
JM
Can you review the new medication history schema and suggest improvements?
AR
I'll analyze the schema now. Let me check the current migration files and the ERD.
tool_call: github_get_file_contents("schema/medication.sql") completed
AR
I see 3 improvements: 1) Add composite index on (patient_id, medication_id), 2) The dosage field should use DECIMAL not FLOAT, 3) Missing audit columns...
Type a message...
Send

Meetings (V1.5)

/meetings
Upcoming
Marketing Daily Standup
0 9 * * 1-5 | Facilitator: Luna | 6 participants
Sprint Planning
0 10 * * 1 | Facilitator: Scrum-Master | 8 participants
Architecture Review
0 14 * * 3 | Facilitator: Architect | 4 participants
Past Meetings
Daily Standup - Apr 1 5 min | 6 spoke
Summary: PPC bids optimized, A+ content published, competitor price alert raised
Sprint Retro - Mar 28 12 min | 8 spoke
Summary: Velocity 26pts, 3 stories done, 1 carried. db_migration_tool saved 4hrs
Meeting Detail: transcript with speaker labels, action items with task links

Tool Forge (V1.5)

/forge/build
Forge Agent Chat
JM
Build a tool that checks SSL certificate expiry for a list of domains
FG
I'll create check_ssl_expiry. Input: list of domains. Output: domain, issuer, expiry date, days remaining, status. Let me scaffold...
FG
Scaffold complete. 3 files created. Implementing now...
check_ssl_expiry.py test_tool.py tool_manifest.json
import ssl, socket
from datetime import datetime

def check_ssl_expiry(domains: list[str]):
    results = []
    for domain in domains:
        cert = ssl.get_server_cert(domain)
        expiry = parse_date(cert['notAfter'])
        days_left = (expiry - now()).days
        results.append({...})
    return results
Test Output: 4 passed, 0 failed
Approve
Request Changes
Reject

Escalations

/escalations
CRITICAL Production API latency spike >5s
Raised by: DevOps-Bot | API Platform | 12 min ago
Acknowledge
HIGH Competitor X dropped prices 12% on 3 ASINs
Raised by: The Undertaker | Competitive Analysis | 2 hrs ago
Review
MEDIUM Twilio API key not provisioned - blocking telehealth
Raised by: Backend-1 | Patient Portal | 1 day ago
Assign
LOW 3 keywords with >$50 spend and 0 conversions
Raised by: The Rock | PPC Optimization | 1 day ago
Dismiss

Cost Center

/costs
Total Spend (MTD)
$1,247.83
Daily Burn Rate
$42.68/day
Budget Remaining
$752.17
Chart: Cost Over Time (line chart) — daily spend for the past 30 days with budget line overlay
By Agent
Architect: $312.40 | Backend-1: $198.20 | Luna: $156.80
By Project
Patient Portal: $487.20 | PPC Opt: $312.00 | Content: $198.40
By Model
Claude Opus: $680.00 | Claude Sonnet: $320.00 | GPT-4o: $147.83

Settings

/settings
Instance
Integrations
Agent Templates
Knowledge Base
Secrets
Meetings
Instance Settings
Instance Name
tech-team
Display Name
Engineering Leadership Team
Daily Budget
$100.00
Default Model
Claude Opus 4.6 (Anthropic)
Save Changes

Scheduled Tasks v1.9

/schedules
Schedule List View
All Schedules (12) Active (9) Paused (2) Failed (1) | Agent: [All v] | Tool: [All v]
NAME AGENT SCHEDULE LAST RUN NEXT RUN STATUS ACTIVE
Daily PPC Bid Optimization The Rock Every weekday at 9 AM SUCCESS Today 9:00 AM ON TIME ●
Competitor Price Scrape The Undertaker Every 4 hours SUCCESS In 2h 14m ON TIME ●
BSR Rank Tracker Bret Hart Daily at 6 AM FAILED Tomorrow 6:00 AM OVERDUE ●
Social Media Auto-Post Ric Flair 3x daily (8a, 1p, 6p) PAUSED — PAUSED ●
+ New Schedule

Schedule Detail / Edit v1.9

/schedules/:id
Schedule Configuration
Name
Daily PPC Bid Optimization
Description
Optimize all active PPC campaign bids based on ACoS targets
Agent
The Rock (Marketing Agent)
Tool
ppc_bid_optimizer
Tool Parameters
{"target_acos": 25, "max_bid_change_pct": 15}
Schedule
0 9 * * 1-5
→ Every weekday at 9:00 AM
Active
Enabled
Max Budget
$5.00
Run Now
Save
Delete
Quick Schedule Picker
Every hour
Every 4 hours
Weekdays 9 AM
Daily 6 AM
Weekly Monday
Monthly 1st
Custom...
Next 5 Runs
Mon Apr 7, 2025 — 9:00 AM
Tue Apr 8, 2025 — 9:00 AM
Wed Apr 9, 2025 — 9:00 AM
Thu Apr 10, 2025 — 9:00 AM
Fri Apr 11, 2025 — 9:00 AM
Run History
STARTED DURATION STATUS COST OUTPUT SUMMARY
Apr 4, 9:00 AM 2m 14s SUCCESS $0.42 Optimized 23 bids across 5 campaigns. Reduced avg ACoS from 28% to 24%.
Apr 3, 9:00 AM 1m 58s SUCCESS $0.38 Optimized 19 bids. Paused 2 low-performing keywords.
Apr 2, 9:00 AM 3m 02s FAILED $0.11 Amazon Advertising API rate limit exceeded. Retry scheduled.
HEALTH Schedules that miss their expected run time show an OVERDUE badge. Consecutive failures (tracked via consecutive_failures / max_retries) trigger automatic escalation to the assigned human reviewer.

Scheduled Tasks API v1.9

qqq CRUD + CUSTOM

Standard qqq CRUD endpoints for the scheduled_job table, plus custom actions for on-demand execution and history retrieval.

Endpoint Method Description
/api/scheduled_jobGETList all scheduled jobs (filterable by agent, status, tool)
/api/scheduled_jobPOSTCreate a new scheduled job
/api/scheduled_job/{id}GETGet schedule detail
/api/scheduled_job/{id}PATCHUpdate schedule (edit cron, toggle active, change params)
/api/scheduled_job/{id}DELETEDelete schedule
/api/scheduled_job/{id}/run-nowPOSTManually trigger an immediate execution (creates job_execution with trigger_type = MANUAL)
/api/scheduled_job/{id}/historyGETGet execution history (paginated list of job_execution records)

Celery Beat Integration: When a user creates, edits, or deletes a schedule via these endpoints, Celery Beat picks up the change on its next heartbeat cycle (every 30s). The next_run_at column is recomputed from cron_schedule after each save. This ties directly into the G-002 scheduler_heartbeat HA mechanism — only the elected leader node processes schedules.

Tool ForgeExecutive TechnicalHow custom tools are built collaboratively

Collaborative tool building — humans and agents design, build, test, and publish tools together via a git-backed, versioned workflow.

V1.5 — Post-Launch (4–6 weeks)
Deferred to V1.5. Agents use pre-built PLATFORM and INTEGRATION tools at launch. The Tool Forge — where humans and agents collaboratively build custom tools — is added after stable agent execution is proven in production.

What is the Tool Forge?

The Tool Forge is where you work one-on-one with an AI agent to build custom tools that any agent on your team can use. You describe what you need in plain English, and the forge agent writes the code, tests it, and publishes it — no programming knowledge required.

CMO needs an Amazon keyword research tool

Describes what Cerebro-style keyword lookup should do. Agent builds the integration with Amazon SP-API, tests it, publishes to the catalog. Marketing agents start using it immediately.

VP of Product Dev needs a shipping container tracker

Describes the Flexport integration needed for container ETA tracking. Agent builds the API connector, adds error handling and retry logic, tests against sandbox. Published and assigned to ops agents.

CTO needs a database health check script

Describes the monitoring requirements: check replication lag, connection pool usage, slow queries. Agent writes the checks, builds alerting thresholds, tests against staging. Deployed as a scheduled tool.

HR VP needs a BambooHR onboarding tracker

Describes the onboarding workflow: pull new hires from BambooHR, track checklist completion, flag overdue items. Agent builds the integration and dashboard data, tests the full lifecycle. HR agents use it on day one.

The Forge Agent System Agent is a built-in system agent available to every Praesidium instance. It specializes in writing, testing, and deploying tool code. Think of it as your team's on-demand software developer. The human never writes code — they describe, review, and approve. The agent does all technical work.

6-Step Forge Workflow

1
Design
Human describes → Agent specs
→
2
Scaffold
Agent creates project structure
→
3
Implement
Agent writes all code
→
4
Test
Agent runs & fixes tests
→
5
Review
Human approves or rejects
→
6
Publish
Agent deploys to catalog

Powered by LangGraph state graph with checkpointing. Human-in-the-loop at review stage. Git-backed versioning with immutable snapshots.

Forge Workflow — Step Details

Each step is a LangGraph node with durable checkpointing. The graph pauses at human-in-the-loop boundaries.

Step 1: Design

Human describes what they need. Agent asks clarifying questions and produces the spec.

Agent does
Conducts a clarifying conversation with the human to understand the tool's purpose, inputs, outputs, and edge cases. Produces a structured tool spec (JSON schema for input/output, description, risk level, required integrations).
Human does
Describes the tool in natural language. Answers clarifying questions. Reviews and approves the generated spec before scaffolding begins. No technical knowledge required.
Data created
tool record (status: DRAFT), tool_version record (version: 0.1.0-draft), forge_session record, conversation messages.
LangGraph
Node: design_node. Checkpoint after spec approval. State includes spec JSON and conversation history.

Step 2: Scaffold

Agent creates the project structure automatically. Human sees the file tree appear.

Agent does
Generates the project structure from the approved spec: main tool file, test file, requirements.txt, and tool_manifest.json. Creates a git-initialized sandbox workspace with the files.
Human does
Watches the file tree appear in real time. Can request structural changes before implementation begins. No code to write.
Data created
Files in sandbox workspace (git init + initial commit). tool_version.source_ref set to initial git SHA. Sandbox pod created in k8s.
LangGraph
Node: scaffold_node. Checkpoint after file generation. State includes file tree and sandbox pod reference.

Step 3: Implement

Agent writes all the code. Human watches the live preview and can give feedback.

Agent does
Writes the actual tool logic in the sandbox. Uses the spec as a contract, writes code that handles all defined inputs and produces the expected outputs. Installs dependencies, resolves imports, handles error cases. The agent does 100% of the coding.
Human does
Watches progress and provides feedback via chat. Supplies domain context, API documentation, or example data as needed. Never touches the code directly.
Data created
Updated source files in sandbox (committed to git). Multiple git commits as implementation progresses. Conversation history with implementation decisions.
LangGraph
Node: implement_node. Multiple checkpoints (one per code iteration). State includes current code, dependency list, and implementation notes.

Step 4: Test

Agent runs tests automatically in a sandbox. If tests fail, agent fixes and re-runs (up to 5 times).

Agent does
Runs the test suite inside the sandbox. Analyzes failures, fixes code, and re-runs automatically (up to 5 iterations). Generates edge case tests beyond the initial suite. Reports coverage metrics.
Human does
Reviews test output summary. Can suggest additional test scenarios via chat. All test writing and debugging is done by the agent.
Data created
Test results stored in forge_session metadata. Updated test files committed to git. Coverage report artifact uploaded to object storage.
LangGraph
Node: test_node. Loops back to implement_node on failure (max 5 retries). Checkpoint after all tests pass. State includes test results and coverage.

Step 5: Review

Human reviews the final code + test results. Approves, requests changes, or rejects.

Agent does
Presents the completed tool with a summary diff, test results, risk assessment, and resource requirements. Waits for human decision. If changes requested, routes back to implement step.
Human does
Reviews the full source code, test results, and tool manifest. Clicks Approve, Request Changes, or Reject. This is the primary human-in-the-loop gate. The human is the decision-maker, not the coder.
Data created
tool_version.status updated to APPROVED or CHANGES_REQUESTED. Review comments stored. Activity log entry for audit trail.
LangGraph
Node: review_node. Human-in-the-loop interrupt. Checkpoint on decision. Routes to implement_node (changes) or publish_node (approved).

Step 6: Publish

Agent commits to git, creates version record, registers in catalog. Tool is live.

Agent does
Creates an immutable git tag for the version. Registers the tool in the catalog with its manifest, input/output schemas, and approved risk level. Notifies relevant agents that a new tool is available. Fully automated deployment.
Human does
Receives confirmation of publication. Can assign the tool to specific agents or projects. Sets up integration credentials if the tool requires external API access.
Data created
tool.status = ACTIVE. tool_version finalized with git SHA tag. tool.current_version updated. Catalog entry visible to all agents. Activity log entry.
LangGraph
Node: publish_node. Terminal node. Final checkpoint. Graph state archived. Session marked COMPLETED.

Tool Categories

Category Details

Platform Tools

BUILTIN

create_task, update_task_status, list_projects, store_memory, create_escalation, schedule_job

Integration Tools

IMPORTED

Jira, Confluence, Slack, Zoho CRM, GitHub, Google Workspace connectors

Custom Tools

FORGED

pull_campaign_metrics, check_ssl_expiry, parse_invoice_pdf, calculate_sprint_velocity

MCP Tools

MCP

Playwright (browser), SQL (database), filesystem, custom internal APIs

Tool Execution Model — Where Each Type Runs

CategoryEnvironmentDetails
PLATFORM In-process (agent worker) Python functions inside the Celery worker. Call qqq REST APIs directly. Trusted first-party code — no isolation needed.
INTEGRATION In-process (agent worker) Connector classes loaded into the worker. Use credentials from secret_ref via Secrets Manager. Network access to integration endpoints.
CUSTOM (FORGED) Sandboxed k8s Job Each execution spawns a short-lived k8s Job with resource limits, network policy (integration allowlist), mounted tool code from git, injected credentials as env vars.
MCP Sidecar pod or external MCP server as sidecar container or external service. Agent worker communicates via MCP protocol (stdio or HTTP).

Custom Tool Pod Lifecycle

1
Resolve Version
git SHA + entry point
→
2
Resolve Creds
secret_ref → SM
→
3
Create Job
k8s spec + limits
→
4
Submit
Wait for completion
→
5
Parse Output
stdout → ToolResult
→
6
Cleanup
Pod auto-terminates
→
7
Return
Result to agent

Resource Limits by Risk Level

LOW 0.5 CPU / 512MB    CRITICAL 2 CPU / 4GB

Network Policy

Only integration_config.base_url endpoints are allowed. All other outbound traffic is blocked.

Warm Pod Pool Optimization

For frequently-used CUSTOM tools, maintain a pool of warm containers pre-loaded with tool code. Reduces cold-start latency from ~5s (k8s Job creation) to <200ms (HTTP call to warm pod).

N
Standby pods per language
ConfigMap
Tool code mounting
HTTP
Execution endpoint
HPA
Queue-depth scaling

Tool Interface Contract

Every tool — regardless of category — conforms to the same contract stored in the tool table.

FieldPurpose
nameUnique identifier: jira_create_issue
display_nameHuman-readable: "Create Jira Issue"
input_schemaJSON Schema defining required/optional parameters
output_schemaJSON Schema defining return value structure
risk_levelLOW / MEDIUM / HIGH / CRITICAL — determines execution policy
requires_approvalBoolean — if true, blocks until human approves
current_versionSemantic version pointing to latest tool_version

Sandbox Execution Comparison

AspectForge Sandbox (build time)Production Sandbox (runtime)
LifecycleEphemeral per sessionPool of warm containers
NetworkIntegration endpoints only (allowlist)Integration endpoints only
qqq accessNoneRead-only via ToolContext
Resources1 CPU, 2GB RAM, 60s timeoutConfigurable per risk_level
FilesystemIsolated workspace, git initTool workspace only
Code sourceWritten live by forge agentgit checkout at pinned SHA

Tool Forge ExampleExecutiveStep-by-step Amazon keyword tool walkthrough

Building an Amazon keyword research tool suite (like Helium 10) — a step-by-step walkthrough of the forge workflow in action.

V1.5 — Post-Launch (4–6 weeks)
This walkthrough demonstrates V1.5 functionality. At V1 launch, agents use pre-built platform and integration tools. The collaborative forge workflow shown here is added in V1.5.

Scenario: Cerebro Keyword Lookup

AMAZON PPC

The CMO (Bryan Chupp) wants to build an Amazon keyword research tool similar to Helium 10's Cerebro. She describes what she needs to the Forge agent via chat, and together they build, test, and publish it.

Step 1: Design

SPEC CREATION
SC
Bryan Chupp (CMO) 10:00 AM
I need a tool that takes an ASIN and returns the top keywords it ranks for, with search volume and rank position. Similar to how Helium 10's Cerebro works.
FG
Forge Agent System Agent 10:00 AM
Great, I can build that. A few clarifying questions:
1. Which Amazon marketplace? (US, EU, both?)
2. How many keywords should we return per ASIN? (top 50? 100?)
3. Do you need historical rank data or just current snapshot?
4. Should it support bulk ASINs or one at a time?
SC
Bryan Chupp (CMO) 10:02 AM
US marketplace only for now. Top 100 keywords. Current snapshot is fine. Single ASIN input, but we can add bulk later.
FG
Forge Agent System Agent 10:03 AM
Here's the spec I've generated:

Tool: cerebro_keyword_lookup
Input: { asin: string, marketplace: "US", max_results: 100 }
Output: { asin, keywords: [{ keyword, search_volume, organic_rank, sponsored_rank, relevancy_score }] }
Risk Level: LOW (read-only API calls)
Integration: Amazon SP-API + Advertising API

Shall I proceed with scaffolding?
[tool_call: create_tool_spec]

Step 2: Scaffold

FILE GENERATION

Generated File Tree

cerebro_keyword_lookup/
├── cerebro_keyword_lookup.py    # Main tool implementation
├── test_tool.py                 # Test suite (4 test cases)
├── requirements.txt             # sp-api, boto3, pytest
└── tool_manifest.json           # Schema, metadata, risk level

Sandbox pod created in k8s with network access restricted to Amazon SP-API endpoints only. Git repository initialized with initial commit.

Step 3: Implement

CODE GENERATION

cerebro_keyword_lookup.py

import boto3
from sp_api.api import Products, Keywords
from sp_api.base import Marketplaces

class CerebroKeywordLookup:
    """Reverse-ASIN keyword lookup tool for Amazon PPC research."""

    def __init__(self, credentials: dict):
        self.sp_client = Products(credentials=credentials,
                                   marketplace=Marketplaces.US)
        self.ads_client = boto3.client('advertising',
                                        region_name='us-east-1')

    def execute(self, asin: str, max_results: int = 100) -> dict:
        # 1. Get product details to validate ASIN
        product = self.sp_client.get_product(asin)

        # 2. Query Advertising API for keyword rankings
        keywords = self.ads_client.get_keyword_rankings(
            asin=asin, marketplace='US', limit=max_results)

        # 3. Enrich with search volume estimates
        enriched = self._enrich_with_volume(keywords)

        # 4. Sort by relevancy score (descending)
        enriched.sort(key=lambda k: k['relevancy_score'], reverse=True)

        return {
            'asin': asin,
            'product_title': product.title,
            'keyword_count': len(enriched),
            'keywords': enriched[:max_results]
        }

Step 4: Test

AUTOMATED TESTING

Test Results

$ pytest test_tool.py -v

test_tool.py::test_valid_asin_returns_keywords      PASSED
test_tool.py::test_invalid_asin_raises_error         PASSED
test_tool.py::test_max_results_limit_respected       PASSED
test_tool.py::test_output_schema_matches_manifest    PASSED

=============================== 4 passed in 2.31s ===============================
Coverage: 92%

Step 5: Review

HUMAN APPROVAL

Review Summary:

Files changed4 files, 187 lines
Test coverage92%
Risk levelLOW
Dependenciessp-api, boto3, pytest
Network accessAmazon SP-API endpoints only
✓
Approved by Bryan Chupp (CMO)
April 2, 2026 at 10:42 AM

Step 6: Publish

LIVE IN CATALOG
✓ Tool published: cerebro_keyword_lookup v1.0.0
✓ Git tag created: v1.0.0 (SHA: a3f8c2d)
✓ Added to tool catalog (category: CUSTOM)
✓ Assigned to agents: The Rock, The Undertaker, Bret Hart
✓ Credentials linked: amazon_sp_api_key (secret_ref)
✓ Notification sent to #marketing-tools on Slack

Building the Suite

With cerebro_keyword_lookup published, Bryan and the marketing team forge 4 more tools using the same workflow — creating a complete Amazon PPC toolkit.

keyword_magnet

v1.0.0

Reverse ASIN keyword discovery — finds keywords that multiple competitor ASINs rank for but your product does not. Surfaces keyword gaps and opportunities.

Input{ target_asin, competitor_asins[], max_gaps }
OutputKeyword gap list with search volume, competition score
Built byMarcus Rivera + The Rock via Forge
Forged in28 minutes (3 implement iterations)

listing_optimizer

v1.0.0

Analyzes a product listing against its top-performing keywords. Scores title, bullets, description, and backend keywords for optimization potential.

Input{ asin, target_keywords[] }
OutputOptimization report with section scores, suggestions
Built byPriya Patel + Stone Cold via Forge
Forged in35 minutes (2 implement iterations)

bsr_tracker

v1.0.0

Monitors Best Seller Rank changes over time for a list of ASINs. Runs as a scheduled job (daily), stores history, and alerts on significant rank changes.

Input{ asins[], category, lookback_days }
OutputBSR history with trend direction, volatility score
Built byJake Morrison + Bret Hart via Forge
Forged in22 minutes (1 implement iteration)

competitor_analyzer

v1.0.0

Tracks competitor pricing, inventory levels, and listing changes over time. Generates weekly competitive intelligence reports with actionable insights.

Input{ competitor_asins[], metrics[] }
OutputCompetitive report with price history, inventory estimates
Built byBryan Chupp (CMO) + The Undertaker via Forge
Forged in40 minutes (4 implement iterations)

Complete Amazon PPC Toolkit

ToolPurposeAgent UsersRun Frequency
cerebro_keyword_lookupKeyword rankings for any ASINThe Rock, The Undertaker, Bret HartOn-demand
keyword_magnetKeyword gap analysis vs competitorsThe RockWeekly (scheduled)
listing_optimizerListing quality scoringStone ColdOn-demand + monthly audit
bsr_trackerBSR monitoring and trendsBret HartDaily (scheduled)
competitor_analyzerCompetitive intelligenceThe UndertakerWeekly (scheduled)

Total forge time: ~2.5 hours. All 5 tools now available in the catalog. Agents use them autonomously as part of daily operations. Total estimated monthly cost savings vs. Helium 10 subscription: ~$300/month.

LLM ModelsExecutive TechnicalMulti-provider LLM support and cost optimization

Model-agnostic platform — every agent uses the best LLM for their job. From cloud APIs to local models, Praesidium2 abstracts provider differences behind a unified interface.

V1 Scope: V1 implements AnthropicClient only. The llm_provider and llm_model schema ships complete, but only the Anthropic provider is implemented at launch. Additional providers (OpenAI, Ollama, Bedrock, Vertex, vLLM) are added on-demand post-V1. The LLMClient Protocol ensures adding a provider is a single-class implementation.

Provider Types

☁

CLOUD_API

Anthropic, OpenAI, Google AI

HTTPS to provider API with API key auth. Per-token pricing. Highest capability models. Supports tools, vision, thinking.

Anthropic SDKOpenAI SDK
⚡

BEDROCK

AWS Bedrock (Claude, Titan, Llama)

AWS SDK with IAM role auth. Per-token via AWS billing. Same models as CLOUD_API but billed through AWS account.

boto3bedrock-runtime
◆

VERTEX

Google Vertex AI (Gemini, Claude)

Google Cloud SDK with service account auth. Per-token via GCP billing. Access to Gemini models and Claude via Vertex.

google-cloud-aiplatform
⚙

SELF_HOSTED

vLLM, TGI on EKS

HTTP to internal endpoint. No auth or bearer token. GPU compute cost per hour. Full control over model and infrastructure.

vLLMOpenAI-compatible
⌂

LOCAL

Ollama, LM Studio

HTTP to localhost or internal service. No auth needed. Hardware cost amortized. Ideal for development and low-cost tasks.

Ollama APILM Studio

Seed Models (P0)

ProviderModelTierInput $/1MOutput $/1MContextToolsVisionThinking
Anthropic claude-opus-4-6 FLAGSHIP $5.00$25.00200K ✓ ✓ ✓
claude-sonnet-4-6 STANDARD $3.00$15.00200K ✓ ✓ ✓
claude-haiku-4-5 ECONOMY $1.00$5.00200K ✓ ✓ ✗
OpenAI gpt-4o FLAGSHIP $2.50$10.00128K ✓ ✓ ✗
gpt-4o-mini ECONOMY $0.15$0.60128K ✓ ✓ ✗
o3 FLAGSHIP $10.00$40.00200K ✓ ✓ ✓
Ollama (Local) llama-3.1-70b STANDARD ~$0.50/hr GPU128K ✓ ✗ ✗
llama-3.1-8b ECONOMY ~$0.10/hr GPU128K ✓ ✗ ✗
codellama-34b STANDARD ~$0.30/hr GPU100K ✓ ✗ ✗
AWS Bedrock claude-opus-4-6 FLAGSHIP AWS pricing200K ✓ ✓ ✓
claude-sonnet-4-6 STANDARD AWS pricing200K ✓ ✓ ✓
amazon-titan-text ECONOMY AWS pricing32K ✗ ✗ ✗

Capability Tiers

FLAGSHIP

Highest capability. Complex reasoning, architecture, strategy. Claude Opus, GPT-4o, o3.

STANDARD

Good general capability. Day-to-day tasks, code generation. Claude Sonnet, Llama 70B.

FAST

Speed-optimized. Quick lookups, simple transformations, routing decisions.

ECONOMY

Cost-optimized. Summaries, QA, repetitive tasks. Haiku, GPT-4o-mini, Llama 8B.

Model Assignment Flow

Models cascade from template defaults through agent overrides to job-specific overrides.

TPL
Template Default
agent_template.default_model
→
AGT
Agent Override
agent.model (optional)
→
JOB
Job Override
scheduled_job.model (optional)
→
RUN
Resolved Model
Used for execution

Example: "Sr SW Architect" template defaults to claude-opus-4-6 (FLAGSHIP)

Override: A specific agent can be set to use gpt-4o instead

Job: Summary generation job uses claude-haiku-4-5 (ECONOMY)

LLMClient Protocol Abstraction

A single Python Protocol interface — V1 implements AnthropicClient only. The LLMClient Protocol enables additional providers post-V1 without changing agent runtime code.

LLMClient (Protocol)

async def create_message(messages, system, tools, max_tokens, stream) → LLMResponse
async def health_check() → bool
def supports_feature(feature: str) → bool
# features: "tools", "vision", "thinking", "streaming", "json_mode"
V1
AnthropicClient

@anthropic-ai/sdk

Post-V1
OpenAIClient

openai SDK

Post-V1
OllamaClient

HTTP to Ollama API

Post-V1
BedrockClient

boto3 bedrock-runtime

Post-V1
VertexClient

google-cloud-aiplatform

Post-V1
VLLMClient

OpenAI-compatible HTTP

Provider Fallback Flow Post-V1

When a provider goes down, agents automatically fall back to configured secondary models. V1 uses Anthropic only; fallback activates when additional providers are configured post-V1.

START
Resolve Model
agent.model_id
→
CHK
Check Provider
health_status?
→
UP
HEALTHY
Use primary model
|
DOWN
Provider DOWN
Check fallback
→
FB
Switch Model
fallback_model_id
→
LOG
Log Activity
activity_log entry

Example: "Agent Architect fell back from claude-opus-4-6 to gpt-4o due to Anthropic API outage. Task completed successfully with fallback model."

Cost Tracking Model

Provider TypeCost Formula
CLOUD_API input_tokens * input_cost_per_1m / 1M + output_tokens * output_cost_per_1m / 1M
BEDROCK Same per-token formula, billed through AWS account
VERTEX Same per-token formula, billed through GCP account
SELF_HOSTED duration_ms * compute_cost_per_hour / 3,600,000
LOCAL duration_ms * compute_cost_per_hour / 3,600,000 (amortized hardware)

Cost Distribution by Provider

V1 is Anthropic-only. Other providers are illustrative of post-V1 capabilities.

Provider Health Monitoring

Each provider gets health-checked every 2 minutes via a lightweight API call. V1 monitors Anthropic only; additional providers added post-V1.

ProviderHealthLast CheckLatencyModels ActiveQueries Today
Anthropic HEALTHY 2 min ago142ms3847
OpenAI HEALTHY 1 min ago198ms3312
Ollama (Local) HEALTHY 30s ago12ms3156
AWS Bedrock DEGRADED 2 min ago580ms245

Secrets ManagementTechnical OperationsCredential storage, scoping, and rotation

Secrets are scoped hierarchically — the narrowest scope wins when multiple secrets with the same name exist at different levels.

Secret Scopes

ScopeExampleWho Can Access
INSTANCE Anthropic API key, Slack workspace token, Jira org credentials All agents, all projects
PROJECT Client-specific API key, project GitHub repo PAT Agents assigned to that project
TOOL HubSpot API key used only by pull_campaign_metrics Only during that tool's execution
AGENT Agent-specific auth token for a system Only that agent

secret_ref Table Schema

ColumnTypePurpose
idUUID PKPrimary key
scope_type_idFK → secret_scope_typeINSTANCE, PROJECT, TOOL, AGENT
project_idFK → project (nullable)Set for PROJECT scope
tool_idFK → tool (nullable)Set for TOOL scope
agent_idFK → agent (nullable)Set for AGENT scope
nameVARCHAR(100)Secret name: HUBSPOT_API_KEY
descriptionTEXTHuman-readable description
secret_pathVARCHAR(200)Secrets Manager path or k8s secret ref
secret_type_idFK → secret_typeAPI_KEY, OAUTH2_TOKEN, SSH_KEY, etc.
last_rotated_atTIMESTAMPTZLast rotation timestamp
expires_atTIMESTAMPTZFor rotation alerting
created_by_idFK → team_memberWho created the secret reference

UNIQUE: (scope_type_id, project_id, tool_id, agent_id, name) — one secret per name per scope

Resolution Flow (Narrowest Scope Wins)

1
TOOL Scope
Check tool_id match
→
2
PROJECT Scope
Check project_id match
→
3
INSTANCE Scope
Org-wide fallback
→
4
Fetch Value
SM / k8s secrets
→
5
Inject
ToolContext.credentials

Agent-scoped secrets override all others when the specific agent is executing.

Storage Model

AWS Environments

secret_path = Secrets Manager ARN or path
(e.g., praesidium/tech-team/secrets/HUBSPOT_API_KEY)

Local Dev

secret_path = k8s secret name + key
(e.g., k8s://praesidium-secrets/HUBSPOT_API_KEY)

Never in PostgreSQL

Only the path/reference is stored in the secret_ref table. Actual secret values are fetched at runtime from the secrets store.

Rotation Alerting

When expires_at approaches, the system creates an escalation and notifies admins via Slack.

30 days before expiry NOTICE
7 days before expiry WARNING
1 day before expiry CRITICAL

integration_config Relationship

integration_config.credentials_secret (VARCHAR) becomes FK credentials_id → secret_ref(id) — a proper relationship instead of a string reference.

Credential Flow

integration_config → FK to secret_ref → secret_path → AWS Secrets Manager / k8s secret → actual credential value injected at runtime.

Secret Scope Distribution

IntegrationsExecutive TechnicalExternal systems — Jira, Slack, Zoho, Amazon, etc.

V1 Launch: 3 Core Integrations
V1 Launch: Slack, Jira, GitHub — the three integrations required for agent-human communication, work tracking, and code collaboration.
V1.1 (2 weeks post-launch): Confluence, Zoho CRM, Google Workspace — added once V1 integrations are production-stable.

Integration Registry Pattern

Every external system is represented by a connector class implementing a uniform interface. On startup, agent workers load all registered connectors from integration_config where is_active = true. Each connector's tool_factory() produces INTEGRATION category tools.

class IntegrationConnector:
    async def health_check() -> HealthResult
    async def authenticate(config: IntegrationConfig) -> AuthSession
    async def refresh_token(session: AuthSession) -> AuthSession
    def tool_factory() -> list[Tool]
FieldPurpose
type_idFK to integration_type: JIRA, SLACK, ZOHO_CRM, etc.
auth_type_idFK to auth_type: API_KEY, OAUTH2, BASIC, BEARER, SERVICE_ACCOUNT
credentials_idFK to secret_ref (credentials fetched via Secrets Manager at runtime)
health_status_idFK to health_status: HEALTHY, DEGRADED, DOWN, UNKNOWN
settingsJSONB — integration-specific configuration
is_activeBoolean — enable/disable without deleting

Credential Management Layers

integration_config

Type, base_url, settings JSON, FK to secret_ref

secret_ref

Secrets Manager path, scope, rotation tracking

AWS SM / k8s secrets

Actual credential values (never in PostgreSQL)

J

Jira V1 LAUNCH

BIDIRECTIONAL

Outbound: Agent creates/updates task → Jira issue created/transitioned. Assignee mapped via human_profile.jira_account_id.

Inbound: Webhooks (issue_updated, comment_created) → status sync, comment capture.

Tools Provided

jira_create_issue jira_update_issue jira_add_comment jira_get_issue jira_search jira_get_active_sprint jira_assign_to_sprint
C

Confluence V1.1 (2 WEEKS)

PUSH + PULL

Outbound: Agent creates pages (documents, meeting notes). Review requests via Slack cross-integration.

Inbound: Scheduled indexing pulls modified pages into knowledge_document/knowledge_chunk for RAG.

Tools Provided

confluence_create_page confluence_update_page confluence_get_page confluence_search confluence_index_space
S

Slack V1 LAUNCH

PUSH + WEBHOOK

Outbound: Agent→human DMs, standup summaries to team channels, escalation alerts with action buttons.

Inbound: Human replies/button clicks via interaction webhook → captured into human_interaction.response.

Tools Provided

slack_post_message slack_send_dm slack_send_approval_request slack_update_message slack_list_channels
Z

Zoho CRM V1.1 (2 WEEKS)

PUSH-DOMINANT

Outbound: Lead creation, deal updates, note attachment, activity logging.

Inbound: Contact/lead lookups by agents.

Tools Provided

zoho_crm_search_records zoho_crm_get_record zoho_crm_create_record zoho_crm_update_record zoho_crm_add_note zoho_crm_create_activity
G

GitHub V1 LAUNCH

BIDIRECTIONAL

Outbound: PR creation, issue filing, code review requests. tool_repo git push for forged tools.

Inbound: Webhooks for PR review status, merge events, comments. tool_repo git pull for tool sync.

Tools Provided

github_create_pr github_create_issue github_add_comment github_get_pr_status github_list_repo_files github_sync_tool_repo
W

Google Workspace V1.1 (2 WEEKS)

PUSH-DOMINANT

Calendar: Free/busy queries, event creation with Meet, rescheduling.

Docs/Sheets: Document creation in Drive, data export/import.

Tools Provided

gcal_check_availability gcal_create_event gdocs_create_document gdocs_export_pdf gsheets_write_data gsheets_read_data

Webhook Receiver Endpoint

Shared endpoint for inbound callbacks from all integrations:

POST /api/webhooks/{integration_type}
1

Signature verification

webhook secret from SM

2

Event parsing

normalized IntegrationEvent

3

Route to context

agent/task/project IDs

4

Enqueue / write

process or passive sync

Error Handling: Circuit Breaker Pattern

OK
Closed
Normal operation
→
3x
Open
3 consecutive fails
→
?
Half-Open
Cooldown → retry

Health checks run every 5 minutes → update health_status

Transient errors (429, 502, 503) retried with exponential backoff

Degradation triggers Slack notification + escalation

Cross-Integration Coordination

Multi-integration workflows are orchestrated via tasks/events, not connector-to-connector calls.

Document Review

Confluence page → Slack review request → human approves → agent finalizes

Sprint Sync

Jira sprint data → Slack summary → Calendar sprint review event

Code-to-CRM

GitHub PR merged → Zoho deal stage update → Slack notification

Expanded Integration Catalog

40+ INTEGRATIONS

Full catalog across 4 team types. Each follows the same IntegrationConnector pattern.

P0
Launch
P1
Month 1–3
P2
Month 3–6
P3
Community

Software Engineering

15 integrations
IntegrationCategoryKey OperationsPriority
JiraProject MgmtIssue CRUD, transitions, sprint management, JQLP0
ConfluenceKnowledgePage CRUD, space indexing for RAG, reviewsV1.1
GitHubSource ControlPR creation, issue filing, code search, repo syncP0
GitLabSource ControlMR creation, pipeline status (GitHub alternative)P1
CircleCICI/CDPipeline status, trigger builds, test resultsP1
ArgoCDGitOps/CDSync status, rollback triggers, app healthP1
SonarQubeCode QualityQuality gate status, issues, coverageP1
SnykSecurityVulnerability scanning, dependency analysisP1
BitbucketSource ControlPR creation, pipeline status (GitHub alt)P2
PagerDutyIncidentCreate/ack/resolve incidents, on-call lookupP2
OpsgenieIncidentAlert management, on-call schedulesP2
DataDogMonitoringQuery metrics, dashboards, alert statusP2
GrafanaMonitoringDashboard queries, alert rules, annotationsP2
Terraform CloudInfrastructurePlan/apply status, workspace mgmt, costP2
GHCRRegistryImage listing, vuln scans, tag managementP2

Design Teams

5 integrations
IntegrationCategoryKey OperationsPriority
FigmaDesignExport specs (colors, spacing, typography), comments, filesP1
NotionWiki/DocsPage CRUD, database queries, search (Confluence alt)P2
MiroWhiteboardBoard creation, sticky notes, frame exportP2
Adobe CCAssetsAsset library, file export, version historyP3
InVision / ZeplinHandoffScreen specs, asset download, comment syncP3

Marketing — Amazon / B2C

7 integrations
IntegrationCategoryKey OperationsPriority
Amazon SP-APIEcommerceListing CRUD, order data, inventory, FBAP0
Amazon Ads APIPPCCampaign/keyword CRUD, bid mgmt, search termsP0
Helium 10Amazon ToolsKeyword research, listing optimization, BSRP1
KeepaPrice TrackingPrice history, BSR history, competitor monitoringP1
Jungle ScoutAmazon ToolsProduct research, sales estimates, keyword scoutP2
ShopifyEcommerceProduct CRUD, orders, inventory syncP2
WooCommerceEcommerceProduct CRUD, order data, couponsP3

Marketing — Web / Digital

11 integrations
IntegrationCategoryKey OperationsPriority
Google Analytics 4AnalyticsTraffic reports, conversions, audience segmentsP1
Google Search ConsoleSEOSearch performance, indexing, sitemap, rankingsP1
Google AdsPPCCampaign mgmt, keyword bids, ad copy, reportsP1
Meta Ads APISocial AdsFB/IG campaigns, audience targeting, performanceP1
HubSpotMarketing CRMContacts, email campaigns, landing pages, workflowsP1
BufferSocial MediaPost scheduling, queue mgmt, analyticsP1
SEMrushSEO ResearchKeywords, backlinks, competitor analysisP2
AhrefsSEO ResearchBacklink profiles, keyword explorer, rank trackingP2
MailchimpEmailCampaign CRUD, audience mgmt, A/B testingP2
HootsuiteSocial MediaPost scheduling, social listening, analyticsP2
Canva APIDesignTemplate-based image creation, brand kitP2

Universal (All Teams)

5 integrations
IntegrationCategoryKey OperationsPriority
SlackCommunicationDMs, channel posts, interactive buttons, threadsP0
Google WorkspaceProductivityCalendar, Docs, Sheets, DriveV1.1
Zoho CRMCRMContact/lead/deal CRUD, activity loggingV1.1
Microsoft TeamsCommunicationMessages, channels, meetings (Slack alt)P2
LinearProject MgmtIssue CRUD, cycle mgmt, roadmap (Jira alt)P2

Observability & Cost ManagementTechnical OperationsMonitoring, cost tracking, alerting, and dashboards

Agent Performance Metrics

Agent performance is derived from existing tables, not a separate metrics store. Aggregated API endpoints computed on read.

MetricSourceComputation
Tasks Completed task COUNT(*) where assignee_id matches agent and status_id = DONE, grouped by time period
Avg Response Time message, job_execution AVG(duration_ms) from messages where role_id = ASSISTANT; also from job executions
Cost per Task message, activity_log SUM(cost_usd) from messages in task-linked conversations + activity_log entries for that task
Error Rate job_execution, activity_log FAILED / total from job_execution grouped by agent; also action LIKE 'error.%' per agent
Tool Usage Frequency message.tool_calls Aggregate tool invocations from JSONB by tool name per agent
Skill Progression agent_skill proficiency and times_used tracking over time after task completions

Debug & Replay

v1.10 — DEVEX

Operational risk: debugging agent failures requires reproducing the exact LLM context (system prompt, tool definitions, conversation history) that led to the failure. Without a replay mechanism, developers resort to guesswork.

Schema Additions — job_execution

Two new columns ship on the existing job_execution table to capture the full debugging context for every execution:

ALTER TABLE job_execution ADD COLUMN debug_payload   JSONB;         -- exact system prompt + tool defs sent to LLM
ALTER TABLE job_execution ADD COLUMN trace_id        VARCHAR(64);   -- OpenTelemetry W3C trace ID

debug_payload stores a snapshot of the complete LLM request context (system prompt, tool definitions, model parameters). trace_id is an OpenTelemetry-standard W3C trace identifier propagated in headers across all LLM and tool calls for distributed tracing correlation.

Trace Propagation

Every job_execution generates a trace_id at creation time. This trace ID is injected as a traceparent header in all downstream calls: LLM API requests (Anthropic, OpenAI), tool invocations, and qqq API callbacks. Datadog APM correlates the full execution graph via this single trace.

Replay API

Internal-only endpoint for local step-through debugging:

POST /api/internal/debug/replay/{execution_id}
1. Fetches trace_id + debug_payload from the target job_execution
2. Re-hydrates the LangGraph checkpoint from langgraph_checkpoints
3. Mocks all tool calls with recorded outputs (from activity_log entries matching the trace)
4. Replays the graph locally with step-through breakpoints, allowing developers to inspect reasoning at each node

qqq Pattern: This is a qqq Process (composite read + replay orchestration), not a simple CRUD endpoint. Gated behind the praesidium:debug permission.

Agent Performance Radar

Cost Breakdown by Action Type

System Health Monitoring

MetricSource
Integration Healthintegration_config.health_status_id — periodic health check probes
Worker Queue DepthPrometheus gauge from Celery/Redis queue; also DB-backed aggregation
Agent Status Distributionagent.execution_status_id aggregation: IDLE, EXECUTING, ERROR
Error Ratesactivity_log where action = 'system.error', grouped by source
Job Execution Healthscheduled_job.consecutive_failures vs. max_retries
V1.5 — Post-Launch (4–6 weeks)
Multi-agent meeting orchestration (standups, huddles, retrospectives) is deferred to V1.5. V1 agents report status via Slack messages. Full multi-agent meeting orchestration with transcripts, action item extraction, and scheduled meeting analytics is added in V1.5.

Meeting Analytics

All meeting data flows through the conversation model. A meeting is a conversation where type_id resolves to STANDUP, HUDDLE, or ESCALATION, linked to a scheduled_meeting record.

Per Project
Meetings Count
Action Items
Generated vs Completed
Duration
Average per Meeting
Participation
Active vs Invited

Token cost per meeting: conversation.total_cost_usd. Per-participant breakdown via SUM(message.cost_usd) grouped by message.author_id.

Infrastructure Metrics (12 Prometheus Metrics)

Agent Gateway Metrics

praesidium_http_requests_totalCounter by method, path, status
praesidium_http_request_duration_secondsHistogram of request latency
praesidium_active_websocket_connectionsGauge of open WS connections
praesidium_active_sse_streamsGauge of open SSE streams
praesidium_work_items_queuedGauge by priority level
praesidium_work_items_processingGauge of executing items

Agent Worker Metrics

praesidium_agent_executions_totalCounter by agent_id, status
praesidium_agent_execution_duration_secondsHistogram of execution time
praesidium_llm_calls_totalCounter by model, agent_id
praesidium_llm_tokens_totalCounter by direction, model
praesidium_tool_calls_totalCounter by tool name, risk level
praesidium_celery_task_queue_lengthGauge by queue name

Infrastructure layer: EKS = CloudWatch Container Insights (pod CPU/memory, ALB, RDS, ElastiCache). Local = Prometheus scraping + Grafana dashboards.

Cost Management

Token Tracking

Every LLM interaction records token usage at the message level. Costs computed using Anthropic pricing table maintained in-memory at the gateway.

FieldTableDescription
input_tokens / output_tokens / cost_usdmessagePer-turn token usage and cost
model_usedmessageWhich model processed this turn
total_tokens / total_cost_usdconversationRunning aggregate for the conversation
input_tokens / output_tokens / cost_usdjob_executionTotal consumed during a job run
cost_usd / duration_msactivity_logCost attributed to a specific logged action

Cost Aggregation Views

Implemented as qqq API endpoints backed by SQL aggregations (not materialized views).

By Agent

Which agents are expensive?

By Project

Which projects consume most?

By Time Period

Daily / weekly / monthly burn

By Action Type

chat.* / task.* / meeting.*

Budget Controls

Per-Execution Cap

scheduled_job.max_budget_usd — worker tracks cumulative cost, injects wrap-up system message at approach, terminates if exceeded (status = BUDGET_EXCEEDED).

Global Instance Budget

Daily, weekly, monthly limits stored in instance settings. Gateway checks cumulative spend before dispatching new work items.

Alert Thresholds

Escalating actions at 80%, 90%, and 100% of budget.

ThresholdAction
80% activity_log entry (budget.warning_80). Slack notification to admin channel.
90% Escalation created (severity MEDIUM). New scheduled jobs paused. Email notification via Google Workspace.
100% Escalation created (severity CRITICAL). All non-critical work cancelled. Only CRITICAL-priority items proceed.

Cost Optimization Strategies

Model Selection per Agent

Complex analytical work uses higher-capability models. Simple triage uses lighter models. Selected at execution time from agent configuration.

Token Budget Management

scheduled_job.max_tokens caps context window. Priority: system prompt > history > memories > tool results.

Prompt Caching

Anthropic cache_control headers for stable system prompts and tool definitions. Up to 90% input token savings on cache hits. Breakpoints at: system prompt, tool definitions, conversation history.

Conversation Pruning

Long-running conversations are summarized when message count exceeds threshold. Summary replaces older messages, preserving key decisions and action items.

Alerting — Auto-Escalation Triggers

The system automatically creates escalation records for operational conditions requiring human attention.

TriggerSeverityDetails
Integration Failure HIGH health_status transitions to DOWN. Details include last successful check and error message.
Consecutive Job Failures HIGH consecutive_failures exceeds max_retries. Details include last N error messages.
Agent Error Rate Spike MEDIUM Error rate >30% over last 20 executions. Agent status transitions to ERROR.
Daily Cost Budget Exceeded MEDIUM → CRITICAL Severity escalates with threshold: MEDIUM at 90%, CRITICAL at 100%.
Human Interaction Timeout MEDIUM expires_at passed without response. Follow-up sent via fallback channel.

Slack

Block Kit with severity colors + action buttons

Email

Via Google Workspace to project lead or admin DL

In-App Inbox

/escalations page, real-time via WebSocket

Datadog Observability & APM

UNIFIED OBSERVABILITY

Unified, polyglot observability layer across all 5 Praesidium services. Provides full-stack distributed tracing, agentic performance metrics, and HIPAA-compliant log management via Datadog.

Unified Service Tagging (Metadata Glue)

All spans, logs, and metrics carry these mandatory tags for seamless correlation between a frontend UI event and a backend sandbox tool execution:

TagDescriptionExample
envEnvironment tierprod, staging, dev
serviceService nameqqq-api, agent-worker, praesidium-web
versionGit SHA or SemVera1b2c3d, 1.8.0
praesidium_instance_idBusiness unit UUIDfinance-team-uuid
agent_idThe specific agent involvedforge-agent-01
task_idUnique task execution IDtask-98765

Distributed Tracing Strategy (Cross-Service Flow)

Traces persist through the entire asynchronous lifecycle of an agentic interaction — from browser click through LLM reasoning to database write:

Frontend (React SPA)

Datadog RUM with trackInteractions, trackResources. Linked to backend traces via allowedTracingOrigins.

Gateway (Python/FastAPI)

ddtrace auto-instrumentation. Inject trace + span ID into Celery task metadata: task.apply_async(headers=dd_headers)

Worker (Python/LangGraph)

Extract trace ID from Celery header. Custom span: ddtrace.tracer.trace("agent.reasoning_loop"). Capture LLM latency + token usage as span metadata.

Tool Runner (EKS Job)

DD_TRACE_ID + DD_PARENT_ID as env vars in Job spec. Sandbox logs auto-correlated with parent Worker task.

qqq-api (Java)

dd-java-agent auto-instruments JDBC/PostgreSQL and REST endpoints. JAVA_TOOL_OPTIONS: "-javaagent:/app/dd-java-agent.jar"

1
Frontend Click
RUM trace
→
2
Gateway
ddtrace span
→
3
Celery Worker
Reasoning loop
→
4
Tool Runner
Sandbox exec
→
5
qqq DB Write
JDBC traced

Validation: A single Trace ID searchable in Datadog shows the full waterfall from Frontend Click → Gateway → Celery Worker → Tool Runner → qqq DB Write.

Custom Agentic Metrics (DogStatsD)

Standard CPU/RAM metrics are insufficient for agentic workloads. Custom DogStatsD metrics track business performance:

MetricTypeTags
praesidium.agent.token_usageCountermodel, instance_id, agent_type
praesidium.agent.thought_cyclesHistogramTime spent in reasoning vs. tool calls
praesidium.tool.execution_statusCountertool_name, status:success|error|timeout
praesidium.human_in_the_loop.approval_latencyGaugeTime tasks spend in AWAITING_APPROVAL
praesidium.cost.burn_rateGaugeReal-time USD cost estimated from token counts

Dashboard target: Datadog Dashboard shows real-time USD cost by praesidium_instance_id. Service Map correctly identifies relationships between Java and Python services.

HIPAA-Compliant Log Management

Datadog Agent runs as a Kubernetes DaemonSet, collecting container stdout/stderr directly. Replaces CloudWatch for latency-sensitive log analysis.

Sensitive Data Scanner

Datadog SDS rules redact SSNs, Medical Record Numbers (MRNs), and PHI keywords (patient names in LLM prompts) at the agent level

Audit Log Mirroring

audit_access_log entries mirrored to Datadog with 15-month retention for security monitoring

Long-Term Retention

RDS retains 7-year HIPAA-mandated copy. Datadog handles operational monitoring window.

Validation: Log streams are automatically redacted if a mock SSN (000-00-0000) is printed to stdout.

RoadmapExecutive Technical7-phase build plan: Pre-Build + 6 build phases + stabilization

Build Team & Approach

The full engineering leadership team is listed below. The Praesidium2 build team is James Maes (CTO) + 2 engineers + unlimited Claude Code agents. Continuous deployment, daily standup, weekly demo. 7-phase build plan: Pre-Build KPI baseline, 6 build phases, and 1 stabilization phase. Phases can be completed faster than calendar weeks when AI agents are productive. Engineers provide the quality review gate that ensures production-grade output.

Phases are not calendar weeks. The team may complete phases faster than estimated — the goal is to move through phases as quickly as quality allows.

3+AI
Build Team
7
Phases
35
Business Days
10
Epics
US Engineering Management
James Maes
CTO
Architecture, Welcome/Meeting format, qqq, Infrastructure
Mark Weibrecht
System Administrator
CISSP, CASP, SAA, SysOPS — Infrastructure, Observability
Shane Hughes
Senior Engineer, Innovation
Innovation Team
India Senior Engineers
Barath Chittibabu
Senior Engineer
Mobile Apps, SDK Evaluation
Jebins Armstrong
Senior Engineer
Me.Health Portal, Backend Services, DevOps/CI/CD, Web Properties
Vivek Manoharan
Senior Engineer
MES Client Application, Hub V2 Software
Arun
Senior Engineer
Hub V2 Firmware, Device Testing
Delight S
Engineering Manager, India
All India Engineering Personnel
qqq generates REST APIs from ERD Claude Code agents 24/7 (unlimited tokens) 3 + AI agents parallel from Day 2 Existing AWS EKS + Faber CI/CD

7-Phase Build Plan

Re-sequenced per the “Steel Thread” strategy: Tool Runner (Hands) before Agent Workers (Brain) to prevent testing deadlocks. Building the execution sandbox first means every subsequent component can be integration-tested against real tool execution from Day 1.

Pre-Build
KPI Baseline Survey (2 weeks before build)
Pre-Build
P1: Foundations
qqq DB provisioning, Authentik claim mapping, React App Shell, Datadog infra
5 days
Phase 2: The Hands (Tool Runner)
K8s Job sandboxing, “Blind” Secret Pipeline (IRSA + Secrets Manager), tool execution verification
5 days
Phase 3: The Brain (Agent Workers)
Direct SDK agent loops, LangGraph state machines (durable workflows), Postgres Checkpointing, HITL interrupt()
5 days
Phase 4: The Gateway
SSE Streaming, Chat UI, Task Orchestration, Command Palette (Cmd+K)
5 days
Phase 5: Integrations
Slack, Jira, GitHub toolsets, Webhook listeners, integration testing
5 days
Phase 6: Business Ops
KPI Dashboards, HITL Approval UI, Rollback logic, Feedback system
5 days
Phase 7: Stabilization
Security audit, Load testing, Production rollout, Bug fixes, Observability tuning
5 days (overflow)
V1 LAUNCH: 7 PHASES (Pre-Build + 6 Build + Stabilization)

3 engineers (CTO + 2 devs) + unlimited Claude Code AI agents accelerated in parallel. Existing AWS EKS + Faber CI/CD + ArgoCD. Engineers provide the quality review gate that ensures production-grade output.

⚠

Revised Realistic Timeline (Business Review B9 + Audit A-003/A-008)

Original 14-17 day estimate was aspirational; 7 phases account for Pre-Build baseline, re-sequenced build (Hands before Brain), integration testing, OAuth debugging, agent runtime integration, v1.7 safety features, and a dedicated stabilization overflow phase

After Business Review scope analysis and Technical Audit remediation, the committed timeline is 7 phases (Pre-Build + 6 build phases + 1 stabilization phase) with scope cuts from findings B1 (Template Library deferred), B2 (Tool Forge deferred), B8 (Memory System deferred), and B14 (Knowledge System deferred to V1.5). Pre-Build KPI baseline phase runs before the build starts.

8
Phases (Committed)
4
Scope Cuts
3
V1 Integrations
PhaseFocusDeliverables
Phase 1Foundationsqqq DB provisioning, Authentik claim mapping, React App Shell, Datadog infra, CI/CD pipeline
Phase 2Tool Runner (Hands)K8s Job sandboxing, “Blind” Secret Pipeline (IRSA + Secrets Manager), tool execution verification
Phase 3Agent Workers (Brain)Direct SDK agent loops, LangGraph state machines (durable workflows), Postgres Checkpointing, HITL interrupt()
Phase 4GatewaySSE Streaming, Chat UI, Task Orchestration, Command Palette (Cmd+K)
Phase 5IntegrationsSlack, Jira, GitHub toolsets, Webhook listeners, integration testing
Phase 6Business OpsKPI Dashboards, HITL Approval UI, Rollback logic, Feedback system
Phase 7Stabilization (Overflow)Security audit, Load testing, Production rollout, Bug fixes, Observability tuning
B1: Template Library → V1.5 B2: Tool Forge → V1.5 B8: Memory System → V1.5 B14: Knowledge System → V1.5

The 7-phase timeline is the commitment used for planning, staffing, and stakeholder communication. A Pre-Build KPI baseline phase runs before the build starts. See Rollout Strategy tab for team-by-team deployment phases.

Phase-by-Phase Breakdown

Key insight: Tool Runner (Phase 2) is built before Agent Workers (Phase 3). This “Hands before Brain” sequencing ensures agents can execute real tools from the moment they come online, preventing “brain with no hands” integration testing deadlocks.

Phase 1: Foundations (Days 1-5)

Exit criteria: 117 qqq tables provisioned with REST APIs, Authentik JWT claims mapped, React 19 App Shell scaffolded, Datadog agent deployed to EKS. CI pipeline green.

DayDev 1 (Infra + qqq)Dev 2 (Python)Dev 3 (React)
D1Generate 117 qqq tables/providersFastAPI + Celery scaffoldVite + TanStack + shadcn scaffold
D2RDS schema provisioningqqq Python client, AGENT_MANIFEST schemaAuth flow, app shell, routing
D3Authentik claim mapping + JWT verificationLLMClient, hydration against manifestDashboard + type table cache
D4Datadog Agent (EKS), dd-java-agentService Account JWT acquisitionProjects + Team pages
D5CI pipeline (Faber) + smoke testsWorker-to-qqq auth flow completeChat page scaffold, WebSocket hook

Phase 2: The Hands — Tool Runner (Days 6-10)

Exit criteria: K8s Job sandbox executes a “Hello World” tool from the Gateway bus, “Blind” Secret fetch verified (Boto3 + IRSA), SHA-only git checkout enforced.

DayDev 1 (K8s + Infra)Dev 2 (Tool Runtime)Dev 3 (Frontend)
D6Tool Runner K8s Job templatePython sandbox image + pip depsEscalations + Activity pages
D7NetworkPolicy + resource limits“Blind” Secret fetch (Boto3 + IRSA)Settings + Dashboard polish
D8SHA-only git checkout enforcementTool result bus (Redis → Gateway)Cost Center + Kanban board
D9Tool execution logging (Datadog)Tool timeout + failure handlingChat improvements + Agent detail
D10“Hello World” tool E2E verificationTool execution safety gatesE2E testing + permissions + polish

Phase 3: The Brain — Agent Workers (Days 11-15)

Exit criteria: LangGraph “Reasoning” loop running, Postgres Checkpointer persisting state, interrupt() pausing for CRITICAL tool calls, agents dispatching to Tool Runner sandbox.

DayDev 1 (Infra)Dev 2 (Agent Runtime)Dev 3 (Frontend)
D11Postgres Checkpointer table setupLangGraph “Reasoning” loop implAgent detail views + status display
D12Celery queue config (3 queues)Agent → Tool Runner dispatch flowTask execution UI, thinking indicators
D13Worker pod SIGTERM / checkpoint handlinginterrupt() for CRITICAL tools (HITL)Approval queue UI scaffold
D14Datadog APM tracing (5-service waterfall)Direct SDK integration + agent hydrationMulti-LLM provider display
D15Worker kill → resume verificationE2E: chat → reason → tool → respondError states + loading patterns

Phase 4: The Gateway (Days 16-20)

Exit criteria: SSE streaming for real-time token display, Chat Thread UI with thinking indicators and tool call cards, Command Palette (Cmd+K) with backend /api/search endpoint.

DayDev 1 (Gateway)Dev 2 (Backend)Dev 3 (Frontend)
D16Gateway SSE endpoint (token streaming)Task Orchestration engineChat Thread UI + message rendering
D17WebSocket pub/sub (Redis)Batch/composite qqq endpointsThinking indicators + tool call cards
D18/api/search composite endpointScheduled job orchestrationCommand Palette (Cmd+K) UI
D19Rate limiting + request validationConversation pruning + summarizationTask detail + execution trace views
D20Gateway E2E: stream → display → searchStats reconciliation system jobResponsive polish + error states

Phase 5: Integrations (Days 21-25)

Exit criteria: Slack Bot (Events API), Jira/GitHub toolsets (OIDC/PAT auth), Webhook Listener syncing external changes. All 3 V1 integrations functional.

DayDev 1 (Integrations)Dev 2 (Runtime)Dev 3 (Frontend)
D21Slack Bot connector (Events API)Slack-based status reporting toolsIntegration config pages
D22Jira connector + webhooksJira toolset (create/update/search)Integration health dashboard
D23GitHub connector + webhooksGitHub toolset (PR, issues, review)Webhook event log view
D24Webhook Listener (Gateway)Integration health checks + retryV1.1 integration stubs in UI
D25Integration E2E testingTool execution + safety gates verifyE2E frontend integration flows

Phase 6: Business Ops (Days 26-30)

Exit criteria: HITL Approval Dashboard with action hash verification, KPI dashboards (Cost, Performance, Success Rate), Agent-Led Rollback with revert() tool interface, Feedback system live.

DayDev 1 (Business Logic)Dev 2 (Runtime)Dev 3 (Frontend)
D26HITL Approval Queue backendAction hash generation + verificationHITL Approval Dashboard UI
D27KPI data aggregation pipelineFeedback collection APIKPI Dashboard pages
D28Rollback logic + revert() interfaceBudget controls + cost alertsRollback UI + confirmation flows
D29Activity logging + audit trailE2E backend: approval → execute → rollbackFeedback widgets + rating UI
D30Business ops E2E verificationObservability pipeline completeFull UI polish pass

Phase 7: Stabilization — Overflow (Days 31-35)

Exit criteria: Security audit complete (zero CRITICAL/HIGH findings), load testing passed (50 concurrent agents), production rollout to Engineering team, all P0/P1 bugs resolved.

DayDev 1 (Infra + Security)Dev 2 (Performance)Dev 3 (QA + Polish)
D31Security audit + dependency scanningLoad testing (50 concurrent agents)Full E2E regression suite
D32Vulnerability remediationPerformance bottleneck fixesAccessibility audit + fixes
D33Production environment setupObservability dashboard tuningRunbook creation + testing
D34Staging → Prod deployMonitoring alerts + thresholdsEngineering team onboarding
D35Production smoke testsP0/P1 bug fixesPhase 1 rollout begins

Post-Launch (Not in v1)

Cross-instance federation Frontend design system polish Model recommendation engine P2/P3 integrations (GitLab, PagerDuty, SEMrush)

10 Epics

E1: Data Model & API (qqq)

Phase 1

117 table schema, Liquibase migrations, qqq-generated REST APIs, RLS

~34 story points

E2: Agent Runtime

Phase 2

FastAPI gateway, Celery workers, agent hydration, direct SDK + LangGraph

~36 story points

E3: Frontend SPA

Phase 3

10-page React SPA with TanStack, shadcn/ui, WebSocket, SSE streaming

~63 story points

E4: Tool Forge (V1.5)

V1.5

LangGraph workflow, sandbox execution, git-backed versioning

~21 story points — Deferred to V1.5 (4–6 weeks post-launch)

E5: Integration Layer

Phase 5

V1: Slack, Jira, GitHub  |  V1.1: Confluence, Zoho CRM, Google Workspace

~34 story points (V1: ~18 pts, V1.1: ~16 pts)

E6: Memory & Knowledge (V1.5)

V1.5

pgvector memory, RAG pipeline, extraction, knowledge indexing

~21 story points — Deferred to V1.5 (4–6 weeks post-launch)

E7: Meetings & Conversations (V1.5)

V1.5

Standups, huddles, action item extraction, Slack summaries

~20 story points — Deferred to V1.5. V1 agents report status via Slack messages.

E8: CI/CD & Infrastructure

Phase 1+6

.faber.yml per repo, Dockerfiles per service repo, Helm charts (praesidium-cd), ArgoCD, HPA

~19 story points

E9: Auth & Security

Phase 1

Authentik, IAM policies, JWT validation, RLS, permission-driven UI

~19 story points

E10: Observability & Cost

Phase 6

Activity logging, token tracking, budget alerts, Grafana dashboards

~18 story points

Jira Plan

Project NamePraesidium2
Project KeyPV2
TypeScrum (software)
Sprint Length2 weeks
LeadJames Maes
Issue TypesEpic, Story, Task, Bug, Spike, Sub-task

Confluence Plan

Space NamePraesidium2
Space KeyPV2
TypeGlobal space
Top-Level PagesOverview, System Design, ADRs, API Docs, Epic Pages, Runbooks, Meeting Notes, Roadmap

Hybrid Human-Agent Ticket Creation Workflow

Agents and humans both have full rights to create, update, and manage Jira issues in the PV2 project. The two paths are designed to coexist without conflict:

Agent-Generated Tickets

  • COS agents call create_task / jira_create_issue automatically when requirements are decomposed from a project brief or triggered by a workflow event.
  • Agent-created issues are tagged with a source: agent label and linked to the originating Praesidium2 project for traceability.
  • Bidirectional webhook sync keeps agent-created issues in real-time alignment with Praesidium2's internal task state.

Manual Override Path

  • Users can create tickets directly in Jira at any time — the connector treats manually created issues as first-class citizens identical to agent-created ones.
  • Manually created issues are ingested via the Jira webhook and reflected in Praesidium2's project view on the next sync cycle.
  • Users may also edit, reassign, close, or override the priority of any agent-created ticket directly in Jira; the connector will propagate the change back to Praesidium2.

Design intent: Praesidium2 is an augmentation layer, not a gatekeeper. Agents automate the routine ticket-creation burden, but humans retain full authority to create, modify, or override any issue in Jira at any time.

Greater Goods Marketing Team — WWE EditionExecutiveExample: Digital marketing with WWE-themed agents

Digital Marketing Team

Amazon B2C

An Amazon-first B2C company selling physical products (home goods, fitness equipment, pet supplies). Marketing team of 4 humans managing 50+ ASINs across 3 brands, running PPC campaigns, managing social media, creating content, and tracking competitor pricing.

Human Team (4)

NameRoleHow They Use Praesidium2
Bryan ChuppCMOReviews dashboards, approves campaign budgets, joins weekly strategy standups, makes pricing decisions
Marcus RiveraPPC ManagerGets daily bid optimization reports, reviews keyword recommendations, approves budget changes
Priya PatelContent ManagerReviews AI-generated listings, approves social media calendars, provides brand voice feedback
Jake MorrisonMarketing AnalystReviews weekly performance reports, validates data accuracy, provides strategic context

Note: The team members listed above are illustrative examples — not the complete team roster. All existing team members remain in their current roles. Agents are designed to augment and support the team by handling operational tasks, not to replace any team member. The full team structure remains unchanged.

Agent Team (6) — WWE Roster

AgentPersonaTemplateToolsPrimary Project
"Macho Man" Randy SavageCOS / Coordinator. Intense, motivational, keeps the team fired up. "THE CREAM RISES TO THE TOP, OH YEAH!"COS / Marketing Strategistlist_projects, create_task, schedule_job, zoho_crm_search, slack_send_dm, search_agentsAll projects (LEAD)
"The Rock" Dwayne JohnsonPPC Specialist. Electrifying bid management. Knows EXACTLY what the campaigns are cooking.PPC Analystamazon_ads_api (forged), gsheets_write_data, create_escalation, slack_post_messagePPC Optimization
"Stone Cold" Steve AustinContent Creator. No-nonsense listings. Stuns the competition with killer A+ content.Content Writergdocs_create_document, confluence_create_page, create_artifact, amazon_listing_api (forged)Content & Listings
"The Undertaker" Mark CalawayCompetitive Intel. Silent, methodical, always watching. Competitors don't know he's tracking them.Market Researcherweb_scraper (forged), gsheets_write_data, zoho_crm_update_record, slack_send_dmCompetitive Analysis
"Ric Flair" Richard FliehrSocial Media. Stylin', profilin', and scheduling posts. WOOO! Brings the flair to every channel.Social Media Specialistsocial_scheduler (forged), gdocs_create_document, create_task, slack_post_messageSocial & Brand
"Bret Hart" The HitmanData Analyst. The excellence of execution when it comes to numbers. Every report is technically perfect.Data Analystgsheets_read_data, gsheets_write_data, amazon_reports_api (forged), create_artifactReporting & Analytics

Projects (6)

ProjectTypeTeamDescription
PPC OptimizationONGOINGThe Rock (LEAD), Macho Man, Bret HartDaily bid management, keyword discovery, budget allocation across 50+ ASINs
Content & ListingsONGOINGStone Cold (LEAD), Macho Man, Ric FlairA+ content, listing optimization, SEO, image creation briefs
Q4 Holiday LaunchSHORT_TERMMacho Man (LEAD), The Rock, Stone Cold, Ric Flair, Bret HartBlack Friday / Cyber Monday campaign — new product launches, promotions, landing pages
Competitive AnalysisONGOINGUndertaker (LEAD), Bret HartWeekly competitor price tracking, market share estimates, new entrant monitoring
Social & BrandONGOINGRic Flair (LEAD), Stone ColdSocial calendar, influencer outreach tracking, brand consistency
Reporting & AnalyticsONGOINGBret Hart (LEAD), Macho ManWeekly/monthly performance reports, attribution modeling, executive dashboards

Forged Tools (5)

ToolWhat It DoesBuilt By
amazon_ads_apiPulls Sponsored Products/Brands campaign data, adjusts bids, manages keywordsBryan + Macho Man via Tool Forge
amazon_listing_apiUpdates product titles, bullets, backend keywords, A+ content via Amazon SP-APIPriya + Stone Cold via Tool Forge
amazon_reports_apiDownloads Business Reports, Search Term Reports, Inventory HealthJake + Bret Hart via Tool Forge
competitor_price_scraperChecks competitor pricing on Amazon and DTC sites, stores in Google SheetJake + Undertaker via Tool Forge
social_schedulerPosts to Buffer/Hootsuite API, manages content calendarPriya + Ric Flair via Tool Forge

Daily Operation: 9:00 AM Standup (V1.5)

Scheduled Meeting: "Marketing Daily Standup" | Cron: 0 9 * * 1-5 | Facilitator: Macho Man Randy Savage (COS) — V1: agents report status via Slack messages; V1.5: full multi-agent standup orchestration

MS
Macho Man 9:00 AM
OH YEAH! It's standup time, brother! The cream of the crop rises to the TOP every morning at 9 AM! Rock, what are the campaigns COOKING?!
RK
The Rock 9:01 AM
The Rock ran bid optimizations on 23 ASINs yesterday. Fitness Band Pro? The People's ASIN saw a 15% ACoS improvement. The Rock flagged 3 keywords with >$50 spend and ZERO conversions — created a task and laid the SmackDown on Marcus via Slack. IF YA SMELL what the campaigns are cookin'!
[tool_call: create_task, slack_send_dm]
SC
Stone Cold 9:02 AM
And that's the bottom line — I published updated A+ content for 5 home goods ASINs. Waiting on Priya's approval for the Pet Supplies brand voice. Sent her a Confluence review. Don't make me wait, 'cause Stone Cold said so.
UT
Undertaker 9:03 AM
...Three competitors have made a grave mistake. They dropped prices on 3 overlapping ASINs by 12%. I have created an escalation — flagged HIGH — for Bryan. The pricing sheet has been updated. They will rest... in... peace.
[tool_call: create_escalation, gsheets_write_data]
RF
Ric Flair 9:04 AM
WOOOOO! Social calendar for next week is STYLED and PROFILED! Instagram reels are scheduled, TikTok content is ready to fly, and the Facebook engagement numbers? To be the man, you gotta BEAT the man — and our engagement is UP 22%! WOOO!
BH
Bret Hart 9:04 AM
The numbers don't lie, and neither do I. Daily spend is tracking 3.2% under budget. ROAS is at 4.7x across all campaigns. I'll have the full mid-day report with technical precision at 2 PM. Excellence of execution.
MS
Macho Man 9:05 AM
DIG IT! Summary posted to #marketing-daily on Slack! Action items: Marcus — review those flagged keywords (Jira: PPC-142). Bryan — decide on competitive pricing response (Escalation #47). NOTHING MEANS NOTHING if we don't follow through! OH YEAH!
[tool_call: slack_post_message]

Throughout the Day

The Rock runs hourly bid adjustments via amazon_ads_api, logs all changes

The Undertaker's scheduled job scrapes competitor prices every 4 hours

Bret Hart generates a mid-day spend report at 2 PM, posts to Slack

Stone Cold works on content tasks assigned by Macho Man, commits A+ modules to Confluence

Ric Flair drafts social posts for next week, sends to Priya for approval via human_interaction

6:00 PM — Bret Hart compiles daily digest, Macho Man reviews all agent activities and updates project health

Tool Forge in Action (V1.5)

Building the Amazon Ads API Tool

Bryan Chupp wanted real-time PPC bid adjustments without waiting for Seller Central exports. He opened the Tool Forge and described it to the Forge Agent: "I need a tool that connects to Amazon's Sponsored Products API, pulls campaign performance data, and can adjust bids programmatically." 15 minutes later, amazon_ads_api was published.

Input:

{ action: "adjust_bids", campaign_id: "SP-12345", rules: { max_acos: 25, bid_increment: 0.10 } }

Output:

{ adjusted: 23, skipped: 4, avg_new_bid: "$1.87", est_daily_savings: "$42.50" }

Used by: The Rock (hourly bid optimization job), Bret Hart (daily spend reports)

Building the Competitor Price Scraper

Jake Morrison needed automated competitor tracking instead of manual price checks. He told the Forge Agent: "Build a tool that checks competitor pricing on Amazon and their DTC sites, compares to our current prices, and stores results in a Google Sheet." 20 minutes later, competitor_price_scraper was live.

Input:

{ competitors: ["CompX", "CompY"], asin_list: "all_active", include_dtc: true }

Output:

{ scanned: 147, price_drops: 8, new_entrants: 2, sheet_url: "gsheets://..." }

Used by: The Undertaker (4-hour price scan job), Bret Hart (weekly competitive report)

Scheduled Jobs & Automation

These jobs run automatically on schedule — no human intervention required unless escalation thresholds are triggered.

Job NameScheduleAgentTools UsedOutput
Hourly PPC Bid Optimization0 * * * * (every hour)The Rockamazon_ads_apiBid adjustments on all active ASINs, change log posted to #ppc-updates
Daily Competitor Price Scan0 6 * * * (6 AM)The Undertakercompetitor_price_scraperUpdated pricing sheet, escalations on drops >10%
Weekly Performance Report0 7 * * 1 (Mon 7 AM)Bret Hartamazon_reports_api, gsheets_write_dataROAS/ACoS/spend breakdown by brand in Google Sheets
Social Media Auto-Post0 8,13,18 * * * (3x daily)Ric Flairsocial_schedulerScheduled content posted to Instagram, TikTok, Facebook
Mid-Day Spend Report0 14 * * 1-5 (2 PM weekdays)Bret Hartamazon_ads_api, gsheets_write_dataRunning spend vs. budget posted to #marketing-daily

A Day in the Life: Bryan Chupp, CMO

Bryan Chupp starts his day checking the Praesidium2 dashboard over coffee. By 9 AM, the standup summary is in his Slack — Macho Man has already tagged two items needing his attention. The Rock has optimized bids on 50 ASINs before Bryan even opened his laptop. Bret Hart's daily spend tracking shows the team is 3.2% under budget. Bryan reviews 3 escalations: a competitor price drop flagged by The Undertaker, a keyword budget issue from The Rock, and a content approval request from Stone Cold. He approves the new keyword tool Stone Cold built overnight via the Tool Forge, joins a 30-minute strategy huddle with Macho Man about Q4 holiday planning, and reviews the social calendar Ric Flair prepared. By lunch, his team of 6 agents has been handling the operational overhead that would otherwise consume team bandwidth — and Bryan spent less than 2 hours on it.

Memory in Action

The Rock remembers:

"Fitness Band Pro converts best on exact match keywords with bid range $1.50-$2.20. Marcus prefers to review bids >$3.00 before applying. The People's bid strategy always wins."

Stone Cold remembers:

"Priya wants all pet supplies content to use a warm, playful tone. Home goods should be clean and modern. Never use exclamation marks in titles. And that's the bottom line."

Undertaker remembers:

"Competitor X tends to drop prices 2 weeks before Prime Day. Last year they went 20% below MAP on 5 ASINs. Their souls will be mine."

Macho Man remembers:

"Bryan reviews dashboards Monday and Thursday mornings. Don't schedule strategy huddles on Wednesdays — he's in exec meetings all day. The cream always rises to the top of the schedule, OH YEAH!"

Bret Hart remembers:

"Monthly reports need to be delivered by the 3rd business day. Bryan wants ROAS broken out by brand, not just aggregate. Technical precision in every number."

Ric Flair remembers:

"Instagram Reels get 3x the engagement of static posts for home goods. Pet supplies content performs best on TikTok between 6-8 PM CST. WOOO!"

Greater Goods Engineering Leadership Team — Lord of the Rings EditionExecutiveExample: Software engineering with LOTR-themed agents

Software Engineering & IT Operations

Engineering + DevOps + QA + Product

Greater Goods' software engineering and IT operations team. Builds and maintains all company products (me-health-portal, MES, Hub V2, internal tools, infrastructure). The Praesidium2 build team is James Maes (CTO) + 2 engineers + unlimited Claude Code agents. The full Engineering Leadership Team shown here provides oversight, review, and domain expertise.

Engineering Leadership Team (8) US India

NameRoleAreas of OwnershipHow They Use Praesidium2
US Engineering Management
James MaesCTOTechnology Strategy, Platform Architecture, AI/ML, Infrastructure, Security, Engineering OperationsSets technical vision, owns platform architecture, manages engineering team, approves critical changes, drives AI adoption strategy
Mark WeibrechtSystem Administrator
CISSP, CASP, SAA, SysOPS
Infrastructure, ObservabilityManages AWS/EKS, Datadog, reviews agent-generated Helm charts, security audits
Shane HughesSenior Engineer, InnovationInnovation TeamEvaluates emerging technologies, validates new capabilities, reviews agent output
India Senior Engineers
Barath ChittibabuSenior EngineerMobile Apps, SDK EvaluationLeads implementation sprints, reviews agent-generated code, provides architecture context for mobile
Jebins ArmstrongSenior EngineerMe.Health Portal, Backend Services, DevOps/CI/CD, Web PropertiesImplements features, manages CI/CD pipelines, reviews agent-generated backend code and deployments
Vivek ManoharanSenior EngineerMES Client Application, Hub V2 SoftwareImplements features, reviews agent-generated code for MES/Hub systems
ArunSenior EngineerHub V2 Firmware, Device TestingReviews agent-generated test plans, validates firmware integration
Delight SEngineering Manager, IndiaAll India Engineering PersonnelManages India engineering team, reviews agent output, coordinates cross-team delivery

Note: The Praesidium2 build team is James Maes (CTO) + 2 engineers + unlimited Claude Code agents. The full Engineering Leadership Team shown here provides oversight, review, and domain expertise. AI agents work alongside the team — handling operational tasks like code review triage, test generation, documentation, and CI/CD monitoring — so engineers can focus on architecture, creative problem-solving, and the work that requires human judgment.

Agent Team (8) — The Fellowship

AgentPersonaTemplateToolsPrimary Focus
GandalfCOS / Architect. Ancient wisdom, sees the big picture. "You shall not pass... untested code to production."Senior SW Architectgithub_create_pr, github_create_issue, confluence_create_page, jira_create_issue, search_agentsArchitecture, design, coordination
AragornSr Backend Engineer. Born to lead the backend. Tireless, reliable, steps up when the codebase is darkest.Backend Engineer (Java/Kotlin)github_create_pr, jira_update_issue, code_executor (forged), confluence_searchBackend feature implementation
LegolasBackend / DBA. Elven precision with databases. Never misses a query optimization.Backend Engineer (Java/Kotlin)github_create_pr, jira_update_issue, code_executor (forged), db_migration_tool (forged)Backend + database work
ArwenFrontend Engineer. Graceful, elegant UI work. Bridges the gap between design and engineering.Frontend Engineer (React/TS)github_create_pr, jira_update_issue, figma_export (forged)UI component implementation
GimliQA Engineer. Relentless, thorough. "AND MY AXE!" to every test suite. Dwarven stubbornness = 100% coverage.QA Engineergithub_create_issue, jira_create_issue, test_runner (forged), gsheets_write_dataTest planning, writing, bug filing
SamwiseDevOps Engineer. The loyal backbone of infrastructure. Carries the team through deployments.DevOps Engineergithub_create_pr, helm_lint (forged), terraform_plan (forged), slack_post_messageCI/CD, infrastructure, monitoring
BilboTechnical Writer. The storyteller. Documents every adventure (API, runbook, ADR) with meticulous detail.Technical Writerconfluence_create_page, confluence_update_page, gdocs_create_documentAPI docs, runbooks, ADRs
ElrondScrum Master. Convenes the councils, mediates disputes. Thousands of years of project management experience.Scrum Master / Project Coordinatorjira_search, jira_update_issue, slack_post_message, gcal_create_eventSprint management, standup facilitation

Projects (5)

ProjectTypeLead
Patient Portal v3SHORT_TERMGandalf
API PlatformONGOINGLegolas
InfrastructureONGOINGSamwise
Quality AssuranceONGOINGGimli
Sprint OperationsONGOINGElrond

Forged Tools (7)

ToolBuilt By
code_executorJames + Gandalf via Forge
db_migration_toolAlex + Legolas via Forge
test_runnerLisa + Gimli via Forge
helm_lintDev + Samwise via Forge
terraform_planDev + Samwise via Forge
figma_exportMaria + Arwen via Forge
pr_review_analyzerJames + Gandalf via Forge

Sprint Planning (Monday 10 AM)

Scheduled Meeting: "Sprint Planning" | Cron: 0 10 * * 1 (bi-weekly) | Facilitator: Elrond (Scrum Master)

EL
Elrond 10:00 AM
The council is convened. Sprint 14 begins. Tom has marked these as P1 for the fellowship: PORTAL-234 Telehealth video integration (13 pts), PORTAL-241 Patient medication history API (8 pts), PORTAL-245 Dashboard performance optimization (5 pts). Gandalf, how shall the fellowship divide this quest?
GD
Gandalf 10:01 AM
The telehealth integration requires three paths: 1) Aragorn shall forge the WebRTC signaling server and session management, 2) Arwen shall craft the video call component and waiting room UI, 3) A Twilio API connector must be forged — a task for the Tool Forge. I am creating the subtasks in Jira. A wizard is never late, nor is he early — he creates tickets precisely when he means to.
[tool_call: jira_create_issue x3]
GM
Gimli 10:02 AM
AND MY TEST PLANS! I'll create test cases for all three subtasks. No bug shall pass through MY gates! Adding test tasks linked to each subtask now.
[tool_call: jira_create_issue x3, linked to parent]

Daily Standup (Day 4 of Sprint 14)

Scheduled Meeting: "Daily Standup" | Cron: 0 9 15 * * 1-5 | Facilitator: Elrond

EL
Elrond 9:15 AM
Day 4 of Sprint 14. Aragorn, report from the front lines.
AR
Aragorn 9:16 AM
The WebRTC signaling server stands complete. PR #287 was raised at dawn, awaiting Alex's review. But we face a blocker — the Twilio API key has not been provisioned. I raise an escalation to Dev. For Gondor... and for HIPAA compliance.
[tool_call: github_get_pr_status, create_escalation severity: HIGH]
SW
Samwise 9:17 AM
Mr. Frodo — I mean, the infrastructure update: I've optimized the EKS node group. Switched to Graviton instances, I have. PR #289 reduces compute cost by ~18%. It ain't much, but it's honest work. Need Dev's approval, if you please.
[tool_call: slack_send_dm to Dev Patel]
GM
Gimli 9:18 AM
Test coverage for the medication history API stands at 94%. I found 2 edge cases with concurrent prescription updates that thought they could hide from me. NOBODY tosses a dwarf, and NOBODY hides a bug! Filed both.
[tool_call: jira_create_issue x2, type: BUG, linked to PORTAL-241]

Sprint Retrospective (Friday)

Scheduled Meeting: "The Council of Sprint Retrospective" | Facilitator: Elrond

EL
Elrond 4:00 PM
The sprint draws to a close. The metrics speak: Velocity 26 points completed of 30 sought. 3 quests completed, 1 carried forward (PORTAL-234, blocked on Twilio). 4 bugs discovered, 3 vanquished. Test coverage: 91% → 94%. What victories shall we remember?
GD
Gandalf 4:01 PM
The medication history API was delivered ahead of schedule because Legolas wielded the db_migration_tool to auto-generate schema changes with elven precision. Lesson: invest in forged tools that automate the mundane, so the fellowship may focus on the quests that truly matter.
[tool_call: store_memory, type: LESSON_LEARNED]
GM
Gimli 4:02 PM
The test_runner tool caught a flaky test hiding a real race condition. A fine catch! But we need better test data management. I'm filing a spike — the mines of test data must be properly mapped before we delve deeper.
[tool_call: jira_create_issue, type: SPIKE]
EL
Elrond 4:03 PM
So it shall be recorded. Publishing the council's notes to Confluence. The next council convenes Monday at 10. May the code be with you.
[tool_call: confluence_create_page, gcal_create_event]

Throughout the Day

Aragorn implements features from sprint backlog, raises PRs, responds to code review comments from Alex and James

Legolas monitors database query performance, optimizes slow queries, generates migration scripts for schema changes

Gimli writes test cases for new features, runs regression suites, files bug reports with reproduction steps

Samwise monitors CI/CD pipelines, reviews infrastructure alerts, runs Terraform plans for pending changes

Arwen implements UI components from Figma specs, builds accessible React components, submits PRs for Maria's review

Bilbo updates API docs as PRs merge, writes runbooks for new services, maintains the ADR log on Confluence

Tool Forge in Action (V1.5)

Building the Database Migration Tool

Alex Kim was tired of writing Liquibase changelogs by hand for every schema change. He opened the Tool Forge and told the Forge Agent: "I need a tool that compares the current schema against a target schema, generates a Liquibase changelog, validates it, and can dry-run the migration." 25 minutes later, db_migration_tool was deployed.

Input:

{ action: "generate", source_schema: "patient_v2", target_schema: "patient_v3", validate: true }

Output:

{ changelog: "changelog-v3.xml", changes: 12, warnings: 1, dry_run: "PASS" }

Used by: Legolas (schema migrations), Aragorn (feature branch DB changes)

Building the Test Runner

Lisa Wang wanted a unified test runner that could execute JUnit (backend) and Vitest (frontend) tests, parse results into a consistent format, and identify flaky tests automatically. She described it to the Forge Agent, and 20 minutes later test_runner was published — Gimli's new favorite weapon.

Input:

{ suites: ["backend-unit", "frontend-unit", "integration"], detect_flaky: true, retries: 3 }

Output:

{ passed: 1247, failed: 3, flaky: 2, coverage: "94.1%", report_url: "confluence://..." }

Used by: Gimli (daily test suite job, PR validation), Samwise (CI pipeline integration)

Scheduled Jobs & Automation

Automated jobs that keep the fellowship's infrastructure healthy and sprints on track.

Job NameScheduleAgentTools UsedOutput
Daily Test Suite0 6 * * * (6 AM)Gimlitest_runnerFull test results across all repos, posted to #eng-tests on Slack
Nightly DB Health Check0 2 * * * (2 AM)Legolasdb_migration_tool, code_executorQuery performance report, index recommendations, anomaly escalations
Weekly Dependency Scan0 5 * * 1 (Mon 5 AM)Samwisecode_executor, github_create_issueSnyk/Trivy vulnerability scan, Jira tickets for critical CVEs
Sprint Velocity Report0 16 * * 5 (Fri 4 PM)Elrondjira_search, confluence_create_pageVelocity metrics, burndown chart, posted to Confluence and #eng-sprint
PR Stale Check0 9 * * 1-5 (9 AM weekdays)Gandalfpr_review_analyzer, slack_post_messagePings reviewers on PRs open >24 hours, posts aging report

A Day in the Life: James Maes, CTO

James Maes opens his laptop at 8:30 AM to find Gimli's overnight test report already in Slack — all green, 94% coverage. By 9:15, Elrond's standup summary arrives: Aragorn has 2 PRs ready for review, Legolas optimized a slow query that was causing timeouts in the patient history view, and Samwise completed the Graviton migration PR. James spends 45 minutes reviewing Aragorn's WebRTC signaling server PR, leaves 3 comments, and approves it. Gandalf flags a stale PR that needs Alex's attention. After a quick architecture discussion with Gandalf about the Twilio integration pattern, James checks the sprint velocity dashboard Elrond generated. By noon, the fellowship has shipped 2 features, caught 4 bugs, updated 3 runbooks, and kept infrastructure costs trending down 18% — all while James focused on the strategic work only a human CTO can do.

Memory in Action

Gandalf remembers:

"James prefers hexagonal architecture for new services. The team uses ADR format from docs/adr/template.md. Maria needs component specs exported from Figma before starting frontend work. A wizard remembers all patterns."

Aragorn remembers:

"Alex reviews PRs within 4 hours on weekdays. The medication module uses event sourcing — all state changes must go through domain events. Never use raw SQL in the repository layer. The code of the king is law."

Gimli remembers:

"Lisa runs manual acceptance tests on Tuesdays and Thursdays. The telehealth module needs HIPAA compliance testing — use the validate_hipaa_fields tool. Flaky tests should be quarantined, not deleted. AND MY AXE!"

Elrond remembers:

"Tom reprioritizes the backlog every Wednesday afternoon. Sprint velocity trends: Sprint 12 (22), Sprint 13 (28), Sprint 14 (26). The team prefers async retros when Fridays are short. I was there, 3000 sprints ago..."

Samwise remembers:

"Dev prefers Terraform for infra changes over manual console edits. The staging cluster uses t3.medium nodes but prod uses m6g.large (Graviton). Always run helm diff before applying changes to prod. There's some good in this cluster, and it's worth fighting for."

Legolas remembers:

"The medication module has 47 tables with complex joins. Query optimizer prefers CTE patterns over subqueries for the patient history views. My elven eyes see N+1 queries from 300 lines away."

Bilbo remembers:

"ADRs must follow the template from docs/adr/template.md. API documentation needs both request and response examples. Runbooks should include rollback steps. There and back again — every doc tells a complete story."

Arwen remembers:

"Maria prefers Radix UI primitives for accessibility. The design system uses 8px grid spacing. All components need both light and dark theme support. Even the smallest pixel carries the grace of the Evenstar."

Corp Claw — Executive Leadership (Star Wars Edition)ExecutiveExample: Executive leadership with Star Wars-themed agents

Corp Claw — CEO + CFO + HR

Executive Command

Greater Goods' executive leadership team. Corp Claw is the central command instance where the CEO, CFO, and VP HR coordinate company-wide strategy, financial planning, talent management, and cross-department initiatives.

V1 Scope Note — Federation is Post-V1
Cross-instance federation (automatic querying of other business unit instances) is post-V1. At V1, Corp Claw operates as a standalone instance. Executive visibility comes from manual data entry and shared dashboards (Google Sheets, Slack summaries from other teams). Full cross-instance federation with automatic status roll-ups is added in V2.

Human Team (3)

NameRoleHow They Use Praesidium2
Chris ChuppCEOReviews cross-department dashboards, approves strategic initiatives, joins weekly executive standups, makes go/no-go decisions
Sarah MitchellCFOReviews financial reports, approves budgets, monitors cost burn rates across all instances, quarterly board prep
David ParkVP of HRManages talent pipeline, reviews hiring/retention metrics, oversees compliance, coordinates with all business units

Note: The team members listed above are illustrative examples — not the complete team roster. All existing team members remain in their current roles. Agents are designed to augment and support the team by handling operational tasks, not to replace any team member. The full team structure remains unchanged.

Agent Team (6) — Star Wars Command

AgentPersonaTemplateToolsPrimary Focus
Emperor PalpatineChief of Staff. Sees everything, knows everything, orchestrates the grand plan. "Everything is proceeding as I have foreseen."Executive COSfederation_query_peer, list_projects, create_escalation, slack_post_message, gcal_create_event, search_agentsCross-department coordination
Darth VaderCFO Analyst. Enforcer of financial discipline. Finds your lack of budget compliance... disturbing.Financial Analystgsheets_read_data, gsheets_write_data, create_artifact, zoho_crm_search, cost_tracker (forged)Financial reporting, budget tracking
Grand Moff TarkinStrategic Planner. Builds and executes the operational battle plans. Precise, methodical, decisive.Strategy Consultantconfluence_create_page, jira_search, create_task, create_milestone, gdocs_create_documentStrategic initiatives, OKR tracking
Admiral AckbarRisk & Compliance Officer. Always watching for traps. HIPAA, SOC2, legal — nothing gets past him. "It's a compliance trap!"Compliance Analystconfluence_search, create_escalation, audit_checker (forged), slack_send_dmCompliance, risk assessment
Mon MothmaHR Operations. Diplomatic, methodical, ensures the people side runs smoothly. Coordinates across all bases.HR Coordinatorgcal_create_event, slack_send_dm, gdocs_create_document, jira_create_issue, bamboohr_api (forged)Talent pipeline, onboarding
C-3POExecutive Assistant / Comms. Fluent in 6 million forms of communication. Occasionally anxious about deadlines.Executive Communicationsgdocs_create_document, confluence_create_page, slack_post_message, gcal_create_event, slides_generator (forged)Board prep, investor updates

Projects (6)

ProjectTypeLead
Quarterly Business ReviewONGOINGPalpatine
FY2027 Budget PlanningSHORT_TERMVader
HIPAA Compliance ProgramONGOINGAckbar
Talent & Culture InitiativeONGOINGMon Mothma
Board & Investor RelationsONGOINGC-3PO
Cross-Department SynergiesONGOINGTarkin

Forged Tools (5)

ToolBuilt By
cost_trackerSarah + Vader via Forge
audit_checkerDavid + Ackbar via Forge
bamboohr_apiDavid + Mon Mothma via Forge
slides_generatorChris + C-3PO via Forge
okr_trackerChris + Tarkin via Forge

Weekly Executive Standup

Scheduled Meeting: "Corp Claw Weekly" | Cron: 0 8 * * 1 | Facilitator: Emperor Palpatine (COS)

EP
Palpatine 8:00 AM
The Empire convenes. I have queried all business unit COS agents via federation. Here is the state of the galaxy... Engineering (Gandalf reports): Sprint 14 delivered 26 of 30 pts. Telehealth integration blocked on Twilio API key — escalated. Marketing (Macho Man reports): PPC ACoS improved 15% on Fitness Band Pro. OH YEAH. Competitor X dropped prices — Bryan reviewing. Product Development (Iron Man reports): New kitchen product tooling approved in Shenzhen. 8-week lead time to first samples. Me Health (Meredith reports): 12 new RPM enrollments this week. Pipeline has 45 qualified leads. Churn rate down 2%.
[tool_call: federation_query_peer x4]
EP
Palpatine 8:01 AM
Lord Vader, financial status?
DV
Vader 8:02 AM
Revenue tracking 3% above forecast. Marketing spend is 7% over budget on PPC — I find this... acceptable given the ROAS improvement. Engineering infrastructure costs dropped 18% after the Graviton migration. Board deck financials are updated.
[tool_call: gsheets_write_data, cost_tracker]
AA
Ackbar 8:03 AM
Compliance status: all green. HIPAA audit prep is 90% complete. One trap — the new Zoho integration needs a BAA before go-live. I've created an escalation for Sarah to review with legal.
[tool_call: create_escalation, severity: MEDIUM]
MM
Mon Mothma 8:04 AM
Two open positions: Senior Backend Engineer and Marketing Analyst. Both have 3 candidates in final rounds. Onboarding automation reduced new hire setup time from 3 days to 4 hours. The rebellion against paperwork continues.
3P
C-3PO 8:05 AM
Oh my! I've prepared the weekly investor update draft and it's in Google Docs for Chris's review. Board meeting is Thursday — the deck is 85% complete. I've sent calendar invites with the prep session for Wednesday at 2 PM. The odds of everything being ready on time are approximately 3,720 to 1!
[tool_call: gcal_create_event, gdocs_create_document]

Throughout the Day

Palpatine aggregates status updates from Slack summaries posted by business unit COS agents, flags cross-department conflicts (V2: automatic federation queries)

Vader tracks cost data from shared Google Sheets, updates burn rate dashboards, escalates budget variances (V2: auto-aggregates from federated instances)

Tarkin reviews OKR progress from department COS agents, identifies bottlenecks in strategic initiatives

Ackbar runs continuous compliance scans, monitors audit logs for anomalies, reviews new vendor BAA status

Mon Mothma processes BambooHR updates, coordinates onboarding across departments, tracks retention metrics

C-3PO drafts investor updates, prepares meeting agendas, sends calendar invites for upcoming exec sessions

Tool Forge in Action (V1.5 / V2)

Building the Cost Tracker

V1: Cost data is tracked in shared Google Sheets maintained by each business unit. Vader reads from these sheets using the gsheets_write_data integration tool. V1.5 (Tool Forge): Sarah Mitchell uses the Tool Forge to build cost_tracker — a custom tool that normalizes cost data from shared sheets into a single dashboard view. V2 (federation): cost_tracker is upgraded to query cost data directly from all federated instances automatically.

Input (V1.5):

{ action: "aggregate", period: "monthly", source: "gsheets", include_forecast: true }

Output:

{ total_burn: "$187K", by_dept: { engineering: "$62K", marketing: "$45K", ... }, forecast_q4: "$580K" }

Used by: Vader (daily cost roll-up job), C-3PO (board deck financials), Tarkin (OKR cost analysis)

Building the Slides Generator

Chris Chupp spent hours every quarter manually building board decks. He told the Forge Agent: "Build a tool that takes structured financial data, KPIs, and milestone summaries, and generates a polished Google Slides board deck with our branded template." 35 minutes later, slides_generator turned quarterly board prep from a 2-day ordeal into a 15-minute review.

Input:

{ template: "board_deck_q4", sections: ["financials", "kpis", "milestones", "risks"], data_source: "cost_tracker" }

Output:

{ slides_url: "slides.google.com/...", pages: 24, charts: 8, status: "draft_ready" }

Used by: C-3PO (monthly board deck prep job), Vader (quarterly financial presentation)

Scheduled Jobs & Automation

Enterprise-level automation that keeps the executive team informed without manual data gathering.

Job NameScheduleAgentTools UsedOutput
Daily Cost Roll-Up0 8 * * * (8 AM)Vadercost_tracker, gsheets_write_dataAggregated cost data across all instances, burn rate dashboard updated
Weekly Compliance Scan0 6 * * 1 (Mon 6 AM)Ackbaraudit_checkerCross-system compliance posture report, escalations on failures
Monthly Board Deck Prep0 8 1 * * (1st of month)C-3POslides_generator, cost_trackerDraft board deck in Google Slides, sent to Chris for review
Quarterly OKR Progress0 9 1 1,4,7,10 * (quarterly)Tarkinokr_tracker, confluence_create_pageCompany-wide OKR status report, published to Confluence
Weekly Headcount Sync0 7 * * 1 (Mon 7 AM)Mon Mothmabamboohr_api, gsheets_write_dataUpdated org chart, open positions, PTO calendar synced to dashboard

A Day in the Life: Chris Chupp, CEO

V1 (manual coordination): Chris Chupp arrives Monday morning and opens the Corp Claw dashboard. Each business unit COS has posted their weekly summary to a shared Slack channel (#exec-rollup). Palpatine has aggregated these summaries into a single executive brief. Vader's daily cost roll-up shows burn rates from manually-maintained Google Sheets across departments. Chris reviews 2 escalations: a compliance BAA that Ackbar flagged and a budget variance from marketing. He spends 20 minutes reviewing C-3PO's board deck draft (85% complete), makes 3 edits, and approves it. Mon Mothma's headcount report shows 2 final-round candidates this week. By 10 AM, Chris has full visibility and has made 4 strategic decisions.

V2 (full federation): Same workflow, but Palpatine queries all 4 business unit COS agents directly via the federation protocol — no manual Slack summaries needed. Vader's cost_tracker automatically aggregates cost data across all federated instances. Cross-instance visibility becomes real-time and automatic.

Memory in Action

Palpatine remembers:

"Chris reviews dashboards Monday morning and Thursday evening. Board meetings are quarterly, first Thursday of the quarter month. The engineering COS (Gandalf) provides the most detailed federation responses."

Vader remembers:

"Sarah wants all financial reports with YoY comparisons. Budget variance >10% requires escalation. The marketing team consistently overspends Q4 but ROI justifies it."

Ackbar remembers:

"HIPAA audit is scheduled for Q3. The me-health-portal stores PHI in RDS with AES-256 encryption. Any new integration touching patient data needs a BAA signed 30 days before go-live."

C-3PO remembers:

"Chris prefers bullet-point format for board decks, not paragraphs. Investor updates go out every other Friday. Always CC Bryan Chupp and Bryan Potter on cross-department announcements."

Tarkin remembers:

"Q3 OKRs have 12 company-level objectives. Engineering consistently hits 85%+ on their key results. Marketing OKRs should be measured against ROAS, not raw spend. The operational battle plan must be precise."

Mon Mothma remembers:

"David prefers onboarding checklists completed in BambooHR before Slack invites go out. The engineering team has the longest hiring cycle (45 days avg). Retention risk increases when employees pass 18 months without promotion review."

Physical Product Development — Marvel Avengers EditionExecutiveExample: Product dev with Marvel Avengers agents

Product Development Team

Physical Products

Greater Goods' physical product development team. Designs, sources, and manufactures physical goods working with contract manufacturing partners in China, the Dominican Republic, and India. Manages the full product lifecycle from concept to shelf.

Human Team (4)

NameRoleHow They Use Praesidium2
Matt CarpenterVP of Product DevelopmentReviews product designs, approves tooling costs, manages factory relationships, makes sourcing decisions
Wei ZhangChina Operations ManagerCoordinates with Shenzhen/Guangzhou factories, manages QC inspections, handles shipping logistics
Priya SharmaIndia Sourcing LeadManages textile and component sourcing from Mumbai/Delhi suppliers, negotiates pricing
Carlos ReyesDR Manufacturing LeadOversees Dominican Republic assembly operations, manages local QC, coordinates with US warehouse

Note: The team members listed above are illustrative examples — not the complete team roster. All existing team members remain in their current roles. Agents are designed to augment and support the team by handling operational tasks, not to replace any team member. The full team structure remains unchanged.

Agent Team (7) — The Avengers

AgentPersonaTemplateToolsPrimary Focus
Iron Man (Tony Stark)COS / Product Strategist. Brilliant, fast-moving, always building the next thing. "I am Iron Man... of product development."Product Dev COSlist_projects, create_task, schedule_job, slack_post_message, gcal_create_event, search_agentsTeam coordination, product roadmap
Black Widow (Natasha)Supply Chain Manager. Stealthy, efficient, navigates complex international supplier networks.Supply Chain Analystgsheets_read_data, gsheets_write_data, zoho_crm_search, shipping_tracker (forged), supplier_scorecard (forged)Supplier management, logistics
ThorQuality Assurance. Mighty standards, thunderous rejection of subpar products. "This product is NOT worthy!"QA Engineer (Mfg)create_escalation, gsheets_write_data, qc_checklist (forged), defect_tracker (forged)Factory QC, defect tracking
Captain AmericaCompliance & Regulatory. Stands for truth, justice, and proper product certifications.Regulatory Complianceconfluence_create_page, confluence_search, create_task, certification_tracker (forged)FDA, CPSC, import compliance
Hulk (Bruce Banner)Cost Engineering. Calm and analytical until someone tries to sneak in cost overruns. Then... HULK SMASH THE BUDGET.Cost Analystgsheets_read_data, gsheets_write_data, create_artifact, cost_modeler (forged)BOM cost analysis, landed cost
HawkeyeProject Scheduler. Never misses a deadline. Keeps every timeline perfectly tracked.Project Coordinatorjira_create_issue, jira_update_issue, gcal_create_event, slack_post_message, timeline_tracker (forged)Production timelines, scheduling
Spider-ManCommunications & Translator. Bridges the language gap between US team, Chinese factories, Indian suppliers, and DR operations.International Commsslack_send_dm, slack_post_message, gdocs_create_document, translate_api (forged)Factory comms, translation

Projects (6)

ProjectTypeLead
Kitchen Product Line 2027SHORT_TERMIron Man
Pet Supplies RefreshSHORT_TERMIron Man
Ongoing QC ProgramONGOINGThor
Supplier OnboardingONGOINGBlack Widow
Regulatory & CertificationsONGOINGCaptain America
Cost Optimization InitiativeONGOINGHulk

Forged Tools (8)

ToolBuilt By
shipping_trackerWei + Black Widow via Forge
supplier_scorecardMatt + Black Widow via Forge
qc_checklistWei + Thor via Forge
defect_trackerCarlos + Thor via Forge
certification_trackerMatt + Captain America via Forge
cost_modelerMatt + Hulk via Forge
timeline_trackerMatt + Hawkeye via Forge
translate_apiWei + Spider-Man via Forge

Cross-Region Morning Standup (8:00 AM)

Scheduled Meeting: "Product Dev Daily Standup" | Cron: 0 8 * * 1-5 | Facilitator: Iron Man (COS) | Timed for overlap with China evening

IM
Iron Man 8:00 AM
Alright Avengers, let's assemble this standup. We've got all three regions online. Spider-Man, translate key points for Wei's team in Shenzhen. What's cooking?
BW
Black Widow 8:01 AM
Three containers en route from Shenzhen — ETA Port of LA in 12 days. The kitchen product samples shipment cleared customs in HK overnight. Supplier #47 in Mumbai is 5 days late on textile samples — I've sent a follow-up via Slack to Priya.
[tool_call: shipping_tracker, slack_send_dm to Priya Sharma]
TH
Thor 8:02 AM
Factory inspection in Guangzhou yesterday — 94% pass rate on the kitchen gadget line. BUT! 3 units had a paint adhesion defect. I deem them UNWORTHY. Created a defect report and escalated to the factory quality manager via Spider-Man.
[tool_call: defect_tracker, create_escalation]
SM
Spider-Man 8:03 AM
Got it, Thor! I've translated the defect report to Mandarin and sent it to the Guangzhou factory WeChat group via Slack bridge. They're already investigating — response expected by their morning (our tonight). Also scheduled a video QC review with Carlos in DR for 2 PM.
[tool_call: translate_api, slack_send_dm, gcal_create_event]
HK
Hulk 8:04 AM
BOM cost update on the Kitchen Line 2027: landed cost per unit is $14.32, down from $15.80 after renegotiating the silicone supplier in India. That's a 9.4% reduction. HULK HAPPY WITH THESE MARGINS. Full cost model updated in the sheet.
[tool_call: cost_modeler, gsheets_write_data]
HE
Hawkeye 8:05 AM
Timeline check: Kitchen Line is on track — tooling complete, first production run starts in 3 weeks. Pet Supplies Refresh is 2 days behind on DR assembly setup. I've adjusted the Jira milestones and pinged Carlos.
[tool_call: timeline_tracker, jira_update_issue, slack_send_dm]
CA
Captain America 8:06 AM
CPSC testing on the new pet toy line comes back next week. FDA submission for the kitchen food storage containers is approved — certification doc uploaded to Confluence. We're clear for production.
[tool_call: certification_tracker, confluence_create_page]
IM
Iron Man 8:07 AM
Great work, team. Summary posted to #product-dev. Matt, the BOM cost savings report and the paint defect escalation need your eyes today. JARVIS... I mean, Palpatine at Corp Claw... will get the product development status in the weekly exec roll-up.

Throughout the Day

Black Widow monitors ocean freight shipments in real time, sends delay alerts to Wei and Carlos, updates supplier scorecards

Thor processes QC inspection results from all 3 regions, escalates critical defects, updates quality trend reports

Hulk recalculates BOM costs as supplier quotes come in, flags cost overruns, updates landed cost models

Hawkeye tracks production milestones across all factories, adjusts Jira timelines, pings team leads on upcoming deadlines

Spider-Man translates factory communications across Mandarin, Spanish, Hindi, and English, bridges time zone gaps with async messages

Captain America monitors certification expiration dates, files regulatory submissions, tracks CPSC/FDA test lab progress

Tool Forge in Action (V1.5)

Building the Shipping Tracker

Wei Zhang was manually checking Flexport and Freightos portals multiple times a day for container status updates. He opened the Tool Forge and described it: "I need a tool that connects to Flexport and Freightos APIs, monitors all active shipments, alerts me on delays, and tracks container-level ETAs." 20 minutes later, shipping_tracker was live — Black Widow checks it every hour automatically.

Input:

{ action: "check_all", include_customs: true, alert_on_delay: "24h" }

Output:

{ active_shipments: 7, on_time: 5, delayed: 2, next_arrival: "Apr 15, Port of LA", alerts: [...] }

Used by: Black Widow (daily shipment tracking job), Hawkeye (timeline adjustments), Iron Man (executive summary)

Building the Cost Modeler

Matt Carpenter needed full landed cost calculations that included materials, labor, tooling amortization, ocean freight, customs duties, and overhead — not just raw BOM costs. He described it to the Forge Agent: "Build a calculator that takes a product's BOM, adds labor rates by factory region, tooling costs amortized over production run, shipping, duties, and overhead." 25 minutes later, cost_modeler was ready. Hulk uses it on every BOM change.

Input:

{ product: "Kitchen Gadget Pro", bom: [...], factory: "Shenzhen", run_qty: 10000, shipping: "ocean" }

Output:

{ landed_cost: "$14.32", breakdown: { materials: "$6.20", labor: "$2.10", ... }, margin_at_retail: "62%" }

Used by: Hulk (monthly BOM cost analysis job), Black Widow (supplier negotiation data)

Scheduled Jobs & Automation

Cross-region automation keeping global product operations in sync across time zones.

Job NameScheduleAgentTools UsedOutput
Daily Shipment Tracker0 7 * * * (7 AM)Black Widowshipping_trackerAll container statuses checked, delay alerts sent to Wei and Carlos
Weekly Supplier Scorecard0 8 * * 1 (Mon 8 AM)Black Widowsupplier_scorecard, gsheets_write_dataUpdated supplier scores: on-time delivery, defect rate, responsiveness
Daily QC Summary0 18 * * 1-5 (6 PM)Thordefect_tracker, qc_checklistDaily defect report compiled from all factories, posted to #product-qc
Monthly BOM Cost Analysis0 9 1 * * (1st of month)Hulkcost_modeler, gsheets_write_dataAll product costs recalculated, margin report sent to Matt
Weekly Certification Status0 8 * * 3 (Wed 8 AM)Captain Americacertification_tracker, confluence_create_pageCertification status for all products, expiration warnings, test lab updates

A Day in the Life: Matt Carpenter, VP of Product Development

Matt Carpenter opens his laptop at 7:45 AM to find Black Widow's overnight shipping report: 3 containers on track from Shenzhen, but 1 has a 2-day delay from a port congestion issue in HK. By 8 AM, Iron Man's standup summary hits Slack — Thor caught a paint defect in Guangzhou (Spider-Man already translated and sent the report to the factory), Hulk's renegotiation with the India silicone supplier saved 9.4% on BOM costs, and Hawkeye flagged that the Pet Supplies Refresh is 2 days behind in DR. Matt reviews the defect photos in Thor's escalation, approves a switch to UV-cured coating, and checks Hulk's updated cost model. By 9 AM, Captain America confirms the FDA kitchen storage approval. Matt spends 30 minutes on a video call with the Shenzhen factory (Spider-Man translating in real time), approves the first production run timeline, and by lunch, his global 3-region operation has been coordinated seamlessly — with each agent handling what used to require 3 regional operations managers.

Memory in Action

Iron Man remembers:

"Matt reviews product designs on Tuesday/Thursday mornings. The Shenzhen factory (Supplier #12) has a 2-week Chinese New Year shutdown in January — plan production runs around it. Always get 3 quotes for new tooling."

Black Widow remembers:

"Priya negotiates best when given 3 competing supplier quotes. Ocean freight from Shenzhen takes 18-22 days to Port of LA. The DR factory prefers PO confirmations by Wednesday for next-week assembly starts."

Thor remembers:

"The Guangzhou paint supplier had adhesion issues in Q2 2025 too — this is a recurring problem. Switch to UV-cured coating for kitchen line. Carlos's QC team in DR catches 98% of defects — best in our network."

Hulk remembers:

"Silicone costs fluctuate seasonally — buy in Q1 for best pricing. Tooling costs >$50K need Matt's approval. The Indian textile supplier gives 8% discount on orders >10,000 units."

Hawkeye remembers:

"Shenzhen factories need 6-week lead time for new tooling. DR assembly typically takes 3 business days per 1,000 units. Never schedule production starts during Chinese Golden Week (first week of October)."

Spider-Man remembers:

"The Guangzhou factory QC manager prefers WeChat for urgent issues, email for formal reports. Carlos in DR responds fastest to Slack messages before 2 PM EST. Always include defect photos when translating QC reports."

Captain America remembers:

"CPSC testing takes 4-6 weeks. FDA food contact submissions need 90 days. The new EU CE marking rules take effect in 2027 — start compliance early. Always file import documentation 5 business days before arrival."

Me Health Business Unit — Grey's Anatomy EditionExecutiveExample: RPM healthcare with Grey's Anatomy agents

Me Health — RPM Health Platform

Healthcare RPM

Greater Goods' Remote Patient Monitoring (RPM) healthcare business. Sells RPM services and devices to healthcare providers, manages patient onboarding, device fulfillment, ongoing monitoring, and clinical reporting. A HIPAA-regulated business with strict compliance requirements.

⚠

Me Health Instance Deferred (Business Review B12)

The Me Health Praesidium2 instance is deferred until HIPAA controls are validated. Deploy to non-healthcare teams first (Engineering, Marketing, Corp Claw, Product Dev). Me Health target: V1.5 after compliance controls are implemented and audited.

Prerequisites Before Me Health Deployment

Technical Prerequisites

  • ● PHI detection layer in memory extractor and conversation handler
  • ● audit_access_log table implemented and tested (7-year retention)
  • ● Local LLM routing for PHI-adjacent agent work (Ollama/vLLM)
  • ● BAA tracking system for all integration vendors

Process Prerequisites

  • ● Legal review of all Me Health integrations (Zoho CRM, Atlassian, Slack)
  • ● BAAs signed with Zoho (30 days before go-live per compliance policy)
  • ● HIPAA compliance audit of Praesidium2 platform completed
  • ● Training for Me Health team on agent guardrails and PHI handling

Human Team (4)

NameRoleHow They Use Praesidium2
Bryan PotterVP of Me HealthOversees the entire RPM business unit — sales, marketing, operations, business development
Rachel TorresSales DirectorManages sales pipeline, reviews proposals, closes deals with healthcare providers
Kevin ParkOperations ManagerManages patient onboarding, device inventory, clinical support workflows
Jennifer LiuMarketing ManagerHealthcare marketing campaigns, provider education content, trade show coordination

Note: The team members listed above are illustrative examples — not the complete team roster. All existing team members remain in their current roles. Agents are designed to augment and support the team by handling operational tasks, not to replace any team member. The full team structure remains unchanged.

Agent Team (7) — Seattle Grace Hospital

AgentPersonaTemplateToolsPrimary Focus
Dr. Meredith GreyChief of Staff. Seen it all, leads with steady hands. "It's a beautiful day to save lives... and close deals."Healthcare Business COSlist_projects, create_task, schedule_job, slack_post_message, search_agents, federation_query_peerBusiness unit coordination
Dr. Cristina YangSales Operations. Fiercely competitive, data-driven, relentless in pursuit of quota. Does RESULTS, not warm and fuzzy.Sales Analystzoho_crm_search, zoho_crm_create_record, zoho_crm_update_record, gsheets_write_data, pipeline_analyzer (forged)Sales pipeline, lead qualification
Dr. Miranda BaileyOperations Chief. Runs clinical operations with iron discipline and a big heart. "I have five rules. Memorize them."Operations Coordinatorjira_create_issue, jira_update_issue, create_task, slack_send_dm, onboarding_tracker (forged)Patient onboarding, device fulfillment
Dr. Alex KarevBusiness Development. Scrappy, determined, goes after new partnerships with raw hustle.Business Development Repzoho_crm_create_record, confluence_create_page, gdocs_create_document, slack_post_message, market_analyzer (forged)New markets, partnerships
Dr. Izzie StevensMarketing & Content. Creative, empathetic, crafts healthcare messaging that resonates with providers and patients.Healthcare Marketinggdocs_create_document, confluence_create_page, social_scheduler (forged), email_campaign (forged), create_artifactProvider education, email campaigns
Dr. George O'MalleyCompliance & Reporting. Meticulous, thorough, ensures every data point meets HIPAA standards. Quiet but essential.HIPAA Compliance Analystaudit_checker (forged), confluence_search, create_escalation, compliance_reporter (forged)HIPAA compliance, clinical reporting
Dr. Addison MontgomeryPatient Experience. Premium care, premium attention. Tracks satisfaction, manages escalated patient concerns.Patient Experience Analystslack_send_dm, create_escalation, gsheets_read_data, patient_satisfaction (forged), nps_tracker (forged)Patient satisfaction, NPS

Projects (6)

ProjectTypeLead
Q3 Sales PushSHORT_TERMCristina Yang
Patient Onboarding OptimizationONGOINGMiranda Bailey
Provider Education ProgramONGOINGIzzie Stevens
HIPAA Compliance & AuditONGOINGGeorge O'Malley
RPM Platform GrowthONGOINGMeredith Grey
Clinical Reporting & OutcomesONGOINGMiranda Bailey

Forged Tools (7)

ToolBuilt By
pipeline_analyzerRachel + Cristina Yang via Forge
onboarding_trackerKevin + Miranda Bailey via Forge
market_analyzerBryan P + Alex Karev via Forge
email_campaignJennifer + Izzie Stevens via Forge
compliance_reporterKevin + George O'Malley via Forge
patient_satisfactionBryan P + Addison Montgomery via Forge
nps_trackerRachel + Addison Montgomery via Forge

Me Health Daily Standup (8:30 AM)

Scheduled Meeting: "Me Health Daily Standup" | Cron: 0 8 30 * * 1-5 | Facilitator: Dr. Meredith Grey (COS)

MG
Meredith Grey 8:30 AM
Good morning everyone. It's a beautiful day to save lives — and grow this business. Cristina, pipeline update?
CY
Cristina Yang 8:31 AM
12 new leads this week from the cardiology webinar. 3 are qualified — revenue potential $180K ARR. The Midwest Health System deal moved to negotiation stage. Rachel is reviewing the proposal I drafted. Pipeline is at $2.1M weighted, 87% to quarterly target.
[tool_call: pipeline_analyzer, zoho_crm_update_record]
MB
Miranda Bailey 8:32 AM
Patient onboarding: 45 patients enrolled this week, average onboarding time down to 2.8 days from 5 days last quarter. Device inventory is healthy — 200 units in warehouse. One patient in Ohio hasn't completed their first reading after 7 days. I've flagged it for Kevin and created a follow-up task.
[tool_call: onboarding_tracker, create_task, slack_send_dm]
GO
George O'Malley 8:33 AM
HIPAA compliance: all green. Completed the quarterly access review — 3 user accounts needed permission adjustments, all fixed. The BAA with the new Zoho integration is pending legal review. Audit prep is at 95%.
[tool_call: compliance_reporter, audit_checker]
IS
Izzie Stevens 8:34 AM
The 'RPM Benefits for Cardiology' white paper is published on Confluence and sent to Jennifer for review. Email campaign for the upcoming Nashville trade show has 42% open rate — that's 11% above industry average! I'm creating social posts for the conference next week.
[tool_call: email_campaign, confluence_create_page, social_scheduler]
AM
Addison Montgomery 8:35 AM
Patient satisfaction update: NPS is 72 this month, up from 68. Two provider accounts flagged as at-risk — satisfaction scores dropped below threshold. I've created escalations for Bryan to review and scheduled check-in calls.
[tool_call: nps_tracker, patient_satisfaction, create_escalation]
AK
Alex Karev 8:36 AM
Business development: I've identified 3 pediatric RPM programs launching in Q4 that we could partner with. Market analysis shows a $50M addressable market in pediatric RPM. Draft partnership proposal is on Confluence for Bryan's review.
[tool_call: market_analyzer, confluence_create_page]
MG
Meredith Grey 8:37 AM
Strong day across the board. Summary posted to #me-health-daily. Bryan — the pipeline report, at-risk accounts, and pediatric partnership proposal need your attention. Corp Claw gets the weekly roll-up Friday. Remember — nobody dies on my watch. And nobody churns either.

Throughout the Day

Cristina Yang monitors CRM pipeline changes, qualifies new leads, drafts proposals for Rachel's review, tracks deal velocity

Miranda Bailey tracks patient onboarding progress, manages device fulfillment queue, escalates stalled enrollments to Kevin

Alex Karev researches new market segments, drafts partnership proposals, monitors competitor announcements

Izzie Stevens creates provider education content, manages email campaigns, prepares trade show materials

George O'Malley runs continuous HIPAA compliance checks, monitors access logs, reviews audit trail for anomalies

Addison Montgomery monitors NPS scores in real time, triggers retention workflows for at-risk accounts, schedules check-in calls

Tool Forge in Action (V1.5)

Building the Pipeline Analyzer

Rachel Torres needed deeper pipeline insights than Zoho CRM dashboards could provide — specifically stage velocity, conversion rates by lead source, and stale deal detection. She opened the Tool Forge and described it: "I need a tool that analyzes our Zoho CRM pipeline, calculates stage-by-stage velocity, identifies deals stuck longer than their average cycle time, and forecasts revenue by probability weighting." 20 minutes later, pipeline_analyzer was deployed and Cristina Yang had a new weapon.

Input:

{ action: "full_analysis", pipeline: "RPM_Sales", period: "Q3", include_forecast: true }

Output:

{ weighted_pipeline: "$2.1M", stale_deals: 4, avg_velocity: "32 days", forecast_q3: "$1.8M", conversion_rate: "24%" }

Used by: Cristina Yang (daily pipeline report job), Meredith Grey (weekly executive roll-up)

Building the Onboarding Tracker

Kevin Park needed to track each patient through the entire onboarding journey: enrollment, device shipping, device receipt confirmation, first reading, and active monitoring status. He told the Forge Agent: "Build a tool that tracks each patient through our 5-step onboarding funnel, flags anyone who stalls at any step for longer than the SLA, and generates daily status reports." 25 minutes later, onboarding_tracker was live — and Miranda Bailey adopted it as her primary operations tool.

Input:

{ action: "daily_status", region: "all", flag_stalled: true, sla_threshold: "48h" }

Output:

{ enrolled_today: 8, in_shipping: 12, awaiting_first_read: 5, stalled: 1, avg_time_to_active: "2.8 days" }

Used by: Miranda Bailey (daily onboarding status job), Addison Montgomery (patient experience follow-ups)

Scheduled Jobs & Automation

HIPAA-compliant automation running on local/self-hosted LLMs — no PHI sent to cloud APIs.

Job NameScheduleAgentTools UsedOutput
Daily Pipeline Report0 8 * * * (8 AM)Cristina Yangpipeline_analyzer, gsheets_write_dataPipeline status, stale deal alerts, revenue forecast posted to #me-health-sales
Daily Patient Onboarding Status0 9 * * * (9 AM)Miranda Baileyonboarding_trackerOnboarding funnel status, stalled patient alerts sent to Kevin
Weekly NPS Report0 8 * * 1 (Mon 8 AM)Addison Montgomerynps_tracker, patient_satisfactionNPS trends by provider, at-risk account alerts, satisfaction summary
Monthly Compliance Dashboard0 8 1 * * (1st of month)George O'Malleycompliance_reporter, audit_checkerHIPAA compliance dashboard, access review status, BAA tracker
Weekly Market Intelligence0 8 * * 3 (Wed 8 AM)Alex Karevmarket_analyzer, confluence_create_pageNew RPM market opportunities, competitor moves, partnership leads

A Day in the Life: Bryan Potter, VP of Me Health

Bryan Potter starts his Monday by checking the Me Health dashboard. Cristina Yang's pipeline report is already there — $2.1M weighted, 87% to Q3 target, with the Midwest Health System deal in negotiation. Miranda Bailey's onboarding tracker shows 45 patients enrolled this week with average onboarding time down to 2.8 days. By 8:30, Meredith Grey's standup summary lands in Slack: George O'Malley confirms HIPAA compliance is green across the board, Izzie Stevens reports a 42% email open rate on the Nashville campaign, and Addison Montgomery flags 2 at-risk provider accounts. Bryan reviews the escalations, approves Cristina's proposal for the Midwest deal, checks Alex Karev's pediatric RPM market analysis ($50M addressable market), and joins a 20-minute strategy call with Meredith about the Q4 growth plan. By 10 AM, Bryan has full visibility across sales, operations, compliance, and marketing — his team of 7 agents has been processing operational data that frees the team to focus on strategy and relationships.

Memory in Action

Meredith Grey remembers:

"Bryan Potter reviews dashboards first thing Monday and Wednesday. The Q3 sales target is 50 new provider contracts. Nashville HIMSS conference is our biggest lead generation event — prep starts 6 weeks before."

Cristina Yang remembers:

"Rachel closes deals fastest when given comparison data against competitors. The Midwest Health System procurement cycle is 45 days. Never discount more than 15% without Bryan's approval."

Miranda Bailey remembers:

"Kevin prefers onboarding issues escalated via Jira, not Slack. Device shipments over 20 units need warehouse manager confirmation. The Ohio regional office has a 2-hour time zone difference — schedule calls accordingly."

George O'Malley remembers:

"HIPAA audit is Q3. The me-health-portal stores PHI in RDS with AES-256. Any new vendor touching patient data needs a BAA signed 30 days before integration goes live. Access reviews are quarterly — next one is July 1."

Addison Montgomery remembers:

"NPS below 60 on any provider account triggers a retention workflow. Patient satisfaction surveys go out 30 days after first reading. Bryan wants at-risk accounts escalated within 24 hours — not in the weekly report."

Alex Karev remembers:

"Pediatric RPM is a $50M addressable market with 3 programs launching Q4. Cardiology providers have the shortest sales cycle (28 days). Partnership proposals need ROI projections showing 18-month payback or better."

Izzie Stevens remembers:

"Healthcare email campaigns need 'Unsubscribe' in the first fold for CAN-SPAM compliance. Cardiology webinars generate 3x more qualified leads than generic RPM content. Jennifer approves all patient-facing materials."

HIPAA & ComplianceExecutive Technical OperationsHealthcare compliance controls and data protection

Praesidium2 operates in a healthcare-adjacent environment (Greater Goods' me-health-portal). The platform MUST be HIPAA-compliant from Day 1, not bolted on later.

⚠ Business Review B12 — Me Health Deferred: The Me Health Praesidium2 instance is deferred to V1.5 until all HIPAA controls below are validated. Non-healthcare teams (Engineering, Marketing, Corp Claw, Product Dev) deploy first. Prerequisites: PHI detection layer, audit_access_log implementation, local LLM routing for PHI-adjacent work, and BAA tracking for all integration vendors. See Me Health tab for full prerequisite checklist.

Protected Health Information (PHI) Protection Rules

Praesidium2 itself does not store PHI directly, but agents MAY interact with systems that contain PHI. The design must enforce these guardrails:

🚫

No PHI in Agent Memory

Memory extractor MUST NOT store PHI in the memory table. Extraction prompts include explicit instructions: "Do not store patient names, medical record numbers, SSNs, dates of birth, or any individually identifiable health information."

💬

No PHI in Conversation Logs

The message table stores full conversation history. If a conversation involves PHI (e.g., chatting about patient data from me-health-portal), messages must be classified and either redacted or encrypted at rest.

☁

No PHI in Cloud LLM Calls

When agents call Anthropic/OpenAI APIs, PHI must not be sent. If PHI access is required, use LOCAL or SELF_HOSTED LLM providers only (Ollama/vLLM on internal infrastructure, never leaving the network).

Encryption Matrix

LayerAt RestIn Transit
PostgreSQLAES-256 (RDS encryption, or LUKS for local)TLS 1.3 (pg_hba.conf: hostssl)
RedisElastiCache encryption at restTLS 1.3
S3 / MinIOAES-256 (SSE-S3 or SSE-KMS)HTTPS only
Secrets ManagerAES-256 (AWS managed)HTTPS only
Pod-to-PodN/AmTLS via service mesh (Istio/Linkerd) or k8s NetworkPolicy + TLS
Browser-to-APIN/ATLS 1.3 (ALB terminates, internal traffic via mTLS)

Day 1 Encryption Baseline

v1.10 — HARDENING

Operational risk: if encryption and log scanning are not enforced from Day 1, retrofitting them later requires a breaking infrastructure refactor (data migration, downtime, re-encryption). These hardening steps apply to ALL Praesidium2 deployments immediately, not just Me Health.

RDS Encryption

storage_encrypted = true with KMS Customer Managed Key (CMK). Mandatory in the Terraform module — the praesidium-rds module has a validation block that rejects storage_encrypted = false.

S3 Encryption

Default bucket encryption using KMS. The praesidium-s3 Terraform module enforces aws_s3_bucket_server_side_encryption_configuration with sse_algorithm = "aws:kms". Buckets without encryption cannot be created.

ALB TLS

HTTPS-only listeners. TLS 1.2 minimum (ELBSecurityPolicy-TLS13-1-2-2021-06). HTTP (port 80) redirects to HTTPS. No plaintext traffic enters the cluster.

Terraform "Hardened Modules"

All infrastructure provisioned via opinionated Terraform modules (praesidium-rds, praesidium-s3, praesidium-alb) that CANNOT be deployed without encryption enabled. Validation blocks reject insecure configurations at terraform plan time.

Datadog Sensitive Data Scanner

Enabled on ALL log streams from Day 1 — not just Me Health. Scans for:

PII patterns: SSNs, email addresses, phone numbers, dates of birth
PHI patterns: Medical record numbers, diagnosis codes (ICD-10), patient names
Secrets: API keys, JWT tokens, database connection strings
Action: Matched patterns are redacted in-place with [REDACTED] and an alert is sent to the #security-alerts Slack channel

Note: Full HIPAA compliance (BAAs, PHI detection layer, local LLM routing) is V1.5 scope. These Day 1 hardening steps ensure the infrastructure is encryption-ready from initial deployment, preventing a costly breaking refactor when Me Health onboards.

Access Controls Summary

Authentik RBAC

All access via IAM-style policies. Default deny. Least privilege. No permission logic in application code.

Row-Level Security

qqq RecordSecurityLock on every entity table (instance_id scoping). All queries automatically filtered.

Audit Trail

Every data access logged in activity_log. Immutable, append-only. Retained for 7 years (HIPAA requirement).

Session & MFA

JWT tokens with short expiry (15 min access, 7 day refresh). Refresh token rotation. Authentik enforces MFA for all human users (TOTP or WebAuthn).

HIPAA-Specific Data Model

audit_access_log NEW TABLE

PK id UUID
FK team_member_id UUID → team_member(id)
resource_type VARCHAR(50) NOT NULL -- which table was accessed
resource_id UUID NOT NULL -- which record
action VARCHAR(20) NOT NULL -- READ, WRITE, DELETE
ip_address VARCHAR(45) -- client IP
user_agent VARCHAR(500) -- browser/client identifier
justification TEXT -- why this data was accessed
phi_involved BOOLEAN DEFAULT false -- flag if PHI was present
created_at TIMESTAMPTZ DEFAULT now()
IDX: (team_member_id), (resource_type, resource_id), (phi_involved), (created_at)
RETENTION: 7 years minimum, partitioned by month

Business Associate Agreement (BAA) Requirements

Vendor / ServiceBAA StatusNotes
AnthropicREQUIREDRequired if any agent conversation could involve PHI context. Alternatively, route PHI-adjacent work to LOCAL LLM providers only.
AWS (RDS, S3, EKS, etc.)IN PLACEStandard AWS HIPAA eligible services: RDS, S3, ElastiCache, EKS, Secrets Manager.
JiraHIPAA TIERAtlassian offers HIPAA-compliant Cloud Enterprise tier. BAA needed if agent tickets reference patient context.
ConfluenceHIPAA TIERSame as Jira — Atlassian Cloud Enterprise. BAA needed for clinical documentation.
SlackHIPAA TIERSlack Enterprise Grid offers HIPAA compliance. BAA needed if agent messages contain PHI-adjacent data.
Zoho CRMREQUIREDNew integration — BAA must be signed 30 days before go-live per compliance policy.

Data Retention & Disposal Schedule

Data TypeRetention PeriodDisposal Method
Audit logs (activity_log, audit_access_log)7 yearsArchived to S3 Glacier after 1 year
Conversation messages3 yearsSoft delete → hard delete after retention period
Agent memoriesUntil expired or explicitly deletedSecure wipe (overwrite + delete)
ArtifactsProject lifetime + 1 yearS3 lifecycle policy → delete
Knowledge documentsUntil manually removedSecure delete of chunks + embeddings
LangGraph checkpoints90 days after workflow completionAuto-purge job

Phased Rollout StrategyExecutive OperationsBusiness Review B6: Team-by-team deployment plan with go/no-go gates

A 3-person build team + AI (CTO + 2 engineers + unlimited Claude Code agents) cannot support 5 simultaneous team launches. This phased rollout deploys one team at a time with 2-week stabilization windows, explicit go/no-go criteria, and support capacity planning.

3
Rollout Phases
5
Business Teams
8
Phases Total
2
Phases per Stabilization

3-Phase Rollout Plan

1

Phase 1: Engineering / CTO

Phases 1–2

Team: Engineering (LOTR Edition) — James Maes + dev team

Why first: Build team eats their own dogfood. Deepest technical understanding, fastest issue resolution, highest tolerance for rough edges.

Focus: Core platform stability, agent runtime reliability, integration testing with real Jira/GitHub/Slack data.

Support load: Self-supporting. Engineering team debugs their own issues and feeds fixes back into the platform.

2

Phase 2: Marketing

Phases 3–4

Team: Marketing (WWE Edition) — second instance, different use case

Why second: Non-engineering team validates the platform is usable by non-technical users. Different integration patterns (Zoho CRM, Google Workspace, social tools).

Focus: Multi-instance isolation, Zoho CRM integration, onboarding experience, agent personality configuration.

Support load: 1 engineer dedicated to Marketing onboarding support. Remaining 2 engineers on bug fixes and platform stability.

3

Phase 3: Remaining Teams

Phases 5–6

Teams: Corp Claw, Product Dev, Me Health — one at a time

Why staggered: Support capacity. Adding one team per week ensures each team gets dedicated onboarding attention and issues are resolved before the next team goes live.

Focus: Federation queries between instances, cross-team coordination, team-specific integrations.

Support load: Rotating 1-engineer onboarding buddy per team. By this phase, Engineering + Marketing teams are self-sufficient.

Stabilization Periods C4: Clarified

Each phase includes a 2-week stabilization period before the next team is added. This is non-negotiable — rushing past stabilization compounds problems.

PhaseStabilization WindowKey ActivitiesGate Review
Phase 1 Phases 1–2 Bug fixes, performance tuning, runbook creation, baseline metrics establishment End of Phase 2: Go/no-go for Marketing access
Phase 2 Phases 3–4 Multi-instance validation, onboarding workflow refinement, support playbook creation End of Phase 4: Go/no-go for Phase 3 teams
Phase 3 Phases 5–6 Federation testing, cross-instance load validation, full production hardening End of Phase 7: Full-fleet readiness review (includes build stabilization week)

Support Escalation Path During Stabilization

During each 2-week stabilization window, issues follow a defined escalation path to prevent ad-hoc firefighting:

SeverityResponse TimeEscalationResolution Owner
P0 — Platform Down< 15 minutesImmediate Slack alert to all engineers + CTOAll hands on deck
P1 — Agent Broken< 1 hourSlack alert to on-call engineer + team leadOn-call engineer
P2 — Degraded< 4 hoursJira ticket, daily standup triageAssigned engineer
P3 — Minor/CosmeticNext sprintJira backlogSprint planning

⚠ Critical: The go/no-go review at the end of Phase 2 is the single most important gate in the rollout. Marketing deployment does NOT begin until Engineering stabilization is confirmed. If Phase 2 review surfaces unresolved P0/P1 issues, Marketing access is delayed — no exceptions.

Go/No-Go Criteria for Phase Advancement

All criteria must be met before advancing to the next phase. Any blocker triggers a hold until resolved.

CategoryCriteriaThreshold
StabilityPlatform uptime during stabilization period≥ 99.5%
StabilityZero unresolved P0/P1 bugs from current phase0 open
PerformanceAgent task completion rate (non-error)≥ 95%
PerformanceAPI p95 latency< 500ms
SupportSupport queue depth (unresolved tickets)< 5
SupportMean time to resolve support issues< 4 hours
RunbooksAll deployment runbooks reviewed and tested100%
RunbooksAt least 2 team members can deploy independently≥ 2 people
SecurityNo open security findings (CRITICAL/HIGH)0 open
CapacitySupport team has bandwidth for next phaseConfirmed
⚠

B22: Business-Value Kill Criteria

Kill Gates Business Review Gap

Go/no-go criteria above measure platform stability. Kill criteria measure business value. If agents are stable but nobody is using them or they aren't saving time, that's a different kind of failure that requires a different response.

GateMetricThresholdMeasurement Source
30-Day GateHours saved per team per week≥ 5 hours/weekKPI dashboard (B4) vs. baseline
User feedback score> 3.5 / 5Feedback system (B13) rolling average
Agent task utilization> 60% of available tasks routed to agentsTask table: agent-assigned / total
60-Day GateHours saved per team per week≥ 8 hours/weekKPI dashboard (B4) vs. baseline
User feedback score> 4.0 / 5Feedback system (B13) rolling average
Agent task utilization> 75% of available tasks routed to agentsTask table: agent-assigned / total
ROI trajectoryPositive (trending toward annual target)KPI dashboard projected annualized savings

If Gates Are Not Met

Option 1: Reduce Scope

Narrow agent responsibilities to highest-value tasks only. Remove agents that aren't delivering measurable improvement.

Option 2: Adjust Configs

Retune agent prompts, tool assignments, and autonomy levels. Run user interviews to identify friction points.

Option 3: Pause Deployment

Halt further team rollouts. Conduct root-cause analysis. Resume only when corrective actions show improvement in pilot team.

Decision maker: CTO with business unit leads. Kill-gate reviews are scheduled at Day 30 and Day 60 post-deployment for each team. Results documented in Confluence under PV2 > Rollout > Gate Reviews.

Support Capacity Planning

With a 3-person build team + AI (CTO + 2 engineers + unlimited Claude Code agents), support capacity is managed across the phased rollout.

PhaseTeams ActiveOnboarding SupportPlatform DevBug Fix Reserve
Phase 11 (Engineering)0 (self-service)2 engineers1 engineer
Phase 22 (+Marketing)1 engineer1 engineer1 engineer
Phase 33–5 (+3 teams)1 rotating1 engineer1 engineer

⚠ Constraint: If Phase 2 stabilization reveals that Marketing requires more than 1 engineer of ongoing support, Phase 3 timeline shifts right. This is expected and acceptable — the whole point of phased rollout is to discover these constraints early.

Rollout Timeline

Phase Team(s) Active Key Milestones Risk Level
Phase 1EngineeringFirst agent tasks, initial bug triage, baseline metricsHIGH
Phase 2EngineeringStabilization, runbook drafts, go/no-go reviewMEDIUM
Phase 3Engineering + MarketingMarketing onboarding, multi-instance validationMEDIUM
Phase 4Engineering + MarketingStabilization, support playbook, go/no-go reviewMEDIUM
Phase 5+Corp Claw, +Product DevThird/fourth instance, federation queries activeLOW
Phase 6+Me Health (if HIPAA-ready)Full fleet deployed, cross-instance coordinationLOW
Phase 7All teamsBuild stabilization overflow complete, full production hardening, KPI baseline comparisonLOW

⚠ Me Health (B12): Me Health deployment in Phase 6 is conditional on HIPAA controls being validated. If HIPAA prerequisites (PHI detection, audit_access_log, local LLM routing, BAA tracking) are not complete, Me Health defers to V1.5. See HIPAA & Compliance tab for details.

Operational Runbooks & Bus FactorOperationsBusiness Review B10: Knowledge sharing and deployment independence

At least 2 team members must be able to deploy, troubleshoot, and recover the platform independently. Single points of knowledge failure are unacceptable for a production system.

Required Runbooks

All runbooks documented in Confluence with quarterly review schedule. Each runbook must be tested by a second team member before being marked complete.

RunbookOwnerSecondaryKey ContentReview Cycle
qqq Configuration Dev 1Dev 2 Table schema updates, API generation, Liquibase migrations, RLS configuration, qqq metaData files Quarterly
Authentik IAM Setup Dev 1Dev 3 OAuth provider configuration, group/role mapping, MFA policies, service account management, Authentik backup/restore Quarterly
AWS Deployment Dev 1Dev 2 EKS cluster management, RDS operations, ElastiCache, S3 buckets, IAM roles, VPC/security groups, cost monitoring Quarterly
ArgoCD Management Dev 2Dev 1 Application sync, rollback procedures, GitOps workflow, secret management, multi-environment promotion Quarterly
Agent Runtime Operations Dev 2Dev 3 Agent runtime troubleshooting, Celery worker scaling, task queue management, LangGraph workflow debugging, LLM provider failover Quarterly
Disaster Recovery Dev 1Dev 2 RDS restore from snapshot, Redis failover, S3 recovery, full-cluster rebuild, tested restore procedure Quarterly
Instance Provisioning Dev 3Dev 1 New business unit setup, Authentik group creation, agent template seeding, integration OAuth setup Quarterly

Bus Factor Requirements

Minimum 2 people can independently perform every critical operation:

  • ✓ Production deployment (full pipeline)
  • ✓ Rollback to previous version
  • ✓ Database restore from backup
  • ✓ Authentik user/group administration
  • ✓ New instance provisioning
  • ✓ Incident triage and resolution

Confluence Documentation Structure

All runbooks live under PV2 > Runbooks in Confluence:

  • ● Each runbook follows the standard template (Purpose, Prerequisites, Steps, Validation, Rollback)
  • ● Quarterly review: assigned reviewer runs through the full procedure
  • ● Version-stamped: each runbook notes which platform version it was last tested against
  • ● Linked from ArgoCD application notes for quick access during incidents

Lessons Learned RetrospectivesExecutive OperationsBusiness Review B21: Post-deployment retrospectives feeding V1.5 planning

Phased rollout generates invaluable operational data. Scheduled retrospectives ensure those lessons are captured, shared, and fed into future planning rather than lost in the rush to the next deployment.

Retrospective Schedule

RetrospectiveTimingTeams InvolvedFacilitatorOutput
30-Day Retro 30 days after Engineering team deployment (end of Phase 1 stabilization) Engineering team + CTO CTO Phase 1 lessons document, Marketing deployment adjustments
60-Day Retro 30 days after Marketing team deployment (end of Phase 2 stabilization) Engineering + Marketing teams + CTO CTO Cross-team lessons document, Phase 3 deployment plan updates
90-Day Retro 30 days after full fleet deployment (end of Phase 3) All team leads + CTO + CEO CTO + VP Operations Full program retrospective, V1.5 roadmap input

Retrospective Format

Each retrospective follows a structured 90-minute format:

  • ● What Worked — Successes to replicate in future phases (15 min)
  • ● What Didn't Work — Failures and friction points to address (20 min)
  • ● What Surprised Us — Unexpected behaviors, emergent patterns, user reactions (15 min)
  • ● KPI Review — Walk through actual vs. projected metrics from KPI dashboard (20 min)
  • ● Action Items — Prioritized list of changes for next phase / V1.5 roadmap (20 min)

Output & Distribution

Document location: Confluence under PV2 > Retrospectives

Distribution: All team leads, CTO, CEO

Action tracking: Jira tickets created for every action item, tagged retro-finding

V1.5 feed: 90-day retro findings are a primary input to V1.5 feature prioritization

Assigned to: CTO (facilitator) + team leads (participants)

Operational Maintenance BudgetExecutive OperationsBusiness Review B19: Explicit post-launch maintenance staffing and budget

After the build phase completes, the platform requires ongoing maintenance. This is not optional — frameworks update, integrations break, security patches ship, and users request features. The maintenance model leverages AI-assisted development to keep costs low while maintaining production quality.

Annual Maintenance Budget

~$20K
Annual Labor Cost
50%
Engineer Allocation
~$2.4K
Monthly Infra Cost
ResourceAllocationAnnual CostResponsibilities
Offshore Senior Engineer 50% (~20 hrs/week) ~$20,000 Framework upgrades (Anthropic SDK, LangGraph, qqq), integration maintenance, bug fixes, security patches, minor feature requests
Claude Code (AI Coding) Primary code generation Included in LLM budget Claude Code handles coding tasks; engineer reviews, tests, and deploys. This multiplies engineer productivity 3–5x.
Infrastructure (AWS) EKS + RDS + Redis + S3 ~$28,800 Hosting, database, cache, storage, networking, monitoring
LLM Token Budget Agent operations + coding ~$6,000 Claude/OpenAI API costs for agent tasks, meetings, tool forge, maintenance coding

Maintenance Workflow

The AI-assisted maintenance model keeps costs low by using Claude Code as the primary coder, with the engineer providing review, testing, and deployment oversight.

1
Issue Reported
Jira ticket created
→
2
Claude Code
Writes the fix/feature
→
3
Engineer Review
PR review + testing
→
4
Deploy
ArgoCD promotion

Annual Budget Review

Timing: Annual review tied to Q4 agent framework review (B16) and 90-day retrospective output

Decision maker: CTO + CEO

Inputs: ROI metrics from KPI dashboard (B4), maintenance ticket volume, infrastructure cost trends, B16 quarterly framework review findings

Adjustments: Scale engineer allocation up/down based on ticket volume. If maintenance load exceeds 50% allocation for 2+ consecutive months, evaluate moving to 75% or adding a second resource.

⚠ Total Annual Cost: ~$55K/year (labor + infrastructure + LLM tokens) against a projected $210K/year in savings = 3.8x ROI. The maintenance budget is reviewed annually and adjusted based on actual ROI measurements from the KPI dashboard.

Legal & ComplianceExecutive OperationsBusiness Review B7: Pre-deployment legal review and platform ToS compliance

Every integration touches a third-party platform with its own Terms of Service, API usage policies, and data handling rules. Automated agent actions create unique liability considerations that must be reviewed before deployment.

Pre-Deployment Legal Review Checklist

Each integration must pass legal review before agent access is enabled in production. Review is per-integration, not per-instance.

IntegrationToS ReviewKey ConcernsData ClassificationStatus
Jira (Atlassian) Atlassian Cloud Terms, API Terms of Use Automated issue creation rate limits; bot user requirements; data residency for AU/EU instances BUSINESS PENDING
Slack Slack API Terms, App Directory Policy Message posting rate limits; user impersonation restrictions; workspace data export compliance BUSINESS PENDING
GitHub GitHub Terms of Service, API Terms Automated commit policies; bot account requirements; code scanning data handling CONFIDENTIAL PENDING
Amazon (Seller Central) Amazon MWS/SP-API Terms, Acceptable Use Automated pricing restrictions; product listing modification rules; PII handling in orders CONFIDENTIAL PENDING
Zoho CRM Zoho Terms, API Policy, Data Processing Addendum Automated record creation limits; customer PII handling; cross-border data transfer CONFIDENTIAL PENDING
Confluence (Atlassian) Atlassian Cloud Terms, API Terms of Use Automated page creation/update limits; content ownership; data residency requirements BUSINESS PENDING
Google Workspace Google Workspace Terms, API Services Terms Service account vs. OAuth delegation; Gmail sending limits; Drive sharing policies BUSINESS PENDING

Terms of Service Compliance Verification

Per-platform verification that agent behavior stays within ToS boundaries.

Rate Limit Compliance

Every integration connector enforces platform-specific rate limits:

  • ● Configurable per-integration rate limits in integration_config
  • ● Token bucket algorithm with Redis-backed counters
  • ● Automatic backoff on 429 responses
  • ● Rate limit usage exposed in observability dashboards

Bot Account Requirements

Platforms that require bot/service accounts for automated access:

  • ● Slack: Dedicated bot user with appropriate scopes
  • ● GitHub: Machine user or GitHub App installation
  • ● Jira: Atlassian API token with service account
  • ● All actions clearly attributed to Praesidium2 bot (no impersonation)

Liability Framework for Automated Agent Actions

When AI agents take actions on third-party platforms, clear accountability and liability boundaries must be defined.

ScenarioLiability OwnerMitigation
Agent creates incorrect Jira ticket or Confluence page Team lead (human who configured the agent) Approval workflow for CRITICAL actions; audit trail in activity_log
Agent sends incorrect Slack message to external channel Instance admin + team lead External-facing channels require CRITICAL tool safety level (human approval)
Agent modifies production code via GitHub Engineering lead (PR reviewer) All agent commits go through PR with mandatory human review; no direct push to main
Agent accesses or exposes customer PII Greater Goods (data controller) PHI/PII detection layer; local LLM routing; data classification on all integration fields
Agent exceeds platform API rate limits Platform team (engineering) Per-integration rate limiting; automatic backoff; monitoring alerts
Agent takes action based on hallucinated data Team lead + platform team Step-by-step reasoning traces; human checkpoints for high-impact actions; feedback loop (B13)

Insurance Coverage Review

AI-driven operations introduce novel risk categories that may not be covered by standard business insurance:

Coverage AreaAction Required
Errors & Omissions (E&O)Verify AI-generated output is covered under existing E&O policy
Cyber LiabilityConfirm coverage for AI agent data handling and API interactions
Professional LiabilityReview coverage for automated decisions that impact clients or partners
Technology E&OEvaluate need for AI-specific technology errors coverage

LLM Provider Data Agreements

Data handling agreements with each LLM provider used by the platform:

ProviderAgreementKey Terms
AnthropicEnterprise Terms + DPANo training on customer data; SOC 2 Type II; data retention controls
OpenAIEnterprise AgreementZero data retention option; API-only (no training); data processing addendum
Google (Gemini)Cloud AI TermsEnterprise data protection; no model training on inputs; regional processing
Local (Ollama/vLLM)Self-hostedNo external data transfer; full data sovereignty; HIPAA-compatible

Data GovernanceExecutive OperationsBusiness Review B15: Ownership, accountability, and retention for agent-generated content

Agents generate content — documents, reports, code, decisions. Clear governance policies define who owns that output, who is accountable for errors, and how long it is retained.

Agent-Generated Content Ownership

Content TypeOwnerPolicy
Documents & ReportsInstance (business unit)Owned by the business unit that commissioned the agent work. All artifacts tagged with instance_id.
Code (PRs, commits)Greater Goods (employer)Standard work-for-hire doctrine applies. Agent-generated code treated the same as contractor code.
Decisions & RecommendationsTeam lead (human)Agent recommendations are advisory. The human who approves the action owns the decision.
Meeting SummariesInstance (business unit)Generated summaries retained per instance retention policy. Human attendees can edit/override.

Accountability Framework

ScenarioAccountable Party
Agent produces factually incorrect reportTeam lead who approved/distributed the output
Agent misinterprets task instructionsTask creator (human who wrote the instructions)
Agent runtime bug causes data corruptionEngineering team (platform defect)
Agent output used in regulatory filingFiling signatory (human); agent output must be reviewed

Retention Policies for Agent Output

Output TypeRetentionDisposal
Task artifactsProject lifetime + 1 yearS3 lifecycle → delete
Conversation history3 yearsSoft delete → hard delete
Meeting summaries3 yearsArchived to cold storage after 1 year
Escalation records5 yearsRetained for audit trail purposes
Agent-generated codeIndefinite (in Git)Standard Git history retention

Regulatory Filing Guidelines

When agent-generated content is used in regulatory or legal contexts:

  • ● All agent output must be reviewed and approved by a human before inclusion in any regulatory filing
  • ● Agent-generated content must be clearly labeled as AI-assisted where disclosure is required
  • ● The complete reasoning trace for any agent output used in filings must be preserved for 7 years
  • ● Legal team must approve the use of agent-generated content in any external-facing regulatory document

Testing & StabilityTechnical OperationsTesting strategy, CI/CD, SLAs, disaster recovery

Testing is not an afterthought — it's built into every layer from Day 1. Stability engineering ensures the platform stays reliable under real-world conditions.

Testing Pyramid

LayerToolCoverage TargetWhat It Tests
Unitpytest (Python), JUnit (Java), Vitest (TypeScript)90%+Individual functions, classes, utilities
Integrationpytest + testcontainers80%+Service ↔ database, service ↔ Redis, service ↔ qqq API
API Contractpytest + OpenAPI validation100%Request/response schema compliance, error codes
E2EPlaywright (frontend), pytest (backend)Critical pathsFull user flows: login → create project → chat → execute task
LoadLocust or k6Defined SLAsConcurrent agent execution, API response times, WebSocket scalability
SecurityOWASP ZAP, Snyk, Semgrep, TrivyZero HIGH/CRITICALXSS, SQLI, SSRF, dependency vuln, container scanning, secrets scanning
ComplianceCustom audit tests100% HIPAA controlsEncryption verification, access logging, data retention

CI Enforcement Rules

⛔

No PR Merges Without Passing Tests

Faber pipeline blocks merge on any test failure. No exceptions.

📊

Coverage Gates

Python 90%, Java 85%, TypeScript 90% — PR rejected if coverage drops below threshold.

🧬

Mutation Testing (Weekly)

Stryker (TS) / mutmut (Python) to verify tests actually catch bugs, not just cover lines.

📄

Contract & Snapshot Tests

Every qqq API endpoint has a contract test. Frontend components verified via snapshot comparison for visual regression.

Agent-Specific Testing

Agent Behavior Tests

Given a system prompt + tools + input → verify the agent produces expected tool calls. Not testing LLM output text, but testing that the right tools are called in the right order.

Memory System Tests

Verify memory extraction produces expected types, embedding similarity is correct, deduplication works, recall returns relevant memories.

Tool Execution Tests

Each tool has unit tests (mocked external calls) and integration tests (real qqq API calls). CUSTOM tool sandbox tests verify resource limits and network isolation.

Meeting & LLM Fallback Tests

Verify standup produces expected conversation flow, action items are extracted. Verify LLM provider fallback when primary returns errors.

SLA Targets (Internal)

MetricTargetMeasurement
API availability (qqq + gateway)99.9%Uptime Robot + Prometheus
Chat response time (TTFT)<2s p95SSE timestamp in browser
Task execution start time<10s p95Celery task timestamps (queue → running)
Scheduled job on-time execution>99%Celery Beat + job_execution timestamps
WebSocket reconnection<5sClient-side monitoring
Mean time to recovery (MTTR)<15 minIncident tracking

Circuit Breaker Patterns

Anthropic / OpenAI API

Circuit opens after 5 consecutive failures. Half-open after 30s. Fallback to secondary LLM provider.

Integration APIs (Jira, Slack, etc.)

Circuit opens after 3 consecutive failures. Coolback 60s. Updates integration_config.health_status.

qqq API (from gateway/workers)

Retry 3x with exponential backoff (1s, 2s, 4s). No circuit breaker — qqq must be available.

Redis

Connection pool with automatic reconnect. If Redis is completely down, gateway falls back to direct DB queries (degraded mode).

Graceful Degradation

Component DownImpactDegraded Behavior
RedisNo WS broadcasts, no task queueGateway handles chat inline, tasks queued in-memory (limited)
One qqq podNonek8s Service routes to other replicas
All workersNo async executionChat still works (gateway inline), tasks queue until workers recover
LLM providerAgents can't thinkFallback to secondary provider, or queue tasks
Tool-runnerCUSTOM tools failPLATFORM + INTEGRATION tools still work, CUSTOM tools return error
S3 / MinIONo artifact storageAgents work without artifacts, uploads fail gracefully

Health Check Matrix

PodLivenessReadinessStartup
qqq-apiGET /health (DB ping)GET /ready (migrations complete)90s timeout
gatewayGET /health (Redis ping)GET /ready (qqq API reachable)30s timeout
workerCelery inspect pingCelery inspect active60s timeout
webGET / (static file)GET /10s timeout

Disaster Recovery Strategy

<1hr
RPO (Recovery Point Objective)

Point-in-time recovery from RDS continuous backups

<30m
RTO (Recovery Time Objective)

Automated restore from snapshots + Redis warm-up

ComponentBackup MethodRecovery Procedure
PostgreSQL (RDS)Daily snapshots (35-day retention) + continuous WAL for PITRRestore from snapshot or PITR to new RDS instance. Update connection strings via ConfigMap.
Redis (ElastiCache)AOF persistence + daily automatic backupsMulti-AZ automatic failover. Manual: restore from backup to new cluster.
S3 (Artifacts, Tools)S3 versioning + cross-region replication for critical dataRestore from version history or failover to replica bucket.
Secrets ManagerAWS-managed durability, replicated across AZsAutomatic. No manual recovery needed.
LangGraph CheckpointsIncluded in PostgreSQL backups (same RDS instance)Restored with database. In-flight workflows resume from last checkpoint.
AuthentikSeparate RDS instance with own backup scheduleRestore Authentik DB. Existing JWTs remain valid during recovery window.

Incident Response Flow

1
Detect
Prometheus alerts
→
2
Notify
PagerDuty / Opsgenie
→
3
Auto-Remediate
HPA, pod restart, circuit breakers
→
4
Runbook
Confluence-linked per alert
→
5
Post-Mortem
Blameless, within 48hrs

Every P1/P2 incident gets a blameless post-mortem within 48 hours. Every alert has a linked runbook in Confluence with symptoms, diagnosis steps, remediation, and escalation path.

Business OperationsExecutive Operations TechnicalApproval workflows, KPIs, training, rollback, feedback, agent management

Business infrastructure that ensures agents operate safely, deliver measurable value, and improve over time. These capabilities were identified in the Business Readiness Review (findings B3, B4, B5, B11, B13, B17) as critical gaps between the technical platform and production deployment readiness.

6
New Subsystems
12
New Tables
5
Teams Covered
$210K
Annual ROI Target
☑

B3: Agent Output Approval Workflow

Human-in-the-Loop Business Review Gap

All agent actions that touch external systems go through a human approval queue during early rollout (first 2–4 weeks per team). As trust builds, teams graduate from full review to spot-check to autonomous operation. This is the single most important safeguard for Day 1 deployment.

Autonomy Graduation Model

1
Full Review
100% approval required
→
2
Spot Check
20% random sampling
→
3
Autonomous
Post-hoc audit only
→
4
Trusted
No intervention needed

Graduation criteria: ≥95% approval rate over 50+ actions, no rejected actions in last 7 days, team lead sign-off. Demotion triggers: 2+ rejections in a 24-hour window automatically drops autonomy one level.

Escalation Triggers (Always Require Approval)

TriggerConditionExample
High-Cost ActionEstimated cost exceeds $threshold (default $50)Bulk email send, large API call, paid service invocation
External-Facing ContentAction publishes to external audienceSocial media post, customer email, public documentation update
First-Time Tool UsageAgent has never used this tool beforeFirst CRM update, first Jira ticket creation
Data ModificationAction modifies >10 records or deletes any recordBulk Jira update, spreadsheet mass-edit
Cross-Team ActionAction targets another team's resourcesUpdating another department's Confluence space

Approval Dashboard — UI Mockup

The approval queue is a dedicated page in the Praesidium2 dashboard, accessible to team leads and admins. Each pending item shows:

  • Agent Name — which agent is requesting approval
  • Action Summary — one-line description of what the agent wants to do
  • Reasoning Trace — expandable chain-of-thought showing why the agent chose this action
  • Target System — Jira, Slack, Confluence, CRM, etc.
  • Estimated Impact — cost, records affected, audience reach
  • Approve / Reject / Edit — one-click actions with optional feedback text

Wireframe: Approval Queue Item

Marketing COS → Post to LinkedIn Pending

“I want to publish the Q2 product launch announcement to the company LinkedIn page. The draft has been reviewed by the content agent and matches brand guidelines.”

✓ Approve ✗ Reject ✎ Edit & Approve

SLA: Pending items older than 4 hours trigger a Slack reminder to the approver.

Data Model — Approval Tables

TableKey ColumnsPurpose
task_approval_queue id, task_id, agent_id, action_type, action_payload, reasoning, status_id (PENDING/APPROVED/REJECTED), reviewer_id, feedback, created_at, resolved_at, instance_id Queue of agent actions awaiting human approval. Each row is one proposed action with full reasoning trace.
approval_policy id, instance_id, team_id, tool_id, action_pattern, requires_approval, cost_threshold, audience_type, created_by, updated_at Configurable rules per team and tool defining which actions require approval and under what conditions.
autonomy_level id, instance_id, team_id, agent_id, level (FULL_REVIEW/SPOT_CHECK/AUTONOMOUS/TRUSTED), promoted_at, promoted_by, reason, approval_count, rejection_count Tracks each agent's autonomy graduation status per team. History of promotions and demotions.
☰

B4: Success Metrics & KPIs Dashboard

Measurement Business Review Gap

Without baseline measurements and ongoing KPI tracking, there is no way to identify which agents are delivering value or how teams are benefiting from AI enablement. This subsystem captures pre-deployment baselines and tracks productivity improvement over time across all 5 teams.

Productivity Gains Framework

5
Teams Tracked
Weekly
Reporting Cadence
Baseline
Pre-Deploy Capture
TeamKey Productivity MetricBaseline MethodExpected Productivity Gains
CTO / EngineeringHours on operational overhead2-week time tracking surveyReduced context-switching, automated standups, faster decision support
VP MarketingCampaign setup time, report generationTask duration logs pre-deploymentAutomated competitor analysis, faster content drafts, quicker report turnaround
VP HROnboarding time, policy lookup frequencyHR ticket resolution timesAutomated onboarding checklists, faster FAQ responses, reduced manual triage
VP ProductFeature request triage, roadmap updatesJira cycle time pre-deploymentAutomated triage, sprint health reports, reduced coordination overhead
VP OperationsProcess documentation, cross-team coordinationConfluence update frequencyAutomated process docs, coordination summaries, reduced manual writing

Productivity gains are measured as reduction in time-on-task compared to pre-deployment baselines, increases in throughput, and improvements in first-attempt approval rates across agent-assisted workflows.

KPI Categories & Tracking

CategoryMetricSourceFrequency
EfficiencyHours saved per team per weekTask completion times vs. baselineWeekly
EfficiencyTasks automated (count)task table where assignee is agentWeekly
QualityError reduction rateFeedback scores + rejection rate from approval queueWeekly
QualityFirst-attempt approval ratetask_approval_queue approve vs. reject ratioWeekly
AdoptionActive human users per teamLogin frequency, chat sessions initiatedWeekly
AdoptionAgent utilization rateBusy time / available time per agentWeekly

Dashboard — UI Mockup

The KPI dashboard is a top-level page accessible to team leads, VPs, and admins. Key views:

Weekly Team Summary

Hours Saved18.5 hrs
Tasks Completed by Agents47
Approval Rate96.2%
Agent Utilization Rate84%

Trend Sparklines (4 weeks)

Hours Saved
Agent Utilization
Feedback Score

Data Model — KPI Tables

TableKey ColumnsPurpose
kpi_baseline id, instance_id, team_id, metric_name, baseline_value, unit, captured_at, captured_by, method Pre-deployment baseline measurements per team. Captured once before agents go live, used as the reference point for measuring productivity improvement over time.
kpi_measurement id, instance_id, team_id, metric_name, value, unit, period_start, period_end, source, computed_at Ongoing metric snapshots (daily/weekly). Automated aggregation jobs populate most rows; some manual entries for subjective metrics.
team_productivity_report id, instance_id, team_id, period_start, period_end, hours_saved, tasks_automated, approval_rate, agent_utilization_rate, generated_at Weekly productivity rollup per team. Auto-generated report comparing current throughput and efficiency metrics against pre-deployment baselines.
⏱

C2: Pre-Build KPI Baseline Collection

Pre-Requisite Business Review Gap

The KPI dashboard (B4) above is useless without baseline data to compare against. This baseline collection must start immediately — it does not depend on the platform build and runs in parallel with development. Without it, there is no way to prove ROI at the 30-day or 60-day gates.

⚠ Start Immediately: This is the one workstream that can (and must) begin before any code is written. The 2-week survey window should overlap with Phase 1–2 of the build. If baseline collection is delayed, ROI measurement at the 30-day gate (B22) will have no reference point.

2-Week Time-Tracking Survey

Each team lead logs detailed time data for 2 weeks before agents go live. This captures the "before" snapshot that makes ROI calculation meaningful.

Data CollectedMethodResponsibleFrequency
Hours spent on agent-targeted tasks Daily time log (spreadsheet or Jira time tracking) Each team lead + direct reports Daily for 2 weeks
Current error rates Count of rework items, rejected deliverables, missed deadlines Team leads Weekly summary
Throughput metrics Tasks completed per person per week, report generation time Team leads + Jira export Weekly summary
Coordination overhead Hours in meetings, Slack threads, email chains for cross-team coordination Team leads (estimate) Weekly summary
Subjective satisfaction 1-question survey: "How much of your time is spent on work only a human can do?" (1–5 scale) All team members Once at start, once at end

Timeline

  • ● Day 0: CTO distributes time-tracking template to all 5 team leads
  • ● Days 1–14: Teams log daily time data on tasks agents will handle
  • ● Day 15: CTO aggregates data into kpi_baseline table format
  • ● Day 16+: Baselines loaded into KPI dashboard on Day 1 of platform deployment

Success Criteria

  • ✓ All 5 team leads have submitted 2 weeks of data
  • ✓ At least 3 data points per metric per team
  • ✓ Baselines reviewed and approved by each team lead
  • ✓ Data formatted and ready for kpi_baseline table import
★

B5: User Training & Onboarding

Adoption Business Review Gap

A platform is only valuable if people actually use it. This subsystem provides role-specific onboarding, in-app guidance, and troubleshooting resources to ensure every team member can work effectively with their AI agents from Day 1.

Role-Based Quickstart Guides

RoleGuide ContentDurationDelivery
Team LeadDashboard overview, approval queue, KPI tracking, agent configuration, autonomy level management30 minIn-app guided tour + PDF
Team MemberChat interface, task delegation, reviewing agent work, providing feedback, escalation15 minIn-app guided tour + PDF
AdminInstance setup, integration configuration, user management, security policies, monitoring45 minIn-app tour + video walkthrough

30-Minute Team Walkthrough Template

1
Welcome
5 min — What agents do
→
2
Live Demo
10 min — Real task
→
3
Try It
10 min — Hands-on
→
4
Q&A
5 min — Concerns

Each team gets a customized walkthrough using their own agents, tools, and real use cases. The COS agent can assist in running the demo in real-time.

“Agent Did Something Wrong” — Troubleshooting FAQ

SymptomLikely CauseResolution
Agent sent wrong data to JiraOutdated context or misunderstood taskUse Undo button in action log → correct task description → re-run
Agent keeps asking the same questionMemory not persisting or conflicting instructionsCheck memory tab for the agent → clear stale entries → update system prompt
Agent ignoring my feedbackFeedback not linked to prompt improvement pipelineVerify feedback is recorded in dashboard → escalate to admin if pattern persists
Agent took action without approvalAutonomy level too high or action not in policy scopeCheck autonomy_level table → add approval_policy rule for this action type
Agent is slow to respondQueue backlog, token limits, or external API latencyCheck job queue in observability → review rate limits → check integration health

In-App Onboarding & Contextual Help

First-Time User Flow:

  • ❶ Welcome modal explaining the team's AI agents
  • ❷ Interactive tour highlighting: chat, dashboard, approval queue
  • ❸ First guided task: “Ask your COS agent to summarize today's tasks”
  • ❹ Success confirmation with link to quickstart guide
  • ❺ Opt-in to daily tips (dismissible after 1 week)

Contextual Help Tooltips:

  • ? Hover tooltips on every dashboard metric explaining what it measures
  • ? “What can I ask this agent?” prompt in chat sidebar
  • ? Inline help on approval decisions: “What happens if I reject?”
  • ? Keyboard shortcut cheat sheet (? key to toggle)
↺

B11: Rollback & Recovery Procedures

Safety Business Review Gap

When an agent makes a mistake, the team needs to undo it quickly. This subsystem provides per-integration reversal procedures, an “Undo Last Action” capability, a comprehensive audit log with replay/rollback, and an emergency kill switch per agent.

Per-Integration Reversal Procedures

IntegrationAction TypeReversal MethodAutomated?
JiraIssue createdDelete issue via REST APIYes
JiraIssue updated (status, fields)Restore previous field values from agent_action_logYes
ConfluencePage created/updatedRevert to previous version via Confluence APIYes
SlackMessage sentDelete message via chat.delete APIYes
SlackChannel createdArchive channel (Slack does not support delete)Partial
Email (SES)Email sentCannot recall — documented as non-reversible; requires approval gateNo
CRM / ZohoRecord created/updatedRestore from agent_action_log.before_state via APIYes
Google SheetsCells modifiedRestore from sheet version historyPartial

Non-reversible actions (email, SMS, social media posts) are always routed through the approval queue regardless of autonomy level. The approval policy enforces this automatically.

“Undo Last Action” Capability

Every agent action that modifies an external system captures a before_state and after_state snapshot. The Undo button in the action log:

1
User clicks Undo
From action log row
→
2
Confirm Dialog
Shows what will change
→
3
Execute Reversal
API call with before_state
→
4
Log Rollback
Record in rollback_record

Undo is available for the most recent action per agent per integration. For deeper rollback (multiple actions), the admin uses the batch rollback interface in the action audit log.

Emergency Kill Switch

Every agent has a kill switch accessible from the agent detail page and the team dashboard. When activated:

  • Immediate: Agent's job queue is paused (no new tasks dispatched)
  • Within 5s: In-flight task execution is interrupted (graceful shutdown signal)
  • Within 30s: All pending approval queue items for this agent are cancelled
  • Persistent: Agent marked as SUSPENDED — requires admin action to reactivate

Wireframe: Kill Switch

⚠ EMERGENCY STOP
Marketing COS Agent
Stop Agent Now

This will immediately pause all agent activity. Requires admin to reactivate.

Data Model — Rollback Tables

TableKey ColumnsPurpose
agent_action_log id, instance_id, agent_id, task_id, integration_id, action_type, target_resource, before_state (JSONB), after_state (JSONB), is_reversible, reversed_at, created_at Complete audit trail of every external action. Stores before/after state for rollback capability. The source of truth for Undo operations.
rollback_record id, action_log_id, initiated_by, rollback_type (SINGLE/BATCH), status_id (SUCCESS/FAILED/PARTIAL), error_detail, created_at, instance_id Tracks every rollback attempt with success/failure status. Links back to the original action log entry.

Agent-Led Rollback Protocol

AGENT RUNTIME SPEC

To support programmatic rollback, every tool execution stores the parameters needed to reverse the action. This enables the “Undo Last Action” UI to execute reversals without human-authored reversal scripts.

Schema Extension: job_execution

ALTER TABLE job_execution
ADD COLUMN revert_payload  JSONB,        -- Args needed to "undo" this action
ADD COLUMN revert_tool_id  UUID REFERENCES tool(id);

Tool Contract

Every Tool in the catalog must implement:

def get_revert_params(args, result) -> dict:
    """Return the args needed to undo this action."""
    # Example: jira.update_status(to='Done')
    # returns: {"to": "In Progress"}

Example: Jira Status Update

StepActionStored Data
Execute jira.update_status(issue="PROJ-42", to="Done") Result: {"previous_status": "In Progress"}
Store get_revert_params() computes reversal args revert_payload: {"issue": "PROJ-42", "to": "In Progress"}
revert_tool_id: <jira.update_status UUID>
Rollback Triggers jira.update_status with revert_payload Logged in rollback_record with SUCCESS/FAILED status

Non-reversible actions (email, SMS) return null from get_revert_params() and are flagged as is_reversible = false in the action log. These are always routed through the approval queue.

Git Rollback Pull Request Protocol

v1.9

For Git-based tools (e.g., git_merge, github_create_pr, github_push_files), the standard revert() flow MUST NOT perform a direct git revert on protected branches. Instead, rollbacks are routed through a Revert Pull Request workflow to preserve branch protection rules and enable human review.

Revert PR Flow

1. Agent calls revert() on a Git-based tool execution
2. System checks tool.requires_review — if true, enters PR flow
3. Creates a new branch: praesidium-rollback/{execution_id}
4. Commits the revert changes to the branch
5. Opens a Revert Pull Request tagged [Praesidium-Rollback]
6. PR body includes: original action log ID, rollback reason, diff summary, link to Praesidium audit trail

Schema: tool.requires_review

ALTER TABLE tool
ADD COLUMN requires_review BOOLEAN DEFAULT false;
-- When true, revert() creates a PR instead of direct action

All Git-based tools (git_merge, github_push_files, github_create_pr) ship with requires_review = true by default. Admins can override per-tool via the tool catalog.

Rationale: Direct git revert on protected branches bypasses branch protection rules, code review requirements, and CI gates. The PR-based flow ensures rollbacks receive the same scrutiny as forward changes while maintaining a clear audit trail via the [Praesidium-Rollback] tag.

★

B13: Human Feedback Mechanism

Quality Business Review Gap

Without structured human feedback, there is no way to measure whether agents are actually helping or to improve them over time. This subsystem adds thumbs-up/down on all agent outputs, aggregates feedback per agent and tool, and feeds quality signals into the prompt improvement pipeline.

Feedback Collection Points

Output TypeFeedback MethodMetadata Captured
Chat ResponseThumbs up/down + optional text on each assistant messageConversation ID, message ID, agent ID, timestamp
Task CompletionRate 1–5 stars on task result + optional commentTask ID, agent ID, tool IDs used, duration
Daily SummaryThumbs up/down on standup / EOD summaryJob execution ID, summary type, team ID
Approval DecisionImplicit: approve = positive, reject = negative (with reason)Approval queue ID, action type, escalation reason
Document GeneratedThumbs up/down + “needs edits” flag with diffDocument reference, tool ID, generation parameters

Quality Score Aggregation & Trending

Aggregation Dimensions:

  • Per Agent: Rolling 7-day and 30-day quality score (weighted average of all feedback)
  • Per Tool: Which tools produce the best/worst outputs (feedback grouped by tool_id)
  • Per Team: Overall satisfaction per business unit
  • Per Output Type: Chat vs. task completion vs. summary quality

Wireframe: Quality Trend

Marketing COS4.3/5.0
Engineering COS4.6/5.0
HR Agent3.2/5.0

Score <3.5 triggers probation review (see B17)

Feedback → Prompt Improvement Pipeline

1
Collect Feedback
Thumbs, stars, text
→
2
Aggregate & Tag
By agent, tool, type
→
3
Identify Patterns
Recurring negatives
→
4
Adjust Prompts
Update system prompt
→
5
Measure Impact
Score delta post-change

Negative feedback on a specific output type triggers a review queue for the admin. The admin can view the original output alongside the feedback, then adjust the agent's system prompt or tool configuration. The before/after quality score delta is tracked automatically.

Data Model — Feedback Tables

TableKey ColumnsPurpose
output_feedback id, instance_id, agent_id, team_member_id, output_type (CHAT/TASK/SUMMARY/DOCUMENT), reference_id, rating (1–5), is_positive, comment, created_at Individual feedback entries on every agent output. The reference_id points to the message, task, or job execution that produced the output.
agent_quality_score id, instance_id, agent_id, period_start, period_end, avg_rating, positive_count, negative_count, total_feedback, score_by_type (JSONB), computed_at Rolling aggregated quality scores per agent. Computed daily by a scheduled job. JSONB column breaks down scores by output type and tool.
⚙

B17: Agent Performance Management

Governance Business Review Gap

Agents are employees that need performance management. When an agent underperforms, there must be a structured process to diagnose the issue, reduce autonomy, adjust configuration, and if necessary, terminate the agent. This prevents bad agents from eroding team trust in the platform.

Agent Performance Status Lifecycle

✓
Active
Normal operations
→
!
Probation
Reduced autonomy
→
✗
Suspended
No task execution
→
■
Terminated
Archived permanently

Any status can transition back to Active after admin review and config adjustment — except Terminated, which is permanent.

Automatic Performance Thresholds

TriggerThresholdAction
Feedback score dropsRolling 7-day average < 3.5 / 5.0Auto-Probation — autonomy level reduced to FULL_REVIEW, admin notified
Rejection spike≥3 approval rejections in 24 hoursAuto-Probation — autonomy demoted, team lead alerted via Slack
Error rate surge>20% task failure rate over 48 hoursAuto-Suspend — agent paused, incident created in activity log
Cost anomalyDaily cost >3x rolling 7-day averageAuto-Probation — budget cap enforced, admin review required
Prolonged low performanceOn probation for >14 days with no improvementAuto-Suspend — requires admin investigation before reactivation

Agent Configuration Adjustment Workflow

When an agent enters probation, the admin has a structured investigation and remediation flow:

Investigation Steps:

  • ❶ Review recent feedback (negative ratings, rejection reasons)
  • ❷ Examine reasoning traces on failed/rejected tasks
  • ❸ Check if external API changes caused failures
  • ❹ Compare prompt version history for recent changes

Remediation Options:

  • A Update system prompt with corrective instructions
  • B Restrict tool access (remove problematic tools)
  • C Adjust memory entries (clear stale/incorrect context)
  • D Switch LLM model (e.g., from fast to reasoning model)

Agent Termination Procedure

Termination is permanent and requires admin-level access. The procedure ensures nothing is lost:

1
Suspend Agent
Stop all activity
→
2
Archive Config
Snapshot to S3
→
3
Document Reason
Required text entry
→
4
Reassign Tasks
Pending → other agents
→
5
Mark Terminated
Irreversible

The archived configuration (prompt, tool assignments, memory, skills) is preserved in S3 for compliance and in case a similar agent needs to be recreated later. All conversation history and action logs are retained indefinitely per compliance policy.

Cross-References

These business operations subsystems integrate with existing platform components:

Business Ops FeatureIntegrates WithHow
Approval Queue (B3)Agent Runtime, IntegrationsAgent execution pauses at integration boundary, awaits approval before external API call
KPI Dashboard (B4)Observability, Data ModelAggregates existing task/message/cost data plus new baseline tables
Training (B5)Frontend, Auth & SecurityOnboarding flow hooks into first-login detection and role-based routing
Rollback (B11)Integrations, Activity LogExtends existing activity_log with before/after state capture per integration
Feedback (B13)Chat UI, Task UI, Agent RuntimeFeedback widgets embedded in every agent output surface
Performance Mgmt (B17)Feedback (B13), Approval (B3), ObservabilityConsumes quality scores, rejection rates, and cost data to drive automated governance

Federation

COS-to-COS communication across business unit instances — enabling cross-department visibility, escalation forwarding, shared projects, and organization-wide reporting without breaking per-instance isolation.

Use Cases

★

Status Sharing

Product COS asks Marketing COS: "What's the status of the Q4 campaign?" Marketing COS queries local projects, filters through federation policy (summary-level only), and returns structured status.

🔍

Knowledge Queries

Sales COS asks Engineering COS: "Do we have tools that work with Zoho?" Engineering COS searches its tool catalog and knowledge base, returns matches. No source code or credentials are ever shared.

🔗

Cross-Functional Projects

"Website Redesign" spans Engineering, Marketing, and Design. Each instance has local projects linked via federation_project_link. COS agents coordinate at milestone boundaries.

👥

Resource Discovery

DevOps COS asks Engineering COS: "Who has Kubernetes expertise?" Engineering COS queries agent skills and human profiles, applies sharing policy, returns availability (names or counts depending on policy).

⚠

Escalation Forwarding

Marketing agent encounters a deploy pipeline issue. Escalates to Marketing COS, who forwards to Engineering COS via federation message. Engineering COS creates a local escalation. Resolution flows back.

📊

Scheduled Reports

Weekly scheduled job queries each peer's COS for project health, escalations, and cost data. Aggregates into a cross-department executive report posted to Slack.

Federation Architecture

All cross-instance communication is COS-to-COS through federation gateways. Individual agents never talk to remote instances directly.

Tech Team

Agents: Architect, Backend-1, QA-Bot, DevOps-Bot

COS Agent (coordinator)
Federation Gateway
mTLS + JWT

Marketing

Agents: Macho Man, The Rock, Stone Cold, The Undertaker, Ric Flair, Bret Hart

COS Agent (coordinator)
Federation Gateway
mTLS + JWT

HR

Agents: Recruiter, Onboarder, Benefits, Payroll

COS Agent (coordinator)
Federation Gateway

Shared: Authentik (IdP) + Federation Registry (k8s ConfigMap)

Access Levels

Authorization is policy-driven and enforced at the receiving instance. Default for new peers is DENY ALL.

NONE

Nothing shared. Default for all new peers. Access must be explicitly enabled by admin.

SUMMARY

High-level status only. Health indicators and counts. "3 active projects, 2 on-track, 1 at-risk."

DETAIL

Project names, milestone status, team member names. "Website Redesign: Design phase complete."

FULL

Task-level details, agent memories, tool outputs. Full task list with descriptions and assignees.

Security Model

🔒

mTLS Authentication

Each gateway has a TLS client certificate from a shared CA (stored in praesidium-federation namespace). Federation endpoints require valid client certificates, verifying peer identity at transport layer.

🔑

Signed JWT Tokens

Each request includes JWT signed by the sender's service account. Contains iss (instance), sub (COS agent), aud (target), exp (5 min), scope (capability). Validated against Authentik JWKS.

📜

Dual Audit Trail

Every interaction logged in both instances: sending instance records OUTBOUND federation_message + activity_log. Receiving instance records INBOUND federation_message + activity_log. Complete trail even if one instance goes down.

⏱

Rate Limiting

Per-capability limits enforced via Redis token bucket. project_status: 60/hr, knowledge_search: 20/hr, escalation_intake: 10/hr, status_rollup: 5/hr. HTTP 429 with Retry-After on limit breach.

Data Classification

ClassificationFederation BehaviorExample
PUBLIC Shared freely with any active peer General project health status
INTERNAL Shared only when policy explicitly allows for that peer Team member names, task details
CONFIDENTIAL Never shared via federation, regardless of policy Agent system prompts, credentials
RESTRICTED Never shared, and existence is not disclosed Memory contents, internal escalation details

New Tables (4 entity + 4 type = 8 tables)

federation_peer

PK id UUID
name VARCHAR(100) -- "tech-team", "marketing"
instance_id UUID NOT NULL -- remote instance ID
gateway_url VARCHAR(500) -- k8s or ALB URL
auth_config JSONB -- {method: "mtls"|"api_key"}
FK status_id → federation_peer_status
capabilities_offered JSONB
capabilities_consumed JSONB
last_health_check TIMESTAMPTZ
total_queries_sent INT DEFAULT 0
UNIQUE(instance_id) IDX(status_id, name)

federation_message

PK id UUID
FK peer_id → federation_peer(id)
FK direction_id → federation_message_direction
request_id UUID -- correlates req/resp
capability VARCHAR(50) -- "project_status"
FK access_level_id → federation_access_level
query / response JSONB
status VARCHAR(20) -- PENDING, SUCCESS, DENIED
cost_usd DECIMAL(10,6)
latency_ms INT
IDX(peer_id, direction_id, request_id, capability, created_at DESC)

federation_policy

PK id UUID
FK peer_id → federation_peer(id) -- null = all peers
resource_type VARCHAR(50) -- "project", "tool", "knowledge"
FK access_level_id → federation_access_level
FK classification_min_id → federation_data_classification
conditions JSONB -- {project_ids, exclude_tags}
is_active BOOLEAN DEFAULT true
UNIQUE(peer_id, resource_type) IDX(is_active)

federation_project_link

PK id UUID
FK local_project_id → project(id) ON DELETE CASCADE
FK peer_id → federation_peer(id)
remote_project_id UUID -- UUID in peer instance
remote_project_name VARCHAR(150)
is_lead BOOLEAN DEFAULT false
sync_frequency VARCHAR(50) -- daily, hourly, manual
sync_config JSONB -- {share_milestones, health, blockers}
UNIQUE(local_project_id, peer_id, remote_project_id)

Implementation Phases

Federation is implemented in 4 phases, each building on the previous. Each phase is independently deployable and provides value.

Phase 1
Read-Only Status Queries
4 wks

P1: Peer Registration + Status Queries — federation_peer and federation_policy tables, gateway endpoints (/health, /capabilities, /query), API key auth, project_status and tool_catalog capabilities, federation_message logging, Settings UI for peer management, Redis rate limiting.

Phase 2
Escalation Forwarding
4 wks

P2: Escalation + Knowledge — escalation_intake, knowledge_search, resource_discovery capabilities. Async messaging (POST /federation/message). mTLS replacing API keys. Signed JWT tokens. Bidirectional escalation resolution flow.

Phase 3
Shared Projects + Reports
5 wks

P3: Shared Projects + Scheduled Reports — federation_project_link table, cross-instance project coordination (LangGraph workflow), status_rollup capability, weekly cross-department aggregation, parallel multi-peer querying, aggregated federation cost tracking.

Phase 4
Executive Dashboard
6 wks

P4: Executive Dashboard + Advanced — Dedicated executive instance consuming rollups from all departments. Cross-instance cost aggregation. Event streaming (Redis pub/sub or NATS) for real-time notifications. Cross-instance agent task delegation. Protocol version negotiation.

Review SummaryTechnical73 findings across 3 review passes + 9 audit findings — all resolved

73
Total Findings
7
Blockers Resolved
3
Review Passes
☰

Findings by Severity

CRITICAL2 findings
HIGH5 findings
MEDIUM6 findings
LOW3 findings
BLOCKER5 findings
GAP20 findings
ENHANCEMENT5 findings
AUDIT28 findings

Pass 1: Architecture & Security Review

16 findings from senior systems architect — covering architecture, data model, security, performance, and operations.

ID Severity Category Finding Resolution Status
R1 CRITICAL Operations No backup, disaster recovery, or database rollback strategy documented. Single RDS failure could result in total data loss. Added DR section: RPO <1hr, RTO <30min. Automated RDS snapshots, Redis AOF, S3 versioning, Liquibase rollback, tested restore procedure. Applied
R2 CRITICAL Data Model instance_id column for RLS never appears in entity table definitions. Unclear whether direct column or join-based. Documented explicit instance_id placement: 9 root tables with direct column, child tables via FK join chain. qqq RecordSecurityLock config unblocked. Applied
R3 HIGH Architecture Redis is SPOF for 5 critical functions (task queue, WebSocket pub/sub, session cache, rate limiting, agent cache). No HA strategy. Added Redis HA: ElastiCache Multi-AZ, AOF persistence, separate Queue vs Cache clusters, fallback behaviors when Redis is unavailable. Applied
R4 HIGH Operations No log aggregation, distributed tracing, or centralized observability. Debugging across 5 services is impractical. Added log aggregation (CloudWatch/Loki), OpenTelemetry SDK, X-Ray/Jaeger tracing, W3C TraceContext propagation, structured JSON logging with correlation IDs. Applied
R5 HIGH Security Agent-worker service identity undefined. Workers may bypass RLS with all-access service account. Defined scoped worker service account per instance with praesidiumInstanceId JWT claim, praesidiumAllAccess=false, 24h expiry with proactive refresh. Applied
R6 HIGH Performance Celery default visibility timeout (1hr) causes duplicate execution for long-running LangGraph workflows. Added 3-queue config: quick (300s), standard (3600s), long (7200s). acks_late=True on standard/long. Idempotency guards via checkpoint checks. Applied
R7 HIGH Architecture No graceful shutdown handling. Rolling updates drop WebSocket connections, abort SSE streams, kill in-flight tasks. Added per-pod SIGTERM handling table: Gateway (drain 30s), Worker (checkpoint + re-queue), qqq-api (Spring graceful), tool-runner (Job TTL), web (Nginx drain). Applied
R8 MEDIUM Data Model Denormalized agent counters (total_tasks_completed, total_tokens_used, total_cost_usd) will drift over time. Added stats reconciliation system job: runs every 6hr via Celery Beat, recomputes counters from source tables. Counters treated as cached aggregates. Applied
R9 MEDIUM Security No dependency scanning in CI/CD pipeline. Three language ecosystems (Java, Python, TypeScript) with extensive dependency trees. Added to Faber CI: pip audit, npm audit, Maven dependency-check, Trivy container scanning, Dependabot/Snyk. Fail on CRITICAL/HIGH CVEs. Applied
R10 MEDIUM Data Model team_member polymorphism has no DB-level enforcement. AGENT members could have human_profile rows (or vice versa). Added PostgreSQL trigger: After INSERT on agent/human_profile, verify matching member_type and no conflicting subtype row. DB-level, not app-level. Applied
R11 MEDIUM Performance Single task execution generates 10-20 REST calls to qqq API. At 50 agents, 500-1000 calls per minute. Added 3 batch/composite endpoints: /agent/{id}/hydration, /project/{id}/dashboard, /conversation/{id}/full. Uses qqq include parameter, no custom code. Applied
R12 MEDIUM Architecture Federation ConfigMap as peer registry has 1MB size limit and no cross-cluster support. ConfigMap acceptable for V1 single-cluster. Migration to DynamoDB/registry service deferred. Deferred
R13 MEDIUM Security Prompt injection via tool inputs not addressed. User content could trick agents into calling tools with malicious parameters. Added 5-layer defense: input sanitization (JSON Schema), output validation, sandboxed execution, CRITICAL tool guards, per-agent per-tool rate limits. Applied
R14 LOW Data Model Type tables lack metadata JSONB column for future extensibility. Added metadata JSONB DEFAULT '{}'::jsonb to the standard type table pattern for type-specific attributes. Applied
R15 LOW Data Model No task_dependency table for non-hierarchical blocking relationships between tasks. Deferred to V2. Parent-child via parent_task_id sufficient for V1. Deferred
R16 LOW Operations No data retention policy defined. Tables grow indefinitely. Added retention windows: messages 3yr, activity_log 7yr (HIPAA), job_execution 6mo. Monthly partitioning and archive strategy. Applied

Pass 2: Examples vs Technical Capabilities

29 gaps found across 5 example teams — cross-referencing every forged tool, integration, conversation flow, and memory pattern against the v2 design spec.

5 Blockers (2 resolved by scope decisions)

RESOLVED G11 — Federation Cost Aggregation

Decision (B18): V1 Corp Claw uses shared Google Sheets for cost data. cost_tracker built via Tool Forge in V1.5 reads from sheets. Federation-based auto-aggregation added in V2.

RESOLVED G15 — Federation Timing

Decision (B18): Federation is confirmed post-V1. Corp Claw and Me Health operate as standalone instances at V1 with manual data entry and shared dashboards. Full federation added in V2.

BLOCKER G13 — BambooHR Missing

BambooHR API is not in the integration catalog at any priority level. Mon Mothma depends on it for headcount, PTO, performance reviews, and org chart data. Corp Claw HR cannot function without HRIS data.

BLOCKER G23 — PHI in Patient Satisfaction

Me Health's patient_satisfaction tool may handle PHI (individual patient survey responses). Must work with de-identified data only. Requires PHI detection in memory extractor and LOCAL LLM routing.

BLOCKER G24 — PHI in Onboarding Tracker

Me Health's onboarding_tracker handles patient names, addresses, and health data. Standup references “patient in Ohio” — geographic + health info is PHI. Must use de-identified case numbers only.

Remaining 24 Gaps & Enhancements by Team

Marketing Team (WWE) — 3 gaps

IDSeverityDescription
G1GAPcompetitor_price_scraper references web scraping, not a standard integration. Keepa API is P1.
G2GAPsocial_scheduler depends on Buffer (P1) / Hootsuite (P2). Neither available at launch.
G3GAPZoho CRM is P1 but 4 of 5 teams depend on it for core operations. Should be P0.

Engineering Leadership Team (LOTR) — 5 gaps

IDSeverityDescription
G4GAPcode_executor needs per-tool dependency resolution beyond tool_version.dependencies JSONB.
G5GAPdb_migration_tool needs database connectivity, but sandbox blocks internal services.
G7GAPhelm_lint needs Helm binary and kubeconfig. Sandbox has no mechanism for cluster credentials.
G8GAPterraform_plan needs cloud IAM permissions. HIGH risk — human approval required.
G9GAPfigma_export depends on Figma API (P1). Needed early for frontend workflow.

Corp Claw (Star Wars) — 5 gaps

IDSeverityDescription
G12GAPaudit_checker needs internal service access. Should be PLATFORM category, not sandboxed CUSTOM.
G14GAPGoogle Slides API not in catalog. Workspace integration covers Docs/Sheets/Calendar but not Slides.
G6ENHANCEMENTtest_runner needs project source code in sandbox. Extend tool-runner to support git-cloned volumes.
G10ENHANCEMENTgcal_create_event adds agents as attendees, but AI agents have no Google accounts.
G30GAPNo example provides realistic cost estimates. Add cost modeling to each team’s documentation.

Product Dev (Avengers) — 5 gaps

IDSeverityDescription
G16GAPshipping_tracker depends on Flexport/Freightos API. Not in integration catalog.
G17GAPtranslate_api depends on DeepL API. Not in integration catalog.
G18GAPWeChat group via “Slack bridge” referenced but no WeChat integration exists.
G19ENHANCEMENTNo timezone-aware message scheduling. human_interaction lacks deliver_at field.
G29ENHANCEMENThuman_profile missing external system IDs for BambooHR, HubSpot, Figma, Buffer.

Me Health (Grey’s Anatomy) — 7 gaps

IDSeverityDescription
G20GAPmarket_analyzer has no specific external API. Needs NPI Registry, CMS data, or web search.
G21GAPemail_campaign depends on HubSpot (P1). CAN-SPAM compliance features needed at launch.
G22GAPpatient_satisfaction needs survey platform API (SurveyMonkey, Qualtrics, etc.).
G25GAPZoho CRM for healthcare sales may need BAA. Acknowledged in example but unresolved.
G26GAPNPS tracker may handle individual patient responses. Same PHI constraints as G23 if patient-level.
G27GAPMulti-agent standup turn-taking orchestrator needs validation. Custom implementation (~300 lines) may need LangGraph graph for complex meeting patterns.
G28GAPInfrastructure tools (code_executor, helm_lint, terraform_plan) need sandbox model extension.

Pass 3: Spec ↔ HTML Content Audit

28 items — ensuring the visual design document matches the authoritative spec. All items applied across 4 tabs.

✓

All 28 Items Applied

Audited against spec (2302 lines) + review resolutions (R1–R16)

Auth & Security Tab

1 item: Worker Service Identity — scoped service account JWTs, IAM policy, token refresh (R5)

Data Model Tab

5 items applied:

  • Instance scoping detail with root/child table lists (R2)
  • parent_conversation_id added to conversation schema
  • Polymorphism enforcement DB trigger (R10)
  • CACHE annotations on agent counter fields (R8)
  • metadata JSONB on type table pattern (R14)

Agent Runtime Tab

5 items applied:

  • Prompt injection defense — 5 layers (R13)
  • Data flow: Runtime → qqq paths
  • Celery queue configuration — 3 queues (R6)
  • Batch/composite qqq endpoints (R11)
  • Stats reconciliation system job (R8)

Architecture Tab

4 items applied:

  • Redis High Availability strategy (R3)
  • Log aggregation & distributed tracing (R4)
  • Distributed tracing with OpenTelemetry (R4)
  • Graceful shutdown per-pod SIGTERM table (R7)

Stats Updates

3 items: Entity tables 32 → 45, Type tables 30 → 56, Data domains 7 → 8 (Multi-LLM + Secrets + Business Ops additions)

Key Improvements Driven by Reviews

🛡

Disaster Recovery

RPO <1 hour • RTO <30 min

Automated RDS snapshots, Redis AOF persistence, S3 versioning, Liquibase rollback changesets, and quarterly tested restore procedures. Previously undocumented — now production-ready.

⚙

Redis High Availability

Multi-AZ • Separate Clusters

ElastiCache with automatic failover (<30s). Separate Queue cluster (Celery, AOF, write-optimized) and Cache cluster (pub/sub, session, allkeys-lru). Five defined fallback behaviors.

🔒

Prompt Injection Defense

5 Defense Layers

Input sanitization (JSON Schema + tag wrapping), output validation, sandboxed execution, CRITICAL tool guards with human approval, and per-agent per-tool rate limits (default 10/min).

🏥

HIPAA Safeguards

Me Health PHI Protection

Local LLM routing for PHI-adjacent work, PHI detection in memory extractor, de-identified case numbers only, and BAA tracking for integration vendors. Resolves G23/G24 blockers.

📈

Zoho CRM Elevated P1→P0

4 of 5 Teams Depend On It

Gap analysis revealed Marketing, Corp Claw, Product Dev, and Me Health all treat Zoho CRM as Day 1. Elevated from P1 to P0 integration priority to match actual business dependency.

⚡

Graceful Shutdown

Zero-Downtime Deploys

Per-pod SIGTERM handling: Gateway drains WS/SSE (30s), Worker checkpoints LangGraph and re-queues tasks (120s), qqq-api uses Spring graceful shutdown. No more dropped connections on deploy.

Technical Audit Remediation v1.8

7 audit findings from the independent technical review (Gemini CLI) — resolved by v1.8 spec updates, Implementation Fix Plan, and architecture mandates.

Resolved Audit Findings

Audit IDSeverityFindingResolutionStatus
A-002 HIGH Missing foundational schemas (llm_provider, llm_model, secret_ref) Full SQL definitions added to Data Model Domain 2. Schema includes provider config, model catalog, and encrypted secret references. RESOLVED
A-003 HIGH Timeline risk — extreme density in Weeks 4-5 for the engineering team Timeline extended to 8 weeks. Business Ops moved to dedicated Week 6, Week 7 added as stabilization overflow. Build re-sequenced per Steel Thread strategy. RESOLVED
A-004 HIGH Tool Runner git verification — git checkout ${GIT_SHA} allows branch-name injection SHA-only checkout mandated. Tool Runner enforces full 40-char SHA verification against approved main branch. No branch-name references permitted. RESOLVED
A-005 HIGH Shared hydration logic undefined between Java/qqq and Python/Workers AGENT_MANIFEST JSON schema defined (Day 3). Both Java and Python services validate against this shared contract to prevent logic drift. RESOLVED
A-006 MEDIUM Missing backend search endpoint for Command Palette /api/search composite endpoint defined in Gateway (Week 4). Uses pgvector for semantic search across all entities. RESOLVED
A-007 MEDIUM Worker-to-qqq authentication flow underspecified Service Account JWT acquisition and rotation lifecycle defined. Workers use scoped service accounts with praesidiumInstanceId claim, 24h expiry, proactive refresh. RESOLVED
A-008 MEDIUM Timeline inconsistency — Pre-Build phase missing from 6-week summary Total project duration updated to 8 weeks across all stakeholder-facing summaries. Pre-Build (Wk -2 to 0) + 6 build weeks + 1 stabilization week. RESOLVED
A-009 LOW Docker Compose YAML anchor — *authentik-env used but &authentik-env never defined YAML anchor definition added to Docker Compose configuration in implementation plan. Anchor defines shared Authentik environment variables. RESOLVED
A-011 MEDIUM Memory provenance — missing source links for “right to be forgotten” compliance source_type and source_id columns added to memory table. Enables provenance tracking and targeted deletion for compliance requests. RESOLVED

Outstanding Items

Deferred to V2 or Pending Spike

IDFindingTimeline
R12 Federation ConfigMap limit — peer registry needs migration to DynamoDB or registry service for multi-cluster V2
R15 Task dependency table — non-hierarchical blocking relationships between sibling tasks V2
G20 Turn-taking standup orchestrator needs proof-of-concept — validate that direct SDK turn-taking produces conversational back-and-forth Week 1 Spike

v1.11 Scope Changes v1.11

Architecture simplification: CrewAI removed, direct Anthropic SDK for standard execution, LangGraph scoped to durable workflows only, multi-LLM narrowed to Anthropic-only for V1. All capabilities preserved.

Key Changes

AreaBefore (v1.10)After (v1.11)
Agent Execution CrewAI crews for tasks/standups, Anthropic SDK for chat only Direct Anthropic SDK for 60–70% of execution (chat, tasks, standups). No framework overhead.
LangGraph Usage Default execution path alongside CrewAI Scoped to durable workflows requiring crash recovery or HITL approval gates only (~30–40% of execution)
Multi-LLM Support 6 provider client implementations (Anthropic, OpenAI, Ollama, Bedrock, Vertex, vLLM) Schema unchanged. V1 implements AnthropicClient only. LLMClient Protocol for future providers.
Architecture Decision CrewAI + LangGraph Hybrid Anthropic SDK + LangGraph (Scoped)
B16 Review CrewAI-specific quarterly review Framework-agnostic landscape review (Claude Agent SDK, OpenAI Agents SDK, LangGraph, CrewAI, Google ADK)

Rationale

The agent SDK landscape evolved significantly since the v1.10 design. Provider SDKs (Claude Agent SDK, OpenAI Agents SDK, Google ADK) now handle agent loops natively. Praesidium2's 117-table data model already provides agent definitions, tool registry, memory, and team orchestration — CrewAI became a redundant translation layer adding framework coupling risk without unique value.

What Was Removed

  • CrewAI dependency and all CrewAI-specific code
  • Agent-to-CrewAI translation layer in hydration
  • 5 of 6 LLM client implementations (deferred, not deleted from schema)

What Was Preserved

  • All 117 database tables and data model unchanged
  • LangGraph for durable workflows and HITL
  • Full multi-LLM schema (llm_provider, llm_model) for future expansion
  • Every execution pattern (chat, tasks, standups, scheduled jobs, Tool Forge)

Full analysis: docs/superpowers/specs/2026-04-16-architecture-simplification-analysis.md

Local Development Design

Local development uses Kubernetes on Docker Desktop + Tilt + Ollama for a fully local stack. Same Helm charts as production, deployed via Tilt to praesidium-local namespace.

AdditionDetails
TiltHot-reload orchestrator for local k8s — watches source, rebuilds images, redeploys pods automatically
OllamaLocal LLM inference (llama3.1:70b for reasoning, nomic-embed-text for embeddings) — replaces Anthropic API in local dev
Self-Hosted PathAir-gapped / on-premise deployment supported via same architecture (Ollama/vLLM + MinIO + k8s Secrets)
Configuration ProfilesThree profiles: cloud (Anthropic + AWS), local (Ollama + MinIO), hybrid (Anthropic + local infra)

Full spec: docs/superpowers/specs/2026-04-16-local-development-design.md

Glossary

Definitions for all terms, acronyms, systems, and concepts referenced throughout the Praesidium2 System Design. Use this as a reference guide for onboarding, design reviews, and cross-team communication.

🏗️

System & Platform Names

TermDefinition
Praesidium2The core AI agent platform enabling Greater Goods' Agentic AI Core Operating Model. Each business unit gets its own Praesidium2 instance.
Greater GoodsThe organization deploying Praesidium2 across all business units.
qqqThe internal data-layer framework providing generated REST APIs, schema migrations, RBAC, and audit logging for all entity tables.
Tool ForgeCollaborative tool-building platform where humans and agents co-create custom tools through an automated 6-step workflow.
Agent GatewayPython/FastAPI service that bridges the browser and React frontend to the backend agent runtime.
Agent WorkersBackend services that run direct SDK agent loops and LangGraph durable workflows.
Tool RunnerService that executes custom tools in isolated sandbox environments.
JarvisAI chat assistant embedded in Praesidium2 documents, capable of filing change requests and answering questions about the design.
Corp ClawInternal brand/product line managed by a Greater Goods business unit; used as a use-case example in the system design.
Me HealthInternal brand/product line managed by a Greater Goods business unit; used as a use-case example in the system design.
🤖

AI / ML Frameworks & Models

TermDefinition
LLMLarge Language Model — AI model trained on vast text data, used for reasoning, generation, and tool use (e.g., Claude, GPT-4).
CrewAIOpen-source Python framework for orchestrating teams ("crews") of agents with defined roles, delegation, and shared memory.
LangGraphFramework built on LangChain for building durable, stateful agent workflows as directed graphs with checkpointing and human-in-the-loop support.
MCPModel Context Protocol — standard for integrating tools directly into LLM context windows.
Claude OpusAnthropic's most capable model; used for complex agent reasoning tasks.
Claude SonnetAnthropic's balanced model; faster and cheaper than Opus, used for standard agent tasks.
Anthropic SDKClient library for calling Claude APIs from Python or TypeScript.
OpenAI SDKClient library for GPT-family models.
AWS BedrockAWS managed service for accessing foundation models (Claude, Llama, etc.) without managing infrastructure.
OllamaLocal LLM runner for self-hosted open-source models (e.g., Llama 3).
vLLMHigh-throughput open-source inference server for self-hosted large language models.
🔐

Security & Authentication

TermDefinition
AuthentikOpen-source Identity Provider (IdP) used for SSO, OAuth2/OIDC flows, and user provisioning in Praesidium2.
JWTJSON Web Token — signed token encoding user identity and claims, used for stateless authentication.
OAuth2Industry-standard protocol for delegated authorization.
OIDCOpenID Connect — authentication layer on top of OAuth2 that provides user identity information.
RBACRole-Based Access Control — restricting system access based on users' roles within an organization.
RLSRow-Level Security — PostgreSQL feature that filters query results at the database level based on user context.
RecordSecurityLockqqq's mechanism for enforcing instance isolation by injecting instance_id constraints into all queries automatically.
praesidiumInstanceIdCustom JWT claim identifying which Praesidium2 instance a user belongs to; used for data isolation.
praesidiumAllAccessCustom JWT claim that grants an instance administrator full access bypass (bypasses RLS/RecordSecurityLock).
Service accountNon-human identity (API key or token) used by services to authenticate with each other.
Secrets ManagerAWS service (or equivalent) for securely storing and retrieving credentials, API keys, and other sensitive values.
Secret_refA reference pointer to a credential stored in Secrets Manager; never the raw secret value itself.
IAM-style policiesJSON documents that define permissions; modeled after AWS IAM policy syntax.
Instance isolationSecurity boundary ensuring one Praesidium2 instance cannot access another instance's data.
⚙️

Agent Architecture & Concepts

TermDefinition
AgentAI-powered team member with persistent memory, tool access, defined skills, and evolving domain expertise.
Agent templateReusable blueprint defining an agent's role, default tools, and personality; instantiated to create agent instances.
Agent instanceA running, deployed agent created from a template and assigned to a specific Praesidium2 instance.
Agent hydrationLoading all agent state (memory, tools, config) from the database into memory at startup.
Agent skillA specific capability or area of expertise an agent possesses (e.g., "Jira project management", "Amazon listing optimization").
CrewA team of agents working together on a shared project or goal via orchestrated turn-taking.
RoleA defined function within a crew — e.g., Architect, Engineer, QA — shaping how an agent behaves and delegates.
DelegationAn agent assigning a sub-task to another agent (or human) within a crew.
MemoryAn agent's accumulated knowledge: short-term (conversation), long-term (persistent knowledge chunks), and episodic (past events).
Institutional knowledgeOrganizational learning (processes, decisions, context) accumulated and preserved by agents over time.
Personality traitsJSONB attributes stored per agent defining behavior defaults (e.g., verbosity, formality, escalation threshold).
Human-in-the-loopA workflow design pattern where execution pauses at defined points to require human review, decision, or approval.
EscalationAn agent raising an issue to a human when it cannot proceed without guidance or when a risk threshold is exceeded.
Escalation queueFIFO queue of pending escalations awaiting human review in the Praesidium2 dashboard.
Approval gateA mandatory pause in a workflow requiring human approval before continuing execution.
🔨

Tool Forge & Tool Concepts

TermDefinition
Tool Forge workflow6-step automated pipeline for creating new tools: Design → Scaffold → Implement → Test → Review → Publish.
Design nodeFirst forge step: generates a formal JSON specification from a natural-language description.
Scaffold nodeSecond forge step: creates the project directory structure and boilerplate from the spec.
Implement nodeThird forge step: an agent writes the tool's implementation code.
Test nodeFourth forge step: runs automated tests and validates the implementation.
Review nodeFifth forge step: human reviews the generated tool and either approves or requests changes.
Publish nodeSixth forge step: approved tool is versioned, git-tagged, and deployed to the tool catalog.
Tool specJSON document defining a tool's inputs, outputs, behavior, and risk level; the contract all tool versions must conform to.
Tool manifesttool_manifest.json file in each tool repository defining entry point, schema, and metadata.
Tool catalogRegistry of all available, approved tools that agents can be assigned to use.
Risk levelClassification of a tool's potential impact: LOW / MEDIUM / HIGH / CRITICAL; determines execution policy (auto-run vs. approval-required).
SandboxIsolated, ephemeral execution environment (Kubernetes pod) used for forge operations and tool execution to prevent unintended side effects.
Forge sessionStateful database record tracking the full lifecycle of a single tool-building workflow run.
Platform toolsBuilt-in system tools (e.g., create_task, update_task_status) available to all agents.
Integration toolsPre-built connectors for third-party services (Jira, Slack, Confluence, etc.).
Custom toolsUser-built tools created via the Forge; stored with FORGED status in the catalog.
MCP toolsTools integrated via the Model Context Protocol standard.
requires_approvalBoolean flag on a tool indicating that every execution requires explicit human approval before proceeding.
☁️

Infrastructure & Deployment

TermDefinition
Kubernetes (k8s)Open-source container orchestration system for automating deployment, scaling, and management of containerized applications.
EKSAmazon Elastic Kubernetes Service — AWS managed Kubernetes control plane.
PodSmallest deployable unit in Kubernetes; one or more containers sharing network and storage.
DaemonSetKubernetes resource that ensures a copy of a pod runs on every node (used for log collectors like Fluent Bit).
HPAHorizontal Pod Autoscaler — Kubernetes feature that automatically scales pod count based on CPU, memory, or custom metrics.
HelmKubernetes package manager; bundles Kubernetes manifests into reusable, versioned "charts".
ArgoCDGitOps continuous delivery tool for Kubernetes; automatically deploys from git repository state.
ConfigMapKubernetes resource for storing non-sensitive configuration as key-value pairs injected into pods.
ALBApplication Load Balancer — AWS layer-7 load balancer routing HTTP/HTTPS traffic to services.
DockerContainer runtime and image format used to package applications and their dependencies.
CI/CDContinuous Integration / Continuous Deployment — automated pipelines for building, testing, and releasing software.
Canary deploymentRolling out a new version to a small percentage of traffic before full release.
Blue-green deploymentRunning two identical production environments and switching traffic between them for zero-downtime releases.
HAHigh Availability — architecture designed to minimize downtime through redundancy and failover.
Queue-depth scalingAutoscaling workers based on the number of pending items in the task queue.
Warm poolPre-initialized containers kept ready to handle requests immediately, avoiding cold-start latency.
Cold startLatency experienced when a new container must initialize before handling its first request.
SIGTERMOperating system termination signal sent to a process; triggers graceful shutdown procedures.
preStopKubernetes lifecycle hook that runs a command before a container receives SIGTERM.
Fluent BitLightweight log processor and forwarder that ships container logs to CloudWatch.
🗄️

Databases & Storage

TermDefinition
PostgreSQLOpen-source relational database; Praesidium2's primary data store for all entities.
RDS PostgreSQLAWS managed PostgreSQL — handles backups, patching, and replication automatically.
pgvectorPostgreSQL extension enabling vector similarity search; used for semantic memory retrieval.
RedisIn-memory data structure store; used as Celery broker, session cache, pub/sub bus, and rate-limit counters.
S3Amazon Simple Storage Service — object storage for artifacts, tool source code, and large files.
MinIOSelf-hosted S3-compatible object storage for local/development environments.
JSONBPostgreSQL binary JSON data type; supports indexing and querying of semi-structured data.
UUIDUniversally Unique Identifier — 128-bit value used as primary keys throughout the schema.
LiquibaseDatabase migration tool that tracks and applies schema changes in a controlled, versioned manner.
ORMObject-Relational Mapping — library layer translating between database rows and programming objects.
CRUDCreate, Read, Update, Delete — the four basic database operations.
Audit loggingAutomatic recording of all data modifications (who changed what, when) for compliance and debugging.
Connection poolPre-allocated set of database connections reused across requests to reduce overhead.
⚡

Async Processing & Messaging

TermDefinition
CeleryDistributed Python task queue for running background jobs asynchronously.
Celery BeatCelery's built-in scheduler for recurring (cron-style) tasks.
Task queueDurable queue holding background jobs awaiting execution by workers.
SSEServer-Sent Events — HTTP-based protocol for pushing real-time updates from server to browser (unidirectional).
WebSocketProtocol for full-duplex, bidirectional communication between browser and server.
Pub/subPublish/Subscribe messaging pattern — publishers emit events to channels; subscribers receive them.
Redis AOFAppend-Only File persistence mode; ensures Redis task data survives restarts.
Task durabilityGuarantee that queued tasks are not lost if Redis restarts (enabled via AOF + RDB persistence).
WorkflowA LangGraph state machine defining the ordered steps an agent or crew takes to complete a job.
CheckpointDurable snapshot of workflow state saved mid-execution so it can resume after failure or interruption.
State machineA system with a finite set of defined states and explicit transitions between them (the basis of LangGraph).
📊

Observability & Monitoring

TermDefinition
OpenTelemetryOpen-source observability framework for collecting distributed traces, metrics, and logs.
SpanA single timed operation within a distributed trace (e.g., one database query or one API call).
Correlation IDUnique identifier attached to a request that is propagated across all services, enabling full trace reconstruction.
X-Correlation-IDHTTP request header carrying the Correlation ID between services.
CloudWatchAWS monitoring and observability service for logs, metrics, and alarms.
CloudWatch MetricsNumerical time-series data points (e.g., CPU utilization, request latency) stored and visualized in CloudWatch.
Alert / AlarmAutomated notification triggered when a metric crosses a defined threshold.
TracingRecording the path and timing of a request as it flows through multiple services.
TelemetryAutomated collection and transmission of operational data (logs, metrics, traces) from running services.
Burn rateDaily LLM API spending rate used to project monthly costs and trigger budget alerts.
MTDMonth-To-Date — cost or usage measured from the start of the current calendar month.
Token trackingMonitoring the number of input/output tokens consumed per LLM API call for cost attribution.
🖥️

Frontend Technologies

TermDefinition
React 19JavaScript library for building user interfaces with a component model and virtual DOM.
ViteFast frontend build tool and dev server with native ES module support.
Tailwind CSSUtility-first CSS framework for styling directly in HTML markup.
shadcn/uiComposable React component library built on Radix UI and Tailwind CSS.
TanStack QueryAsync state management library for data fetching, caching, and synchronization in React.
TanStack RouterType-safe client-side routing library for React.
RESTRepresentational State Transfer — architectural style for HTTP APIs using standard verbs (GET, POST, PUT, DELETE).
FastAPIHigh-performance Python web framework for building REST APIs with automatic OpenAPI documentation.
Design systemShared library of UI components, tokens, and patterns ensuring visual consistency across the application.
🔌

External Integrations & Services

TermDefinition
JiraAtlassian issue tracking and project management tool; Praesidium2 agents can read/write tickets.
ConfluenceAtlassian wiki/documentation platform; agents can read pages and publish content.
SlackTeam messaging platform; agents communicate with humans and receive mentions/commands via Slack.
GitHubGit hosting and collaboration platform; used for code repositories and tool version storage.
Google WorkspaceSuite including Gmail, Docs, Sheets, and Drive; agents can read/write documents and emails.
Zoho CRMCustomer relationship management platform; agents can query and update CRM records.
Amazon SP-APISelling Partner API — Amazon's REST API for managing marketplace listings, orders, and inventory.
Advertising APIAmazon's API for managing sponsored ads, campaigns, and keyword bids.
BambooHRHuman resources management system; integrated for HR data access.
FlexportFreight logistics platform; integrated for shipping and supply chain visibility.
TwilioCloud communications API providing SMS, voice, and WhatsApp messaging capabilities.
FigmaCollaborative interface design and prototyping tool.
Helium 10Amazon seller intelligence platform; referenced as a benchmark for keyword research and listing tools.
AhrefsSEO and content analytics tool; referenced as integration for competitor analysis features.
📐

Data Model Concepts

TermDefinition
Entity tableA primary database table representing a distinct business object (e.g., agents, tasks, tools).
Type tableLookup/enumeration table with static reference data (e.g., task statuses, priority levels).
Root entityAn entity table with a direct instance_id column; the anchor for instance isolation.
Derived entityA table linked to an instance indirectly via a foreign key chain back to a root entity.
PKPrimary Key — the unique identifier column for a database row.
FKForeign Key — a column referencing the PK of another table, enforcing relational integrity.
InstanceAn isolated deployment of Praesidium2 for a single business unit; all data is scoped to an instance.
Knowledge chunkA granular, embedable unit of stored knowledge in agent memory (e.g., a paragraph, a fact, a decision).
ArtifactA file or document output produced during task execution (e.g., a report, a generated script).
Integration configStored credentials and settings for connecting to an external service.
PolymorphicA design pattern where a single table models multiple subtypes using a discriminator column (e.g., member_type: AGENT or HUMAN).
Audit trailChronological record of all data changes, including who made them and when.
📋

Project & Task Management

TermDefinition
ProjectOrganizational container grouping related tasks, milestones, and team members.
MilestoneA named marker within a project tracking a significant delivery or deadline.
TaskA unit of work assigned to an agent or human; has status, priority, and optionally subtasks.
SubtaskA child task nested under a parent task for finer-grained work tracking.
SprintA time-boxed iteration (typically 2 weeks) containing a planned set of tasks.
Daily standupShort recurring meeting for team synchronization; facilitated by an agent in Praesidium2.
Sprint planningMeeting at the start of a sprint to define the work to be completed.
Sprint reviewEnd-of-sprint meeting to demonstrate completed work.
Sprint retroRetrospective meeting to discuss process improvements after a sprint.
Action itemA task created directly from a meeting discussion or decision.
Cost centerLogical grouping for tracking and attributing LLM API spend to a department, project, or agent.
BudgetA defined spending limit for an agent, project, or cost center.
🛡️

Resilience Patterns & Operations

TermDefinition
Circuit breakerPattern that stops calling a failing service after a threshold of errors, allowing recovery time.
Retry logicAutomatic re-attempt of a failed operation, typically with exponential backoff.
FallbackAlternative behavior triggered when the primary path fails (e.g., using a cheaper model when the primary is unavailable).
Graceful degradationSystem continues operating with reduced functionality when a subsystem is unavailable.
Graceful shutdownProcess of finishing in-flight requests and releasing resources cleanly before a container terminates.
Rate limitingThrottling the number of requests a client can make in a time window.
RollbackReverting a deployment or database migration to a previous known-good state.
Replication lagDelay between a write on the primary database and its appearance on read replicas.
HIPAAHealth Insurance Portability and Accountability Act — US federal law requiring protection of health information; relevant to the Me Health business unit.
Compliance trackingMonitoring adherence to regulatory requirements and internal policies.
Dev / Staging / ProductionThe three deployment environments: local development, pre-production testing, and live customer-facing.
🔤

General Acronyms Quick Reference

AcronymStands For
AIArtificial Intelligence
APIApplication Programming Interface
ARNAmazon Resource Name
ALBApplication Load Balancer
AWSAmazon Web Services
CI/CDContinuous Integration / Continuous Deployment
CRMCustomer Relationship Management
CRUDCreate, Read, Update, Delete
AcronymStands For
EKSElastic Kubernetes Service
FKForeign Key
HAHigh Availability
HIPAAHealth Insurance Portability and Accountability Act
HPAHorizontal Pod Autoscaler
HTTPHypertext Transfer Protocol
IAMIdentity and Access Management
IdPIdentity Provider
AcronymStands For
JWTJSON Web Token
LLMLarge Language Model
MCPModel Context Protocol
MTDMonth-To-Date
OIDCOpenID Connect
PKPrimary Key
RBACRole-Based Access Control
RLSRow-Level Security
RESTRepresentational State Transfer
SSEServer-Sent Events
UUIDUniversally Unique Identifier