Browser Action Execution with Playwright/Lux

Browser actions are executed via Playwright/Lux. Fast actions (navigate, simple click) take 500ms-1s. Complex actions (multiple steps, data extraction, Lux reasoning) take 1s-5s+. Lux inference speed is critical for live calls - using Gemini Flash helps optimize inference speed for real-time voice interactions.


Proprietary Intelligence Graph

Create a proprietary internal knowledge graph that connects disparate data points (e.g., identifying that a customer in a ChatGPT log is the same entity as a contact in the CRM). Rationale: Exporting gives raw text; staying provides interconnected intelligence that cannot be recreated easily.


Hyper-optimized Query Engine

Tune the FastMCP protocol and specific PostgreSQL/Qdrant/Redis stack into a hyper-optimized query engine. Rationale: The 'speed of thought' performance becomes a feature; querying raw exports on competitor systems is noticeably slower.


Enterprise Compliance Infrastructure

Initiate SOC 2 Type 1 audit immediately. Use Elestio infrastructure to offer data residency in US, EU, and APAC regions. Rationale: Trust and risk-mitigation are paramount for enterprise sales; compliance is the cost of entry.


Compounding Value Dashboard

Visualize the brain's growth with a dashboard displaying 'Memories Synced', 'Connections Formed', and 'Insights Discovered' as an exponential curve. Rationale: Users tangibly see the asset they are building, making it feel indispensable.


Proactive Insights Engine

The system actively generates alerts and reports, such as 'Sunaiva has learned that customers who mention Feature X are 75% more likely to churn.' Rationale: This makes the system feel alive, growing, and indispensable.


Sunaiva App Store Platform

Create an app marketplace with tiered API access (free read-only, paid read/write), a 15-20% revenue share, strict security vetting, and mandatory 'Powered by Sunaiva' co-branding. Rationale: Transforms the MCP into a platform, creating a self-reinforcing moat.


Progressive Deepening (6-Month Journey)

A 6-month lock-in journey: M1 (Connect 1 source -> Dashboard), M2 (Connect CRM -> Link to revenue), M3 (Connect P2 Widget -> Inherit brain), M4 (System suggests next step), M5 (Weekly insight emails), M6 (Introduce P3/P4 -> Deep integration).

Month 1: Connect one data source (e.g., ChatGPT history) for instant dashboard

Month 2: Connect CRM to link conversations to revenue

Month 3: Connect P2 Talking Widget to inherit brain

Month 4: System suggests next step (e.g., upload pricing PDF)

Month 5: Send automated weekly insight emails

Month 6: Introduce P3 Browser Agent and P4 Radar Audit


Enterprise Bus Factor Plan

A two-step trust plan: 1. Sign legal agreement with data escrow service for full export if Sunaiva fails. 2. Offer automated daily/weekly exports to customer's S3/Azure.

Data Escrow: Legal agreement for full export

Automated Backups: Daily/weekly exports to customer cloud


Ecosystem Entanglement

Every product (P2-P5) must become deeply dependent on the MCP's unique intelligence. The P2 Talking Widget inherits personality, not just facts. Rationale: Migrating away means re-training and re-configuring every agent from scratch.


The Business's Brain Frame

Frame the MCP as the company's persistent, shared brain. Marketing language should frame leaving as 'inducing corporate amnesia'. Rationale: Psychological lock-in makes switching feel like a loss of identity.


Service Layer Moat

The moat consists of three layers: 1. Intelligence Layer (proprietary derived data assets), 2. Managed Service (hosting, scaling, security), 3. Optimized Ecosystem (P2-P5 finely tuned to MCP). Rationale: Competitors can implement the protocol but cannot replicate the R&D, service, or entire product suite.


Memory Depth Score (MDS)

MDS = (Data Sources Connected) x (Data Volume) x (Integrated Apps) x (Daily Active Users). Rationale: Churn rate is inversely proportional to MDS.


Customer Lifetime Value (CLV) Trajectory

CLV evolves over time: Months 1-6 (~1.5x ACV), Months 7-12 (~3x ACV), Months 13-24+ (~5-7x ACV). The critical inflection point for 'lobotomy' switching costs is between months 9 and 12.


Highlight Emergent Intelligence

Use notifications to surface novel insights (e.g., 'Customers mentioning Feature X are 75% more likely to churn'). Rationale: This feels like the system is growing and learning, making it feel indispensable.


P2 Talking Widget Integration

The P2 Talking Widget should connect to the MCP to inherit the personality and context of past conversations, not just pull raw facts. Rationale: Creates deep dependency on the memory system.


Enrichment Pipeline

