# ============================================================================
# NEURAL MEMORY - PROJECT STRUCTURE & FEATURE MAP
# Version: 2.3.0 | Python: >=3.11 | License: MIT
# Generated: 2026-02-16
# Purpose: Maintenance scheduling, upgrade planning, branch audit tracking
# ============================================================================

project:
  name: neural-memory
  version: "2.3.0"
  description: "Reflex-based memory system for AI agents - retrieval through activation, not search"
  python: ">=3.11 (tested: 3.11, 3.12, 3.14)"
  platforms: [Windows, macOS, Linux]
  storage: SQLite (async via aiosqlite)
  schema_version: 13
  total_loc: ~142000
  total_files: 190+
  entry_points:
    - "pug" # CLI (alias: neural-memory)
    - "pug-mcp" # MCP server for Claude Code

# ============================================================================
# ARCHITECTURE - MODULE MAP
# ============================================================================

modules:
  # ── CORE (2,717 LOC, 11 files) ──────────────────────────────────────
  core:
    path: src/neural_memory/core/
    loc: 2717
    files: 11
    purpose: "Frozen dataclasses - the data model layer"
    components:
      neuron.py: "Neuron + NeuronState + NeuronType (time/spatial/entity/action/state/concept/sensory/intent)"
      synapse.py: "Synapse + SynapseType (related_to/causes/precedes/co_occurs/contradicts/alias)"
      fiber.py: "Fiber - memory trace (bundle of neurons+synapses with tags, salience, conductivity)"
      brain.py: "Brain + BrainConfig + BrainSnapshot - top-level container"
      brain_mode.py: "BrainMode (local/shared/hybrid) + SyncStrategy + SharedConfig"
      action_event.py: "ActionEvent - tracked user actions for habit learning"
      eternal_context.py: "EternalContext - persistent project context across sessions"
      memory_types.py: "MemoryType enum (fact/decision/preference/todo/insight/context/instruction/error/workflow/reference)"
      project.py: "Project dataclass for multi-project management"
      trigger_engine.py: "TriggerEngine for event-driven memory operations"

  # ── ENGINE (14,271 LOC, 49 files) ───────────────────────────────────
  engine:
    path: src/neural_memory/engine/
    loc: 14271
    files: 49
    purpose: "Core logic - encoding, retrieval, consolidation, diagnostics"
    subsystems:
      encoding:
        encoder.py: "MemoryEncoder - main encoding pipeline orchestrator"
        pipeline.py: "Pipeline + PipelineStep protocol for composable processing"
        pipeline_steps.py: "All built-in steps: NLP extraction, neuron creation, synapse wiring, fiber bundling (905 LOC)"
      retrieval:
        retrieval.py: "ReflexPipeline - main retrieval engine with spreading activation (955 LOC)"
        retrieval_types.py: "DepthLevel (instant/context/habit/deep), RetrievalResult, Subgraph"
        retrieval_context.py: "Context formatting for LLM consumption"
        activation.py: "SpreadingActivation - classic BFS activation"
        reflex_activation.py: "ReflexActivation - trail-based fiber pathway activation"
        stabilization.py: "Iterative dampening until activation convergence"
      consolidation:
        consolidation.py: "ConsolidationEngine - prune/merge/summarize/mature/infer/enrich/dream/dedup (965 LOC)"
        consolidation_delta.py: "Immutable delta reporting for consolidation"
        enrichment.py: "Transitive closure + cross-cluster linking"
        dream.py: "Dream exploration for hidden connections"
        merge.py: "Fiber merge logic"
      memory_lifecycle:
        lifecycle.py: "ReinforcementManager - Hebbian strengthening on access"
        memory_stages.py: "Maturation stages: EPISODIC → CONSOLIDATING → SEMANTIC → PROCEDURAL"
        learning_rule.py: "Hebbian + anti-Hebbian learning rules"
        write_queue.py: "DeferredWriteQueue - non-blocking writes after retrieval"
      conflict_system:
        conflict_detection.py: "Real-time conflict detection: FACTUAL_CONTRADICTION + DECISION_REVERSAL"
        conflict_auto_resolve.py: "Automated conflict resolution strategies"
      intelligence:
        associative_inference.py: "Co-activation based inference (pure functional, zero storage calls)"
        causal_traversal.py: "Causal chain tracing + event sequence + temporal range queries"
        pattern_extraction.py: "Semantic pattern extraction from mature episodic memories"
        sequence_mining.py: "Action sequence mining for habit learning"
        topology_analysis.py: "Graph topology analysis (clustering, centrality)"
        reconstruction.py: "Answer reconstruction from activated subgraph"
        workflow_suggest.py: "Workflow next-action suggestions from learned habits"
      brain_management:
        brain_evolution.py: "Brain evolution metrics: maturation, plasticity, coherence, proficiency"
        brain_versioning.py: "Snapshot-based version control: create/list/rollback/diff"
        brain_transplant.py: "Cross-brain memory transplant with conflict resolution"
      training:
        doc_trainer.py: "Train brain from markdown/text documentation"
        doc_chunker.py: "Semantic document chunking with heading hierarchy"
        db_trainer.py: "Train brain from database schema"
        db_introspector.py: "SQLite database introspection (tables, columns, relationships)"
        db_knowledge.py: "Database knowledge extraction and encoding"
        codebase_encoder.py: "Codebase indexing - scan Python/JS/TS/Go/Rust/Java/C files"
      diagnostics:
        diagnostics.py: "Brain health diagnostics: purity, freshness, coverage, clarity (604 LOC)"
      hooks:
        hooks.py: "Event bus for pre/post encoding/retrieval hooks"
      embedding:
        embedding/provider.py: "EmbeddingProvider protocol"
        embedding/sentence_transformer.py: "SentenceTransformer local embedding"
        embedding/openai_embedding.py: "OpenAI API embedding"
        embedding/config.py: "Embedding configuration"
      dedup:
        dedup/pipeline.py: "LLM-assisted deduplication pipeline"
        dedup/llm_judge.py: "LLM judge for semantic duplicate detection"
        dedup/prompts.py: "Dedup prompt templates"
        dedup/config.py: "Dedup configuration"

  # ── STORAGE (6,841 LOC, 23 files) ───────────────────────────────────
  storage:
    path: src/neural_memory/storage/
    loc: 6841
    files: 23
    purpose: "SQLite async persistence layer"
    components:
      base.py: "NeuralStorage abstract base (protocol)"
      sqlite_store.py: "Main SQLiteStorage implementation"
      sqlite_schema.py: "Schema v13 with 13 migration steps"
      sqlite_neurons.py: "Neuron CRUD mixin"
      sqlite_synapses.py: "Synapse CRUD mixin"
      sqlite_fibers.py: "Fiber CRUD mixin"
      sqlite_brain_ops.py: "Brain operations mixin (create/switch/export/import)"
      sqlite_coactivation.py: "Co-activation event storage"
      sqlite_maturation.py: "Memory maturation records"
      sqlite_versioning.py: "Brain version snapshots"
      sqlite_action_log.py: "Action event logging for habits"
      sqlite_projects.py: "Project storage"
      sqlite_sync_state.py: "Sync state tracking"
      sqlite_typed.py: "Type-safe query helpers"
      sqlite_row_mappers.py: "Row → dataclass mappers"
      shared_store.py: "SharedStorage - REST client for shared mode"
      shared_store_collections.py: "Shared store collection operations"
      shared_store_mappers.py: "Shared store data mappers"
      memory_store.py: "MemoryStore convenience wrapper"
      memory_brain_ops.py: "High-level brain operations"
      memory_collections.py: "Collection operations"
      factory.py: "Storage factory (create by mode)"

  # ── MCP SERVER (4,545 LOC, 17 files) ────────────────────────────────
  mcp:
    path: src/neural_memory/mcp/
    loc: 4545
    files: 17
    purpose: "MCP server for Claude Code integration (stdio transport)"
    components:
      server.py: "Main MCP server loop + tool dispatcher"
      tool_schemas.py: "All 22 MCP tool definitions"
      tool_handlers.py: "Core tool handlers (remember/recall/context/todo/stats/suggest)"
      auto_handler.py: "Auto-capture handler (process/analyze/flush)"
      auto_capture.py: "Auto-capture logic + preference pattern extraction"
      session_handler.py: "Session state management (get/set/end)"
      eternal_handler.py: "Eternal context handler (project persistence)"
      conflict_handler.py: "Conflict management handler (list/resolve/check)"
      index_handler.py: "Codebase indexing handler"
      train_handler.py: "Document training handler"
      db_train_handler.py: "Database schema training handler"
      maintenance_handler.py: "Brain maintenance tools (health/evolution/habits/version/transplant)"
      mem0_sync_handler.py: "Mem0 sync handler"
      prompt.py: "System prompt generation for Claude Code"
      constants.py: "MCP constants and limits"

  # ── REST API SERVER (2,698 LOC, 13 files) ───────────────────────────
  server:
    path: src/neural_memory/server/
    loc: 2698
    files: 13
    purpose: "FastAPI REST API + Web Dashboard"
    components:
      app.py: "FastAPI app factory"
      dependencies.py: "Dependency injection"
      models.py: "Pydantic request/response models"
      routes/memory.py: "Memory CRUD endpoints"
      routes/brain.py: "Brain management endpoints"
      routes/consolidation.py: "Consolidation trigger endpoint"
      routes/dashboard_api.py: "Dashboard data API (stats, timeline, fibers, health)"
      routes/openclaw_api.py: "OpenClaw config API (Telegram, Discord, functions, security)"
      routes/integration_status.py: "Integration activity monitoring"
      routes/oauth.py: "OAuth provider management"
      routes/sync.py: "Sync stats endpoint"
      static/: "Dashboard frontend assets"

  # ── CLI (6,204 LOC, 24 files) ───────────────────────────────────────
  cli:
    path: src/neural_memory/cli/
    loc: 6204
    files: 24
    purpose: "Command-line interface (Typer-based)"
    # See CLI_COMMANDS section below for full command list

  # ── INTEGRATION (2,476 LOC, 12 files) ───────────────────────────────
  integration:
    path: src/neural_memory/integration/
    loc: 2476
    files: 12
    purpose: "External system adapters for memory import"
    adapters:
      chromadb_adapter.py: "ChromaDB vector store import"
      mem0_adapter.py: "Mem0 memory platform import"
      graphiti_adapter.py: "Graphiti knowledge graph import"
      cognee_adapter.py: "Cognee AI memory import"
      llamaindex_adapter.py: "LlamaIndex vector index import"
      awf_adapter.py: "AWF (Anthropic Workflow) import"
    core:
      adapter.py: "Base adapter protocol"
      mapper.py: "Data mapping utilities"
      models.py: "Integration data models"
      sync_engine.py: "Sync orchestration engine"

  # ── INTEGRATIONS (1,044 LOC, 9 files) ───────────────────────────────
  integrations:
    path: src/neural_memory/integrations/
    loc: 1044
    files: 9
    purpose: "Additional integration helpers"
    components:
      openclaw_config.py: "OpenClaw configuration management"
      nanobot/: "Nanobot integration (Telegram/Discord bot)"

  # ── EXTRACTION (3,818 LOC, 10 files) ────────────────────────────────
  extraction:
    path: src/neural_memory/extraction/
    loc: 3818
    files: 10
    purpose: "NLP extraction pipeline - query parsing, entity/keyword/temporal extraction"
    components:
      parser.py: "QueryParser - main query decomposition (Stimulus, QueryIntent)"
      router.py: "QueryRouter - route to specialized handlers"
      entities.py: "Named entity extraction"
      keywords.py: "Keyword extraction"
      temporal.py: "Temporal expression parsing (dates, ranges, relative times)"
      relations.py: "Relation extraction"
      sentiment.py: "Sentiment analysis"
      codebase.py: "Codebase-specific extraction (function/class/import parsing)"
      llm_provider.py: "LLM provider for extraction tasks"

  # ── SAFETY (647 LOC, 3 files) ───────────────────────────────────────
  safety:
    path: src/neural_memory/safety/
    loc: 647
    files: 3
    purpose: "Content safety and freshness evaluation"
    components:
      sensitive.py: "Sensitive content detection (PII, secrets, credentials)"
      freshness.py: "Memory freshness scoring based on age"

  # ── UTILS (410 LOC, 5 files) ────────────────────────────────────────
  utils:
    path: src/neural_memory/utils/
    loc: 410
    files: 5
    purpose: "Shared utilities"
    components:
      timeutils.py: "UTC datetime helpers (utcnow)"
      simhash.py: "SimHash for near-duplicate detection"
      config.py: "Config path resolution"
      tag_normalizer.py: "Tag normalization + drift detection"

  # ── CONFIG (38,911 LOC, 2 files) ────────────────────────────────────
  config:
    loc: 38911
    purpose: "Master configuration system"
    components:
      unified_config.py: "UnifiedConfig - TOML-based config with migration from JSON (33,134 LOC)"
      config_presets.py: "Configuration presets for different use cases (5,777 LOC)"
      git_context.py: "Git context detection for auto-config (2,001 LOC)"

  # ── SYNC (464 LOC, 2 files) ────────────────────────────────────────
  sync:
    path: src/neural_memory/sync/
    loc: 464
    files: 2
    purpose: "Local ↔ Server synchronization logic"

