# lenotfound/qjinera architecture

> Architecture diagram of the GitHub repository lenotfound/qjinera, generated by GitDiagram from its file tree, README and a sample of source files (last updated 2026-03-09). It is an AI-made overview: check details against the source.

- Interactive diagram: https://gitdiagram.com/lenotfound/qjinera
- Repository: https://github.com/lenotfound/qjinera

## Overview

##### 项目类型与目的（从 README + 文件树归纳）
这是一个 **Python 3.10+ 的 QQ 群聊拟人化 Bot**，基于 **AliceBot**（Bot 框架）+ **NapCat / OneBot v11**（QQ 协议适配与 WS 网关），核心能力是：
- **四模型协同**（Judge / Writer(Chat) / Extractor / Consolidator）
- **增量式记忆**（Facts → Consolidate 成长期印象/描述）
- **主动插话/主动话题**（调度器）
- **Dashboard 监控**（Streamlit 实时可视化“思维流/记忆流”）
- **SQLite 持久化**（`qjinera.db` 自动生成，storage 模块）

因此你的系统设计图不应该画成“一个 bot 调 OpenAI”那么简单，而应拆成：**消息入口层、策略决策层、对话生成层、记忆流水线、调度/后台任务、存储层、监控面板、外部 LLM**。

##### 读文件树：架构分层与关键模块定位
按目录/文件名可以较稳定地映射到以下分层（你画图时可直接用这些组件名）：

##### 启动与配置
- `main.py`：Bot 进程入口（启动 AliceBot、注册插件、连接 NapCat WS、初始化服务）
- `config.py` + `example.config.toml`（实际运行是 `config.toml`）：LLM 端点/模型名/阈值/Prompt/策略参数
- `logger.py`：统一日志/事件记录（Dashboard 多半依赖它产出的可观测数据）

##### 插件层（AliceBot 插件 = “控制面”核心）
- `plugins/core.py`：**消息流处理与模型调度中枢**（README 指的“核心：消息流处理与模型调度”）
- 这里通常是：接入 OneBot 事件 → 组织上下文 → 调用 Judge/Writer/Extractor → 发送消息
- （文件树里 `plugins/scheduler.py` 不在，但存在 `services/scheduler.py`；以 file tree 为准）
- 主动话题/定时任务很可能由 `services/scheduler.py` 提供能力，然后被 `plugins/core.py` 或 `main.py` 注册/启动

##### 业务服务层（“数据面”能力封装）
- `services/llm.py`：LLM 统一接口封装（四模型调用都从这里走）
- `services/topic.py`：话题与上下文管理（topic 边界判定、topic 状态、可能用于判断“话题结束”触发巩固）
- `services/memory_service.py`：记忆巩固服务（Extractor 的 facts 缓存 + Consolidator 的长期化写入）
- `services/scheduler.py`：主动社交/定时触发（群冷场抛话题、定期 consolidate 或 housekeeping 等）

##### 存储层（SQLite + 数据访问对象）
- `services/storage/database.py`：SQLite 连接/初始化/迁移（如果有）
- `services/storage/{users.py, topics.py, memories.py, decisions.py}`：按领域拆分的 DAO/Repository
- `decisions` 很关键：对应 Judge 的“是否插嘴/是否吃瓜”决策记录（Dashboard 的“思维流”也可能读它）
- `services/storage/__init__.py`：导出/聚合 storage API
- `data/`：可能放运行时产物、缓存、导出等（`.gitkeep` 表示目录保留）

##### 监控与可视化
- `dashboard.py`：Streamlit 页面（读取 DB/日志，展示思维流、记忆流、刷新）
- `docs/`：`prd.md` 等说明文档（对画图可提炼业务流程/指标/事件流）

##### 关系/箭头（务必标注方向与协议）
- QQ 群聊 → NapCat：QQ 消息事件
- NapCat ↔ QJinEra：**WebSocket（OneBot v11 事件/发送消息）**
- QJinEra → LLM Provider：HTTPS API（Judge/Writer/Extractor/Consolidator）
- QJinEra ↔ SQLite：本地文件 DB 读写（memories/topics/users/decisions）
- Dashboard → SQLite / 日志：读（可视化）
- Dashboard ↔ 运维者：HTTP（浏览器访问 Streamlit）