The 4-step data processing pipeline: 1. Ingest & Normalize (Raw logs), 2. Entity Extraction & Canonicalization (Merge variations like 'John Smith' and 'jsmith'), 3. Relationship Inference (Link entities like 'works_for'), 4. Temporal & Sentiment Analysis (Historical ledger). Rationale: Transforms raw logs into irreplaceable derived assets.


Multi-layered Defense-in-Depth Architecture

The system uses a multi-layered defense approach combining explicit intent declaration, real-time risk assessment, automated trust progression, and a Permission & Safeguard Engine (PSE) to balance capability with safety. This addresses the OpenClaw Permission Paradox by granting powerful capabilities incrementally without sacrificing real-time performance.


Capability-Based, Context-Aware, Risk-Tiered Permission System

Permissions are defined by Tool/Service, Operation Type (CRUD+), Resource Scope (Wildcard/Specific/Contextual), Risk Level (Tier 0-4), Context/Conditions, and Lease Duration. This allows granular control over what the agent can access and do.


Hybrid Static vs Dynamic Permission Approach

Base permissions are static and role-based, tied to agent maturity levels (L1-L4). Dynamic overlays allow contextual conditions (time, user request, previous actions) to modify permissions in real-time. This provides both stability and flexibility.


Constitutional Firewall as Absolute Veto Layer

The lowest-level, hardest-coded layer acts as circuit breakers with absolute vetoes: never delete more than N records without human confirmation, never expose PII without consent, never initiate financial transactions over $X without approval, never grant root SSH access.


Agent Intent Capability Checksum

Agents must propose actions in structured JSON format (e.g., { "tool": "PostgreSQL.delete", "args": {...} }) rather than natural language. The PSE validates this specific structured intent against permissions, preventing prompt injection bypass.


Maturity Progression Pathway L1 to L4

Agents progress through 4 maturity levels with increasing permissions and trust. Progression is based on quantifiable metrics including Successful Operation Count (SOC), Error Rate (ER), Safety Score (SS), Efficiency Score (ES), and Compliance Score (CS).

L1 (Basic): 100 successful ops in Simulation, permissions: Browser.navigate, Qdrant.search, PostgreSQL.read

L2 (Standard): SOC > 500, ER < 5%, SS = 100%, permissions: Browser.click, Browser.type, PostgreSQL.insert

L3 (Domain Expert): SOC > 1000, ER < 2%, ES > 80%, permissions: Browser.form_submit, PostgreSQL.update, API.send_email

L4 (Full Autonomous): SOC > 2000, ER < 0.5%, ES > 90%, permissions: PostgreSQL.delete, API.process_payment, SSH.execute


Pre-execution Validation Decision Flow

A 10-step decision flow for every agent action: Intent Capture -> Maturity Check -> Base Permission Check -> Contextual Policy Evaluation -> Risk Tier Assessment -> Constitutional Firewall Check -> Blast Radius Calculation -> Reversibility Enforcement -> Anomaly Detection -> Final Decision (ALLOW/ALLOW_WITH_LOGGING/ESCALATE/AUTO-BLOCK).

1. Agent Intent Capture (JSON format)
2. Maturity Check
3. Base Permission Check
4. Contextual Policy Evaluation
5. Risk Tier Assessment
6. Constitutional Firewall Check
7. Blast Radius Calculation
8. Reversibility Enforcement
9. Anomaly Detection
10. Final Decision


Permission Lease System Flow

When an agent needs elevated access, it sends a PermissionEscalationRequest to OpenClaw Orchestrator. PSE evaluates and either auto-approves (fast path for low-risk) or flags for human review (slow path). Leases are automatically revoked at expiration or if abuse is detected.

Agent identifies need for elevated access

Agent sends structured PermissionEscalationRequest with justification

PSE evaluates against maturity, context, history

Auto-Approval (Fast Path) for low-risk, short-duration

Human Approval (Slow Path) for high-risk

Lease automatically revoked at expiration or abuse detection


Permission Schema Structure

JSON schema defining permissions by tool with risk_tier (0-4), description, and conditions. Example: Browser.upload_file has risk_tier 3 with conditions for whitelist_domain and max_file_size_mb. PostgreSQL.delete has risk_tier 3 with conditions for table_whitelist, require_undo_mechanism, and max_rows_affected.


Risk Tier Classification System

Tier 0 (Informational): Read-only, low-impact (Browser.navigate, Qdrant.search). Tier 1 (Standard): Create/Update non-critical data (PostgreSQL.insert, API.webhook_trigger). Tier 2 (Sensitive): Create/Update critical data (PostgreSQL.update: customers.billing_info). Tier 3 (Dangerous): Delete operations, financial transactions (PostgreSQL.delete, Stripe.charge). Tier 4 (Critical): System-level changes, code execution (SSH.execute, VPS.reboot).


