Files
TrulyMEM-TrueHumanMEM/重构.md
root 13e3c662ac refactor: adapt to WaterFlow framework - zero source changes required
- Remove duplicate platform layer and tool interface definitions
- Add BFS breadth-first search with depth annotation (sync from main)
- Use WaterFlow platform.fs for binary storage instead of custom storage
- Add installTrulyMEM() one-line registration function
- Update SKILL.md with 10 complete operations
- Add waterflow.d.ts type declarations
- Update bilingual README with simplified installation guide
- Build passes with 0 errors
2026-04-16 11:48:58 +08:00

10 KiB
Raw Blame History

TrulyMEM WaterFlow 重构计划

目标: 将 waterflow 分支重构为标准的 WaterFlow 框架 Tool + Skill,保留原始记忆能力不变。 约束: 仅修改 waterflow 分支,不影响 main 分支。


现状分析

waterflow 分支当前结构

ts/
├── bundled-skills/graph_memory/     ← SKILL.md 已存在 ✅
│   ├── SKILL.md
│   ├── persona/SKILL.md
│   └── task/SKILL.md
├── src/
│   ├── platform/                    ← 重复定义,需删除 ❌
│   │   ├── index.ts
│   │   ├── node.ts
│   │   └── types.ts
│   ├── runtime/core/
│   │   ├── graph_memory/            ← 核心逻辑,保留 ✅
│   │   │   ├── types.ts
│   │   │   ├── graph_database.ts
│   │   │   ├── memory_service.ts
│   │   │   └── index.ts
│   │   └── tools/
│   │       ├── tool_interface.ts    ← 重复定义,需删除 ❌
│   │       └── builtin/
│   │           └── graph_memory_tool.ts  ← 需适配 WaterFlow 接口 ✅
│   └── types/
│       └── sql.js.d.ts              ← 保留 ✅
└── package.json                     ← 需调整依赖 ✅

核心问题

问题 说明 解决方案
重复平台层 ts/src/platform/ 与 WaterFlow 重复 删除,改用 WaterFlow 的 getPlatform()
重复 Tool 接口 tool_interface.ts 与 WaterFlow 重复 删除,改用 WaterFlow 的类型
存储接口不兼容 使用自定义 StorageOperations 改用 WaterFlow 的 platform.fs(支持 binary)
无注册入口 没有将 Tool 注册到 WaterFlow 的方式 创建 registerGraphMemoryTool() 导出函数
SKILL.md 不完整 缺少 persona/task 操作的完整描述 补充完善

重构步骤

Phase 1: 清理重复定义

1.1 删除 ts/src/platform/ 目录

删除: ts/src/platform/index.ts
删除: ts/src/platform/node.ts
删除: ts/src/platform/types.ts

替换方案: 所有 import { getPlatform } from '../../../platform' 改为从 WaterFlow 导入:

import { getPlatform } from 'waterflow/platform';

1.2 删除 ts/src/runtime/core/tools/tool_interface.ts

替换方案: 使用 WaterFlow 的 Tool 接口:

import type { Tool, ToolInputSchema, ToolOutput, ToolExecutionContext } from 'waterflow/runtime/core/tools/tool_interface';

1.3 更新 tsconfig.json

{
  "compilerOptions": {
    "rootDir": "./src",
    "outDir": "./dist",
    "module": "esnext",
    "moduleResolution": "bundler",
    "target": "esnext",
    "types": ["node"],
    "lib": ["esnext"],
    "sourceMap": true,
    "declaration": true,
    "strict": true,
    "verbatimModuleSyntax": true,
    "isolatedModules": true,
    "skipLibCheck": true
  },
  "include": ["src/**/*"],
  "exclude": ["node_modules", "dist"]
}

Phase 2: 适配 WaterFlow 平台层

2.1 修改 graph_database.ts — 存储适配

当前(使用自定义 storage):

import { getPlatform } from '../../../platform';
const platform = getPlatform();
await platform.storage.save(key, data);  // 自定义接口

