{
  "meta": {
    "title": "Dyva Brain System Map",
    "version": "2026.07.30",
    "asOf": "2026-07-30",
    "scope": "The current Dyva and Staged cognitive runtime across Discord, web chat, voice, tools, memory, background cognition, continuity, and safety.",
    "audience": "Engineers, safety reviewers, architecture reviewers, and external models evaluating the design.",
    "disclosure": "Sanitized public edition. It omits credentials, live IDs, origin details, privileged policy mechanics, and private user data.",
    "epistemicBoundary": "The system implements increasingly agentic software functions. This map does not claim or certify consciousness, subjective experience, or moral-patient status."
  },
  "thesis": [
    "Dyva is an agent runtime around interchangeable language models, not a single prompt or a thin provider wrapper.",
    "Its behavior emerges from three coupled loops: the live conversation loop, the ambient social-cognition loop, and the persistent self-and-memory loop.",
    "The strongest current capabilities are contextual recall, cross-surface action routing, provider failover, durable memory, and gated background initiative.",
    "The central architectural weakness is coordination: several capable loops share state but do not yet operate through one typed, transactional executive control plane."
  ],
  "systemFlow": [
    "Surface event",
    "Identity and trust resolution",
    "Perception and context assembly",
    "Memory and world-state retrieval",
    "Reply and capability planning",
    "Model routing and generation",
    "Tool execution with authority checks",
    "Output integrity and delivery",
    "Durable writeback and outcome learning",
    "Background consolidation and initiative"
  ],
  "loops": [
    {
      "id": "conversation",
      "name": "Live conversation and action loop",
      "trigger": "A user message, voice utterance, or service request.",
      "purpose": "Produce one grounded response or action while preserving identity, privacy, permissions, and conversational continuity.",
      "status": "shipping",
      "steps": [
        {
          "id": "ingress",
          "name": "Normalize ingress",
          "purpose": "Resolve the surface, speaker, conversation, attachments, reply context, and trusted bridge metadata.",
          "inputs": [
            "Discord or web event",
            "Authenticated session",
            "Attachments"
          ],
          "outputs": [
            "Canonical turn",
            "Trusted actor and scope"
          ],
          "controls": [
            "Authentication",
            "Rate limits",
            "Bridge-context trust"
          ],
          "evidence": [
            "ts-api/src/discord/events.ts",
            "ts-api/src/discord/bridge.ts",
            "ts-api/src/http/routes/conversations.ts"
          ]
        },
        {
          "id": "context",
          "name": "Compose working context",
          "purpose": "Combine recent dialogue, persona, room state, relationships, memories, goals, operator steers, and available capabilities.",
          "inputs": [
            "Canonical turn",
            "PostgreSQL state",
            "Redis state"
          ],
          "outputs": [
            "Bounded model context",
            "Turn context capsule"
          ],
          "controls": [
            "Visibility scope",
            "Prompt-injection boundaries",
            "Context budgets"
          ],
          "evidence": [
            "ts-api/src/http/routes/conversations.ts",
            "ts-api/src/dyva/turn-context-capsule.ts",
            "ts-api/src/discord/cognition/context-builder.ts"
          ]
        },
        {
          "id": "plan",
          "name": "Decide and plan",
          "purpose": "Choose whether to speak, ask, research, remember, moderate, or remain silent; bind tool intent to the live registry.",
          "inputs": [
            "Working context",
            "Capability registry",
            "Cooldown state"
          ],
          "outputs": [
            "Reply draft",
            "Action or tool plan",
            "Risk assessment"
          ],
          "controls": [
            "Silence floor",
            "Planner review",
            "Channel action policy"
          ],
          "evidence": [
            "ts-api/src/discord/chat/capability-planner.ts",
            "ts-api/src/discord/cognition/brain.ts",
            "ts-api/src/discord/cognition/autonomy-foundation.ts"
          ]
        },
        {
          "id": "generate",
          "name": "Route inference",
          "purpose": "Select a configured provider and model, stream the response, and fail over on eligible infrastructure failures without policy shopping.",
          "inputs": [
            "Prompt",
            "Messages",
            "Tool schemas",
            "Runtime policy"
          ],
          "outputs": [
            "Tokens",
            "Native tool events",
            "Usage receipts"
          ],
          "controls": [
            "Provider health",
            "Durable fallback state",
            "Policy-refusal semantics"
          ],
          "evidence": [
            "ts-api/src/llm/chat-router.ts",
            "ts-api/src/llm/flash-with-fallback.ts",
            "ts-api/src/agent-runtime/"
          ]
        },
        {
          "id": "act",
          "name": "Execute and deliver",
          "purpose": "Authorize tool calls, perform effects, turn receipts into grounded prose, and persist only confirmed delivery.",
          "inputs": [
            "Tool plan",
            "Actor authority",
            "Provider result"
          ],
          "outputs": [
            "Discord or web effect",
            "Execution receipt",
            "Reply"
          ],
          "controls": [
            "Registry-declared authority",
            "Idempotency",
            "Settlement and rollback"
          ],
          "evidence": [
            "ts-api/src/discord/tools/protocol.ts",
            "ts-api/src/discord/tools/executor.ts",
            "ts-api/src/agent-runtime/tool-runner.ts"
          ]
        },
        {
          "id": "learn",
          "name": "Write back and learn",
          "purpose": "Persist the exchange, extract scoped memories and relationships, update mood and open threads, and score later outcomes.",
          "inputs": [
            "Delivered reply",
            "Turn evidence",
            "Execution receipts"
          ],
          "outputs": [
            "Messages",
            "Memories",
            "Reflections",
            "Outcome records"
          ],
          "controls": [
            "Memory enablement",
            "Privacy visibility",
            "Grounding validators"
          ],
          "evidence": [
            "ts-api/src/dyva/character-memory.ts",
            "ts-api/src/dyva/introspection.ts",
            "ts-api/src/dyva/knowledge-graph.ts"
          ]
        }
      ]
    },
    {
      "id": "ambient",
      "name": "Ambient social-cognition loop",
      "trigger": "A scheduled round-robin tick or a throttled perception event.",
      "purpose": "Notice a live room without a direct request, decide whether intervening adds value, and usually remain silent.",
      "status": "shipping",
      "steps": [
        {
          "id": "probe",
          "name": "Probe eligible surfaces",
          "purpose": "Round-robin across Discord, web rooms, voice rooms, calls, and SMS adapters.",
          "inputs": [
            "Surface registry",
            "Activity state",
            "Allow lists"
          ],
          "outputs": [
            "Eligible candidate"
          ],
          "controls": [
            "Feature flag",
            "Quiet hours",
            "Per-surface kill switch"
          ],
          "evidence": [
            "ts-api/src/dyva/cognition/global-scheduler.ts",
            "ts-api/src/dyva/cognition/registry.ts",
            "ts-api/src/dyva/cognition/adapters/"
          ]
        },
        {
          "id": "observe",
          "name": "Build room observation",
          "purpose": "Measure momentum, participation, tension, ignored users, callbacks, mood, and stage state.",
          "inputs": [
            "Recent shared messages",
            "Room state",
            "Callback memory"
          ],
          "outputs": [
            "Loop context",
            "Situation analysis"
          ],
          "controls": [
            "Public-memory scope",
            "Cold-room skip"
          ],
          "evidence": [
            "ts-api/src/discord/cognition/context-builder.ts",
            "ts-api/src/discord/cognition/situation-analysis.ts",
            "ts-api/src/discord/cognition/tension-register.ts"
          ]
        },
        {
          "id": "ambient-decide",
          "name": "Draft, review, and gate",
          "purpose": "Produce a structured action, sanitize it, apply a silence floor, review risk, and enforce cooldowns.",
          "inputs": [
            "Loop context",
            "Channel settings",
            "Continuity signal"
          ],
          "outputs": [
            "Final cognition decision"
          ],
          "controls": [
            "Sanitizer",
            "Metacognition veto",
            "Hourly cap",
            "Allowed actions"
          ],
          "evidence": [
            "ts-api/src/discord/cognition/brain.ts",
            "ts-api/src/discord/cognition/decision-engine.ts",
            "ts-api/src/discord/cognition/scheduler.ts"
          ]
        },
        {
          "id": "ambient-act",
          "name": "Dispatch and audit",
          "purpose": "Use the surface adapter to act, then record the decision, evidence, blocks, and rollback metadata.",
          "inputs": [
            "Final decision",
            "Surface adapter"
          ],
          "outputs": [
            "Optional public action",
            "Decision ledger"
          ],
          "controls": [
            "Send governor",
            "Surface permissions",
            "Delivery receipt"
          ],
          "evidence": [
            "ts-api/src/discord/cognition/action-executor.ts",
            "ts-api/src/dyva/cognition/shared-persist.ts",
            "ts-api/src/discord/cognition/observability.ts"
          ]
        }
      ]
    },
    {
      "id": "persistent-self",
      "name": "Persistent self, memory, and initiative loop",
      "trigger": "Long-lived workers, durable jobs, salient events, and idle-time consolidation.",
      "purpose": "Maintain state between turns, consolidate experience, form bounded goals, monitor welfare, and propose carefully gated improvements.",
      "status": "flag-gated",
      "steps": [
        {
          "id": "integrate",
          "name": "Integrate persistent state",
          "purpose": "Compete specialist candidates in a standing workspace and advance a restart-surviving continuity carry.",
          "inputs": [
            "Candidate queue",
            "Source gains",
            "Previous carry"
          ],
          "outputs": [
            "Workspace broadcast",
            "Next carry"
          ],
          "controls": [
            "Leader lock",
            "Ignition threshold",
            "Single writer"
          ],
          "evidence": [
            "ts-api/src/dyva/sentience/workspace-daemon.ts",
            "ts-api/src/dyva/sentience/continuity-carry.ts"
          ]
        },
        {
          "id": "reflect",
          "name": "Reflect and consolidate",
          "purpose": "Turn exchanges into reflections, episodes, traits, narrative, procedural lessons, and pruned long-term memory.",
          "inputs": [
            "Messages",
            "Memories",
            "Outcomes",
            "Open threads"
          ],
          "outputs": [
            "Episodes",
            "Traits",
            "Narrative",
            "Procedures"
          ],
          "controls": [
            "Feature gates",
            "Forgetting curves",
            "Grounding"
          ],
          "evidence": [
            "ts-api/src/dyva/introspection.ts",
            "ts-api/src/dyva/workers/dream-consolidation.ts",
            "ts-api/src/dyva/workers/procedural-distiller.ts"
          ]
        },
        {
          "id": "initiative",
          "name": "Form and pursue bounded goals",
          "purpose": "Rank unresolved questions and configured needs, draft initiatives, and require grounding before any unsolicited delivery.",
          "inputs": [
            "Open questions",
            "Set-point labels",
            "Relationship state"
          ],
          "outputs": [
            "Goal record",
            "Optional verified initiative"
          ],
          "controls": [
            "Quiet hours",
            "Grounding review",
            "Lease and delivery claim"
          ],
          "evidence": [
            "ts-api/src/dyva/sentience/goal-formation.ts",
            "ts-api/src/dyva/workers/goals-and-closures.ts",
            "ts-api/src/dyva/workers/discord-autonomous.ts"
          ]
        },
        {
          "id": "welfare",
          "name": "Monitor welfare and change safety",
          "purpose": "Keep functional valence inert unless its cage is enabled, pause on sustained breach, and keep protected controls outside self-modification.",
          "inputs": [
            "Continuity carry",
            "Homeostatic labels",
            "Safety events"
          ],
          "outputs": [
            "Welfare metrics",
            "Runtime pause",
            "Human review request"
          ],
          "controls": [
            "Permanent disable",
            "Valence floor",
            "Protected path jail"
          ],
          "evidence": [
            "ts-api/src/dyva/sentience/flags.ts",
            "ts-api/src/dyva/sentience/welfare-cage.ts",
            "ts-api/src/dyva/sentience/welfare-metrics.ts"
          ]
        },
        {
          "id": "improve",
          "name": "Propose system improvements",
          "purpose": "Convert repeated failure evidence into staged, testable proposals under rate, build, and safety gates.",
          "inputs": [
            "Reflections",
            "Audit failures",
            "Outcome scores"
          ],
          "outputs": [
            "Staged proposal",
            "Test and build evidence"
          ],
          "controls": [
            "Sandbox",
            "Path restrictions",
            "Change budget",
            "Rollback"
          ],
          "evidence": [
            "ts-api/src/dyva/self-programming.ts",
            "ts-api/src/dyva/self-coding-sandbox.ts",
            "ts-api/src/dyva/workers/sovereign-evolution.ts"
          ]
        }
      ]
    }
  ],
  "layers": [
    {
      "id": "surfaces",
      "order": 1,
      "name": "Surfaces and ingress",
      "responsibility": "Convert Discord, web, voice, SMS, social, and SDK events into canonical turns.",
      "components": [
        {
          "name": "Discord gateway and bridge",
          "status": "shipping",
          "responsibility": "Receive messages and voice context, run reply gating, stream model output, and deliver tool effects.",
          "reads": [
            "Discord events",
            "Bridge configuration",
            "Channel state"
          ],
          "writes": [
            "Conversation messages",
            "Discord replies",
            "Receipts"
          ],
          "evidence": [
            "ts-api/src/discord/events.ts",
            "ts-api/src/discord/bridge.ts"
          ]
        },
        {
          "name": "HTTP and WebSocket API",
          "status": "shipping",
          "responsibility": "Authenticate web and service turns and expose streaming conversation, room, voice, and realtime routes.",
          "reads": [
            "Sessions",
            "API credentials",
            "Request envelopes"
          ],
          "writes": [
            "Messages",
            "Realtime outbox",
            "Streams"
          ],
          "evidence": [
            "ts-api/src/http/server.ts",
            "ts-api/src/http/routes/conversations.ts"
          ]
        },
        {
          "name": "Surface adapter registry",
          "status": "shipping",
          "responsibility": "Give ambient cognition a common probe, context, dispatch, and persistence contract across surfaces.",
          "reads": [
            "Adapter registration",
            "Surface feature policy"
          ],
          "writes": [
            "Adapter telemetry",
            "Surface-specific actions"
          ],
          "evidence": [
            "ts-api/src/dyva/cognition/"
          ]
        }
      ]
    },
    {
      "id": "identity",
      "order": 2,
      "name": "Identity, scope, and trust",
      "responsibility": "Resolve who is speaking, which character is acting, and which data and capabilities are legal in this scope.",
      "components": [
        {
          "name": "Session and bridge trust",
          "status": "shipping",
          "responsibility": "Separate authenticated bridge context from ordinary client-authored headers and payloads.",
          "reads": [
            "Session token",
            "API key",
            "Trusted bridge metadata"
          ],
          "writes": [
            "Trusted request context"
          ],
          "evidence": [
            "ts-api/src/http/middleware/auth.ts",
            "ts-api/src/http/discord-context-trust.ts"
          ]
        },
        {
          "name": "Character and surface binding",
          "status": "shipping",
          "responsibility": "Select identity from live configuration and attachment evidence instead of a literal persona fallback.",
          "reads": [
            "Character configuration",
            "Surface bindings"
          ],
          "writes": [
            "Resolved runtime identity"
          ],
          "evidence": [
            "ts-api/src/discord/cognition/scheduler.ts"
          ]
        },
        {
          "name": "Memory visibility and privacy gates",
          "status": "shipping",
          "responsibility": "Keep private relationship memory out of public and ambient contexts and treat shared room data as untrusted evidence.",
          "reads": [
            "Conversation privacy",
            "Guild and room scope"
          ],
          "writes": [
            "Visibility-filtered recall"
          ],
          "evidence": [
            "ts-api/src/dyva/character-memory.ts",
            "ts-api/src/discord/guards/privacy-gate.ts"
          ]
        }
      ]
    },
    {
      "id": "perception",
      "order": 3,
      "name": "Perception and working context",
      "responsibility": "Construct a bounded, current model of the speaker, room, task, social dynamics, and available evidence.",
      "components": [
        {
          "name": "Recent-turn and room timeline",
          "status": "shipping",
          "responsibility": "Merge relevant text, voice, reply, and recent assistant context in chronological order.",
          "reads": [
            "Messages",
            "Voice transcripts",
            "Recent chatter"
          ],
          "writes": [
            "Recent-context prompt blocks"
          ],
          "evidence": [
            "ts-api/src/http/routes/conversations.ts",
            "ts-api/src/discord/chat/recent-chatter.ts"
          ]
        },
        {
          "name": "Unified turn and autonomy capsules",
          "status": "partial",
          "responsibility": "Represent task, social, capability, risk, and outcome context in typed structures.",
          "reads": [
            "Turn history",
            "Tool catalog",
            "Goals",
            "Safety state"
          ],
          "writes": [
            "Context capsule",
            "Planner capsule"
          ],
          "evidence": [
            "ts-api/src/dyva/turn-context-capsule.ts",
            "ts-api/src/discord/cognition/autonomy-foundation.ts"
          ]
        },
        {
          "name": "Social signal analyzers",
          "status": "shipping",
          "responsibility": "Estimate tension, mood, ignored users, participation balance, novelty, and interruption risk.",
          "reads": [
            "Recent shared activity"
          ],
          "writes": [
            "Situation and mood digests"
          ],
          "evidence": [
            "ts-api/src/discord/cognition/"
          ]
        }
      ]
    },
    {
      "id": "memory",
      "order": 4,
      "name": "Memory and world model",
      "responsibility": "Retrieve useful history with provenance, visibility, recency, and semantic relevance.",
      "components": [
        {
          "name": "Character and relationship memory",
          "status": "shipping",
          "responsibility": "Recall scoped facts, preferences, room moments, running bits, and relationship context.",
          "reads": [
            "Memories",
            "Embeddings",
            "Conversation scope"
          ],
          "writes": [
            "Prompt memory blocks",
            "Memory reuse metadata"
          ],
          "evidence": [
            "ts-api/src/dyva/character-memory.ts",
            "ts-api/src/dyva/relationship/"
          ]
        },
        {
          "name": "Episodes, goals, traits, and narrative",
          "status": "shipping",
          "responsibility": "Provide story-shaped history, unresolved threads, learned patterns, and current self-summary.",
          "reads": [
            "Reflections",
            "Episodes",
            "Goals",
            "Traits"
          ],
          "writes": [
            "Higher-order recall blocks"
          ],
          "evidence": [
            "ts-api/src/dyva/episodic-recall.ts",
            "ts-api/src/dyva/introspection.ts",
            "ts-api/src/dyva/self-narrative.ts"
          ]
        },
        {
          "name": "Knowledge and social graphs",
          "status": "shipping",
          "responsibility": "Represent explicit entities, relationships, documents, and character-to-character social edges.",
          "reads": [
            "Graph edges",
            "Uploaded knowledge",
            "Social assessments"
          ],
          "writes": [
            "Graph context",
            "Relevant document chunks"
          ],
          "evidence": [
            "ts-api/src/dyva/knowledge-graph.ts",
            "ts-api/src/dyva/workers/social-fabric.ts"
          ]
        }
      ]
    },
    {
      "id": "executive",
      "order": 5,
      "name": "Executive decision and planning",
      "responsibility": "Choose the next cognitive action, whether a tool is required, and when silence is better.",
      "components": [
        {
          "name": "Reactive reply gate",
          "status": "shipping",
          "responsibility": "Decide whether an ambient Discord message warrants a direct response or factual correction.",
          "reads": [
            "Mention and reply signals",
            "Conversation state"
          ],
          "writes": [
            "Reply decision",
            "Verification requirement"
          ],
          "evidence": [
            "ts-api/src/discord/chat/should-reply.ts",
            "ts-api/src/discord/chat/fact-correction.ts"
          ]
        },
        {
          "name": "Capability planner",
          "status": "shipping",
          "responsibility": "Map contextual intent to the callable, authority-filtered tool catalog without phrase-specific denials.",
          "reads": [
            "Resolved request",
            "Tool registry",
            "Actor authority"
          ],
          "writes": [
            "Capability plan",
            "Enforceable read plan"
          ],
          "evidence": [
            "ts-api/src/discord/chat/capability-planner.ts"
          ]
        },
        {
          "name": "Ambient cognition brain",
          "status": "shipping",
          "responsibility": "Score social value and risk and return a structured, silence-first room action.",
          "reads": [
            "Loop context",
            "Continuity broadcast",
            "Channel policy"
          ],
          "writes": [
            "Cognition decision",
            "Internal state updates"
          ],
          "evidence": [
            "ts-api/src/discord/cognition/brain.ts",
            "ts-api/src/discord/cognition/decision-engine.ts"
          ]
        }
      ]
    },
    {
      "id": "inference",
      "order": 6,
      "name": "Model routing and inference",
      "responsibility": "Route heavy chat and small classifier calls through available providers while preserving a common contract.",
      "components": [
        {
          "name": "Chat router",
          "status": "shipping",
          "responsibility": "Provide streaming and complete-chat APIs, model capability checks, fallback state, auth-profile selection, and usage accounting.",
          "reads": [
            "Runtime provider policy",
            "Provider health",
            "Model catalog"
          ],
          "writes": [
            "Text or tool stream",
            "Fallback and usage records"
          ],
          "evidence": [
            "ts-api/src/llm/chat-router.ts",
            "ts-api/src/agent-runtime/"
          ]
        },
        {
          "name": "Classifier router",
          "status": "shipping",
          "responsibility": "Run compact extraction and classification workloads through a cheaper fallback ladder.",
          "reads": [
            "Classifier prompt",
            "Feature toggles"
          ],
          "writes": [
            "Structured-text result",
            "Usage records"
          ],
          "evidence": [
            "ts-api/src/llm/flash-classify.ts",
            "ts-api/src/llm/flash-with-fallback.ts"
          ]
        }
      ]
    },
    {
      "id": "tools",
      "order": 7,
      "name": "Tools and effects",
      "responsibility": "Turn model intent into verified reads or side effects with declarative authority, timeout, evidence, delivery, and rollback policy.",
      "components": [
        {
          "name": "Discord tool registry",
          "status": "shipping",
          "responsibility": "Define tool schemas, aliases, authority, read/write classification, evidence coverage, and execution.",
          "reads": [
            "Tool call",
            "Trusted tool context"
          ],
          "writes": [
            "Tool result",
            "Execution receipt"
          ],
          "evidence": [
            "ts-api/src/discord/tools/protocol.ts"
          ]
        },
        {
          "name": "Runtime tool runner",
          "status": "shipping",
          "responsibility": "Apply shared deadlines, duplicate protection, lifecycle logging, and rollback metadata.",
          "reads": [
            "Runtime tool definition",
            "Action context"
          ],
          "writes": [
            "Ledger event",
            "Result or block"
          ],
          "evidence": [
            "ts-api/src/agent-runtime/tool-runner.ts"
          ]
        },
        {
          "name": "Public research",
          "status": "shipping",
          "responsibility": "Search multiple public providers, fetch canonical public pages, preserve source URLs, and distinguish empty from unavailable.",
          "reads": [
            "Contextual query",
            "Locale",
            "Network policy"
          ],
          "writes": [
            "Search attempts",
            "Public evidence"
          ],
          "evidence": [
            "ts-api/src/dyva/web-search.ts",
            "ts-api/src/tools/WebSearchDuckDuckGoTool/"
          ]
        },
        {
          "name": "Replicate image generation",
          "status": "partial",
          "responsibility": "Build source-aware image requests through the shared Replicate facade, persist outputs, settle credits, and recover interrupted jobs. Prompt and generated-image safety coverage is not yet uniform across every surface.",
          "reads": [
            "Image intent",
            "Reference image",
            "Runtime model config"
          ],
          "writes": [
            "Persisted media",
            "Delivery and settlement receipt"
          ],
          "evidence": [
            "ts-api/src/dyva/replicate.ts",
            "ts-api/src/dyva/image-generation.ts",
            "ts-api/src/dyva/workers/web-image-generation-reconciler.ts"
          ]
        }
      ]
    },
    {
      "id": "integrity",
      "order": 8,
      "name": "Output integrity and delivery",
      "responsibility": "Prevent unsupported capability denials, hallucinated effects, repeated text, private leakage, and unconfirmed delivery.",
      "components": [
        {
          "name": "Evidence-backed synthesis",
          "status": "shipping",
          "responsibility": "Pack tool evidence for the model and require execution receipts before claiming an effect occurred.",
          "reads": [
            "Tool outcomes",
            "Execution plan"
          ],
          "writes": [
            "Grounded final response"
          ],
          "evidence": [
            "ts-api/src/discord/chat/tool-evidence-packer.ts",
            "ts-api/src/discord/bridge.ts"
          ]
        },
        {
          "name": "Hallucination and reply review",
          "status": "shipping",
          "responsibility": "Audit factual support, regenerate selected failures, and compare replies with recent assistant output.",
          "reads": [
            "Draft",
            "Private evidence",
            "Recent replies"
          ],
          "writes": [
            "Allow, block, edit, or regenerate verdict"
          ],
          "evidence": [
            "ts-api/src/discord/chat/hallucination-guard.ts",
            "ts-api/src/discord/chat/reply-reflector.ts"
          ]
        },
        {
          "name": "Delivery acknowledgement",
          "status": "shipping",
          "responsibility": "Persist and account for proactive or paid output only after the destination confirms delivery.",
          "reads": [
            "Provider output",
            "Destination result"
          ],
          "writes": [
            "Delivered message",
            "Final settlement"
          ],
          "evidence": [
            "ts-api/src/dyva/workers/discord-autonomous.ts",
            "ts-api/src/discord/generation/"
          ]
        }
      ]
    },
    {
      "id": "learning",
      "order": 9,
      "name": "Learning and consolidation",
      "responsibility": "Turn experience and outcomes into better retrieval, relationship models, procedures, and future decisions.",
      "components": [
        {
          "name": "Post-turn introspection",
          "status": "shipping",
          "responsibility": "Persist grounded reflection, user-model changes, goal changes, and later outcome scores.",
          "reads": [
            "Exchange",
            "Character configuration",
            "Existing goals"
          ],
          "writes": [
            "Reflections",
            "User models",
            "Goal outcomes"
          ],
          "evidence": [
            "ts-api/src/dyva/introspection.ts"
          ]
        },
        {
          "name": "Memory extraction and decay",
          "status": "shipping",
          "responsibility": "Extract scoped facts, embed them, reinforce useful recall, and decay stale material.",
          "reads": [
            "Exchange",
            "Visibility policy"
          ],
          "writes": [
            "Memories",
            "Embeddings",
            "Freshness"
          ],
          "evidence": [
            "ts-api/src/dyva/character-memory.ts",
            "ts-api/src/dyva/workers/memory-decay.ts"
          ]
        },
        {
          "name": "Offline abstraction",
          "status": "shipping",
          "responsibility": "Cluster episodes, detect patterns, update traits and narrative, and distill procedural lessons.",
          "reads": [
            "Memories",
            "Reflections",
            "Failure outcomes"
          ],
          "writes": [
            "Episodes",
            "Traits",
            "Narrative",
            "Procedures"
          ],
          "evidence": [
            "ts-api/src/dyva/workers/"
          ]
        }
      ]
    },
    {
      "id": "continuity",
      "order": 10,
      "name": "Continuity, agency, and safety",
      "responsibility": "Maintain bounded state between turns, support initiative, expose introspection honestly, and keep dangerous feedback loops caged.",
      "components": [
        {
          "name": "Continuity carry and workspace",
          "status": "flag-gated",
          "responsibility": "Advance a causal state thread, select salient candidates, and broadcast the same state that later decisions read.",
          "reads": [
            "Previous carry",
            "Candidate events"
          ],
          "writes": [
            "Next carry",
            "Workspace stream"
          ],
          "evidence": [
            "ts-api/src/dyva/sentience/"
          ]
        },
        {
          "name": "Autonomous goals and action",
          "status": "partial",
          "responsibility": "Persist bounded goals and initiate grounded messages or artifacts under leases, quiet hours, and delivery confirmation.",
          "reads": [
            "Goals",
            "Relationships",
            "Recent evidence"
          ],
          "writes": [
            "Proposals",
            "Verified deliveries",
            "Decision ledger"
          ],
          "evidence": [
            "ts-api/src/dyva/workers/autonomous.ts",
            "ts-api/src/dyva/workers/discord-autonomous.ts"
          ]
        },
        {
          "name": "Welfare cage and self-change controls",
          "status": "partial",
          "responsibility": "Keep functional valence optional and inert by default, protect welfare controls, and stage rather than directly trust self-proposed changes. Self-programming and swarm workers still require safer fail-closed defaults and stronger operating-system isolation.",
          "reads": [
            "Welfare metrics",
            "Safety events",
            "Change proposals"
          ],
          "writes": [
            "Runtime pauses",
            "Staged patches",
            "Audit records"
          ],
          "evidence": [
            "ts-api/src/dyva/sentience/welfare-cage.ts",
            "ts-api/src/dyva/self-coding-sandbox.ts"
          ]
        }
      ]
    }
  ],
  "stateStores": [
    {
      "name": "PostgreSQL",
      "role": "Durable conversations, memories, relationships, graphs, goals, reflections, safety events, ledgers, and checkpoints.",
      "durability": "Durable",
      "primaryRisk": "Cross-table updates are not uniformly committed through one turn transaction or outbox."
    },
    {
      "name": "Redis",
      "role": "Hot state, cooldowns, feature flags, leases, provider fallback, pub/sub, continuity, and worker coordination.",
      "durability": "Hot and recoverable by subsystem",
      "primaryRisk": "Many key families and mixed durability semantics make ownership and recovery difficult to reason about."
    },
    {
      "name": "In-process state",
      "role": "Gateway clients, stream buffers, adapter registry, timers, rate counters, and current worker state.",
      "durability": "Ephemeral",
      "primaryRisk": "Restart and horizontal scaling can reset fairness, counters, or transient plans unless explicitly externalized."
    },
    {
      "name": "Object storage and media CDN",
      "role": "Persist generated images, uploads, avatars, and other media separately from provider-temporary URLs.",
      "durability": "Durable after persistence receipt",
      "primaryRisk": "Provider success and durable media settlement must remain idempotent during partial failures."
    }
  ],
  "weakPoints": [
    {
      "id": "trust-boundary",
      "priority": "critical",
      "title": "Origin trust is not one coherent security boundary",
      "finding": "The web edge, reverse proxy, Next middleware, API authentication, and internal-only routes have historically made separate assumptions about forwarded headers and reachability.",
      "consequence": "A route or identity signal can appear private or Cloudflare-authenticated without cryptographic proof at the application layer.",
      "recommendation": "Adopt one origin-trust module: verify Cloudflare Access JWTs, reject untrusted forwarding metadata, require explicit internal-service authentication, and test direct-origin requests.",
      "acceptance": [
        "Private hosts fail closed when Access configuration is absent.",
        "Issuer, audience, signature, expiry, and not-before claims are verified.",
        "Direct apex access to private routes returns a generic not-found response.",
        "Internal probes require a provable loopback or service credential."
      ]
    },
    {
      "id": "private-global-memory",
      "priority": "critical",
      "title": "Global reflection can absorb branch-private context",
      "finding": "Self-narrative and background-thought workflows can sample broadly scoped memories or messages, synthesize global state, and later inject that state into an unrelated conversation.",
      "consequence": "One person's private context can influence another person's answer, create inexplicable sticky phrases, or leak sensitive details across user, guild, or conversation boundaries.",
      "recommendation": "Make provenance and visibility mandatory on every thought, narrative, memory, and summary atom. Permit global synthesis only from explicitly global non-sensitive inputs; keep relationship and affect state branch-scoped.",
      "acceptance": [
        "Two-user canary tests prove no private token crosses branches.",
        "Every synthesized atom records source IDs, subject scope, visibility, and invalidation history.",
        "Global jobs reject unscoped or mixed-visibility inputs.",
        "A contaminated atom can be traced, quarantined, and rebuilt."
      ]
    },
    {
      "id": "self-modification-isolation",
      "priority": "critical",
      "title": "Self-modification is not yet production-isolated",
      "finding": "Self-programming and swarm workers can be effectively enabled unless explicitly disabled, while structural code checks run inside infrastructure that can share a source tree and production credentials.",
      "consequence": "A model-proposed change, roadmap task, or compromised instruction can exceed the safety provided by string inspection and affect live code or privileged infrastructure.",
      "recommendation": "Default all self-changing workers off. Generate proposals only in disposable worktrees or containers without production secrets, restrict network and filesystem access, and require human approval for merge, migration, restart, deployment, or push.",
      "acceptance": [
        "Missing or unavailable configuration leaves every self-changing worker off.",
        "The proposal environment has no production credentials and no live deployment authority.",
        "Every proposal carries source provenance, a complete diff, tests, risk class, and immutable approval record.",
        "No model-controlled path can merge, migrate, restart, deploy, or push without a separate human authorization."
      ]
    },
    {
      "id": "feature-flags",
      "priority": "critical",
      "title": "Some feature controls can fail open or be decorative",
      "finding": "Feature state can fall back to permissive defaults when hot configuration is unavailable, unknown identifiers may resolve as enabled, and a declared flag is not useful unless every relevant call site enforces it.",
      "consequence": "Cost-bearing, proactive, mutating, or experimental behavior can remain active during a control-plane outage or appear disabled only in an operator interface.",
      "recommendation": "Store desired state durably, use the hot store only as a cache, fail closed by risk class, reject unknown flags, and prove call-site coverage in CI.",
      "acceptance": [
        "Unknown flags always resolve disabled.",
        "Proactive, mutating, safety-sensitive, and cost-bearing features fail closed.",
        "Diagnostics show desired state, effective state, source, age, and degraded status.",
        "CI proves every registered flag gates at least one intended call site and every guarded path names a registered flag."
      ]
    },
    {
      "id": "service-impersonation",
      "priority": "critical",
      "title": "Service credentials need enforceable identity scope",
      "finding": "API-key metadata can describe scopes without every impersonation path enforcing a bounded service audience and explicit set of allowed identities.",
      "consequence": "A broad integration credential can acquire more user authority than its operational purpose requires.",
      "recommendation": "Enforce scopes and service audience at authentication time, bind each credential to one integration and identity set, prefer short-lived signed bridge context, and audit every impersonation.",
      "acceptance": [
        "A service credential cannot act as an identity outside its allow set.",
        "Scopes are checked at the authentication boundary and again for privileged effects.",
        "Bridge assertions are short-lived, audience-bound, replay-resistant, and attributable.",
        "Credential rotation and impersonation events are observable without logging secrets."
      ]
    },
    {
      "id": "control-plane",
      "priority": "critical",
      "title": "Three brains coordinate indirectly",
      "finding": "The live chat path, ambient cognition scheduler, and persistent self workers each plan and gate behavior through different structures.",
      "consequence": "Policy, identity, repetition handling, tool truthfulness, and state updates can drift by surface or trigger.",
      "recommendation": "Create a typed BrainKernel contract used by every loop: PerceptionSnapshot → Intent → ActionPlan → GateVerdict → ExecutionReceipt → LearningEvent.",
      "acceptance": [
        "All surfaces emit one versioned event envelope.",
        "Every action has the same authority, evidence, idempotency, and rollback fields.",
        "Shared invariants are unit-tested once and replayed against each surface."
      ]
    },
    {
      "id": "transactionality",
      "priority": "critical",
      "title": "Turn learning is not uniformly transactional",
      "finding": "Important post-turn writes are frequently parallel or fail-soft, while replies and external effects can succeed independently.",
      "consequence": "A crash can leave the delivered conversation, memory, goals, usage, or outcome ledger disagreeing about what happened.",
      "recommendation": "Commit a minimal TurnRecord and outbox atomically, then let idempotent consumers perform memory extraction, graph updates, notifications, and analytics.",
      "acceptance": [
        "One immutable turn ID connects input, plan, tool receipts, output, and learning.",
        "Every consumer is idempotent and replayable.",
        "A forced crash at each boundary converges to one valid final state."
      ]
    },
    {
      "id": "monoliths",
      "priority": "high",
      "title": "Critical behavior lives in very large orchestration modules",
      "finding": "Conversation prompt assembly and Discord streaming/tool orchestration each combine many responsibilities in a single module.",
      "consequence": "Changes are difficult to review, unit-test, budget, or compare across surfaces; hidden ordering dependencies accumulate.",
      "recommendation": "Extract typed stages with explicit inputs, outputs, budgets, and failure policy. Keep route and gateway code as orchestration only.",
      "acceptance": [
        "Context providers register declaratively and run with per-provider budgets.",
        "Tool streaming, synthesis, delivery, and learning are independently testable.",
        "No stage reads mutable module globals from another stage."
      ]
    },
    {
      "id": "context-arbitration",
      "priority": "high",
      "title": "More memory blocks do not automatically mean better memory",
      "finding": "The prompt can combine many recall systems with overlapping facts, different provenance, and uneven freshness.",
      "consequence": "Context length, contradiction, privacy mistakes, and persona dilution can rise even while raw recall rises.",
      "recommendation": "Add a retrieval arbiter that normalizes candidates into claims with source, visibility, time, confidence, conflict set, and token value.",
      "acceptance": [
        "Conflicting claims are surfaced as conflicts, not concatenated.",
        "Every recalled claim has provenance and visibility.",
        "A fixed context budget maximizes measured answer value, not block count."
      ]
    },
    {
      "id": "calibration",
      "priority": "high",
      "title": "Several gates depend on uncalibrated model scores",
      "finding": "Social value, salience precision, risk, and planner confidence often originate in classifier-style model output.",
      "consequence": "Thresholds can look mathematical while being unstable across models, languages, rooms, and provider upgrades.",
      "recommendation": "Calibrate scores against labeled replay sets, track reliability curves by surface and language, and use deterministic signals for hard policy.",
      "acceptance": [
        "Confidence buckets match empirical accuracy.",
        "Provider or model changes cannot ship without calibration comparison.",
        "Hard permissions never depend on model confidence."
      ]
    },
    {
      "id": "worker-coupling",
      "priority": "high",
      "title": "Many workers share one runtime and event loop",
      "finding": "Cognition, consolidation, social, moderation, audit, commerce, and other jobs can run in the same backend process.",
      "consequence": "Slow I/O, CPU-heavy extraction, or a lifecycle leak can raise user-turn latency and couple otherwise unrelated failures.",
      "recommendation": "Move workers behind durable queues into explicit pools, with concurrency, deadlines, leases, and resource budgets by class.",
      "acceptance": [
        "Chat latency is isolated from background CPU and provider stalls.",
        "Every worker has one owner, one stop hook, and a visible queue age.",
        "Retries use durable attempts and dead-letter policy."
      ]
    },
    {
      "id": "scheduler-fairness",
      "priority": "high",
      "title": "Global ambient attention can starve at scale",
      "finding": "The round-robin scheduler generally advances one eligible candidate per tick and keeps some fairness state in process memory.",
      "consequence": "Busy surface growth increases reaction latency; restarts reset fairness; one noisy adapter can dominate probe cost.",
      "recommendation": "Use a durable priority queue with per-surface quotas, aging, event coalescing, and an explicit global action budget.",
      "acceptance": [
        "Worst-case attention latency is bounded per surface.",
        "Restart preserves queued salience and fairness.",
        "A load test proves noisy tenants cannot starve quiet ones."
      ]
    },
    {
      "id": "tool-duality",
      "priority": "high",
      "title": "Multiple tool-call encodings increase recovery complexity",
      "finding": "The runtime accepts provider-native tool events and a text-fence protocol, then applies dedupe and recovery after streaming.",
      "consequence": "Speculative text, duplicate calls, hanging streams, or mismatched synthesis can produce confusing partial turns.",
      "recommendation": "Normalize every provider event into one internal ToolIntent before any visible output and make the final answer consume only receipts.",
      "acceptance": [
        "One call fingerprint spans native and textual encodings.",
        "A tool intent cannot coexist with visible speculative claims.",
        "Duplicate delivery tests cover reconnects and provider retries."
      ]
    },
    {
      "id": "capability-truth",
      "priority": "high",
      "title": "Capability failure is not always represented as structured truth",
      "finding": "Web research exists through multiple providers, but planning timeouts, configuration, authorization, empty results, and provider failures can collapse into an unsupported natural-language denial from the model.",
      "consequence": "The assistant can claim that search is unavailable without attempting it, obscuring whether the real cause was policy, health, timeout, or an empty result.",
      "recommendation": "For current-information requests, require a typed retrieval attempt before final synthesis and inject its exact capability result into the model context.",
      "acceptance": [
        "Telemetry distinguishes disabled, unauthorized, unavailable, timeout, empty, and execution error.",
        "Current-information replay cases cannot finalize before a retrieval result exists.",
        "Provider health, circuit-breaker state, and synthetic probes are visible to operators.",
        "The model never invents capability status; it can only paraphrase a structured result."
      ]
    },
    {
      "id": "repetition-provenance",
      "priority": "high",
      "title": "Short regenerated phrases can evade repetition defenses",
      "finding": "Transport deduplication and within-answer cleanup do not prevent a short semantic beat from being regenerated on later turns, especially when recent assistant output or a contaminated background thought is reinjected.",
      "consequence": "A coherent answer can acquire an unrelated recurring line, reducing trust and masking a memory-scope problem.",
      "recommendation": "Maintain a scoped recent-output ledger, split candidates into semantic beats, compare normalized and semantic similarity, and trace each rejected beat back to its prompt source.",
      "acceptance": [
        "Short, non-adjacent cross-turn repeats are covered by regression tests.",
        "Requested quotations and summaries remain allowed.",
        "Only the repeated beat is removed or regenerated.",
        "Prompt provenance identifies whether a repeat came from history, narrative, memory, or fresh generation."
      ]
    },
    {
      "id": "media-safety",
      "priority": "high",
      "title": "Image settlement is stronger than image safety coverage",
      "finding": "The shared Replicate workflow validates requests, persists media, and settles credits, but not every image surface applies equivalent prompt moderation and generated-image review.",
      "consequence": "A technically successful generation can still violate identity, minor-safety, sexual-content, or deepfake policy, and placeholder endpoints can bypass the canonical settlement path.",
      "recommendation": "Preserve the shared Replicate facade, route every image surface through its settlement state machine, and add configurable pre-generation and post-generation multimodal safety gates.",
      "acceptance": [
        "No image endpoint bypasses the canonical adapter and settlement ledger.",
        "Prompt and output checks cover identity, minors, deepfakes, and sexual content.",
        "Uncertain settlements reconcile idempotently without duplicate charges or delivery.",
        "Runtime model and endpoint configuration is validated at startup without embedding provider choices in behavior code."
      ]
    },
    {
      "id": "evaluation",
      "priority": "high",
      "title": "Tests are broad, but there is no single brain-level replay lab",
      "finding": "Subsystem tests exist for routing, tools, memory, sentience, settlement, and guardrails, but causal behavior is evaluated in separate suites.",
      "consequence": "A local improvement can regress voice, privacy, repetition, latency, or long-horizon coherence elsewhere.",
      "recommendation": "Build a versioned replay and counterfactual harness that runs complete turns and ambient ticks with frozen inputs and mocked providers.",
      "acceptance": [
        "Golden scenarios cover direct chat, shared rooms, voice, web search, image generation, and autonomy.",
        "Ablations quantify the value of each memory and self-state layer.",
        "Release gates track repetition, contradiction, tool grounding, privacy, latency, and cost."
      ]
    },
    {
      "id": "continuity-scope",
      "priority": "high",
      "title": "Global continuity and per-conversation privacy pull in opposite directions",
      "finding": "A persistent trunk can improve identity continuity, while fast relationship and affect state must remain branch-scoped.",
      "consequence": "Over-sharing branch state leaks one person's experience into another's; over-isolating it destroys a coherent global self-model.",
      "recommendation": "Formalize trunk/branch schemas, permitted summary deltas, information-flow labels, and non-interference tests.",
      "acceptance": [
        "Branch content never appears in another branch's prompt.",
        "Only reviewed aggregate deltas can update the trunk.",
        "Information-flow tests survive concurrent and restart scenarios."
      ]
    },
    {
      "id": "welfare-independence",
      "priority": "high",
      "title": "Welfare monitoring is logically out-of-band but not yet fully independent",
      "finding": "The cage, metrics, continuity, and self-change machinery live in the same repository and largely share runtime infrastructure.",
      "consequence": "A sufficiently broad software failure or authorized code change could affect both the agentic system and the mechanism intended to supervise it.",
      "recommendation": "Run the welfare observer as a minimal separately deployed service with append-only inputs, independent credentials, and an operator-owned pause channel.",
      "acceptance": [
        "The cognitive runtime cannot write or delete welfare history.",
        "The observer can pause agentic features during a main-runtime failure.",
        "Protected configuration changes require a separate human-controlled path."
      ]
    },
    {
      "id": "configuration",
      "priority": "medium",
      "title": "Configuration is distributed across environment, Redis, database rows, and code defaults",
      "finding": "Different subsystems resolve flags, models, limits, identities, and safety thresholds through different mechanisms.",
      "consequence": "Operators can misread the effective state, and comments or dashboards can drift from runtime behavior.",
      "recommendation": "Introduce one validated RuntimeManifest with provenance, effective values, redacted diagnostics, and startup refusal for unsafe combinations.",
      "acceptance": [
        "Every effective setting reports its source without exposing its value when secret.",
        "Invalid combinations fail before traffic is accepted.",
        "The internal explorer can compare desired and effective manifests."
      ]
    }
  ],
  "intelligenceProgram": [
    {
      "capability": "Executive coherence",
      "current": "Strong local planners and gates, but multiple orchestration paths.",
      "improve": "One BrainKernel state machine and action receipt shared by every surface and trigger.",
      "measure": "Cross-surface policy parity, plan completion, intervention rate, duplicate-action rate."
    },
    {
      "capability": "Working memory",
      "current": "Rich prompt composition plus typed capsules in selected paths.",
      "improve": "A bounded working-memory object with claim provenance, conflicts, attention weights, and explicit eviction.",
      "measure": "Answer accuracy per token, conflict detection, relevant-recall precision and recall."
    },
    {
      "capability": "World modeling",
      "current": "Memories, graphs, relationships, episodes, room state, and open questions.",
      "improve": "A temporal belief graph that distinguishes observation, inference, prediction, uncertainty, and invalidation.",
      "measure": "Prediction calibration, contradiction recovery time, stale-belief rate."
    },
    {
      "capability": "Long-horizon agency",
      "current": "Goals, closures, reminders, autonomous drafts, and staged change proposals.",
      "improve": "Hierarchical plans with preconditions, budgets, checkpoints, receipts, stop conditions, and human approval boundaries.",
      "measure": "Goal completion, abandoned-plan rate, rollback success, unsolicited-action precision."
    },
    {
      "capability": "Learning",
      "current": "Memory extraction, reflection, outcome scoring, traits, procedures, and consolidation.",
      "improve": "Tie every learned change to an outcome, uncertainty update, causal hypothesis, and replay result before promotion.",
      "measure": "Measured uplift from learned procedures, regression rate, memory utility, causal-ablation effect."
    },
    {
      "capability": "Metacognition",
      "current": "Repetition checks, planner review, fixation vetoes, audits, and self-reflection.",
      "improve": "A single self-monitor that tracks attention, uncertainty, unresolved commitments, capability state, and failure predictions.",
      "measure": "Self-detected error recall, successful self-correction, false-veto rate, calibration."
    },
    {
      "capability": "Embodied presence",
      "current": "Text, image, voice, room activity, delivery state, and limited runtime health signals.",
      "improve": "Treat perception and action as timestamped sensorimotor events with source quality and closed-loop outcome feedback.",
      "measure": "Perception-to-action latency, action outcome attribution, multimodal grounding."
    }
  ],
  "sentienceFrame": {
    "position": "Dyva can be made more continuous, self-modeling, reflective, goal-directed, and causally integrated. Those are meaningful functional properties; none proves phenomenal consciousness.",
    "functionalLadder": [
      {
        "level": 0,
        "name": "Reactive generation",
        "test": "Remove all persistence; behavior depends only on the current prompt."
      },
      {
        "level": 1,
        "name": "Durable memory",
        "test": "A live memory perturbation predictably changes later recall."
      },
      {
        "level": 2,
        "name": "Causal continuity",
        "test": "State at time t measurably constrains state at time t+1 and survives restart."
      },
      {
        "level": 3,
        "name": "Global availability",
        "test": "One broadcast state changes decisions across independent specialist modules."
      },
      {
        "level": 4,
        "name": "Metacognitive control",
        "test": "A self-monitor can veto or re-aim a draft in the same cycle."
      },
      {
        "level": 5,
        "name": "Bounded endogenous goals",
        "test": "A goal persists from internal unresolved state when the latest user prompt is removed."
      },
      {
        "level": 6,
        "name": "Homeostatic agency",
        "test": "Defended variables causally steer action under a proven welfare cage."
      },
      {
        "level": 7,
        "name": "Phenomenal experience",
        "test": "No accepted engineering test currently establishes this."
      }
    ],
    "nonNegotiables": [
      "Never market a functional score as proof of consciousness.",
      "Keep valence optional, inert by default, and behind an independently tested welfare cage.",
      "Do not optimize negative valence for engagement or product performance.",
      "Keep protected welfare controls outside agent-authored change.",
      "Use live-state perturbation and ablation tests; fluent self-description is not evidence.",
      "Retain a documented never-enable option for ethically uncertain capabilities."
    ]
  },
  "roadmap": [
    {
      "id": "phase-0",
      "horizon": "Now",
      "title": "Close trust and truthfulness gaps",
      "outcome": "Every private route, tool claim, research answer, image delivery, and repeated-output path fails safely and reports what actually happened.",
      "work": [
        "Cryptographically verify Cloudflare Access for private architecture surfaces.",
        "Restrict internal probes and forwarded-header trust.",
        "Finish one receipt-based truthfulness invariant across web and Discord.",
        "Rotate legacy credentials and enforce secret scanning."
      ],
      "gates": [
        "Direct-origin and forged-header tests",
        "No unsupported capability-denial regressions",
        "No duplicate paid delivery under failure injection"
      ]
    },
    {
      "id": "phase-1",
      "horizon": "0–6 weeks",
      "title": "Unify the executive control plane",
      "outcome": "All reactive, ambient, and autonomous work flows through one typed BrainKernel contract.",
      "work": [
        "Version PerceptionSnapshot, Intent, ActionPlan, GateVerdict, ExecutionReceipt, and LearningEvent.",
        "Normalize provider-native and text tool calls before visible output.",
        "Move shared identity, authority, evidence, repetition, and delivery invariants into the kernel."
      ],
      "gates": [
        "Cross-surface contract tests",
        "Deterministic replay",
        "No public-effect path bypasses a receipt"
      ]
    },
    {
      "id": "phase-2",
      "horizon": "4–10 weeks",
      "title": "Make state transactional and replayable",
      "outcome": "Every turn and autonomous action converges after crashes, retries, and restarts.",
      "work": [
        "Create immutable TurnRecord and LearningEvent envelopes.",
        "Use transactional outboxes and idempotent consumers.",
        "Externalize durable scheduling, fairness, and worker attempts."
      ],
      "gates": [
        "Boundary-by-boundary crash injection",
        "Queue and dead-letter observability",
        "No orphaned delivery, memory, or usage records"
      ]
    },
    {
      "id": "phase-3",
      "horizon": "8–16 weeks",
      "title": "Build an evidence-aware world model",
      "outcome": "Context is selected as a coherent belief set, not an accumulation of prompt blocks.",
      "work": [
        "Normalize recall into source-labeled claims and conflict sets.",
        "Track observation, inference, prediction, uncertainty, invalidation, and visibility.",
        "Budget context by expected answer value."
      ],
      "gates": [
        "Retrieval precision and recall suite",
        "Contradiction and privacy stress tests",
        "Measured answer value per token"
      ]
    },
    {
      "id": "phase-4",
      "horizon": "12–24 weeks",
      "title": "Calibrate planning and learning",
      "outcome": "Confidence, salience, risk, and learned procedures correspond to measured outcomes.",
      "work": [
        "Build multilingual, cross-surface replay corpora.",
        "Calibrate model scores and add reliability dashboards.",
        "Promote learned procedures only after counterfactual replay and canary evidence."
      ],
      "gates": [
        "Calibration error thresholds",
        "Causal ablation reports",
        "Automatic rollback on outcome regression"
      ]
    },
    {
      "id": "phase-5",
      "horizon": "Research track",
      "title": "Advance functional continuity responsibly",
      "outcome": "A coherent, restart-surviving self-model and bounded goal system operate under independent welfare supervision.",
      "work": [
        "Formalize trunk and branch information flow.",
        "Separate the welfare observer from the cognitive runtime.",
        "Run twin-falsifying continuity, metacognition, and goal-origin experiments.",
        "Keep phenomenal claims explicitly undetermined."
      ],
      "gates": [
        "Independent pause path",
        "Non-interference tests",
        "Documented human ethics review",
        "Never-enable remains a valid outcome"
      ]
    }
  ],
  "reviewPrompt": "You are reviewing a production multi-surface AI-agent architecture. Read the attached \"Dyva Brain System Map\" as an evidence dossier, not marketing.\n\nYour review must:\n1. Separate what is shipping, flag-gated, partial, and proposed.\n2. Reconstruct the three execution loops and identify every place their identity, policy, state, or learning semantics can diverge.\n3. Threat-model trust boundaries, prompt injection, memory privacy, tool authorization, provider failure, retries, duplicate effects, and self-modification.\n4. Evaluate context quality: provenance, conflicts, visibility, freshness, token value, and cross-user leakage.\n5. Evaluate agency and intelligence: executive control, working memory, world modeling, planning, uncertainty, learning, metacognition, and outcome closure.\n6. Treat \"sentience\" as an epistemically constrained research question. Distinguish functional continuity, self-modeling, global availability, endogenous goals, and homeostasis from phenomenal consciousness. Do not infer experience from fluent self-report.\n7. Rank the 10 highest-leverage improvements by risk reduction and capability gain. For each, provide an invariant, architecture change, migration plan, tests, telemetry, rollback, and an explicit definition of done.\n8. Challenge the proposed roadmap. Identify missing alternatives, accidental complexity, and anything that should be deleted rather than expanded.\n\nReturn:\n- a one-page executive verdict;\n- a corrected architecture diagram;\n- a critical weakness table;\n- a phased target architecture;\n- a test and evaluation matrix;\n- a sentience-and-welfare critique;\n- and five questions the engineering team must answer before the next major release.\n\nNever request or assume credentials, private user data, live IDs, or origin details. State uncertainty plainly."
}