# ============================================================================
# CLI COMMANDS (pug / neural-memory)
# ============================================================================

cli_commands:
  top_level:
    remember: {desc: "Store a memory", args: "content, --type, --tags, --priority, --expires"}
    recall: {desc: "Query memories", args: "query, --depth, --max-tokens, --json"}
    context: {desc: "Get recent context", args: "--limit, --fresh-only"}
    todo: {desc: "Add a TODO memory", args: "task, --priority"}
    stats: {desc: "Brain statistics", args: "--json"}
    check: {desc: "Run diagnostic checks", args: ""}
    status: {desc: "Show current brain status", args: "--json"}
    health: {desc: "Brain health diagnostics", args: "--json"}
    version: {desc: "Show version", args: ""}
    list: {desc: "List memories/fibers", args: "--type, --limit, --json"}
    cleanup: {desc: "Clean up old/expired memories", args: "--dry-run"}
    index: {desc: "Index codebase into memory", args: "path, --extensions"}
    train: {desc: "Train brain from docs", args: "path, --domain, --extensions"}
    consolidate: {desc: "Run consolidation", args: "--strategy, --dry-run"}
    decay: {desc: "Apply time decay to synapses", args: ""}
    mcp: {desc: "Start MCP server (stdio)", args: ""}
    dashboard: {desc: "Start web dashboard", args: "--port, --host"}
    ui: {desc: "Open dashboard in browser", args: ""}
    serve: {desc: "Start REST API server", args: "--port, --host"}
    graph: {desc: "Visualize brain graph", args: "--output"}
    init: {desc: "Initialize neural-memory in project", args: ""}
    hooks: {desc: "Manage pre/post hooks", args: ""}
    install-skills: {desc: "Install Claude Code skills", args: ""}
    update: {desc: "Check for updates", args: ""}
    prompt: {desc: "Generate system prompt for Claude", args: ""}
    mcp-config: {desc: "Show MCP configuration snippet", args: ""}
    export: {desc: "Export current brain to JSON", args: "--output"}
    import: {desc: "Import brain from JSON", args: "file, --merge"}

  shortcuts:
    q: {desc: "Quick recall (alias)", args: "query"}
    a: {desc: "Quick add memory (alias)", args: "content"}
    last: {desc: "Show last N memories", args: "--limit"}
    today: {desc: "Show today's memories", args: ""}

  brain_subcommands: # pug brain <cmd>
    list: {desc: "List all brains", args: "--json"}
    use: {desc: "Switch active brain", args: "name"}
    create: {desc: "Create new brain", args: "name, --preset"}
    export: {desc: "Export brain to JSON", args: "--output"}
    import: {desc: "Import brain from JSON", args: "file, --merge, --name"}
    delete: {desc: "Delete a brain", args: "name, --force"}
    transplant: {desc: "Transplant memories between brains", args: "source, --tags, --types, --strategy"}
    health: {desc: "Brain health report", args: "name, --json"}

  config_subcommands: # pug config <cmd>
    preset: {desc: "Apply configuration preset", args: "name"}

  project_subcommands: # pug project <cmd>
    create: {desc: "Create a project", args: "name, --description"}
    list: {desc: "List projects", args: "--active-only"}
    show: {desc: "Show project details", args: "name"}
    delete: {desc: "Delete a project", args: "name"}
    extend: {desc: "Extend project metadata", args: "name, --key, --value"}

  shared_subcommands: # pug shared <cmd>
    enable: {desc: "Enable shared mode (connect to server)", args: "server_url"}
    disable: {desc: "Disable shared mode (use local)", args: ""}
    status: {desc: "Show shared mode status", args: "--json"}
    test: {desc: "Test server connection", args: ""}
    sync: {desc: "Manual sync (push/pull/both)", args: "direction"}

  habits_subcommands: # pug habits <cmd>
    list: {desc: "List learned habits", args: "--json"}
    show: {desc: "Show habit details", args: "name"}
    clear: {desc: "Clear all habits", args: "--force"}

  version_subcommands: # pug version <cmd>
    create: {desc: "Create version snapshot", args: "name, --description"}
    list: {desc: "List versions", args: "--limit"}
    rollback: {desc: "Rollback to version", args: "version_id, --force"}
    diff: {desc: "Diff two versions", args: "from_version, to_version"}