> 这张图的目标：说明“系统边界在哪里、外部依赖有哪些、数据从哪里来/到哪里去”。

把 “QJinEra Bot 进程”拆成内部容器/子系统（哪怕都在一个进程里，也建议逻辑容器化）：

##### 容器/子系统（对应文件）
- **Entry & Bootstrap**
- `main.py`, `config.py`, `logger.py`
- **AliceBot Plugin Layer**
- `plugins/core.py`（事件入口 + 编排）
- **Service Layer**
- LLM Service：`services/llm.py`
- Topic Service：`services/topic.py`
- Memory Service：`services/memory_service.py`
- Scheduler：`services/scheduler.py`
- **Storage Layer (SQLite Repos)**
- `services/storage/database.py`
- `services/storage/users.py`
- `services/storage/topics.py`
- `services/storage/memories.py`
- `services/storage/decisions.py`
- **Dashboard App**
- `dashboard.py`（单独进程运行：`streamlit run`）

##### 容器间交互（用粗箭头标主路径）
- NapCat WS 事件 → `plugins/core.py`
- `plugins/core.py` → `services/llm.py`（调用四模型）
- `plugins/core.py` ↔ `services/topic.py`（读写 topic 状态/上下文）
- `plugins/core.py` → `services/storage/*`（记录 decisions / 消息相关数据）
- `services/memory_service.py` ↔ `services/storage/memories.py`（facts/长期印象持久化）
- `services/scheduler.py` → `plugins/core.py` 或 → `services/topic.py`（触发主动话题/触发 consolidate）
- Dashboard → Storage（读 decisions/memories/topics/users）+ （可选）读日志

> 这张图的目标：让读者一眼明白“代码结构对应的架构分层”。

##### 图 3：Component / Sequence（组件/时序图：四模型协同 + 记忆流水线）
这项目的“独特性”在于四模型与记忆巩固，所以建议画 **两条时序**：实时回复链路 + 话题结束巩固链路。

##### 6.1 实时消息处理（核心链路）
建议时序参与者（从左到右）：
- QQ User → NapCat → AliceBot/`plugins/core.py`
- `services/topic.py`
- `services/llm.py`（内部再标注四个 logical model calls）
- `services/storage/decisions.py`, `services/storage/topics.py`（可选）
- NapCat（发送消息回 QQ）

建议步骤（用编号标注）：
##### 如果需要回复：
- **Writer(Chat) 调用**：`llm.chat(...)` 生成回复草案
- 分条/打字延迟策略（应在 core 或 service 中体现；至少在图上标注“Message Post-processing: split + delay”）
##### 并行/或后置：
- **Extractor 调用**：`llm.extract(...)` 从对话中抽取 Facts
- Facts 写入短期缓存/或 DB（在图里标注“Short-term facts buffer”，落地位置可写 Memory Service）

##### 6.2 话题结束后的“赛博回响”（巩固链路）
参与者：
- `services/topic.py`（检测 topic end / idle）
- `services/memory_service.py`
- `services/llm.py`（Consolidator）
- `services/storage/memories.py`, `services/storage/topics.py`, `services/storage/users.py`

建议步骤：
##### 标记 topic 已巩固/归档（topics 表）

> 这张图的目标：把 README 的“四模型架构 + 增量记忆 + 赛博回响”落实为工程可读的链路。

##### 关系与交互：在图上必须显式标注的“关键点”
为了“最准确”，建议你在箭头旁写清楚以下语义（否则读者会以为只是普通聊天 Bot）：
- Judge 输出的是 **decision**（是否插话、插话类型、阈值命中等），且会被**记录**（`decisions.py`）
- Extractor 产物是 **Facts 列表**，进入短期区（由 `memory_service.py` 管）
- Consolidator 触发条件来自 **topic 生命周期/静默窗口**（`topic.py` + `scheduler.py`）
- Dashboard 的数据源来自 **SQLite/日志**，不是从 LLM 直接来

##### 技术/框架在图中的标注建议（别漏）
- AliceBot（插件驱动、事件回调）
- NapCat / OneBot v11（WS 协议）
- Streamlit（Dashboard 单独进程）
- SQLite（本地 DB 文件）
- 外部 LLM（OpenAI-compatible / Gemini；四个 logical model role）