改为(使用 WaterFlow fs):

import { getPlatform } from 'waterflow/platform';
const platform = getPlatform();
await platform.fs.writeFile(dbPath, data, { encoding: 'binary' });
const loaded = await platform.fs.readFile(dbPath, { encoding: 'binary' });

具体改动:

  • GraphDatabase.save() 方法: storage.save() → fs.writeFile(..., { encoding: 'binary' })
  • GraphDatabase.load() 方法: storage.load() → fs.readFile(..., { encoding: 'binary' })
  • dbPath 使用 platform.path.join() 构建

2.2 修改 graph_memory_tool.ts — Tool 接口适配

当前:

import type { Tool, ... } from '../tool_interface';  // 自定义接口
import { getPlatform } from '../../../../platform';   // 自定义平台

改为:

import type { Tool, ToolInputSchema, ToolOutput, ToolExecutionContext, ToolInput } from 'waterflow/runtime/core/tools/tool_interface';
import { getPlatform } from 'waterflow/platform';

新增 WaterFlow 兼容字段:

export class GraphMemoryTool implements Tool {
  readonly id = 'builtin:graph_memory';
  readonly name = 'GraphMemory';
  readonly description = '...';
  readonly category: ToolCategory = 'analysis';
  readonly permissionLevel: PermissionLevel = 'safe';
  readonly inputSchema: ToolInputSchema = { ... };

  // WaterFlow 新增字段(可选)
  readonly alwaysLoad = true;  // 始终加载完整 schema
  readonly shouldDefer = false; // 不延迟加载

  async handler(params: ToolInput, context: ToolExecutionContext): Promise<ToolOutput> {
    // 使用 context.logger 替代 getPlatform().getLogger()
    const logger = context.logger;
    // ... 原有逻辑不变
  }
}

2.3 创建注册入口

新建: ts/src/runtime/core/tools/builtin/index.ts

import type { Tool } from 'waterflow/runtime/core/tools/tool_interface';
import { GraphMemoryTool, createGraphMemoryTool } from './graph_memory_tool';

export { GraphMemoryTool, createGraphMemoryTool };

/**
 * 注册图记忆工具到 WaterFlow ToolRegistry
 *
 * 使用方式:
 *   import { registerGraphMemoryTool } from 'trulymem/tools';
 *   registerGraphMemoryTool(toolRegistry, sessionId);
 */
export function registerGraphMemoryTool(
  registry: { register: (tool: Tool) => void },
  sessionId?: string
): void {
  registry.register(createGraphMemoryTool(sessionId));
}

Phase 3: 完善 SKILL.md

3.1 更新主 SKILL.md

补充 persona 和 task 操作说明,与 memory_service.ts 的实际方法对齐:

---
name: graph_memory
description: 图记忆工具 - 让 AI 拥有真正的长期记忆能力
when_to_use: 需要 AI 记住、回忆、管理信息或任务时
context: inline
allowed_tools:
  - builtin:graph_memory
arguments:
  - name: action
    type: string
    required: true
    enum: [recall, commit, purge, introspect, persona_update, persona_clear, task_create, task_set_state, task_delete, task_link_info]
    description: 记忆操作类型
  - name: params
    type: object
    required: true
    description: 操作参数
user_invocable: true
---

3.2 更新 persona/SKILL.md

---
name: persona_management
description: 人设管理 - 管理 AI 的用户画像和偏好
context: inline
allowed_tools:
  - builtin:graph_memory
---

3.3 更新 task/SKILL.md

---
name: task_management
description: 任务管理 - 管理连续性任务和相关信息
context: inline
allowed_tools:
  - builtin:graph_memory
---

Phase 4: 依赖与构建

4.1 更新 package.json