Maturity Level Permission Bundles

L1: Browser.navigate, Qdrant.search, PostgreSQL.read: customers.leads. L2: Browser.click, Browser.type, PostgreSQL.insert: leads, API.get_customer_info. L3: Browser.form_submit, PostgreSQL.update: customers, API.send_email, File.read: config/*.json. L4: PostgreSQL.delete: leads_archive, API.process_payment (max_amount: 500), SSH.execute (whitelisted commands only).


Minimum Stays and Probationary Periods

L1: Minimum 1 day or 100 successful low-risk ops in sandbox/dev. L2: Minimum 3 days with 24h probation. L3: Minimum 7 days with 24h probation. L4: Minimum 14 days with 48h probation. Any significant error during probation leads to immediate demotion.


Canary Deployment for High-Risk Operations

For L3/L4 agents or new high-risk features, use shadow mode where risky operations execute in a non-production canary environment in parallel. Results are compared - if canary would cause error, real action is blocked/escalated. Part of maturity progression with X canary tests required.


Maturity-Based Trust Earning System

The system creates a defensible competitive advantage through quantified trust progression. Agents must earn permissions through demonstrated competence (SOC, ER, SS, ES, CS metrics) rather than receiving blanket access. This creates a high barrier to entry for competitors and ensures predictable, safe behavior.


Constitutional Firewall as Irreversible Safety Net

Hard-coded absolute vetoes (never delete N records without human confirmation, never expose PII without consent, never process financial transactions over $X without approval) provide safety guarantees that are difficult for competitors to replicate without similar architectural investment.


Telnyx WebRTC to AIVA Connection

Telnyx WebRTC handles Voice Input/Output and connects bidirectionally to AIVA (Agent Core) which uses Claude/Gemini/LLM. This is the primary voice interaction channel for the Genesis system.


AIVA to OpenClaw Orchestrator (MCP) Connection

AIVA (Agent Core) connects to OpenClaw Orchestrator via MCP (Model Context Protocol). OpenClaw is the Primary Decision Point handling Permission & Safeguard Engine (PSE), Maturity Manager (MM), and Constitutional Firewall.


OpenClaw to Tool Service Layer Connection

OpenClaw Orchestrator connects to Tool Service Layer which includes Tool-Specific Validators. This layer handles external system calls to Browser, DB, API, and SSH services.


Tool Service Layer to External Systems

Tool Service Layer connects to: PostgreSQL/Qdrant (Data/Memory), Elestio VPS (Filesystem/SSH), Stripe/GoHighLevel (APIs), AIVA's Mac Mini (SSH/Remote Code). These are the actual resources the agent can access.


Human Oversight Console Integration

Human Oversight Console connects to the main architecture for dashboards, alerts, and approvals. Agents can escalate to this console for human confirmation on high-risk operations, and the console provides monitoring of all agent activities.


Granularity Progression Strategy

Start coarse-grained (tool level: Browser, PostgreSQL) at L1, then refine to method level (Browser.click, Browser.type) at L2, then to argument-level conditions (Browser.click: button_id='submit_order') at L3/L4. This matches the maturity progression and prevents over-permissioning early on.


Self-Adjustment and Demotion Logic

The RLM (Reinforcement Learning from Memory) framework feeds performance data into the Maturity Manager. Anomaly-triggered demotion occurs on sudden spike in error rate or unusual permission requests. Catastrophic incidents cause instant demotion to L1 or quarantined state. Probationary failures cause automatic demotion.


Maturity Progression Rubric Criteria

L1 advancement: 100 successful operations in Simulation. L2: SOC > 500, ER < 5%, SS = 100%, CS = 100%. L3: SOC > 1000, ER < 2%, SS = 100%, ES > 80%, CS = 100%. L4: SOC > 2000, ER < 0.5%, SS = 100%, ES > 90%, CS = 100%.


Permission Dependencies Resolution

The PSE implicitly resolves dependencies - if PostgreSQL.update is requested, PostgreSQL.read for the target resource is implicitly assumed/granted for the agent's internal reasoning, but read is not separately permissioned unless explicitly stated. The system tracks effective permissions.


Cold Start - Founder's Fleet Strategy

Begin with a curated 'Founder's Fleet' of 3-5 seed agents targeting high-pain, high-ROI verticals like local services (trades, med spas). Use the P2 Voice Agent as the initial 'killer app' and the P4 Radar Audit tool to identify and pre-qualify leads in these verticals.

Select 3-5 high-pain local service verticals (e.g., trades, med spas)

Configure P2 Voice Agent as the core offering

Deploy P4 Radar Audit to identify businesses with poor call handling

Launch via direct sales and initial agency partners


Marketplace Subscription Tiers & Revenue Share

Implement a tiered monthly subscription model: $397, $597, and $997 per month, plus a one-time setup fee. Direct sales yield 100% revenue. Partner sales operate on a 70/30 split, with Genesis retaining 70% of the recurring revenue.


High-ROI Value Proposition

Target local service businesses where a single missed call can result in a $1,000+ job. This provides an immediate 10x ROI, framing the AI agent as a revenue generator rather than a cost, leveraging the acute pain of missed leads.


GHL Snapshot as Packaging Standard

Adopt GoHighLevel (GHL) Snapshot as the de facto standard for packaging agents. This 'build once, sell forever' model ensures quality control by packaging the entire agent configuration—AI settings, CRM automations, funnels, websites, and permissions—into a single, deployable template.


GHL Snapshot Contents

A snapshot is a directory of JSON, SQL, and files containing: Metadata (agent name, version), Permissions (scopes like calendar/SMS access), Business Logic (CRM workflows, triggers), Configuration (API keys, AI models like 'Sydney Stack'), and UI (websites, landing pages). It supports rollback.


Data Network Effect

Deploying multiple agents in a vertical (e.g., 100 'AI Plumber' agents) generates data on high-converting conversational flows. This data improves the master template, instantly benefiting all 100 agents. This creates a moat where more clients make the agents smarter and more effective than any competitor can match.


Agency Channel Evolution

Scale growth through agency partners by implementing a Reseller model first, then evolving to White-Label for trusted partners. The technical complexity of the underlying stack (P1-P4) combined with a 30% recurring commission makes partnership more profitable than building in-house.

Onboard initial agency partners (38 target)

Implement 30% recurring commission structure

Enable Reseller model for standard partners

Enable White-Label model for trusted partners


Templated Storefront System

Manage 73 domains as a single templated system using GHL. Create a master website snapshot optimized for conversion. For each domain, deploy the master snapshot and customize only the content (logo, headline). Conduct A/B tests on the master to propagate winning variations across all domains.


3-Year Platform Evolution Roadmap

The platform will evolve through three distinct phases: Curated (Franchise), Open (Channel), and Platform (API).

Year 1 (Curated): Perfect 5-10 vertical-specific snapshots, focus on MRR and active clients

Year 2 (Open): Scale agency reseller program, onboard 38 partners, introduce Certified Partner program

Year 3 (Platform): Abstract core tech (P1, P2, P3) into public API, allow external developers to build agents


Fusion Differentiator vs DIY Tools

Position Genesis as a 'Done-for-you' AI Employee (fusing Voice, Browser, and Memory) versus Zapier's 'Do-it-yourself' toolkit. The unique advantage is selling a fully-trained, autonomous employee that comes pre-integrated with these capabilities, targeting business owners who want solutions to business problems, not technical tools.


Genesis Stack Integration (P1-P3)

The core differentiator is the integration of P1 Memory, P2 Voice, and P3 Browser into a cohesive 'AI Employee' solution. This fusion allows the agent to remember, speak, and act (via browser), unlike standalone voice or automation tools.


Event Sourcing + CQRS Architecture

All state changes are captured as events in an append-only log (Event Bus using Redis Stream + PostgreSQL), with a separate read model (Session DNA) optimized for fast boot. This separates write concerns (capturing every detail) from read concerns (fast context loading), enabling state reconstruction, time-travel queries, and zero information loss.


Session DNA Compact Snapshot

Session state is compressed into a YAML file under 2K tokens (vs 80K current boot tax) containing only essential information: session_id, active_mission, state_summary, next_actions, blockers, conversation_state, and context_pointers. This single file is the ONLY file loaded on respawn, reducing boot tax from 40% to <5%.


Decoupled Agent Lifecycle

Agents run as persistent worker processes in a Redis Queue, completely decoupled from the Claude session lifecycle. When a session respawns, agents continue running in the background and write results to an Agent Mailbox (Redis + PostgreSQL). The new session picks up completed results seamlessly, achieving 100% agent survival vs 0% currently.


Tiered Memory Architecture

Three-tier memory system: Hot (Session DNA <2K tokens, always loaded), Warm (Last 3-5 sessions in PostgreSQL, query on-demand), Cold (Full history in Qdrant, Supermemory, S3). This enables lazy loading—most conversations don't need full history, so don't pay the token cost upfront.


15-Phase Implementation Roadmap

Full phased rollout from database schema to full Tapestry mode: Phase 1-2 (Event Bus + schema), Phase 3-5 (Session DNA generator + hooks), Phase 6-10 (Agent Mailbox + workers + testing), Phase 11-15 (MEMORY.md auto-curation + tiered queries + MCP server + user acceptance).

Phase 1: Implement database schema (create 5 tables)

Phase 2: Implement Event Bus (Redis Stream + PostgreSQL logger)

Phase 3: Implement Session DNA generator

Phase 4: Update PreCompact hook (flush events before compaction)

Phase 5: Create SessionStart hook (load DNA, greet user)

Phase 6: Implement Agent Mailbox (Redis + PostgreSQL sync)

Phase 7: Implement Agent Execution Engine (Redis queue workers)

Phase 8: Implement Session DNA Projector (event → DNA updater)

Phase 11: Implement MEMORY.md auto-curation

Phase 12: Implement tiered memory queries

Phase 13: Implement MCP server for session state

Phase 15: Deprecate old handoff files, full Tapestry mode


Boot Tax Reduction Metrics

Current state: 80K tokens (~40% of context) boot tax, ~30 seconds load time. Target state: <10K tokens (<5%), with actual target of 3K tokens (1.5%). Reduction: 140K → 3K tokens (97% reduction). User re-orientation moments reduced from ~3/session to 0.


Infrastructure Cost Analysis

Total infrastructure cost: ~$1/month. PostgreSQL: $0 (already on Elestio). Redis: $0 (already on Elestio). Qdrant: $0 (already on Elestio). Supermemory: $0 (free tier). FalkorDB: $0 (self-hosted). S3 storage (snapshots): ~$1/mo for 1GB at $0.02/GB. Compute (background workers): $0 (same Elestio VPS). Well under $5/mo constraint.


Database Schema (5 Tables)

PostgreSQL schema includes: session_events (event sourcing log with event_id, session_id, event_type, payload JSONB, metadata, created_at), session_dna (read model snapshots with dna_id, session_id, dna_content YAML, version), agent_manifest (central registry with agent_id, task_description, status, story_id, heartbeat, result_summary JSONB), agent_results (durable outputs with result_id, agent_id FK, status, payload JSONB), workflow_sagas (multi-session workflows with workflow_id, workflow_type, current_step, state JSONB, status).


Session DNA YAML Structure

YAML structure under 2K tokens: session_id, previous_session, active_mission, state_summary (status, agents running/completed/failed, progress_percent), next_actions (array), blockers (type, item, status), conversation_state (tone, rapport_level, active_threads, interrupted_exchange), context_pointers (agent_manifest, session_history, knowledge_graph, full_handoff_log), version, timestamp, dna_hash.


pre_compact_hook() Function

Pseudocode: Before context compaction, analyze conversation transcript, extract decisions, blockers, agent dispatches, interrupted exchanges. Publish events to Event Bus (STRATEGIC_DECISION_LOCKED, BLOCKER_ENCOUNTERED, etc.). Force Session DNA update. Snapshot full conversation to cold storage. Result: Zero state loss despite compaction.


session_start_hook() Function

Pseudocode: On new session start, load data/session_dna.yml ONLY (2K tokens). Check Agent Mailbox for completed agents. Update DNA in-memory with completed agents. Synthesize greeting from DNA: 'Resuming session 24. Awaiting user input on 6 blockers.' Inject DNA YAML into context. Result: <5% boot tax, seamless continuity.


update_session_dna() Background Projector

Pseudocode: Subscribe to Event Bus. For each event, load latest DNA. Apply event to DNA (e.g., BLOCKER_ENCOUNTERED → append to blockers list). Save updated DNA. Result: Session DNA is always up-to-date snapshot reflecting latest events.


Information Density Through Event Sourcing

Event sourcing provides a defensibility mechanism: by storing every state change as an event (not just snapshots), the system can replay to rebuild state at any point, debug exactly what happened, support time-travel queries ('what was state at 14:30?'), and never lose information. This creates a complete audit trail that's difficult for competitors to replicate without similar infrastructure.


Invisible Session Respawns

The system makes session boundaries invisible to the user—Kinan experiences ONE continuous conversation regardless of respawns. This creates a superior user experience (95%+ continuity perception vs ~50% currently) that would be difficult for competitors to match without similar architectural investment in Session DNA and decoupled agent execution.


Event Bus Integration (Redis + PostgreSQL)

Event Bus uses Redis Stream for real-time event processing and PostgreSQL for durability. All state changes = events (AGENT_DISPATCHED, DECISION_MADE, BLOCKER_ENCOUNTERED, AGENT_COMPLETED). Redis handles real-time consumption, PostgreSQL provides append-only log for reconstruction.


Agent Mailbox Integration

Completed agent results written to Redis (fast access) and archived to PostgreSQL (durability). New session picks up results by polling the Agent Mailbox, updating its in-memory DNA with completed agent information. This bridges the gap between persistent agent workers and ephemeral session lifecycles.


Context Pointer System

Session DNA contains context_pointers linking to external systems: agent_manifest (mcp://genesis-session/agents/manifest), session_history (mcp://genesis-session/query_session_history), knowledge_graph (falkordb://query), full_handoff_log (file://hive/progress/session_23_handoff.md). These enable lazy-loading of deeper context when needed.


Session Continuity Tapestry System

A system designed to make Genesis session respawns invisible to the user, reduce boot tax from 40% to <5%, and preserve 100% of agent and conversational state across session boundaries. Core innovation: Event Sourcing + CQRS + Tiered Memory + Decoupled Agent Execution. Targets: <10K tokens boot tax, <5 seconds boot time, 100% agent survival, >95% session continuity perception.


Seamless Respawn Experience

By synthesizing greetings from Session DNA ('Resuming session 24. Awaiting user input on 6 blockers.') and tracking interrupted_exchange state, the system eliminates user re-orientation moments (~3 per session currently). Users experience zero friction from respawns, maintaining psychological flow and trust in the AI assistant.


Mid-Sentence Continuity Tracking

Session DNA tracks interrupted_exchange state (user_spoke, agent_was_replying), enabling the system to resume conversations from exactly where they were interrupted. This preserves conversational context that would otherwise be lost, making respawns truly invisible.


Event Sourcing & CQRS for Session State

The architecture uses Event Sourcing and CQRS to decouple agent execution from the session lifecycle. All state-changing actions are published as events to a Redis Stream for real-time processing and logged to PostgreSQL for durability, creating a reliable 'Write Model' that can be projected into various 'Read Models' like the Session DNA.


Tiered Memory Model (Hot/Warm/Cold)

The system implements a tiered memory model: Hot (Session DNA injected into context), Warm (recent events in PostgreSQL), and Cold (full archives in Qdrant, Supermemory, S3). This optimizes context usage by keeping only the most critical state in the active context.


Agent Execution via Redis Queue

Agents are dispatched as tasks to a Redis queue and executed by independent, persistent worker processes. This ensures agents survive session termination and can complete long-running tasks even if the user disconnects.


Session DNA Specification

The Session DNA is a compact (<2K token) YAML file acting as the 'Hot Memory'. It contains session_id, active_mission, state_summary (status, agents running/completed), next_actions, blockers, conversation_state (tone, rapport, interrupted_exchange), and context_pointers to warm/cold storage.


Database Schema for Session Continuity

PostgreSQL schema includes: session_events (event sourcing log), session_dna (read model snapshots), agent_manifest (registry of agents/status), agent_results (durable storage for agent outputs), and workflow_sagas (multi-session workflow state).


Pre-Compact Hook Logic

The pre_compact_hook() analyzes the conversation transcript to extract decisions, blockers, and agent commands, publishes them as events to the Event Bus, forces a Session DNA update, and snapshots the full conversation to cold storage before context compaction.


Session Start Hook Logic

The session_start_hook() loads the Session DNA (the only major context-loading step), checks the Agent Mailbox for completed agents, synthesizes a greeting from the DNA, and injects the summary into the LLM context to achieve low boot tax.


Session Respawn Data Flow

The sequence for session respawn involves: 1. SessionStart Hook triggers, 2. Load Session DNA (reducing boot tax), 3. Inject DNA into context, 4. Synthesize greeting from DNA, 5. Check Mailbox for completed agents, 6. Lazy load from Warm/Cold memory if needed.


Reduced Context Boot Tax

The architecture reduces the context 'boot tax' from 40% to under 5% by using a compact Session DNA YAML file instead of loading full conversation history, providing a significant performance and cost advantage.


100% State Preservation

The Event Sourcing model ensures 100% of agent and conversational state is preserved across session terminations, allowing seamless resumption and long-running agent tasks.


Event Bus (Redis Stream & PostgreSQL)

The Event Bus integrates Redis Stream (for real-time processing) and PostgreSQL (for durability). All state-changing actions are published here and consumed by the Session DNA Projector to update the read model.


Agent Mailbox (Redis to PostgreSQL)

Completed agent results are written to a Redis Hash for fast retrieval and then archived to a PostgreSQL agent_results table, ensuring both speed and durability.


Session DNA Token Size

The Session DNA is designed to be compact, using less than 2K tokens, significantly reducing the context window usage and associated costs compared to loading full session history.


Synthesized Status Greeting

Instead of reading multiple large files, the agent synthesizes a status update greeting directly from the Session DNA. This provides a coherent entry point for the user and maintains narrative continuity.


Lazy Loading for Context

As the conversation progresses, if the user asks about something not in the Hot Memory (Session DNA), the agent queries the Warm (PostgreSQL) or Cold (Qdrant/Supermemory) memory tiers on-demand. This prevents overwhelming the context window while retaining access to full history.


Session Continuity Tapestry

A comprehensive architecture solution to the session continuity problem in the Genesis system. It is designed to make session respawns seamless, reduce context boot tax to under 5%, and ensure 100% of agent and conversational state is preserved using Event Sourcing and a tiered memory model.


Shift to CP (Consistency/Partition Tolerance) System

Genesis will shift from prioritizing Availability and Partition Tolerance (AP) to Consistency and Partition Tolerance (CP) during state handoffs. This ensures every new session is a state-consistent successor, eliminating 'session amnesia' and guaranteeing the user interacts with an agent possessing a complete, correct project history.


Event Sourcing as Single Source of Truth

The core architectural choice is to use an append-only event log in PostgreSQL as the definitive source of truth. Instead of saving final state, every change (decision, blocker, code generation) is saved as an event. The current state is a pure function of replaying these events, ensuring perfect historical fidelity and deterministic reconstruction.


Raft-Inspired Leader Election using Redis

To prevent split-brain scenarios where multiple sessions corrupt shared state, Genesis implements a strict leader election protocol using Redis distributed locks. Only the session holding the Redis lock (the 'Leader') can write to the event log, ensuring serializability of writes.


Vector Clocks for Causality Validation

To ensure state reconstruction is accurate, every event in the log will contain a Vector Clock. This allows new sessions to validate that they have received a complete history of events and detect any causal anomalies (e.g., missing events).


CRDTs for In-Memory State Management

In-memory state objects (like active agents or blockers) will be modeled as Conflict-free Replicated Data Types (CRDTs), such as OR-Sets (Observed-Remove Sets) and LWW-Registers (Last-Write-Wins). This ensures that even if events are applied out of order, the final state remains consistent.


Saga Pattern for Multi-Session Projects

Long-running tasks (e.g., 'Ship Talking Widget') will be tracked as 'Sagas' using a unique saga_id in the event log. This allows state machines to reconstruct the exact step of a project, identify failures, and trigger compensating actions (rollbacks) across sessions.


PostgreSQL Event Log Schema

Implementation of the `session_events` table in PostgreSQL with columns: event_id (BIGSERIAL), session_id (UUID), saga_id (UUID), event_type (VARCHAR), payload (JSONB), vector_clock (JSONB), and committed (BOOLEAN). Indexes on session_id and saga_id are required for fast retrieval.


Redis Lock Acquisition Protocol

Session start protocol: Generate unique session_id -> Attempt to acquire lock via `SET genesis:active_session_lock <session_id> NX EX 7200`. Success promotes to Candidate. Failure implies another session is active. The leader must heartbeat to refresh TTL.


State Reconstruction Workflow

The 5-step recovery process for a new session: (1) Acquire Redis Lock, (2) Query latest snapshot from `session_snapshots`, (3) Replay all events from log after snapshot's last_event_id, (4) Validate Vector Clock against prior session's clock, (5) Promote to Leader and accept user input.


Quorum-Based Write Strategy

To ensure durability, a Write Quorum (W=3) is defined across N=5 systems (Postgres, Redis, Qdrant, Supermemory, FalkorDB). An event is only marked `committed=TRUE` in Postgres after propagating to at least 2 secondary systems, ensuring critical state changes are durable.


Gossip Protocol for Reconciliation

A background 'Gossip/Repair Agent' runs periodically (e.g., every 60s), reads committed events from Postgres, and checks other systems (Qdrant, FalkorDB) for consistency. If systems are missing data, the agent triggers a repair/update to ensure eventual consistency.


Session Lifecycle: Candidate to Leader to Shutdown

Ordered phases of a Genesis session: Start -> Acquire Redis Lock (Candidate) -> Reconstruct State -> Promote to Leader -> Active User Interaction -> Graceful Shutdown (Append 'session_terminated', Delete Lock). If crash occurs, lock expires (TTL) allowing next session to seize leadership.

Start Session
Acquire Redis Lock (Candidate Election)
Load Snapshot & Replay Events
Validate Vector Clock
Promote to Leader
Handle User Input
Graceful Shutdown (Release Lock)


Elimination of Session Amnesia

The primary competitive advantage is solving 'session amnesia'. By ensuring perfect memory and context continuity across sessions, Genesis provides a seamless user experience that competitors relying on stateless or simple context windowing cannot match.


Technical Complexity as Defensible Barrier

Implementing a robust consensus system combining Raft-style leadership, Event Sourcing, CRDTs, and Vector Clocks is architecturally complex and difficult to replicate. This creates a high engineering barrier to entry for competitors.


PostgreSQL to Qdrant/Supermemory (Embeddings)

The PostgreSQL event log replicates data to Qdrant and Supermemory. This allows the system to perform similarity search and maintain embedding-based memory of the project's evolution for retrieval-augmented generation.


PostgreSQL to FalkorDB (Knowledge Graph)

The event log replicates structural data to FalkorDB (a graph database). This maintains a causal knowledge graph of the project, allowing the agent to reason about relationships between decisions, code, and blockers.


PostgreSQL to Redis (Cache & Lock)

PostgreSQL replicates events to Redis to serve as a fast Active State Cache and maintain the Leader Election Lock mechanism, ensuring fast read access and coordination.


Project Continuity Feature Specification

The 'Project Continuity' product is defined by these capabilities: (1) Consensus-based state management, (2) Event sourcing for auditability, (3) Deterministic state reconstruction via snapshots, (4) Vector clock validation, (5) Leader election to prevent split-brain, (6) Saga pattern for multi-session workflows, and (7) Gossip protocol for eventual consistency.


Session DNA Format: JSON over YAML

JSON is chosen for the Session DNA format due to its token efficiency, strictness to reduce parsing errors, and ubiquitous library support in Python.


Three-Tier Memory Architecture

The system uses Hot Memory (In-Prompt <2K tokens, includes Session DNA), Warm Memory (On-Demand Redis <10ms, last 50 events), and Cold Memory (Semantic Search PostgreSQL/Qdrant >10ms) to optimize token usage.


Agent Queue Implementation: Redis Lists

Agents are decoupled from the session using Redis Lists as a task queue, with a persistent worker process, ensuring agents survive session respawns.


Zero-Boot Protocol Steps

The new protocol reduces boot context from 80K to <10K tokens: 1. Load static rules (~8K tokens). 2. Call on_session_start() to fetch DNA and reconstruct state. 3. Generate curated <200 line MEMORY.md. 4. Inject DNA and memory (~1.5K tokens).

Load GLOBAL_RULES.md and CLAUDE.md (~8K tokens)

Inject DNA and curated memory into prompt (~1.5K tokens)


5-Week Migration Plan

Phased rollout plan: Week 1 (Passive Instrumentation), Week 2 (Build Core Components), Week 3 (Activate Agent Survival), Week 4 (Beta Test Zero-Boot), Week 5 (Full Rollout).

Week 2: Develop MCP server, DNA logic, Redis queue

Week 3: Reroute agent dispatching, verify restart survival

Week 4: Implement new boot logic, A/B test

Week 5: Make Zero-Boot default, deprecate old handoff


Session DNA Zero-Boot Capability

The Session DNA allows resuming sessions with <10K tokens instead of 80K, reducing boot overhead from 40% to under 5%, creating a seamless 'Invisible Seams' experience for the user.


Infrastructure Cost: $0 Additional

The architecture runs on existing Elestio stack (PostgreSQL, Redis, Qdrant). Marginal increase in storage is within limits, meeting the <$5/mo constraint. Performance targets: DNA load <200ms, Event persist <50ms.


Invisible Seams User Experience

UX strategy to make session boundaries undetectable: synthesized proactive greeting from DNA, warning at 80% context, and mid-sentence continuity via snapshot saved to Redis.


Event Sourcing: PostgreSQL & Redis

Dual-write strategy for state: Events are written to PostgreSQL (durable primary) and simultaneously XADDed to a Redis Stream (hot cache) with TTL for fast state reconstruction on respawn.


FalkorDB Knowledge Graph Update

On DECISION_MADE events, the system updates the FalkorDB knowledge graph, creating relationships between entities (e.g., FastAPI-[:IS_CHOSEN_FOR]->Talking Widget).


Session DNA JSON Schema

Draft-07 JSON Schema defining the structure of the Session DNA, including schema_version, session_id, mission (objective, status), conversation (tone, rapport_level), agents (status, heartbeat), state (decisions, blockers), and plan.


PreCompact Hook Logic

Hook triggered near context limit: Scans conversation for keywords (I decide, blocked by), generates structured events (DECISION_MADE), injects breadcrumbs ([Decision D-124]...), saves snapshot to Redis, updates DNA.


Agent Mailbox Pattern Workflow

Agent survival workflow: Genesis LPUSHes task to Redis List 'agent_task_queue' -> Worker BRPOPs and executes -> Worker HSETs result to 'agent_results_store' -> Genesis checks 'active_agents' table and picks up result.


MEMORY.md Auto-Curation Algorithm

Python pseudocode function generate_curated_memory(dna) that iterates over DNA fields (Mission, Blockers, Decisions, Plan) to produce a <200 line MEMORY.md file.


MCP Server (Session State Manager) Endpoints

FastAPI server with endpoints: GET /dna/{session_id}, POST /dna/{session_id}, POST /events/{session_id} to manage state.