##### 组件标识
- 用统一命名：`plugins/core.py (Message Orchestrator)`、`services/llm.py (LLM Gateway)`、`services/memory_service.py (Memory Pipeline)` 等
- 组件框里同时写：**职责 + 对应文件路径**（对代码读者最友好）

##### 箭头与数据流
- 实线：同步调用（WS/HTTP/函数调用）
- 虚线：异步/延迟任务（scheduler 触发、consolidation 后台）
- 箭头 label 里写 payload：`OneBot Event` / `Decision` / `Facts[]` / `Description` / `DB Read/Write`

##### 颜色/形状建议（简单但信息密度高）
- 外部系统（QQ/NapCat/LLM）：灰色云形
- 应用内部模块（plugin/service/storage）：蓝色矩形
- 数据存储（SQLite）：圆柱体
- 监控/可视化（Streamlit）：绿色矩形

##### 针对该项目的“不要过度思考”的拆分清单（直接照抄到图里）
如果你想“尽可能拆成更多组件”，但仍保持真实可落地，可以按下列粒度：
- Ingress: NapCat WS Client (OneBot)
- Orchestrator: AliceBot Plugin Core (`plugins/core.py`)
- Policy: Judge Pipeline (`services/llm.py::judge`)
- Generation: Writer Pipeline (`services/llm.py::chat`)
- Extraction: Fact Extractor (`services/llm.py::extract`)
- Consolidation: Memory Consolidator (`services/llm.py::consolidate`)
- Context: Topic Manager (`services/topic.py`)
- Memory Pipeline: (`services/memory_service.py`)
- Scheduler: (`services/scheduler.py`)
- Storage: UsersRepo / TopicsRepo / MemoriesRepo / DecisionsRepo (`services/storage/*.py`)
- Observability: Logger (`logger.py`) + Dashboard (`dashboard.py`)
- Config: (`config.py` + `config.toml`)

用这份清单，你基本能画出一张“细到可实现、且和代码严格对应”的架构图。

## Diagram (Mermaid)

