Compare commits
No commits in common. "main" and "unified-management-0.7.0" have entirely different histories.
main
...
unified-ma
|
|
@ -24,14 +24,3 @@ node_modules/
|
||||||
# generated previews (node preview-card.mjs)
|
# generated previews (node preview-card.mjs)
|
||||||
_preview/
|
_preview/
|
||||||
preview-debug.mjs
|
preview-debug.mjs
|
||||||
.codegraph/
|
|
||||||
|
|
||||||
# 可重新生成的输出与临时文件
|
|
||||||
artifacts/
|
|
||||||
.tmp-*
|
|
||||||
|
|
||||||
# 项目本地记忆数据(.dsh 本身仍可跟踪)
|
|
||||||
/.dsh/brain/
|
|
||||||
|
|
||||||
# 测试/本地运行生成的项目记忆脚手架
|
|
||||||
/.dsh/.gitignore
|
|
||||||
|
|
|
||||||
357
README.md
357
README.md
|
|
@ -1,22 +1,8 @@
|
||||||
# dsh-brain
|
# dsh-cloud-memory
|
||||||
|
|
||||||
> Brain 内置 Mnemon 后端。Brain 页面和普通记忆工具使用同一套 Mnemon 数据。
|
把 DeepSeek Harness 接到 LongMemory 云端记忆服务:**每轮对话结束自动上报一条活动记录**(只上传元数据),并把云端记忆库变成 agent 可用的工具。
|
||||||
> 旧 Brain 本地和 LongMemory 记忆数据保留原处。
|
|
||||||
>
|
|
||||||
> **0.10.3**:插件按功能拆成六个可单独开关的子插件,新增可选的原始记录层
|
|
||||||
> `dsh-brain-raw`(见「六个子插件」);同步清理了不可达的防御性分支与重复
|
|
||||||
> 响应校验。0.10.1 起技能同步按内容与更新时间自动解决冲突(0.9.9/0.9.10
|
|
||||||
> 语义),令牌环境变量**绑定服务地址**(见「配置」)。
|
|
||||||
|
|
||||||
Brain 为 DeepSeek Harness 提供 Mnemon 记忆和项目文档浏览,可通过 LongMemory
|
当前版本 **0.1.1**,含宿主端与浏览器端两部分:host 半负责活动上报与工具注册,`client/index.js` 提供「设置 → 插件 → 云端记忆」配置卡片。
|
||||||
上报回合活动元数据,并在云端技能中心和本机技能目录之间双向同步。
|
|
||||||
|
|
||||||
当前版本 **0.10.5**,含宿主端与浏览器端两部分:宿主端负责活动上报、
|
|
||||||
记忆工具注册与技能同步。浏览器 UI 有三个入口:
|
|
||||||
|
|
||||||
- 左侧栏 **Brain** 展示全局运行状态,管理全局记忆与部门。
|
|
||||||
- Better Sidebar 的 **项目记忆** 使用当前会话的项目目录,管理该项目的记忆、文档与部门。
|
|
||||||
- **设置 → 云端记忆** 提供完整配置,包括连接与上报、技能管理和 MCP 管理。
|
|
||||||
|
|
||||||
## 它做什么
|
## 它做什么
|
||||||
|
|
||||||
|
|
@ -24,51 +10,31 @@ Brain 为 DeepSeek Harness 提供 Mnemon 记忆和项目文档浏览,可通过
|
||||||
| --- | --- |
|
| --- | --- |
|
||||||
| 活动上报 | 监听 `session/event` 的 `turn/start`、`turn/end`,每个结束的回合调用一次 `POST /activity/turn`。上报字段只有 6 个:`client_id`、`conversation_id`、`turn_id`、`status`、`started_at`、`completed_at`。 |
|
| 活动上报 | 监听 `session/event` 的 `turn/start`、`turn/end`,每个结束的回合调用一次 `POST /activity/turn`。上报字段只有 6 个:`client_id`、`conversation_id`、`turn_id`、`status`、`started_at`、`completed_at`。 |
|
||||||
| 幂等 | `turn_id` 为 `<sessionId>:<turn>`,服务端按 `turn_id` 去重,重试不会重复计数。 |
|
| 幂等 | `turn_id` 为 `<sessionId>:<turn>`,服务端按 `turn_id` 去重,重试不会重复计数。 |
|
||||||
| 失败重试 | 网络错误与 5xx 进入待重试队列(上限 200 条),每 30 秒补发一次;4xx 不重试。切换账号或换服务地址后,旧队列条目会被丢弃,不会发到新账号。 |
|
| 失败重试 | 网络错误与 5xx 进入待重试队列(上限 200 条),每 30 秒补发一次;4xx 不重试(说明载荷或令牌有问题)。 |
|
||||||
| 记忆工具 | `memory_search`、`memory_read`、`memory_add`、`memory_list`、`memory_projects` 五个工具通过内置 Mnemon 读写记忆。 |
|
| 记忆工具 | `memory_search`、`memory_read`、`memory_add`、`memory_list`、`memory_projects` 五个工具直接读写云端记忆库。 |
|
||||||
| 技能同步 | 云端技能中心 ↔ 本机技能目录双向同步,冲突按内容与时间自动取较新(详见「技能同步」)。 |
|
| 配置页 | `GET /cloud-memory` 提供完整配置界面(本 profile 关闭了原生设置页,所以自带页面)。 |
|
||||||
| 配置页 | 设置中的「云端记忆」提供完整配置,另有独立页面 `GET /dsh-brain`。 |
|
|
||||||
|
|
||||||
**上传范围(如实说明)**:活动上报只上传上表 6 个元数据字段,不含提示词
|
**绝不上传**:提示词正文、工具输出、文件内容、本地路径、令牌。上报载荷在类型层面就只有六个字段,构造它的函数拿不到正文。
|
||||||
正文。**可选的摘要功能**(`summaryToken`)开启时,会把结束回合的对话文本
|
|
||||||
(脱敏、截断后)发送到独立的 summary 端点用于生成摘要——不开启该功能就
|
|
||||||
没有正文上传。令牌永不随页面回显原文,只回掩码。
|
|
||||||
|
|
||||||
## 六个子插件
|
|
||||||
|
|
||||||
0.10.1 起 `dsh-brain` 以一个包提供五个子插件行,0.10.3 起增加可选的
|
|
||||||
`dsh-brain-raw`(原始记录层),共六个,可在宿主
|
|
||||||
「设置 → 插件」页逐行开关(HMR 生效、重启保持):
|
|
||||||
|
|
||||||
| 子插件 | 提供什么 |
|
|
||||||
| --- | --- |
|
|
||||||
| `dsh-brain-cloudsync` | 连接与上报:登录/测试/补发/技能同步路由、重试定时器、同步定时器。 |
|
|
||||||
| `dsh-brain-raw` | 可选原始记录层:把 user/assistant 原话按会话追加到 `$DSH_HOME/brain/raw/`,提供 `memory_raw_search` / `memory_raw_read` / `memory_raw_status`。 |
|
|
||||||
| `dsh-brain-memory` | 五个 `memory_*` 工具注册。 |
|
|
||||||
| `dsh-brain-skills` | 技能管理页、`skill_list` 工具、技能市场、来源树。 |
|
|
||||||
| `dsh-brain-mcp` | MCP 管理页开关(页签与宿主桥接能力声明;MCP 连接本身由宿主 `dsh-mcp-connector` 管理,本插件不做 MCP 云同步)。 |
|
|
||||||
| `dsh-brain-ui` | 左侧栏 Brain 总面板与 better-sidebar 项目记忆页签;配置页与状态/能力/配置路由。 |
|
|
||||||
|
|
||||||
- `dsh-brain-cloudsync` 控制活动上报与云端技能同步。`dsh-brain-memory` 注册记忆工具,`dsh-brain-mnemon` 提供工具和页面读取的后端。
|
|
||||||
- 共享服务(设置、客户端、同步引擎)由进程级内核统一构造,关掉再开不会
|
|
||||||
重复实例;设置持久化在 `$DSH_HOME/dsh-brain.json`(侧车文件为权威,
|
|
||||||
插件行的 config 只作首次种子)。
|
|
||||||
- UI 子插件以包根名 `dsh-brain` 注册,供 DSH 发现浏览器端入口;该子插件行传入 `entry: ui`。旧的单行 profile 继续通过根导出加载全部子插件。
|
|
||||||
- 0.11.0 起第五个子插件行 id 从 `dsh-brain-settings-ui` 改为 `dsh-brain-ui`(package exports 保留 `./settings-ui` 别名指向同一入口)。若 profile 里还留有旧 id 的禁用/配置行,请到「设置 → 插件」对 `dsh-brain-ui` 重新设置;插件不会自动改写宿主配置文件。
|
|
||||||
|
|
||||||
## 安装
|
## 安装
|
||||||
|
|
||||||
```powershell
|
```powershell
|
||||||
# 装进当前 profile(默认 desktop)
|
# 装进当前 profile(默认 desktop)
|
||||||
dsh plugin --profile desktop add dsh-brain
|
dsh plugin --profile desktop add dsh-cloud-memory
|
||||||
```
|
```
|
||||||
|
|
||||||
装好后确认 profile 的 `package.json` 依赖里有 `dsh-brain`。重启 DSH,在
|
装好后确认 profile 的 `package.json` 里有两处:
|
||||||
「设置 → 云端记忆」里配置。也可从插件详情的配置入口或
|
|
||||||
`http://127.0.0.1:<当次端口>/dsh-brain` 使用完整配置,旧 `/cloud-memory` 路由保留为别名。
|
|
||||||
|
|
||||||
> `baseUrl` 默认是占位符 `https://your-memory-host/api/longmemory`。
|
```jsonc
|
||||||
> 配置自己的 LongMemory 地址后可使用云端活动上报和技能同步。内置 Mnemon 可独立使用。
|
{
|
||||||
|
"dependencies": { "dsh-cloud-memory": "^0.1.0" },
|
||||||
|
"dsh": { "profile": { "bundles": [ /* ..., */ "dsh-cloud-memory" ] } }
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
重启 DSH,在「设置 → 插件 → 云端记忆」里配置(备用入口:`http://127.0.0.1:<当次端口>/cloud-memory`)。
|
||||||
|
|
||||||
|
> `baseUrl` 默认是占位符 `https://your-memory-host/api/longmemory`。**首次使用必须先把它改成你自己的 LongMemory 服务地址**(配置页里填,或写进 `$DSH_HOME/cloud-memory.json`),否则上报与工具都会连接失败。
|
||||||
|
|
||||||
## 登录(推荐)
|
## 登录(推荐)
|
||||||
|
|
||||||
|
|
@ -76,202 +42,129 @@ dsh plugin --profile desktop add dsh-brain
|
||||||
|
|
||||||
```
|
```
|
||||||
密码 → POST /api/auth/login(一次性会话 cookie)
|
密码 → POST /api/auth/login(一次性会话 cookie)
|
||||||
→ POST /api/auth/tokens ×3(activity:write、memory:write、summary:write)
|
→ POST /api/auth/tokens ×2(activity:write、memory:write)
|
||||||
→ 把成功签发的 cmt_… 令牌写进 $DSH_HOME/dsh-brain.json
|
→ 只把两个 cmt_… 令牌写进 $DSH_HOME/cloud-memory.json
|
||||||
→ 失败的 scope 同步清除旧令牌(账号切换是原子的,不留上一个账号的凭据)
|
|
||||||
→ 密码与会话 cookie 立即丢弃
|
→ 密码与会话 cookie 立即丢弃
|
||||||
```
|
```
|
||||||
|
|
||||||
- 密码只在这一串请求里存在:不落盘、不写日志、不随 `/dsh-brain/status` 回显。
|
- 密码只在这一串请求里存在:不落盘、不写日志、不随 `/cloud-memory/status` 回显。
|
||||||
- 服务端只保存令牌哈希,令牌可单独撤销;改密码不影响已签发令牌。
|
- 服务端只保存令牌哈希,令牌可单独撤销;改密码不影响已签发令牌。
|
||||||
- 服务地址不是 HTTPS(且不是 loopback)时插件拒绝发送密码。
|
- 服务地址不是 HTTPS(且不是 loopback)时插件拒绝发送密码。
|
||||||
- 管理员账号不能签发个人令牌(服务端 `403 management_only`),请用普通用户。
|
- 管理员账号不能签发个人令牌(服务端 `403 management_only`),请用普通用户。
|
||||||
- 也可跳过登录,直接手填令牌(见下)。
|
- 也可跳过登录,直接手填两个令牌(见下)。
|
||||||
|
|
||||||
## 配置
|
## 配置
|
||||||
|
|
||||||
配置文件 `$DSH_HOME/dsh-brain.json`(默认 `%USERPROFILE%\.dsh\dsh-brain.json`;
|
配置文件 `$DSH_HOME/cloud-memory.json`(默认 `%USERPROFILE%\.dsh\cloud-memory.json`),字段:
|
||||||
旧的 `cloud-memory.json` 首次加载时自动复制迁移、原文件保留),字段:
|
|
||||||
|
|
||||||
| 字段 | 默认 | 说明 |
|
| 字段 | 默认 | 说明 |
|
||||||
| --- | --- | --- |
|
| --- | --- | --- |
|
||||||
| `enabled` | `true` | 总开关。新字段(`activityEnabled` 等)未设置时继承它。 |
|
| `enabled` | `true` | 关闭后不上报、工具直接报错。 |
|
||||||
| `activityEnabled` | 继承 `enabled` | 只关活动上报。 |
|
|
||||||
| `memoryEnabled` | 继承 `enabled` | 只关记忆工具。 |
|
|
||||||
| `skillsSyncEnabled` | `true` | 云端技能中心与本机技能目录的双向同步开关。 |
|
|
||||||
| `baseUrl` | `https://your-memory-host/api/longmemory` | 服务基址,自动去掉结尾斜杠。 |
|
| `baseUrl` | `https://your-memory-host/api/longmemory` | 服务基址,自动去掉结尾斜杠。 |
|
||||||
| `clientId` | `dsh-desktop` | 上报时的 `client_id`。 |
|
| `clientId` | `dsh-desktop` | 上报时的 `client_id`。 |
|
||||||
| `requestTimeoutMs` | `8000` | 单次请求超时,1000–60000。 |
|
| `requestTimeoutMs` | `8000` | 单次请求超时,1000–60000。 |
|
||||||
| `defaultK` | `10` | `memory_search` 未指定 `k` 时的条数。 |
|
| `defaultK` | `10` | `memory_search` 未指定 `k` 时的条数。 |
|
||||||
| `activityToken` | — | `activity:write` 令牌,形如 `cmt_…`。 |
|
| `activityToken` | — | `activity:write` 令牌,形如 `cmt_…`。 |
|
||||||
| `memoryToken` | — | `memory:read` / `memory:write` 令牌。 |
|
| `memoryToken` | — | `memory:read` / `memory:write` 令牌,形如 `cmt_…`。 |
|
||||||
| `summaryToken` | — | `summary:write` 令牌(摘要功能,可选)。 |
|
| `skillsSyncEnabled` | `true` | 云端技能中心与本机技能目录的双向同步开关。 |
|
||||||
| `skillsDir` | 空 | 本机技能目录覆盖;为空时用 `$DSH_HOME/skills`。 |
|
| `skillsDir` | 空 | 本机技能目录覆盖;为空时用 `$DSH_HOME/skills`。 |
|
||||||
| `localMemoryEnabled` | `true` | 本地优先记忆总开关;离线、无令牌可用。 |
|
|
||||||
| `cloudMemoryEnabled` | `false` | 云端记忆适配器开关;需要 memory 令牌,默认关闭。 |
|
|
||||||
| `autoMemorySpaces` | `true` | 首次使用时幂等创建全局与当前项目空间。 |
|
|
||||||
| `autoSummaryEnabled` | `true` | 自动捕获用户明确表达的长期信息。 |
|
|
||||||
| `autoProfileEnabled` | `true` | 自动维护 USER.md 画像(推测进入待确认区)。 |
|
|
||||||
| `localMemoryK` | `5` | 本地检索默认返回条数。 |
|
|
||||||
|
|
||||||
三个令牌也可以用环境变量覆盖:`DSH_BRAIN_ACTIVITY_TOKEN`、
|
两个令牌也可以用环境变量 `DSH_CLOUD_MEMORY_ACTIVITY_TOKEN`、`DSH_CLOUD_MEMORY_MEMORY_TOKEN` 覆盖。
|
||||||
`DSH_BRAIN_MEMORY_TOKEN`、`DSH_BRAIN_SUMMARY_TOKEN`(旧名
|
|
||||||
`DSH_CLOUD_MEMORY_*` 继续有效)。环境变量令牌**绑定服务地址**:必须同时
|
|
||||||
设置 `DSH_BRAIN_TOKEN_ORIGIN`(或旧名 `DSH_CLOUD_MEMORY_TOKEN_ORIGIN`)
|
|
||||||
且等于当前 `baseUrl` 的 origin 才会生效;在配置页清除令牌后,环境变量
|
|
||||||
也不会再兜底回来。
|
|
||||||
|
|
||||||
> 一个 key 只有一种 scope,所以需要三个令牌:只做上报就只填活动令牌,
|
> 一个 key 只有一种 scope,所以需要两个令牌:只做上报就只填活动令牌,只做检索就只填记忆令牌。
|
||||||
> 只做检索就只填记忆令牌。
|
|
||||||
|
|
||||||
## 旧版 Brain 本地记忆
|
|
||||||
|
|
||||||
旧版全局数据位于 `$DSH_HOME/brain`,项目数据位于 `<项目>/.dsh/brain`。Brain 保留这套存储供旧版记录、部门记忆和自动摘要使用。当前普通 `memory_*` 工具通过内置 Mnemon 读写。相关实现见 `docs/LOCAL_MEMORY_IMPLEMENTATION.md`、`docs/LOCAL_MEMORY_ACCEPTANCE.md` 和 `docs/MNEMON_FORK.md`。
|
|
||||||
|
|
||||||
## 原始记录层(dsh-brain-raw)
|
|
||||||
|
|
||||||
`dsh-brain-raw` 是独立可选子插件,用来保存“原话”而不是摘要:监听宿主
|
|
||||||
`session/event`,把真实的 user / assistant 消息追加到
|
|
||||||
`$DSH_HOME/brain/raw/` 下的 JSONL 文件(每个会话一个文件,超过
|
|
||||||
`rawMaxBytesPerSession` 自动轮转),不写入 Mnemon 的 `mnemon.db`,也不
|
|
||||||
影响现有记忆条目。
|
|
||||||
|
|
||||||
默认配置(bundle patch 的 `dsh-brain-raw` 行):
|
|
||||||
|
|
||||||
```yaml
|
|
||||||
- id: dsh-brain-raw
|
|
||||||
name: dsh-brain/raw
|
|
||||||
config:
|
|
||||||
rawEnabled: true
|
|
||||||
rawCaptureAssistant: true
|
|
||||||
rawRetentionDays: 90
|
|
||||||
```
|
|
||||||
|
|
||||||
可用工具:
|
|
||||||
|
|
||||||
- `memory_raw_search`:按关键词搜索原话,返回会话 id、事件 seq、角色和片段;
|
|
||||||
- `memory_raw_read`:按 `session_id` + `seq` 读某一条原话,或按 `offset/limit` 浏览;
|
|
||||||
- `memory_raw_status`:查看保存目录、会话数、记录数、占用空间和保留天数。
|
|
||||||
|
|
||||||
原始记录写入本地 JSONL。采集范围是用户和助手的消息文本,每条先经密钥脱敏,再按默认 16,000 字符上限保存。原文文件默认保留 90 天。停用 `dsh-brain-raw` 行即停止采集。Mnemon 的外部 Provider 和 Git 同步都使用 Mnemon 自己的数据源。
|
|
||||||
|
|
||||||
## 内置 Mnemon 后端
|
|
||||||
|
|
||||||
Brain 内含 Mnemon Host、四个数据源(Runtime、Documents、Memory Spaces、Skills)、五个策略(默认三层、通用、范围限定、轻上下文、自动捕获)以及九个 Memory Spaces Provider。默认启用三层策略,其他策略可在 Mnemon 工作台按需选择。Mnemon 设置和工作台随 Brain 的 Web 客户端加载。
|
|
||||||
|
|
||||||
- 全局 Brain 页和不带 `project_id` 的记忆工具使用 Mnemon Runtime。全局 `memory_add` 写入工作记忆,省略 `tags` 和 `sector`。
|
|
||||||
- 项目记忆页使用当前会话的工作区。工具调用时用 `memory_projects` 返回的 ID 指定 `project_id`。项目写入使用工作区的可写默认记忆空间,或唯一可写空间。新工作区需要先配置一个可写的 Mnemon 记忆空间。
|
|
||||||
- `memory_read` 接受 `memory_search`、`memory_list`、`memory_add` 返回的 Mnemon ID。旧 Brain 本地和 LongMemory 数据没有自动迁入。
|
|
||||||
|
|
||||||
## Mnemon 远程接入
|
|
||||||
|
|
||||||
- Brain 内置 Mnemon 默认设置 `remoteAccess: disabled`,关闭 DSH 远程 Mnemon 服务。本地工作台和记忆工具仍可使用。需要远程读取时,可在宿主配置 `remoteAccess: read-only` 并重启。远程写入记忆、修改配置和发起同步需要 `remoteAccess: trusted-host`,仍受 Mnemon 的写入设置和能力限制。Brain 的 LongMemory 云同步默认关闭。
|
|
||||||
- Memory Spaces 支持外部服务。内置适配器包括 OpenViking、Honcho、Mem0、Hindsight、Holographic、RetainDB、ByteRover、Supermemory,以及本地 Mnemon Native。服务按 Provider 配置端点、权限和空间。
|
|
||||||
- Mnemon 还提供 Git 备份和同步,可配置仓库和同步范围。Brain 的原始对话 JSONL 由独立记录层管理。
|
|
||||||
|
|
||||||
## Mnemon 集成(记忆空间 Provider)
|
## Mnemon 集成(记忆空间 Provider)
|
||||||
|
|
||||||
本包同时保留 Mnemon 记忆空间 Provider 适配:Mnemon 管本地在场(运行时记忆
|
自 0.2.0 起,本包同时是一个 Mnemon 记忆空间 Provider:Mnemon 管本地在场
|
||||||
每轮注入),云端 Provider 的每一次读、写都实时穿透到 LongMemory。启用方式:在 Mnemon 的记忆空间来源配置里给 providers 列表加一行
|
(运行时记忆每轮注入),长期记忆的每一次读、写都实时穿透到 LongMemory——
|
||||||
|
云端是真源,本地不留长期副本。因此其他工具(Claude Code、Codex、看板)
|
||||||
|
刚写进 LongMemory 的记忆,DSH 里立刻能召回。
|
||||||
|
|
||||||
|
启用方式:在 Mnemon 的记忆空间来源配置里给 providers 列表加一行
|
||||||
(profile 覆盖或 bundle 配置均可),然后重启 DSH:
|
(profile 覆盖或 bundle 配置均可),然后重启 DSH:
|
||||||
|
|
||||||
```yaml
|
```yaml
|
||||||
providers:
|
providers:
|
||||||
- use: dsh-brain/mnemon-provider
|
- use: dsh-cloud-memory/mnemon-provider
|
||||||
instanceId: longmemory
|
instanceId: longmemory
|
||||||
```
|
```
|
||||||
|
|
||||||
之后在 Mnemon 的插件页会出现 LongMemory 的服务字段(Endpoint / Memory
|
之后在 Mnemon 的插件页会出现 LongMemory 的服务字段(Endpoint / Memory
|
||||||
token / Project ID),留空即复用本插件已有的 `dsh-brain.json` 配置,一处
|
token),留空即复用本插件已有的 `cloud-memory.json` 配置,一处配置两处生效。
|
||||||
配置两处生效。每个记忆空间映射一个 LongMemory 项目:发现流程会自动列出
|
每个记忆空间映射一个 LongMemory 项目:发现流程会自动列出账号下的全部
|
||||||
账号下的全部项目,外加一个不分项目的「全部」空间;也可以在空间上手动填
|
项目,外加一个不分项目的「全部」空间;也可以在空间上手动填 Project ID。
|
||||||
Project ID。读取会校验命中的项目与空间一致(项目隔离)。
|
|
||||||
|
|
||||||
v1 范围:支持发现 / 状态 / 搜索 / 浏览 / 写入 / 按 id 读取;暂不支持删除
|
v1 范围:支持 发现 / 状态 / 搜索 / 浏览 / 写入 / 按 id 读取;暂不支持
|
||||||
(LongMemory 客户端接口没有删除操作)与图谱读取(接口未暴露,返回空图
|
删除(LongMemory 客户端接口没有删除操作)与图谱读取(接口未暴露,
|
||||||
谱且能力声明为关)。写入按服务端回执区分「已存储 / 排队中(未确认)」。
|
返回空图谱且能力声明为关)。离线时长期记忆不可用,Mnemon 的本地
|
||||||
离线时长期记忆不可用,Mnemon 的本地运行时记忆不受影响。
|
运行时记忆不受影响。
|
||||||
|
|
||||||
本地长期记忆也通过 `dsh-brain/mnemon-native-provider` 暴露为 Mnemon Native Provider,使用 vendored `dsh-brain-mnemon.memory-space-provider/v1` 协议;验证:`node verify-mnemon-native.mjs`。
|
|
||||||
|
|
||||||
验证:`node verify-mnemon-provider.mjs`(对本地 stub 服务跑通
|
验证:`node verify-mnemon-provider.mjs`(对本地 stub 服务跑通
|
||||||
发现→写入→召回→项目隔离全流程)。
|
发现→写入→召回→项目隔离全流程)。
|
||||||
|
|
||||||
## 技能同步
|
## 技能同步
|
||||||
|
|
||||||
插件在记忆之外还双向同步技能:云端技能中心是总汇,本机技能目录(默认
|
自 0.3.0 起,插件在记忆之外还双向同步技能:云端技能中心是总汇,本机
|
||||||
`$DSH_HOME/skills`)是工作副本,本地的浏览、启停、分类仍归技能管理页。
|
技能目录(默认 `$DSH_HOME/skills`)是工作副本,本地的浏览、启停、分类
|
||||||
插件启动 5 秒后首跑,之后每 15 分钟对账一次;结果与冲突列表见
|
仍归 DSH 技能管理器。插件启动 5 秒后首跑,之后每 15 分钟对账一次;
|
||||||
`GET /dsh-brain/status` 的 `skills` 字段,聊天里也可以用 `skill_list`
|
结果与冲突列表见 `GET /cloud-memory/status` 的 `skills` 字段,聊天里
|
||||||
工具查看云端清单。
|
也可以用 `skill_list` 工具查看云端清单。
|
||||||
|
|
||||||
- **下行**:云端技能先验整包清单哈希、再逐文件验 sha256,原子写入(临时
|
- **下行**:云端技能按平台自己的规矩落地——先验整包清单哈希、再逐
|
||||||
文件随机命名),并留下 `.manifest.json` 交付记录;文件路径逐个校验
|
文件验 sha256,原子写入,并留下 `.manifest.json` 交付记录;云端标
|
||||||
(相对路径、固定布局、扩展名白名单),路径穿越与校验和不符直接拒绝。
|
记了「脚本已变更待确认」的包不会自动安装,先在看板里确认。
|
||||||
云端标记了「脚本已变更待确认」的包不会自动安装,先在看板里确认。
|
- **上行**:本地原创技能(管理器安装、导入或手写的)自动发布到云
|
||||||
- **上行**:本地原创技能(管理器安装、导入或手写的)自动发布到云端;
|
端;之后的修改以新修订发布,带 `expected_revision` 守卫,云端被
|
||||||
之后的修改以新修订发布,带 `expected_revision` 守卫,云端被别人先改过
|
别人先改过就报冲突、不强行覆盖。
|
||||||
就报冲突、不强行覆盖。
|
|
||||||
|
|
||||||
防事故的规矩:先比内容,本地与云端逐字节一致时直接补交付记录,不传
|
防事故的规矩:云端交付的技能从不回传,本地改动它只报
|
||||||
不覆盖;内容不同时按时间自动取较新的一边——云端 `updated_at` 更新就
|
`locally_modified` 冲突、原样不动;本地删除不删云端,且同版本不会
|
||||||
先备份本地再覆盖(备份在 `$DSH_HOME/.dsh-brain-backups/sync/`),本地
|
被重新拉回(云端出了新版才会再下来);同名技能两边都有时互不抢占,
|
||||||
文件 mtime 更新就发布新修订;只有时间相同或缺失时才报冲突
|
报 `name_collision`。云端只接受固定布局(根目录只有 `SKILL.md`,
|
||||||
(`locally_modified` / `name_collision` / `cloud_newer`),等面板里逐项
|
其余文件进 `references/`、`scripts/`、`assets/`,扩展名有白名单,
|
||||||
确认。本地删除不删云端,且同版本不会被重新拉回(云端出了新版才会再
|
单文件 ≤512 KiB、整包 ≤2 MiB、≤100 个文件),不符合的本地技能报
|
||||||
下来)。面板里可逐项处理,也可用「全部保留本地 / 全部采用云端」批量处
|
`unsupported_layout`,不会为了迁就而裁剪文件。
|
||||||
理(有二次确认,失败项会逐条汇总)。云端只接受固定布局(根目录只有
|
|
||||||
`SKILL.md`,其余文件进 `references/`、`scripts/`、`assets/`,扩展名有
|
|
||||||
白名单,单文件 ≤512 KiB、整包 ≤2 MiB、≤100 个文件),不符合的本地技能
|
|
||||||
报 `unsupported_layout`,不会为了迁就而裁剪文件。
|
|
||||||
|
|
||||||
验证:`node verify-skills-sync.mjs` / `node verify-sync-resolve.mjs`
|
验证:`node verify-skills-sync.mjs`(对本地 stub 技能中心跑通
|
||||||
(对本地 stub 技能中心跑通下行安装、上行发布与修订、按时间自动上行/
|
下行安装、上行发布与修订、改云端技能报冲突、同名冲突、脚本待审、
|
||||||
下行、内容一致自动认领、同名同时间保留冲突、脚本待审、布局拒绝、删除
|
布局拒绝、删除不传播全流程)。
|
||||||
不传播、批量解决全流程)。
|
|
||||||
|
|
||||||
## 技能管理(内置)
|
## 技能管理(内置)
|
||||||
|
|
||||||
常用的本地管理也长在插件里,页面在 `/dsh-brain/skills`(配置页有链接
|
自 0.4.0 起,常用的本地管理也长在插件里,页面在 `/cloud-memory/skills`
|
||||||
进入):
|
(配置页有链接进入):
|
||||||
|
|
||||||
- **列表**:本机全部技能,标注来源(云端交付 / 本地已传云端 / 本地)与
|
- **列表**:本机全部技能,标注来源(云端交付 / 本地已传云端 / 本地)
|
||||||
云端修订号;
|
与云端修订号;
|
||||||
- **启停**:停用是把技能文件夹挪到 `$DSH_HOME/skills-disabled/` 暂存
|
- **启停**:停用是把技能文件夹挪到 `$DSH_HOME/skills-disabled/` 暂存
|
||||||
——DSH 看不见它,自然不会加载;启用再挪回来。不碰 DSH 内部机制,
|
——DSH 看不见它,自然不会加载;启用再挪回来。不碰 DSH 内部机制,
|
||||||
可靠且可逆。同步引擎认识暂存区:停用的云端技能不会被拉回技能目录,
|
可靠且可逆。同步引擎认识暂存区:停用的云端技能不会被拉回技能目
|
||||||
云端出了新版会在暂存区里原地更新;
|
录,云端出了新版会在暂存区里原地更新;
|
||||||
- **删除**:真删,文件夹直接删除、不可恢复(页面上会先弹确认)。只删
|
- **删除**:真删,文件夹直接删除、不可恢复(页面上会先弹确认)。
|
||||||
本地:云端副本不动,删掉的同版本也不会被同步重新拉回来;
|
只删本地:云端副本不动,删掉的同版本也不会被同步重新拉回来;
|
||||||
- **从 git 安装**:粘贴 https:// 或 file:// 仓库地址,浅克隆后把仓库里
|
- **从 git 安装**:粘贴 https:// 或 file:// 仓库地址,浅克隆后把仓
|
||||||
所有带 `SKILL.md` 的文件夹装进技能目录;不执行仓库里的任何代码,
|
库里所有带 `SKILL.md` 的文件夹装进技能目录;不执行仓库里的任何
|
||||||
同名技能跳过不覆盖。
|
代码,同名技能跳过不覆盖。
|
||||||
|
|
||||||
范围就到 DSH 技能目录这一处:技能市场的发现中心、扫描其它工具(Codex、
|
范围就到 DSH 技能目录这一处:技能市场的发现中心、扫描其它工具
|
||||||
Cursor 等)的技能目录不在内置范围——还需要那些的话继续留着第三方管
|
(Codex、Cursor 等)的技能目录不在内置范围——还需要那些的话继续
|
||||||
理器,两边不冲突;不需要的话现在可以卸掉它了。
|
留着第三方管理器,两边不冲突;不需要的话现在可以卸掉它了。
|
||||||
|
|
||||||
验证:`node verify-skill-admin.mjs`(列表与来源判定、启停、真删、git 安装
|
验证:`node verify-skill-admin.mjs`(列表与来源判定、启停、真删、
|
||||||
与同名跳过、以及停用技能与同步引擎的配合)。
|
git 安装与同名跳过、以及停用技能与同步引擎的配合共 15 项)。
|
||||||
|
|
||||||
## HTTP 接口
|
## HTTP 接口
|
||||||
|
|
||||||
主路径 `/dsh-brain/*`(旧 `/cloud-memory/*` 保留为别名):
|
|
||||||
|
|
||||||
| 方法 | 路径 | 用途 |
|
| 方法 | 路径 | 用途 |
|
||||||
| --- | --- | --- |
|
| --- | --- | --- |
|
||||||
| GET | `/dsh-brain` | 配置页面 |
|
| GET | `/cloud-memory` | 配置页面 |
|
||||||
| GET | `/dsh-brain/status` | 设置 + 上报计数 + 最近 50 条记录 + 技能同步状态(令牌只返回掩码) |
|
| GET | `/cloud-memory/status` | 设置 + 上报计数 + 最近 50 条记录(令牌只返回掩码) |
|
||||||
| GET | `/dsh-brain/capabilities` | 能力声明(按已启用的子插件聚合) |
|
| PUT | `/cloud-memory/config` | 应用设置补丁(令牌留空表示不修改) |
|
||||||
| PUT | `/dsh-brain/config` | 应用设置补丁(令牌留空表示不修改) |
|
| POST | `/cloud-memory/login` | 账号密码登录,换取两个令牌并保存(密码不落盘) |
|
||||||
| POST | `/dsh-brain/login` | 账号密码登录,换取令牌并保存(密码不落盘;失败的 scope 同时清除旧令牌) |
|
| POST | `/cloud-memory/test` | 分别校验两个令牌(活动令牌用空载荷探测,鉴权先于载荷校验,返回 400 即代表令牌有效,不会写入记录) |
|
||||||
| POST | `/dsh-brain/test` | 分别校验令牌(活动令牌用空载荷探测,鉴权先于载荷校验,返回 400 即代表令牌有效,不会写入记录) |
|
| POST | `/cloud-memory/flush` | 立即补发待重试队列 |
|
||||||
| POST | `/dsh-brain/flush` | 立即补发待重试队列(总开关关闭时不补发) |
|
|
||||||
| GET | `/dsh-brain/sync/status` · POST `/dsh-brain/sync/run` | 同步状态 / 立即同步(run 要求同源 JSON POST) |
|
|
||||||
| POST | `/dsh-brain/sync/resolve` · `/dsh-brain/sync/resolve-all` | 逐项 / 批量解决冲突 |
|
|
||||||
|
|
||||||
写接口会校验同源 `Origin` 与 `Content-Type: application/json`,跨站请求
|
写接口会校验同源 `Origin`,跨站请求返回 403。
|
||||||
返回 403/415。
|
|
||||||
|
|
||||||
## 状态语义
|
## 状态语义
|
||||||
|
|
||||||
|
|
@ -286,19 +179,10 @@ Cursor 等)的技能目录不在内置范围——还需要那些的话继续
|
||||||
|
|
||||||
## 故障排查
|
## 故障排查
|
||||||
|
|
||||||
- **热力图不涨**:看 `/dsh-brain/status` 的 `reporter.skipped` 与
|
- **热力图不涨**:看 `/cloud-memory/status` 的 `reporter.skipped` 与 `lastError`;常见原因是没配 `activityToken`、插件被 `enabled:false` 关掉,或令牌缺 `activity:write` scope。
|
||||||
`lastError`;常见原因是没配 `activityToken`、`activityEnabled:false`、
|
- **工具报“未配置记忆令牌”**:填 `memoryToken`;写入还需要云端已配置 WebDAV 主存储(否则服务端 409 `storage_not_configured`)。
|
||||||
总开关 `enabled:false`,或令牌缺 `activity:write` scope。
|
- **网络不可用**:上报会进队列,恢复后 30 秒内自动补发;也可以在配置页点“重试上报队列”。
|
||||||
- **工具报「未配置记忆令牌」**:填 `memoryToken`(配置页或环境变量——
|
- **令牌泄漏风险**:令牌只存在本机 JSON 文件里,页面只回显掩码(`cmt_act…0001`)。文件权限依赖用户目录 ACL(Windows 无 POSIX 位)。
|
||||||
环境变量需同时设置正确的 `DSH_BRAIN_TOKEN_ORIGIN`);写入还需要云端
|
|
||||||
已配置 WebDAV 主存储(否则服务端 409 `storage_not_configured`)。
|
|
||||||
- **环境变量令牌不生效**:检查 `DSH_BRAIN_TOKEN_ORIGIN` 是否设置且等于
|
|
||||||
当前 `baseUrl` 的 origin(`https://host:port` 形式);origin 不匹配时
|
|
||||||
插件有意忽略环境变量。
|
|
||||||
- **网络不可用**:上报会进队列,恢复后 30 秒内自动补发;也可以在配置页
|
|
||||||
点「重试上报队列」。
|
|
||||||
- **令牌泄漏风险**:令牌只存在本机 JSON 文件里,页面只回显掩码
|
|
||||||
(`cmt_act…0001`)。文件权限依赖用户目录 ACL(Windows 无 POSIX 位)。
|
|
||||||
|
|
||||||
## 开发与发布
|
## 开发与发布
|
||||||
|
|
||||||
|
|
@ -313,54 +197,31 @@ node scripts/pack-guard.mjs # 白名单与脱敏闸门,不通
|
||||||
pnpm publish --access public --no-git-checks
|
pnpm publish --access public --no-git-checks
|
||||||
```
|
```
|
||||||
|
|
||||||
`prepack` 会先重建 `lib/`,`prepublishOnly` 会先跑 `pack-guard`:包里一旦
|
`prepack` 会先重建 `lib/`,`prepublishOnly` 会先跑 `pack-guard`:包里一旦出现 `AGENTS.md`、`TODO.md`、`*.mjs` 探测脚本、`tsconfig*.json`、本机路径、个人域名或令牌原文,发布立刻中止。
|
||||||
出现 `AGENTS.md`、`TODO.md`、`*.mjs` 探测脚本、`tsconfig*.json`、本机路径、
|
|
||||||
个人域名或令牌原文,发布立刻中止。
|
|
||||||
|
|
||||||
> lifecycle 脚本要求 `node` 在 `PATH` 里。若报 `'node' is not recognized`,
|
> lifecycle 脚本要求 `node` 在 `PATH` 里。若报 `'node' is not recognized`,先把 DSH 运行时自带 node 的 `bin` 目录加进 `$env:Path` 再发布。
|
||||||
> 先把 DSH 运行时自带 node 的 `bin` 目录加进 `$env:Path` 再发布。
|
|
||||||
|
|
||||||
## 统一管理卡
|
## 统一管理卡(0.7.0)
|
||||||
|
|
||||||
「设置 → 云端记忆」是三个页签:**连接与上报 / 技能管理 / MCP 管理**。
|
「设置 → 云端记忆」现在是三个页签:**连接与上报 / 技能管理 / MCP 管理**。
|
||||||
|
|
||||||
- 身份验证卡内切换「账号登录 / 手动令牌」,切换不清凭据、不发请求。
|
- 身份验证卡内切换「账号登录 / 手动令牌」,切换不清凭据、不发请求。
|
||||||
- 服务地址换 origin 时,旧令牌一律清除(`credentialsCleared`),要求重新
|
- 服务地址换 origin 时,旧令牌一律清除(`credentialsCleared`),要求重新认证。
|
||||||
认证;环境变量令牌也会因 origin 绑定而失效。
|
- 技能安装是两步:`install/plan` 把仓库克隆到隔离暂存目录并列出候选(含冲突、脚本、体积),`install/commit` 只写入选中的目录;`.git` 与符号链接不复制,仓库脚本不执行。
|
||||||
- 技能安装是两步:`install/plan` 把仓库克隆到隔离暂存目录并列出候选
|
- 卸载同样是两步:`uninstall/plan` 给出真实目录、文件数与不可恢复提示并签发一次性 token,`remove` 必须带 `confirmed: true` 与匹配 token。
|
||||||
(含冲突、脚本、体积),`install/commit` 只写入选中的目录;`.git` 与
|
- **技能市场(P3)**:接入经验证来源 `anthropics/skills` 的 `.claude-plugin/marketplace.json`;搜索→详情→`market/plan`(固定提交)→勾选安装。客户端只传 provider/id,从不传 URL。
|
||||||
符号链接不复制,仓库脚本不执行。
|
- **更新/回退(P3)**:安装写 `.skill-source.json`;`skills/update/check|apply` 与 `skills/rollback` 更新前整目录备份,过期提交拒绝。
|
||||||
- 卸载同样是两步:`uninstall/plan` 给出真实目录、文件数与不可恢复提示
|
- **同步冲突(P3)**:`sync/status|run|resolve` 提供两侧信息,逐项「保留本地 / 采用云端 / 手动合并」。
|
||||||
并签发一次性 token,`remove` 必须带 `confirmed: true` 与匹配 token。
|
- **MCP 管理(P4)**:读取宿主 `dsh-mcp-connector` 的同源公开接口 `/mcp-connector/api`;覆盖连接、健康检查、工具、启停、重连、两段式移除、目录市场连接、自定义 HTTP/stdio、JSON 导入、配置编辑、作用域与治理策略。
|
||||||
- **技能市场(P3)**:接入经验证来源 `anthropics/skills` 的
|
|
||||||
`.claude-plugin/marketplace.json`;搜索→详情→`market/plan`(固定提交)
|
|
||||||
→勾选安装。客户端只传 provider/id,从不传 URL。
|
|
||||||
- **更新/回退(P3)**:安装写 `.skill-source.json`;`skills/update/check|apply`
|
|
||||||
与 `skills/rollback` 更新前整目录备份,过期提交拒绝。
|
|
||||||
- **同步冲突(P3)**:`sync/status|run|resolve|resolve-all` 提供两侧信息;
|
|
||||||
面板支持逐项「保留本地 / 采用云端 / 手动合并」,也支持「全部保留本地 /
|
|
||||||
全部采用云端」批量处理(二次确认,逐项失败会汇总提示)。
|
|
||||||
- **MCP 管理(P4)**:读取宿主 `dsh-mcp-connector` 的同源公开接口
|
|
||||||
`/mcp-connector/api`;覆盖连接、健康检查、工具、启停、重连、两段式移
|
|
||||||
除、目录市场连接、自定义 HTTP/stdio、JSON 导入、配置编辑、作用域与治
|
|
||||||
理策略。停用 `dsh-brain-mcp` 子插件只隐藏 MCP 页签与能力声明,不影响
|
|
||||||
宿主连接本身;本插件不做 MCP 配置的云端同步。
|
|
||||||
|
|
||||||
接口清单见 `docs/management-surface.md`;验收脚本见 `verify-*.mjs`(含
|
接口清单见 `docs/management-surface.md`;验收脚本见 `verify-*.mjs`(含 `verify-market` / `verify-skill-update` / `verify-sync-resolve` / `verify-mcp-bridge` / `verify-upgrade` / `verify-concurrency` / `verify-theme`)。
|
||||||
`verify-market` / `verify-skill-update` / `verify-sync-resolve` /
|
|
||||||
`verify-mcp-bridge` / `verify-upgrade` / `verify-concurrency` /
|
|
||||||
`verify-review-fixes` / `verify-theme`)。
|
|
||||||
|
|
||||||
### 技能来源树
|
### 技能来源树
|
||||||
|
|
||||||
「技能管理」按软件来源分组(DSH / 公共 Agent / Codex / WorkBuddy /
|
「技能管理」按软件来源分组(DSH / 公共 Agent / Codex / WorkBuddy / Claude Code / OpenCode),
|
||||||
Claude Code / OpenCode),每个来源下是分类,分类下是技能:
|
每个来源下是分类,分类下是技能:
|
||||||
|
|
||||||
- 分类只记在 `$DSH_HOME/dsh-brain-skill-groups.json` 里,**不移动文件**;
|
- 分类只记在 `$DSH_HOME/cloud-memory-skill-groups.json` 里,**不移动文件**;删除分类只是把技能放回「未分类」。
|
||||||
删除分类只是把技能放回「未分类」。
|
- 只有 DSH 来源的开关是真的(目录移入/移出 `skills-disabled`,新会话生效);其他软件的目录本卡只读,开关标记为「仅本卡」。
|
||||||
- 只有 DSH 来源的开关是真的(目录移入/移出 `skills-disabled`,新会话生
|
- 来源行提供「+ 新建分类」「打开目录」「来源开关」;分类行提供「+ 加入技能 / 改名 / 删除 / 分类开关」;技能行提供详情、启停、卸载。
|
||||||
效);其他软件的目录本卡只读,开关标记为「仅本卡」。
|
- 预览(真实数据、光照/暗色):`node preview-card.mjs` 生成 `_preview/skill-tree*.png`。
|
||||||
- 来源行提供「+ 新建分类」「打开目录」「来源开关」;分类行提供「+ 加入
|
|
||||||
技能 / 改名 / 删除 / 分类开关」;技能行提供详情、启停、卸载。
|
|
||||||
- 预览(真实数据、光照/暗色):`node preview-card.mjs` 生成
|
|
||||||
`_preview/skill-tree*.png`。
|
|
||||||
|
|
|
||||||
53546
client/index.js
53546
client/index.js
File diff suppressed because one or more lines are too long
138
cordis.patch.yml
138
cordis.patch.yml
|
|
@ -1,137 +1,13 @@
|
||||||
# dsh-brain bundle patch. The original six entries share the Brain kernel.
|
# cloud-memory bundle patch
|
||||||
# The Mnemon backend has its own Loader entry and contribution graph.
|
|
||||||
#
|
#
|
||||||
# Toggling: the host Settings → Plugins page (and dshmarket) write
|
# Local-only build: this package is never published, so the row below is the
|
||||||
# `- id: <row> / disabled: true` lines into the profile patch, keyed by row
|
# only way the plugin reaches the desktop profile tree. The host Loader
|
||||||
# id. Settings themselves persist in $DSH_HOME/dsh-brain.json; the seed
|
# resolves the row `name` as a package from the profile node_modules.
|
||||||
# config below only matters on first boot, so the rows stay safe to toggle
|
|
||||||
# in any order.
|
|
||||||
#
|
|
||||||
# Do NOT copy this insert block into the profile's cordis.patch.yml —
|
|
||||||
# duplicating entry ids breaks the Settings page. Keep overrides as
|
|
||||||
# top-level `- id: <row>` rows only.
|
|
||||||
#
|
|
||||||
# The compat root export (`.`) stays for older single-row profiles: it
|
|
||||||
# applies all six entries at once.
|
|
||||||
- insert:
|
- insert:
|
||||||
- id: dsh-brain-cloudsync
|
- id: cloud-memory
|
||||||
name: dsh-brain/cloudsync
|
name: 'dsh-cloud-memory'
|
||||||
config:
|
config:
|
||||||
enabled: false
|
enabled: true
|
||||||
baseUrl: https://your-memory-host/api/longmemory
|
baseUrl: https://your-memory-host/api/longmemory
|
||||||
clientId: dsh-desktop
|
clientId: dsh-desktop
|
||||||
skillsSyncEnabled: true
|
skillsSyncEnabled: true
|
||||||
- id: dsh-brain-memory
|
|
||||||
name: dsh-brain/memory
|
|
||||||
- id: dsh-brain-raw
|
|
||||||
name: dsh-brain/raw
|
|
||||||
config:
|
|
||||||
rawEnabled: true
|
|
||||||
rawCaptureAssistant: true
|
|
||||||
rawRetentionDays: 90
|
|
||||||
- id: dsh-brain-skills
|
|
||||||
name: dsh-brain/skills
|
|
||||||
- id: dsh-brain-mcp
|
|
||||||
name: dsh-brain/mcp
|
|
||||||
- id: dsh-brain-ui
|
|
||||||
# DSH discovers browser bundles from bare package names.
|
|
||||||
name: dsh-brain
|
|
||||||
config:
|
|
||||||
entry: ui
|
|
||||||
# Mount the tracked fork and its components through this package's host exports.
|
|
||||||
- id: dsh-brain-mnemon-bundle
|
|
||||||
name: cordis:group
|
|
||||||
group: true
|
|
||||||
disabled: !!js >-
|
|
||||||
(() => {
|
|
||||||
let bundle = ctx[Symbol.for('cordis.entry')];
|
|
||||||
while (bundle && !/(?:^|-)mnemon-bundle$/.test(bundle.options.id)) {
|
|
||||||
bundle = bundle.parent?.ctx.fiber.entry;
|
|
||||||
}
|
|
||||||
if (!bundle?.subgroup) return false;
|
|
||||||
const coreId = bundle.options.id.replace(/-bundle$/, '');
|
|
||||||
const core = [...loader.entries()].find(entry =>
|
|
||||||
entry.parent === bundle.subgroup && entry.options.id === coreId);
|
|
||||||
const disabled = core?.options.disabled;
|
|
||||||
return disabled?.__jsExpr
|
|
||||||
? Boolean(core.evaluate(disabled.__jsExpr))
|
|
||||||
: Boolean(disabled);
|
|
||||||
})()
|
|
||||||
config:
|
|
||||||
- id: dsh-brain-mnemon
|
|
||||||
# Core/Host and default settings. Sources own their independent Entries.
|
|
||||||
name: dsh-brain/mnemon
|
|
||||||
config:
|
|
||||||
routingGuidance: true
|
|
||||||
lifecycleEnabled: true
|
|
||||||
recallMode: guided
|
|
||||||
writebackMode: guided
|
|
||||||
idleReviewMs: 30000
|
|
||||||
storageScope: workspaces
|
|
||||||
tabEnabled: true
|
|
||||||
writeEnabled: true
|
|
||||||
remoteAccess: disabled
|
|
||||||
timeoutMs: 10000
|
|
||||||
defaultRecallLimit: 10
|
|
||||||
embedding:
|
|
||||||
enabled: false
|
|
||||||
endpoint: http://localhost:11434
|
|
||||||
model: nomic-embed-text
|
|
||||||
recallQuality:
|
|
||||||
policy: strict-v1
|
|
||||||
lowScoreThreshold: 0.25
|
|
||||||
highScoreThreshold: 0.6
|
|
||||||
candidateMultiplier: 3
|
|
||||||
maxMediumResults: 4
|
|
||||||
maxRankedResults: 4
|
|
||||||
maxUnknownResults: 2
|
|
||||||
- id: dsh-brain-mnemon-source-runtime
|
|
||||||
name: dsh-brain/mnemon/source-runtime
|
|
||||||
- id: dsh-brain-mnemon-source-documents
|
|
||||||
name: dsh-brain/mnemon/source-documents
|
|
||||||
- id: dsh-brain-mnemon-source-memory-spaces
|
|
||||||
name: dsh-brain/mnemon/source-memory-spaces
|
|
||||||
config:
|
|
||||||
# Every default Provider is an
|
|
||||||
# explicit child. A custom parent composition may choose a subset.
|
|
||||||
providers:
|
|
||||||
- use: dsh-brain/mnemon/provider-mnemon-native
|
|
||||||
instanceId: mnemon-native
|
|
||||||
- use: dsh-brain/mnemon/provider-openviking
|
|
||||||
instanceId: openviking
|
|
||||||
- use: dsh-brain/mnemon/provider-honcho
|
|
||||||
instanceId: honcho
|
|
||||||
- use: dsh-brain/mnemon/provider-mem0
|
|
||||||
instanceId: mem0
|
|
||||||
- use: dsh-brain/mnemon/provider-hindsight
|
|
||||||
instanceId: hindsight
|
|
||||||
- use: dsh-brain/mnemon/provider-holographic
|
|
||||||
instanceId: holographic
|
|
||||||
- use: dsh-brain/mnemon/provider-retaindb
|
|
||||||
instanceId: retaindb
|
|
||||||
- use: dsh-brain/mnemon/provider-byterover
|
|
||||||
instanceId: byterover
|
|
||||||
- use: dsh-brain/mnemon/provider-supermemory
|
|
||||||
instanceId: supermemory
|
|
||||||
# Skills keep DSH's own files and their evolution data; the page lives
|
|
||||||
# in the Memory System and nothing joins a model View.
|
|
||||||
- id: dsh-brain-mnemon-source-skills
|
|
||||||
name: dsh-brain/mnemon/source-skills
|
|
||||||
- id: dsh-brain-mnemon-strategy-default-three-tier
|
|
||||||
name: dsh-brain/mnemon/strategy-default-three-tier
|
|
||||||
# A second main Strategy; memoryView.strategyTypeId selects which one
|
|
||||||
# composes the View. It stays off until selected.
|
|
||||||
- id: dsh-brain-mnemon-strategy-general
|
|
||||||
name: dsh-brain/mnemon/strategy-general
|
|
||||||
disabled: true
|
|
||||||
# v0.5 ships these narrowly scoped enhancements with the Starter so the
|
|
||||||
# Settings switches are always available. They remain opt-in.
|
|
||||||
- id: dsh-brain-mnemon-strategy-auto-capture
|
|
||||||
name: dsh-brain/mnemon/strategy-auto-capture
|
|
||||||
disabled: true
|
|
||||||
- id: dsh-brain-mnemon-strategy-light-context
|
|
||||||
name: dsh-brain/mnemon/strategy-light-context
|
|
||||||
disabled: true
|
|
||||||
- id: dsh-brain-mnemon-strategy-scoped
|
|
||||||
name: dsh-brain/mnemon/strategy-scoped
|
|
||||||
disabled: true
|
|
||||||
|
|
|
||||||
|
|
@ -1,122 +0,0 @@
|
||||||
# Local Memory Phase 1 Acceptance
|
|
||||||
|
|
||||||
Date: 2026-11-24 (Asia/Shanghai)
|
|
||||||
|
|
||||||
Scope: the local-first phase described by `docs/plans/LOCAL_MEMORY_PLAN.md`.
|
|
||||||
Cloud synchronization is deliberately **not** implemented in this phase (plan
|
|
||||||
section 15); the local layer remains usable without an account, token or network.
|
|
||||||
|
|
||||||
## Commands and results
|
|
||||||
|
|
||||||
| Command | Result |
|
|
||||||
| --- | --- |
|
|
||||||
| `node verify-local-memory.mjs` | ALL 22 CHECKS PASSED |
|
|
||||||
| `node verify-local-memory-acceptance.mjs` | ALL 23 CHECKS PASSED |
|
|
||||||
| `node verify-local-memory-round3.mjs` | ALL 19 CHECKS PASSED |
|
|
||||||
| `node verify-auto-summary-round3.mjs` | ALL 7 CHECKS PASSED |
|
|
||||||
| `node verify-memory-switches-round3.mjs` | ALL 5 CHECKS PASSED |
|
|
||||||
| `node verify-skill-sync-round2.mjs` | ALL 13 CHECKS PASSED |
|
|
||||||
| `node verify-sync-resolve.mjs` | 23/23 passed |
|
|
||||||
| `node verify-skill-sync-scope-round3.mjs` | ALL 2 CHECKS PASSED |
|
|
||||||
| `node verify-skill-sync-conflict-round5.mjs` | ALL 19 CHECKS PASSED |
|
|
||||||
| `node verify-local-memory-round4.mjs` | ALL 12 CHECKS PASSED |
|
|
||||||
| `node verify-local-memory-round5.mjs` | ALL 6 CHECKS PASSED |
|
|
||||||
| `node verify-local-memory-round6.mjs` | ALL 8 CHECKS PASSED |
|
|
||||||
| `node verify-auto-summary-host-retry-round5.mjs` | ALL 3 CHECKS PASSED |
|
|
||||||
| `node verify-skill-update.mjs` | 16/16 passed |
|
|
||||||
| `node verify-mnemon-native.mjs` | ALL 6 CHECKS PASSED |
|
|
||||||
| `node verify-mnemon-fork.mjs` | ALL 23 CHECKS PASSED |
|
|
||||||
| `node verify-mnemon-provider.mjs` | ALL 14 CHECKS PASSED |
|
|
||||||
| `node scripts/verify-all.mjs` | 38 scripts: 38 passed (1 with environmental skips), all green |
|
|
||||||
|
|
||||||
## Acceptance mapping
|
|
||||||
|
|
||||||
| # | Criterion | Evidence |
|
|
||||||
| --- | --- | --- |
|
|
||||||
| 1 | Fresh environment can use memory without manual space creation | `verify-local-memory-acceptance.mjs` check 1 |
|
|
||||||
| 2 | One global and one current-project space are created automatically | check 2 |
|
|
||||||
| 3 | Restart / repeated initialization does not duplicate spaces | checks 3, 13 |
|
|
||||||
| 4 | Global and project directories follow `.dsh/brain`, no `.mnemon` | check 4 |
|
|
||||||
| 5 | Offline / no-account / no-cloud-config local use works | check 5 and `verify-local-memory.mjs` |
|
|
||||||
| 6 | Cloud adapter receives zero calls when sync is off | checks 16, 17 |
|
|
||||||
| 7 | Automatic summary is incremental, deduplicated, source-traceable and compactly projected | checks 10, 22 |
|
|
||||||
| 8 | Automatic profile stores only explicit preferences; one-off wording is ignored; correction invalidates the old text | checks 9, 11, 23 |
|
|
||||||
| 9 | Default search covers current project + global and caps results | checks 6, 7, 8 |
|
|
||||||
| 10 | Update / delete / concurrent writes / restart do not lose or duplicate records | checks 12, 13; tombstone check in `verify-local-memory.mjs` |
|
|
||||||
| 11 | Project `.dsh/brain` is not committed by default | check 19 |
|
|
||||||
| 12 | Existing Source / Provider / Strategy / Skill / public interfaces remain available | `verify-all.mjs`, `verify-mnemon-provider.mjs` |
|
|
||||||
| 13 | Settings page never accesses SQLite, CLI or Provider internals | check 18 |
|
|
||||||
| 14 | Legacy migration is verifiable and rollbackable, original files remain | check 15 |
|
|
||||||
| 15 | Automatic summary and manual writes never store secrets | checks 20, 21 |
|
|
||||||
|
|
||||||
## Fourth-round regression mapping
|
|
||||||
|
|
||||||
| Area | Assertions |
|
|
||||||
| --- | --- |
|
|
||||||
| Migration rollback | occupied destination failure leaves active records intact; retry restores and repeated rollback is safe; parallel migration receipts |
|
|
||||||
| Summary document transaction | corrupt index, index success + Markdown failure, retry, replay and duplicate prevention |
|
|
||||||
| Conflict scope | connection snapshot test plus existing account-isolation assertions |
|
|
||||||
| Profile validation | empty/secret update rejected without changing the old record |
|
|
||||||
| Skill rollback | added/changed/removed file statistics checked in `verify-skill-update.mjs` |
|
|
||||||
|
|
||||||
## Third-round regression mapping
|
|
||||||
|
|
||||||
| Area | Assertions |
|
|
||||||
| --- | --- |
|
|
||||||
| Workspace isolation | `verify-local-memory-round3.mjs` A/B writes, searches, reads and shared global state |
|
|
||||||
| Storage safety | concurrent first initialization; corrupt JSON preserved; projection retry; 1005-record pagination |
|
|
||||||
| Summary events | `verify-auto-summary-round3.mjs` structured text, injected-content exclusion, three replays, empty replay, one-off rule |
|
|
||||||
| Query scope | project filter before `k` truncation; filtered list total and offset |
|
|
||||||
| Memory switches | `verify-memory-switches-round3.mjs` local/cloud/all-off combinations and status without side effects |
|
|
||||||
| Skill sync | uploaded-file deletion, different local folder name, connection snapshot, existing account isolation |
|
|
||||||
|
|
||||||
## Fix found during acceptance
|
|
||||||
|
|
||||||
`LocalMemoryManager.createBackup()` originally asked `fs.cp` to copy the whole
|
|
||||||
global root into a subdirectory of itself, which fails with
|
|
||||||
`ERR_FS_CP_EINVAL` on Windows and Node 24. It now creates the backup directory
|
|
||||||
and copies each top-level entry except `backups` into it. The acceptance test
|
|
||||||
check 14 covers this regression.
|
|
||||||
|
|
||||||
## Fifth-round regression mapping
|
|
||||||
|
|
||||||
| Area | Assertions |
|
|
||||||
| --- | --- |
|
|
||||||
| Rollback final copy | destination child conflict fails before active mutation; retry and restore copy remain valid |
|
|
||||||
| Re-import after rollback | re-migration restores exactly one active record; repeated migration deduplicates |
|
|
||||||
| Host summary retry | host event failure keeps the pending turn; retry after document repair creates one summary |
|
|
||||||
| Conflict confirmation | conflict preview carries conflictId/scope/local/cloud versions; stale confirmation is rejected |
|
|
||||||
|
|
||||||
## Sixth-round regression mapping
|
|
||||||
|
|
||||||
| Area | Assertions |
|
|
||||||
| --- | --- |
|
|
||||||
| Migration ownership | content-only duplicate is not owned; mixed existing/new rollback removes only the new record |
|
|
||||||
| Restore safety | non-empty target rejected before active mutation; completed rollback copy path verified |
|
|
||||||
| Workspace-scoped rollback | migration initiated in A and rolled back from B uses A's receipt target |
|
|
||||||
| Conflict/alias | preview-bound confirmation; physical directory aliases preserved (round-5/round-2 scripts) |
|
|
||||||
|
|
||||||
## Environment limits
|
|
||||||
|
|
||||||
- Verified with Node 24.21.0 and the bundled TypeScript toolchain. Node 20 was
|
|
||||||
not installed in this environment; the package engine remains `>=20`.
|
|
||||||
- `pnpm install --lockfile-only --ignore-scripts` regenerated the lockfile with
|
|
||||||
the root Mnemon dependency removed. A clean frozen install was not re-run;
|
|
||||||
the offline mirror lacked the metadata needed for that check.
|
|
||||||
- Real DSH host MCP, a real Mnemon host process and a real cloud endpoint were
|
|
||||||
not exercised. `verify-mcp-bridge.mjs` is excluded from the default suite;
|
|
||||||
run it explicitly with `DSH_VERIFY_REAL_MCP=1`. The provider registration
|
|
||||||
test uses a host-shaped fake and temporary files.
|
|
||||||
- The host-event pending-summary queue is in-process only; restart persistence
|
|
||||||
is not implemented in this phase.
|
|
||||||
|
|
||||||
## Not covered in this phase
|
|
||||||
|
|
||||||
- Real cloud push/pull, cloud change cursors, remote conflict merge and external
|
|
||||||
Provider adapters (plan section 15; later cloud-sync).
|
|
||||||
- The full upstream Mnemon runtime is not loaded automatically as dsh-brain's
|
|
||||||
active engine: the complete source fork is in `vendor/dsh-mnemon`, the active
|
|
||||||
provider SDK subset is `src/mnemon/fork`, and the local native provider entry
|
|
||||||
is `src/mnemon/native.ts` (host registration covered by `verify-mnemon-native.mjs`).
|
|
||||||
- Cross-process file-lock behavior under adversarial operating-system failures;
|
|
||||||
normal concurrent writes and restart behavior are covered.
|
|
||||||
|
|
@ -1,111 +0,0 @@
|
||||||
# Local Memory Implementation (Phase 1)
|
|
||||||
|
|
||||||
This repository now implements the local-first memory phase from
|
|
||||||
`docs/plans/LOCAL_MEMORY_PLAN.md`. Cloud syncing remains disabled by default
|
|
||||||
and no local memory operation requires an account, token or network.
|
|
||||||
|
|
||||||
## Layout
|
|
||||||
|
|
||||||
- Global: `$DSH_HOME/brain/`
|
|
||||||
- `runtime/memories.json` — local JSON record store
|
|
||||||
- `runtime/USER.md`, `runtime/MEMORY.md` — generated compact projections
|
|
||||||
- `spaces/global/space.json` — stable global space marker
|
|
||||||
- `backups/`, `state/`
|
|
||||||
- Project: `<project>/.dsh/brain/`
|
|
||||||
- `documents/` — project summaries and decisions
|
|
||||||
- `memory-space/` — project memory records and space marker
|
|
||||||
- `state/`
|
|
||||||
- The project `.dsh/.gitignore` ignores `brain/` only; it does not ignore
|
|
||||||
the rest of `.dsh`.
|
|
||||||
- No `.mnemon` directory is created.
|
|
||||||
|
|
||||||
## Management API
|
|
||||||
|
|
||||||
The settings-ui bundle exposes a local-memory management surface under
|
|
||||||
`/dsh-brain/local-memory`:
|
|
||||||
|
|
||||||
- `GET /status` — storage roots, space markers and sync switches;
|
|
||||||
- `GET /spaces` and `GET /documents` — available spaces and project documents;
|
|
||||||
- `GET /memories?limit=&offset=` — paginated local records;
|
|
||||||
- `GET /search?q=&k=` — bounded local search over the project and global spaces;
|
|
||||||
- `POST /forget` — revision-checked tombstone delete;
|
|
||||||
- `POST /backup` — create a copy of the global brain root;
|
|
||||||
- `GET|POST /migrate` — inspect legacy `.mnemon` locations, copy one into
|
|
||||||
backups, or roll a copied backup into a new destination.
|
|
||||||
|
|
||||||
All write routes require a same-origin request. These routes only use
|
|
||||||
`LocalMemoryManager`'s public methods and never touch SQLite, CLI or provider
|
|
||||||
privates.
|
|
||||||
|
|
||||||
## Data model
|
|
||||||
|
|
||||||
Every memory record has a unique id, scope, space id, content, category,
|
|
||||||
tags, source, created/updated timestamps, revision (starting at 1), a local
|
|
||||||
monotonic `changeSeq`, and a tombstone flag for deletes. Writes are atomic and
|
|
||||||
serialized through a per-space lock. Exact duplicate content returns the
|
|
||||||
existing record with `duplicate: true`.
|
|
||||||
|
|
||||||
## Automatic behavior
|
|
||||||
|
|
||||||
- Global and project spaces are created lazily and idempotently on first memory
|
|
||||||
use; restarting or opening multiple windows reuses the same markers.
|
|
||||||
- Explicit long-term statements from user turns are captured incrementally into
|
|
||||||
USER.md/MEMORY.md by `LocalMemoryManager.summarizeConversation`; assistant
|
|
||||||
text and raw transcripts are never stored by that path.
|
|
||||||
- The generated USER.md/MEMORY.md files are exposed as a compact system-prompt
|
|
||||||
section (`dsh-brain:local-memory`) once per turn; they are not re-injected in
|
|
||||||
full and are empty when local memory is disabled.
|
|
||||||
- `proposeProfile(..., inferred=true)` keeps inferred behavior in a pending
|
|
||||||
area; only explicit entries are projected into USER.md. `correctProfile`
|
|
||||||
increments the revision and regenerates the projection.
|
|
||||||
- Search defaults to the project and global spaces only and returns five items.
|
|
||||||
- Cloud memory is selected only when `cloudMemoryEnabled` is true **and** a
|
|
||||||
memory token is configured; otherwise the memory tools use the local remote.
|
|
||||||
|
|
||||||
## Migration
|
|
||||||
|
|
||||||
`legacyMigrationReport()` reports existing `.mnemon` locations without moving
|
|
||||||
anything. `migrateLegacy(path)` copies a legacy tree into `backups/` and records
|
|
||||||
the operation in `state/migrations.json`; `rollbackMigration(backup, destination)`
|
|
||||||
copies it back to a new location. Neither operation deletes the original.
|
|
||||||
|
|
||||||
## Verification
|
|
||||||
|
|
||||||
`node verify-local-memory.mjs` covers directory creation, idempotent spaces,
|
|
||||||
deduplication, revisions/tombstones, restart persistence, summary/profile
|
|
||||||
projections, documents, migration reporting and the local memory remote.
|
|
||||||
`node scripts/verify-all.mjs` runs the complete repository suite.
|
|
||||||
`node verify-local-memory-acceptance.mjs` and `docs/LOCAL_MEMORY_ACCEPTANCE.md`
|
|
||||||
map the plan criteria to executable evidence.
|
|
||||||
|
|
||||||
## Workspace and reliability
|
|
||||||
|
|
||||||
- Every tool/session operation runs inside `LocalMemoryManager.withWorkspace`
|
|
||||||
(AsyncLocalStorage). Project stores and document stores are cached per
|
|
||||||
normalized workspace path, not per manager instance, so switching A to B in
|
|
||||||
one process cannot read A's project records.
|
|
||||||
- `JsonMemoryStore` and `JsonDocumentStore` distinguish a missing data file from
|
|
||||||
a corrupt or incompatible one. Corrupt files are preserved and reported; only
|
|
||||||
a missing file initializes an empty store.
|
|
||||||
- Initialization, project mapping, session checkpoints and projection writes
|
|
||||||
use per-target file locks and unique temporary names. A committed memory write
|
|
||||||
with a failed projection leaves `state/projection.json` dirty; the next
|
|
||||||
`ensureGlobal()` retries it.
|
|
||||||
- `src/mnemon/native.ts` exposes the local store as a Mnemon Native provider
|
|
||||||
using the vendored `dsh-brain-mnemon.memory-space-provider/v1` contract.
|
|
||||||
|
|
||||||
## Mnemon fork and remaining gaps
|
|
||||||
|
|
||||||
`vendor/dsh-mnemon` is the independent `dsh-brain-mnemon` source fork of
|
|
||||||
`omdsh-dev/dsh-mnemon` (upstream revision `8b650ab5ef33522e03887b250b13336593daa26f`,
|
|
||||||
0.5.54, MIT). It retains the complete upstream Monorepo source, including
|
|
||||||
Runtime, Documents, Memory Spaces, Skills Source, Mnemon Native, all external
|
|
||||||
Provider plugins and all strategy plugins. See `docs/MNEMON_FORK.md` and
|
|
||||||
`vendor/dsh-mnemon/FORK_NOTICE.md`.
|
|
||||||
|
|
||||||
The provider-SDK subset used by dsh-brain is copied to `src/mnemon/fork`; the
|
|
||||||
package no longer depends on `dsh-mnemon-source-memory-spaces`. The local JSON
|
|
||||||
engine above remains the phase-1 kernel behind the public memory tools. Loading
|
|
||||||
the full upstream Mnemon runtime as the memory engine, cloud change cursors,
|
|
||||||
remote conflict merge and external Provider adapters remain later cloud-sync
|
|
||||||
work.
|
|
||||||
|
|
@ -1,79 +0,0 @@
|
||||||
# Mnemon fork (dsh-brain)
|
|
||||||
|
|
||||||
## Status
|
|
||||||
|
|
||||||
- Fork location: `vendor/dsh-mnemon`
|
|
||||||
- Fork package: `dsh-brain-mnemon` `0.5.54-dsh.1` (private)
|
|
||||||
- Upstream: `omdsh-dev/dsh-mnemon`
|
|
||||||
- Upstream revision: `8b650ab5ef33522e03887b250b13336593daa26f`
|
|
||||||
- Upstream version: `0.5.54`
|
|
||||||
- License: MIT, Copyright (c) 2026 dsh-external contributors
|
|
||||||
|
|
||||||
The snapshot contains the complete upstream Monorepo source: core/host/client/sdk,
|
|
||||||
Runtime, Documents, Memory Spaces, Skills Source, Mnemon Native, every external
|
|
||||||
Provider plugin and every strategy plugin. Upstream docs, changelogs and the MIT
|
|
||||||
license/third-party notices are kept as-is.
|
|
||||||
|
|
||||||
## Identity policy
|
|
||||||
|
|
||||||
Every package name, import specifier, runtime schema id, bundle entry id and
|
|
||||||
plugin directory has been rewritten from `dsh-mnemon` to `dsh-brain-mnemon`.
|
|
||||||
The root package is marked private and records its upstream provenance in
|
|
||||||
`package.json#dshBrainFork` and `FORK_NOTICE.md`. Upstream repository URLs,
|
|
||||||
copyright notices and license files are preserved.
|
|
||||||
|
|
||||||
## Active integration
|
|
||||||
|
|
||||||
`src/mnemon/fork` is the provider-SDK subset dsh-brain actually builds against.
|
|
||||||
It mirrors `plugins/dsh-mnemon-source-memory-spaces/src` from the same upstream
|
|
||||||
revision with a local contract adapter, and is imported by `src/mnemon/index.ts`,
|
|
||||||
`src/mnemon/descriptor.ts` and `src/mnemon/driver.ts`. dsh-brain no longer
|
|
||||||
declares `dsh-mnemon-source-memory-spaces` as a peer or dev dependency.
|
|
||||||
|
|
||||||
## Sync and verification
|
|
||||||
|
|
||||||
Regenerate the snapshot with:
|
|
||||||
|
|
||||||
```bash
|
|
||||||
node scripts/fork-mnemon.mjs --source <upstream-checkout> --target vendor/dsh-mnemon --force
|
|
||||||
node scripts/fork-mnemon.mjs --check
|
|
||||||
node verify-mnemon-fork.mjs
|
|
||||||
```
|
|
||||||
|
|
||||||
Update `PINNED_REVISION` and `PINNED_VERSION` in `scripts/fork-mnemon.mjs` when
|
|
||||||
syncing. Review the diff and keep `LICENSE`, `THIRD_PARTY_NOTICES.md` and
|
|
||||||
`FORK_NOTICE.md` intact.
|
|
||||||
|
|
||||||
## Current scope
|
|
||||||
|
|
||||||
The fork snapshot is complete, but dsh-brain currently loads only its local
|
|
||||||
provider-SDK subset and the phase-1 local JSON memory engine. Loading the full
|
|
||||||
upstream Mnemon runtime as the memory engine, cloud change cursors, remote
|
|
||||||
conflict merging and external Provider adapters remain later cloud-sync work.
|
|
||||||
|
|
||||||
## Native provider entry
|
|
||||||
|
|
||||||
`src/mnemon/native.ts` exposes the local JSON memory store through the vendored
|
|
||||||
provider contract `dsh-brain-mnemon.memory-space-provider/v1`. Its manifest and
|
|
||||||
actual host `install()` path are covered by `verify-mnemon-native.mjs`, including
|
|
||||||
remember / search / get / forget against a temporary project workspace.
|
|
||||||
|
|
||||||
## Cloud-sync handoff
|
|
||||||
|
|
||||||
The later cloud-sync layer must add, rather than assume, these semantics on top of
|
|
||||||
the provider protocol:
|
|
||||||
|
|
||||||
- local `changeSeq` is not a cloud `change_id`; each sync stream needs a durable
|
|
||||||
cloud cursor and a local outbox state (`pending` / `pushed` / `acknowledged`);
|
|
||||||
- idempotency keys per write/delete operation, plus retry and backoff policy;
|
|
||||||
- revision-based conflict detection and a merge/quarantine result instead of
|
|
||||||
last-write-wins;
|
|
||||||
- tombstone/delete events because some providers hard-delete and cannot expose
|
|
||||||
deletions through browse;
|
|
||||||
- Provider transport adapters reusing connection discovery, status, search,
|
|
||||||
read/write, graph, timeout, cancellation and redaction;
|
|
||||||
- separate switches for memory sync and Skill sync, and an explicit first-sync
|
|
||||||
scope confirmation for spaces, profile and project documents.
|
|
||||||
|
|
||||||
The current phase intentionally does not implement cloud push/pull or conflict
|
|
||||||
merge (plan section 15).
|
|
||||||
|
|
@ -74,7 +74,7 @@ POST /mcp-connector/api { "method": "status" | "healthCheck" | "toolsList" | "
|
||||||
- 技能市场:无经验证来源,`features.skillsMarketplace=false`。
|
- 技能市场:无经验证来源,`features.skillsMarketplace=false`。
|
||||||
- 云端同步冲突的交互式处理(保留本地/采用云端/手动合并):仍由现有引擎按原策略暂停冲突项,界面只读展示。
|
- 云端同步冲突的交互式处理(保留本地/采用云端/手动合并):仍由现有引擎按原策略暂停冲突项,界面只读展示。
|
||||||
- 自动更新与版本回退:未实现(无来源清单与制品基线)。
|
- 自动更新与版本回退:未实现(无来源清单与制品基线)。
|
||||||
- MCP 市场的内嵌浏览与安装:**0.9.6 起从卡片移除**(宿主 `catalog` 返回 405,只留错误条没有意义),目录浏览回到宿主插件市场。
|
- MCP 市场的内嵌浏览与安装:未实现,只给宿主面板位置。
|
||||||
- 跨软件(Codex / Claude Code / OpenCode)适配与工作区级作用域:未实现,仍在方案 P0/P4 调研项。
|
- 跨软件(Codex / Claude Code / OpenCode)适配与工作区级作用域:未实现,仍在方案 P0/P4 调研项。
|
||||||
- 浏览器端实机验收(375/574/1280 宽、深色模式、真实上报):需要重启 DSH 后由用户在界面确认。
|
- 浏览器端实机验收(375/574/1280 宽、深色模式、真实上报):需要重启 DSH 后由用户在界面确认。
|
||||||
|
|
||||||
|
|
@ -165,24 +165,23 @@ POST /mcp-connector/api { "method": "status" | "healthCheck" | "toolsList" | "
|
||||||
|
|
||||||
### 6.3 同步冲突交互
|
### 6.3 同步冲突交互
|
||||||
|
|
||||||
`SkillSync` 先自动处置:内容一致直接认领,内容不同按「本地文件 mtime vs 云端 `updated_at`」自动采用较新的一边(下行覆盖前备份到 `$DSH_HOME/.dsh-brain-backups/sync/`);只有时间相同/缺失、或本地布局无法上传时才留下冲突,并暴露两侧信息允许人工处置:
|
`SkillSync` 仍然只按原策略暂停冲突项,但会暴露两侧信息并允许人工处置:
|
||||||
|
|
||||||
| 方法 | 路径 | 说明 |
|
| 方法 | 路径 | 说明 |
|
||||||
|---|---|---|
|
|---|---|---|
|
||||||
| GET | `/cloud-memory/sync/status` | 最近统计 + 每个冲突的本地/云端两侧 |
|
| GET | `/cloud-memory/sync/status` | 最近统计 + 每个冲突的本地/云端两侧 |
|
||||||
| POST | `/cloud-memory/sync/run` | 立即执行一次同步 |
|
| POST | `/cloud-memory/sync/run` | 立即执行一次同步 |
|
||||||
| POST | `/cloud-memory/sync/resolve` | `{name,action}`:`keep_local` / `take_cloud` / `manual` |
|
| POST | `/cloud-memory/sync/resolve` | `{name,action}`:`keep_local` / `take_cloud` / `manual` |
|
||||||
| POST | `/cloud-memory/sync/resolve-all` | `{action}`:对当前全部冲突批量 `keep_local` / `take_cloud`,返回 `{resolved[], failed[{name,error}]}` |
|
|
||||||
|
|
||||||
- `keep_local`:用本地文件按当前云端 revision 上传为新版本;revision 过期返回 `stale_revision`。
|
- `keep_local`:用本地文件按当前云端 revision 上传为新版本;revision 过期返回 `stale_revision`。
|
||||||
- `take_cloud`:先把本地目录备份到 `$DSH_HOME/.dsh-brain-backups/sync/<name>/<时间>`,再写入云端 bundle。
|
- `take_cloud`:先把本地目录备份到 `$DSH_HOME/.cloud-memory-backups/sync/<name>/<时间>`,再写入云端 bundle。
|
||||||
- `manual`:只返回两侧信息,不改任何文件。
|
- `manual`:只返回两侧信息,不改任何文件。
|
||||||
|
|
||||||
### 6.4 验证
|
### 6.4 验证
|
||||||
|
|
||||||
- `verify-market.mjs`:19 项通过(清单解析、search/detail、未知来源 400、plan 固定提交、只装勾选项、来源记录)。
|
- `verify-market.mjs`:19 项通过(清单解析、search/detail、未知来源 400、plan 固定提交、只装勾选项、来源记录)。
|
||||||
- `verify-skill-update.mjs`:15 项通过(真实 git 仓库的 check/apply/rollback、无来源拒绝、过期提交拒绝、备份存在)。
|
- `verify-skill-update.mjs`:15 项通过(真实 git 仓库的 check/apply/rollback、无来源拒绝、过期提交拒绝、备份存在)。
|
||||||
- `verify-sync-resolve.mjs`:23 项通过(一次真实 pass 产生 4 个冲突、take_cloud 备份并覆盖、keep_local 上传、manual 只读、stale 拒绝、批量成功与部分失败)。
|
- `verify-sync-resolve.mjs`:12 项通过(一次真实 pass 产生 4 个冲突、take_cloud 备份并覆盖、keep_local 上传、manual 只读、stale 拒绝)。
|
||||||
|
|
||||||
## 7. P4:MCP 管理与市场(0.6.0)
|
## 7. P4:MCP 管理与市场(0.6.0)
|
||||||
|
|
||||||
|
|
@ -200,8 +199,8 @@ refreshCatalog, toolsList, toolSearch, toolExplorer, toolDetail`
|
||||||
|
|
||||||
| 区块 | 能力 |
|
| 区块 | 能力 |
|
||||||
|---|---|
|
|---|---|
|
||||||
| 我的连接 | 默认一行骨架(名称 + 状态 + 传输 + 「详情」),展开后才显示鉴权/注入/范围/健康检查/最近错误与单条操作;上方有搜索、状态筛选、多选与全选、批量健康检查/启用/停用/重连/两段式批量移除 |
|
| 我的连接 | 读取连接(名称/传输/鉴权/启用/状态/注入方式/范围/健康时间/最近错误)、健康检查、工具缓存、启停、重连、两段式移除 |
|
||||||
| ~~MCP 市场~~ | **0.9.6 已删除**:宿主的 `catalog` 方法在当前 dsh-mcp-connector 上返回 `HTTP 405`,内嵌面板只能显示错误条。目录浏览与安装回到宿主自己的插件市场,本卡不再渲染该区块 |
|
| MCP 市场 | `catalog` 目录浏览与搜索;无认证直接 `connect`;OAuth 走浏览器授权 `connect`;bearer / api-key 通过 `configure` 填凭据(只写宿主,不回显) |
|
||||||
| 新增 / 导入 | 自定义 Streamable HTTP 与 stdio 连接(显示实际启动命令,云端不执行)、`importJson` 批量导入 |
|
| 新增 / 导入 | 自定义 Streamable HTTP 与 stdio 连接(显示实际启动命令,云端不执行)、`importJson` 批量导入 |
|
||||||
| 配置编辑 | `editableConnectionConfig` 读取(敏感值以 `<KEEP_EXISTING>` 保留标记返回),`reconfigureConnection` 保存;空输入不清除已有密钥 |
|
| 配置编辑 | `editableConnectionConfig` 读取(敏感值以 `<KEEP_EXISTING>` 保留标记返回),`reconfigureConnection` 保存;空输入不清除已有密钥 |
|
||||||
| 范围 | `previewConnectionScope` → `applyConnectionScope`,带 `expectedRevision`,`mode=move`,凭据不复制 |
|
| 范围 | `previewConnectionScope` → `applyConnectionScope`,带 `expectedRevision`,`mode=move`,凭据不复制 |
|
||||||
|
|
@ -237,7 +236,7 @@ refreshCatalog, toolsList, toolSearch, toolExplorer, toolDetail`
|
||||||
| `skills/install/plan` `install/commit` | `sync_running` |
|
| `skills/install/plan` `install/commit` | `sync_running` |
|
||||||
| `skills/toggle` `skills/remove` | `sync_running` |
|
| `skills/toggle` `skills/remove` | `sync_running` |
|
||||||
| `skills/update/apply` `skills/rollback` | `sync_running` |
|
| `skills/update/apply` `skills/rollback` | `sync_running` |
|
||||||
| `sync/resolve` `sync/resolve-all` | `sync_running` |
|
| `sync/resolve` | `sync_running` |
|
||||||
|
|
||||||
HTTP 层统一映射为 **409 `sync_running`**。`verify-concurrency.mjs`:8 项通过(六个入口 + 路由 409 + 同步结束后放行)。
|
HTTP 层统一映射为 **409 `sync_running`**。`verify-concurrency.mjs`:8 项通过(六个入口 + 路由 409 + 同步结束后放行)。
|
||||||
|
|
||||||
|
|
@ -282,9 +281,9 @@ HTTP 层统一映射为 **409 `sync_running`**。`verify-concurrency.mjs`:8
|
||||||
|
|
||||||
### 9.4 dsh-brain 数据迁移(RENAME-01 数据半区)
|
### 9.4 dsh-brain 数据迁移(RENAME-01 数据半区)
|
||||||
|
|
||||||
- `GET /dsh-brain/migrate/brain` 报告旧文件与目标文件状态、`packageRename: done`(0.8.0 起包改名已完成;旧 `/cloud-memory/*` 路由保留为别名)。
|
- `GET /cloud-memory/migrate/brain` 报告旧文件与目标文件状态、`packageRename: pending-deploy`。
|
||||||
- `POST /dsh-brain/migrate/brain` 把 `cloud-memory.json / -skills.json / -skill-groups.json / -workspaces.json / .cloud-memory-plans.json` 复制为 `dsh-brain*` 对应名,**保留旧文件、不覆盖已存在目标、幂等**;各加载路径首次使用时也会自动做同样的复制迁移。
|
- `POST /cloud-memory/migrate/brain` 把 `cloud-memory.json / -skills.json / -skill-groups.json` 复制为 `dsh-brain*.json`,**保留旧文件、不覆盖已存在目标、幂等**。
|
||||||
- 实际包名、客户端模块 id 与 profile 加载入口的切换已在 **0.8.0 统一版**完成(部署步骤,切换后需完全重启 DSH)。
|
- 实际包名、客户端模块 id 与 profile 加载入口的切换是**部署步骤**,需要完全重启 DSH;不在运行中的会话里静默改名,避免同时注册或丢配置。
|
||||||
|
|
||||||
### 9.5 验证
|
### 9.5 验证
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -1,117 +0,0 @@
|
||||||
# 验收单 · 部门接线 D1+D2(给 GPT 审查会话)
|
|
||||||
|
|
||||||
日期:2026-11-24
|
|
||||||
仓库:C:\Users\qyh15\dsh-brain(分支 main)
|
|
||||||
角色:你是独立验收者。实施者是 DeepSeek(另一会话),你只检查、不修改代码。
|
|
||||||
依据:DEPARTMENT_HANDOFF.md(交接单)、DEPARTMENT_TASKS.md(任务卡)、DEPARTMENT_PLAN.md(边界)。
|
|
||||||
前提:DeepSeek 已报告完成。若未报告完成,只做预检并如实标注"未完成验收"。
|
|
||||||
|
|
||||||
## 0. 验收纪律
|
|
||||||
|
|
||||||
- 一切结论以你亲自跑出的命令输出和读到的代码为准;实施者的自述只是线索。
|
|
||||||
- 每项给 PASS / FAIL / SKIP(附证据:命令输出片段或 文件:行号)。
|
|
||||||
- 发现问题只记录,不顺手修;FAIL 项汇总后交回用户裁决。
|
|
||||||
- 不 push、不打 tag、不改任何源码;允许写临时脚本到系统 temp 目录。
|
|
||||||
|
|
||||||
## 1. 基线与范围核对(先做)
|
|
||||||
|
|
||||||
| # | 检查 | 方法 | 通过标准 |
|
|
||||||
| --- | --- | --- | --- |
|
|
||||||
| A1 | 起点基线 | git log --oneline v0.10.1..HEAD | 首个新增 commit 为 docs/plans 交接文档(规划侧),其后 5 个左右对应 D1a/D1b/D2a/D2b/V |
|
|
||||||
| A2 | 库层零改动 | git diff v0.10.1..HEAD -- src/local-memory/departments/ | **输出必须为空**;非空即 FAIL(硬约束) |
|
|
||||||
| A3 | 范围不越界 | git diff --stat v0.10.1..HEAD | 改动应限于:src/kernel.ts、src/routes.ts、src/settings-ui/(新路由文件)、src/memory/departments-tools.ts(新)、src/entries/memory.ts、lib/ 对应产物、verify-departments-wiring.mjs(新)、package.json 若有 scripts 增补。出现 cloud-sync/src/local-memory 其他子目录改动 → 逐条质询 |
|
|
||||||
| A4 | 无新依赖 | git diff v0.10.1..HEAD -- package.json pnpm-lock.yaml | dependencies/devDependencies 无新增;lockfile 不应大变 |
|
|
||||||
| A5 | 工作树状态 | git status --porcelain | 干净(全部已提交);脏则记录未提交内容 |
|
|
||||||
|
|
||||||
## 2. 门禁命令(亲自重跑,不采信报告)
|
|
||||||
|
|
||||||
npm run typecheck
|
|
||||||
npm run build
|
|
||||||
node verify-departments.mjs # 原库层 21 项必须仍全绿(实测口径)
|
|
||||||
node scripts/verify-all.mjs # 口径:38 过 + 2 环境跳过 + 新增 wiring 全绿;exit 0
|
|
||||||
node verify-plugin-entry.mjs # 入口形状不变
|
|
||||||
|
|
||||||
| # | 通过标准 |
|
|
||||||
| --- | --- |
|
|
||||||
| B1 | typecheck exit 0 |
|
|
||||||
| B2 | build exit 0,且 build 后 git status 仍干净(lib 产物已随卡提交,重建无 diff)|
|
|
||||||
| B3 | verify-departments 21 PASS 0 FAIL |
|
|
||||||
| B4 | verify-all exit 0;对比基线口径,原有脚本无一转 FAIL;wiring 脚本 0 SKIP |
|
|
||||||
| B5 | verify-plugin-entry 全绿 |
|
|
||||||
|
|
||||||
注意:verify-all 的 SKIP 判定是输出行 /^SKIP/;环境性跳过只允许出现在原有 2 个脚本。
|
|
||||||
|
|
||||||
## 3. 代码审查要点(读 diff,对照任务卡)
|
|
||||||
|
|
||||||
| # | 检查 | 位置 | 通过标准 |
|
|
||||||
| --- | --- | --- | --- |
|
|
||||||
| C1 | kernel 构造共享实例 | src/kernel.ts | DepartmentManager({ memory: this.localMemory }),同一实例;routeDeps() 暴露 departments |
|
|
||||||
| C2 | 路由归属与别名 | src/routes.ts | ROUTES.departments='/dsh-brain/departments';挂在 createCoreRoutes(settings-ui bundle);legacy 别名自动派生 |
|
|
||||||
| C3 | 写门禁 | 新路由 handler | 每个 POST 先 sameOrigin(req)(src/http.ts),跨源 403 origin-rejected;GET 不设写闸但 405 拒非 GET |
|
|
||||||
| C4 | 错误码映射 | 新路由 handler | 库层错误 message 精确映射:revision_conflict→409、department_not_found→404、department_disabled/secret_not_allowed/department_required_field/department_invalid_host→400 或 409(按任务卡表);未知错误 500 且不泄栈 |
|
|
||||||
| C5 | 开关语义 | 路由 + 工具 | localMemoryEnabled=false → 路由 503、工具抛中文禁用错误;departments 未构造 → 503 departments-unavailable |
|
|
||||||
| C6 | 工具手写定义 | src/memory/departments-tools.ts | 6 个工具名齐全(department_create/list/remember/recall/checkpoint/resume);无 import @deepseek-ai/dsh-tools;execute 抛错契约 |
|
|
||||||
| C7 | recall 预算(2026-11-24 修订) | 工具 + 路由 | k clamp 1..5 默认 5;**工具 content ≤600 含省略号**;路由允许全文但必须带 contentSnippet ≤600(共用同一 snippet 实现);hits 带 origin |
|
|
||||||
| C8 | workspace 绑定(2026-11-24 修订) | 工具 + 路由 | 不仅解析 deps.workspace(exec),还必须经 localMemory.withWorkspace 包裹**全部六个操作**(create/list/remember/recall/checkpoint/resume);双工作区探针:同名 project 部门各自 created=true、ID 不同、私有记忆互不可见 |
|
|
||||||
| C9 | entry 注册生命周期 | src/entries/memory.ts | 注册在 ctx.inject(['tools']) 内、经 toolsCtx.effect;随 memory bundle 卸载;未动 systemPrompt 段与自动总结监听器 |
|
|
||||||
| C10 | 私有空间不上云 | 全 diff | 无任何把 department 空间接入 cloud-sync/reporter 的改动 |
|
|
||||||
| C11 | resume/attach 语义 | 工具 + 路由 | 给 hostSessionId 走 attachSession,否则 resumeSession;返回 reusable 引用 |
|
|
||||||
| C12 | revision 透传 | update/disable/checkpoint | expectedRevision 可选参数原样传库层,不在接线层吞掉 |
|
|
||||||
|
|
||||||
## 4. 行为抽查(独立探针,不复用实施者的测试)
|
|
||||||
|
|
||||||
写一个临时探针脚本(系统 temp 目录,import 仓库 lib/),至少覆盖:
|
|
||||||
|
|
||||||
1. 闭环:create → remember → recall(query 命中, origin='department') → checkpoint → resume(reusable=true)。
|
|
||||||
2. 幂等:同名同 scope 二次 create 返回 created=false 且 id 不变。
|
|
||||||
3. 隔离:部门 A remember 的内容,部门 B recall 不命中(私有空间语义)。
|
|
||||||
4. 禁用:disable 后 remember 抛 department_disabled;数据文件仍在磁盘。
|
|
||||||
5. 秘密拒收:remember 含 API key 样式内容抛 secret_not_allowed。
|
|
||||||
6. HTTP:起真实 server 挂 createCoreRoutes(kernel.routeDeps())(手法参考 verify-brain-panel.mjs):
|
|
||||||
- GET /dsh-brain/departments/list → 200
|
|
||||||
- POST /dsh-brain/departments/create 带跨源 Origin → 403
|
|
||||||
- 同源 POST 缺 name → 400;正常 → 200
|
|
||||||
- expectedRevision 过期 → 409
|
|
||||||
- GET /cloud-memory/departments/list(legacy)→ 200
|
|
||||||
7. 上下文预算:recall k=99 实际返回 ≤5 条。
|
|
||||||
|
|
||||||
| # | 通过标准 |
|
|
||||||
| --- | --- |
|
|
||||||
| D1–D7 | 上述 7 组探针全部符合预期;任何一组失败即 FAIL 并附输出 |
|
|
||||||
|
|
||||||
## 5. 发布件一致性
|
|
||||||
|
|
||||||
npm pack --dry-run
|
|
||||||
|
|
||||||
| # | 通过标准 |
|
|
||||||
| --- | --- |
|
|
||||||
| E1 | files 清单仍只含 lib/client/cordis.patch.yml/README/LICENSE 系;verify-*.mjs、tests/、docs/plans 不进包 |
|
|
||||||
| E2 | 包内 lib/memory/departments-tools.js 存在(新工具随包发布)|
|
|
||||||
|
|
||||||
## 6. 裁决与回报格式
|
|
||||||
|
|
||||||
- 全 PASS → 结论"验收通过,D1+D2 最小可用闭环成立",建议用户打 tag(如 v0.10.2-dept.1,由用户定)。
|
|
||||||
- 有 FAIL → 逐条列出:编号 / 证据(输出或 文件:行号)/ 影响 / 建议修复方向(不实施)。
|
|
||||||
- 有偏离任务卡但合理的决定 → 单列"偏离清单",交用户追认。
|
|
||||||
- 回报末尾附:你亲自跑过的命令清单 + 各自 exit code。
|
|
||||||
|
|
||||||
## 7. 明确不在本次验收范围
|
|
||||||
|
|
||||||
D3 宿主会话挂钩、D4 设置页页签、云同步、部门协作编排——发现"没做"不算缺陷。
|
|
||||||
|
|
||||||
|
|
||||||
## 8. 复验口径(2026-11-24,FAIL 修复后)
|
|
||||||
|
|
||||||
- 首轮验收 FAIL:C7(片段 601/715 超预算)、C8(项目部门未按调用工作区隔离)、A5(skill-sync.ts 在途改动混树)。
|
|
||||||
- 修复单:docs/plans/DEPARTMENT_FIX.md(DeepSeek 执行,两 commit)。
|
|
||||||
- 复验范围:C7/C8 新断言 + A5 干净树 + verify-all 口径不回退;其余 PASS 项不重跑,除非修复 diff 触及。
|
|
||||||
- **复验基线(2026-11-24 23:25 规划侧预检)**:修复已入库并推送,HEAD `45f1ca9`。
|
|
||||||
三个修复 commit:`cae5c08`(skill-sync 冲突绑定确认快照,含 19 项 conflict-round5 全绿)、
|
|
||||||
`22b2497`(C8 工作区绑定)、`45f1ca9`(C7 省略号计入预算)。
|
|
||||||
规划侧亲跑:typecheck exit 0;verify-all 39 脚本全绿;wiring **25 项**全 PASS(原 18+新 7);
|
|
||||||
departments 21 项全 PASS;工作树干净。
|
|
||||||
实现要点供复核:工具面 inDepartmentWorkspace 助手包裹六操作;路由面 withWorkspace 9 处;
|
|
||||||
departmentSnippet 导出共享(slice(0,limit-1)+'…');路由 /recall 返回 content 全文 + contentSnippet 双字段。
|
|
||||||
GPT 复验请独立重跑 C7/C8 探针(双工作区隔离 + 600 预算),并抽查 cae5c08 是否满足
|
|
||||||
"提交前修复任务" P1 的 5 条验收用例(该线属技能同步,不在部门验收范围,但同批交付建议顺带核)。
|
|
||||||
- npm 不在 PATH 时用 bundled node + pnpm 等价命令,记 PASS(等价)而非 SKIP。
|
|
||||||
|
|
@ -1,86 +0,0 @@
|
||||||
# D1+D2 验收 FAIL 项修复单(给 DeepSeek)
|
|
||||||
|
|
||||||
日期:2026-11-24
|
|
||||||
依据:GPT 独立验收报告(基线 accc1c3)。规划侧已逐项对照源码复核,两个 FAIL 均属实。
|
|
||||||
基线注意(2026-11-24 21:55 溯源定案):工作树的 src/skill-sync.ts 未提交改动
|
|
||||||
**已查明是 DeepSeek 会话(8adf7c86)自己的在途工作**——第五/六轮修复任务与
|
|
||||||
"提交前修复任务"(P1 技能冲突按用户确认版本执行)期间,turn 9–14 共 23 次
|
|
||||||
run_code 直写该文件(08:38–12:22 UTC),最后一次 seq5642 在 12:22:54Z。
|
|
||||||
它不是旧项目残留,也不是 GPT 验收所改(GPT 全程只读+临时副本)。
|
|
||||||
**处置:该改动属于另一条任务线(技能冲突确认),与部门修复无关。
|
|
||||||
DeepSeek 修部门 FAIL 前,先把 skill-sync.ts 的在途改动按原任务收尾单独提交
|
|
||||||
(或经用户同意 stash),部门修复 commit 不得混入它。**
|
|
||||||
注意:该在途 diff 的方向与"提交前修复任务"要求相反(移除了 confirmed 快照守卫、
|
|
||||||
改用新鲜云端列表),收尾提交前须按原任务验收用例复核,不能直接当成品提交。
|
|
||||||
|
|
||||||
## FAIL-1(C8)· 项目部门未按调用工作区隔离【严重,先修】
|
|
||||||
|
|
||||||
现象:同一进程内,工作区 A、B 分别创建同名 project 部门,B 得到 created=false
|
|
||||||
和 A 的 ID——B 的部门建到了 A 的项目注册表里。
|
|
||||||
|
|
||||||
根因(已核实):
|
|
||||||
- DepartmentManager.root(scope) 读 this.memory.projectRoot(manager.ts:36 附近),
|
|
||||||
而 projectRoot 取 AsyncLocalStorage 的 workspaceContext,缺省回落 process.cwd()。
|
|
||||||
- LocalMemoryManager 已有现成绑定机制:withWorkspace(workspace, job)(manager.ts:94)。
|
|
||||||
- memory/tools.ts 的五个工具把 workspace 作为参数传给 remote(remote 内部绑定);
|
|
||||||
但 departments-tools.ts 只有 recall 传了 workspace 参数,create/list/remember/
|
|
||||||
checkpoint/resume 都没绑定,且 DepartmentManager 公开方法除 recall 外不收 workspace。
|
|
||||||
|
|
||||||
修法(库层零改动约束下,接线层绑定):
|
|
||||||
1. DepartmentToolDeps 增加 memory: () => LocalMemoryManager(kernel.departmentToolDeps()
|
|
||||||
补返回 this.localMemory)。
|
|
||||||
2. 六个工具的 execute 统一包一层:
|
|
||||||
const ws = deps.workspace(exec)
|
|
||||||
return deps.memory().withWorkspace(ws, async () => { …原逻辑… })
|
|
||||||
recall 保留现有 workspace 参数传递(双保险,库层 recall 自己也会用)。
|
|
||||||
3. HTTP 路由侧:departments-routes.ts 的每个分支同样用
|
|
||||||
deps.localMemory.withWorkspace(workspace, …) 包裹;workspace 来源:
|
|
||||||
- 工具面:exec 上下文(已有)。
|
|
||||||
- HTTP 面:query/body 的 workspace 参数(recall 已支持,扩展到 create/list/
|
|
||||||
remember/checkpoint/resume/update/disable);缺省时回落 process.cwd() 语义不变。
|
|
||||||
RouteDeps 已含 localMemory,无需新增依赖面。
|
|
||||||
4. 不改 src/local-memory/departments/ 任何字节(A2 红线)。
|
|
||||||
|
|
||||||
验证(新增断言进 verify-departments-wiring.mjs):
|
|
||||||
- 同进程双工作区:withWorkspace(A) create 'X' → withWorkspace(B) create 'X'
|
|
||||||
必须 created=true 且 ID 不同;B recall 不见 A 的私有记忆。
|
|
||||||
- 工具面模拟 exec={workspace:B} 调 department_create,注册表落 B 的
|
|
||||||
.dsh/brain/departments/registry.json(mkdtemp 双项目夹具)。
|
|
||||||
- 原 18 项 wiring + 21 项库层保持全绿。
|
|
||||||
|
|
||||||
commit:fix(departments): bind caller workspace around every department operation
|
|
||||||
|
|
||||||
## FAIL-2(C7)· 召回片段超 600 字符预算【轻,后修】
|
|
||||||
|
|
||||||
现象:工具 snippet 截 600 后追加 '…' 实长 601;HTTP /recall 直接返回完整
|
|
||||||
record.content(实测 715)。
|
|
||||||
|
|
||||||
裁定(规划侧统一口径,消除任务卡与验收单的矛盾):
|
|
||||||
- **agent 工具面**:snippet 总长 ≤600 **含省略号**——改 slice(0, limit-1) + '…'。
|
|
||||||
- **HTTP 管理路由**:/recall 是同源管理页消费,允许全文(任务卡 D1b 原口径),
|
|
||||||
但为防误用也加投影:默认返回 content 全文 + contentSnippet(≤600 含省略号)双字段;
|
|
||||||
验收断言改为"snippet 字段 ≤600"。若 GPT 复验坚持路由也限 600,则路由直接复用
|
|
||||||
同一 snippet 函数返回短片段——两种都合规,实施者选前者(管理页需要全文编辑)。
|
|
||||||
- 共用一个 snippet 实现:从 departments-tools.ts 导出或挪到共享 util,
|
|
||||||
路由 import 同一函数,杜绝两处漂移。
|
|
||||||
|
|
||||||
验证:wiring 脚本加断言——构造 700 字符记忆,工具返回 content.length ≤600;
|
|
||||||
路由返回 contentSnippet.length ≤600。
|
|
||||||
|
|
||||||
commit:fix(departments): count ellipsis inside the 600-char recall budget
|
|
||||||
|
|
||||||
## 执行顺序与门禁
|
|
||||||
|
|
||||||
1. 先处置 skill-sync.ts 在途改动(问用户),保证干净起点。
|
|
||||||
2. FAIL-1 → FAIL-2 各一 commit,每 commit 前跑:
|
|
||||||
typecheck + build + verify-departments(21) + verify-departments-wiring(18+新断言)。
|
|
||||||
3. 终验:verify-all 全绿(39+ 脚本口径不回退)。
|
|
||||||
4. 完成后 push,通知用户转 GPT 复验(复验范围:C7/C8 + 新断言 + A5 干净树;
|
|
||||||
其余 PASS 项不重跑,除非 diff 触及)。
|
|
||||||
|
|
||||||
## 给 GPT 复验的口径更新
|
|
||||||
|
|
||||||
- C7 通过标准修订:工具 content ≤600 含省略号;路由 contentSnippet ≤600(全文字段允许)。
|
|
||||||
- C8 通过标准:双工作区 create 各自 created=true、ID 不同、私有记忆互不可见;
|
|
||||||
工具与 HTTP 两面都要探。
|
|
||||||
- A5:交付提交必须干净树;skill-sync 改动若属另一任务,单独 commit 不混入。
|
|
||||||
|
|
@ -1,52 +0,0 @@
|
||||||
# 执行交接单 · 部门接线 D1+D2(给 DeepSeek 实施会话)
|
|
||||||
|
|
||||||
日期:2026-11-24
|
|
||||||
仓库:C:\Users\qyh15\dsh-brain(分支 main,基线 tag v0.10.1 / commit 1dfc7c7)
|
|
||||||
角色:你是实施者。本单 + DEPARTMENT_TASKS.md 是你的全部任务来源;规划会话不参与实施。
|
|
||||||
|
|
||||||
## 任务一句话
|
|
||||||
|
|
||||||
把已验收的部门库层(src/local-memory/departments/,21 项验证全绿)接上用户面:
|
|
||||||
kernel 构造 + 管理路由(D1)+ 6 个 department_* agent 工具(D2),并新增 wiring 验收。
|
|
||||||
完成标志:V 卡终验命令全绿。预计一天内。
|
|
||||||
|
|
||||||
## 开工前核对(5 分钟)
|
|
||||||
|
|
||||||
1. git status 干净、git log -1 为 docs/plans 交接文档 commit 或其后继(基线 v0.10.1 + 规划文档);若工作树脏,停下报告,不要混提交。
|
|
||||||
注:node 不在系统 PATH 时用宿主自带 node.exe(DeepSeek Harness resources/runtime/.../node/bin/node.exe),npm 同理。
|
|
||||||
2. 读 docs/plans/DEPARTMENT_TASKS.md 全文——每卡的改动文件、签名、错误码、验证命令都在里面。
|
|
||||||
3. 背景按需查:DEPARTMENT_PLAN.md(概念与边界)、NEXT_PHASE_PLAN.md §4.5(阶段位置)。
|
|
||||||
4. node verify-departments.mjs 先跑一遍确认 21 项全绿(你的起点基线;原稿误记 26,已修订)。
|
|
||||||
|
|
||||||
## 执行顺序
|
|
||||||
|
|
||||||
D1a(kernel 构造)→ ┬ D1b(管理路由)┐
|
|
||||||
└ D2a(工具工厂)→ D2b(entry 注册)┴→ V(wiring 验收)
|
|
||||||
|
|
||||||
D1b 与 D2a 可并行。每卡独立 commit,commit 主题按任务卡给定文案。
|
|
||||||
|
|
||||||
## 硬约束(违反即返工)
|
|
||||||
|
|
||||||
- src/local-memory/departments/ 库层零改动;只消费其公开 API。
|
|
||||||
- 不引新依赖;工具手写 ToolDefinition(禁 import @deepseek-ai/dsh-tools,原因见 memory/tools.ts 头注释)。
|
|
||||||
- 不动 cloud-sync;部门私有空间不上云。
|
|
||||||
- 不做 D3(宿主会话挂钩)、D4(设置页页签)——超出本轮范围。
|
|
||||||
- recall k 上限 5 硬 clamp;POST 路由必须过 sameOrigin 闸门。
|
|
||||||
- lib/ 构建产物随卡提交(仓库约定 lib 入库);每卡 commit 前跑该卡验证命令。
|
|
||||||
|
|
||||||
## 终验(全部通过才报完成)
|
|
||||||
|
|
||||||
npm run typecheck && npm run build
|
|
||||||
node scripts/verify-all.mjs # 原 38 过 + 2 环境跳过口径不变,新增 wiring 全绿
|
|
||||||
node verify-plugin-entry.mjs
|
|
||||||
|
|
||||||
## 验收
|
|
||||||
|
|
||||||
完成后由独立 GPT 审查会话按 docs/plans/DEPARTMENT_ACCEPTANCE.md 验收(A/B/C/D/E 五组检查)。
|
|
||||||
实施者不得自验代替独立验收。
|
|
||||||
|
|
||||||
## 交付物
|
|
||||||
|
|
||||||
1. 5 个 commit(D1a/D1b/D2a/D2b/V),push 与否听用户指示。
|
|
||||||
2. 回报格式:每卡 commit hash + 验证结果摘要;如有偏离任务卡的决定,逐条列出原因。
|
|
||||||
3. 遇到任务卡与代码现状不符(基线漂移):停下,报告差异,等规划侧修订,不要自行改方案。
|
|
||||||
|
|
@ -1,70 +0,0 @@
|
||||||
# 部门(Departments)规划
|
|
||||||
|
|
||||||
版本:v1(规划稿,本会话只做规划,不实施)
|
|
||||||
日期:2026-11-24
|
|
||||||
来源:主会话 11-24 16:05–17:04 的讨论定论 + 已验收的库层实现。
|
|
||||||
|
|
||||||
## 1. 概念定稿(用户确认)
|
|
||||||
|
|
||||||
- **部门 = 专家**,同一概念的两种叫法,统一用"部门"。
|
|
||||||
- 部门是一个**可复用的长期工作身份**:每次使用沉淀一点记忆,
|
|
||||||
久了靠压缩上下文延续——不是另起一套 Agent 运行时。
|
|
||||||
- 记忆三层:部门私有记忆 + 项目记忆 + 全局记忆,按需注入,
|
|
||||||
不全量塞上下文。
|
|
||||||
- billion-context 继续做**独立工具**,不内置进记忆系统
|
|
||||||
(16:35 用户拍板:"听你的 bc 继续用做独立的")。
|
|
||||||
|
|
||||||
## 2. 选型结论(search-first,11-24 17:04 核对)
|
|
||||||
|
|
||||||
| 候选 | 结论 |
|
|
||||||
| --- | --- |
|
|
||||||
| DSH 原生(子 Agent / 任务会话 / reuseSession) | **会话执行与恢复直接复用**,不重造 |
|
|
||||||
| Letta(Apache-2.0) | 最接近部门概念;借鉴"身份 + 私有记忆 + 会话引用"数据模型;运行时太重,不接入 |
|
|
||||||
| LangGraph(MIT) | 借鉴"短期 thread + 长期 namespace"边界:恢复会话 ≠ 注入全部记忆 |
|
|
||||||
| Mastra | thread+resource 类似,但无必要引入;许可证未核清,不入选 |
|
|
||||||
|
|
||||||
**Verdict:会话执行复用 DSH;数据模型借鉴 Letta/LangGraph;
|
|
||||||
部门注册、私有空间与记忆策略基于现有 LocalMemoryManager 薄实现,
|
|
||||||
不 Fork 新框架。**
|
|
||||||
|
|
||||||
## 3. 已完成(库层,另一会话实施并验收)
|
|
||||||
|
|
||||||
src/local-memory/departments/(types/registry/manager/index),
|
|
||||||
verify-departments.mjs 21 项全绿(2026-11-24 实测复核,原稿误记 26):
|
|
||||||
|
|
||||||
- 幂等创建(scope+名称,重名不覆盖);全局/项目两种归属
|
|
||||||
- role / skills / allowedTools / readGlobal / readProject 策略
|
|
||||||
- 私有 memory-space(departments/<id>/memory-space),跨部门不可见,
|
|
||||||
精确去重,写入自动打 departmentId
|
|
||||||
- recall:私有优先 → 项目 → 全局,总量限 k(默认 5),跨源去重
|
|
||||||
- resumeSession 返回同一可移植引用;attachSession 显式绑宿主会话
|
|
||||||
- checkpoint(currentTask/handoff);revision 冲突拒绝过期写
|
|
||||||
- disable 保留数据不复活;秘密拒收;文件锁 + 原子写
|
|
||||||
|
|
||||||
## 4. 缺口与接线规划(P1.5,详见 NEXT_PHASE_PLAN.md §4.5)
|
|
||||||
|
|
||||||
D1/D2 已拆为可执行任务卡:docs/plans/DEPARTMENT_TASKS.md(D1a/D1b/D2a/D2b/V,含改动文件、签名、错误码、验证命令)。
|
|
||||||
|
|
||||||
库层只有 ./local-memory 导出,未接用户面:
|
|
||||||
|
|
||||||
- D1 kernel 构造 DepartmentManager + settings-ui 管理路由
|
|
||||||
(/dsh-brain/departments,同源写门禁)
|
|
||||||
- D2 memory 子插件注册 department_* 工具
|
|
||||||
(create/list/remember/recall/checkpoint/resume)
|
|
||||||
- D3 宿主会话挂钩:启动 resume+attach,回合结束可选 checkpoint;
|
|
||||||
失败不阻塞对话
|
|
||||||
- D4 设置页部门页签(只走公开 API)
|
|
||||||
|
|
||||||
## 5. 边界与约束
|
|
||||||
|
|
||||||
- 部门私有空间云同步**默认不上传**,纳入 cloud-sync M4 范围确认。
|
|
||||||
- 部门不是权限隔离的替代品:项目空间隔离语义不变。
|
|
||||||
- 上下文预算:recall 总量受限;部门身份注入走精简投影,
|
|
||||||
不整段注入 role 全文(role 上限 12000 字符仅存储用)。
|
|
||||||
- 本阶段不做:部门间协作编排、部门层级树、自动部门推荐。
|
|
||||||
|
|
||||||
## 6. 验收
|
|
||||||
|
|
||||||
- verify-departments.mjs 21 项保持全绿
|
|
||||||
- 新增 verify-departments-wiring.mjs:工具注册 / 路由鉴权 /
|
|
||||||
开关行为 / 会话恢复 / 禁用后工具拒绝
|
|
||||||
|
|
@ -1,79 +0,0 @@
|
||||||
# 复验单 · 部门接线 D1+D2 FAIL 修复(给 GPT)
|
|
||||||
|
|
||||||
日期:2026-11-24
|
|
||||||
仓库:C:\Users\qyh15\dsh-brain(main,已推送)
|
|
||||||
角色:独立复验者。只检查、不修改源码、不 commit/push/tag。
|
|
||||||
前情:首轮验收(基线 accc1c3)FAIL 三项:C7 片段超预算、C8 项目部门未按工作区隔离、A5 混树。
|
|
||||||
DeepSeek 已修复,规划侧预检全绿。本次是**复验**,不是全量重验。
|
|
||||||
|
|
||||||
## 0. 基线与范围
|
|
||||||
|
|
||||||
- 复验基线:`45f1ca9`(fix(departments): count ellipsis inside the 600-char recall budget)。
|
|
||||||
- 三个修复 commit(v0.10.1 之后、本轮审查对象):
|
|
||||||
| commit | 内容 |
|
|
||||||
| --- | --- |
|
|
||||||
| cae5c08 | fix(skill-sync): bind conflict resolution to the confirmed preview snapshot |
|
|
||||||
| 22b2497 | fix(departments): bind caller workspace around every department operation |
|
|
||||||
| 45f1ca9 | fix(departments): count ellipsis inside the 600-char recall budget |
|
|
||||||
- 注意:HEAD 可能已前进(UI 规划文档 commit 89e67d0/5fef328/9fe5e49 等,纯 docs/plans)。
|
|
||||||
审查 diff 用 `git diff accc1c3..45f1ca9`;若 HEAD 更新,确认新增仅 docs/plans 或 UI 施工
|
|
||||||
(src-client/ 等),UI 施工不在本次复验范围。
|
|
||||||
- 环境:npm/node 不在 PATH 时用 bundled node + pnpm 等价命令,记 PASS(等价):
|
|
||||||
node: C:/Users/qyh15/.dsh/dsh-runtimes/dsh-primary-runtime/dependencies/node/bin/node.exe
|
|
||||||
或 C:/Users/qyh15/AppData/Local/Programs/DeepSeek Harness/resources/runtime/primary-runtime/dependencies/node/bin/node.exe
|
|
||||||
pnpm: C:/Users/qyh15/.dsh/dsh-runtimes/dsh-primary-runtime/dependencies/pnpm/bin/pnpm.mjs
|
|
||||||
|
|
||||||
## 1. 门禁(亲自重跑)
|
|
||||||
|
|
||||||
git status --porcelain # A5:必须干净(UI 施工在途则记录并区分归属)
|
|
||||||
pnpm run typecheck # B1
|
|
||||||
pnpm run build # B2:build 后 git status 仍干净(lib 已入库)
|
|
||||||
node verify-departments.mjs # B3:21 项全 PASS
|
|
||||||
node scripts/verify-all.mjs # B4:39 脚本全绿(1 环境跳过),exit 0
|
|
||||||
node verify-departments-wiring.mjs # 25 项全 PASS(原 18 + 新 7),0 SKIP
|
|
||||||
node verify-skill-sync-conflict-round5.mjs # cae5c08 配套:19 项全 PASS
|
|
||||||
|
|
||||||
## 2. C8 复验(工作区隔离)——独立探针,不复用实施者测试
|
|
||||||
|
|
||||||
写临时探针(系统 temp,import 仓库 lib/),至少断言:
|
|
||||||
1. 同一进程、两个 mkdtemp 工作区 A/B:
|
|
||||||
withWorkspace(A) 内 create({name:'X',scope:'project'}) → created=true, idA;
|
|
||||||
withWorkspace(B) 内同名 create → **created=true, idB ≠ idA**(首轮 FAIL 点:B 曾拿到 A 的 id)。
|
|
||||||
2. A 内 remember 私有内容,B 内 recall 同 query → 0 命中。
|
|
||||||
3. 工具面:createDepartmentTools(deps) 的 department_create.execute(args, {workspace:B})
|
|
||||||
→ 注册表落 B 的 .dsh/brain/departments/registry.json(检查磁盘路径)。
|
|
||||||
4. HTTP 面:起真实 server 挂 createCoreRoutes(kernel.routeDeps()),
|
|
||||||
POST /departments/create?workspace=A 与 body workspace=B 分别建同名部门 → 两个 id。
|
|
||||||
5. 六操作全覆盖抽查:list/remember/recall/checkpoint/resume 在 withWorkspace(B) 下
|
|
||||||
不读不写 A 的目录(recall 已有 workspace 参数,其余靠包裹)。
|
|
||||||
代码核对点:src/memory/departments-tools.ts 的 inDepartmentWorkspace 助手是否包裹全部六个
|
|
||||||
execute;src/settings-ui/departments-routes.ts 各分支 withWorkspace(9 处);
|
|
||||||
kernel.departmentToolDeps() 是否暴露 memory 访问器。库层 src/local-memory/departments/ 必须零改动
|
|
||||||
(git diff accc1c3..45f1ca9 -- src/local-memory/departments/ 为空)。
|
|
||||||
|
|
||||||
## 3. C7 复验(600 字符预算)
|
|
||||||
|
|
||||||
1. 构造 700 字符记忆 → department_recall 工具返回 content.length **≤600**(省略号计入)。
|
|
||||||
2. HTTP GET /departments/recall → hits[].contentSnippet.length ≤600;content 全文字段允许存在
|
|
||||||
(管理页消费,裁定口径见 DEPARTMENT_ACCEPTANCE.md §8)。
|
|
||||||
3. departmentSnippet 为共享导出(departments-tools.ts export,路由 import 同一函数),
|
|
||||||
实现 slice(0, limit-1)+'…'。
|
|
||||||
4. k=99 仍 clamp 到 5(回归确认)。
|
|
||||||
|
|
||||||
## 4. cae5c08 顺带核(技能冲突线,非部门验收范围)
|
|
||||||
|
|
||||||
对照"提交前修复任务"P1 的 5 条验收用例(verify-skill-sync-conflict-round5.mjs 已扩到 19 项):
|
|
||||||
1. 有效确认 keep_local/take_cloud 跑通,断言实际远端调用/磁盘/回执;
|
|
||||||
2. 确认后远端变化 → 条件写入拒绝,expected_revision 仍是预览值;
|
|
||||||
3. 下载包完整但 revision/manifest 不同 → 过期,本地不动;
|
|
||||||
4. 确认后本地变化 → 不上传不覆盖;
|
|
||||||
5. 批量混合有效+过期 → 只有有效条目写入。
|
|
||||||
读 diff 确认 previews Map 快照机制方向正确(绑定用户确认的预览,而非新鲜列表)。
|
|
||||||
此项结论单列,不影响部门复验裁决。
|
|
||||||
|
|
||||||
## 5. 裁决与回报
|
|
||||||
|
|
||||||
- 全 PASS → "复验通过,D1+D2 最小可用闭环成立",建议用户打 tag(如 v0.10.2-dept.1,用户定)。
|
|
||||||
- 有 FAIL → 编号/证据(输出或 文件:行号)/影响/修复方向(不实施)。
|
|
||||||
- 回报末尾附亲自跑过的命令清单 + exit code。
|
|
||||||
- 首轮已 PASS 的 A1–A4/B5/C1–C6/C9–C12/D1–D7/E1–E2 不重跑,除非修复 diff 触及对应文件。
|
|
||||||
|
|
@ -1,188 +0,0 @@
|
||||||
# P1.5 · 部门接线 D1/D2 可执行任务卡
|
|
||||||
|
|
||||||
版本:v1(规划稿;实施会话照卡执行,本会话只维护规划)
|
|
||||||
日期:2026-11-24
|
|
||||||
基线:v0.10.1(commit 1dfc7c7)+ docs/plans 交接文档 commit(见 HANDOFF 开工核对)。上游方案:DEPARTMENT_PLAN.md、NEXT_PHASE_PLAN.md §4.5。
|
|
||||||
所有行号/签名以 2026-11-24 对 src/ 的实测为准;执行前若基线变动先重新核对。
|
|
||||||
|
|
||||||
## 总览
|
|
||||||
|
|
||||||
| 卡 | 内容 | 依赖 | 预估 |
|
|
||||||
| --- | --- | --- | --- |
|
|
||||||
| D1a | kernel 构造 DepartmentManager + routeDeps 暴露 | 无 | 0.5h |
|
|
||||||
| D1b | /dsh-brain/departments 管理路由(settings-ui bundle) | D1a | 2–3h |
|
|
||||||
| D2a | department_* 工具工厂(6 个工具) | D1a | 2–3h |
|
|
||||||
| D2b | memory entry 注册工具 + 开关语义 | D2a | 0.5h |
|
|
||||||
| V | verify-departments-wiring.mjs 新增验收 | D1b+D2b | 1–2h |
|
|
||||||
|
|
||||||
D1a→D1b 与 D1a→D2a 两条链可并行。每卡独立 commit;全部完成后跑 V 卡终验。
|
|
||||||
D3(宿主会话挂钩)、D4(设置页页签)不在本轮,见 DEPARTMENT_PLAN §4。
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## D1a · kernel 构造 DepartmentManager
|
|
||||||
|
|
||||||
改动文件:src/kernel.ts(现 324 行)
|
|
||||||
|
|
||||||
1. import 增加 DepartmentManager:现有行
|
|
||||||
`import { LocalMemoryManager, LocalMemoryRemote } from './local-memory/index.ts'`
|
|
||||||
改为同时导入 DepartmentManager(index.ts 已导出,无需动 local-memory)。
|
|
||||||
2. BrainKernel 类字段区(readonly localMemoryRemote 之后)加:
|
|
||||||
`readonly departments: DepartmentManager`
|
|
||||||
3. constructor 中 `this.localMemoryRemote = new LocalMemoryRemote(this.localMemory)`
|
|
||||||
之后加:`this.departments = new DepartmentManager({ memory: this.localMemory })`
|
|
||||||
——共享同一 LocalMemoryManager 实例(库层约定,见 verify-departments.mjs 用法)。
|
|
||||||
不做 ensureGlobal 之类的额外初始化:部门私有空间由 create 时懒建。
|
|
||||||
4. routeDeps() 返回对象(现有 localMemory: this.localMemory 之后)加:
|
|
||||||
`departments: this.departments,`
|
|
||||||
5. src/routes.ts 的 RouteDeps 接口加可选字段:
|
|
||||||
`/** Department registry (P1.5), when wired in. */ departments?: DepartmentManager`
|
|
||||||
(import type 自 ./local-memory/index.ts)。
|
|
||||||
|
|
||||||
开关语义:DepartmentManager 构造无副作用,常建即可;
|
|
||||||
localMemoryEnabled=false 的拒绝发生在路由/工具层(D1b/D2a),不在构造层。
|
|
||||||
|
|
||||||
验证:npm run typecheck && npm run build;node verify-departments.mjs 保持 21 项全绿。
|
|
||||||
commit:feat(departments): construct DepartmentManager in the shared kernel
|
|
||||||
|
|
||||||
## D1b · /dsh-brain/departments 管理路由
|
|
||||||
|
|
||||||
改动文件:src/routes.ts(ROUTES 表 + createCoreRoutes)、
|
|
||||||
新文件 src/settings-ui/departments-routes.ts(或并入 routes.ts 的 serveDepartments,二选一,建议独立文件对齐 settings-ui/routes.ts 风格)。
|
|
||||||
|
|
||||||
路由归属:settings-ui bundle(createCoreRoutes 已被 settings-ui entry 注册,
|
|
||||||
legacy /cloud-memory 别名自动跟随,无需另接)。
|
|
||||||
|
|
||||||
1. ROUTES 表加 `departments: '/dsh-brain/departments'`。
|
|
||||||
2. createCoreRoutes 数组加一项:
|
|
||||||
`{ kind: 'prefix', path: ROUTES.departments, handler: (req,res) => serveDepartments(deps, req, res) }`
|
|
||||||
3. serveDepartments 完全仿照 serveLocalMemory 的既有模式:
|
|
||||||
- deps.departments === undefined → 503 'departments-unavailable'
|
|
||||||
- suffix 解析用 marker '/departments'(同 serveLocalMemory 的 markerAt 写法)
|
|
||||||
- 子路由与方法:
|
|
||||||
|
|
||||||
| suffix | 方法 | 行为 | 错误码 |
|
|
||||||
| --- | --- | --- | --- |
|
|
||||||
| '' 或 '/' 或 '/list' | GET | list(scope?),scope 取 query(global/project) | 405 |
|
|
||||||
| '/create' | POST | create(input);name 必填 trim 非空 | 400 name-required / 403 origin-rejected |
|
|
||||||
| '/update' | POST | update(id, patch, expectedRevision?) | 400 id-required / 409 revision-conflict(库层抛错映射) |
|
|
||||||
| '/disable' | POST | disable(id, expectedRevision?) | 同上 |
|
|
||||||
| '/checkpoint' | POST | checkpoint(id, {currentTask?, handoff?}, expectedRevision?) | 同上 |
|
|
||||||
| '/recall' | GET | recall(id, query, k?, workspace?);k clamp 1..5(默认 5) | 400 id-required |
|
|
||||||
| '/resume' | POST | resumeSession(id, host?);attach 语义(hostSessionId)同 POST 传入 | 400 id-required |
|
|
||||||
|
|
||||||
- 所有 POST:sameOrigin(req) 闸门(复用 src/http.ts 现有函数)→ readBody → JSON.parse
|
|
||||||
→ 对象校验,失败 400 invalid-json / invalid-body(照抄 serveLocalMemory '/forget' 段)。
|
|
||||||
- localMemoryEnabled=false 时统一 503 'local-memory-disabled'(读 settings 判定,
|
|
||||||
与工具层口径一致)。
|
|
||||||
- 库层错误消息(如 revision 冲突、department-not-found、disabled)用 try/catch 映射:
|
|
||||||
已知 message → 409/404/400;未知 → 500,不泄内部栈。
|
|
||||||
4. 响应投影:Department 对象直接 JSON 化即可(role 上限 12000 字符仅存储用,
|
|
||||||
管理路由是同源页面消费,允许全文;agent 工具侧才做精简投影,见 D2a)。
|
|
||||||
|
|
||||||
验证:typecheck + build;手工 curl 或 V 卡脚本覆盖:GET list 200、POST create 同源 200/
|
|
||||||
跨源 403、缺 name 400、revision 过期 409、禁用后 503。
|
|
||||||
commit:feat(departments): management routes under the settings-ui bundle
|
|
||||||
|
|
||||||
## D2a · department_* 工具工厂
|
|
||||||
|
|
||||||
新文件:src/memory/departments-tools.ts(对齐 memory/tools.ts 的手写 ToolDefinition 风格,
|
|
||||||
不用 defineTool——该文件头注释已说明双模块实例风险,遵守)。
|
|
||||||
|
|
||||||
导出:`export function createDepartmentTools(deps: DepartmentToolDeps): ToolDefinitionLike[]`
|
|
||||||
|
|
||||||
DepartmentToolDeps 接口(kernel.toolDeps() 扩展或独立工厂均可,建议独立):
|
|
||||||
```ts
|
|
||||||
interface DepartmentToolDeps {
|
|
||||||
departments: () => DepartmentManager
|
|
||||||
settings: () => { localMemoryEnabled: boolean; memoryEnabled: boolean }
|
|
||||||
workspace: (exec?: unknown) => string | undefined
|
|
||||||
}
|
|
||||||
```
|
|
||||||
kernel.ts 加 departmentToolDeps() 方法返回上述形状(departments: () => this.departments)。
|
|
||||||
|
|
||||||
六个工具(名字即 agent 面 API,描述必须声明私有空间语义):
|
|
||||||
|
|
||||||
| 工具 | 参数(JSON Schema) | 行为 |
|
|
||||||
| --- | --- | --- |
|
|
||||||
| department_create | name*, role?, scope?(global/project), skills?[], allowedTools?[], readGlobal?, readProject? | create;返回 {id,name,scope,created};重名幂等不覆盖 |
|
|
||||||
| department_list | scope? | list;返回精简视图 {id,name,scope,active,currentTask?,revision}(不含 role 全文) |
|
|
||||||
| department_remember | departmentId*, content*, category?, tags?[] | remember;返回 {id,duplicate};秘密拒收错误原样透传 |
|
|
||||||
| department_recall | departmentId*, query*, k?(1..5 默认 5) | recall(id,query,k,workspace(exec));返回 hits[{origin,content snippet≤600,id}](复用 memory/tools.ts 的 snippet 手法) |
|
|
||||||
| department_checkpoint | departmentId*, currentTask?, handoff?, expectedRevision? | checkpoint;返回 {revision,updatedAt} |
|
|
||||||
| department_resume | departmentId*, host?, hostSessionId? | resumeSession 或 attachSession(给了 hostSessionId 走 attach);返回 sessionRef |
|
|
||||||
|
|
||||||
共同契约(照抄 memory/tools.ts 既有约定):
|
|
||||||
- execute 抛错 → 宿主转 isError:true;错误消息中文可行动(参照 requireMemoryToken 文案风格)。
|
|
||||||
- 前置检查:memoryEnabled=false 或 localMemoryEnabled=false → 抛
|
|
||||||
'部门功能当前已禁用…请在 /dsh-brain 页面开启';部门 active=false → 库层已拒绝,透传。
|
|
||||||
- 输出统一 renderJson(从 memory/tools.ts 导出复用,已是 export)。
|
|
||||||
- workspace 解析:execute(args, exec) 的 exec 经 deps.workspace(exec)(kernel 已有
|
|
||||||
workspaceFromExec,勿重造)。
|
|
||||||
- recall 的 k 上限 5 硬 clamp,防上下文膨胀(DEPARTMENT_PLAN §5 边界)。
|
|
||||||
|
|
||||||
验证:typecheck + build;V 卡覆盖工具行为。
|
|
||||||
commit:feat(departments): six department_* agent tools
|
|
||||||
|
|
||||||
## D2b · memory entry 注册
|
|
||||||
|
|
||||||
改动文件:src/entries/memory.ts(现 134 行)
|
|
||||||
|
|
||||||
在现有 createMemoryTools 注册循环之后(同一 ctx.inject(['tools']) 回调内)加:
|
|
||||||
```ts
|
|
||||||
for (const tool of createDepartmentTools(kernel.departmentToolDeps())) {
|
|
||||||
toolsCtx.effect(() => tools.register(tool), `dsh-brain-memory: tool \${tool.name}`)
|
|
||||||
}
|
|
||||||
```
|
|
||||||
(模板字符串反引号按正常 TS 写,此处为文档转义。)
|
|
||||||
|
|
||||||
要点:
|
|
||||||
- 工具随 memory bundle 开关整体注册/卸载——与五个 memory_* 工具同生命周期,
|
|
||||||
不新增 bundle、不动 inject 声明。
|
|
||||||
- systemPrompt 投影段(order 151)本轮不加部门内容(D3 范围)。
|
|
||||||
- 自动总结监听器不动。
|
|
||||||
|
|
||||||
验证:typecheck + build + node verify-plugin-entry.mjs(入口形状不变);
|
|
||||||
V 卡验证注册名单含 6 个 department_*。
|
|
||||||
commit:feat(departments): register department tools in the memory entry
|
|
||||||
|
|
||||||
## V · verify-departments-wiring.mjs
|
|
||||||
|
|
||||||
新文件:仓库根 verify-departments-wiring.mjs(P1 整理前的出生位置;
|
|
||||||
若执行时 REPO_CLEANUP_PLAN 已先行,则直接写 tests/verification/ 并改 ../../lib 引用)。
|
|
||||||
|
|
||||||
harness 风格照抄 verify-departments.mjs:mkdtemp 假 DSH_HOME + project、
|
|
||||||
check/throws 计数、动态 import('./lib/...')、结尾汇总 exit code。
|
|
||||||
|
|
||||||
覆盖清单(对应 DEPARTMENT_PLAN §6 验收):
|
|
||||||
1. 工具注册:resetBrainKernel() 后 brainKernel(config,logger),
|
|
||||||
createDepartmentTools(kernel.departmentToolDeps()) 长度 6、名字齐全、
|
|
||||||
parameters 为合法 JSON Schema 对象。
|
|
||||||
2. 工具行为闭环:create→remember→recall(私有命中 origin='department')→
|
|
||||||
checkpoint→resume 返回 reusable 引用;k>5 被 clamp。
|
|
||||||
3. 开关行为:localMemoryEnabled=false 时 execute 抛禁用错误;
|
|
||||||
memoryEnabled=false 同理。
|
|
||||||
4. 禁用部门:disable 后 remember/recall 抛错(库层语义透传)。
|
|
||||||
5. 路由鉴权:起真实 http server 挂 createCoreRoutes(kernel.routeDeps())
|
|
||||||
(参考 verify-brain-panel.mjs 的起服务手法):
|
|
||||||
GET list 200;POST create 无 Origin 闸门票据 → 403;同源 → 200;
|
|
||||||
缺 name → 400;expectedRevision 过期 → 409;未构造 departments → 503。
|
|
||||||
6. legacy 别名:/cloud-memory/departments/list 同样可达。
|
|
||||||
7. 环境性跳过口径:无真实宿主依赖,本脚本应 0 SKIP。
|
|
||||||
|
|
||||||
终验命令(全部通过才算 P1.5 D1+D2 完成):
|
|
||||||
```
|
|
||||||
npm run typecheck && npm run build
|
|
||||||
node scripts/verify-all.mjs # 原 38 过 + 2 环境跳过不变,新增 wiring 全绿
|
|
||||||
node verify-plugin-entry.mjs # 入口形状
|
|
||||||
```
|
|
||||||
commit:test(departments): wiring verification for tools and routes
|
|
||||||
|
|
||||||
## 边界提醒(执行者必读)
|
|
||||||
|
|
||||||
- 不改 src/local-memory/departments/ 库层任何字节——21 项验收是既成事实,
|
|
||||||
接线只消费其公开 API。
|
|
||||||
- 不动 cloud-sync:部门私有空间默认不上云(M4 再议)。
|
|
||||||
- 不引新依赖;手写 ToolDefinition,不 import @deepseek-ai/dsh-tools。
|
|
||||||
- lib/ 产物由 npm run build 生成后随卡提交(仓库约定 lib 入库)。
|
|
||||||
- 每卡 commit 前跑该卡验证命令;V 卡终验后才向用户报"最小可用闭环完成"。
|
|
||||||
|
|
@ -1,405 +0,0 @@
|
||||||
# DSH Brain 本地记忆与 Mnemon Fork 改造方案
|
|
||||||
|
|
||||||
版本:讨论定稿
|
|
||||||
日期:2026-11-24
|
|
||||||
范围:第一阶段只实现本地记忆;云端同步当前关闭,只保留接口和 Provider 源码拆解成果。
|
|
||||||
|
|
||||||
## 1. 已确认的需求
|
|
||||||
|
|
||||||
1. 独立 Fork Mnemon,作为记忆内核;dsh-brain 的 memory 模块只做连接和适配。
|
|
||||||
2. 本地优先:断网、无账号、无云端配置时,全部本地记忆功能可用。
|
|
||||||
3. 同时使用全局记忆空间和项目记忆空间,两者都自动创建。
|
|
||||||
4. 不再创建 .mnemon 目录。
|
|
||||||
5. 全局数据放用户目录的 .dsh/brain,项目数据放项目目录的 .dsh/brain。
|
|
||||||
6. 自动总结记忆、自动生成和更新用户画像。
|
|
||||||
7. 自动分流、去重、按需检索,控制每轮 token 消耗。
|
|
||||||
8. 云同步与本地功能彻底解耦,当前默认关闭;稳定后可对新安装默认开启,但不得覆盖用户手动关闭的配置。
|
|
||||||
9. 本阶段不移除 Skill、Source、Provider、Strategy 或其他现有功能。
|
|
||||||
10. 拆解外部 Provider 源码,为后续云端同步复用,不把它们误当成同步本身。
|
|
||||||
|
|
||||||
## 2. 总体结构
|
|
||||||
|
|
||||||
dsh-brain
|
|
||||||
├── memory:连接 Fork 后的 Mnemon,提供本地记忆能力
|
|
||||||
├── skill-management:保留 Skill 管理、自进化、市场与评测
|
|
||||||
├── mcp-management:保留 MCP 管理
|
|
||||||
├── cloud-sync:后续负责同步、冲突和外部 Agent 接入
|
|
||||||
└── settings-ui:统一设置页面,只调用公开 API
|
|
||||||
|
|
||||||
Fork 后的 Mnemon 继续保留:
|
|
||||||
├── Runtime
|
|
||||||
├── Documents
|
|
||||||
├── Memory Spaces
|
|
||||||
├── Skills Source
|
|
||||||
├── Mnemon Native 与全部外部 Provider
|
|
||||||
├── 默认三层策略及其他策略
|
|
||||||
├── 自动捕获、蒸馏与空闲总结
|
|
||||||
└── Pack 备份、Git 同步与公开管理 API
|
|
||||||
|
|
||||||
本阶段不调整上述功能的归属,不停止注册,不删除依赖,不物理删除源码。
|
|
||||||
|
|
||||||
## 3. 许可证与 Fork 约束
|
|
||||||
|
|
||||||
上游仓库:omdsh-dev/dsh-mnemon。
|
|
||||||
已核对 dsh-mnemon@0.5.44 与上游仓库均为 MIT。
|
|
||||||
|
|
||||||
允许复制、修改、合并、发布、再许可和商用。必须保留完整 MIT 许可证与原版权声明:
|
|
||||||
|
|
||||||
Copyright (c) 2026 dsh-external contributors
|
|
||||||
|
|
||||||
Fork 应使用新的包名、插件标识和显示名称,避免与原版同时注册相同的工具、路由和服务。保留 upstream 远程仓库,以便合并后续安全修复。
|
|
||||||
|
|
||||||
## 4. 四层记忆与两类长期空间
|
|
||||||
|
|
||||||
| 层级 | 内容 | 默认读取方式 |
|
|
||||||
|---|---|---|
|
|
||||||
| USER.md | 用户身份、长期偏好 | 每轮提供精简投影 |
|
|
||||||
| MEMORY.md | 跨会话协作规则 | 每轮提供精简投影 |
|
|
||||||
| Documents | 项目总结、决策、实施记录、未解决问题 | 相关时检索,按需读全文 |
|
|
||||||
| Memory Spaces | 长期事实、知识、经验、实体和关系 | 按需搜索,只返回相关条目 |
|
|
||||||
|
|
||||||
长期空间分为:
|
|
||||||
|
|
||||||
- 全局记忆空间:保存跨项目通用的长期知识,所有项目可搜索。
|
|
||||||
- 项目记忆空间:保存当前项目特有的长期事实,默认只服务当前项目。
|
|
||||||
|
|
||||||
项目记忆也可以保留项目 ID、来源和标签,但项目空间不能仅靠标签代替权限隔离。
|
|
||||||
|
|
||||||
## 5. 本地目录定稿
|
|
||||||
|
|
||||||
全局根目录:
|
|
||||||
|
|
||||||
C:\Users\qyh15\.dsh\brain\
|
|
||||||
├─ runtime\
|
|
||||||
│ ├─ memories.json
|
|
||||||
│ ├─ USER.md
|
|
||||||
│ └─ MEMORY.md
|
|
||||||
├─ spaces\
|
|
||||||
│ └─ global\
|
|
||||||
├─ backups\
|
|
||||||
└─ state\
|
|
||||||
|
|
||||||
项目根目录:
|
|
||||||
|
|
||||||
<项目目录>\.dsh\brain\
|
|
||||||
├─ documents\
|
|
||||||
├─ memory-space\
|
|
||||||
└─ state\
|
|
||||||
|
|
||||||
要求:
|
|
||||||
|
|
||||||
- 项目首次使用记忆时才自动创建项目内目录。
|
|
||||||
- 不在项目源码中生成 .mnemon。
|
|
||||||
- 全局 Runtime 使用 JSON 作为真实记录,USER.md 与 MEMORY.md 是生成的紧凑投影。
|
|
||||||
- 长期记忆沿用 Mnemon Native 的实际存储结构;如使用 SQLite,不上传数据库文件给云端拆解。
|
|
||||||
- 项目的 .dsh/brain 必须默认不被 Git 提交,但不要因此忽略整个 .dsh。
|
|
||||||
- 若发现旧 .mnemon 数据,不静默移动或删除;提供明确的迁移、验证和回滚入口。
|
|
||||||
- 修改 Runtime、Documents、Native、Pack、锁、临时文件和项目映射的全部默认路径,不能只修改界面显示。
|
|
||||||
|
|
||||||
## 6. 自动初始化与自动创建空间
|
|
||||||
|
|
||||||
### 6.1 全局空间
|
|
||||||
|
|
||||||
首次启动自动完成:
|
|
||||||
|
|
||||||
1. 准备本地 Native 运行组件和存储目录。
|
|
||||||
2. 创建固定内部 ID 的全局空间。
|
|
||||||
3. 激活空间并设为全局长期记忆的默认读写位置。
|
|
||||||
4. 保存初始化完成状态。
|
|
||||||
|
|
||||||
### 6.2 项目空间
|
|
||||||
|
|
||||||
第一次在某项目中使用记忆时自动完成:
|
|
||||||
|
|
||||||
1. 创建项目内 .dsh/brain。
|
|
||||||
2. 初始化项目 Documents。
|
|
||||||
3. 创建并激活当前项目空间。
|
|
||||||
4. 建立稳定的项目 ID 与路径映射。
|
|
||||||
|
|
||||||
### 6.3 一致性与用户控制
|
|
||||||
|
|
||||||
- 重启后复用已有空间,不重复创建。
|
|
||||||
- 多窗口同时初始化同一空间也必须保持幂等。
|
|
||||||
- 用户主动删除或停用后不得自动复活。
|
|
||||||
- 自动创建空间、自动总结、自动画像分别提供独立开关。
|
|
||||||
- 初始化失败时明确报告,不静默切换云端 Provider。
|
|
||||||
- Runtime 和 Documents 应尽量保持可用,长期空间故障不能拖垮全部本地功能。
|
|
||||||
|
|
||||||
## 7. 自动总结与内容分流
|
|
||||||
|
|
||||||
自动总结只提炼值得长期保存的信息,不保存聊天全文。
|
|
||||||
|
|
||||||
分流规则:
|
|
||||||
|
|
||||||
- 用户明确表达的长期偏好 → USER.md。
|
|
||||||
- 跨会话协作规则 → MEMORY.md。
|
|
||||||
- 项目总结、实施记录、未解决问题 → 当前项目 Documents。
|
|
||||||
- 项目特有的长期事实 → 当前项目空间。
|
|
||||||
- 跨项目通用的知识和经验 → 全局空间。
|
|
||||||
- 无法确定是否通用的内容 → 先放当前项目空间,避免污染全局记忆。
|
|
||||||
|
|
||||||
执行要求:
|
|
||||||
|
|
||||||
- 使用增量检查点,不每次重读和总结全部历史。
|
|
||||||
- 保留来源会话、来源记录和修订信息。
|
|
||||||
- 不覆盖原始项目档案,总结与原文分开保存。
|
|
||||||
- 相同内容重复出现时去重。
|
|
||||||
- 总结失败不阻塞对话、本地读写或手工记忆。
|
|
||||||
- 不保存密码、API Key、Token、恢复码等秘密。
|
|
||||||
- 默认不保存原始聊天全文。
|
|
||||||
- 如调用模型,沿用现有模型配置,不新增另一套密钥;设置中说明模型处理的内容范围。
|
|
||||||
|
|
||||||
## 8. 自动生成用户画像
|
|
||||||
|
|
||||||
画像只保存用户明确表达且适合长期保留的信息:
|
|
||||||
|
|
||||||
- 身份、角色和专业背景。
|
|
||||||
- 常用语言。
|
|
||||||
- 回答长度、详细程度和表达风格偏好。
|
|
||||||
- 明确要求长期遵守的协作规则。
|
|
||||||
|
|
||||||
约束:
|
|
||||||
|
|
||||||
- 行为推测只能进入待确认区,不能直接写成事实。
|
|
||||||
- 一次性要求不能升级为永久偏好。
|
|
||||||
- 不能根据助手回答、网页或工具输出推断用户画像。
|
|
||||||
- 用户纠正后更新旧条目,不保留互相冲突的有效版本。
|
|
||||||
- 每条画像保留来源、更新时间和修订号。
|
|
||||||
- 用户可查看、修改、删除和关闭自动画像。
|
|
||||||
- 画像默认只保存在本地,未来云同步也需单独确认范围。
|
|
||||||
|
|
||||||
## 9. 搜索与 token 控制
|
|
||||||
|
|
||||||
- 第一阶段以现有关键词、Native 召回和本地检索能力为基础,不强制引入新的向量数据库。
|
|
||||||
- 默认只搜索当前项目空间和全局空间,不扫描所有历史项目。
|
|
||||||
- 默认返回约 5 条相关结果,可配置上限。
|
|
||||||
- 列表优先返回摘要、ID、分类、标签、来源和修订信息。
|
|
||||||
- 完整正文按需读取。
|
|
||||||
- 全局共享不等于每轮全量注入。
|
|
||||||
- Runtime 保持小而稳定;Documents 与 Memory Spaces 按需检索。
|
|
||||||
|
|
||||||
## 10. 本地数据可靠性
|
|
||||||
|
|
||||||
每条长期记忆至少需要:
|
|
||||||
|
|
||||||
- 唯一 ID。
|
|
||||||
- 所属空间。
|
|
||||||
- 内容和分类。
|
|
||||||
- 来源。
|
|
||||||
- 创建时间和更新时间。
|
|
||||||
- revision,初始为 1,每次修改或删除递增。
|
|
||||||
- 删除标记或等效 tombstone。
|
|
||||||
- 本地变化编号,为未来同步准备;它不是云端 change_id。
|
|
||||||
|
|
||||||
写入要求:
|
|
||||||
|
|
||||||
- 记忆内容与本地变化记录在同一事务中保存。
|
|
||||||
- 完全相同的重复写入不产生多条有效记忆。
|
|
||||||
- 重复命中返回已有记录并明确标记去重。
|
|
||||||
- 修改冲突依据 revision 检测,不仅依赖设备时间。
|
|
||||||
- 保留锁、原子写入、路径限制、超时、输出上限和凭据脱敏。
|
|
||||||
|
|
||||||
## 11. Provider 源码拆解:共同协议
|
|
||||||
|
|
||||||
源码位置:
|
|
||||||
|
|
||||||
plugins/dsh-mnemon-source-memory-spaces/src/provider-sdk.ts
|
|
||||||
plugins/dsh-mnemon-source-memory-spaces/src/contracts.ts
|
|
||||||
plugins/dsh-mnemon-source-memory-spaces/src/providers/http.ts
|
|
||||||
plugins/dsh-mnemon-source-memory-spaces/src/providers/process.ts
|
|
||||||
|
|
||||||
公共协议可复用为后续云端适配层:
|
|
||||||
|
|
||||||
- discover:发现远端或本地已有空间。
|
|
||||||
- status:健康状态、统计和能力检查。
|
|
||||||
- search:按 smart、keyword、basic 等模式检索。
|
|
||||||
- list/browse:浏览和读取记忆。
|
|
||||||
- remember:写入记忆。
|
|
||||||
- forget:删除记忆。
|
|
||||||
- graph、related、entities、link:可选关系能力。
|
|
||||||
- connection:端点、用户、Agent、项目、容器等连接字段。
|
|
||||||
- secret 字段、已配置状态、清除秘密和响应脱敏。
|
|
||||||
- AbortSignal、超时、取消和输出限制。
|
|
||||||
|
|
||||||
共同 Insight 当前包含 id、content、category、importance、tags、entities、source、score、createdAt、externalUri 等字段。
|
|
||||||
|
|
||||||
重要缺口:公共协议没有统一的 revision、云端 change_id、同步游标、幂等操作号和冲突回执。后续 cloud-sync 必须扩展这些语义,不能直接假设所有第三方 Provider 已支持增量同步。
|
|
||||||
|
|
||||||
## 12. 各 Provider 源码与能力
|
|
||||||
|
|
||||||
| Provider | 类型与核心能力 | 写入/删除 | 对云端同步的参考价值 |
|
|
||||||
|---|---|---|---|
|
|
||||||
| Mnemon Native | 本地精确写入、搜索、浏览、图谱、实体、关系、手动链接 | exact;soft delete | 本地主存储、删除记录、关系与本地变化基础 |
|
|
||||||
| OpenViking | 文件系统式共享记忆;语义检索;关键词 grep;空间和用户发现 | exact;hard delete | 写后读校验、内容回执、URI 映射、空间发现 |
|
|
||||||
| Honcho | 用户建模、用户/Agent peer、持久结论 | exact;hard delete | 多 Agent 身份、用户与 Agent 分权、结论查询 |
|
|
||||||
| Mem0 | 自动事实提取、语义搜索、重排、去重;平台或自托管 | async-extracting;hard delete | 异步写入状态、提取结果与本地原文的一致性 |
|
|
||||||
| Hindsight | 知识图谱、实体解析、多策略召回、反思 | async-extracting;soft delete;operation_id | 异步操作号、图谱关系、软删除与状态统计 |
|
|
||||||
| Holographic | 本地结构化事实、信任分、实体解析、组合检索 | exact;hard delete | 本地事实去重、信任过滤、图谱与关系查询 |
|
|
||||||
| RetainDB | 向量与 BM25 混合检索、用户画像、类型化事实 | exact;hard delete | 用户画像、混合检索、项目与用户维度 |
|
|
||||||
| ByteRover | 通过 brv CLI 的本地层次知识树 | async-extracting;不支持 browse/forget | CLI 进程约束;不能作为完整云同步协议模板 |
|
|
||||||
| Supermemory | 语义记忆、持久画像、会话摄取、多容器召回 | async-extracting;soft delete | 容器隔离、画像、异步写入和软删除 |
|
|
||||||
|
|
||||||
注意:
|
|
||||||
|
|
||||||
- OpenViking 默认端点可以是本机地址,但协议属于远程共享记忆,不应仅凭地址判断部署位置。
|
|
||||||
- Holographic 与 ByteRover 是本地 Provider,不是云端同步方案。
|
|
||||||
- async-extracting 表示提交后还可能异步提炼,不能把 HTTP 成功误当成最终记忆已完全一致。
|
|
||||||
- hard delete 的 Provider 无法天然提供云端 tombstone,需要 cloud-sync 自己保存删除事件。
|
|
||||||
- 不支持 browse 或 forget 的 Provider 不能承担完整双向同步。
|
|
||||||
|
|
||||||
## 13. 云端同步如何复用这些源码
|
|
||||||
|
|
||||||
后续建议拆成三层,而不是把 Provider 驱动直接当作同步器:
|
|
||||||
|
|
||||||
1. 本地变化层:记录本地新增、修改、删除、revision、本地变化编号和待同步状态。
|
|
||||||
2. cloud-sync 编排层:推送变化、拉取云端 change_id、重试、幂等、冲突和删除事件。
|
|
||||||
3. Provider/传输适配层:复用连接配置、发现、状态、搜索、读写、图谱、超时、取消和脱敏能力。
|
|
||||||
|
|
||||||
云端可以建立自己的 Brain Cloud Provider,实现公共 Provider 协议;但真正的增量同步仍由 cloud-sync 负责。
|
|
||||||
|
|
||||||
云端同步的是记忆条目及变化,不是 SQLite 文件。其他 Agent 通过统一 MCP 或 HTTP 服务访问云端,不需要知道本地数据库格式。
|
|
||||||
|
|
||||||
## 14. 云同步开关与默认策略
|
|
||||||
|
|
||||||
当前阶段:
|
|
||||||
|
|
||||||
- 默认关闭。
|
|
||||||
- 不要求登录、令牌或云端地址。
|
|
||||||
- 不启动同步定时器,不发起云端记忆请求。
|
|
||||||
- 云端故障不影响本地功能。
|
|
||||||
- 记忆同步与 Skill 同步分别控制。
|
|
||||||
- 本地 memory 不直接依赖云端客户端。
|
|
||||||
|
|
||||||
未来稳定并验收后:
|
|
||||||
|
|
||||||
- 新安装可默认开启。
|
|
||||||
- 已手动关闭的用户保持关闭。
|
|
||||||
- 默认开启不等于静默上传;首次同步前必须确认空间、画像和项目档案的同步范围。
|
|
||||||
- 反复开关不得删除或复制本地数据。
|
|
||||||
|
|
||||||
## 15. 本阶段明确不做
|
|
||||||
|
|
||||||
- 不实际推送或拉取云端记忆。
|
|
||||||
- 不实现云端冲突合并。
|
|
||||||
- 不上传 SQLite 文件。
|
|
||||||
- 不用 Git 代替实时数据库同步。
|
|
||||||
- 不实现 WorkBuddy、Codex 的云端服务入口。
|
|
||||||
- 不移除、不迁移、不停止注册任何现有功能。
|
|
||||||
- 不为了精简而删除 Provider 协议、安全检查、revision 或文件锁。
|
|
||||||
|
|
||||||
## 16. 实施顺序
|
|
||||||
|
|
||||||
1. 建立独立 Fork,修改包名和插件标识,保留 MIT 与 upstream。
|
|
||||||
2. 保持全部现有功能和默认装配,先建立回归基线。
|
|
||||||
3. 将本地默认根目录迁移到约定的 .dsh/brain,提供旧目录迁移与回滚。
|
|
||||||
4. 实现 Native 自动就绪、全局空间和项目空间的幂等自动创建。
|
|
||||||
5. 实现本地数据模型、revision、变化记录、去重和删除标记。
|
|
||||||
6. 实现自动总结、内容分流、自动画像及独立开关。
|
|
||||||
7. 完善搜索、token 预算、管理 API、设置页和本地备份。
|
|
||||||
8. 完成断网、重启、并发、安全和兼容验收。
|
|
||||||
9. 云端阶段再基于 Provider 拆解成果实现 cloud-sync。
|
|
||||||
|
|
||||||
## 17. 第一阶段验收标准
|
|
||||||
|
|
||||||
1. 全新环境无需手工创建空间即可使用记忆。
|
|
||||||
2. 自动得到一个全局空间和当前项目空间。
|
|
||||||
3. 重启、多窗口和重复初始化不会重复创建空间。
|
|
||||||
4. 全局与项目目录均符合 .dsh/brain 约定,不生成 .mnemon。
|
|
||||||
5. 断网、无账号、无云端配置时本地功能完整可用。
|
|
||||||
6. 云同步关闭时云端适配器调用次数为零。
|
|
||||||
7. 自动总结可增量执行、去重并追溯来源。
|
|
||||||
8. 自动画像只保存明确偏好,用户纠正后旧版本失效。
|
|
||||||
9. 默认搜索只覆盖当前项目与全局空间,并限制返回数量。
|
|
||||||
10. 修改、删除、并发写入和重启不会丢失或复制记忆。
|
|
||||||
11. 项目的 .dsh/brain 不被 Git 默认提交。
|
|
||||||
12. 所有现有 Source、Provider、Strategy、Skill 和公开插件接口保持可用。
|
|
||||||
13. 配置页不直接访问 SQLite、CLI 或 Provider 私有实现。
|
|
||||||
14. 旧数据迁移可验证、可回滚,不静默删除旧文件。
|
|
||||||
|
|
||||||
## 18. 后续移除决定(已确认,当前不执行)
|
|
||||||
|
|
||||||
后续要做功能移除和精简,但不属于本地第一阶段。
|
|
||||||
|
|
||||||
执行前置条件:
|
|
||||||
|
|
||||||
- 本地记忆、自动空间、自动总结和用户画像已经稳定并通过验收。
|
|
||||||
- cloud-sync 所需的 Provider 公共协议、适配层和必要源码已经完成拆解与复用。
|
|
||||||
- 已用依赖分析确认待移除功能没有被公开导出、工具、路由、配置、页面或其他模块引用。
|
|
||||||
|
|
||||||
后续移除原则:
|
|
||||||
|
|
||||||
- Skill、Provider、Strategy、Git 同步等分别确定归属,不做不加区分的一次性删除。
|
|
||||||
- 云端同步仍需的能力先提取并验证,再移除默认内置或冗余实现。
|
|
||||||
- 每次移除都保留可回滚点,并运行完整回归测试。
|
|
||||||
- 在该阶段正式开始前,继续保留全部现有功能,不停止注册、不删除依赖、不物理删除源码。
|
|
||||||
|
|
||||||
## 19. 仓库整理与生成物归档
|
|
||||||
|
|
||||||
本节只记录整理方案,不代表已经删除或移动相关文件。清理必须在单独任务中执行,并先核对文件内容与 Git 状态。
|
|
||||||
|
|
||||||
### 19.1 目标目录约定
|
|
||||||
|
|
||||||
dsh-brain/
|
|
||||||
├─ docs/
|
|
||||||
│ └─ plans/ ← 设计、改造与实施方案
|
|
||||||
├─ tests/
|
|
||||||
│ └─ verification/ ← 后续统一收纳 verify-*.mjs
|
|
||||||
├─ artifacts/ ← 可重新生成的输出,默认不提交 Git
|
|
||||||
│ ├─ analysis/ ← 临时分析和工具导出
|
|
||||||
│ ├─ logs/ ← 验证与运行日志
|
|
||||||
│ └─ preview/ ← HTML、截图和预览输出
|
|
||||||
├─ src/ ← 源码
|
|
||||||
├─ client/ ← 浏览器端源码
|
|
||||||
└─ lib/ ← 入库的构建产物与发布入口
|
|
||||||
|
|
||||||
后续新增方案统一放 docs/plans,不得在仓库根目录新增 LOCAL_MEMORY_PLAN.md 一类散落文档。临时分析、日志和预览输出统一进入 artifacts 对应子目录,不得继续堆在根目录。
|
|
||||||
|
|
||||||
### 19.2 可优先清理的历史输出
|
|
||||||
|
|
||||||
在确认不需要保留历史分析过程后,可清理以下历史对话或工具调用记录:
|
|
||||||
|
|
||||||
- .code-graph-core-history.txt
|
|
||||||
- .dsh-analysis-archive.json
|
|
||||||
- .dsh-analysis-task.txt
|
|
||||||
- .review-context.txt
|
|
||||||
- .session-init.txt
|
|
||||||
- .tmp-b1.txt
|
|
||||||
- .tmp-b5.txt
|
|
||||||
- .tmp-codegraph-history.txt
|
|
||||||
- .tmp-mnemon-history.txt
|
|
||||||
- .tmp-review-history.txt
|
|
||||||
|
|
||||||
根目录的 .tmp-verify-*.log 属于旧验证日志,_preview 属于可重新生成的 HTML 和截图,可在核对后清理。清理这些输出不应改变源码、测试和发布行为。
|
|
||||||
|
|
||||||
.codegraph/cache 是可重建索引缓存;node_modules 是可重装依赖,但删除后当前项目不能立即构建和测试。默认暂时保留,不与普通垃圾文件一起清理。
|
|
||||||
|
|
||||||
### 19.3 必须保留的成果与运行目录
|
|
||||||
|
|
||||||
- docs/plans/LOCAL_MEMORY_PLAN.md:本方案,必须保留。
|
|
||||||
- verify-review-fixes.mjs:新增修复验证成果,不能当作临时垃圾删除。
|
|
||||||
- src/version.ts 与 lib/version.js:新增修复成果,不能因未被 Git 跟踪而删除。
|
|
||||||
- 其他 verify-*.mjs:保留;后续移入 tests/verification 时必须同步调整引用、包脚本和工作目录,再运行验证。
|
|
||||||
- .tmp-remote-skill-sync.ts:虽然名称带临时前缀,但包含源代码;比较差异并确认归并前必须保留。
|
|
||||||
- lib:项目入口和发布包直接使用,且 .gitignore 明确要求入库,禁止按普通编译缓存删除。
|
|
||||||
- client:浏览器端代码,必须保留。
|
|
||||||
|
|
||||||
### 19.4 整理执行门禁
|
|
||||||
|
|
||||||
1. 先列出待处理文件、来源和 Git 状态,再执行删除或移动。
|
|
||||||
2. 删除前区分历史输出、可重建缓存、源码、测试和未跟踪修复成果。
|
|
||||||
3. 移动测试脚本后更新 import 路径、package.json scripts、文档和 CI 调用。
|
|
||||||
4. 将 artifacts 加入适当的 Git 忽略规则;不要误忽略 src、client、lib 或正式文档。
|
|
||||||
5. 项目记忆数据仍按 .dsh/brain 约定存放,不得混入 artifacts,也不得默认提交 Git。
|
|
||||||
6. 整理完成后运行类型检查、构建、现有验证脚本和插件入口检查。
|
|
||||||
7. 根目录只保留项目标准配置、说明和必要入口,不遗留临时记录、旧日志或预览输出。
|
|
||||||
|
|
||||||
## 20. 实施交付物
|
|
||||||
|
|
||||||
- Fork 仓库与上游跟踪说明。
|
|
||||||
- MIT 和第三方声明确认。
|
|
||||||
- 本地目录与旧数据迁移说明。
|
|
||||||
- 自动初始化、自动总结、自动画像的配置和状态说明。
|
|
||||||
- 本地数据结构与 revision 约定。
|
|
||||||
- Provider 公共协议和云端同步缺口说明。
|
|
||||||
- 测试命令、真实结果和未覆盖范围。
|
|
||||||
- 后续 cloud-sync 所需接口清单。
|
|
||||||
|
|
@ -1,248 +0,0 @@
|
||||||
# 本机记忆分层与共享现状对照表
|
|
||||||
|
|
||||||
> 状态:0.10.3 现状盘点(2026-11-27)。
|
|
||||||
> 范围:只描述代码**当前实际行为**,不含方案、不含取舍建议。
|
|
||||||
> 用途:给「B3 本机记忆共享」的规格和验收标准提供事实底稿。
|
|
||||||
> 约定:文中 `$DSH_HOME` 指 DSH 的主目录,未设置环境变量时是 `~/.dsh`(`src/store.ts:67-72`);`<工作区>` 指会话的工作目录(见第 3 节)。文中标了 `文件:行` 的结论都可以在仓库里直接核对。
|
|
||||||
|
|
||||||
## 一句话结论
|
|
||||||
|
|
||||||
- 记忆分四层:**全局**(整台机器一份)、**项目**(跟着工作区目录走)、**工作区**(只是“选哪个项目”的路由键,本身不存记忆)、**部门**(每个部门一份私有空间,分全局/项目两种)。
|
|
||||||
- 同一份项目记忆,只在“工作区路径解析后完全相同”的会话之间共享;目录不同(包括父目录和子目录)就是两份互不相通的记忆。
|
|
||||||
- 原始记录(原话)是单独的一层:全局一个档案库,不按项目/工作区过滤。
|
|
||||||
|
|
||||||
## 一、四层总表
|
|
||||||
|
|
||||||
| 层 | 实际存放位置(默认) | 分区键 | 谁写 | 谁读 | 共享范围 |
|
|
||||||
| --- | --- | --- | --- | --- | --- |
|
|
||||||
| 全局记忆 | `$DSH_HOME/brain/runtime/` | 无,一台机器一份 | `memory_add` 且 `project_id=global`;自动摘要抽出的偏好/规则;profile 工具 | 所有会话的 `memory_*`;全局面板;系统提示;部门的全局共享读取 | 同一个 `$DSH_HOME` 下全部会话 |
|
|
||||||
| 项目记忆 | `<工作区>/.dsh/brain/memory-space/` | 工作区解析后的绝对路径 | `memory_add`(默认);自动摘要的会话文档 | 同一路径的会话;侧栏「项目记忆」;部门的项目共享读取 | 只有解析后路径相同的会话 |
|
|
||||||
| 工作区 | 不存记忆,只是一个路径参数 | 解析后的绝对路径 | 宿主会话、侧栏、HTTP 请求传入 | 决定项目记忆/文档/项目部门的根 | 路径相同才相同 |
|
|
||||||
| 部门私有空间 | 全局部门:`$DSH_HOME/brain/departments/<部门id>/memory-space/`;项目部门:`<工作区>/.dsh/brain/departments/<部门id>/memory-space/` | `scope` + 部门 id | `department_remember` / `department_checkpoint` / `department_update` | `department_recall`;部门面板/接口 | 全局部门全机可见;项目部门只在该工作区路径可见 |
|
|
||||||
|
|
||||||
## 二、每一层的具体情况
|
|
||||||
|
|
||||||
### 2.1 全局记忆
|
|
||||||
|
|
||||||
**位置与文件**
|
|
||||||
|
|
||||||
- 根目录:`$DSH_HOME/brain`。代码常量在 `src/local-memory/manager.ts:12`。
|
|
||||||
- 记录库:`brain/runtime/memories.json`(记录 + 幂等键 + 变更序号),空间元信息 `brain/runtime/space.json`,锁文件 `brain/runtime/.lock`(`src/local-memory/manager.ts:108`、`src/local-memory/storage.ts:60-70`)。
|
|
||||||
- 生成物:`brain/runtime/USER.md`、`brain/runtime/MEMORY.md`,由全局记录里的 `preference`/`identity`/`rule` 三类生成(`src/local-memory/manager.ts:317-338`)。
|
|
||||||
- 镜像:`brain/spaces/global/memories.json`,在重算投影时从 `runtime/memories.json` 复制一份;仓内没有读取方(`src/local-memory/manager.ts:321-324`)。
|
|
||||||
- 状态:`brain/state/projects.json`(项目 id → 项目根映射,**只写不读**)、`brain/state/sessions.json`(自动摘要的增量检查点)、`brain/state/projection.json`(投影失败时的脏标记)、`brain/state/init.json`(初始化标记)。
|
|
||||||
- 备份:`brain/backups/`,只备份**全局根**(`src/local-memory/manager.ts:391-401`)。因为原始记录默认也在 `brain/raw/` 下,所以全局备份会连原话档案一起复制;各项目的 `.dsh/brain` 不在备份范围内。
|
|
||||||
|
|
||||||
**写入路径**
|
|
||||||
|
|
||||||
- `memory_add` 带 `project_id=global` 时写全局(`src/memory/tools.ts:204-230`、`src/local-memory/remote.ts:31-36`)。
|
|
||||||
- 自动摘要从用户原话里筛出“记住/以后/偏好/规则”一类句子,写成 `preference` 或 `rule`,写入全局(`src/local-memory/manager.ts:340-361`)。助手原话不进入这条路径。
|
|
||||||
- `proposeProfile` / `correctProfile` 等 profile 操作写全局(`src/local-memory/manager.ts:382-389`)。
|
|
||||||
|
|
||||||
**读取路径**
|
|
||||||
|
|
||||||
- 所有会话的 `memory_search` / `memory_list` 默认都会合并全局记录(`src/local-memory/manager.ts:216-228`、`243-258`)。
|
|
||||||
- `memory_read` 先查全局,再查当前项目的项目记忆(`src/local-memory/manager.ts:211-215`)。
|
|
||||||
- 每轮系统提示读取 `runtime/USER.md` 和 `runtime/MEMORY.md`,每个文件最多注入 2000 字符(`src/local-memory/manager.ts:307-315`、`src/entries/memory.ts:41-52`)。
|
|
||||||
- 部门召回在 `readGlobal=true` 时读全局(`src/local-memory/departments/manager.ts:199-209`)。
|
|
||||||
|
|
||||||
**共享与边界**
|
|
||||||
|
|
||||||
- 不分项目:同一个 `$DSH_HOME` 下,任何工作区的会话看到的是同一份全局记忆。
|
|
||||||
- 全局记录不会跟着项目目录移动;换机器不会自动出现,除非手动备份/迁移。
|
|
||||||
- 全局的 `state/sessions.json` 以会话 id 为键,会话跨项目时检查点仍在同一个文件里。
|
|
||||||
|
|
||||||
### 2.2 项目记忆
|
|
||||||
|
|
||||||
**位置与文件**
|
|
||||||
|
|
||||||
- 根目录:`<工作区>/.dsh/brain`,其中 `<工作区>` 是会话目录或显式传入的路径。解析规则见 `src/local-memory/manager.ts:14-19`:
|
|
||||||
- `projectBaseOf(path)`:先 `resolve(path)`;如果路径本身以 `.dsh/brain` 结尾,就退回项目的上一级。
|
|
||||||
- `projectBrainRoot(path)` = `<projectBase>/.dsh/brain`。
|
|
||||||
- 不做“向上找项目根”的扫描:在子目录里开会话,子目录自己就是项目根。
|
|
||||||
- 记录库:`<工作区>/.dsh/brain/memory-space/memories.json`,元信息 `space.json`,锁 `.lock`(`src/local-memory/manager.ts:109`、`src/local-memory/storage.ts:60-70`)。
|
|
||||||
- 文档:`<工作区>/.dsh/brain/documents/index.json` + `files/<doc_id>.md`(`src/local-memory/manager.ts:167-172`、`src/local-memory/storage.ts:144-171`)。
|
|
||||||
- 项目 id:`project_` + `sha256(resolve(项目根))` 取前 16 位(`src/local-memory/manager.ts:20`)。身份按**路径字符串**算,没做 `realpath`、没做大小写归一。
|
|
||||||
- 首次使用时才创建;创建时会在 `<工作区>/.dsh/.gitignore` 里补一行 `brain/`,所以项目记忆默认不进 git(`src/local-memory/manager.ts:57-63`)。
|
|
||||||
- 每创建一个项目根,会把 `项目id → 根路径` 写进全局的 `state/projects.json`(`src/local-memory/manager.ts:174-179`),但仓内没有读取这个映射的代码。
|
|
||||||
|
|
||||||
**写入路径**
|
|
||||||
|
|
||||||
- `memory_add` 不带 `project_id`(或带的是普通项目 id)时写当前工作区的项目记忆;本地实现只区分“global / 当前项目”,传别的项目 id 不会写到那个项目(`src/local-memory/remote.ts:31-36`)。
|
|
||||||
- 自动摘要在每个项目下写一份“会话总结”文档:`<工作区>/.dsh/brain/documents/`,内容默认是“本次会话共 N 轮,已更新增量检查点”,不是原话(`src/local-memory/manager.ts:366-370`)。
|
|
||||||
|
|
||||||
**读取路径**
|
|
||||||
|
|
||||||
- 同一工作区路径的所有会话共享同一份项目记忆;`memory_search` / `memory_list` 默认把它和全局合并。
|
|
||||||
- 侧栏「项目记忆」用当前会话的目录作为工作区,读项目 scope(`src-client/sidebar/ProjectMemoryView.tsx:19-28,46-48`)。
|
|
||||||
- 部门召回在 `readProject=true` 时读当前工作区的项目记忆(`src/local-memory/departments/manager.ts:199-209`)。
|
|
||||||
|
|
||||||
**共享与边界**
|
|
||||||
|
|
||||||
- 只有“解析后路径完全相同”的会话共享。同一个项目开多个会话、多个窗口,共享;换一个目录(包括父目录/子目录)就是另一份。
|
|
||||||
- 项目目录移动、重命名、重新 clone:新路径是新的项目 id、空的记忆和文档;旧路径的数据留在原地,没有迁移逻辑。
|
|
||||||
- 同一物理目录用不同大小写或软链接路径访问时:文件通常会落到同一个 `.dsh/brain` 下,但 `projectId` 可能不同(id 只按路径字符串算)。这会影响按 `project_id` 过滤的结果。
|
|
||||||
- 项目记忆随项目目录存在;删掉目录,记忆和文档一起消失(除非另做备份,当前备份只覆盖全局根)。
|
|
||||||
|
|
||||||
### 2.3 工作区(路径路由键)
|
|
||||||
|
|
||||||
**它是什么**
|
|
||||||
|
|
||||||
- 在记忆代码里,工作区不是独立存储,而是一个“传给每一次操作”的路径参数。`LocalMemoryManager` 用 `AsyncLocalStorage` 把一次操作绑定到一个工作区,避免并发会话互相读串(`src/local-memory/manager.ts:85,98-105`)。
|
|
||||||
- 没有传工作区时,回落到进程当前目录 `process.cwd()`(`src/local-memory/manager.ts:100-103`)。
|
|
||||||
|
|
||||||
**从哪里来**
|
|
||||||
|
|
||||||
- 工具的调用上下文:`exec.workspace` / `exec.cwd` / `exec.projectPath` / `exec.session.cwd` 等(`src/kernel.ts:55-67`)。
|
|
||||||
- 会话事件:`session.cwd` / `session.workspace` / `session.header.*`(`src/entries/memory.ts:65-66`、`src/entries/raw.ts:27-29`)。
|
|
||||||
- HTTP:查询参数 `?workspace=` 或请求体里的 `workspace` 字段(`src/routes.ts:242-258`、`src/settings-ui/departments-routes.ts:51-65`)。
|
|
||||||
- 侧栏:前端向宿主问当前会话的 cwd(`/sidebar/api/session.cwd`),拿不到就显示提示、不猜目录(`src-client/sidebar/ProjectMemoryView.tsx:19-28`)。
|
|
||||||
- 面板:Brain 总面板的「记忆」「部门」页签固定用全局 scope;项目 scope 只出现在侧栏的「项目记忆」页签(`src-client/panel/BrainPanel.tsx:21-24`)。
|
|
||||||
|
|
||||||
**作用范围**
|
|
||||||
|
|
||||||
- 工作区路径决定三样东西的根:项目记忆、项目文档、项目部门。
|
|
||||||
- 同一个路径字符串 → 同一份项目层;不同路径 → 不同项目层。
|
|
||||||
- 传入 `<项目>/.dsh/brain` 会被还原成 `<项目>`;传入普通子目录不会向上找项目根。
|
|
||||||
- HTTP 接口里的 `workspace` 就是一条本机路径,不校验它是否在 DSH 的工作区清单里。
|
|
||||||
|
|
||||||
**容易混淆的“技能工作区”**
|
|
||||||
|
|
||||||
- 技能域确实有工作区实体:DSH 宿主维护的工作区清单 `$DSH_HOME/workspace-groups.folders.json`、本插件手动添加的 `$DSH_HOME/dsh-brain-workspaces.json`;工作区级技能目录是 `<工作区>/.dsh/skills`,停用技能放在 `$DSH_HOME/skills-workspace-disabled/<workspaceId>`(`src/clients.ts:76-80,87-96,173-188,218-249`)。
|
|
||||||
- 这套清单**只服务技能**;记忆代码不读它,记忆只管传进来的路径。
|
|
||||||
|
|
||||||
### 2.4 部门私有空间
|
|
||||||
|
|
||||||
**位置与文件**
|
|
||||||
|
|
||||||
- 全局部门(`scope=global`):
|
|
||||||
- 注册表:`$DSH_HOME/brain/departments/registry.json`
|
|
||||||
- 私有记忆:`$DSH_HOME/brain/departments/<部门id>/memory-space/memories.json`
|
|
||||||
- 项目部门(`scope=project`):
|
|
||||||
- 注册表:`<工作区>/.dsh/brain/departments/registry.json`
|
|
||||||
- 私有记忆:`<工作区>/.dsh/brain/departments/<部门id>/memory-space/memories.json`
|
|
||||||
- 路径规则在 `src/local-memory/departments/manager.ts:36-40`;注册表的读写和加锁在 `src/local-memory/departments/registry.ts:26-55`。
|
|
||||||
- 私有空间使用和全局/项目一样的 `JsonMemoryStore`,只是 scope 记为 `department`,删除是软删除(`src/local-memory/departments/manager.ts:38-46`、`src/local-memory/storage.ts:114-141`)。
|
|
||||||
|
|
||||||
**创建与归属**
|
|
||||||
|
|
||||||
- `department_create` 默认 `scope=project`;同一个 scope 下部门名大小写不敏感唯一,重名返回已有部门(`src/local-memory/departments/manager.ts:62-85`)。
|
|
||||||
- 按 id 查找时先查全局注册表,再查**当前工作区**的项目注册表(`src/local-memory/departments/manager.ts:48-52`)。项目部门换一个工作区路径就找不到。
|
|
||||||
- 部门记录里带 `projectId`(创建时按当时工作区算);项目部门召回时用它过滤项目记忆(`src/local-memory/departments/types.ts:21-38`、`src/local-memory/departments/manager.ts:207-208`)。
|
|
||||||
|
|
||||||
**写入与召回**
|
|
||||||
|
|
||||||
- `department_remember` 只写该部门的私有空间,不写全局/项目空间(`src/memory/departments-tools.ts:84-105`)。
|
|
||||||
- `department_recall` 的合并规则(`src/local-memory/departments/manager.ts:194-223`):
|
|
||||||
1. 先查部门私有空间;
|
|
||||||
2. 再按 `readGlobal` / `readProject` 开关读共享的全局/项目记忆;
|
|
||||||
3. 合并后按“分数 → 部门 > 项目 > 全局 → 更新时间”排序;
|
|
||||||
4. 按去掉首尾空白的正文去重;
|
|
||||||
5. 工具层最多返回 5 条(`src/memory/departments-tools.ts:107-130`),管理器层最多 50 条。
|
|
||||||
- 部门面板/接口只列当前 scope 的部门;项目 scope 必须带工作区,否则 400 `workspace-required`(`src/settings-ui/departments-routes.ts:51-65,71-76`)。
|
|
||||||
|
|
||||||
**共享与边界**
|
|
||||||
|
|
||||||
- 全局部门:所有项目/会话都能看到、都能召回(只要知道部门 id)。
|
|
||||||
- 项目部门:只在创建它的那个工作区路径下存在;换目录既列不出也召不回。
|
|
||||||
- 部门私有记忆**不进入** `memory_search` / `memory_list`,普通记忆检索看不到;只有 `department_recall` 能读。
|
|
||||||
- 部门私有空间不随项目复制/移动;项目部门跟着项目目录走,删目录即消失。
|
|
||||||
|
|
||||||
### 2.5 附:原始记录层(不在四层内,但属于记忆面)
|
|
||||||
|
|
||||||
- 默认目录:`$DSH_HOME/brain/raw`,可用 raw 行配置的 `rawDir` 覆盖(`src/raw-memory/settings.ts:40-52`)。
|
|
||||||
- 一个会话一个 JSONL 文件;单文件超过 20MB 轮转成 `.1.jsonl`;保留 90 天后按整文件清理(`src/raw-memory/store.ts:72-84,118-141,271-288`)。
|
|
||||||
- 记录里有 `workspace` 字段,但搜索、读取、会话列表都不按 workspace 过滤(`src/entries/raw.ts:98-110`、`src/raw-memory/store.ts:144-214`)。也就是说原话档案是**全局混合**的。
|
|
||||||
- 面板「原始记录」页签和 `memory_raw_*` 工具读的是同一个全局档案(`src/raw-memory/routes.ts:34-79`、`src/raw-memory/tools.ts:28-145`)。
|
|
||||||
- 原话与记忆的关系是“出处”和“摘要”的关系:`memory_search` 不搜索原始记录,需要原话时用 `memory_raw_search` / `memory_raw_read`。
|
|
||||||
|
|
||||||
## 三、一次读写实际怎么走
|
|
||||||
|
|
||||||
### 3.1 `memory_*` 工具
|
|
||||||
|
|
||||||
| 工具 | 读/写哪里 | 关键规则 |
|
|
||||||
| --- | --- | --- |
|
|
||||||
| `memory_search` | 当前工作区项目 + 全局,合并 | 不传 `project_id` 时两边都搜;`project_id=global` 只看全局;传具体项目 id 只匹配该 id 的项目记录(本地只有当前项目的记录) |
|
|
||||||
| `memory_read` | 先全局,后当前项目 | 全局找到就返回,不再看项目 |
|
|
||||||
| `memory_add` | `project_id=global` → 全局;其它/不传 → 当前项目 | 本地实现不会把记录写到“另一个项目”里 |
|
|
||||||
| `memory_list` | 默认合并;带 `scope` 时只看单层 | `scope=global` / `scope=project` 由接口参数决定 |
|
|
||||||
| `memory_projects` | 返回两项:`global` 和当前项目 id | 项目 id 按当前工作区算 |
|
|
||||||
| `memory_forget` | 不给 scope 时先找全局,再找当前项目;给 scope 时只操作该层 | 删除是软删除,记录保留 tombstone |
|
|
||||||
|
|
||||||
补充条件:只有 `cloudMemoryEnabled=true` **并且**配置了 memory token 时,`memory_*` 才改走云端适配器;否则走本地(`src/kernel.ts:304-310`)。云端模式下,本地四层不参与 `memory_*` 的读写;自动摘要、部门、面板仍走本地。
|
|
||||||
|
|
||||||
### 3.2 自动摘要与投影
|
|
||||||
|
|
||||||
- 每轮结束时,从用户原话里筛“长期有效”的句子,写全局记录(偏好/规则),然后重算 `USER.md` / `MEMORY.md`(`src/local-memory/manager.ts:340-381`)。
|
|
||||||
- 同一轮还会写一份项目文档到当前工作区的 `documents/`(`src/local-memory/manager.ts:366-370`)。
|
|
||||||
- 增量检查点写全局 `state/sessions.json`,按会话 id 记录已处理过的 turn(`src/local-memory/manager.ts:344-376`)。
|
|
||||||
- 投影只由**全局**记录生成,项目记录不参与;投影失败会留脏标记,下次 `ensureGlobal()` 重试(`src/local-memory/manager.ts:117-130,316-338`)。
|
|
||||||
|
|
||||||
### 3.3 面板与 HTTP
|
|
||||||
|
|
||||||
- Brain 总面板:概览(全局状态)、记忆(固定 `scope=global`)、原始记录(全局档案)、部门(固定 `scope=global`)。
|
|
||||||
- 侧栏「项目记忆」:用当前会话 cwd 作为 workspace,记忆和部门都是项目 scope;地址栏/标题显示这个目录。
|
|
||||||
- `/dsh-brain/local-memory/*`:`workspace` 是查询参数;项目 scope 必须带 workspace;`documents` 只支持项目;`backup` 只备份全局根;列表/搜索不带 scope 时合并全局+项目。
|
|
||||||
- `/dsh-brain/departments/*`:`scope` 可为 `global` / `project` / 不传;项目 scope 必须带 workspace。
|
|
||||||
|
|
||||||
## 四、跨目录/跨会话时的结果
|
|
||||||
|
|
||||||
| 情形 | 全局记忆 | 项目记忆 | 项目部门 | 说明 |
|
|
||||||
| --- | --- | --- | --- | --- |
|
|
||||||
| 同一工作区路径,开两个会话 | 同一份 | 同一份 | 同一份 | 正常共享 |
|
|
||||||
| 不同工作区路径(两个项目、两个 clone) | 同一份 | 各自一份 | 各自一份 | 项目层互不相通 |
|
|
||||||
| 在项目的子目录里开会话 | 同一份 | 子目录成为新项目,空记忆 | 新项目下空部门 | 不会向上读取父项目 |
|
|
||||||
| 传入 `<项目>/.dsh/brain` | 同一份 | 同一份 | 同一份 | 会还原成项目根 |
|
|
||||||
| 项目目录移动/重命名后打开 | 同一份 | 新路径为空,旧数据留在原目录 | 同上 | 没有迁移逻辑 |
|
|
||||||
| 同一物理目录用不同大小写/软链接路径 | 同一份 | 文件可能落在同一目录,但 project id 可能不同 | 注册表按路径算 | 未做 `realpath` / 大小写归一 |
|
|
||||||
| 云端模式开启且配置了 token | 不读本地 | 不读本地 | 仍读本地 | `memory_*` 切云端;摘要/部门/面板仍本地 |
|
|
||||||
| 两个 DSH 实例用不同 `$DSH_HOME` | 各自一份 | 按各自工作区 | 按各自工作区 | 全局层按 `$DSH_HOME` 隔离 |
|
|
||||||
|
|
||||||
## 五、容易踩的边界(现状事实)
|
|
||||||
|
|
||||||
1. 项目记忆跟**目录路径**走,不跟 DSH 工作区 id 走;DSH 工作区清单只服务技能。
|
|
||||||
2. 全局记忆不区分项目,所有会话都能搜到;要按项目隔离只能换 `$DSH_HOME`。
|
|
||||||
3. `memory_search` 默认合并全局+项目,结果里的 `scope` 字段能区分来源;`memory_add` 默认写项目,写全局必须显式 `project_id=global`。
|
|
||||||
4. 本地 `memory_add` 不会跨项目写入:传别的项目 id 效果等同于写当前项目。
|
|
||||||
5. 部门私有记忆不在 `memory_search` / `memory_list` 里;只有 `department_recall` 能读,且共享部分受 `readGlobal` / `readProject` 开关限制。
|
|
||||||
6. 项目部门只属于创建它的工作区路径;换目录连查找都找不到。
|
|
||||||
7. 原始记录全局一份、未按 workspace 过滤;面板和 `memory_raw_*` 都能看到所有项目的话。
|
|
||||||
8. 备份只备份 `$DSH_HOME/brain`(含 `raw/`、`logs/`),不含各项目的 `.dsh/brain`。
|
|
||||||
9. 全局 `state/projects.json` 只写不读;`spaces/global/memories.json` 镜像也只写不读,当前仓内没有消费方。
|
|
||||||
10. 删除是软删除:记录保留、`deleted=true`,列表和搜索会过滤掉;文件里的记录不会立即减少。
|
|
||||||
11. 项目 `.dsh/.gitignore` 会加 `brain/`,所以项目记忆默认不进 git;换机器/重新 clone 不会带上项目记忆。
|
|
||||||
12. 自动摘要只收用户话里的特定句式(“记住/以后/偏好/每次/规则”等),助手的原话只进原始记录层;文档内容默认是轮数说明,不是原话。
|
|
||||||
13. 自动摘要的增量检查点存在全局,按会话 id 记;它不区分项目。
|
|
||||||
14. Mnemon 原生 Provider 读的是同一批文件:它把 `MemorySpace.dbPath` 当工作区,`search` / `list` 同样合并全局+项目,`remember` 固定写项目(`src/mnemon/native.ts:31-65`)。
|
|
||||||
|
|
||||||
## 六、证据索引
|
|
||||||
|
|
||||||
| 结论 | 代码位置 |
|
|
||||||
| --- | --- |
|
|
||||||
| `$DSH_HOME` 解析、默认 `~/.dsh` | `src/store.ts:67-72` |
|
|
||||||
| 全局根 `$DSH_HOME/brain` | `src/local-memory/manager.ts:12` |
|
|
||||||
| 项目根、`.dsh/brain` 归一、project id | `src/local-memory/manager.ts:14-20` |
|
|
||||||
| 单次操作绑定工作区(AsyncLocalStorage) | `src/local-memory/manager.ts:85,98-105` |
|
|
||||||
| 全局/项目 store 路径 | `src/local-memory/manager.ts:106-116` |
|
|
||||||
| 空间文件布局(`memories.json` / `space.json` / `.lock`) | `src/local-memory/storage.ts:60-70` |
|
|
||||||
| 项目初始化、文档目录、`.gitignore`、projects.json | `src/local-memory/manager.ts:57-63,157-185` |
|
|
||||||
| 全局+项目合并搜索/列表 | `src/local-memory/manager.ts:216-258` |
|
|
||||||
| `memory_read` 先全局后项目 | `src/local-memory/manager.ts:211-215` |
|
|
||||||
| `memory_forget` 目标层判定 | `src/local-memory/manager.ts:259-274` |
|
|
||||||
| 自动摘要写全局记录、项目文档、检查点 | `src/local-memory/manager.ts:340-381` |
|
|
||||||
| USER.md / MEMORY.md 生成与注入 | `src/local-memory/manager.ts:307-338`、`src/entries/memory.ts:41-52` |
|
|
||||||
| 备份只覆盖全局根 | `src/local-memory/manager.ts:391-401` |
|
|
||||||
| 部门目录、注册表、私有 store | `src/local-memory/departments/manager.ts:36-40`、`src/local-memory/departments/registry.ts:26-55` |
|
|
||||||
| 部门创建默认 project、同名幂等 | `src/local-memory/departments/manager.ts:62-85` |
|
|
||||||
| 部门召回合并与排序 | `src/local-memory/departments/manager.ts:194-223` |
|
|
||||||
| 工具层部门召回上限 5 条 | `src/memory/departments-tools.ts:107-130` |
|
|
||||||
| `memory_*` 本地/云端切换 | `src/kernel.ts:304-310` |
|
|
||||||
| 本地 remote 的 scope 规则 | `src/local-memory/remote.ts:17-45` |
|
|
||||||
| 工作区来源(工具/会话/HTTP/侧栏) | `src/kernel.ts:55-67`、`src/entries/memory.ts:65-66`、`src/routes.ts:242-258`、`src-client/sidebar/ProjectMemoryView.tsx:19-28` |
|
|
||||||
| 面板页签的 scope | `src-client/panel/BrainPanel.tsx:21-24`、`src-client/sidebar/ProjectMemoryView.tsx:46-48` |
|
|
||||||
| 部门 HTTP 的 scope/workspace 校验 | `src/settings-ui/departments-routes.ts:51-65,71-150` |
|
|
||||||
| 原始记录目录、文件、轮转、保留 | `src/raw-memory/settings.ts:40-52`、`src/raw-memory/store.ts:72-84,118-141,271-288` |
|
|
||||||
| 原始记录搜索不过滤 workspace | `src/raw-memory/store.ts:144-214` |
|
|
||||||
| 原始记录采集时记录 workspace 字段 | `src/entries/raw.ts:98-110` |
|
|
||||||
| 技能工作区清单与目录(与记忆无关) | `src/clients.ts:76-80,87-96,173-188,218-249` |
|
|
||||||
| Mnemon 原生 Provider 复用本地存储 | `src/mnemon/native.ts:31-65` |
|
|
||||||
|
|
@ -1,108 +0,0 @@
|
||||||
# 诊断日志规格(.dsh/brain/logs,随 UI 批次交付)
|
|
||||||
|
|
||||||
版本:v1 · 2026-11-24 23:40
|
|
||||||
需求(用户原话):"这个版本需要在 .dsh 里面的 brain 留下 log,用来后续出问题 debug 的。
|
|
||||||
先不升级,等 UI 做好一起升级。"
|
|
||||||
定位:新增 U5 卡,与 U0–U4 同批交付、同次升级生效。基线 8f5ee01。
|
|
||||||
|
|
||||||
## 1. 落盘位置与文件布局
|
|
||||||
|
|
||||||
$DSH_HOME/brain/logs/ ← 全局(globalBrainRoot()/logs)
|
|
||||||
brain-YYYY-MM-DD.log ← 按天滚动,JSONL(每行一个事件)
|
|
||||||
brain-YYYY-MM-DD.1.log ← 单日超 5 MB 时序号滚动
|
|
||||||
<project>/.dsh/brain/logs/ ← 项目级(projectBrainRoot(ws)/logs)
|
|
||||||
brain-YYYY-MM-DD.log ← 只记该项目工作区的事件
|
|
||||||
|
|
||||||
- 全局事件(启动/开关/迁移/云同步/技能同步)落全局;带 workspace 的记忆/部门操作落项目。
|
|
||||||
- 目录懒创建(首次写时 mkdir recursive);**.gitignore 已忽略 /.dsh/brain/,日志天然不入库**。
|
|
||||||
- 保留策略:启动时清理 14 天前的日志文件(只删 logs/ 内 brain-*.log,别的不碰)。
|
|
||||||
|
|
||||||
## 2. 事件格式(JSONL,一行一事件)
|
|
||||||
|
|
||||||
{"ts":"ISO8601","level":"info|warn|error","event":"<点分名>","scope":"global|project",
|
|
||||||
"workspace":"<路径,可省>","sessionId":"<可省>","detail":{…},"err":"<message,可省>"}
|
|
||||||
|
|
||||||
- detail 只放结构化小字段(id/scope/revision/耗时 ms/计数),**禁止记忆正文全文**;
|
|
||||||
内容类字段一律截断 ≤120 字符并过 containsSecret(storage.ts 已有)拒收秘密。
|
|
||||||
- 写入必须不阻塞主流程:appendFile 异步 + 失败静默(日志自身错误只 console.warn 一次)。
|
|
||||||
- 单进程内串行队列(Promise chain)防交错;跨进程靠 append 原子性(单行 <64KB)。
|
|
||||||
|
|
||||||
## 3. 埋点清单( event 名 → 触发处 )
|
|
||||||
|
|
||||||
### 启动与配置(kernel.ts / entries)
|
|
||||||
- boot.kernel constructor 完成:version、五 bundle 激活态、localMemoryEnabled/cloudMemoryEnabled/autoSummaryEnabled
|
|
||||||
- boot.entry 各 entry apply/deactivate:bundle 名
|
|
||||||
- config.change SettingsStore 写入时:变更键名列表(值不落盘,token 类只记 present/absent)
|
|
||||||
- switch.gate memoryEnabled/localMemoryEnabled 拒绝工具/路由时:被拒面(tool/route)、名字
|
|
||||||
|
|
||||||
### 本地记忆(local-memory/manager.ts)
|
|
||||||
- memory.ensure ensureGlobal/ensureProject:root、created/reused
|
|
||||||
- memory.remember add/remember:scope、recordId、duplicate、category、耗时
|
|
||||||
- memory.search search/searchHits:query 截断、k、命中数、来源分布、耗时
|
|
||||||
- memory.forget forget:recordId、revision
|
|
||||||
- memory.projection regenerateProjections/repair:dirty 原因、字节数、耗时
|
|
||||||
- memory.summary summarizeConversation:sessionId、turn、成功/失败/重试次数、err
|
|
||||||
- memory.profile proposeProfile/confirmProfile/correctProfile:动作、记录数
|
|
||||||
- memory.migration migrateLegacy/rollbackMigration/importLegacyRecords:阶段、计数、err(数据安全关键路径,全阶段落盘)
|
|
||||||
- memory.backup createBackup:路径、字节数
|
|
||||||
|
|
||||||
### 部门(接线层埋,库层零改动约束不变)
|
|
||||||
- dept.create/update/disable/checkpoint/resume/recall/remember
|
|
||||||
在 departments-tools.ts execute 与 departments-routes.ts handler 的包裹层记:
|
|
||||||
departmentId、workspace、revision、结果/错误码。**不改 src/local-memory/departments/**。
|
|
||||||
|
|
||||||
### 云与技能(reporter/skill-sync,保护期后埋)
|
|
||||||
- cloud.report 上报批次:turn 数、成功/失败、http 状态(token 不落盘)
|
|
||||||
- sync.pass skill-sync 每轮:downloaded/uploaded/conflicts/skipped 计数、耗时
|
|
||||||
- sync.resolve 冲突解决:name、action、conflictId、结果
|
|
||||||
⚠ skill-sync.ts 在 GPT 复验保护期内禁改——本组埋点放 U5 后半段,
|
|
||||||
复验通过后补;若 UI 批次先完成,cloud/sync 埋点单独小 commit 跟进,不阻塞升级。
|
|
||||||
|
|
||||||
### UI(src-client,浏览器侧)
|
|
||||||
- 浏览器端不直接写文件:面板/页签的关键错误经既有路由无法上报时,
|
|
||||||
console.warn 带 [dsh-brain] 前缀即可(宿主控制台可见);
|
|
||||||
服务端路由错误已由 http 层 fail() 统一记 route.error(见下)。
|
|
||||||
|
|
||||||
### 路由层(routes.ts / settings-ui/*routes.ts / departments-routes.ts 保护期后)
|
|
||||||
- route.error 任何 4xx/5xx:path、method、status、错误码(body 不落盘)
|
|
||||||
- route.write POST 成功:path、关键 id(create/forget/resolve 类)
|
|
||||||
|
|
||||||
## 4. 实现形态
|
|
||||||
|
|
||||||
新文件 src/diagnostics.ts(host 侧,~150 行):
|
|
||||||
export interface BrainLogEvent { level; event; scope?; workspace?; sessionId?; detail?; err? }
|
|
||||||
export class BrainLogger {
|
|
||||||
constructor(opts: { globalRoot: () => string; projectRootOf: (ws?: string) => string; enabled: () => boolean })
|
|
||||||
log(e: BrainLogEvent): void // 同步入队,异步落盘,永不 throw
|
|
||||||
flush(): Promise<void> // 测试用
|
|
||||||
prune(): void // 启动清 14 天前
|
|
||||||
}
|
|
||||||
- kernel 构造 BrainLogger 并注入:LocalMemoryManager options 加 logger?(可选,缺省 noop,
|
|
||||||
库层签名向后兼容);DepartmentToolDeps/RouteDeps 加 logger?;reporter/skillSync 的 log 回调
|
|
||||||
双写(宿主 logger + BrainLogger)。
|
|
||||||
- 开关:settings 加 diagnosticsEnabled(默认 true,继承 enabled);关闭时 noop。
|
|
||||||
侧车 dsh-brain.json 可关;设置页 U2 概览卡显示日志路径与开关。
|
|
||||||
- **LocalMemoryManager 属库层但不在部门保护目录内**,加可选 logger 参数允许;
|
|
||||||
verify-local-memory* 现有断言不得回退(logger 缺省时行为字节等价)。
|
|
||||||
|
|
||||||
## 5. 验收(新增 verify-diagnostics.mjs)
|
|
||||||
|
|
||||||
1. mkdtemp DSH_HOME + 双项目:remember/search/forget 后项目 logs/ 出现当日 JSONL,
|
|
||||||
事件名/字段齐全;全局操作落全局 logs/。
|
|
||||||
2. 秘密拒收:detail 含 API key 样式 → 该字段被拒/截断,文件无秘密原文。
|
|
||||||
3. 正文不落盘:700 字符记忆 remember → 日志无全文(≤120 截断)。
|
|
||||||
4. 滚动:写 >5MB(测试用小阈值注入)→ .1.log 出现;14 天前旧文件被 prune。
|
|
||||||
5. 关闭开关 → 零文件产生;logger 抛错注入 → 主流程不受影响。
|
|
||||||
6. 日志失败静默:logs 目录置只读 → remember 仍成功。
|
|
||||||
7. verify-all 全量口径不回退;typecheck/build 全绿。
|
|
||||||
|
|
||||||
commit:feat(diagnostics): JSONL debug logs under .dsh/brain/logs with redaction and rotation
|
|
||||||
|
|
||||||
## 6. 排期与升级批次
|
|
||||||
|
|
||||||
- U5 与 U0–U4 并行可行(diagnostics.ts 独立;manager 可选参数不碰部门保护文件)。
|
|
||||||
- 建议顺序:U0 → U1 → (U2 ∥ U3 ∥ U5) → U4 终验。
|
|
||||||
- **升级批次**:U0–U5 全部完成 + GPT 部门复验通过 → 一次升级 profile 依赖 → 重启 →
|
|
||||||
冒烟清单(另出升级卡):status 版本、.dsh/brain 生成、memory_search 离线命中、
|
|
||||||
部门工具可见、左栏 Brain 面板、better-sidebar 页签、**logs/ 出现当日 JSONL**。
|
|
||||||
- skill-sync/cloud 埋点若因保护期滞后,升级后小 commit 补,不阻塞。
|
|
||||||
|
|
@ -1,193 +0,0 @@
|
||||||
# DSH Brain 四模块拆分 · 后续阶段规划
|
|
||||||
|
|
||||||
版本:v1(接续 LOCAL_MEMORY_PLAN.md)
|
|
||||||
日期:2026-11-24
|
|
||||||
状态:待确认排期;本文档只记录规划,不代表已执行。
|
|
||||||
|
|
||||||
## 0. 当前基线(已完成事实)
|
|
||||||
|
|
||||||
四模块 + 设置页的 bundle 拆分**已经落地**(0.9.11,commit `3ef7ffe`):
|
|
||||||
|
|
||||||
| Bundle | 入口 | 职责 |
|
|
||||||
| --- | --- | --- |
|
|
||||||
| dsh-brain-memory | src/entries/memory.ts | memory_* 工具,经 kernel MemoryRemoteFactory 访问存储 |
|
|
||||||
| dsh-brain-skills | src/entries/skills.ts | 技能管理页、skill_list、市场、来源树、客户端注册 |
|
|
||||||
| dsh-brain-mcp | src/entries/mcp.ts | MCP 管理页能力声明(连接由宿主 dsh-mcp-connector 管理) |
|
|
||||||
| dsh-brain-cloudsync | src/entries/cloudsync.ts | 活动上报、登录/测试/补发/技能同步路由与定时器 |
|
|
||||||
| dsh-brain-settings-ui | src/entries/settings-ui.ts | 配置页与 status/capabilities/config/migrate 路由 |
|
|
||||||
|
|
||||||
本地记忆第一阶段(LOCAL_MEMORY_PLAN.md §1–17)**已验收**:
|
|
||||||
docs/LOCAL_MEMORY_ACCEPTANCE.md 记录 38 个验证脚本全绿(2 个环境性跳过)。
|
|
||||||
Mnemon fork 位于 vendor/dsh-mnemon(dsh-brain-mnemon 0.5.54-dsh.1,MIT 保留),
|
|
||||||
活跃适配层为 src/mnemon/fork + src/mnemon/native.ts。
|
|
||||||
|
|
||||||
收口状态(2026-11-24 20:33 复核):**P0 已完成**——用户已提交并推送,
|
|
||||||
HEAD `1dfc7c7` feat: complete local memory and Mnemon integration (0.10.1),
|
|
||||||
tag `v0.10.1`(替代原建议名 v0.10.0-local.1),工作树干净,origin/main 同步。
|
|
||||||
后续阶段的回滚点即 v0.10.1。
|
|
||||||
- verify-all 本轮未能重跑(宿主 shell 审批通道故障),沿用验收文档记录;P0 需重跑确认。
|
|
||||||
- 真实云 endpoint、真实 Mnemon 宿主进程、frozen install 未在验收中覆盖。
|
|
||||||
|
|
||||||
## 1. 阶段总览
|
|
||||||
|
|
||||||
P0 收口固化 → P1 仓库整理(§19) → P2 cloud-sync 记忆同步 → P3 功能移除精简(§18) → P4 发布
|
|
||||||
|
|
||||||
P2 与 P1 可并行;P3 严格依赖 P2 验收通过(§18 前置条件)。
|
|
||||||
|
|
||||||
新增需求(2026-11-24):settings-ui 升格为 UI bundle——左侧栏总面板 + better-sidebar 项目记忆页签。方案 docs/plans/UI_PLAN.md;决策已定:B 借壳不借芯 + 彻底改名 dsh-brain-ui;可执行任务卡 docs/plans/UI_TASKS.md + 详细规格 UI_SPEC.md(U0–U4)+ 诊断日志 LOGGING_SPEC.md(U5)。升级批次(用户拍板):先不升级宿主,UI 全卡完成 + 部门复验通过后一次升级,新版须带 .dsh/brain/logs 诊断日志。
|
|
||||||
|
|
||||||
**推荐执行序(2026-11-24 调整,待用户确认)**:
|
|
||||||
|
|
||||||
P0 收口固化 → P1.5 部门接线(D1→D2→D3→D4) → P1 仓库整理 → P2 cloud-sync → P3 → P4
|
|
||||||
|
|
||||||
理由:部门库层已验收、只差接线(2–3 天),是用户可见价值最快的路径;
|
|
||||||
先于 P2 做出真实使用反馈,还能反过来校准云同步的条目模型。
|
|
||||||
P0 仍是硬门禁(部门代码就在未提交的 85 个文件里,先固化基线再动新刀)。
|
|
||||||
P1 仓库整理让位到部门之后:整理会移动 verify 脚本位置,放在接线后做可少改一次引用。
|
|
||||||
|
|
||||||
## 2. P0 · 收口与基线固化(先做,半天)
|
|
||||||
|
|
||||||
**状态:已完成(2026-11-24)**。实际落账:单 commit `1dfc7c7` + tag `v0.10.1`(未按下面 1–3 的分主题拆分,成果已入库为准;verify-all 重跑记录见验收文档)。以下保留原计划供追溯:
|
|
||||||
|
|
||||||
1. 重跑 `npm run typecheck`、`npm run build`、`node scripts/verify-all.mjs`,确认全绿。
|
|
||||||
2. 审阅并提交本地记忆阶段成果,按主题分 commit:
|
|
||||||
- feat(local-memory): 本地存储/空间/部门/迁移 + 对应 verify
|
|
||||||
- feat(mnemon): fork 快照、provider-sdk 子集、native 入口 + vendor/
|
|
||||||
- feat(auto-summary): 自动总结/画像/开关 + 对应 verify
|
|
||||||
- docs: 方案、验收、fork 说明
|
|
||||||
- chore: lib 构建产物与 lockfile
|
|
||||||
3. 打 tag(建议 v0.10.0-local.1)作为后续所有阶段的回滚点。
|
|
||||||
|
|
||||||
门禁:typecheck + build + verify-all 全绿才允许进入后续阶段。
|
|
||||||
|
|
||||||
## 3. P1 · 仓库整理(执行 LOCAL_MEMORY_PLAN §19,1 天)
|
|
||||||
|
|
||||||
详细实施方案已细化为 docs/plans/REPO_CLEANUP_PLAN.md(含 39 个 verify 脚本引用全量扫描、C0–C5 执行切片、发布件零改动门禁)。要点:
|
|
||||||
1. 先产出「待处理文件清单 + Git 状态」再动手;区分历史输出 / 可重建缓存 / 源码 / 未跟踪修复成果。
|
|
||||||
2. verify-*.mjs 迁入 tests/verification/,同步更新 package.json scripts、
|
|
||||||
scripts/verify-all.mjs 引用与工作目录假设;verify-review-fixes.mjs、
|
|
||||||
src/version.ts、lib/version.js 是成果不是垃圾。
|
|
||||||
3. 建 artifacts/{analysis,logs,preview},加入 .gitignore;_preview 与
|
|
||||||
.tmp-verify-*.log 核对后归档或清理。
|
|
||||||
4. .codegraph/planning-context.txt 等历史会话导出移入 artifacts/analysis。
|
|
||||||
5. lib 保持入库(发布入口),client 保留;.dsh/brain 数据不混入 artifacts。
|
|
||||||
6. 整理后重跑 typecheck + build + verify-all + 插件入口检查,单独 commit。
|
|
||||||
|
|
||||||
## 4. P2 · cloud-sync 记忆增量同步(核心新工作,约 1–2 周)
|
|
||||||
|
|
||||||
目标:把本地记忆(Runtime 投影之外的 Documents / Memory Spaces / 画像)
|
|
||||||
与 LongMemory 云端做**条目级**增量双向同步。不做 SQLite 文件上传,
|
|
||||||
不用 Git 代替实时同步(§15 边界继续有效)。
|
|
||||||
|
|
||||||
### 4.1 三层架构(复用 §13 拆解成果)
|
|
||||||
|
|
||||||
L1 本地变化层 (src/local-memory/changelog)
|
|
||||||
outbox:id、space、op(create/update/delete)、revision、
|
|
||||||
local_change_no、payload 摘要、pending/synced/failed 状态
|
|
||||||
—— 与记忆写入同事务落盘(§10 已有 revision/tombstone 基础)
|
|
||||||
L2 同步编排层 (src/cloudsync/memory-sync)
|
|
||||||
push outbox → 云端 change_id 游标 pull → 幂等重试 →
|
|
||||||
冲突检测(revision + 内容 hash) → 冲突预览/确认 UI →
|
|
||||||
删除事件(tombstone)传播
|
|
||||||
L3 Provider/传输适配层 (src/mnemon/fork 协议扩展)
|
|
||||||
实现 Brain Cloud Provider:discover/status/search/list/
|
|
||||||
remember/forget + connection/secret 脱敏/AbortSignal
|
|
||||||
—— 补齐公共协议缺口:revision、change_id、游标、
|
|
||||||
幂等操作号、冲突回执(§11 已确认缺口)
|
|
||||||
|
|
||||||
### 4.2 分期切片
|
|
||||||
|
|
||||||
- M1 协议定稿:云端 API 契约(change feed、幂等号、冲突回执)书面化,
|
|
||||||
服务端与插件两侧确认;产出 docs/plans/CLOUD_SYNC_CONTRACT.md。
|
|
||||||
- M2 单向推送:outbox → push,幂等重试、账号切换隔离(复用 activity
|
|
||||||
队列的账号绑定语义);断网堆积、恢复补发。
|
|
||||||
- M3 拉取与合并:change_id 游标 pull、远端 tombstone 应用、
|
|
||||||
revision 冲突检测;冲突走「预览 + conflictId + 过期确认拒绝」
|
|
||||||
(沿用 skill-sync round5 已验证的交互语义)。
|
|
||||||
- M4 范围确认与默认策略:首次同步前确认空间/画像/项目档案范围;
|
|
||||||
记忆同步与 Skill 同步独立开关;手动关闭永不覆盖(§14)。
|
|
||||||
|
|
||||||
### 4.3 验收标准(新增 verify-cloud-sync-*.mjs)
|
|
||||||
|
|
||||||
1. sync 关闭时云端调用为零(沿用第一阶段 check 16/17 语义)。
|
|
||||||
2. 断网→恢复:outbox 不丢不重,幂等号去重。
|
|
||||||
3. 双端并发修改同一记忆:revision 冲突被检出,预览含双方版本,
|
|
||||||
过期确认被拒绝;解决后两端一致。
|
|
||||||
4. 删除传播:本地删→云端 tombstone;云端删→本地 tombstone;
|
|
||||||
hard-delete Provider 场景由 L1 自存删除事件。
|
|
||||||
5. 账号/服务地址切换:旧队列与游标作废,不串号。
|
|
||||||
6. 反复开关同步不删除、不复制本地数据。
|
|
||||||
7. 秘密字段永不上传;画像同步需单独确认。
|
|
||||||
8. 真实 endpoint 冒烟(弥补第一阶段环境缺口)。
|
|
||||||
|
|
||||||
## 4.5 P1.5 · 部门(Departments)接线与暴露(新增,约 2–3 天)
|
|
||||||
|
|
||||||
状态(2026-11-24 23:25):D1+D2 实施完成,GPT 首轮验收 FAIL 两项(C7/C8)已修复
|
|
||||||
(22b2497/45f1ca9),wiring 25 项全绿,待 GPT 复验。复验通过后进入 UI 改造(UI_PLAN.md)或 P1 仓库整理。
|
|
||||||
|
|
||||||
执行序建议:**提前到 P1 之前**(P0 之后立即做),见 §1 推荐执行序。
|
|
||||||
每个切片 D1–D4 独立 commit + verify,D1+D2 完成即有最小可用闭环
|
|
||||||
(agent 能建部门/存记忆/召回),D3/D4 可再拆半天粒度跟进。
|
|
||||||
|
|
||||||
概念定稿与选型依据见 docs/plans/DEPARTMENT_PLAN.md。
|
|
||||||
|
|
||||||
现状核实(2026-11-24):
|
|
||||||
- DepartmentManager 已完整实现于 src/local-memory/departments/
|
|
||||||
(types/registry/manager/index),verify-departments.mjs 21 项检查全绿(实测复核,原稿误记 26)。
|
|
||||||
- 能力:按 scope+名称幂等创建;角色/skills/allowedTools/记忆读取策略;
|
|
||||||
私有 memory-space(departments/<id>/memory-space,对其他部门不可见);
|
|
||||||
可复用会话引用 resumeSession/attachSession(host 绑定显式);
|
|
||||||
checkpoint(currentTask/handoff);recall 私有优先+项目/全局可选、
|
|
||||||
总量受限、去重;revision 冲突检测;disable 不删数据不复活;秘密拒收。
|
|
||||||
- **缺口:只有库级导出(./local-memory),未接任何用户面**——
|
|
||||||
kernel 未构造实例,无 agent 工具、无 /dsh-brain 管理路由、
|
|
||||||
设置页无部门页签、宿主会话生命周期未挂 attach/checkpoint。
|
|
||||||
|
|
||||||
接线切片(每步独立 commit + verify;D1/D2 可执行任务卡见 docs/plans/DEPARTMENT_TASKS.md):
|
|
||||||
- D1 kernel 构造 DepartmentManager(共享 LocalMemoryManager),
|
|
||||||
随 localMemoryEnabled 开关;settings-ui 增加 /dsh-brain/departments
|
|
||||||
管理路由(list/create/update/disable/checkpoint,同源写门禁)。
|
|
||||||
- D2 memory 子插件注册 department_* agent 工具
|
|
||||||
(create/list/remember/recall/checkpoint/resume),
|
|
||||||
工具描述声明私有空间语义;k 上限沿用 5。
|
|
||||||
- D3 宿主会话挂钩:会话启动时按部门 resumeSession + attachSession,
|
|
||||||
回合结束可选 checkpoint;失败不阻塞对话。
|
|
||||||
- D4 设置页部门页签(只走公开 API,不触存储内部);
|
|
||||||
云同步阶段部门私有空间默认不上传,纳入 M4 范围确认。
|
|
||||||
|
|
||||||
验收:verify-departments.mjs 保持全绿 + 新增 verify-departments-wiring.mjs
|
|
||||||
(工具注册/路由鉴权/开关行为/会话恢复/禁用后工具拒绝)。
|
|
||||||
|
|
||||||
## 5. P3 · 功能移除与精简(执行 §18,P2 验收后)
|
|
||||||
|
|
||||||
前置条件(§18):本地记忆稳定 ✅ + cloud-sync 协议拆解复用 ✅(P2) +
|
|
||||||
依赖分析确认无引用。
|
|
||||||
|
|
||||||
1. 用 code-graph 对候选移除项逐项出影响面报告(公开导出/工具/路由/
|
|
||||||
配置/页面引用为零才可移除)。
|
|
||||||
2. 候选顺序(每项独立 commit + 回滚点 + 全量回归):
|
|
||||||
a. 冗余外部 Provider 默认内置(保留协议与源码于 vendor,停止默认注册)
|
|
||||||
b. 旧 cloud-memory 兼容别名路由(确认无存量 profile 依赖后)
|
|
||||||
c. 根导出组合器中已被五入口取代的重复装配
|
|
||||||
3. 原则:不停止仍被引用的注册;不物理删除 vendor 源码;
|
|
||||||
每步保留回滚点。
|
|
||||||
|
|
||||||
## 6. P4 · 发布与分发
|
|
||||||
|
|
||||||
1. 版本 0.10.0:README 更新(本地优先 + 云同步可选)、CHANGELOG。
|
|
||||||
2. pack-guard + prepack 校验五入口 exports 完整;frozen install 验证
|
|
||||||
(补第一阶段缺口)。
|
|
||||||
3. 新安装默认策略评审:cloudMemoryEnabled 是否默认开(§14:需 P2
|
|
||||||
验收 + 首次范围确认交互就绪后才允许)。
|
|
||||||
4. 真实 DSH 宿主端到端冒烟:五子插件逐行开关 HMR、重启保持、
|
|
||||||
离线全功能。
|
|
||||||
|
|
||||||
## 7. 风险与开放问题
|
|
||||||
|
|
||||||
- 云端 LongMemory 服务端是否已有 change feed / 幂等号接口?M1 前需确认,
|
|
||||||
否则 P2 工期取决于服务端改造。
|
|
||||||
- async-extracting 类 Provider(Mem0/Hindsight/Supermemory)不承担
|
|
||||||
双向同步;Brain Cloud Provider 必须 exact 语义。
|
|
||||||
- 多窗口并发同步的文件锁对抗性故障未覆盖(第一阶段遗留),P2 M2
|
|
||||||
加并发用例。
|
|
||||||
- 宿主 shell 审批通道当前故障,P0 重跑验证前需恢复或换通道。
|
|
||||||
|
|
@ -1,118 +0,0 @@
|
||||||
# P1 · 仓库整理实施方案(Repo Cleanup)
|
|
||||||
|
|
||||||
版本:v1(规划稿,本会话只做规划,不实施)
|
|
||||||
日期:2026-11-24
|
|
||||||
依据:LOCAL_MEMORY_PLAN.md §19 + 本轮逐项核实(39 个 verify 脚本的引用扫描、Git 状态、目录实测)。
|
|
||||||
执行归属:实施会话/人工;每步独立 commit,门禁见 §7。
|
|
||||||
|
|
||||||
## 0. 前置核对(执行前必读)
|
|
||||||
|
|
||||||
**基线已固化(2026-11-24 20:33 复核)**:P0 完成——HEAD `1dfc7c7`(0.10.1 本地记忆+Mnemon 集成),
|
|
||||||
tag `v0.10.1`,工作树干净,已推送 origin/main。本方案的回滚点即 v0.10.1。
|
|
||||||
C0 仍保留"动手前再核对一次 Git 状态"的动作,防执行时隔了新的改动。
|
|
||||||
|
|
||||||
## 1. 现状盘点(已核实事实)
|
|
||||||
|
|
||||||
根目录现有内容分类:
|
|
||||||
|
|
||||||
| 类别 | 内容 | 处置 |
|
|
||||||
| --- | --- | --- |
|
|
||||||
| 源码/产物(保留原位) | src/ client/ lib/ vendor/ scripts/ docs/ | 不动(lib 是发布入口,.gitignore 明确入库) |
|
|
||||||
| 验证脚本 ×39 | 根目录 verify-*.mjs(26 tracked + 13 untracked) | 迁入 tests/verification/(§3) |
|
|
||||||
| 预览生成器 ×3 | preview-card/import-mcp.mjs(tracked) | 迁入 scripts/preview/,输出改 artifacts/preview(§4) |
|
|
||||||
| 可再生输出 | _preview/(2.3 MB,12 个 html/png,已忽略) | 删除,可由生成器重建 |
|
|
||||||
| 索引缓存 | .codegraph/cache(26.7 MB,已忽略) | 保留不动(重建成本高,非垃圾) |
|
|
||||||
| 历史会话导出 | .codegraph/*.txt ×4(planning-context、session-recap-b1×2、mnemon-storage-investigation)+ code-graph.json/CODE-GRAPH.md/manifest.json | txt 移入 artifacts/analysis/;json/md 是 codegraph 工具自身数据,留在 .codegraph |
|
|
||||||
| §19.2 列举的旧临时文件 | .tmp-b1.txt、.review-context.txt 等 10 项 | **已不存在**(本轮实测根目录无任何 .tmp*),无需清理 |
|
|
||||||
| 项目记忆数据 | .dsh/brain/(已忽略) | 不动,不混入 artifacts |
|
|
||||||
|
|
||||||
其他事实:
|
|
||||||
- package.json 的 verify/test 都指向 scripts/verify-all.mjs;typecheck/build/prepack 不涉及根目录脚本。
|
|
||||||
- .npmignore 已排除 *.mjs 与 scripts/,files 字段只含 lib/client/cordis.patch.yml/README/LICENSE——**迁移不影响发布件**。
|
|
||||||
- pack-guard.mjs / release-prep.mjs / fork-mnemon.mjs 无 verify-*/_preview/.codegraph 引用(已扫描)。
|
|
||||||
- .gitignore 已含 artifacts/、_preview/、.tmp-*、.codegraph/ 规则,artifacts 目录建立后无需新增忽略规则。
|
|
||||||
|
|
||||||
## 2. 目标目录(沿用 §19.1,微调预览生成器归属)
|
|
||||||
|
|
||||||
dsh-brain/
|
|
||||||
├─ docs/plans/ ← 方案(已就位:LOCAL_MEMORY/NEXT_PHASE/DEPARTMENT/本文档)
|
|
||||||
├─ tests/verification/ ← 39 个 verify-*.mjs 统一收纳
|
|
||||||
├─ scripts/
|
|
||||||
│ ├─ verify-all.mjs ← 扫描目录改为 tests/verification
|
|
||||||
│ └─ preview/ ← 3 个 preview-*.mjs 生成器(源码归 scripts)
|
|
||||||
├─ artifacts/ ← 已忽略,不提交
|
|
||||||
│ ├─ analysis/ ← .codegraph 历史 txt 导出
|
|
||||||
│ ├─ logs/ ← 预留:验证/运行日志
|
|
||||||
│ └─ preview/ ← 预览生成器的新输出目录(替代 _preview)
|
|
||||||
├─ src/ client/ lib/ vendor/ ← 不动
|
|
||||||
└─ 根目录 ← 只剩标准配置 + README + LICENSE
|
|
||||||
|
|
||||||
## 3. 验证脚本迁移(核心步骤,引用已全量扫描)
|
|
||||||
|
|
||||||
39 个脚本的项目引用只有三种形态,全部要改:
|
|
||||||
|
|
||||||
1. **相对导入 `./lib/...`(36 个脚本)** → 改 `../../lib/...`。
|
|
||||||
涉及 api/store/config/reporter/kernel/entries/local-memory/mnemon/skills 等,
|
|
||||||
逐脚本正则替换 `from './lib/` → `from '../../lib/`(含动态 import())。
|
|
||||||
2. **cwd 相对读取(1 个)**:verify-theme.mjs 读 `'./client/index.js'`。
|
|
||||||
verify-all 以 cwd=root 跑子进程,迁移后 cwd 不变则仍可用;
|
|
||||||
但为消除 cwd 依赖,统一改成基于 import.meta.url 定位仓库根(与第 3 类同法)。
|
|
||||||
3. **here 相对读取(2 个)**:verify-card-debug/card-render 用
|
|
||||||
`dirname(fileURLToPath(import.meta.url))` join 'client'。
|
|
||||||
迁移后 here 变成 tests/verification,须改为 `join(here,'..','..','client')`
|
|
||||||
或引入统一的 root 常量。
|
|
||||||
|
|
||||||
配套改动:
|
|
||||||
- scripts/verify-all.mjs:扫描目录从仓库根改为 `join(root,'tests','verification')`;
|
|
||||||
子进程 cwd 保持仓库根不变(保证第 2 类兼容);文件名过滤正则不变。
|
|
||||||
- README.md:8 处 `node verify-*.mjs` 示例路径更新为 `node tests/verification/verify-*.mjs`。
|
|
||||||
- docs/management-surface.md:约 20 处脚本名提及多为纯文件名(无路径),核对后仅改带路径的。
|
|
||||||
- docs/plans/LOCAL_MEMORY_PLAN.md §19 与验收文档中的路径描述追加"已迁移"注记,不改历史记录正文。
|
|
||||||
|
|
||||||
**保留红线(§19.3)**:verify-review-fixes.mjs、src/version.ts、lib/version.js 是成果;
|
|
||||||
.tmp-remote-skill-sync.ts 若在其他检出存在,归并前不得删(本检出未见此文件)。
|
|
||||||
|
|
||||||
## 4. 预览生成器与输出
|
|
||||||
|
|
||||||
- preview-card/import/mcp.mjs 迁至 scripts/preview/(tracked 源码,git mv 保历史)。
|
|
||||||
- 三个脚本的 outDir 从 `join(here,'_preview')` 改为仓库根下 `artifacts/preview`
|
|
||||||
(here 现在指向 scripts/preview,用 `join(here,'..','..','artifacts','preview')`)。
|
|
||||||
- README 中 `node preview-card.mjs` 的调用示例同步更新。
|
|
||||||
- 旧 _preview/(2.3 MB)确认生成器可重建后删除;.gitignore 的 _preview/ 规则可留可删(建议留,防旧工具复活)。
|
|
||||||
|
|
||||||
## 5. 历史导出归档
|
|
||||||
|
|
||||||
- .codegraph/planning-context.txt、session-recap-b1.txt、session-recap-b1-full.txt、
|
|
||||||
mnemon-storage-investigation.txt → 移入 artifacts/analysis/(移动即出 Git 视野,因 .codegraph 本就忽略)。
|
|
||||||
- .codegraph/code-graph.json、CODE-GRAPH.md、manifest.json、cache/ 留在原地(工具工作数据)。
|
|
||||||
- 本轮解码产生的 .codegraph/cache/dept-*.jsonl、sess-*.jsonl 属可重建缓存,随 cache 保留或由实施者清理,不影响仓库。
|
|
||||||
|
|
||||||
## 6. 执行切片(每步独立 commit + 验证)
|
|
||||||
|
|
||||||
| 步 | 动作 | commit 主题 | 验证 |
|
|
||||||
| --- | --- | --- | --- |
|
|
||||||
| C0 | 核对 Git 基线(§0),产出待处理清单 | 无(只读) | 清单评审 |
|
|
||||||
| C1 | 建 tests/verification + git mv 39 个脚本 + 改三类引用 + verify-all 扫描目录 | refactor(tests): move verify scripts into tests/verification | typecheck + build + npm run verify 全绿(38 过 + 2 环境跳过口径不变) |
|
|
||||||
| C2 | 预览生成器迁 scripts/preview + 输出改 artifacts/preview + 删 _preview | chore(preview): relocate generators and outputs | 跑一次 preview-card 确认产物落 artifacts/preview |
|
|
||||||
| C3 | .codegraph 历史 txt 归档 artifacts/analysis + 建 artifacts/logs 占位 | chore(artifacts): archive historical exports | git status 干净度核对 |
|
|
||||||
| C4 | README / management-surface / 计划文档路径注记 | docs: update paths after repo cleanup | 文档内路径抽查 |
|
|
||||||
| C5 | 终验:typecheck + build + verify-all + verify-plugin-entry + npm pack --dry-run 比对 files 清单 | 无(验证) | 发布件与整理前一致(lib/client 字节不变) |
|
|
||||||
|
|
||||||
预计工作量:半天~1 天(C1 占大头,36 个脚本的机械替换 + 全量验证)。
|
|
||||||
|
|
||||||
## 7. 门禁与回滚
|
|
||||||
|
|
||||||
1. C0 清单先行:任何删除/移动前列出文件名、来源、Git 状态(§19.4)。
|
|
||||||
2. 每步 commit 独立,出问题 revert 单步即可;C1 之前打轻量 tag(如 pre-cleanup)可选。
|
|
||||||
3. lib/ client/ src/ vendor/ 的字节在本阶段**零改动**——整理只动位置与引用,
|
|
||||||
npm pack --dry-run 前后对比作为硬证据。
|
|
||||||
4. artifacts/ 不提交;.dsh/brain 数据不进 artifacts;不误加忽略规则覆盖源码。
|
|
||||||
5. 完成后根目录仅剩:配置文件(package/tsconfig/git/npm 系)、README、LICENSE、
|
|
||||||
cordis.patch.yml 与标准目录。
|
|
||||||
|
|
||||||
## 8. 与后续阶段的衔接
|
|
||||||
|
|
||||||
- 本方案即 NEXT_PHASE_PLAN 的 P1;推荐执行序中排在 P1.5 部门接线之后
|
|
||||||
(部门 D1–D4 会新增 verify-departments-wiring.mjs,先接线后迁移可少搬一次)。
|
|
||||||
- 若用户决定先整理后接线,本方案同样成立:新验证脚本直接写进 tests/verification 即可。
|
|
||||||
- P2 cloud-sync 的新 verify-cloud-sync-*.mjs 一律出生在新位置,不再回落根目录。
|
|
||||||
|
|
@ -1,110 +0,0 @@
|
||||||
# UI 批次验收 FAIL 修复单(给 GPT 执行)
|
|
||||||
|
|
||||||
日期:2026-11-25
|
|
||||||
基线:c8101a3(U0–U5 七个交付 commit 齐全,工作树干净)。
|
|
||||||
依据:GPT 独立复核报告(三个 P1 + diff --check 六处)。规划侧已逐项对照源码核实,全部属实。
|
|
||||||
角色变更:本轮由 **GPT 实施修复**(此前 GPT 只验收;用户明确指派)。修完自验 + 交回规划侧复核。
|
|
||||||
环境:npm/node 不在 PATH,用宿主 bundled node + pnpm(路径见 UI_HANDOFF.md §开工前核对)。
|
|
||||||
|
|
||||||
## 根因分析(已核实,照此修,不要另起方案)
|
|
||||||
|
|
||||||
### P1-A 项目记忆跨工作区混列
|
|
||||||
两处断点,都要修:
|
|
||||||
1. **服务端**:src/routes.ts serveLocalMemory 的五个 GET 分支(status/spaces/documents/memories)
|
|
||||||
与 forget POST 都**不读 workspace 参数**,直接调 manager.xxx()——manager 这些方法
|
|
||||||
全都已支持可选 workspace 尾参(storageStatus(workspace?)/projects(workspace?)/
|
|
||||||
documents(workspace?)/list(options,workspace?,projectId?)/forget(id,rev?,workspace?)),
|
|
||||||
路由层没传而已。
|
|
||||||
2. **客户端**:src-client/sidebar/ProjectMemoryView.tsx 的 status/memories 请求不带
|
|
||||||
workspace(departments/list 带了);src-client/panel/MemoryTab.tsx 定义了
|
|
||||||
workspaceSuffix 助手但**三个请求都没用它**,且组件 props 没有 workspace 来源。
|
|
||||||
|
|
||||||
修法:
|
|
||||||
- routes.ts:每个分支加
|
|
||||||
`const workspace = url.searchParams.get('workspace')?.trim() || undefined`
|
|
||||||
并传入 manager 对应方法;forget 从 body.workspace 取(string trim)。
|
|
||||||
响应形状不变(新增可选入参,向后兼容)。
|
|
||||||
- ProjectMemoryView.tsx:status/memories/documents 请求统一加
|
|
||||||
`workspace === undefined ? '' : '?workspace=' + encodeURIComponent(workspace)`
|
|
||||||
(memories 已有 query 用 &)。workspace 来自 props.scope?.cwd(已有变量)。
|
|
||||||
- MemoryTab.tsx:props 加 workspace?: string;BrainPanel 渲染 MemoryTab 时传入
|
|
||||||
面板持有的当前会话 cwd(与 DepartmentTab 同源;若面板尚无 workspace 状态,
|
|
||||||
加一个经 ctx sessions 面探测的 hook,参考 UI_SPEC U2 的 workspace 取值段)。
|
|
||||||
三个请求用上 workspaceSuffix。
|
|
||||||
- **注意**:local-memory 路由不在部门保护清单内(保护的是 departments-routes.ts),可以改。
|
|
||||||
|
|
||||||
### P1-B 发布包带构建机绝对路径 + 重建不一致
|
|
||||||
根因:tsdown.config.ts brainCssPlugin 的虚拟模块 id 用**绝对路径**
|
|
||||||
(CSS_VIRTUAL_PREFIX + absolute + '.mjs'),rolldown 把虚拟 id 写成产物注释:
|
|
||||||
client/index.js L4193/L5092 出现
|
|
||||||
`// \0dsh-brain-css:C:\Users\qyh15\dsh-brain\src-client\...module.css.mjs`。
|
|
||||||
pack-guard 内容黑名单 /C:[\\/]Users[\\/]/ 命中 → exit 1;换机重建注释路径不同 → 字节不一致。
|
|
||||||
|
|
||||||
修法(tsdown.config.ts):
|
|
||||||
1. resolveId 返回的虚拟 id 改用**仓库相对路径**:
|
|
||||||
`const rel = relative(process.cwd(), absolute).replaceAll('\\','/')`
|
|
||||||
return CSS_VIRTUAL_PREFIX + rel + CSS_VIRTUAL_SUFFIX
|
|
||||||
2. load 里 fileId 还原绝对路径供 readFile/addWatchFile:
|
|
||||||
`const fileId = resolvePath(process.cwd(), virtualId.slice(prefix.length, -suffix.length))`
|
|
||||||
3. filename(classMap 哈希与 tagId)已经是 relative——保持不变,确保哈希稳定。
|
|
||||||
4. 重建后 client/index.js 不得再含 C:\\Users 或 qyh15;
|
|
||||||
隔离副本重建产物与提交产物逐字节一致(pack-guard 的 rebuild-parity 口径)。
|
|
||||||
5. 顺手核 client/index.js 是否还有其他绝对路径注释(grep 'C:' 全文件)。
|
|
||||||
|
|
||||||
### P1-C 诊断搜索日志落错工作区 + 121 字符
|
|
||||||
两个独立小 bug:
|
|
||||||
1. **search 日志 workspace 丢失**:manager.ts searchHits L233 把形参 workspace 直接传给
|
|
||||||
logger;当调用方经 withWorkspace(B) 包裹而**不显式传 workspace 形参**时(remote.run
|
|
||||||
之外的路径、或测试直调),形参为 undefined → BrainLogger.directoryFor('project', undefined)
|
|
||||||
→ projectRootOf(undefined) 回落默认工作区 A。remember 之所以正确,是因为它用
|
|
||||||
`this.workspacePath()`(读 AsyncLocalStorage 上下文)而非形参。
|
|
||||||
修法:searchHits 日志行改用 `const ws = this.workspacePath(workspace)`
|
|
||||||
(workspacePath 已接受可选 override,看 manager 现有签名;若只读上下文则
|
|
||||||
`workspace ?? this.workspacePath()`),与 remember 同口径。
|
|
||||||
同查 forget/projects/documents/storageStatus 各日志行是否同样依赖形参——统一改上下文优先。
|
|
||||||
2. **121 字符**:diagnostics.ts sanitizeValue 截断 `value.slice(0,120)+'…'` = 121。
|
|
||||||
与部门 C7 同款错误。修法:`value.slice(0, MAX_FIELD_CHARS - 1) + '…'`;
|
|
||||||
err 字段同理 `slice(0, MAX_ERR_CHARS - 1)`。规格口径"≤120 含省略号"。
|
|
||||||
|
|
||||||
### P2 diff --check 六处 EOF 空行
|
|
||||||
src-client/api.ts:95 / format.ts:98 / sections/ImportSection.tsx:301 /
|
|
||||||
sections/McpCustomSection.tsx:99 / sections/SyncResolveSection.tsx:118 / styles.ts:368
|
|
||||||
——各删文件末尾多余空行(保留单个终止换行)。
|
|
||||||
|
|
||||||
## 测试补强(修代码同时补断言,防回归)
|
|
||||||
|
|
||||||
1. verify-diagnostics.mjs:
|
|
||||||
- 双工作区 search:withWorkspace(B) 内 memory.search(不显式传 workspace)→
|
|
||||||
日志落 B 的 logs/,A 无该事件(现有测试 L44 只搜默认区,漏了这个路径)。
|
|
||||||
- 截断边界:构造 130 字符 detail 字段 → 落盘值 length ≤120(含省略号)。
|
|
||||||
2. verify-client-build.mjs(或新增 verify-ui-workspace.mjs):
|
|
||||||
- 静态断言 ProjectMemoryView/MemoryTab 的 memories/status/documents 请求含 workspace 拼接。
|
|
||||||
- HTTP 探针:双工作区 A/B 各 remember 一条 → GET memories?workspace=B 只含 B 记录
|
|
||||||
(服务端隔离);GET 不带 workspace 行为与旧版一致(回落 process.cwd())。
|
|
||||||
3. pack-guard 重跑 exit 0;隔离重建 parity changed=[] extra=[]。
|
|
||||||
4. git diff --check exit 0。
|
|
||||||
|
|
||||||
## 执行与验收
|
|
||||||
|
|
||||||
顺序:P1-C(最小)→ P1-A → P1-B → P2 → 测试补强,可合 2–3 个 commit:
|
|
||||||
- fix(diagnostics): route search logs by workspace context and count ellipsis in budget
|
|
||||||
- fix(ui): pass workspace through local-memory routes and both memory views
|
|
||||||
- build(client): relative css virtual ids — no machine paths in bundle
|
|
||||||
- style: trim EOF blank lines flagged by git diff --check
|
|
||||||
(测试补强随对应 fix commit 入库。)
|
|
||||||
|
|
||||||
终验(全绿才报完成):
|
|
||||||
typecheck + build(bundled node + pnpm)
|
|
||||||
node scripts/verify-all.mjs # 41 脚本口径不回退
|
|
||||||
node verify-client-build.mjs # 40 项
|
|
||||||
node verify-diagnostics.mjs # 15 项 + 新断言
|
|
||||||
node verify-departments-wiring.mjs # 25 项(保护期回归)
|
|
||||||
node scripts/pack-guard.mjs # exit 0
|
|
||||||
git diff --check # exit 0
|
|
||||||
隔离副本重建 → client/index.js 与提交逐字节一致
|
|
||||||
|
|
||||||
约束:
|
|
||||||
- 部门保护四文件仍禁改(departments-tools/departments-routes/skill-sync/库层 departments/)。
|
|
||||||
manager.ts 的日志行修改允许(不在保护清单);不改任何存储语义。
|
|
||||||
- 不 push 不打 tag 不升级宿主;修完回报 commit hash + 验证摘要,规划侧复核后由用户定推送。
|
|
||||||
- 与根因分析不符的现状:停下报告,不自行改方案。
|
|
||||||
|
|
@ -1,71 +0,0 @@
|
||||||
# 执行交接单 · UI 改造 U0–U5(给新 DeepSeek 会话)
|
|
||||||
|
|
||||||
日期:2026-11-24
|
|
||||||
仓库:C:\Users\qyh15\dsh-brain(分支 main,基线 af42877,已推送)
|
|
||||||
角色:你是实施者。本单 + docs/plans/ 下四份规格是你的全部任务来源;规划会话不参与实施。
|
|
||||||
你不需要知道之前会话的历史——所有结论都已固化在文档里。
|
|
||||||
|
|
||||||
## 任务一句话
|
|
||||||
|
|
||||||
把 dsh-brain 的 settings-ui 子插件升格为 UI bundle:左侧栏总面板 + better-sidebar
|
|
||||||
项目记忆页签 + .dsh/brain/logs 诊断日志,bundle id 彻底改名 dsh-brain-ui。
|
|
||||||
完成标志:U0–U5 全部 commit、终验命令全绿。预计 4–5 天。
|
|
||||||
|
|
||||||
## 必读文档(按序)
|
|
||||||
|
|
||||||
1. docs/plans/UI_HANDOFF.md ← 本单
|
|
||||||
2. docs/plans/UI_SPEC.md ← 详细施工规格(文件级改动、代码骨架、API 契约、逐卡验收)——执行以此为准
|
|
||||||
3. docs/plans/UI_TASKS.md ← 任务卡总览(U0–U5 依赖与排期)
|
|
||||||
4. docs/plans/LOGGING_SPEC.md ← U5 诊断日志独立规格
|
|
||||||
背景按需查:UI_PLAN.md(决策记录:B 借壳不借芯 + 彻底改名)、DEPARTMENT_PLAN.md(部门概念)。
|
|
||||||
|
|
||||||
## 开工前核对(5 分钟)
|
|
||||||
|
|
||||||
1. git status 干净、git log -1 为 af42877 或其后继(后继应仅 docs/plans 或他人 UI 施工)。
|
|
||||||
若工作树脏:停下报告,不要混提交。
|
|
||||||
2. node verify-departments.mjs → ALL 21 CHECKS PASSED(起点基线)。
|
|
||||||
3. node scripts/verify-all.mjs → 39 scripts 全绿(1 环境跳过)。
|
|
||||||
4. 环境:npm/node 不在系统 PATH。用宿主自带运行时:
|
|
||||||
node: C:/Users/qyh15/.dsh/dsh-runtimes/dsh-primary-runtime/dependencies/node/bin/node.exe
|
|
||||||
(或 C:/Users/qyh15/AppData/Local/Programs/DeepSeek Harness/resources/runtime/primary-runtime/dependencies/node/bin/node.exe)
|
|
||||||
pnpm: C:/Users/qyh15/.dsh/dsh-runtimes/dsh-primary-runtime/dependencies/pnpm/bin/pnpm.mjs
|
|
||||||
npm run X 等价于 node <pnpm.mjs> run X;tsc 直接 node node_modules/typescript/bin/tsc。
|
|
||||||
|
|
||||||
## 执行顺序
|
|
||||||
|
|
||||||
U0(client 构建链)→ U1(左栏面板骨架)→ ┬ U2(记忆/部门页签)┐
|
|
||||||
├ U3(better-sidebar 页签)├→ U4(改名+终验)
|
|
||||||
└ U5(诊断日志)──────────┘
|
|
||||||
|
|
||||||
U2/U3/U5 可并行。每卡独立 commit,文案按 UI_SPEC.md 各卡给定。
|
|
||||||
|
|
||||||
## 硬约束(违反即返工)
|
|
||||||
|
|
||||||
- **保护期禁改四文件**(GPT 部门复验未结束):src/memory/departments-tools.ts、
|
|
||||||
src/settings-ui/departments-routes.ts、src/skill-sync.ts、src/local-memory/departments/。
|
|
||||||
可以 import 它们的导出(如 departmentSnippet)。U5 的 skill-sync/cloud 埋点因此滞后,
|
|
||||||
复验通过后单独小 commit 补,不阻塞本批。
|
|
||||||
- 运行时零新依赖:tsdown ^0.22.2 已在 devDependencies;react 走宿主 shim externals。
|
|
||||||
- client 产物必须仍是单文件 window.__ModuleLoader__ IIFE,id:'dsh-brain' 不变
|
|
||||||
(子插件 row id 才改 dsh-brain-ui,两者是两回事)。
|
|
||||||
- 抄 vendor/dsh-mnemon 源码处保留 MIT 出处注释。
|
|
||||||
- 样式走 --dsw-alias-* token,无纯白纯黑硬编码(verify-theme 会查)。
|
|
||||||
- lib/ 与 client/index.js 构建产物随卡入库(仓库约定)。
|
|
||||||
- 每卡 commit 前跑该卡验证命令;遇到与规格不符的现状:停下报告差异,等规划侧修订。
|
|
||||||
- 不 push 不打 tag 不升级宿主 profile——完成后回报,由用户决定推送与升级时机。
|
|
||||||
|
|
||||||
## 终验(U4 末尾,全部通过才报完成)
|
|
||||||
|
|
||||||
node <pnpm> run typecheck && node <pnpm> run build
|
|
||||||
node scripts/verify-all.mjs # 39+ 脚本口径不回退
|
|
||||||
node verify-plugin-entry.mjs # 含 './settings-ui' 别名兼容断言
|
|
||||||
node verify-client-build.mjs # U0 新增
|
|
||||||
node verify-diagnostics.mjs # U5 新增
|
|
||||||
node <pnpm> pack --dry-run # files 含 client/index.js、lib/entries/ui.js
|
|
||||||
|
|
||||||
## 交付物
|
|
||||||
|
|
||||||
1. 每卡一个 commit(U0/U1/U2/U3/U5/U4,共 6 个左右),回报 hash + 验证摘要。
|
|
||||||
2. 偏离规格的决定逐条列原因,交用户追认。
|
|
||||||
3. 完成后通知用户:可转 GPT 做 UI 验收(验收单由规划侧另出),并触发宿主升级批次
|
|
||||||
(升级前提:本批全绿 + 部门复验通过;升级卡规划侧另备)。
|
|
||||||
|
|
@ -1,197 +0,0 @@
|
||||||
# settings-ui → UI 改造方案(总面板 + better-sidebar 项目记忆入口)
|
|
||||||
|
|
||||||
版本:v1(规划稿,本会话只做规划,不实施)
|
|
||||||
日期:2026-11-24
|
|
||||||
基线:accc1c3(D1+D2 部门接线已入库并推送)。
|
|
||||||
需求(用户原话):"把 setting ui 改成 UI,因为我需要有左侧栏入口打开的总面板,
|
|
||||||
有需要挂载在 better-sidebar 的项目记忆入口。"
|
|
||||||
|
|
||||||
## 0. 宿主接入面实测结论(2026-11-24,全部来自本机已装插件源码)
|
|
||||||
|
|
||||||
三个真实可用的注册面,各有现成范例:
|
|
||||||
|
|
||||||
| 面 | 机制 | 范例(本机已装) | 效果 |
|
|
||||||
| --- | --- | --- | --- |
|
|
||||||
| 左侧栏全局面板 | client 半区 ctx.slots.inject('sidebar.panellist', …) 注册行 + ctx.slots.inject('main', …) 注册页面 | @linxin666/dsh-client-ui-task-board v0.4.20(lib/client.js native-panel 段) | 与宿主"插件/日程"页同级的左栏入口,点开占中列主区;shell 拥有行盒/标签/高亮/折叠轨 |
|
|
||||||
| better-sidebar 页签 | client 半区 inject ['betterSidebar'],ctx.betterSidebar.registerTab(descriptor) | dsh-better-sidebar 0.32.1 README_ZH 最小示例 + lib/types/client/service.d.ts | 右侧栏/底部工作台新增页签类型,按会话 scope 渲染 |
|
|
||||||
| 设置卡(现状保留) | ctx.slots.inject('settings.section' / 'plugins.bundle.config') | dsh-brain client/index.js 现有 apply() | 设置页内嵌卡,不动 |
|
|
||||||
|
|
||||||
关键契约细节(照抄范例,不自造):
|
|
||||||
- panellist 行 options:{ name:'sidebar.panellist', id:<panelId>, order:<n>, label:()=>string },
|
|
||||||
组件只画 glyph(svg,带 data-dsh-panel-entry=<panelId> 语义锚点);
|
|
||||||
Plugins order=0、Schedule=10、task-board=20 → 本项目建议 order=30。
|
|
||||||
- main 页 options:{ name:'main', key:<panelId>, inject:()=>({…}) },
|
|
||||||
组件收 shell 注入的 face;layout 只在该面板选中时挂载,其余时间中列归会话。
|
|
||||||
- registerTab descriptor:{ id:'dsh-brain:memory', title, description, icon?, order?,
|
|
||||||
single:true, component:(props:TabComponentProps)=>ReactNode };
|
|
||||||
props 含 ctx/store/scope/sessionId/tab/visible——**visible=false 时暂停轮询**(契约明说)。
|
|
||||||
single:true = 单实例,重复打开聚焦已有页签。
|
|
||||||
- 两个 seat 都经 slots.inject 延迟触发,与 shell 加载顺序无关;shell 不支持时静默不挂。
|
|
||||||
- better-sidebar 未安装时 registerTab 面不存在 → 必须优雅降级(见 §3)。
|
|
||||||
|
|
||||||
|
|
||||||
## 0.5 复用 Mnemon 面板的评估(2026-11-24 用户提议:"mnemon 里面有面板,拿他的面板改")
|
|
||||||
|
|
||||||
**事实核对(全部实测)**:
|
|
||||||
- Mnemon 确实有完整面板,且**正在你宿主里运行**:desktop profile 的 mnemon 行
|
|
||||||
disabled:false,左栏已有"记忆系统"(panel id 'mnemon')与技能页(order 31),
|
|
||||||
better-sidebar 页签 'dsh-mnemon:memory'(order 55,single)。
|
|
||||||
- vendor/dsh-mnemon fork 含全部客户端源码:src/client 96 文件 / 737 KB
|
|
||||||
(45 tsx + 40 ts + 9 css),MnemonWorkbench.tsx 单文件 49 KB。
|
|
||||||
- **接入面可直接抄**:native-sidebar.tsx(panellist+main 双 seat、usePanelInfo
|
|
||||||
激活判定、window-drag band)、better-sidebar.tsx(registerTab + internal/service
|
|
||||||
事件 reconcile 热插拔)、HeldSeat/ExternalStore 模式——比 task-board 范例更完整。
|
|
||||||
- **但 Workbench 本体不能直接搬**:数据面走 connection.rpc.call(MNEMON_*_CHANNEL)
|
|
||||||
的宿主 RPC(9 条通道),类型耦合 ../host/protocol.ts(client 内 52 处 import)
|
|
||||||
与 @deepseek-ai/dsh-client-ui-slots/layout(58 处);渲染的是 Mnemon 运行时视图
|
|
||||||
(MemoryViewDashboard/策略/组件目录),不是 dsh-brain 的 HTTP JSON。
|
|
||||||
直接改 = 给 LocalMemoryManager 假扮整个 Mnemon host RPC 面,或把 49 KB Workbench
|
|
||||||
逐页改写到 HTTP——两者都比手写面板贵。
|
|
||||||
- **存在一条真复用路(选项 C)**:dsh-brain 已有 native provider
|
|
||||||
(src/mnemon/native.ts,descriptor id 'dsh-brain-native',经 vendored provider-sdk
|
|
||||||
暴露 verify-mnemon-native 6 项全绿)。把它注册进**正在运行的 Mnemon 宿主**当一个
|
|
||||||
source,Mnemon 现成面板即可浏览/搜索/编辑 dsh-brain 本地记忆——零新 UI。
|
|
||||||
代价:①依赖外部 dsh-mnemon@0.5.48 与 fork 0.5.54-dsh.1 的 provider 协议兼容性
|
|
||||||
(需实测);②面板是 Mnemon 品牌与概念(空间/来源/策略),部门、技能同步、
|
|
||||||
连接上报等 dsh-brain 自有面不在其中;③与 P3"功能移除精简"方向相悖
|
|
||||||
(长期要摆脱双记忆系统并存)。
|
|
||||||
|
|
||||||
**三选项对比**:
|
|
||||||
|
|
||||||
| 选项 | 做法 | 工作量 | 得到 | 风险 |
|
|
||||||
| --- | --- | --- | --- | --- |
|
|
||||||
| A 原方案 | 手写 React 总面板 + 侧栏页签(U1–U4) | 中(3–5 天) | 完全自有品牌与概念,部门/技能/连接全纳入 | 无外部依赖;样式从零 |
|
|
||||||
| B 借壳不借芯(推荐) | A 的骨架 + **抄 Mnemon 接入层代码**(双 seat 注册、HeldSeat、reconcile、css module 布局样式),内容页对 HTTP 手写 | 中偏小(2–4 天) | 接入层经过生产验证,少踩坑;数据面干净 | 需引入 client 构建链(tsx/css modules → 单文件 bundle,见下) |
|
|
||||||
| C 寄生 Mnemon | native provider 注册进运行中的 Mnemon,用它的现成面板 | 小(1–2 天,若协议兼容) | 立即有成熟面板可看本地记忆 | 双系统耦合、品牌混淆、与 P3 精简方向冲突;部门等自有面无着落 |
|
|
||||||
|
|
||||||
**推荐:B 为主,C 作可选过渡**——若你想"今天就能在面板里看到本地记忆",
|
|
||||||
先做 C 的 provider 注册(小活,独立验收),再按 B 建自有面板,建成后 C 可撤。
|
|
||||||
不推荐整体搬 Workbench(数据面假扮成本 > 手写)。
|
|
||||||
|
|
||||||
**B 的构建链决策点**:现有 client/index.js 是手写无打包器(__ModuleLoader__ 契约)。
|
|
||||||
抄 Mnemon 的 tsx/css module 代码需要加一条 client 构建(tsup/esbuild → 单文件 IIFE,
|
|
||||||
产物仍写 client/index.js 入库,宿主加载方式不变)。这是 devDependency 级新增,
|
|
||||||
不违反"运行时零新依赖",但要在 U1 前定案。若坚持零构建,则只抄逻辑不抄 tsx,
|
|
||||||
样式手写等价物(工作量回到 A)。
|
|
||||||
|
|
||||||
## 1. 目标形态
|
|
||||||
|
|
||||||
左侧栏 [Brain] 行(order 30)
|
|
||||||
└─ 总面板(main slot,key='dsh-brain')
|
|
||||||
页签:概览 / 记忆 / 部门 / 技能 / MCP / 连接与上报
|
|
||||||
—— 现有 client/index.js 三页签 + settings-ui page.ts 八卡片的全部能力
|
|
||||||
收进一个 React 面板,数据仍走同源公开路由,零新后端。
|
|
||||||
better-sidebar 页签 "项目记忆"(id='dsh-brain:memory',single)
|
|
||||||
└─ 当前会话项目的记忆视图:空间状态 / 记忆列表 / 搜索 / 文档 / 部门召回
|
|
||||||
按 scope.sessionId → 会话 cwd → projectId 定位项目空间。
|
|
||||||
设置卡(settings.section)保留为精简入口:状态 + 跳转总面板按钮。
|
|
||||||
/dsh-brain 独立 HTML 页保留为兜底(无 shell seat 的环境仍可用)。
|
|
||||||
|
|
||||||
## 2. bundle 改名与边界
|
|
||||||
|
|
||||||
- src/entries/settings-ui.ts → src/entries/ui.ts;export name 'dsh-brain-settings-ui'
|
|
||||||
→ 'dsh-brain-ui';package.json exports './settings-ui' → './ui'(保留 './settings-ui'
|
|
||||||
别名导出指向同一文件,老 profile 行不断)。
|
|
||||||
- cordis.patch.yml insert 行 id 同步改 dsh-brain-ui;**兼容风险**:宿主 Settings→Plugins
|
|
||||||
的禁用行按旧 id 写死过(profile patch 里可能有 '- id: dsh-brain-settings-ui'),
|
|
||||||
改名后旧禁用行失效 → 迁移说明必须写清,或保留旧 id 只改显示名(见 §6 决策点)。
|
|
||||||
- kernel BrainBundle 类型 'settings-ui' → 'ui'(isActive/routeDeps 同步);
|
|
||||||
路由归属不变:page + core routes(status/capabilities/config/migrate/local-memory/departments)
|
|
||||||
仍由该 entry 注册,legacy /cloud-memory 别名自动跟随。
|
|
||||||
- 五子插件结构不变,只是第五个从"设置页"升格为"UI 面板";其余四 bundle 零改动。
|
|
||||||
|
|
||||||
## 3. 切片(每片独立 commit + verify)
|
|
||||||
|
|
||||||
### U1 · client 总面板骨架(左栏入口)
|
|
||||||
- client/index.js:新增 panelId='dsh-brain';apply() 里加两个 slots.inject
|
|
||||||
(panellist 行 + main 页),照 task-board native-panel 模式;glyph 自绘 svg。
|
|
||||||
- main 页组件 = 现有 SettingsCard 升格为 BrainPanel:页签壳 + 现有三页签内容复用,
|
|
||||||
新增"概览"页签(status/capabilities 聚合,数据已有)。
|
|
||||||
- 设置卡注册保留但瘦身:状态摘要 + "打开总面板"按钮(经 shell 面板切换 API;
|
|
||||||
若 seat 不可用则回退 window.open('/dsh-brain'))。
|
|
||||||
- 降级:slots 里没有 sidebar.panellist/main seat 时(web 精简 shell),
|
|
||||||
仅保留设置卡 + 独立页,console.info 一次,不报错。
|
|
||||||
- verify:verify-plugin-entry.mjs 更新入口名单;新增 verify-ui-panel.mjs
|
|
||||||
(静态断言 client bundle 含两 seat 注册、panelId、降级分支;形状检查为主,
|
|
||||||
DOM 行为留给 U4 冒烟)。
|
|
||||||
|
|
||||||
### U2 · 记忆/部门页签并入总面板
|
|
||||||
- "记忆"页签:消费 /dsh-brain/local-memory(status/spaces/documents/memories/forget),
|
|
||||||
列表 + 搜索 + 分页(limit/offset 路由已支持)。
|
|
||||||
- "部门"页签:消费 /dsh-brain/departments(list/create/update/disable/checkpoint/recall/resume),
|
|
||||||
表单走同源 POST(sameOrigin 闸门天然满足)。
|
|
||||||
- 两页签均为 React 手写(沿用 client/index.js 无打包器约定),不引新依赖。
|
|
||||||
- verify:verify-ui-panel.mjs 扩展路由消费断言;手工冒烟脚本起真实 server 核对 JSON 形状。
|
|
||||||
|
|
||||||
### U3 · better-sidebar "项目记忆"页签
|
|
||||||
- client apply():探测 ctx.betterSidebar(typeof registerTab === 'function');
|
|
||||||
存在则 ctx.effect(() => ctx.betterSidebar.registerTab({...})),不存在静默跳过。
|
|
||||||
- descriptor:id='dsh-brain:memory',title='项目记忆',description 写明
|
|
||||||
"当前会话项目的本地记忆:空间/条目/搜索/部门召回",single:true,order 建议 60。
|
|
||||||
- component(props):scope.sessionId → 会话 header.cwd(经 ctx sessions 面或
|
|
||||||
status 路由带回)→ 项目空间视图;visible=false 暂停一切轮询。
|
|
||||||
- 内容 = U2 记忆页签的项目子集(只读浏览 + 搜索 + forget),不做创建部门等重操作
|
|
||||||
(重操作引导去总面板)。
|
|
||||||
- 降级链:better-sidebar 未装 → 无页签(总面板不受影响);装了但 fiber 卸载 → disposer 自动清理。
|
|
||||||
- verify:verify-ui-panel.mjs 断言 registerTab 探测与 disposer;
|
|
||||||
真实宿主冒烟(U4)确认页签出现在 + 菜单。
|
|
||||||
|
|
||||||
### U4 · 改名落地 + 终验
|
|
||||||
- entries/settings-ui.ts → entries/ui.ts(含 exports 别名、patch 行、kernel 类型)。
|
|
||||||
- 全量门禁:typecheck + build + verify-all(39 脚本口径不回退)+ verify-plugin-entry。
|
|
||||||
- 宿主冒烟(升级 profile 依赖后):左栏出现 Brain 行 → 点开总面板六页签;
|
|
||||||
better-sidebar + 菜单出现"项目记忆";设置卡仍在;/dsh-brain 独立页仍可达。
|
|
||||||
- npm pack --dry-run:files 清单不变(client/lib 入库),exports 新增 './ui'。
|
|
||||||
|
|
||||||
## 4. 数据面(零新后端原则)
|
|
||||||
|
|
||||||
总面板与侧栏页签全部消费既有公开路由:
|
|
||||||
status / capabilities / config / local-memory/* / departments/* / skills / market / sync / clients / migrate。
|
|
||||||
唯一可能的新增:GET /dsh-brain/local-memory/memories 已支持 limit/offset,够用;
|
|
||||||
项目定位若需要"会话→cwd"映射,优先用 better-sidebar props.scope 自带信息,
|
|
||||||
其次 status 路由扩展一个 workspace 字段(小改,单独评审)。
|
|
||||||
**不新增写路由**;所有写操作沿用 sameOrigin 闸门与 revision 冲突语义。
|
|
||||||
|
|
||||||
## 5. 边界与约束
|
|
||||||
|
|
||||||
- client/index.js 保持手写无打包器(宿主 __ModuleLoader__ require shim 契约,
|
|
||||||
文件头注释已写明);不引 React 之外的运行时依赖。
|
|
||||||
- 面板/页签组件必须容错:路由失败显示可行动错误条,不白屏(沿用 CardBoundary 模式)。
|
|
||||||
- better-sidebar 是可选增强:未安装时一切功能经总面板/独立页可达,不硬依赖。
|
|
||||||
- 部门私有空间不上云边界不变;侧栏页签只读浏览为主。
|
|
||||||
- 皮肤语义锚点:glyph 带 data-dsh-panel-entry,面板根带 data-dsh-plugin="dsh-brain"
|
|
||||||
(对齐 task-board 的 L2 皮肤契约,避免主题适配找不到行)。
|
|
||||||
|
|
||||||
## 6. 决策记录与待决点
|
|
||||||
|
|
||||||
**已定(2026-11-24 23:30,用户拍板):选项 B 借壳不借芯**——抄 Mnemon 接入层
|
|
||||||
(native-sidebar/better-sidebar 双 seat 注册、HeldSeat、reconcile)与 css module 布局样式,
|
|
||||||
内容页对 dsh-brain 自有 HTTP 路由手写;接受新增 client 构建 devDependency
|
|
||||||
(tsup/esbuild → 单文件 IIFE,产物仍 client/index.js 入库,宿主 __ModuleLoader__ 加载方式不变)。
|
|
||||||
不做 C 寄生过渡。构建链选型在 U1 任务卡定案(倾向 tsup,与 vendor fork 同链)。
|
|
||||||
|
|
||||||
**已定(2026-11-24 23:33,用户拍板):bundle id 彻底改名 dsh-brain-ui**——
|
|
||||||
exports 保留 './settings-ui' 别名指向同一文件,老 profile 行不断;
|
|
||||||
旧 id 的宿主禁用/配置行不自动改写(越权),entry 探测到旧行时 logger.warn 提示,
|
|
||||||
README 升级说明写明。详见 UI_TASKS.md U4 改名清单。
|
|
||||||
|
|
||||||
可执行任务卡:docs/plans/UI_TASKS.md(U0 构建链→U1 面板骨架→U2 记忆/部门页签→
|
|
||||||
U3 better-sidebar 页签→U4 改名+终验;tsdown 已在 devDeps,无需新增依赖)。
|
|
||||||
|
|
||||||
以下为原待决点存档:
|
|
||||||
|
|
||||||
1. **bundle id 改名策略**:彻底改 'dsh-brain-ui'(干净,但老 profile 禁用行需迁移)
|
|
||||||
vs 保留 id 'dsh-brain-settings-ui' 只改显示名与职责(零迁移成本)。建议后者起步,
|
|
||||||
发布 0.11.0 时再彻底改名。
|
|
||||||
2. 总面板页签顺序与命名:概览/记忆/部门/技能/MCP/连接与上报(可调)。
|
|
||||||
3. better-sidebar 页签是否也要"部门"独立页签(本轮建议只做一个"项目记忆",部门在总面板)。
|
|
||||||
4. 排期位置:建议插在 P1 仓库整理之前、GPT 验收 D1+D2 之后(UI 改造会动 client 与
|
|
||||||
entries,先让部门验收落定,避免验收基线漂移)。
|
|
||||||
|
|
||||||
## 7. 验收(新增 verify-ui-panel.mjs + 宿主冒烟)
|
|
||||||
|
|
||||||
- 静态:client bundle 含 panellist/main/betterSidebar 三注册面与各自降级分支;
|
|
||||||
panelId/descriptor id 唯一;exports 别名齐全。
|
|
||||||
- 门禁:typecheck/build/verify-all 全绿,39 脚本口径不回退。
|
|
||||||
- 宿主冒烟清单(U4):左栏行、总面板六页签、侧栏页签、设置卡、独立页五处逐一截图核对。
|
|
||||||
- 发布件:npm pack --dry-run 比对,client/index.js 与 lib/entries/ui.js 在包内。
|
|
||||||
|
|
@ -1,260 +0,0 @@
|
||||||
# UI 改造详细实施规格(给 DeepSeek 执行)
|
|
||||||
|
|
||||||
版本:v1 · 2026-11-24 23:40
|
|
||||||
基线:5fef328(main,已推送)。开工前 git status 必须干净。
|
|
||||||
决策:B 借壳不借芯 + bundle id 彻底改名 dsh-brain-ui(用户拍板)。
|
|
||||||
本规格是 UI_TASKS.md 的展开版:每卡给出文件级改动、可抄源码位置、代码骨架、验收命令。
|
|
||||||
U5 诊断日志独立规格:LOGGING_SPEC.md(.dsh/brain/logs JSONL,脱敏/滚动/开关,随本批交付)。
|
|
||||||
冲突保护:GPT 部门复验未结束前,**禁改** src/memory/departments-tools.ts、
|
|
||||||
src/settings-ui/departments-routes.ts、src/skill-sync.ts、src/local-memory/departments/。
|
|
||||||
(可以 import 它们的导出,如 departmentSnippet。)
|
|
||||||
|
|
||||||
═══════════════════════════════════════════
|
|
||||||
U0 · client 构建链落地(0.5–1 天)
|
|
||||||
═══════════════════════════════════════════
|
|
||||||
|
|
||||||
## 现状事实(已实测)
|
|
||||||
- client/index.js:3735 行手写 IIFE,window.__ModuleLoader__.load({id:'dsh-brain',factory})。
|
|
||||||
- devDependencies 已含 tsdown ^0.22.2、typescript ^5.6.0、react ^18.2.0、@types/react。
|
|
||||||
**不需要新增任何依赖。**
|
|
||||||
- vendor/dsh-mnemon/tsdown.config.ts 的 client 段是现成模板(banner/intro/footer、
|
|
||||||
css modules 内联插件 clientCssPlugin、react externals)。
|
|
||||||
- 现有 client 结构图(迁移按此切模块):
|
|
||||||
L22 API 常量 / L49 request / L67 postJson / L71 messageOf / L79 bridgeCall(MCP)
|
|
||||||
L108-235 格式化与标签表 / L246-612 styles 对象 / L613-762 基础组件(Pill,Banner,Field,Btn,IconBtn,Switch,Toggle,Section)
|
|
||||||
L774 MarketSection / L929 SyncResolveSection / L1038 McpCustomSection / L1127 McpConfigSection
|
|
||||||
L1259 ImportSection / L1551 SettingsCard(主体,含 connection/skills/mcp 三页签) / L3680 CardBoundary / L3704 apply
|
|
||||||
|
|
||||||
## 改动清单
|
|
||||||
1. 新建 src-client/ 目录,把上述结构迁为 TS 模块(行为等价优先,不重构逻辑):
|
|
||||||
src-client/index.ts ← 入口,导出 {apply, inject:['slots'], name:'dsh-brain'}
|
|
||||||
src-client/api.ts ← API 常量 + request/postJson/messageOf/bodyError
|
|
||||||
src-client/format.ts ← formatTime/formatIso/formatBytes/shortHash/readStored/store + 标签表
|
|
||||||
src-client/components.tsx ← Pill/Banner/Field/Btn/IconBtn/Switch/Toggle/Section/CardBoundary
|
|
||||||
src-client/bridge.ts ← bridgeCall/bridgeMessage(MCP 宿主桥探测)
|
|
||||||
src-client/sections/*.tsx ← MarketSection/SyncResolveSection/McpCustomSection/McpConfigSection/ImportSection
|
|
||||||
src-client/SettingsCard.tsx ← 主体(三页签状态机原样搬)
|
|
||||||
src-client/styles.ts ← 现 styles 对象暂原样保留(U1 起新样式走 .module.css)
|
|
||||||
迁移规则:var→const/let、function 组件补 props 类型(宽松 any 起步,后续收紧)、
|
|
||||||
h=React.createElement 保留或改 jsx(tsdown jsx:'automatic' 需 react/jsx-runtime external,
|
|
||||||
建议保留 h 写法减少差异)。
|
|
||||||
2. 新建根 tsdown.config.ts,只含 client 段(host lib 仍走 tsc,不动):
|
|
||||||
```ts
|
|
||||||
import type { UserConfig } from 'tsdown'
|
|
||||||
const PLUGIN_ID = 'dsh-brain'
|
|
||||||
export default {
|
|
||||||
name: PLUGIN_ID + '/client',
|
|
||||||
entry: { index: 'src-client/index.ts' },
|
|
||||||
outDir: 'client',
|
|
||||||
format: 'cjs',
|
|
||||||
platform: 'browser',
|
|
||||||
target: 'es2022',
|
|
||||||
fixedExtension: false,
|
|
||||||
outExtensions: () => ({ js: '.js' }),
|
|
||||||
dts: false, sourcemap: false, clean: false,
|
|
||||||
deps: { neverBundle: [/^react(?:\/.*)?$/, /^react-dom(?:\/.*)?$/] },
|
|
||||||
define: { 'process.env.NODE_ENV': '"production"' },
|
|
||||||
plugins: [clientCssPlugin()], // U1 再启用;U0 可先空数组
|
|
||||||
outputOptions: {
|
|
||||||
banner: `window.__ModuleLoader__.load({ id: '${PLUGIN_ID}', factory: (require) => {`,
|
|
||||||
intro: 'var module = { exports: {} }; var exports = module.exports;',
|
|
||||||
footer: 'return module.exports; } });',
|
|
||||||
},
|
|
||||||
} satisfies UserConfig
|
|
||||||
```
|
|
||||||
css 插件从 vendor/dsh-mnemon/tsdown.config.ts 的 clientCssPlugin 抄(lightningcss
|
|
||||||
transform → style 注入),vendor 已是 devDep 链内可用?——**核对 lightningcss 是否
|
|
||||||
已在 node_modules(tsdown 自带依赖)**;若不可直接 import,用 tsdown 内置 css 处理
|
|
||||||
(modules 选项)替代,产物同样内联。U0 阶段无 css 文件,插件可后置到 U1。
|
|
||||||
3. package.json scripts:
|
|
||||||
"build:client": "tsdown"
|
|
||||||
"build": "tsc -p tsconfig.build.json && tsdown"
|
|
||||||
"prepack": "tsc -p tsconfig.build.json && tsdown"
|
|
||||||
tsconfig.json / tsconfig.build.json 的 include 排除 src-client(避免 host tsc 双编译);
|
|
||||||
新增 tsconfig.client.json(extends 根,include src-client,jsx react-jsx,noEmit true)
|
|
||||||
并把 typecheck 改为 "tsc -p tsconfig.json --noEmit && tsc -p tsconfig.client.json --noEmit"。
|
|
||||||
4. 旧手写版备份:cp client/index.js artifacts/analysis/client-legacy.js(artifacts 已 gitignore)。
|
|
||||||
5. 新增 verify-client-build.mjs(仓库根,harness 风格照抄 verify-departments.mjs):
|
|
||||||
- 读 client/index.js 断言:含 __ModuleLoader__.load、id:'dsh-brain'、
|
|
||||||
'settings.section'、'plugins.bundle.config'、三页签标签(连接与上报/技能管理/MCP 管理)。
|
|
||||||
- 用 vm + react shim require 产物,调 apply({slots:{inject:(seat,cb)=>{…记录}}}),
|
|
||||||
断言两个 seat 注册回调可触发、组件渲染不抛(react shim 用 node_modules/react 真身,
|
|
||||||
createElement 返回普通对象即可,不需要 DOM)。
|
|
||||||
- 与 artifacts/analysis/client-legacy.js 做"行为面"对比:两版 apply 注册的 seat/options
|
|
||||||
JSON 形状一致(order/id/key/label() 输出)。
|
|
||||||
|
|
||||||
## 验收
|
|
||||||
npm run typecheck && npm run build && node verify-client-build.mjs
|
|
||||||
node scripts/verify-all.mjs # 39 脚本口径不回退
|
|
||||||
git status:client/index.js 变更 + src-client/ 新增 + 配置,全部入库。
|
|
||||||
commit:build(client): migrate hand-written bundle to tsdown with equivalent output
|
|
||||||
|
|
||||||
═══════════════════════════════════════════
|
|
||||||
U1 · 左栏总面板骨架(1 天)
|
|
||||||
═══════════════════════════════════════════
|
|
||||||
|
|
||||||
## 可抄源码(vendor/dsh-mnemon/src/client/,MIT 保留声明)
|
|
||||||
- shared/store.ts ExternalStore(~40 行,整抄改前缀)
|
|
||||||
- shared/dom-seat.ts HeldSeat + createRafCoalescer(整抄)
|
|
||||||
- native-sidebar.tsx mountMnemonSidebarNavigation 的双 seat 注册模式:
|
|
||||||
ctx.slots.inject('main', () => ctx.slots.inject('sidebar.panellist', () => {
|
|
||||||
register main {name:'main', key:PANEL_ID, inject:()=>({…})}
|
|
||||||
register panellist {name:'sidebar.panellist', id:PANEL_ID, order:30, label:()=>'Brain'}
|
|
||||||
}))
|
|
||||||
**简化**:Mnemon 的 fallback DOM 注入(mountMnemonSidebarEntry/coordinateSidebarPanels)
|
|
||||||
不抄——seat 不可用时本项目回退设置卡+独立页,不做 DOM 接管。
|
|
||||||
- MnemonWorkspace.module.css(2KB 全文已核):nativeWorkspace/windowDragBand/entry 系列
|
|
||||||
抄骨架,data-dsh-brain-mnemon-* 属性改 data-dsh-brain-*;配色全走
|
|
||||||
--dsw-alias-* token(verify-theme 口径:无纯白纯黑硬编码)。
|
|
||||||
- panelInfo 激活判定:ctx.layout.panelInfo.{getSnapshot,subscribe},
|
|
||||||
activePanelId !== PANEL_ID 时暂停轮询(照抄 MnemonMainPanel 的 usePanelInfo)。
|
|
||||||
|
|
||||||
## 新文件
|
|
||||||
src-client/panel/seat.ts ← ExternalStore/HeldSeat(抄改)
|
|
||||||
src-client/panel/register.ts ← registerBrainPanel(ctx): 双 seat + disposer;
|
|
||||||
PANEL_ID='dsh-brain';order 30;
|
|
||||||
glyph svg data-dsh-panel-entry="dsh-brain";
|
|
||||||
seat 缺席静默(inject 回调不触发即降级)
|
|
||||||
src-client/panel/BrainPanel.tsx ← 页签壳:概览/记忆/部门/技能/MCP/连接与上报;
|
|
||||||
本轮实现"概览"+"连接与上报",其余占位;
|
|
||||||
根 div data-dsh-plugin="dsh-brain" + windowDragBand
|
|
||||||
src-client/panel/Overview.tsx ← GET /dsh-brain/status + /capabilities 聚合卡片
|
|
||||||
(版本、五 bundle 开关态、本地记忆状态、同步统计),
|
|
||||||
15s 轮询仅激活时跑
|
|
||||||
src-client/panel/BrainPanel.module.css ← 抄 vendor css 骨架
|
|
||||||
src-client/panel/brain-icon.tsx ← 脑形 glyph(参考 vendor memory-icon.tsx 简化自绘)
|
|
||||||
|
|
||||||
## 改动
|
|
||||||
- src-client/index.ts apply:保留 settings.section/plugins.bundle.config 注册;
|
|
||||||
新增 registerBrainPanel(ctx)(经 ctx.effect 挂 disposer)。
|
|
||||||
- SettingsCard 瘦身:settings.section 的卡内容改为状态摘要 + "打开总面板"按钮:
|
|
||||||
onClick → typeof ctx.layout?.selectPanel==='function' ? ctx.layout.selectPanel('dsh-brain')
|
|
||||||
: window.open('/dsh-brain')。原三页签完整内容迁入 BrainPanel 的对应页签
|
|
||||||
(connection 本轮搬,skills/mcp 在 U2 后随占位替换——**本轮先把现有 SettingsCard
|
|
||||||
整体作为"连接与上报"页签内容复用,避免大改**)。
|
|
||||||
- inject 声明:['slots'] 不变(layout 经 ctx.get 探测,不硬依赖)。
|
|
||||||
|
|
||||||
## 验收
|
|
||||||
verify-client-build.mjs 扩展:panellist/main 注册断言、PANEL_ID、order 30、
|
|
||||||
降级分支(无 seat 时 apply 不抛)、glyph 语义锚点字符串。
|
|
||||||
typecheck + build + verify-all 全绿。
|
|
||||||
commit:feat(ui): left-rail Brain panel with overview and connection tabs
|
|
||||||
|
|
||||||
═══════════════════════════════════════════
|
|
||||||
U2 · 记忆/部门页签(1 天,可与 U3 并行)
|
|
||||||
═══════════════════════════════════════════
|
|
||||||
|
|
||||||
## API 契约(已实测响应形状)
|
|
||||||
GET /dsh-brain/local-memory/status → {ok,provider:'local',globalRoot,projectRoot,spaces:{global,project},cloudSyncEnabled,localMemoryEnabled}
|
|
||||||
GET /dsh-brain/local-memory/spaces → {ok,spaces:[…]}
|
|
||||||
GET /dsh-brain/local-memory/documents → {ok,documents:[…]}
|
|
||||||
GET /dsh-brain/local-memory/memories?limit&offset → {ok,total,items:[{id,scope,content,category,tags,source,revision,updatedAt}]}
|
|
||||||
POST /dsh-brain/local-memory/forget {id,expectedRevision?} → 同源闸门
|
|
||||||
GET /dsh-brain/departments/list?scope → {ok,departments:[Department]}
|
|
||||||
POST /dsh-brain/departments/create {name,role?,scope?,skills?,allowedTools?,readGlobal?,readProject?,workspace?}
|
|
||||||
POST /dsh-brain/departments/update {id,…patch,expectedRevision?,workspace?}
|
|
||||||
POST /dsh-brain/departments/disable {id,expectedRevision?,workspace?}
|
|
||||||
POST /dsh-brain/departments/checkpoint {id,currentTask?,handoff?,expectedRevision?,workspace?}
|
|
||||||
GET /dsh-brain/departments/recall?id&query&k&workspace → {ok,hits:[{origin,record,content,contentSnippet}]}
|
|
||||||
POST /dsh-brain/departments/resume {id,host?,hostSessionId?,workspace?}
|
|
||||||
错误码:400 name-required/invalid-json;403 origin-rejected;404 department_not_found;
|
|
||||||
409 revision_conflict/department_disabled;503 local-memory-disabled/departments-unavailable。
|
|
||||||
|
|
||||||
## 新文件
|
|
||||||
src-client/panel/MemoryTab.tsx ← 空间状态卡 + 记忆列表(分页 limit 50)+ 前端搜索过滤
|
|
||||||
+ forget 按钮(确认弹窗)+ 文档列表只读
|
|
||||||
src-client/panel/DepartmentTab.tsx ← 部门列表(name/scope/active/currentTask/revision)
|
|
||||||
+ 创建表单 + 详情抽屉(update/disable/checkpoint)
|
|
||||||
+ recall 查询框(展示 contentSnippet,标注 origin)
|
|
||||||
+ 409 → "数据已变化,请刷新" 提示条
|
|
||||||
src-client/panel/useApi.ts ← 轮询/加载状态机助手(idle/loading/ready/error),
|
|
||||||
错误条复用 Banner;visible=false 暂停
|
|
||||||
workspace 取值:ctx.get('sessions') 面探测当前会话 cwd(参考 vendor session-binding.ts
|
|
||||||
的 useMnemonSessionId 模式,简化为一次性读取);取不到则省略参数。
|
|
||||||
|
|
||||||
## 约束
|
|
||||||
- 零新后端路由;不改 departments-routes.ts(保护期)。
|
|
||||||
- recall k 输入框 max=5;snippet 展示直接用服务端 contentSnippet。
|
|
||||||
- 所有 POST 走 postJson(同源自动满足)。
|
|
||||||
|
|
||||||
## 验收
|
|
||||||
verify-client-build 断言两页签组件存在、API 路径字符串齐全;
|
|
||||||
手工冒烟:起真实 server(参考 verify-brain-panel.mjs 夹具)核对每个消费路由 200。
|
|
||||||
typecheck + build + verify-all 全绿。
|
|
||||||
commit:feat(ui): memory and department tabs in the Brain panel
|
|
||||||
|
|
||||||
═══════════════════════════════════════════
|
|
||||||
U3 · better-sidebar 项目记忆页签(0.5 天)
|
|
||||||
═══════════════════════════════════════════
|
|
||||||
|
|
||||||
## 可抄源码
|
|
||||||
vendor/dsh-mnemon/src/client/better-sidebar.tsx(全文 2.4KB 已核):
|
|
||||||
mountBetterSidebarTab 的 reconcile 模式——ctx.get('betterSidebar') 探测 +
|
|
||||||
ctx.on('internal/service', name => name==='betterSidebar' && reconcile()) 热插拔 +
|
|
||||||
disposer 链。**整抄改前缀**,descriptor 换成本项目:
|
|
||||||
{ id:'dsh-brain:memory', title:()=>'项目记忆',
|
|
||||||
description:'当前会话项目的本地记忆:空间/条目/搜索/部门召回',
|
|
||||||
icon:size=><BrainIcon size={size}/>, order:60, single:true,
|
|
||||||
component:({scope,visible}) => <ProjectMemoryView scope={scope} visible={visible}/> }
|
|
||||||
|
|
||||||
## 新文件
|
|
||||||
src-client/sidebar/register.ts ← mountBrainSidebarTab(ctx)(抄改)
|
|
||||||
src-client/sidebar/ProjectMemoryView.tsx ← 只读视图:status + memories 列表 + 搜索
|
|
||||||
+ recall 查询(部门选择下拉);
|
|
||||||
visible=false 暂停轮询(契约);
|
|
||||||
重操作按钮"去总面板"→ selectPanel('dsh-brain')
|
|
||||||
src-client/sidebar/ProjectMemory.module.css ← betterSidebarSeat 骨架抄 vendor
|
|
||||||
|
|
||||||
## 降级链
|
|
||||||
无 betterSidebar 服务 → reconcile 不注册,静默;服务后到 → internal/service 触发补注册;
|
|
||||||
fiber 卸载 → disposer 自动清理。总面板不受影响。
|
|
||||||
|
|
||||||
## 验收
|
|
||||||
verify-client-build 断言:registerTab 探测、descriptor id/order/single、
|
|
||||||
internal/service 监听、visible 暂停分支、无服务时 apply 不抛。
|
|
||||||
typecheck + build + verify-all 全绿。
|
|
||||||
commit:feat(ui): project-memory tab for better-sidebar with graceful fallback
|
|
||||||
|
|
||||||
═══════════════════════════════════════════
|
|
||||||
U4 · 彻底改名 + 迁移 + 终验(0.5 天)
|
|
||||||
═══════════════════════════════════════════
|
|
||||||
|
|
||||||
## 改名清单(一处不漏,已实测现状)
|
|
||||||
1. src/entries/settings-ui.ts → src/entries/ui.ts:
|
|
||||||
export name='dsh-brain-ui';kernel.activate('ui')/deactivate('ui');
|
|
||||||
effect 标签 'dsh-brain-ui: …';头注释更新。
|
|
||||||
2. src/kernel.ts L48:BrainBundle 类型 'settings-ui'→'ui';L5 注释同步。
|
|
||||||
3. package.json exports:加 './ui':'./lib/entries/ui.js';
|
|
||||||
**保留 './settings-ui':'./lib/entries/ui.js'(别名指向新文件)**。
|
|
||||||
4. cordis.patch.yml:insert 行 id:'dsh-brain-ui',name:'dsh-brain/ui'。
|
|
||||||
5. src/index.ts compat root:import * as ui from './entries/ui.ts';ui.apply(...)。
|
|
||||||
6. src/settings-ui/ 目录暂不改名(departments-routes.ts 保护期);
|
|
||||||
entry 内 import 路径不变。目录搬迁留待复验通过后单独 commit。
|
|
||||||
7. 旧 id 迁移探测:ui entry apply 开头读宿主 patch 面(若 ctx 暴露)或
|
|
||||||
logger.info 提示"若你曾禁用 dsh-brain-settings-ui,请在设置→插件重新禁用 dsh-brain-ui"。
|
|
||||||
**不自动改写宿主文件**。README 升级节写明。
|
|
||||||
8. verify-plugin-entry.mjs:import './lib/entries/ui.js';断言文案改 ui;
|
|
||||||
加一条兼容断言:import './lib/entries/settings-ui.js'(exports 别名)仍可用。
|
|
||||||
9. README 五行表 id 列、docs/management-surface.md 提及同步。
|
|
||||||
10. lib/ 产物:build 后 lib/entries/ui.js 新增;lib/entries/settings-ui.js 由
|
|
||||||
exports 别名兜底——**物理文件也保留一份 re-export**(export * from './ui.js'),
|
|
||||||
防老 profile 直接路径解析绕过 exports map。
|
|
||||||
|
|
||||||
## 终验(全绿才报完成)
|
|
||||||
npm run typecheck && npm run build
|
|
||||||
node scripts/verify-all.mjs && node verify-plugin-entry.mjs && node verify-client-build.mjs
|
|
||||||
npm pack --dry-run # files 含 client/index.js、lib/entries/ui.js、lib/entries/settings-ui.js
|
|
||||||
宿主冒烟(升级 profile 依赖后另行授权,不在本卡):
|
|
||||||
左栏 Brain 行/总面板六页签/better-sidebar 页签/设置卡/独立页/legacy 别名 六处核对。
|
|
||||||
commit:refactor(ui)!: rename settings-ui bundle to dsh-brain-ui with export alias
|
|
||||||
|
|
||||||
═══════════════════════════════════════════
|
|
||||||
全局硬约束
|
|
||||||
═══════════════════════════════════════════
|
|
||||||
- 运行时零新依赖;tsdown/react 均已在 devDeps。
|
|
||||||
- client 产物单文件 __ModuleLoader__ IIFE,id:'dsh-brain' 不变(row id 才改)。
|
|
||||||
- 保护期禁改四文件(见头部);可 import 其导出。
|
|
||||||
- 每卡独立 commit + 该卡验证命令;lib/ 与 client/index.js 产物随卡入库。
|
|
||||||
- 样式走 --dsw-alias-* token,无纯白纯黑硬编码(verify-theme 会查)。
|
|
||||||
- 与现状不符:停下报告差异,等规划侧修订,不自行改方案。
|
|
||||||
- vendor 源码抄改处保留 MIT 出处注释(// Adapted from dsh-mnemon (MIT), see vendor/dsh-mnemon/LICENSE)。
|
|
||||||
|
|
@ -1,166 +0,0 @@
|
||||||
# UI 改造 U0–U4 可执行任务卡(给 DeepSeek)
|
|
||||||
|
|
||||||
版本:v1(2026-11-24 23:35)
|
|
||||||
基线:89e67d0(部门 FAIL 修复已入库推送,待 GPT 复验——**UI 开工不等复验,但不得触碰
|
|
||||||
src/memory/departments-tools.ts、src/settings-ui/departments-routes.ts、src/skill-sync.ts**,
|
|
||||||
避免与复验/修复线冲突)。
|
|
||||||
决策已定(用户拍板):**选项 B 借壳不借芯** + **bundle id 彻底改名 dsh-brain-ui**。
|
|
||||||
上游方案:UI_PLAN.md(§0.5 三选项评估、§2 改名边界、§3 切片)。
|
|
||||||
**详细实施规格:UI_SPEC.md**(文件级改动清单、可抄源码位置、代码骨架、API 契约、逐卡验收命令)——执行以 UI_SPEC.md 为准,本卡为总览。
|
|
||||||
|
|
||||||
## 总览
|
|
||||||
|
|
||||||
| 卡 | 内容 | 依赖 | 预估 |
|
|
||||||
| --- | --- | --- | --- |
|
|
||||||
| U0 | client 构建链落地(tsdown,devDep 已有)+ 现有 client 迁 TS 源 | 无 | 0.5–1 天 |
|
|
||||||
| U1 | 左栏总面板骨架(panellist+main 双 seat,抄 Mnemon 接入层) | U0 | 1 天 |
|
|
||||||
| U2 | 记忆/部门页签并入总面板(消费既有 HTTP 路由) | U1 | 1 天 |
|
|
||||||
| U3 | better-sidebar "项目记忆"页签(registerTab + 降级) | U1 | 0.5 天 |
|
|
||||||
| U4 | bundle 彻底改名 settings-ui → ui(含迁移)+ 终验 | U1–U3 | 0.5 天 |
|
|
||||||
| U5 | 诊断日志 .dsh/brain/logs(JSONL/脱敏/滚动),详见 LOGGING_SPEC.md | 可与 U2/U3 并行 | 0.5–1 天 |
|
|
||||||
|
|
||||||
每卡独立 commit;U2/U3/U5 可并行。总量约 4–5 天。
|
|
||||||
升级批次(用户拍板 2026-11-24):**先不升级宿主**,U0–U5 全部完成 + GPT 部门复验通过后一次升级。
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## U0 · client 构建链(先决)
|
|
||||||
|
|
||||||
现状:client/index.js 是 3735 行手写 IIFE(__ModuleLoader__ 契约);
|
|
||||||
devDependencies **已含 tsdown ^0.22.2**(无需新增依赖!);vendor/dsh-mnemon/tsdown.config.ts
|
|
||||||
有现成的 client 构建配置可抄(banner/footer/intro 包裹 __ModuleLoader__、css modules 内联插件、
|
|
||||||
react externals)。
|
|
||||||
|
|
||||||
1. 新建 src-client/(或 client-src/)目录放 TS 源;把现有 client/index.js 的逻辑
|
|
||||||
**原样迁为 TS**(第一步不求重构,求字节级行为等价):
|
|
||||||
- 入口 src-client/index.ts,导出 { apply, inject, name:'dsh-brain' }。
|
|
||||||
- 现有 SettingsCard 三页签、API 常量、request 助手、CardBoundary 全部搬入。
|
|
||||||
2. 新建 tsdown.config.ts(根目录),client 段照抄 vendor 配置:
|
|
||||||
- format:'cjs'、platform:'browser'、target:'es2022'、deps.neverBundle:[/^react(?:\/.*)?$/]
|
|
||||||
- outputOptions.banner/intro/footer 生成 window.__ModuleLoader__.load({id:'dsh-brain',factory:(require)=>{…}})
|
|
||||||
- 产物固定写 **client/index.js**(outDir:'client',entry:{index:'src-client/index.ts'},
|
|
||||||
outExtensions 强制 .js;clean:false 防误删)。
|
|
||||||
- css modules 内联插件从 vendor 抄(lightningcss transform → 注入 style),
|
|
||||||
U1 起样式用 .module.css。
|
|
||||||
3. package.json scripts 加 "build:client": "tsdown";"build" 改为
|
|
||||||
"tsc -p tsconfig.build.json && tsdown"(host lib 与 client 一起出)。
|
|
||||||
prepack 同步。tsconfig.json include 排除 src-client(走 tsdown 自己的转译,
|
|
||||||
或单列 tsconfig.client.json——二选一,保证 npm run typecheck 仍覆盖 host src)。
|
|
||||||
4. **等价门禁**:构建后 client/index.js 与迁移前手写版做行为对比——
|
|
||||||
新增 verify-client-build.mjs:断言产物含 __ModuleLoader__.load、id:'dsh-brain'、
|
|
||||||
settings.section/plugins.bundle.config 注册、三页签标签字符串;
|
|
||||||
再起临时 http server 用 jsdom-free 方式静态 require 产物(react shim)验证 apply 不抛。
|
|
||||||
旧手写版先备份到 artifacts/analysis/client-legacy.js(gitignore 内)供比对。
|
|
||||||
5. .gitignore 确认 client/index.js **仍入库**(发布件),src-client/ 入库。
|
|
||||||
|
|
||||||
commit:build(client): migrate hand-written bundle to tsdown with byte-equivalent output
|
|
||||||
验证:npm run typecheck && npm run build && node verify-client-build.mjs && verify-all 不回退。
|
|
||||||
|
|
||||||
## U1 · 左栏总面板骨架
|
|
||||||
|
|
||||||
抄 Mnemon 接入层(vendor/dsh-mnemon/src/client/):
|
|
||||||
- native-sidebar.tsx:mountMnemonSidebarNavigation 的 panellist+main 双 slots.inject、
|
|
||||||
usePanelInfo 激活判定、window-drag band、glyph 语义锚点。
|
|
||||||
- shared/dom-seat.ts 的 HeldSeat、shared/store.ts 的 ExternalStore(小文件,直接搬改前缀)。
|
|
||||||
- workspace-mount.tsx 的 coordinateSidebarPanels 协调逻辑按需简化。
|
|
||||||
|
|
||||||
落点(src-client/):
|
|
||||||
1. panel.ts:PANEL_ID='dsh-brain';registerBrainPanel(ctx):
|
|
||||||
- slots.inject('sidebar.panellist', () => slots.register({name:'sidebar.panellist',
|
|
||||||
id:PANEL_ID, order:30, label:()=>'Brain'}, BrainPanelIcon))
|
|
||||||
- slots.inject('main', () => slots.register({name:'main', key:PANEL_ID,
|
|
||||||
inject:()=>({…})}, BrainPanel))
|
|
||||||
- glyph svg 带 data-dsh-panel-entry="dsh-brain";面板根带 data-dsh-plugin="dsh-brain"。
|
|
||||||
- seat 不存在时静默(slots.inject 回调不触发即天然降级),console.info 一次。
|
|
||||||
2. BrainPanel 组件:页签壳(概览/记忆/部门/技能/MCP/连接与上报),
|
|
||||||
本轮先实现"概览"(GET status+capabilities 聚合卡片)与"连接与上报"
|
|
||||||
(现有 SettingsCard connection 页签内容搬入);其余页签占位"即将上线"。
|
|
||||||
轮询仅面板激活时跑(usePanelInfo),15s 间隔沿用现状。
|
|
||||||
3. 设置卡瘦身:settings.section 注册保留,内容改为状态摘要 + "打开总面板"按钮
|
|
||||||
(经 ctx.layout.selectPanel(PANEL_ID)——该服务面参考 task-board/mnemon 用法,
|
|
||||||
typeof 探测,不可用时回退 window.open('/dsh-brain'))。
|
|
||||||
4. 样式:BrainPanel.module.css 布局抄 MnemonWorkspace.module.css 的骨架
|
|
||||||
(nativeWorkspace/windowDragBand/entry 系列),配色用宿主中性 token,不硬编码纯白纯黑
|
|
||||||
(verify-theme 口径)。
|
|
||||||
|
|
||||||
commit:feat(ui): left-rail Brain panel with overview and connection tabs
|
|
||||||
验证:verify-client-build.mjs 扩展断言(panellist/main 注册、PANEL_ID、降级分支);
|
|
||||||
typecheck+build+verify-all 全绿。宿主冒烟留 U4。
|
|
||||||
|
|
||||||
## U2 · 记忆/部门页签
|
|
||||||
|
|
||||||
数据面零新后端,全部既有路由(UI_PLAN §4):
|
|
||||||
1. 记忆页签:GET /dsh-brain/local-memory/status|spaces|documents|memories?limit&offset;
|
|
||||||
列表+搜索框(前端过滤当前页即可,不做服务端搜索新路由)+分页;
|
|
||||||
forget 按钮走 POST /dsh-brain/local-memory/forget(同源天然满足)。
|
|
||||||
2. 部门页签:GET /dsh-brain/departments/list;create/update/disable/checkpoint 表单
|
|
||||||
POST 对应子路由;recall 查询框 GET /departments/recall?id&query&k&workspace;
|
|
||||||
展示 contentSnippet(≤600)而非全文;revision 冲突 409 显示"数据已变化,请刷新"。
|
|
||||||
3. 错误条组件复用 CardBoundary 模式:路由失败显示可行动文案,不白屏。
|
|
||||||
4. workspace 参数:面板处于会话上下文时经 ctx sessions 面取当前会话 cwd 传入;
|
|
||||||
取不到则省略(服务端回落 process.cwd() 语义)。
|
|
||||||
|
|
||||||
commit:feat(ui): memory and department tabs in the Brain panel
|
|
||||||
验证:verify-client-build 断言两页签路由消费;手工冒烟脚本起真实 server 核对 JSON 形状;
|
|
||||||
verify-all 不回退。**不得改 departments-routes.ts/departments-tools.ts**(复验保护期)。
|
|
||||||
|
|
||||||
## U3 · better-sidebar 项目记忆页签
|
|
||||||
|
|
||||||
抄 vendor better-sidebar.tsx 的 mountBetterSidebarTab 模式(reconcile + internal/service 监听):
|
|
||||||
1. src-client/better-sidebar.ts:detect ctx.get('betterSidebar'),存在则
|
|
||||||
ctx.effect(() => service.registerTab(descriptor));监听 'internal/service' 热插拔;
|
|
||||||
不存在静默跳过(总面板不受影响)。
|
|
||||||
2. descriptor:id:'dsh-brain:memory',title:'项目记忆',description:'当前会话项目的本地记忆:空间/条目/搜索/部门召回',
|
|
||||||
single:true,order:60,icon 自绘脑形 svg(可参考 MnemonLogo/memory-icon 简化)。
|
|
||||||
3. component(props:TabComponentProps):scope.sessionId/cwd → 项目空间只读视图
|
|
||||||
(status+memories 列表+搜索+recall);**visible=false 暂停一切轮询**(契约);
|
|
||||||
重操作(建部门/forget)引导"去总面板"按钮(selectPanel)。
|
|
||||||
4. 降级链测试:无 betterSidebar 服务时 apply 不抛、无注册。
|
|
||||||
|
|
||||||
commit:feat(ui): project-memory tab for better-sidebar with graceful fallback
|
|
||||||
验证:verify-client-build 断言 registerTab 探测/disposer/visible 暂停逻辑;verify-all 不回退。
|
|
||||||
|
|
||||||
## U4 · 彻底改名 settings-ui → ui + 迁移 + 终验
|
|
||||||
|
|
||||||
改名清单(一处不漏):
|
|
||||||
1. src/entries/settings-ui.ts → src/entries/ui.ts;export name='dsh-brain-ui';
|
|
||||||
kernel.activate('ui');effect 标签前缀改 'dsh-brain-ui:'。
|
|
||||||
2. src/kernel.ts:BrainBundle 类型 'settings-ui'→'ui';注释同步。
|
|
||||||
3. package.json exports:'./ui':'./lib/entries/ui.js';**保留 './settings-ui' 别名**
|
|
||||||
指向同一文件(老 profile 行不断)。
|
|
||||||
4. cordis.patch.yml:insert 行 id:'dsh-brain-ui',name:'dsh-brain/ui'。
|
|
||||||
5. src/index.ts compat root:import * as ui from './entries/ui.ts'。
|
|
||||||
6. src/settings-ui/ 目录(page.ts/routes.ts/departments-routes.ts)→ src/ui/?
|
|
||||||
**注意:departments-routes.ts 在复验保护期,本卡只改 import 路径不改其内容**;
|
|
||||||
若 GPT 复验尚未结束,目录搬迁推迟到复验通过后(改名先只动 entry/kernel/exports/patch 四处,
|
|
||||||
目录名 settings-ui 暂留,单独后续 commit 搬)。
|
|
||||||
7. **旧 id 迁移**:宿主 profile patch 里可能存在 '- id: dsh-brain-settings-ui' 禁用/配置行
|
|
||||||
(本机实测 desktop/web 均无,但其他机器可能有)。在 ui entry apply 开头做一次迁移探测:
|
|
||||||
读 ctx 配置面若发现旧 id 行,logger.warn 提示用户在新行重设;
|
|
||||||
不自动改写宿主文件(越权)。README 升级说明写明此点。
|
|
||||||
8. verify-plugin-entry.mjs:import 路径改 lib/entries/ui.js,断言名改 'ui entry …';
|
|
||||||
兼容断言:require('./lib/entries/settings-ui.js') 别名仍可用(exports 别名生效)。
|
|
||||||
9. README 五行表、docs/management-surface.md 的 id 提及同步。
|
|
||||||
|
|
||||||
终验(全绿才报完成):
|
|
||||||
npm run typecheck && npm run build
|
|
||||||
node scripts/verify-all.mjs # 39+ 脚本口径不回退
|
|
||||||
node verify-plugin-entry.mjs
|
|
||||||
node verify-client-build.mjs
|
|
||||||
npm pack --dry-run # files 含 client/index.js + lib/entries/ui.js
|
|
||||||
宿主冒烟(升级 profile 依赖后,另行授权):
|
|
||||||
左栏 Brain 行 → 总面板六页签;better-sidebar + 菜单"项目记忆";
|
|
||||||
设置卡仍在;/dsh-brain 独立页可达;旧 /cloud-memory 别名可达。
|
|
||||||
|
|
||||||
commit:refactor(ui)!: rename settings-ui bundle to dsh-brain-ui with export alias
|
|
||||||
(breaking 标记仅指内部 id;exports 别名保证老 profile 不断。)
|
|
||||||
|
|
||||||
## 硬约束(全卡通用)
|
|
||||||
|
|
||||||
- 运行时零新依赖(tsdown 已在 devDeps;react 走宿主 shim externals)。
|
|
||||||
- 复验保护期不碰:departments-tools.ts / departments-routes.ts / skill-sync.ts /
|
|
||||||
src/local-memory/departments/。
|
|
||||||
- client 产物必须仍是单文件 __ModuleLoader__ IIFE,id:'dsh-brain' 不变(client bundle id
|
|
||||||
与子插件 row id 是两回事,后者才改 dsh-brain-ui)。
|
|
||||||
- 每卡 commit 前跑该卡验证;lib/ 与 client/index.js 产物随卡入库。
|
|
||||||
- 遇到与本卡不符的代码现状:停下报告差异,等规划侧修订。
|
|
||||||
324
lib/api.js
324
lib/api.js
|
|
@ -38,194 +38,6 @@ function sessionCookieOf(headers) {
|
||||||
}
|
}
|
||||||
return '';
|
return '';
|
||||||
}
|
}
|
||||||
/**
|
|
||||||
* Runtime response-shape guards.
|
|
||||||
*
|
|
||||||
* A 2xx with syntactically valid JSON but the wrong shape is still a failed
|
|
||||||
* call: without these checks `null` becomes `data: null` and every downstream
|
|
||||||
* `data.items ?? []` silently turns a contract violation into "empty". The
|
|
||||||
* helpers throw; request() normalizes the throw to `invalid_response`.
|
|
||||||
*/
|
|
||||||
function requireResponseObject(value, what) {
|
|
||||||
if (value === null || typeof value !== 'object' || Array.isArray(value)) {
|
|
||||||
throw new Error(`${what} must be a JSON object`);
|
|
||||||
}
|
|
||||||
return value;
|
|
||||||
}
|
|
||||||
function requireResponseArray(body, key) {
|
|
||||||
const value = body[key];
|
|
||||||
if (!Array.isArray(value))
|
|
||||||
throw new Error(`${key} must be an array`);
|
|
||||||
return value;
|
|
||||||
}
|
|
||||||
function requireResponseString(body, key, allowEmpty = false) {
|
|
||||||
const value = body[key];
|
|
||||||
if (typeof value !== 'string' || (!allowEmpty && value === '')) {
|
|
||||||
throw new Error(`${key} must be a non-empty string`);
|
|
||||||
}
|
|
||||||
return value;
|
|
||||||
}
|
|
||||||
function optionalResponseString(body, key) {
|
|
||||||
const value = body[key];
|
|
||||||
if (value !== undefined && typeof value !== 'string')
|
|
||||||
throw new Error(`${key} must be a string`);
|
|
||||||
}
|
|
||||||
function optionalNullableString(body, key) {
|
|
||||||
const value = body[key];
|
|
||||||
if (value !== undefined && value !== null && typeof value !== 'string') {
|
|
||||||
throw new Error(`${key} must be a string or null`);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
function optionalResponseNumber(body, key) {
|
|
||||||
const value = body[key];
|
|
||||||
if (value !== undefined && (typeof value !== 'number' || !Number.isFinite(value))) {
|
|
||||||
throw new Error(`${key} must be a number`);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
function optionalResponseBoolean(body, key) {
|
|
||||||
const value = body[key];
|
|
||||||
if (value !== undefined && typeof value !== 'boolean')
|
|
||||||
throw new Error(`${key} must be a boolean`);
|
|
||||||
}
|
|
||||||
function optionalResponseStringArray(body, key) {
|
|
||||||
const value = body[key];
|
|
||||||
if (value === undefined)
|
|
||||||
return;
|
|
||||||
if (!Array.isArray(value) || value.some((entry) => typeof entry !== 'string')) {
|
|
||||||
throw new Error(`${key} must be an array of strings`);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
function optionalStringOrNumber(body, key) {
|
|
||||||
const value = body[key];
|
|
||||||
if (value !== undefined && typeof value !== 'string' && typeof value !== 'number') {
|
|
||||||
throw new Error(`${key} must be a string or number`);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
function validateTurnAck(value) {
|
|
||||||
const body = requireResponseObject(value, 'activity turn response');
|
|
||||||
optionalResponseBoolean(body, 'recorded');
|
|
||||||
optionalResponseBoolean(body, 'duplicate');
|
|
||||||
return body;
|
|
||||||
}
|
|
||||||
function validateSummaryAck(value) {
|
|
||||||
const body = requireResponseObject(value, 'activity summary response');
|
|
||||||
optionalResponseNumber(body, 'staged');
|
|
||||||
optionalResponseNumber(body, 'skipped');
|
|
||||||
optionalResponseBoolean(body, 'full');
|
|
||||||
return body;
|
|
||||||
}
|
|
||||||
function validateMemoryHitItem(value, what) {
|
|
||||||
const body = requireResponseObject(value, what);
|
|
||||||
optionalResponseString(body, 'id');
|
|
||||||
optionalResponseString(body, 'content');
|
|
||||||
optionalResponseStringArray(body, 'tags');
|
|
||||||
optionalResponseString(body, 'primary_sector');
|
|
||||||
if (body.project_id !== undefined && body.project_id !== null && typeof body.project_id !== 'string') {
|
|
||||||
throw new Error(`${what}.project_id must be a string or null`);
|
|
||||||
}
|
|
||||||
optionalResponseNumber(body, 'revision');
|
|
||||||
optionalResponseNumber(body, 'created_at');
|
|
||||||
optionalResponseNumber(body, 'updated_at');
|
|
||||||
return body;
|
|
||||||
}
|
|
||||||
function validateMemoryRead(value) {
|
|
||||||
const body = requireResponseObject(value, 'memory response');
|
|
||||||
requireResponseString(body, 'id');
|
|
||||||
return validateMemoryHitItem(body, 'memory response');
|
|
||||||
}
|
|
||||||
function validateSearchResponse(value) {
|
|
||||||
const body = requireResponseObject(value, 'memory search response');
|
|
||||||
const matches = requireResponseArray(body, 'matches');
|
|
||||||
matches.forEach((entry, index) => validateMemoryHitItem(entry, `matches[${index}]`));
|
|
||||||
optionalResponseNumber(body, 'total');
|
|
||||||
optionalResponseString(body, 'search_mode');
|
|
||||||
return body;
|
|
||||||
}
|
|
||||||
function validateListResponse(value) {
|
|
||||||
const body = requireResponseObject(value, 'memory list response');
|
|
||||||
const items = requireResponseArray(body, 'items');
|
|
||||||
items.forEach((entry, index) => validateMemoryHitItem(entry, `items[${index}]`));
|
|
||||||
optionalResponseNumber(body, 'total');
|
|
||||||
return body;
|
|
||||||
}
|
|
||||||
function validateProjectsResponse(value) {
|
|
||||||
const body = requireResponseObject(value, 'projects response');
|
|
||||||
const projects = requireResponseArray(body, 'projects');
|
|
||||||
projects.forEach((entry, index) => {
|
|
||||||
const project = requireResponseObject(entry, `projects[${index}]`);
|
|
||||||
optionalResponseString(project, 'id');
|
|
||||||
optionalResponseString(project, 'name');
|
|
||||||
});
|
|
||||||
return body;
|
|
||||||
}
|
|
||||||
function validateAddResponse(value) {
|
|
||||||
const body = requireResponseObject(value, 'memory add response');
|
|
||||||
optionalResponseString(body, 'id');
|
|
||||||
optionalResponseNumber(body, 'revision');
|
|
||||||
optionalResponseBoolean(body, 'deleted');
|
|
||||||
optionalResponseString(body, 'state');
|
|
||||||
optionalResponseBoolean(body, 'remote_saved');
|
|
||||||
if (body.memory !== undefined && body.memory !== null) {
|
|
||||||
validateMemoryHitItem(body.memory, 'memory');
|
|
||||||
}
|
|
||||||
return body;
|
|
||||||
}
|
|
||||||
function validateStorageStatus(value) {
|
|
||||||
return requireResponseObject(value, 'storage status response');
|
|
||||||
}
|
|
||||||
function validateSkillSummary(value, what) {
|
|
||||||
const body = requireResponseObject(value, what);
|
|
||||||
requireResponseString(body, 'name');
|
|
||||||
optionalResponseString(body, 'description');
|
|
||||||
optionalNullableString(body, 'category');
|
|
||||||
optionalResponseString(body, 'execution_mode');
|
|
||||||
optionalResponseBoolean(body, 'enabled');
|
|
||||||
optionalResponseNumber(body, 'revision');
|
|
||||||
optionalResponseString(body, 'manifest_sha256');
|
|
||||||
optionalResponseNumber(body, 'files');
|
|
||||||
optionalResponseNumber(body, 'bytes');
|
|
||||||
optionalResponseBoolean(body, 'script_changed');
|
|
||||||
optionalStringOrNumber(body, 'created_at');
|
|
||||||
optionalStringOrNumber(body, 'updated_at');
|
|
||||||
return body;
|
|
||||||
}
|
|
||||||
function validateSkillListing(value) {
|
|
||||||
const body = requireResponseObject(value, 'skills response');
|
|
||||||
const items = requireResponseArray(body, 'items');
|
|
||||||
items.forEach((entry, index) => validateSkillSummary(entry, `items[${index}]`));
|
|
||||||
optionalResponseNumber(body, 'total');
|
|
||||||
optionalResponseNumber(body, 'trash_total');
|
|
||||||
return body;
|
|
||||||
}
|
|
||||||
function validateSkillBundle(value) {
|
|
||||||
const body = requireResponseObject(value, 'skill bundle response');
|
|
||||||
requireResponseString(body, 'name');
|
|
||||||
if (typeof body.revision !== 'number' || !Number.isFinite(body.revision)) {
|
|
||||||
throw new Error('revision must be a number');
|
|
||||||
}
|
|
||||||
requireResponseString(body, 'manifest_sha256');
|
|
||||||
optionalResponseBoolean(body, 'script_changed');
|
|
||||||
optionalResponseStringArray(body, 'script_changes');
|
|
||||||
const files = requireResponseArray(body, 'files');
|
|
||||||
files.forEach((entry, index) => {
|
|
||||||
const file = requireResponseObject(entry, `files[${index}]`);
|
|
||||||
requireResponseString(file, 'path');
|
|
||||||
requireResponseString(file, 'sha256');
|
|
||||||
requireResponseString(file, 'data', true);
|
|
||||||
optionalResponseNumber(file, 'size');
|
|
||||||
optionalResponseString(file, 'encoding');
|
|
||||||
});
|
|
||||||
return body;
|
|
||||||
}
|
|
||||||
function validateSkillWriteResult(value) {
|
|
||||||
const body = requireResponseObject(value, 'skill write response');
|
|
||||||
if (body.skill !== undefined && body.skill !== null) {
|
|
||||||
validateSkillSummary(body.skill, 'skill');
|
|
||||||
}
|
|
||||||
optionalResponseNumber(body, 'revision');
|
|
||||||
optionalResponseString(body, 'manifest_sha256');
|
|
||||||
return body;
|
|
||||||
}
|
|
||||||
/** Map one HTTP error body onto a {@link CloudError}. */
|
/** Map one HTTP error body onto a {@link CloudError}. */
|
||||||
function errorFromBody(status, raw, retryAfterHeader) {
|
function errorFromBody(status, raw, retryAfterHeader) {
|
||||||
let code = `http_${status}`;
|
let code = `http_${status}`;
|
||||||
|
|
@ -266,7 +78,7 @@ export class CloudClient {
|
||||||
constructor(options) {
|
constructor(options) {
|
||||||
this.options = options;
|
this.options = options;
|
||||||
}
|
}
|
||||||
async request(method, path, body, tokenOverride, validate) {
|
async request(method, path, body, tokenOverride) {
|
||||||
const token = tokenOverride ?? this.options.token();
|
const token = tokenOverride ?? this.options.token();
|
||||||
const base = this.options.baseUrl();
|
const base = this.options.baseUrl();
|
||||||
const url = `${base}${path}`;
|
const url = `${base}${path}`;
|
||||||
|
|
@ -286,51 +98,22 @@ export class CloudClient {
|
||||||
const reason = error instanceof Error ? error.message : String(error);
|
const reason = error instanceof Error ? error.message : String(error);
|
||||||
return { ok: false, error: { status: 0, code: 'network_error', message: `${method} ${path}: ${reason}` } };
|
return { ok: false, error: { status: 0, code: 'network_error', message: `${method} ${path}: ${reason}` } };
|
||||||
}
|
}
|
||||||
// A failed body read (connection torn mid-response) is NOT an empty
|
const text = await response.text().catch(() => '');
|
||||||
// success: a 200 whose payload cannot be read must surface as an error,
|
|
||||||
// not as `{ ok: true, data: {} }`.
|
|
||||||
let text;
|
|
||||||
try {
|
|
||||||
text = await response.text();
|
|
||||||
}
|
|
||||||
catch (error) {
|
|
||||||
const reason = error instanceof Error ? error.message : String(error);
|
|
||||||
if (!response.ok) {
|
|
||||||
return { ok: false, error: errorFromBody(response.status, `body read failed: ${reason}`, response.headers.get('retry-after')) };
|
|
||||||
}
|
|
||||||
return { ok: false, error: { status: response.status, code: 'body_read_error', message: `${method} ${path}: body read failed: ${reason}` } };
|
|
||||||
}
|
|
||||||
if (!response.ok) {
|
if (!response.ok) {
|
||||||
return { ok: false, error: errorFromBody(response.status, text, response.headers.get('retry-after')) };
|
return { ok: false, error: errorFromBody(response.status, text, response.headers.get('retry-after')) };
|
||||||
}
|
}
|
||||||
// Empty bodies are endpoint-specific: the validator decides whether `{}`
|
if (text.trim() === '')
|
||||||
// is an acceptable 2xx payload (add/turn acknowledgements) or a missing
|
return { ok: true, status: response.status, data: {} };
|
||||||
// required field (list/search/projects/skills/bundle). Probes pass no
|
|
||||||
// validator on purpose: any 2xx already proves the credential, and a 400
|
|
||||||
// remains their "authenticated but bad body" signal.
|
|
||||||
let parsed = {};
|
|
||||||
if (text.trim() !== '') {
|
|
||||||
try {
|
try {
|
||||||
parsed = JSON.parse(text);
|
return { ok: true, status: response.status, data: JSON.parse(text) };
|
||||||
}
|
}
|
||||||
catch {
|
catch {
|
||||||
return { ok: false, error: { status: response.status, code: 'invalid_json', message: `${method} ${path}: response was not JSON` } };
|
return { ok: false, error: { status: response.status, code: 'invalid_json', message: 'response was not JSON' } };
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if (validate !== undefined) {
|
|
||||||
try {
|
|
||||||
validate(parsed);
|
|
||||||
}
|
|
||||||
catch (error) {
|
|
||||||
const reason = error instanceof Error ? error.message : String(error);
|
|
||||||
return { ok: false, error: { status: response.status, code: 'invalid_response', message: `${method} ${path}: ${reason}` } };
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return { ok: true, status: response.status, data: parsed };
|
|
||||||
}
|
|
||||||
/** Report one conversation turn (activity:write token). */
|
/** Report one conversation turn (activity:write token). */
|
||||||
reportTurn(payload, token) {
|
reportTurn(payload, token) {
|
||||||
return this.request('POST', '/activity/turn', payload, token, validateTurnAck);
|
return this.request('POST', '/activity/turn', payload, token);
|
||||||
}
|
}
|
||||||
/**
|
/**
|
||||||
* Read-only reachability probe: any HTTP answer (even 401 or 404) proves the
|
* Read-only reachability probe: any HTTP answer (even 401 or 404) proves the
|
||||||
|
|
@ -353,7 +136,7 @@ export class CloudClient {
|
||||||
}
|
}
|
||||||
/** Stage one turn summary as pending proposals (summary:write token). */
|
/** Stage one turn summary as pending proposals (summary:write token). */
|
||||||
submitSummary(payload, token) {
|
submitSummary(payload, token) {
|
||||||
return this.request('POST', '/activity/summary', payload, token, validateSummaryAck);
|
return this.request('POST', '/activity/summary', payload, token);
|
||||||
}
|
}
|
||||||
/**
|
/**
|
||||||
* Verify a summary token without staging anything.
|
* Verify a summary token without staging anything.
|
||||||
|
|
@ -391,11 +174,11 @@ export class CloudClient {
|
||||||
const body = { query, k };
|
const body = { query, k };
|
||||||
if (project !== undefined && project !== '')
|
if (project !== undefined && project !== '')
|
||||||
body.filters = { project_id: project };
|
body.filters = { project_id: project };
|
||||||
return this.request('POST', '/memory/query', body, undefined, validateSearchResponse);
|
return this.request('POST', '/memory/query', body);
|
||||||
}
|
}
|
||||||
/** Read one memory by id (memory token). */
|
/** Read one memory by id (memory token). */
|
||||||
read(id) {
|
read(id) {
|
||||||
return this.request('GET', `/memory/${encodeURIComponent(id)}`, undefined, undefined, validateMemoryRead);
|
return this.request('GET', `/memory/${encodeURIComponent(id)}`);
|
||||||
}
|
}
|
||||||
/** List memories with optional paging filters (memory token). */
|
/** List memories with optional paging filters (memory token). */
|
||||||
list(options = {}) {
|
list(options = {}) {
|
||||||
|
|
@ -407,7 +190,7 @@ export class CloudClient {
|
||||||
if (options.project !== undefined && options.project !== '')
|
if (options.project !== undefined && options.project !== '')
|
||||||
params.set('project_id', options.project);
|
params.set('project_id', options.project);
|
||||||
const suffix = params.toString() === '' ? '' : `?${params.toString()}`;
|
const suffix = params.toString() === '' ? '' : `?${params.toString()}`;
|
||||||
return this.request('GET', `/memory/all${suffix}`, undefined, undefined, validateListResponse);
|
return this.request('GET', `/memory/all${suffix}`);
|
||||||
}
|
}
|
||||||
/** Store one memory; `operationId` makes the write idempotent (memory token). */
|
/** Store one memory; `operationId` makes the write idempotent (memory token). */
|
||||||
add(input) {
|
add(input) {
|
||||||
|
|
@ -421,31 +204,31 @@ export class CloudClient {
|
||||||
body.project_id = input.project;
|
body.project_id = input.project;
|
||||||
if (input.sector !== undefined && input.sector !== '')
|
if (input.sector !== undefined && input.sector !== '')
|
||||||
body.metadata = { primary_sector: input.sector };
|
body.metadata = { primary_sector: input.sector };
|
||||||
return this.request('POST', '/memory/add', body, undefined, validateAddResponse);
|
return this.request('POST', '/memory/add', body);
|
||||||
}
|
}
|
||||||
/** List the account's projects (memory token). */
|
/** List the account's projects (memory token). */
|
||||||
projects() {
|
projects() {
|
||||||
return this.request('GET', '/dashboard/projects', undefined, undefined, validateProjectsResponse);
|
return this.request('GET', '/dashboard/projects');
|
||||||
}
|
}
|
||||||
/** Storage configuration state (memory token). */
|
/** Storage configuration state (memory token). */
|
||||||
storageStatus() {
|
storageStatus() {
|
||||||
return this.request('GET', '/storage/status', undefined, undefined, validateStorageStatus);
|
return this.request('GET', '/storage/status');
|
||||||
}
|
}
|
||||||
/** List the cloud skill center inventory (memory token). */
|
/** List the cloud skill center inventory (memory token). */
|
||||||
listSkills() {
|
listSkills() {
|
||||||
return this.request('GET', '/skills', undefined, undefined, validateSkillListing);
|
return this.request('GET', '/skills');
|
||||||
}
|
}
|
||||||
/** Fetch one skill bundle with hashed, base64-carried files (memory token). */
|
/** Fetch one skill bundle with hashed, base64-carried files (memory token). */
|
||||||
skillBundle(name) {
|
skillBundle(name) {
|
||||||
return this.request('GET', `/skills/${encodeURIComponent(name)}/bundle`, undefined, undefined, validateSkillBundle);
|
return this.request('GET', `/skills/${encodeURIComponent(name)}/bundle`);
|
||||||
}
|
}
|
||||||
/** Create one skill in the center; `expected_revision` must be 0 (memory token). */
|
/** Create one skill in the center; `expected_revision` must be 0 (memory token). */
|
||||||
createSkill(body) {
|
createSkill(body) {
|
||||||
return this.request('POST', '/skills', body, undefined, validateSkillWriteResult);
|
return this.request('POST', '/skills', body);
|
||||||
}
|
}
|
||||||
/** Replace one skill's files/description at an expected revision (memory token). */
|
/** Replace one skill's files/description at an expected revision (memory token). */
|
||||||
updateSkill(name, body) {
|
updateSkill(name, body) {
|
||||||
return this.request('PATCH', `/skills/${encodeURIComponent(name)}`, body, undefined, validateSkillWriteResult);
|
return this.request('PATCH', `/skills/${encodeURIComponent(name)}`, body);
|
||||||
}
|
}
|
||||||
/**
|
/**
|
||||||
* One call against the dashboard auth surface (`/api/auth/*`).
|
* One call against the dashboard auth surface (`/api/auth/*`).
|
||||||
|
|
@ -455,21 +238,21 @@ export class CloudClient {
|
||||||
* the origin of the configured base URL is sent explicitly — that is a header
|
* the origin of the configured base URL is sent explicitly — that is a header
|
||||||
* only a non-browser client can set, which is exactly what this is.
|
* only a non-browser client can set, which is exactly what this is.
|
||||||
*/
|
*/
|
||||||
async authFetch(method, path, body, cookie, target) {
|
async authFetch(method, path, body, cookie) {
|
||||||
// The target is frozen by the caller at the start of the login flow; every
|
const baseUrl = this.options.baseUrl();
|
||||||
// auth request in that flow must hit the same service, even if settings
|
|
||||||
// change while a request is in flight.
|
|
||||||
const baseUrl = target?.baseUrl ?? this.options.baseUrl();
|
|
||||||
const timeoutMs = target?.timeoutMs ?? this.options.timeoutMs();
|
|
||||||
const base = authBase(baseUrl);
|
const base = authBase(baseUrl);
|
||||||
if (base === '')
|
if (base === '')
|
||||||
return { ok: false, error: { status: 0, code: 'invalid_base_url', message: '服务地址无效,无法登录' } };
|
return { ok: false, error: { status: 0, code: 'invalid_base_url', message: '服务地址无效,无法登录' } };
|
||||||
const headers = { Accept: 'application/json' };
|
const headers = { Accept: 'application/json' };
|
||||||
// authBase already parsed this exact URL successfully, so this cannot throw.
|
try {
|
||||||
headers.Origin = new URL(baseUrl).origin;
|
headers.Origin = new URL(baseUrl).origin;
|
||||||
|
}
|
||||||
|
catch {
|
||||||
|
return { ok: false, error: { status: 0, code: 'invalid_base_url', message: '服务地址无效,无法登录' } };
|
||||||
|
}
|
||||||
if (cookie !== undefined && cookie !== '')
|
if (cookie !== undefined && cookie !== '')
|
||||||
headers.Cookie = cookie;
|
headers.Cookie = cookie;
|
||||||
const init = { method, headers, signal: AbortSignal.timeout(timeoutMs) };
|
const init = { method, headers, signal: AbortSignal.timeout(this.options.timeoutMs()) };
|
||||||
if (body !== undefined) {
|
if (body !== undefined) {
|
||||||
headers['Content-Type'] = 'application/json';
|
headers['Content-Type'] = 'application/json';
|
||||||
init.body = JSON.stringify(body);
|
init.body = JSON.stringify(body);
|
||||||
|
|
@ -482,17 +265,7 @@ export class CloudClient {
|
||||||
const reason = error instanceof Error ? error.message : String(error);
|
const reason = error instanceof Error ? error.message : String(error);
|
||||||
return { ok: false, error: { status: 0, code: 'network_error', message: `${method} /auth${path}: ${reason}` } };
|
return { ok: false, error: { status: 0, code: 'network_error', message: `${method} /auth${path}: ${reason}` } };
|
||||||
}
|
}
|
||||||
let text;
|
const text = await response.text().catch(() => '');
|
||||||
try {
|
|
||||||
text = await response.text();
|
|
||||||
}
|
|
||||||
catch (error) {
|
|
||||||
const reason = error instanceof Error ? error.message : String(error);
|
|
||||||
if (!response.ok) {
|
|
||||||
return { ok: false, error: errorFromBody(response.status, `body read failed: ${reason}`, response.headers.get('retry-after')) };
|
|
||||||
}
|
|
||||||
return { ok: false, error: { status: response.status, code: 'body_read_error', message: `${method} /auth${path}: body read failed: ${reason}` } };
|
|
||||||
}
|
|
||||||
if (!response.ok) {
|
if (!response.ok) {
|
||||||
return { ok: false, error: errorFromBody(response.status, text, response.headers.get('retry-after')) };
|
return { ok: false, error: errorFromBody(response.status, text, response.headers.get('retry-after')) };
|
||||||
}
|
}
|
||||||
|
|
@ -502,9 +275,7 @@ export class CloudClient {
|
||||||
parsed = JSON.parse(text);
|
parsed = JSON.parse(text);
|
||||||
}
|
}
|
||||||
catch {
|
catch {
|
||||||
// Swallowing a malformed login/token body would make the caller treat
|
parsed = {};
|
||||||
// garbage as an empty success; surface it as a normalized failure.
|
|
||||||
return { ok: false, error: { status: response.status, code: 'invalid_json', message: `${method} /auth${path}: response was not JSON` } };
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return { ok: true, status: response.status, body: parsed, headers: response.headers };
|
return { ok: true, status: response.status, body: parsed, headers: response.headers };
|
||||||
|
|
@ -516,46 +287,29 @@ export class CloudClient {
|
||||||
* is a short-lived session cookie that the caller immediately spends on
|
* is a short-lived session cookie that the caller immediately spends on
|
||||||
* {@link CloudClient.mintToken} and then drops.
|
* {@link CloudClient.mintToken} and then drops.
|
||||||
*/
|
*/
|
||||||
async login(username, password, target) {
|
async login(username, password) {
|
||||||
const sent = await this.authFetch('POST', '/login', { username, password }, undefined, target);
|
const sent = await this.authFetch('POST', '/login', { username, password });
|
||||||
if (!sent.ok)
|
if (!sent.ok)
|
||||||
return sent;
|
return sent;
|
||||||
const cookie = sessionCookieOf(sent.headers);
|
const cookie = sessionCookieOf(sent.headers);
|
||||||
if (cookie === '') {
|
if (cookie === '') {
|
||||||
return { ok: false, error: { status: sent.status, code: 'no_session', message: '登录成功,但服务端没有下发会话' } };
|
return { ok: false, error: { status: sent.status, code: 'no_session', message: '登录成功,但服务端没有下发会话' } };
|
||||||
}
|
}
|
||||||
let body;
|
const body = sent.body;
|
||||||
try {
|
return { ok: true, status: sent.status, data: { user: body.user ?? {}, sessionCookie: cookie } };
|
||||||
body = requireResponseObject(sent.body, 'login response');
|
|
||||||
if (body.user !== undefined && body.user !== null)
|
|
||||||
requireResponseObject(body.user, 'login response user');
|
|
||||||
}
|
|
||||||
catch (error) {
|
|
||||||
const reason = error instanceof Error ? error.message : String(error);
|
|
||||||
return { ok: false, error: { status: sent.status, code: 'invalid_response', message: `POST /auth/login: ${reason}` } };
|
|
||||||
}
|
|
||||||
const user = (body.user ?? {});
|
|
||||||
return { ok: true, status: sent.status, data: { user, sessionCookie: cookie } };
|
|
||||||
}
|
}
|
||||||
/** Mint one scoped API token using a live session cookie. */
|
/** Mint one scoped API token using a live session cookie. */
|
||||||
async mintToken(sessionCookie, scope, label, target) {
|
async mintToken(sessionCookie, scope, label) {
|
||||||
const sent = await this.authFetch('POST', '/tokens', { scope, label }, sessionCookie, target);
|
const sent = await this.authFetch('POST', '/tokens', { scope, label }, sessionCookie);
|
||||||
if (!sent.ok)
|
if (!sent.ok)
|
||||||
return sent;
|
return sent;
|
||||||
try {
|
const body = sent.body;
|
||||||
const body = requireResponseObject(sent.body, 'token response');
|
const issued = body.token;
|
||||||
const issued = requireResponseObject(body.token, 'token response token');
|
if (issued === undefined || typeof issued.token !== 'string' || issued.token === '') {
|
||||||
requireResponseString(issued, 'token');
|
return { ok: false, error: { status: sent.status, code: 'no_token', message: '服务端没有返回令牌' } };
|
||||||
optionalResponseString(issued, 'id');
|
}
|
||||||
optionalResponseString(issued, 'scope');
|
|
||||||
optionalResponseString(issued, 'label');
|
|
||||||
return { ok: true, status: sent.status, data: issued };
|
return { ok: true, status: sent.status, data: issued };
|
||||||
}
|
}
|
||||||
catch (error) {
|
|
||||||
const reason = error instanceof Error ? error.message : String(error);
|
|
||||||
return { ok: false, error: { status: sent.status, code: 'invalid_response', message: `POST /auth/tokens: ${reason}` } };
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
/** Render a {@link CloudError} as one display line. */
|
/** Render a {@link CloudError} as one display line. */
|
||||||
export function describeError(error) {
|
export function describeError(error) {
|
||||||
|
|
|
||||||
|
|
@ -1,10 +1,10 @@
|
||||||
/**
|
/**
|
||||||
* dsh-cloud-memory → dsh-brain naming migration (v1.1 §15.1, RENAME-01).
|
* dsh-cloud-memory → dsh-brain naming migration (v1.1 §15.1, RENAME-01).
|
||||||
*
|
*
|
||||||
* The 0.8.0 unification build ships AS `dsh-brain`: the package rename
|
* This build still ships as `dsh-cloud-memory`; renaming the live package and
|
||||||
* (the deploy step RENAME-01 deferred) has been performed, and the load
|
* its profile link is a deploy step that needs a full DSH restart, so it is not
|
||||||
* paths read the `dsh-brain` names. What is implemented here is the
|
* performed from inside a running session. What is implemented here is the
|
||||||
* *data* half, which is what RENAME-01 asserts:
|
* *data* half, which is what RENAME-01 actually asserts:
|
||||||
*
|
*
|
||||||
* - copy the legacy sidecars to the `dsh-brain` names when the target is
|
* - copy the legacy sidecars to the `dsh-brain` names when the target is
|
||||||
* missing, never deleting or modifying the legacy files;
|
* missing, never deleting or modifying the legacy files;
|
||||||
|
|
@ -24,8 +24,6 @@ const PAIRS = [
|
||||||
['cloud-memory.json', 'dsh-brain.json'],
|
['cloud-memory.json', 'dsh-brain.json'],
|
||||||
['cloud-memory-skills.json', 'dsh-brain-skills.json'],
|
['cloud-memory-skills.json', 'dsh-brain-skills.json'],
|
||||||
['cloud-memory-skill-groups.json', 'dsh-brain-skill-groups.json'],
|
['cloud-memory-skill-groups.json', 'dsh-brain-skill-groups.json'],
|
||||||
['cloud-memory-workspaces.json', 'dsh-brain-workspaces.json'],
|
|
||||||
['.cloud-memory-plans.json', '.dsh-brain-plans.json'],
|
|
||||||
];
|
];
|
||||||
async function exists(path) {
|
async function exists(path) {
|
||||||
return stat(path).then((value) => value.isFile()).catch(() => false);
|
return stat(path).then((value) => value.isFile()).catch(() => false);
|
||||||
|
|
@ -47,7 +45,7 @@ export async function brainStatus() {
|
||||||
legacyPackage: BRAIN.legacyPackage,
|
legacyPackage: BRAIN.legacyPackage,
|
||||||
files,
|
files,
|
||||||
migrationNeeded: files.some((file) => file.needsMigration),
|
migrationNeeded: files.some((file) => file.needsMigration),
|
||||||
packageRename: 'done',
|
packageRename: 'pending-deploy',
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
/** Copy legacy sidecars to the new names. Existing targets are never overwritten. */
|
/** Copy legacy sidecars to the new names. Existing targets are never overwritten. */
|
||||||
|
|
|
||||||
|
|
@ -16,14 +16,12 @@ import { existsSync } from 'node:fs';
|
||||||
import { readFile, readdir, stat } from 'node:fs/promises';
|
import { readFile, readdir, stat } from 'node:fs/promises';
|
||||||
import { homedir } from 'node:os';
|
import { homedir } from 'node:os';
|
||||||
import { join, resolve, sep } from 'node:path';
|
import { join, resolve, sep } from 'node:path';
|
||||||
import { dshHome, migrateLegacyFile } from "./store.js";
|
import { dshHome } from "./store.js";
|
||||||
import { parseSkillFrontmatter } from "./skills/shared.js";
|
import { parseSkillFrontmatter } from "./skill-sync.js";
|
||||||
import { SkillAdmin } from "./skill-admin.js";
|
import { SkillAdmin } from "./skill-admin.js";
|
||||||
/** Manual workspace additions live in the plugin's own metadata file. */
|
/** Manual workspace additions live in the plugin's own metadata file. */
|
||||||
export function manualWorkspacesPath() {
|
export function manualWorkspacesPath() {
|
||||||
const target = join(dshHome(), 'dsh-brain-workspaces.json');
|
return join(dshHome(), 'cloud-memory-workspaces.json');
|
||||||
migrateLegacyFile(target, join(dshHome(), 'cloud-memory-workspaces.json'));
|
|
||||||
return target;
|
|
||||||
}
|
}
|
||||||
function rootsOf(home) {
|
function rootsOf(home) {
|
||||||
return {
|
return {
|
||||||
|
|
@ -108,10 +106,12 @@ export class ClientRegistry {
|
||||||
throw new Error('unknown_workspace');
|
throw new Error('unknown_workspace');
|
||||||
const skillsRoot = resolve(workspace.path, '.dsh', 'skills');
|
const skillsRoot = resolve(workspace.path, '.dsh', 'skills');
|
||||||
const holdingDir = join(dshHome(), 'skills-workspace-disabled', workspace.id);
|
const holdingDir = join(dshHome(), 'skills-workspace-disabled', workspace.id);
|
||||||
|
const statePath = join(dshHome(), `cloud-memory-workspace-${workspace.id.replace(/[^A-Za-z0-9_-]/g, '_')}.json`);
|
||||||
const admin = new SkillAdmin({
|
const admin = new SkillAdmin({
|
||||||
skillsRoot: () => skillsRoot,
|
skillsRoot: () => skillsRoot,
|
||||||
holdingDir: () => holdingDir,
|
holdingDir: () => holdingDir,
|
||||||
gate: () => ({ isRunning: () => false, provenance: async () => null }),
|
syncStatePath: () => statePath,
|
||||||
|
syncRunning: () => false,
|
||||||
log: () => { },
|
log: () => { },
|
||||||
});
|
});
|
||||||
return { admin, workspace };
|
return { admin, workspace };
|
||||||
|
|
@ -191,7 +191,9 @@ export class ClientRegistry {
|
||||||
if (software === undefined)
|
if (software === undefined)
|
||||||
throw new Error('invalid_software');
|
throw new Error('invalid_software');
|
||||||
const path = typeof pathInput === 'string' ? pathInput.trim() : '';
|
const path = typeof pathInput === 'string' ? pathInput.trim() : '';
|
||||||
const stats = path === '' ? undefined : await stat(path).catch(() => undefined);
|
if (path === '' || !existsSync(path))
|
||||||
|
throw new Error('invalid_path');
|
||||||
|
const stats = await stat(path).catch(() => undefined);
|
||||||
if (stats === undefined || !stats.isDirectory())
|
if (stats === undefined || !stats.isDirectory())
|
||||||
throw new Error('invalid_path');
|
throw new Error('invalid_path');
|
||||||
const resolved = resolve(path);
|
const resolved = resolve(path);
|
||||||
|
|
@ -230,7 +232,7 @@ export class ClientRegistry {
|
||||||
const frontmatter = parseSkillFrontmatter(markdown);
|
const frontmatter = parseSkillFrontmatter(markdown);
|
||||||
out.push({
|
out.push({
|
||||||
folder: entry.name,
|
folder: entry.name,
|
||||||
name: frontmatter.name ?? entry.name,
|
name: typeof frontmatter.name === 'string' && frontmatter.name !== '' ? frontmatter.name : entry.name,
|
||||||
description: String(frontmatter.description ?? '').slice(0, 300),
|
description: String(frontmatter.description ?? '').slice(0, 300),
|
||||||
path: skillDir,
|
path: skillDir,
|
||||||
softwareId: software,
|
softwareId: software,
|
||||||
|
|
|
||||||
|
|
@ -1,314 +0,0 @@
|
||||||
import { describeError, isSecureLoginTarget } from "./api.js";
|
|
||||||
import { fail, json, jsonBody, readBody, sameOrigin } from "./http.js";
|
|
||||||
/** Path constants — kept in sync with the ROUTES map in routes.ts by hand. */
|
|
||||||
const PATHS = {
|
|
||||||
login: '/dsh-brain/login',
|
|
||||||
test: '/dsh-brain/test',
|
|
||||||
flush: '/dsh-brain/flush',
|
|
||||||
sync: '/dsh-brain/sync',
|
|
||||||
};
|
|
||||||
/** Last test run, kept in memory so the card can show "最后检查". */
|
|
||||||
let lastCheck = null;
|
|
||||||
/** The root status view reads the same probe memory; one source of truth. */
|
|
||||||
export function getLastCheck() {
|
|
||||||
return lastCheck;
|
|
||||||
}
|
|
||||||
/** Labels attached to the tokens this plugin asks the dashboard to mint. */
|
|
||||||
const TOKEN_LABELS = {
|
|
||||||
activity: 'DSH desktop 活动上报',
|
|
||||||
memory: 'DSH desktop 记忆读写',
|
|
||||||
summary: 'DSH desktop 对话摘要',
|
|
||||||
};
|
|
||||||
/** Map one failed credential probe onto a check state. */
|
|
||||||
function checkState(error) {
|
|
||||||
if (error.status === 0)
|
|
||||||
return 'unreachable';
|
|
||||||
if (error.status === 401)
|
|
||||||
return 'invalid';
|
|
||||||
if (error.status === 403)
|
|
||||||
return 'forbidden';
|
|
||||||
return 'error';
|
|
||||||
}
|
|
||||||
/** `POST /dsh-brain/test` — read-only checks, one per credential. */
|
|
||||||
async function serveTest(deps, req, res) {
|
|
||||||
if (req.method !== 'POST') {
|
|
||||||
fail(res, 405, 'method-not-allowed');
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
if (!sameOrigin(req)) {
|
|
||||||
fail(res, 403, 'origin-rejected');
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
const client = deps.client();
|
|
||||||
const checks = [];
|
|
||||||
const settings = deps.store.settings();
|
|
||||||
const reach = await client.reach();
|
|
||||||
checks.push({
|
|
||||||
id: 'network',
|
|
||||||
label: '服务地址',
|
|
||||||
state: reach.ok ? 'ok' : 'unreachable',
|
|
||||||
message: deps.store.describe().baseUrlConfigured === false ? '服务地址还是打包默认值,请先填写真实地址。' : reach.message,
|
|
||||||
});
|
|
||||||
const activityToken = deps.store.activityToken();
|
|
||||||
if (activityToken === '') {
|
|
||||||
checks.push({ id: 'activity', label: '活动上报权限(activity:write)', state: 'unconfigured', message: '未配置令牌' });
|
|
||||||
}
|
|
||||||
else {
|
|
||||||
const probe = await client.probeActivity(activityToken);
|
|
||||||
checks.push({
|
|
||||||
id: 'activity',
|
|
||||||
label: '活动上报权限(activity:write)',
|
|
||||||
state: probe.ok ? 'ok' : checkState(probe.error),
|
|
||||||
message: probe.ok ? '鉴权通过(只验证权限,不代表已写入一条上报)' : describeError(probe.error),
|
|
||||||
});
|
|
||||||
}
|
|
||||||
const memoryToken = deps.store.memoryToken();
|
|
||||||
if (memoryToken === '') {
|
|
||||||
checks.push({ id: 'memory', label: '记忆读写权限(memory:write)', state: 'unconfigured', message: '未配置令牌' });
|
|
||||||
}
|
|
||||||
else {
|
|
||||||
const probe = await client.projects();
|
|
||||||
checks.push({
|
|
||||||
id: 'memory',
|
|
||||||
label: '记忆读写权限(memory:write)',
|
|
||||||
state: probe.ok ? 'ok' : checkState(probe.error),
|
|
||||||
message: probe.ok ? `鉴权通过(${probe.data.projects.length} 个项目)` : describeError(probe.error),
|
|
||||||
});
|
|
||||||
}
|
|
||||||
const summaryToken = deps.store.summaryToken();
|
|
||||||
if (!settings.summaryEnabled) {
|
|
||||||
checks.push({ id: 'summary', label: '摘要权限(summary:write)', state: 'unconfigured', message: '自动摘要已关闭' });
|
|
||||||
}
|
|
||||||
else if (summaryToken === '') {
|
|
||||||
checks.push({ id: 'summary', label: '摘要权限(summary:write)', state: 'unconfigured', message: '未配置摘要令牌(可选)' });
|
|
||||||
}
|
|
||||||
else {
|
|
||||||
const probe = await client.probeSummary(summaryToken);
|
|
||||||
checks.push({
|
|
||||||
id: 'summary',
|
|
||||||
label: '摘要权限(summary:write)',
|
|
||||||
state: probe.ok ? 'ok' : checkState(probe.error),
|
|
||||||
message: probe.ok ? '鉴权通过(只进待确认队列)' : describeError(probe.error),
|
|
||||||
});
|
|
||||||
}
|
|
||||||
lastCheck = { at: Date.now(), checks };
|
|
||||||
json(res, 200, {
|
|
||||||
ok: true,
|
|
||||||
checkedAt: lastCheck.at,
|
|
||||||
checks,
|
|
||||||
// Kept for the older card/page shape; both views read the same probes.
|
|
||||||
activity: { ok: checks[1]?.state === 'ok', message: checks[1]?.message ?? '' },
|
|
||||||
memory: { ok: checks[2]?.state === 'ok', message: checks[2]?.message ?? '' },
|
|
||||||
summary: { ok: checks[3]?.state === 'ok', message: checks[3]?.message ?? '' },
|
|
||||||
});
|
|
||||||
}
|
|
||||||
/** `POST /dsh-brain/flush`. */
|
|
||||||
async function serveFlush(deps, req, res) {
|
|
||||||
if (req.method !== 'POST') {
|
|
||||||
fail(res, 405, 'method-not-allowed');
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
if (!sameOrigin(req)) {
|
|
||||||
fail(res, 403, 'origin-rejected');
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
const result = await deps.reporter.flush();
|
|
||||||
json(res, 200, { ok: true, ...result });
|
|
||||||
}
|
|
||||||
/**
|
|
||||||
* `POST /dsh-brain/login` — sign in with the cloud account and exchange it
|
|
||||||
* for the scoped tokens.
|
|
||||||
*
|
|
||||||
* The password is used once, in memory, and never written anywhere: the flow is
|
|
||||||
* password → short-lived session cookie → tokens → cookie dropped. Only the
|
|
||||||
* tokens are persisted, so a later password change does not break the plugin
|
|
||||||
* and revoking a token does not reveal the password.
|
|
||||||
*/
|
|
||||||
async function serveLogin(deps, req, res) {
|
|
||||||
if (req.method !== 'POST') {
|
|
||||||
fail(res, 405, 'method-not-allowed');
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
if (!sameOrigin(req)) {
|
|
||||||
fail(res, 403, 'origin-rejected');
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
// Snapshot the complete connection before any credential leaves the
|
|
||||||
// process. Every auth call in this flow is pinned to this target, and the
|
|
||||||
// final patch is refused if the configured address changed meanwhile.
|
|
||||||
const settings = deps.store.settings();
|
|
||||||
const target = { baseUrl: settings.baseUrl, timeoutMs: settings.requestTimeoutMs };
|
|
||||||
if (!isSecureLoginTarget(target.baseUrl)) {
|
|
||||||
// Refuse to put a password on a plaintext channel that is not loopback.
|
|
||||||
json(res, 400, { ok: false, error: '服务地址不是 HTTPS,拒绝在上面发送密码,请先把服务地址改成 https://' });
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
let raw;
|
|
||||||
try {
|
|
||||||
raw = await readBody(req);
|
|
||||||
}
|
|
||||||
catch {
|
|
||||||
fail(res, 413, 'request-too-large');
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
let body;
|
|
||||||
try {
|
|
||||||
const parsed = JSON.parse(raw);
|
|
||||||
if (parsed === null || typeof parsed !== 'object' || Array.isArray(parsed))
|
|
||||||
throw new Error('object required');
|
|
||||||
body = parsed;
|
|
||||||
}
|
|
||||||
catch {
|
|
||||||
fail(res, 400, 'invalid-json');
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
const username = typeof body.username === 'string' ? body.username.trim() : '';
|
|
||||||
const password = typeof body.password === 'string' ? body.password : '';
|
|
||||||
if (username === '' || password === '') {
|
|
||||||
json(res, 400, { ok: false, error: '请填写用户名和密码' });
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
if (username.length > 64 || password.length > 256) {
|
|
||||||
json(res, 400, { ok: false, error: '用户名或密码过长' });
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
const client = deps.client();
|
|
||||||
const session = await client.login(username, password, target);
|
|
||||||
if (!session.ok) {
|
|
||||||
const status = session.error.status === 429 ? 429 : 401;
|
|
||||||
json(res, status, { ok: false, error: describeError(session.error) });
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
const activity = await client.mintToken(session.data.sessionCookie, 'activity:write', TOKEN_LABELS.activity, target);
|
|
||||||
const memory = await client.mintToken(session.data.sessionCookie, 'memory:write', TOKEN_LABELS.memory, target);
|
|
||||||
const summary = await client.mintToken(session.data.sessionCookie, 'summary:write', TOKEN_LABELS.summary, target);
|
|
||||||
if (!activity.ok && !memory.ok) {
|
|
||||||
json(res, 400, { ok: false, error: `登录成功,但创建令牌失败:${describeError(activity.error)}` });
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
// Atomic account switch: a scope whose mint failed must not keep the token
|
|
||||||
// of the PREVIOUS account — clearing beats carrying a stale credential the
|
|
||||||
// user just replaced. (Writing a token clears the clear-marker, so ordering
|
|
||||||
// inside one patch is irrelevant.)
|
|
||||||
const patch = {};
|
|
||||||
if (activity.ok && typeof activity.data.token === 'string')
|
|
||||||
patch.activityToken = activity.data.token;
|
|
||||||
if (memory.ok && typeof memory.data.token === 'string')
|
|
||||||
patch.memoryToken = memory.data.token;
|
|
||||||
if (summary.ok && typeof summary.data.token === 'string')
|
|
||||||
patch.summaryToken = summary.data.token;
|
|
||||||
if (!activity.ok || typeof activity.data.token !== 'string')
|
|
||||||
patch.clearActivityToken = true;
|
|
||||||
if (!memory.ok || typeof memory.data.token !== 'string')
|
|
||||||
patch.clearMemoryToken = true;
|
|
||||||
if (!summary.ok || typeof summary.data.token !== 'string')
|
|
||||||
patch.clearSummaryToken = true;
|
|
||||||
// A settings edit while login/mintToken was in flight could otherwise bind
|
|
||||||
// fresh tokens minted for the OLD service to the NEW address. Refuse the
|
|
||||||
// patch outright: no token at all is safer than a wrong-attribution token.
|
|
||||||
if (deps.store.settings().baseUrl !== target.baseUrl) {
|
|
||||||
json(res, 409, { ok: false, error: '登录过程中服务地址已变更,本次登录结果已丢弃,请确认服务地址后重新登录' });
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
const applied = deps.store.patch(patch);
|
|
||||||
if (!applied.ok) {
|
|
||||||
json(res, 500, { ok: false, error: applied.error });
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
const failed = activity.ok ? memory : activity;
|
|
||||||
const partial = !activity.ok || !memory.ok;
|
|
||||||
json(res, 200, {
|
|
||||||
...deps.statusView(),
|
|
||||||
login: {
|
|
||||||
ok: true,
|
|
||||||
partial,
|
|
||||||
user: {
|
|
||||||
username: typeof session.data.user.username === 'string' ? session.data.user.username : username,
|
|
||||||
role: session.data.user.role,
|
|
||||||
},
|
|
||||||
activity: activity.ok,
|
|
||||||
memory: memory.ok,
|
|
||||||
summary: summary.ok,
|
|
||||||
warning: failed.ok ? undefined : `部分令牌没有创建成功:${describeError(failed.error)}`,
|
|
||||||
},
|
|
||||||
});
|
|
||||||
}
|
|
||||||
/**
|
|
||||||
* Sync surface:
|
|
||||||
* `GET /dsh-brain/sync/status` latest stats + both sides of each conflict
|
|
||||||
* `POST /dsh-brain/sync/run` trigger one pass now
|
|
||||||
* `POST /dsh-brain/sync/resolve` { name, action: keep_local | take_cloud | manual }
|
|
||||||
* `POST /dsh-brain/sync/resolve-all` { action: keep_local | take_cloud }
|
|
||||||
*/
|
|
||||||
async function serveSync(deps, req, res) {
|
|
||||||
const sync = deps.sync;
|
|
||||||
if (sync === undefined) {
|
|
||||||
fail(res, 404, 'sync-unavailable');
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
const url = new URL(req.url ?? '/', 'http://localhost');
|
|
||||||
const suffix = url.pathname.slice(PATHS.sync.length);
|
|
||||||
try {
|
|
||||||
if (suffix === '' || suffix === '/' || suffix === '/status') {
|
|
||||||
if (req.method !== 'GET') {
|
|
||||||
fail(res, 405, 'method-not-allowed');
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
json(res, 200, { ok: true, stats: sync.stats(), conflicts: await sync.conflictDetails() });
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
if (suffix === '/run') {
|
|
||||||
// Mutating route: the method, origin and content-type gates live in
|
|
||||||
// jsonBody so a cross-site form/text POST cannot trigger a sync pass.
|
|
||||||
const body = await jsonBody(req, res);
|
|
||||||
if (body === undefined)
|
|
||||||
return;
|
|
||||||
const stats = await sync.syncOnce();
|
|
||||||
json(res, 200, { ok: true, stats, conflicts: await sync.conflictDetails() });
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
if (suffix === '/resolve') {
|
|
||||||
if (req.method !== 'POST') {
|
|
||||||
fail(res, 405, 'method-not-allowed');
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
const body = await jsonBody(req, res);
|
|
||||||
if (body === undefined)
|
|
||||||
return;
|
|
||||||
const result = await sync.resolveConflict(body.name, body.action, body.conflictId);
|
|
||||||
json(res, 200, { ok: true, ...result, conflicts: await sync.conflictDetails() });
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
if (suffix === '/resolve-all') {
|
|
||||||
if (req.method !== 'POST') {
|
|
||||||
fail(res, 405, 'method-not-allowed');
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
const body = await jsonBody(req, res);
|
|
||||||
if (body === undefined)
|
|
||||||
return;
|
|
||||||
const result = await sync.resolveConflicts(body.action, body.conflictIds);
|
|
||||||
json(res, 200, { ok: true, ...result, stats: sync.stats(), conflicts: await sync.conflictDetails() });
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
fail(res, 404, 'unknown-sync-route');
|
|
||||||
}
|
|
||||||
catch (error) {
|
|
||||||
const message = error instanceof Error ? error.message : String(error);
|
|
||||||
const known = ['invalid_name', 'invalid_action', 'no_local_copy', 'no_cloud_copy', 'stale_revision', 'sync_running', 'manifest_mismatch'];
|
|
||||||
const code = known.includes(message) ? message : 'internal';
|
|
||||||
const status = code === 'internal' ? 500
|
|
||||||
: code === 'invalid_name' || code === 'invalid_action' ? 400
|
|
||||||
: 409;
|
|
||||||
json(res, status, { ok: false, code, error: message });
|
|
||||||
}
|
|
||||||
}
|
|
||||||
/** Cloud-sync routes; the root aggregator decides the registration order. */
|
|
||||||
export function createCloudSyncRoutes(deps) {
|
|
||||||
return [
|
|
||||||
{ kind: 'exact', path: PATHS.login, handler: (req, res) => serveLogin(deps, req, res) },
|
|
||||||
{ kind: 'exact', path: PATHS.test, handler: (req, res) => serveTest(deps, req, res) },
|
|
||||||
{ kind: 'exact', path: PATHS.flush, handler: (req, res) => serveFlush(deps, req, res) },
|
|
||||||
{ kind: 'prefix', path: PATHS.sync, handler: (req, res) => serveSync(deps, req, res) },
|
|
||||||
];
|
|
||||||
}
|
|
||||||
|
|
@ -1,47 +0,0 @@
|
||||||
/**
|
|
||||||
* Cloud-sync bundle — the remote side of the memory feature.
|
|
||||||
*
|
|
||||||
* This module owns the concrete transport: one cloud client per connection,
|
|
||||||
* with the package settings sidecar as the fallback for any field the
|
|
||||||
* connection left empty. The memory bundle consumes the `MemoryRemote`
|
|
||||||
* contract and never sees this file — the composition root injects the
|
|
||||||
* factory, so swapping the transport never touches the tools or the
|
|
||||||
* Mnemon provider.
|
|
||||||
*/
|
|
||||||
import { CloudClient } from "./api.js";
|
|
||||||
import { SettingsStore } from "./store.js";
|
|
||||||
/** Build a factory over live settings closures (the composition root's path). */
|
|
||||||
export function createCloudMemoryRemoteFactory(deps) {
|
|
||||||
let shared;
|
|
||||||
return {
|
|
||||||
current: () => {
|
|
||||||
shared ??= new CloudClient({
|
|
||||||
baseUrl: () => deps.settings().baseUrl,
|
|
||||||
token: () => deps.memoryToken(),
|
|
||||||
timeoutMs: () => deps.settings().requestTimeoutMs,
|
|
||||||
});
|
|
||||||
return shared;
|
|
||||||
},
|
|
||||||
forConnection: (connection) => new CloudClient({
|
|
||||||
baseUrl: () => connection.endpoint ?? deps.settings().baseUrl,
|
|
||||||
token: () => connection.token ?? deps.memoryToken(),
|
|
||||||
timeoutMs: () => connection.timeoutMs ?? deps.settings().requestTimeoutMs,
|
|
||||||
}),
|
|
||||||
};
|
|
||||||
}
|
|
||||||
/**
|
|
||||||
* The standalone Mnemon-provider path: the same factory, backed lazily by
|
|
||||||
* the settings sidecar so a provider constructed before any configuration
|
|
||||||
* still resolves against live settings at call time.
|
|
||||||
*/
|
|
||||||
export function createSidecarMemoryRemoteFactory() {
|
|
||||||
let store;
|
|
||||||
const ensure = () => {
|
|
||||||
store ??= new SettingsStore({});
|
|
||||||
return store;
|
|
||||||
};
|
|
||||||
return createCloudMemoryRemoteFactory({
|
|
||||||
settings: () => ensure().settings(),
|
|
||||||
memoryToken: () => ensure().memoryToken(),
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
@ -1,13 +1,11 @@
|
||||||
/**
|
/**
|
||||||
* Settings model: the cordis row config supplies defaults, the user-editable
|
* Settings model: the cordis row config supplies defaults, the user-editable
|
||||||
* sidecar (`$DSH_HOME/dsh-brain.json`) overrides them, and secrets live ONLY
|
* sidecar (`$DSH_HOME/cloud-memory.json`) overrides them, and secrets live ONLY
|
||||||
* in the sidecar. Nothing here ever reaches the conversation or a model context.
|
* in the sidecar. Nothing here ever reaches the conversation or a model context.
|
||||||
*/
|
*/
|
||||||
/** Defaults written into cordis.patch.yml; also the fallback for missing keys. */
|
/** Defaults written into cordis.patch.yml; also the fallback for missing keys. */
|
||||||
export const DEFAULT_SETTINGS = {
|
export const DEFAULT_SETTINGS = {
|
||||||
enabled: true,
|
enabled: true,
|
||||||
activityEnabled: true,
|
|
||||||
memoryEnabled: true,
|
|
||||||
baseUrl: 'https://your-memory-host/api/longmemory',
|
baseUrl: 'https://your-memory-host/api/longmemory',
|
||||||
clientId: 'dsh-desktop',
|
clientId: 'dsh-desktop',
|
||||||
requestTimeoutMs: 5000,
|
requestTimeoutMs: 5000,
|
||||||
|
|
@ -16,20 +14,6 @@ export const DEFAULT_SETTINGS = {
|
||||||
summaryMaxChars: 6000,
|
summaryMaxChars: 6000,
|
||||||
skillsSyncEnabled: true,
|
skillsSyncEnabled: true,
|
||||||
skillsDir: '',
|
skillsDir: '',
|
||||||
/** Local-first memory: on by default, independent of any cloud account. */
|
|
||||||
localMemoryEnabled: true,
|
|
||||||
/** Cloud memory adapter; off by default in the local-first phase. */
|
|
||||||
cloudMemoryEnabled: false,
|
|
||||||
/** Automatically create the global and current-project spaces. */
|
|
||||||
autoMemorySpaces: true,
|
|
||||||
/** Automatically capture explicit long-term facts from conversation turns. */
|
|
||||||
autoSummaryEnabled: true,
|
|
||||||
/** Automatically maintain the USER.md profile from explicit preferences. */
|
|
||||||
autoProfileEnabled: true,
|
|
||||||
/** Default result count for local memory search. */
|
|
||||||
localMemoryK: 5,
|
|
||||||
/** Diagnostic JSONL logs under .dsh/brain/logs; defaults on, inherits enabled. */
|
|
||||||
diagnosticsEnabled: true,
|
|
||||||
};
|
};
|
||||||
const MIN_TIMEOUT_MS = 1000;
|
const MIN_TIMEOUT_MS = 1000;
|
||||||
const MAX_TIMEOUT_MS = 60_000;
|
const MAX_TIMEOUT_MS = 60_000;
|
||||||
|
|
@ -70,10 +54,14 @@ export function isPlaceholderBaseUrl(value) {
|
||||||
const normalized = normalizeBaseUrl(value);
|
const normalized = normalizeBaseUrl(value);
|
||||||
if (normalized === undefined)
|
if (normalized === undefined)
|
||||||
return true;
|
return true;
|
||||||
// normalized was built from a successfully parsed URL, so this cannot throw.
|
try {
|
||||||
const host = new URL(normalized).hostname.toLowerCase();
|
const host = new URL(normalized).hostname.toLowerCase();
|
||||||
return host === 'your-memory-host' || host === 'example.com';
|
return host === 'your-memory-host' || host === 'example.com';
|
||||||
}
|
}
|
||||||
|
catch {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
}
|
||||||
/** Service origin of one base URL, or '' when it cannot be parsed. */
|
/** Service origin of one base URL, or '' when it cannot be parsed. */
|
||||||
export function originOf(value) {
|
export function originOf(value) {
|
||||||
try {
|
try {
|
||||||
|
|
@ -97,10 +85,6 @@ export function settingsFromConfig(raw) {
|
||||||
const result = {};
|
const result = {};
|
||||||
if (typeof source.enabled === 'boolean')
|
if (typeof source.enabled === 'boolean')
|
||||||
result.enabled = source.enabled;
|
result.enabled = source.enabled;
|
||||||
if (typeof source.activityEnabled === 'boolean')
|
|
||||||
result.activityEnabled = source.activityEnabled;
|
|
||||||
if (typeof source.memoryEnabled === 'boolean')
|
|
||||||
result.memoryEnabled = source.memoryEnabled;
|
|
||||||
const baseUrl = normalizeBaseUrl(source.baseUrl);
|
const baseUrl = normalizeBaseUrl(source.baseUrl);
|
||||||
if (baseUrl !== undefined)
|
if (baseUrl !== undefined)
|
||||||
result.baseUrl = baseUrl;
|
result.baseUrl = baseUrl;
|
||||||
|
|
@ -122,20 +106,5 @@ export function settingsFromConfig(raw) {
|
||||||
result.skillsSyncEnabled = source.skillsSyncEnabled;
|
result.skillsSyncEnabled = source.skillsSyncEnabled;
|
||||||
if (typeof source.skillsDir === 'string')
|
if (typeof source.skillsDir === 'string')
|
||||||
result.skillsDir = source.skillsDir.trim().slice(0, 512);
|
result.skillsDir = source.skillsDir.trim().slice(0, 512);
|
||||||
if (typeof source.localMemoryEnabled === 'boolean')
|
|
||||||
result.localMemoryEnabled = source.localMemoryEnabled;
|
|
||||||
if (typeof source.cloudMemoryEnabled === 'boolean')
|
|
||||||
result.cloudMemoryEnabled = source.cloudMemoryEnabled;
|
|
||||||
if (typeof source.autoMemorySpaces === 'boolean')
|
|
||||||
result.autoMemorySpaces = source.autoMemorySpaces;
|
|
||||||
if (typeof source.autoSummaryEnabled === 'boolean')
|
|
||||||
result.autoSummaryEnabled = source.autoSummaryEnabled;
|
|
||||||
if (typeof source.autoProfileEnabled === 'boolean')
|
|
||||||
result.autoProfileEnabled = source.autoProfileEnabled;
|
|
||||||
if (typeof source.diagnosticsEnabled === 'boolean')
|
|
||||||
result.diagnosticsEnabled = source.diagnosticsEnabled;
|
|
||||||
const localMemoryK = boundedInt(source.localMemoryK, 1, 100);
|
|
||||||
if (localMemoryK !== undefined)
|
|
||||||
result.localMemoryK = localMemoryK;
|
|
||||||
return result;
|
return result;
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -1,152 +0,0 @@
|
||||||
/**
|
|
||||||
* Diagnostic JSONL logging for dsh-brain.
|
|
||||||
*
|
|
||||||
* Layout: <root>/logs/brain-YYYY-MM-DD.log, with numbered rollover files when
|
|
||||||
* one day's file exceeds the size cap. Global events go to $DSH_HOME/brain,
|
|
||||||
* workspace-scoped events to <project>/.dsh/brain. Writes are asynchronous and
|
|
||||||
* must never affect the operation they describe: every failure is swallowed
|
|
||||||
* after one console.warn.
|
|
||||||
*/
|
|
||||||
import { appendFile, mkdir, readdir, rename, stat, unlink } from 'node:fs/promises';
|
|
||||||
import { join } from 'node:path';
|
|
||||||
import { containsSecret } from "./local-memory/storage.js";
|
|
||||||
const MAX_FIELD_CHARS = 120;
|
|
||||||
const MAX_ERR_CHARS = 300;
|
|
||||||
const DEFAULT_MAX_BYTES = 5 * 1024 * 1024;
|
|
||||||
const DEFAULT_RETENTION_DAYS = 14;
|
|
||||||
function pad(value) { return value < 10 ? '0' + String(value) : String(value); }
|
|
||||||
function dateStamp(date) { return String(date.getFullYear()) + '-' + pad(date.getMonth() + 1) + '-' + pad(date.getDate()); }
|
|
||||||
/** Keep only small structured fields; long strings are truncated and secrets redacted. */
|
|
||||||
function sanitizeValue(value) {
|
|
||||||
if (typeof value === 'string') {
|
|
||||||
if (containsSecret(value))
|
|
||||||
return '[redacted]';
|
|
||||||
return value.length > MAX_FIELD_CHARS ? value.slice(0, MAX_FIELD_CHARS - 1) + '…' : value;
|
|
||||||
}
|
|
||||||
if (typeof value === 'number' || typeof value === 'boolean' || value === null)
|
|
||||||
return value;
|
|
||||||
if (Array.isArray(value))
|
|
||||||
return value.slice(0, 20).map((item) => sanitizeValue(item));
|
|
||||||
if (typeof value === 'object' && value !== undefined) {
|
|
||||||
const record = {};
|
|
||||||
for (const [key, item] of Object.entries(value))
|
|
||||||
record[key] = sanitizeValue(item);
|
|
||||||
return record;
|
|
||||||
}
|
|
||||||
return undefined;
|
|
||||||
}
|
|
||||||
function sanitizeDetail(detail) {
|
|
||||||
if (detail === undefined)
|
|
||||||
return undefined;
|
|
||||||
const result = {};
|
|
||||||
for (const [key, value] of Object.entries(detail)) {
|
|
||||||
const sanitized = sanitizeValue(value);
|
|
||||||
if (sanitized !== undefined)
|
|
||||||
result[key] = sanitized;
|
|
||||||
}
|
|
||||||
return result;
|
|
||||||
}
|
|
||||||
export class BrainLogger {
|
|
||||||
opts;
|
|
||||||
queue = Promise.resolve();
|
|
||||||
warned = false;
|
|
||||||
constructor(options) {
|
|
||||||
this.opts = {
|
|
||||||
globalRoot: options.globalRoot,
|
|
||||||
projectRootOf: options.projectRootOf,
|
|
||||||
enabled: options.enabled,
|
|
||||||
maxBytes: options.maxBytes ?? DEFAULT_MAX_BYTES,
|
|
||||||
retentionDays: options.retentionDays ?? DEFAULT_RETENTION_DAYS,
|
|
||||||
now: options.now ?? (() => new Date()),
|
|
||||||
};
|
|
||||||
}
|
|
||||||
/** Synchronous enqueue; asynchronous append. Never throws. */
|
|
||||||
log(event) {
|
|
||||||
try {
|
|
||||||
if (!this.opts.enabled())
|
|
||||||
return;
|
|
||||||
const now = this.opts.now();
|
|
||||||
const scope = event.scope ?? (event.workspace === undefined ? 'global' : 'project');
|
|
||||||
const record = {
|
|
||||||
ts: now.toISOString(),
|
|
||||||
level: event.level ?? 'info',
|
|
||||||
event: event.event,
|
|
||||||
scope,
|
|
||||||
};
|
|
||||||
if (event.workspace !== undefined)
|
|
||||||
record.workspace = event.workspace;
|
|
||||||
if (event.sessionId !== undefined)
|
|
||||||
record.sessionId = event.sessionId;
|
|
||||||
const detail = sanitizeDetail(event.detail);
|
|
||||||
if (detail !== undefined && Object.keys(detail).length > 0)
|
|
||||||
record.detail = detail;
|
|
||||||
if (event.err !== undefined) {
|
|
||||||
const err = containsSecret(event.err) ? '[redacted]' : event.err.length > MAX_ERR_CHARS ? event.err.slice(0, MAX_ERR_CHARS - 1) + '…' : event.err;
|
|
||||||
record.err = err;
|
|
||||||
}
|
|
||||||
const line = JSON.stringify(record) + '\n';
|
|
||||||
const directory = this.directoryFor(scope, event.workspace);
|
|
||||||
this.queue = this.queue.then(() => this.appendLine(directory, dateStamp(now), line)).catch(() => { this.warnOnce(); });
|
|
||||||
}
|
|
||||||
catch {
|
|
||||||
this.warnOnce();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
/** Await all queued writes (tests / graceful shutdown). */
|
|
||||||
async flush() {
|
|
||||||
await this.queue.catch(() => { });
|
|
||||||
}
|
|
||||||
/** Start-of-boot retention sweep; fire-and-forget and never throws. */
|
|
||||||
prune() {
|
|
||||||
void this.pruneAsync().catch(() => { });
|
|
||||||
}
|
|
||||||
directoryFor(scope, workspace) {
|
|
||||||
return scope === 'project' ? join(this.opts.projectRootOf(workspace), 'logs') : join(this.opts.globalRoot(), 'logs');
|
|
||||||
}
|
|
||||||
async appendLine(directory, stamp, line) {
|
|
||||||
await mkdir(directory, { recursive: true });
|
|
||||||
let file = join(directory, 'brain-' + stamp + '.log');
|
|
||||||
try {
|
|
||||||
const info = await stat(file);
|
|
||||||
if (info.size > 0 && info.size + Buffer.byteLength(line) > this.opts.maxBytes) {
|
|
||||||
let index = 1;
|
|
||||||
while (true) {
|
|
||||||
const candidate = join(directory, 'brain-' + stamp + '.' + String(index) + '.log');
|
|
||||||
const exists = await stat(candidate).catch(() => undefined);
|
|
||||||
if (exists === undefined) {
|
|
||||||
await rename(file, candidate);
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
index += 1;
|
|
||||||
}
|
|
||||||
file = join(directory, 'brain-' + stamp + '.log');
|
|
||||||
}
|
|
||||||
}
|
|
||||||
catch {
|
|
||||||
/* first write of the day: the file does not exist yet */
|
|
||||||
}
|
|
||||||
await appendFile(file, line, { encoding: 'utf8' });
|
|
||||||
}
|
|
||||||
async pruneAsync() {
|
|
||||||
const roots = new Set([this.opts.globalRoot(), this.opts.projectRootOf(undefined)]);
|
|
||||||
const cutoff = this.opts.now().getTime() - this.opts.retentionDays * 24 * 60 * 60 * 1000;
|
|
||||||
for (const root of roots) {
|
|
||||||
const directory = join(root, 'logs');
|
|
||||||
const entries = await readdir(directory).catch(() => []);
|
|
||||||
for (const name of entries) {
|
|
||||||
const match = /^brain-(\d{4}-\d{2}-\d{2})(?:\.\d+)?\.log$/.exec(name);
|
|
||||||
if (match === null)
|
|
||||||
continue;
|
|
||||||
const stamp = Date.parse(match[1] + 'T00:00:00');
|
|
||||||
if (Number.isFinite(stamp) && stamp < cutoff)
|
|
||||||
await unlink(join(directory, name)).catch(() => { });
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
warnOnce() {
|
|
||||||
if (this.warned)
|
|
||||||
return;
|
|
||||||
this.warned = true;
|
|
||||||
console.warn('[dsh-brain] diagnostic log write failed; continuing without logs');
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
@ -1,67 +0,0 @@
|
||||||
import { brainKernel, VERSION } from "../kernel.js";
|
|
||||||
import { buildStatusPayload, legacyAliases } from "../routes.js";
|
|
||||||
import { createCloudSyncRoutes } from "../cloudsync-routes.js";
|
|
||||||
export const name = 'dsh-brain-cloudsync';
|
|
||||||
/** Services required before `apply` runs. */
|
|
||||||
export const inject = ['webServer'];
|
|
||||||
/** How often the skill directory is reconciled with the cloud center. */
|
|
||||||
const SKILL_SYNC_INTERVAL_MS = 15 * 60_000;
|
|
||||||
/** How often queued reports are retried. */
|
|
||||||
const RETRY_INTERVAL_MS = 30_000;
|
|
||||||
/** Register the sub-plugin with the host. */
|
|
||||||
export function apply(ctx, config) {
|
|
||||||
const logger = ctx.logger('dsh-brain');
|
|
||||||
const kernel = brainKernel(config, logger);
|
|
||||||
kernel.activate('cloudsync');
|
|
||||||
kernel.logEvent('boot.entry', { bundle: 'cloudsync' });
|
|
||||||
ctx.effect(() => () => kernel.deactivate('cloudsync'), 'dsh-brain-cloudsync: activation');
|
|
||||||
// The host's `Events` map is augmented by @deepseek-ai/dsh-session, which a
|
|
||||||
// third-party bundle cannot rely on; bind the listener through a local shape.
|
|
||||||
const onEvent = ctx.on;
|
|
||||||
ctx.effect(() => onEvent('session/event', (session, event) => {
|
|
||||||
try {
|
|
||||||
kernel.reporter.handleEvent(session, event);
|
|
||||||
}
|
|
||||||
catch (error) {
|
|
||||||
logger.warn(`turn event handling failed: ${error instanceof Error ? error.message : String(error)}`);
|
|
||||||
}
|
|
||||||
}), 'dsh-brain-cloudsync: turn reporting');
|
|
||||||
ctx.effect(() => {
|
|
||||||
const timer = setInterval(() => {
|
|
||||||
if (kernel.store.activityToken() !== '' && kernel.settings().activityEnabled) {
|
|
||||||
void kernel.reporter.flush().catch((error) => {
|
|
||||||
logger.warn(`retry flush failed: ${error instanceof Error ? error.message : String(error)}`);
|
|
||||||
});
|
|
||||||
}
|
|
||||||
}, RETRY_INTERVAL_MS);
|
|
||||||
timer.unref?.();
|
|
||||||
return () => clearInterval(timer);
|
|
||||||
}, 'dsh-brain-cloudsync: retry timer');
|
|
||||||
ctx.effect(() => {
|
|
||||||
const run = () => {
|
|
||||||
if (kernel.store.memoryToken() !== '')
|
|
||||||
void kernel.skillSync.syncOnce().catch(() => { });
|
|
||||||
};
|
|
||||||
const first = setTimeout(run, 5_000);
|
|
||||||
first.unref?.();
|
|
||||||
const timer = setInterval(run, SKILL_SYNC_INTERVAL_MS);
|
|
||||||
timer.unref?.();
|
|
||||||
return () => { clearTimeout(first); clearInterval(timer); };
|
|
||||||
}, 'dsh-brain-cloudsync: skill sync timer');
|
|
||||||
const webServer = ctx.webServer;
|
|
||||||
if (webServer === undefined) {
|
|
||||||
logger.warn('webServer service unavailable; cloud-sync routes stay disabled');
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
const routes = createCloudSyncRoutes({
|
|
||||||
store: kernel.store,
|
|
||||||
client: () => kernel.client,
|
|
||||||
reporter: kernel.reporter,
|
|
||||||
sync: kernel.skillSync,
|
|
||||||
statusView: () => buildStatusPayload(kernel.routeDeps()),
|
|
||||||
});
|
|
||||||
routes.push(...legacyAliases(routes));
|
|
||||||
for (const route of routes) {
|
|
||||||
ctx.effect(() => webServer.register(route), `dsh-brain-cloudsync: route ${route.path}`);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
@ -1,11 +0,0 @@
|
||||||
import { brainKernel } from "../kernel.js";
|
|
||||||
export const name = 'dsh-brain-mcp';
|
|
||||||
/** Services required before `apply` runs (none: activation only). */
|
|
||||||
export const inject = [];
|
|
||||||
/** Register the sub-plugin with the host. */
|
|
||||||
export function apply(ctx, config) {
|
|
||||||
const kernel = brainKernel(config, ctx.logger('dsh-brain'));
|
|
||||||
kernel.activate('mcp');
|
|
||||||
kernel.logEvent('boot.entry', { bundle: 'mcp' });
|
|
||||||
ctx.effect(() => () => kernel.deactivate('mcp'), 'dsh-brain-mcp: activation');
|
|
||||||
}
|
|
||||||
|
|
@ -1,145 +0,0 @@
|
||||||
import { brainKernel } from "../kernel.js";
|
|
||||||
import { createMemoryTools } from "../memory/tools.js";
|
|
||||||
import { createMnemonMemoryRemote } from "../memory/mnemon-remote.js";
|
|
||||||
import { mnemonToolsFromContext } from "../mnemon/read-service.js";
|
|
||||||
import { createDepartmentTools } from "../memory/departments-tools.js";
|
|
||||||
import { conversationIdOf, redactSecrets, textOf, turnOf } from "../reporter.js";
|
|
||||||
export const name = 'dsh-brain-memory';
|
|
||||||
/** Services required before `apply` runs. */
|
|
||||||
export const inject = ['tools'];
|
|
||||||
/** Register the sub-plugin with the host. */
|
|
||||||
export function apply(ctx, config) {
|
|
||||||
const logger = ctx.logger('dsh-brain');
|
|
||||||
const kernel = brainKernel(config, logger);
|
|
||||||
kernel.activate('memory');
|
|
||||||
kernel.logEvent('boot.entry', { bundle: 'memory' });
|
|
||||||
ctx.effect(() => () => kernel.deactivate('memory'), 'dsh-brain-memory: activation');
|
|
||||||
ctx.inject(['tools'], (toolsCtx) => {
|
|
||||||
const tools = toolsCtx.tools;
|
|
||||||
if (tools === undefined)
|
|
||||||
return;
|
|
||||||
const remote = createMnemonMemoryRemote(() => mnemonToolsFromContext(toolsCtx));
|
|
||||||
for (const tool of createMemoryTools({
|
|
||||||
remote: () => remote,
|
|
||||||
settings: () => {
|
|
||||||
const settings = kernel.settings();
|
|
||||||
return { enabled: settings.memoryEnabled, defaultK: settings.localMemoryK };
|
|
||||||
},
|
|
||||||
})) {
|
|
||||||
toolsCtx.effect(() => tools.register(tool), `dsh-brain-memory: tool ${tool.name}`);
|
|
||||||
}
|
|
||||||
for (const tool of createDepartmentTools(kernel.departmentToolDeps())) {
|
|
||||||
toolsCtx.effect(() => tools.register(tool), `dsh-brain-memory: tool ${tool.name}`);
|
|
||||||
}
|
|
||||||
});
|
|
||||||
// Project the compact USER.md/MEMORY.md state into the system prompt each turn.
|
|
||||||
// The files are generated from explicit profile/rule records only.
|
|
||||||
ctx.inject(['systemPrompt'], (prompted) => {
|
|
||||||
const host = prompted;
|
|
||||||
const service = typeof host.get === 'function' ? host.get('systemPrompt') : host.systemPrompt;
|
|
||||||
const prompt = service;
|
|
||||||
prompt?.section?.({
|
|
||||||
name: 'dsh-brain:local-memory',
|
|
||||||
order: 151,
|
|
||||||
text: () => kernel.settings().localMemoryEnabled === false ? '' : kernel.localMemory.projectionText(),
|
|
||||||
});
|
|
||||||
});
|
|
||||||
// Local automatic summary: consume real host messages (structured content),
|
|
||||||
// ignore host/plugin injections, and persist progress by stable session + turn.
|
|
||||||
const turns = new Map();
|
|
||||||
const pending = new Map();
|
|
||||||
const openTurns = new Map();
|
|
||||||
let flushing = false;
|
|
||||||
let retryTimer;
|
|
||||||
const onEvent = ctx.on;
|
|
||||||
const workspaceOfSession = (session) => session.cwd ?? session.workspace ?? session.header?.cwd ?? session.header?.workspace;
|
|
||||||
const isInjected = (value) => {
|
|
||||||
if (value === null || typeof value !== 'object')
|
|
||||||
return false;
|
|
||||||
const source = value.source;
|
|
||||||
if (source === null || typeof source !== 'object')
|
|
||||||
return false;
|
|
||||||
const kind = source.kind;
|
|
||||||
return typeof kind === 'string' && kind !== 'user';
|
|
||||||
};
|
|
||||||
const flushPending = async () => {
|
|
||||||
if (flushing || pending.size === 0)
|
|
||||||
return;
|
|
||||||
flushing = true;
|
|
||||||
try {
|
|
||||||
for (const [key, item] of [...pending]) {
|
|
||||||
try {
|
|
||||||
await kernel.localMemory.withWorkspace(item.workspace, () => kernel.localMemory.summarizeConversation({
|
|
||||||
sessionId: item.conversation,
|
|
||||||
turns: [{ turnId: String(item.turn), user: item.user }],
|
|
||||||
}, item.workspace));
|
|
||||||
pending.delete(key);
|
|
||||||
}
|
|
||||||
catch (error) {
|
|
||||||
item.attempts += 1;
|
|
||||||
logger.warn('dsh-brain local summary failed (will retry): ' + (error instanceof Error ? error.message : String(error)));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
finally {
|
|
||||||
flushing = false;
|
|
||||||
if (pending.size > 0) {
|
|
||||||
if (retryTimer !== undefined)
|
|
||||||
clearTimeout(retryTimer);
|
|
||||||
retryTimer = setTimeout(() => { retryTimer = undefined; void flushPending(); }, 2000);
|
|
||||||
retryTimer.unref?.();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
};
|
|
||||||
ctx.effect(() => {
|
|
||||||
const dispose = onEvent('session/event', (session, event) => {
|
|
||||||
const conversation = conversationIdOf(session);
|
|
||||||
if (conversation === undefined)
|
|
||||||
return;
|
|
||||||
if (event.type === 'turn/start') {
|
|
||||||
const started = turnOf(event.data);
|
|
||||||
if (started !== undefined)
|
|
||||||
openTurns.set(conversation, started);
|
|
||||||
void flushPending();
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
const eventTurn = turnOf(event.data);
|
|
||||||
const turn = eventTurn ?? openTurns.get(conversation);
|
|
||||||
if (event.type === 'user/message') {
|
|
||||||
const raw = textOf(event.data?.message ?? event.data);
|
|
||||||
if (turn === undefined || raw === undefined || isInjected(event.data?.message ?? event.data))
|
|
||||||
return;
|
|
||||||
const key = conversation + ':' + String(turn);
|
|
||||||
const entry = turns.get(key) ?? { turn, user: [] };
|
|
||||||
entry.user.push(redactSecrets(raw).slice(0, 4000));
|
|
||||||
turns.set(key, entry);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
if (event.type === 'turn/end' && turn !== undefined) {
|
|
||||||
const key = conversation + ':' + String(turn);
|
|
||||||
const entry = turns.get(key);
|
|
||||||
turns.delete(key);
|
|
||||||
if (eventTurn === undefined || openTurns.get(conversation) === eventTurn)
|
|
||||||
openTurns.delete(conversation);
|
|
||||||
if (entry === undefined || entry.user.length === 0)
|
|
||||||
return;
|
|
||||||
const settings = kernel.settings();
|
|
||||||
if (settings.localMemoryEnabled === false || settings.autoSummaryEnabled === false)
|
|
||||||
return;
|
|
||||||
pending.set(key, { conversation, turn, ...(workspaceOfSession(session) === undefined ? {} : { workspace: workspaceOfSession(session) }), user: entry.user.join('\n'), attempts: 0 });
|
|
||||||
void flushPending();
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
if (event.type === 'session/end' || event.type === 'session/close' || event.type === 'session/closed' || event.type === 'session/terminated') {
|
|
||||||
openTurns.delete(conversation);
|
|
||||||
for (const key of turns.keys())
|
|
||||||
if (key.startsWith(conversation + ':'))
|
|
||||||
turns.delete(key);
|
|
||||||
}
|
|
||||||
});
|
|
||||||
return () => { dispose(); if (retryTimer !== undefined) {
|
|
||||||
clearTimeout(retryTimer);
|
|
||||||
retryTimer = undefined;
|
|
||||||
} };
|
|
||||||
}, 'dsh-brain-memory: local summary');
|
|
||||||
}
|
|
||||||
|
|
@ -1,115 +0,0 @@
|
||||||
import { createRawMemoryRuntime } from "../raw-memory/index.js";
|
|
||||||
import { createRawMemoryRoutes } from "../raw-memory/routes.js";
|
|
||||||
import { conversationIdOf, redactSecrets, textOf, turnOf } from "../reporter.js";
|
|
||||||
export const name = 'dsh-brain-raw';
|
|
||||||
/** Services required before `apply` runs. */
|
|
||||||
export const inject = ['tools'];
|
|
||||||
function isInjected(value) {
|
|
||||||
if (value === null || typeof value !== 'object')
|
|
||||||
return false;
|
|
||||||
const source = value.source;
|
|
||||||
if (source === null || typeof source !== 'object')
|
|
||||||
return false;
|
|
||||||
const kind = source.kind;
|
|
||||||
return typeof kind === 'string' && kind !== 'user';
|
|
||||||
}
|
|
||||||
function workspaceOf(session) {
|
|
||||||
return session.cwd ?? session.workspace ?? session.header?.cwd ?? session.header?.workspace;
|
|
||||||
}
|
|
||||||
function messageIdOf(value) {
|
|
||||||
if (value === null || typeof value !== 'object')
|
|
||||||
return undefined;
|
|
||||||
const id = value.id;
|
|
||||||
return typeof id === 'string' && id !== '' ? id : undefined;
|
|
||||||
}
|
|
||||||
function epochOf(time) {
|
|
||||||
if (typeof time === 'number' && Number.isFinite(time))
|
|
||||||
return time;
|
|
||||||
if (typeof time === 'string' && time.trim() !== '') {
|
|
||||||
const parsed = Date.parse(time);
|
|
||||||
return Number.isFinite(parsed) ? parsed : undefined;
|
|
||||||
}
|
|
||||||
return undefined;
|
|
||||||
}
|
|
||||||
/** Register the raw recorder with the host. */
|
|
||||||
export function apply(ctx, config) {
|
|
||||||
const runtime = createRawMemoryRuntime(config);
|
|
||||||
const logger = ctx.logger('dsh-brain');
|
|
||||||
ctx.inject(['tools'], (toolsCtx) => {
|
|
||||||
const tools = toolsCtx.tools;
|
|
||||||
if (tools === undefined)
|
|
||||||
return;
|
|
||||||
for (const tool of runtime.tools) {
|
|
||||||
toolsCtx.effect(() => tools.register(tool), `dsh-brain-raw: tool ${tool.name}`);
|
|
||||||
}
|
|
||||||
});
|
|
||||||
ctx.inject(['webServer'], (webCtx) => {
|
|
||||||
const webServer = webCtx.webServer;
|
|
||||||
if (webServer === undefined)
|
|
||||||
return;
|
|
||||||
for (const route of createRawMemoryRoutes({ store: runtime.store, settings: () => runtime.settings })) {
|
|
||||||
webCtx.effect(() => webServer.register(route), `dsh-brain-raw: route ${route.path}`);
|
|
||||||
}
|
|
||||||
});
|
|
||||||
const seen = new Map();
|
|
||||||
const onEvent = ctx.on;
|
|
||||||
ctx.effect(() => {
|
|
||||||
const dispose = onEvent('session/event', (session, event) => {
|
|
||||||
if (!runtime.settings.enabled)
|
|
||||||
return;
|
|
||||||
if (event === null || typeof event !== 'object')
|
|
||||||
return;
|
|
||||||
if (event.type !== 'user/message' && event.type !== 'assistant/message')
|
|
||||||
return;
|
|
||||||
if (event.type === 'assistant/message' && !runtime.settings.captureAssistant)
|
|
||||||
return;
|
|
||||||
const sessionId = conversationIdOf(session);
|
|
||||||
if (sessionId === undefined)
|
|
||||||
return;
|
|
||||||
const value = event.data?.message ?? event.data;
|
|
||||||
if (event.type === 'user/message' && isInjected(value))
|
|
||||||
return;
|
|
||||||
const raw = textOf(value);
|
|
||||||
if (raw === undefined || raw.trim() === '')
|
|
||||||
return;
|
|
||||||
const seq = typeof event.seq === 'number' && Number.isFinite(event.seq) ? event.seq : undefined;
|
|
||||||
const dedupe = `${sessionId}:${seq === undefined ? event.type + ':' + raw.slice(0, 120) : String(seq)}:${event.type}`;
|
|
||||||
if (seen.has(dedupe))
|
|
||||||
return;
|
|
||||||
seen.set(dedupe, Date.now());
|
|
||||||
if (seen.size > 10_000) {
|
|
||||||
const oldest = seen.keys().next();
|
|
||||||
if (oldest.done !== true)
|
|
||||||
seen.delete(oldest.value);
|
|
||||||
}
|
|
||||||
const turn = turnOf(event.data);
|
|
||||||
const messageId = messageIdOf(value);
|
|
||||||
const time = epochOf(event.time);
|
|
||||||
const workspace = workspaceOf(session);
|
|
||||||
const record = {
|
|
||||||
v: 1,
|
|
||||||
sessionId,
|
|
||||||
...(seq === undefined ? {} : { seq }),
|
|
||||||
...(turn === undefined ? {} : { turn }),
|
|
||||||
role: event.type === 'user/message' ? 'user' : 'assistant',
|
|
||||||
text: redactSecrets(raw).slice(0, runtime.settings.maxTextChars),
|
|
||||||
...(time === undefined ? {} : { time }),
|
|
||||||
...(messageId === undefined ? {} : { messageId }),
|
|
||||||
createdAt: Date.now(),
|
|
||||||
...(workspace === undefined ? {} : { workspace }),
|
|
||||||
};
|
|
||||||
void runtime.store.append(record).catch((error) => {
|
|
||||||
logger.warn('dsh-brain-raw capture failed: ' + (error instanceof Error ? error.message : String(error)));
|
|
||||||
});
|
|
||||||
});
|
|
||||||
return () => dispose();
|
|
||||||
}, 'dsh-brain-raw: session capture');
|
|
||||||
// Retention is checked once on load and then every six hours; it only deletes
|
|
||||||
// whole session files whose last write is older than the configured window.
|
|
||||||
ctx.effect(() => {
|
|
||||||
void runtime.store.prune(runtime.settings.retentionDays).catch(() => undefined);
|
|
||||||
const timer = setInterval(() => { void runtime.store.prune(runtime.settings.retentionDays); }, 6 * 60 * 60 * 1000);
|
|
||||||
timer.unref?.();
|
|
||||||
return () => clearInterval(timer);
|
|
||||||
}, 'dsh-brain-raw: retention');
|
|
||||||
}
|
|
||||||
|
|
@ -1,7 +0,0 @@
|
||||||
/**
|
|
||||||
* Backward-compatible entry alias: the bundle was renamed from
|
|
||||||
* dsh-brain-settings-ui to dsh-brain-ui. The package exports map points the
|
|
||||||
* old './settings-ui' subpath at lib/entries/ui.js; this physical module is a
|
|
||||||
* second safety net for profiles that resolve the old file path directly.
|
|
||||||
*/
|
|
||||||
export * from "./ui.js";
|
|
||||||
|
|
@ -1,40 +0,0 @@
|
||||||
import { brainKernel, VERSION } from "../kernel.js";
|
|
||||||
import { legacyAliases } from "../routes.js";
|
|
||||||
import { createSkillRoutes } from "../skills/routes.js";
|
|
||||||
import { createSkillTools } from "../tools.js";
|
|
||||||
export const name = 'dsh-brain-skills';
|
|
||||||
/** Services required before `apply` runs. */
|
|
||||||
export const inject = ['tools', 'webServer'];
|
|
||||||
/** Register the sub-plugin with the host. */
|
|
||||||
export function apply(ctx, config) {
|
|
||||||
const logger = ctx.logger('dsh-brain');
|
|
||||||
const kernel = brainKernel(config, logger);
|
|
||||||
kernel.activate('skills');
|
|
||||||
kernel.logEvent('boot.entry', { bundle: 'skills' });
|
|
||||||
ctx.effect(() => () => kernel.deactivate('skills'), 'dsh-brain-skills: activation');
|
|
||||||
ctx.inject(['tools'], (toolsCtx) => {
|
|
||||||
const tools = toolsCtx.tools;
|
|
||||||
if (tools === undefined)
|
|
||||||
return;
|
|
||||||
for (const tool of createSkillTools(kernel.toolDeps())) {
|
|
||||||
toolsCtx.effect(() => tools.register(tool), `dsh-brain-skills: tool ${tool.name}`);
|
|
||||||
}
|
|
||||||
});
|
|
||||||
const webServer = ctx.webServer;
|
|
||||||
if (webServer === undefined) {
|
|
||||||
logger.warn('webServer service unavailable; skill routes stay disabled');
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
const routes = createSkillRoutes({
|
|
||||||
version: VERSION,
|
|
||||||
admin: kernel.skillAdmin,
|
|
||||||
groups: kernel.skillGroups,
|
|
||||||
market: kernel.market,
|
|
||||||
updates: kernel.updater,
|
|
||||||
clients: kernel.clients,
|
|
||||||
});
|
|
||||||
routes.push(...legacyAliases(routes));
|
|
||||||
for (const route of routes) {
|
|
||||||
ctx.effect(() => webServer.register(route), `dsh-brain-skills: route ${route.path}`);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
@ -1,47 +0,0 @@
|
||||||
import { brainKernel, VERSION } from "../kernel.js";
|
|
||||||
import { mnemonReadFromContext } from "../mnemon/read-service.js";
|
|
||||||
import { createCoreRoutes, legacyAliases } from "../routes.js";
|
|
||||||
import { createSettingsUiRoutes } from "../settings-ui/routes.js";
|
|
||||||
export const name = 'dsh-brain-ui';
|
|
||||||
/** Services required before `apply` runs. */
|
|
||||||
export const inject = ['webServer'];
|
|
||||||
/** The pre-rename row id; only used to point a stale profile at the new row. */
|
|
||||||
const LEGACY_BUNDLE_ID = 'dsh-brain-settings-ui';
|
|
||||||
function profileMentionsLegacyId(ctx) {
|
|
||||||
try {
|
|
||||||
const face = ctx;
|
|
||||||
return [face.config, face.settings].some((value) => value !== undefined && JSON.stringify(value).includes(LEGACY_BUNDLE_ID));
|
|
||||||
}
|
|
||||||
catch {
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
/** Register the sub-plugin with the host. */
|
|
||||||
export function apply(ctx, config) {
|
|
||||||
const logger = ctx.logger('dsh-brain');
|
|
||||||
const kernel = brainKernel(config, logger);
|
|
||||||
kernel.activate('ui');
|
|
||||||
kernel.logEvent('boot.entry', { bundle: 'ui' });
|
|
||||||
ctx.effect(() => () => kernel.deactivate('ui'), 'dsh-brain-ui: activation');
|
|
||||||
// We never rewrite host files: if the old row is visible in the live config
|
|
||||||
// face, tell the user which row to re-toggle after the rename.
|
|
||||||
if (profileMentionsLegacyId(ctx)) {
|
|
||||||
logger.info('detected the old plugin id ' + LEGACY_BUNDLE_ID + '; re-apply the plugin toggle under dsh-brain-ui in Settings → Plugins');
|
|
||||||
}
|
|
||||||
const webServer = ctx.webServer;
|
|
||||||
if (webServer === undefined) {
|
|
||||||
logger.warn('webServer service unavailable; the configuration page stays disabled');
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
const routes = [
|
|
||||||
...createSettingsUiRoutes({ version: VERSION, store: kernel.store }),
|
|
||||||
...createCoreRoutes({
|
|
||||||
...kernel.routeDeps(),
|
|
||||||
mnemon: () => mnemonReadFromContext(ctx),
|
|
||||||
}),
|
|
||||||
];
|
|
||||||
routes.push(...legacyAliases(routes));
|
|
||||||
for (const route of routes) {
|
|
||||||
ctx.effect(() => webServer.register(route), `dsh-brain-ui: route ${route.path}`);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
89
lib/http.js
89
lib/http.js
|
|
@ -1,89 +0,0 @@
|
||||||
/** Largest request body we accept (a settings patch is tiny). */
|
|
||||||
export const MAX_BODY_BYTES = 64 * 1024;
|
|
||||||
/** Optional diagnostics hook for failed route responses (set by the kernel). */
|
|
||||||
let routeErrorHook;
|
|
||||||
export function setRouteErrorHook(hook) {
|
|
||||||
routeErrorHook = hook;
|
|
||||||
}
|
|
||||||
/** Collect a request body as UTF-8 text. */
|
|
||||||
export async function readBody(req, maxBytes = MAX_BODY_BYTES) {
|
|
||||||
const chunks = [];
|
|
||||||
let bytes = 0;
|
|
||||||
for await (const chunk of req) {
|
|
||||||
const buffer = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);
|
|
||||||
bytes += buffer.byteLength;
|
|
||||||
if (bytes > maxBytes)
|
|
||||||
throw new Error('request-too-large');
|
|
||||||
chunks.push(buffer);
|
|
||||||
}
|
|
||||||
return Buffer.concat(chunks).toString('utf8');
|
|
||||||
}
|
|
||||||
/** Reject cross-origin browser writes. */
|
|
||||||
export function sameOrigin(req) {
|
|
||||||
const origin = req.headers.origin;
|
|
||||||
const host = req.headers.host;
|
|
||||||
if (origin === undefined || host === undefined)
|
|
||||||
return true;
|
|
||||||
return origin === `http://${host}` || origin === `https://${host}`;
|
|
||||||
}
|
|
||||||
/** Emit one JSON response with no caching. */
|
|
||||||
export function json(res, status, body) {
|
|
||||||
const text = JSON.stringify(body);
|
|
||||||
res.writeHead(status, {
|
|
||||||
'content-type': 'application/json; charset=utf-8',
|
|
||||||
'cache-control': 'no-store',
|
|
||||||
'content-length': Buffer.byteLength(text),
|
|
||||||
});
|
|
||||||
res.end(text);
|
|
||||||
}
|
|
||||||
/** Emit a plain-text error (page route) or JSON error (API routes). */
|
|
||||||
export function fail(res, status, message, asHtml = false) {
|
|
||||||
try {
|
|
||||||
routeErrorHook?.('route.error', { status, error: message, html: asHtml });
|
|
||||||
}
|
|
||||||
catch {
|
|
||||||
/* diagnostics must never change the response */
|
|
||||||
}
|
|
||||||
const text = asHtml
|
|
||||||
? `<!doctype html><meta charset="utf-8"><title>云端记忆</title><body style="font:14px system-ui;padding:32px">${message}</body>`
|
|
||||||
: JSON.stringify({ ok: false, error: message });
|
|
||||||
res.writeHead(status, {
|
|
||||||
'content-type': asHtml ? 'text/html; charset=utf-8' : 'application/json; charset=utf-8',
|
|
||||||
'cache-control': 'no-store',
|
|
||||||
});
|
|
||||||
res.end(text);
|
|
||||||
}
|
|
||||||
/**
|
|
||||||
* Read one JSON object body, or answer the request and return undefined.
|
|
||||||
*
|
|
||||||
* The method, origin and content-type gates live here so every write route
|
|
||||||
* cannot forget one of them.
|
|
||||||
*/
|
|
||||||
export async function jsonBody(req, res) {
|
|
||||||
if (req.method !== 'POST' && req.method !== 'PUT') {
|
|
||||||
fail(res, 405, 'method-not-allowed');
|
|
||||||
return undefined;
|
|
||||||
}
|
|
||||||
if (!sameOrigin(req)) {
|
|
||||||
fail(res, 403, 'origin-rejected');
|
|
||||||
return undefined;
|
|
||||||
}
|
|
||||||
const type = (req.headers['content-type'] ?? '').toLowerCase();
|
|
||||||
if (!type.startsWith('application/json')) {
|
|
||||||
fail(res, 415, 'json-required');
|
|
||||||
return undefined;
|
|
||||||
}
|
|
||||||
let parsed;
|
|
||||||
try {
|
|
||||||
parsed = JSON.parse(await readBody(req));
|
|
||||||
}
|
|
||||||
catch (error) {
|
|
||||||
fail(res, 400, error instanceof Error && error.message === 'request-too-large' ? 'request-too-large' : 'invalid-json');
|
|
||||||
return undefined;
|
|
||||||
}
|
|
||||||
if (parsed === null || typeof parsed !== 'object' || Array.isArray(parsed)) {
|
|
||||||
fail(res, 400, 'invalid-body');
|
|
||||||
return undefined;
|
|
||||||
}
|
|
||||||
return parsed;
|
|
||||||
}
|
|
||||||
177
lib/index.js
177
lib/index.js
|
|
@ -1,23 +1,168 @@
|
||||||
import * as cloudsync from "./entries/cloudsync.js";
|
/**
|
||||||
import * as memory from "./entries/memory.js";
|
* Plugin entry — host half.
|
||||||
import * as skills from "./entries/skills.js";
|
*
|
||||||
import * as mcp from "./entries/mcp.js";
|
* Responsibilities:
|
||||||
import * as ui from "./entries/ui.js";
|
* 1. report one activity record per finished conversation round,
|
||||||
import * as raw from "./entries/raw.js";
|
* 2. expose the memory tools to the agent,
|
||||||
|
* 3. serve the configuration page under `/cloud-memory`.
|
||||||
|
*
|
||||||
|
* Everything registers through `ctx.effect(...)` so a plugin reload tears down
|
||||||
|
* its routes, timer, listeners, and tools without leftovers.
|
||||||
|
*/
|
||||||
|
import { CloudClient } from "./api.js";
|
||||||
|
import { Reporter } from "./reporter.js";
|
||||||
|
import { createRoutes } from "./routes.js";
|
||||||
|
import { join } from 'node:path';
|
||||||
|
import { SettingsStore, dshHome } from "./store.js";
|
||||||
|
import { SkillSync } from "./skill-sync.js";
|
||||||
|
import { SkillAdmin, skillsHoldingDir } from "./skill-admin.js";
|
||||||
|
import { SkillGroupManager, detectSources } from "./skill-groups.js";
|
||||||
|
import { ClaudePluginMarketplaceProvider, MarketService } from "./market.js";
|
||||||
|
import { SkillUpdater } from "./skill-update.js";
|
||||||
|
import { ClientRegistry } from "./clients.js";
|
||||||
|
import { createMemoryTools, createSkillTools } from "./tools.js";
|
||||||
/** Package name; also the client bundle id. */
|
/** Package name; also the client bundle id. */
|
||||||
export const name = 'dsh-brain';
|
export const name = 'dsh-cloud-memory';
|
||||||
/** Services required before `apply` runs. */
|
/** Services required before `apply` runs. */
|
||||||
export const inject = ['webServer'];
|
export const inject = ['webServer'];
|
||||||
/** Mount the discoverable UI row or the legacy all-in-one plugin. */
|
/** Version reported by the status card. */
|
||||||
|
const VERSION = '0.7.0';
|
||||||
|
/** How often the skill directory is reconciled with the cloud center. */
|
||||||
|
const SKILL_SYNC_INTERVAL_MS = 15 * 60_000;
|
||||||
|
/** How often queued reports are retried. */
|
||||||
|
const RETRY_INTERVAL_MS = 30_000;
|
||||||
|
/** Register the plugin with the host. */
|
||||||
export function apply(ctx, config) {
|
export function apply(ctx, config) {
|
||||||
if (config !== null && typeof config === 'object' && 'entry' in config && config.entry === 'ui') {
|
const logger = ctx.logger('cloud-memory');
|
||||||
ui.apply(ctx, config);
|
const store = new SettingsStore(config);
|
||||||
|
const settings = () => store.settings();
|
||||||
|
// One client per instance; the settings closures keep it live across edits.
|
||||||
|
const client = new CloudClient({
|
||||||
|
baseUrl: () => settings().baseUrl,
|
||||||
|
token: () => store.memoryToken(),
|
||||||
|
timeoutMs: () => settings().requestTimeoutMs,
|
||||||
|
});
|
||||||
|
const reporter = new Reporter({
|
||||||
|
client,
|
||||||
|
settings: () => ({ enabled: settings().enabled, clientId: settings().clientId }),
|
||||||
|
activityToken: () => store.activityToken(),
|
||||||
|
summary: () => ({ enabled: settings().summaryEnabled, maxChars: settings().summaryMaxChars }),
|
||||||
|
summaryToken: () => store.summaryToken(),
|
||||||
|
log: (message) => logger.warn(message),
|
||||||
|
});
|
||||||
|
const skillSync = new SkillSync({
|
||||||
|
client: () => client,
|
||||||
|
settings: () => ({
|
||||||
|
enabled: settings().enabled,
|
||||||
|
skillsSyncEnabled: settings().skillsSyncEnabled,
|
||||||
|
skillsDir: settings().skillsDir,
|
||||||
|
}),
|
||||||
|
log: (message) => logger.info(message),
|
||||||
|
holdingDir: () => skillsHoldingDir(),
|
||||||
|
});
|
||||||
|
const skillAdmin = new SkillAdmin({
|
||||||
|
skillsRoot: () => skillSync.skillsRoot(),
|
||||||
|
holdingDir: () => skillsHoldingDir(),
|
||||||
|
syncStatePath: () => join(dshHome(), 'cloud-memory-skills.json'),
|
||||||
|
syncRunning: () => skillSync.stats().running,
|
||||||
|
log: (message) => logger.info(message),
|
||||||
|
});
|
||||||
|
// The tree's sources are detected per call so a directory created while the
|
||||||
|
// process runs shows up on the next refresh.
|
||||||
|
const skillGroups = new SkillGroupManager({
|
||||||
|
sources: () => detectSources(),
|
||||||
|
admin: skillAdmin,
|
||||||
|
log: (message) => logger.info(message),
|
||||||
|
});
|
||||||
|
// One verified market source to start with: the Claude Code plugin marketplace
|
||||||
|
// manifest that Anthropic publishes. Entry ids never carry a URL, so the card
|
||||||
|
// cannot make the host fetch an arbitrary repository.
|
||||||
|
const market = new MarketService([
|
||||||
|
new ClaudePluginMarketplaceProvider({
|
||||||
|
id: 'anthropic-skills',
|
||||||
|
label: 'Anthropic Agent Skills',
|
||||||
|
description: 'Anthropic 公开的 Claude 技能市场(.claude-plugin/marketplace.json)',
|
||||||
|
repo: 'anthropics/skills',
|
||||||
|
ref: 'main',
|
||||||
|
}),
|
||||||
|
]);
|
||||||
|
const updater = new SkillUpdater({
|
||||||
|
admin: skillAdmin,
|
||||||
|
skillsRoot: () => skillSync.skillsRoot(),
|
||||||
|
holdingDir: () => skillsHoldingDir(),
|
||||||
|
syncRunning: () => skillSync.stats().running,
|
||||||
|
log: (message) => logger.info(message),
|
||||||
|
});
|
||||||
|
// Cross-software / workspace inventory. Read-only for every client except DSH.
|
||||||
|
const clients = new ClientRegistry();
|
||||||
|
// Announce at most once per activation so a missing token is obvious in logs.
|
||||||
|
const effective = settings();
|
||||||
|
if (!effective.enabled) {
|
||||||
|
logger.info('disabled by settings');
|
||||||
|
}
|
||||||
|
else if (store.activityToken() === '') {
|
||||||
|
logger.warn(`reporting enabled but no activity token; configure one at ${store.path} or open /cloud-memory`);
|
||||||
|
}
|
||||||
|
else {
|
||||||
|
logger.info(`reporting to ${effective.baseUrl} as ${effective.clientId}`);
|
||||||
|
}
|
||||||
|
if (effective.summaryEnabled && store.summaryToken() === '') {
|
||||||
|
logger.info('turn summaries are enabled but no summary token is configured; nothing will be staged');
|
||||||
|
}
|
||||||
|
// The host's `Events` map is augmented by @deepseek-ai/dsh-session, which a
|
||||||
|
// third-party bundle cannot rely on; bind the listener through a local shape.
|
||||||
|
const onEvent = ctx.on;
|
||||||
|
ctx.effect(() => onEvent('session/event', (session, event) => {
|
||||||
|
try {
|
||||||
|
reporter.handleEvent(session, event);
|
||||||
|
}
|
||||||
|
catch (error) {
|
||||||
|
logger.warn(`turn event handling failed: ${error instanceof Error ? error.message : String(error)}`);
|
||||||
|
}
|
||||||
|
}), 'dsh-cloud-memory: turn reporting');
|
||||||
|
ctx.inject(['tools'], (toolsCtx) => {
|
||||||
|
const tools = toolsCtx.tools;
|
||||||
|
if (tools === undefined)
|
||||||
return;
|
return;
|
||||||
|
const toolDeps = {
|
||||||
|
client: () => client,
|
||||||
|
memoryToken: () => store.memoryToken(),
|
||||||
|
settings: () => ({ enabled: settings().enabled, defaultK: settings().defaultK }),
|
||||||
|
};
|
||||||
|
for (const tool of [...createMemoryTools(toolDeps), ...createSkillTools(toolDeps)]) {
|
||||||
|
toolsCtx.effect(() => tools.register(tool), `dsh-cloud-memory: tool ${tool.name}`);
|
||||||
}
|
}
|
||||||
cloudsync.apply(ctx, config);
|
});
|
||||||
memory.apply(ctx, config);
|
const webServer = ctx.webServer;
|
||||||
skills.apply(ctx, config);
|
if (webServer === undefined) {
|
||||||
mcp.apply(ctx, config);
|
logger.warn('webServer service unavailable; the configuration page stays disabled');
|
||||||
ui.apply(ctx, config);
|
}
|
||||||
raw.apply(ctx, config);
|
else {
|
||||||
|
const routes = createRoutes({ version: VERSION, store, reporter, client: () => client, skills: () => skillSync.stats(), admin: skillAdmin, groups: skillGroups, market, sync: skillSync, updates: updater, clients });
|
||||||
|
for (const route of routes) {
|
||||||
|
ctx.effect(() => webServer.register(route), `dsh-cloud-memory: route ${route.path}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
ctx.effect(() => {
|
||||||
|
const timer = setInterval(() => {
|
||||||
|
if (store.activityToken() !== '' && settings().enabled) {
|
||||||
|
void reporter.flush().catch((error) => {
|
||||||
|
logger.warn(`retry flush failed: ${error instanceof Error ? error.message : String(error)}`);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}, RETRY_INTERVAL_MS);
|
||||||
|
timer.unref?.();
|
||||||
|
return () => clearInterval(timer);
|
||||||
|
}, 'dsh-cloud-memory: retry timer');
|
||||||
|
ctx.effect(() => {
|
||||||
|
const run = () => {
|
||||||
|
if (store.memoryToken() !== '')
|
||||||
|
void skillSync.syncOnce().catch(() => { });
|
||||||
|
};
|
||||||
|
const first = setTimeout(run, 5_000);
|
||||||
|
first.unref?.();
|
||||||
|
const timer = setInterval(run, SKILL_SYNC_INTERVAL_MS);
|
||||||
|
timer.unref?.();
|
||||||
|
return () => { clearTimeout(first); clearInterval(timer); };
|
||||||
|
}, 'dsh-cloud-memory: skill sync timer');
|
||||||
}
|
}
|
||||||
|
|
|
||||||
339
lib/kernel.js
339
lib/kernel.js
|
|
@ -1,339 +0,0 @@
|
||||||
/**
|
|
||||||
* Shared kernel for the dsh-brain sub-plugins.
|
|
||||||
*
|
|
||||||
* The five bundle entries (dsh-brain/cloudsync, dsh-brain/memory,
|
|
||||||
* dsh-brain/skills, dsh-brain/mcp, dsh-brain/ui) and the compat
|
|
||||||
* root entry all load from the same package inside the same host process,
|
|
||||||
* so this module's export resolves to a single instance: whichever entry
|
|
||||||
* applies first builds the services, the rest reuse them.
|
|
||||||
*
|
|
||||||
* The kernel holds service OBJECTS only. Routes, tools, timers, and the
|
|
||||||
* session listener belong to the entry that registers them through its own
|
|
||||||
* `ctx.effect(...)`, so toggling a sub-plugin off in the host plugin
|
|
||||||
* settings tears down exactly that slice and nothing else. `routeDeps()`
|
|
||||||
* assembles the RouteDeps view from the currently active bundles, which is
|
|
||||||
* how `/status` and `/capabilities` report what is actually enabled.
|
|
||||||
*
|
|
||||||
* Settings persist in `$DSH_HOME/dsh-brain.json`; the row config each
|
|
||||||
* entry receives is only the first-boot seed, so any entry may seed the
|
|
||||||
* kernel without diverging.
|
|
||||||
*/
|
|
||||||
import { join, resolve } from 'node:path';
|
|
||||||
import { CloudClient } from "./api.js";
|
|
||||||
import { BrainLogger } from "./diagnostics.js";
|
|
||||||
import { setRouteErrorHook } from "./http.js";
|
|
||||||
import { DepartmentManager, LocalMemoryManager, LocalMemoryRemote, globalBrainRoot, projectBrainRoot } from "./local-memory/index.js";
|
|
||||||
import { VERSION } from "./version.js";
|
|
||||||
import { createCloudMemoryRemoteFactory } from "./cloudsync.js";
|
|
||||||
import { ClientRegistry } from "./clients.js";
|
|
||||||
import { ClaudePluginMarketplaceProvider, MarketService } from "./market.js";
|
|
||||||
import { Reporter } from "./reporter.js";
|
|
||||||
import { SkillAdmin, skillsHoldingDir } from "./skill-admin.js";
|
|
||||||
import { SkillGroupManager, detectSources } from "./skill-groups.js";
|
|
||||||
import { SkillSync } from "./skill-sync.js";
|
|
||||||
import { SkillUpdater } from "./skill-update.js";
|
|
||||||
import { SettingsStore, dshHome } from "./store.js";
|
|
||||||
import { AdminSkillRepository } from "./skills/repository.js";
|
|
||||||
/** Version reported by the status card (single source: package.json). */
|
|
||||||
export { VERSION };
|
|
||||||
/** The shared service set behind every dsh-brain sub-plugin entry. */
|
|
||||||
/** Resolve a workspace from the different host tool/session context shapes. */
|
|
||||||
function workspaceFromExec(exec) {
|
|
||||||
if (exec === null || typeof exec !== 'object')
|
|
||||||
return undefined;
|
|
||||||
const value = exec;
|
|
||||||
const candidates = [
|
|
||||||
value.workspace, value.cwd, value.projectPath,
|
|
||||||
value.session?.cwd, value.session?.workspace, value.session?.header?.cwd, value.session?.header?.workspace,
|
|
||||||
value.agent?.session?.cwd, value.agent?.session?.header?.cwd,
|
|
||||||
];
|
|
||||||
for (const candidate of candidates) {
|
|
||||||
if (typeof candidate === 'string' && candidate.trim() !== '')
|
|
||||||
return candidate;
|
|
||||||
}
|
|
||||||
return undefined;
|
|
||||||
}
|
|
||||||
export class BrainKernel {
|
|
||||||
active = new Set();
|
|
||||||
settingsOf;
|
|
||||||
store;
|
|
||||||
diagnostics;
|
|
||||||
client;
|
|
||||||
memoryRemoteFactory;
|
|
||||||
localMemory;
|
|
||||||
localMemoryRemote;
|
|
||||||
departments;
|
|
||||||
reporter;
|
|
||||||
skillAdmin;
|
|
||||||
skillRepository;
|
|
||||||
skillSync;
|
|
||||||
skillGroups;
|
|
||||||
market;
|
|
||||||
updater;
|
|
||||||
clients;
|
|
||||||
constructor(config, logger) {
|
|
||||||
const store = new SettingsStore(config);
|
|
||||||
this.store = store;
|
|
||||||
const settings = () => store.settings();
|
|
||||||
this.settingsOf = settings;
|
|
||||||
this.diagnostics = new BrainLogger({
|
|
||||||
globalRoot: globalBrainRoot,
|
|
||||||
projectRootOf: (workspace) => projectBrainRoot(workspace),
|
|
||||||
enabled: () => {
|
|
||||||
const effective = settings();
|
|
||||||
return effective.diagnosticsEnabled !== false && effective.enabled !== false;
|
|
||||||
},
|
|
||||||
});
|
|
||||||
setRouteErrorHook((event, detail) => this.diagnostics.log({ event, level: 'warn', detail }));
|
|
||||||
this.diagnostics.prune();
|
|
||||||
// One client per instance; the settings closures keep it live across edits.
|
|
||||||
const client = new CloudClient({
|
|
||||||
baseUrl: () => settings().baseUrl,
|
|
||||||
token: () => store.memoryToken(),
|
|
||||||
timeoutMs: () => settings().requestTimeoutMs,
|
|
||||||
});
|
|
||||||
this.client = client;
|
|
||||||
// The memory bundle sees the cloud through this factory only: the concrete
|
|
||||||
// client stays a cloud-sync concern, injected here at the composition root.
|
|
||||||
this.memoryRemoteFactory = createCloudMemoryRemoteFactory({
|
|
||||||
settings: () => settings(),
|
|
||||||
memoryToken: () => store.memoryToken(),
|
|
||||||
});
|
|
||||||
// Local-first memory is independent of the cloud adapter: it initializes
|
|
||||||
// lazily on the first memory tool call and needs no token or account.
|
|
||||||
this.localMemory = new LocalMemoryManager({
|
|
||||||
cwd: () => process.cwd(),
|
|
||||||
logger: this.diagnostics,
|
|
||||||
settings: () => ({
|
|
||||||
localMemoryEnabled: settings().localMemoryEnabled,
|
|
||||||
cloudMemoryEnabled: settings().cloudMemoryEnabled,
|
|
||||||
autoMemorySpaces: settings().autoMemorySpaces,
|
|
||||||
autoSummaryEnabled: settings().autoSummaryEnabled,
|
|
||||||
autoProfileEnabled: settings().autoProfileEnabled,
|
|
||||||
localMemoryK: settings().localMemoryK,
|
|
||||||
}),
|
|
||||||
});
|
|
||||||
this.localMemoryRemote = new LocalMemoryRemote(this.localMemory);
|
|
||||||
this.departments = new DepartmentManager({ memory: this.localMemory });
|
|
||||||
// The global space is part of first boot; project space stays lazy until
|
|
||||||
// the first memory use in that project.
|
|
||||||
if (settings().localMemoryEnabled !== false && settings().autoMemorySpaces !== false)
|
|
||||||
void this.localMemory.ensureGlobal().catch((error) => { logger.warn('dsh-brain local memory initialization failed: ' + (error instanceof Error ? error.message : String(error))); });
|
|
||||||
this.reporter = new Reporter({
|
|
||||||
// Pinned clients: one request leaves under the connection it started
|
|
||||||
// with, never under whatever settings say by the time it lands.
|
|
||||||
clientFor: (context) => new CloudClient({
|
|
||||||
baseUrl: () => context.baseUrl,
|
|
||||||
token: () => context.activityToken,
|
|
||||||
timeoutMs: () => context.timeoutMs,
|
|
||||||
}),
|
|
||||||
settings: () => ({ enabled: settings().activityEnabled, clientId: settings().clientId }),
|
|
||||||
activityToken: () => store.activityToken(),
|
|
||||||
baseUrl: () => settings().baseUrl,
|
|
||||||
summary: () => ({ enabled: settings().summaryEnabled, maxChars: settings().summaryMaxChars }),
|
|
||||||
summaryToken: () => store.summaryToken(),
|
|
||||||
timeoutMs: () => settings().requestTimeoutMs,
|
|
||||||
log: (message) => logger.warn(message),
|
|
||||||
});
|
|
||||||
// The skill bundle owns its folders; the kernel only wires the shared root
|
|
||||||
// path and the parking area. The sync engine touches folders exclusively
|
|
||||||
// through AdminSkillRepository below.
|
|
||||||
const skillsRootDir = () => {
|
|
||||||
const dir = settings().skillsDir;
|
|
||||||
return dir !== '' ? resolve(dir) : join(dshHome(), 'skills');
|
|
||||||
};
|
|
||||||
// Built before the sync engine: the gate closures dereference skillSync
|
|
||||||
// lazily, so the TDZ order here is safe.
|
|
||||||
const skillAdmin = new SkillAdmin({
|
|
||||||
skillsRoot: skillsRootDir,
|
|
||||||
holdingDir: () => skillsHoldingDir(),
|
|
||||||
gate: () => this.skillSync,
|
|
||||||
log: (message) => logger.info(message),
|
|
||||||
});
|
|
||||||
this.skillAdmin = skillAdmin;
|
|
||||||
this.skillRepository = new AdminSkillRepository({
|
|
||||||
admin: skillAdmin,
|
|
||||||
skillsRoot: skillsRootDir,
|
|
||||||
holdingDir: () => skillsHoldingDir(),
|
|
||||||
});
|
|
||||||
this.skillSync = new SkillSync({
|
|
||||||
client: () => client,
|
|
||||||
clientForScope: (scope) => new CloudClient({
|
|
||||||
baseUrl: () => scope.endpoint,
|
|
||||||
token: () => scope.accountToken,
|
|
||||||
timeoutMs: () => settings().requestTimeoutMs,
|
|
||||||
}),
|
|
||||||
settings: () => ({
|
|
||||||
enabled: settings().enabled,
|
|
||||||
skillsSyncEnabled: settings().skillsSyncEnabled,
|
|
||||||
}),
|
|
||||||
repository: () => this.skillRepository,
|
|
||||||
repositoryForScope: (scope) => new AdminSkillRepository({
|
|
||||||
admin: skillAdmin,
|
|
||||||
skillsRoot: () => scope.root,
|
|
||||||
holdingDir: () => skillsHoldingDir(),
|
|
||||||
}),
|
|
||||||
scope: () => ({
|
|
||||||
endpoint: settings().baseUrl,
|
|
||||||
accountToken: store.memoryToken(),
|
|
||||||
root: skillsRootDir(),
|
|
||||||
}),
|
|
||||||
log: (message) => logger.info(message),
|
|
||||||
});
|
|
||||||
// The tree's sources are detected per call so a directory created while
|
|
||||||
// the process runs shows up on the next refresh.
|
|
||||||
this.skillGroups = new SkillGroupManager({
|
|
||||||
sources: () => detectSources(),
|
|
||||||
admin: skillAdmin,
|
|
||||||
log: (message) => logger.info(message),
|
|
||||||
});
|
|
||||||
// One verified market source to start with: the Claude Code plugin
|
|
||||||
// marketplace manifest that Anthropic publishes. Entry ids never carry a
|
|
||||||
// URL, so the card cannot make the host fetch an arbitrary repository.
|
|
||||||
this.market = new MarketService([
|
|
||||||
new ClaudePluginMarketplaceProvider({
|
|
||||||
id: 'anthropic-skills',
|
|
||||||
label: 'Anthropic Agent Skills',
|
|
||||||
description: 'Anthropic 公开的 Claude 技能市场(.claude-plugin/marketplace.json)',
|
|
||||||
repo: 'anthropics/skills',
|
|
||||||
ref: 'main',
|
|
||||||
}),
|
|
||||||
]);
|
|
||||||
this.updater = new SkillUpdater({
|
|
||||||
admin: skillAdmin,
|
|
||||||
skillsRoot: skillsRootDir,
|
|
||||||
holdingDir: () => skillsHoldingDir(),
|
|
||||||
gate: () => this.skillSync,
|
|
||||||
log: (message) => logger.info(message),
|
|
||||||
});
|
|
||||||
// Cross-software / workspace inventory. Read-only for every client but DSH.
|
|
||||||
this.clients = new ClientRegistry();
|
|
||||||
// Announce at most once per kernel so a missing token is obvious in logs.
|
|
||||||
const effective = settings();
|
|
||||||
if (!effective.activityEnabled) {
|
|
||||||
logger.info('turn reporting disabled by settings');
|
|
||||||
}
|
|
||||||
else if (store.activityToken() === '') {
|
|
||||||
logger.warn(`reporting enabled but no activity token; configure one at ${store.path} or open /dsh-brain`);
|
|
||||||
}
|
|
||||||
else {
|
|
||||||
logger.info(`reporting to ${effective.baseUrl} as ${effective.clientId}`);
|
|
||||||
}
|
|
||||||
if (effective.summaryEnabled && store.summaryToken() === '') {
|
|
||||||
logger.info('turn summaries are enabled but no summary token is configured; nothing will be staged');
|
|
||||||
}
|
|
||||||
this.diagnostics.log({
|
|
||||||
event: 'boot.kernel',
|
|
||||||
detail: {
|
|
||||||
version: VERSION,
|
|
||||||
localMemoryEnabled: effective.localMemoryEnabled !== false,
|
|
||||||
cloudMemoryEnabled: effective.cloudMemoryEnabled === true,
|
|
||||||
autoSummaryEnabled: effective.autoSummaryEnabled !== false,
|
|
||||||
},
|
|
||||||
});
|
|
||||||
}
|
|
||||||
/** Current settings snapshot (live: re-read on every call). */
|
|
||||||
settings() {
|
|
||||||
return this.settingsOf();
|
|
||||||
}
|
|
||||||
/** Emit one diagnostic event through the shared logger (entries and route wiring). */
|
|
||||||
logEvent(event, detail, scope, workspace) {
|
|
||||||
this.diagnostics.log({ event, detail, scope, workspace });
|
|
||||||
}
|
|
||||||
/** Mark a bundle's entry as applied; feeds `routeDeps()` gating. */
|
|
||||||
activate(bundle) {
|
|
||||||
this.active.add(bundle);
|
|
||||||
}
|
|
||||||
/** Drop a bundle from the active set (entry teardown). */
|
|
||||||
deactivate(bundle) {
|
|
||||||
this.active.delete(bundle);
|
|
||||||
}
|
|
||||||
/** Whether a bundle's entry is currently applied. */
|
|
||||||
isActive(bundle) {
|
|
||||||
return this.active.has(bundle);
|
|
||||||
}
|
|
||||||
/** Tool deps shared by the memory and skill entries. */
|
|
||||||
departmentToolDeps() {
|
|
||||||
return {
|
|
||||||
departments: () => this.departments,
|
|
||||||
memory: () => this.localMemory,
|
|
||||||
settings: () => ({ localMemoryEnabled: this.settingsOf().localMemoryEnabled, memoryEnabled: this.settingsOf().memoryEnabled }),
|
|
||||||
workspace: (exec) => workspaceFromExec(exec),
|
|
||||||
};
|
|
||||||
}
|
|
||||||
toolDeps() {
|
|
||||||
const store = this.store;
|
|
||||||
const settings = this.settingsOf;
|
|
||||||
return {
|
|
||||||
// Local-first by default. The cloud adapter is only selected when the
|
|
||||||
// user explicitly enables it AND has a memory token; otherwise memory
|
|
||||||
// tools stay fully usable offline.
|
|
||||||
remote: () => {
|
|
||||||
const effective = settings();
|
|
||||||
const localEnabled = effective.localMemoryEnabled !== false;
|
|
||||||
const cloudEnabled = effective.cloudMemoryEnabled === true && store.memoryToken() !== '';
|
|
||||||
if (cloudEnabled)
|
|
||||||
return this.memoryRemoteFactory.current();
|
|
||||||
if (localEnabled)
|
|
||||||
return this.localMemoryRemote;
|
|
||||||
throw new Error('memory_disabled');
|
|
||||||
},
|
|
||||||
client: () => this.client,
|
|
||||||
memoryToken: () => store.memoryToken(),
|
|
||||||
settings: () => {
|
|
||||||
const effective = settings();
|
|
||||||
const local = effective.localMemoryEnabled !== false && !(effective.cloudMemoryEnabled === true && store.memoryToken() !== '');
|
|
||||||
return { enabled: effective.memoryEnabled, defaultK: local ? effective.localMemoryK : effective.defaultK };
|
|
||||||
},
|
|
||||||
localMemory: () => settings().localMemoryEnabled !== false,
|
|
||||||
workspace: (exec) => workspaceFromExec(exec),
|
|
||||||
};
|
|
||||||
}
|
|
||||||
/**
|
|
||||||
* RouteDeps assembled from the currently active bundles: the status card
|
|
||||||
* then reports exactly what is on, not what this build could do.
|
|
||||||
*/
|
|
||||||
routeDeps() {
|
|
||||||
const skills = this.isActive('skills');
|
|
||||||
const cloudsync = this.isActive('cloudsync');
|
|
||||||
return {
|
|
||||||
version: VERSION,
|
|
||||||
store: this.store,
|
|
||||||
reporter: this.reporter,
|
|
||||||
client: () => this.client,
|
|
||||||
skills: cloudsync ? () => this.skillSync.stats() : undefined,
|
|
||||||
admin: skills ? this.skillAdmin : undefined,
|
|
||||||
groups: skills ? this.skillGroups : undefined,
|
|
||||||
market: skills ? this.market : undefined,
|
|
||||||
sync: cloudsync ? this.skillSync : undefined,
|
|
||||||
updates: skills ? this.updater : undefined,
|
|
||||||
clients: skills ? this.clients : undefined,
|
|
||||||
mcp: this.isActive('mcp'),
|
|
||||||
localMemory: this.localMemory,
|
|
||||||
departments: this.departments,
|
|
||||||
bundles: {
|
|
||||||
cloudsync: this.isActive('cloudsync'),
|
|
||||||
memory: this.isActive('memory'),
|
|
||||||
skills: this.isActive('skills'),
|
|
||||||
mcp: this.isActive('mcp'),
|
|
||||||
ui: this.isActive('ui'),
|
|
||||||
},
|
|
||||||
};
|
|
||||||
}
|
|
||||||
}
|
|
||||||
let instance;
|
|
||||||
/**
|
|
||||||
* The process-wide kernel. The first entry to apply builds it (seeding from
|
|
||||||
* that row's config; the sidecar file is authoritative afterwards); every
|
|
||||||
* later entry — and the compat root — reuses the same instance.
|
|
||||||
*/
|
|
||||||
export function brainKernel(config, logger) {
|
|
||||||
if (instance === undefined)
|
|
||||||
instance = new BrainKernel(config, logger);
|
|
||||||
return instance;
|
|
||||||
}
|
|
||||||
/** Test hook: drop the singleton so the next call rebuilds it. */
|
|
||||||
export function resetBrainKernel() {
|
|
||||||
instance = undefined;
|
|
||||||
setRouteErrorHook(undefined);
|
|
||||||
}
|
|
||||||
|
|
@ -1 +0,0 @@
|
||||||
export { DepartmentManager } from "./manager.js";
|
|
||||||
|
|
@ -1,262 +0,0 @@
|
||||||
import { randomUUID } from 'node:crypto';
|
|
||||||
import { join } from 'node:path';
|
|
||||||
import { LocalMemoryManager, projectIdFor } from "../manager.js";
|
|
||||||
import { containsSecret, JsonMemoryStore } from "../storage.js";
|
|
||||||
import { DepartmentRegistry } from "./registry.js";
|
|
||||||
function text(value, max, required = false) {
|
|
||||||
const result = typeof value === 'string' ? value.trim().slice(0, max) : '';
|
|
||||||
if (required && result === '')
|
|
||||||
throw new Error('department_required_field');
|
|
||||||
return result;
|
|
||||||
}
|
|
||||||
function list(value) {
|
|
||||||
if (!Array.isArray(value))
|
|
||||||
return [];
|
|
||||||
return [...new Set(value.filter((item) => typeof item === 'string').map((item) => item.trim().slice(0, 200)).filter((item) => item !== ''))].slice(0, 50);
|
|
||||||
}
|
|
||||||
function hostName(value) {
|
|
||||||
const host = text(value, 64, true);
|
|
||||||
if (!/^[a-z0-9][a-z0-9_-]*$/.test(host))
|
|
||||||
throw new Error('department_invalid_host');
|
|
||||||
return host;
|
|
||||||
}
|
|
||||||
function limitOf(value) {
|
|
||||||
return Math.max(1, Math.min(50, Math.trunc(value ?? 5)));
|
|
||||||
}
|
|
||||||
/** Persistent departments: private memory, reusable session references and bounded recall. */
|
|
||||||
export class DepartmentManager {
|
|
||||||
memory;
|
|
||||||
constructor(options) { this.memory = options.memory; }
|
|
||||||
root(scope) { return scope === 'global' ? this.memory.globalRoot : this.memory.projectRoot; }
|
|
||||||
registry(scope) { return new DepartmentRegistry(join(this.root(scope), 'departments', 'registry.json')); }
|
|
||||||
store(department) {
|
|
||||||
return new JsonMemoryStore(join(this.root(department.scope), 'departments', department.id, 'memory-space'), 'department', department.spaceId);
|
|
||||||
}
|
|
||||||
async activeStore(department) {
|
|
||||||
if (!department.active)
|
|
||||||
throw new Error('department_disabled');
|
|
||||||
const store = this.store(department);
|
|
||||||
const meta = await store.init(department.name + ' 私有记忆');
|
|
||||||
if (!meta.active)
|
|
||||||
throw new Error('department_disabled');
|
|
||||||
return store;
|
|
||||||
}
|
|
||||||
async find(id) {
|
|
||||||
const global = (await this.registry('global').read()).departments.find((item) => item.id === id);
|
|
||||||
if (global !== undefined)
|
|
||||||
return global;
|
|
||||||
return (await this.registry('project').read()).departments.find((item) => item.id === id);
|
|
||||||
}
|
|
||||||
async required(id, scope) {
|
|
||||||
const department = scope === undefined
|
|
||||||
? await this.find(id)
|
|
||||||
: (await this.registry(scope).read()).departments.find((item) => item.id === id && item.scope === scope);
|
|
||||||
if (department === undefined)
|
|
||||||
throw new Error('department_not_found');
|
|
||||||
return department;
|
|
||||||
}
|
|
||||||
/** Create once by scope + case-insensitive name; repeated calls return the existing department. */
|
|
||||||
async create(input) {
|
|
||||||
const scope = input.scope ?? 'project';
|
|
||||||
const name = text(input.name, 100, true);
|
|
||||||
const role = text(input.role ?? '', 12000);
|
|
||||||
if (containsSecret(role))
|
|
||||||
throw new Error('secret_not_allowed');
|
|
||||||
await this.memory.ensureGlobal();
|
|
||||||
if (scope === 'project')
|
|
||||||
await this.memory.ensureProject();
|
|
||||||
return this.registry(scope).update(async (file) => {
|
|
||||||
const existing = file.departments.find((item) => item.name.toLocaleLowerCase() === name.toLocaleLowerCase());
|
|
||||||
if (existing !== undefined)
|
|
||||||
return { department: existing, created: false };
|
|
||||||
const id = 'dept_' + randomUUID();
|
|
||||||
const timestamp = new Date().toISOString();
|
|
||||||
const department = {
|
|
||||||
id, name, role, scope,
|
|
||||||
...(scope === 'project' ? { projectId: projectIdFor(this.memory.projectRoot) } : {}),
|
|
||||||
spaceId: 'department_' + id.slice(5),
|
|
||||||
skills: list(input.skills), allowedTools: list(input.allowedTools),
|
|
||||||
memory: { readGlobal: input.readGlobal ?? true, readProject: input.readProject ?? true },
|
|
||||||
sessionRefs: {}, active: true, createdAt: timestamp, updatedAt: timestamp, revision: 1,
|
|
||||||
};
|
|
||||||
await this.activeStore(department);
|
|
||||||
file.departments.push(department);
|
|
||||||
return { department, created: true };
|
|
||||||
});
|
|
||||||
}
|
|
||||||
async get(id) { return this.find(id); }
|
|
||||||
async list(scope) {
|
|
||||||
const scopes = scope === undefined ? ['project', 'global'] : [scope];
|
|
||||||
const files = await Promise.all(scopes.map((item) => this.registry(item).read()));
|
|
||||||
return files.flatMap((file) => file.departments).sort((a, b) => b.updatedAt.localeCompare(a.updatedAt) || a.id.localeCompare(b.id));
|
|
||||||
}
|
|
||||||
async update(id, patch, expectedRevision, scope) {
|
|
||||||
const current = await this.required(id, scope);
|
|
||||||
if (patch.role !== undefined && containsSecret(patch.role))
|
|
||||||
throw new Error('secret_not_allowed');
|
|
||||||
return this.registry(current.scope).update(async (file) => {
|
|
||||||
const department = file.departments.find((item) => item.id === id);
|
|
||||||
if (department === undefined)
|
|
||||||
throw new Error('department_not_found');
|
|
||||||
if (expectedRevision !== undefined && department.revision !== expectedRevision)
|
|
||||||
throw new Error('revision_conflict');
|
|
||||||
if (patch.name !== undefined)
|
|
||||||
department.name = text(patch.name, 100, true);
|
|
||||||
if (patch.role !== undefined)
|
|
||||||
department.role = text(patch.role, 12000);
|
|
||||||
if (patch.skills !== undefined)
|
|
||||||
department.skills = list(patch.skills);
|
|
||||||
if (patch.allowedTools !== undefined)
|
|
||||||
department.allowedTools = list(patch.allowedTools);
|
|
||||||
if (patch.readGlobal !== undefined || patch.readProject !== undefined) {
|
|
||||||
department.memory = {
|
|
||||||
readGlobal: patch.readGlobal ?? department.memory.readGlobal,
|
|
||||||
readProject: patch.readProject ?? department.memory.readProject,
|
|
||||||
};
|
|
||||||
}
|
|
||||||
department.revision += 1;
|
|
||||||
department.updatedAt = new Date().toISOString();
|
|
||||||
return department;
|
|
||||||
});
|
|
||||||
}
|
|
||||||
/** Return the same portable reference on every resume; a host session id can be attached separately. */
|
|
||||||
async resumeSession(id, host = 'dsh') {
|
|
||||||
const current = await this.required(id);
|
|
||||||
await this.activeStore(current);
|
|
||||||
const normalizedHost = hostName(host);
|
|
||||||
return this.registry(current.scope).update(async (file) => {
|
|
||||||
const department = file.departments.find((item) => item.id === id);
|
|
||||||
if (department === undefined)
|
|
||||||
throw new Error('department_not_found');
|
|
||||||
if (!department.active)
|
|
||||||
throw new Error('department_disabled');
|
|
||||||
const timestamp = new Date().toISOString();
|
|
||||||
const existing = department.sessionRefs[normalizedHost];
|
|
||||||
if (existing !== undefined) {
|
|
||||||
existing.lastUsedAt = timestamp;
|
|
||||||
department.updatedAt = timestamp;
|
|
||||||
return existing;
|
|
||||||
}
|
|
||||||
const reference = { id: 'ds_' + randomUUID(), host: normalizedHost, reusable: true, createdAt: timestamp, lastUsedAt: timestamp };
|
|
||||||
department.sessionRefs[normalizedHost] = reference;
|
|
||||||
department.updatedAt = timestamp;
|
|
||||||
return reference;
|
|
||||||
});
|
|
||||||
}
|
|
||||||
/** Attach a real host session without replacing the portable reference. */
|
|
||||||
async attachSession(id, host, hostSessionId) {
|
|
||||||
const normalizedHost = hostName(host);
|
|
||||||
const externalId = text(hostSessionId, 500, true);
|
|
||||||
const reference = await this.resumeSession(id, normalizedHost);
|
|
||||||
const current = await this.required(id);
|
|
||||||
await this.registry(current.scope).update(async (file) => {
|
|
||||||
const department = file.departments.find((item) => item.id === id);
|
|
||||||
if (department === undefined)
|
|
||||||
throw new Error('department_not_found');
|
|
||||||
const target = department.sessionRefs[normalizedHost];
|
|
||||||
if (target === undefined)
|
|
||||||
throw new Error('department_session_not_found');
|
|
||||||
target.hostSessionId = externalId;
|
|
||||||
target.lastUsedAt = new Date().toISOString();
|
|
||||||
department.updatedAt = target.lastUsedAt;
|
|
||||||
});
|
|
||||||
return { ...reference, hostSessionId: externalId };
|
|
||||||
}
|
|
||||||
async checkpoint(id, input, expectedRevision, scope) {
|
|
||||||
const current = await this.required(id, scope);
|
|
||||||
const currentTask = input.currentTask === undefined ? undefined : text(input.currentTask, 4000);
|
|
||||||
const handoff = input.handoff === undefined ? undefined : text(input.handoff, 20000);
|
|
||||||
if ((currentTask !== undefined && containsSecret(currentTask)) || (handoff !== undefined && containsSecret(handoff)))
|
|
||||||
throw new Error('secret_not_allowed');
|
|
||||||
return this.registry(current.scope).update(async (file) => {
|
|
||||||
const department = file.departments.find((item) => item.id === id);
|
|
||||||
if (department === undefined)
|
|
||||||
throw new Error('department_not_found');
|
|
||||||
if (expectedRevision !== undefined && department.revision !== expectedRevision)
|
|
||||||
throw new Error('revision_conflict');
|
|
||||||
if (input.currentTask !== undefined) {
|
|
||||||
if (currentTask === '')
|
|
||||||
delete department.currentTask;
|
|
||||||
else
|
|
||||||
department.currentTask = currentTask;
|
|
||||||
}
|
|
||||||
if (input.handoff !== undefined) {
|
|
||||||
if (handoff === '')
|
|
||||||
delete department.handoff;
|
|
||||||
else
|
|
||||||
department.handoff = handoff;
|
|
||||||
}
|
|
||||||
department.revision += 1;
|
|
||||||
department.updatedAt = new Date().toISOString();
|
|
||||||
return department;
|
|
||||||
});
|
|
||||||
}
|
|
||||||
async remember(id, input) {
|
|
||||||
const department = await this.required(id);
|
|
||||||
const store = await this.activeStore(department);
|
|
||||||
return store.add({
|
|
||||||
...input,
|
|
||||||
source: input.source ?? 'department:' + id,
|
|
||||||
departmentId: id,
|
|
||||||
...(department.projectId === undefined ? {} : { projectId: department.projectId }),
|
|
||||||
});
|
|
||||||
}
|
|
||||||
/** Private first on equal scores; project/global are opt-in and the total result count stays bounded. */
|
|
||||||
async recall(id, query, k = 5, workspace, scope) {
|
|
||||||
const department = await this.required(id, scope);
|
|
||||||
const limit = limitOf(k);
|
|
||||||
const privateHits = await this.store(department).search(query, limit);
|
|
||||||
const shared = [];
|
|
||||||
if (scope !== undefined) {
|
|
||||||
const readShared = scope === 'global' ? department.memory.readGlobal : department.memory.readProject;
|
|
||||||
if (readShared)
|
|
||||||
shared.push(...await this.memory.searchHits(query, limit, workspace, undefined, scope));
|
|
||||||
}
|
|
||||||
else if (department.memory.readProject && department.memory.readGlobal) {
|
|
||||||
shared.push(...await this.memory.searchHits(query, limit * 2, workspace));
|
|
||||||
}
|
|
||||||
else if (department.memory.readGlobal) {
|
|
||||||
shared.push(...await this.memory.searchHits(query, limit, workspace, 'global'));
|
|
||||||
}
|
|
||||||
else if (department.memory.readProject) {
|
|
||||||
shared.push(...await this.memory.searchHits(query, limit, workspace, department.projectId ?? projectIdFor(this.memory.projectRoot)));
|
|
||||||
}
|
|
||||||
const rank = { department: 3, project: 2, global: 1 };
|
|
||||||
const candidates = [
|
|
||||||
...privateHits.map((hit) => ({ ...hit, origin: 'department' })),
|
|
||||||
...shared.map((hit) => ({ ...hit, origin: hit.record.scope === 'global' ? 'global' : 'project' })),
|
|
||||||
];
|
|
||||||
const seen = new Set();
|
|
||||||
return candidates.sort((a, b) => b.score - a.score || rank[b.origin] - rank[a.origin] || b.record.updatedAt.localeCompare(a.record.updatedAt))
|
|
||||||
.filter((hit) => {
|
|
||||||
const key = hit.record.content.trim();
|
|
||||||
if (seen.has(key))
|
|
||||||
return false;
|
|
||||||
seen.add(key);
|
|
||||||
return true;
|
|
||||||
}).slice(0, limit);
|
|
||||||
}
|
|
||||||
/** Disable without deleting private memories or allowing automatic session recovery. */
|
|
||||||
async disable(id, expectedRevision, scope) {
|
|
||||||
const current = await this.required(id, scope);
|
|
||||||
// Fail on a stale revision before deactivating the space below: the update
|
|
||||||
// callback re-checks under the registry lock, but the deactivation has
|
|
||||||
// already happened by then.
|
|
||||||
if (expectedRevision !== undefined && current.revision !== expectedRevision)
|
|
||||||
throw new Error('revision_conflict');
|
|
||||||
const store = this.store(current);
|
|
||||||
if (await store.spaceMeta() !== undefined)
|
|
||||||
await store.setActive(false);
|
|
||||||
return this.registry(current.scope).update(async (file) => {
|
|
||||||
const department = file.departments.find((item) => item.id === id);
|
|
||||||
if (department === undefined)
|
|
||||||
throw new Error('department_not_found');
|
|
||||||
if (expectedRevision !== undefined && department.revision !== expectedRevision)
|
|
||||||
throw new Error('revision_conflict');
|
|
||||||
department.active = false;
|
|
||||||
department.revision += 1;
|
|
||||||
department.updatedAt = new Date().toISOString();
|
|
||||||
return department;
|
|
||||||
});
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
@ -1,56 +0,0 @@
|
||||||
import { randomUUID } from 'node:crypto';
|
|
||||||
import { mkdir, readFile, rename, rm, writeFile } from 'node:fs/promises';
|
|
||||||
import { dirname } from 'node:path';
|
|
||||||
import { withFileLock } from "../storage.js";
|
|
||||||
const EMPTY = { version: 1, departments: [] };
|
|
||||||
async function atomicWrite(path, content) {
|
|
||||||
await mkdir(dirname(path), { recursive: true });
|
|
||||||
const temporary = path + '.' + String(process.pid) + '.' + randomUUID() + '.tmp';
|
|
||||||
try {
|
|
||||||
await writeFile(temporary, content, { encoding: 'utf8', mode: 0o600 });
|
|
||||||
await rename(temporary, path);
|
|
||||||
}
|
|
||||||
catch (error) {
|
|
||||||
await rm(temporary, { force: true }).catch(() => { });
|
|
||||||
throw error;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
/** JSON registry for one global or project department collection. */
|
|
||||||
export class DepartmentRegistry {
|
|
||||||
path;
|
|
||||||
constructor(path) { this.path = path; }
|
|
||||||
async read() {
|
|
||||||
let text;
|
|
||||||
try {
|
|
||||||
text = await readFile(this.path, 'utf8');
|
|
||||||
}
|
|
||||||
catch (error) {
|
|
||||||
if (error.code === 'ENOENT')
|
|
||||||
return { ...EMPTY, departments: [] };
|
|
||||||
throw new Error('department_registry_read_failed: ' + (error instanceof Error ? error.message : String(error)));
|
|
||||||
}
|
|
||||||
let value;
|
|
||||||
try {
|
|
||||||
value = JSON.parse(text);
|
|
||||||
}
|
|
||||||
catch {
|
|
||||||
throw new Error('department_registry_corrupt');
|
|
||||||
}
|
|
||||||
if (value === null || typeof value !== 'object' || Array.isArray(value))
|
|
||||||
throw new Error('department_registry_corrupt');
|
|
||||||
const file = value;
|
|
||||||
if (file.version !== undefined && file.version !== 1)
|
|
||||||
throw new Error('department_registry_incompatible');
|
|
||||||
if (!Array.isArray(file.departments))
|
|
||||||
throw new Error('department_registry_incompatible');
|
|
||||||
return { version: 1, departments: file.departments };
|
|
||||||
}
|
|
||||||
async update(job) {
|
|
||||||
return withFileLock(this.path + '.lock', async () => {
|
|
||||||
const file = await this.read();
|
|
||||||
const result = await job(file);
|
|
||||||
await atomicWrite(this.path, JSON.stringify(file, null, 2) + '\n');
|
|
||||||
return result;
|
|
||||||
});
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
@ -1 +0,0 @@
|
||||||
export {};
|
|
||||||
|
|
@ -1,4 +0,0 @@
|
||||||
export { LocalMemoryManager, globalBrainRoot, projectBrainRoot, projectIdFor } from "./manager.js";
|
|
||||||
export { LocalMemoryRemote } from "./remote.js";
|
|
||||||
export { DepartmentManager } from "./departments/index.js";
|
|
||||||
export { JsonMemoryStore, JsonMemoryStore as LocalMemoryStore, JsonDocumentStore, JsonDocumentStore as LocalDocumentStore, localMemoryHash, containsSecret } from "./storage.js";
|
|
||||||
|
|
@ -1,675 +0,0 @@
|
||||||
/** Local-first memory manager: .dsh/brain layout, spaces, projections and summaries. */
|
|
||||||
import { AsyncLocalStorage } from 'node:async_hooks';
|
|
||||||
import { mkdir, readFile, writeFile, rename, rm, cp, stat, readdir } from 'node:fs/promises';
|
|
||||||
import { existsSync, readFileSync } from 'node:fs';
|
|
||||||
import { randomUUID } from 'node:crypto';
|
|
||||||
import { dirname, join, resolve } from 'node:path';
|
|
||||||
import { dshHome } from "../store.js";
|
|
||||||
import { JsonDocumentStore, JsonMemoryStore, containsSecret, localMemoryHash, withFileLock } from "./storage.js";
|
|
||||||
export function globalBrainRoot() { return resolve(dshHome(), 'brain'); }
|
|
||||||
/** Resolve a user-supplied workspace to its project base, accepting both the project root and its .dsh/brain path. */
|
|
||||||
export function projectBaseOf(value) {
|
|
||||||
const normalized = resolve(value);
|
|
||||||
const brainSuffix = join('.dsh', 'brain');
|
|
||||||
return normalized.endsWith(brainSuffix) ? dirname(dirname(normalized)) : normalized;
|
|
||||||
}
|
|
||||||
export function projectBrainRoot(cwd = process.cwd()) { return join(projectBaseOf(cwd), '.dsh', 'brain'); }
|
|
||||||
export function projectIdFor(root) { return 'project_' + localMemoryHash(resolve(root)).slice(0, 16); }
|
|
||||||
async function atomicWrite(path, content) {
|
|
||||||
await mkdir(dirname(path), { recursive: true });
|
|
||||||
const tmp = path + '.' + String(process.pid) + '.' + randomUUID() + '.tmp';
|
|
||||||
try {
|
|
||||||
await writeFile(tmp, content, { encoding: 'utf8', mode: 0o600 });
|
|
||||||
await rename(tmp, path);
|
|
||||||
}
|
|
||||||
catch (error) {
|
|
||||||
await rm(tmp, { force: true }).catch(() => { });
|
|
||||||
throw error;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
async function treeDigest(root) {
|
|
||||||
const files = [];
|
|
||||||
const walk = async (dir, prefix) => {
|
|
||||||
for (const entry of await readdir(dir, { withFileTypes: true }).catch(() => [])) {
|
|
||||||
const rel = prefix === '' ? entry.name : prefix + '/' + entry.name;
|
|
||||||
const full = join(dir, entry.name);
|
|
||||||
if (entry.isDirectory()) {
|
|
||||||
await walk(full, rel);
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
if (entry.isFile())
|
|
||||||
files.push(rel + ':' + localMemoryHash((await readFile(full)).toString('base64')));
|
|
||||||
}
|
|
||||||
};
|
|
||||||
await walk(root, '');
|
|
||||||
return localMemoryHash(files.sort().join('\n'));
|
|
||||||
}
|
|
||||||
async function readJson(path, fallback) {
|
|
||||||
let text;
|
|
||||||
try {
|
|
||||||
text = await readFile(path, 'utf8');
|
|
||||||
}
|
|
||||||
catch (error) {
|
|
||||||
if (error.code === 'ENOENT')
|
|
||||||
return fallback;
|
|
||||||
throw new Error(`local_memory_state_read_failed: ${path}: ${error instanceof Error ? error.message : String(error)}`);
|
|
||||||
}
|
|
||||||
try {
|
|
||||||
return JSON.parse(text);
|
|
||||||
}
|
|
||||||
catch {
|
|
||||||
throw new Error(`local_memory_state_corrupt: ${path}`);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
async function writeGitIgnore(projectBase) {
|
|
||||||
const dsh = join(projectBase, '.dsh');
|
|
||||||
await mkdir(dsh, { recursive: true });
|
|
||||||
const path = join(dsh, '.gitignore');
|
|
||||||
let text = '';
|
|
||||||
try {
|
|
||||||
text = await readFile(path, 'utf8');
|
|
||||||
}
|
|
||||||
catch { }
|
|
||||||
if (!/^brain\/?$/m.test(text)) {
|
|
||||||
text = text.trimEnd() + (text === '' ? '' : '\n') + 'brain/\n';
|
|
||||||
await atomicWrite(path, text);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
export class LocalMemoryManager {
|
|
||||||
cwdOf;
|
|
||||||
defaultWorkspaceOf;
|
|
||||||
settingsOf;
|
|
||||||
workspaceContext = new AsyncLocalStorage();
|
|
||||||
workspaces = new Map();
|
|
||||||
fixedGlobalRoot;
|
|
||||||
fixedProjectRoot;
|
|
||||||
loggerOf;
|
|
||||||
constructor(options = {}) {
|
|
||||||
this.cwdOf = options.cwd ?? (() => process.cwd());
|
|
||||||
this.defaultWorkspaceOf = options.workspace;
|
|
||||||
this.settingsOf = options.settings ?? (() => ({}));
|
|
||||||
this.fixedGlobalRoot = options.globalRoot;
|
|
||||||
this.fixedProjectRoot = options.projectRoot;
|
|
||||||
this.loggerOf = options.logger === undefined ? undefined : { log: (event) => { try {
|
|
||||||
options.logger.log(event);
|
|
||||||
}
|
|
||||||
catch { /* diagnostics must never break memory operations */ } } };
|
|
||||||
}
|
|
||||||
/** Bind one operation to a workspace; AsyncLocalStorage keeps concurrent sessions isolated. */
|
|
||||||
withWorkspace(workspace, job) { return this.workspaceContext.run(workspace, job); }
|
|
||||||
workspacePath(workspace) {
|
|
||||||
const value = workspace ?? this.workspaceContext.getStore() ?? this.defaultWorkspaceOf?.() ?? this.cwdOf();
|
|
||||||
return resolve(value);
|
|
||||||
}
|
|
||||||
projectRootFor(workspace) { return this.fixedProjectRoot ?? projectBrainRoot(this.workspacePath(workspace)); }
|
|
||||||
projectBaseFor(workspace) { return projectBaseOf(this.workspacePath(workspace)); }
|
|
||||||
get globalRoot() { return this.fixedGlobalRoot ?? globalBrainRoot(); }
|
|
||||||
get projectRoot() { return this.projectRootFor(); }
|
|
||||||
get globalStore() { return new JsonMemoryStore(join(this.globalRoot, 'runtime'), 'global', 'global'); }
|
|
||||||
projectStoreFor(workspace) { return new JsonMemoryStore(join(this.projectRootFor(workspace), 'memory-space'), 'project', projectIdFor(this.projectRootFor(workspace))); }
|
|
||||||
scopedStore(scope, workspace) {
|
|
||||||
return scope === 'global' ? this.globalStore : this.projectStoreFor(workspace);
|
|
||||||
}
|
|
||||||
async storeFor(scope, workspace) {
|
|
||||||
if (scope === 'global')
|
|
||||||
return this.globalStore;
|
|
||||||
return this.ensureProject(workspace);
|
|
||||||
}
|
|
||||||
projectionDirtyPath() { return join(this.globalRoot, 'state', 'projection.json'); }
|
|
||||||
async markProjectionDirty(error) {
|
|
||||||
const marker = String(Date.now()) + '-' + randomUUID();
|
|
||||||
await atomicWrite(this.projectionDirtyPath(), JSON.stringify({ dirty: true, marker, ...(error === undefined ? {} : { lastError: error instanceof Error ? error.message : String(error) }), updatedAt: new Date().toISOString() }, null, 2) + '\n');
|
|
||||||
return marker;
|
|
||||||
}
|
|
||||||
async clearProjectionDirty(marker) {
|
|
||||||
try {
|
|
||||||
const state = JSON.parse(await readFile(this.projectionDirtyPath(), 'utf8'));
|
|
||||||
if (state.marker === marker)
|
|
||||||
await rm(this.projectionDirtyPath(), { force: true });
|
|
||||||
}
|
|
||||||
catch { }
|
|
||||||
}
|
|
||||||
/** Retry a projection left dirty by a committed memory write. */
|
|
||||||
async repairProjectionsIfDirty() {
|
|
||||||
if (!existsSync(this.projectionDirtyPath()))
|
|
||||||
return false;
|
|
||||||
try {
|
|
||||||
await this.regenerateProjections();
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
catch {
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
async tryRegenerateProjections() {
|
|
||||||
try {
|
|
||||||
await this.regenerateProjections();
|
|
||||||
return { projectionPending: false };
|
|
||||||
}
|
|
||||||
catch (error) {
|
|
||||||
return { projectionPending: true, projectionError: error instanceof Error ? error.message : String(error) };
|
|
||||||
}
|
|
||||||
}
|
|
||||||
/** Idempotently create the global space and its runtime projections. */
|
|
||||||
async ensureGlobal() {
|
|
||||||
return withFileLock(join(this.globalRoot, 'state', '.init.lock'), async () => {
|
|
||||||
await mkdir(join(this.globalRoot, 'runtime'), { recursive: true });
|
|
||||||
await mkdir(join(this.globalRoot, 'spaces', 'global'), { recursive: true });
|
|
||||||
await mkdir(join(this.globalRoot, 'backups'), { recursive: true });
|
|
||||||
await mkdir(join(this.globalRoot, 'state'), { recursive: true });
|
|
||||||
const meta = await this.globalStore.init('全局记忆');
|
|
||||||
const spaceMarker = join(this.globalRoot, 'spaces', 'global', 'space.json');
|
|
||||||
if (!(await stat(spaceMarker).catch(() => undefined)))
|
|
||||||
await atomicWrite(spaceMarker, JSON.stringify(meta, null, 2) + '\n');
|
|
||||||
const userPath = join(this.globalRoot, 'runtime', 'USER.md');
|
|
||||||
const memoryPath = join(this.globalRoot, 'runtime', 'MEMORY.md');
|
|
||||||
if (!(await stat(userPath).catch(() => undefined)))
|
|
||||||
await atomicWrite(userPath, '# USER\n\n');
|
|
||||||
if (!(await stat(memoryPath).catch(() => undefined)))
|
|
||||||
await atomicWrite(memoryPath, '# MEMORY\n\n');
|
|
||||||
const initPath = join(this.globalRoot, 'state', 'init.json');
|
|
||||||
if (!(await stat(initPath).catch(() => undefined)))
|
|
||||||
await atomicWrite(initPath, JSON.stringify({ version: 1, globalReady: true, createdAt: new Date().toISOString() }, null, 2) + '\n');
|
|
||||||
await this.repairProjectionsIfDirty();
|
|
||||||
this.loggerOf?.log({ event: 'memory.ensure', detail: { scope: 'global', root: this.globalRoot } });
|
|
||||||
return meta;
|
|
||||||
});
|
|
||||||
}
|
|
||||||
/** First use in a project creates its .dsh/brain and a stable project space. */
|
|
||||||
async ensureProject(workspace) {
|
|
||||||
await this.ensureGlobal();
|
|
||||||
const root = this.fixedProjectRoot ?? join(this.projectBaseFor(workspace), '.dsh', 'brain');
|
|
||||||
const base = projectBaseOf(root);
|
|
||||||
const cached = this.workspaces.get(root);
|
|
||||||
if (cached !== undefined)
|
|
||||||
return cached.store;
|
|
||||||
return withFileLock(join(root, '.init.lock'), async () => {
|
|
||||||
const again = this.workspaces.get(root);
|
|
||||||
if (again !== undefined)
|
|
||||||
return again.store;
|
|
||||||
const id = projectIdFor(root);
|
|
||||||
await mkdir(join(root, 'documents'), { recursive: true });
|
|
||||||
await mkdir(join(root, 'state'), { recursive: true });
|
|
||||||
const store = new JsonMemoryStore(join(root, 'memory-space'), 'project', id);
|
|
||||||
await store.init('项目记忆');
|
|
||||||
const documents = new JsonDocumentStore(join(root, 'documents'));
|
|
||||||
await documents.init();
|
|
||||||
await writeGitIgnore(base);
|
|
||||||
const mappingPath = join(this.globalRoot, 'state', 'projects.json');
|
|
||||||
await withFileLock(join(this.globalRoot, 'state', '.projects.lock'), async () => {
|
|
||||||
const mapping = await readJson(mappingPath, {});
|
|
||||||
mapping[id] = { root, updatedAt: new Date().toISOString() };
|
|
||||||
await atomicWrite(mappingPath, JSON.stringify(mapping, null, 2) + '\n');
|
|
||||||
});
|
|
||||||
const state = { root, store, documents };
|
|
||||||
this.workspaces.set(root, state);
|
|
||||||
this.loggerOf?.log({ event: 'memory.ensure', scope: 'project', workspace: base, detail: { scope: 'project', root } });
|
|
||||||
return store;
|
|
||||||
});
|
|
||||||
}
|
|
||||||
/** Public alias used by callers that initialize explicit local memory. */
|
|
||||||
async initialize(workspace) { return this.ensure(workspace); }
|
|
||||||
async ensure(workspace) {
|
|
||||||
const global = await this.ensureGlobal();
|
|
||||||
const projectStore = await this.ensureProject(workspace);
|
|
||||||
const project = await projectStore.spaceMeta();
|
|
||||||
return { global, project: project ?? { id: projectStore.spaceId, scope: 'project', name: '项目记忆', root: projectStore.root, createdAt: new Date().toISOString(), active: true } };
|
|
||||||
}
|
|
||||||
/** Add one memory and regenerate the compact projections. */
|
|
||||||
async remember(input) {
|
|
||||||
const startedAt = Date.now();
|
|
||||||
const workspace = this.workspacePath();
|
|
||||||
const scope = input.scope ?? 'project';
|
|
||||||
const store = await this.storeFor(scope, workspace);
|
|
||||||
await this.markProjectionDirty();
|
|
||||||
const result = await store.add({ ...input, projectId: input.projectId ?? (scope === 'project' ? projectIdFor(this.projectRootFor(workspace)) : undefined) });
|
|
||||||
if (result.duplicate) {
|
|
||||||
this.loggerOf?.log({ event: 'memory.remember', scope: scope === 'global' ? 'global' : 'project', workspace, sessionId: input.sessionId, detail: { recordId: result.record.id, duplicate: true, category: input.category, durationMs: Date.now() - startedAt } });
|
|
||||||
return result;
|
|
||||||
}
|
|
||||||
const outcome = { ...result, ...(await this.tryRegenerateProjections()) };
|
|
||||||
this.loggerOf?.log({ event: 'memory.remember', scope: scope === 'global' ? 'global' : 'project', workspace, sessionId: input.sessionId, detail: { recordId: outcome.record.id, duplicate: false, category: input.category, durationMs: Date.now() - startedAt } });
|
|
||||||
return outcome;
|
|
||||||
}
|
|
||||||
async add(input) { return this.remember(input); }
|
|
||||||
async read(id, workspace) {
|
|
||||||
const globalRecord = await this.globalStore.read(id);
|
|
||||||
if (globalRecord !== undefined)
|
|
||||||
return globalRecord;
|
|
||||||
return (await this.ensureProject(workspace)).read(id);
|
|
||||||
}
|
|
||||||
async collectHits(query, workspace, projectId) {
|
|
||||||
const projectStore = await this.ensureProject(workspace);
|
|
||||||
const globalHits = await this.globalStore.search(query, 1000);
|
|
||||||
const projectHits = await projectStore.search(query, 1000);
|
|
||||||
const scoped = [...projectHits, ...globalHits].filter(({ record }) => {
|
|
||||||
if (projectId === undefined || projectId === '')
|
|
||||||
return true;
|
|
||||||
if (projectId === 'global')
|
|
||||||
return record.scope === 'global';
|
|
||||||
return record.scope === 'project' && record.projectId === projectId;
|
|
||||||
});
|
|
||||||
const seen = new Set();
|
|
||||||
return scoped.filter(({ record }) => { if (seen.has(record.id))
|
|
||||||
return false; seen.add(record.id); return true; })
|
|
||||||
.sort((a, b) => b.score - a.score || b.record.updatedAt.localeCompare(a.record.updatedAt));
|
|
||||||
}
|
|
||||||
async searchHits(query, k = this.settingsOf().localMemoryK ?? 5, workspace, projectId, scope) {
|
|
||||||
const startedAt = Date.now();
|
|
||||||
const limit = Math.max(1, Math.min(100, Math.trunc(k)));
|
|
||||||
const result = scope === undefined
|
|
||||||
? (await this.collectHits(query, workspace, projectId)).slice(0, limit)
|
|
||||||
: await this.scopedStore(scope, workspace).search(query, limit);
|
|
||||||
const sources = {};
|
|
||||||
for (const hit of result)
|
|
||||||
sources[hit.record.scope] = (sources[hit.record.scope] ?? 0) + 1;
|
|
||||||
this.loggerOf?.log({ event: 'memory.search', scope: scope ?? 'project', workspace: scope === 'global' ? undefined : this.workspacePath(workspace), detail: { query, k: limit, hits: result.length, sources, durationMs: Date.now() - startedAt } });
|
|
||||||
return result;
|
|
||||||
}
|
|
||||||
async search(query, k = this.settingsOf().localMemoryK ?? 5, workspace, projectId) {
|
|
||||||
return (await this.searchHits(query, k, workspace, projectId)).map((hit) => hit.record);
|
|
||||||
}
|
|
||||||
async list(options = {}, workspace, projectId) {
|
|
||||||
if (options.scope !== undefined)
|
|
||||||
return this.scopedStore(options.scope, workspace).list(options);
|
|
||||||
const projectStore = await this.ensureProject(workspace);
|
|
||||||
const records = [...(await this.globalStore.records()), ...(await projectStore.records())];
|
|
||||||
const scoped = records.filter((record) => {
|
|
||||||
if (projectId === undefined || projectId === '')
|
|
||||||
return true;
|
|
||||||
if (projectId === 'global')
|
|
||||||
return record.scope === 'global';
|
|
||||||
return record.scope === 'project' && record.projectId === projectId;
|
|
||||||
});
|
|
||||||
const seen = new Set();
|
|
||||||
// The whole merged set is ordered before pagination (never just the page).
|
|
||||||
// `updated` keeps the historical order; `created` is the API's new default.
|
|
||||||
const compare = options.order === 'created'
|
|
||||||
? (a, b) => b.createdAt.localeCompare(a.createdAt) || a.id.localeCompare(b.id)
|
|
||||||
: (a, b) => b.updatedAt.localeCompare(a.updatedAt) || a.id.localeCompare(b.id);
|
|
||||||
const ordered = scoped.filter((record) => { if (seen.has(record.id))
|
|
||||||
return false; seen.add(record.id); return true; }).sort(compare);
|
|
||||||
const offset = Math.max(0, Math.trunc(options.offset ?? 0));
|
|
||||||
const limit = Math.max(1, Math.min(1000, Math.trunc(options.limit ?? 50)));
|
|
||||||
return { items: ordered.slice(offset, offset + limit), total: ordered.length };
|
|
||||||
}
|
|
||||||
async forget(id, expectedRevision, workspace, scope) {
|
|
||||||
const targetScope = scope ?? ((await this.globalStore.read(id)) === undefined ? 'project' : 'global');
|
|
||||||
const scopedStore = scope === undefined ? undefined : this.scopedStore(scope, workspace);
|
|
||||||
if (scopedStore !== undefined) {
|
|
||||||
const record = await scopedStore.read(id);
|
|
||||||
if (record === undefined)
|
|
||||||
throw new Error('memory_not_found');
|
|
||||||
if (expectedRevision !== undefined && record.revision !== expectedRevision)
|
|
||||||
throw new Error('revision_conflict');
|
|
||||||
}
|
|
||||||
// The runtime projections are built exclusively from the global store.
|
|
||||||
if (scope !== 'project')
|
|
||||||
await this.markProjectionDirty();
|
|
||||||
const store = scopedStore ?? await this.storeFor(targetScope, workspace);
|
|
||||||
const removed = await store.forget(id, expectedRevision);
|
|
||||||
if (scope !== 'project')
|
|
||||||
await this.tryRegenerateProjections();
|
|
||||||
this.loggerOf?.log({ event: 'memory.forget', scope: targetScope, workspace: targetScope === 'project' ? this.workspacePath(workspace) : undefined, detail: { recordId: id, revision: removed.revision } });
|
|
||||||
return removed;
|
|
||||||
}
|
|
||||||
async projects(workspace) {
|
|
||||||
const global = await this.globalStore.spaceMeta();
|
|
||||||
const root = this.projectRootFor(workspace);
|
|
||||||
const project = await this.projectStoreFor(workspace).spaceMeta();
|
|
||||||
return [...(global === undefined ? [] : [{ id: 'global', name: '全局记忆' }]), { id: project?.id ?? projectIdFor(root), name: '项目记忆' }];
|
|
||||||
}
|
|
||||||
async documents(workspace) {
|
|
||||||
const root = this.projectRootFor(workspace);
|
|
||||||
return new JsonDocumentStore(join(root, 'documents')).list();
|
|
||||||
}
|
|
||||||
async addDocument(input, workspace) {
|
|
||||||
await this.ensureProject(workspace);
|
|
||||||
// ensureProject guarantees the workspace entry exists (the map is never pruned).
|
|
||||||
const documents = this.workspaces.get(this.projectRootFor(workspace)).documents;
|
|
||||||
return documents.add(input);
|
|
||||||
}
|
|
||||||
async storageStatus(workspace, scope) {
|
|
||||||
const projectRoot = scope === 'global' ? undefined : this.projectRootFor(workspace);
|
|
||||||
const global = scope === 'project' ? undefined : await this.globalStore.spaceMeta();
|
|
||||||
const project = scope === 'global' ? undefined : await this.projectStoreFor(workspace).spaceMeta();
|
|
||||||
return {
|
|
||||||
provider: 'local',
|
|
||||||
...(scope === 'project' ? {} : { globalRoot: this.globalRoot }),
|
|
||||||
...(projectRoot === undefined ? {} : { projectRoot }),
|
|
||||||
spaces: {
|
|
||||||
...(scope === 'project' ? {} : { global: global ?? null }),
|
|
||||||
...(scope === 'global' ? {} : { project: project ?? null }),
|
|
||||||
},
|
|
||||||
cloudSyncEnabled: this.settingsOf().cloudMemoryEnabled === true,
|
|
||||||
localMemoryEnabled: this.settingsOf().localMemoryEnabled !== false,
|
|
||||||
};
|
|
||||||
}
|
|
||||||
/** Return the compact per-turn projection used by the system prompt. */
|
|
||||||
projectionText(limit = 2000) {
|
|
||||||
const read = (path) => { try {
|
|
||||||
return readFileSync(path, 'utf8').trim();
|
|
||||||
}
|
|
||||||
catch {
|
|
||||||
return '';
|
|
||||||
} };
|
|
||||||
const user = read(join(this.globalRoot, 'runtime', 'USER.md'));
|
|
||||||
const memory = read(join(this.globalRoot, 'runtime', 'MEMORY.md'));
|
|
||||||
if (user === '' && memory === '')
|
|
||||||
return '';
|
|
||||||
const cut = (text) => text.length > limit ? text.slice(0, limit) + '\n…' : text;
|
|
||||||
return ['## dsh-brain local memory', '### USER.md', cut(user || '(empty)'), '### MEMORY.md', cut(memory || '(empty)')].join('\n');
|
|
||||||
}
|
|
||||||
/** Generate USER.md/MEMORY.md from explicit profile/rule records only. */
|
|
||||||
async regenerateProjections() {
|
|
||||||
const marker = await this.markProjectionDirty();
|
|
||||||
await withFileLock(join(this.globalRoot, 'state', '.projection.lock'), async () => {
|
|
||||||
try {
|
|
||||||
const runtimeFile = join(this.globalRoot, 'runtime', 'memories.json');
|
|
||||||
const mirrorFile = join(this.globalRoot, 'spaces', 'global', 'memories.json');
|
|
||||||
const data = await readFile(runtimeFile, 'utf8').catch((error) => { if (error.code === 'ENOENT')
|
|
||||||
return undefined; throw error; });
|
|
||||||
if (data !== undefined)
|
|
||||||
await atomicWrite(mirrorFile, data);
|
|
||||||
const records = await this.globalStore.records();
|
|
||||||
const user = records.filter((record) => record.category === 'preference' || record.category === 'identity');
|
|
||||||
const rules = records.filter((record) => record.category === 'rule');
|
|
||||||
const render = (title, items) => '# ' + title + '\n\n' + items.map((record) => '- ' + record.content.replace(/\n/g, ' ') + ' *(rev ' + String(record.revision) + ', ' + record.source + ')*').join('\n') + (items.length === 0 ? '' : '\n');
|
|
||||||
await atomicWrite(join(this.globalRoot, 'runtime', 'USER.md'), render('USER', user));
|
|
||||||
await atomicWrite(join(this.globalRoot, 'runtime', 'MEMORY.md'), render('MEMORY', rules));
|
|
||||||
await this.clearProjectionDirty(marker);
|
|
||||||
this.loggerOf?.log({ event: 'memory.projection', detail: { root: this.globalRoot } });
|
|
||||||
}
|
|
||||||
catch (error) {
|
|
||||||
await this.markProjectionDirty(error);
|
|
||||||
throw error;
|
|
||||||
}
|
|
||||||
});
|
|
||||||
}
|
|
||||||
/** Incremental, privacy-preserving summary: only explicit text is stored. */
|
|
||||||
async summarizeConversation(input, workspace) {
|
|
||||||
if (this.settingsOf().autoSummaryEnabled === false)
|
|
||||||
return { stored: 0, duplicates: 0, skipped: true };
|
|
||||||
await this.ensureProject(workspace);
|
|
||||||
await this.markProjectionDirty();
|
|
||||||
return withFileLock(join(this.globalRoot, 'state', '.sessions.lock'), async () => {
|
|
||||||
const checkpointPath = join(this.globalRoot, 'state', 'sessions.json');
|
|
||||||
const checkpoints = await readJson(checkpointPath, {});
|
|
||||||
const prior = checkpoints[input.sessionId];
|
|
||||||
const processed = new Set(prior?.processed ?? []);
|
|
||||||
const fresh = input.turns.filter((turn) => turn.turnId === undefined || !processed.has(turn.turnId));
|
|
||||||
let stored = 0;
|
|
||||||
let duplicates = 0;
|
|
||||||
for (const turn of fresh) {
|
|
||||||
const user = (turn.user ?? '').trim();
|
|
||||||
if (user === '' || containsSecret(user))
|
|
||||||
continue;
|
|
||||||
for (const sentence of user.split(/[\n。!?!?]/).map((item) => item.trim()).filter((item) => item !== '')) {
|
|
||||||
if (/(这次|本次|今天|暂时|临时|只此一次|一次性)/.test(sentence))
|
|
||||||
continue;
|
|
||||||
if (!/(记住|长期|以后|今后|往后|每次|永远|始终|总是|从来不|我一向|我(?:喜欢|偏好|习惯|希望|要求)|规则|偏好|习惯|from now on|remember|prefer)/i.test(sentence))
|
|
||||||
continue;
|
|
||||||
const category = /(总是|始终|必须|不要|别|规则|要求|always|never|must)/i.test(sentence) ? 'rule' : 'preference';
|
|
||||||
if (category === 'preference' && this.settingsOf().autoProfileEnabled === false)
|
|
||||||
continue;
|
|
||||||
const result = await this.globalStore.add({ content: sentence, category, source: 'session:' + input.sessionId, sessionId: input.sessionId, tags: ['auto-summary'] });
|
|
||||||
if (result.duplicate)
|
|
||||||
duplicates += 1;
|
|
||||||
else
|
|
||||||
stored += 1;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
const nextCount = (prior?.count ?? 0) + fresh.length;
|
|
||||||
const processedNext = new Set(processed);
|
|
||||||
for (const turn of fresh)
|
|
||||||
if (turn.turnId !== undefined)
|
|
||||||
processedNext.add(turn.turnId);
|
|
||||||
let documentId;
|
|
||||||
if (fresh.length > 0) {
|
|
||||||
// ensureProject above guarantees the workspace entry exists (the map is never pruned).
|
|
||||||
const documents = this.workspaces.get(this.projectRootFor(workspace)).documents;
|
|
||||||
const document = await documents.add({ title: '会话总结 ' + input.sessionId, content: input.summary ?? ('本次会话共 ' + String(nextCount) + ' 轮,已更新增量检查点。'), source: 'session:' + input.sessionId, tags: ['auto-summary'] });
|
|
||||||
documentId = document.id;
|
|
||||||
}
|
|
||||||
const lastTurn = prior?.lastTurn;
|
|
||||||
const lastCandidate = fresh.map((turn) => turn.turnId).filter((value) => value !== undefined).at(-1);
|
|
||||||
const lastValue = lastCandidate === undefined ? lastTurn : lastTurn === undefined ? lastCandidate : (Number.isFinite(Number(lastCandidate)) && Number.isFinite(Number(lastTurn)) ? (Number(lastCandidate) >= Number(lastTurn) ? lastCandidate : lastTurn) : lastTurn);
|
|
||||||
checkpoints[input.sessionId] = { ...(lastValue === undefined ? {} : { lastTurn: lastValue }), count: nextCount, processed: [...processedNext].slice(-1000) };
|
|
||||||
await atomicWrite(checkpointPath, JSON.stringify(checkpoints, null, 2) + '\n');
|
|
||||||
if (stored > 0) {
|
|
||||||
const repair = await this.tryRegenerateProjections();
|
|
||||||
this.loggerOf?.log({ event: 'memory.summary', sessionId: input.sessionId, detail: { turns: input.turns.length, stored, duplicates, skipped: false } });
|
|
||||||
return { stored, duplicates, ...(documentId === undefined ? {} : { documentId }), skipped: false, ...repair };
|
|
||||||
}
|
|
||||||
this.loggerOf?.log({ event: 'memory.summary', sessionId: input.sessionId, detail: { turns: input.turns.length, stored, duplicates, skipped: false } });
|
|
||||||
return { stored, duplicates, ...(documentId === undefined ? {} : { documentId }), skipped: false };
|
|
||||||
});
|
|
||||||
}
|
|
||||||
/** Add an explicit profile entry; inferred entries stay in the pending area. */
|
|
||||||
async proposeProfile(content, source = 'user', inferred = false) {
|
|
||||||
if (this.settingsOf().autoProfileEnabled === false)
|
|
||||||
throw new Error('auto_profile_disabled');
|
|
||||||
await this.ensureGlobal();
|
|
||||||
await this.markProjectionDirty();
|
|
||||||
const result = await this.globalStore.add({ content, category: inferred ? 'profile-pending' : 'preference', source, tags: ['profile'] });
|
|
||||||
if (!inferred)
|
|
||||||
await this.tryRegenerateProjections();
|
|
||||||
return result.record;
|
|
||||||
}
|
|
||||||
async confirmProfile(id) { await this.ensureGlobal(); await this.markProjectionDirty(); const record = await this.globalStore.read(id); if (record === undefined)
|
|
||||||
throw new Error('memory_not_found'); await this.globalStore.update(id, { category: 'preference' }); await this.tryRegenerateProjections(); }
|
|
||||||
/** Correct an existing profile entry in place; the revision increments and prior text is not kept as a live entry. */
|
|
||||||
async correctProfile(id, content, expectedRevision) { await this.ensureGlobal(); await this.markProjectionDirty(); const record = await this.globalStore.update(id, { content, category: 'preference' }, expectedRevision); await this.tryRegenerateProjections(); return record; }
|
|
||||||
/** Copy the whole global memory root into backups; no source file is removed. */
|
|
||||||
async createBackup() {
|
|
||||||
await this.ensureGlobal();
|
|
||||||
const path = join(this.globalRoot, 'backups', 'backup-' + new Date().toISOString().replace(/[:.]/g, '-'));
|
|
||||||
await mkdir(path, { recursive: true });
|
|
||||||
for (const entry of await readdir(this.globalRoot, { withFileTypes: true })) {
|
|
||||||
if (entry.name === 'backups')
|
|
||||||
continue;
|
|
||||||
await cp(join(this.globalRoot, entry.name), join(path, entry.name), { recursive: true, force: false });
|
|
||||||
}
|
|
||||||
this.loggerOf?.log({ event: 'memory.backup', detail: { path } });
|
|
||||||
return { path };
|
|
||||||
}
|
|
||||||
/** Report legacy .mnemon locations without deleting anything. */
|
|
||||||
async legacyMigrationReport(workspace) {
|
|
||||||
const found = [];
|
|
||||||
for (const path of [join(this.projectBaseFor(workspace), '.mnemon'), join(dshHome(), '.mnemon')]) {
|
|
||||||
if (await stat(path).catch(() => undefined) !== undefined)
|
|
||||||
found.push(path);
|
|
||||||
}
|
|
||||||
return { found, targetGlobal: this.globalRoot, targetProject: this.projectRootFor(workspace) };
|
|
||||||
}
|
|
||||||
async findLegacyMemoryFiles(root) {
|
|
||||||
const out = [];
|
|
||||||
const walk = async (dir) => {
|
|
||||||
for (const entry of await readdir(dir, { withFileTypes: true }).catch(() => [])) {
|
|
||||||
const full = join(dir, entry.name);
|
|
||||||
if (entry.isDirectory()) {
|
|
||||||
await walk(full);
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
if (/^(memories|memory)\.json$/i.test(entry.name) || /\.memory\.json$/i.test(entry.name))
|
|
||||||
out.push(full);
|
|
||||||
}
|
|
||||||
};
|
|
||||||
await walk(root);
|
|
||||||
return out;
|
|
||||||
}
|
|
||||||
legacyRecordsFrom(value) {
|
|
||||||
if (Array.isArray(value))
|
|
||||||
return value.filter((item) => item !== null && typeof item === 'object' && !Array.isArray(item));
|
|
||||||
if (value === null || typeof value !== 'object' || Array.isArray(value))
|
|
||||||
return [];
|
|
||||||
const record = value;
|
|
||||||
for (const key of ['records', 'memories', 'items']) {
|
|
||||||
if (Array.isArray(record[key]))
|
|
||||||
return this.legacyRecordsFrom(record[key]);
|
|
||||||
}
|
|
||||||
return record.content === undefined && record.text === undefined && record.memory === undefined ? [] : [record];
|
|
||||||
}
|
|
||||||
async importLegacyRecords(sourcePath, workspace) {
|
|
||||||
const projectLegacy = resolve(join(this.projectBaseFor(workspace), '.mnemon')) === resolve(sourcePath);
|
|
||||||
const scope = projectLegacy ? 'project' : 'global';
|
|
||||||
const store = await this.storeFor(scope, workspace);
|
|
||||||
let imported = 0;
|
|
||||||
let duplicates = 0;
|
|
||||||
let skipped = 0;
|
|
||||||
const ids = [];
|
|
||||||
for (const file of await this.findLegacyMemoryFiles(sourcePath)) {
|
|
||||||
let parsed;
|
|
||||||
try {
|
|
||||||
parsed = JSON.parse(await readFile(file, 'utf8'));
|
|
||||||
}
|
|
||||||
catch {
|
|
||||||
skipped += 1;
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
for (const item of this.legacyRecordsFrom(parsed)) {
|
|
||||||
const content = typeof item.content === 'string' ? item.content : typeof item.text === 'string' ? item.text : typeof item.memory === 'string' ? item.memory : '';
|
|
||||||
if (content.trim() === '') {
|
|
||||||
skipped += 1;
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
const category = typeof item.category === 'string' ? item.category : typeof item.sector === 'string' ? item.sector : undefined;
|
|
||||||
const tags = Array.isArray(item.tags) ? item.tags.filter((tag) => typeof tag === 'string') : [];
|
|
||||||
const legacyId = typeof item.id === 'string' ? item.id : '';
|
|
||||||
const operationId = 'legacy-' + localMemoryHash(file + '|' + legacyId + '|' + content);
|
|
||||||
try {
|
|
||||||
const result = await store.add({ content, ...(category === undefined ? {} : { category }), tags, source: 'legacy:' + file, operationId, scope, ...(scope === 'project' ? { projectId: projectIdFor(this.projectRootFor(workspace)) } : {}) });
|
|
||||||
if (result.duplicate)
|
|
||||||
duplicates += 1;
|
|
||||||
else
|
|
||||||
imported += 1;
|
|
||||||
// Content-only duplicates were present before this migration and
|
|
||||||
// must never enter this migration's rollback ownership list.
|
|
||||||
if ((!result.duplicate || result.duplicateKind === 'operation') && !ids.includes(result.record.id))
|
|
||||||
ids.push(result.record.id);
|
|
||||||
}
|
|
||||||
catch {
|
|
||||||
skipped += 1;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return { imported, duplicates, skipped, ids, scope, ...(workspace === undefined ? {} : { workspace }) };
|
|
||||||
}
|
|
||||||
/** Copy a legacy directory into backups; never moves or deletes the source. */
|
|
||||||
async migrateLegacy(path, workspace) {
|
|
||||||
return withFileLock(join(this.globalRoot, 'state', '.migrations.lock'), async () => {
|
|
||||||
const target = join(this.globalRoot, 'backups', 'migration-' + Date.now().toString(36) + '-' + randomUUID().slice(0, 8));
|
|
||||||
await mkdir(this.globalRoot, { recursive: true });
|
|
||||||
await cp(path, target, { recursive: true, force: false });
|
|
||||||
await this.markProjectionDirty();
|
|
||||||
const manifestPath = join(this.globalRoot, 'state', 'migrations.json');
|
|
||||||
const manifest = await readJson(manifestPath, []);
|
|
||||||
const resolvedWorkspace = this.workspacePath(workspace);
|
|
||||||
const projectLegacy = resolve(join(this.projectBaseFor(workspace), '.mnemon')) === resolve(path);
|
|
||||||
const targetScope = projectLegacy ? 'project' : 'global';
|
|
||||||
const entry = { source: path, copiedTo: target, createdAt: new Date().toISOString(), status: 'importing', importedIds: [], targetScope, workspace: resolvedWorkspace };
|
|
||||||
manifest.push(entry);
|
|
||||||
await atomicWrite(manifestPath, JSON.stringify(manifest, null, 2) + '\n');
|
|
||||||
try {
|
|
||||||
const imported = await this.importLegacyRecords(path, workspace);
|
|
||||||
entry.importedIds = imported.ids;
|
|
||||||
entry.status = imported.skipped > 0 ? 'partial' : 'complete';
|
|
||||||
Object.assign(entry, { imported: imported.imported, duplicates: imported.duplicates, skipped: imported.skipped, partial: imported.skipped > 0 });
|
|
||||||
await atomicWrite(manifestPath, JSON.stringify(manifest, null, 2) + '\n');
|
|
||||||
return { copiedTo: target, imported: imported.imported, duplicates: imported.duplicates, skipped: imported.skipped, partial: imported.skipped > 0 };
|
|
||||||
}
|
|
||||||
catch (error) {
|
|
||||||
entry.status = 'error';
|
|
||||||
entry.error = error instanceof Error ? error.message : String(error);
|
|
||||||
await atomicWrite(manifestPath, JSON.stringify(manifest, null, 2) + '\n').catch(() => { });
|
|
||||||
throw error;
|
|
||||||
}
|
|
||||||
});
|
|
||||||
}
|
|
||||||
/** Restore a prepared backup first, then remove imported records; retries resume safely. */
|
|
||||||
async rollbackMigration(copiedTo, destination) {
|
|
||||||
return withFileLock(join(this.globalRoot, 'state', '.migrations.lock'), async () => {
|
|
||||||
const manifestPath = join(this.globalRoot, 'state', 'migrations.json');
|
|
||||||
const manifest = await readJson(manifestPath, []);
|
|
||||||
const entry = manifest.find((item) => item.copiedTo === copiedTo);
|
|
||||||
if (entry === undefined)
|
|
||||||
throw new Error('migration_not_found');
|
|
||||||
const backupStat = await stat(copiedTo).catch(() => undefined);
|
|
||||||
if (backupStat === undefined || !backupStat.isDirectory())
|
|
||||||
throw new Error('migration_backup_missing');
|
|
||||||
const completedDestination = entry.rollback?.destination;
|
|
||||||
if (entry.rollback?.status === 'complete' && completedDestination !== undefined) {
|
|
||||||
return { restoredTo: completedDestination, removedImported: 0 };
|
|
||||||
}
|
|
||||||
if (completedDestination !== undefined && destination !== undefined && resolve(completedDestination) !== resolve(destination)) {
|
|
||||||
throw new Error('restore_destination_mismatch');
|
|
||||||
}
|
|
||||||
const restoredTo = completedDestination ?? destination ?? join(this.globalRoot, 'backups', 'restore-' + Date.now().toString(36));
|
|
||||||
const destinationStat = await stat(restoredTo).catch(() => undefined);
|
|
||||||
if (destinationStat !== undefined && !destinationStat.isDirectory())
|
|
||||||
throw new Error('restore_destination_not_directory');
|
|
||||||
entry.rollback = entry.rollback ?? {};
|
|
||||||
entry.rollback.destination = restoredTo;
|
|
||||||
if (entry.rollback.staging === undefined || !(await stat(entry.rollback.staging).catch(() => undefined))?.isDirectory()) {
|
|
||||||
const staging = join(this.globalRoot, 'backups', '.restore-' + Date.now().toString(36) + '-' + randomUUID());
|
|
||||||
await cp(copiedTo, staging, { recursive: true, force: false });
|
|
||||||
entry.rollback.staging = staging;
|
|
||||||
}
|
|
||||||
const rollbackStatus = entry.rollback.status;
|
|
||||||
if (rollbackStatus === 'complete') {
|
|
||||||
if ((await readdir(restoredTo).catch(() => [])).length > 0)
|
|
||||||
throw new Error('restore_destination_not_empty');
|
|
||||||
await cp(copiedTo, restoredTo, { recursive: true, force: false });
|
|
||||||
if (await treeDigest(copiedTo) !== await treeDigest(restoredTo))
|
|
||||||
throw new Error('restore_copy_incomplete');
|
|
||||||
return { restoredTo, removedImported: 0 };
|
|
||||||
}
|
|
||||||
if (rollbackStatus === undefined || rollbackStatus === 'prepared') {
|
|
||||||
entry.rollback.status = 'prepared';
|
|
||||||
await atomicWrite(manifestPath, JSON.stringify(manifest, null, 2) + '\n');
|
|
||||||
}
|
|
||||||
// Land the restore copy before touching the active store. A conflicting
|
|
||||||
// child in the destination therefore fails with the active store intact.
|
|
||||||
if (rollbackStatus !== 'copied' && rollbackStatus !== 'records_removed' && rollbackStatus !== 'complete') {
|
|
||||||
if ((await readdir(restoredTo).catch(() => [])).length > 0)
|
|
||||||
throw new Error('restore_destination_not_empty');
|
|
||||||
await cp(entry.rollback.staging, restoredTo, { recursive: true, force: false });
|
|
||||||
if (await treeDigest(entry.rollback.staging) !== await treeDigest(restoredTo))
|
|
||||||
throw new Error('restore_copy_incomplete');
|
|
||||||
entry.rollback.status = 'copied';
|
|
||||||
await atomicWrite(manifestPath, JSON.stringify(manifest, null, 2) + '\n');
|
|
||||||
}
|
|
||||||
if (rollbackStatus === 'copied') {
|
|
||||||
const copyStat = await stat(restoredTo).catch(() => undefined);
|
|
||||||
if (copyStat === undefined || !copyStat.isDirectory())
|
|
||||||
throw new Error('restore_copy_missing');
|
|
||||||
if (await treeDigest(restoredTo) !== await treeDigest(copiedTo))
|
|
||||||
throw new Error('restore_copy_incomplete');
|
|
||||||
}
|
|
||||||
const store = entry.targetScope === 'project' ? await this.storeFor('project', entry.workspace) : this.globalStore;
|
|
||||||
let removedImported = 0;
|
|
||||||
if (rollbackStatus !== 'records_removed' && rollbackStatus !== 'complete') {
|
|
||||||
for (const id of entry.importedIds ?? []) {
|
|
||||||
try {
|
|
||||||
await store.forget(id);
|
|
||||||
removedImported += 1;
|
|
||||||
}
|
|
||||||
catch (error) {
|
|
||||||
const message = error instanceof Error ? error.message : String(error);
|
|
||||||
if (message.includes('memory_not_found'))
|
|
||||||
continue;
|
|
||||||
throw new Error('rollback_record_failed: ' + message);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
entry.rollback.status = 'records_removed';
|
|
||||||
await atomicWrite(manifestPath, JSON.stringify(manifest, null, 2) + '\n');
|
|
||||||
}
|
|
||||||
await rm(entry.rollback.staging, { recursive: true, force: true }).catch(() => { });
|
|
||||||
entry.rollback.status = 'complete';
|
|
||||||
entry.status = 'rolled_back';
|
|
||||||
await atomicWrite(manifestPath, JSON.stringify(manifest, null, 2) + '\n');
|
|
||||||
const projection = removedImported > 0 ? await this.tryRegenerateProjections() : { projectionPending: false };
|
|
||||||
return { restoredTo, removedImported, ...projection };
|
|
||||||
});
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
@ -1,46 +0,0 @@
|
||||||
function hitOf(record) {
|
|
||||||
return { id: record.id, content: record.content, tags: record.tags, project_id: record.projectId ?? null, primary_sector: record.category, revision: record.revision, created_at: Date.parse(record.createdAt), updated_at: Date.parse(record.updatedAt) };
|
|
||||||
}
|
|
||||||
function ok(data) { return { ok: true, status: 200, data }; }
|
|
||||||
export class LocalMemoryRemote {
|
|
||||||
manager;
|
|
||||||
constructor(manager) {
|
|
||||||
this.manager = manager;
|
|
||||||
}
|
|
||||||
run(workspace, job) {
|
|
||||||
return workspace === undefined ? job() : this.manager.withWorkspace(workspace, job);
|
|
||||||
}
|
|
||||||
async search(query, k, project, workspace) {
|
|
||||||
return this.run(workspace, async () => {
|
|
||||||
const records = await this.manager.search(query, k, workspace, project);
|
|
||||||
const matches = records.map(hitOf);
|
|
||||||
return ok({ matches, total: matches.length, search_mode: 'local' });
|
|
||||||
});
|
|
||||||
}
|
|
||||||
async read(id, workspace) {
|
|
||||||
return this.run(workspace, async () => {
|
|
||||||
const record = await this.manager.read(id, workspace);
|
|
||||||
if (record === undefined)
|
|
||||||
return { ok: false, error: { status: 404, code: 'memory_not_found', message: '记忆不存在' } };
|
|
||||||
return ok(hitOf(record));
|
|
||||||
});
|
|
||||||
}
|
|
||||||
async add(input, workspace) {
|
|
||||||
return this.run(workspace, async () => {
|
|
||||||
const result = await this.manager.remember({ content: input.content, tags: input.tags, category: input.sector, source: 'memory_tool', operationId: input.operationId, scope: input.project === 'global' ? 'global' : 'project' });
|
|
||||||
return ok({ id: result.record.id, revision: result.record.revision, state: 'stored', remote_saved: true });
|
|
||||||
});
|
|
||||||
}
|
|
||||||
async list(options = {}, workspace) {
|
|
||||||
return this.run(workspace, async () => {
|
|
||||||
const page = await this.manager.list({ limit: options.limit, offset: options.offset }, workspace, options.project);
|
|
||||||
return ok({ items: page.items.map(hitOf), total: page.total });
|
|
||||||
});
|
|
||||||
}
|
|
||||||
async projects(workspace) {
|
|
||||||
return this.run(workspace, async () => ok({ projects: await this.manager.projects(workspace) }));
|
|
||||||
}
|
|
||||||
async storageStatus(workspace) {
|
|
||||||
return this.run(workspace, async () => ok(await this.manager.storageStatus(workspace)));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
@ -1,271 +0,0 @@
|
||||||
/** Atomic JSON storage for one local memory space. */
|
|
||||||
import { createHash, randomUUID } from 'node:crypto';
|
|
||||||
import { mkdir, open, readFile, rename, rm, stat, writeFile } from 'node:fs/promises';
|
|
||||||
import { dirname, join } from 'node:path';
|
|
||||||
const EMPTY_FILE = { version: 1, nextChange: 1, operations: {}, records: [] };
|
|
||||||
function nowIso() { return new Date().toISOString(); }
|
|
||||||
const SECRET_PATTERNS = [
|
|
||||||
/(?:api[ _-]?key|access[ _-]?token|client[ _-]?secret|secret|password|passwd|pwd)\s*(?:是|为|[:=:])\s*["']?[A-Za-z0-9_\-./+=]{6,}/i,
|
|
||||||
/(?:密码|口令|令牌|密钥|恢复码)\s*(?:是|为|[:=:])\s*\S{6,}/,
|
|
||||||
/\b(?:gh[pousr]_[A-Za-z0-9]{20,}|AKIA[0-9A-Z]{16}|xox[baprs]-[A-Za-z0-9-]{10,})\b/,
|
|
||||||
/\bBearer\s+[A-Za-z0-9\-._~+/]+=*/i,
|
|
||||||
];
|
|
||||||
/** Secrets never belong in a memory record or an automatic summary. */
|
|
||||||
export function containsSecret(value) { return SECRET_PATTERNS.some((pattern) => pattern.test(value)); }
|
|
||||||
function safeText(value, max = 64000) { return typeof value === 'string' ? value.trim().slice(0, max) : ''; }
|
|
||||||
function tagsOf(value) {
|
|
||||||
if (!Array.isArray(value))
|
|
||||||
return [];
|
|
||||||
const tags = value.filter((item) => typeof item === 'string').map((item) => item.trim()).filter((item) => item !== '');
|
|
||||||
return [...new Set(tags)].slice(0, 20);
|
|
||||||
}
|
|
||||||
async function atomicWrite(path, content) {
|
|
||||||
await mkdir(dirname(path), { recursive: true });
|
|
||||||
const tmp = path + '.' + String(process.pid) + '.' + randomUUID() + '.tmp';
|
|
||||||
try {
|
|
||||||
await writeFile(tmp, content, { encoding: 'utf8', mode: 0o600 });
|
|
||||||
await rename(tmp, path);
|
|
||||||
}
|
|
||||||
catch (error) {
|
|
||||||
await rm(tmp, { force: true }).catch(() => { });
|
|
||||||
throw error;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
export async function withFileLock(lockPath, job) {
|
|
||||||
await mkdir(dirname(lockPath), { recursive: true });
|
|
||||||
const started = Date.now();
|
|
||||||
let handle;
|
|
||||||
while (handle === undefined) {
|
|
||||||
try {
|
|
||||||
handle = await open(lockPath, 'wx', 0o600);
|
|
||||||
}
|
|
||||||
catch (error) {
|
|
||||||
const code = error.code;
|
|
||||||
if (code !== 'EEXIST')
|
|
||||||
throw error;
|
|
||||||
const info = await stat(lockPath).catch(() => undefined);
|
|
||||||
if (info !== undefined && Date.now() - info.mtimeMs > 60000) {
|
|
||||||
await rm(lockPath, { force: true }).catch(() => { });
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
if (Date.now() - started > 10000)
|
|
||||||
throw new Error('local_memory_lock_timeout');
|
|
||||||
await new Promise((resolve) => setTimeout(resolve, 40));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
try {
|
|
||||||
return await job();
|
|
||||||
}
|
|
||||||
finally {
|
|
||||||
await handle.close().catch(() => { });
|
|
||||||
await rm(lockPath, { force: true }).catch(() => { });
|
|
||||||
}
|
|
||||||
}
|
|
||||||
export class JsonMemoryStore {
|
|
||||||
root;
|
|
||||||
scope;
|
|
||||||
spaceId;
|
|
||||||
dataPath;
|
|
||||||
metaPath;
|
|
||||||
lockPath;
|
|
||||||
constructor(root, scope, spaceId) {
|
|
||||||
this.root = root;
|
|
||||||
this.scope = scope;
|
|
||||||
this.spaceId = spaceId;
|
|
||||||
this.dataPath = join(root, 'memories.json');
|
|
||||||
this.metaPath = join(root, 'space.json');
|
|
||||||
this.lockPath = join(root, '.lock');
|
|
||||||
}
|
|
||||||
async init(name = this.scope === 'global' ? '全局记忆' : '项目记忆') {
|
|
||||||
await mkdir(this.root, { recursive: true });
|
|
||||||
return withFileLock(this.lockPath, async () => {
|
|
||||||
const existing = await this.spaceMeta();
|
|
||||||
if (existing !== undefined)
|
|
||||||
return existing;
|
|
||||||
const meta = { id: this.spaceId, scope: this.scope, name, root: this.root, createdAt: nowIso(), active: true };
|
|
||||||
await atomicWrite(this.metaPath, JSON.stringify(meta, null, 2) + '\n');
|
|
||||||
return meta;
|
|
||||||
});
|
|
||||||
}
|
|
||||||
async setActive(active) {
|
|
||||||
return withFileLock(this.lockPath, async () => {
|
|
||||||
const existing = await this.spaceMeta();
|
|
||||||
if (existing === undefined)
|
|
||||||
throw new Error('local_memory_space_not_found');
|
|
||||||
const next = { ...existing, active };
|
|
||||||
await atomicWrite(this.metaPath, JSON.stringify(next, null, 2) + '\n');
|
|
||||||
return next;
|
|
||||||
});
|
|
||||||
}
|
|
||||||
async spaceMeta() {
|
|
||||||
let text;
|
|
||||||
try {
|
|
||||||
text = await readFile(this.metaPath, 'utf8');
|
|
||||||
}
|
|
||||||
catch (error) {
|
|
||||||
if (error.code === 'ENOENT')
|
|
||||||
return undefined;
|
|
||||||
throw new Error(`local_memory_meta_read_failed: ${this.metaPath}: ${error instanceof Error ? error.message : String(error)}`);
|
|
||||||
}
|
|
||||||
let parsed;
|
|
||||||
try {
|
|
||||||
parsed = JSON.parse(text);
|
|
||||||
}
|
|
||||||
catch {
|
|
||||||
throw new Error(`local_memory_meta_corrupt: ${this.metaPath}`);
|
|
||||||
}
|
|
||||||
if (parsed === null || typeof parsed !== 'object' || Array.isArray(parsed))
|
|
||||||
throw new Error(`local_memory_meta_corrupt: ${this.metaPath}`);
|
|
||||||
const value = parsed;
|
|
||||||
if (typeof value.id !== 'string' || (value.scope !== 'global' && value.scope !== 'project' && value.scope !== 'department'))
|
|
||||||
throw new Error(`local_memory_meta_incompatible: ${this.metaPath}`);
|
|
||||||
return { id: value.id, scope: value.scope, name: typeof value.name === 'string' ? value.name : value.id, root: typeof value.root === 'string' ? value.root : this.root, createdAt: typeof value.createdAt === 'string' ? value.createdAt : nowIso(), active: value.active !== false };
|
|
||||||
}
|
|
||||||
async readFile() {
|
|
||||||
let text;
|
|
||||||
try {
|
|
||||||
text = await readFile(this.dataPath, 'utf8');
|
|
||||||
}
|
|
||||||
catch (error) {
|
|
||||||
if (error.code === 'ENOENT')
|
|
||||||
return { ...EMPTY_FILE, operations: {}, records: [] };
|
|
||||||
throw new Error(`local_memory_read_failed: ${this.dataPath}: ${error instanceof Error ? error.message : String(error)}`);
|
|
||||||
}
|
|
||||||
let parsed;
|
|
||||||
try {
|
|
||||||
parsed = JSON.parse(text);
|
|
||||||
}
|
|
||||||
catch {
|
|
||||||
throw new Error(`local_memory_corrupt: ${this.dataPath}`);
|
|
||||||
}
|
|
||||||
if (parsed === null || typeof parsed !== 'object' || Array.isArray(parsed))
|
|
||||||
throw new Error(`local_memory_corrupt: ${this.dataPath}`);
|
|
||||||
const value = parsed;
|
|
||||||
if (value.version !== undefined && value.version !== 1)
|
|
||||||
throw new Error(`local_memory_incompatible: ${this.dataPath}`);
|
|
||||||
if (value.records !== undefined && !Array.isArray(value.records))
|
|
||||||
throw new Error(`local_memory_incompatible: ${this.dataPath}`);
|
|
||||||
return { version: 1, nextChange: typeof value.nextChange === 'number' && Number.isFinite(value.nextChange) ? value.nextChange : 1, operations: value.operations !== null && typeof value.operations === 'object' && !Array.isArray(value.operations) ? value.operations : {}, records: Array.isArray(value.records) ? value.records.filter((record) => record !== null && typeof record === 'object') : [] };
|
|
||||||
}
|
|
||||||
async writeFile(file) { await atomicWrite(this.dataPath, JSON.stringify(file, null, 2) + '\n'); }
|
|
||||||
activeRecords(file) { return file.records.filter((record) => record.deleted !== true); }
|
|
||||||
async add(input) {
|
|
||||||
const content = safeText(input.content);
|
|
||||||
if (content === '')
|
|
||||||
throw new Error('记忆内容不能为空');
|
|
||||||
if (containsSecret(content))
|
|
||||||
throw new Error('secret_not_allowed');
|
|
||||||
return withFileLock(this.lockPath, async () => {
|
|
||||||
const file = await this.readFile();
|
|
||||||
if (input.operationId !== undefined && input.operationId !== '') {
|
|
||||||
const prior = file.operations[input.operationId];
|
|
||||||
if (prior !== undefined) {
|
|
||||||
const found = file.records.find((record) => record.id === prior);
|
|
||||||
if (found !== undefined && found.deleted !== true)
|
|
||||||
return { record: found, duplicate: true, duplicateKind: 'operation' };
|
|
||||||
}
|
|
||||||
}
|
|
||||||
const duplicate = this.activeRecords(file).find((record) => record.content === content && record.spaceId === this.spaceId);
|
|
||||||
if (duplicate !== undefined)
|
|
||||||
return { record: duplicate, duplicate: true, duplicateKind: 'content' };
|
|
||||||
const timestamp = nowIso();
|
|
||||||
const record = { id: 'lm_' + randomUUID(), scope: this.scope, spaceId: this.spaceId, content, ...(input.category === undefined || input.category === '' ? {} : { category: input.category }), tags: tagsOf(input.tags), source: safeText(input.source, 500) || 'local', ...(input.sessionId === undefined ? {} : { sessionId: input.sessionId }), ...(input.projectId === undefined ? {} : { projectId: input.projectId }), ...(input.departmentId === undefined ? {} : { departmentId: input.departmentId }), createdAt: timestamp, updatedAt: timestamp, revision: 1, changeSeq: file.nextChange, ...(input.operationId === undefined ? {} : { operationId: input.operationId }) };
|
|
||||||
file.nextChange += 1;
|
|
||||||
file.records.push(record);
|
|
||||||
if (input.operationId !== undefined && input.operationId !== '')
|
|
||||||
file.operations[input.operationId] = record.id;
|
|
||||||
await this.writeFile(file);
|
|
||||||
return { record, duplicate: false };
|
|
||||||
});
|
|
||||||
}
|
|
||||||
async read(id) { return this.activeRecords(await this.readFile()).find((record) => record.id === id); }
|
|
||||||
async search(query, k = 5) {
|
|
||||||
const file = await this.readFile();
|
|
||||||
const q = query.trim().toLowerCase();
|
|
||||||
const terms = q.split(/\s+/).filter((term) => term !== '');
|
|
||||||
return this.activeRecords(file).map((record) => { const haystack = (record.content + '\n' + (record.tags ?? []).join(' ') + '\n' + (record.category ?? '')).toLowerCase(); const score = terms.length === 0 ? 1 : terms.reduce((sum, term) => sum + (haystack.includes(term) ? 1 : 0), 0); return { record, score }; }).filter((hit) => terms.length === 0 || hit.score > 0).sort((a, b) => b.score - a.score || b.record.updatedAt.localeCompare(a.record.updatedAt)).slice(0, Math.max(1, Math.min(100, Math.trunc(k))));
|
|
||||||
}
|
|
||||||
async list(options = {}) {
|
|
||||||
const file = await this.readFile();
|
|
||||||
const records = this.activeRecords(file);
|
|
||||||
// Order the whole set before slicing: paging must stay stable across pages.
|
|
||||||
// `updated` keeps the historical order; `created` is the API's new default.
|
|
||||||
const ordered = options.order === 'created'
|
|
||||||
? records.sort((a, b) => b.createdAt.localeCompare(a.createdAt) || a.id.localeCompare(b.id))
|
|
||||||
: records.sort((a, b) => b.updatedAt.localeCompare(a.updatedAt));
|
|
||||||
const offset = Math.max(0, Math.trunc(options.offset ?? 0));
|
|
||||||
const limit = Math.max(1, Math.min(1000, Math.trunc(options.limit ?? 50)));
|
|
||||||
return { items: ordered.slice(offset, offset + limit), total: ordered.length };
|
|
||||||
}
|
|
||||||
async update(id, patch, expectedRevision) {
|
|
||||||
return withFileLock(this.lockPath, async () => { const file = await this.readFile(); const record = file.records.find((item) => item.id === id && item.deleted !== true); if (record === undefined)
|
|
||||||
throw new Error('memory_not_found'); if (expectedRevision !== undefined && record.revision !== expectedRevision)
|
|
||||||
throw new Error('revision_conflict'); if (patch.content !== undefined) {
|
|
||||||
const content = safeText(patch.content);
|
|
||||||
if (content === '')
|
|
||||||
throw new Error('记忆内容不能为空');
|
|
||||||
if (containsSecret(content))
|
|
||||||
throw new Error('secret_not_allowed');
|
|
||||||
record.content = content;
|
|
||||||
} if (patch.tags !== undefined)
|
|
||||||
record.tags = tagsOf(patch.tags); if (patch.category !== undefined)
|
|
||||||
record.category = patch.category; record.revision += 1; record.changeSeq = file.nextChange; record.updatedAt = nowIso(); file.nextChange += 1; await this.writeFile(file); return record; });
|
|
||||||
}
|
|
||||||
async forget(id, expectedRevision) {
|
|
||||||
return withFileLock(this.lockPath, async () => { const file = await this.readFile(); const record = file.records.find((item) => item.id === id && item.deleted !== true); if (record === undefined)
|
|
||||||
throw new Error('memory_not_found'); if (expectedRevision !== undefined && record.revision !== expectedRevision)
|
|
||||||
throw new Error('revision_conflict'); record.deleted = true; record.revision += 1; record.changeSeq = file.nextChange; record.updatedAt = nowIso(); file.nextChange += 1; await this.writeFile(file); return record; });
|
|
||||||
}
|
|
||||||
async records() { return this.activeRecords(await this.readFile()); }
|
|
||||||
}
|
|
||||||
export class JsonDocumentStore {
|
|
||||||
root;
|
|
||||||
indexPath;
|
|
||||||
lockPath;
|
|
||||||
constructor(root) { this.root = root; this.indexPath = join(root, 'index.json'); this.lockPath = join(root, '.lock'); }
|
|
||||||
async init() { await mkdir(this.root, { recursive: true }); await mkdir(join(this.root, 'files'), { recursive: true }); }
|
|
||||||
async read() {
|
|
||||||
let text;
|
|
||||||
try {
|
|
||||||
text = await readFile(this.indexPath, 'utf8');
|
|
||||||
}
|
|
||||||
catch (error) {
|
|
||||||
if (error.code === 'ENOENT')
|
|
||||||
return { version: 1, nextRevision: 1, documents: [] };
|
|
||||||
throw new Error(`local_documents_read_failed: ${this.indexPath}: ${error instanceof Error ? error.message : String(error)}`);
|
|
||||||
}
|
|
||||||
let parsed;
|
|
||||||
try {
|
|
||||||
parsed = JSON.parse(text);
|
|
||||||
}
|
|
||||||
catch {
|
|
||||||
throw new Error(`local_documents_corrupt: ${this.indexPath}`);
|
|
||||||
}
|
|
||||||
if (parsed === null || typeof parsed !== 'object' || Array.isArray(parsed))
|
|
||||||
throw new Error(`local_documents_corrupt: ${this.indexPath}`);
|
|
||||||
const value = parsed;
|
|
||||||
if (value.documents !== undefined && !Array.isArray(value.documents))
|
|
||||||
throw new Error(`local_documents_incompatible: ${this.indexPath}`);
|
|
||||||
return { version: 1, nextRevision: typeof value.nextRevision === 'number' ? value.nextRevision : 1, documents: Array.isArray(value.documents) ? value.documents : [] };
|
|
||||||
}
|
|
||||||
async write(file) { await atomicWrite(this.indexPath, JSON.stringify(file, null, 2) + '\n'); }
|
|
||||||
async add(input) {
|
|
||||||
const title = safeText(input.title, 500);
|
|
||||||
const content = safeText(input.content, 200000);
|
|
||||||
if (title === '' || content === '')
|
|
||||||
throw new Error('文档标题和内容不能为空');
|
|
||||||
if (containsSecret(title) || containsSecret(content))
|
|
||||||
throw new Error('secret_not_allowed');
|
|
||||||
return withFileLock(this.lockPath, async () => { const file = await this.read(); const duplicate = file.documents.find((document) => document.deleted !== true && document.title === title && document.content === content); if (duplicate !== undefined) {
|
|
||||||
const filePath = join(this.root, 'files', duplicate.id + '.md');
|
|
||||||
if ((await readFile(filePath).catch(() => undefined)) === undefined)
|
|
||||||
await atomicWrite(filePath, '# ' + title + '\n\n' + content + '\n');
|
|
||||||
return duplicate;
|
|
||||||
} const timestamp = nowIso(); const document = { id: 'doc_' + randomUUID(), title, content, source: safeText(input.source, 500) || 'local', tags: tagsOf(input.tags), createdAt: timestamp, updatedAt: timestamp, revision: 1 }; file.documents.push(document); await this.write(file); await atomicWrite(join(this.root, 'files', document.id + '.md'), '# ' + title + '\n\n' + content + '\n'); return document; });
|
|
||||||
}
|
|
||||||
async list() { return (await this.read()).documents.filter((document) => document.deleted !== true); }
|
|
||||||
async readDocument(id) { return (await this.read()).documents.find((document) => document.id === id && document.deleted !== true); }
|
|
||||||
async remove(id) { await withFileLock(this.lockPath, async () => { const file = await this.read(); const document = file.documents.find((item) => item.id === id && item.deleted !== true); if (document === undefined)
|
|
||||||
return; document.deleted = true; document.revision += 1; document.updatedAt = nowIso(); await this.write(file); }); }
|
|
||||||
}
|
|
||||||
export function localMemoryHash(value) { return createHash('sha256').update(value).digest('hex'); }
|
|
||||||
|
|
@ -1 +0,0 @@
|
||||||
export {};
|
|
||||||
|
|
@ -12,7 +12,7 @@
|
||||||
* it ships. Installing an entry reuses the same staged plan/commit pipeline as
|
* it ships. Installing an entry reuses the same staged plan/commit pipeline as
|
||||||
* a manual git install, pinned to the commit resolved here.
|
* a manual git install, pinned to the commit resolved here.
|
||||||
*/
|
*/
|
||||||
import { parseSkillFrontmatter } from "./skills/shared.js";
|
import { parseSkillFrontmatter } from "./skill-sync.js";
|
||||||
/** Typed failure so routes can map it to a status code. */
|
/** Typed failure so routes can map it to a status code. */
|
||||||
export class MarketError extends Error {
|
export class MarketError extends Error {
|
||||||
code;
|
code;
|
||||||
|
|
@ -60,7 +60,7 @@ export class ClaudePluginMarketplaceProvider {
|
||||||
let response;
|
let response;
|
||||||
try {
|
try {
|
||||||
response = await this.fetchImpl(url, {
|
response = await this.fetchImpl(url, {
|
||||||
headers: { accept: 'application/json, text/plain, */*', 'user-agent': 'dsh-brain-market' },
|
headers: { accept: 'application/json, text/plain, */*', 'user-agent': 'dsh-cloud-memory-market' },
|
||||||
signal: AbortSignal.timeout(this.timeoutMs()),
|
signal: AbortSignal.timeout(this.timeoutMs()),
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
|
||||||
24
lib/mcp.js
24
lib/mcp.js
|
|
@ -1,24 +0,0 @@
|
||||||
/**
|
|
||||||
* MCP bundle — the host half of the MCP management tab.
|
|
||||||
*
|
|
||||||
* In this package the MCP feature is a browser bridge, nothing more: the
|
|
||||||
* client tab talks to the host `dsh-mcp-connector` plugin over
|
|
||||||
* `/mcp-connector/api`, wrapping one JSON envelope per call, a fixed probe
|
|
||||||
* timeout and an explicit host-unavailable state. Connections, credentials
|
|
||||||
* and tool management belong to the host plugin; this bundle never stores
|
|
||||||
* them and never syncs MCP configuration to the cloud.
|
|
||||||
*/
|
|
||||||
/**
|
|
||||||
* The MCP bridge capability fragment owned by this bundle. `capabilities()`
|
|
||||||
* in routes.ts aggregates it with the rest of the build's report; the MCP
|
|
||||||
* text lives here so the bundle keeps its own surface in one place.
|
|
||||||
*/
|
|
||||||
export function mcpCapability() {
|
|
||||||
return {
|
|
||||||
bridge: 'host-plugin',
|
|
||||||
notes: [
|
|
||||||
'MCP 管理由宿主 dsh-mcp-connector 插件提供,本卡通过其公开接口读写,不另建凭据库。',
|
|
||||||
'MCP 工具可见性与会话级激活分属两层:本卡展示连接与工具缓存,会话级“选择精确工具后激活”由宿主 session-tools 负责,本卡不伪造激活。',
|
|
||||||
],
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
@ -1,164 +0,0 @@
|
||||||
import { renderJson } from "./tools.js";
|
|
||||||
export function departmentSnippet(text, limit = 600) {
|
|
||||||
return text.length <= limit ? text : text.slice(0, Math.max(0, limit - 1)) + '…';
|
|
||||||
}
|
|
||||||
function inDepartmentWorkspace(deps, exec, job) {
|
|
||||||
return deps.memory().withWorkspace(deps.workspace(exec), job);
|
|
||||||
}
|
|
||||||
function requireEnabled(deps) {
|
|
||||||
const settings = deps.settings();
|
|
||||||
if (settings.memoryEnabled === false || settings.localMemoryEnabled === false) {
|
|
||||||
throw new Error('部门功能当前已禁用。请在 /dsh-brain 页面开启本地记忆和记忆功能后再试。');
|
|
||||||
}
|
|
||||||
}
|
|
||||||
function list(value) {
|
|
||||||
if (!Array.isArray(value))
|
|
||||||
return undefined;
|
|
||||||
return value.filter((item) => typeof item === 'string').slice(0, 50);
|
|
||||||
}
|
|
||||||
function text(value) { return typeof value === 'string' ? value : undefined; }
|
|
||||||
function revision(value) { return typeof value === 'number' && Number.isFinite(value) ? Math.trunc(value) : undefined; }
|
|
||||||
export function createDepartmentTools(deps) {
|
|
||||||
const department_create = {
|
|
||||||
name: 'department_create',
|
|
||||||
description: '创建一个部门工作身份。部门拥有私有记忆空间;同名同 scope 幂等返回已有部门,不覆盖。',
|
|
||||||
parameters: {
|
|
||||||
type: 'object',
|
|
||||||
properties: {
|
|
||||||
name: { type: 'string', description: '部门名称(必填)' },
|
|
||||||
role: { type: 'string', description: '部门角色说明(可选,最多 12000 字符)' },
|
|
||||||
scope: { type: 'string', enum: ['global', 'project'], description: '部门空间范围,默认 project' },
|
|
||||||
skills: { type: 'array', items: { type: 'string' }, description: '关联技能名列表' },
|
|
||||||
allowedTools: { type: 'array', items: { type: 'string' }, description: '允许使用的工具名列表' },
|
|
||||||
readGlobal: { type: 'boolean', description: '是否允许读取全局记忆,默认 true' },
|
|
||||||
readProject: { type: 'boolean', description: '是否允许读取项目记忆,默认 true' },
|
|
||||||
},
|
|
||||||
required: ['name'],
|
|
||||||
additionalProperties: false,
|
|
||||||
},
|
|
||||||
output: { schema: { type: 'object' }, render: renderJson },
|
|
||||||
async execute(args, exec) {
|
|
||||||
requireEnabled(deps);
|
|
||||||
return inDepartmentWorkspace(deps, exec, async () => {
|
|
||||||
const name = text(args.name)?.trim() ?? '';
|
|
||||||
if (name === '')
|
|
||||||
throw new Error('部门名称不能为空。');
|
|
||||||
const input = { name, ...(text(args.role) === undefined ? {} : { role: text(args.role) }), ...(args.scope === 'global' || args.scope === 'project' ? { scope: args.scope } : {}), ...(list(args.skills) === undefined ? {} : { skills: list(args.skills) }), ...(list(args.allowedTools) === undefined ? {} : { allowedTools: list(args.allowedTools) }), ...(typeof args.readGlobal === 'boolean' ? { readGlobal: args.readGlobal } : {}), ...(typeof args.readProject === 'boolean' ? { readProject: args.readProject } : {}) };
|
|
||||||
const result = await deps.departments().create(input);
|
|
||||||
return { id: result.department.id, name: result.department.name, scope: result.department.scope, created: result.created };
|
|
||||||
});
|
|
||||||
},
|
|
||||||
};
|
|
||||||
const department_list = {
|
|
||||||
name: 'department_list',
|
|
||||||
description: '列出部门及其精简状态;role 全文不返回,按需使用部门详情接口。',
|
|
||||||
parameters: { type: 'object', properties: { scope: { type: 'string', enum: ['global', 'project'] } }, additionalProperties: false },
|
|
||||||
output: { schema: { type: 'object' }, render: renderJson },
|
|
||||||
async execute(args, exec) {
|
|
||||||
requireEnabled(deps);
|
|
||||||
return inDepartmentWorkspace(deps, exec, async () => {
|
|
||||||
const scope = args.scope === 'global' || args.scope === 'project' ? args.scope : undefined;
|
|
||||||
const rows = await deps.departments().list(scope);
|
|
||||||
return { departments: rows.map((department) => ({ id: department.id, name: department.name, scope: department.scope, active: department.active, ...(department.currentTask === undefined ? {} : { currentTask: department.currentTask }), revision: department.revision })) };
|
|
||||||
});
|
|
||||||
},
|
|
||||||
};
|
|
||||||
const department_remember = {
|
|
||||||
name: 'department_remember',
|
|
||||||
description: '向一个部门的私有记忆空间写入记忆。秘密、令牌和密钥不得写入。',
|
|
||||||
parameters: {
|
|
||||||
type: 'object',
|
|
||||||
properties: { departmentId: { type: 'string' }, content: { type: 'string' }, category: { type: 'string' }, tags: { type: 'array', items: { type: 'string' } } },
|
|
||||||
required: ['departmentId', 'content'],
|
|
||||||
additionalProperties: false,
|
|
||||||
},
|
|
||||||
output: { schema: { type: 'object' }, render: renderJson },
|
|
||||||
async execute(args, exec) {
|
|
||||||
requireEnabled(deps);
|
|
||||||
return inDepartmentWorkspace(deps, exec, async () => {
|
|
||||||
const id = text(args.departmentId)?.trim() ?? '';
|
|
||||||
const content = text(args.content)?.trim() ?? '';
|
|
||||||
if (id === '')
|
|
||||||
throw new Error('departmentId 不能为空。');
|
|
||||||
if (content === '')
|
|
||||||
throw new Error('content 不能为空。');
|
|
||||||
const result = await deps.departments().remember(id, { content, ...(text(args.category) === undefined ? {} : { category: text(args.category) }), ...(list(args.tags) === undefined ? {} : { tags: list(args.tags) }) });
|
|
||||||
return { id: result.record.id, duplicate: result.duplicate };
|
|
||||||
});
|
|
||||||
},
|
|
||||||
};
|
|
||||||
const department_recall = {
|
|
||||||
name: 'department_recall',
|
|
||||||
description: '从部门私有空间召回相关记忆,最多 5 条;返回内容为去敏后的短片段。',
|
|
||||||
parameters: {
|
|
||||||
type: 'object',
|
|
||||||
properties: { departmentId: { type: 'string' }, query: { type: 'string' }, k: { type: 'integer', minimum: 1, maximum: 5 } },
|
|
||||||
required: ['departmentId', 'query'],
|
|
||||||
additionalProperties: false,
|
|
||||||
},
|
|
||||||
output: { schema: { type: 'object' }, render: renderJson },
|
|
||||||
async execute(args, exec) {
|
|
||||||
requireEnabled(deps);
|
|
||||||
const ws = deps.workspace(exec);
|
|
||||||
return deps.memory().withWorkspace(ws, async () => {
|
|
||||||
const id = text(args.departmentId)?.trim() ?? '';
|
|
||||||
const query = text(args.query)?.trim() ?? '';
|
|
||||||
if (id === '')
|
|
||||||
throw new Error('departmentId 不能为空。');
|
|
||||||
if (query === '')
|
|
||||||
throw new Error('query 不能为空。');
|
|
||||||
const requested = revision(args.k) ?? 5;
|
|
||||||
const k = Math.max(1, Math.min(5, requested));
|
|
||||||
const hits = await deps.departments().recall(id, query, k, ws);
|
|
||||||
return { hits: hits.map((hit) => ({ id: hit.record.id, origin: hit.origin, content: departmentSnippet(hit.record.content) })) };
|
|
||||||
});
|
|
||||||
},
|
|
||||||
};
|
|
||||||
const department_checkpoint = {
|
|
||||||
name: 'department_checkpoint',
|
|
||||||
description: '更新部门当前任务或交接说明,并返回新 revision。',
|
|
||||||
parameters: {
|
|
||||||
type: 'object',
|
|
||||||
properties: { departmentId: { type: 'string' }, currentTask: { type: 'string' }, handoff: { type: 'string' }, expectedRevision: { type: 'integer' } },
|
|
||||||
required: ['departmentId'],
|
|
||||||
additionalProperties: false,
|
|
||||||
},
|
|
||||||
output: { schema: { type: 'object' }, render: renderJson },
|
|
||||||
async execute(args, exec) {
|
|
||||||
requireEnabled(deps);
|
|
||||||
return inDepartmentWorkspace(deps, exec, async () => {
|
|
||||||
const id = text(args.departmentId)?.trim() ?? '';
|
|
||||||
if (id === '')
|
|
||||||
throw new Error('departmentId 不能为空。');
|
|
||||||
const department = await deps.departments().checkpoint(id, { ...(text(args.currentTask) === undefined ? {} : { currentTask: text(args.currentTask) }), ...(text(args.handoff) === undefined ? {} : { handoff: text(args.handoff) }) }, revision(args.expectedRevision));
|
|
||||||
return { revision: department.revision, updatedAt: department.updatedAt };
|
|
||||||
});
|
|
||||||
},
|
|
||||||
};
|
|
||||||
const department_resume = {
|
|
||||||
name: 'department_resume',
|
|
||||||
description: '获取部门可复用会话引用;传入 hostSessionId 时显式绑定宿主会话。',
|
|
||||||
parameters: {
|
|
||||||
type: 'object',
|
|
||||||
properties: { departmentId: { type: 'string' }, host: { type: 'string' }, hostSessionId: { type: 'string' } },
|
|
||||||
required: ['departmentId'],
|
|
||||||
additionalProperties: false,
|
|
||||||
},
|
|
||||||
output: { schema: { type: 'object' }, render: renderJson },
|
|
||||||
async execute(args, exec) {
|
|
||||||
requireEnabled(deps);
|
|
||||||
return inDepartmentWorkspace(deps, exec, async () => {
|
|
||||||
const id = text(args.departmentId)?.trim() ?? '';
|
|
||||||
if (id === '')
|
|
||||||
throw new Error('departmentId 不能为空。');
|
|
||||||
const host = text(args.host)?.trim() || 'dsh';
|
|
||||||
const hostSessionId = text(args.hostSessionId)?.trim();
|
|
||||||
const sessionRef = hostSessionId !== undefined && hostSessionId !== ''
|
|
||||||
? await deps.departments().attachSession(id, host, hostSessionId)
|
|
||||||
: await deps.departments().resumeSession(id, host);
|
|
||||||
return { sessionRef };
|
|
||||||
});
|
|
||||||
},
|
|
||||||
};
|
|
||||||
return [department_create, department_list, department_remember, department_recall, department_checkpoint, department_resume];
|
|
||||||
}
|
|
||||||
|
|
@ -1,200 +0,0 @@
|
||||||
import { createHash } from 'node:crypto';
|
|
||||||
const PROJECT_LIST_LIMIT = 1000;
|
|
||||||
const CATEGORY_BY_SECTOR = {
|
|
||||||
semantic: 'fact',
|
|
||||||
episodic: 'context',
|
|
||||||
procedural: 'general',
|
|
||||||
emotional: 'general',
|
|
||||||
reflective: 'insight',
|
|
||||||
};
|
|
||||||
function row(value) {
|
|
||||||
if (value === null || typeof value !== 'object' || Array.isArray(value))
|
|
||||||
throw new Error('Mnemon 返回了意外的结果格式。');
|
|
||||||
return value;
|
|
||||||
}
|
|
||||||
function rows(value) {
|
|
||||||
if (!Array.isArray(value))
|
|
||||||
throw new Error('Mnemon 返回了意外的条目列表格式。');
|
|
||||||
return value.map(row);
|
|
||||||
}
|
|
||||||
function text(value) {
|
|
||||||
return typeof value === 'string' && value !== '' ? value : undefined;
|
|
||||||
}
|
|
||||||
function time(value) {
|
|
||||||
const timestamp = typeof value === 'string' ? Date.parse(value) : value;
|
|
||||||
return typeof timestamp === 'number' && Number.isFinite(timestamp) ? timestamp : undefined;
|
|
||||||
}
|
|
||||||
function rpcValue(result) {
|
|
||||||
if (!result.ok)
|
|
||||||
throw new Error(result.error.message ?? result.error.code ?? 'Mnemon 请求失败。');
|
|
||||||
return result.value;
|
|
||||||
}
|
|
||||||
function failure(status, code, message) {
|
|
||||||
return { ok: false, error: { status, code, message } };
|
|
||||||
}
|
|
||||||
function runtimeId(entry) {
|
|
||||||
const identity = JSON.stringify([entry.target, entry.created_at, entry.content]);
|
|
||||||
return 'mnemon-rt:' + createHash('sha256').update(identity).digest('hex');
|
|
||||||
}
|
|
||||||
function projectId(workspaceId, memoryBodyId, id) {
|
|
||||||
return 'mnemon-sp:' + Buffer.from(JSON.stringify([workspaceId, memoryBodyId, id])).toString('base64url');
|
|
||||||
}
|
|
||||||
function decodeProjectId(id) {
|
|
||||||
if (!/^mnemon-sp:[A-Za-z0-9_-]{1,16000}$/.test(id))
|
|
||||||
return undefined;
|
|
||||||
try {
|
|
||||||
const decoded = JSON.parse(Buffer.from(id.slice(10), 'base64url').toString('utf8'));
|
|
||||||
if (!Array.isArray(decoded) || decoded.length !== 3 || !decoded.every(value => typeof value === 'string' && value !== ''))
|
|
||||||
return undefined;
|
|
||||||
const [workspaceId, memoryBodyId, memoryId] = decoded;
|
|
||||||
if (id !== projectId(workspaceId, memoryBodyId, memoryId))
|
|
||||||
return undefined;
|
|
||||||
return { workspaceId, memoryBodyId, id: memoryId };
|
|
||||||
}
|
|
||||||
catch {
|
|
||||||
return undefined;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
function runtimeHit(entry) {
|
|
||||||
const content = text(entry.content);
|
|
||||||
if (content === undefined)
|
|
||||||
throw new Error('Mnemon Runtime 条目缺少正文。');
|
|
||||||
const created = time(entry.created_at);
|
|
||||||
const updated = time(entry.updated_at);
|
|
||||||
return {
|
|
||||||
id: runtimeId(entry), content, project_id: null,
|
|
||||||
...(created === undefined ? {} : { created_at: created }),
|
|
||||||
...(updated === undefined ? {} : { updated_at: updated }),
|
|
||||||
...(text(entry.target) === undefined ? {} : { target: entry.target }),
|
|
||||||
};
|
|
||||||
}
|
|
||||||
function projectHit(entry, workspaceId) {
|
|
||||||
const id = text(entry.id);
|
|
||||||
const memoryBodyId = text(entry.memoryBodyId);
|
|
||||||
const content = text(entry.content);
|
|
||||||
if (id === undefined || memoryBodyId === undefined || content === undefined)
|
|
||||||
throw new Error('Mnemon 项目条目缺少可读取的标识或正文。');
|
|
||||||
const created = time(entry.created_at ?? entry.createdAt);
|
|
||||||
const updated = time(entry.updated_at ?? entry.updatedAt);
|
|
||||||
return {
|
|
||||||
id: projectId(workspaceId, memoryBodyId, id), content, project_id: workspaceId,
|
|
||||||
tags: Array.isArray(entry.tags) ? entry.tags.filter((tag) => typeof tag === 'string') : [],
|
|
||||||
...(created === undefined ? {} : { created_at: created }),
|
|
||||||
...(updated === undefined ? {} : { updated_at: updated }),
|
|
||||||
...(text(entry.category) === undefined ? {} : { category: entry.category }),
|
|
||||||
};
|
|
||||||
}
|
|
||||||
function newestFirst(hits) {
|
|
||||||
return hits.sort((left, right) => (right.created_at ?? 0) - (left.created_at ?? 0) || (left.id ?? '').localeCompare(right.id ?? ''));
|
|
||||||
}
|
|
||||||
function matchingWorkspace(bridge, project) {
|
|
||||||
if (!bridge.workspaces().some(workspace => workspace.id === project))
|
|
||||||
throw new Error('找不到该 DSH 工作区,请先用 memory_projects 查找项目 ID。');
|
|
||||||
return project;
|
|
||||||
}
|
|
||||||
async function runtimeHits(bridge) {
|
|
||||||
const snapshot = row(rpcValue(await bridge.read('runtime-memory', {})));
|
|
||||||
return newestFirst(rows(snapshot.entries).map(runtimeHit));
|
|
||||||
}
|
|
||||||
async function writableSpace(bridge, workspaceId) {
|
|
||||||
const directory = row(rpcValue(await bridge.read('body-directory', { workspaceId })));
|
|
||||||
const spaces = rows(directory.items).filter(space => {
|
|
||||||
const provider = row(space.provider);
|
|
||||||
return text(space.id) !== undefined && space.active === true && space.providerEnabled !== false
|
|
||||||
&& row(provider.capabilities).remember === true;
|
|
||||||
});
|
|
||||||
const defaults = spaces.filter(space => space.mnemonDefault === true);
|
|
||||||
const candidates = defaults.length > 0 ? defaults : spaces;
|
|
||||||
const selected = candidates.length === 1 ? text(candidates[0]?.id) : undefined;
|
|
||||||
if (selected === undefined)
|
|
||||||
throw new Error('该工作区没有唯一可写的 Mnemon 记忆空间。请在 Mnemon 中配置默认空间。');
|
|
||||||
return selected;
|
|
||||||
}
|
|
||||||
/** Use the same live Mnemon sources as Brain's global and project views. */
|
|
||||||
export function createMnemonMemoryRemote(resolveBridge) {
|
|
||||||
async function invoke(operation) {
|
|
||||||
try {
|
|
||||||
const bridge = resolveBridge();
|
|
||||||
if (bridge === undefined)
|
|
||||||
return failure(503, 'mnemon_unavailable', '当前宿主没有可用的 Mnemon 服务。');
|
|
||||||
return await operation(bridge);
|
|
||||||
}
|
|
||||||
catch (error) {
|
|
||||||
return failure(502, 'mnemon_error', error instanceof Error ? error.message : String(error));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return {
|
|
||||||
search: (query, k, project) => invoke(async (bridge) => {
|
|
||||||
if (project === undefined) {
|
|
||||||
const needle = query.toLocaleLowerCase();
|
|
||||||
const matched = (await runtimeHits(bridge)).filter(hit => hit.content?.toLocaleLowerCase().includes(needle));
|
|
||||||
return { ok: true, status: 200, data: { matches: matched.slice(0, k), total: matched.length, search_mode: 'keyword' } };
|
|
||||||
}
|
|
||||||
const workspaceId = matchingWorkspace(bridge, project);
|
|
||||||
const result = row(rpcValue(await bridge.read('search', { workspaceId, query, mode: 'keyword', limit: k })));
|
|
||||||
const matches = rows(result.results).map(entry => projectHit(entry, workspaceId));
|
|
||||||
return { ok: true, status: 200, data: { matches, total: matches.length, search_mode: text(result.mode) ?? 'keyword' } };
|
|
||||||
}),
|
|
||||||
read: id => invoke(async (bridge) => {
|
|
||||||
const missing = () => failure(404, 'mnemon_memory_not_found', '没有找到该 Mnemon 记忆。');
|
|
||||||
if (/^mnemon-rt:[a-f0-9]{64}$/.test(id)) {
|
|
||||||
const matches = (await runtimeHits(bridge)).filter(hit => hit.id === id);
|
|
||||||
if (matches.length > 1)
|
|
||||||
return failure(409, 'mnemon_memory_ambiguous', '有多条 Mnemon Runtime 条目匹配此 ID。');
|
|
||||||
return matches[0] === undefined ? missing() : { ok: true, status: 200, data: matches[0] };
|
|
||||||
}
|
|
||||||
const target = decodeProjectId(id);
|
|
||||||
if (target === undefined)
|
|
||||||
return missing();
|
|
||||||
matchingWorkspace(bridge, target.workspaceId);
|
|
||||||
const result = rpcValue(await bridge.read('memory-exact', target));
|
|
||||||
if (result === null)
|
|
||||||
return missing();
|
|
||||||
const hit = projectHit(row(result), target.workspaceId);
|
|
||||||
if (hit.id !== id)
|
|
||||||
return missing();
|
|
||||||
return { ok: true, status: 200, data: hit };
|
|
||||||
}),
|
|
||||||
add: input => invoke(async (bridge) => {
|
|
||||||
const { content, operationId, project, tags, sector } = input;
|
|
||||||
if (project === undefined) {
|
|
||||||
if ((tags?.length ?? 0) !== 0 || sector !== undefined)
|
|
||||||
return failure(400, 'mnemon_runtime_metadata_unsupported', '全局 Mnemon Runtime 条目不支持标签或分类。请省略 tags 和 sector。');
|
|
||||||
const result = row(rpcValue(await bridge.append('runtime-memory', { action: 'add', target: 'memory', content, operationId })));
|
|
||||||
if (result.success !== true || text(result.added) === undefined)
|
|
||||||
throw new Error('Mnemon 没有确认保存该 Runtime 条目。');
|
|
||||||
const matches = (await runtimeHits(bridge)).filter(hit => hit.target === 'memory' && hit.content === result.added);
|
|
||||||
const id = matches.length === 1 ? matches[0]?.id : undefined;
|
|
||||||
if (id === undefined)
|
|
||||||
throw new Error('Mnemon 返回了保存回执,但 Runtime 中无法唯一定位该条目。');
|
|
||||||
return { ok: true, status: 200, data: { id, operation_id: operationId, state: 'saved' } };
|
|
||||||
}
|
|
||||||
const workspaceId = matchingWorkspace(bridge, project);
|
|
||||||
const memoryBodyId = await writableSpace(bridge, workspaceId);
|
|
||||||
const category = sector === undefined ? undefined : CATEGORY_BY_SECTOR[sector];
|
|
||||||
const result = row(rpcValue(await bridge.append('remember', { workspaceId, memoryBodyId, content, tags, category, operationId })));
|
|
||||||
const id = text(result.id);
|
|
||||||
if (id === undefined || result.memoryBodyId !== memoryBodyId || result.committed !== true) {
|
|
||||||
throw new Error('Mnemon 没有返回可验证的项目记忆保存回执。');
|
|
||||||
}
|
|
||||||
return { ok: true, status: 200, data: { id: projectId(workspaceId, memoryBodyId, id), operation_id: operationId, state: 'saved' } };
|
|
||||||
}),
|
|
||||||
list: (options = {}) => invoke(async (bridge) => {
|
|
||||||
const { offset = 0, limit = 20, project } = options;
|
|
||||||
if (project === undefined) {
|
|
||||||
const hits = await runtimeHits(bridge);
|
|
||||||
return { ok: true, status: 200, data: { items: hits.slice(offset, offset + limit), total: hits.length } };
|
|
||||||
}
|
|
||||||
const workspaceId = matchingWorkspace(bridge, project);
|
|
||||||
const result = row(rpcValue(await bridge.read('list', { workspaceId, limit: PROJECT_LIST_LIMIT })));
|
|
||||||
const hits = newestFirst(rows(result.items).map(entry => projectHit(entry, workspaceId)));
|
|
||||||
return { ok: true, status: 200, data: { items: hits.slice(offset, offset + limit), total: typeof result.total === 'number' ? result.total : hits.length } };
|
|
||||||
}),
|
|
||||||
projects: () => invoke(async (bridge) => ({
|
|
||||||
ok: true, status: 200, data: { projects: bridge.workspaces().map(({ id, name }) => ({ id, name })) },
|
|
||||||
})),
|
|
||||||
storageStatus: () => invoke(async (bridge) => ({
|
|
||||||
ok: true, status: 200, data: row(rpcValue(await bridge.read('status', {}))),
|
|
||||||
})),
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
@ -1 +0,0 @@
|
||||||
export {};
|
|
||||||
|
|
@ -1,274 +0,0 @@
|
||||||
/**
|
|
||||||
* Agent-facing memory tools — the memory bundle's tool face.
|
|
||||||
*
|
|
||||||
* The entry injects a narrow MemoryRemote adapter.
|
|
||||||
*
|
|
||||||
* These definitions are hand-written `ToolDefinition` objects rather than
|
|
||||||
* `defineTool(...)` calls: `defineTool` only compiles an authoring DSL into the
|
|
||||||
* same raw JSON Schema, and importing `@deepseek-ai/dsh-tools` at runtime would
|
|
||||||
* risk a second module instance (and a second class identity) inside a linked
|
|
||||||
* plugin.
|
|
||||||
*
|
|
||||||
* Failure contract: `execute` throws and the registry turns that into
|
|
||||||
* `isError: true`.
|
|
||||||
*/
|
|
||||||
import { randomUUID } from 'node:crypto';
|
|
||||||
import { describeError } from "../api.js";
|
|
||||||
/** Sectors the service accepts for `metadata.primary_sector`. */
|
|
||||||
export const SECTORS = ['semantic', 'episodic', 'procedural', 'emotional', 'reflective'];
|
|
||||||
/** Trim a memory body down to a display-sized snippet. */
|
|
||||||
function snippet(text, limit = 600) {
|
|
||||||
if (typeof text !== 'string')
|
|
||||||
return '';
|
|
||||||
if (text.length <= limit)
|
|
||||||
return text;
|
|
||||||
return `${text.slice(0, limit)}…`;
|
|
||||||
}
|
|
||||||
/** Project one hit into the compact shape returned to the model. */
|
|
||||||
function toHitView(hit) {
|
|
||||||
return {
|
|
||||||
id: hit.id,
|
|
||||||
content: snippet(hit.content),
|
|
||||||
tags: hit.tags ?? [],
|
|
||||||
project_id: hit.project_id ?? null,
|
|
||||||
sector: hit.primary_sector ?? null,
|
|
||||||
revision: hit.revision ?? null,
|
|
||||||
created_at: hit.created_at ?? null,
|
|
||||||
...(typeof hit.category === 'string' ? { category: hit.category } : {}),
|
|
||||||
...(typeof hit.target === 'string' ? { target: hit.target } : {}),
|
|
||||||
};
|
|
||||||
}
|
|
||||||
/** Render any tool value as one JSON text block. */
|
|
||||||
export function renderJson(_args, value) {
|
|
||||||
const text = typeof value === 'string' ? value : JSON.stringify(value, null, 2);
|
|
||||||
return [{ type: 'text', text }];
|
|
||||||
}
|
|
||||||
/** Assert the memory scope is usable, or throw a message the model can act on. */
|
|
||||||
export function requireMemoryToken(deps) {
|
|
||||||
if (!deps.settings().enabled) {
|
|
||||||
throw new Error('记忆插件当前已禁用(enabled=false)。请在 /dsh-brain 页面开启后再试。');
|
|
||||||
}
|
|
||||||
// Local-first mode needs no credential and wins unless cloud mode was
|
|
||||||
// explicitly selected and configured. If local memory is off, only a
|
|
||||||
// configured cloud credential may select the cloud adapter.
|
|
||||||
if (deps.localMemory?.() === true)
|
|
||||||
return '';
|
|
||||||
const token = deps.memoryToken();
|
|
||||||
if (token !== '')
|
|
||||||
return token;
|
|
||||||
throw new Error('记忆功能未启用或未配置令牌。请在 /dsh-brain 页面开启本地记忆,或填入 mem_… / cmt_… 记忆令牌。');
|
|
||||||
}
|
|
||||||
function requireMemoryEnabled(deps) {
|
|
||||||
if (!deps.settings().enabled)
|
|
||||||
throw new Error('记忆工具当前已禁用。请在 /dsh-brain 页面开启后再试。');
|
|
||||||
}
|
|
||||||
function projectId(value) {
|
|
||||||
if (value === undefined)
|
|
||||||
return undefined;
|
|
||||||
if (typeof value !== 'string' || value.trim() === '')
|
|
||||||
throw new Error('project_id 必须是 memory_projects 返回的工作区 ID。');
|
|
||||||
return value.trim();
|
|
||||||
}
|
|
||||||
/** Search stored memories by keyword. */
|
|
||||||
function searchTool(deps) {
|
|
||||||
return {
|
|
||||||
name: 'memory_search',
|
|
||||||
description: '按关键词检索 Mnemon 记忆。默认检索全局 Runtime,指定 project_id 时检索对应 DSH 工作区的记忆空间。' +
|
|
||||||
'需要全文时用 memory_read 读取返回的 id。',
|
|
||||||
parameters: {
|
|
||||||
type: 'object',
|
|
||||||
properties: {
|
|
||||||
query: { type: 'string', description: '检索关键词或短语(必填)。' },
|
|
||||||
k: { type: 'integer', description: '最多返回条数,默认取配置值(1..1000)。' },
|
|
||||||
project_id: { type: 'string', description: '可选:memory_projects 返回的 DSH 工作区 ID。省略时检索全局。' },
|
|
||||||
},
|
|
||||||
required: ['query'],
|
|
||||||
additionalProperties: false,
|
|
||||||
},
|
|
||||||
output: {
|
|
||||||
schema: {
|
|
||||||
type: 'object',
|
|
||||||
properties: {
|
|
||||||
query: { type: 'string' },
|
|
||||||
total: { type: 'number' },
|
|
||||||
search_mode: { type: 'string' },
|
|
||||||
matches: { type: 'array', items: { type: 'object' } },
|
|
||||||
},
|
|
||||||
required: ['query', 'matches'],
|
|
||||||
additionalProperties: true,
|
|
||||||
},
|
|
||||||
render: renderJson,
|
|
||||||
},
|
|
||||||
async execute(args) {
|
|
||||||
requireMemoryEnabled(deps);
|
|
||||||
const query = typeof args.query === 'string' ? args.query.trim() : '';
|
|
||||||
if (query === '')
|
|
||||||
throw new Error('query 不能为空。');
|
|
||||||
const requested = typeof args.k === 'number' && Number.isFinite(args.k) ? Math.trunc(args.k) : deps.settings().defaultK;
|
|
||||||
const k = Math.min(1000, Math.max(1, requested));
|
|
||||||
const project = projectId(args.project_id);
|
|
||||||
const result = await deps.remote().search(query, k, project);
|
|
||||||
if (!result.ok)
|
|
||||||
throw new Error(`检索失败:${describeError(result.error)}`);
|
|
||||||
const matches = result.data.matches;
|
|
||||||
return {
|
|
||||||
query,
|
|
||||||
total: result.data.total ?? matches.length,
|
|
||||||
search_mode: result.data.search_mode ?? 'keyword',
|
|
||||||
matches: matches.map(toHitView),
|
|
||||||
};
|
|
||||||
},
|
|
||||||
};
|
|
||||||
}
|
|
||||||
/** Read one memory by id. */
|
|
||||||
function readTool(deps) {
|
|
||||||
return {
|
|
||||||
name: 'memory_read',
|
|
||||||
description: '按 memory_search、memory_list 或 memory_add 返回的 id 读取 Mnemon 条目全文及其可用元数据。',
|
|
||||||
parameters: {
|
|
||||||
type: 'object',
|
|
||||||
properties: {
|
|
||||||
id: { type: 'string', description: '记忆条目 id(必填)。' },
|
|
||||||
},
|
|
||||||
required: ['id'],
|
|
||||||
additionalProperties: false,
|
|
||||||
},
|
|
||||||
output: {
|
|
||||||
schema: { type: 'object', properties: { id: { type: 'string' }, content: { type: 'string' } }, required: ['id'], additionalProperties: true },
|
|
||||||
render: renderJson,
|
|
||||||
},
|
|
||||||
async execute(args) {
|
|
||||||
requireMemoryEnabled(deps);
|
|
||||||
const id = typeof args.id === 'string' ? args.id.trim() : '';
|
|
||||||
if (id === '')
|
|
||||||
throw new Error('id 不能为空。');
|
|
||||||
const result = await deps.remote().read(id);
|
|
||||||
if (!result.ok) {
|
|
||||||
if (result.error.status === 404)
|
|
||||||
throw new Error(`没有找到 id=${id} 的记忆(可能已删除)。`);
|
|
||||||
throw new Error(`读取失败:${describeError(result.error)}`);
|
|
||||||
}
|
|
||||||
return result.data;
|
|
||||||
},
|
|
||||||
};
|
|
||||||
}
|
|
||||||
/** Store one new memory. */
|
|
||||||
function addTool(deps) {
|
|
||||||
return {
|
|
||||||
name: 'memory_add',
|
|
||||||
description: '追加一条 Mnemon 记忆。默认写入全局 Runtime,指定 project_id 时写入对应 DSH 工作区的记忆空间。正文上限 7000 字节。' +
|
|
||||||
'不要保存密钥、令牌或完整源码。重试同一次写入请复用 operation_id。',
|
|
||||||
parameters: {
|
|
||||||
type: 'object',
|
|
||||||
properties: {
|
|
||||||
content: { type: 'string', description: '要长期保存的正文(≤7000 字节)。' },
|
|
||||||
tags: { type: 'array', items: { type: 'string' }, description: '项目条目可选标签,最多 30 个。全局 Runtime 不支持标签。' },
|
|
||||||
project_id: { type: 'string', description: '可选:memory_projects 返回的 DSH 工作区 ID。省略时写入全局。' },
|
|
||||||
sector: { type: 'string', enum: [...SECTORS], description: '项目条目可选分类。全局 Runtime 不支持分类。' },
|
|
||||||
operation_id: { type: 'string', description: '可选:幂等键(uuid);省略时自动生成。重试同一次写入时请复用同一个值。' },
|
|
||||||
},
|
|
||||||
required: ['content'],
|
|
||||||
additionalProperties: false,
|
|
||||||
},
|
|
||||||
output: {
|
|
||||||
schema: {
|
|
||||||
type: 'object',
|
|
||||||
properties: {
|
|
||||||
id: { type: 'string' },
|
|
||||||
revision: { type: 'number' },
|
|
||||||
remote_saved: { type: 'boolean' },
|
|
||||||
state: { type: 'string' },
|
|
||||||
operation_id: { type: 'string' },
|
|
||||||
},
|
|
||||||
required: ['id'],
|
|
||||||
additionalProperties: true,
|
|
||||||
},
|
|
||||||
render: renderJson,
|
|
||||||
},
|
|
||||||
async execute(args) {
|
|
||||||
requireMemoryEnabled(deps);
|
|
||||||
const content = typeof args.content === 'string' ? args.content : '';
|
|
||||||
if (content.trim() === '')
|
|
||||||
throw new Error('content 不能为空。');
|
|
||||||
const bytes = Buffer.byteLength(content, 'utf8');
|
|
||||||
if (bytes > 7000)
|
|
||||||
throw new Error(`content 过大:${bytes} 字节,上限 7000 字节。`);
|
|
||||||
const rawTags = Array.isArray(args.tags) ? args.tags : [];
|
|
||||||
const tags = rawTags.filter((tag) => typeof tag === 'string' && tag !== '').slice(0, 30);
|
|
||||||
const project = projectId(args.project_id);
|
|
||||||
const sector = typeof args.sector === 'string' && SECTORS.includes(args.sector) ? args.sector : undefined;
|
|
||||||
const candidate = typeof args.operation_id === 'string' ? args.operation_id.trim() : '';
|
|
||||||
if (args.operation_id !== undefined && !/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(candidate)) {
|
|
||||||
throw new Error('operation_id 必须是 UUID。');
|
|
||||||
}
|
|
||||||
const operationId = candidate.toLowerCase() || randomUUID();
|
|
||||||
const result = await deps.remote().add({ content, tags, project, sector, operationId });
|
|
||||||
if (!result.ok) {
|
|
||||||
throw new Error(`写入失败(operation_id=${operationId}):${describeError(result.error)}`);
|
|
||||||
}
|
|
||||||
return {
|
|
||||||
id: result.data.id,
|
|
||||||
...(result.data.revision === undefined ? {} : { revision: result.data.revision }),
|
|
||||||
...(result.data.remote_saved === undefined ? {} : { remote_saved: result.data.remote_saved }),
|
|
||||||
...(result.data.state === undefined ? {} : { state: result.data.state }),
|
|
||||||
operation_id: result.data.operation_id ?? operationId,
|
|
||||||
};
|
|
||||||
},
|
|
||||||
};
|
|
||||||
}
|
|
||||||
/** List recent memories. */
|
|
||||||
function listTool(deps) {
|
|
||||||
return {
|
|
||||||
name: 'memory_list',
|
|
||||||
description: '按时间倒序列出 Mnemon 记忆。省略 project_id 时列出全局 Runtime 条目。',
|
|
||||||
parameters: {
|
|
||||||
type: 'object',
|
|
||||||
properties: {
|
|
||||||
limit: { type: 'integer', description: '返回条数,默认 20,上限 100。' },
|
|
||||||
offset: { type: 'integer', description: '跳过条数,默认 0。' },
|
|
||||||
project_id: { type: 'string', description: '可选:memory_projects 返回的 DSH 工作区 ID。' },
|
|
||||||
},
|
|
||||||
additionalProperties: false,
|
|
||||||
},
|
|
||||||
output: {
|
|
||||||
schema: { type: 'object', properties: { total: { type: 'number' }, items: { type: 'array', items: { type: 'object' } } }, required: ['items'], additionalProperties: true },
|
|
||||||
render: renderJson,
|
|
||||||
},
|
|
||||||
async execute(args) {
|
|
||||||
requireMemoryEnabled(deps);
|
|
||||||
const rawLimit = typeof args.limit === 'number' && Number.isFinite(args.limit) ? Math.trunc(args.limit) : 20;
|
|
||||||
const limit = Math.min(100, Math.max(1, rawLimit));
|
|
||||||
const rawOffset = typeof args.offset === 'number' && Number.isFinite(args.offset) ? Math.trunc(args.offset) : 0;
|
|
||||||
const offset = Math.max(0, rawOffset);
|
|
||||||
const project = projectId(args.project_id);
|
|
||||||
const result = await deps.remote().list({ limit, offset, project });
|
|
||||||
if (!result.ok)
|
|
||||||
throw new Error(`列表读取失败:${describeError(result.error)}`);
|
|
||||||
const items = result.data.items;
|
|
||||||
return { total: result.data.total ?? items.length, items: items.map(toHitView) };
|
|
||||||
},
|
|
||||||
};
|
|
||||||
}
|
|
||||||
/** List projects known to the account. */
|
|
||||||
function projectsTool(deps) {
|
|
||||||
return {
|
|
||||||
name: 'memory_projects',
|
|
||||||
description: '列出 DSH 注册的工作区 ID 和名称。将返回的 id 用作其他记忆工具的 project_id。',
|
|
||||||
parameters: { type: 'object', properties: {}, additionalProperties: false },
|
|
||||||
output: {
|
|
||||||
schema: { type: 'object', properties: { projects: { type: 'array', items: { type: 'object' } } }, required: ['projects'], additionalProperties: true },
|
|
||||||
render: renderJson,
|
|
||||||
},
|
|
||||||
async execute(_args) {
|
|
||||||
requireMemoryEnabled(deps);
|
|
||||||
const result = await deps.remote().projects();
|
|
||||||
if (!result.ok)
|
|
||||||
throw new Error(`项目列表读取失败:${describeError(result.error)}`);
|
|
||||||
return { projects: result.data.projects };
|
|
||||||
},
|
|
||||||
};
|
|
||||||
}
|
|
||||||
/** Build every memory tool for one plugin instance. */
|
|
||||||
export function createMemoryTools(deps) {
|
|
||||||
return [searchTool(deps), readTool(deps), addTool(deps), listTool(deps), projectsTool(deps)];
|
|
||||||
}
|
|
||||||
|
|
@ -1,23 +0,0 @@
|
||||||
# dsh-brain Mnemon fork
|
|
||||||
|
|
||||||
- Display name: Dsh Brain Mnemon
|
|
||||||
- Fork package name: dsh-brain-mnemon
|
|
||||||
- Fork version: 0.5.54-dsh.1
|
|
||||||
- Upstream: https://github.com/omdsh-dev/dsh-mnemon.git
|
|
||||||
- Upstream revision: 8b650ab5ef33522e03887b250b13336593daa26f
|
|
||||||
- Upstream version: 0.5.54
|
|
||||||
- License: MIT (see LICENSE)
|
|
||||||
|
|
||||||
This directory is a source snapshot, not a git submodule. The tree keeps the upstream
|
|
||||||
MIT license, copyright notice and third-party notices. Package names, import
|
|
||||||
specifiers, runtime schema ids, bundle entry ids and the repair-session bin name
|
|
||||||
are rewritten from dsh-mnemon to dsh-brain-mnemon so the fork can coexist with
|
|
||||||
the upstream plugin without registering the same package or entry ids.
|
|
||||||
|
|
||||||
Regenerate with:
|
|
||||||
|
|
||||||
node scripts/fork-mnemon.mjs --source <upstream-checkout> --target vendor/dsh-mnemon --force
|
|
||||||
|
|
||||||
Update procedure: check out the desired upstream revision, run the command above,
|
|
||||||
then bump PINNED_REVISION / PINNED_VERSION in scripts/fork-mnemon.mjs.
|
|
||||||
Review the diff before committing; do not rewrite upstream docs or license files.
|
|
||||||
|
|
@ -1,21 +0,0 @@
|
||||||
MIT License
|
|
||||||
|
|
||||||
Copyright (c) 2026 dsh-external contributors
|
|
||||||
|
|
||||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
||||||
of this software and associated documentation files (the "Software"), to deal
|
|
||||||
in the Software without restriction, including without limitation the rights
|
|
||||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
||||||
copies of the Software, and to permit persons to whom the Software is
|
|
||||||
furnished to do so, subject to the following conditions:
|
|
||||||
|
|
||||||
The above copyright notice and this permission notice shall be included in all
|
|
||||||
copies or substantial portions of the Software.
|
|
||||||
|
|
||||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
||||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
||||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
||||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
||||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
||||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
||||||
SOFTWARE.
|
|
||||||
|
|
@ -1,7 +0,0 @@
|
||||||
# Third-party notices
|
|
||||||
|
|
||||||
`dsh-mnemon` is licensed under the MIT License. Its provider adapters are original TypeScript integrations adapted to DSH's contracts and verified against the relevant public API or CLI behavior. This package does not bundle provider SDKs or provider services.
|
|
||||||
|
|
||||||
Honcho's open-source server is licensed under AGPL-3.0. dsh-mnemon does not copy or bundle that server; its Honcho adapter communicates with a separately operated v3 HTTP API. Other external providers and hosted services—including OpenViking, Mem0, Hindsight, Holographic, RetainDB, ByteRover, and Supermemory—remain separate products governed by their own licenses and service terms.
|
|
||||||
|
|
||||||
Provider marks displayed by the Web UI are sourced from each provider's official website or source repository and bundled solely to identify the configured integration. Holographic is a built-in provider without an independent brand asset, so the UI uses its canonical mirror motif. Names, marks, and trademarks belong to their respective owners. Inclusion identifies interoperability only and does not imply endorsement.
|
|
||||||
|
|
@ -1,803 +0,0 @@
|
||||||
#!/usr/bin/env node
|
|
||||||
import { createHash } from 'node:crypto'
|
|
||||||
import { createReadStream, realpathSync } from 'node:fs'
|
|
||||||
import { link, mkdtemp, open, rm } from 'node:fs/promises'
|
|
||||||
import { dirname, join, resolve } from 'node:path'
|
|
||||||
import { fileURLToPath } from 'node:url'
|
|
||||||
import { isDeepStrictEqual } from 'node:util'
|
|
||||||
import * as zlib from 'node:zlib'
|
|
||||||
|
|
||||||
const maximumBytes = 128 * 1024 * 1024
|
|
||||||
const summaries = {
|
|
||||||
recall: ['Memory View snapshot', 'Runtime memory snapshot'],
|
|
||||||
instructions: ['Optional memory recall and remember reminder'],
|
|
||||||
}
|
|
||||||
const sha256 = value => createHash('sha256').update(value).digest('hex')
|
|
||||||
const record = value => value !== null && typeof value === 'object' && !Array.isArray(value)
|
|
||||||
const nonempty = value => typeof value === 'string' && value.length > 0
|
|
||||||
const integer = value => Number.isSafeInteger(value) && !Object.is(value, -0)
|
|
||||||
const count = value => integer(value) && value >= 0
|
|
||||||
const exactKeys = (value, required, optional = []) => record(value) && required.every(key => Object.hasOwn(value, key)) &&
|
|
||||||
Object.keys(value).every(key => required.includes(key) || optional.includes(key))
|
|
||||||
|
|
||||||
function supportedDescriptorV2(value) {
|
|
||||||
if (!record(value) || value.version !== 2 || !nonempty(value.provider)) return false
|
|
||||||
const base = ['version', 'mode', 'provider', 'label']
|
|
||||||
if (value.mode === 'one-shot') return Object.keys(value).every(key => base.includes(key)) &&
|
|
||||||
(!Object.hasOwn(value, 'label') || typeof value.label === 'string')
|
|
||||||
if (value.mode !== 'continuable' || !nonempty(value.label)) return false
|
|
||||||
if (!Object.keys(value).every(key => [...base, 'agentProvider', 'agentModel', 'persona', 'toolFilter'].includes(key))) return false
|
|
||||||
for (const key of ['agentProvider', 'agentModel', 'persona']) if (Object.hasOwn(value, key) && !nonempty(value[key])) return false
|
|
||||||
if (Object.hasOwn(value, 'agentProvider') !== Object.hasOwn(value, 'agentModel')) return false
|
|
||||||
if (!Object.hasOwn(value, 'toolFilter')) return true
|
|
||||||
const filter = value.toolFilter
|
|
||||||
return record(filter) && Object.keys(filter).length > 0 && Object.keys(filter).every(key =>
|
|
||||||
['allow', 'deny'].includes(key) && Array.isArray(filter[key]) && filter[key].every(nonempty))
|
|
||||||
}
|
|
||||||
|
|
||||||
function supportedPackedToolRun(row, placeholdersOnly = true) {
|
|
||||||
if (!exactKeys(row, ['type', 'seq0', 'time0', 'data']) || !count(row.seq0) || !integer(row.time0)) return false
|
|
||||||
const data = row.data
|
|
||||||
if (!exactKeys(data, ['turn', 'step', 'index', 'id', 'dt', 'args'], ['name']) || typeof data.id !== 'string' || (placeholdersOnly && data.id !== '' && data.name !== '' && data.name !== null) ||
|
|
||||||
(Object.hasOwn(data, 'name') && data.name !== null && typeof data.name !== 'string')) return false
|
|
||||||
if (![data.turn, data.step, data.index].every(count) || !Array.isArray(data.args) || data.args.length === 0 ||
|
|
||||||
!data.args.every(value => typeof value === 'string') || !Array.isArray(data.dt) || data.dt.length !== data.args.length - 1 ||
|
|
||||||
data.args.length - 1 > Number.MAX_SAFE_INTEGER - row.seq0) return false
|
|
||||||
let time = row.time0
|
|
||||||
return data.dt.every(gap => integer(gap) && integer(time += gap))
|
|
||||||
}
|
|
||||||
|
|
||||||
const rawChunkEnvelope = row => exactKeys(row, ['type', 'seq', 'time', 'data'], ['ignorable']) && count(row.seq) && integer(row.time) &&
|
|
||||||
(!Object.hasOwn(row, 'ignorable') || row.ignorable === true) && exactKeys(row.data, ['turn', 'step', 'chunk']) && [row.data.turn, row.data.step].every(count)
|
|
||||||
const surfaceEnvelope = row => exactKeys(row, ['type', 'seq', 'time', 'data'], ['surfaceOp', 'sourceEventSeqs', 'ignorable']) && count(row.seq) && integer(row.time) &&
|
|
||||||
(!Object.hasOwn(row, 'ignorable') || row.ignorable === true)
|
|
||||||
const messageShape = value => exactKeys(value, ['role', 'id', 'source', 'content']) && nonempty(value.id) && Array.isArray(value.content)
|
|
||||||
const toolBlockShape = value => exactKeys(value, ['type', 'id', 'name', 'arguments']) && value.type === 'tool-call' && typeof value.id === 'string' && nonempty(value.name) && typeof value.arguments === 'string'
|
|
||||||
|
|
||||||
function supportedPackedTextRun(row) {
|
|
||||||
const data = row.data
|
|
||||||
return exactKeys(data, ['turn', 'step', 'index', 'dt', 'texts']) && supportedPackedToolRun({ ...row,
|
|
||||||
data: { turn: data.turn, step: data.step, index: data.index, id: 'unchanged-text-run', dt: data.dt, args: data.texts } }, false)
|
|
||||||
}
|
|
||||||
|
|
||||||
function supportedNullToolDelta(row) {
|
|
||||||
if (!rawChunkEnvelope(row)) return false
|
|
||||||
const chunk = row.data.chunk
|
|
||||||
return exactKeys(chunk, ['type', 'index', 'id', 'name', 'argumentsDelta']) && chunk.type === 'tool-call-delta' &&
|
|
||||||
chunk.name === null && count(chunk.index) && typeof chunk.id === 'string' && typeof chunk.argumentsDelta === 'string'
|
|
||||||
}
|
|
||||||
|
|
||||||
function recoverRecordedToolIdentities(entries) {
|
|
||||||
const rawPatches = new Map()
|
|
||||||
const packedIds = new Map()
|
|
||||||
const refusals = { occurrences: 0, samples: [] }
|
|
||||||
let chains = 0
|
|
||||||
let fields = 0
|
|
||||||
const emptyBlock = block => block?.type === 'tool-call' && block.id === '' || block?.type === 'tool-result' && block.toolCallId === ''
|
|
||||||
const emptyDurable = row => row.type === 'tool/call' && row.data?.callId === '' ||
|
|
||||||
row.type === 'assistant/chunk' && row.data?.chunk?.type === 'block-end' && emptyBlock(row.data.chunk.block) ||
|
|
||||||
['assistant/message', 'tool/result'].includes(row.type) && (row.data?.message?.content?.some?.(emptyBlock) || row.data?.message?.source?.callId === '')
|
|
||||||
const result = () => ({ rawPatches, packedIds, chains, fields, refusals })
|
|
||||||
if (!entries.some(entry => emptyDurable(entry.row))) return result()
|
|
||||||
const require = (condition, reason) => { if (!condition) throw reason }
|
|
||||||
const refuse = (entry, reason) => {
|
|
||||||
refusals.occurrences++
|
|
||||||
if (refusals.samples.length < 10) refusals.samples.push({ line: entry.index + 1, ...(count(entry.row.seq) ? { seq: entry.row.seq } : {}), reason })
|
|
||||||
}
|
|
||||||
const logical = []
|
|
||||||
let turn, step
|
|
||||||
try {
|
|
||||||
for (const entry of entries.slice(1)) {
|
|
||||||
const row = entry.row
|
|
||||||
objectMembers(entry.line, 0)
|
|
||||||
if (row.type === 'turn/start') turn = row.data?.turn
|
|
||||||
if (row.type === 'step/start') { turn = row.data?.turn; step = row.data?.step }
|
|
||||||
entry.scope = { turn: row.data?.turn ?? turn, step: row.data?.step ?? step }
|
|
||||||
if (['tool-call-chunks', 'text-chunks', 'reasoning-chunks'].includes(row.type)) {
|
|
||||||
const tool = row.type === 'tool-call-chunks'
|
|
||||||
require(tool ? supportedPackedToolRun(row, false) : supportedPackedTextRun(row), 'A packed source has unsupported fields or coordinates.')
|
|
||||||
const fragments = tool ? row.data.args : row.data.texts
|
|
||||||
let time = row.time0
|
|
||||||
for (let offset = 0; offset < fragments.length; offset++) {
|
|
||||||
if (offset) time += row.data.dt[offset - 1]
|
|
||||||
require(logical.length < maximumBytes / 128, 'The identity proof exceeds its bounded event count.')
|
|
||||||
logical.push({ entry, offset, row: { type: 'assistant/chunk', seq: row.seq0 + offset, time,
|
|
||||||
data: { turn: row.data.turn, step: row.data.step, chunk: tool ? { type: 'tool-call-delta', index: row.data.index, id: row.data.id,
|
|
||||||
...(Object.hasOwn(row.data, 'name') ? { name: row.data.name } : {}), argumentsDelta: fragments[offset] }
|
|
||||||
: { type: row.type === 'text-chunks' ? 'text-delta' : 'reasoning-delta', index: row.data.index, text: fragments[offset] } } } })
|
|
||||||
}
|
|
||||||
} else logical.push({ entry, row })
|
|
||||||
if (row.type === 'step/end') step = undefined
|
|
||||||
if (row.type === 'turn/end') { turn = undefined; step = undefined }
|
|
||||||
}
|
|
||||||
require(logical.every((value, index) => value.row.seq === index && integer(value.row.time)), 'Logical events must have unique complete sequence coordinates and safe times.')
|
|
||||||
} catch (error) {
|
|
||||||
if (typeof error !== 'string') throw error
|
|
||||||
refuse(entries.find(entry => emptyDurable(entry.row)), error)
|
|
||||||
return result()
|
|
||||||
}
|
|
||||||
const sourceSeqs = (row, nonempty = true) => {
|
|
||||||
const values = row.sourceEventSeqs
|
|
||||||
require(Array.isArray(values), 'Tool history needs explicit, valid assistant chunk provenance.')
|
|
||||||
const selected = new Set()
|
|
||||||
const hasRanges = values.some(Array.isArray)
|
|
||||||
let previous = -1
|
|
||||||
for (const member of values) {
|
|
||||||
const range = Array.isArray(member)
|
|
||||||
require(!range || member.length === 2, 'A provenance range must contain exactly two coordinates.')
|
|
||||||
const start = range ? member[0] : member
|
|
||||||
const end = range ? member[1] : member
|
|
||||||
require(count(start) && count(end) && start <= end && end < row.seq && end - start < logical.length - selected.size,
|
|
||||||
'Provenance contains an unsafe, missing or excessive source range.')
|
|
||||||
require((!hasRanges && row.type !== 'assistant/message') || start > previous, 'Chunk provenance is not one complete ordered attempt.')
|
|
||||||
for (let seq = start; seq <= end; seq++) {
|
|
||||||
require(!selected.has(seq), 'Provenance contains duplicate or overlapping source coordinates.')
|
|
||||||
selected.add(seq)
|
|
||||||
}
|
|
||||||
previous = end
|
|
||||||
}
|
|
||||||
require(!nonempty || selected.size > 0, 'A completed tool stream needs nonempty chunk provenance.')
|
|
||||||
return [...selected].sort((left, right) => left - right)
|
|
||||||
}
|
|
||||||
const sameStep = (left, right) => left?.turn === right?.turn && left?.step === right?.step
|
|
||||||
const messages = entries.filter(entry => entry.row.type === 'assistant/message')
|
|
||||||
for (const assistant of messages) {
|
|
||||||
const row = assistant.row
|
|
||||||
const data = row.data
|
|
||||||
const content = data?.message?.content
|
|
||||||
if (!Array.isArray(content) || !content.some(block => block?.type === 'tool-call') ||
|
|
||||||
!entries.some(entry => sameStep(entry.scope, data) && emptyDurable(entry.row))) continue
|
|
||||||
try {
|
|
||||||
require(surfaceEnvelope(row) && row.surfaceOp === 'append' && exactKeys(data, ['turn', 'step', 'message'], ['usage']) && count(data.turn) && count(data.step) &&
|
|
||||||
messageShape(data.message) && data.message.role === 'assistant' && exactKeys(data.message.source, ['kind', 'provider', 'model']) &&
|
|
||||||
data.message.source.kind === 'model' && data.message.source.provider === 'deepseek-official' && nonempty(data.message.source.model),
|
|
||||||
'Only the uninterrupted recorded DeepSeek append-message shape without owner replay state is supported.')
|
|
||||||
const sources = sourceSeqs(row)
|
|
||||||
const selected = new Set(sources)
|
|
||||||
const stream = sources.map(seq => logical[seq])
|
|
||||||
require(stream.every(value => value?.row.type === 'assistant/chunk' && sameStep(value.row.data, data)), 'Chunk provenance cites another event, turn or step.')
|
|
||||||
require(logical.slice(sources[0], sources.at(-1) + 1).every(value => value.row.type !== 'assistant/chunk' || !sameStep(value.row.data, data) || selected.has(value.row.seq)),
|
|
||||||
'Chunk provenance omits a delta inside this stream attempt.')
|
|
||||||
for (const other of messages) if (other !== assistant && Object.hasOwn(other.row, 'sourceEventSeqs')) {
|
|
||||||
require(!sourceSeqs(other.row, false).some(seq => selected.has(seq)), 'Two assistant messages share source chunks.')
|
|
||||||
}
|
|
||||||
const blocks = new Map()
|
|
||||||
let finished = false
|
|
||||||
let usage
|
|
||||||
for (const value of stream) {
|
|
||||||
const current = value.row
|
|
||||||
const chunk = current.data.chunk
|
|
||||||
require(rawChunkEnvelope(current) && record(chunk) && !finished, 'The stream has unsupported fields or chunks after finish.')
|
|
||||||
assertUniqueJson(value.entry.line, value.entry.row)
|
|
||||||
if (chunk.type === 'usage') {
|
|
||||||
require(exactKeys(chunk, ['type', 'usage']) && record(chunk.usage), 'An unrecognized usage chunk prevents identity recovery.')
|
|
||||||
usage = chunk.usage
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
if (chunk.type === 'finish') {
|
|
||||||
require(exactKeys(chunk, ['type', 'reason']) && exactKeys(chunk.reason, ['kind']) && chunk.reason.kind === 'tool-calls', 'The tool stream is interrupted, truncated or has owner replay state.')
|
|
||||||
finished = true
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
require(count(chunk.index), 'A stream block index is unsafe.')
|
|
||||||
let block = blocks.get(chunk.index)
|
|
||||||
if (chunk.type === 'block-start') {
|
|
||||||
require(exactKeys(chunk, ['type', 'index', 'blockType']) && ['text', 'reasoning', 'tool-call'].includes(chunk.blockType) && !block,
|
|
||||||
'A block start is repeated or unsupported.')
|
|
||||||
blocks.set(chunk.index, { type: chunk.blockType, started: true, text: '', arguments: '', deltas: [] })
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
const type = chunk.type === 'text-delta' ? 'text' : chunk.type === 'reasoning-delta' ? 'reasoning' : chunk.type === 'tool-call-delta' ? 'tool-call' : chunk.block?.type
|
|
||||||
require(['text', 'reasoning', 'tool-call'].includes(type), 'A stream chunk has an unsupported block type.')
|
|
||||||
if (!block) {
|
|
||||||
require(type !== 'tool-call', 'A tool delta or end is missing its block start.')
|
|
||||||
block = { type, text: '', arguments: '', deltas: [] }
|
|
||||||
blocks.set(chunk.index, block)
|
|
||||||
}
|
|
||||||
require(block.type === type && !block.end, 'A block changes type, repeats its end or receives a late delta.')
|
|
||||||
if (chunk.type === 'block-end') {
|
|
||||||
require(exactKeys(chunk, ['type', 'index', 'block']) && record(chunk.block), 'A block end has unsupported fields.')
|
|
||||||
block.end = value
|
|
||||||
block.content = chunk.block
|
|
||||||
if (type === 'tool-call') require(toolBlockShape(chunk.block) &&
|
|
||||||
chunk.block.name === block.name && chunk.block.arguments === block.arguments, 'The final tool name or arguments disagree with its deltas.')
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
if (type === 'tool-call') {
|
|
||||||
require(exactKeys(chunk, ['type', 'index', 'id', 'argumentsDelta'], ['name']) && typeof chunk.id === 'string' && typeof chunk.argumentsDelta === 'string' &&
|
|
||||||
(!Object.hasOwn(chunk, 'name') || chunk.name === null || typeof chunk.name === 'string'), 'A tool delta has unsupported identity or argument fields.')
|
|
||||||
if (chunk.name) block.name = chunk.name
|
|
||||||
block.arguments += chunk.argumentsDelta
|
|
||||||
block.deltas.push(value)
|
|
||||||
} else {
|
|
||||||
require(exactKeys(chunk, ['type', 'index', 'text']) && typeof chunk.text === 'string', 'A text or reasoning delta has unsupported fields.')
|
|
||||||
block.text += chunk.text
|
|
||||||
}
|
|
||||||
}
|
|
||||||
require(finished && blocks.size === content.length, 'The completed stream and assistant block list do not match.')
|
|
||||||
require(isDeepStrictEqual(usage, data.usage), 'The completed stream and assistant usage do not match.')
|
|
||||||
const ordered = [...blocks.values()]
|
|
||||||
const advertised = messages.filter(entry => sameStep(entry.row.data, data)).flatMap(entry => entry.row.data?.message?.content ?? []).filter(block => block?.type === 'tool-call')
|
|
||||||
const calls = entries.filter(entry => entry.row.type === 'tool/call' && sameStep(entry.row.data, data))
|
|
||||||
const results = entries.filter(entry => entry.row.type === 'tool/result' && sameStep(entry.row.data, data))
|
|
||||||
const proposals = []
|
|
||||||
const provenChains = []
|
|
||||||
for (const [position, block] of ordered.entries()) {
|
|
||||||
const actual = block.content ?? { type: block.type, text: block.text }
|
|
||||||
const declared = content[position]
|
|
||||||
if (block.type !== 'tool-call') {
|
|
||||||
require(isDeepStrictEqual(actual, declared), 'Text or reasoning differs between the stream and assistant message.')
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
require(block.end && toolBlockShape(declared) &&
|
|
||||||
isDeepStrictEqual({ ...actual, id: '' }, { ...declared, id: '' }), 'The tool block and assistant advertisement disagree.')
|
|
||||||
const matchingCalls = calls.filter(entry => entry.row.data.name === actual.name && entry.row.data.arguments === actual.arguments)
|
|
||||||
require(matchingCalls.length === 1 && advertised.filter(value => value.name === actual.name && value.arguments === actual.arguments).length === 1,
|
|
||||||
'The tool advertisement and execution cannot be paired uniquely by name and arguments.')
|
|
||||||
const call = matchingCalls[0]
|
|
||||||
require(surfaceEnvelope(call.row) && !Object.hasOwn(call.row, 'surfaceOp') && !Object.hasOwn(call.row, 'sourceEventSeqs') &&
|
|
||||||
exactKeys(call.row.data, ['turn', 'step', 'callId', 'name', 'arguments']) && row.seq < call.row.seq && typeof call.row.data.callId === 'string',
|
|
||||||
'The tool execution has unsupported fields, precedes its advertisement or has an invalid ID.')
|
|
||||||
const matchingResults = results.filter(entry => Object.hasOwn(entry.row, 'sourceEventSeqs') && sourceSeqs(entry.row).includes(call.row.seq))
|
|
||||||
let toolResult
|
|
||||||
if (matchingResults.length === 1) {
|
|
||||||
toolResult = matchingResults[0]
|
|
||||||
require(isDeepStrictEqual(sourceSeqs(toolResult.row), [call.row.seq]), 'The result provenance does not select exactly this tool execution.')
|
|
||||||
} else {
|
|
||||||
require(matchingResults.length === 0 && advertised.length === 1 && calls.length === 1 && results.length === 1 && !Object.hasOwn(results[0].row, 'sourceEventSeqs'),
|
|
||||||
'The tool result is missing, ambiguous or has conflicting provenance.')
|
|
||||||
require(!logical.some(value => value.row.type === 'assistant/chunk' && sameStep(value.row.data, data) && !selected.has(value.row.seq)),
|
|
||||||
'A result without provenance cannot be matched across a retry or another stream attempt.')
|
|
||||||
toolResult = results[0]
|
|
||||||
}
|
|
||||||
const resultMessage = toolResult.row.data?.message
|
|
||||||
const resultBlock = resultMessage?.content?.[0]
|
|
||||||
require(surfaceEnvelope(toolResult.row) && exactKeys(toolResult.row.data, ['turn', 'step', 'message'], ['error', 'meta']) &&
|
|
||||||
call.row.seq < toolResult.row.seq && toolResult.row.surfaceOp === 'append' && messageShape(resultMessage) && resultMessage.role === 'user' &&
|
|
||||||
exactKeys(resultMessage.source, ['kind', 'callId']) && resultMessage.source.kind === 'tool' && typeof resultMessage.source.callId === 'string' && resultMessage.content.length === 1 &&
|
|
||||||
exactKeys(resultBlock, ['type', 'toolCallId', 'content'], ['isError']) && resultBlock.type === 'tool-result' && typeof resultBlock.toolCallId === 'string' &&
|
|
||||||
Array.isArray(resultBlock.content) && (!Object.hasOwn(resultBlock, 'isError') || typeof resultBlock.isError === 'boolean'), 'The tool result is not a complete append result with a single identity.')
|
|
||||||
const slots = [
|
|
||||||
[block.end, ['data', 'chunk', 'block', 'id'], actual.id],
|
|
||||||
[{ entry: assistant, row }, ['data', 'message', 'content', position, 'id'], declared.id],
|
|
||||||
[{ entry: call, row: call.row }, ['data', 'callId'], call.row.data.callId],
|
|
||||||
[{ entry: toolResult, row: toolResult.row }, ['data', 'message', 'source', 'callId'], resultMessage.source.callId],
|
|
||||||
[{ entry: toolResult, row: toolResult.row }, ['data', 'message', 'content', 0, 'toolCallId'], resultMessage.content[0].toolCallId],
|
|
||||||
]
|
|
||||||
if (!slots.some(slot => slot[2] === '')) {
|
|
||||||
require(slots.every(slot => slot[2] === actual.id) && block.deltas.every(value => value.row.data.chunk.id === '' || value.row.data.chunk.id === actual.id),
|
|
||||||
'An already nonempty tool chain contains conflicting recorded identities.')
|
|
||||||
provenChains.push(slots)
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
const candidates = new Set(block.deltas.map(value => value.row.data.chunk.id).filter(nonempty))
|
|
||||||
require(candidates.size === 1, 'The tool stream has no unique previously recorded provider ID.')
|
|
||||||
const candidate = [...candidates][0]
|
|
||||||
require(slots.every(slot => slot[2] === '' || slot[2] === candidate), 'A durable ID conflicts with the recorded provider ID.')
|
|
||||||
require(advertised.every(value => value === declared || value.id !== candidate), 'The recorded ID is already advertised by another tool in this step.')
|
|
||||||
let seen = false
|
|
||||||
const deltas = []
|
|
||||||
for (const value of block.deltas) {
|
|
||||||
if (value.row.data.chunk.id === candidate) seen = true
|
|
||||||
else if (seen) deltas.push([value, ['data', 'chunk', 'id'], ''])
|
|
||||||
}
|
|
||||||
require(deltas.length > 0, 'No empty continuation delta follows the recorded provider ID.')
|
|
||||||
provenChains.push(slots)
|
|
||||||
proposals.push({ candidate, name: actual.name, assistant, call, toolResult, block, slots: [...deltas, ...slots.filter(slot => slot[2] === '')], sources })
|
|
||||||
}
|
|
||||||
require(new Set(proposals.map(value => value.candidate)).size === proposals.length, 'Multiple tools claim the same recorded provider ID.')
|
|
||||||
for (const proposal of proposals) {
|
|
||||||
const owned = new Map()
|
|
||||||
const allow = (entry, path) => {
|
|
||||||
if (!owned.has(entry)) owned.set(entry, new Set())
|
|
||||||
owned.get(entry).add(JSON.stringify(path))
|
|
||||||
}
|
|
||||||
for (const slots of provenChains) for (const [value, path] of slots) allow(value.entry, path)
|
|
||||||
const linkedSeqs = new Set([...sources, row.seq, proposal.call.row.seq, proposal.toolResult.row.seq])
|
|
||||||
const linkedMessages = new Set([data.message.id, proposal.toolResult.row.data.message.id])
|
|
||||||
const cites = value => {
|
|
||||||
if (!record(value) && !Array.isArray(value)) return false
|
|
||||||
return Object.entries(value).some(([key, child]) => {
|
|
||||||
if (key === 'sourceEventSeq' && linkedSeqs.has(child)) return true
|
|
||||||
if ((/^(?:messageId|.*MessageId)s?$/.test(key) || key === 'id' && ['assistant', 'user'].includes(value.role)) &&
|
|
||||||
(linkedMessages.has(child) || Array.isArray(child) && child.some(id => linkedMessages.has(id)))) return true
|
|
||||||
if (key === 'shadowedRange' && record(child) && [...linkedSeqs].some(seq => count(child.start) && count(child.end) && child.start <= seq && seq <= child.end)) return true
|
|
||||||
if (['sourceEventSeqs', 'shadowedSeqs', 'shadowedRange'].includes(key) && Array.isArray(child)) {
|
|
||||||
if (key === 'shadowedRange' && child.length === 2 && [...linkedSeqs].some(seq => count(child[0]) && count(child[1]) && child[0] <= seq && seq <= child[1])) return true
|
|
||||||
if (child.some(member => linkedSeqs.has(member) || Array.isArray(member) && member.length === 2 && [...linkedSeqs].some(seq => count(member[0]) && count(member[1]) && member[0] <= seq && seq <= member[1]))) return true
|
|
||||||
}
|
|
||||||
return cites(child)
|
|
||||||
})
|
|
||||||
}
|
|
||||||
for (const entry of entries.slice(1)) {
|
|
||||||
const value = entry.row
|
|
||||||
const replacement = value.surfaceOp
|
|
||||||
const surfaces = [row.seq, proposal.toolResult.row.seq]
|
|
||||||
const replaces = record(replacement) && replacement.op === 'replace' && surfaces.some(seq => count(replacement.start) && count(replacement.end) && replacement.start <= seq && seq <= replacement.end)
|
|
||||||
require(!replaces, 'A surface replacement also owns the affected historical message.')
|
|
||||||
const copiesMessage = [data.message.id, proposal.toolResult.row.data.message.id].includes(value.data?.message?.id) && entry !== assistant && entry !== proposal.toolResult
|
|
||||||
require(!copiesMessage, 'A copied message identity needs owner-aware recovery.')
|
|
||||||
if (!sameStep(entry.scope, data) && !cites(value)) continue
|
|
||||||
assertUniqueJson(entry.line, value)
|
|
||||||
require(!(value.type === 'approval/asked' && value.data?.toolName === proposal.name &&
|
|
||||||
(value.data.callId === undefined || value.data.callId === '' || value.data.callId === proposal.candidate)), 'An associated approval retains the historical tool identity.')
|
|
||||||
const visit = (current, path = []) => {
|
|
||||||
if (!record(current) && !Array.isArray(current)) return
|
|
||||||
for (const [key, child] of Object.entries(current)) {
|
|
||||||
const next = [...path, Array.isArray(current) ? Number(key) : key]
|
|
||||||
const identity = ['callId', 'toolCallId', 'rootCallId', 'parentCallId', 'subCallId'].includes(key) || key === 'id' && current.type === 'tool-call'
|
|
||||||
if (key === 'replayState') require(false, 'Owner replay state needs owner-aware identity recovery.')
|
|
||||||
if (identity && (child === '' || child === proposal.candidate || typeof child === 'string' && (child.startsWith(`${proposal.candidate}:code:`) || child.startsWith(':code:')))) {
|
|
||||||
require(owned.get(entry)?.has(JSON.stringify(next)), 'An additional approval, dispatch, plugin or copied-content identity reference remains.')
|
|
||||||
}
|
|
||||||
visit(child, next)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
visit(value)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
for (const proposal of proposals) {
|
|
||||||
chains++
|
|
||||||
for (const [value, path] of proposal.slots) {
|
|
||||||
fields++
|
|
||||||
if (value.offset !== undefined) {
|
|
||||||
if (!packedIds.has(value.entry.index)) packedIds.set(value.entry.index, new Map())
|
|
||||||
packedIds.get(value.entry.index).set(value.offset, proposal.candidate)
|
|
||||||
} else {
|
|
||||||
if (!rawPatches.has(value.entry.index)) rawPatches.set(value.entry.index, [])
|
|
||||||
rawPatches.get(value.entry.index).push({ path, value: proposal.candidate })
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
} catch (error) {
|
|
||||||
if (typeof error !== 'string') throw error
|
|
||||||
refuse(assistant, error)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if (refusals.occurrences > 0) { rawPatches.clear(); packedIds.clear(); chains = 0; fields = 0 }
|
|
||||||
return result()
|
|
||||||
}
|
|
||||||
|
|
||||||
function legacyBlockers() {
|
|
||||||
const issues = new Map()
|
|
||||||
const add = (code, message, row, line, path) => {
|
|
||||||
if (!issues.has(code)) issues.set(code, { code, message, occurrences: 0, samples: [] })
|
|
||||||
const issue = issues.get(code)
|
|
||||||
issue.occurrences++
|
|
||||||
const seq = row.seq ?? row.seq0
|
|
||||||
if (issue.samples.length < 10) issue.samples.push({ line, type: row.type, ...(count(seq) ? { seq } : {}), path })
|
|
||||||
}
|
|
||||||
const identifier = (value, row, line, path) => {
|
|
||||||
if (value === '') add('empty-durable-tool-id', 'An empty durable tool ID lacks a proven closed chain to its recorded provider identity; new identities are not synthesized.', row, line, path)
|
|
||||||
}
|
|
||||||
const block = (value, row, line, path) => {
|
|
||||||
if (value?.type === 'tool-call') identifier(value.id, row, line, `${path}.id`)
|
|
||||||
if (value?.type === 'tool-result') identifier(value.toolCallId, row, line, `${path}.toolCallId`)
|
|
||||||
}
|
|
||||||
const message = (value, row, line, path) => {
|
|
||||||
if (value?.source?.kind === 'tool') identifier(value.source.callId, row, line, `${path}.source.callId`)
|
|
||||||
if (Array.isArray(value?.content)) value.content.forEach((value, index) => block(value, row, line, `${path}.content[${index}]`))
|
|
||||||
}
|
|
||||||
return {
|
|
||||||
inspect(row, line) {
|
|
||||||
const data = row?.data
|
|
||||||
if (row?.type === 'subagent/descriptor' && data?.version !== 3 && !supportedDescriptorV2(data)) {
|
|
||||||
add('unsupported-subagent-descriptor', 'Only exact historical v2 descriptors with equivalent v3 composition are supported; this descriptor needs recovery by its original writer.', row, line, 'data.version')
|
|
||||||
}
|
|
||||||
if (row?.type === 'tool-call-chunks') {
|
|
||||||
if ((data?.id === '' || data?.name === '' || data?.name === null) && !supportedPackedToolRun(row)) add('unsupported-packed-tool-chunks', 'The packed row cannot be expanded losslessly: it needs exact fields, string deltas and safe sequence/time coordinates.', row, line, 'data')
|
|
||||||
}
|
|
||||||
if (row?.type === 'assistant/chunk') {
|
|
||||||
if (data?.chunk?.type === 'tool-call-delta' && data.chunk.name === null && !supportedNullToolDelta(row)) {
|
|
||||||
add('null-stream-tool-name', 'A null streaming tool name needs exact raw fields, string ID/arguments and safe coordinates before normalization.', row, line, 'data.chunk.name')
|
|
||||||
}
|
|
||||||
if (data?.chunk?.type === 'block-end') block(data.chunk.block, row, line, 'data.chunk.block')
|
|
||||||
}
|
|
||||||
if (row?.type === 'assistant/message') {
|
|
||||||
message(data?.message, row, line, 'data.message')
|
|
||||||
if (record(data) && !Object.hasOwn(data, 'message') && Object.hasOwn(data, 'content') && Object.hasOwn(data, 'provenance')) {
|
|
||||||
message(data, row, line, 'data')
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if (row?.type === 'tool/call') identifier(data?.callId, row, line, 'data.callId')
|
|
||||||
if (row?.type === 'tool/result') {
|
|
||||||
identifier(data?.callId, row, line, 'data.callId')
|
|
||||||
message(data?.message, row, line, 'data.message')
|
|
||||||
}
|
|
||||||
},
|
|
||||||
report: () => [...issues.values()],
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
function objectMembers(text, start, array = false) {
|
|
||||||
let cursor = start
|
|
||||||
const space = () => { while (/\s/.test(text[cursor] ?? '') && cursor < text.length) cursor++ }
|
|
||||||
const stringEnd = () => {
|
|
||||||
cursor++
|
|
||||||
while (cursor < text.length) {
|
|
||||||
if (text[cursor++] === '"') return
|
|
||||||
if (text[cursor - 1] === '\\') cursor++
|
|
||||||
}
|
|
||||||
}
|
|
||||||
const valueEnd = () => {
|
|
||||||
if (text[cursor] === '"') return stringEnd()
|
|
||||||
if (text[cursor] === '{' || text[cursor] === '[') {
|
|
||||||
let depth = 0
|
|
||||||
do {
|
|
||||||
if (text[cursor] === '"') stringEnd()
|
|
||||||
else {
|
|
||||||
if ('{['.includes(text[cursor])) depth++
|
|
||||||
if ('}]'.includes(text[cursor])) depth--
|
|
||||||
cursor++
|
|
||||||
}
|
|
||||||
} while (depth > 0)
|
|
||||||
} else {
|
|
||||||
while (cursor < text.length && !/[\s,}\]]/.test(text[cursor])) cursor++
|
|
||||||
}
|
|
||||||
}
|
|
||||||
space()
|
|
||||||
if (text[cursor++] !== (array ? '[' : '{')) throw new Error('Expected a JSON container in the legacy message path.')
|
|
||||||
const members = []
|
|
||||||
const names = new Set()
|
|
||||||
space()
|
|
||||||
const close = array ? ']' : '}'
|
|
||||||
while (text[cursor] !== close) {
|
|
||||||
const start = cursor
|
|
||||||
let name = members.length
|
|
||||||
if (!array) {
|
|
||||||
stringEnd()
|
|
||||||
name = JSON.parse(text.slice(start, cursor))
|
|
||||||
if (names.has(name)) throw new Error('Duplicate JSON property in the legacy message path; refusing ambiguous repair.')
|
|
||||||
names.add(name)
|
|
||||||
space()
|
|
||||||
cursor++
|
|
||||||
space()
|
|
||||||
}
|
|
||||||
const valueStart = cursor
|
|
||||||
valueEnd()
|
|
||||||
members.push({ name, start, end: cursor, valueStart })
|
|
||||||
space()
|
|
||||||
if (text[cursor] === close) break
|
|
||||||
cursor++
|
|
||||||
space()
|
|
||||||
}
|
|
||||||
return members
|
|
||||||
}
|
|
||||||
|
|
||||||
function assertUniqueJson(line, row, start = 0) {
|
|
||||||
if (!record(row) && !Array.isArray(row)) return
|
|
||||||
for (const member of objectMembers(line, start, Array.isArray(row))) assertUniqueJson(line, row[member.name], member.valueStart)
|
|
||||||
}
|
|
||||||
|
|
||||||
function replaceIdentityValues(line, patches) {
|
|
||||||
for (const patch of patches) {
|
|
||||||
let start = 0
|
|
||||||
let member
|
|
||||||
for (const key of patch.path) {
|
|
||||||
member = objectMembers(line, start, typeof key === 'number').find(value => value.name === key)
|
|
||||||
if (!member) throw new Error('An identity patch no longer matches its proven JSON path.')
|
|
||||||
start = member.valueStart
|
|
||||||
}
|
|
||||||
line = line.slice(0, member.valueStart) + JSON.stringify(patch.value) + line.slice(member.end)
|
|
||||||
}
|
|
||||||
return line
|
|
||||||
}
|
|
||||||
|
|
||||||
function removeSummary(line) {
|
|
||||||
const data = objectMembers(line, 0).find(member => member.name === 'data')
|
|
||||||
const source = objectMembers(line, data.valueStart).find(member => member.name === 'source')
|
|
||||||
const members = objectMembers(line, source.valueStart)
|
|
||||||
const index = members.findIndex(member => member.name === 'summary')
|
|
||||||
const member = members[index]
|
|
||||||
const start = index === members.length - 1 && index > 0 ? members[index - 1].end : member.start
|
|
||||||
const end = index < members.length - 1 ? members[index + 1].start : member.end
|
|
||||||
return line.slice(0, start) + line.slice(end)
|
|
||||||
}
|
|
||||||
|
|
||||||
function promoteDescriptor(line) {
|
|
||||||
const data = objectMembers(line, 0).find(member => member.name === 'data')
|
|
||||||
const members = objectMembers(line, data.valueStart)
|
|
||||||
const filter = members.find(member => member.name === 'toolFilter')
|
|
||||||
if (filter) objectMembers(line, filter.valueStart)
|
|
||||||
const version = members.find(member => member.name === 'version')
|
|
||||||
return line.slice(0, version.valueStart) + '3' + line.slice(version.end)
|
|
||||||
}
|
|
||||||
|
|
||||||
function normalizeNullToolName(line) {
|
|
||||||
const data = objectMembers(line, 0).find(member => member.name === 'data')
|
|
||||||
const chunk = objectMembers(line, data.valueStart).find(member => member.name === 'chunk')
|
|
||||||
const name = objectMembers(line, chunk.valueStart).find(member => member.name === 'name')
|
|
||||||
return line.slice(0, name.valueStart) + '""' + line.slice(name.end)
|
|
||||||
}
|
|
||||||
|
|
||||||
function expandPackedToolRun(line, row, retain, recoveredIds) {
|
|
||||||
const data = objectMembers(line, 0).find(member => member.name === 'data')
|
|
||||||
objectMembers(line, data.valueStart)
|
|
||||||
let time = row.time0
|
|
||||||
const expanded = []
|
|
||||||
for (let index = 0; index < row.data.args.length; index++) {
|
|
||||||
if (index > 0) time += row.data.dt[index - 1]
|
|
||||||
expanded.push(retain(JSON.stringify({
|
|
||||||
type: 'assistant/chunk', seq: row.seq0 + index, time,
|
|
||||||
data: { turn: row.data.turn, step: row.data.step, chunk: {
|
|
||||||
type: 'tool-call-delta', index: row.data.index, id: recoveredIds?.get(index) ?? row.data.id,
|
|
||||||
...(Object.hasOwn(row.data, 'name') ? { name: row.data.name ?? '' } : {}), argumentsDelta: row.data.args[index],
|
|
||||||
} },
|
|
||||||
}) + (line.endsWith('\r\n') ? '\r\n' : '\n')))
|
|
||||||
}
|
|
||||||
return expanded.join('')
|
|
||||||
}
|
|
||||||
|
|
||||||
async function readBounded(path) {
|
|
||||||
const chunks = []
|
|
||||||
let length = 0
|
|
||||||
for await (const chunk of createReadStream(path)) {
|
|
||||||
length += chunk.length
|
|
||||||
if (length > maximumBytes) throw new Error('Session exceeds the 128 MiB repair limit.')
|
|
||||||
chunks.push(chunk)
|
|
||||||
}
|
|
||||||
return Buffer.concat(chunks)
|
|
||||||
}
|
|
||||||
|
|
||||||
function frameLength(input, start) {
|
|
||||||
const requireBytes = end => { if (end > input.length) throw new Error('Truncated Zstandard frame; no output written.') }
|
|
||||||
requireBytes(start + 5)
|
|
||||||
if (input.readUInt32LE(start) !== 0xfd2fb528) throw new Error('Unsupported Zstandard frame; only ordinary DSH frames are accepted.')
|
|
||||||
const descriptor = input[start + 4]
|
|
||||||
if (descriptor & 0x18) throw new Error('Reserved Zstandard frame header bits are set.')
|
|
||||||
const single = (descriptor & 0x20) !== 0
|
|
||||||
const sizeFlag = descriptor >>> 6
|
|
||||||
const contentSizeBytes = sizeFlag === 0 ? (single ? 1 : 0) : [0, 2, 4, 8][sizeFlag]
|
|
||||||
let offset = start + 5 + (single ? 0 : 1) + [0, 1, 2, 4][descriptor & 3] + contentSizeBytes
|
|
||||||
requireBytes(offset)
|
|
||||||
let last = false
|
|
||||||
while (!last) {
|
|
||||||
requireBytes(offset + 3)
|
|
||||||
const block = input.readUIntLE(offset, 3)
|
|
||||||
last = (block & 1) !== 0
|
|
||||||
const type = (block >>> 1) & 3
|
|
||||||
if (type === 3) throw new Error('Reserved Zstandard block type.')
|
|
||||||
offset += 3 + (type === 1 ? 1 : block >>> 3)
|
|
||||||
requireBytes(offset)
|
|
||||||
}
|
|
||||||
offset += descriptor & 4 ? 4 : 0
|
|
||||||
requireBytes(offset)
|
|
||||||
return offset - start
|
|
||||||
}
|
|
||||||
|
|
||||||
function decodeFrames(input) {
|
|
||||||
const chunks = []
|
|
||||||
let offset = 0
|
|
||||||
let length = 0
|
|
||||||
while (offset < input.length) {
|
|
||||||
const lengthOnDisk = frameLength(input, offset)
|
|
||||||
const { buffer, engine } = zlib.zstdDecompressSync(input.subarray(offset, offset + lengthOnDisk), {
|
|
||||||
info: true, maxOutputLength: maximumBytes - length,
|
|
||||||
})
|
|
||||||
if (engine.bytesWritten !== lengthOnDisk) throw new Error('Invalid Zstandard frame length.')
|
|
||||||
offset += engine.bytesWritten
|
|
||||||
length += buffer.length
|
|
||||||
chunks.push(buffer)
|
|
||||||
}
|
|
||||||
return Buffer.concat(chunks)
|
|
||||||
}
|
|
||||||
|
|
||||||
function encodeFrames(text) {
|
|
||||||
const end = text.indexOf('\n') + 1
|
|
||||||
const options = { params: { [zlib.constants.ZSTD_c_checksumFlag]: 1 } }
|
|
||||||
return Buffer.concat([text.slice(0, end), text.slice(end)].filter(Boolean).map(part => zlib.zstdCompressSync(part, options)))
|
|
||||||
}
|
|
||||||
|
|
||||||
async function writeRepairCopy(input, output, result) {
|
|
||||||
if (resolve(input) === resolve(output)) throw new Error('Output must be a new copy; the input cannot be overwritten.')
|
|
||||||
const temporary = await mkdtemp(join(dirname(resolve(output)), '.mnemon-repair-'))
|
|
||||||
try {
|
|
||||||
const path = join(temporary, 'session')
|
|
||||||
const file = await open(path, 'wx', 0o600)
|
|
||||||
try { await file.writeFile(result); await file.sync() } finally { await file.close() }
|
|
||||||
await link(path, output)
|
|
||||||
} finally { await rm(temporary, { recursive: true, force: true }) }
|
|
||||||
}
|
|
||||||
|
|
||||||
async function repairIdleProbeSession(entries, original, compressed, input, output) {
|
|
||||||
const header = entries[0].row
|
|
||||||
assertUniqueJson(entries[0].line, header)
|
|
||||||
if (header.type !== 'session' || header.version !== 4 || header.isSeeded !== false || header.delegationDepth !== 0 ||
|
|
||||||
header.parentSession !== undefined || header.origin !== undefined) throw new Error('Idle probe recovery requires an unseeded v4 root Session.')
|
|
||||||
const uuid = /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/u
|
|
||||||
const recovered = new Set()
|
|
||||||
const pending = new Map()
|
|
||||||
const roots = new Set()
|
|
||||||
let openTurn
|
|
||||||
let openStep
|
|
||||||
let completedStep = false
|
|
||||||
let completed = false
|
|
||||||
const refuse = () => { throw new Error('Unrecognized or incomplete out-of-turn PTC audit; no output written.') }
|
|
||||||
for (const entry of entries.slice(1)) {
|
|
||||||
const row = entry.row
|
|
||||||
if (row.type === 'turn/start' || row.type === 'turn/end') {
|
|
||||||
assertUniqueJson(entry.line, row)
|
|
||||||
if (pending.size || !count(row.data?.turn)) refuse()
|
|
||||||
if (row.type === 'turn/start') {
|
|
||||||
if (openTurn !== undefined) refuse()
|
|
||||||
openTurn = row.data.turn
|
|
||||||
completedStep = false
|
|
||||||
} else {
|
|
||||||
if (openTurn !== row.data.turn) refuse()
|
|
||||||
openTurn = undefined
|
|
||||||
completed = true
|
|
||||||
}
|
|
||||||
openStep = undefined
|
|
||||||
}
|
|
||||||
if (row.type === 'step/start' || row.type === 'step/end') {
|
|
||||||
assertUniqueJson(entry.line, row)
|
|
||||||
if (pending.size || openTurn !== row.data?.turn || !count(row.data?.step)) refuse()
|
|
||||||
if (row.type === 'step/start') {
|
|
||||||
if (openStep !== undefined) refuse()
|
|
||||||
openStep = row.data.step
|
|
||||||
} else {
|
|
||||||
if (openStep !== row.data.step) refuse()
|
|
||||||
openStep = undefined
|
|
||||||
completedStep = true
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if (!['tool/ptc-dispatch-start', 'tool/ptc-dispatch'].includes(row.type) || openStep !== undefined) continue
|
|
||||||
assertUniqueJson(entry.line, row)
|
|
||||||
const data = row.data
|
|
||||||
const start = row.type === 'tool/ptc-dispatch-start'
|
|
||||||
if (!(openTurn === undefined ? completed : completedStep) || !exactKeys(row, ['type', 'seq', 'time', 'data']) || !count(row.seq) || !integer(row.time) ||
|
|
||||||
!exactKeys(data, ['rootCallId', 'parentCallId', 'subCallId', 'name', 'arguments', ...(start ? [] : ['isError', 'content'])], start ? [] : ['error', 'meta']) ||
|
|
||||||
!uuid.test(data.rootCallId) || data.parentCallId !== data.rootCallId || data.subCallId !== `${data.rootCallId}:ptc:1` ||
|
|
||||||
data.name !== 'mnemon_subagent_result' || !exactKeys(data.arguments, ['requestId', 'result']) ||
|
|
||||||
!uuid.test(data.arguments.requestId) || !exactKeys(data.arguments.result, [])) refuse()
|
|
||||||
if (start) {
|
|
||||||
if (roots.has(data.rootCallId)) refuse()
|
|
||||||
roots.add(data.rootCallId)
|
|
||||||
pending.set(data.rootCallId, entry)
|
|
||||||
} else {
|
|
||||||
const previous = pending.get(data.rootCallId)
|
|
||||||
if (!previous || !isDeepStrictEqual(previous.row.data.arguments, data.arguments) || previous.row.seq >= row.seq ||
|
|
||||||
typeof data.isError !== 'boolean' || !Array.isArray(data.content) ||
|
|
||||||
!data.isError && !isDeepStrictEqual(data.content, [{ type: 'text', text: 'Mnemon subagent result recorded.' }])) refuse()
|
|
||||||
pending.delete(data.rootCallId)
|
|
||||||
recovered.add(previous)
|
|
||||||
recovered.add(entry)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if (pending.size) refuse()
|
|
||||||
const changedSeqs = new Set([...recovered].map(entry => entry.row.seq))
|
|
||||||
for (const { row } of entries.slice(1)) {
|
|
||||||
for (const range of row.sourceEventSeqs ?? []) {
|
|
||||||
if (typeof range === 'number' ? changedSeqs.has(range) : Array.isArray(range) && [...changedSeqs].some(seq => seq >= range[0] && seq <= range[1])) refuse()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
const text = entries.map(entry => recovered.has(entry)
|
|
||||||
? JSON.stringify({ type: 'dsh-brain-mnemon/recovered-idle-probe', seq: entry.row.seq, time: entry.row.time, ignorable: true,
|
|
||||||
data: { originalType: entry.row.type, originalData: entry.row.data } }) + '\n'
|
|
||||||
: entry.line).join('')
|
|
||||||
const plain = Buffer.from(text)
|
|
||||||
if (plain.length > maximumBytes) throw new Error('Repaired Session exceeds the 128 MiB repair limit; no output written.')
|
|
||||||
const result = recovered.size === 0 ? original : compressed ? encodeFrames(text) : plain
|
|
||||||
if (result.length > maximumBytes) throw new Error('Repaired Session exceeds the 128 MiB repair limit; no output written.')
|
|
||||||
if (output !== undefined) await writeRepairCopy(input, output, result)
|
|
||||||
return { mode: output === undefined ? 'preview' : 'copy', format: 4, encoding: compressed ? 'zstd' : 'jsonl',
|
|
||||||
recoveredIdleProbeEvents: recovered.size, inputSha256: sha256(original), outputSha256: sha256(result),
|
|
||||||
originalPreserved: true, migrationValidated: false, blockers: [] }
|
|
||||||
}
|
|
||||||
|
|
||||||
export async function repairLegacySession(input, output) {
|
|
||||||
const original = await readBounded(input)
|
|
||||||
const compressed = original.subarray(0, 4).equals(Buffer.from([0x28, 0xb5, 0x2f, 0xfd]))
|
|
||||||
if (compressed && (typeof zlib.zstdDecompressSync !== 'function' || typeof zlib.zstdCompressSync !== 'function')) {
|
|
||||||
throw new Error('Zstandard sessions require Node 22.19 or newer (or Node 24+).')
|
|
||||||
}
|
|
||||||
const decoded = compressed ? decodeFrames(original) : original
|
|
||||||
const text = new TextDecoder('utf-8', { fatal: true, ignoreBOM: true }).decode(decoded)
|
|
||||||
if (!text.endsWith('\n')) throw new Error('Session must end with a complete newline-terminated JSON record.')
|
|
||||||
const lines = text.match(/[^\n]*\n/g) ?? []
|
|
||||||
const entries = lines.map((line, index) => {
|
|
||||||
try { return { line, index, row: JSON.parse(line) } } catch { throw new Error(`Invalid JSON at line ${index + 1}; no output written.`) }
|
|
||||||
})
|
|
||||||
if (entries[0]?.row?.version === 4) return repairIdleProbeSession(entries, original, compressed, input, output)
|
|
||||||
const recovery = recoverRecordedToolIdentities(entries)
|
|
||||||
let changes = 0
|
|
||||||
let descriptors = 0
|
|
||||||
let expandedRows = 0
|
|
||||||
let expandedChunks = 0
|
|
||||||
let normalizedNames = 0
|
|
||||||
let outputBytes = 0
|
|
||||||
const retain = line => {
|
|
||||||
outputBytes += Buffer.byteLength(line)
|
|
||||||
if (outputBytes > maximumBytes) throw new Error('Expanded Session exceeds the 128 MiB repair limit; no output written.')
|
|
||||||
return line
|
|
||||||
}
|
|
||||||
const diagnostics = legacyBlockers()
|
|
||||||
const repaired = entries.map(entry => {
|
|
||||||
const { index } = entry
|
|
||||||
let { line, row } = entry
|
|
||||||
if (index === 0) {
|
|
||||||
objectMembers(line, 0)
|
|
||||||
if (row.type !== 'session' || row.version !== 0 || typeof row.id !== 'string' || !row.id ||
|
|
||||||
!Number.isSafeInteger(row.createdAt) || row.createdAt < 0 ||
|
|
||||||
!Number.isSafeInteger(row.delegationDepth) || row.delegationDepth < 0) {
|
|
||||||
throw new Error('Only a legacy DSH format v0 Session header is supported.')
|
|
||||||
}
|
|
||||||
return retain(line)
|
|
||||||
}
|
|
||||||
const patches = recovery.rawPatches.get(index)
|
|
||||||
if (patches) { line = replaceIdentityValues(line, patches); row = JSON.parse(line) }
|
|
||||||
diagnostics.inspect(row, index + 1)
|
|
||||||
if (row?.type === 'subagent/descriptor' && supportedDescriptorV2(row.data)) {
|
|
||||||
descriptors++
|
|
||||||
return retain(promoteDescriptor(line))
|
|
||||||
}
|
|
||||||
if (row?.type === 'tool-call-chunks' && supportedPackedToolRun(row)) {
|
|
||||||
expandedRows++
|
|
||||||
expandedChunks += row.data.args.length
|
|
||||||
if (row.data.name === null) normalizedNames += row.data.args.length
|
|
||||||
return expandPackedToolRun(line, row, retain, recovery.packedIds.get(index))
|
|
||||||
}
|
|
||||||
if (row?.type === 'assistant/chunk' && supportedNullToolDelta(row)) {
|
|
||||||
normalizedNames++
|
|
||||||
return retain(normalizeNullToolName(line))
|
|
||||||
}
|
|
||||||
const source = row?.data?.source
|
|
||||||
if (row?.type !== 'user/message' || source?.kind !== 'plugin' || source.plugin !== 'dsh-brain-mnemon' ||
|
|
||||||
!Object.hasOwn(summaries, source.form) || !summaries[source.form].includes(source.summary)) return retain(line)
|
|
||||||
changes++
|
|
||||||
return retain(removeSummary(line))
|
|
||||||
}).join('')
|
|
||||||
const plain = Buffer.from(repaired)
|
|
||||||
const result = changes + descriptors + expandedRows + normalizedNames + recovery.fields === 0 ? original : compressed ? encodeFrames(repaired) : plain
|
|
||||||
if (result.length > maximumBytes) throw new Error('Repaired Session exceeds the 128 MiB repair limit; no output written.')
|
|
||||||
const blockers = diagnostics.report()
|
|
||||||
if (output !== undefined && blockers.length === 0) {
|
|
||||||
await writeRepairCopy(input, output, result)
|
|
||||||
}
|
|
||||||
return {
|
|
||||||
mode: output === undefined ? 'preview' : blockers.length === 0 ? 'copy' : 'refused',
|
|
||||||
format: 0,
|
|
||||||
encoding: compressed ? 'zstd' : 'jsonl',
|
|
||||||
repairedMessages: changes,
|
|
||||||
repairedDescriptors: descriptors,
|
|
||||||
expandedToolChunkRows: expandedRows,
|
|
||||||
expandedToolChunks: expandedChunks,
|
|
||||||
normalizedToolChunkNames: normalizedNames,
|
|
||||||
recoveredToolIdentityChains: recovery.chains,
|
|
||||||
recoveredToolIdentityFields: recovery.fields,
|
|
||||||
toolIdentityRecoveryRefusals: recovery.refusals,
|
|
||||||
inputSha256: sha256(original),
|
|
||||||
outputSha256: blockers.length === 0 ? sha256(result) : null,
|
|
||||||
originalPreserved: true,
|
|
||||||
migrationValidated: false,
|
|
||||||
blockers,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
async function main(args) {
|
|
||||||
const usage = 'Usage: dsh-brain-mnemon-repair-session --input FILE [--output NEW_FILE]\nWithout --output, preview recognized v4 idle-review probe audit recovery or the three known Mnemon v0 summary repairs, exact compatible v2 subagent descriptors, packed deltas with empty IDs/names, property-preserving null-to-empty delta names and proven DeepSeek chains with a previously recorded provider ID. Unsupported descriptor/tool shapes are reported with exit status 1 and prevent output. DSH must still validate the repaired copy. Stop DSH and work on a backup copy. The input and existing output files are never overwritten.'
|
|
||||||
if (args.length === 1 && args[0] === '--help') { console.log(usage); return }
|
|
||||||
const options = new Map()
|
|
||||||
for (let index = 0; index < args.length; index += 2) {
|
|
||||||
const name = args[index]
|
|
||||||
const value = args[index + 1]
|
|
||||||
if (!['--input', '--output'].includes(name) || !value || value.startsWith('--') || options.has(name)) throw new Error(usage)
|
|
||||||
options.set(name, value)
|
|
||||||
}
|
|
||||||
if (!options.has('--input')) throw new Error(usage)
|
|
||||||
const report = await repairLegacySession(options.get('--input'), options.get('--output'))
|
|
||||||
console.log(JSON.stringify(report, null, 2))
|
|
||||||
if (report.blockers.length > 0) {
|
|
||||||
console.error('Unsupported legacy descriptor/tool data remains; no output written. Review blockers and request recovery from the original DSH writer with a sanitized reproducer.')
|
|
||||||
process.exitCode = 1
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
function isEntrypoint() {
|
|
||||||
try { return process.argv[1] !== undefined && realpathSync(process.argv[1]) === realpathSync(fileURLToPath(import.meta.url)) }
|
|
||||||
catch { return false }
|
|
||||||
}
|
|
||||||
|
|
||||||
if (isEntrypoint()) {
|
|
||||||
main(process.argv.slice(2)).catch(error => { console.error(error.message); process.exitCode = 1 })
|
|
||||||
}
|
|
||||||
|
|
@ -1,4 +0,0 @@
|
||||||
import { ct as MemoryProviderDescriptor } from "../../../lib/contracts-DuGgDm58.js";
|
|
||||||
import "../../source-memory-spaces/lib/provider-sdk.js";
|
|
||||||
declare const descriptor: MemoryProviderDescriptor;
|
|
||||||
export { descriptor };
|
|
||||||
|
|
@ -1 +0,0 @@
|
||||||
export { t as descriptor } from "../../../lib/descriptor-B535Gkvl.js";
|
|
||||||
|
|
@ -1,36 +0,0 @@
|
||||||
import { a as MemoryJsonValue } from "../../../lib/index-3Wnpy9oQ.js";
|
|
||||||
import { $t as SearchRequest, J as MemoryGraphSnapshot, Jt as RememberRequest, L as MemoryBody, Y as MemoryListRequest, ot as MemoryProviderConnection, w as Insight } from "../../../lib/contracts-DuGgDm58.js";
|
|
||||||
import { C as ProviderSearchResult, f as MemoryProviderAdapter, h as MemorySpaceAuthority, n as MemorySpaceProviderDefinition, s as MemorySpaceProviderModule, x as ProviderMemorySpace, y as ProviderBodyStatus } from "../../../lib/definitions-C41Daez1.js";
|
|
||||||
import { ProcessRunner } from "../../source-memory-spaces/lib/provider-sdk.js";
|
|
||||||
import { descriptor } from "./descriptor.js";
|
|
||||||
interface ByteRoverProviderOptions {
|
|
||||||
process?: ProcessRunner;
|
|
||||||
queryTimeoutMs?: number;
|
|
||||||
curateTimeoutMs?: number;
|
|
||||||
}
|
|
||||||
declare class ByteRoverProvider implements MemoryProviderAdapter {
|
|
||||||
private readonly memorySpaces;
|
|
||||||
readonly id: "byterover";
|
|
||||||
readonly scoreSemantics: Readonly<{
|
|
||||||
kind: "provider-native";
|
|
||||||
}>;
|
|
||||||
private readonly process;
|
|
||||||
private readonly queryTimeoutMs;
|
|
||||||
private readonly curateTimeoutMs;
|
|
||||||
private readonly statusCache;
|
|
||||||
private readonly statusInFlight;
|
|
||||||
constructor(memorySpaces: MemorySpaceAuthority, options?: ByteRoverProviderOptions);
|
|
||||||
discover(connection: MemoryProviderConnection): Promise<ProviderMemorySpace[]>;
|
|
||||||
status(body: MemoryBody, signal?: AbortSignal): Promise<ProviderBodyStatus>;
|
|
||||||
invalidateStatus(memoryBodyId?: string): void;
|
|
||||||
private checkStatus;
|
|
||||||
search(body: MemoryBody, request: SearchRequest, signal?: AbortSignal): Promise<ProviderSearchResult>;
|
|
||||||
graph(body: MemoryBody): Promise<MemoryGraphSnapshot>;
|
|
||||||
list(body: MemoryBody, request: MemoryListRequest, signal?: AbortSignal): Promise<Insight[]>;
|
|
||||||
remember(body: MemoryBody, request: RememberRequest, signal?: AbortSignal): Promise<MemoryJsonValue>;
|
|
||||||
private connection;
|
|
||||||
private run;
|
|
||||||
}
|
|
||||||
declare const definition: MemorySpaceProviderDefinition;
|
|
||||||
declare const _default: MemorySpaceProviderModule<undefined>;
|
|
||||||
export { ByteRoverProvider, _default as default, definition, descriptor };
|
|
||||||
|
|
@ -1,264 +0,0 @@
|
||||||
import { i as runProcess } from "../../../lib/adapter-CF9Q9xOa.js";
|
|
||||||
import { i as defineMemorySpaceProviderDefinition, r as defineMemorySpaceProvider, t as MEMORY_SPACE_PROVIDER_API_VERSION } from "../../../lib/definitions-Du9KQuKM.js";
|
|
||||||
import "../../source-memory-spaces/lib/provider-sdk.js";
|
|
||||||
import { t as descriptor } from "../../../lib/descriptor-B535Gkvl.js";
|
|
||||||
import { createHash } from "node:crypto";
|
|
||||||
import { basename, dirname, isAbsolute, join, resolve } from "node:path";
|
|
||||||
import { mkdirSync, readFileSync, realpathSync, statSync } from "node:fs";
|
|
||||||
import { homedir } from "node:os";
|
|
||||||
// vendor/dsh-mnemon/plugins/dsh-brain-mnemon-provider-byterover/src/cli.ts
|
|
||||||
const INSTALL_GUIDANCE = "Install ByteRover with npm install -g byterover-cli or pnpm add -g byterover-cli. Ensure DSH can see PATH or PNPM_HOME, or set cliPath to its brv.cmd or executable.";
|
|
||||||
function isFile(path) {
|
|
||||||
try {
|
|
||||||
return statSync(path).isFile();
|
|
||||||
} catch {
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
function globalBins(env) {
|
|
||||||
const directory = (name) => {
|
|
||||||
const value = Object.entries(env).find(([key]) => key.toUpperCase() === name)?.[1]?.trim().replace(/^"(.*)"$/, "$1");
|
|
||||||
return value !== void 0 && isAbsolute(value) ? value : void 0;
|
|
||||||
};
|
|
||||||
const pnpm = directory("PNPM_HOME");
|
|
||||||
const local = directory("LOCALAPPDATA") ?? join(homedir(), "AppData", "Local");
|
|
||||||
const roaming = directory("APPDATA") ?? join(homedir(), "AppData", "Roaming");
|
|
||||||
return [
|
|
||||||
pnpm,
|
|
||||||
pnpm === void 0 ? void 0 : join(pnpm, "bin"),
|
|
||||||
directory("NVM_SYMLINK"),
|
|
||||||
join(local, "pnpm"),
|
|
||||||
join(local, "pnpm", "bin"),
|
|
||||||
join(roaming, "npm")
|
|
||||||
].filter((value) => value !== void 0);
|
|
||||||
}
|
|
||||||
function resolveByteRoverInvocation(command, args, env, cwd = process.cwd()) {
|
|
||||||
if (process.platform !== "win32") return {
|
|
||||||
command,
|
|
||||||
args: [...args],
|
|
||||||
env
|
|
||||||
};
|
|
||||||
if (/^brv(?:\.cmd)?$/i.test(command)) {
|
|
||||||
const path = Object.entries(env).find(([key]) => key.toUpperCase() === "PATH")?.[1] ?? "";
|
|
||||||
let found;
|
|
||||||
for (const directory of [...path.split(";"), ...globalBins(env)]) {
|
|
||||||
if (directory === "") continue;
|
|
||||||
const root = directory.replace(/^"(.*)"$/, "$1");
|
|
||||||
for (const name of /\.cmd$/i.test(command) ? ["brv.cmd"] : ["brv.exe", "brv.cmd"]) {
|
|
||||||
const candidate = resolve(cwd, root, name);
|
|
||||||
if (isFile(candidate)) {
|
|
||||||
found = candidate;
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if (found !== void 0) break;
|
|
||||||
}
|
|
||||||
if (found === void 0) throw new Error(`ByteRover brv was not found. ${INSTALL_GUIDANCE}`);
|
|
||||||
command = found;
|
|
||||||
}
|
|
||||||
if (!/\.cmd$/i.test(command)) return {
|
|
||||||
command,
|
|
||||||
args: [...args],
|
|
||||||
env
|
|
||||||
};
|
|
||||||
command = resolve(cwd, command);
|
|
||||||
try {
|
|
||||||
const shim = readFileSync(command, "utf8").replaceAll("\\", "/");
|
|
||||||
const launchers = /* @__PURE__ */ new Set();
|
|
||||||
for (const match of shim.matchAll(/"([^"\r\n]+)"/g)) {
|
|
||||||
let target = match[1];
|
|
||||||
if (!target.endsWith("/bin/run.js")) continue;
|
|
||||||
if (/^%(?:dp0%|~dp0)\//i.test(target)) target = target.replace(/^%(?:dp0%|~dp0)\//i, "");
|
|
||||||
else if (!isAbsolute(target)) continue;
|
|
||||||
if (target.includes("%")) continue;
|
|
||||||
const launcher = resolve(dirname(command), target);
|
|
||||||
const pkg = JSON.parse(readFileSync(join(dirname(dirname(launcher)), "package.json"), "utf8"));
|
|
||||||
const bin = pkg.bin?.brv;
|
|
||||||
if (pkg.name === "byterover-cli" && typeof bin === "string" && bin.replace(/^\.\//, "") === "bin/run.js" && isFile(launcher)) launchers.add(realpathSync(launcher));
|
|
||||||
}
|
|
||||||
if (launchers.size === 1) {
|
|
||||||
const inherited = Object.fromEntries(Object.entries(env).filter(([key]) => key.toUpperCase() !== "ELECTRON_RUN_AS_NODE"));
|
|
||||||
return {
|
|
||||||
command: process.execPath,
|
|
||||||
args: [[...launchers][0], ...args],
|
|
||||||
env: {
|
|
||||||
...inherited,
|
|
||||||
ELECTRON_RUN_AS_NODE: "1"
|
|
||||||
}
|
|
||||||
};
|
|
||||||
}
|
|
||||||
} catch {}
|
|
||||||
throw new Error(`ByteRover cliPath is not a recognized npm/pnpm brv.cmd launcher. ${INSTALL_GUIDANCE}`);
|
|
||||||
}
|
|
||||||
// vendor/dsh-mnemon/plugins/dsh-brain-mnemon-provider-byterover/src/driver.ts
|
|
||||||
var ByteRoverProvider = class {
|
|
||||||
memorySpaces;
|
|
||||||
id = "byterover";
|
|
||||||
scoreSemantics = Object.freeze({ kind: "provider-native" });
|
|
||||||
process;
|
|
||||||
queryTimeoutMs;
|
|
||||||
curateTimeoutMs;
|
|
||||||
statusCache = /* @__PURE__ */ new Map();
|
|
||||||
statusInFlight = /* @__PURE__ */ new Map();
|
|
||||||
constructor(memorySpaces, options = {}) {
|
|
||||||
this.memorySpaces = memorySpaces;
|
|
||||||
this.process = options.process ?? runProcess;
|
|
||||||
this.queryTimeoutMs = options.queryTimeoutMs ?? 1e4;
|
|
||||||
this.curateTimeoutMs = options.curateTimeoutMs ?? 12e4;
|
|
||||||
}
|
|
||||||
async discover(connection) {
|
|
||||||
const configured = String(connection.defaultDirectory ?? "").trim();
|
|
||||||
const existingDirectory = this.memorySpaces.list().find((body) => (body.provider.typeId ?? body.provider.id) === this.id)?.provider.settings.workingDirectory;
|
|
||||||
const directory = configured === "" ? String(existingDirectory ?? "").trim() || join(this.memorySpaces.runner.effectiveDataDir(), "state", "byterover", "default") : isAbsolute(configured) ? configured : resolve(this.memorySpaces.runner.effectiveDataDir(), configured);
|
|
||||||
return [{
|
|
||||||
externalId: directory,
|
|
||||||
name: basename(directory) || "ByteRover",
|
|
||||||
description: `ByteRover knowledge directory at ${directory}`,
|
|
||||||
connection: { workingDirectory: directory }
|
|
||||||
}];
|
|
||||||
}
|
|
||||||
async status(body, signal) {
|
|
||||||
if (signal !== void 0) return this.checkStatus(body, signal);
|
|
||||||
const cached = this.statusCache.get(body.id);
|
|
||||||
if (cached !== void 0 && Date.now() - cached.checkedAt < 6e4) return cached.value;
|
|
||||||
const running = this.statusInFlight.get(body.id);
|
|
||||||
if (running !== void 0) return running;
|
|
||||||
const pending = this.checkStatus(body);
|
|
||||||
this.statusInFlight.set(body.id, pending);
|
|
||||||
try {
|
|
||||||
const value = await pending;
|
|
||||||
this.statusCache.set(body.id, {
|
|
||||||
checkedAt: Date.now(),
|
|
||||||
value
|
|
||||||
});
|
|
||||||
return value;
|
|
||||||
} finally {
|
|
||||||
if (this.statusInFlight.get(body.id) === pending) this.statusInFlight.delete(body.id);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
invalidateStatus(memoryBodyId) {
|
|
||||||
if (memoryBodyId === void 0) this.statusCache.clear();
|
|
||||||
else this.statusCache.delete(memoryBodyId);
|
|
||||||
}
|
|
||||||
async checkStatus(body, signal) {
|
|
||||||
try {
|
|
||||||
await this.run(body, ["status"], 15e3, signal);
|
|
||||||
return { healthy: true };
|
|
||||||
} catch (error) {
|
|
||||||
return {
|
|
||||||
healthy: false,
|
|
||||||
error: error instanceof Error ? error.message : String(error)
|
|
||||||
};
|
|
||||||
}
|
|
||||||
}
|
|
||||||
async search(body, request, signal) {
|
|
||||||
const output = await this.run(body, [
|
|
||||||
"query",
|
|
||||||
"--",
|
|
||||||
request.query.slice(0, 5e3)
|
|
||||||
], this.queryTimeoutMs, signal);
|
|
||||||
if (output.length < 20 || /^no relevant (?:context|memories)\b/iu.test(output)) return {
|
|
||||||
results: [],
|
|
||||||
hint: "ByteRover found no relevant memories."
|
|
||||||
};
|
|
||||||
const content = output.length > 8e3 ? `${output.slice(0, 8e3)}\n\n[... truncated]` : output;
|
|
||||||
return { results: [{
|
|
||||||
id: `byterover:${createHash("sha256").update(content).digest("hex").slice(0, 24)}`,
|
|
||||||
content,
|
|
||||||
category: "context",
|
|
||||||
source: "external"
|
|
||||||
}] };
|
|
||||||
}
|
|
||||||
async graph(body) {
|
|
||||||
this.connection(body);
|
|
||||||
return {
|
|
||||||
nodes: [],
|
|
||||||
edges: [],
|
|
||||||
generatedAt: (/* @__PURE__ */ new Date()).toISOString()
|
|
||||||
};
|
|
||||||
}
|
|
||||||
async list(body, request, signal) {
|
|
||||||
if (request.query === void 0 || request.query.trim() === "") {
|
|
||||||
this.connection(body);
|
|
||||||
return [];
|
|
||||||
}
|
|
||||||
return (await this.search(body, {
|
|
||||||
query: request.query,
|
|
||||||
...request.limit === void 0 ? {} : { limit: request.limit }
|
|
||||||
}, signal)).results;
|
|
||||||
}
|
|
||||||
async remember(body, request, signal) {
|
|
||||||
await this.run(body, [
|
|
||||||
"curate",
|
|
||||||
"--",
|
|
||||||
request.content
|
|
||||||
], this.curateTimeoutMs, signal);
|
|
||||||
this.invalidateStatus(body.id);
|
|
||||||
return {
|
|
||||||
action: "stored",
|
|
||||||
provider: this.id,
|
|
||||||
summary: "ByteRover curated the memory into its knowledge tree."
|
|
||||||
};
|
|
||||||
}
|
|
||||||
connection(body) {
|
|
||||||
if ((body.provider.typeId ?? body.provider.id) !== this.id) throw new Error(`ByteRover cannot serve provider ${body.provider.id}`);
|
|
||||||
return this.memorySpaces.providerConnection(body.id, body.provider.id);
|
|
||||||
}
|
|
||||||
async run(body, args, timeoutMs, signal) {
|
|
||||||
const connection = this.connection(body);
|
|
||||||
const command = String(connection.cliPath ?? "brv");
|
|
||||||
const configuredDirectory = String(connection.workingDirectory ?? connection.defaultDirectory ?? "").trim();
|
|
||||||
const defaultDirectory = join(this.memorySpaces.runner.effectiveDataDir(), "state", "byterover", "default");
|
|
||||||
const cwd = configuredDirectory === "" ? defaultDirectory : isAbsolute(configuredDirectory) ? configuredDirectory : resolve(this.memorySpaces.runner.effectiveDataDir(), configuredDirectory);
|
|
||||||
mkdirSync(cwd, {
|
|
||||||
recursive: true,
|
|
||||||
mode: 448
|
|
||||||
});
|
|
||||||
const apiKey = String(connection.apiKey ?? "").trim();
|
|
||||||
const invocation = resolveByteRoverInvocation(command, args, {
|
|
||||||
...process.env,
|
|
||||||
...apiKey === "" ? {} : { BRV_API_KEY: apiKey }
|
|
||||||
}, cwd);
|
|
||||||
const result = await this.process(invocation.command, invocation.args, {
|
|
||||||
timeoutMs,
|
|
||||||
maxOutputBytes: 262144,
|
|
||||||
...signal === void 0 ? {} : { signal },
|
|
||||||
cwd,
|
|
||||||
label: "ByteRover",
|
|
||||||
env: invocation.env
|
|
||||||
});
|
|
||||||
const stdout = result.stdout.trim();
|
|
||||||
const stderr = result.stderr.trim();
|
|
||||||
if (result.exitCode !== 0) throw new Error(stderr || stdout || `ByteRover exited with code ${String(result.exitCode)}`);
|
|
||||||
return stdout;
|
|
||||||
}
|
|
||||||
};
|
|
||||||
// vendor/dsh-mnemon/plugins/dsh-brain-mnemon-provider-byterover/src/index.ts
|
|
||||||
const definition = defineMemorySpaceProviderDefinition({
|
|
||||||
manifest: {
|
|
||||||
apiVersion: MEMORY_SPACE_PROVIDER_API_VERSION,
|
|
||||||
kind: "provider",
|
|
||||||
typeId: descriptor.id,
|
|
||||||
packageName: "dsh-brain-mnemon-provider-byterover",
|
|
||||||
version: "0.5.9",
|
|
||||||
label: descriptor.label,
|
|
||||||
icon: descriptor.icon,
|
|
||||||
summary: descriptor.summary,
|
|
||||||
...descriptor.summaryI18nKey === void 0 ? {} : { summaryI18nKey: descriptor.summaryI18nKey },
|
|
||||||
origin: descriptor.origin,
|
|
||||||
locality: descriptor.kind,
|
|
||||||
workspaceBinding: descriptor.workspaceBinding,
|
|
||||||
capabilities: descriptor.capabilities,
|
|
||||||
fields: descriptor.fields,
|
|
||||||
secrets: descriptor.fields.filter((field) => field.input === "secret").map((field) => field.key),
|
|
||||||
scoreSemantics: "provider-native"
|
|
||||||
},
|
|
||||||
create: (context) => new ByteRoverProvider(context.memorySpaces ?? context.memoryBodies, { queryTimeoutMs: context.config.timeoutMs })
|
|
||||||
});
|
|
||||||
var src_default = defineMemorySpaceProvider({
|
|
||||||
id: descriptor.id,
|
|
||||||
apply(ctx, host) {
|
|
||||||
host.install(ctx, definition);
|
|
||||||
}
|
|
||||||
});
|
|
||||||
export { ByteRoverProvider, src_default as default, definition, descriptor };
|
|
||||||
|
|
@ -1,55 +0,0 @@
|
||||||
{
|
|
||||||
"name": "dsh-brain-mnemon-provider-byterover",
|
|
||||||
"version": "0.5.9",
|
|
||||||
"description": "ByteRover Provider child for the Memory Spaces Source.",
|
|
||||||
"license": "MIT",
|
|
||||||
"type": "module",
|
|
||||||
"engines": {
|
|
||||||
"node": ">=20"
|
|
||||||
},
|
|
||||||
"exports": {
|
|
||||||
".": {
|
|
||||||
"types": "./lib/index.d.ts",
|
|
||||||
"default": "./lib/index.js"
|
|
||||||
},
|
|
||||||
"./descriptor": {
|
|
||||||
"types": "./lib/descriptor.d.ts",
|
|
||||||
"default": "./lib/descriptor.js"
|
|
||||||
},
|
|
||||||
"./package.json": "./package.json"
|
|
||||||
},
|
|
||||||
"files": [
|
|
||||||
"lib",
|
|
||||||
"README.md"
|
|
||||||
],
|
|
||||||
"scripts": {
|
|
||||||
"typecheck": "tsc --noEmit",
|
|
||||||
"build": "tsdown",
|
|
||||||
"test": "vitest run",
|
|
||||||
"verify": "pnpm typecheck && pnpm test && pnpm build"
|
|
||||||
},
|
|
||||||
"peerDependencies": {
|
|
||||||
"@deepseek-ai/cordis": "^4.0.1",
|
|
||||||
"dsh-brain-mnemon-source-memory-spaces": "^0.5.1"
|
|
||||||
},
|
|
||||||
"devDependencies": {
|
|
||||||
"@types/node": "^22.0.0",
|
|
||||||
"dsh-brain-mnemon-source-memory-spaces": "^0.5.33",
|
|
||||||
"tsdown": "^0.22.0",
|
|
||||||
"typescript": "^5.9.0",
|
|
||||||
"vitest": "^3.2.0"
|
|
||||||
},
|
|
||||||
"publishConfig": {
|
|
||||||
"access": "public",
|
|
||||||
"tag": "latest"
|
|
||||||
},
|
|
||||||
"repository": {
|
|
||||||
"type": "git",
|
|
||||||
"url": "git+https://github.com/omdsh-dev/dsh-mnemon.git",
|
|
||||||
"directory": "plugins/dsh-brain-mnemon-provider-byterover"
|
|
||||||
},
|
|
||||||
"homepage": "https://github.com/omdsh-dev/dsh-mnemon/tree/main/plugins/dsh-brain-mnemon-provider-byterover#readme",
|
|
||||||
"bugs": {
|
|
||||||
"url": "https://github.com/omdsh-dev/dsh-mnemon/issues"
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
@ -1,4 +0,0 @@
|
||||||
import { ct as MemoryProviderDescriptor } from "../../../lib/contracts-DuGgDm58.js";
|
|
||||||
import "../../source-memory-spaces/lib/provider-sdk.js";
|
|
||||||
declare const descriptor: MemoryProviderDescriptor;
|
|
||||||
export { descriptor };
|
|
||||||
|
|
@ -1 +0,0 @@
|
||||||
export { t as descriptor } from "../../../lib/descriptor-BBhLI7C8.js";
|
|
||||||
|
|
@ -1,25 +0,0 @@
|
||||||
import { a as MemoryJsonValue } from "../../../lib/index-3Wnpy9oQ.js";
|
|
||||||
import { $t as SearchRequest, J as MemoryGraphSnapshot, Jt as RememberRequest, L as MemoryBody, Y as MemoryListRequest, w as Insight, y as EdgeType } from "../../../lib/contracts-DuGgDm58.js";
|
|
||||||
import { C as ProviderSearchResult, f as MemoryProviderAdapter, h as MemorySpaceAuthority, n as MemorySpaceProviderDefinition, s as MemorySpaceProviderModule, x as ProviderMemorySpace, y as ProviderBodyStatus } from "../../../lib/definitions-C41Daez1.js";
|
|
||||||
import { HttpMemoryProvider, HttpProviderOptions } from "../../source-memory-spaces/lib/provider-sdk.js";
|
|
||||||
import { descriptor } from "./descriptor.js";
|
|
||||||
declare class HindsightProvider extends HttpMemoryProvider implements MemoryProviderAdapter {
|
|
||||||
readonly id: "hindsight";
|
|
||||||
readonly scoreSemantics: Readonly<{
|
|
||||||
kind: "provider-native";
|
|
||||||
}>;
|
|
||||||
constructor(memorySpaces: MemorySpaceAuthority, options?: HttpProviderOptions);
|
|
||||||
discover(connection: Record<string, string | number | boolean>, signal?: AbortSignal): Promise<ProviderMemorySpace[]>;
|
|
||||||
status(body: MemoryBody, signal?: AbortSignal): Promise<ProviderBodyStatus>;
|
|
||||||
search(body: MemoryBody, request: SearchRequest, signal?: AbortSignal): Promise<ProviderSearchResult>;
|
|
||||||
list(body: MemoryBody, request: MemoryListRequest, signal?: AbortSignal): Promise<Insight[]>;
|
|
||||||
graph(body: MemoryBody, signal?: AbortSignal): Promise<MemoryGraphSnapshot>;
|
|
||||||
related(body: MemoryBody, id: string, depth: number, _edge?: EdgeType, signal?: AbortSignal): Promise<Insight[]>;
|
|
||||||
remember(body: MemoryBody, request: RememberRequest, signal?: AbortSignal): Promise<MemoryJsonValue>;
|
|
||||||
forget(body: MemoryBody, id: string, signal?: AbortSignal): Promise<MemoryJsonValue>;
|
|
||||||
private bankPath;
|
|
||||||
private headers;
|
|
||||||
}
|
|
||||||
declare const definition: MemorySpaceProviderDefinition;
|
|
||||||
declare const _default: MemorySpaceProviderModule<undefined>;
|
|
||||||
export { HindsightProvider, _default as default, definition, descriptor };
|
|
||||||
|
|
@ -1,283 +0,0 @@
|
||||||
import { i as defineMemorySpaceProviderDefinition, r as defineMemorySpaceProvider, t as MEMORY_SPACE_PROVIDER_API_VERSION } from "../../../lib/definitions-Du9KQuKM.js";
|
|
||||||
import { HttpMemoryProvider, firstArray, jsonArray, jsonNumber, jsonObject, jsonString } from "../../source-memory-spaces/lib/provider-sdk.js";
|
|
||||||
import { t as descriptor } from "../../../lib/descriptor-BBhLI7C8.js";
|
|
||||||
import { randomUUID } from "node:crypto";
|
|
||||||
// vendor/dsh-mnemon/plugins/dsh-brain-mnemon-provider-hindsight/src/driver.ts
|
|
||||||
function withoutTrailingNote(entry) {
|
|
||||||
const trimmed = entry.trimEnd();
|
|
||||||
if (!trimmed.endsWith(")")) return entry.trim();
|
|
||||||
const close = trimmed.length - 1;
|
|
||||||
const open = trimmed.indexOf("(", trimmed.lastIndexOf(")", close - 1) + 1);
|
|
||||||
return open < 0 || open >= close ? entry.trim() : trimmed.slice(0, open).trim();
|
|
||||||
}
|
|
||||||
function insight(value) {
|
|
||||||
const item = jsonObject(value);
|
|
||||||
const id = jsonString(item?.id);
|
|
||||||
const content = jsonString(item?.text) ?? jsonString(item?.content) ?? jsonString(item?.label);
|
|
||||||
if (id === void 0 || content === void 0) return void 0;
|
|
||||||
const scores = jsonObject(item?.scores);
|
|
||||||
const score = jsonNumber(scores?.final) ?? jsonNumber(item?.score);
|
|
||||||
const createdAt = jsonString(item?.mentioned_at) ?? jsonString(item?.date) ?? jsonString(item?.occurred_start);
|
|
||||||
const rawEntities = item?.entities;
|
|
||||||
const entities = Array.isArray(rawEntities) ? rawEntities.filter((entry) => typeof entry === "string") : typeof rawEntities === "string" ? rawEntities.split(",").map(withoutTrailingNote).filter(Boolean) : [];
|
|
||||||
const tags = jsonArray(item?.tags).filter((entry) => typeof entry === "string");
|
|
||||||
return {
|
|
||||||
id,
|
|
||||||
content,
|
|
||||||
category: jsonString(item?.type) ?? jsonString(item?.fact_type) ?? "general",
|
|
||||||
source: "external",
|
|
||||||
...score === void 0 ? {} : { score },
|
|
||||||
...createdAt === void 0 ? {} : { createdAt },
|
|
||||||
...entities.length === 0 ? {} : { entities },
|
|
||||||
...tags.length === 0 ? {} : { tags }
|
|
||||||
};
|
|
||||||
}
|
|
||||||
function edgeType(value) {
|
|
||||||
return value === "temporal" || value === "semantic" || value === "causal" || value === "entity" ? value : void 0;
|
|
||||||
}
|
|
||||||
var HindsightProvider = class extends HttpMemoryProvider {
|
|
||||||
id = "hindsight";
|
|
||||||
scoreSemantics = Object.freeze({ kind: "provider-native" });
|
|
||||||
constructor(memorySpaces, options = {}) {
|
|
||||||
super(memorySpaces, {
|
|
||||||
label: descriptor.label,
|
|
||||||
...options
|
|
||||||
});
|
|
||||||
}
|
|
||||||
async discover(connection, signal) {
|
|
||||||
const payload = await this.requestConnection(connection, "/v1/default/banks", {
|
|
||||||
headers: this.headers(connection),
|
|
||||||
signal
|
|
||||||
});
|
|
||||||
return firstArray(payload, "banks", "items").flatMap((value) => {
|
|
||||||
const item = jsonObject(value);
|
|
||||||
const id = jsonString(item?.bank_id) ?? jsonString(item?.id);
|
|
||||||
if (id === void 0) return [];
|
|
||||||
const description = jsonString(item?.mission)?.trim() || jsonString(item?.description)?.trim() || `Hindsight memory bank ${id}`;
|
|
||||||
return [{
|
|
||||||
externalId: id,
|
|
||||||
name: jsonString(item?.name) ?? id,
|
|
||||||
description,
|
|
||||||
connection: {
|
|
||||||
bankId: id,
|
|
||||||
budget: "mid"
|
|
||||||
}
|
|
||||||
}];
|
|
||||||
});
|
|
||||||
}
|
|
||||||
async status(body, signal) {
|
|
||||||
try {
|
|
||||||
const connection = this.connection(body);
|
|
||||||
await this.request(body, "/health/live", {
|
|
||||||
headers: this.headers(connection),
|
|
||||||
signal
|
|
||||||
});
|
|
||||||
try {
|
|
||||||
const [statsPayload, entitiesPayload] = await Promise.all([this.request(body, `${this.bankPath(connection)}/stats`, {
|
|
||||||
headers: this.headers(connection),
|
|
||||||
signal
|
|
||||||
}), this.request(body, `${this.bankPath(connection)}/entities?limit=100&offset=0`, {
|
|
||||||
headers: this.headers(connection),
|
|
||||||
signal
|
|
||||||
})]);
|
|
||||||
const stats = jsonObject(statsPayload) ?? {};
|
|
||||||
const byFactType = jsonObject(stats.nodes_by_fact_type) ?? {};
|
|
||||||
const byCategory = Object.fromEntries(Object.entries(byFactType).flatMap(([category, count]) => {
|
|
||||||
const value = jsonNumber(count);
|
|
||||||
return value === void 0 ? [] : [[category, value]];
|
|
||||||
}));
|
|
||||||
const operations = jsonObject(stats.operations_by_status) ?? {};
|
|
||||||
const topEntities = firstArray(entitiesPayload, "items").flatMap((value) => {
|
|
||||||
const item = jsonObject(value);
|
|
||||||
const entity = jsonString(item?.canonical_name);
|
|
||||||
const count = jsonNumber(item?.mention_count);
|
|
||||||
return entity === void 0 || count === void 0 ? [] : [{
|
|
||||||
entity,
|
|
||||||
count
|
|
||||||
}];
|
|
||||||
});
|
|
||||||
return {
|
|
||||||
healthy: true,
|
|
||||||
stats: {
|
|
||||||
totalInsights: jsonNumber(stats.total_nodes) ?? 0,
|
|
||||||
deletedInsights: 0,
|
|
||||||
edgeCount: jsonNumber(stats.total_links) ?? 0,
|
|
||||||
oplogCount: Object.values(operations).reduce((total, value) => total + (jsonNumber(value) ?? 0), 0),
|
|
||||||
dbSizeBytes: 0,
|
|
||||||
byCategory,
|
|
||||||
topEntities
|
|
||||||
}
|
|
||||||
};
|
|
||||||
} catch {
|
|
||||||
return { healthy: true };
|
|
||||||
}
|
|
||||||
} catch (error) {
|
|
||||||
return {
|
|
||||||
healthy: false,
|
|
||||||
error: error instanceof Error ? error.message : String(error)
|
|
||||||
};
|
|
||||||
}
|
|
||||||
}
|
|
||||||
async search(body, request, signal) {
|
|
||||||
const connection = this.connection(body);
|
|
||||||
const payload = await this.request(body, `${this.bankPath(connection)}/memories/recall`, {
|
|
||||||
headers: this.headers(connection),
|
|
||||||
json: {
|
|
||||||
query: request.query,
|
|
||||||
budget: String(connection.budget ?? "mid"),
|
|
||||||
max_tokens: Math.min(Math.max((request.limit ?? 10) * 400, 400), 8e3),
|
|
||||||
types: [
|
|
||||||
"world",
|
|
||||||
"experience",
|
|
||||||
"observation"
|
|
||||||
],
|
|
||||||
prefer_observations: true
|
|
||||||
},
|
|
||||||
signal
|
|
||||||
});
|
|
||||||
return { results: firstArray(payload, "results", "items").map(insight).filter((item) => item !== void 0).slice(0, request.limit ?? 10) };
|
|
||||||
}
|
|
||||||
async list(body, request, signal) {
|
|
||||||
const connection = this.connection(body);
|
|
||||||
const params = new URLSearchParams({
|
|
||||||
limit: String(Math.min(Math.max(request.limit ?? 200, 1), 1e3)),
|
|
||||||
offset: "0",
|
|
||||||
state: "valid"
|
|
||||||
});
|
|
||||||
if (request.query !== void 0 && request.query.trim() !== "") params.set("q", request.query.trim());
|
|
||||||
const payload = await this.request(body, `${this.bankPath(connection)}/memories/list?${params}`, {
|
|
||||||
headers: this.headers(connection),
|
|
||||||
signal
|
|
||||||
});
|
|
||||||
return firstArray(payload, "items", "results").map(insight).filter((item) => item !== void 0).filter((item) => request.category === void 0 || item.category === request.category);
|
|
||||||
}
|
|
||||||
async graph(body, signal) {
|
|
||||||
const connection = this.connection(body);
|
|
||||||
const payload = jsonObject(await this.request(body, `${this.bankPath(connection)}/graph?limit=1000`, {
|
|
||||||
headers: this.headers(connection),
|
|
||||||
signal
|
|
||||||
})) ?? {};
|
|
||||||
return {
|
|
||||||
nodes: jsonArray(payload.nodes).flatMap((value) => {
|
|
||||||
const item = jsonObject(value);
|
|
||||||
const data = jsonObject(item?.data) ?? item;
|
|
||||||
const projected = insight(data);
|
|
||||||
return projected === void 0 ? [] : [{
|
|
||||||
...projected,
|
|
||||||
color: jsonString(data?.color) ?? "#6574d9"
|
|
||||||
}];
|
|
||||||
}),
|
|
||||||
edges: jsonArray(payload.edges).flatMap((value) => {
|
|
||||||
const item = jsonObject(value);
|
|
||||||
const data = jsonObject(item?.data) ?? item;
|
|
||||||
const sourceId = jsonString(data?.from) ?? jsonString(data?.source);
|
|
||||||
const targetId = jsonString(data?.to) ?? jsonString(data?.target);
|
|
||||||
if (sourceId === void 0 || targetId === void 0) return [];
|
|
||||||
const rawType = jsonString(data?.type) ?? jsonString(data?.linkType);
|
|
||||||
const type = edgeType(rawType);
|
|
||||||
return [{
|
|
||||||
sourceId,
|
|
||||||
targetId,
|
|
||||||
label: rawType ?? "related",
|
|
||||||
color: type === "causal" ? "#e74c3c" : type === "entity" ? "#2ecc71" : type === "temporal" ? "#aaaaaa" : "#3498db",
|
|
||||||
...type === void 0 ? {} : { type }
|
|
||||||
}];
|
|
||||||
}),
|
|
||||||
generatedAt: (/* @__PURE__ */ new Date()).toISOString()
|
|
||||||
};
|
|
||||||
}
|
|
||||||
async related(body, id, depth, _edge, signal) {
|
|
||||||
const graph = await this.graph(body, signal);
|
|
||||||
let frontier = /* @__PURE__ */ new Set([id]);
|
|
||||||
const visited = /* @__PURE__ */ new Set([id]);
|
|
||||||
for (let level = 0; level < depth; level += 1) {
|
|
||||||
const next = /* @__PURE__ */ new Set();
|
|
||||||
for (const edge of graph.edges) {
|
|
||||||
if (frontier.has(edge.sourceId) && !visited.has(edge.targetId)) next.add(edge.targetId);
|
|
||||||
if (frontier.has(edge.targetId) && !visited.has(edge.sourceId)) next.add(edge.sourceId);
|
|
||||||
}
|
|
||||||
for (const value of next) visited.add(value);
|
|
||||||
frontier = next;
|
|
||||||
}
|
|
||||||
return graph.nodes.filter((node) => node.id !== id && visited.has(node.id)).map(({ color: _color, ...node }) => node);
|
|
||||||
}
|
|
||||||
async remember(body, request, signal) {
|
|
||||||
const connection = this.connection(body);
|
|
||||||
const operationId = randomUUID();
|
|
||||||
const payload = jsonObject(await this.request(body, `${this.bankPath(connection)}/memories`, {
|
|
||||||
headers: this.headers(connection),
|
|
||||||
json: {
|
|
||||||
items: [{
|
|
||||||
content: request.content,
|
|
||||||
context: request.category ?? "dsh-brain-mnemon",
|
|
||||||
metadata: { source: "dsh-brain-mnemon" },
|
|
||||||
...request.tags === void 0 ? {} : { tags: request.tags },
|
|
||||||
...request.entities === void 0 ? {} : { entities: request.entities.map((text) => ({ text })) }
|
|
||||||
}],
|
|
||||||
async: true,
|
|
||||||
operation_id: operationId
|
|
||||||
},
|
|
||||||
signal
|
|
||||||
})) ?? {};
|
|
||||||
return {
|
|
||||||
action: "queued",
|
|
||||||
provider: this.id,
|
|
||||||
summary: "Hindsight queued the content for structured memory extraction.",
|
|
||||||
operationId: jsonString(payload.operation_id) ?? operationId,
|
|
||||||
...jsonNumber(payload.items_count) === void 0 ? {} : { itemsCount: jsonNumber(payload.items_count) }
|
|
||||||
};
|
|
||||||
}
|
|
||||||
async forget(body, id, signal) {
|
|
||||||
const connection = this.connection(body);
|
|
||||||
await this.request(body, `${this.bankPath(connection)}/memories/${encodeURIComponent(id)}`, {
|
|
||||||
method: "PATCH",
|
|
||||||
headers: this.headers(connection),
|
|
||||||
json: {
|
|
||||||
state: "invalidated",
|
|
||||||
reason: "Forgotten from dsh-brain-mnemon"
|
|
||||||
},
|
|
||||||
signal
|
|
||||||
});
|
|
||||||
return {
|
|
||||||
action: "invalidated",
|
|
||||||
provider: this.id,
|
|
||||||
id
|
|
||||||
};
|
|
||||||
}
|
|
||||||
bankPath(connection) {
|
|
||||||
return `/v1/default/banks/${encodeURIComponent(String(connection.bankId))}`;
|
|
||||||
}
|
|
||||||
headers(connection) {
|
|
||||||
const token = String(connection.apiKey ?? "").replace(/^Bearer\s+/iu, "");
|
|
||||||
return token === "" ? {} : { Authorization: `Bearer ${token}` };
|
|
||||||
}
|
|
||||||
};
|
|
||||||
// vendor/dsh-mnemon/plugins/dsh-brain-mnemon-provider-hindsight/src/index.ts
|
|
||||||
const definition = defineMemorySpaceProviderDefinition({
|
|
||||||
manifest: {
|
|
||||||
apiVersion: MEMORY_SPACE_PROVIDER_API_VERSION,
|
|
||||||
kind: "provider",
|
|
||||||
typeId: descriptor.id,
|
|
||||||
packageName: "dsh-brain-mnemon-provider-hindsight",
|
|
||||||
version: "0.5.8",
|
|
||||||
label: descriptor.label,
|
|
||||||
icon: descriptor.icon,
|
|
||||||
summary: descriptor.summary,
|
|
||||||
...descriptor.summaryI18nKey === void 0 ? {} : { summaryI18nKey: descriptor.summaryI18nKey },
|
|
||||||
origin: descriptor.origin,
|
|
||||||
locality: descriptor.kind,
|
|
||||||
workspaceBinding: descriptor.workspaceBinding,
|
|
||||||
capabilities: descriptor.capabilities,
|
|
||||||
fields: descriptor.fields,
|
|
||||||
secrets: descriptor.fields.filter((field) => field.input === "secret").map((field) => field.key),
|
|
||||||
scoreSemantics: "provider-native"
|
|
||||||
},
|
|
||||||
create: (context) => new HindsightProvider(context.memorySpaces ?? context.memoryBodies, { requestTimeoutMs: context.config.timeoutMs })
|
|
||||||
});
|
|
||||||
var src_default = defineMemorySpaceProvider({
|
|
||||||
id: descriptor.id,
|
|
||||||
apply(ctx, host) {
|
|
||||||
host.install(ctx, definition);
|
|
||||||
}
|
|
||||||
});
|
|
||||||
export { HindsightProvider, src_default as default, definition, descriptor };
|
|
||||||
|
|
@ -1,55 +0,0 @@
|
||||||
{
|
|
||||||
"name": "dsh-brain-mnemon-provider-hindsight",
|
|
||||||
"version": "0.5.8",
|
|
||||||
"description": "Hindsight Provider child for the Memory Spaces Source.",
|
|
||||||
"license": "MIT",
|
|
||||||
"type": "module",
|
|
||||||
"engines": {
|
|
||||||
"node": ">=20"
|
|
||||||
},
|
|
||||||
"exports": {
|
|
||||||
".": {
|
|
||||||
"types": "./lib/index.d.ts",
|
|
||||||
"default": "./lib/index.js"
|
|
||||||
},
|
|
||||||
"./descriptor": {
|
|
||||||
"types": "./lib/descriptor.d.ts",
|
|
||||||
"default": "./lib/descriptor.js"
|
|
||||||
},
|
|
||||||
"./package.json": "./package.json"
|
|
||||||
},
|
|
||||||
"files": [
|
|
||||||
"lib",
|
|
||||||
"README.md"
|
|
||||||
],
|
|
||||||
"scripts": {
|
|
||||||
"typecheck": "tsc --noEmit",
|
|
||||||
"build": "tsdown",
|
|
||||||
"test": "vitest run",
|
|
||||||
"verify": "pnpm typecheck && pnpm test && pnpm build"
|
|
||||||
},
|
|
||||||
"peerDependencies": {
|
|
||||||
"@deepseek-ai/cordis": "^4.0.1",
|
|
||||||
"dsh-brain-mnemon-source-memory-spaces": "^0.5.1"
|
|
||||||
},
|
|
||||||
"devDependencies": {
|
|
||||||
"@types/node": "^22.0.0",
|
|
||||||
"dsh-brain-mnemon-source-memory-spaces": "^0.5.33",
|
|
||||||
"tsdown": "^0.22.0",
|
|
||||||
"typescript": "^5.9.0",
|
|
||||||
"vitest": "^3.2.0"
|
|
||||||
},
|
|
||||||
"publishConfig": {
|
|
||||||
"access": "public",
|
|
||||||
"tag": "latest"
|
|
||||||
},
|
|
||||||
"repository": {
|
|
||||||
"type": "git",
|
|
||||||
"url": "git+https://github.com/omdsh-dev/dsh-mnemon.git",
|
|
||||||
"directory": "plugins/dsh-brain-mnemon-provider-hindsight"
|
|
||||||
},
|
|
||||||
"homepage": "https://github.com/omdsh-dev/dsh-mnemon/tree/main/plugins/dsh-brain-mnemon-provider-hindsight#readme",
|
|
||||||
"bugs": {
|
|
||||||
"url": "https://github.com/omdsh-dev/dsh-mnemon/issues"
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
@ -1,4 +0,0 @@
|
||||||
import { ct as MemoryProviderDescriptor } from "../../../lib/contracts-DuGgDm58.js";
|
|
||||||
import "../../source-memory-spaces/lib/provider-sdk.js";
|
|
||||||
declare const descriptor: MemoryProviderDescriptor;
|
|
||||||
export { descriptor };
|
|
||||||
|
|
@ -1 +0,0 @@
|
||||||
export { t as descriptor } from "../../../lib/descriptor-Bo7K54GN.js";
|
|
||||||
|
|
@ -1,28 +0,0 @@
|
||||||
import { a as MemoryJsonValue } from "../../../lib/index-3Wnpy9oQ.js";
|
|
||||||
import { $t as SearchRequest, J as MemoryGraphSnapshot, Jt as RememberRequest, L as MemoryBody, Y as MemoryListRequest, ot as MemoryProviderConnection, w as Insight } from "../../../lib/contracts-DuGgDm58.js";
|
|
||||||
import { C as ProviderSearchResult, S as ProviderScoreSemantics, f as MemoryProviderAdapter, h as MemorySpaceAuthority, n as MemorySpaceProviderDefinition, s as MemorySpaceProviderModule, x as ProviderMemorySpace, y as ProviderBodyStatus } from "../../../lib/definitions-C41Daez1.js";
|
|
||||||
import "../../source-memory-spaces/lib/provider-sdk.js";
|
|
||||||
import { descriptor } from "./descriptor.js";
|
|
||||||
declare class HolographicProvider implements MemoryProviderAdapter {
|
|
||||||
private readonly memorySpaces;
|
|
||||||
readonly id: "holographic";
|
|
||||||
readonly scoreSemantics: ProviderScoreSemantics;
|
|
||||||
constructor(memorySpaces: MemorySpaceAuthority);
|
|
||||||
discover(connection: MemoryProviderConnection): Promise<ProviderMemorySpace[]>;
|
|
||||||
status(body: MemoryBody): Promise<ProviderBodyStatus>;
|
|
||||||
search(body: MemoryBody, request: SearchRequest): Promise<ProviderSearchResult>;
|
|
||||||
list(body: MemoryBody, request: MemoryListRequest): Promise<Insight[]>;
|
|
||||||
graph(body: MemoryBody): Promise<MemoryGraphSnapshot>;
|
|
||||||
related(body: MemoryBody, id: string, _depth: number): Promise<Insight[]>;
|
|
||||||
remember(body: MemoryBody, request: RememberRequest): Promise<MemoryJsonValue>;
|
|
||||||
forget(body: MemoryBody, id: string): Promise<MemoryJsonValue>;
|
|
||||||
private connection;
|
|
||||||
private path;
|
|
||||||
private load;
|
|
||||||
private loadFromPath;
|
|
||||||
private save;
|
|
||||||
private stats;
|
|
||||||
}
|
|
||||||
declare const definition: MemorySpaceProviderDefinition;
|
|
||||||
declare const _default: MemorySpaceProviderModule<undefined>;
|
|
||||||
export { HolographicProvider, _default as default, definition, descriptor };
|
|
||||||
|
|
@ -1,335 +0,0 @@
|
||||||
import { t as NORMALIZED_RELEVANCE_SCORE } from "../../../lib/adapter-CF9Q9xOa.js";
|
|
||||||
import { i as defineMemorySpaceProviderDefinition, r as defineMemorySpaceProvider, t as MEMORY_SPACE_PROVIDER_API_VERSION } from "../../../lib/definitions-Du9KQuKM.js";
|
|
||||||
import "../../source-memory-spaces/lib/provider-sdk.js";
|
|
||||||
import { t as descriptor } from "../../../lib/descriptor-Bo7K54GN.js";
|
|
||||||
import { randomUUID } from "node:crypto";
|
|
||||||
import { basename, dirname, isAbsolute, join, resolve } from "node:path";
|
|
||||||
import { chmodSync, existsSync, mkdirSync, readFileSync, renameSync, rmSync, statSync, writeFileSync } from "node:fs";
|
|
||||||
// vendor/dsh-mnemon/plugins/dsh-brain-mnemon-provider-holographic/src/top-scored.ts
|
|
||||||
function topScored(values, limit) {
|
|
||||||
const count = Math.min(values.length, Math.max(0, Math.trunc(limit) || 0));
|
|
||||||
if (count === 0) return [];
|
|
||||||
if (values.length <= Math.max(64, count * 2) || values.some((value) => !Number.isFinite(value.score))) return values.sort((left, right) => right.score - left.score).slice(0, count);
|
|
||||||
const compare = (left, right) => values[right].score - values[left].score || left - right;
|
|
||||||
const heap = [];
|
|
||||||
for (let index = 0; index < values.length; index++) if (heap.length < count) {
|
|
||||||
let child = heap.length;
|
|
||||||
heap.push(index);
|
|
||||||
while (child > 0) {
|
|
||||||
const parent = child - 1 >>> 1;
|
|
||||||
if (compare(heap[parent], index) >= 0) break;
|
|
||||||
heap[child] = heap[parent];
|
|
||||||
child = parent;
|
|
||||||
}
|
|
||||||
heap[child] = index;
|
|
||||||
} else if (compare(index, heap[0]) < 0) {
|
|
||||||
let parent = 0;
|
|
||||||
while (parent * 2 + 1 < count) {
|
|
||||||
let child = parent * 2 + 1;
|
|
||||||
if (child + 1 < count && compare(heap[child + 1], heap[child]) > 0) child += 1;
|
|
||||||
if (compare(index, heap[child]) >= 0) break;
|
|
||||||
heap[parent] = heap[child];
|
|
||||||
parent = child;
|
|
||||||
}
|
|
||||||
heap[parent] = index;
|
|
||||||
}
|
|
||||||
return heap.sort(compare).map((index) => values[index]);
|
|
||||||
}
|
|
||||||
// vendor/dsh-mnemon/plugins/dsh-brain-mnemon-provider-holographic/src/driver.ts
|
|
||||||
const WORD = /[\p{L}\p{N}_-]+/gu;
|
|
||||||
const CJK = /[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Hangul}]+/gu;
|
|
||||||
const HAS_CJK = /[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Hangul}]/u;
|
|
||||||
const QUOTED = /["“”'‘’]([^"“”'‘’]{2,100})["“”'‘’]/gu;
|
|
||||||
const CAPITALIZED = /\b([A-Z][\p{L}\p{N}_-]+(?:\s+[A-Z][\p{L}\p{N}_-]+)*)\b/gu;
|
|
||||||
function clampTrust(value) {
|
|
||||||
return Math.min(1, Math.max(0, value));
|
|
||||||
}
|
|
||||||
function matchesEntity(queryLower, queryWords, rawEntity) {
|
|
||||||
const entity = rawEntity.trim().toLocaleLowerCase();
|
|
||||||
if (entity === "") return false;
|
|
||||||
if (HAS_CJK.test(entity)) return queryLower.includes(entity);
|
|
||||||
const entityWords = entity.match(WORD) ?? [];
|
|
||||||
if (entityWords.length === 0) return queryLower.includes(entity);
|
|
||||||
if (entityWords.length === 1 && entityWords[0] === entity) return queryWords.has(entity);
|
|
||||||
const escaped = entity.replace(/[.*+?^${}()|[\]\\]/gu, "\\$&");
|
|
||||||
return new RegExp(`(?<![\\p{L}\\p{N}_-])${escaped}(?![\\p{L}\\p{N}_-])`, "u").test(queryLower);
|
|
||||||
}
|
|
||||||
function terms(value) {
|
|
||||||
const normalized = value.toLocaleLowerCase();
|
|
||||||
const output = new Set((normalized.match(WORD) ?? []).filter((token) => token.length > 1));
|
|
||||||
for (const run of normalized.match(CJK) ?? []) {
|
|
||||||
for (const character of run) output.add(character);
|
|
||||||
for (let index = 0; index < run.length - 1; index += 1) output.add(run.slice(index, index + 2));
|
|
||||||
}
|
|
||||||
return output;
|
|
||||||
}
|
|
||||||
function overlap(left, right) {
|
|
||||||
if (left.size === 0 || right.size === 0) return 0;
|
|
||||||
let shared = 0;
|
|
||||||
const [smaller, larger] = left.size <= right.size ? [left, right] : [right, left];
|
|
||||||
for (const value of smaller) if (larger.has(value)) shared += 1;
|
|
||||||
return shared / (left.size + right.size - shared);
|
|
||||||
}
|
|
||||||
function extractEntities(content, supplied = []) {
|
|
||||||
const values = [...supplied];
|
|
||||||
for (const match of content.matchAll(QUOTED)) values.push(match[1]);
|
|
||||||
for (const match of content.matchAll(CAPITALIZED)) values.push(match[1]);
|
|
||||||
return [...new Set(values.map((value) => value.trim()).filter((value) => value.length >= 2 && value.length <= 100))].slice(0, 50);
|
|
||||||
}
|
|
||||||
function insight(fact, score) {
|
|
||||||
return {
|
|
||||||
id: fact.id,
|
|
||||||
content: fact.content,
|
|
||||||
category: fact.category,
|
|
||||||
...fact.importance === void 0 ? {} : { importance: fact.importance },
|
|
||||||
tags: fact.tags,
|
|
||||||
entities: fact.entities,
|
|
||||||
source: "external",
|
|
||||||
createdAt: fact.createdAt,
|
|
||||||
...score === void 0 ? {} : { score }
|
|
||||||
};
|
|
||||||
}
|
|
||||||
var HolographicProvider = class {
|
|
||||||
memorySpaces;
|
|
||||||
id = "holographic";
|
|
||||||
scoreSemantics = NORMALIZED_RELEVANCE_SCORE;
|
|
||||||
constructor(memorySpaces) {
|
|
||||||
this.memorySpaces = memorySpaces;
|
|
||||||
}
|
|
||||||
async discover(connection) {
|
|
||||||
const configured = String(connection.dataPath ?? "").trim();
|
|
||||||
const path = configured === "" ? join(this.memorySpaces.runner.effectiveDataDir(), "state", "holographic", "store.json") : isAbsolute(configured) ? configured : resolve(this.memorySpaces.runner.effectiveDataDir(), configured);
|
|
||||||
const label = basename(path).replace(/\.json$/iu, "") || "Holographic";
|
|
||||||
return [{
|
|
||||||
externalId: path,
|
|
||||||
name: label === "store" ? "Holographic" : label,
|
|
||||||
description: `Holographic fact store at ${path}`,
|
|
||||||
connection: {
|
|
||||||
defaultTrust: .5,
|
|
||||||
minTrust: .3
|
|
||||||
}
|
|
||||||
}];
|
|
||||||
}
|
|
||||||
async status(body) {
|
|
||||||
try {
|
|
||||||
const path = this.path(body);
|
|
||||||
const store = this.loadFromPath(path);
|
|
||||||
return {
|
|
||||||
healthy: true,
|
|
||||||
stats: this.stats(store, path)
|
|
||||||
};
|
|
||||||
} catch (error) {
|
|
||||||
return {
|
|
||||||
healthy: false,
|
|
||||||
error: error instanceof Error ? error.message : String(error)
|
|
||||||
};
|
|
||||||
}
|
|
||||||
}
|
|
||||||
async search(body, request) {
|
|
||||||
const store = this.load(body);
|
|
||||||
const connection = this.connection(body);
|
|
||||||
const minTrust = clampTrust(Number(connection.minTrust ?? .3));
|
|
||||||
const queryTerms = terms(request.query);
|
|
||||||
const query = request.query.toLocaleLowerCase();
|
|
||||||
const queryWords = new Set(query.match(WORD) ?? []);
|
|
||||||
const limit = Math.min(Math.max(request.limit ?? 10, 1), 50);
|
|
||||||
return { results: topScored(store.facts.flatMap((fact) => {
|
|
||||||
if (fact.trustScore < minTrust || request.category !== void 0 && fact.category !== request.category) return [];
|
|
||||||
const lexical = overlap(queryTerms, terms(`${fact.content} ${fact.tags.join(" ")} ${fact.entities.join(" ")}`));
|
|
||||||
const phrase = fact.content.toLocaleLowerCase().includes(query) ? 1 : 0;
|
|
||||||
const entity = fact.entities.some((value) => matchesEntity(query, queryWords, value)) ? 1 : 0;
|
|
||||||
const relevance = Math.max(lexical, phrase * .9, entity * .8);
|
|
||||||
return relevance <= 0 ? [] : [{
|
|
||||||
fact,
|
|
||||||
score: relevance * fact.trustScore
|
|
||||||
}];
|
|
||||||
}), limit).map((result) => insight(result.fact, result.score)) };
|
|
||||||
}
|
|
||||||
async list(body, request) {
|
|
||||||
if (request.query !== void 0 && request.query.trim() !== "") return (await this.search(body, {
|
|
||||||
query: request.query,
|
|
||||||
...request.category === void 0 ? {} : { category: request.category },
|
|
||||||
...request.limit === void 0 ? {} : { limit: request.limit }
|
|
||||||
})).results;
|
|
||||||
const store = this.load(body);
|
|
||||||
const minTrust = clampTrust(Number(this.connection(body).minTrust ?? .3));
|
|
||||||
return store.facts.filter((fact) => fact.trustScore >= minTrust && (request.category === void 0 || fact.category === request.category)).sort((left, right) => right.updatedAt.localeCompare(left.updatedAt)).slice(0, Math.min(Math.max(request.limit ?? 200, 1), 1e3)).map((fact) => insight(fact));
|
|
||||||
}
|
|
||||||
async graph(body) {
|
|
||||||
const facts = await this.list(body, { limit: 500 });
|
|
||||||
const entities = [...new Set(facts.flatMap((fact) => fact.entities ?? []))];
|
|
||||||
return {
|
|
||||||
nodes: [...facts.map((fact) => ({
|
|
||||||
...fact,
|
|
||||||
color: "#6574d9",
|
|
||||||
kind: "memory"
|
|
||||||
})), ...entities.map((entity) => ({
|
|
||||||
id: `entity:${encodeURIComponent(entity)}`,
|
|
||||||
content: entity,
|
|
||||||
color: "#2ecc71",
|
|
||||||
kind: "entity"
|
|
||||||
}))],
|
|
||||||
edges: facts.flatMap((fact) => (fact.entities ?? []).map((entity) => ({
|
|
||||||
sourceId: fact.id,
|
|
||||||
targetId: `entity:${encodeURIComponent(entity)}`,
|
|
||||||
label: "entity",
|
|
||||||
color: "#2ecc71",
|
|
||||||
type: "entity"
|
|
||||||
}))),
|
|
||||||
generatedAt: (/* @__PURE__ */ new Date()).toISOString()
|
|
||||||
};
|
|
||||||
}
|
|
||||||
async related(body, id, _depth) {
|
|
||||||
const store = this.load(body);
|
|
||||||
const source = store.facts.find((fact) => fact.id === id);
|
|
||||||
if (source === void 0) return [];
|
|
||||||
const sourceEntities = new Set(source.entities.map((value) => value.toLocaleLowerCase()));
|
|
||||||
const sourceTerms = terms(source.content);
|
|
||||||
const minTrust = clampTrust(Number(this.connection(body).minTrust ?? .3));
|
|
||||||
return topScored(store.facts.flatMap((fact) => {
|
|
||||||
if (fact.id === id || fact.trustScore < minTrust) return [];
|
|
||||||
const sharedEntities = fact.entities.filter((value) => sourceEntities.has(value.toLocaleLowerCase())).length;
|
|
||||||
const score = Math.max(sharedEntities === 0 ? 0 : Math.min(1, .5 + sharedEntities * .2), overlap(sourceTerms, terms(fact.content))) * fact.trustScore;
|
|
||||||
return score <= 0 ? [] : [{
|
|
||||||
fact,
|
|
||||||
score
|
|
||||||
}];
|
|
||||||
}), 20).map((result) => insight(result.fact, result.score));
|
|
||||||
}
|
|
||||||
async remember(body, request) {
|
|
||||||
if (request.importance !== void 0 && (!Number.isInteger(request.importance) || request.importance < 1 || request.importance > 5)) throw new Error("importance must be an integer from 1 through 5");
|
|
||||||
const store = this.load(body);
|
|
||||||
const existing = store.facts.find((fact) => fact.content === request.content.trim());
|
|
||||||
if (existing !== void 0) return {
|
|
||||||
action: "skipped",
|
|
||||||
provider: this.id,
|
|
||||||
id: existing.id,
|
|
||||||
content: existing.content,
|
|
||||||
summary: "Holographic already contains this fact."
|
|
||||||
};
|
|
||||||
const now = (/* @__PURE__ */ new Date()).toISOString();
|
|
||||||
const connection = this.connection(body);
|
|
||||||
const fact = {
|
|
||||||
id: `holo-${randomUUID()}`,
|
|
||||||
content: request.content.trim(),
|
|
||||||
category: request.category ?? "general",
|
|
||||||
tags: [...new Set(request.tags ?? [])],
|
|
||||||
entities: extractEntities(request.content, request.entities),
|
|
||||||
trustScore: request.importance === void 0 ? clampTrust(Number(connection.defaultTrust ?? .5)) : request.importance / 5,
|
|
||||||
importance: request.importance ?? 3,
|
|
||||||
createdAt: now,
|
|
||||||
updatedAt: now
|
|
||||||
};
|
|
||||||
store.facts.push(fact);
|
|
||||||
this.save(body, store);
|
|
||||||
return {
|
|
||||||
action: "stored",
|
|
||||||
provider: this.id,
|
|
||||||
id: fact.id,
|
|
||||||
summary: "Holographic stored the structured fact."
|
|
||||||
};
|
|
||||||
}
|
|
||||||
async forget(body, id) {
|
|
||||||
const store = this.load(body);
|
|
||||||
const before = store.facts.length;
|
|
||||||
store.facts = store.facts.filter((fact) => fact.id !== id);
|
|
||||||
if (store.facts.length === before) throw new Error(`unknown Holographic fact: ${id}`);
|
|
||||||
this.save(body, store);
|
|
||||||
return {
|
|
||||||
action: "deleted",
|
|
||||||
provider: this.id,
|
|
||||||
id
|
|
||||||
};
|
|
||||||
}
|
|
||||||
connection(body) {
|
|
||||||
if ((body.provider.typeId ?? body.provider.id) !== this.id) throw new Error(`Holographic cannot serve provider ${body.provider.id}`);
|
|
||||||
return this.memorySpaces.providerConnection(body.id, body.provider.id);
|
|
||||||
}
|
|
||||||
path(body) {
|
|
||||||
const configured = String(this.connection(body).dataPath ?? "").trim();
|
|
||||||
if (configured === "") return join(this.memorySpaces.runner.effectiveDataDir(), "state", "holographic", "store.json");
|
|
||||||
return isAbsolute(configured) ? configured : resolve(this.memorySpaces.runner.effectiveDataDir(), configured);
|
|
||||||
}
|
|
||||||
load(body) {
|
|
||||||
return this.loadFromPath(this.path(body));
|
|
||||||
}
|
|
||||||
loadFromPath(path) {
|
|
||||||
if (!existsSync(path)) return {
|
|
||||||
version: 1,
|
|
||||||
facts: []
|
|
||||||
};
|
|
||||||
const value = JSON.parse(readFileSync(path, "utf8"));
|
|
||||||
if (value.version !== 1 || !Array.isArray(value.facts)) throw new Error(`invalid Holographic fact store: ${path}`);
|
|
||||||
return {
|
|
||||||
version: 1,
|
|
||||||
facts: value.facts
|
|
||||||
};
|
|
||||||
}
|
|
||||||
save(body, store) {
|
|
||||||
const path = this.path(body);
|
|
||||||
mkdirSync(dirname(path), {
|
|
||||||
recursive: true,
|
|
||||||
mode: 448
|
|
||||||
});
|
|
||||||
const temporary = `${path}.${process.pid}.${randomUUID()}.tmp`;
|
|
||||||
try {
|
|
||||||
writeFileSync(temporary, `${JSON.stringify(store, null, 2)}\n`, {
|
|
||||||
encoding: "utf8",
|
|
||||||
mode: 384
|
|
||||||
});
|
|
||||||
renameSync(temporary, path);
|
|
||||||
chmodSync(path, 384);
|
|
||||||
} finally {
|
|
||||||
rmSync(temporary, { force: true });
|
|
||||||
}
|
|
||||||
}
|
|
||||||
stats(store, path) {
|
|
||||||
const byCategory = {};
|
|
||||||
const entityCounts = /* @__PURE__ */ new Map();
|
|
||||||
for (const fact of store.facts) {
|
|
||||||
byCategory[fact.category] = (byCategory[fact.category] ?? 0) + 1;
|
|
||||||
for (const entity of fact.entities) entityCounts.set(entity, (entityCounts.get(entity) ?? 0) + 1);
|
|
||||||
}
|
|
||||||
return {
|
|
||||||
totalInsights: store.facts.length,
|
|
||||||
deletedInsights: 0,
|
|
||||||
edgeCount: store.facts.reduce((total, fact) => total + fact.entities.length, 0),
|
|
||||||
oplogCount: 0,
|
|
||||||
dbSizeBytes: existsSync(path) ? statSync(path).size : 0,
|
|
||||||
byCategory,
|
|
||||||
topEntities: [...entityCounts].map(([entity, count]) => ({
|
|
||||||
entity,
|
|
||||||
count
|
|
||||||
})).sort((left, right) => right.count - left.count).slice(0, 20)
|
|
||||||
};
|
|
||||||
}
|
|
||||||
};
|
|
||||||
// vendor/dsh-mnemon/plugins/dsh-brain-mnemon-provider-holographic/src/index.ts
|
|
||||||
const definition = defineMemorySpaceProviderDefinition({
|
|
||||||
manifest: {
|
|
||||||
apiVersion: MEMORY_SPACE_PROVIDER_API_VERSION,
|
|
||||||
kind: "provider",
|
|
||||||
typeId: descriptor.id,
|
|
||||||
packageName: "dsh-brain-mnemon-provider-holographic",
|
|
||||||
version: "0.5.9",
|
|
||||||
label: descriptor.label,
|
|
||||||
icon: descriptor.icon,
|
|
||||||
summary: descriptor.summary,
|
|
||||||
...descriptor.summaryI18nKey === void 0 ? {} : { summaryI18nKey: descriptor.summaryI18nKey },
|
|
||||||
origin: descriptor.origin,
|
|
||||||
locality: descriptor.kind,
|
|
||||||
workspaceBinding: descriptor.workspaceBinding,
|
|
||||||
capabilities: descriptor.capabilities,
|
|
||||||
fields: descriptor.fields,
|
|
||||||
secrets: descriptor.fields.filter((field) => field.input === "secret").map((field) => field.key),
|
|
||||||
scoreSemantics: "normalized-relevance"
|
|
||||||
},
|
|
||||||
create: (context) => new HolographicProvider(context.memorySpaces ?? context.memoryBodies)
|
|
||||||
});
|
|
||||||
var src_default = defineMemorySpaceProvider({
|
|
||||||
id: descriptor.id,
|
|
||||||
apply(ctx, host) {
|
|
||||||
host.install(ctx, definition);
|
|
||||||
}
|
|
||||||
});
|
|
||||||
export { HolographicProvider, src_default as default, definition, descriptor };
|
|
||||||
|
|
@ -1,55 +0,0 @@
|
||||||
{
|
|
||||||
"name": "dsh-brain-mnemon-provider-holographic",
|
|
||||||
"version": "0.5.9",
|
|
||||||
"description": "Holographic Provider child for the Memory Spaces Source.",
|
|
||||||
"license": "MIT",
|
|
||||||
"type": "module",
|
|
||||||
"engines": {
|
|
||||||
"node": ">=20"
|
|
||||||
},
|
|
||||||
"exports": {
|
|
||||||
".": {
|
|
||||||
"types": "./lib/index.d.ts",
|
|
||||||
"default": "./lib/index.js"
|
|
||||||
},
|
|
||||||
"./descriptor": {
|
|
||||||
"types": "./lib/descriptor.d.ts",
|
|
||||||
"default": "./lib/descriptor.js"
|
|
||||||
},
|
|
||||||
"./package.json": "./package.json"
|
|
||||||
},
|
|
||||||
"files": [
|
|
||||||
"lib",
|
|
||||||
"README.md"
|
|
||||||
],
|
|
||||||
"scripts": {
|
|
||||||
"typecheck": "tsc --noEmit",
|
|
||||||
"build": "tsdown",
|
|
||||||
"test": "vitest run",
|
|
||||||
"verify": "pnpm typecheck && pnpm test && pnpm build"
|
|
||||||
},
|
|
||||||
"peerDependencies": {
|
|
||||||
"@deepseek-ai/cordis": "^4.0.1",
|
|
||||||
"dsh-brain-mnemon-source-memory-spaces": "^0.5.1"
|
|
||||||
},
|
|
||||||
"devDependencies": {
|
|
||||||
"@types/node": "^22.0.0",
|
|
||||||
"dsh-brain-mnemon-source-memory-spaces": "^0.5.33",
|
|
||||||
"tsdown": "^0.22.0",
|
|
||||||
"typescript": "^5.9.0",
|
|
||||||
"vitest": "^3.2.0"
|
|
||||||
},
|
|
||||||
"publishConfig": {
|
|
||||||
"access": "public",
|
|
||||||
"tag": "latest"
|
|
||||||
},
|
|
||||||
"repository": {
|
|
||||||
"type": "git",
|
|
||||||
"url": "git+https://github.com/omdsh-dev/dsh-mnemon.git",
|
|
||||||
"directory": "plugins/dsh-brain-mnemon-provider-holographic"
|
|
||||||
},
|
|
||||||
"homepage": "https://github.com/omdsh-dev/dsh-mnemon/tree/main/plugins/dsh-brain-mnemon-provider-holographic#readme",
|
|
||||||
"bugs": {
|
|
||||||
"url": "https://github.com/omdsh-dev/dsh-mnemon/issues"
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
@ -1,4 +0,0 @@
|
||||||
import { ct as MemoryProviderDescriptor } from "../../../lib/contracts-DuGgDm58.js";
|
|
||||||
import "../../source-memory-spaces/lib/provider-sdk.js";
|
|
||||||
declare const descriptor: MemoryProviderDescriptor;
|
|
||||||
export { descriptor };
|
|
||||||
|
|
@ -1 +0,0 @@
|
||||||
export { t as descriptor } from "../../../lib/descriptor-Ck-nyEdk.js";
|
|
||||||
|
|
@ -1,21 +0,0 @@
|
||||||
import { a as MemoryJsonValue } from "../../../lib/index-3Wnpy9oQ.js";
|
|
||||||
import { $t as SearchRequest, Jt as RememberRequest, L as MemoryBody, Y as MemoryListRequest, w as Insight } from "../../../lib/contracts-DuGgDm58.js";
|
|
||||||
import { C as ProviderSearchResult, f as MemoryProviderAdapter, h as MemorySpaceAuthority, n as MemorySpaceProviderDefinition, s as MemorySpaceProviderModule, x as ProviderMemorySpace, y as ProviderBodyStatus } from "../../../lib/definitions-C41Daez1.js";
|
|
||||||
import { HttpMemoryProvider, HttpProviderOptions } from "../../source-memory-spaces/lib/provider-sdk.js";
|
|
||||||
import { descriptor } from "./descriptor.js";
|
|
||||||
declare class HonchoProvider extends HttpMemoryProvider implements MemoryProviderAdapter {
|
|
||||||
readonly id: "honcho";
|
|
||||||
constructor(memorySpaces: MemorySpaceAuthority, options?: HttpProviderOptions);
|
|
||||||
discover(connection: Record<string, string | number | boolean>, signal?: AbortSignal): Promise<ProviderMemorySpace[]>;
|
|
||||||
status(body: MemoryBody, signal?: AbortSignal): Promise<ProviderBodyStatus>;
|
|
||||||
search(body: MemoryBody, request: SearchRequest, signal?: AbortSignal): Promise<ProviderSearchResult>;
|
|
||||||
list(body: MemoryBody, request: MemoryListRequest, signal?: AbortSignal): Promise<Insight[]>;
|
|
||||||
remember(body: MemoryBody, request: RememberRequest, signal?: AbortSignal): Promise<MemoryJsonValue>;
|
|
||||||
forget(body: MemoryBody, id: string, signal?: AbortSignal): Promise<MemoryJsonValue>;
|
|
||||||
private basePath;
|
|
||||||
private scope;
|
|
||||||
private headers;
|
|
||||||
}
|
|
||||||
declare const definition: MemorySpaceProviderDefinition;
|
|
||||||
declare const _default: MemorySpaceProviderModule<undefined>;
|
|
||||||
export { HonchoProvider, _default as default, definition, descriptor };
|
|
||||||
|
|
@ -1,168 +0,0 @@
|
||||||
import { i as defineMemorySpaceProviderDefinition, r as defineMemorySpaceProvider, t as MEMORY_SPACE_PROVIDER_API_VERSION } from "../../../lib/definitions-Du9KQuKM.js";
|
|
||||||
import { HttpMemoryProvider, firstArray, jsonObject, jsonString } from "../../source-memory-spaces/lib/provider-sdk.js";
|
|
||||||
import { t as descriptor } from "../../../lib/descriptor-Ck-nyEdk.js";
|
|
||||||
// vendor/dsh-mnemon/plugins/dsh-brain-mnemon-provider-honcho/src/driver.ts
|
|
||||||
function insight(value) {
|
|
||||||
const item = jsonObject(value);
|
|
||||||
const id = jsonString(item?.id);
|
|
||||||
const content = jsonString(item?.content);
|
|
||||||
if (id === void 0 || content === void 0) return void 0;
|
|
||||||
const observer = jsonString(item?.observer_id) ?? jsonString(item?.observer);
|
|
||||||
const observed = jsonString(item?.observed_id) ?? jsonString(item?.observed);
|
|
||||||
const createdAt = jsonString(item?.created_at) ?? jsonString(item?.createdAt);
|
|
||||||
const entities = [observer, observed].filter((entry) => entry !== void 0);
|
|
||||||
return {
|
|
||||||
id,
|
|
||||||
content,
|
|
||||||
category: jsonString(item?.level) ?? "insight",
|
|
||||||
source: "external",
|
|
||||||
...createdAt === void 0 ? {} : { createdAt },
|
|
||||||
...entities.length === 0 ? {} : { entities }
|
|
||||||
};
|
|
||||||
}
|
|
||||||
var HonchoProvider = class extends HttpMemoryProvider {
|
|
||||||
id = "honcho";
|
|
||||||
constructor(memorySpaces, options = {}) {
|
|
||||||
super(memorySpaces, {
|
|
||||||
label: descriptor.label,
|
|
||||||
...options
|
|
||||||
});
|
|
||||||
}
|
|
||||||
async discover(connection, signal) {
|
|
||||||
const payload = await this.requestConnection(connection, "/v3/workspaces/list?page=1&size=100", {
|
|
||||||
headers: this.headers(connection),
|
|
||||||
json: {},
|
|
||||||
signal
|
|
||||||
});
|
|
||||||
return firstArray(payload, "items", "results").flatMap((value) => {
|
|
||||||
const item = jsonObject(value);
|
|
||||||
const id = jsonString(item?.id);
|
|
||||||
if (id === void 0) return [];
|
|
||||||
const metadata = jsonObject(item?.metadata);
|
|
||||||
return [{
|
|
||||||
externalId: id,
|
|
||||||
name: jsonString(metadata?.name) ?? jsonString(metadata?.title) ?? id,
|
|
||||||
description: jsonString(metadata?.description) ?? `Honcho workspace ${id}`,
|
|
||||||
connection: {
|
|
||||||
workspace: id,
|
|
||||||
userId: "*",
|
|
||||||
agentId: "*"
|
|
||||||
}
|
|
||||||
}];
|
|
||||||
});
|
|
||||||
}
|
|
||||||
async status(body, signal) {
|
|
||||||
try {
|
|
||||||
await this.list(body, { limit: 1 }, signal);
|
|
||||||
return { healthy: true };
|
|
||||||
} catch (error) {
|
|
||||||
return {
|
|
||||||
healthy: false,
|
|
||||||
error: error instanceof Error ? error.message : String(error)
|
|
||||||
};
|
|
||||||
}
|
|
||||||
}
|
|
||||||
async search(body, request, signal) {
|
|
||||||
const connection = this.connection(body);
|
|
||||||
const payload = await this.request(body, `${this.basePath(connection)}/conclusions/query`, {
|
|
||||||
headers: this.headers(connection),
|
|
||||||
json: {
|
|
||||||
query: request.query,
|
|
||||||
top_k: Math.min(request.limit ?? 10, 100),
|
|
||||||
filters: this.scope(connection, true)
|
|
||||||
},
|
|
||||||
signal
|
|
||||||
});
|
|
||||||
return { results: firstArray(payload, "items", "results").map(insight).filter((item) => item !== void 0) };
|
|
||||||
}
|
|
||||||
async list(body, request, signal) {
|
|
||||||
const connection = this.connection(body);
|
|
||||||
const limit = Math.min(Math.max(request.limit ?? 200, 1), 100);
|
|
||||||
const payload = await this.request(body, `${this.basePath(connection)}/conclusions/list?page=1&size=${limit}`, {
|
|
||||||
headers: this.headers(connection),
|
|
||||||
json: { filters: {
|
|
||||||
...this.scope(connection),
|
|
||||||
...request.category === void 0 ? {} : { level: request.category }
|
|
||||||
} },
|
|
||||||
signal
|
|
||||||
});
|
|
||||||
return firstArray(payload, "items", "results").map(insight).filter((item) => item !== void 0);
|
|
||||||
}
|
|
||||||
async remember(body, request, signal) {
|
|
||||||
const connection = this.connection(body);
|
|
||||||
const payload = await this.request(body, `${this.basePath(connection)}/conclusions`, {
|
|
||||||
headers: this.headers(connection),
|
|
||||||
json: { conclusions: [{
|
|
||||||
content: request.content,
|
|
||||||
observer_id: String(connection.agentId) === "*" ? "dsh" : String(connection.agentId),
|
|
||||||
observed_id: String(connection.userId) === "*" ? "dsh-user" : String(connection.userId),
|
|
||||||
session_id: null
|
|
||||||
}] },
|
|
||||||
signal
|
|
||||||
});
|
|
||||||
const created = firstArray(payload, "items", "results").map(jsonObject).find((item) => item !== void 0);
|
|
||||||
return {
|
|
||||||
action: "stored",
|
|
||||||
provider: this.id,
|
|
||||||
summary: "Honcho stored an explicit peer conclusion.",
|
|
||||||
...jsonString(created?.id) === void 0 ? {} : { id: jsonString(created?.id) }
|
|
||||||
};
|
|
||||||
}
|
|
||||||
async forget(body, id, signal) {
|
|
||||||
const connection = this.connection(body);
|
|
||||||
await this.request(body, `${this.basePath(connection)}/conclusions/${encodeURIComponent(id)}`, {
|
|
||||||
method: "DELETE",
|
|
||||||
headers: this.headers(connection),
|
|
||||||
signal
|
|
||||||
});
|
|
||||||
return {
|
|
||||||
action: "deleted",
|
|
||||||
provider: this.id,
|
|
||||||
id
|
|
||||||
};
|
|
||||||
}
|
|
||||||
basePath(connection) {
|
|
||||||
return `/v3/workspaces/${encodeURIComponent(String(connection.workspace))}`;
|
|
||||||
}
|
|
||||||
scope(connection, requirePeers = false) {
|
|
||||||
const agentId = String(connection.agentId);
|
|
||||||
const userId = String(connection.userId);
|
|
||||||
return {
|
|
||||||
...agentId === "*" ? requirePeers ? { observer_id: "dsh" } : {} : { observer_id: agentId },
|
|
||||||
...userId === "*" ? requirePeers ? { observed_id: "dsh-user" } : {} : { observed_id: userId }
|
|
||||||
};
|
|
||||||
}
|
|
||||||
headers(connection) {
|
|
||||||
const token = String(connection.apiKey ?? "").replace(/^Bearer\s+/iu, "");
|
|
||||||
return token === "" ? {} : { Authorization: `Bearer ${token}` };
|
|
||||||
}
|
|
||||||
};
|
|
||||||
// vendor/dsh-mnemon/plugins/dsh-brain-mnemon-provider-honcho/src/index.ts
|
|
||||||
const definition = defineMemorySpaceProviderDefinition({
|
|
||||||
manifest: {
|
|
||||||
apiVersion: MEMORY_SPACE_PROVIDER_API_VERSION,
|
|
||||||
kind: "provider",
|
|
||||||
typeId: descriptor.id,
|
|
||||||
packageName: "dsh-brain-mnemon-provider-honcho",
|
|
||||||
version: "0.5.6",
|
|
||||||
label: descriptor.label,
|
|
||||||
icon: descriptor.icon,
|
|
||||||
summary: descriptor.summary,
|
|
||||||
...descriptor.summaryI18nKey === void 0 ? {} : { summaryI18nKey: descriptor.summaryI18nKey },
|
|
||||||
origin: descriptor.origin,
|
|
||||||
locality: descriptor.kind,
|
|
||||||
workspaceBinding: descriptor.workspaceBinding,
|
|
||||||
capabilities: descriptor.capabilities,
|
|
||||||
fields: descriptor.fields,
|
|
||||||
secrets: descriptor.fields.filter((field) => field.input === "secret").map((field) => field.key),
|
|
||||||
scoreSemantics: "provider-native"
|
|
||||||
},
|
|
||||||
create: (context) => new HonchoProvider(context.memorySpaces ?? context.memoryBodies, { requestTimeoutMs: context.config.timeoutMs })
|
|
||||||
});
|
|
||||||
var src_default = defineMemorySpaceProvider({
|
|
||||||
id: descriptor.id,
|
|
||||||
apply(ctx, host) {
|
|
||||||
host.install(ctx, definition);
|
|
||||||
}
|
|
||||||
});
|
|
||||||
export { HonchoProvider, src_default as default, definition, descriptor };
|
|
||||||
|
|
@ -1,55 +0,0 @@
|
||||||
{
|
|
||||||
"name": "dsh-brain-mnemon-provider-honcho",
|
|
||||||
"version": "0.5.6",
|
|
||||||
"description": "Honcho Provider child for the Memory Spaces Source.",
|
|
||||||
"license": "MIT",
|
|
||||||
"type": "module",
|
|
||||||
"engines": {
|
|
||||||
"node": ">=20"
|
|
||||||
},
|
|
||||||
"exports": {
|
|
||||||
".": {
|
|
||||||
"types": "./lib/index.d.ts",
|
|
||||||
"default": "./lib/index.js"
|
|
||||||
},
|
|
||||||
"./descriptor": {
|
|
||||||
"types": "./lib/descriptor.d.ts",
|
|
||||||
"default": "./lib/descriptor.js"
|
|
||||||
},
|
|
||||||
"./package.json": "./package.json"
|
|
||||||
},
|
|
||||||
"files": [
|
|
||||||
"lib",
|
|
||||||
"README.md"
|
|
||||||
],
|
|
||||||
"scripts": {
|
|
||||||
"typecheck": "tsc --noEmit",
|
|
||||||
"build": "tsdown",
|
|
||||||
"test": "vitest run",
|
|
||||||
"verify": "pnpm typecheck && pnpm test && pnpm build"
|
|
||||||
},
|
|
||||||
"peerDependencies": {
|
|
||||||
"@deepseek-ai/cordis": "^4.0.1",
|
|
||||||
"dsh-brain-mnemon-source-memory-spaces": "^0.5.1"
|
|
||||||
},
|
|
||||||
"devDependencies": {
|
|
||||||
"@types/node": "^22.0.0",
|
|
||||||
"dsh-brain-mnemon-source-memory-spaces": "^0.5.33",
|
|
||||||
"tsdown": "^0.22.0",
|
|
||||||
"typescript": "^5.9.0",
|
|
||||||
"vitest": "^3.2.0"
|
|
||||||
},
|
|
||||||
"publishConfig": {
|
|
||||||
"access": "public",
|
|
||||||
"tag": "latest"
|
|
||||||
},
|
|
||||||
"repository": {
|
|
||||||
"type": "git",
|
|
||||||
"url": "git+https://github.com/omdsh-dev/dsh-mnemon.git",
|
|
||||||
"directory": "plugins/dsh-brain-mnemon-provider-honcho"
|
|
||||||
},
|
|
||||||
"homepage": "https://github.com/omdsh-dev/dsh-mnemon/tree/main/plugins/dsh-brain-mnemon-provider-honcho#readme",
|
|
||||||
"bugs": {
|
|
||||||
"url": "https://github.com/omdsh-dev/dsh-mnemon/issues"
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
@ -1,4 +0,0 @@
|
||||||
import { ct as MemoryProviderDescriptor } from "../../../lib/contracts-DuGgDm58.js";
|
|
||||||
import "../../source-memory-spaces/lib/provider-sdk.js";
|
|
||||||
declare const descriptor: MemoryProviderDescriptor;
|
|
||||||
export { descriptor };
|
|
||||||
|
|
@ -1 +0,0 @@
|
||||||
export { t as descriptor } from "../../../lib/descriptor-DIAMITdX.js";
|
|
||||||
|
|
@ -1,21 +0,0 @@
|
||||||
import { a as MemoryJsonValue } from "../../../lib/index-3Wnpy9oQ.js";
|
|
||||||
import { $t as SearchRequest, Jt as RememberRequest, L as MemoryBody, Y as MemoryListRequest, w as Insight } from "../../../lib/contracts-DuGgDm58.js";
|
|
||||||
import { C as ProviderSearchResult, S as ProviderScoreSemantics, f as MemoryProviderAdapter, h as MemorySpaceAuthority, n as MemorySpaceProviderDefinition, s as MemorySpaceProviderModule, x as ProviderMemorySpace, y as ProviderBodyStatus } from "../../../lib/definitions-C41Daez1.js";
|
|
||||||
import { HttpMemoryProvider, HttpProviderOptions } from "../../source-memory-spaces/lib/provider-sdk.js";
|
|
||||||
import { descriptor } from "./descriptor.js";
|
|
||||||
declare class Mem0Provider extends HttpMemoryProvider implements MemoryProviderAdapter {
|
|
||||||
readonly id: "mem0";
|
|
||||||
readonly scoreSemantics: ProviderScoreSemantics;
|
|
||||||
constructor(memorySpaces: MemorySpaceAuthority, options?: HttpProviderOptions);
|
|
||||||
discover(connection: Record<string, string | number | boolean>, signal?: AbortSignal): Promise<ProviderMemorySpace[]>;
|
|
||||||
status(body: MemoryBody, signal?: AbortSignal): Promise<ProviderBodyStatus>;
|
|
||||||
search(body: MemoryBody, request: SearchRequest, signal?: AbortSignal): Promise<ProviderSearchResult>;
|
|
||||||
list(body: MemoryBody, request: MemoryListRequest, signal?: AbortSignal): Promise<Insight[]>;
|
|
||||||
remember(body: MemoryBody, request: RememberRequest, signal?: AbortSignal): Promise<MemoryJsonValue>;
|
|
||||||
forget(body: MemoryBody, id: string, signal?: AbortSignal): Promise<MemoryJsonValue>;
|
|
||||||
private filters;
|
|
||||||
private headers;
|
|
||||||
}
|
|
||||||
declare const definition: MemorySpaceProviderDefinition;
|
|
||||||
declare const _default: MemorySpaceProviderModule<undefined>;
|
|
||||||
export { Mem0Provider, _default as default, definition, descriptor };
|
|
||||||
|
|
@ -1,202 +0,0 @@
|
||||||
import { t as NORMALIZED_RELEVANCE_SCORE } from "../../../lib/adapter-CF9Q9xOa.js";
|
|
||||||
import { i as defineMemorySpaceProviderDefinition, r as defineMemorySpaceProvider, t as MEMORY_SPACE_PROVIDER_API_VERSION } from "../../../lib/definitions-Du9KQuKM.js";
|
|
||||||
import { HttpMemoryProvider, firstArray, jsonArray, jsonNumber, jsonObject, jsonString } from "../../source-memory-spaces/lib/provider-sdk.js";
|
|
||||||
import { t as descriptor } from "../../../lib/descriptor-DIAMITdX.js";
|
|
||||||
// vendor/dsh-mnemon/plugins/dsh-brain-mnemon-provider-mem0/src/driver.ts
|
|
||||||
function category(item) {
|
|
||||||
const categories = jsonArray(item.categories).filter((value) => typeof value === "string");
|
|
||||||
return jsonString(item.category) ?? categories[0] ?? "general";
|
|
||||||
}
|
|
||||||
function insight(value) {
|
|
||||||
const item = jsonObject(value);
|
|
||||||
const id = jsonString(item?.id);
|
|
||||||
const content = jsonString(item?.memory) ?? jsonString(item?.text) ?? jsonString(item?.content);
|
|
||||||
if (id === void 0 || content === void 0) return void 0;
|
|
||||||
const score = jsonNumber(item?.score);
|
|
||||||
const createdAt = jsonString(item?.created_at) ?? jsonString(item?.createdAt) ?? jsonString(item?.updated_at);
|
|
||||||
const tags = jsonArray(item?.categories).filter((entry) => typeof entry === "string");
|
|
||||||
return {
|
|
||||||
id,
|
|
||||||
content,
|
|
||||||
category: category(item),
|
|
||||||
source: "external",
|
|
||||||
...score === void 0 ? {} : { score },
|
|
||||||
...createdAt === void 0 ? {} : { createdAt },
|
|
||||||
...tags.length === 0 ? {} : { tags }
|
|
||||||
};
|
|
||||||
}
|
|
||||||
var Mem0Provider = class extends HttpMemoryProvider {
|
|
||||||
id = "mem0";
|
|
||||||
scoreSemantics = NORMALIZED_RELEVANCE_SCORE;
|
|
||||||
constructor(memorySpaces, options = {}) {
|
|
||||||
super(memorySpaces, {
|
|
||||||
label: descriptor.label,
|
|
||||||
...options
|
|
||||||
});
|
|
||||||
}
|
|
||||||
async discover(connection, signal) {
|
|
||||||
const mode = String(connection.mode ?? "platform");
|
|
||||||
const payload = await this.requestConnection(connection, mode === "self-hosted" ? "/entities" : "/v1/entities", {
|
|
||||||
headers: this.headers(connection, mode),
|
|
||||||
signal
|
|
||||||
});
|
|
||||||
return firstArray(payload, "entities", "results").flatMap((value) => {
|
|
||||||
const item = jsonObject(value);
|
|
||||||
const id = jsonString(item?.id);
|
|
||||||
const type = jsonString(item?.type);
|
|
||||||
if (id === void 0 || type !== "user" && type !== "agent") return [];
|
|
||||||
const metadata = jsonObject(item?.metadata);
|
|
||||||
const count = jsonNumber(item?.total_memories);
|
|
||||||
return [{
|
|
||||||
externalId: `${type}:${id}`,
|
|
||||||
name: jsonString(item?.name) ?? jsonString(metadata?.name) ?? id,
|
|
||||||
description: jsonString(metadata?.description) ?? `${type === "user" ? "User" : "Agent"} memory${count === void 0 ? "" : ` · ${count} memories`}`,
|
|
||||||
connection: type === "user" ? {
|
|
||||||
userId: id,
|
|
||||||
agentId: "*",
|
|
||||||
rerank: false
|
|
||||||
} : {
|
|
||||||
userId: "*",
|
|
||||||
agentId: id,
|
|
||||||
rerank: false
|
|
||||||
}
|
|
||||||
}];
|
|
||||||
});
|
|
||||||
}
|
|
||||||
async status(body, signal) {
|
|
||||||
try {
|
|
||||||
await this.list(body, { limit: 1 }, signal);
|
|
||||||
return { healthy: true };
|
|
||||||
} catch (error) {
|
|
||||||
return {
|
|
||||||
healthy: false,
|
|
||||||
error: error instanceof Error ? error.message : String(error)
|
|
||||||
};
|
|
||||||
}
|
|
||||||
}
|
|
||||||
async search(body, request, signal) {
|
|
||||||
const connection = this.connection(body);
|
|
||||||
const mode = String(connection.mode ?? "platform");
|
|
||||||
const filters = this.filters(connection);
|
|
||||||
const payload = await this.request(body, mode === "self-hosted" ? "/search" : "/v3/memories/search/", {
|
|
||||||
headers: this.headers(connection, mode),
|
|
||||||
json: {
|
|
||||||
query: request.query,
|
|
||||||
filters,
|
|
||||||
top_k: request.limit ?? 10,
|
|
||||||
...mode === "platform" && connection.rerank === true ? { rerank: true } : {}
|
|
||||||
},
|
|
||||||
signal
|
|
||||||
});
|
|
||||||
return { results: firstArray(payload, "results", "memories").map(insight).filter((item) => item !== void 0) };
|
|
||||||
}
|
|
||||||
async list(body, request, signal) {
|
|
||||||
const connection = this.connection(body);
|
|
||||||
const mode = String(connection.mode ?? "platform");
|
|
||||||
const limit = Math.min(Math.max(request.limit ?? 200, 1), 200);
|
|
||||||
const payload = mode === "self-hosted" ? await this.request(body, `/memories?${new URLSearchParams({
|
|
||||||
...this.filters(connection),
|
|
||||||
limit: String(limit)
|
|
||||||
})}`, {
|
|
||||||
headers: this.headers(connection, mode),
|
|
||||||
signal
|
|
||||||
}) : await this.request(body, `/v3/memories/?page=1&page_size=${limit}`, {
|
|
||||||
headers: this.headers(connection, mode),
|
|
||||||
json: {
|
|
||||||
filters: this.filters(connection),
|
|
||||||
...request.category === void 0 ? {} : { categories: [request.category] }
|
|
||||||
},
|
|
||||||
signal
|
|
||||||
});
|
|
||||||
return firstArray(payload, "results", "memories").map(insight).filter((item) => item !== void 0);
|
|
||||||
}
|
|
||||||
async remember(body, request, signal) {
|
|
||||||
const connection = this.connection(body);
|
|
||||||
const mode = String(connection.mode ?? "platform");
|
|
||||||
const payload = await this.request(body, mode === "self-hosted" ? "/memories" : "/v3/memories/add/", {
|
|
||||||
headers: this.headers(connection, mode),
|
|
||||||
json: {
|
|
||||||
messages: [{
|
|
||||||
role: "user",
|
|
||||||
content: request.content
|
|
||||||
}],
|
|
||||||
user_id: String(connection.userId) === "*" ? "dsh-user" : String(connection.userId),
|
|
||||||
agent_id: String(connection.agentId) === "*" ? "dsh" : String(connection.agentId),
|
|
||||||
...mode === "self-hosted" ? { infer: false } : {},
|
|
||||||
metadata: {
|
|
||||||
source: "dsh-brain-mnemon",
|
|
||||||
...request.category === void 0 ? {} : { category: request.category },
|
|
||||||
...request.importance === void 0 ? {} : { importance: request.importance },
|
|
||||||
...request.tags === void 0 ? {} : { tags: request.tags },
|
|
||||||
...request.entities === void 0 ? {} : { entities: request.entities }
|
|
||||||
}
|
|
||||||
},
|
|
||||||
signal
|
|
||||||
});
|
|
||||||
const result = jsonObject(payload) ?? {};
|
|
||||||
return {
|
|
||||||
action: mode === "platform" ? "queued" : "stored",
|
|
||||||
provider: this.id,
|
|
||||||
summary: mode === "platform" ? "Mem0 queued the memory for extraction." : "Mem0 stored the explicit memory.",
|
|
||||||
...jsonString(result.event_id) === void 0 ? {} : { eventId: jsonString(result.event_id) },
|
|
||||||
...jsonString(result.status) === void 0 ? {} : { status: jsonString(result.status) }
|
|
||||||
};
|
|
||||||
}
|
|
||||||
async forget(body, id, signal) {
|
|
||||||
const connection = this.connection(body);
|
|
||||||
const mode = String(connection.mode ?? "platform");
|
|
||||||
const path = mode === "self-hosted" ? `/memories/${encodeURIComponent(id)}` : `/v1/memories/${encodeURIComponent(id)}`;
|
|
||||||
await this.request(body, path, {
|
|
||||||
method: "DELETE",
|
|
||||||
headers: this.headers(connection, mode),
|
|
||||||
signal
|
|
||||||
});
|
|
||||||
return {
|
|
||||||
action: "deleted",
|
|
||||||
provider: this.id,
|
|
||||||
id
|
|
||||||
};
|
|
||||||
}
|
|
||||||
filters(connection) {
|
|
||||||
const userId = String(connection.userId);
|
|
||||||
const agentId = String(connection.agentId ?? "");
|
|
||||||
return {
|
|
||||||
...userId === "*" ? {} : { user_id: userId },
|
|
||||||
...agentId === "" || agentId === "*" ? {} : { agent_id: agentId }
|
|
||||||
};
|
|
||||||
}
|
|
||||||
headers(connection, mode) {
|
|
||||||
const apiKey = String(connection.apiKey ?? "").replace(/^(?:Token|Bearer)\s+/iu, "");
|
|
||||||
if (apiKey === "") return {};
|
|
||||||
return mode === "self-hosted" ? { "X-API-Key": apiKey } : { Authorization: `Token ${apiKey}` };
|
|
||||||
}
|
|
||||||
};
|
|
||||||
// vendor/dsh-mnemon/plugins/dsh-brain-mnemon-provider-mem0/src/index.ts
|
|
||||||
const definition = defineMemorySpaceProviderDefinition({
|
|
||||||
manifest: {
|
|
||||||
apiVersion: MEMORY_SPACE_PROVIDER_API_VERSION,
|
|
||||||
kind: "provider",
|
|
||||||
typeId: descriptor.id,
|
|
||||||
packageName: "dsh-brain-mnemon-provider-mem0",
|
|
||||||
version: "0.5.6",
|
|
||||||
label: descriptor.label,
|
|
||||||
icon: descriptor.icon,
|
|
||||||
summary: descriptor.summary,
|
|
||||||
...descriptor.summaryI18nKey === void 0 ? {} : { summaryI18nKey: descriptor.summaryI18nKey },
|
|
||||||
origin: descriptor.origin,
|
|
||||||
locality: descriptor.kind,
|
|
||||||
workspaceBinding: descriptor.workspaceBinding,
|
|
||||||
capabilities: descriptor.capabilities,
|
|
||||||
fields: descriptor.fields,
|
|
||||||
secrets: descriptor.fields.filter((field) => field.input === "secret").map((field) => field.key),
|
|
||||||
scoreSemantics: "normalized-relevance"
|
|
||||||
},
|
|
||||||
create: (context) => new Mem0Provider(context.memorySpaces ?? context.memoryBodies, { requestTimeoutMs: context.config.timeoutMs })
|
|
||||||
});
|
|
||||||
var src_default = defineMemorySpaceProvider({
|
|
||||||
id: descriptor.id,
|
|
||||||
apply(ctx, host) {
|
|
||||||
host.install(ctx, definition);
|
|
||||||
}
|
|
||||||
});
|
|
||||||
export { Mem0Provider, src_default as default, definition, descriptor };
|
|
||||||
|
|
@ -1,55 +0,0 @@
|
||||||
{
|
|
||||||
"name": "dsh-brain-mnemon-provider-mem0",
|
|
||||||
"version": "0.5.6",
|
|
||||||
"description": "Mem0 Provider child for the Memory Spaces Source.",
|
|
||||||
"license": "MIT",
|
|
||||||
"type": "module",
|
|
||||||
"engines": {
|
|
||||||
"node": ">=20"
|
|
||||||
},
|
|
||||||
"exports": {
|
|
||||||
".": {
|
|
||||||
"types": "./lib/index.d.ts",
|
|
||||||
"default": "./lib/index.js"
|
|
||||||
},
|
|
||||||
"./descriptor": {
|
|
||||||
"types": "./lib/descriptor.d.ts",
|
|
||||||
"default": "./lib/descriptor.js"
|
|
||||||
},
|
|
||||||
"./package.json": "./package.json"
|
|
||||||
},
|
|
||||||
"files": [
|
|
||||||
"lib",
|
|
||||||
"README.md"
|
|
||||||
],
|
|
||||||
"scripts": {
|
|
||||||
"typecheck": "tsc --noEmit",
|
|
||||||
"build": "tsdown",
|
|
||||||
"test": "vitest run",
|
|
||||||
"verify": "pnpm typecheck && pnpm test && pnpm build"
|
|
||||||
},
|
|
||||||
"peerDependencies": {
|
|
||||||
"@deepseek-ai/cordis": "^4.0.1",
|
|
||||||
"dsh-brain-mnemon-source-memory-spaces": "^0.5.1"
|
|
||||||
},
|
|
||||||
"devDependencies": {
|
|
||||||
"@types/node": "^22.0.0",
|
|
||||||
"dsh-brain-mnemon-source-memory-spaces": "^0.5.33",
|
|
||||||
"tsdown": "^0.22.0",
|
|
||||||
"typescript": "^5.9.0",
|
|
||||||
"vitest": "^3.2.0"
|
|
||||||
},
|
|
||||||
"publishConfig": {
|
|
||||||
"access": "public",
|
|
||||||
"tag": "latest"
|
|
||||||
},
|
|
||||||
"repository": {
|
|
||||||
"type": "git",
|
|
||||||
"url": "git+https://github.com/omdsh-dev/dsh-mnemon.git",
|
|
||||||
"directory": "plugins/dsh-brain-mnemon-provider-mem0"
|
|
||||||
},
|
|
||||||
"homepage": "https://github.com/omdsh-dev/dsh-mnemon/tree/main/plugins/dsh-brain-mnemon-provider-mem0#readme",
|
|
||||||
"bugs": {
|
|
||||||
"url": "https://github.com/omdsh-dev/dsh-mnemon/issues"
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
@ -1,4 +0,0 @@
|
||||||
import { ct as MemoryProviderDescriptor } from "../../../lib/contracts-DuGgDm58.js";
|
|
||||||
import "../../source-memory-spaces/lib/provider-sdk.js";
|
|
||||||
declare const descriptor: MemoryProviderDescriptor;
|
|
||||||
export { descriptor };
|
|
||||||
|
|
@ -1,28 +0,0 @@
|
||||||
// vendor/dsh-mnemon/plugins/dsh-brain-mnemon-provider-mnemon-native/src/descriptor.ts
|
|
||||||
const descriptor = {
|
|
||||||
"id": "mnemon-native",
|
|
||||||
"label": "Mnemon Native",
|
|
||||||
"icon": {
|
|
||||||
"kind": "brand",
|
|
||||||
"value": "mnemon"
|
|
||||||
},
|
|
||||||
"kind": "local",
|
|
||||||
"workspaceBinding": "automatic",
|
|
||||||
"summary": "Official local-first memory with exact writes, typed graph relations, and soft deletion.",
|
|
||||||
"summaryI18nKey": "overview.providerSummary.mnemon-native",
|
|
||||||
"origin": "native",
|
|
||||||
"capabilities": {
|
|
||||||
"search": true,
|
|
||||||
"browse": true,
|
|
||||||
"graph": true,
|
|
||||||
"entities": true,
|
|
||||||
"related": true,
|
|
||||||
"remember": true,
|
|
||||||
"link": true,
|
|
||||||
"forget": true,
|
|
||||||
"writeMode": "exact",
|
|
||||||
"deletionMode": "soft"
|
|
||||||
},
|
|
||||||
"fields": []
|
|
||||||
};
|
|
||||||
export { descriptor };
|
|
||||||
|
|
@ -1,32 +0,0 @@
|
||||||
import { a as MemoryJsonValue } from "../../../lib/index-3Wnpy9oQ.js";
|
|
||||||
import { $t as SearchRequest, J as MemoryGraphSnapshot, Jt as RememberRequest, L as MemoryBody, Y as MemoryListRequest, w as Insight, y as EdgeType } from "../../../lib/contracts-DuGgDm58.js";
|
|
||||||
import { C as ProviderSearchResult, S as ProviderScoreSemantics, _ as MemorySpaceNativeRunner, f as MemoryProviderAdapter, n as MemorySpaceProviderDefinition, s as MemorySpaceProviderModule, y as ProviderBodyStatus } from "../../../lib/definitions-C41Daez1.js";
|
|
||||||
import "../../source-memory-spaces/lib/provider-sdk.js";
|
|
||||||
import { descriptor } from "./descriptor.js";
|
|
||||||
declare function parseMemoryGraph(html: string, now?: Date): MemoryGraphSnapshot;
|
|
||||||
declare class MnemonNativeProvider implements MemoryProviderAdapter {
|
|
||||||
private readonly runner;
|
|
||||||
private readonly config;
|
|
||||||
readonly id = "mnemon-native";
|
|
||||||
readonly scoreSemantics: ProviderScoreSemantics;
|
|
||||||
constructor(runner: MemorySpaceNativeRunner, config?: {
|
|
||||||
defaultRecallLimit: number;
|
|
||||||
});
|
|
||||||
list(body: MemoryBody, _request: MemoryListRequest, signal?: AbortSignal): Promise<Insight[]>;
|
|
||||||
status(body: MemoryBody, signal?: AbortSignal): Promise<ProviderBodyStatus>;
|
|
||||||
private parseStats;
|
|
||||||
graph(body: MemoryBody, signal?: AbortSignal): Promise<MemoryGraphSnapshot>;
|
|
||||||
private allNativeInsights;
|
|
||||||
metadataSample(body: MemoryBody, limit: number, signal?: AbortSignal): Promise<Insight[]>;
|
|
||||||
search(body: MemoryBody, request: SearchRequest, signal?: AbortSignal): Promise<ProviderSearchResult>;
|
|
||||||
remember(body: MemoryBody, request: RememberRequest, signal?: AbortSignal): Promise<MemoryJsonValue>;
|
|
||||||
rememberMany(body: MemoryBody, requests: readonly RememberRequest[], signal?: AbortSignal): Promise<MemoryJsonValue[]>;
|
|
||||||
private importExact;
|
|
||||||
get(body: MemoryBody, id: string, signal?: AbortSignal): Promise<Insight | undefined>;
|
|
||||||
related(body: MemoryBody, id: string, depth: number, edge?: EdgeType, signal?: AbortSignal): Promise<Insight[]>;
|
|
||||||
link(body: MemoryBody, sourceId: string, targetId: string, type: EdgeType, weight: number, reason?: string, signal?: AbortSignal): Promise<MemoryJsonValue>;
|
|
||||||
forget(body: MemoryBody, id: string, signal?: AbortSignal): Promise<MemoryJsonValue>;
|
|
||||||
}
|
|
||||||
declare const definition: MemorySpaceProviderDefinition;
|
|
||||||
declare const _default: MemorySpaceProviderModule<undefined>;
|
|
||||||
export { MnemonNativeProvider, _default as default, definition, descriptor, parseMemoryGraph };
|
|
||||||
|
|
@ -1,496 +0,0 @@
|
||||||
import { t as NORMALIZED_RELEVANCE_SCORE } from "../../../lib/adapter-CF9Q9xOa.js";
|
|
||||||
import { i as defineMemorySpaceProviderDefinition, r as defineMemorySpaceProvider, t as MEMORY_SPACE_PROVIDER_API_VERSION } from "../../../lib/definitions-Du9KQuKM.js";
|
|
||||||
import "../../source-memory-spaces/lib/provider-sdk.js";
|
|
||||||
import { descriptor } from "./descriptor.js";
|
|
||||||
import { join } from "node:path";
|
|
||||||
import { mkdtempSync, rmSync, writeFileSync } from "node:fs";
|
|
||||||
import { tmpdir } from "node:os";
|
|
||||||
// vendor/dsh-mnemon/plugins/dsh-brain-mnemon-provider-mnemon-native/src/driver.ts
|
|
||||||
const STORE_DUMP_MAX_OUTPUT_BYTES = 134217728;
|
|
||||||
function record(value) {
|
|
||||||
return typeof value === "object" && value !== null && !Array.isArray(value) ? value : void 0;
|
|
||||||
}
|
|
||||||
function text(value) {
|
|
||||||
return typeof value === "string" ? value : void 0;
|
|
||||||
}
|
|
||||||
function number(value) {
|
|
||||||
return typeof value === "number" && Number.isFinite(value) ? value : void 0;
|
|
||||||
}
|
|
||||||
function stringArray(value) {
|
|
||||||
if (!Array.isArray(value)) return void 0;
|
|
||||||
return value.filter((entry) => typeof entry === "string");
|
|
||||||
}
|
|
||||||
function normalizeInsight(value) {
|
|
||||||
const item = record(value);
|
|
||||||
if (item === void 0) return void 0;
|
|
||||||
const core = record(item.insight) ?? item;
|
|
||||||
const id = text(core.id);
|
|
||||||
const content = text(core.content);
|
|
||||||
if (id === void 0 || content === void 0) return void 0;
|
|
||||||
const insight = {
|
|
||||||
id,
|
|
||||||
content
|
|
||||||
};
|
|
||||||
const optionalText = {
|
|
||||||
category: text(core.category),
|
|
||||||
source: text(core.source),
|
|
||||||
confidence: text(item.confidence),
|
|
||||||
intent: text(item.intent),
|
|
||||||
matchedVia: text(item.matched_via ?? item.via ?? item.via_edge_type),
|
|
||||||
createdAt: text(core.created_at),
|
|
||||||
edgeType: text(item.via_edge_type)
|
|
||||||
};
|
|
||||||
for (const [key, value] of Object.entries(optionalText)) if (value !== void 0) Object.assign(insight, { [key]: value });
|
|
||||||
const optionalNumbers = {
|
|
||||||
importance: number(core.importance),
|
|
||||||
score: number(item.score),
|
|
||||||
depth: number(item.depth)
|
|
||||||
};
|
|
||||||
for (const [key, value] of Object.entries(optionalNumbers)) if (value !== void 0) Object.assign(insight, { [key]: value });
|
|
||||||
const tags = stringArray(core.tags);
|
|
||||||
const entities = stringArray(core.entities);
|
|
||||||
if (tags !== void 0) insight.tags = tags;
|
|
||||||
if (entities !== void 0) insight.entities = entities;
|
|
||||||
return insight;
|
|
||||||
}
|
|
||||||
const JS_STRING = "\"(?:\\\\.|[^\"\\\\])*\"";
|
|
||||||
const VIZ_NODE_PATTERN = new RegExp(`\\{id:(${JS_STRING}),label:(${JS_STRING}),title:(${JS_STRING}),color:(${JS_STRING}),font:\\{color:"white"\\}\\}`, "g");
|
|
||||||
const VIZ_EDGE_PATTERN = new RegExp(`\\{from:(${JS_STRING}),to:(${JS_STRING}),label:(${JS_STRING}),color:\\{color:(${JS_STRING})\\},arrows:"to"`, "g");
|
|
||||||
const EDGE_COLORS = {
|
|
||||||
"#aaaaaa": "temporal",
|
|
||||||
"#3498db": "semantic",
|
|
||||||
"#e74c3c": "causal",
|
|
||||||
"#2ecc71": "entity"
|
|
||||||
};
|
|
||||||
function decodeJsString(value) {
|
|
||||||
const decoded = JSON.parse(value);
|
|
||||||
if (typeof decoded !== "string") throw new Error("Mnemon viz contained an invalid string");
|
|
||||||
return decoded;
|
|
||||||
}
|
|
||||||
function parseMemoryGraph(html, now = /* @__PURE__ */ new Date()) {
|
|
||||||
const nodes = [];
|
|
||||||
const edges = [];
|
|
||||||
for (const match of html.matchAll(VIZ_NODE_PATTERN)) {
|
|
||||||
const id = decodeJsString(match[1]);
|
|
||||||
const label = decodeJsString(match[2]);
|
|
||||||
const content = decodeJsString(match[3]).replaceAll("\\n", "\n");
|
|
||||||
const color = decodeJsString(match[4]);
|
|
||||||
const category = /\[([a-z_]+)\]/i.exec(label)?.[1] ?? "general";
|
|
||||||
nodes.push({
|
|
||||||
id,
|
|
||||||
content,
|
|
||||||
category,
|
|
||||||
color
|
|
||||||
});
|
|
||||||
}
|
|
||||||
for (const match of html.matchAll(VIZ_EDGE_PATTERN)) {
|
|
||||||
const color = decodeJsString(match[4]);
|
|
||||||
const type = EDGE_COLORS[color.toLowerCase()];
|
|
||||||
edges.push({
|
|
||||||
sourceId: decodeJsString(match[1]),
|
|
||||||
targetId: decodeJsString(match[2]),
|
|
||||||
label: decodeJsString(match[3]),
|
|
||||||
color,
|
|
||||||
...type === void 0 ? {} : { type }
|
|
||||||
});
|
|
||||||
}
|
|
||||||
if (!html.includes("var nodes = new vis.DataSet([")) throw new Error("Mnemon viz returned an unexpected HTML payload");
|
|
||||||
return {
|
|
||||||
nodes,
|
|
||||||
edges,
|
|
||||||
generatedAt: now.toISOString()
|
|
||||||
};
|
|
||||||
}
|
|
||||||
function commaList(values, label, limit) {
|
|
||||||
if (values === void 0) return void 0;
|
|
||||||
const normalized = values.map((value) => value.trim()).filter((value) => value !== "");
|
|
||||||
if (normalized.length > limit) throw new Error(`${label} accepts at most ${limit} values`);
|
|
||||||
if (normalized.some((value) => value.includes(","))) throw new Error(`${label} values cannot contain commas`);
|
|
||||||
return normalized.length === 0 ? void 0 : normalized.join(",");
|
|
||||||
}
|
|
||||||
var MnemonNativeProvider = class {
|
|
||||||
runner;
|
|
||||||
config;
|
|
||||||
id = "mnemon-native";
|
|
||||||
scoreSemantics = NORMALIZED_RELEVANCE_SCORE;
|
|
||||||
constructor(runner, config = { defaultRecallLimit: 10 }) {
|
|
||||||
this.runner = runner;
|
|
||||||
this.config = config;
|
|
||||||
}
|
|
||||||
list(body, _request, signal) {
|
|
||||||
return this.allNativeInsights(body, signal, true);
|
|
||||||
}
|
|
||||||
async status(body, signal) {
|
|
||||||
try {
|
|
||||||
const status = record(await this.runner.runJson(["status"], {
|
|
||||||
...signal === void 0 ? {} : { signal },
|
|
||||||
store: body.id
|
|
||||||
}));
|
|
||||||
if (status === void 0) throw new Error("mnemon status returned an unexpected payload");
|
|
||||||
return {
|
|
||||||
healthy: true,
|
|
||||||
stats: this.parseStats(status)
|
|
||||||
};
|
|
||||||
} catch (error) {
|
|
||||||
return {
|
|
||||||
healthy: false,
|
|
||||||
error: error instanceof Error ? error.message : String(error)
|
|
||||||
};
|
|
||||||
}
|
|
||||||
}
|
|
||||||
parseStats(status) {
|
|
||||||
const byCategoryRecord = record(status.by_category) ?? {};
|
|
||||||
const byCategory = {};
|
|
||||||
for (const [category, count] of Object.entries(byCategoryRecord)) if (typeof count === "number") byCategory[category] = count;
|
|
||||||
const topEntities = Array.isArray(status.top_entities) ? status.top_entities.flatMap((entry) => {
|
|
||||||
const entity = record(entry);
|
|
||||||
const name = text(entity?.entity);
|
|
||||||
const count = number(entity?.count);
|
|
||||||
return name === void 0 || count === void 0 ? [] : [{
|
|
||||||
entity: name,
|
|
||||||
count
|
|
||||||
}];
|
|
||||||
}) : [];
|
|
||||||
return {
|
|
||||||
totalInsights: number(status.total_insights) ?? 0,
|
|
||||||
deletedInsights: number(status.deleted_insights) ?? 0,
|
|
||||||
edgeCount: number(status.edge_count) ?? 0,
|
|
||||||
oplogCount: number(status.oplog_count) ?? 0,
|
|
||||||
dbSizeBytes: number(status.db_size_bytes) ?? 0,
|
|
||||||
byCategory,
|
|
||||||
topEntities
|
|
||||||
};
|
|
||||||
}
|
|
||||||
async graph(body, signal) {
|
|
||||||
const [html, insights] = await Promise.all([this.runner.runText([
|
|
||||||
"viz",
|
|
||||||
"--format",
|
|
||||||
"html",
|
|
||||||
"--output",
|
|
||||||
"-"
|
|
||||||
], {
|
|
||||||
...signal === void 0 ? {} : { signal },
|
|
||||||
store: body.id,
|
|
||||||
maxOutputBytes: STORE_DUMP_MAX_OUTPUT_BYTES
|
|
||||||
}), this.allNativeInsights(body, signal, true)]);
|
|
||||||
const snapshot = parseMemoryGraph(html);
|
|
||||||
const metadata = new Map(insights.map((insight) => [insight.id, insight]));
|
|
||||||
return {
|
|
||||||
...snapshot,
|
|
||||||
nodes: snapshot.nodes.map((node) => {
|
|
||||||
const insight = metadata.get(node.id);
|
|
||||||
return insight === void 0 ? node : {
|
|
||||||
...node,
|
|
||||||
...insight,
|
|
||||||
id: node.id,
|
|
||||||
content: node.content,
|
|
||||||
color: node.color
|
|
||||||
};
|
|
||||||
})
|
|
||||||
};
|
|
||||||
}
|
|
||||||
async allNativeInsights(body, signal, readonly = false) {
|
|
||||||
const payload = await this.runner.runJson([
|
|
||||||
...readonly ? ["--readonly"] : [],
|
|
||||||
"recall",
|
|
||||||
"",
|
|
||||||
"--basic",
|
|
||||||
"--limit",
|
|
||||||
"100000"
|
|
||||||
], {
|
|
||||||
...signal === void 0 ? {} : { signal },
|
|
||||||
store: body.id,
|
|
||||||
maxOutputBytes: STORE_DUMP_MAX_OUTPUT_BYTES
|
|
||||||
});
|
|
||||||
return (Array.isArray(payload) ? payload : Array.isArray(record(payload)?.results) ? record(payload).results : []).map(normalizeInsight).filter((entry) => entry !== void 0);
|
|
||||||
}
|
|
||||||
async metadataSample(body, limit, signal) {
|
|
||||||
const payload = await this.runner.runJson([
|
|
||||||
"--readonly",
|
|
||||||
"recall",
|
|
||||||
"",
|
|
||||||
"--basic",
|
|
||||||
"--limit",
|
|
||||||
String(limit)
|
|
||||||
], {
|
|
||||||
...signal === void 0 ? {} : { signal },
|
|
||||||
store: body.id
|
|
||||||
});
|
|
||||||
const wrapper = record(payload);
|
|
||||||
return (Array.isArray(payload) ? payload : Array.isArray(wrapper?.results) ? wrapper.results : []).map(normalizeInsight).filter((entry) => entry !== void 0);
|
|
||||||
}
|
|
||||||
async search(body, request, signal) {
|
|
||||||
const mode = request.mode ?? "smart";
|
|
||||||
const semantic = mode === "smart";
|
|
||||||
const limit = request.limit ?? this.config.defaultRecallLimit;
|
|
||||||
const candidateLimit = semantic ? Math.max(limit, Math.min(50, Math.max(20, limit * 4))) : limit;
|
|
||||||
const readonly = request.inspect === true ? ["--readonly"] : [];
|
|
||||||
const args = mode === "keyword" ? [
|
|
||||||
...readonly,
|
|
||||||
"search",
|
|
||||||
request.query,
|
|
||||||
"--limit",
|
|
||||||
String(candidateLimit)
|
|
||||||
] : [
|
|
||||||
...readonly,
|
|
||||||
"recall",
|
|
||||||
request.query,
|
|
||||||
"--limit",
|
|
||||||
String(candidateLimit)
|
|
||||||
];
|
|
||||||
if (semantic) args.push("--verbose");
|
|
||||||
if (mode === "basic") args.push("--basic");
|
|
||||||
if (mode !== "keyword") {
|
|
||||||
if (request.category !== void 0) args.push("--cat", request.category);
|
|
||||||
if (request.source !== void 0) args.push("--source", request.source);
|
|
||||||
if (request.intent !== void 0) args.push("--intent", request.intent);
|
|
||||||
}
|
|
||||||
const options = {
|
|
||||||
...signal === void 0 ? {} : { signal },
|
|
||||||
store: body.id
|
|
||||||
};
|
|
||||||
let payload;
|
|
||||||
try {
|
|
||||||
payload = await this.runner.runJson(args, options);
|
|
||||||
} catch (error) {
|
|
||||||
if (!semantic || signal?.aborted || !(error instanceof Error)) throw error;
|
|
||||||
const prefix = `mnemon ${args.join(" ")} exited `;
|
|
||||||
const detail = error.message.startsWith(prefix) ? error.message.slice(prefix.length) : error.message;
|
|
||||||
if (!/^(?:[1-9]\d*:\s*)?(?:Error:\s*)?unknown flag: --verbose[ \t]*(?:\r?\n|$)/u.test(detail)) throw error;
|
|
||||||
const legacyArgs = [...args];
|
|
||||||
legacyArgs.splice(readonly.length + 4, 1);
|
|
||||||
payload = await this.runner.runJson(legacyArgs, options);
|
|
||||||
}
|
|
||||||
const wrapper = record(payload);
|
|
||||||
const candidates = (Array.isArray(payload) ? payload : Array.isArray(wrapper?.results) ? wrapper.results : []).flatMap((value) => {
|
|
||||||
const insight = normalizeInsight(value);
|
|
||||||
if (insight === void 0) return [];
|
|
||||||
const item = record(value);
|
|
||||||
return [{
|
|
||||||
insight,
|
|
||||||
similarity: number(record(item?.signals)?.similarity),
|
|
||||||
superseded: item?.superseded === true
|
|
||||||
}];
|
|
||||||
});
|
|
||||||
if (semantic && candidates.some((candidate) => candidate.similarity !== void 0 && candidate.similarity > 0)) {
|
|
||||||
for (const candidate of candidates) {
|
|
||||||
const { insight, similarity } = candidate;
|
|
||||||
delete insight.confidence;
|
|
||||||
if (similarity === void 0) {
|
|
||||||
if (!candidate.superseded) delete insight.score;
|
|
||||||
} else {
|
|
||||||
const relevance = Math.min(1, Math.max(0, similarity));
|
|
||||||
insight.score = candidate.superseded ? Math.min(relevance, insight.score ?? 0) : relevance;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
candidates.sort((left, right) => (right.insight.score ?? -1) - (left.insight.score ?? -1));
|
|
||||||
}
|
|
||||||
const hint = text(wrapper?.hint) ?? text(record(wrapper?.meta)?.hint);
|
|
||||||
return {
|
|
||||||
results: candidates.slice(0, limit).map((candidate) => candidate.insight),
|
|
||||||
...hint === void 0 ? {} : { hint }
|
|
||||||
};
|
|
||||||
}
|
|
||||||
async remember(body, request, signal) {
|
|
||||||
const args = [
|
|
||||||
"remember",
|
|
||||||
request.content,
|
|
||||||
"--cat",
|
|
||||||
request.category ?? "general",
|
|
||||||
"--imp",
|
|
||||||
String(request.importance ?? 3),
|
|
||||||
"--source",
|
|
||||||
request.source ?? "user"
|
|
||||||
];
|
|
||||||
const tags = commaList(request.tags, "tags", 20);
|
|
||||||
const entities = commaList(request.entities, "entities", 50);
|
|
||||||
if (tags !== void 0) args.push("--tags", tags);
|
|
||||||
if (entities !== void 0) args.push("--entities", entities);
|
|
||||||
return this.runner.runJson(args, {
|
|
||||||
...signal === void 0 ? {} : { signal },
|
|
||||||
store: body.id
|
|
||||||
});
|
|
||||||
}
|
|
||||||
async rememberMany(body, requests, signal) {
|
|
||||||
if (requests.length === 0) return [];
|
|
||||||
const existing = new Map((await this.allNativeInsights(body, signal, true)).map((entry) => [entry.content, entry]));
|
|
||||||
const ordered = new Array(requests.length);
|
|
||||||
const reused = /* @__PURE__ */ new Set();
|
|
||||||
let pending = /* @__PURE__ */ new Map();
|
|
||||||
const queue = (index) => {
|
|
||||||
const request = requests[index];
|
|
||||||
const group = pending.get(request.content);
|
|
||||||
if (group === void 0) pending.set(request.content, {
|
|
||||||
request,
|
|
||||||
indexes: [index]
|
|
||||||
});
|
|
||||||
else group.indexes.push(index);
|
|
||||||
};
|
|
||||||
for (const [index, request] of requests.entries()) {
|
|
||||||
const exact = existing.get(request.content);
|
|
||||||
if (exact === void 0) queue(index);
|
|
||||||
else {
|
|
||||||
ordered[index] = {
|
|
||||||
action: "skipped",
|
|
||||||
id: exact.id,
|
|
||||||
content: exact.content
|
|
||||||
};
|
|
||||||
reused.add(index);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
while (pending.size > 0) {
|
|
||||||
const pruned = await this.importExact(body, [...pending.values()], ordered, signal);
|
|
||||||
pending = /* @__PURE__ */ new Map();
|
|
||||||
for (const index of reused) {
|
|
||||||
const id = record(ordered[index])?.id;
|
|
||||||
if (typeof id === "string" && pruned.has(id)) {
|
|
||||||
reused.delete(index);
|
|
||||||
queue(index);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return ordered;
|
|
||||||
}
|
|
||||||
async importExact(body, batch, ordered, signal) {
|
|
||||||
const temporary = mkdtempSync(join(tmpdir(), "dsh-brain-mnemon-runtime-archive-"));
|
|
||||||
const draftPath = join(temporary, "memory-draft.json");
|
|
||||||
try {
|
|
||||||
writeFileSync(draftPath, JSON.stringify({
|
|
||||||
schema_version: "1",
|
|
||||||
source: "dsh-brain-mnemon-runtime-archive",
|
|
||||||
insights: batch.map(({ request }) => ({
|
|
||||||
content: request.content,
|
|
||||||
category: request.category,
|
|
||||||
importance: request.importance ?? 3,
|
|
||||||
source: request.source,
|
|
||||||
...request.tags === void 0 ? {} : { tags: request.tags },
|
|
||||||
...request.entities === void 0 ? {} : { entities: request.entities }
|
|
||||||
}))
|
|
||||||
}), {
|
|
||||||
encoding: "utf8",
|
|
||||||
mode: 384
|
|
||||||
});
|
|
||||||
const summary = record(await this.runner.runJson([
|
|
||||||
"import",
|
|
||||||
draftPath,
|
|
||||||
"--no-diff"
|
|
||||||
], {
|
|
||||||
...signal === void 0 ? {} : { signal },
|
|
||||||
store: body.id
|
|
||||||
}));
|
|
||||||
const rows = Array.isArray(summary?.results) ? summary.results : void 0;
|
|
||||||
const errors = number(summary?.errors);
|
|
||||||
const imported = number(summary?.imported);
|
|
||||||
const updated = number(summary?.updated);
|
|
||||||
const skipped = number(summary?.skipped);
|
|
||||||
const invalid = () => /* @__PURE__ */ new Error(`Mnemon runtime archive import returned an invalid or partial result for Memory Space ${body.id}`);
|
|
||||||
if (errors !== 0 || imported === void 0 || updated === void 0 || skipped === void 0 || rows === void 0 || ![
|
|
||||||
imported,
|
|
||||||
updated,
|
|
||||||
skipped
|
|
||||||
].every((value) => Number.isInteger(value) && value >= 0) || imported !== batch.length || updated !== 0 || skipped !== 0 || rows.length !== batch.length) throw invalid();
|
|
||||||
const seen = /* @__PURE__ */ new Set();
|
|
||||||
for (const candidate of rows) {
|
|
||||||
const row = record(candidate);
|
|
||||||
const index = number(row?.index);
|
|
||||||
const action = text(row?.action)?.trim().toLocaleLowerCase();
|
|
||||||
if (index === void 0 || !Number.isInteger(index) || index < 0 || index >= batch.length || seen.has(index)) throw invalid();
|
|
||||||
if (row?.content !== batch[index].request.content || action !== "added") throw invalid();
|
|
||||||
seen.add(index);
|
|
||||||
for (const [offset, originalIndex] of batch[index].indexes.entries()) ordered[originalIndex] = offset === 0 ? row : {
|
|
||||||
...row,
|
|
||||||
action: "skipped"
|
|
||||||
};
|
|
||||||
}
|
|
||||||
return new Set(stringArray(summary?.auto_pruned_ids) ?? []);
|
|
||||||
} finally {
|
|
||||||
rmSync(temporary, {
|
|
||||||
recursive: true,
|
|
||||||
force: true
|
|
||||||
});
|
|
||||||
}
|
|
||||||
}
|
|
||||||
async get(body, id, signal) {
|
|
||||||
try {
|
|
||||||
return normalizeInsight(await this.runner.runJson([
|
|
||||||
"--readonly",
|
|
||||||
"show",
|
|
||||||
id
|
|
||||||
], {
|
|
||||||
...signal === void 0 ? {} : { signal },
|
|
||||||
store: body.id
|
|
||||||
}));
|
|
||||||
} catch (error) {
|
|
||||||
if (error instanceof Error && /no rows in result set/u.test(error.message)) return void 0;
|
|
||||||
throw error;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
async related(body, id, depth, edge, signal) {
|
|
||||||
const args = [
|
|
||||||
"related",
|
|
||||||
id,
|
|
||||||
"--depth",
|
|
||||||
String(depth)
|
|
||||||
];
|
|
||||||
if (edge !== void 0) args.push("--edge", edge);
|
|
||||||
const payload = await this.runner.runJson(args, {
|
|
||||||
...signal === void 0 ? {} : { signal },
|
|
||||||
store: body.id
|
|
||||||
});
|
|
||||||
return Array.isArray(payload) ? payload.map(normalizeInsight).filter((entry) => entry !== void 0) : [];
|
|
||||||
}
|
|
||||||
async link(body, sourceId, targetId, type, weight, reason, signal) {
|
|
||||||
const args = [
|
|
||||||
"link",
|
|
||||||
sourceId,
|
|
||||||
targetId,
|
|
||||||
"--type",
|
|
||||||
type,
|
|
||||||
"--weight",
|
|
||||||
String(weight)
|
|
||||||
];
|
|
||||||
if (reason !== void 0) args.push("--meta", JSON.stringify({ reason }));
|
|
||||||
return this.runner.runJson(args, {
|
|
||||||
...signal === void 0 ? {} : { signal },
|
|
||||||
store: body.id
|
|
||||||
});
|
|
||||||
}
|
|
||||||
forget(body, id, signal) {
|
|
||||||
return this.runner.runJson(["forget", id], {
|
|
||||||
...signal === void 0 ? {} : { signal },
|
|
||||||
store: body.id
|
|
||||||
});
|
|
||||||
}
|
|
||||||
};
|
|
||||||
// vendor/dsh-mnemon/plugins/dsh-brain-mnemon-provider-mnemon-native/src/index.ts
|
|
||||||
const definition = defineMemorySpaceProviderDefinition({
|
|
||||||
manifest: {
|
|
||||||
apiVersion: MEMORY_SPACE_PROVIDER_API_VERSION,
|
|
||||||
kind: "provider",
|
|
||||||
typeId: descriptor.id,
|
|
||||||
packageName: "dsh-brain-mnemon-provider-mnemon-native",
|
|
||||||
version: "0.5.12",
|
|
||||||
label: descriptor.label,
|
|
||||||
icon: descriptor.icon,
|
|
||||||
summary: descriptor.summary,
|
|
||||||
...descriptor.summaryI18nKey === void 0 ? {} : { summaryI18nKey: descriptor.summaryI18nKey },
|
|
||||||
origin: descriptor.origin,
|
|
||||||
locality: descriptor.kind,
|
|
||||||
workspaceBinding: descriptor.workspaceBinding,
|
|
||||||
capabilities: descriptor.capabilities,
|
|
||||||
fields: descriptor.fields,
|
|
||||||
secrets: descriptor.fields.filter((field) => field.input === "secret").map((field) => field.key),
|
|
||||||
scoreSemantics: "normalized-relevance"
|
|
||||||
},
|
|
||||||
create(context) {
|
|
||||||
if (context.nativeRunner === void 0) throw new Error("Mnemon Native requires the Memory Spaces nativeRunner capability");
|
|
||||||
return new MnemonNativeProvider(context.nativeRunner, { defaultRecallLimit: context.config.defaultRecallLimit ?? 10 });
|
|
||||||
}
|
|
||||||
});
|
|
||||||
var src_default = defineMemorySpaceProvider({
|
|
||||||
id: descriptor.id,
|
|
||||||
apply(ctx, host) {
|
|
||||||
host.install(ctx, definition);
|
|
||||||
}
|
|
||||||
});
|
|
||||||
export { MnemonNativeProvider, src_default as default, definition, descriptor, parseMemoryGraph };
|
|
||||||
|
|
@ -1,55 +0,0 @@
|
||||||
{
|
|
||||||
"name": "dsh-brain-mnemon-provider-mnemon-native",
|
|
||||||
"version": "0.5.12",
|
|
||||||
"description": "Native Mnemon CLI Provider child for Memory Spaces.",
|
|
||||||
"license": "MIT",
|
|
||||||
"type": "module",
|
|
||||||
"engines": {
|
|
||||||
"node": ">=20"
|
|
||||||
},
|
|
||||||
"exports": {
|
|
||||||
".": {
|
|
||||||
"types": "./lib/index.d.ts",
|
|
||||||
"default": "./lib/index.js"
|
|
||||||
},
|
|
||||||
"./descriptor": {
|
|
||||||
"types": "./lib/descriptor.d.ts",
|
|
||||||
"default": "./lib/descriptor.js"
|
|
||||||
},
|
|
||||||
"./package.json": "./package.json"
|
|
||||||
},
|
|
||||||
"files": [
|
|
||||||
"lib",
|
|
||||||
"README.md"
|
|
||||||
],
|
|
||||||
"scripts": {
|
|
||||||
"typecheck": "tsc --noEmit",
|
|
||||||
"build": "tsdown",
|
|
||||||
"test": "vitest run",
|
|
||||||
"verify": "pnpm typecheck && pnpm test && pnpm build"
|
|
||||||
},
|
|
||||||
"peerDependencies": {
|
|
||||||
"@deepseek-ai/cordis": "^4.0.1",
|
|
||||||
"dsh-brain-mnemon-source-memory-spaces": "^0.5.1"
|
|
||||||
},
|
|
||||||
"devDependencies": {
|
|
||||||
"@types/node": "^22.0.0",
|
|
||||||
"dsh-brain-mnemon-source-memory-spaces": "^0.5.33",
|
|
||||||
"tsdown": "^0.22.0",
|
|
||||||
"typescript": "^5.9.0",
|
|
||||||
"vitest": "^3.2.0"
|
|
||||||
},
|
|
||||||
"publishConfig": {
|
|
||||||
"access": "public",
|
|
||||||
"tag": "latest"
|
|
||||||
},
|
|
||||||
"repository": {
|
|
||||||
"type": "git",
|
|
||||||
"url": "git+https://github.com/omdsh-dev/dsh-mnemon.git",
|
|
||||||
"directory": "plugins/dsh-brain-mnemon-provider-mnemon-native"
|
|
||||||
},
|
|
||||||
"homepage": "https://github.com/omdsh-dev/dsh-mnemon/tree/main/plugins/dsh-brain-mnemon-provider-mnemon-native#readme",
|
|
||||||
"bugs": {
|
|
||||||
"url": "https://github.com/omdsh-dev/dsh-mnemon/issues"
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
@ -1,4 +0,0 @@
|
||||||
import { ct as MemoryProviderDescriptor } from "../../../lib/contracts-DuGgDm58.js";
|
|
||||||
import "../../source-memory-spaces/lib/provider-sdk.js";
|
|
||||||
declare const descriptor: MemoryProviderDescriptor;
|
|
||||||
export { descriptor };
|
|
||||||
|
|
@ -1 +0,0 @@
|
||||||
export { t as descriptor } from "../../../lib/descriptor-D_OcOjAK.js";
|
|
||||||
|
|
@ -1,37 +0,0 @@
|
||||||
import { a as MemoryJsonValue } from "../../../lib/index-3Wnpy9oQ.js";
|
|
||||||
import { $t as SearchRequest, J as MemoryGraphSnapshot, Jt as RememberRequest, L as MemoryBody, Y as MemoryListRequest, ot as MemoryProviderConnection, w as Insight } from "../../../lib/contracts-DuGgDm58.js";
|
|
||||||
import { C as ProviderSearchResult, f as MemoryProviderAdapter, h as MemorySpaceAuthority, n as MemorySpaceProviderDefinition, s as MemorySpaceProviderModule, x as ProviderMemorySpace, y as ProviderBodyStatus } from "../../../lib/definitions-C41Daez1.js";
|
|
||||||
import "../../source-memory-spaces/lib/provider-sdk.js";
|
|
||||||
import { descriptor } from "./descriptor.js";
|
|
||||||
interface OpenVikingProviderOptions {
|
|
||||||
fetch?: typeof fetch;
|
|
||||||
requestTimeoutMs?: number;
|
|
||||||
}
|
|
||||||
declare class OpenVikingProvider implements MemoryProviderAdapter {
|
|
||||||
private readonly memorySpaces;
|
|
||||||
readonly id: "openviking";
|
|
||||||
readonly scoreSemantics: Readonly<{
|
|
||||||
kind: "provider-native";
|
|
||||||
}>;
|
|
||||||
private readonly requestFetch;
|
|
||||||
private readonly requestTimeoutMs;
|
|
||||||
constructor(memorySpaces: MemorySpaceAuthority, options?: OpenVikingProviderOptions);
|
|
||||||
discover(connection: MemoryProviderConnection, signal?: AbortSignal): Promise<ProviderMemorySpace[]>;
|
|
||||||
status(body: MemoryBody, signal?: AbortSignal): Promise<ProviderBodyStatus>;
|
|
||||||
search(body: MemoryBody, request: SearchRequest, signal?: AbortSignal): Promise<ProviderSearchResult>;
|
|
||||||
graph(body: MemoryBody, signal?: AbortSignal): Promise<MemoryGraphSnapshot>;
|
|
||||||
list(body: MemoryBody, request: MemoryListRequest, signal?: AbortSignal): Promise<Insight[]>;
|
|
||||||
private readAll;
|
|
||||||
remember(body: MemoryBody, request: RememberRequest, signal?: AbortSignal): Promise<MemoryJsonValue>;
|
|
||||||
private tag;
|
|
||||||
forget(body: MemoryBody, id: string, signal?: AbortSignal): Promise<MemoryJsonValue>;
|
|
||||||
private connection;
|
|
||||||
private validateUserNamespace;
|
|
||||||
private memoryRoot;
|
|
||||||
private readContent;
|
|
||||||
private request;
|
|
||||||
private requestConnection;
|
|
||||||
}
|
|
||||||
declare const definition: MemorySpaceProviderDefinition;
|
|
||||||
declare const _default: MemorySpaceProviderModule<undefined>;
|
|
||||||
export { OpenVikingProvider, _default as default, definition, descriptor };
|
|
||||||
|
|
@ -1,446 +0,0 @@
|
||||||
import { CATEGORIES } from "../../source-memory-spaces/lib/contracts.js";
|
|
||||||
import { i as defineMemorySpaceProviderDefinition, r as defineMemorySpaceProvider, t as MEMORY_SPACE_PROVIDER_API_VERSION } from "../../../lib/definitions-Du9KQuKM.js";
|
|
||||||
import { bearerAuthHeader, jsonNumber, jsonObject, jsonString } from "../../source-memory-spaces/lib/provider-sdk.js";
|
|
||||||
import { t as descriptor } from "../../../lib/descriptor-D_OcOjAK.js";
|
|
||||||
import { randomUUID } from "node:crypto";
|
|
||||||
// vendor/dsh-mnemon/plugins/dsh-brain-mnemon-provider-openviking/src/driver.ts
|
|
||||||
function normalizeBearerHeader(apiKey) {
|
|
||||||
if (typeof bearerAuthHeader === "function") return bearerAuthHeader(apiKey);
|
|
||||||
if (typeof apiKey !== "string") return void 0;
|
|
||||||
const stripped = apiKey.trim().replace(/^Bearer(?:\s+|$)/iu, "").trim();
|
|
||||||
return stripped === "" ? void 0 : `Bearer ${stripped}`;
|
|
||||||
}
|
|
||||||
const CATEGORY_NAMES = new Set(CATEGORIES);
|
|
||||||
function categoryOf(value) {
|
|
||||||
const category = jsonString(value)?.trim().toLowerCase();
|
|
||||||
return category !== void 0 && CATEGORY_NAMES.has(category) ? category : "general";
|
|
||||||
}
|
|
||||||
const MEMORY_FOLDERS = {
|
|
||||||
preference: "preferences",
|
|
||||||
insight: "experiences",
|
|
||||||
decision: "experiences",
|
|
||||||
context: "events",
|
|
||||||
fact: "entities",
|
|
||||||
general: "entities"
|
|
||||||
};
|
|
||||||
const SLUG_BYTES = 180;
|
|
||||||
function memoryUri(root, category, content) {
|
|
||||||
const folder = Object.hasOwn(MEMORY_FOLDERS, category) ? MEMORY_FOLDERS[category] : "entities";
|
|
||||||
const firstLine = content.split("\n").find((line) => line.trim().length > 0) ?? "memory";
|
|
||||||
const characters = Array.from(firstLine.replace(/^#+\s*/u, "").replace(/[^\p{L}\p{N}]+/gu, "-").replace(/^-+|-+$/gu, "")).slice(0, 48);
|
|
||||||
while (Buffer.byteLength(characters.join("").toLowerCase()) > SLUG_BYTES) characters.pop();
|
|
||||||
const slug = characters.join("").toLowerCase() || "memory";
|
|
||||||
return `${root}/${folder}/${(/* @__PURE__ */ new Date()).toISOString().replace(/[-:T]/gu, "").slice(0, 14)}-${slug}_${category}-${randomUUID()}.md`;
|
|
||||||
}
|
|
||||||
function safeUser(user) {
|
|
||||||
return /^[a-zA-Z0-9_.@-]+$/u.test(user) && user !== "." && user !== ".." && (user.match(/@/gu)?.length ?? 0) <= 1;
|
|
||||||
}
|
|
||||||
function discoveryUser(connection) {
|
|
||||||
const user = String(connection.discoveryUser ?? "").trim();
|
|
||||||
if (user === "") return void 0;
|
|
||||||
if (!safeUser(user) || !safeUser(String(connection.account ?? "").trim())) throw new Error("OpenViking user-key discovery requires an explicit account and a safe discovery user");
|
|
||||||
if (normalizeBearerHeader(connection.apiKey) === void 0) throw new Error("OpenViking user-key discovery requires a user API key");
|
|
||||||
return user;
|
|
||||||
}
|
|
||||||
function isMemoryFile(uri, root) {
|
|
||||||
if (!uri.startsWith(`${root}/`) || !uri.endsWith(".md") || /[%?#\\\u0000-\u001f\u007f]/u.test(uri)) return false;
|
|
||||||
return uri.slice(root.length + 1).split("/").every((part) => part !== "" && !part.startsWith(".") && part.trim() === part);
|
|
||||||
}
|
|
||||||
function queueFailed(value) {
|
|
||||||
return Object.values(jsonObject(value) ?? {}).some((entry) => {
|
|
||||||
const queue = jsonObject(entry);
|
|
||||||
return (jsonNumber(queue?.error_count) ?? 0) > 0 || Array.isArray(queue?.errors) && queue.errors.length > 0;
|
|
||||||
});
|
|
||||||
}
|
|
||||||
const FOLDER_CATEGORIES = {
|
|
||||||
preferences: "preference",
|
|
||||||
experiences: "insight",
|
|
||||||
events: "context",
|
|
||||||
entities: "fact"
|
|
||||||
};
|
|
||||||
function categoryFromUri(uri, reported) {
|
|
||||||
const named = /_([a-z]+)-[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\.md$/u.exec(uri)?.[1];
|
|
||||||
if (named !== void 0 && CATEGORY_NAMES.has(named)) return named;
|
|
||||||
const stated = jsonString(reported);
|
|
||||||
if (stated !== void 0 && CATEGORY_NAMES.has(stated)) return stated;
|
|
||||||
const marker = "/memories/";
|
|
||||||
const folder = (uri.includes(marker) ? uri.slice(uri.indexOf(marker) + 10) : "").split("/")[0] ?? "";
|
|
||||||
return Object.hasOwn(FOLDER_CATEGORIES, folder) ? FOLDER_CATEGORIES[folder] : "general";
|
|
||||||
}
|
|
||||||
function refused(error) {
|
|
||||||
const status = error?.status;
|
|
||||||
return typeof status === "number" && status >= 400 && status < 500 && status !== 408 && status !== 409;
|
|
||||||
}
|
|
||||||
var OpenVikingProvider = class {
|
|
||||||
memorySpaces;
|
|
||||||
id = "openviking";
|
|
||||||
scoreSemantics = Object.freeze({ kind: "provider-native" });
|
|
||||||
requestFetch;
|
|
||||||
requestTimeoutMs;
|
|
||||||
constructor(memorySpaces, options = {}) {
|
|
||||||
this.memorySpaces = memorySpaces;
|
|
||||||
this.requestFetch = options.fetch ?? globalThis.fetch;
|
|
||||||
this.requestTimeoutMs = options.requestTimeoutMs ?? 15e3;
|
|
||||||
}
|
|
||||||
async discover(connection, signal) {
|
|
||||||
signal?.throwIfAborted();
|
|
||||||
let account = String(connection.account ?? "").trim();
|
|
||||||
const selectedUser = discoveryUser(connection);
|
|
||||||
if (selectedUser !== void 0) {
|
|
||||||
const targetUri = await this.validateUserNamespace(connection, selectedUser, signal);
|
|
||||||
return [{
|
|
||||||
externalId: `${account}:${selectedUser}`,
|
|
||||||
name: selectedUser,
|
|
||||||
description: `OpenViking memory namespace for ${selectedUser}`,
|
|
||||||
connection: {
|
|
||||||
targetUri,
|
|
||||||
user: selectedUser,
|
|
||||||
actorPeerId: "dsh"
|
|
||||||
}
|
|
||||||
}];
|
|
||||||
}
|
|
||||||
if (account === "") {
|
|
||||||
const accounts = await this.requestConnection(connection, "/api/v1/admin/accounts", {}, { signal });
|
|
||||||
const ids = (Array.isArray(accounts) ? accounts : []).flatMap((value) => {
|
|
||||||
const id = jsonString(jsonObject(value)?.account_id) ?? jsonString(jsonObject(value)?.id);
|
|
||||||
return id === void 0 ? [] : [id];
|
|
||||||
});
|
|
||||||
if (ids.length > 1) throw new Error("OpenViking exposes multiple accounts; configure the account to select one discovery scope");
|
|
||||||
account = ids[0] ?? "default";
|
|
||||||
}
|
|
||||||
const users = await this.requestConnection({
|
|
||||||
...connection,
|
|
||||||
account
|
|
||||||
}, `/api/v1/admin/accounts/${encodeURIComponent(account)}/users?limit=100`, {}, { signal });
|
|
||||||
return (Array.isArray(users) ? users : []).flatMap((value) => {
|
|
||||||
const item = jsonObject(value);
|
|
||||||
const user = jsonString(item?.user_id) ?? jsonString(item?.id) ?? jsonString(item?.name);
|
|
||||||
if (user === void 0 || !safeUser(user)) return [];
|
|
||||||
return [{
|
|
||||||
externalId: `${account}:${user}`,
|
|
||||||
name: jsonString(item?.display_name) ?? jsonString(item?.name) ?? user,
|
|
||||||
description: jsonString(item?.description) ?? jsonString(item?.role) ?? `OpenViking memory namespace for ${user}`,
|
|
||||||
connection: {
|
|
||||||
targetUri: `viking://user/${user}/memories`,
|
|
||||||
user,
|
|
||||||
actorPeerId: "dsh"
|
|
||||||
}
|
|
||||||
}];
|
|
||||||
});
|
|
||||||
}
|
|
||||||
async status(body, signal) {
|
|
||||||
try {
|
|
||||||
const connection = this.connection(body);
|
|
||||||
const selectedUser = discoveryUser(connection);
|
|
||||||
if (selectedUser === void 0) await this.request(body, "/health", {}, {
|
|
||||||
signal,
|
|
||||||
timeoutMs: 5e3
|
|
||||||
});
|
|
||||||
else {
|
|
||||||
await this.memoryRoot(body, signal);
|
|
||||||
await this.validateUserNamespace(connection, selectedUser, signal);
|
|
||||||
}
|
|
||||||
return { healthy: true };
|
|
||||||
} catch (error) {
|
|
||||||
return {
|
|
||||||
healthy: false,
|
|
||||||
error: error instanceof Error ? error.message : String(error)
|
|
||||||
};
|
|
||||||
}
|
|
||||||
}
|
|
||||||
async search(body, request, signal) {
|
|
||||||
const keyword = request.mode === "keyword";
|
|
||||||
signal?.throwIfAborted();
|
|
||||||
if (keyword && request.query.trim() === "") return { results: [] };
|
|
||||||
const limit = keyword ? Math.min(50, Math.max(1, Math.floor(jsonNumber(request.limit) ?? 10))) : request.limit;
|
|
||||||
const memoryRoot = await this.memoryRoot(body, signal);
|
|
||||||
const result = await this.request(body, keyword ? "/api/v1/search/grep" : "/api/v1/search/find", {
|
|
||||||
method: "POST",
|
|
||||||
body: JSON.stringify(keyword ? {
|
|
||||||
uri: memoryRoot,
|
|
||||||
pattern: request.query.replace(/[.*+?^${}()|[\]\\]/gu, "\\$&"),
|
|
||||||
case_insensitive: true,
|
|
||||||
node_limit: limit
|
|
||||||
} : {
|
|
||||||
query: request.query,
|
|
||||||
target_uri: memoryRoot,
|
|
||||||
context_type: ["memory"],
|
|
||||||
limit: request.limit
|
|
||||||
})
|
|
||||||
}, { signal });
|
|
||||||
const root = jsonObject(result);
|
|
||||||
if (keyword && !Array.isArray(root?.matches)) throw new Error("OpenViking keyword search did not return matches");
|
|
||||||
const values = keyword ? root?.matches : root?.memories;
|
|
||||||
const entries = Array.isArray(values) ? values : [];
|
|
||||||
const seen = /* @__PURE__ */ new Set();
|
|
||||||
const matches = entries.flatMap((value) => {
|
|
||||||
const item = jsonObject(value);
|
|
||||||
const uri = jsonString(item?.uri);
|
|
||||||
if (uri === void 0 || !isMemoryFile(uri, memoryRoot)) return [];
|
|
||||||
if (keyword && seen.has(uri)) return [];
|
|
||||||
seen.add(uri);
|
|
||||||
const score = keyword ? void 0 : jsonNumber(item?.score);
|
|
||||||
return [{
|
|
||||||
id: uri,
|
|
||||||
externalUri: uri,
|
|
||||||
content: jsonString(item?.overview) ?? jsonString(item?.abstract) ?? uri,
|
|
||||||
category: categoryFromUri(uri, item?.category),
|
|
||||||
source: "external",
|
|
||||||
...score === void 0 ? {} : { score }
|
|
||||||
}];
|
|
||||||
}).slice(0, limit);
|
|
||||||
const { read, skipped } = await this.readAll(body, matches, signal);
|
|
||||||
return {
|
|
||||||
results: read,
|
|
||||||
...skipped === 0 ? {} : { hint: `${skipped} OpenViking ${skipped === 1 ? "result" : "results"} could not be read and ${skipped === 1 ? "was" : "were"} left out; the server can list a file it no longer holds.` }
|
|
||||||
};
|
|
||||||
}
|
|
||||||
async graph(body, signal) {
|
|
||||||
return {
|
|
||||||
nodes: (await this.list(body, { limit: 200 }, signal)).map((item) => ({
|
|
||||||
...item,
|
|
||||||
color: "#5568d9"
|
|
||||||
})),
|
|
||||||
edges: [],
|
|
||||||
generatedAt: (/* @__PURE__ */ new Date()).toISOString()
|
|
||||||
};
|
|
||||||
}
|
|
||||||
async list(body, request, signal) {
|
|
||||||
const memoryRoot = await this.memoryRoot(body, signal);
|
|
||||||
const query = new URLSearchParams({
|
|
||||||
uri: memoryRoot,
|
|
||||||
recursive: "true",
|
|
||||||
output: "original"
|
|
||||||
});
|
|
||||||
const result = await this.request(body, `/api/v1/fs/ls?${query}`, {}, { signal });
|
|
||||||
const entries = Array.isArray(result) ? result : [];
|
|
||||||
const limit = Math.min(Math.max(request.limit ?? 200, 1), 1e3);
|
|
||||||
const files = entries.flatMap((value) => {
|
|
||||||
const item = jsonObject(value);
|
|
||||||
const uri = jsonString(item?.uri);
|
|
||||||
return item === void 0 || uri === void 0 || item.isDir === true || !isMemoryFile(uri, memoryRoot) ? [] : [{
|
|
||||||
item,
|
|
||||||
uri
|
|
||||||
}];
|
|
||||||
}).slice(0, limit);
|
|
||||||
const { read } = await this.readAll(body, files.map(({ item, uri }) => ({
|
|
||||||
id: uri,
|
|
||||||
item
|
|
||||||
})), signal);
|
|
||||||
return read.map(({ item, id, content }) => {
|
|
||||||
const createdAt = jsonString(item.modTime);
|
|
||||||
return {
|
|
||||||
id,
|
|
||||||
externalUri: id,
|
|
||||||
content,
|
|
||||||
category: categoryFromUri(id),
|
|
||||||
source: "external",
|
|
||||||
...createdAt === void 0 ? {} : { createdAt }
|
|
||||||
};
|
|
||||||
});
|
|
||||||
}
|
|
||||||
async readAll(body, items, signal) {
|
|
||||||
const settled = await Promise.allSettled(items.map(async (item) => ({
|
|
||||||
...item,
|
|
||||||
content: await this.readContent(body, item.id, signal)
|
|
||||||
})));
|
|
||||||
signal?.throwIfAborted();
|
|
||||||
const read = settled.flatMap((outcome) => outcome.status === "fulfilled" ? [outcome.value] : []);
|
|
||||||
const failed = settled.find((outcome) => outcome.status === "rejected");
|
|
||||||
if (read.length === 0 && failed !== void 0) throw failed.reason;
|
|
||||||
return {
|
|
||||||
read,
|
|
||||||
skipped: settled.length - read.length
|
|
||||||
};
|
|
||||||
}
|
|
||||||
async remember(body, request, signal) {
|
|
||||||
const root = await this.memoryRoot(body, signal);
|
|
||||||
const category = categoryOf(request.category);
|
|
||||||
const uri = memoryUri(root, category, request.content);
|
|
||||||
const tags = ["source=mnemon", `category=${category}`];
|
|
||||||
const importance = jsonNumber(request.importance);
|
|
||||||
if (importance !== void 0) tags.push(`importance=${importance}`);
|
|
||||||
const writtenBytes = Buffer.byteLength(request.content, "utf8");
|
|
||||||
let written;
|
|
||||||
try {
|
|
||||||
written = jsonObject(await this.request(body, "/api/v1/content/write", {
|
|
||||||
method: "POST",
|
|
||||||
body: JSON.stringify({
|
|
||||||
uri,
|
|
||||||
content: request.content,
|
|
||||||
mode: "create",
|
|
||||||
wait: true
|
|
||||||
})
|
|
||||||
}, { signal }));
|
|
||||||
} catch (error) {
|
|
||||||
if (refused(error)) throw new Error(`OpenViking refused the write at ${uri}; nothing was stored. ${error instanceof Error ? error.message : String(error)}`, { cause: error });
|
|
||||||
throw new Error(`OpenViking write was not verified at ${uri}; remote content may remain. Inspect this URI before retrying. ${error instanceof Error ? error.message : String(error)}`, { cause: error });
|
|
||||||
}
|
|
||||||
try {
|
|
||||||
if (written?.uri !== uri || written.content_updated !== true || (jsonNumber(written.written_bytes) ?? -1) < writtenBytes || written.mode !== "create" || written.context_type !== "memory" || written.vector_status !== "complete" || !["complete", "skipped"].includes(String(written.semantic_status)) || queueFailed(written.queue_status)) throw new Error("content API did not confirm this exact memory and completed indexing");
|
|
||||||
if (await this.readContent(body, uri, signal) !== request.content) throw new Error("stored content does not match the requested text");
|
|
||||||
signal?.throwIfAborted();
|
|
||||||
} catch (error) {
|
|
||||||
throw new Error(`OpenViking write was not verified at ${uri}; remote content may remain. Inspect this URI before retrying. ${error instanceof Error ? error.message : String(error)}`, { cause: error });
|
|
||||||
}
|
|
||||||
return {
|
|
||||||
action: "stored",
|
|
||||||
provider: "openviking",
|
|
||||||
id: uri,
|
|
||||||
uri,
|
|
||||||
externalUri: uri,
|
|
||||||
summary: `OpenViking stored the memory at ${uri} (category ${category}).`,
|
|
||||||
writtenBytes,
|
|
||||||
vectorStatus: "complete",
|
|
||||||
tagsApplied: await this.tag(body, uri, tags, signal)
|
|
||||||
};
|
|
||||||
}
|
|
||||||
async tag(body, uri, tags, signal) {
|
|
||||||
try {
|
|
||||||
return jsonObject(await this.request(body, "/api/v1/content/set_tags", {
|
|
||||||
method: "POST",
|
|
||||||
body: JSON.stringify({
|
|
||||||
uri,
|
|
||||||
tags,
|
|
||||||
mode: "replace"
|
|
||||||
})
|
|
||||||
}, {
|
|
||||||
signal,
|
|
||||||
timeoutMs: Math.min(this.requestTimeoutMs, 5e3)
|
|
||||||
}))?.tags_updated === true;
|
|
||||||
} catch {
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
async forget(body, id, signal) {
|
|
||||||
const root = await this.memoryRoot(body, signal);
|
|
||||||
const uri = id.trim();
|
|
||||||
if (!isMemoryFile(uri, root)) throw new Error("OpenViking forget requires an exact non-generated .md memory URI inside this Memory Space");
|
|
||||||
const query = new URLSearchParams({
|
|
||||||
uri,
|
|
||||||
recursive: "false"
|
|
||||||
});
|
|
||||||
const result = jsonObject(await this.request(body, `/api/v1/fs?${query}`, { method: "DELETE" }, { signal })) ?? {};
|
|
||||||
if (result.uri !== uri) throw new Error("OpenViking did not confirm deletion of the requested memory URI");
|
|
||||||
return {
|
|
||||||
action: "deleted",
|
|
||||||
provider: this.id,
|
|
||||||
id: uri,
|
|
||||||
uri,
|
|
||||||
...jsonNumber(result.estimated_deleted_count) === void 0 ? {} : { estimatedDeletedCount: jsonNumber(result.estimated_deleted_count) }
|
|
||||||
};
|
|
||||||
}
|
|
||||||
connection(body) {
|
|
||||||
if ((body.provider.typeId ?? body.provider.id) !== this.id) throw new Error(`OpenViking cannot serve provider ${body.provider.id}`);
|
|
||||||
const connection = this.memorySpaces.providerConnection(body.id, body.provider.id);
|
|
||||||
return {
|
|
||||||
endpoint: String(connection.endpoint ?? ""),
|
|
||||||
targetUri: String(connection.targetUri ?? ""),
|
|
||||||
apiKey: String(connection.apiKey ?? ""),
|
|
||||||
account: String(connection.account ?? ""),
|
|
||||||
user: String(connection.user ?? ""),
|
|
||||||
actorPeerId: String(connection.actorPeerId ?? ""),
|
|
||||||
discoveryUser: String(connection.discoveryUser ?? "")
|
|
||||||
};
|
|
||||||
}
|
|
||||||
async validateUserNamespace(connection, user, signal) {
|
|
||||||
const root = `viking://user/${user}/memories`;
|
|
||||||
const query = new URLSearchParams({
|
|
||||||
uri: root,
|
|
||||||
recursive: "false",
|
|
||||||
output: "original"
|
|
||||||
});
|
|
||||||
const result = await this.requestConnection(connection, `/api/v1/fs/ls?${query}`, {}, { signal });
|
|
||||||
if (!Array.isArray(result) || result.some((item) => !jsonString(jsonObject(item)?.uri)?.startsWith(`${root}/`))) throw new Error("OpenViking could not validate the selected memory namespace");
|
|
||||||
return root;
|
|
||||||
}
|
|
||||||
async memoryRoot(body, signal) {
|
|
||||||
signal?.throwIfAborted();
|
|
||||||
const connection = this.connection(body);
|
|
||||||
const root = connection.targetUri.replace(/\/+$/u, "");
|
|
||||||
const match = /^viking:\/\/user(?:\/([^/]+))?\/memories$/u.exec(root);
|
|
||||||
if (match === null || match[1] !== void 0 && !safeUser(match[1])) throw new Error("OpenViking memory URI must be a safe viking://user/<user>/memories root");
|
|
||||||
const selectedUser = discoveryUser(connection);
|
|
||||||
if (selectedUser !== void 0) {
|
|
||||||
if (match[1] !== void 0 && match[1] !== selectedUser || connection.user?.trim() && connection.user.trim() !== selectedUser) throw new Error("OpenViking memory owner must match the configured discovery user");
|
|
||||||
return `viking://user/${selectedUser}/memories`;
|
|
||||||
}
|
|
||||||
if (match[1] !== void 0) return root;
|
|
||||||
const user = connection.user?.trim() || jsonString(jsonObject(await this.request(body, "/api/v1/system/status", {}, { signal }))?.user) || "";
|
|
||||||
if (!safeUser(user)) throw new Error("OpenViking could not resolve the memory owner; configure an explicit user memory URI");
|
|
||||||
return `viking://user/${user}/memories`;
|
|
||||||
}
|
|
||||||
async readContent(body, uri, signal) {
|
|
||||||
const result = await this.request(body, `/api/v1/content/read?${new URLSearchParams({ uri })}`, {}, { signal });
|
|
||||||
if (typeof result !== "string") throw new Error("OpenViking content read did not return text");
|
|
||||||
return result;
|
|
||||||
}
|
|
||||||
async request(body, path, init = {}, options = {}) {
|
|
||||||
const connection = this.connection(body);
|
|
||||||
return this.requestConnection(connection, path, init, options);
|
|
||||||
}
|
|
||||||
async requestConnection(connection, path, init = {}, options = {}) {
|
|
||||||
options.signal?.throwIfAborted();
|
|
||||||
const keyBound = discoveryUser(connection) !== void 0;
|
|
||||||
const controller = new AbortController();
|
|
||||||
const relay = () => controller.abort(options.signal?.reason);
|
|
||||||
options.signal?.addEventListener("abort", relay, { once: true });
|
|
||||||
const timer = setTimeout(() => controller.abort(/* @__PURE__ */ new Error("OpenViking request timed out")), options.timeoutMs ?? this.requestTimeoutMs);
|
|
||||||
try {
|
|
||||||
const auth = normalizeBearerHeader(connection.apiKey);
|
|
||||||
const response = await this.requestFetch(`${connection.endpoint}${path}`, {
|
|
||||||
...init,
|
|
||||||
headers: {
|
|
||||||
"Content-Type": "application/json",
|
|
||||||
...auth === void 0 ? {} : { Authorization: auth },
|
|
||||||
...keyBound || connection.account === void 0 || connection.account === "" ? {} : { "X-OpenViking-Account": String(connection.account) },
|
|
||||||
...keyBound || connection.user === void 0 || connection.user === "" ? {} : { "X-OpenViking-User": String(connection.user) },
|
|
||||||
...connection.actorPeerId === void 0 || connection.actorPeerId === "" ? {} : { "X-OpenViking-Actor-Peer": String(connection.actorPeerId) },
|
|
||||||
...init.headers
|
|
||||||
},
|
|
||||||
signal: controller.signal
|
|
||||||
});
|
|
||||||
const envelope = await response.json().catch(() => ({}));
|
|
||||||
if (!response.ok || envelope.status === "error") {
|
|
||||||
const trace = envelope.error?.trace_id ?? envelope.trace_id;
|
|
||||||
throw Object.assign(/* @__PURE__ */ new Error(`${envelope.error?.message ?? `OpenViking HTTP ${response.status}`}${trace === void 0 ? "" : ` (trace ${trace})`}`), { status: response.status });
|
|
||||||
}
|
|
||||||
return envelope.result ?? envelope;
|
|
||||||
} catch (error) {
|
|
||||||
if (controller.signal.aborted && options.signal?.aborted !== true) throw new Error(`OpenViking request timed out after ${options.timeoutMs ?? this.requestTimeoutMs}ms`);
|
|
||||||
throw error;
|
|
||||||
} finally {
|
|
||||||
clearTimeout(timer);
|
|
||||||
options.signal?.removeEventListener("abort", relay);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
};
|
|
||||||
// vendor/dsh-mnemon/plugins/dsh-brain-mnemon-provider-openviking/src/index.ts
|
|
||||||
const definition = defineMemorySpaceProviderDefinition({
|
|
||||||
manifest: {
|
|
||||||
apiVersion: MEMORY_SPACE_PROVIDER_API_VERSION,
|
|
||||||
kind: "provider",
|
|
||||||
typeId: descriptor.id,
|
|
||||||
packageName: "dsh-brain-mnemon-provider-openviking",
|
|
||||||
version: "0.5.12",
|
|
||||||
label: descriptor.label,
|
|
||||||
icon: descriptor.icon,
|
|
||||||
summary: descriptor.summary,
|
|
||||||
...descriptor.summaryI18nKey === void 0 ? {} : { summaryI18nKey: descriptor.summaryI18nKey },
|
|
||||||
origin: descriptor.origin,
|
|
||||||
locality: descriptor.kind,
|
|
||||||
workspaceBinding: descriptor.workspaceBinding,
|
|
||||||
capabilities: descriptor.capabilities,
|
|
||||||
fields: descriptor.fields,
|
|
||||||
secrets: descriptor.fields.filter((field) => field.input === "secret").map((field) => field.key),
|
|
||||||
scoreSemantics: "provider-native"
|
|
||||||
},
|
|
||||||
create: (context) => new OpenVikingProvider(context.memorySpaces ?? context.memoryBodies, { requestTimeoutMs: context.config.timeoutMs })
|
|
||||||
});
|
|
||||||
var src_default = defineMemorySpaceProvider({
|
|
||||||
id: descriptor.id,
|
|
||||||
apply(ctx, host) {
|
|
||||||
host.install(ctx, definition);
|
|
||||||
}
|
|
||||||
});
|
|
||||||
export { OpenVikingProvider, src_default as default, definition, descriptor };
|
|
||||||
|
|
@ -1,55 +0,0 @@
|
||||||
{
|
|
||||||
"name": "dsh-brain-mnemon-provider-openviking",
|
|
||||||
"version": "0.5.12",
|
|
||||||
"description": "OpenViking Provider child for the Memory Spaces Source.",
|
|
||||||
"license": "MIT",
|
|
||||||
"type": "module",
|
|
||||||
"engines": {
|
|
||||||
"node": ">=20"
|
|
||||||
},
|
|
||||||
"exports": {
|
|
||||||
".": {
|
|
||||||
"types": "./lib/index.d.ts",
|
|
||||||
"default": "./lib/index.js"
|
|
||||||
},
|
|
||||||
"./descriptor": {
|
|
||||||
"types": "./lib/descriptor.d.ts",
|
|
||||||
"default": "./lib/descriptor.js"
|
|
||||||
},
|
|
||||||
"./package.json": "./package.json"
|
|
||||||
},
|
|
||||||
"files": [
|
|
||||||
"lib",
|
|
||||||
"README.md"
|
|
||||||
],
|
|
||||||
"scripts": {
|
|
||||||
"typecheck": "tsc --noEmit",
|
|
||||||
"build": "tsdown",
|
|
||||||
"test": "vitest run",
|
|
||||||
"verify": "pnpm typecheck && pnpm test && pnpm build"
|
|
||||||
},
|
|
||||||
"peerDependencies": {
|
|
||||||
"@deepseek-ai/cordis": "^4.0.1",
|
|
||||||
"dsh-brain-mnemon-source-memory-spaces": "^0.5.1"
|
|
||||||
},
|
|
||||||
"devDependencies": {
|
|
||||||
"@types/node": "^22.0.0",
|
|
||||||
"dsh-brain-mnemon-source-memory-spaces": "^0.5.33",
|
|
||||||
"tsdown": "^0.22.0",
|
|
||||||
"typescript": "^5.9.0",
|
|
||||||
"vitest": "^3.2.0"
|
|
||||||
},
|
|
||||||
"publishConfig": {
|
|
||||||
"access": "public",
|
|
||||||
"tag": "latest"
|
|
||||||
},
|
|
||||||
"repository": {
|
|
||||||
"type": "git",
|
|
||||||
"url": "git+https://github.com/omdsh-dev/dsh-mnemon.git",
|
|
||||||
"directory": "plugins/dsh-brain-mnemon-provider-openviking"
|
|
||||||
},
|
|
||||||
"homepage": "https://github.com/omdsh-dev/dsh-mnemon/tree/main/plugins/dsh-brain-mnemon-provider-openviking#readme",
|
|
||||||
"bugs": {
|
|
||||||
"url": "https://github.com/omdsh-dev/dsh-mnemon/issues"
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
@ -1,4 +0,0 @@
|
||||||
import { ct as MemoryProviderDescriptor } from "../../../lib/contracts-DuGgDm58.js";
|
|
||||||
import "../../source-memory-spaces/lib/provider-sdk.js";
|
|
||||||
declare const descriptor: MemoryProviderDescriptor;
|
|
||||||
export { descriptor };
|
|
||||||
|
|
@ -1 +0,0 @@
|
||||||
export { t as descriptor } from "../../../lib/descriptor-C2HZA_V0.js";
|
|
||||||
|
|
@ -1,20 +0,0 @@
|
||||||
import { a as MemoryJsonValue } from "../../../lib/index-3Wnpy9oQ.js";
|
|
||||||
import { $t as SearchRequest, Jt as RememberRequest, L as MemoryBody, Y as MemoryListRequest, w as Insight } from "../../../lib/contracts-DuGgDm58.js";
|
|
||||||
import { C as ProviderSearchResult, S as ProviderScoreSemantics, f as MemoryProviderAdapter, h as MemorySpaceAuthority, n as MemorySpaceProviderDefinition, s as MemorySpaceProviderModule, x as ProviderMemorySpace, y as ProviderBodyStatus } from "../../../lib/definitions-C41Daez1.js";
|
|
||||||
import { HttpMemoryProvider, HttpProviderOptions } from "../../source-memory-spaces/lib/provider-sdk.js";
|
|
||||||
import { descriptor } from "./descriptor.js";
|
|
||||||
declare class RetainDbProvider extends HttpMemoryProvider implements MemoryProviderAdapter {
|
|
||||||
readonly id: "retaindb";
|
|
||||||
readonly scoreSemantics: ProviderScoreSemantics;
|
|
||||||
constructor(memorySpaces: MemorySpaceAuthority, options?: HttpProviderOptions);
|
|
||||||
discover(connection: Record<string, string | number | boolean>, signal?: AbortSignal): Promise<ProviderMemorySpace[]>;
|
|
||||||
status(body: MemoryBody, signal?: AbortSignal): Promise<ProviderBodyStatus>;
|
|
||||||
search(body: MemoryBody, request: SearchRequest, signal?: AbortSignal): Promise<ProviderSearchResult>;
|
|
||||||
list(body: MemoryBody, request: MemoryListRequest, signal?: AbortSignal): Promise<Insight[]>;
|
|
||||||
remember(body: MemoryBody, request: RememberRequest, signal?: AbortSignal): Promise<MemoryJsonValue>;
|
|
||||||
forget(body: MemoryBody, id: string, signal?: AbortSignal): Promise<MemoryJsonValue>;
|
|
||||||
private headers;
|
|
||||||
}
|
|
||||||
declare const definition: MemorySpaceProviderDefinition;
|
|
||||||
declare const _default: MemorySpaceProviderModule<undefined>;
|
|
||||||
export { RetainDbProvider, _default as default, definition, descriptor };
|
|
||||||
|
|
@ -1,211 +0,0 @@
|
||||||
import { t as NORMALIZED_RELEVANCE_SCORE } from "../../../lib/adapter-CF9Q9xOa.js";
|
|
||||||
import { i as defineMemorySpaceProviderDefinition, r as defineMemorySpaceProvider, t as MEMORY_SPACE_PROVIDER_API_VERSION } from "../../../lib/definitions-Du9KQuKM.js";
|
|
||||||
import { HttpMemoryProvider, bearerAuthHeader, firstArray, jsonNumber, jsonObject, jsonString } from "../../source-memory-spaces/lib/provider-sdk.js";
|
|
||||||
import { t as descriptor } from "../../../lib/descriptor-C2HZA_V0.js";
|
|
||||||
// vendor/dsh-mnemon/plugins/dsh-brain-mnemon-provider-retaindb/src/driver.ts
|
|
||||||
function insight(value) {
|
|
||||||
const item = jsonObject(value);
|
|
||||||
const id = jsonString(item?.id) ?? jsonString(item?.memory_id);
|
|
||||||
const content = jsonString(item?.content) ?? jsonString(item?.memory) ?? jsonString(item?.text);
|
|
||||||
if (id === void 0 || content === void 0) return void 0;
|
|
||||||
const score = jsonNumber(item?.score) ?? jsonNumber(item?.similarity);
|
|
||||||
const createdAt = jsonString(item?.created_at) ?? jsonString(item?.createdAt) ?? jsonString(item?.updated_at);
|
|
||||||
return {
|
|
||||||
id,
|
|
||||||
content,
|
|
||||||
category: jsonString(item?.memory_type) ?? jsonString(item?.category) ?? "general",
|
|
||||||
source: "external",
|
|
||||||
...score === void 0 ? {} : { score },
|
|
||||||
...createdAt === void 0 ? {} : { createdAt }
|
|
||||||
};
|
|
||||||
}
|
|
||||||
function isEndpointMissing(error) {
|
|
||||||
const status = typeof error === "object" && error !== null ? error.status : void 0;
|
|
||||||
if (typeof status === "number") return status === 404;
|
|
||||||
return error instanceof Error && /^[^:]+ HTTP 404\b/u.test(error.message);
|
|
||||||
}
|
|
||||||
var RetainDbProvider = class extends HttpMemoryProvider {
|
|
||||||
id = "retaindb";
|
|
||||||
scoreSemantics = NORMALIZED_RELEVANCE_SCORE;
|
|
||||||
constructor(memorySpaces, options = {}) {
|
|
||||||
super(memorySpaces, {
|
|
||||||
label: descriptor.label,
|
|
||||||
...options
|
|
||||||
});
|
|
||||||
}
|
|
||||||
async discover(connection, signal) {
|
|
||||||
const payload = await this.requestConnection(connection, "/v1/projects", {
|
|
||||||
headers: this.headers(connection, "/v1/projects"),
|
|
||||||
signal
|
|
||||||
});
|
|
||||||
return firstArray(payload, "projects", "items").flatMap((value) => {
|
|
||||||
const item = jsonObject(value);
|
|
||||||
const project = jsonString(item?.slug) ?? jsonString(item?.name) ?? jsonString(item?.id);
|
|
||||||
if (project === void 0) return [];
|
|
||||||
return [{
|
|
||||||
externalId: jsonString(item?.id) ?? project,
|
|
||||||
name: jsonString(item?.name) ?? project,
|
|
||||||
description: jsonString(item?.description) ?? `RetainDB project ${project}`,
|
|
||||||
connection: {
|
|
||||||
project,
|
|
||||||
userId: "*"
|
|
||||||
}
|
|
||||||
}];
|
|
||||||
});
|
|
||||||
}
|
|
||||||
async status(body, signal) {
|
|
||||||
try {
|
|
||||||
await this.list(body, { limit: 1 }, signal);
|
|
||||||
return { healthy: true };
|
|
||||||
} catch (error) {
|
|
||||||
return {
|
|
||||||
healthy: false,
|
|
||||||
error: error instanceof Error ? error.message : String(error)
|
|
||||||
};
|
|
||||||
}
|
|
||||||
}
|
|
||||||
async search(body, request, signal) {
|
|
||||||
const connection = this.connection(body);
|
|
||||||
const payload = await this.request(body, "/v1/memory/search", {
|
|
||||||
headers: this.headers(connection, "/v1/memory/search"),
|
|
||||||
json: {
|
|
||||||
project: String(connection.project),
|
|
||||||
query: request.query,
|
|
||||||
...String(connection.userId) === "*" ? {} : { user_id: String(connection.userId) },
|
|
||||||
session_id: `dsh-${body.id}`,
|
|
||||||
top_k: request.limit ?? 10,
|
|
||||||
include_pending: true
|
|
||||||
},
|
|
||||||
signal
|
|
||||||
});
|
|
||||||
return { results: firstArray(payload, "results", "memories").map(insight).filter((item) => item !== void 0) };
|
|
||||||
}
|
|
||||||
async list(body, request, signal) {
|
|
||||||
const connection = this.connection(body);
|
|
||||||
const params = new URLSearchParams({
|
|
||||||
project: String(connection.project),
|
|
||||||
include_pending: "true"
|
|
||||||
});
|
|
||||||
let payload;
|
|
||||||
if (String(connection.userId) === "*") {
|
|
||||||
params.set("limit", String(Math.min(Math.max(request.limit ?? 200, 1), 200)));
|
|
||||||
payload = await this.request(body, `/v1/memories?${params}`, {
|
|
||||||
headers: this.headers(connection, "/v1/memories"),
|
|
||||||
signal
|
|
||||||
});
|
|
||||||
} else try {
|
|
||||||
payload = await this.request(body, `/v1/memory/profile/${encodeURIComponent(String(connection.userId))}?${params}`, {
|
|
||||||
headers: this.headers(connection, "/v1/memory/profile"),
|
|
||||||
signal
|
|
||||||
});
|
|
||||||
} catch (error) {
|
|
||||||
if (!isEndpointMissing(error)) throw error;
|
|
||||||
params.set("user_id", String(connection.userId));
|
|
||||||
params.set("limit", String(Math.min(Math.max(request.limit ?? 200, 1), 200)));
|
|
||||||
payload = await this.request(body, `/v1/memories?${params}`, {
|
|
||||||
headers: this.headers(connection, "/v1/memories"),
|
|
||||||
signal
|
|
||||||
});
|
|
||||||
}
|
|
||||||
return firstArray(payload, "memories", "results").map(insight).filter((item) => item !== void 0).filter((item) => request.category === void 0 || item.category === request.category).slice(0, Math.min(Math.max(request.limit ?? 200, 1), 200));
|
|
||||||
}
|
|
||||||
async remember(body, request, signal) {
|
|
||||||
const connection = this.connection(body);
|
|
||||||
const json = {
|
|
||||||
project: String(connection.project),
|
|
||||||
content: request.content,
|
|
||||||
memory_type: request.category ?? "factual",
|
|
||||||
user_id: String(connection.userId) === "*" ? "dsh-user" : String(connection.userId),
|
|
||||||
session_id: `dsh-${body.id}`,
|
|
||||||
importance: request.importance ?? .7,
|
|
||||||
write_mode: "sync"
|
|
||||||
};
|
|
||||||
let payload;
|
|
||||||
try {
|
|
||||||
payload = await this.request(body, "/v1/memory", {
|
|
||||||
headers: this.headers(connection, "/v1/memory"),
|
|
||||||
json,
|
|
||||||
signal
|
|
||||||
});
|
|
||||||
} catch (error) {
|
|
||||||
if (!isEndpointMissing(error)) throw error;
|
|
||||||
const { write_mode: _writeMode, ...legacy } = json;
|
|
||||||
payload = await this.request(body, "/v1/memories", {
|
|
||||||
headers: this.headers(connection, "/v1/memories"),
|
|
||||||
json: legacy,
|
|
||||||
signal
|
|
||||||
});
|
|
||||||
}
|
|
||||||
const result = jsonObject(payload) ?? {};
|
|
||||||
return {
|
|
||||||
action: "stored",
|
|
||||||
provider: this.id,
|
|
||||||
summary: "RetainDB stored the memory synchronously.",
|
|
||||||
...jsonString(result.id) === void 0 ? {} : { id: jsonString(result.id) }
|
|
||||||
};
|
|
||||||
}
|
|
||||||
async forget(body, id, signal) {
|
|
||||||
const connection = this.connection(body);
|
|
||||||
try {
|
|
||||||
await this.request(body, `/v1/memory/${encodeURIComponent(id)}`, {
|
|
||||||
method: "DELETE",
|
|
||||||
headers: this.headers(connection, "/v1/memory"),
|
|
||||||
signal
|
|
||||||
});
|
|
||||||
} catch (error) {
|
|
||||||
if (!isEndpointMissing(error)) throw error;
|
|
||||||
await this.request(body, `/v1/memories/${encodeURIComponent(id)}`, {
|
|
||||||
method: "DELETE",
|
|
||||||
headers: this.headers(connection, "/v1/memories"),
|
|
||||||
signal
|
|
||||||
});
|
|
||||||
}
|
|
||||||
return {
|
|
||||||
action: "deleted",
|
|
||||||
provider: this.id,
|
|
||||||
id
|
|
||||||
};
|
|
||||||
}
|
|
||||||
headers(connection, path) {
|
|
||||||
const rawKey = String(connection.apiKey ?? "").trim();
|
|
||||||
const auth = typeof bearerAuthHeader === "function" ? bearerAuthHeader(rawKey) : (() => {
|
|
||||||
const stripped = rawKey.replace(/^Bearer(?:\s+|$)/iu, "").trim();
|
|
||||||
return stripped === "" ? void 0 : `Bearer ${stripped}`;
|
|
||||||
})();
|
|
||||||
const token = auth?.slice(7);
|
|
||||||
return {
|
|
||||||
...auth === void 0 ? {} : { Authorization: auth },
|
|
||||||
"x-sdk-runtime": "dsh-brain-mnemon",
|
|
||||||
...token !== void 0 && (path.startsWith("/v1/memory") || path.startsWith("/v1/context")) ? { "X-API-Key": token } : {}
|
|
||||||
};
|
|
||||||
}
|
|
||||||
};
|
|
||||||
// vendor/dsh-mnemon/plugins/dsh-brain-mnemon-provider-retaindb/src/index.ts
|
|
||||||
const definition = defineMemorySpaceProviderDefinition({
|
|
||||||
manifest: {
|
|
||||||
apiVersion: MEMORY_SPACE_PROVIDER_API_VERSION,
|
|
||||||
kind: "provider",
|
|
||||||
typeId: descriptor.id,
|
|
||||||
packageName: "dsh-brain-mnemon-provider-retaindb",
|
|
||||||
version: "0.5.8",
|
|
||||||
label: descriptor.label,
|
|
||||||
icon: descriptor.icon,
|
|
||||||
summary: descriptor.summary,
|
|
||||||
...descriptor.summaryI18nKey === void 0 ? {} : { summaryI18nKey: descriptor.summaryI18nKey },
|
|
||||||
origin: descriptor.origin,
|
|
||||||
locality: descriptor.kind,
|
|
||||||
workspaceBinding: descriptor.workspaceBinding,
|
|
||||||
capabilities: descriptor.capabilities,
|
|
||||||
fields: descriptor.fields,
|
|
||||||
secrets: descriptor.fields.filter((field) => field.input === "secret").map((field) => field.key),
|
|
||||||
scoreSemantics: "normalized-relevance"
|
|
||||||
},
|
|
||||||
create: (context) => new RetainDbProvider(context.memorySpaces ?? context.memoryBodies, { requestTimeoutMs: context.config.timeoutMs })
|
|
||||||
});
|
|
||||||
var src_default = defineMemorySpaceProvider({
|
|
||||||
id: descriptor.id,
|
|
||||||
apply(ctx, host) {
|
|
||||||
host.install(ctx, definition);
|
|
||||||
}
|
|
||||||
});
|
|
||||||
export { RetainDbProvider, src_default as default, definition, descriptor };
|
|
||||||
|
|
@ -1,55 +0,0 @@
|
||||||
{
|
|
||||||
"name": "dsh-brain-mnemon-provider-retaindb",
|
|
||||||
"version": "0.5.8",
|
|
||||||
"description": "RetainDB Provider child for the Memory Spaces Source.",
|
|
||||||
"license": "MIT",
|
|
||||||
"type": "module",
|
|
||||||
"engines": {
|
|
||||||
"node": ">=20"
|
|
||||||
},
|
|
||||||
"exports": {
|
|
||||||
".": {
|
|
||||||
"types": "./lib/index.d.ts",
|
|
||||||
"default": "./lib/index.js"
|
|
||||||
},
|
|
||||||
"./descriptor": {
|
|
||||||
"types": "./lib/descriptor.d.ts",
|
|
||||||
"default": "./lib/descriptor.js"
|
|
||||||
},
|
|
||||||
"./package.json": "./package.json"
|
|
||||||
},
|
|
||||||
"files": [
|
|
||||||
"lib",
|
|
||||||
"README.md"
|
|
||||||
],
|
|
||||||
"scripts": {
|
|
||||||
"typecheck": "tsc --noEmit",
|
|
||||||
"build": "tsdown",
|
|
||||||
"test": "vitest run",
|
|
||||||
"verify": "pnpm typecheck && pnpm test && pnpm build"
|
|
||||||
},
|
|
||||||
"peerDependencies": {
|
|
||||||
"@deepseek-ai/cordis": "^4.0.1",
|
|
||||||
"dsh-brain-mnemon-source-memory-spaces": "^0.5.1"
|
|
||||||
},
|
|
||||||
"devDependencies": {
|
|
||||||
"@types/node": "^22.0.0",
|
|
||||||
"dsh-brain-mnemon-source-memory-spaces": "^0.5.33",
|
|
||||||
"tsdown": "^0.22.0",
|
|
||||||
"typescript": "^5.9.0",
|
|
||||||
"vitest": "^3.2.0"
|
|
||||||
},
|
|
||||||
"publishConfig": {
|
|
||||||
"access": "public",
|
|
||||||
"tag": "latest"
|
|
||||||
},
|
|
||||||
"repository": {
|
|
||||||
"type": "git",
|
|
||||||
"url": "git+https://github.com/omdsh-dev/dsh-mnemon.git",
|
|
||||||
"directory": "plugins/dsh-brain-mnemon-provider-retaindb"
|
|
||||||
},
|
|
||||||
"homepage": "https://github.com/omdsh-dev/dsh-mnemon/tree/main/plugins/dsh-brain-mnemon-provider-retaindb#readme",
|
|
||||||
"bugs": {
|
|
||||||
"url": "https://github.com/omdsh-dev/dsh-mnemon/issues"
|
|
||||||
}
|
|
||||||
}
|
|
||||||
Some files were not shown because too many files have changed in this diff Show More
Loading…
Reference in New Issue