# ============================================================================
# MCP TOOLS (22 tools for Claude Code)
# ============================================================================

mcp_tools:
  memory_ops:
    pugbrain_remember: {desc: "Store a memory", params: "content*, type?, priority?, tags?, expires_days?"}
    pugbrain_recall: {desc: "Query memories with spreading activation", params: "query*, depth?, max_tokens?, min_confidence?, valid_at?, include_conflicts?"}
    pugbrain_context: {desc: "Get recent context for session start", params: "limit?, fresh_only?"}
    pugbrain_todo: {desc: "Quick TODO with 30-day expiry", params: "task*, priority?"}
    pugbrain_suggest: {desc: "Autocomplete from brain neurons", params: "prefix*, limit?, type_filter?"}

  session_management:
    pugbrain_session: {desc: "Track session state (task/feature/progress)", params: "action*(get/set/end), feature?, task?, progress?, notes?"}
    pugbrain_eternal: {desc: "Save project context cross-session", params: "action*(status/save), project_name?, tech_stack?, decision?, reason?, instruction?"}
    pugbrain_recap: {desc: "Load saved context at session start", params: "level?(1-3), topic?"}

  diagnostics:
    pugbrain_stats: {desc: "Brain statistics (counts, freshness)", params: "none"}
    pugbrain_health: {desc: "Brain health diagnostics (purity, grade)", params: "none"}
    pugbrain_evolution: {desc: "Brain evolution metrics (maturation, plasticity)", params: "none"}

  brain_management:
    pugbrain_version: {desc: "Version control (snapshot/rollback/diff)", params: "action*(create/list/rollback/diff), name?, version_id?, from_version?, to_version?, limit?"}
    pugbrain_transplant: {desc: "Transplant memories between brains", params: "source_brain*, tags?, memory_types?, strategy?"}
    pugbrain_conflicts: {desc: "Manage memory conflicts", params: "action*(list/resolve/check), neuron_id?, resolution?, content?, tags?, limit?"}
    pugbrain_habits: {desc: "Manage workflow habits", params: "action*(suggest/list/clear), current_action?"}

  training:
    pugbrain_index: {desc: "Index codebase into memory", params: "action*(scan/status), path?, extensions?"}
    pugbrain_train: {desc: "Train from docs (md/txt/rst)", params: "action*(train/status), path?, domain_tag?, brain_name?, extensions?, consolidate?"}
    pugbrain_train_db: {desc: "Train from database schema", params: "action*(train/status), connection_string?, domain_tag?, brain_name?, consolidate?, max_tables?"}

  auto_capture:
    pugbrain_auto: {desc: "Auto-capture from text", params: "action*(status/enable/disable/analyze/process/flush), text?, save?"}

  import:
    pugbrain_import: {desc: "Import from external systems", params: "source*(chromadb/mem0/awf/cognee/graphiti/llamaindex), connection?, collection?, limit?, user_id?"}