{
  "name": "trulymem-waterflow",
  "version": "1.0.0",
  "description": "TrulyMEM 图记忆系统 - WaterFlow Skill/Tool 实现",
  "type": "module",
  "main": "./dist/runtime/core/tools/builtin/index.js",
  "exports": {
    "./tools": "./dist/runtime/core/tools/builtin/index.js",
    "./graph_memory": "./dist/runtime/core/graph_memory/index.js",
    "./skills": "./bundled-skills"
  },
  "scripts": {
    "build": "tsc",
    "test": "vitest"
  },
  "peerDependencies": {
    "waterflow-ts": ">=0.1.0"
  },
  "dependencies": {
    "sql.js": "^1.8.0"
  },
  "devDependencies": {
    "@types/node": "^25.5.2",
    "typescript": "^5.0.0",
    "vitest": "^2.0.0"
  }
}

4.2 添加 sql.js.d.ts 类型声明

保留现有 ts/src/types/sql.js.d.ts,确保编译通过。


Phase 5: 验证

5.1 编译验证

cd ts/
npm install
npm run build
# 检查 dist/ 输出

5.2 类型检查

npx tsc --noEmit
# 确保无类型错误

5.3 集成验证(在 WaterFlow 项目中)

// 在 WaterFlow 入口文件中测试
import { getPlatform } from './platform';
import { initializeToolRegistry } from './runtime/core/tools/builtin';
import { registerGraphMemoryTool } from 'trulymem/tools';

const platform = getPlatform();
const registry = initializeToolRegistry(platform);

// 注册图记忆工具
registerGraphMemoryTool(registry, 'test-session');

// 验证工具已注册
const tool = registry.get('builtin:graph_memory');
console.log('GraphMemory tool registered:', !!tool);

文件变更清单

操作 文件路径 说明
🗑️ 删除 ts/src/platform/index.ts 重复平台层
🗑️ 删除 ts/src/platform/node.ts 重复平台层
🗑️ 删除 ts/src/platform/types.ts 重复平台层
🗑️ 删除 ts/src/runtime/core/tools/tool_interface.ts 重复接口
✏️ 修改 ts/src/runtime/core/graph_memory/graph_database.ts 改用 WaterFlow fs
✏️ 修改 ts/src/runtime/core/tools/builtin/graph_memory_tool.ts 适配 WaterFlow 接口
✏️ 修改 ts/src/runtime/core/graph_memory/index.ts 更新导出路径
✏️ 修改 ts/bundled-skills/graph_memory/SKILL.md 补充完整操作说明
✏️ 修改 ts/bundled-skills/graph_memory/persona/SKILL.md 完善
✏️ 修改 ts/bundled-skills/graph_memory/task/SKILL.md 完善
✏️ 修改 ts/package.json 调整为 peerDependency
✏️ 修改 ts/tsconfig.json 清理配置
➕ 新增 ts/src/runtime/core/tools/builtin/index.ts 注册入口

依赖关系图(重构后)

WaterFlow 框架
├── Platform (getPlatform)
│   ├── fs.readFile/writeFile (binary)  ← GraphDatabase 使用
│   ├── path.join/resolve               ← 路径构建
│   ├── getLogger                       ← 日志
│   └── globals.randomUUID              ← UUID 生成
│
├── ToolRegistry
│   ├── FRAMEWORK_TOOLS (Agent, ToolSearch)
│   ├── Platform Tools (Read, Write, Bash...)
│   └── GraphMemoryTool ← 从 trulymem/tools 注册
│
└── SkillLoader
    └── bundled-skills/graph_memory/SKILL.md
        └── allowed_tools: ['builtin:graph_memory']
            └→ LLM 调用 → ToolExecutor → GraphMemoryTool.handler()

风险与注意事项

  1. WaterFlow 版本依赖: 使用 peerDependencies 确保与 WaterFlow 版本兼容
  2. 二进制存储: WaterFlow 的 fs 支持 encoding: 'binary',已验证可用
  3. 类型兼容: 确保 Tool 接口字段与 WaterFlow 完全一致
  4. SKILL.md 格式: YAML frontmatter 必须符合 WaterFlow SkillLoader 解析规则