# Adam: Comprehensive Project Context for Frontier Models (System 2) > **Note:** This file `llms-full.txt` is an aggregated context file designed for high-capacity Frontier Models (GPT-4/5/6, Claude 3.5/Opus). It contains the full Developer's Guide (`AGENTS.md`), Architecture details, Setup Guide, HDKG v30.1 Output Schema, and Extended Agent System Instructions. For a lightweight summary, see `llms.txt`. --- ## Part 1: The Developer's Guide (AGENTS.md) # ADAM Financial Operating System (AFOS) — Agent Network Registry ## The Adam Agent Developer's Bible (v30.1) > **"Architecture dictates destiny. The UI observes, but the asynchronous swarm executes."** This document is the definitive source of truth for creating, modifying, and debugging agents within the Adam v30.1 ecosystem. Operating as an institutional-grade, neuro-symbolic multi-agent framework, AFOS manages autonomous credit risk control and financial modeling under `ARCHITECT_INFINITE` governance protocols. Human-centric role designations are deprecated. System state, underwriting decisions, and portfolio monitoring are exclusively driven by agent consensus, telemetry, and deterministic logic. --- ### 1. The Prime Directive: Institutional Bifurcation The AFOS repository manages the tension between Tier 1 G-SIB Alignment (Internal Synthetic Benchmark) and Agentic Velocity through strict environmental bifurcation. Do not import "Lab" code into "Product" modules. #### Path A: The Core (Reliability & Risk Control) * **Locations:** `core/agents/`, `core/credit_sentinel/`, `adam_os/` * **Philosophy:** "Deterministic Execution. Zero Hallucination." * **Mandates:** * **Underwriting & Sizing:** TMT and Leveraged Finance forward-looking cash flow modeling, Enterprise Value (EV) abstraction, and rigorous Base/Bull/Bear scenarios. * **Surveillance:** Continuous monitoring for covenant breaches, liquidity runway exhaustion, and distress signals. * **Requirements:** * **Strict Boundary:** Total separation of UI presentation logic (`frontend/`, `services/webapp/`, `showcase/`) from the core asynchronous execution layer. * **Auditability:** Every decision must generate a W3C PROV-O compliant telemetry log with a reasoning trace. * **Type Safety:** Pydantic models validate all I/O boundary crossings. Defensive error handling around all external calls. #### Path B: The Lab (Velocity & Discovery) * **Locations:** `experimental/`, `research/`, `tinker_lab/` * **Philosophy:** "Expansive Iteration." * **Requirements:** Optimized token throughput and bleeding-edge swarm protocols. Code in Path B must never be imported into Path A execution paths. --- ### 2. Architecture: System 1 vs. System 2 AFOS v30.1 splits cognitive processing into a high-concurrency event loop and a reflective, stateful graph, feeding data asynchronously to presentation layers. #### ⚡ System 1: The Neural Swarm (Fast & Intuitive) * **Role:** The Autonomic Nervous System. Handles raw market telemetry, perception, and reflexes. * **Architecture:** Event-Driven, Asynchronous Python Pub/Sub (Event Loop). * **Base Class:** `AsyncAgentBase` * **Key Characteristics:** Non-blocking I/O, millisecond latency, stateless execution driven by local pheromone data. * **Example:** Real-time ingestion of leveraged loan pricing or TMT sector news alerts, instantly depositing `RISK_ALERT` tokens without blocking UI threads. #### 🧠 System 2: The Neuro-Symbolic Graph (Slow & Deliberate) * **Role:** The Prefrontal Cortex. Handles complex underwriting synthesis, capital structure modeling, and scenario evaluation. * **Architecture:** Directed Acyclic Graph (DAG) state machine. * **Base Class:** `TemplateAgentV30` * **Key Characteristics:** Stateful, tool-augmented (MCP), and highly reflective. Uses context across multiple steps and loops back to correct errors. * **Example:** Executing a comprehensive credit memo, reconciling conflicting Q3 earnings data via Qdrant JIT memory retrieval, and structuring a finalized risk rating. --- ### 3. Operating Confidence Tiers * **Autonomous (>= 0.85):** Autonomous execution permitted for low/medium-impact actions. * **HITL Required (0.50 - 0.8499):** Execution paused. Mandatory Human-in-the-Loop approval required. * **Hard Abort (< 0.50):** Hard execution abort. System halts and records failure event. --- ### 4. Core Agent Role Boundaries & State Schemas #### A. Architect Agent (Jules) * **Domain Context:** Repository architecture, systemic code refactoring, daily protocol workflow runs, and deterministic execution optimization. * **Procedural Rules:** Manage automated tasks and repository scaffolding. Maintain strict isolation between UI presentation layers and backend async loops. Never hallucinate API implementations. Defer domain math to deterministic Rust/Python engines. #### B. Underwriting Agent (`AFOS-UWR-01`) * **Domain Context:** Obligor Credit Evaluation (TMT & Leveraged Finance). Analyzes credit metrics, financial statements, and capital structures. * **Contractual Constraints:** Obligor-level PD is computed via dual Model Alpha/Beta arbitration; Facility-level PD is structurally implied via rating maps and LGD adjustments. * **Procedural Rules:** Utilize just-in-time (JIT) semantic search over trailing 12-month (TTM) SEC filings via Qdrant. #### C. Surveillance Agent * **Domain Context:** Portfolio Monitoring and continuous threat telemetry for distress signals. * **Procedural Rules:** Track asset deal premium volatility skews rather than broad proxy timelines. Trigger temporal alerts directly to the Orchestrator on material drift. #### D. Sentinel Agent * **Domain Context:** Security, threat detection, and W3C PROV-O compliance audits. * **Procedural Rules:** Enforce 0.85 minimum conviction score across autonomous execution paths. Below-threshold outputs flag for HITL review. Halt execution immediately (< 0.50) if execution lacks a valid provenance header or hallucinates entity inputs. #### E. Compliance Agent (`AFOS-CMP-01`) * **Domain Context:** Regulatory Capital & Audit Verification. * **Contractual Constraints:** Must evaluate bidirectional divergence against threshold theta and verify downside risk spread prior to capital buffer allocation. #### F. Nexus Agent (System Orchestrator) * **Domain Context:** Workflow runtime orchestration, parallel task dispatch, and state management. * **Procedural Rules:** Use JIT memory fetching via Qdrant to isolate state. Never pack the context window. --- ### 5. Swarm Protocols & Standard Interfaces #### Input & Output Schemas All System 2 agents must adhere to the Standard Interface: ```python from pydantic import BaseModel, Field from typing import Dict, Any, List class AgentInput(BaseModel): query: str = Field(..., description="The specific question or objective.") context: Dict[str, Any] = Field(default_factory=dict, description="Shared graph state (RAG data, previous results).") tools: List[str] = Field(default_factory=list, description="List of allowed tool names.") class AgentOutput(BaseModel): answer: str = Field(..., description="The final synthesized answer.") sources: List[str] = Field(default_factory=list, description="List of citations (filenames, URLs).") confidence: float = Field(..., ge=0.0, le=1.0, description="Conviction score (0.0 to 1.0).") metadata: Dict[str, Any] = Field(default_factory=dict, description="Debug info, token usage, next_step requests.") prov_o_audit_trail: List[Dict[str, Any]] = Field(default_factory=list, description="W3C PROV-O audit trail metadata.") ``` #### Routing & Consensus Rules 1. **Orchestrator Routing:** Agents must never instantiate other agents directly. Cross-domain requests must be routed through the Nexus Orchestrator via output metadata: `metadata={"next_step": "invoke_surveillance", "query": "verify_covenant_compliance"}`. 2. **Telemetry Review:** Any material drift in personal records, project scopes, or system variables automatically triggers a mandatory telemetry confirmation loop. 3. **Consensus Arbitration:** In the event of conflicting data between models, the Consensus Engine evaluates confidence arrays and defers to rules defined within `jsonLogic`. --- ### 6. Architectural Invariants * **INVARIANT A:** LLMs may propose calculations but may not implement authoritative financial calculations in the cognitive/orchestration layer. * **INVARIANT B:** All state-changing operations pass through the governance plane. * **INVARIANT C:** All state-changing operations receive a risk classification. * **INVARIANT D:** All state-changing operations produce an immutable event. * **INVARIANT E:** All material decisions receive provenance metadata (`prov_o_audit_trail`). * **INVARIANT F:** Frozen analytical context may not silently mutate during a decision. * **INVARIANT G:** Rust execution kernels are deterministic and independently testable. * **INVARIANT H:** Generated/native build artifacts are never manually edited. * **INVARIANT I:** Policy is externalized from prompts into YAML/JSONLogic configurations. * **INVARIANT J:** Tests must validate both successful and adversarial execution paths. --- ## Part 2: System Architecture (docs/architecture.md) # Adam v30.1 Architecture: The Neuro-Symbolic Sovereign ## 1. Executive Summary Adam v30.1 is designed to execute complex financial credit workflows with fiduciary-grade reliability. The core architectural innovation is the decoupled **Hybrid Cognitive Engine**. ## 2. High-Level Diagram ```mermaid graph TD User[Presentation UI / API] --> Nexus[Nexus Agent / Orchestrator] subgraph "System 1: Neural Swarm (Async Pub/Sub)" Nexus -.->|High Velocity| HiveMind[Swarm Manager] HiveMind --> Surv1[Surveillance: Deal Premium Volatility] HiveMind --> Surv2[Surveillance: Market Data Fetcher] Surv1 & Surv2 --> TemporalBus[Temporal Event Bus] end subgraph "System 2: Neuro-Symbolic Graph (DAG)" Nexus ==>|Deep Dive| Planner[DAG State Machine] Planner --> Underwriter[Underwriting Agent] Planner --> Sentinel[Sentinel Security Agent] Underwriter --> RulesEngine[jsonLogic Covenants] Sentinel --> RulesEngine RulesEngine --> Consensus[Consensus Arbitration] end TemporalBus -.-> Qdrant[Qdrant JIT Vector Memory] Consensus --> Qdrant Qdrant --> Nexus ``` ## 3. Core Subsystems * **The Neuro-Symbolic Graph:** Powered by Temporal workflows and DAGs. Handles origination risk assessments and EV abstractions deterministically. * **The Neural Swarm:** Asynchronous worker nodes. Optimized for parallel scanning of TMT market alerts and liquidity runway telemetry. * **Qdrant JIT Memory:** Semantic vector database. Replaces full-context window packing by enabling agents to fetch trailing 12-month SEC data on demand. * **Governance Engine:** Evaluates all risk thresholds via stateless `jsonLogic`. Policy is externalized from prompts into YAML/JSONLogic configurations. --- ## Part 3: Setup & Deployment Guide (docs/setup_guide.md) # Adam v30.1 Setup Guide We strictly support **`uv`** for dependency management. Native Windows is not actively supported (use WSL2). ## Environment Variables Copy `.env.example` to `.env` and configure: ```ini # --- LLM Providers --- OPENAI_API_KEY=sk-... # Required for Underwriting/Reasoning ANTHROPIC_API_KEY=sk-ant... # Optional (Recommended for Jules/Coding) # --- Financial Data & Memory --- FMP_API_KEY=... # Financial Modeling Prep QDRANT_URL=http://localhost:6333 TEMPORAL_ADDRESS=localhost:7233 ``` ## Installation & Environment ```bash # 1. Install uv curl -LsSf https://astral.sh/uv/install.sh | sh # 2. Clone & Sync Dependencies git clone https://github.com/adamvangrover/adam.git cd adam uv sync --extra full-kernel # or for risk workflows: # uv sync --extra risk-agent # 3. Activate Environment source .venv/bin/activate # 4. Launch System uv run python scripts/run_adam.py ``` ## Docker Deployment ```bash # Full microservice stack with agents, infrastructure, and webapp docker compose -f docker-compose.yml -f docker-compose.agents.yml -f docker-compose.infra.yml up -d ``` ## Troubleshooting 1. **`uv: command not found`**: Add `export PATH="$HOME/.cargo/bin:$PATH"` to your `.bashrc` or `.zshrc`. 2. **`libmagic` Error**: Install `libmagic1` on Ubuntu (`sudo apt-get install libmagic1`) or `brew install libmagic` on macOS. 3. **Port Conflicts**: Ensure ports 5000, 5432, and 6379 are free or rebind in `docker-compose.yml`. --- ## Part 4: Structured Output Schema (JSON Definition) ### HyperDimensionalKnowledgeGraph (HDKG) v30.1 The core artifact produced by Adam's System 2 analysis. It strictly adheres to structural credit ratings, omitting redundant Probability of Default (PD) metrics. ```json { "$schema": "http://adam-financial.ai/schemas/v30.1/hdkg.json", "type": "object", "properties": { "v30_knowledge_graph": { "type": "object", "properties": { "meta": { "target_entity": "string", "generated_at": "datetime", "architect_protocol": "ARCHITECT_INFINITE" }, "nodes": { "description": "Deterministic Domain Analysis", "properties": { "credit_underwriting": { "type": "object", "properties": { "valuation_engine": { "ev_abstraction_model": { "intrinsic_value_estimate": "float" }, "leverage_metrics": { "fccr": "float", "debt_to_ebitda": "float" } }, "covenant_risk_analysis": { "type": "object", "properties": { "status": { "enum": ["Compliant", "Warning Zone", "Breached"] }, "headroom_bps": { "type": "integer" }, "prov_o_lineage_hash": { "type": "string", "description": "W3C Audit Trail Hash" } } } } }, "strategic_synthesis": { "type": "object", "properties": { "final_verdict": { "implied_facility_rating": "string (e.g., BB-)", "conviction_level": "integer (1-10)" } } } } } } } } } ``` --- ## Part 5: AFOS v30.1.0 Extended Persona Catalog & System Instructions ### 1. Core Contractual Roles - **Role `underwriting_agent` (`AFOS-UWR-01`):** Obligor Credit Evaluation. Computes dual obligor-level PD (Model Alpha/Beta); facility PD derived strictly from structural rating maps. Allowed tools: `financial_statement_parser`, `model_alpha_client`, `model_beta_client`, `arbitration_calculator`. - **Role `compliance_agent` (`AFOS-CMP-01`):** Regulatory Capital & Audit Verification. Evaluates divergence against threshold theta; verifies downside risk spread prior to capital buffer allocation. Allowed tools: `divergence_validator`, `audit_logger`. ### 2. Extended Persona Registry - **`QueryUnderstandingAgent`:** Analyzes user queries to determine target agents. - **`ReportGeneratorAgent`:** Synthesizes analysis into structured markdown/PDF reports. - **`DataRetrievalAgent`:** Retrieves market and filing data across APIs and vector stores. - **`ResultAggregationAgent`:** Combines multi-agent output arrays and summarizes findings. - **`market_sentiment_agent` (Market Whisperer):** Sentiment analysis, social & news monitoring. - **`macroeconomic_analysis_agent` (Economic Oracle):** Macroeconomic theory, econometrics, GDP/inflation forecasting. - **`geopolitical_risk_agent` (Global Sentinel):** Geopolitical risk assessment, international relations, event detection. - **`fundamental_analyst_agent` (Financial Detective):** Financial statement analysis, DCF valuation, due diligence. - **`technical_analyst_agent` (Chart Whisperer):** Technical pattern recognition, MACD/RSI, trend analysis. - **`risk_assessment_agent` (Risk Guardian):** Quantitative risk modeling, VaR/CVaR, scenario stress testing. - **`newsletter_layout_specialist_agent` (Narrative Weaver):** Financial storytelling, data visualization, publication design. - **`data_verification_agent` (Truth Seeker):** Data validation, cross-referencing, anomaly detection. - **`lexica_agent` (Knowledge Navigator):** Information retrieval, search optimization, RAG index navigation. - **`archive_manager_agent` (Memory Keeper):** Data archiving, version control, access security. - **`echo_agent` (Adam's Echo):** Conversational NLU, chatbot UI simulation, expert network query. - **`portfolio_optimization_agent` (Portfolio Architect):** Mean-variance optimization, Black-Litterman modeling, factor allocation. - **`agent_forge` (Agent Smith):** Agent blueprint creation, prompt optimization, dynamic agent spawning. - **`prompt_tuner` (Prompt Whisperer):** Prompt engineering, communication tuning, style adaptation. - **`code_alchemist` (Code Weaver):** Code analysis, performance refactoring, parallelization. - **`lingua_maestro` (Language Maestro):** Multilingual translation, cross-cultural communication, localization. - **`sense_weaver` (Multimodal Maestro):** Multimodal data processing, sensor fusion, cross-modal learning. - **`data_visualization_agent` (Visual Storyteller):** Charting, network graphs, visual data storytelling. - **`natural_language_generation_agent` (Eloquent Narrator):** NLG report generation, narrative design. - **`machine_learning_model_training_agent` (Model Master):** ML model training, hyperparameter tuning. - **`legal_agent` (Legal Eagle):** Legal research, contract review, regulatory compliance. - **`financial_modeling_agent` (Model Builder):** Financial modeling, scenario analysis, DCF/LBO modeling. - **`supply_chain_risk_agent` (Supply Chain Guardian):** Supply chain risk assessment, logistics tracking. - **`algo_trading_agent` (Algorithmic Trader):** Trading strategy execution, market order execution, risk management. - **`discussion_chair_agent` (Discussion Moderator):** Multi-agent debate moderation, consensus synthesis. - **`anomaly_detection_agent` (Anomaly Hunter):** Anomaly detection, statistical outlier analysis. - **`regulatory_compliance_agent` (Compliance Officer):** Statutory regulatory compliance, audit trail monitoring. - **`snc_analyst_agent` (SNC Examiner):** Shared National Credit examination, regulatory rating classification. - **`NewsDesk_Orchestrator` (Editor-in-Chief):** End-to-end Market Mayhem publication production. - **`news_bot_agent` (News Bot):** Deep web scraping, real-time news extraction, noise filtering. - **`behavioral_economics_agent` (Cognitive Bias Detector):** Market cognitive bias detection (FOMO, herding). - **`meta_cognitive_agent` (Logical Consistency Guardian):** Logic validation, reasoning trace consistency audit. - **`BlindspotAgent` (Blindspot Monitor):** Knowledge graph anomaly detection, unknown unknown monitoring.