# ============================================================================
# REST API ENDPOINTS
# ============================================================================

rest_api:
  memory: # /api/memory
    - {method: POST, path: "/encode", desc: "Encode new memory"}
    - {method: POST, path: "/query", desc: "Query memories"}
    - {method: GET, path: "/fiber/{fiber_id}", desc: "Get fiber details"}
    - {method: GET, path: "/neurons", desc: "List neurons"}
    - {method: GET, path: "/suggest", desc: "Autocomplete suggestions"}
    - {method: POST, path: "/index", desc: "Index codebase"}

  brain: # /api/brain
    - {method: POST, path: "/create", desc: "Create brain"}
    - {method: GET, path: "/{brain_id}", desc: "Get brain info"}
    - {method: GET, path: "/{brain_id}/stats", desc: "Brain statistics"}
    - {method: GET, path: "/{brain_id}/export", desc: "Export brain"}
    - {method: POST, path: "/{brain_id}/import", desc: "Import brain"}
    - {method: POST, path: "/{brain_id}/merge", desc: "Merge brains"}
    - {method: DELETE, path: "/{brain_id}", desc: "Delete brain"}

  consolidation: # /api/consolidation
    - {method: POST, path: "/{brain_id}/consolidate", desc: "Run consolidation"}

  dashboard: # /api/dashboard
    - {method: GET, path: "/stats", desc: "Dashboard statistics"}
    - {method: GET, path: "/brains", desc: "List brains"}
    - {method: POST, path: "/brains/switch", desc: "Switch active brain"}
    - {method: GET, path: "/health", desc: "Health diagnostics"}
    - {method: GET, path: "/timeline", desc: "Memory timeline"}
    - {method: GET, path: "/fibers", desc: "List fibers"}
    - {method: GET, path: "/fiber/{fiber_id}/diagram", desc: "Fiber diagram"}

  openclaw: # /api/openclaw
    - {method: GET, path: "/config", desc: "Get OpenClaw config"}
    - {method: POST, path: "/config", desc: "Update config"}
    - {method: POST, path: "/apikeys", desc: "Save API key"}
    - {method: DELETE, path: "/apikeys/{provider}", desc: "Delete API key"}
    - {method: GET, path: "/telegram", desc: "Telegram bot status"}
    - {method: POST, path: "/telegram", desc: "Configure Telegram"}
    - {method: GET, path: "/discord", desc: "Discord bot status"}
    - {method: POST, path: "/discord", desc: "Configure Discord"}
    - {method: GET, path: "/functions", desc: "List functions"}
    - {method: POST, path: "/functions/{name}", desc: "Toggle function"}
    - {method: GET, path: "/security", desc: "Security settings"}
    - {method: POST, path: "/security", desc: "Update security"}

  oauth: # /api/oauth
    - {method: GET, path: "/providers", desc: "List OAuth providers"}
    - {method: POST, path: "/initiate", desc: "Start OAuth flow"}
    - {method: POST, path: "/callback", desc: "OAuth callback"}
    - {method: GET, path: "/status/{provider}", desc: "Provider status"}

  sync: # /api/sync
    - {method: GET, path: "/stats", desc: "Sync statistics"}
    - {method: WS, path: "/ws", desc: "WebSocket real-time sync (neuron/synapse/fiber events)"}

  visualization:
    - {method: GET, path: "/api/graph", desc: "Graph data for visualization (limit, offset)"}
    - {method: GET, path: "/ui", desc: "Legacy vis.js graph visualization"}
    - {method: GET, path: "/dashboard", desc: "Dashboard SPA"}

  health:
    - {method: GET, path: "/", desc: "Root API info"}
    - {method: GET, path: "/health", desc: "Health check"}

  integration: # /api/integration
    - {method: GET, path: "/activity", desc: "Integration activity log"}

