mirror of
https://gitcode.com/JianFeeeee/HomeAgent.git
synced 2026-11-05 16:57:32 +00:00
## 起因(生产故障)
A2A 分诊助手(驻留子)把 terminal_create 当一次性命令执行器:
terminal_create(command='cd /usr/lib/node_modules/@deepseek-ai && ls -d */ | head -60 && …')
→ read /dev/ptmx: input/output error
→ 再开 term_7、term_8、term_9 …
链路拆开四层:
① cmd 插件 auto_start=false ⇒ 工具表里没有 cmd_run
② 需要 cmd-tools skill 说明"先 plugin_start cmd"
③ 但 skill 索引没进那个 agent 的提示词
④ 因为 skillIndex 只是根 agent 的字段、由 bootstrap 手工接线
④ 才是总根。而它之所以必须手工接线:agent/core 读不到内核的共享数据。
## 环的精确形状(实测,非推测)
kernelboot 因为持有 KernelState 而依赖 19 个业务包:
kernelboot ──▶ agent/core ──▶ …
──▶ plugin
──▶ security
──▶ memory / knowledge / text / coldcontext / …
而 kernelboot.go / scheduler.go / funcmodule.go / syncbus.go / lifecycle.go
**一行业务代码都不需要** —— 依赖全在 kernelstate.go 这一个数据文件里。
后果是四个底层包各自造通道:
core → Agent 字段(每种 agent 构造点都要记得传)
plugin → 12 个 SetXxx
sdk → SDKConfig 传参
security → 包级单例 Global() / RuntimeGlobal() / ConfigCodec()
四条通道是同一个根因的四个表现。
## 本次做的事
### 1. 抽出 internal/kstate(断环)
kernelstate.go / syncbus.go / lifecycle.go 搬出 kernelboot:
internal/kstate 纯数据 + 唯一挂载点(叶子,谁都能 import)
internal/kernelboot 装配引擎,零业务包
挂载点 API:Mount / Get(nil 安全)/ MountForTest(返回 restore,并行测试隔离)。
验证:core 现在能 import kstate(此前 import cycle not allowed)。
### 2. StageHost / Agent 字段存 any
它们是 core 自己的类型(core 是环的一极,这是真环)。按用户裁定的方向:
> 是其他包在kstate挂共享内容啊
存 any,消费方断言回具体类型 —— 与本仓既有的 PluginCatalog /
PluginScheduler / UpdateCapabilities 同型。
★ 其余字段保持**具体类型**,没有一律改 any。判据是"它会不会反向依赖
agent/core":实测 plugin / security / sdk 都不依赖 core,所以它们作为
具体类型不构成环,而类型化字段让"拼错/取错类型"是编译错误(本结构体的
设计原则)。
### 3. 插件声明式系统提示词段
SDK 新增 SystemPromptAPI(见 submodule 提交)。内核侧:
kstate.State.PromptSections *promptsec.Registry ← 唯一事实来源
Agent.renderSystemPrompt() 每轮重建时读它
skillmgr 从"实现 SkillIndexProvider 让内核来问"改为"声明自己的段":
DeclarePromptSection{Section:"skillmgr.skills", Order:100, Volatile:true}
并挂到全部变更点(启动全扫后、移交事件后、load/unload/create/install/
enable/disable 后、Stop 时撤销)。
### 4. 内核自身的提示词段也走同一管理器
按用户裁定「把现在内核所有 systemprompt 的相关注入都接入到这个统一的
systemprompt 管理器上」,把 buildSystemPrompt 里硬拼的十几块
(人格卡/任务提示词/记忆说明/输出规则/工具目录…)改为声明式:
kernelSections() 当轮计算 → 与插件段按 Order 合并渲染。
顺序由 Order 常量决定,改结构变成调常量而不是挪代码块。
## 判据(均经变异验证)
TestCoreCanImportKstate 真编译探针;环重现则红(实测)
TestKstateDoesNotDependOnCore 静态版,指向具体字段
TestKstateIsLeaf kstate 不得反依赖上层
TestRTChildSeesPromptSections 子 agent 能看到插件段
TestResidentSeesPromptSections 生产实际中招的那一类;变异后红(实测)
TestRootAgentSeesPromptSections 确认没改坏根路径
TestNoPromptSectionsMount 未装配时不 panic、不凭空出现段
TestDeclareTwiceRendersOnce ★ 回应"会不会多份":声明 5 次渲染 1 份
TestSectionRemovalTakesEffect Stop 后段消失
TestRuntimeUpdateVisibleToExistingAgent 同一实例下一轮看到新内容
TestSectionOrderIsRespected Order 生效且稳定
## 验证
go build ./... PASS
go vet ./... PASS
gofmt -l internal/ cmd/ pkg/ 干净
go test ./... -count=1 63 包全过,0 FAIL
干净检出(git worktree) build + 4 包测试全绿
## 未做(见 kernelplan.md)
T3 security 三单例收敛(含 Store 复用 Codec 的惰性迁移)
T5 plugin Setter 收敛
T6 防腐判据(部分已随本次落地)
150 lines
6.1 KiB
Go
150 lines
6.1 KiB
Go
// Package memory 是 memory 模块:图记忆 + 索引 + 社交图 + 蒸馏管线 + 共享词嵌入。
|
||
//
|
||
// ## 为什么依赖 kernel-io
|
||
//
|
||
// 本模块产出 MemoryBundle(4 个同生共死的东西打包)。它**不**直接读 IO,
|
||
// 但"记忆子系统就绪"在语义上包含它后续要被候选消费管线使用,而那条管线需要 iom。
|
||
//
|
||
// ★ 这是**刻意声明**的依赖(不是签名要求的):让"记忆子系统在 IO 就绪后才建"
|
||
// 成为结构保证 —— 若将来 initMemoryStack 内部要用 iom,不会因为"忘了声明"
|
||
// 而静默拿 nil。
|
||
package memory
|
||
|
||
import (
|
||
"fmt"
|
||
"log"
|
||
"path/filepath"
|
||
"strings"
|
||
"time"
|
||
|
||
"github.com/JianFeeeee/HologramAgent/internal/config"
|
||
"github.com/JianFeeeee/HologramAgent/internal/kernelmod"
|
||
"github.com/JianFeeeee/HologramAgent/internal/kstate"
|
||
"github.com/JianFeeeee/HologramAgent/internal/memory"
|
||
"github.com/JianFeeeee/HologramAgent/internal/memory/distill"
|
||
"github.com/JianFeeeee/HologramAgent/internal/memory/pipeline"
|
||
"github.com/JianFeeeee/HologramAgent/internal/memory/social"
|
||
"github.com/JianFeeeee/HologramAgent/pkg/generation"
|
||
)
|
||
|
||
// Module 提供图记忆子系统。
|
||
type Module struct{}
|
||
|
||
func (Module) Name() string { return "memory" }
|
||
func (Module) Requires() []string { return []string{kernelmod.FacKernelIO} }
|
||
func (Module) Provides() []string { return []string{kernelmod.FacMemory} }
|
||
|
||
func (Module) Init(ks *kstate.State) error {
|
||
// ★ 读取前检查(用户指定的做法:"结构体成员初始置 nil 加读取前检查")。
|
||
//
|
||
// 为何要检查 CfgReg:它是 **Group 0** 的产物(不由任何调度模块提供),
|
||
// 所以不可能通过 Requires 声明它 —— 依赖图保证不了它非 nil。
|
||
// 而上面那行 `ks.CfgReg.GetString(...)` 在 nil 时会**panic**,
|
||
// 栈信息指向 strings.Split 之类无关处,排查成本高。
|
||
if ks.CfgReg == nil {
|
||
return fmt.Errorf("memory 模块:ks.CfgReg 为 nil —— " +
|
||
"Group 0 必须先建好配置中心(NewConfigRegistry)再启动本调度器")
|
||
}
|
||
if ks.DataDir == "" {
|
||
return fmt.Errorf("memory 模块:ks.DataDir 为空 —— 它是 Group 0 的产物,必须先设置")
|
||
}
|
||
memDB, err := memory.NewGraphDB(filepath.Join(ks.DataDir, "memory", "graph.db"))
|
||
if err != nil {
|
||
log.Printf("[homed] warning: memory init failed: %v", err)
|
||
memDB = nil
|
||
} else {
|
||
log.Printf("[homed] graph memory initialized")
|
||
}
|
||
memIdx := memory.NewIndexer(memDB)
|
||
memIdx.Sync() // 启动时立即同步,避免前 30 分钟空窗
|
||
socialStore := social.New(memDB)
|
||
|
||
distiller := pipeline.NewDistiller(memDB, ks.DataDir, pipeline.DistillerConfig{
|
||
Interval: 10 * time.Minute,
|
||
RetentionDays: 7,
|
||
BatchSize: 50,
|
||
})
|
||
// ★ 必须在 distiller.Start() **之前**注入:Start 会起 distillLoop,
|
||
// 而第一次 tick 在 Interval 之后。若先 Start 再注入,头一个周期
|
||
// (实测配置 10 分钟)会白跑一次 jieba 路 —— 而那条路实测产出 0 条。
|
||
if memDB != nil {
|
||
distiller.SetSplitter(initDistillSplitter(ks.CfgReg))
|
||
}
|
||
if memDB != nil {
|
||
// 这里**故意不写 defer distiller.Stop()**:函数 return 即触发 defer,
|
||
// 而 Stop() → cancel() 会让刚启动的 distillLoop 立刻退出,
|
||
// 规则蒸馏管线启动即死、10min 心跳从不运行(旧 main() 拆分时的残留)。
|
||
// 停机由 AddCloser 负责(见下方)。
|
||
distiller.Start()
|
||
}
|
||
|
||
ks.Memory = &kstate.MemoryBundle{
|
||
DB: memDB,
|
||
Indexer: memIdx,
|
||
Social: socialStore,
|
||
Distiller: distiller,
|
||
}
|
||
// 共享词嵌入:蒸馏与 Agent 上下文复用同一实例
|
||
// (避免同一模型被二次加载,约 200k×300 维 ≈ 数百 MB)。
|
||
ks.Embedder = memory.NewStaticEmbedder(
|
||
strings.Split(ks.CfgReg.GetString("core.agent.embedding_model_path", ""), ",")...)
|
||
distiller.SetEmbedder(ks.Embedder)
|
||
|
||
// ★ 伪关机登记(迁移数据目录用,见 kernelboot/lifecycle.go)。
|
||
// 只登记**持有写句柄**的 distiller —— 它每 10min 写 memory/graph.db,
|
||
// 迁移期间一旦写入就会搬走"写了一半的库"。
|
||
if ks.Memory != nil && ks.Memory.Distiller != nil {
|
||
ks.AddQuiescer("distiller",
|
||
func() error { return ks.Memory.Distiller.Pause() },
|
||
func() error { return ks.Memory.Distiller.Resume() })
|
||
}
|
||
|
||
ks.AddCloser(func() {
|
||
// 与原 main 的两个 defer 同序(LIFO):先停蒸馏器,再关图库。
|
||
if memDB != nil {
|
||
distiller.Stop()
|
||
memDB.Close()
|
||
}
|
||
})
|
||
return nil
|
||
}
|
||
|
||
// initDistillSplitter 按配置打开蒸馏用的生成侧 provider 并组装拆分器。
|
||
//
|
||
// 返回 nil 表示不启用(未配置 provider、或打开失败)—— 此时蒸馏回退既有的
|
||
// jieba/ONNX 路。**不因为模型不可用而让蒸馏停摆**:那条路虽然实测产出 0 条,
|
||
// 但它至少不会让对话记忆丢失。
|
||
func initDistillSplitter(cfgReg *config.ConfigRegistry) pipeline.RecordSplitter {
|
||
if cfgReg == nil {
|
||
return nil
|
||
}
|
||
providerName := cfgReg.GetString("core.memory.distill.generation.provider", "")
|
||
if providerName == "" {
|
||
return nil
|
||
}
|
||
opts := map[string]string{}
|
||
const optPrefix = "core.memory.distill.generation.options."
|
||
for _, key := range cfgReg.List(optPrefix) {
|
||
opts[strings.TrimPrefix(key, optPrefix)] = cfgReg.GetString(key, "")
|
||
}
|
||
provider, err := generation.Open(providerName, generation.Config{Options: opts})
|
||
if err != nil {
|
||
log.Printf("[homed] warning: opening distillation provider %q failed: %v (distillation falls back to jieba; registered: %s)",
|
||
providerName, err, strings.Join(generation.Names(), ", "))
|
||
return nil
|
||
}
|
||
if !provider.Info().SupportsJSONSchema {
|
||
// 拆分器的零幻觉完全依赖 schema 约束。不支持 schema 的 provider
|
||
// 会拿到自由文本,解析必炸 —— 与其让它运行时反复失败,不如现在就拒。
|
||
log.Printf("[homed] warning: distillation provider %q does not support JSON Schema, splitting is unreliable (falling back to jieba)",
|
||
providerName)
|
||
provider.Close()
|
||
return nil
|
||
}
|
||
log.Printf("[homed] distill generation active: provider=%s model=%s",
|
||
providerName, provider.Info().Model)
|
||
return distill.NewExtractor(provider, nil)
|
||
}
|
||
|
||
func init() { kernelmod.Register(Module{}) }
|