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 防腐判据(部分已随本次落地)
184 lines
7.0 KiB
Go
184 lines
7.0 KiB
Go
package kernelboot
|
||
|
||
// 数据目录迁移的**编排**:伪关机 → 迁移 → 唤醒。
|
||
//
|
||
// ## 流程(用户要求的顺序)
|
||
//
|
||
// ① Freeze 插件工具入口 —— 不再进新的工具调用
|
||
// ② Quiesce 各模块写者 —— distiller/textmem 等停下后台写
|
||
// ③ WaitDrain 等在途调用归零 —— 不能搬"写了一半的数据"
|
||
// ④ (外部脚本执行 rsync) —— 真搬数据 + 改 systemd + 改 DB
|
||
// ⑤ Resume 写者 —— 按启动顺序恢复
|
||
// ⑥ Thaw 工具入口 —— 重新接受工具调用
|
||
//
|
||
// ## ★ 本包只做 ①②③⑤⑥,不执行 ④
|
||
//
|
||
// 迁移是**破坏性且不可逆**的(21G 数据 + 12 处 DB 改写 + 46 个插件文件改写),
|
||
// 而且内核跑在 systemd 沙箱里(ProtectSystem/ProtectHome)**本来就写不了
|
||
// /etc/systemd**。⇒ 真迁移交给运维执行生成的脚本(见 internal/systemd/migrate.go),
|
||
// 本包负责**把它前后包起来**:确保迁移窗口内没有任何写者。
|
||
//
|
||
// ## ★ 失败策略:任何一步失败都要**回滚到能跑的状态**
|
||
//
|
||
// 伪关机失败 ⇒ 立刻唤醒已停的,让内核回到正常态,别卡在半关。
|
||
// 迁移失败 ⇒ 调用方负责回滚数据;本包的 Resume 仍然要执行(否则内核永久冻结)。
|
||
|
||
import (
|
||
"fmt"
|
||
"github.com/JianFeeeee/HologramAgent/internal/kstate"
|
||
"log"
|
||
"sync/atomic"
|
||
"time"
|
||
)
|
||
|
||
// inflightToolsFn 报告当前在途工具调用数(由装配处注入)。
|
||
//
|
||
// 用函数注入而不用字段直连:kernelboot 不能依赖 agent/core。
|
||
var inflightToolsFn atomic.Value // func() int64
|
||
|
||
// SetInflightToolCounter 注入在途工具计数(装配处调一次)。
|
||
func SetInflightToolCounter(fn func() int64) {
|
||
if fn != nil {
|
||
inflightToolsFn.Store(fn)
|
||
}
|
||
}
|
||
|
||
func hasInflightTools() bool {
|
||
v := inflightToolsFn.Load()
|
||
if v == nil {
|
||
return false
|
||
}
|
||
fn, _ := v.(func() int64)
|
||
if fn == nil {
|
||
return false
|
||
}
|
||
return fn() > 0
|
||
}
|
||
|
||
// PluginQuiescer 是**插件层的伪关机能力**。
|
||
//
|
||
// ★ 这里刻意复用已有的**运行态停启**(Registry.StopPlugin/StartPlugin),
|
||
//
|
||
// 而不是新造"冻结"机制 —— 三态生命周期(自动启动 / 启用但不自动启动 /
|
||
// 禁用)早已存在,且运行态停启**不写任何持久状态**(不碰 disabled_plugins,
|
||
// 也不置 shuttingDown)⇒ 天然可逆,正是伪关机需要的语义。
|
||
//
|
||
// StopPlugin ⇒ 停掉子进程 + **摘掉注册面**(工具/stage/通道)
|
||
// ⇒ 停完模型看不到、也调不到它们(比"冻结入口"更彻底)
|
||
// StartPlugin ⇒ 重新拉起,清运行态门
|
||
//
|
||
// ★ 与 StopAll 的区别(用错就是灾难):StopAll 置 shuttingDown 后
|
||
//
|
||
// **插件永远无法再加载**,那是进程退出用的,绝不能用于伪关机。
|
||
type PluginQuiescer interface {
|
||
// StopPluginRuntime 运行态停掉一个插件(不改持久状态)。
|
||
StopPluginRuntime(name string) error
|
||
// StartPluginRuntime 运行态拉起一个插件。
|
||
StartPluginRuntime(name string) error
|
||
// RunningPlugins 返回当前正在运行的插件名(用于决定停哪些)。
|
||
RunningPlugins() []string
|
||
}
|
||
|
||
// MigrateSession 表示一次"伪关机窗口"。用它包住外部迁移动作。
|
||
//
|
||
// ★ 用法必须用 defer 保证唤醒 —— 否则迁移失败时内核永久冻结:
|
||
//
|
||
// sess, err := ks.BeginMigration(freezer)
|
||
// if err != nil { return err }
|
||
// defer sess.End() // 无论成功失败都唤醒
|
||
// // ... 外部脚本迁移 ...
|
||
type MigrateSession struct {
|
||
ks *kstate.State
|
||
plugins PluginQuiescer
|
||
paused []string
|
||
stopped []string // 已运行态停掉的插件(按停止顺序,唤醒时逆序)
|
||
ended atomic.Bool
|
||
}
|
||
|
||
// BeginMigration 进入伪关机:停插件(运行态)→ 逆序暂停内核写者 → 等在途归零。
|
||
//
|
||
// 返回的 session 必须由调用方 `defer sess.End()`。
|
||
func BeginMigration(s *kstate.State, pq PluginQuiescer) (*MigrateSession, error) {
|
||
sess := &MigrateSession{ks: s, plugins: pq}
|
||
|
||
// ① 先停**插件**(运行态停启,可逆)。
|
||
//
|
||
// 为什么插件排第一:插件是最大的写入源(rss 写 feeds、calendar 写 events、
|
||
// commondev 写 git 镜像)。而且 StopPlugin 会**摘掉注册面** ⇒ 停完
|
||
// 模型看不到也调不到它们,比"只挡入口"更彻底。
|
||
//
|
||
// ★ 为什么不用 StopAll:它会置 shuttingDown,之后插件**永久无法加载**。
|
||
// 那是进程退出路径用的,用于伪关机等于"关了就起不来"。
|
||
if pq != nil {
|
||
running := pq.RunningPlugins()
|
||
// 逆序停(最后启动的先停,与依赖相反)
|
||
for i := len(running) - 1; i >= 0; i-- {
|
||
name := running[i]
|
||
if err := pq.StopPluginRuntime(name); err != nil {
|
||
// 停不下来 ⇒ 回滚已停的,别留半关
|
||
for j := len(sess.stopped) - 1; j >= 0; j-- {
|
||
if r := pq.StartPluginRuntime(sess.stopped[j]); r != nil {
|
||
log.Printf("[migrate] rollback start plugin %s failed: %v", sess.stopped[j], r)
|
||
}
|
||
}
|
||
return nil, fmt.Errorf("运行态停止插件 %s 失败(已回滚 %d 个): %w",
|
||
name, len(sess.stopped), err)
|
||
}
|
||
sess.stopped = append(sess.stopped, name)
|
||
}
|
||
log.Printf("[migrate] stopped %d plugin(s) at runtime (persistent state unchanged, restored on wake)", len(sess.stopped))
|
||
}
|
||
|
||
// ② 逆序暂停内核写者(distiller/textmem 等后台定时写)
|
||
paused, err := s.Quiesce()
|
||
if err != nil {
|
||
// 失败 ⇒ 把插件拉回去,内核回到正常态
|
||
for j := len(sess.stopped) - 1; j >= 0; j-- {
|
||
if r := pq.StartPluginRuntime(sess.stopped[j]); r != nil {
|
||
log.Printf("[migrate] rollback start plugin %s failed: %v", sess.stopped[j], r)
|
||
}
|
||
}
|
||
log.Printf("[migrate] pseudo-shutdown failed, rolled back: %v", err)
|
||
return nil, fmt.Errorf("伪关机失败: %w", err)
|
||
}
|
||
sess.paused = paused
|
||
|
||
// ③ 等在途工具调用归零(尽力而为,见下)
|
||
deadline := time.Now().Add(5 * time.Second)
|
||
for time.Now().Before(deadline) {
|
||
if !hasInflightTools() {
|
||
break
|
||
}
|
||
time.Sleep(50 * time.Millisecond)
|
||
}
|
||
if hasInflightTools() {
|
||
log.Printf("[migrate] warning: tool calls still in flight (continuing; safe after migration script stops the service)")
|
||
}
|
||
|
||
log.Printf("[migrate] pseudo-shutdown complete (%d plugins, %d kernel writers)", len(sess.stopped), len(paused))
|
||
return sess, nil
|
||
}
|
||
|
||
// End 唤醒:逆序恢复内核写者 → 逆序拉起插件。幂等。
|
||
func (m *MigrateSession) End() {
|
||
if m == nil || m.ended.Swap(true) {
|
||
return
|
||
}
|
||
// ① 先恢复内核写者(它们是被插件依赖的下层)
|
||
if err := m.ks.Resume(m.paused); err != nil {
|
||
log.Printf("[migrate] * waking kernel writers failed (may be half-awake): %v", err)
|
||
}
|
||
// ② 再拉起插件(按**停止的逆序** = 原启动顺序)
|
||
if m.plugins != nil {
|
||
for i := len(m.stopped) - 1; i >= 0; i-- {
|
||
name := m.stopped[i]
|
||
if err := m.plugins.StartPluginRuntime(name); err != nil {
|
||
log.Printf("[migrate] * starting plugin %s failed: %v", name, err)
|
||
} else {
|
||
log.Printf("[migrate] plugin started: %s", name)
|
||
}
|
||
}
|
||
}
|
||
log.Printf("[migrate] wake complete")
|
||
}
|