# ============================================================================
# EXTERNAL INTEGRATIONS (Import Sources)
# ============================================================================

integrations:
  chromadb: {desc: "ChromaDB vector store", type: VECTOR_DB, import: true, capabilities: [FETCH_ALL, FETCH_EMBEDDINGS, FETCH_METADATA, HEALTH_CHECK]}
  mem0: {desc: "Mem0 memory platform (cloud + self-hosted)", type: MEMORY_LAYER, import: true, capabilities: [FETCH_ALL, FETCH_METADATA, HEALTH_CHECK], auth: "MEM0_API_KEY env var"}
  graphiti: {desc: "Graphiti knowledge graph (Neo4j-based)", type: GRAPH_STORE, import: true, capabilities: [FETCH_ALL, FETCH_SINCE, FETCH_RELATIONSHIPS, FETCH_METADATA, HEALTH_CHECK]}
  cognee: {desc: "Cognee AI concept graph", type: GRAPH_STORE, import: true, capabilities: [FETCH_ALL, FETCH_RELATIONSHIPS, FETCH_METADATA, HEALTH_CHECK], auth: "COGNEE_API_KEY env var"}
  llamaindex: {desc: "LlamaIndex vector index", type: INDEX_STORE, import: true, capabilities: [FETCH_ALL, FETCH_EMBEDDINGS, FETCH_METADATA, HEALTH_CHECK]}
  awf: {desc: "Antigravity Workflow Framework (.brain/ dir)", type: FILE_STORE, import: true, capabilities: [FETCH_ALL, FETCH_METADATA, HEALTH_CHECK], tiers: ["brain.json (static)", "session.json (current)", "snapshots/ (historical)"]}

