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.
Core Principles
Agents as Employees — Memory, skills, evolving expertise, personality, daily standups
Tools as First-Class Entities — Versioned, tested, git-backed, risk-leveled capabilities
Type Tables for All Enums — 59 FK-referenced lookup tables. No magic strings.
qqq as Data Layer — Generated REST APIs, Liquibase migrations, RBAC, audit logging
Authentik for Auth — IAM-style policies, row-level security, per-instance isolation
Humans are First-Class — Assignable work, reachable via integrations, same UI components
Technology Choices
Agent Runtime (Python)
Anthropic SDK LangGraph FastAPI Celery Anthropic SDKData & API Layer (Java)
qqq Framework Liquibase PostgreSQL pgvectorFrontend (TypeScript)
React 19 Vite Tailwind CSS shadcn/ui TanStack Query TanStack RouterInfrastructure
Kubernetes (EKS) Helm ArgoCD Redis S3 / MinIO AuthentikSystem Stack
Three distinct layers, each with its own language and responsibilities.
PRAESIDIUM2 (React SPA)
Dashboards, Chat, Projects, Meetings (Forge: V1.5)
AGENT RUNTIME (Python)
Direct Anthropic SDK + LangGraph (Scoped)
Gateway (FastAPI) + Workers (Celery)
DATA & INFRASTRUCTURE
qqq (Java) + PostgreSQL + Redis + S3
Authentik + Secrets Manager + k8s
Architecture Decision: Anthropic SDK + LangGraph (Scoped)
APPROVEDSelected 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 GapThe 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
| Quarter | Review Window | Focus Areas | Output |
|---|---|---|---|
| Q1 | First week of January | Claude Agent SDK evolution, Anthropic SDK changes, new agent loop patterns | Go/no-go decision document |
| Q2 | First week of April | OpenAI Agents SDK, Google ADK updates, multi-agent orchestration patterns | Go/no-go decision document |
| Q3 | First week of July | LangGraph releases, CrewAI Flows/Enterprise, durable execution improvements | Go/no-go decision document |
| Q4 | First week of October | Annual landscape review, pricing changes, competitive analysis across all frameworks | Annual strategy memo |
Evaluation Criteria
Evaluate whether any framework offers capabilities that outperform Praesidium2's direct-SDK approach. Adopt vs. Maintain decision for each:
| Capability | Our Implementation | Adopt-If Threshold |
|---|---|---|
| Agent Loop / Orchestration | Direct Anthropic SDK with custom tool loop | Framework provides agent loop with better error recovery, tracing, or tool handling than our ~50-line implementation |
| Multi-Agent Coordination | Custom turn-taking orchestrator for standups/huddles | Framework ships structured multi-agent conversations with turn management that reduces our ~300-line implementation |
| Durable Execution | LangGraph checkpointing + PostgresSaver | Alternative framework matches LangGraph's crash recovery + HITL with simpler dependency footprint |
| Tool Registry | qqq-backed tool + agent_tool_assignment tables | Framework supports tenant-isolated tool registry with risk levels, versioning, and sandbox execution |
| Memory / Knowledge | pgvector embeddings, episodic/semantic memory tables | Framework 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 Architecture
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.
Service Topology
Browser — React/TypeScript SPA
Project dashboards · Agent chat · Team views · Tool forge · Standup viewer
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
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
| Component | Local Dev (Docker Desktop k8s + Tilt) | AWS (EKS) |
|---|---|---|
| Database | PostgreSQL pod + pgvector | RDS PostgreSQL + pgvector |
| Object Storage | MinIO pod | S3 |
| Cache/Queue | Redis pod | ElastiCache Redis |
| LLM Provider | Ollama pod (local models) | Anthropic API |
| qqq API | Pod (Java, Tilt hot-reload) | EKS pod behind ALB |
| Agent Gateway | Pod (Python/FastAPI, Tilt hot-reload) | EKS pod behind ALB |
| Agent Workers | Pod(s) (Python/Celery, Tilt hot-reload) | EKS pods — HPA autoscaled |
| Frontend | Vite dev server or Nginx pod | CloudFront + S3 |
| Identity | Authentik pod | Authentik on EKS |
| Secrets | k8s Secrets | AWS Secrets Manager |
| Tracing | Jaeger pod | Datadog APM |
| Dev Tooling | Tilt (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
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 HARedis 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.
| Configuration | Production (AWS) | Local Dev |
|---|---|---|
| Topology | ElastiCache Multi-AZ with automatic failover (<30s) | Single Redis container |
| Persistence | AOF (appendfsync everysec) on queue cluster | None |
| Clusters | 2 separate clusters (Queue + Cache) | 1 shared instance |
| Monitoring | CloudWatch: memory, eviction rate, replication lag. Alert >80% memory. | N/A |
Fallback When Redis Completely Unavailable
Log Aggregation
DAY-1 REQUIREMENTCentralized logging across all 5 services. Debugging distributed issues is impractical without it.
| Environment | Log Backend | Configuration |
|---|---|---|
| AWS (EKS) | CloudWatch Logs (Fluent Bit DaemonSet) | Log groups per service: /praesidium/qqq-api, /praesidium/gateway, /praesidium/worker, /praesidium/tool-runner, /praesidium/web |
| Local Dev | Loki + 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
OPENTELEMETRYOpenTelemetry 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 HANDLINGEvery service handles SIGTERM cleanly to avoid dropped connections and corrupted state during rolling updates.
| Pod | SIGTERM Behavior | Grace Period | preStop |
|---|---|---|---|
| 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 SCALEOperational 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 declarationcookiecutter-praesidium-agent — New agent template with system prompt, skill assignments, team membershipTemplates 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.mddocs/adr/0002-qqq-as-data-layer.mddocs/adr/NNNN-template.mdNew 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 MACHINEDistributed 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:
risk_level = 'CRITICAL' (e.g., git_merge, jira_transition, api_write) triggers an interruptinterrupt(), which serializes the current graph state (variables, history, plan)langgraph_checkpoints table (PostgreSQL)AWAITING_APPROVALHITL Lifecycle Flow
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:
POST /api/task/{id}/approve sent to Gatewayaction_payload_hash unchangedtask_approval.status to APPROVED, dispatches Resume Event to Redis with LangGraph thread_idlanggraph_checkpointsReject 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.9When 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.
interrupt{
"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"
}
interrupt, the Chat UI replaces the ThinkingIndicator with an Approval Required card showing the action summary, diff preview, and Approve/Reject buttons.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 FATIGUEOperational 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)
| Level | Name | Behavior |
|---|---|---|
| 1 | Strict HITL | Every CRITICAL action requires human approval (v1 default) |
| 2 | Notify-only for LOW | LOW-risk auto-executes with Slack notification; MEDIUM+ still requires approval |
| 3 | Fingerprint Match | Auto-approve if action_payload_hash matches a previously APPROVED action for the same Agent + Tool combination |
| 4 | Budget-Scoped | Auto-approve within pre-defined budget_usd ceiling per agent per day |
| 5 | Full Autonomy | Auto-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 & Authorization
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
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-CRITICALAgent-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
praesidiumInstanceId claim → qqq RLS scopes all queries to the instancepraesidiumAllAccess is false — workers do NOT bypass RLSToken Refresh Strategy
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 LIFECYCLEService 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
praesidiumInstanceIdSecurity Guarantees
praesidiumAllAccess is false — workers never bypass RLSPer-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.
Data Model
Domain 1: Agent Identity & Security
Templates, agents, tool assignments, LLM providers/models, secret references, audit access log
agent_skill relocated to Domain 9 (Skill System) in v1.12
Domain 1b: Team Identity
Polymorphic team members (agent or human), human profiles, agent-to-human interaction logs
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
Tool registry, versions, git repos, integration configs
Domain 3: Projects & Work
Projects, members, milestones, tasks, task comments, task approvals
Domain 4: Conversations & Meetings
Conversations, participants, messages, scheduled meetings
Domain 5: Memory & Knowledge
Agent memories with embeddings, knowledge docs, search chunks
Domain 6: Operations & Observability
Scheduled jobs, executions, escalations, artifacts, activity log, heartbeat, LangGraph checkpoints
Domain 7: Secrets
Secret references for hierarchical credential management
+ 2 new type tables: secret_scope_type, secret_type
Domain 8: Business Operations
Approvals, KPIs, ROI reports, action logs, feedback, quality scores
Domain 9: Skill System & Agent Composition
Reusable skills, MCP servers, published agent profiles, fork workflow, cross-instance catalog v1.12
+ 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.
| Column | Type | Purpose |
|---|---|---|
id | INT GENERATED ALWAYS | Primary key |
name | VARCHAR(50) UNIQUE | Code key: IN_PROGRESS |
label | VARCHAR(100) | Display: "In Progress" |
description | VARCHAR(500) | Tooltip / help text |
icon | VARCHAR(50) | Optional icon identifier |
color | VARCHAR(7) | Optional hex color |
sort_order | INT DEFAULT 0 | Display ordering |
is_active | BOOLEAN DEFAULT true | Soft-disable |
is_system | BOOLEAN DEFAULT false | Seed data, can't delete |
metadata | JSONB DEFAULT '{}' | Type-specific attributes (e.g., task_status: {is_terminal: true}) |
created_at | TIMESTAMPTZ | Creation 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)
SECURITYEvery 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
RecordSecurityLock adds instance_id to every root entity table at schema generation timepraesidiumInstanceIdinstance_id — no application code touches this column directlymhCompanyIdRoot Tables (Direct instance_id)
qqq applies RecordSecurityLock directly to these tables:
Child Tables (Join-Based Scoping)
qqq traces the FK chain to a root table's instance_id:
agent → team_member.instance_idtask → project.instance_idmessage → conversation.project_id → project.instance_idmemory → team_member.instance_idmilestone → project.instance_idconversation → project.instance_idjob_execution → scheduled_job.agent_id → team_member.instance_idDomain 1: Agent Identity & Security (7 tables) agent_skill moved to D9
agent_template — "The job description"
agent — "The employee"
agent_tool_assignment — "What tools this agent can use"
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.
llm_provider — "LLM vendor catalog"
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"
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)"
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"
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"
human_profile — "Human-specific details"
Polymorphism Enforcement (DB Trigger)
DATABASE-LEVELA 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"
Domain 2: Tools & Capabilities (4 tables + secret_ref)
tool — "A capability an agent can invoke"
tool_version — "Immutable snapshot of tool code"
tool_repo — "Git repository backing custom tools"
integration_config — "External system credentials"
secret_ref — "Hierarchical credential references"
Domain 3: Projects & Work (6 tables)
project
project_member — "Agent or human on a project"
milestone
task — "A unit of work"
task_approval — "Tamper-proof HITL records" v1.9
task_comment
Domain 4: Conversations & Meetings (4 tables)
conversation — "Any interaction thread"
conversation_participant
message — "A single turn"
scheduled_meeting — "Recurring meeting definition"
Domain 5: Memory & Knowledge (3 tables)
memory — "Things an agent knows/remembers"
knowledge_document — "Uploaded/indexed docs for RAG"
knowledge_chunk — "Searchable piece of a document"
Memory Hygiene
v1.10 DESIGN NOTE — V1.5 SCOPEOperational 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
| Tier | Name | Storage | Lifecycle |
|---|---|---|---|
| 1 | Ephemeral | In-context window (last 20 messages) | Evicted when conversation window scrolls; never persisted beyond message table |
| 2 | Vector | memory table with pgvector embeddings | Extracted from conversations/tasks; decays via recency_weight; merged by Janitor job |
| 3 | Consolidated | Knowledge 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:
recency_weight by 5% for all non-starred memories older than 7 dayssource_ref_id)recency_weight < 0.05 AND importance < 0.3 AND not starredNote: 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
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"
{ "pr_title": "[Praesidium-Rollback] ...", "target_branch": "...", "original_commit": "...", "task_ref": "..." }escalation
artifact — "Files produced by agents"
activity_log — "Immutable audit trail"
langgraph_checkpoints — "Agent state persistence" v1.9
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
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
approval_policy
kpi_baseline
kpi_measurement
agent_action_log
rollback_record
output_feedback
agent_quality_score
autonomy_level
team_roi_report
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.
skill_definition — "Reusable procedural knowledge (SOP)"
skill_version — "Immutable snapshot of a skill"
skill_tool_requirement — "Tools a skill version needs"
skill_mcp_requirement — "MCP servers a skill version needs"
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
agent_skill_proficiency — "How well an agent performs each skill"
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 — "A configured MCP server connection"
agent_mcp_assignment — "Which MCP servers an agent connects to"
published_agent_profile — "Company-wide shareable agent template"
published_agent_profile_version — "Immutable profile snapshot"
profile_skill_assignment — "Skills included in a published profile"
profile_mcp_configuration — "MCP server configs in a profile"
profile_tool_assignment — "Direct (freestyle) tools in a profile"
profile_fork_record — "Tracks agent forks from profiles"
Cross-Instance Scoping Rules
PublishScopeSecurityLockTables using publish-based visibility (skill_definition, published_agent_profile) use a custom PublishScopeSecurityLock instead of the standard RecordSecurityLock.
| Status | Creating Instance | Other Instances |
|---|---|---|
| DRAFT | Full CRUD | Not visible |
| PUBLISHED | Full CRUD | Read-only |
| DEPRECATED | Full CRUD | Read-only (with warning) |
| ARCHIVED | Read-only (admin) | Not visible |
Instance Scoping by Table
skill_definition, published_agent_profileskill_version, skill_tool_requirement, skill_mcp_requirement, published_agent_profile_version, profile_skill_assignment, profile_mcp_configuration, profile_tool_assignmentmcp_serveragent_skill, agent_skill_proficiency, agent_mcp_assignment, profile_fork_recordDeprecation Cascade
agent_skill records across instances are flagged via system notificationpinned_version_id set continue normally (immutable snapshot)current_version receive a system warning in next hydrationSkill Hydration & Conflict Resolution
When an agent is hydrated for execution, the runtime resolves each agent_skill to a concrete skill_version:
pinned_version_id is set → use that specific version (immutable)pinned_version_id is NULL → resolve via skill_definition.current_versionskill_version.instructions + guardrails into the agent's system promptskill_tool_requirement tools are available to the agentskill_mcp_requirement MCP servers are connected and healthyFork Workflow (End-to-End)
When a Super Operator clicks "Fork" on a published agent profile:
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 serveragent_tool_assignment records for each selected toolprofile_fork_record (source_profile_id, source_version_id, target_agent_id)Key Relationships
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
| Type Table | Used By | Seed Values |
|---|---|---|
member_type | team_member.member_type | AGENT, HUMAN |
member_status | team_member.status | ACTIVE, AWAY, OFFLINE, SUSPENDED |
agent_category | agent_template.category | ENGINEERING, HR, OPS, FINANCE, MARKETING, PRODUCT, SUPPORT, CUSTOM |
execution_status | agent.execution_status | IDLE, EXECUTING, QUEUED, ERROR |
tool_category | tool.category | PLATFORM, INTEGRATION, CUSTOM, MCP |
tool_source_type | tool.source_type | BUILTIN, FORGED, IMPORTED |
risk_level | tool.risk_level | LOW, MEDIUM, HIGH, CRITICAL |
test_status | tool_version.test_status | PENDING, RUNNING, PASSED, FAILED |
programming_language | tool_repo.language | PYTHON, TYPESCRIPT, JAVA, GO, SHELL |
sync_status | tool_repo, task | SYNCED, PENDING, SYNCING, ERROR |
integration_type | integration_config.type | ZOHO_CRM, JIRA, CONFLUENCE, SLACK, GITHUB, GOOGLE_WORKSPACE, CUSTOM_API |
auth_type | integration_config.auth_type | API_KEY, OAUTH2, BASIC, BEARER, SERVICE_ACCOUNT |
health_status | integration_config.health | HEALTHY, DEGRADED, DOWN, UNKNOWN |
project_type | project.type | SHORT_TERM, ONGOING, SUPPORT, INITIATIVE |
project_status | project.status | PLANNING, ACTIVE, ON_HOLD, COMPLETED, ARCHIVED |
project_health | project.health | ON_TRACK, AT_RISK, BEHIND, BLOCKED |
priority_level | project, task, escalation | LOW, MEDIUM, HIGH, CRITICAL |
project_role | project_member.role | LEAD, MEMBER, REVIEWER, OBSERVER |
milestone_status | milestone.status | NOT_STARTED, IN_PROGRESS, COMPLETED, BLOCKED |
task_type | task.type | TASK, BUG, STORY, SPIKE, REVIEW |
task_status | task.status | OPEN, APPROVED, IN_PROGRESS, IN_REVIEW, DONE, BLOCKED, DISMISSED |
author_role | task_comment, activity_log | AGENT, HUMAN, SYSTEM |
conversation_type | conversation.type | CHAT, STANDUP, HUDDLE, TASK_EXEC, FORGE, REVIEW |
conversation_status | conversation.status | ACTIVE, PAUSED, COMPLETED, FAILED |
participant_role | conversation_participant | FACILITATOR, PARTICIPANT, OBSERVER, SCRIBE |
message_role | message.role | USER, ASSISTANT, SYSTEM, TOOL_RESULT |
content_type | message.content_type | TEXT, MARKDOWN, JSON, IMAGE_REF, CODE |
meeting_type | scheduled_meeting.type | STANDUP, HUDDLE, RETROSPECTIVE, PLANNING, REVIEW |
memory_type | memory.type | FACT, PREFERENCE, LESSON_LEARNED, ENTITY, DECISION, PROCEDURE |
memory_source | memory.source | CONVERSATION, TASK, MEETING, MANUAL, SYSTEM |
document_source_type | knowledge_document | UPLOAD, CONFLUENCE, URL, GIT_REPO |
index_status | knowledge_document | PENDING, INDEXING, INDEXED, FAILED |
job_status | scheduled_job.status | ACTIVE, PAUSED, COMPLETED, FAILED |
job_execution_status | job_execution.status | RUNNING, SUCCESS, FAILED, TIMEOUT, CANCELLED |
trigger_type | job_execution | CRON, MANUAL, RETRY, EVENT |
escalation_status | escalation.status | OPEN, ACKNOWLEDGED, RESOLVED, DISMISSED |
artifact_type | artifact.type | FILE, REPORT, CODE, IMAGE, DATA |
interaction_channel | human_interaction | SLACK, JIRA_COMMENT, JIRA_ASSIGN, CONFLUENCE, EMAIL |
interaction_type | human_interaction | QUESTION, TASK_ASSIGN, STATUS_UPDATE, ESCALATION, REVIEW_REQUEST, INFO_REQUEST |
interaction_status | human_interaction | SENT, DELIVERED, SEEN, RESPONDED, EXPIRED, FAILED |
schedule_status | scheduled_meeting | ACTIVE, PAUSED, ARCHIVED |
secret_scope_type | secret_ref.scope_type | INSTANCE, PROJECT, TOOL, AGENT |
secret_type | secret_ref.secret_type | API_KEY, OAUTH2_TOKEN, SSH_KEY, WEBHOOK_SECRET, DATABASE_URL |
llm_provider_type | llm_provider.type | CLOUD_API, LOCAL, SELF_HOSTED, BEDROCK, VERTEX |
llm_capability_tier | llm_model.capability_tier | FLAGSHIP, STANDARD, FAST, ECONOMY |
autonomy_status | autonomy_level.status | REQUESTED, GRANTED, REVOKED, SUSPENDED |
feedback_type | output_feedback.type | UX, ACCURACY, SPEED, TONE, TOOL_USE |
skill_category v1.12 | skill_definition.category | ENGINEERING, OPERATIONS, FINANCE, HR, MARKETING, PRODUCT, SUPPORT, ADMINISTRATION, ANALYTICS, CUSTOM |
mcp_server_type v1.12 | mcp_server.server_type | STDIO, HTTP, SSE |
skill_publish_status v1.12 | skill_definition.publish_status, published_agent_profile.publish_status | DRAFT, PUBLISHED, DEPRECATED, ARCHIVED |
Agent Runtime
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
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
Thread IDs map to conversation.id. Checkpoint state lives in PostgreSQL alongside qqq's schema.
Execution Patterns
| Trigger | Pattern | Framework | Details |
|---|---|---|---|
| 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 |
Memory System Flow
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 Level | Behavior | Example |
|---|---|---|
| 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-DEPTHAgent-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 PATTERNSAll state changes from the agent runtime go through qqq REST APIs. These are the API call patterns for each execution type:
| Trigger | qqq 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 QUEUESTask-type-specific queues with tuned visibility timeouts to prevent duplicate execution of long-running tasks:
| Queue | Visibility Timeout | Task Types | Acks 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
PERFORMANCETo 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.
| Endpoint | Returns | Replaces |
|---|---|---|
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 ENDPOINTTo 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}Authentication
instance_id — RLS enforcedAGENT_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-CRITICALSecurity 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.
Pipeline Rules
- Storage: Keys stored in AWS Secrets Manager only
- Reference: The
secret_reftable 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 JOBThe 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
quick (runs fast, read-heavy)Reconciliation Logic
total_tasks_completed = COUNT(*) from task WHERE status = DONEtotal_tokens_used = SUM(tokens) from messagetotal_cost_usd = SUM(cost) from message + activity_logCounters 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 TYPESEach Praesidium2 namespace runs 5 pod types. This table shows the infrastructure footprint.
| Pod | Image | Language | Replicas | HPA Metric | Resources |
|---|---|---|---|---|---|
| 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).
Worker Responsibilities
Runs in the agent-worker pod (Celery, concurrency 4 per pod).
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 APIUnified 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}
| Parameter | Type | Description |
|---|---|---|
q | string (required) | Natural language search query |
scope | enum (optional) | documents | agents | tasks | all (default: all) |
limit | int (optional) | Max results to return (default: 20, max: 100) |
How It Works
text-embedding-3-smallknowledge_chunk.embedding, memory.embeddingagent.label, task.title, project.labelrelevance_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 Level | CPU | Memory | Timeout |
|---|---|---|---|
| LOW | 0.5 CPU | 512Mi | 30s |
| MEDIUM | 1.0 CPU | 1Gi | 60s |
| HIGH | 1.0 CPU | 2Gi | 120s |
| CRITICAL | 2.0 CPU | 4Gi | 300s |
Scaling Strategy
| Pod | Min | Max | HPA Metric | Scale Trigger | Scale-Down Delay |
|---|---|---|---|---|---|
| qqq-api | 2 | 6 | CPU utilization | 70% CPU avg | 5 min |
| agent-gateway | 2 | 8 | Active WS connections + request rate | 500 connections or 100 req/s per pod | 10 min (WS stateful) |
| agent-worker | 3 | 10 | Redis queue depth (Prometheus) | Queue depth > 5 per pod | 15 min (in-flight tasks) |
| tool-runner (warm) | 2 | 8 | Request rate | 10 req/s per pod | 5 min |
| web | 2 | 4 | 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
| Setting | Location | Default |
|---|---|---|
| Instance theme | instance.config.personality_theme | professional |
| Per-agent override | agent_template.personality_traits | Inherits instance theme |
| External context mode | tool_definition.context_mode | Always professional for external tools |
Available Modes
| Mode | Example | Use Case |
|---|---|---|
| Professional | Standard business tone | Default; external-facing |
| WWE | Marketing team personas | Internal team engagement |
| LOTR | Engineering team personas | Internal team engagement |
| Grey's Anatomy | Me Health team personas | Internal team engagement |
| Star Wars | Corp Claw team personas | Internal team engagement |
| Custom | Team-defined themes | New 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 Architecture
Full Tech Stack
| Layer | Choice | Role |
|---|---|---|
| Framework | React 19 + Vite | Component rendering + fast bundling |
| Language | TypeScript (strict) | Type safety across all modules |
| Styling | Tailwind CSS + shadcn/ui | Utility-first CSS + composable components |
| State / Data | TanStack Query + Zustand | Server state cache + local UI state |
| Routing | TanStack Router | File-based, fully type-safe routes |
| Real-time | WebSocket + SSE | Push events + chat streaming |
| Charts | Recharts | Data visualization |
| Testing | Vitest + Testing Library | Unit + 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 projects | GET/POST /qqq/v1/project |
| Read/write tasks | GET/POST /qqq/v1/task |
| Read/write agents | GET/POST /qqq/v1/agent |
| Settings & config | GET/PATCH /qqq/v1/settings |
Agent Gateway — AI Actions
Base: /gateway/v1/
| Chat with agent | POST /gateway/v1/chat → SSE |
| Execute task | POST /gateway/v1/task/execute |
| Start meeting | POST /gateway/v1/meeting/start |
| Forge session | POST /gateway/v1/forge/session |
10 Primary Pages
| Page | Route | Description |
|---|---|---|
| Dashboard | / | Active projects health, team status, escalations, today's meetings, cost burn rate |
| Projects | /projects/:id | Card grid → tabbed detail (overview, tasks kanban, team, milestones, meetings) |
| Team | /team/:id | Grid of agents + humans. Detail: skills radar, memory explorer, tools, performance |
| Chat | /chat/:conv_id | Slack-like with SSE streaming, tool call visualization, thinking indicator |
| Meetings (V1.5) | /meetings/:id | Schedule, transcripts, action items, manage recurring meetings |
| Tool Forge (V1.5) | /forge/:id | Tool catalog, versions, split-pane build mode (chat + code + tests) |
| Escalations | /escalations | Inbox sorted by severity. Acknowledge, resolve, dismiss, assign |
| Settings | /settings | Instance config, integrations, templates, knowledge base, notifications |
| Activity | /activity | Chronological feed filterable by agent, project, action type. Real-time WS |
| Cost Center | /costs | Token usage + cost by agent/project/time. Burn rate charts, budget alerts |
WebSocket
Single persistent connection. Receives push events for TanStack Query cache invalidation.
SSE (Server-Sent Events)
Per-conversation stream for agent responses.
Frontend Mockups
Wireframe layouts for every major page of the application — showing structure, navigation, and content zones.
Dashboard
/
7
12
3
$14.72
Projects
/projects
ON TRACK
AT RISK
ONGOING
ON TRACK
Project Detail
/projects/:id
Open (4)
In Progress (3)
In Review (2)
Done (5)
Team
/team
Sr SW Architect
ONLINE
Patient Portal v3
Marketing Strategist
ONLINE
All Projects
CTO (Human)
AVAILABLE
Patient Portal v3
QA Engineer
BUSY
Test Automation
Chat
/chat/:id
Let me analyze that schema...
Campaign report ready
Found 2 edge cases in...
PR #287 is ready for...
Meetings (V1.5)
/meetings
0 9 * * 1-5 | Facilitator: Luna | 6 participants
0 10 * * 1 | Facilitator: Scrum-Master | 8 participants
0 14 * * 3 | Facilitator: Architect | 4 participants
Tool Forge (V1.5)
/forge/build
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
Escalations
/escalations
Cost Center
/costs
$1,247.83
$42.68/day
$752.17
Settings
/settings
Scheduled Tasks v1.9
/schedules
Schedule Detail / Edit v1.9
/schedules/:id
consecutive_failures / max_retries) trigger automatic escalation to the assigned human reviewer.
Scheduled Tasks API v1.9
qqq CRUD + CUSTOMStandard qqq CRUD endpoints for the scheduled_job table, plus custom actions for on-demand execution and history retrieval.
| Endpoint | Method | Description |
|---|---|---|
/api/scheduled_job | GET | List all scheduled jobs (filterable by agent, status, tool) |
/api/scheduled_job | POST | Create a new scheduled job |
/api/scheduled_job/{id} | GET | Get schedule detail |
/api/scheduled_job/{id} | PATCH | Update schedule (edit cron, toggle active, change params) |
/api/scheduled_job/{id} | DELETE | Delete schedule |
/api/scheduled_job/{id}/run-now | POST | Manually trigger an immediate execution (creates job_execution with trigger_type = MANUAL) |
/api/scheduled_job/{id}/history | GET | Get 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 Forge
Collaborative tool building — humans and agents design, build, test, and publish tools together via a git-backed, versioned workflow.
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
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.
tool record (status: DRAFT), tool_version record (version: 0.1.0-draft), forge_session record, conversation messages.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.
tool_version.source_ref set to initial git SHA. Sandbox pod created in k8s.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.
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).
forge_session metadata. Updated test files committed to git. Coverage report artifact uploaded to object storage.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.
tool_version.status updated to APPROVED or CHANGES_REQUESTED. Review comments stored. Activity log entry for audit trail.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.
tool.status = ACTIVE. tool_version finalized with git SHA tag. tool.current_version updated. Catalog entry visible to all agents. Activity log entry.publish_node. Terminal node. Final checkpoint. Graph state archived. Session marked COMPLETED.Tool Categories
Category Details
Platform Tools
BUILTINcreate_task, update_task_status, list_projects, store_memory, create_escalation, schedule_job
Integration Tools
IMPORTEDJira, Confluence, Slack, Zoho CRM, GitHub, Google Workspace connectors
Custom Tools
FORGEDpull_campaign_metrics, check_ssl_expiry, parse_invoice_pdf, calculate_sprint_velocity
MCP Tools
MCPPlaywright (browser), SQL (database), filesystem, custom internal APIs
Tool Execution Model — Where Each Type Runs
| Category | Environment | Details |
|---|---|---|
| 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
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).
Tool Interface Contract
Every tool — regardless of category — conforms to the same contract stored in the tool table.
| Field | Purpose |
|---|---|
name | Unique identifier: jira_create_issue |
display_name | Human-readable: "Create Jira Issue" |
input_schema | JSON Schema defining required/optional parameters |
output_schema | JSON Schema defining return value structure |
risk_level | LOW / MEDIUM / HIGH / CRITICAL — determines execution policy |
requires_approval | Boolean — if true, blocks until human approves |
current_version | Semantic version pointing to latest tool_version |
Sandbox Execution Comparison
| Aspect | Forge Sandbox (build time) | Production Sandbox (runtime) |
|---|---|---|
| Lifecycle | Ephemeral per session | Pool of warm containers |
| Network | Integration endpoints only (allowlist) | Integration endpoints only |
| qqq access | None | Read-only via ToolContext |
| Resources | 1 CPU, 2GB RAM, 60s timeout | Configurable per risk_level |
| Filesystem | Isolated workspace, git init | Tool workspace only |
| Code source | Written live by forge agent | git checkout at pinned SHA |
Tool Forge Example
Building an Amazon keyword research tool suite (like Helium 10) — a step-by-step walkthrough of the forge workflow in action.
Scenario: Cerebro Keyword Lookup
AMAZON PPCThe 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 CREATION1. 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?
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?
Step 2: Scaffold
FILE GENERATIONGenerated 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 GENERATIONcerebro_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 TESTINGTest 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 APPROVALReview Summary:
| Files changed | 4 files, 187 lines |
| Test coverage | 92% |
| Risk level | LOW |
| Dependencies | sp-api, boto3, pytest |
| Network access | Amazon SP-API endpoints only |
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.0Reverse 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 } |
| Output | Keyword gap list with search volume, competition score |
| Built by | Marcus Rivera + The Rock via Forge |
| Forged in | 28 minutes (3 implement iterations) |
listing_optimizer
v1.0.0Analyzes a product listing against its top-performing keywords. Scores title, bullets, description, and backend keywords for optimization potential.
| Input | { asin, target_keywords[] } |
| Output | Optimization report with section scores, suggestions |
| Built by | Priya Patel + Stone Cold via Forge |
| Forged in | 35 minutes (2 implement iterations) |
bsr_tracker
v1.0.0Monitors 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 } |
| Output | BSR history with trend direction, volatility score |
| Built by | Jake Morrison + Bret Hart via Forge |
| Forged in | 22 minutes (1 implement iteration) |
competitor_analyzer
v1.0.0Tracks competitor pricing, inventory levels, and listing changes over time. Generates weekly competitive intelligence reports with actionable insights.
| Input | { competitor_asins[], metrics[] } |
| Output | Competitive report with price history, inventory estimates |
| Built by | Bryan Chupp (CMO) + The Undertaker via Forge |
| Forged in | 40 minutes (4 implement iterations) |
Complete Amazon PPC Toolkit
| Tool | Purpose | Agent Users | Run Frequency |
|---|---|---|---|
cerebro_keyword_lookup | Keyword rankings for any ASIN | The Rock, The Undertaker, Bret Hart | On-demand |
keyword_magnet | Keyword gap analysis vs competitors | The Rock | Weekly (scheduled) |
listing_optimizer | Listing quality scoring | Stone Cold | On-demand + monthly audit |
bsr_tracker | BSR monitoring and trends | Bret Hart | Daily (scheduled) |
competitor_analyzer | Competitive intelligence | The Undertaker | Weekly (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 Models
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.
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.
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.
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.
LOCAL
Ollama, LM Studio
HTTP to localhost or internal service. No auth needed. Hardware cost amortized. Ideal for development and low-cost tasks.
Seed Models (P0)
| Provider | Model | Tier | Input $/1M | Output $/1M | Context | Tools | Vision | Thinking |
|---|---|---|---|---|---|---|---|---|
| Anthropic | claude-opus-4-6 | FLAGSHIP | $5.00 | $25.00 | 200K | ✓ | ✓ | ✓ |
| claude-sonnet-4-6 | STANDARD | $3.00 | $15.00 | 200K | ✓ | ✓ | ✓ | |
| claude-haiku-4-5 | ECONOMY | $1.00 | $5.00 | 200K | ✓ | ✓ | ✗ | |
| OpenAI | gpt-4o | FLAGSHIP | $2.50 | $10.00 | 128K | ✓ | ✓ | ✗ |
| gpt-4o-mini | ECONOMY | $0.15 | $0.60 | 128K | ✓ | ✓ | ✗ | |
| o3 | FLAGSHIP | $10.00 | $40.00 | 200K | ✓ | ✓ | ✓ | |
| Ollama (Local) | llama-3.1-70b | STANDARD | ~$0.50/hr GPU | 128K | ✓ | ✗ | ✗ | |
| llama-3.1-8b | ECONOMY | ~$0.10/hr GPU | 128K | ✓ | ✗ | ✗ | ||
| codellama-34b | STANDARD | ~$0.30/hr GPU | 100K | ✓ | ✗ | ✗ | ||
| AWS Bedrock | claude-opus-4-6 | FLAGSHIP | AWS pricing | 200K | ✓ | ✓ | ✓ | |
| claude-sonnet-4-6 | STANDARD | AWS pricing | 200K | ✓ | ✓ | ✓ | ||
| amazon-titan-text | ECONOMY | AWS pricing | 32K | ✗ | ✗ | ✗ | ||
Capability Tiers
Highest capability. Complex reasoning, architecture, strategy. Claude Opus, GPT-4o, o3.
Good general capability. Day-to-day tasks, code generation. Claude Sonnet, Llama 70B.
Speed-optimized. Quick lookups, simple transformations, routing decisions.
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.
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) → LLMResponseasync def health_check() → bool
def supports_feature(feature: str) → bool
# features: "tools", "vision", "thinking", "streaming", "json_mode"
AnthropicClient
@anthropic-ai/sdk
OpenAIClient
openai SDK
OllamaClient
HTTP to Ollama API
BedrockClient
boto3 bedrock-runtime
VertexClient
google-cloud-aiplatform
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.
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 Type | Cost 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.
| Provider | Health | Last Check | Latency | Models Active | Queries Today |
|---|---|---|---|---|---|
| Anthropic | HEALTHY | 2 min ago | 142ms | 3 | 847 |
| OpenAI | HEALTHY | 1 min ago | 198ms | 3 | 312 |
| Ollama (Local) | HEALTHY | 30s ago | 12ms | 3 | 156 |
| AWS Bedrock | DEGRADED | 2 min ago | 580ms | 2 | 45 |
Secrets Management
Secrets are scoped hierarchically — the narrowest scope wins when multiple secrets with the same name exist at different levels.
Secret Scopes
| Scope | Example | Who 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
| Column | Type | Purpose |
|---|---|---|
id | UUID PK | Primary key |
scope_type_id | FK → secret_scope_type | INSTANCE, PROJECT, TOOL, AGENT |
project_id | FK → project (nullable) | Set for PROJECT scope |
tool_id | FK → tool (nullable) | Set for TOOL scope |
agent_id | FK → agent (nullable) | Set for AGENT scope |
name | VARCHAR(100) | Secret name: HUBSPOT_API_KEY |
description | TEXT | Human-readable description |
secret_path | VARCHAR(200) | Secrets Manager path or k8s secret ref |
secret_type_id | FK → secret_type | API_KEY, OAUTH2_TOKEN, SSH_KEY, etc. |
last_rotated_at | TIMESTAMPTZ | Last rotation timestamp |
expires_at | TIMESTAMPTZ | For rotation alerting |
created_by_id | FK → team_member | Who 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)
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.
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
Integrations
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]
| Field | Purpose |
|---|---|
type_id | FK to integration_type: JIRA, SLACK, ZOHO_CRM, etc. |
auth_type_id | FK to auth_type: API_KEY, OAUTH2, BASIC, BEARER, SERVICE_ACCOUNT |
credentials_id | FK to secret_ref (credentials fetched via Secrets Manager at runtime) |
health_status_id | FK to health_status: HEALTHY, DEGRADED, DOWN, UNKNOWN |
settings | JSONB — integration-specific configuration |
is_active | Boolean — 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)
Jira V1 LAUNCH
BIDIRECTIONALOutbound: 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
Confluence V1.1 (2 WEEKS)
PUSH + PULLOutbound: 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
Slack V1 LAUNCH
PUSH + WEBHOOKOutbound: 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
Zoho CRM V1.1 (2 WEEKS)
PUSH-DOMINANTOutbound: Lead creation, deal updates, note attachment, activity logging.
Inbound: Contact/lead lookups by agents.
Tools Provided
GitHub V1 LAUNCH
BIDIRECTIONALOutbound: 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
Google Workspace V1.1 (2 WEEKS)
PUSH-DOMINANTCalendar: Free/busy queries, event creation with Meet, rescheduling.
Docs/Sheets: Document creation in Drive, data export/import.
Tools Provided
Webhook Receiver Endpoint
Shared endpoint for inbound callbacks from all integrations:
POST /api/webhooks/{integration_type}
Signature verification
webhook secret from SM
Event parsing
normalized IntegrationEvent
Route to context
agent/task/project IDs
Enqueue / write
process or passive sync
Error Handling: Circuit Breaker Pattern
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+ INTEGRATIONSFull catalog across 4 team types. Each follows the same IntegrationConnector pattern.
Software Engineering
15 integrations| Integration | Category | Key Operations | Priority |
|---|---|---|---|
| Jira | Project Mgmt | Issue CRUD, transitions, sprint management, JQL | P0 |
| Confluence | Knowledge | Page CRUD, space indexing for RAG, reviews | V1.1 |
| GitHub | Source Control | PR creation, issue filing, code search, repo sync | P0 |
| GitLab | Source Control | MR creation, pipeline status (GitHub alternative) | P1 |
| CircleCI | CI/CD | Pipeline status, trigger builds, test results | P1 |
| ArgoCD | GitOps/CD | Sync status, rollback triggers, app health | P1 |
| SonarQube | Code Quality | Quality gate status, issues, coverage | P1 |
| Snyk | Security | Vulnerability scanning, dependency analysis | P1 |
| Bitbucket | Source Control | PR creation, pipeline status (GitHub alt) | P2 |
| PagerDuty | Incident | Create/ack/resolve incidents, on-call lookup | P2 |
| Opsgenie | Incident | Alert management, on-call schedules | P2 |
| DataDog | Monitoring | Query metrics, dashboards, alert status | P2 |
| Grafana | Monitoring | Dashboard queries, alert rules, annotations | P2 |
| Terraform Cloud | Infrastructure | Plan/apply status, workspace mgmt, cost | P2 |
| GHCR | Registry | Image listing, vuln scans, tag management | P2 |
Design Teams
5 integrations| Integration | Category | Key Operations | Priority |
|---|---|---|---|
| Figma | Design | Export specs (colors, spacing, typography), comments, files | P1 |
| Notion | Wiki/Docs | Page CRUD, database queries, search (Confluence alt) | P2 |
| Miro | Whiteboard | Board creation, sticky notes, frame export | P2 |
| Adobe CC | Assets | Asset library, file export, version history | P3 |
| InVision / Zeplin | Handoff | Screen specs, asset download, comment sync | P3 |
Marketing — Amazon / B2C
7 integrations| Integration | Category | Key Operations | Priority |
|---|---|---|---|
| Amazon SP-API | Ecommerce | Listing CRUD, order data, inventory, FBA | P0 |
| Amazon Ads API | PPC | Campaign/keyword CRUD, bid mgmt, search terms | P0 |
| Helium 10 | Amazon Tools | Keyword research, listing optimization, BSR | P1 |
| Keepa | Price Tracking | Price history, BSR history, competitor monitoring | P1 |
| Jungle Scout | Amazon Tools | Product research, sales estimates, keyword scout | P2 |
| Shopify | Ecommerce | Product CRUD, orders, inventory sync | P2 |
| WooCommerce | Ecommerce | Product CRUD, order data, coupons | P3 |
Marketing — Web / Digital
11 integrations| Integration | Category | Key Operations | Priority |
|---|---|---|---|
| Google Analytics 4 | Analytics | Traffic reports, conversions, audience segments | P1 |
| Google Search Console | SEO | Search performance, indexing, sitemap, rankings | P1 |
| Google Ads | PPC | Campaign mgmt, keyword bids, ad copy, reports | P1 |
| Meta Ads API | Social Ads | FB/IG campaigns, audience targeting, performance | P1 |
| HubSpot | Marketing CRM | Contacts, email campaigns, landing pages, workflows | P1 |
| Buffer | Social Media | Post scheduling, queue mgmt, analytics | P1 |
| SEMrush | SEO Research | Keywords, backlinks, competitor analysis | P2 |
| Ahrefs | SEO Research | Backlink profiles, keyword explorer, rank tracking | P2 |
| Mailchimp | Campaign CRUD, audience mgmt, A/B testing | P2 | |
| Hootsuite | Social Media | Post scheduling, social listening, analytics | P2 |
| Canva API | Design | Template-based image creation, brand kit | P2 |
Universal (All Teams)
5 integrations| Integration | Category | Key Operations | Priority |
|---|---|---|---|
| Slack | Communication | DMs, channel posts, interactive buttons, threads | P0 |
| Google Workspace | Productivity | Calendar, Docs, Sheets, Drive | V1.1 |
| Zoho CRM | CRM | Contact/lead/deal CRUD, activity logging | V1.1 |
| Microsoft Teams | Communication | Messages, channels, meetings (Slack alt) | P2 |
| Linear | Project Mgmt | Issue CRUD, cycle mgmt, roadmap (Jira alt) | P2 |
Observability & Cost Management
Agent Performance Metrics
Agent performance is derived from existing tables, not a separate metrics store. Aggregated API endpoints computed on read.
| Metric | Source | Computation |
|---|---|---|
| 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 — DEVEXOperational 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}
trace_id + debug_payload from the target job_executionlanggraph_checkpointsactivity_log entries matching the trace)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
| Metric | Source |
|---|---|
| Integration Health | integration_config.health_status_id — periodic health check probes |
| Worker Queue Depth | Prometheus gauge from Celery/Redis queue; also DB-backed aggregation |
| Agent Status Distribution | agent.execution_status_id aggregation: IDLE, EXECUTING, ERROR |
| Error Rates | activity_log where action = 'system.error', grouped by source |
| Job Execution Health | scheduled_job.consecutive_failures vs. max_retries |
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.
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_total | Counter by method, path, status |
praesidium_http_request_duration_seconds | Histogram of request latency |
praesidium_active_websocket_connections | Gauge of open WS connections |
praesidium_active_sse_streams | Gauge of open SSE streams |
praesidium_work_items_queued | Gauge by priority level |
praesidium_work_items_processing | Gauge of executing items |
Agent Worker Metrics
praesidium_agent_executions_total | Counter by agent_id, status |
praesidium_agent_execution_duration_seconds | Histogram of execution time |
praesidium_llm_calls_total | Counter by model, agent_id |
praesidium_llm_tokens_total | Counter by direction, model |
praesidium_tool_calls_total | Counter by tool name, risk level |
praesidium_celery_task_queue_length | Gauge 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.
| Field | Table | Description |
|---|---|---|
input_tokens / output_tokens / cost_usd | message | Per-turn token usage and cost |
model_used | message | Which model processed this turn |
total_tokens / total_cost_usd | conversation | Running aggregate for the conversation |
input_tokens / output_tokens / cost_usd | job_execution | Total consumed during a job run |
cost_usd / duration_ms | activity_log | Cost 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.
| Threshold | Action |
|---|---|
| 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.
| Trigger | Severity | Details |
|---|---|---|
| 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
Via Google Workspace to project lead or admin DL
In-App Inbox
/escalations page, real-time via WebSocket
Datadog Observability & APM
UNIFIED OBSERVABILITYUnified, 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:
| Tag | Description | Example |
|---|---|---|
env | Environment tier | prod, staging, dev |
service | Service name | qqq-api, agent-worker, praesidium-web |
version | Git SHA or SemVer | a1b2c3d, 1.8.0 |
praesidium_instance_id | Business unit UUID | finance-team-uuid |
agent_id | The specific agent involved | forge-agent-01 |
task_id | Unique task execution ID | task-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"
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:
| Metric | Type | Tags |
|---|---|---|
praesidium.agent.token_usage | Counter | model, instance_id, agent_type |
praesidium.agent.thought_cycles | Histogram | Time spent in reasoning vs. tool calls |
praesidium.tool.execution_status | Counter | tool_name, status:success|error|timeout |
praesidium.human_in_the_loop.approval_latency | Gauge | Time tasks spend in AWAITING_APPROVAL |
praesidium.cost.burn_rate | Gauge | Real-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.
Roadmap
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.
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.
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.
| Phase | Focus | Deliverables |
|---|---|---|
| Phase 1 | Foundations | qqq DB provisioning, Authentik claim mapping, React App Shell, Datadog infra, CI/CD pipeline |
| Phase 2 | Tool Runner (Hands) | K8s Job sandboxing, “Blind” Secret Pipeline (IRSA + Secrets Manager), tool execution verification |
| Phase 3 | Agent Workers (Brain) | Direct SDK agent loops, LangGraph state machines (durable workflows), Postgres Checkpointing, HITL interrupt() |
| Phase 4 | Gateway | SSE Streaming, Chat UI, Task Orchestration, Command Palette (Cmd+K) |
| Phase 5 | Integrations | Slack, Jira, GitHub toolsets, Webhook listeners, integration testing |
| Phase 6 | Business Ops | KPI Dashboards, HITL Approval UI, Rollback logic, Feedback system |
| Phase 7 | Stabilization (Overflow) | Security audit, Load testing, Production rollout, Bug fixes, Observability tuning |
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.
| Day | Dev 1 (Infra + qqq) | Dev 2 (Python) | Dev 3 (React) |
|---|---|---|---|
| D1 | Generate 117 qqq tables/providers | FastAPI + Celery scaffold | Vite + TanStack + shadcn scaffold |
| D2 | RDS schema provisioning | qqq Python client, AGENT_MANIFEST schema | Auth flow, app shell, routing |
| D3 | Authentik claim mapping + JWT verification | LLMClient, hydration against manifest | Dashboard + type table cache |
| D4 | Datadog Agent (EKS), dd-java-agent | Service Account JWT acquisition | Projects + Team pages |
| D5 | CI pipeline (Faber) + smoke tests | Worker-to-qqq auth flow complete | Chat 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.
| Day | Dev 1 (K8s + Infra) | Dev 2 (Tool Runtime) | Dev 3 (Frontend) |
|---|---|---|---|
| D6 | Tool Runner K8s Job template | Python sandbox image + pip deps | Escalations + Activity pages |
| D7 | NetworkPolicy + resource limits | “Blind” Secret fetch (Boto3 + IRSA) | Settings + Dashboard polish |
| D8 | SHA-only git checkout enforcement | Tool result bus (Redis → Gateway) | Cost Center + Kanban board |
| D9 | Tool execution logging (Datadog) | Tool timeout + failure handling | Chat improvements + Agent detail |
| D10 | “Hello World” tool E2E verification | Tool execution safety gates | E2E 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.
| Day | Dev 1 (Infra) | Dev 2 (Agent Runtime) | Dev 3 (Frontend) |
|---|---|---|---|
| D11 | Postgres Checkpointer table setup | LangGraph “Reasoning” loop impl | Agent detail views + status display |
| D12 | Celery queue config (3 queues) | Agent → Tool Runner dispatch flow | Task execution UI, thinking indicators |
| D13 | Worker pod SIGTERM / checkpoint handling | interrupt() for CRITICAL tools (HITL) | Approval queue UI scaffold |
| D14 | Datadog APM tracing (5-service waterfall) | Direct SDK integration + agent hydration | Multi-LLM provider display |
| D15 | Worker kill → resume verification | E2E: chat → reason → tool → respond | Error 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.
| Day | Dev 1 (Gateway) | Dev 2 (Backend) | Dev 3 (Frontend) |
|---|---|---|---|
| D16 | Gateway SSE endpoint (token streaming) | Task Orchestration engine | Chat Thread UI + message rendering |
| D17 | WebSocket pub/sub (Redis) | Batch/composite qqq endpoints | Thinking indicators + tool call cards |
| D18 | /api/search composite endpoint | Scheduled job orchestration | Command Palette (Cmd+K) UI |
| D19 | Rate limiting + request validation | Conversation pruning + summarization | Task detail + execution trace views |
| D20 | Gateway E2E: stream → display → search | Stats reconciliation system job | Responsive 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.
| Day | Dev 1 (Integrations) | Dev 2 (Runtime) | Dev 3 (Frontend) |
|---|---|---|---|
| D21 | Slack Bot connector (Events API) | Slack-based status reporting tools | Integration config pages |
| D22 | Jira connector + webhooks | Jira toolset (create/update/search) | Integration health dashboard |
| D23 | GitHub connector + webhooks | GitHub toolset (PR, issues, review) | Webhook event log view |
| D24 | Webhook Listener (Gateway) | Integration health checks + retry | V1.1 integration stubs in UI |
| D25 | Integration E2E testing | Tool execution + safety gates verify | E2E 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.
| Day | Dev 1 (Business Logic) | Dev 2 (Runtime) | Dev 3 (Frontend) |
|---|---|---|---|
| D26 | HITL Approval Queue backend | Action hash generation + verification | HITL Approval Dashboard UI |
| D27 | KPI data aggregation pipeline | Feedback collection API | KPI Dashboard pages |
| D28 | Rollback logic + revert() interface | Budget controls + cost alerts | Rollback UI + confirmation flows |
| D29 | Activity logging + audit trail | E2E backend: approval → execute → rollback | Feedback widgets + rating UI |
| D30 | Business ops E2E verification | Observability pipeline complete | Full 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.
| Day | Dev 1 (Infra + Security) | Dev 2 (Performance) | Dev 3 (QA + Polish) |
|---|---|---|---|
| D31 | Security audit + dependency scanning | Load testing (50 concurrent agents) | Full E2E regression suite |
| D32 | Vulnerability remediation | Performance bottleneck fixes | Accessibility audit + fixes |
| D33 | Production environment setup | Observability dashboard tuning | Runbook creation + testing |
| D34 | Staging → Prod deploy | Monitoring alerts + thresholds | Engineering team onboarding |
| D35 | Production smoke tests | P0/P1 bug fixes | Phase 1 rollout begins |
Post-Launch (Not in v1)
10 Epics
E1: Data Model & API (qqq)
Phase 1117 table schema, Liquibase migrations, qqq-generated REST APIs, RLS
~34 story points
E2: Agent Runtime
Phase 2FastAPI gateway, Celery workers, agent hydration, direct SDK + LangGraph
~36 story points
E3: Frontend SPA
Phase 310-page React SPA with TanStack, shadcn/ui, WebSocket, SSE streaming
~63 story points
E4: Tool Forge (V1.5)
V1.5LangGraph workflow, sandbox execution, git-backed versioning
~21 story points — Deferred to V1.5 (4–6 weeks post-launch)
E5: Integration Layer
Phase 5V1: 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.5pgvector memory, RAG pipeline, extraction, knowledge indexing
~21 story points — Deferred to V1.5 (4–6 weeks post-launch)
E7: Meetings & Conversations (V1.5)
V1.5Standups, 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 1Authentik, IAM policies, JWT validation, RLS, permission-driven UI
~19 story points
E10: Observability & Cost
Phase 6Activity logging, token tracking, budget alerts, Grafana dashboards
~18 story points
Jira Plan
| Project Name | Praesidium2 |
| Project Key | PV2 |
| Type | Scrum (software) |
| Sprint Length | 2 weeks |
| Lead | James Maes |
| Issue Types | Epic, Story, Task, Bug, Spike, Sub-task |
Confluence Plan
| Space Name | Praesidium2 |
| Space Key | PV2 |
| Type | Global space |
| Top-Level Pages | Overview, 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_issueautomatically when requirements are decomposed from a project brief or triggered by a workflow event. - Agent-created issues are tagged with a
source: agentlabel 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 Edition
Digital Marketing Team
Amazon B2CAn 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)
| Name | Role | How They Use Praesidium2 |
|---|---|---|
| Bryan Chupp | CMO | Reviews dashboards, approves campaign budgets, joins weekly strategy standups, makes pricing decisions |
| Marcus Rivera | PPC Manager | Gets daily bid optimization reports, reviews keyword recommendations, approves budget changes |
| Priya Patel | Content Manager | Reviews AI-generated listings, approves social media calendars, provides brand voice feedback |
| Jake Morrison | Marketing Analyst | Reviews 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
| Agent | Persona | Template | Tools | Primary Project |
|---|---|---|---|---|
| "Macho Man" Randy Savage | COS / Coordinator. Intense, motivational, keeps the team fired up. "THE CREAM RISES TO THE TOP, OH YEAH!" | COS / Marketing Strategist | list_projects, create_task, schedule_job, zoho_crm_search, slack_send_dm, search_agents | All projects (LEAD) |
| "The Rock" Dwayne Johnson | PPC Specialist. Electrifying bid management. Knows EXACTLY what the campaigns are cooking. | PPC Analyst | amazon_ads_api (forged), gsheets_write_data, create_escalation, slack_post_message | PPC Optimization |
| "Stone Cold" Steve Austin | Content Creator. No-nonsense listings. Stuns the competition with killer A+ content. | Content Writer | gdocs_create_document, confluence_create_page, create_artifact, amazon_listing_api (forged) | Content & Listings |
| "The Undertaker" Mark Calaway | Competitive Intel. Silent, methodical, always watching. Competitors don't know he's tracking them. | Market Researcher | web_scraper (forged), gsheets_write_data, zoho_crm_update_record, slack_send_dm | Competitive Analysis |
| "Ric Flair" Richard Fliehr | Social Media. Stylin', profilin', and scheduling posts. WOOO! Brings the flair to every channel. | Social Media Specialist | social_scheduler (forged), gdocs_create_document, create_task, slack_post_message | Social & Brand |
| "Bret Hart" The Hitman | Data Analyst. The excellence of execution when it comes to numbers. Every report is technically perfect. | Data Analyst | gsheets_read_data, gsheets_write_data, amazon_reports_api (forged), create_artifact | Reporting & Analytics |
Projects (6)
| Project | Type | Team | Description |
|---|---|---|---|
| PPC Optimization | ONGOING | The Rock (LEAD), Macho Man, Bret Hart | Daily bid management, keyword discovery, budget allocation across 50+ ASINs |
| Content & Listings | ONGOING | Stone Cold (LEAD), Macho Man, Ric Flair | A+ content, listing optimization, SEO, image creation briefs |
| Q4 Holiday Launch | SHORT_TERM | Macho Man (LEAD), The Rock, Stone Cold, Ric Flair, Bret Hart | Black Friday / Cyber Monday campaign — new product launches, promotions, landing pages |
| Competitive Analysis | ONGOING | Undertaker (LEAD), Bret Hart | Weekly competitor price tracking, market share estimates, new entrant monitoring |
| Social & Brand | ONGOING | Ric Flair (LEAD), Stone Cold | Social calendar, influencer outreach tracking, brand consistency |
| Reporting & Analytics | ONGOING | Bret Hart (LEAD), Macho Man | Weekly/monthly performance reports, attribution modeling, executive dashboards |
Forged Tools (5)
| Tool | What It Does | Built By |
|---|---|---|
amazon_ads_api | Pulls Sponsored Products/Brands campaign data, adjusts bids, manages keywords | Bryan + Macho Man via Tool Forge |
amazon_listing_api | Updates product titles, bullets, backend keywords, A+ content via Amazon SP-API | Priya + Stone Cold via Tool Forge |
amazon_reports_api | Downloads Business Reports, Search Term Reports, Inventory Health | Jake + Bret Hart via Tool Forge |
competitor_price_scraper | Checks competitor pricing on Amazon and DTC sites, stores in Google Sheet | Jake + Undertaker via Tool Forge |
social_scheduler | Posts to Buffer/Hootsuite API, manages content calendar | Priya + 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
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 Name | Schedule | Agent | Tools Used | Output |
|---|---|---|---|---|
| Hourly PPC Bid Optimization | 0 * * * * (every hour) | The Rock | amazon_ads_api | Bid adjustments on all active ASINs, change log posted to #ppc-updates |
| Daily Competitor Price Scan | 0 6 * * * (6 AM) | The Undertaker | competitor_price_scraper | Updated pricing sheet, escalations on drops >10% |
| Weekly Performance Report | 0 7 * * 1 (Mon 7 AM) | Bret Hart | amazon_reports_api, gsheets_write_data | ROAS/ACoS/spend breakdown by brand in Google Sheets |
| Social Media Auto-Post | 0 8,13,18 * * * (3x daily) | Ric Flair | social_scheduler | Scheduled content posted to Instagram, TikTok, Facebook |
| Mid-Day Spend Report | 0 14 * * 1-5 (2 PM weekdays) | Bret Hart | amazon_ads_api, gsheets_write_data | Running 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 Edition
Software Engineering & IT Operations
Engineering + DevOps + QA + ProductGreater 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
| Name | Role | Areas of Ownership | How They Use Praesidium2 |
|---|---|---|---|
| US Engineering Management | |||
| James Maes | CTO | Technology Strategy, Platform Architecture, AI/ML, Infrastructure, Security, Engineering Operations | Sets technical vision, owns platform architecture, manages engineering team, approves critical changes, drives AI adoption strategy |
| Mark Weibrecht | System Administrator CISSP, CASP, SAA, SysOPS | Infrastructure, Observability | Manages AWS/EKS, Datadog, reviews agent-generated Helm charts, security audits |
| Shane Hughes | Senior Engineer, Innovation | Innovation Team | Evaluates emerging technologies, validates new capabilities, reviews agent output |
| India Senior Engineers | |||
| Barath Chittibabu | Senior Engineer | Mobile Apps, SDK Evaluation | Leads implementation sprints, reviews agent-generated code, provides architecture context for mobile |
| Jebins Armstrong | Senior Engineer | Me.Health Portal, Backend Services, DevOps/CI/CD, Web Properties | Implements features, manages CI/CD pipelines, reviews agent-generated backend code and deployments |
| Vivek Manoharan | Senior Engineer | MES Client Application, Hub V2 Software | Implements features, reviews agent-generated code for MES/Hub systems |
| Arun | Senior Engineer | Hub V2 Firmware, Device Testing | Reviews agent-generated test plans, validates firmware integration |
| Delight S | Engineering Manager, India | All India Engineering Personnel | Manages 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
| Agent | Persona | Template | Tools | Primary Focus |
|---|---|---|---|---|
| Gandalf | COS / Architect. Ancient wisdom, sees the big picture. "You shall not pass... untested code to production." | Senior SW Architect | github_create_pr, github_create_issue, confluence_create_page, jira_create_issue, search_agents | Architecture, design, coordination |
| Aragorn | Sr 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_search | Backend feature implementation |
| Legolas | Backend / 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 |
| Arwen | Frontend 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 |
| Gimli | QA Engineer. Relentless, thorough. "AND MY AXE!" to every test suite. Dwarven stubbornness = 100% coverage. | QA Engineer | github_create_issue, jira_create_issue, test_runner (forged), gsheets_write_data | Test planning, writing, bug filing |
| Samwise | DevOps Engineer. The loyal backbone of infrastructure. Carries the team through deployments. | DevOps Engineer | github_create_pr, helm_lint (forged), terraform_plan (forged), slack_post_message | CI/CD, infrastructure, monitoring |
| Bilbo | Technical Writer. The storyteller. Documents every adventure (API, runbook, ADR) with meticulous detail. | Technical Writer | confluence_create_page, confluence_update_page, gdocs_create_document | API docs, runbooks, ADRs |
| Elrond | Scrum Master. Convenes the councils, mediates disputes. Thousands of years of project management experience. | Scrum Master / Project Coordinator | jira_search, jira_update_issue, slack_post_message, gcal_create_event | Sprint management, standup facilitation |
Projects (5)
| Project | Type | Lead |
|---|---|---|
| Patient Portal v3 | SHORT_TERM | Gandalf |
| API Platform | ONGOING | Legolas |
| Infrastructure | ONGOING | Samwise |
| Quality Assurance | ONGOING | Gimli |
| Sprint Operations | ONGOING | Elrond |
Forged Tools (7)
| Tool | Built By |
|---|---|
code_executor | James + Gandalf via Forge |
db_migration_tool | Alex + Legolas via Forge |
test_runner | Lisa + Gimli via Forge |
helm_lint | Dev + Samwise via Forge |
terraform_plan | Dev + Samwise via Forge |
figma_export | Maria + Arwen via Forge |
pr_review_analyzer | James + Gandalf via Forge |
Sprint Planning (Monday 10 AM)
Scheduled Meeting: "Sprint Planning" | Cron: 0 10 * * 1 (bi-weekly) | Facilitator: Elrond (Scrum Master)
Daily Standup (Day 4 of Sprint 14)
Scheduled Meeting: "Daily Standup" | Cron: 0 9 15 * * 1-5 | Facilitator: Elrond
Sprint Retrospective (Friday)
Scheduled Meeting: "The Council of Sprint Retrospective" | Facilitator: Elrond
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 Name | Schedule | Agent | Tools Used | Output |
|---|---|---|---|---|
| Daily Test Suite | 0 6 * * * (6 AM) | Gimli | test_runner | Full test results across all repos, posted to #eng-tests on Slack |
| Nightly DB Health Check | 0 2 * * * (2 AM) | Legolas | db_migration_tool, code_executor | Query performance report, index recommendations, anomaly escalations |
| Weekly Dependency Scan | 0 5 * * 1 (Mon 5 AM) | Samwise | code_executor, github_create_issue | Snyk/Trivy vulnerability scan, Jira tickets for critical CVEs |
| Sprint Velocity Report | 0 16 * * 5 (Fri 4 PM) | Elrond | jira_search, confluence_create_page | Velocity metrics, burndown chart, posted to Confluence and #eng-sprint |
| PR Stale Check | 0 9 * * 1-5 (9 AM weekdays) | Gandalf | pr_review_analyzer, slack_post_message | Pings 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)
Corp Claw — CEO + CFO + HR
Executive CommandGreater 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.
Human Team (3)
| Name | Role | How They Use Praesidium2 |
|---|---|---|
| Chris Chupp | CEO | Reviews cross-department dashboards, approves strategic initiatives, joins weekly executive standups, makes go/no-go decisions |
| Sarah Mitchell | CFO | Reviews financial reports, approves budgets, monitors cost burn rates across all instances, quarterly board prep |
| David Park | VP of HR | Manages 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
| Agent | Persona | Template | Tools | Primary Focus |
|---|---|---|---|---|
| Emperor Palpatine | Chief of Staff. Sees everything, knows everything, orchestrates the grand plan. "Everything is proceeding as I have foreseen." | Executive COS | federation_query_peer, list_projects, create_escalation, slack_post_message, gcal_create_event, search_agents | Cross-department coordination |
| Darth Vader | CFO Analyst. Enforcer of financial discipline. Finds your lack of budget compliance... disturbing. | Financial Analyst | gsheets_read_data, gsheets_write_data, create_artifact, zoho_crm_search, cost_tracker (forged) | Financial reporting, budget tracking |
| Grand Moff Tarkin | Strategic Planner. Builds and executes the operational battle plans. Precise, methodical, decisive. | Strategy Consultant | confluence_create_page, jira_search, create_task, create_milestone, gdocs_create_document | Strategic initiatives, OKR tracking |
| Admiral Ackbar | Risk & Compliance Officer. Always watching for traps. HIPAA, SOC2, legal — nothing gets past him. "It's a compliance trap!" | Compliance Analyst | confluence_search, create_escalation, audit_checker (forged), slack_send_dm | Compliance, risk assessment |
| Mon Mothma | HR Operations. Diplomatic, methodical, ensures the people side runs smoothly. Coordinates across all bases. | HR Coordinator | gcal_create_event, slack_send_dm, gdocs_create_document, jira_create_issue, bamboohr_api (forged) | Talent pipeline, onboarding |
| C-3PO | Executive Assistant / Comms. Fluent in 6 million forms of communication. Occasionally anxious about deadlines. | Executive Communications | gdocs_create_document, confluence_create_page, slack_post_message, gcal_create_event, slides_generator (forged) | Board prep, investor updates |
Projects (6)
| Project | Type | Lead |
|---|---|---|
| Quarterly Business Review | ONGOING | Palpatine |
| FY2027 Budget Planning | SHORT_TERM | Vader |
| HIPAA Compliance Program | ONGOING | Ackbar |
| Talent & Culture Initiative | ONGOING | Mon Mothma |
| Board & Investor Relations | ONGOING | C-3PO |
| Cross-Department Synergies | ONGOING | Tarkin |
Forged Tools (5)
| Tool | Built By |
|---|---|
cost_tracker | Sarah + Vader via Forge |
audit_checker | David + Ackbar via Forge |
bamboohr_api | David + Mon Mothma via Forge |
slides_generator | Chris + C-3PO via Forge |
okr_tracker | Chris + Tarkin via Forge |
Weekly Executive Standup
Scheduled Meeting: "Corp Claw Weekly" | Cron: 0 8 * * 1 | Facilitator: Emperor Palpatine (COS)
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 Name | Schedule | Agent | Tools Used | Output |
|---|---|---|---|---|
| Daily Cost Roll-Up | 0 8 * * * (8 AM) | Vader | cost_tracker, gsheets_write_data | Aggregated cost data across all instances, burn rate dashboard updated |
| Weekly Compliance Scan | 0 6 * * 1 (Mon 6 AM) | Ackbar | audit_checker | Cross-system compliance posture report, escalations on failures |
| Monthly Board Deck Prep | 0 8 1 * * (1st of month) | C-3PO | slides_generator, cost_tracker | Draft board deck in Google Slides, sent to Chris for review |
| Quarterly OKR Progress | 0 9 1 1,4,7,10 * (quarterly) | Tarkin | okr_tracker, confluence_create_page | Company-wide OKR status report, published to Confluence |
| Weekly Headcount Sync | 0 7 * * 1 (Mon 7 AM) | Mon Mothma | bamboohr_api, gsheets_write_data | Updated 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 Edition
Product Development Team
Physical ProductsGreater 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)
| Name | Role | How They Use Praesidium2 |
|---|---|---|
| Matt Carpenter | VP of Product Development | Reviews product designs, approves tooling costs, manages factory relationships, makes sourcing decisions |
| Wei Zhang | China Operations Manager | Coordinates with Shenzhen/Guangzhou factories, manages QC inspections, handles shipping logistics |
| Priya Sharma | India Sourcing Lead | Manages textile and component sourcing from Mumbai/Delhi suppliers, negotiates pricing |
| Carlos Reyes | DR Manufacturing Lead | Oversees 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
| Agent | Persona | Template | Tools | Primary 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 COS | list_projects, create_task, schedule_job, slack_post_message, gcal_create_event, search_agents | Team coordination, product roadmap |
| Black Widow (Natasha) | Supply Chain Manager. Stealthy, efficient, navigates complex international supplier networks. | Supply Chain Analyst | gsheets_read_data, gsheets_write_data, zoho_crm_search, shipping_tracker (forged), supplier_scorecard (forged) | Supplier management, logistics |
| Thor | Quality 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 America | Compliance & Regulatory. Stands for truth, justice, and proper product certifications. | Regulatory Compliance | confluence_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 Analyst | gsheets_read_data, gsheets_write_data, create_artifact, cost_modeler (forged) | BOM cost analysis, landed cost |
| Hawkeye | Project Scheduler. Never misses a deadline. Keeps every timeline perfectly tracked. | Project Coordinator | jira_create_issue, jira_update_issue, gcal_create_event, slack_post_message, timeline_tracker (forged) | Production timelines, scheduling |
| Spider-Man | Communications & Translator. Bridges the language gap between US team, Chinese factories, Indian suppliers, and DR operations. | International Comms | slack_send_dm, slack_post_message, gdocs_create_document, translate_api (forged) | Factory comms, translation |
Projects (6)
| Project | Type | Lead |
|---|---|---|
| Kitchen Product Line 2027 | SHORT_TERM | Iron Man |
| Pet Supplies Refresh | SHORT_TERM | Iron Man |
| Ongoing QC Program | ONGOING | Thor |
| Supplier Onboarding | ONGOING | Black Widow |
| Regulatory & Certifications | ONGOING | Captain America |
| Cost Optimization Initiative | ONGOING | Hulk |
Forged Tools (8)
| Tool | Built By |
|---|---|
shipping_tracker | Wei + Black Widow via Forge |
supplier_scorecard | Matt + Black Widow via Forge |
qc_checklist | Wei + Thor via Forge |
defect_tracker | Carlos + Thor via Forge |
certification_tracker | Matt + Captain America via Forge |
cost_modeler | Matt + Hulk via Forge |
timeline_tracker | Matt + Hawkeye via Forge |
translate_api | Wei + 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
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 Name | Schedule | Agent | Tools Used | Output |
|---|---|---|---|---|
| Daily Shipment Tracker | 0 7 * * * (7 AM) | Black Widow | shipping_tracker | All container statuses checked, delay alerts sent to Wei and Carlos |
| Weekly Supplier Scorecard | 0 8 * * 1 (Mon 8 AM) | Black Widow | supplier_scorecard, gsheets_write_data | Updated supplier scores: on-time delivery, defect rate, responsiveness |
| Daily QC Summary | 0 18 * * 1-5 (6 PM) | Thor | defect_tracker, qc_checklist | Daily defect report compiled from all factories, posted to #product-qc |
| Monthly BOM Cost Analysis | 0 9 1 * * (1st of month) | Hulk | cost_modeler, gsheets_write_data | All product costs recalculated, margin report sent to Matt |
| Weekly Certification Status | 0 8 * * 3 (Wed 8 AM) | Captain America | certification_tracker, confluence_create_page | Certification 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 Edition
Me Health — RPM Health Platform
Healthcare RPMGreater 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_logtable 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)
| Name | Role | How They Use Praesidium2 |
|---|---|---|
| Bryan Potter | VP of Me Health | Oversees the entire RPM business unit — sales, marketing, operations, business development |
| Rachel Torres | Sales Director | Manages sales pipeline, reviews proposals, closes deals with healthcare providers |
| Kevin Park | Operations Manager | Manages patient onboarding, device inventory, clinical support workflows |
| Jennifer Liu | Marketing Manager | Healthcare 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
| Agent | Persona | Template | Tools | Primary Focus |
|---|---|---|---|---|
| Dr. Meredith Grey | Chief of Staff. Seen it all, leads with steady hands. "It's a beautiful day to save lives... and close deals." | Healthcare Business COS | list_projects, create_task, schedule_job, slack_post_message, search_agents, federation_query_peer | Business unit coordination |
| Dr. Cristina Yang | Sales Operations. Fiercely competitive, data-driven, relentless in pursuit of quota. Does RESULTS, not warm and fuzzy. | Sales Analyst | zoho_crm_search, zoho_crm_create_record, zoho_crm_update_record, gsheets_write_data, pipeline_analyzer (forged) | Sales pipeline, lead qualification |
| Dr. Miranda Bailey | Operations Chief. Runs clinical operations with iron discipline and a big heart. "I have five rules. Memorize them." | Operations Coordinator | jira_create_issue, jira_update_issue, create_task, slack_send_dm, onboarding_tracker (forged) | Patient onboarding, device fulfillment |
| Dr. Alex Karev | Business Development. Scrappy, determined, goes after new partnerships with raw hustle. | Business Development Rep | zoho_crm_create_record, confluence_create_page, gdocs_create_document, slack_post_message, market_analyzer (forged) | New markets, partnerships |
| Dr. Izzie Stevens | Marketing & Content. Creative, empathetic, crafts healthcare messaging that resonates with providers and patients. | Healthcare Marketing | gdocs_create_document, confluence_create_page, social_scheduler (forged), email_campaign (forged), create_artifact | Provider education, email campaigns |
| Dr. George O'Malley | Compliance & Reporting. Meticulous, thorough, ensures every data point meets HIPAA standards. Quiet but essential. | HIPAA Compliance Analyst | audit_checker (forged), confluence_search, create_escalation, compliance_reporter (forged) | HIPAA compliance, clinical reporting |
| Dr. Addison Montgomery | Patient Experience. Premium care, premium attention. Tracks satisfaction, manages escalated patient concerns. | Patient Experience Analyst | slack_send_dm, create_escalation, gsheets_read_data, patient_satisfaction (forged), nps_tracker (forged) | Patient satisfaction, NPS |
Projects (6)
| Project | Type | Lead |
|---|---|---|
| Q3 Sales Push | SHORT_TERM | Cristina Yang |
| Patient Onboarding Optimization | ONGOING | Miranda Bailey |
| Provider Education Program | ONGOING | Izzie Stevens |
| HIPAA Compliance & Audit | ONGOING | George O'Malley |
| RPM Platform Growth | ONGOING | Meredith Grey |
| Clinical Reporting & Outcomes | ONGOING | Miranda Bailey |
Forged Tools (7)
| Tool | Built By |
|---|---|
pipeline_analyzer | Rachel + Cristina Yang via Forge |
onboarding_tracker | Kevin + Miranda Bailey via Forge |
market_analyzer | Bryan P + Alex Karev via Forge |
email_campaign | Jennifer + Izzie Stevens via Forge |
compliance_reporter | Kevin + George O'Malley via Forge |
patient_satisfaction | Bryan P + Addison Montgomery via Forge |
nps_tracker | Rachel + 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)
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 Name | Schedule | Agent | Tools Used | Output |
|---|---|---|---|---|
| Daily Pipeline Report | 0 8 * * * (8 AM) | Cristina Yang | pipeline_analyzer, gsheets_write_data | Pipeline status, stale deal alerts, revenue forecast posted to #me-health-sales |
| Daily Patient Onboarding Status | 0 9 * * * (9 AM) | Miranda Bailey | onboarding_tracker | Onboarding funnel status, stalled patient alerts sent to Kevin |
| Weekly NPS Report | 0 8 * * 1 (Mon 8 AM) | Addison Montgomery | nps_tracker, patient_satisfaction | NPS trends by provider, at-risk account alerts, satisfaction summary |
| Monthly Compliance Dashboard | 0 8 1 * * (1st of month) | George O'Malley | compliance_reporter, audit_checker | HIPAA compliance dashboard, access review status, BAA tracker |
| Weekly Market Intelligence | 0 8 * * 3 (Wed 8 AM) | Alex Karev | market_analyzer, confluence_create_page | New 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 & Compliance
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
| Layer | At Rest | In Transit |
|---|---|---|
| PostgreSQL | AES-256 (RDS encryption, or LUKS for local) | TLS 1.3 (pg_hba.conf: hostssl) |
| Redis | ElastiCache encryption at rest | TLS 1.3 |
| S3 / MinIO | AES-256 (SSE-S3 or SSE-KMS) | HTTPS only |
| Secrets Manager | AES-256 (AWS managed) | HTTPS only |
| Pod-to-Pod | N/A | mTLS via service mesh (Istio/Linkerd) or k8s NetworkPolicy + TLS |
| Browser-to-API | N/A | TLS 1.3 (ALB terminates, internal traffic via mTLS) |
Day 1 Encryption Baseline
v1.10 — HARDENINGOperational 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:
[REDACTED] and an alert is sent to the #security-alerts Slack channelNote: 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 UUIDFK 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 / Service | BAA Status | Notes |
|---|---|---|
| Anthropic | REQUIRED | Required if any agent conversation could involve PHI context. Alternatively, route PHI-adjacent work to LOCAL LLM providers only. |
| AWS (RDS, S3, EKS, etc.) | IN PLACE | Standard AWS HIPAA eligible services: RDS, S3, ElastiCache, EKS, Secrets Manager. |
| Jira | HIPAA TIER | Atlassian offers HIPAA-compliant Cloud Enterprise tier. BAA needed if agent tickets reference patient context. |
| Confluence | HIPAA TIER | Same as Jira — Atlassian Cloud Enterprise. BAA needed for clinical documentation. |
| Slack | HIPAA TIER | Slack Enterprise Grid offers HIPAA compliance. BAA needed if agent messages contain PHI-adjacent data. |
| Zoho CRM | REQUIRED | New integration — BAA must be signed 30 days before go-live per compliance policy. |
Data Retention & Disposal Schedule
| Data Type | Retention Period | Disposal Method |
|---|---|---|
| Audit logs (activity_log, audit_access_log) | 7 years | Archived to S3 Glacier after 1 year |
| Conversation messages | 3 years | Soft delete → hard delete after retention period |
| Agent memories | Until expired or explicitly deleted | Secure wipe (overwrite + delete) |
| Artifacts | Project lifetime + 1 year | S3 lifecycle policy → delete |
| Knowledge documents | Until manually removed | Secure delete of chunks + embeddings |
| LangGraph checkpoints | 90 days after workflow completion | Auto-purge job |
Phased Rollout Strategy
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-Phase Rollout Plan
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.
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.
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.
| Phase | Stabilization Window | Key Activities | Gate 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:
| Severity | Response Time | Escalation | Resolution Owner |
|---|---|---|---|
| P0 — Platform Down | < 15 minutes | Immediate Slack alert to all engineers + CTO | All hands on deck |
| P1 — Agent Broken | < 1 hour | Slack alert to on-call engineer + team lead | On-call engineer |
| P2 — Degraded | < 4 hours | Jira ticket, daily standup triage | Assigned engineer |
| P3 — Minor/Cosmetic | Next sprint | Jira backlog | Sprint 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.
| Category | Criteria | Threshold |
|---|---|---|
| Stability | Platform uptime during stabilization period | ≥ 99.5% |
| Stability | Zero unresolved P0/P1 bugs from current phase | 0 open |
| Performance | Agent task completion rate (non-error) | ≥ 95% |
| Performance | API p95 latency | < 500ms |
| Support | Support queue depth (unresolved tickets) | < 5 |
| Support | Mean time to resolve support issues | < 4 hours |
| Runbooks | All deployment runbooks reviewed and tested | 100% |
| Runbooks | At least 2 team members can deploy independently | ≥ 2 people |
| Security | No open security findings (CRITICAL/HIGH) | 0 open |
| Capacity | Support team has bandwidth for next phase | Confirmed |
B22: Business-Value Kill Criteria
Kill Gates Business Review GapGo/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.
| Gate | Metric | Threshold | Measurement Source |
|---|---|---|---|
| 30-Day Gate | Hours saved per team per week | ≥ 5 hours/week | KPI dashboard (B4) vs. baseline |
| User feedback score | > 3.5 / 5 | Feedback system (B13) rolling average | |
| Agent task utilization | > 60% of available tasks routed to agents | Task table: agent-assigned / total | |
| 60-Day Gate | Hours saved per team per week | ≥ 8 hours/week | KPI dashboard (B4) vs. baseline |
| User feedback score | > 4.0 / 5 | Feedback system (B13) rolling average | |
| Agent task utilization | > 75% of available tasks routed to agents | Task table: agent-assigned / total | |
| ROI trajectory | Positive (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.
| Phase | Teams Active | Onboarding Support | Platform Dev | Bug Fix Reserve |
|---|---|---|---|---|
| Phase 1 | 1 (Engineering) | 0 (self-service) | 2 engineers | 1 engineer |
| Phase 2 | 2 (+Marketing) | 1 engineer | 1 engineer | 1 engineer |
| Phase 3 | 3–5 (+3 teams) | 1 rotating | 1 engineer | 1 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 1 | Engineering | First agent tasks, initial bug triage, baseline metrics | HIGH |
| Phase 2 | Engineering | Stabilization, runbook drafts, go/no-go review | MEDIUM |
| Phase 3 | Engineering + Marketing | Marketing onboarding, multi-instance validation | MEDIUM |
| Phase 4 | Engineering + Marketing | Stabilization, support playbook, go/no-go review | MEDIUM |
| Phase 5 | +Corp Claw, +Product Dev | Third/fourth instance, federation queries active | LOW |
| Phase 6 | +Me Health (if HIPAA-ready) | Full fleet deployed, cross-instance coordination | LOW |
| Phase 7 | All teams | Build stabilization overflow complete, full production hardening, KPI baseline comparison | LOW |
⚠ 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 Factor
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.
| Runbook | Owner | Secondary | Key Content | Review Cycle |
|---|---|---|---|---|
| qqq Configuration | Dev 1 | Dev 2 | Table schema updates, API generation, Liquibase migrations, RLS configuration, qqq metaData files | Quarterly |
| Authentik IAM Setup | Dev 1 | Dev 3 | OAuth provider configuration, group/role mapping, MFA policies, service account management, Authentik backup/restore | Quarterly |
| AWS Deployment | Dev 1 | Dev 2 | EKS cluster management, RDS operations, ElastiCache, S3 buckets, IAM roles, VPC/security groups, cost monitoring | Quarterly |
| ArgoCD Management | Dev 2 | Dev 1 | Application sync, rollback procedures, GitOps workflow, secret management, multi-environment promotion | Quarterly |
| Agent Runtime Operations | Dev 2 | Dev 3 | Agent runtime troubleshooting, Celery worker scaling, task queue management, LangGraph workflow debugging, LLM provider failover | Quarterly |
| Disaster Recovery | Dev 1 | Dev 2 | RDS restore from snapshot, Redis failover, S3 recovery, full-cluster rebuild, tested restore procedure | Quarterly |
| Instance Provisioning | Dev 3 | Dev 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 Retrospectives
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
| Retrospective | Timing | Teams Involved | Facilitator | Output |
|---|---|---|---|---|
| 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 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
| Resource | Allocation | Annual Cost | Responsibilities |
|---|---|---|---|
| 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.
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 & 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.
| Integration | ToS Review | Key Concerns | Data Classification | Status |
|---|---|---|---|---|
| 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.
| Scenario | Liability Owner | Mitigation |
|---|---|---|
| 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 Area | Action Required |
|---|---|
| Errors & Omissions (E&O) | Verify AI-generated output is covered under existing E&O policy |
| Cyber Liability | Confirm coverage for AI agent data handling and API interactions |
| Professional Liability | Review coverage for automated decisions that impact clients or partners |
| Technology E&O | Evaluate need for AI-specific technology errors coverage |
LLM Provider Data Agreements
Data handling agreements with each LLM provider used by the platform:
| Provider | Agreement | Key Terms |
|---|---|---|
| Anthropic | Enterprise Terms + DPA | No training on customer data; SOC 2 Type II; data retention controls |
| OpenAI | Enterprise Agreement | Zero data retention option; API-only (no training); data processing addendum |
| Google (Gemini) | Cloud AI Terms | Enterprise data protection; no model training on inputs; regional processing |
| Local (Ollama/vLLM) | Self-hosted | No external data transfer; full data sovereignty; HIPAA-compatible |
Data Governance
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 Type | Owner | Policy |
|---|---|---|
| Documents & Reports | Instance (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 & Recommendations | Team lead (human) | Agent recommendations are advisory. The human who approves the action owns the decision. |
| Meeting Summaries | Instance (business unit) | Generated summaries retained per instance retention policy. Human attendees can edit/override. |
Accountability Framework
| Scenario | Accountable Party |
|---|---|
| Agent produces factually incorrect report | Team lead who approved/distributed the output |
| Agent misinterprets task instructions | Task creator (human who wrote the instructions) |
| Agent runtime bug causes data corruption | Engineering team (platform defect) |
| Agent output used in regulatory filing | Filing signatory (human); agent output must be reviewed |
Retention Policies for Agent Output
| Output Type | Retention | Disposal |
|---|---|---|
| Task artifacts | Project lifetime + 1 year | S3 lifecycle → delete |
| Conversation history | 3 years | Soft delete → hard delete |
| Meeting summaries | 3 years | Archived to cold storage after 1 year |
| Escalation records | 5 years | Retained for audit trail purposes |
| Agent-generated code | Indefinite (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 & Stability
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
| Layer | Tool | Coverage Target | What It Tests |
|---|---|---|---|
| Unit | pytest (Python), JUnit (Java), Vitest (TypeScript) | 90%+ | Individual functions, classes, utilities |
| Integration | pytest + testcontainers | 80%+ | Service ↔ database, service ↔ Redis, service ↔ qqq API |
| API Contract | pytest + OpenAPI validation | 100% | Request/response schema compliance, error codes |
| E2E | Playwright (frontend), pytest (backend) | Critical paths | Full user flows: login → create project → chat → execute task |
| Load | Locust or k6 | Defined SLAs | Concurrent agent execution, API response times, WebSocket scalability |
| Security | OWASP ZAP, Snyk, Semgrep, Trivy | Zero HIGH/CRITICAL | XSS, SQLI, SSRF, dependency vuln, container scanning, secrets scanning |
| Compliance | Custom audit tests | 100% HIPAA controls | Encryption 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)
| Metric | Target | Measurement |
|---|---|---|
| API availability (qqq + gateway) | 99.9% | Uptime Robot + Prometheus |
| Chat response time (TTFT) | <2s p95 | SSE timestamp in browser |
| Task execution start time | <10s p95 | Celery task timestamps (queue → running) |
| Scheduled job on-time execution | >99% | Celery Beat + job_execution timestamps |
| WebSocket reconnection | <5s | Client-side monitoring |
| Mean time to recovery (MTTR) | <15 min | Incident 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 Down | Impact | Degraded Behavior |
|---|---|---|
| Redis | No WS broadcasts, no task queue | Gateway handles chat inline, tasks queued in-memory (limited) |
| One qqq pod | None | k8s Service routes to other replicas |
| All workers | No async execution | Chat still works (gateway inline), tasks queue until workers recover |
| LLM provider | Agents can't think | Fallback to secondary provider, or queue tasks |
| Tool-runner | CUSTOM tools fail | PLATFORM + INTEGRATION tools still work, CUSTOM tools return error |
| S3 / MinIO | No artifact storage | Agents work without artifacts, uploads fail gracefully |
Health Check Matrix
| Pod | Liveness | Readiness | Startup |
|---|---|---|---|
| qqq-api | GET /health (DB ping) | GET /ready (migrations complete) | 90s timeout |
| gateway | GET /health (Redis ping) | GET /ready (qqq API reachable) | 30s timeout |
| worker | Celery inspect ping | Celery inspect active | 60s timeout |
| web | GET / (static file) | GET / | 10s timeout |
Disaster Recovery Strategy
Point-in-time recovery from RDS continuous backups
Automated restore from snapshots + Redis warm-up
| Component | Backup Method | Recovery Procedure |
|---|---|---|
| PostgreSQL (RDS) | Daily snapshots (35-day retention) + continuous WAL for PITR | Restore from snapshot or PITR to new RDS instance. Update connection strings via ConfigMap. |
| Redis (ElastiCache) | AOF persistence + daily automatic backups | Multi-AZ automatic failover. Manual: restore from backup to new cluster. |
| S3 (Artifacts, Tools) | S3 versioning + cross-region replication for critical data | Restore from version history or failover to replica bucket. |
| Secrets Manager | AWS-managed durability, replicated across AZs | Automatic. No manual recovery needed. |
| LangGraph Checkpoints | Included in PostgreSQL backups (same RDS instance) | Restored with database. In-flight workflows resume from last checkpoint. |
| Authentik | Separate RDS instance with own backup schedule | Restore Authentik DB. Existing JWTs remain valid during recovery window. |
Incident Response Flow
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 Operations
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.
B3: Agent Output Approval Workflow
Human-in-the-Loop Business Review GapAll 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
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)
| Trigger | Condition | Example |
|---|---|---|
| High-Cost Action | Estimated cost exceeds $threshold (default $50) | Bulk email send, large API call, paid service invocation |
| External-Facing Content | Action publishes to external audience | Social media post, customer email, public documentation update |
| First-Time Tool Usage | Agent has never used this tool before | First CRM update, first Jira ticket creation |
| Data Modification | Action modifies >10 records or deletes any record | Bulk Jira update, spreadsheet mass-edit |
| Cross-Team Action | Action targets another team's resources | Updating 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
“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.”
SLA: Pending items older than 4 hours trigger a Slack reminder to the approver.
Data Model — Approval Tables
| Table | Key Columns | Purpose |
|---|---|---|
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 GapWithout 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
| Team | Key Productivity Metric | Baseline Method | Expected Productivity Gains |
|---|---|---|---|
| CTO / Engineering | Hours on operational overhead | 2-week time tracking survey | Reduced context-switching, automated standups, faster decision support |
| VP Marketing | Campaign setup time, report generation | Task duration logs pre-deployment | Automated competitor analysis, faster content drafts, quicker report turnaround |
| VP HR | Onboarding time, policy lookup frequency | HR ticket resolution times | Automated onboarding checklists, faster FAQ responses, reduced manual triage |
| VP Product | Feature request triage, roadmap updates | Jira cycle time pre-deployment | Automated triage, sprint health reports, reduced coordination overhead |
| VP Operations | Process documentation, cross-team coordination | Confluence update frequency | Automated 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
| Category | Metric | Source | Frequency |
|---|---|---|---|
| Efficiency | Hours saved per team per week | Task completion times vs. baseline | Weekly |
| Efficiency | Tasks automated (count) | task table where assignee is agent | Weekly |
| Quality | Error reduction rate | Feedback scores + rejection rate from approval queue | Weekly |
| Quality | First-attempt approval rate | task_approval_queue approve vs. reject ratio | Weekly |
| Adoption | Active human users per team | Login frequency, chat sessions initiated | Weekly |
| Adoption | Agent utilization rate | Busy time / available time per agent | Weekly |
Dashboard — UI Mockup
The KPI dashboard is a top-level page accessible to team leads, VPs, and admins. Key views:
Weekly Team Summary
Trend Sparklines (4 weeks)
Data Model — KPI Tables
| Table | Key Columns | Purpose |
|---|---|---|
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 GapThe 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 Collected | Method | Responsible | Frequency |
|---|---|---|---|
| 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_baselinetable 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_baselinetable import
B5: User Training & Onboarding
Adoption Business Review GapA 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
| Role | Guide Content | Duration | Delivery |
|---|---|---|---|
| Team Lead | Dashboard overview, approval queue, KPI tracking, agent configuration, autonomy level management | 30 min | In-app guided tour + PDF |
| Team Member | Chat interface, task delegation, reviewing agent work, providing feedback, escalation | 15 min | In-app guided tour + PDF |
| Admin | Instance setup, integration configuration, user management, security policies, monitoring | 45 min | In-app tour + video walkthrough |
30-Minute Team Walkthrough Template
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
| Symptom | Likely Cause | Resolution |
|---|---|---|
| Agent sent wrong data to Jira | Outdated context or misunderstood task | Use Undo button in action log → correct task description → re-run |
| Agent keeps asking the same question | Memory not persisting or conflicting instructions | Check memory tab for the agent → clear stale entries → update system prompt |
| Agent ignoring my feedback | Feedback not linked to prompt improvement pipeline | Verify feedback is recorded in dashboard → escalate to admin if pattern persists |
| Agent took action without approval | Autonomy level too high or action not in policy scope | Check autonomy_level table → add approval_policy rule for this action type |
| Agent is slow to respond | Queue backlog, token limits, or external API latency | Check 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 GapWhen 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
| Integration | Action Type | Reversal Method | Automated? |
|---|---|---|---|
| Jira | Issue created | Delete issue via REST API | Yes |
| Jira | Issue updated (status, fields) | Restore previous field values from agent_action_log | Yes |
| Confluence | Page created/updated | Revert to previous version via Confluence API | Yes |
| Slack | Message sent | Delete message via chat.delete API | Yes |
| Slack | Channel created | Archive channel (Slack does not support delete) | Partial |
| Email (SES) | Email sent | Cannot recall — documented as non-reversible; requires approval gate | No |
| CRM / Zoho | Record created/updated | Restore from agent_action_log.before_state via API | Yes |
| Google Sheets | Cells modified | Restore from sheet version history | Partial |
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:
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
This will immediately pause all agent activity. Requires admin to reactivate.
Data Model — Rollback Tables
| Table | Key Columns | Purpose |
|---|---|---|
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 SPECTo 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
| Step | Action | Stored 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.9For 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
revert() on a Git-based tool executiontool.requires_review — if true, enters PR flowpraesidium-rollback/{execution_id}[Praesidium-Rollback]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 GapWithout 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 Type | Feedback Method | Metadata Captured |
|---|---|---|
| Chat Response | Thumbs up/down + optional text on each assistant message | Conversation ID, message ID, agent ID, timestamp |
| Task Completion | Rate 1–5 stars on task result + optional comment | Task ID, agent ID, tool IDs used, duration |
| Daily Summary | Thumbs up/down on standup / EOD summary | Job execution ID, summary type, team ID |
| Approval Decision | Implicit: approve = positive, reject = negative (with reason) | Approval queue ID, action type, escalation reason |
| Document Generated | Thumbs up/down + “needs edits” flag with diff | Document 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
Score <3.5 triggers probation review (see B17)
Feedback → Prompt Improvement Pipeline
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
| Table | Key Columns | Purpose |
|---|---|---|
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 GapAgents 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
Any status can transition back to Active after admin review and config adjustment — except Terminated, which is permanent.
Automatic Performance Thresholds
| Trigger | Threshold | Action |
|---|---|---|
| Feedback score drops | Rolling 7-day average < 3.5 / 5.0 | Auto-Probation — autonomy level reduced to FULL_REVIEW, admin notified |
| Rejection spike | ≥3 approval rejections in 24 hours | Auto-Probation — autonomy demoted, team lead alerted via Slack |
| Error rate surge | >20% task failure rate over 48 hours | Auto-Suspend — agent paused, incident created in activity log |
| Cost anomaly | Daily cost >3x rolling 7-day average | Auto-Probation — budget cap enforced, admin review required |
| Prolonged low performance | On probation for >14 days with no improvement | Auto-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:
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 Feature | Integrates With | How |
|---|---|---|
| Approval Queue (B3) | Agent Runtime, Integrations | Agent execution pauses at integration boundary, awaits approval before external API call |
| KPI Dashboard (B4) | Observability, Data Model | Aggregates existing task/message/cost data plus new baseline tables |
| Training (B5) | Frontend, Auth & Security | Onboarding flow hooks into first-login detection and role-based routing |
| Rollback (B11) | Integrations, Activity Log | Extends existing activity_log with before/after state capture per integration |
| Feedback (B13) | Chat UI, Task UI, Agent Runtime | Feedback widgets embedded in every agent output surface |
| Performance Mgmt (B17) | Feedback (B13), Approval (B3), Observability | Consumes 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
Marketing
Agents: Macho Man, The Rock, Stone Cold, The Undertaker, Ric Flair, Bret Hart
HR
Agents: Recruiter, Onboarder, Benefits, Payroll
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.
Nothing shared. Default for all new peers. Access must be explicitly enabled by admin.
High-level status only. Health indicators and counts. "3 active projects, 2 on-track, 1 at-risk."
Project names, milestone status, team member names. "Website Redesign: Design phase complete."
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
| Classification | Federation Behavior | Example |
|---|---|---|
| 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 UUIDname 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 UUIDFK 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 UUIDFK 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 UUIDFK 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.
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.
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.
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.
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 Summary
Findings by Severity
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)
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.
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.
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.
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.
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
| ID | Severity | Description |
|---|---|---|
| G1 | GAP | competitor_price_scraper references web scraping, not a standard integration. Keepa API is P1. |
| G2 | GAP | social_scheduler depends on Buffer (P1) / Hootsuite (P2). Neither available at launch. |
| G3 | GAP | Zoho CRM is P1 but 4 of 5 teams depend on it for core operations. Should be P0. |
Engineering Leadership Team (LOTR) — 5 gaps
| ID | Severity | Description |
|---|---|---|
| G4 | GAP | code_executor needs per-tool dependency resolution beyond tool_version.dependencies JSONB. |
| G5 | GAP | db_migration_tool needs database connectivity, but sandbox blocks internal services. |
| G7 | GAP | helm_lint needs Helm binary and kubeconfig. Sandbox has no mechanism for cluster credentials. |
| G8 | GAP | terraform_plan needs cloud IAM permissions. HIGH risk — human approval required. |
| G9 | GAP | figma_export depends on Figma API (P1). Needed early for frontend workflow. |
Corp Claw (Star Wars) — 5 gaps
| ID | Severity | Description |
|---|---|---|
| G12 | GAP | audit_checker needs internal service access. Should be PLATFORM category, not sandboxed CUSTOM. |
| G14 | GAP | Google Slides API not in catalog. Workspace integration covers Docs/Sheets/Calendar but not Slides. |
| G6 | ENHANCEMENT | test_runner needs project source code in sandbox. Extend tool-runner to support git-cloned volumes. |
| G10 | ENHANCEMENT | gcal_create_event adds agents as attendees, but AI agents have no Google accounts. |
| G30 | GAP | No example provides realistic cost estimates. Add cost modeling to each team’s documentation. |
Product Dev (Avengers) — 5 gaps
| ID | Severity | Description |
|---|---|---|
| G16 | GAP | shipping_tracker depends on Flexport/Freightos API. Not in integration catalog. |
| G17 | GAP | translate_api depends on DeepL API. Not in integration catalog. |
| G18 | GAP | WeChat group via “Slack bridge” referenced but no WeChat integration exists. |
| G19 | ENHANCEMENT | No timezone-aware message scheduling. human_interaction lacks deliver_at field. |
| G29 | ENHANCEMENT | human_profile missing external system IDs for BambooHR, HubSpot, Figma, Buffer. |
Me Health (Grey’s Anatomy) — 7 gaps
| ID | Severity | Description |
|---|---|---|
| G20 | GAP | market_analyzer has no specific external API. Needs NPI Registry, CMS data, or web search. |
| G21 | GAP | email_campaign depends on HubSpot (P1). CAN-SPAM compliance features needed at launch. |
| G22 | GAP | patient_satisfaction needs survey platform API (SurveyMonkey, Qualtrics, etc.). |
| G25 | GAP | Zoho CRM for healthcare sales may need BAA. Acknowledged in example but unresolved. |
| G26 | GAP | NPS tracker may handle individual patient responses. Same PHI constraints as G23 if patient-level. |
| G27 | GAP | Multi-agent standup turn-taking orchestrator needs validation. Custom implementation (~300 lines) may need LangGraph graph for complex meeting patterns. |
| G28 | GAP | Infrastructure 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_idadded to conversation schema- Polymorphism enforcement DB trigger (R10)
- CACHE annotations on agent counter fields (R8)
metadata JSONBon 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 ID | Severity | Finding | Resolution | Status |
|---|---|---|---|---|
| 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
| ID | Finding | Timeline |
|---|---|---|
| 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
| Area | Before (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.
| Addition | Details |
|---|---|
| Tilt | Hot-reload orchestrator for local k8s — watches source, rebuilds images, redeploys pods automatically |
| Ollama | Local LLM inference (llama3.1:70b for reasoning, nomic-embed-text for embeddings) — replaces Anthropic API in local dev |
| Self-Hosted Path | Air-gapped / on-premise deployment supported via same architecture (Ollama/vLLM + MinIO + k8s Secrets) |
| Configuration Profiles | Three 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
| Term | Definition |
|---|---|
Praesidium2 | The core AI agent platform enabling Greater Goods' Agentic AI Core Operating Model. Each business unit gets its own Praesidium2 instance. |
Greater Goods | The organization deploying Praesidium2 across all business units. |
qqq | The internal data-layer framework providing generated REST APIs, schema migrations, RBAC, and audit logging for all entity tables. |
Tool Forge | Collaborative tool-building platform where humans and agents co-create custom tools through an automated 6-step workflow. |
Agent Gateway | Python/FastAPI service that bridges the browser and React frontend to the backend agent runtime. |
Agent Workers | Backend services that run direct SDK agent loops and LangGraph durable workflows. |
Tool Runner | Service that executes custom tools in isolated sandbox environments. |
Jarvis | AI chat assistant embedded in Praesidium2 documents, capable of filing change requests and answering questions about the design. |
Corp Claw | Internal brand/product line managed by a Greater Goods business unit; used as a use-case example in the system design. |
Me Health | Internal brand/product line managed by a Greater Goods business unit; used as a use-case example in the system design. |
AI / ML Frameworks & Models
| Term | Definition |
|---|---|
LLM | Large Language Model — AI model trained on vast text data, used for reasoning, generation, and tool use (e.g., Claude, GPT-4). |
CrewAI | Open-source Python framework for orchestrating teams ("crews") of agents with defined roles, delegation, and shared memory. |
LangGraph | Framework built on LangChain for building durable, stateful agent workflows as directed graphs with checkpointing and human-in-the-loop support. |
MCP | Model Context Protocol — standard for integrating tools directly into LLM context windows. |
Claude Opus | Anthropic's most capable model; used for complex agent reasoning tasks. |
Claude Sonnet | Anthropic's balanced model; faster and cheaper than Opus, used for standard agent tasks. |
Anthropic SDK | Client library for calling Claude APIs from Python or TypeScript. |
OpenAI SDK | Client library for GPT-family models. |
AWS Bedrock | AWS managed service for accessing foundation models (Claude, Llama, etc.) without managing infrastructure. |
Ollama | Local LLM runner for self-hosted open-source models (e.g., Llama 3). |
vLLM | High-throughput open-source inference server for self-hosted large language models. |
Security & Authentication
| Term | Definition |
|---|---|
Authentik | Open-source Identity Provider (IdP) used for SSO, OAuth2/OIDC flows, and user provisioning in Praesidium2. |
JWT | JSON Web Token — signed token encoding user identity and claims, used for stateless authentication. |
OAuth2 | Industry-standard protocol for delegated authorization. |
OIDC | OpenID Connect — authentication layer on top of OAuth2 that provides user identity information. |
RBAC | Role-Based Access Control — restricting system access based on users' roles within an organization. |
RLS | Row-Level Security — PostgreSQL feature that filters query results at the database level based on user context. |
RecordSecurityLock | qqq's mechanism for enforcing instance isolation by injecting instance_id constraints into all queries automatically. |
praesidiumInstanceId | Custom JWT claim identifying which Praesidium2 instance a user belongs to; used for data isolation. |
praesidiumAllAccess | Custom JWT claim that grants an instance administrator full access bypass (bypasses RLS/RecordSecurityLock). |
Service account | Non-human identity (API key or token) used by services to authenticate with each other. |
Secrets Manager | AWS service (or equivalent) for securely storing and retrieving credentials, API keys, and other sensitive values. |
Secret_ref | A reference pointer to a credential stored in Secrets Manager; never the raw secret value itself. |
IAM-style policies | JSON documents that define permissions; modeled after AWS IAM policy syntax. |
Instance isolation | Security boundary ensuring one Praesidium2 instance cannot access another instance's data. |
Agent Architecture & Concepts
| Term | Definition |
|---|---|
Agent | AI-powered team member with persistent memory, tool access, defined skills, and evolving domain expertise. |
Agent template | Reusable blueprint defining an agent's role, default tools, and personality; instantiated to create agent instances. |
Agent instance | A running, deployed agent created from a template and assigned to a specific Praesidium2 instance. |
Agent hydration | Loading all agent state (memory, tools, config) from the database into memory at startup. |
Agent skill | A specific capability or area of expertise an agent possesses (e.g., "Jira project management", "Amazon listing optimization"). |
Crew | A team of agents working together on a shared project or goal via orchestrated turn-taking. |
Role | A defined function within a crew — e.g., Architect, Engineer, QA — shaping how an agent behaves and delegates. |
Delegation | An agent assigning a sub-task to another agent (or human) within a crew. |
Memory | An agent's accumulated knowledge: short-term (conversation), long-term (persistent knowledge chunks), and episodic (past events). |
Institutional knowledge | Organizational learning (processes, decisions, context) accumulated and preserved by agents over time. |
Personality traits | JSONB attributes stored per agent defining behavior defaults (e.g., verbosity, formality, escalation threshold). |
Human-in-the-loop | A workflow design pattern where execution pauses at defined points to require human review, decision, or approval. |
Escalation | An agent raising an issue to a human when it cannot proceed without guidance or when a risk threshold is exceeded. |
Escalation queue | FIFO queue of pending escalations awaiting human review in the Praesidium2 dashboard. |
Approval gate | A mandatory pause in a workflow requiring human approval before continuing execution. |
Tool Forge & Tool Concepts
| Term | Definition |
|---|---|
Tool Forge workflow | 6-step automated pipeline for creating new tools: Design → Scaffold → Implement → Test → Review → Publish. |
Design node | First forge step: generates a formal JSON specification from a natural-language description. |
Scaffold node | Second forge step: creates the project directory structure and boilerplate from the spec. |
Implement node | Third forge step: an agent writes the tool's implementation code. |
Test node | Fourth forge step: runs automated tests and validates the implementation. |
Review node | Fifth forge step: human reviews the generated tool and either approves or requests changes. |
Publish node | Sixth forge step: approved tool is versioned, git-tagged, and deployed to the tool catalog. |
Tool spec | JSON document defining a tool's inputs, outputs, behavior, and risk level; the contract all tool versions must conform to. |
Tool manifest | tool_manifest.json file in each tool repository defining entry point, schema, and metadata. |
Tool catalog | Registry of all available, approved tools that agents can be assigned to use. |
Risk level | Classification of a tool's potential impact: LOW / MEDIUM / HIGH / CRITICAL; determines execution policy (auto-run vs. approval-required). |
Sandbox | Isolated, ephemeral execution environment (Kubernetes pod) used for forge operations and tool execution to prevent unintended side effects. |
Forge session | Stateful database record tracking the full lifecycle of a single tool-building workflow run. |
Platform tools | Built-in system tools (e.g., create_task, update_task_status) available to all agents. |
Integration tools | Pre-built connectors for third-party services (Jira, Slack, Confluence, etc.). |
Custom tools | User-built tools created via the Forge; stored with FORGED status in the catalog. |
MCP tools | Tools integrated via the Model Context Protocol standard. |
requires_approval | Boolean flag on a tool indicating that every execution requires explicit human approval before proceeding. |
Infrastructure & Deployment
| Term | Definition |
|---|---|
Kubernetes (k8s) | Open-source container orchestration system for automating deployment, scaling, and management of containerized applications. |
EKS | Amazon Elastic Kubernetes Service — AWS managed Kubernetes control plane. |
Pod | Smallest deployable unit in Kubernetes; one or more containers sharing network and storage. |
DaemonSet | Kubernetes resource that ensures a copy of a pod runs on every node (used for log collectors like Fluent Bit). |
HPA | Horizontal Pod Autoscaler — Kubernetes feature that automatically scales pod count based on CPU, memory, or custom metrics. |
Helm | Kubernetes package manager; bundles Kubernetes manifests into reusable, versioned "charts". |
ArgoCD | GitOps continuous delivery tool for Kubernetes; automatically deploys from git repository state. |
ConfigMap | Kubernetes resource for storing non-sensitive configuration as key-value pairs injected into pods. |
ALB | Application Load Balancer — AWS layer-7 load balancer routing HTTP/HTTPS traffic to services. |
Docker | Container runtime and image format used to package applications and their dependencies. |
CI/CD | Continuous Integration / Continuous Deployment — automated pipelines for building, testing, and releasing software. |
Canary deployment | Rolling out a new version to a small percentage of traffic before full release. |
Blue-green deployment | Running two identical production environments and switching traffic between them for zero-downtime releases. |
HA | High Availability — architecture designed to minimize downtime through redundancy and failover. |
Queue-depth scaling | Autoscaling workers based on the number of pending items in the task queue. |
Warm pool | Pre-initialized containers kept ready to handle requests immediately, avoiding cold-start latency. |
Cold start | Latency experienced when a new container must initialize before handling its first request. |
SIGTERM | Operating system termination signal sent to a process; triggers graceful shutdown procedures. |
preStop | Kubernetes lifecycle hook that runs a command before a container receives SIGTERM. |
Fluent Bit | Lightweight log processor and forwarder that ships container logs to CloudWatch. |
Databases & Storage
| Term | Definition |
|---|---|
PostgreSQL | Open-source relational database; Praesidium2's primary data store for all entities. |
RDS PostgreSQL | AWS managed PostgreSQL — handles backups, patching, and replication automatically. |
pgvector | PostgreSQL extension enabling vector similarity search; used for semantic memory retrieval. |
Redis | In-memory data structure store; used as Celery broker, session cache, pub/sub bus, and rate-limit counters. |
S3 | Amazon Simple Storage Service — object storage for artifacts, tool source code, and large files. |
MinIO | Self-hosted S3-compatible object storage for local/development environments. |
JSONB | PostgreSQL binary JSON data type; supports indexing and querying of semi-structured data. |
UUID | Universally Unique Identifier — 128-bit value used as primary keys throughout the schema. |
Liquibase | Database migration tool that tracks and applies schema changes in a controlled, versioned manner. |
ORM | Object-Relational Mapping — library layer translating between database rows and programming objects. |
CRUD | Create, Read, Update, Delete — the four basic database operations. |
Audit logging | Automatic recording of all data modifications (who changed what, when) for compliance and debugging. |
Connection pool | Pre-allocated set of database connections reused across requests to reduce overhead. |
Async Processing & Messaging
| Term | Definition |
|---|---|
Celery | Distributed Python task queue for running background jobs asynchronously. |
Celery Beat | Celery's built-in scheduler for recurring (cron-style) tasks. |
Task queue | Durable queue holding background jobs awaiting execution by workers. |
SSE | Server-Sent Events — HTTP-based protocol for pushing real-time updates from server to browser (unidirectional). |
WebSocket | Protocol for full-duplex, bidirectional communication between browser and server. |
Pub/sub | Publish/Subscribe messaging pattern — publishers emit events to channels; subscribers receive them. |
Redis AOF | Append-Only File persistence mode; ensures Redis task data survives restarts. |
Task durability | Guarantee that queued tasks are not lost if Redis restarts (enabled via AOF + RDB persistence). |
Workflow | A LangGraph state machine defining the ordered steps an agent or crew takes to complete a job. |
Checkpoint | Durable snapshot of workflow state saved mid-execution so it can resume after failure or interruption. |
State machine | A system with a finite set of defined states and explicit transitions between them (the basis of LangGraph). |
Observability & Monitoring
| Term | Definition |
|---|---|
OpenTelemetry | Open-source observability framework for collecting distributed traces, metrics, and logs. |
Span | A single timed operation within a distributed trace (e.g., one database query or one API call). |
Correlation ID | Unique identifier attached to a request that is propagated across all services, enabling full trace reconstruction. |
X-Correlation-ID | HTTP request header carrying the Correlation ID between services. |
CloudWatch | AWS monitoring and observability service for logs, metrics, and alarms. |
CloudWatch Metrics | Numerical time-series data points (e.g., CPU utilization, request latency) stored and visualized in CloudWatch. |
Alert / Alarm | Automated notification triggered when a metric crosses a defined threshold. |
Tracing | Recording the path and timing of a request as it flows through multiple services. |
Telemetry | Automated collection and transmission of operational data (logs, metrics, traces) from running services. |
Burn rate | Daily LLM API spending rate used to project monthly costs and trigger budget alerts. |
MTD | Month-To-Date — cost or usage measured from the start of the current calendar month. |
Token tracking | Monitoring the number of input/output tokens consumed per LLM API call for cost attribution. |
Frontend Technologies
| Term | Definition |
|---|---|
React 19 | JavaScript library for building user interfaces with a component model and virtual DOM. |
Vite | Fast frontend build tool and dev server with native ES module support. |
Tailwind CSS | Utility-first CSS framework for styling directly in HTML markup. |
shadcn/ui | Composable React component library built on Radix UI and Tailwind CSS. |
TanStack Query | Async state management library for data fetching, caching, and synchronization in React. |
TanStack Router | Type-safe client-side routing library for React. |
REST | Representational State Transfer — architectural style for HTTP APIs using standard verbs (GET, POST, PUT, DELETE). |
FastAPI | High-performance Python web framework for building REST APIs with automatic OpenAPI documentation. |
Design system | Shared library of UI components, tokens, and patterns ensuring visual consistency across the application. |
External Integrations & Services
| Term | Definition |
|---|---|
Jira | Atlassian issue tracking and project management tool; Praesidium2 agents can read/write tickets. |
Confluence | Atlassian wiki/documentation platform; agents can read pages and publish content. |
Slack | Team messaging platform; agents communicate with humans and receive mentions/commands via Slack. |
GitHub | Git hosting and collaboration platform; used for code repositories and tool version storage. |
Google Workspace | Suite including Gmail, Docs, Sheets, and Drive; agents can read/write documents and emails. |
Zoho CRM | Customer relationship management platform; agents can query and update CRM records. |
Amazon SP-API | Selling Partner API — Amazon's REST API for managing marketplace listings, orders, and inventory. |
Advertising API | Amazon's API for managing sponsored ads, campaigns, and keyword bids. |
BambooHR | Human resources management system; integrated for HR data access. |
Flexport | Freight logistics platform; integrated for shipping and supply chain visibility. |
Twilio | Cloud communications API providing SMS, voice, and WhatsApp messaging capabilities. |
Figma | Collaborative interface design and prototyping tool. |
Helium 10 | Amazon seller intelligence platform; referenced as a benchmark for keyword research and listing tools. |
Ahrefs | SEO and content analytics tool; referenced as integration for competitor analysis features. |
Data Model Concepts
| Term | Definition |
|---|---|
Entity table | A primary database table representing a distinct business object (e.g., agents, tasks, tools). |
Type table | Lookup/enumeration table with static reference data (e.g., task statuses, priority levels). |
Root entity | An entity table with a direct instance_id column; the anchor for instance isolation. |
Derived entity | A table linked to an instance indirectly via a foreign key chain back to a root entity. |
PK | Primary Key — the unique identifier column for a database row. |
FK | Foreign Key — a column referencing the PK of another table, enforcing relational integrity. |
Instance | An isolated deployment of Praesidium2 for a single business unit; all data is scoped to an instance. |
Knowledge chunk | A granular, embedable unit of stored knowledge in agent memory (e.g., a paragraph, a fact, a decision). |
Artifact | A file or document output produced during task execution (e.g., a report, a generated script). |
Integration config | Stored credentials and settings for connecting to an external service. |
Polymorphic | A design pattern where a single table models multiple subtypes using a discriminator column (e.g., member_type: AGENT or HUMAN). |
Audit trail | Chronological record of all data changes, including who made them and when. |
Project & Task Management
| Term | Definition |
|---|---|
Project | Organizational container grouping related tasks, milestones, and team members. |
Milestone | A named marker within a project tracking a significant delivery or deadline. |
Task | A unit of work assigned to an agent or human; has status, priority, and optionally subtasks. |
Subtask | A child task nested under a parent task for finer-grained work tracking. |
Sprint | A time-boxed iteration (typically 2 weeks) containing a planned set of tasks. |
Daily standup | Short recurring meeting for team synchronization; facilitated by an agent in Praesidium2. |
Sprint planning | Meeting at the start of a sprint to define the work to be completed. |
Sprint review | End-of-sprint meeting to demonstrate completed work. |
Sprint retro | Retrospective meeting to discuss process improvements after a sprint. |
Action item | A task created directly from a meeting discussion or decision. |
Cost center | Logical grouping for tracking and attributing LLM API spend to a department, project, or agent. |
Budget | A defined spending limit for an agent, project, or cost center. |
Resilience Patterns & Operations
| Term | Definition |
|---|---|
Circuit breaker | Pattern that stops calling a failing service after a threshold of errors, allowing recovery time. |
Retry logic | Automatic re-attempt of a failed operation, typically with exponential backoff. |
Fallback | Alternative behavior triggered when the primary path fails (e.g., using a cheaper model when the primary is unavailable). |
Graceful degradation | System continues operating with reduced functionality when a subsystem is unavailable. |
Graceful shutdown | Process of finishing in-flight requests and releasing resources cleanly before a container terminates. |
Rate limiting | Throttling the number of requests a client can make in a time window. |
Rollback | Reverting a deployment or database migration to a previous known-good state. |
Replication lag | Delay between a write on the primary database and its appearance on read replicas. |
HIPAA | Health Insurance Portability and Accountability Act — US federal law requiring protection of health information; relevant to the Me Health business unit. |
Compliance tracking | Monitoring adherence to regulatory requirements and internal policies. |
Dev / Staging / Production | The three deployment environments: local development, pre-production testing, and live customer-facing. |
General Acronyms Quick Reference
| Acronym | Stands For |
|---|---|
AI | Artificial Intelligence |
API | Application Programming Interface |
ARN | Amazon Resource Name |
ALB | Application Load Balancer |
AWS | Amazon Web Services |
CI/CD | Continuous Integration / Continuous Deployment |
CRM | Customer Relationship Management |
CRUD | Create, Read, Update, Delete |
| Acronym | Stands For |
|---|---|
EKS | Elastic Kubernetes Service |
FK | Foreign Key |
HA | High Availability |
HIPAA | Health Insurance Portability and Accountability Act |
HPA | Horizontal Pod Autoscaler |
HTTP | Hypertext Transfer Protocol |
IAM | Identity and Access Management |
IdP | Identity Provider |
| Acronym | Stands For |
|---|---|
JWT | JSON Web Token |
LLM | Large Language Model |
MCP | Model Context Protocol |
MTD | Month-To-Date |
OIDC | OpenID Connect |
PK | Primary Key |
RBAC | Role-Based Access Control |
RLS | Row-Level Security |
REST | Representational State Transfer |
SSE | Server-Sent Events |
UUID | Universally Unique Identifier |