```mermaid
flowchart TD
  %% =========================
  %% System Context (C4-L1)
  %% =========================
  subgraph "System Context"
    direction TB
    QQ["QQ Users / Group Chat"]:::external
    NapCat["NapCat (OneBot v11)"]:::external
    BotSys["QJinEra Bot System (AliceBot-based)"]:::system
    LLM["External LLM Provider\n(OpenAI-compatible / Gemini)"]:::external
    DB[("SQLite DB\nqjinera.db")]:::db
    Dash["Dashboard (Streamlit Web UI)"]:::dashboard
    Admin["Operator / Admin"]:::external

    QQ -->|"QQMessageEvents"| NapCat
    NapCat <-->|"WebSocketOneBotv11\nEvents/SendMessage"| BotSys
    BotSys -->|"HTTPSAPI\nJudge/Writer/Extractor/Consolidator"| LLM
    BotSys <-->|"DBReadWrite\nusers/topics/memories/decisions"| DB
    Dash -->|"ReadOnly\nmetrics/thoughtFlow/memoryFlow"| DB
    Dash -->|"ReadOptional\nlogs/events"| BotSys
    Admin <-->|"HTTPBrowser"| Dash
  end

  %% =========================
  %% Container / Module View (C4-L2)
  %% =========================
  subgraph "Bot Process Containers (Single Python App)"
    direction TB

    subgraph "Entry & Bootstrap"
      direction TB
      Main["main.py\nEntry/Bootstrap"]:::bootstrap
      Config["config.py\nConfig Management"]:::bootstrap
      ExCfg["example.config.toml\nExample Config"]:::artifact
      Log["logger.py\nUnified Logging/Observability"]:::obs
    end

    subgraph "AliceBot Plugin Layer"
      direction TB
      Core["plugins/core.py\nMessage Orchestrator\n(Model Scheduling + Reply Send)"]:::plugin
    end

    subgraph "Service Layer"
      direction TB
      LLMsvc["services/llm.py\nLLM Gateway\n(judge/chat/extract/consolidate)"]:::service
      TopicSvc["services/topic.py\nTopic & Context Manager\n(lifecycle/end detection)"]:::service
      MemSvc["services/memory_service.py\nMemory Pipeline\n(facts buffer + consolidation)"]:::service
      Sched["services/scheduler.py\nScheduler\n(proactive topics / timed tasks)"]:::service
    end

    subgraph "Storage Layer (SQLite Repositories)"
      direction TB
      StorageInit["services/storage/__init__.py\nStorage API Facade"]:::storage
      DBMod["services/storage/database.py\nSQLite Connection/Init"]:::storage
      UsersRepo["services/storage/users.py\nUsers Repository"]:::storage
      TopicsRepo["services/storage/topics.py\nTopics Repository"]:::storage
      MemoriesRepo["services/storage/memories.py\nMemories Repository"]:::storage
      DecisionsRepo["services/storage/decisions.py\nDecisions Repository\n(Judge decisions)"]:::storage
      DataDir["data/\nRuntime Data Dir"]:::artifact
    end

    subgraph "Dashboard App (Separate Process)"
      direction TB
      DashApp["dashboard.py\nStreamlit Dashboard"]:::dashboard
    end

    subgraph "Docs"
      direction TB
      PRD["docs/prd.md\nProduct/Architecture Notes"]:::artifact
    end

    %% Internal wiring (main paths)
    Main -->|"loadConfig"| Config
    Main -->|"initLogging"| Log
    Main -->|"registerPlugin"| Core

    Core -->|"contextReadWrite"| TopicSvc
    Core -->|"callLLM\nJudge/Writer/Extractor"| LLMsvc
    Core -->|"recordDecision"| DecisionsRepo
    Core -->|"topicState"| TopicsRepo

    LLMsvc -->|"HTTPSAPI"| LLM

    MemSvc -->|"factsBufferUpdate"| MemoriesRepo
    MemSvc -->|"userImpressionWrite"| UsersRepo
    MemSvc -->|"topicArchiveMark"| TopicsRepo
    MemSvc -->|"callLLM\nConsolidator"| LLMsvc

    Sched -.->|"idleWindowOrTimer\ntriggerConsolidate"| MemSvc
    Sched -.->|"proactiveTopic"| TopicSvc
    Sched -.->|"proactiveInterject\nsignal"| Core

    StorageInit --> DBMod
    DBMod --> DB
    UsersRepo --> DBMod
    TopicsRepo --> DBMod
    MemoriesRepo --> DBMod
    DecisionsRepo --> DBMod

    DBMod -.->|"dbFileIn"| DataDir

    DashApp -->|"readDecisions"| DecisionsRepo
    DashApp -->|"readMemories"| MemoriesRepo
    DashApp -->|"readTopics"| TopicsRepo
    DashApp -->|"readUsers"| UsersRepo
    DashApp -.->|"optionalReadLogs"| Log
  end

  %% Tie System boundary node to internal containers
  BotSys -->|"contains"| Main
  BotSys -->|"contains"| Core
  BotSys -->|"contains"| LLMsvc
  BotSys -->|"contains"| TopicSvc
  BotSys -->|"contains"| MemSvc
  BotSys -->|"contains"| Sched
  BotSys -->|"contains"| StorageInit
  Dash -->|"implementedBy"| DashApp

  %% =========================
  %% Key Runtime Flows (L3-ish)
  %% =========================
  subgraph "Key Runtime Flows (Four-Model + Incremental Memory)"
    direction TB

    subgraph "Realtime Message Handling"
      direction TB
      E1["1.OneBotEventReceived"]:::step
      E2["2.UpdateTopicContext"]:::step
      E3["3.JudgeDecision"]:::step
      E4["4.RecordDecisionToDB\n(Thought Flow)"]:::step
      E5["5.WriterChatGenerateReply"]:::step
      E6["6.PostProcess\n(split + delay)"]:::step
      E7["7.SendMessageViaOneBot"]:::step
      E8["8.ExtractorFacts\n(Short-term facts buffer)"]:::step

      NapCat -->|"Event"| E1 --> E2 --> E3 --> E4 --> E5 --> E6 --> E7 --> NapCat
      E3 -->|"calls"| LLMsvc
      E5 -->|"calls"| LLMsvc
      E8 -->|"calls"| LLMsvc
      E4 -->|"write"| DecisionsRepo
      E2 -->|"readWrite"| TopicSvc
      E8 -.->|"facts[]toBuffer"| MemSvc
    end

    subgraph "Topic End Consolidation (Cyber Echo)"
      direction TB
      C1["1.DetectTopicEndOrIdleWindow"]:::step
      C2["2.LoadFacts/Summary"]:::step
      C3["3.ConsolidatorGenerateDescription"]:::step
      C4["4.PersistLongTermMemory\n(memories/users)"]:::step
      C5["5.ArchiveTopic\n(markConsolidated)"]:::step

      TopicSvc -.->|"topicLifecycleSignal"| C1 --> C2 --> C3 --> C4 --> C5
      Sched -.->|"timerTrigger"| C1
      C3 -->|"calls"| LLMsvc
      C4 -->|"write"| MemoriesRepo
      C4 -->|"write"| UsersRepo
      C5 -->|"write"| TopicsRepo
    end
  end

  %% =========================
  %% Click Events (from component_mapping)
  %% =========================
  click Main "https://github.com/lenotfound/qjinera/blob/main/main.py"
  click Config "https://github.com/lenotfound/qjinera/blob/main/config.py"
  click ExCfg "https://github.com/lenotfound/qjinera/blob/main/example.config.toml"
  click Log "https://github.com/lenotfound/qjinera/blob/main/logger.py"
  click Core "https://github.com/lenotfound/qjinera/blob/main/plugins/core.py"
  click LLMsvc "https://github.com/lenotfound/qjinera/blob/main/services/llm.py"
  click TopicSvc "https://github.com/lenotfound/qjinera/blob/main/services/topic.py"
  click MemSvc "https://github.com/lenotfound/qjinera/blob/main/services/memory_service.py"
  click Sched "https://github.com/lenotfound/qjinera/blob/main/services/scheduler.py"
  click StorageInit "https://github.com/lenotfound/qjinera/blob/main/services/storage/__init__.py"
  click DBMod "https://github.com/lenotfound/qjinera/blob/main/services/storage/database.py"
  click UsersRepo "https://github.com/lenotfound/qjinera/blob/main/services/storage/users.py"
  click TopicsRepo "https://github.com/lenotfound/qjinera/blob/main/services/storage/topics.py"
  click MemoriesRepo "https://github.com/lenotfound/qjinera/blob/main/services/storage/memories.py"
  click DecisionsRepo "https://github.com/lenotfound/qjinera/blob/main/services/storage/decisions.py"
  click DashApp "https://github.com/lenotfound/qjinera/blob/main/dashboard.py"
  click DataDir "https://github.com/lenotfound/qjinera/tree/main/data/"
  click PRD "https://github.com/lenotfound/qjinera/blob/main/docs/prd.md"

  %% =========================
  %% Styles
  %% =========================
  classDef external fill:#ECEFF4,stroke:#4C566A,color:#2E3440,stroke-width:1px
  classDef system fill:#D8DEE9,stroke:#2E3440,color:#2E3440,stroke-width:2px
  classDef bootstrap fill:#BEE3F8,stroke:#2B6CB0,color:#1A365D,stroke-width:1px
  classDef plugin fill:#90CDF4,stroke:#2C5282,color:#1A365D,stroke-width:2px
  classDef service fill:#A3D9FF,stroke:#2B6CB0,color:#1A365D,stroke-width:1px
  classDef storage fill:#FBD38D,stroke:#B7791F,color:#4A2C0A,stroke-width:1px
  classDef db fill:#F6AD55,stroke:#9C4221,color:#4A2C0A,stroke-width:2px
  classDef dashboard fill:#9AE6B4,stroke:#2F855A,color:#1C4532,stroke-width:2px
  classDef obs fill:#C4B5FD,stroke:#6D28D9,color:#2E1065,stroke-width:1px
  classDef artifact fill:#E5E7EB,stroke:#6B7280,color:#111827,stroke-width:1px
  classDef step fill:#FFFFFF,stroke:#374151,color:#111827,stroke-width:1px
```