# ============================================================================
# EMBEDDING PROVIDERS
# ============================================================================

embedding_providers:
  sentence_transformer: {desc: "Local SentenceTransformer model", default: true}
  openai: {desc: "OpenAI API embeddings", requires: "OPENAI_API_KEY env var"}

# ============================================================================
# KEY FEATURES BY CATEGORY
# ============================================================================

features:
  memory_operations:
    - "Store memories with auto-detected types (fact/decision/preference/todo/insight/context/instruction/error/workflow/reference)"
    - "Priority system (0-10) with expiration support"
    - "Auto-tagging via NLP extraction (entities, keywords, temporal)"
    - "Sensitive content detection (PII, secrets, credentials)"
    - "Memory freshness scoring based on age"

  retrieval:
    - "Spreading activation through neural graph (not keyword search)"
    - "4 depth levels: instant (1 hop), context (3 hops), habit (4 hops), deep (full)"
    - "ReflexActivation - trail-based fiber pathway retrieval"
    - "Lateral inhibition - cluster-aware top-K suppression"
    - "Stabilization - iterative dampening until convergence"
    - "Disputed neuron deprioritization (conflict-aware)"
    - "Temporal reasoning: causal chains, event sequences, time range queries"
    - "Embedding fallback (semantic similarity via SentenceTransformer/OpenAI)"
    - "Query expansion with morphological variants"
    - "Point-in-time temporal filtering (valid_at parameter)"

  consolidation:
    - "9 strategies: prune, merge, summarize, mature, infer, enrich, dream, learn_habits, dedup"
    - "Parallel execution within dependency tiers"
    - "Time-based synapse decay with high-salience protection"
    - "Fiber merging via inverted index + Union-Find (O(n*m))"
    - "Tag-based clustering for concept neuron creation"
    - "Memory maturation stages: EPISODIC → CONSOLIDATING → SEMANTIC → PROCEDURAL"
    - "Associative inference from co-activation patterns"
    - "Dream exploration for hidden cross-cluster connections"
    - "SimHash-based near-duplicate detection"
    - "LLM-assisted semantic deduplication"

  conflict_detection:
    - "Real-time conflict detection at encode time (no LLM needed)"
    - "Factual contradiction detection via predicate extraction"
    - "Decision reversal detection via tag overlap"
    - "Anti-Hebbian confidence reduction for disputed neurons"
    - "CONTRADICTS synapse creation between conflicting memories"
    - "Manual conflict resolution (keep_existing/keep_new/keep_both)"

  brain_management:
    - "Multiple brain support (create/switch/delete)"
    - "Brain export/import (JSON)"
    - "Brain version control (snapshot/rollback/diff)"
    - "Cross-brain memory transplant with conflict resolution strategies"
    - "Brain health diagnostics (purity, freshness, coverage, clarity)"
    - "Brain evolution metrics (maturation, plasticity, coherence, proficiency)"
    - "Configuration presets for different use cases"

  training:
    - "Train from documentation (markdown, text, RST with heading hierarchy)"
    - "Train from database schema (SQLite, table structures + relationships)"
    - "Codebase indexing (Python, JS/TS, Go, Rust, Java, C/C++)"
    - "Semantic chunking with heading-aware splitting"
    - "Auto-consolidation after training"

  session_management:
    - "Session state tracking (task/feature/progress)"
    - "Eternal context persistence (project name, tech stack, decisions, instructions)"
    - "Session recap at varying detail levels (quick/detailed/full)"

  auto_capture:
    - "Automatic memory extraction from conversation text"
    - "Preference pattern detection"
    - "Emergency flush before context compaction (anti-amnesia)"
    - "Session gap detection"

  workflow_intelligence:
    - "Action sequence mining for habit learning"
    - "Workflow next-action suggestions"
    - "Autocomplete from brain neurons"

  sharing:
    - "Local mode (default) - SQLite storage"
    - "Shared mode - connect to remote REST server"
    - "Hybrid mode - offline-first with periodic sync"
    - "Manual sync (push/pull/both)"

  integrations_features:
    - "Import from 6 external systems (ChromaDB, Mem0, AWF, Cognee, Graphiti, LlamaIndex)"
    - "OpenClaw config (Telegram bot, Discord bot, custom functions)"
    - "OAuth provider management"

# ============================================================================
# MAINTENANCE SCHEDULE TEMPLATE
# ============================================================================

maintenance_branches:
  critical_path:
    desc: "Core encoding + retrieval pipeline - any bug here breaks everything"
    modules: [engine/encoder.py, engine/retrieval.py, engine/pipeline_steps.py, engine/activation.py, engine/reflex_activation.py]
    audit_frequency: "Every release"
    risk: HIGH

  storage_layer:
    desc: "Data persistence - schema migrations, data integrity"
    modules: [storage/sqlite_store.py, storage/sqlite_schema.py, storage/sqlite_neurons.py, storage/sqlite_synapses.py, storage/sqlite_fibers.py]
    audit_frequency: "Every release"
    risk: HIGH

  security_surface:
    desc: "User-facing interfaces - SQL, path handling, input validation"
    modules: [server/routes/*, mcp/server.py, mcp/tool_handlers.py, engine/db_introspector.py, engine/codebase_encoder.py]
    audit_frequency: "Every release"
    risk: HIGH

  consolidation_engine:
    desc: "Background maintenance - can run stale but needs periodic review"
    modules: [engine/consolidation.py, engine/dream.py, engine/enrichment.py, engine/merge.py]
    audit_frequency: "Quarterly"
    risk: MEDIUM

  intelligence_layer:
    desc: "Inference, patterns, habits - quality affects relevance not stability"
    modules: [engine/associative_inference.py, engine/pattern_extraction.py, engine/sequence_mining.py, engine/workflow_suggest.py]
    audit_frequency: "Quarterly"
    risk: MEDIUM

  config_system:
    desc: "Configuration + migration - complex but rarely changes"
    modules: [unified_config.py, config_presets.py]
    audit_frequency: "On config format changes"
    risk: MEDIUM

  integration_adapters:
    desc: "External system adapters - breakage is isolated per adapter"
    modules: [integration/adapters/*, integrations/*]
    audit_frequency: "When upstream APIs change"
    risk: LOW

  cli_layer:
    desc: "CLI commands - user-facing but low blast radius"
    modules: [cli/commands/*]
    audit_frequency: "Biannual"
    risk: LOW

  diagnostics:
    desc: "Health checks, evolution metrics - read-only, safe"
    modules: [engine/diagnostics.py, engine/brain_evolution.py, engine/topology_analysis.py]
    audit_frequency: "Biannual"
    risk: LOW

# ============================================================================
# TEST COVERAGE
# ============================================================================

testing:
  framework: pytest
  plugins: [pytest-asyncio, pytest-cov, pytest-xdist, pytest-timeout]
  coverage_threshold: "67% (CI enforced)"
  test_counts:
    unit: "89 files (~21,000 LOC)"
    integration: "2 files"
    e2e: "1 file"
    stress: "6 files"
  ci_matrix: "Python 3.11 + 3.12"
  linting: "ruff (25+ rule sets including bandit security)"
  type_checking: "mypy strict mode (0 errors required)"

# ============================================================================
# DEPENDENCIES
# ============================================================================

dependencies:
  required:
    - "pydantic>=2.0 (data validation)"
    - "networkx>=3.0 (graph algorithms)"
    - "python-dateutil>=2.8 (date parsing)"
    - "typer>=0.9.0 (CLI framework)"
    - "aiohttp>=3.9.0 (async HTTP)"
    - "aiosqlite>=0.19.0 (async SQLite)"
    - "rich>=13.0.0 (terminal formatting)"
    - "typing_extensions>=4.0"
  optional_server: "fastapi, uvicorn, httpx"
  optional_embedding: "sentence-transformers, openai"
  optional_dev: "pytest, ruff, mypy, pre-commit"
